hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b2d03b0b492537c5a55cac6853119e893b9b5980 | 5,980 | cpp | C++ | kernel/elfreader.cpp | Bunogi/bunos | 52e55d16938c87d45aa148c18d3bf389f2067445 | [
"BSD-3-Clause"
] | null | null | null | kernel/elfreader.cpp | Bunogi/bunos | 52e55d16938c87d45aa148c18d3bf389f2067445 | [
"BSD-3-Clause"
] | null | null | null | kernel/elfreader.cpp | Bunogi/bunos | 52e55d16938c87d45aa148c18d3bf389f2067445 | [
"BSD-3-Clause"
] | null | null | null | #include <bustd/math.hpp>
#include <bustd/vector.hpp>
#include <kernel/elfreader.hpp>
#include <kernel/filesystem/vfs.hpp>
#include <kernel/memory.hpp>
#include <kernel/process.hpp>
#include <kernel/x86/memory.hpp>
#include <string.h>
#define ELFSIZE 32
#include <kernel/exec_elf.h>
#define DEBUG_ELF
#ifdef DEBUG_ELF
#include <stdio.h>
#define ELFREADER_PREFIX "[ELFreader] "
#define DEBUG_PRINTF(...) printf(ELFREADER_PREFIX __VA_ARGS__)
#define DEBUG_PUTS(...) puts(ELFREADER_PREFIX __VA_ARGS__)
#else
#define DEBUG_PRINTF(...)
#define DEBUG_PUTS(...)
#endif
namespace {
bool validate_ident(const u8 *data) {
if (data[EI_MAG0] != ELFMAG0 || data[EI_MAG1] != ELFMAG1 ||
data[EI_MAG2] != ELFMAG2 || data[EI_MAG3] != ELFMAG3) {
DEBUG_PUTS("Invalid magic number");
return false;
}
if (data[EI_CLASS] != ELFCLASS32) {
DEBUG_PUTS("Invalid class");
return false;
}
if (data[EI_DATA] != ELFDATA2LSB) {
DEBUG_PUTS("Invalid data encoding");
return false;
}
if (data[EI_VERSION] != EV_CURRENT) {
DEBUG_PUTS("Invalid ELF version");
return false;
}
// EI_OSABI seems to be an openbsd thing, so ignore it
return true;
}
bool validate_header(const Elf32_Ehdr *header) {
if (!validate_ident(header->e_ident)) {
return false;
}
if (header->e_type != ET_EXEC) {
DEBUG_PUTS("error: Invalid type");
return false;
}
if (header->e_machine != EM_386) {
DEBUG_PUTS("error: Invalid machine");
return false;
}
if (header->e_version != EV_CURRENT) {
DEBUG_PUTS("error: Invalid version");
return false;
}
if (header->e_entry == 0) {
DEBUG_PUTS("error: Entry is zero");
return false;
}
return true;
}
bool handle_program_headers(const u8 *const data, const usize data_len,
kernel::Process &process,
const Elf32_Ehdr *header) {
const auto header_offset = header->e_phoff;
if (header_offset == 0) {
DEBUG_PUTS("error: No program header found");
return false;
}
const auto header_count = header->e_phnum;
const auto header_size = header->e_phentsize;
for (usize i = 0; i < header_count; i++) {
const auto *const prog_header = reinterpret_cast<const Elf32_Phdr *>(
&data[header_offset + i * header_size]);
switch (prog_header->p_type) {
case PT_NULL:
case PT_NOTE:
// Can safely ignore these
DEBUG_PRINTF("Ignored program header of type %u", prog_header->p_type);
continue;
case PT_LOAD:
break;
case PT_DYNAMIC:
DEBUG_PUTS("error: found dynamic section");
return false;
case PT_INTERP:
DEBUG_PUTS("error: Program has interpreter");
return false;
case PT_SHLIB:
default:
DEBUG_PRINTF("Unrecognized field type %u\n", prog_header->p_type);
return false;
}
// Only support PT_LOAD for now
ASSERT_EQ(prog_header->p_type, PT_LOAD);
DEBUG_PRINTF("p_align: 0x%x\n", prog_header->p_align);
ASSERT(prog_header->p_offset + prog_header->p_memsz < data_len);
// FIXME: Is this right?
ASSERT_EQ(prog_header->p_align, PAGE_SIZE);
auto segment_offset = kernel::VirtualAddress(
reinterpret_cast<uintptr_t>(data + prog_header->p_offset));
auto vaddr = kernel::VirtualAddress(prog_header->p_vaddr);
auto pages_to_allocate = bu::divide_ceil(
prog_header->p_memsz, static_cast<Elf32_Word>(PAGE_SIZE));
DEBUG_PRINTF("memsz: 0x%x, filesz: 0x%x, have to allocate %u pages\n",
prog_header->p_memsz, prog_header->p_filesz,
pages_to_allocate);
DEBUG_PRINTF("p_virtaddr: %p\n", prog_header->p_vaddr);
for (usize j = 0; j < pages_to_allocate; j++) {
const auto page_aligned_address = vaddr.get() - vaddr.get() % PAGE_SIZE;
const auto address_offset = vaddr.get() - page_aligned_address;
const auto new_mapping = kernel::VirtualAddress(page_aligned_address);
DEBUG_PRINTF("Page_aligned address: %p, address_offset: %p, "
"new_mapping: %p, vaddr: %p\n",
page_aligned_address, address_offset, new_mapping.ptr(),
vaddr.ptr());
ASSERT(kernel::x86::map_user_memory(process, new_mapping));
memset(new_mapping.ptr(), 0, address_offset);
if (segment_offset.get() + PAGE_SIZE < prog_header->p_filesz) {
const auto to_copy = prog_header->p_filesz - segment_offset;
const auto to_zero = (segment_offset.get() + PAGE_SIZE) % PAGE_SIZE;
memcpy(vaddr.ptr(), segment_offset.ptr(), to_copy);
memset(reinterpret_cast<char *>(vaddr.ptr()) + to_copy, 0, to_zero);
} else {
memcpy(vaddr.ptr(), segment_offset.ptr(), PAGE_SIZE - address_offset);
}
if (!(prog_header->p_flags & PF_W)) {
// FIXME: We should probably maybe protect against executing writable
// segments
kernel::x86::set_user_mem_no_write(process, new_mapping);
}
if (address_offset != 0) {
const auto diff = PAGE_SIZE - address_offset;
segment_offset += diff;
vaddr += diff;
ASSERT_EQ(vaddr.get() % PAGE_SIZE, 0);
} else {
segment_offset += PAGE_SIZE;
vaddr += PAGE_SIZE;
}
}
}
return true;
}
} // namespace
namespace kernel::elf {
void (*parse(Process &proc, bu::StringView file))() {
const auto elf_file_data = Vfs::instance().quick_read_all_data(file);
const auto contents = *elf_file_data;
_x86_set_page_directory(proc.page_dir().get());
DEBUG_PRINTF("Read %u chars\n", contents.len());
const auto *data = contents.data();
const auto *header = reinterpret_cast<const Elf32_Ehdr *>(data);
if (!validate_header(header)) {
return nullptr;
}
DEBUG_PUTS("are HERE");
if (!handle_program_headers(data, contents.len(), proc, header)) {
return nullptr;
}
DEBUG_PUTS("AM HERE");
// TODO();
return reinterpret_cast<void (*)()>(header->e_entry);
}
} // namespace kernel::elf
| 29.60396 | 78 | 0.653344 | [
"vector"
] |
b2d56deb26e0696f9ce96a29f32d7d29fc6e980f | 5,380 | cpp | C++ | tests/test_point.cpp | orbingol/PointVector | c1c11d934b40105b4cf37019655bb78481f9091a | [
"MIT"
] | 1 | 2019-03-26T00:58:51.000Z | 2019-03-26T00:58:51.000Z | tests/test_point.cpp | orbingol/PointVector | c1c11d934b40105b4cf37019655bb78481f9091a | [
"MIT"
] | null | null | null | tests/test_point.cpp | orbingol/PointVector | c1c11d934b40105b4cf37019655bb78481f9091a | [
"MIT"
] | 1 | 2019-03-26T00:58:50.000Z | 2019-03-26T00:58:50.000Z | /**
* PointVector -- n-dimensional point and vector implementations
* Copyright (c) 2018 Onur Rauf Bingol
*
* Licensed under the MIT License
* Catch2 is licensed under the Boost Software Licence 1.0 -- https://github.com/catchorg/Catch2
*
*
* Unit testing of Point class using Catch Framework
*/
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "Point.hxx"
#define Point3 geomdl::Point<float, 3>
#define GPV_TEST_EQTOL 10e-5
TEST_CASE("Test Point Template Class", "[point]") {
SECTION("Default constructor") {
Point3 pt;
REQUIRE(abs(pt[0] - 0) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 0) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 0) < GPV_TEST_EQTOL);
}
SECTION("Initializer list constructor") {
Point3 pt = {1, 2, 3};
REQUIRE(abs(pt[0] - 1) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 2) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 3) < GPV_TEST_EQTOL);
}
SECTION("Pointer constructor") {
float *dataptr = new float[3];
dataptr[0] = 1;
dataptr[1] = 2;
dataptr[2] = 3;
Point3 pt(dataptr);
delete[] dataptr;
REQUIRE(abs(pt[0] - 1) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 2) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 3) < GPV_TEST_EQTOL);
}
SECTION("Single value constructor") {
Point3 pt(10);
REQUIRE(abs(pt[0] - 10) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 10) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 10) < GPV_TEST_EQTOL);
}
SECTION("Copy constructor") {
Point3 pt2 = {2, 5, 7};
Point3 pt(pt2);
REQUIRE(abs(pt[0] - 2) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 5) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 7) < GPV_TEST_EQTOL);
}
SECTION("Copy assignment operator") {
Point3 pt = {20, 50, 70};
Point3 pt2 = {2, 5, 7};
pt = pt2;
REQUIRE(abs(pt[0] - 2) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 5) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 7) < GPV_TEST_EQTOL);
}
SECTION("Point addition operator") {
Point3 pt;
Point3 pt1 = {6, 5, 4};
Point3 pt2 = {1, 2, 3};
pt = pt1 + pt2;
REQUIRE(abs(pt[0] - 7) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 7) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 7) < GPV_TEST_EQTOL);
}
SECTION("Point subtraction operator") {
Point3 pt;
Point3 pt1 = {6, 5, 4};
Point3 pt2 = {1, 2, 3};
pt = pt1 - pt2;
REQUIRE(abs(pt[0] - 5) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 3) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 1) < GPV_TEST_EQTOL);
}
SECTION("Value addition operator") {
Point3 pt;
Point3 pt1 = {1, 2, 3};
float val = 1;
pt = pt1 + val;
REQUIRE(abs(pt[0] - 2) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 3) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 4) < GPV_TEST_EQTOL);
}
SECTION("Value subtraction operator") {
Point3 pt;
Point3 pt1 = {6, 5, 4};
float val = 1;
pt = pt1 - val;
REQUIRE(abs(pt[0] - 5) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 4) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 3) < GPV_TEST_EQTOL);
}
SECTION("Value multiplication operator") {
Point3 pt;
Point3 pt1 = {6, 5, 4};
float val = 2;
pt = pt1 * val;
REQUIRE(abs(pt[0] - 12) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 10) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 8) < GPV_TEST_EQTOL);
}
SECTION("Value division operator") {
Point3 pt;
Point3 pt1 = {6, 5, 1};
float val = 2;
pt = pt1 / val;
REQUIRE(abs(pt[0] - 3) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 2.5) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 0.5) < GPV_TEST_EQTOL);
}
SECTION("Equality operator") {
Point3 pt1 = {2.7f, 3.11f, 6.65f};
Point3 pt2 = {2.7f, 3.11f, 6.65f};
REQUIRE((pt1 == pt2) == true);
}
SECTION("Inequality operator") {
Point3 pt1 = {2.7f, 3.11f, 6.65f};
Point3 pt2 = {2.7f, 3.12f, 6.67f};
REQUIRE((pt1 != pt2) == true);
}
SECTION("Stream extraction operator") {
Point3 pt = {10, 20, 30};
std::stringstream out;
out << pt;
REQUIRE((out.str() == "(10, 20, 30)") == true);
}
SECTION("Stream insertion & extraction operator") {
Point3 pt;
std::stringstream in;
in.str("100 200 356");
in >> pt;
std::stringstream out;
out << pt;
REQUIRE((out.str() == "(100, 200, 356)") == true);
}
SECTION("Stream insertion operator") {
Point3 pt;
std::stringstream in;
in.str("1.1 2.71 3.9234");
in >> pt;
REQUIRE(abs(pt[0] - 1.1) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[1] - 2.71) < GPV_TEST_EQTOL);
REQUIRE(abs(pt[2] - 3.9234) < GPV_TEST_EQTOL);
}
SECTION("Stream insertion & data() method") {
Point3 pt;
std::stringstream in;
in.str("1.1 2.71 3.9234");
in >> pt;
float *data = pt.data();
REQUIRE(abs(data[0] - 1.1) < GPV_TEST_EQTOL);
REQUIRE(abs(data[1] - 2.71) < GPV_TEST_EQTOL);
REQUIRE(abs(data[2] - 3.9234) < GPV_TEST_EQTOL);
}
}
| 24.125561 | 96 | 0.529182 | [
"vector"
] |
b2d9707fd7e239574d2c7e1b7792ae47c281234b | 33,432 | cpp | C++ | admin/wmi/wbem/tools/wmic/wmiclixmllog.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/wmi/wbem/tools/wmic/wmiclixmllog.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/wmi/wbem/tools/wmic/wmiclixmllog.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | ///////////////////////////////////////////////////////////////////////
/****************************************************************************
Copyright information : Copyright (c) 1998-1999 Microsoft Corporation
File Name : WMICliLog.cpp
Project Name : WMI Command Line
Author Name : Biplab Mistry
Date of Creation (dd/mm/yy) : 02-March-2001
Version Number : 1.0
Brief Description : This class encapsulates the functionality needed
for logging the input and output.
Revision History :
Last Modified By : Ch. Sriramachandramurthy
Last Modified Date : 27-March-2001
*****************************************************************************/
// WMICliXMLLog.cpp : implementation file
#include "Precomp.h"
#include "helpinfo.h"
#include "ErrorLog.h"
#include "GlobalSwitches.h"
#include "CommandSwitches.h"
#include "ParsedInfo.h"
#include "ErrorInfo.h"
#include "WMICliXMLLog.h"
#include "CmdTokenizer.h"
#include "CmdAlias.h"
#include "ParserEngine.h"
#include "ExecEngine.h"
#include "FormatEngine.h"
#include "WmiCmdLn.h"
/*------------------------------------------------------------------------
Name :CWMICliXMLLog
Synopsis :Constructor
Type :Constructor
Input parameter :None
Output parameters :None
Return Type :None
Global Variables :None
Calling Syntax :None
Notes :None
------------------------------------------------------------------------*/
CWMICliXMLLog::CWMICliXMLLog()
{
m_pIXMLDoc = NULL;
m_pszLogFile = NULL;
m_bCreate = FALSE;
m_nItrNum = 0;
m_bTrace = FALSE;
m_eloErrLogOpt = NO_LOGGING;
}
/*------------------------------------------------------------------------
Name :~CWMICliXMLLog
Synopsis :Destructor
Type :Destructor
Input parameter :None
Output parameters :None
Return Type :None
Global Variables :None
Calling Syntax :None
Notes :None
------------------------------------------------------------------------*/
CWMICliXMLLog::~CWMICliXMLLog()
{
SAFEDELETE(m_pszLogFile);
SAFEIRELEASE(m_pIXMLDoc);
}
/*----------------------------------------------------------------------------
Name :Uninitialize
Synopsis :This function uninitializes the member variables when
the execution of a command string issued on the command
line is completed.
Type :Member Function
Input Parameter(s):
bFinal - boolean value which when set indicates that the program
Output parameters :None
Return Type :None
Global Variables :None
Calling Syntax :Uninitialize(bFinal)
Notes :None
----------------------------------------------------------------------------*/
void CWMICliXMLLog::Uninitialize(BOOL bFinal)
{
if (bFinal)
{
SAFEDELETE(m_pszLogFile);
SAFEIRELEASE(m_pIXMLDoc);
}
m_bTrace = FALSE;
m_eloErrLogOpt = NO_LOGGING;
}
/*------------------------------------------------------------------------
Name :WriteToXMLLog
Synopsis :Logs the input & output to the xml log file
Type :Member Function
Input parameter :
rParsedInfo - reference to CParsedInfo object
bstrOutput - output that goes into CDATA section.
Output parameters :None
Return Type :HRESULT
Global Variables :None
Calling Syntax :WriteToXMLLog(rParsedInfo, bstrOutput)
Notes :None
------------------------------------------------------------------------*/
HRESULT CWMICliXMLLog::WriteToXMLLog(CParsedInfo& rParsedInfo, BSTR bstrOutput)
{
HRESULT hr = S_OK;
_variant_t varValue;
DWORD dwThreadId = GetCurrentThreadId();
BSTR bstrUser = NULL,
bstrStart = NULL,
bstrInput = NULL,
bstrTarget = NULL,
bstrNode = NULL;
WMICLIINT nSeqNum = 0;
BOOL bNewCmd = FALSE;
BOOL bNewCycle = FALSE;
// Initialize the TRACE and ERRORLOG variables.
m_bTrace = rParsedInfo.GetGlblSwitchesObject().GetTraceStatus();
m_eloErrLogOpt = rParsedInfo.GetErrorLogObject().GetErrLogOption();
bNewCmd = rParsedInfo.GetNewCommandStatus();
bNewCycle = rParsedInfo.GetNewCycleStatus();
CHString chsMsg;
try
{
bstrUser = ::SysAllocString(rParsedInfo.GetGlblSwitchesObject().
GetLoggedonUser());
if (bstrUser == NULL)
throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
bstrStart = ::SysAllocString(rParsedInfo.GetGlblSwitchesObject().
GetStartTime());
if (bstrStart == NULL)
throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
_TCHAR *pszCommandInput = rParsedInfo.GetCmdSwitchesObject().
GetCommandInput();
STRING strCommand(pszCommandInput);
// Delete /RECORD entries
FindAndDeleteRecord(strCommand);
bstrInput = ::SysAllocString((LPTSTR)strCommand.data());
if (bstrInput == NULL)
throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
if (!rParsedInfo.GetGlblSwitchesObject().GetAggregateFlag())
{
bstrTarget = ::SysAllocString(rParsedInfo.GetGlblSwitchesObject().
GetNode());
if (bstrTarget == NULL)
throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
}
else
{
_bstr_t bstrTemp;
_TCHAR* pszVerb = rParsedInfo.GetCmdSwitchesObject().GetVerbName();
if (pszVerb)
{
if ( CompareTokens(pszVerb, CLI_TOKEN_LIST) ||
CompareTokens(pszVerb, CLI_TOKEN_ASSOC) ||
CompareTokens(pszVerb, CLI_TOKEN_GET))
{
rParsedInfo.GetGlblSwitchesObject().GetNodeString(bstrTemp);
bstrTarget = ::SysAllocString((LPWSTR)bstrTemp);
if (bstrTarget == NULL)
throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
}
// CALL, SET, CREATE, DELETE and, user defined verbs
else
{
bstrTarget= ::SysAllocString(rParsedInfo.GetGlblSwitchesObject().
GetNode());
if (bstrTarget == NULL)
throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
}
}
else
{
rParsedInfo.GetGlblSwitchesObject().GetNodeString(bstrTemp);
bstrTarget = ::SysAllocString((LPWSTR)bstrTemp);
if (bstrTarget == NULL)
throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
}
}
bstrNode = ::SysAllocString(rParsedInfo.GetGlblSwitchesObject().
GetMgmtStationName());
if (bstrNode == NULL)
throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
nSeqNum = rParsedInfo.GetGlblSwitchesObject().GetSequenceNumber();
// If first time.
if(!m_bCreate)
{
// Create the XML root node
hr = CreateXMLLogRoot(rParsedInfo, bstrUser);
ONFAILTHROWERROR(hr);
}
if (bNewCmd == TRUE)
{
m_nItrNum = 1;
// Create the node fragment and append it
hr = CreateNodeFragment(nSeqNum, bstrNode, bstrStart,
bstrInput, bstrOutput, bstrTarget,
rParsedInfo);
ONFAILTHROWERROR(hr);
}
else
{
if (bNewCycle)
m_nItrNum++;
hr = AppendOutputNode(bstrOutput, bstrTarget, rParsedInfo);
ONFAILTHROWERROR(hr);
}
// Save the result to the XML file specified.
varValue = (WCHAR*) m_pszLogFile;
hr = m_pIXMLDoc->save(varValue);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMDocument2::save(L\"%s\")",
(LPWSTR) varValue.bstrVal);
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
::SysFreeString(bstrUser);
::SysFreeString(bstrStart);
::SysFreeString(bstrInput);
::SysFreeString(bstrTarget);
::SysFreeString(bstrNode);
}
catch(_com_error& e)
{
::SysFreeString(bstrUser);
::SysFreeString(bstrStart);
::SysFreeString(bstrInput);
::SysFreeString(bstrTarget);
::SysFreeString(bstrNode);
hr = e.Error();
}
catch(CHeap_Exception)
{
::SysFreeString(bstrUser);
::SysFreeString(bstrStart);
::SysFreeString(bstrInput);
::SysFreeString(bstrTarget);
::SysFreeString(bstrNode);
hr = WBEM_E_OUT_OF_MEMORY;
}
return hr;
}
/*------------------------------------------------------------------------
Name :SetLogFilePath
Synopsis :This function sets the m_pszLogFile name with the
input
Type :Member Function
Input parameter :
pszLogFile - String type,Contains the log file name
Return Type :void
Global Variables :None
Calling Syntax :SetLogFilePath(pszLogFile)
Notes :None
------------------------------------------------------------------------*/
void CWMICliXMLLog::SetLogFilePath(_TCHAR* pszLogFile) throw (WMICLIINT)
{
SAFEDELETE(m_pszLogFile);
m_pszLogFile = new _TCHAR [lstrlen(pszLogFile) + 1];
if (m_pszLogFile)
{
//Copy the input argument into the log file name
lstrcpy(m_pszLogFile, pszLogFile);
}
else
throw(OUT_OF_MEMORY);
}
/*------------------------------------------------------------------------
Name :CreateXMLLogRoot
Synopsis :Creates the root node of the xml log file
Type :Member Function
Input parameter :
rParsedInfo - reference to CParsedInfo object
bstrUser - current user name
Output parameters :None
Return Type :HRESULT
Global Variables :None
Calling Syntax :CreateXMLLogRoot(rParsedInfo, bstrUser)
Notes :None
------------------------------------------------------------------------*/
HRESULT CWMICliXMLLog::CreateXMLLogRoot(CParsedInfo& rParsedInfo, BSTR bstrUser)
{
HRESULT hr = S_OK;
IXMLDOMNode *pINode = NULL;
DWORD dwThreadId = GetCurrentThreadId();
CHString chsMsg;
try
{
// Create single instance of the IXMLDOMDocument2 interface
hr = CoCreateInstance(CLSID_FreeThreadedDOMDocument, NULL,
CLSCTX_INPROC_SERVER,
IID_IXMLDOMDocument2,
(LPVOID*)&m_pIXMLDoc);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"CoCreateInstance(CLSID_FreeThreadedDOMDocument, NULL,"
L"CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument2, -)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
// Create the XML root node <WMICRECORD USER=XXX>
_variant_t varType((short)NODE_ELEMENT);
_bstr_t bstrName(L"WMIRECORD");
_variant_t varValue;
// Create a new node
hr = CreateNodeAndSetContent(&pINode, varType, bstrName, NULL,
rParsedInfo);
ONFAILTHROWERROR(hr);
// Append the attribute "USER"
bstrName = L"USER";
varValue = (WCHAR*)bstrUser;
hr = AppendAttribute(pINode, bstrName, varValue, rParsedInfo);
ONFAILTHROWERROR(hr);
hr = m_pIXMLDoc->appendChild(pINode, NULL);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::appendChild(-, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
SAFEIRELEASE(pINode);
// set the m_bCreate flag to TRUE
m_bCreate=TRUE;
}
catch(_com_error& e)
{
SAFEIRELEASE(pINode);
hr = e.Error();
}
catch(CHeap_Exception)
{
SAFEIRELEASE(pINode);
hr = WBEM_E_OUT_OF_MEMORY;
}
return hr;
}
/*------------------------------------------------------------------------
Name :StopLogging
Synopsis :Stops logging and closes the xml DOM document object
Type :Member Function
Input parameter :None
Output parameters :None
Return Type :void
Global Variables :None
Calling Syntax :StopLogging()
Notes :None
------------------------------------------------------------------------*/
void CWMICliXMLLog::StopLogging()
{
SAFEDELETE(m_pszLogFile);
SAFEIRELEASE(m_pIXMLDoc);
m_bCreate = FALSE;
}
/*------------------------------------------------------------------------
Name :CreateNodeAndSetContent
Synopsis :Creates the new node and sets the content
Type :Member Function
Input parameter :
pINode - pointer to node object
varType - node type
bstrName - Node name
bstrValue - node content
rParsedInfo - reference to CParsedInfo object
Output parameters :None
Return Type :HRESULT
Global Variables :None
Calling Syntax :CreateNodeAndSetContent(&pINode, varType,
bstrName, bstrValue, rParsedInfo)
Notes :None
------------------------------------------------------------------------*/
HRESULT CWMICliXMLLog::CreateNodeAndSetContent(IXMLDOMNode** pINode,
VARIANT varType,
BSTR bstrName, BSTR bstrValue,
CParsedInfo& rParsedInfo)
{
HRESULT hr = S_OK;
DWORD dwThreadId = GetCurrentThreadId();
CHString chsMsg;
try
{
hr = m_pIXMLDoc->createNode(varType, bstrName, L"", pINode);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMDocument2::createNode(%d, \"%s\", L\"\","
L" -)", varType.lVal, (LPWSTR) bstrName);
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
if (bstrValue)
{
hr = (*pINode)->put_text(bstrValue);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::put_text(L\"%s\")", (LPWSTR) bstrValue);
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
}
}
catch(_com_error& e)
{
hr = e.Error();
}
catch(CHeap_Exception)
{
hr = WBEM_E_OUT_OF_MEMORY;
}
return hr;
}
/*------------------------------------------------------------------------
Name :AppendAttribute
Synopsis :Append attribute with the given value to the node
specified.
Type :Member Function
Input parameter :
pINode - node object
bstrAttribName - Attribute name
varValue - attribute value
rParsedInfo - reference to CParsedInfo object
Output parameters :None
Return Type :HRESULT
Global Variables :None
Calling Syntax :AppendAttribute(pINode, bstrAttribName, varValue,
rParsedInfo)
Notes :None
------------------------------------------------------------------------*/
HRESULT CWMICliXMLLog::AppendAttribute(IXMLDOMNode* pINode, BSTR bstrAttribName,
VARIANT varValue, CParsedInfo& rParsedInfo)
{
HRESULT hr = S_OK;
IXMLDOMNamedNodeMap *pINodeMap = NULL;
IXMLDOMAttribute *pIAttrib = NULL;
DWORD dwThreadId = GetCurrentThreadId();
CHString chsMsg;
try
{
// Get the attributes map
hr = pINode->get_attributes(&pINodeMap);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::get_attributes(-)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
if (pINodeMap)
{
// Create the attribute with the given name.
hr = m_pIXMLDoc->createAttribute(bstrAttribName, &pIAttrib);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMDocument2::createAttribute(L\"%s\", -)",
(LPWSTR) bstrAttribName);
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
// Set the attribute value
if (pIAttrib)
{
hr = pIAttrib->put_nodeValue(varValue);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMAttribute::put_nodeValue(L\"%s\")",
(LPWSTR) _bstr_t(varValue));
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
hr = pINodeMap->setNamedItem(pIAttrib, NULL);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNamedNodeMap::setNamedItem(-, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
SAFEIRELEASE(pIAttrib);
}
SAFEIRELEASE(pINodeMap);
}
}
catch(_com_error& e)
{
SAFEIRELEASE(pIAttrib);
SAFEIRELEASE(pINodeMap);
hr = e.Error();
}
catch(CHeap_Exception)
{
SAFEIRELEASE(pIAttrib);
SAFEIRELEASE(pINodeMap);
hr = WBEM_E_OUT_OF_MEMORY;
}
return hr;
}
/*------------------------------------------------------------------------
Name :CreateNodeFragment
Synopsis :Creates a new node fragment with the predefined format
and appends it to the document object
Type :Member Function
Input parameter :
nSeqNum - sequence # of the command.
bstrNode - management workstation name
bstrStart - command issued time
bstrInput - commandline input
bstrOutput - commandline output
bstrTarget - target node
rParsedInfo - reference to CParsedInfo object
Output parameters :None
Return Type :HRESULT
Global Variables :None
Calling Syntax :CreateNodeFragment(nSeqNum, bstrNode, bstrStart,
bstrInput, bstrOutput, bstrTarget, rParsedInfo)
Notes :None
------------------------------------------------------------------------*/
HRESULT CWMICliXMLLog::CreateNodeFragment(WMICLIINT nSeqNum, BSTR bstrNode,
BSTR bstrStart, BSTR bstrInput,
BSTR bstrOutput, BSTR bstrTarget,
CParsedInfo& rParsedInfo)
{
HRESULT hr = S_OK;
IXMLDOMNode *pINode = NULL,
*pISNode = NULL,
*pITNode = NULL;
IXMLDOMDocumentFragment *pIFrag = NULL;
IXMLDOMElement *pIElement = NULL;
_variant_t varType;
_bstr_t bstrName;
_variant_t varValue;
DWORD dwThreadId = GetCurrentThreadId();
CHString chsMsg;
try
{
// The nodetype is NODE_ELEMENT
varType = ((short)NODE_ELEMENT);
bstrName = _T("RECORD");
// Create a new node
hr = CreateNodeAndSetContent(&pINode, varType,
bstrName, NULL, rParsedInfo);
ONFAILTHROWERROR(hr);
// Append the attribute "SEQUENCENUM"
bstrName = L"SEQUENCENUM";
varValue = (long) nSeqNum;
hr = AppendAttribute(pINode, bstrName, varValue, rParsedInfo);
ONFAILTHROWERROR(hr);
// Append the attribute "ISSUEDFROM"
bstrName = L"ISSUEDFROM";
varValue = (WCHAR*)bstrNode;
hr = AppendAttribute(pINode, bstrName, varValue, rParsedInfo);
ONFAILTHROWERROR(hr);
// Append the attribute "STARTTIME"
bstrName = L"STARTTIME";
varValue = (WCHAR*) bstrStart;
hr = AppendAttribute(pINode, bstrName, varValue, rParsedInfo);
ONFAILTHROWERROR(hr);
// Create a document fragment and associate the new node with it.
hr = m_pIXMLDoc->createDocumentFragment(&pIFrag);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMDocument2::createDocumentFragment(-)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
hr = pIFrag->appendChild(pINode, NULL);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMDocumentFragment::appendChild(-, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
// Append the REQUEST node together with the input command.
bstrName = _T("REQUEST");
hr = CreateNodeAndSetContent(&pISNode, varType,
bstrName, NULL, rParsedInfo);
ONFAILTHROWERROR(hr);
hr = pINode->appendChild(pISNode, &pITNode);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::appendChild(-, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
SAFEIRELEASE(pISNode);
bstrName = _T("COMMANDLINE");
hr = CreateNodeAndSetContent(&pISNode, varType,
bstrName, bstrInput, rParsedInfo);
ONFAILTHROWERROR(hr);
hr = pITNode->appendChild(pISNode, NULL);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::appendChild(-, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
SAFEIRELEASE(pISNode);
SAFEIRELEASE(pITNode);
hr = FrameOutputNode(&pINode, bstrOutput, bstrTarget, rParsedInfo);
// Get the document element of the XML log file
hr = m_pIXMLDoc->get_documentElement(&pIElement);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMDocument2::get_documentElement(-, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
// Append the newly create fragment to the document element
hr = pIElement->appendChild(pIFrag, NULL);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMElement::appendChild(-, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
SAFEIRELEASE(pINode);
SAFEIRELEASE(pIFrag);
SAFEIRELEASE(pIElement);
}
catch(_com_error& e)
{
SAFEIRELEASE(pISNode);
SAFEIRELEASE(pITNode);
SAFEIRELEASE(pINode);
SAFEIRELEASE(pIFrag);
SAFEIRELEASE(pIElement);
hr = e.Error();
}
catch(CHeap_Exception)
{
SAFEIRELEASE(pISNode);
SAFEIRELEASE(pITNode);
SAFEIRELEASE(pINode);
SAFEIRELEASE(pIFrag);
SAFEIRELEASE(pIElement);
hr = WBEM_E_OUT_OF_MEMORY;
}
return hr;
}
/*------------------------------------------------------------------------
Name :FrameOutputNode
Synopsis :Frames a new output node
Type :Member Function
Input parameter :
pINode - pointer to pointer to IXMLDOMNode object
bstrOutput - commandline output
bstrTarget - target node
rParsedInfo - reference to CParsedInfo object
Output parameters :
pINode - pointer to pointer to IXMLDOMNode object
Return Type :HRESULT
Global Variables :None
Calling Syntax :FrameOutputNode(&pINode, bstrOutput, bstrTarget,
rParsedInfo)
Notes :None
------------------------------------------------------------------------*/
HRESULT CWMICliXMLLog::FrameOutputNode(IXMLDOMNode **pINode, BSTR bstrOutput,
BSTR bstrTarget,
CParsedInfo& rParsedInfo)
{
HRESULT hr = S_OK;
IXMLDOMNode *pISNode = NULL;
IXMLDOMCDATASection *pICDATASec = NULL;
_bstr_t bstrName;
_variant_t varType,
varValue;
DWORD dwThreadId = GetCurrentThreadId();
CHString chsMsg;
try
{
// The nodetype is NODE_ELEMENT
varType = ((short)NODE_ELEMENT);
// Append the OUTPUT node together with the output generated.
bstrName = _T("OUTPUT");
hr = CreateNodeAndSetContent(&pISNode, varType,
bstrName, NULL, rParsedInfo);
ONFAILTHROWERROR(hr);
// Append the attribute "TARGETNODE"
bstrName = L"TARGETNODE";
varValue = (WCHAR*) bstrTarget;
hr = AppendAttribute(pISNode, bstrName, varValue, rParsedInfo);
ONFAILTHROWERROR(hr);
// Append the attribute "ITERATION"
bstrName = L"ITERATION";
varValue = (long)m_nItrNum;
hr = AppendAttribute(pISNode, bstrName, varValue, rParsedInfo);
ONFAILTHROWERROR(hr);
// Create the CDATASection
hr = m_pIXMLDoc->createCDATASection(bstrOutput, &pICDATASec);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMDocument2::createCDATASection(-, -)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
// Append the CDATASection node to the OUTPUT node.
hr = pISNode->appendChild(pICDATASec, NULL);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::appendChild(-, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
SAFEIRELEASE(pICDATASec);
hr = (*pINode)->appendChild(pISNode, NULL);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::appendChild(-, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
SAFEIRELEASE(pISNode);
}
catch(_com_error& e)
{
SAFEIRELEASE(pICDATASec);
SAFEIRELEASE(pISNode);
hr = e.Error();
}
catch(CHeap_Exception)
{
SAFEIRELEASE(pICDATASec);
SAFEIRELEASE(pISNode);
hr = WBEM_E_OUT_OF_MEMORY;
}
return hr;
}
/*------------------------------------------------------------------------
Name :AppendOutputNode
Synopsis :appends the newoutput node element to the exisitng
and that too last RECORD node
Type :Member Function
Input parameter :
bstrOutput - commandline output
bstrTarget - target node
rParsedInfo - reference to CParsedInfo object
Output parameters : None
Return Type :HRESULT
Global Variables :None
Calling Syntax :AppendOutputNode(bstrOutput, bstrTarget,
rParsedInfo)
Notes :None
------------------------------------------------------------------------*/
HRESULT CWMICliXMLLog::AppendOutputNode(BSTR bstrOutput, BSTR bstrTarget,
CParsedInfo& rParsedInfo)
{
IXMLDOMNodeList *pINodeList = NULL;
HRESULT hr = S_OK;
LONG lValue = 0;
IXMLDOMNode *pINode = NULL;
IXMLDOMNode *pIParent = NULL,
*pIClone = NULL;
DWORD dwThreadId = GetCurrentThreadId();
CHString chsMsg;
try
{
hr = m_pIXMLDoc->getElementsByTagName(_T("RECORD"), &pINodeList);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMDocument2::getElementsByTagName(L\"RECORD\", -)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
hr = pINodeList->get_length(&lValue);
ONFAILTHROWERROR(hr);
hr = pINodeList->get_item(lValue-1, &pINode);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNodeList::get_item(%d, -)", lValue-1);
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
if (pINode)
{
hr = pINode->cloneNode(VARIANT_TRUE, &pIClone);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::cloneNode(VARIANT_TRUE, -)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
hr = pINode->get_parentNode(&pIParent);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::get_ParentNode(-)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
hr = FrameOutputNode(&pIClone, bstrOutput, bstrTarget, rParsedInfo);
ONFAILTHROWERROR(hr);
hr = pIParent->replaceChild(pIClone, pINode, NULL);
if (m_bTrace || m_eloErrLogOpt)
{
chsMsg.Format(L"IXMLDOMNode::replaceChild(-, -, NULL)");
WMITRACEORERRORLOG(hr, __LINE__, __FILE__, (LPCWSTR)chsMsg,
dwThreadId, rParsedInfo, m_bTrace);
}
ONFAILTHROWERROR(hr);
}
SAFEIRELEASE(pINodeList);
SAFEIRELEASE(pIClone);
SAFEIRELEASE(pIParent);
SAFEIRELEASE(pINode);
}
catch(_com_error& e)
{
SAFEIRELEASE(pINodeList);
SAFEIRELEASE(pIClone);
SAFEIRELEASE(pIParent);
SAFEIRELEASE(pINode);
hr = e.Error();
}
catch(CHeap_Exception)
{
SAFEIRELEASE(pINodeList);
SAFEIRELEASE(pIClone);
SAFEIRELEASE(pIParent);
SAFEIRELEASE(pINode);
hr = WBEM_E_OUT_OF_MEMORY;
}
return hr;
}
/*----------------------------------------------------------------------------
Name :FindAndDeleteRecord
Synopsis :Search and deletes all the occurences of /RECORD entries
in the given string strString
Type :Member Function
Input parameter :
strString - string buffer
Output parameters :None
Return Type :void
Global Variables :g_wmiCmd
Calling Syntax :FindAndDeleteRecord(strString)
Notes :None
----------------------------------------------------------------------------*/
void CWMICliXMLLog::FindAndDeleteRecord(STRING& strString)
{
CHARVECTOR cvTokens = g_wmiCmd.GetTokenVector();
//the iterator to span throuh the vector variable
CHARVECTOR::iterator theIterator;
// Check for the presence of tokens. Absence of tokens indicates
// no command string is fed as input.
if (cvTokens.size())
{
// Obtain the pointer to the beginning of the token vector.
theIterator = cvTokens.begin();
// If first token is forward slash then check for /RECORD entry
if (CompareTokens(*theIterator, CLI_TOKEN_FSLASH))
{
DeleteRecord(strString, cvTokens, theIterator);
}
while (GetNextToken(cvTokens, theIterator))
{
// If token is forward slash then check for /RECORD entry
// and delete it
if (CompareTokens(*theIterator, CLI_TOKEN_FSLASH))
{
DeleteRecord(strString, cvTokens, theIterator);
}
}
}
}
/*----------------------------------------------------------------------------
Name :DeleteRecord
Synopsis :Search and deletes the /RECORD entry at current position
in the given string strString
Type :Member Function
Input parameter :
strString - string buffer
cvTokens - the tokens vector
theIterator - the Iterator to the cvTokens vector.
Output parameters :None
Return Type :void
Global Variables :None
Calling Syntax :DeleteRecord(strString)
Notes :None
----------------------------------------------------------------------------*/
void CWMICliXMLLog::DeleteRecord(STRING& strString, CHARVECTOR& cvTokens,
CHARVECTOR::iterator& theIterator)
{
if (GetNextToken(cvTokens, theIterator))
{
// if current token is RECORD the delete the complete entry
if (CompareTokens(*theIterator, CLI_TOKEN_RECORD))
{
_TCHAR* pszFromStr = *theIterator;
_TCHAR* pszToStr = _T("");
STRING::size_type stFromStrLen = lstrlen(pszFromStr);
STRING::size_type stToStrLen = lstrlen(pszToStr);
STRING::size_type stStartPos = 0;
STRING::size_type stPos = 0;
stPos = strString.find(pszFromStr, stStartPos, stFromStrLen);
strString.replace(stPos, stFromStrLen, pszToStr);
stStartPos = stPos;
// Search and delete forward slash just before RECORD
pszFromStr = CLI_TOKEN_FSLASH;
stFromStrLen = lstrlen(pszFromStr);
stPos = strString.rfind(pszFromStr, stStartPos, stFromStrLen);
strString.replace(stPos, stFromStrLen, pszToStr);
stStartPos = stPos;
WMICLIINT nCount = 0;
// Delete the /RECORD value that is /RECORD:<record file name>
while (GetNextToken(cvTokens, theIterator))
{
if (nCount == 0 &&
!CompareTokens(*theIterator, CLI_TOKEN_COLON))
{
// if after /RECORD, next token is not ":" then break
break;
}
// Delete the record file name from command line string
// which will be recorded in the recorded file
nCount++;
pszFromStr = *theIterator;
stFromStrLen = lstrlen(pszFromStr);
stPos = strString.find(pszFromStr, stStartPos, stFromStrLen);
strString.replace(stPos, stFromStrLen, pszToStr);
stStartPos = stPos;
// Delete only 2 tokens that is ":" and record file name
if(nCount == 2)
{
// Search and delete double quotes that may be
// used with record file name
pszFromStr = _T("\"\"");
stFromStrLen = lstrlen(pszFromStr);
stStartPos--;
stPos = strString.find(pszFromStr, stStartPos, stFromStrLen);
if(stPos != strString.npos)
strString.replace(stPos, stFromStrLen, pszToStr);
break;
}
}
}
}
return;
}
/*----------------------------------------------------------------------------
Name :GetNextToken
Synopsis :This function retrieves the next token from the token
vector list, returns FALSE if no more tokens are present
Type :Member Function
Input Parameter(s):
cvTokens - the tokens vector
theIterator - the Iterator to the cvTokens vector.
Output Parameter(s):None
Return Type :BOOL
Global Variables :None
Calling Syntax :GetNextToken(cvTokens,theIterator)
Notes :None
----------------------------------------------------------------------------*/
BOOL CWMICliXMLLog::GetNextToken(CHARVECTOR& cvTokens,
CHARVECTOR::iterator& theIterator)
{
theIterator++;
return (theIterator >= cvTokens.end()) ? FALSE : TRUE;
}
| 31.480226 | 82 | 0.609087 | [
"object",
"vector"
] |
b2db194df7dd6a65303da502fd743745202cc2ec | 1,032 | cpp | C++ | solutions/binary_search.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/binary_search.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/binary_search.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | // Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
// Example 1:
// Input: nums = [-1,0,3,5,9,12], target = 9
// Output: 4
// Explanation: 9 exists in nums and its index is 4
// Example 2:
// Input: nums = [-1,0,3,5,9,12], target = 2
// Output: -1
// Explanation: 2 does not exist in nums so return -1
// Note:
// You may assume that all elements in nums are unique.
// n will be in the range [1, 10000].
// The value of each element in nums will be in the range [-9999, 9999].
// solution: binary search
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size()-1;
while (left <= right) {
int mid = left + (right-left)/2;
if (nums[mid] == target) return mid;
if (target < nums[mid]) right = mid - 1;
else left = mid + 1;
}
return -1;
}
}; | 25.8 | 196 | 0.598837 | [
"vector"
] |
b2de378cc3b4be62ae742e0379202901116159cd | 3,005 | hpp | C++ | include/anvil (deprecated)/ocl/Event.hpp | asmith-git/anvil | 5f31fdeccf70016b8276c261f8ac4f2525dc6f66 | [
"Apache-2.0"
] | null | null | null | include/anvil (deprecated)/ocl/Event.hpp | asmith-git/anvil | 5f31fdeccf70016b8276c261f8ac4f2525dc6f66 | [
"Apache-2.0"
] | null | null | null | include/anvil (deprecated)/ocl/Event.hpp | asmith-git/anvil | 5f31fdeccf70016b8276c261f8ac4f2525dc6f66 | [
"Apache-2.0"
] | null | null | null | //Copyright 2017 Adam G. Smith
//
//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.
#ifndef ANVIL_OCL_EVENT_HPP
#define ANVIL_OCL_EVENT_HPP
#include <memory>
#include "anvil/ocl/Context.hpp"
namespace anvil { namespace ocl {
class EventListener;
struct ProfileInfo {
cl_ulong queued;
cl_ulong submit;
cl_ulong start;
cl_ulong end;
};
class Event : public Object {
private:
Event(const Event&) = delete;
Event& operator=(const Event&) = delete;
protected:
// Inherited from Object
bool ANVIL_CALL retain() throw() override;
public:
enum CommandType : cl_command_type {
NDRANGE_KERNEL = CL_COMMAND_NDRANGE_KERNEL,
TASK = CL_COMMAND_TASK,
NATIVE_KERNEL = CL_COMMAND_NATIVE_KERNEL,
READ_BUFFER = CL_COMMAND_READ_BUFFER,
WRITE_BUFFER = CL_COMMAND_WRITE_BUFFER,
COPY_BUFFER = CL_COMMAND_COPY_BUFFER,
READ_IMAGE = CL_COMMAND_READ_IMAGE,
WRITE_IMAGE = CL_COMMAND_WRITE_IMAGE,
COPY_IMAGE = CL_COMMAND_COPY_IMAGE,
COPY_BUFFER_TO_IMAGE = CL_COMMAND_COPY_BUFFER_TO_IMAGE,
COPY_IMAGE_TO_BUFFER = CL_COMMAND_COPY_IMAGE_TO_BUFFER,
MAP_BUFFER = CL_COMMAND_MAP_BUFFER,
MAP_IMAGE = CL_COMMAND_MAP_IMAGE,
UNMAP_MEM_OBJECT = CL_COMMAND_UNMAP_MEM_OBJECT,
MARKER = CL_COMMAND_MARKER,
ACQUIRE_GL_OBJECTS = CL_COMMAND_ACQUIRE_GL_OBJECTS,
RELEASE_GL_OBJECTS = CL_COMMAND_RELEASE_GL_OBJECTS,
READ_BUFFER_RECT = CL_COMMAND_READ_BUFFER_RECT,
WRITE_BUFFER_RECT = CL_COMMAND_WRITE_BUFFER_RECT,
COPY_BUFFER_RECT = CL_COMMAND_COPY_BUFFER_RECT,
USER = CL_COMMAND_USER,
};
enum Status : cl_int {
COMPLETE = CL_COMPLETE,
RUNNING = CL_RUNNING,
SUBMITTED = CL_SUBMITTED,
QUEUED = CL_QUEUED
};
ANVIL_CALL Event() throw();
ANVIL_CALL Event(Event&&) throw();
ANVIL_CALL ~Event() throw();
Event& ANVIL_CALL operator=(Event&&) throw();
void ANVIL_CALL swap(Event&) throw();
bool ANVIL_CALL setListener(EventListener&) throw();
bool ANVIL_CALL wait() throw();
CommandType ANVIL_CALL commandType() const throw();
Status ANVIL_CALL status() const throw();
ProfileInfo ANVIL_CALL profileInfo() const throw();
static bool ANVIL_CALL wait(const std::vector<Event>&) throw();
// Inherited from Object
bool ANVIL_CALL destroy() throw() override;
cl_uint ANVIL_CALL referenceCount() const throw() override;
Handle::Type ANVIL_CALL type() const throw() override;
};
class EventListener {
protected:
virtual void onComplete() throw() = 0;
public:
friend Event;
virtual ~EventListener() {}
};
}}
#endif
| 29.174757 | 74 | 0.753078 | [
"object",
"vector"
] |
b2e3c7c86f8d55e60d0411353697bb18331bf1d2 | 25,514 | cpp | C++ | src_main/materialsystem/stdshaders/vortwarp_dx9.cpp | ArcadiusGFN/SourceEngine2007 | 51cd6d4f0f9ed901cb9b61456eb621a50ce44f55 | [
"bzip2-1.0.6"
] | 25 | 2018-02-28T15:04:42.000Z | 2021-08-16T03:49:00.000Z | src_main/materialsystem/stdshaders/vortwarp_dx9.cpp | ArcadiusGFN/SourceEngine2007 | 51cd6d4f0f9ed901cb9b61456eb621a50ce44f55 | [
"bzip2-1.0.6"
] | 1 | 2019-09-20T11:06:03.000Z | 2019-09-20T11:06:03.000Z | src_main/materialsystem/stdshaders/vortwarp_dx9.cpp | ArcadiusGFN/SourceEngine2007 | 51cd6d4f0f9ed901cb9b61456eb621a50ce44f55 | [
"bzip2-1.0.6"
] | 9 | 2019-07-31T11:58:20.000Z | 2021-08-31T11:18:15.000Z | // Copyright © 1996-2018, Valve Corporation, All rights reserved.
#include "BaseVSShader.h"
#include "vertexlitgeneric_dx9_helper.h"
#include "vortwarp_ps20.inc"
#include "vortwarp_ps20b.inc"
#include "vortwarp_vs20.inc"
#include "tier1/convar.h"
#include "vortwarp_ps30.inc"
#include "vortwarp_vs30.inc"
DEFINE_FALLBACK_SHADER(VortWarp, VortWarp_dx9)
extern ConVar r_flashlight_version2;
struct VortWarp_DX9_Vars_t : public VertexLitGeneric_DX9_Vars_t {
VortWarp_DX9_Vars_t() { memset(this, 0xFF, sizeof(*this)); }
int m_nEntityOrigin;
int m_nWarpParam;
int m_nFlowMap;
int m_nSelfIllumMap;
int m_nUnlit;
};
//-----------------------------------------------------------------------------
// Draws the shader
//-----------------------------------------------------------------------------
void DrawVortWarp_DX9(CBaseVSShader *pShader, IMaterialVar **params,
IShaderDynamicAPI *pShaderAPI,
IShaderShadow *pShaderShadow, bool bVertexLitGeneric,
bool hasFlashlight, VortWarp_DX9_Vars_t &info,
VertexCompressionType_t vertexCompression) {
bool hasBaseTexture = params[info.m_nBaseTexture]->IsTexture();
bool hasBump =
(info.m_nBumpmap != -1) && params[info.m_nBumpmap]->IsTexture();
bool hasDetailTexture = !hasBump && params[info.m_nDetail]->IsTexture();
bool hasNormalMapAlphaEnvmapMask =
IS_FLAG_SET(MATERIAL_VAR_NORMALMAPALPHAENVMAPMASK);
bool hasVertexColor =
bVertexLitGeneric ? false : IS_FLAG_SET(MATERIAL_VAR_VERTEXCOLOR);
bool hasVertexAlpha =
bVertexLitGeneric ? false : IS_FLAG_SET(MATERIAL_VAR_VERTEXALPHA);
bool bIsAlphaTested = IS_FLAG_SET(MATERIAL_VAR_ALPHATEST) != 0;
bool hasSelfIllumInEnvMapMask =
(info.m_nSelfIllumEnvMapMask_Alpha != -1) &&
(params[info.m_nSelfIllumEnvMapMask_Alpha]->GetFloatValue() != 0.0);
bool bHasFlowMap =
(info.m_nFlowMap != -1) && params[info.m_nFlowMap]->IsTexture();
bool bHasSelfIllumMap =
(info.m_nSelfIllumMap != -1) && params[info.m_nSelfIllumMap]->IsTexture();
BlendType_t blendType;
if (params[info.m_nBaseTexture]->IsTexture()) {
blendType = pShader->EvaluateBlendRequirements(info.m_nBaseTexture, true);
} else {
blendType = pShader->EvaluateBlendRequirements(info.m_nEnvmapMask, false);
}
if (pShader->IsSnapshotting()) {
// look at color and alphamod stuff.
// Unlit generic never uses the flashlight
bool hasEnvmap = !hasFlashlight && params[info.m_nEnvmap]->IsTexture();
bool hasEnvmapMask = (hasSelfIllumInEnvMapMask || !hasFlashlight) &&
params[info.m_nEnvmapMask]->IsTexture();
bool bHasNormal = bVertexLitGeneric || hasEnvmap;
if (hasFlashlight) {
hasEnvmapMask = false;
}
bool bHalfLambert = IS_FLAG_SET(MATERIAL_VAR_HALFLAMBERT);
// Alpha test: TODO(d.rattman): shouldn't this be handled in
// CBaseVSShader::SetInitialShadowState
pShaderShadow->EnableAlphaTest(bIsAlphaTested);
if (info.m_nAlphaTestReference != -1 &&
params[info.m_nAlphaTestReference]->GetFloatValue() > 0.0f) {
pShaderShadow->AlphaFunc(
SHADER_ALPHAFUNC_GEQUAL,
params[info.m_nAlphaTestReference]->GetFloatValue());
}
if (hasFlashlight) {
if (params[info.m_nBaseTexture]->IsTexture()) {
pShader->SetAdditiveBlendingShadowState(info.m_nBaseTexture, true);
} else {
pShader->SetAdditiveBlendingShadowState(info.m_nEnvmapMask, false);
}
if (bIsAlphaTested) {
// disable alpha test and use the zfunc zequals since alpha isn't
// guaranteed to be the same on both the regular pass and the flashlight
// pass.
pShaderShadow->EnableAlphaTest(false);
pShaderShadow->DepthFunc(SHADER_DEPTHFUNC_EQUAL);
}
pShaderShadow->EnableBlending(true);
pShaderShadow->EnableDepthWrites(false);
} else {
if (params[info.m_nBaseTexture]->IsTexture()) {
pShader->SetDefaultBlendingShadowState(info.m_nBaseTexture, true);
} else {
pShader->SetDefaultBlendingShadowState(info.m_nEnvmapMask, false);
}
}
unsigned int flags = VERTEX_POSITION;
int nTexCoordCount = 1; // texcoord0 : base texcoord
int userDataSize = 0;
if (bHasNormal) {
flags |= VERTEX_NORMAL;
}
if (hasBaseTexture) {
pShaderShadow->EnableTexture(SHADER_SAMPLER0, true);
pShaderShadow->EnableSRGBRead(SHADER_SAMPLER0, true);
}
if (hasEnvmap) {
pShaderShadow->EnableTexture(SHADER_SAMPLER1, true);
if (g_pHardwareConfig->GetHDRType() == HDR_TYPE_NONE) {
pShaderShadow->EnableSRGBRead(SHADER_SAMPLER1, true);
}
}
if (hasFlashlight) {
pShaderShadow->EnableTexture(SHADER_SAMPLER7, true);
pShaderShadow->EnableTexture(SHADER_SAMPLER4, true);
userDataSize = 4; // tangent S
}
if (hasDetailTexture) {
pShaderShadow->EnableTexture(SHADER_SAMPLER2, true);
}
if (hasBump) {
pShaderShadow->EnableTexture(SHADER_SAMPLER3, true);
userDataSize = 4; // tangent S
// Normalizing cube map
pShaderShadow->EnableTexture(SHADER_SAMPLER5, true);
}
if (hasEnvmapMask) {
pShaderShadow->EnableTexture(SHADER_SAMPLER4, true);
}
if (hasVertexColor || hasVertexAlpha) {
flags |= VERTEX_COLOR;
}
pShaderShadow->EnableSRGBWrite(true);
if (bHasSelfIllumMap) {
pShaderShadow->EnableTexture(SHADER_SAMPLER6, true);
}
if (bHasFlowMap) {
pShaderShadow->EnableTexture(SHADER_SAMPLER2, true);
}
// This shader supports compressed vertices, so OR in that flag:
flags |= VERTEX_FORMAT_COMPRESSED;
pShaderShadow->VertexShaderVertexFormat(flags, nTexCoordCount, NULL,
userDataSize);
Assert(hasBump);
#ifndef _X360
if (!g_pHardwareConfig->HasFastVertexTextures())
#endif
{
DECLARE_STATIC_VERTEX_SHADER(vortwarp_vs20);
SET_STATIC_VERTEX_SHADER_COMBO(HALFLAMBERT, bHalfLambert);
SET_STATIC_VERTEX_SHADER(vortwarp_vs20);
if (g_pHardwareConfig->SupportsPixelShaders_2_b()) {
DECLARE_STATIC_PIXEL_SHADER(vortwarp_ps20b);
SET_STATIC_PIXEL_SHADER_COMBO(BASETEXTURE, hasBaseTexture);
SET_STATIC_PIXEL_SHADER_COMBO(CUBEMAP, hasEnvmap);
SET_STATIC_PIXEL_SHADER_COMBO(DIFFUSELIGHTING,
!params[info.m_nUnlit]->GetIntValue());
SET_STATIC_PIXEL_SHADER_COMBO(NORMALMAPALPHAENVMAPMASK,
hasNormalMapAlphaEnvmapMask);
SET_STATIC_PIXEL_SHADER_COMBO(HALFLAMBERT, bHalfLambert);
SET_STATIC_PIXEL_SHADER_COMBO(FLASHLIGHT, hasFlashlight);
SET_STATIC_PIXEL_SHADER_COMBO(TRANSLUCENT, blendType == BT_BLEND);
SET_STATIC_PIXEL_SHADER(vortwarp_ps20b);
} else {
DECLARE_STATIC_PIXEL_SHADER(vortwarp_ps20);
SET_STATIC_PIXEL_SHADER_COMBO(BASETEXTURE, hasBaseTexture);
SET_STATIC_PIXEL_SHADER_COMBO(CUBEMAP, hasEnvmap);
SET_STATIC_PIXEL_SHADER_COMBO(DIFFUSELIGHTING,
!params[info.m_nUnlit]->GetIntValue());
SET_STATIC_PIXEL_SHADER_COMBO(NORMALMAPALPHAENVMAPMASK,
hasNormalMapAlphaEnvmapMask);
SET_STATIC_PIXEL_SHADER_COMBO(HALFLAMBERT, bHalfLambert);
SET_STATIC_PIXEL_SHADER_COMBO(FLASHLIGHT, hasFlashlight);
SET_STATIC_PIXEL_SHADER_COMBO(TRANSLUCENT, blendType == BT_BLEND);
SET_STATIC_PIXEL_SHADER(vortwarp_ps20);
}
}
#ifndef _X360
else {
// The vertex shader uses the vertex id stream
SET_FLAGS2(MATERIAL_VAR2_USES_VERTEXID);
DECLARE_STATIC_VERTEX_SHADER(vortwarp_vs30);
SET_STATIC_VERTEX_SHADER_COMBO(HALFLAMBERT, bHalfLambert);
SET_STATIC_VERTEX_SHADER(vortwarp_vs30);
DECLARE_STATIC_PIXEL_SHADER(vortwarp_ps30);
SET_STATIC_PIXEL_SHADER_COMBO(BASETEXTURE, hasBaseTexture);
SET_STATIC_PIXEL_SHADER_COMBO(CUBEMAP, hasEnvmap);
SET_STATIC_PIXEL_SHADER_COMBO(DIFFUSELIGHTING,
!params[info.m_nUnlit]->GetIntValue());
SET_STATIC_PIXEL_SHADER_COMBO(NORMALMAPALPHAENVMAPMASK,
hasNormalMapAlphaEnvmapMask);
SET_STATIC_PIXEL_SHADER_COMBO(HALFLAMBERT, bHalfLambert);
SET_STATIC_PIXEL_SHADER_COMBO(FLASHLIGHT, hasFlashlight);
SET_STATIC_PIXEL_SHADER_COMBO(TRANSLUCENT, blendType == BT_BLEND);
SET_STATIC_PIXEL_SHADER(vortwarp_ps30);
}
#endif
if (hasFlashlight) {
pShader->FogToBlack();
} else {
pShader->DefaultFog();
}
if (blendType == BT_BLEND) {
pShaderShadow->EnableBlending(true);
pShaderShadow->BlendFunc(SHADER_BLEND_SRC_ALPHA,
SHADER_BLEND_ONE_MINUS_SRC_ALPHA);
pShaderShadow->EnableAlphaWrites(false);
} else {
pShaderShadow->EnableAlphaWrites(true);
}
} else {
bool hasEnvmap = !hasFlashlight && params[info.m_nEnvmap]->IsTexture();
bool hasEnvmapMask =
!hasFlashlight && params[info.m_nEnvmapMask]->IsTexture();
if (hasBaseTexture) {
pShader->BindTexture(SHADER_SAMPLER0, info.m_nBaseTexture,
info.m_nBaseTextureFrame);
}
if (hasEnvmap) {
pShader->BindTexture(SHADER_SAMPLER1, info.m_nEnvmap,
info.m_nEnvmapFrame);
}
if (hasDetailTexture) {
pShader->BindTexture(SHADER_SAMPLER2, info.m_nDetail,
info.m_nDetailFrame);
}
if (!g_pConfig->m_bFastNoBump) {
if (hasBump) {
pShader->BindTexture(SHADER_SAMPLER3, info.m_nBumpmap,
info.m_nBumpFrame);
}
} else {
if (hasBump) {
pShaderAPI->BindStandardTexture(SHADER_SAMPLER3,
TEXTURE_NORMALMAP_FLAT);
}
}
if (hasEnvmapMask) {
pShader->BindTexture(SHADER_SAMPLER4, info.m_nEnvmapMask,
info.m_nEnvmapMaskFrame);
}
if (hasFlashlight) {
Assert(info.m_nFlashlightTexture >= 0 &&
info.m_nFlashlightTextureFrame >= 0);
pShader->BindTexture(SHADER_SAMPLER7, info.m_nFlashlightTexture,
info.m_nFlashlightTextureFrame);
VMatrix worldToTexture;
ITexture *pFlashlightDepthTexture;
FlashlightState_t state = pShaderAPI->GetFlashlightStateEx(
worldToTexture, &pFlashlightDepthTexture);
SetFlashLightColorFromState(state, pShaderAPI);
}
// Set up light combo state
LightState_t lightState = {0, false, false};
if (bVertexLitGeneric && !hasFlashlight) {
pShaderAPI->GetDX9LightState(&lightState);
}
MaterialFogMode_t fogType = pShaderAPI->GetSceneFogMode();
int fogIndex = (fogType == MATERIAL_FOG_LINEAR_BELOW_FOG_Z) ? 1 : 0;
int numBones = pShaderAPI->GetCurrentNumBones();
Assert(hasBump);
#ifndef _X360
if (!g_pHardwareConfig->HasFastVertexTextures())
#endif
{
DECLARE_DYNAMIC_VERTEX_SHADER(vortwarp_vs20);
SET_DYNAMIC_VERTEX_SHADER_COMBO(DOWATERFOG, fogIndex);
SET_DYNAMIC_VERTEX_SHADER_COMBO(SKINNING, numBones > 0);
SET_DYNAMIC_VERTEX_SHADER_COMBO(COMPRESSED_VERTS, (int)vertexCompression);
SET_DYNAMIC_VERTEX_SHADER(vortwarp_vs20);
if (g_pHardwareConfig->SupportsPixelShaders_2_b()) {
DECLARE_DYNAMIC_PIXEL_SHADER(vortwarp_ps20b);
SET_DYNAMIC_PIXEL_SHADER_COMBO(NUM_LIGHTS, lightState.m_nNumLights);
SET_DYNAMIC_PIXEL_SHADER_COMBO(AMBIENT_LIGHT,
lightState.m_bAmbientLight ? 1 : 0);
SET_DYNAMIC_PIXEL_SHADER_COMBO(
WRITEWATERFOGTODESTALPHA,
fogType == MATERIAL_FOG_LINEAR_BELOW_FOG_Z &&
blendType != BT_BLENDADD && blendType != BT_BLEND &&
!bIsAlphaTested);
SET_DYNAMIC_PIXEL_SHADER_COMBO(PIXELFOGTYPE,
pShaderAPI->GetPixelFogCombo());
float warpParam = params[info.m_nWarpParam]->GetFloatValue();
// float selfIllumTint =
// params[info.m_nSelfIllumTint]->GetFloatValue(); DevMsg( 1,
// "warpParam: %f %f\n", warpParam, selfIllumTint );
SET_DYNAMIC_PIXEL_SHADER_COMBO(WARPINGIN,
warpParam > 0.0f && warpParam < 1.0f);
SET_DYNAMIC_PIXEL_SHADER(vortwarp_ps20b);
} else {
DECLARE_DYNAMIC_PIXEL_SHADER(vortwarp_ps20);
SET_DYNAMIC_PIXEL_SHADER_COMBO(NUM_LIGHTS, lightState.m_nNumLights);
SET_DYNAMIC_PIXEL_SHADER_COMBO(AMBIENT_LIGHT,
lightState.m_bAmbientLight ? 1 : 0);
SET_DYNAMIC_PIXEL_SHADER_COMBO(
WRITEWATERFOGTODESTALPHA,
fogType == MATERIAL_FOG_LINEAR_BELOW_FOG_Z &&
blendType != BT_BLENDADD && blendType != BT_BLEND &&
!bIsAlphaTested);
SET_DYNAMIC_PIXEL_SHADER_COMBO(PIXELFOGTYPE,
pShaderAPI->GetPixelFogCombo());
float warpParam = params[info.m_nWarpParam]->GetFloatValue();
// float selfIllumTint =
// params[info.m_nSelfIllumTint]->GetFloatValue(); DevMsg( 1,
// "warpParam: %f %f\n", warpParam, selfIllumTint );
SET_DYNAMIC_PIXEL_SHADER_COMBO(WARPINGIN,
warpParam > 0.0f && warpParam < 1.0f);
SET_DYNAMIC_PIXEL_SHADER(vortwarp_ps20);
}
}
#ifndef _X360
else {
pShader->SetHWMorphVertexShaderState(
VERTEX_SHADER_SHADER_SPECIFIC_CONST_6,
VERTEX_SHADER_SHADER_SPECIFIC_CONST_7, SHADER_VERTEXTEXTURE_SAMPLER0);
DECLARE_DYNAMIC_VERTEX_SHADER(vortwarp_vs30);
SET_DYNAMIC_VERTEX_SHADER_COMBO(DOWATERFOG, fogIndex);
SET_DYNAMIC_VERTEX_SHADER_COMBO(SKINNING, numBones > 0);
SET_DYNAMIC_VERTEX_SHADER_COMBO(MORPHING,
pShaderAPI->IsHWMorphingEnabled());
SET_DYNAMIC_VERTEX_SHADER_COMBO(COMPRESSED_VERTS, (int)vertexCompression);
SET_DYNAMIC_VERTEX_SHADER(vortwarp_vs30);
DECLARE_DYNAMIC_PIXEL_SHADER(vortwarp_ps30);
SET_DYNAMIC_PIXEL_SHADER_COMBO(NUM_LIGHTS, lightState.m_nNumLights);
SET_DYNAMIC_PIXEL_SHADER_COMBO(AMBIENT_LIGHT,
lightState.m_bAmbientLight ? 1 : 0);
SET_DYNAMIC_PIXEL_SHADER_COMBO(
WRITEWATERFOGTODESTALPHA,
fogType == MATERIAL_FOG_LINEAR_BELOW_FOG_Z &&
blendType != BT_BLENDADD && blendType != BT_BLEND &&
!bIsAlphaTested);
SET_DYNAMIC_PIXEL_SHADER_COMBO(PIXELFOGTYPE,
pShaderAPI->GetPixelFogCombo());
float warpParam = params[info.m_nWarpParam]->GetFloatValue();
// float selfIllumTint =
// params[info.m_nSelfIllumTint]->GetFloatValue(); DevMsg(
// 1, "warpParam: %f %f\n", warpParam, selfIllumTint );
SET_DYNAMIC_PIXEL_SHADER_COMBO(WARPINGIN,
warpParam > 0.0f && warpParam < 1.0f);
SET_DYNAMIC_PIXEL_SHADER(vortwarp_ps30);
}
#endif
pShader->SetVertexShaderTextureTransform(
VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, info.m_nBaseTextureTransform);
if (hasDetailTexture) {
pShader->SetVertexShaderTextureScaledTransform(
VERTEX_SHADER_SHADER_SPECIFIC_CONST_2, info.m_nBaseTextureTransform,
info.m_nDetailScale);
Assert(!hasBump);
}
if (hasBump) {
pShader->SetVertexShaderTextureTransform(
VERTEX_SHADER_SHADER_SPECIFIC_CONST_2, info.m_nBumpTransform);
Assert(!hasDetailTexture);
}
if (hasEnvmapMask) {
pShader->SetVertexShaderTextureTransform(
VERTEX_SHADER_SHADER_SPECIFIC_CONST_4, info.m_nEnvmapMaskTransform);
}
if (hasEnvmap) {
pShader->SetEnvMapTintPixelShaderDynamicState(0, info.m_nEnvmapTint, -1,
true);
}
if ((info.m_nHDRColorScale != -1) && pShader->IsHDREnabled()) {
pShader
->SetModulationPixelShaderDynamicState_LinearColorSpace_LinearScale(
1, params[info.m_nHDRColorScale]->GetFloatValue());
} else {
pShader->SetModulationPixelShaderDynamicState_LinearColorSpace(1);
}
pShader->SetPixelShaderConstant(2, info.m_nEnvmapContrast);
pShader->SetPixelShaderConstant(3, info.m_nEnvmapSaturation);
pShader->SetPixelShaderConstant(4, info.m_nSelfIllumTint);
pShader->SetAmbientCubeDynamicStateVertexShader();
if (hasBump) {
pShaderAPI->BindStandardTexture(SHADER_SAMPLER5,
TEXTURE_NORMALIZATION_CUBEMAP_SIGNED);
pShaderAPI->SetPixelShaderStateAmbientLightCube(5);
pShaderAPI->CommitPixelShaderLighting(13);
}
if (bHasSelfIllumMap) {
pShader->BindTexture(SHADER_SAMPLER6, info.m_nSelfIllumMap, -1);
}
if (bHasFlowMap) {
pShader->BindTexture(SHADER_SAMPLER2, info.m_nFlowMap, -1);
}
float eyePos[4];
pShaderAPI->GetWorldSpaceCameraPosition(eyePos);
pShaderAPI->SetPixelShaderConstant(20, eyePos, 1);
pShaderAPI->SetPixelShaderFogParams(21);
// dynamic drawing code that extends vertexlitgeneric
float curTime = params[info.m_nWarpParam]->GetFloatValue();
float timeVec[4] = {0.0f, 0.0f, 0.0f, curTime};
Assert(params[info.m_nEntityOrigin]->IsDefined());
params[info.m_nEntityOrigin]->GetVecValue(timeVec, 3);
pShaderAPI->SetVertexShaderConstant(VERTEX_SHADER_SHADER_SPECIFIC_CONST_4,
timeVec, 1);
curTime = pShaderAPI->CurrentTime();
timeVec[0] = curTime;
timeVec[1] = curTime;
timeVec[2] = curTime;
timeVec[3] = curTime;
pShaderAPI->SetPixelShaderConstant(22, timeVec, 1);
// flashlightfixme: put this in common code.
if (hasFlashlight) {
VMatrix worldToTexture;
const FlashlightState_t &flashlightState =
pShaderAPI->GetFlashlightState(worldToTexture);
// Set the flashlight attenuation factors
float atten[4];
atten[0] = flashlightState.m_fConstantAtten;
atten[1] = flashlightState.m_fLinearAtten;
atten[2] = flashlightState.m_fQuadraticAtten;
atten[3] = flashlightState.m_FarZ;
pShaderAPI->SetPixelShaderConstant(22, atten, 1);
// Set the flashlight origin
float pos[4];
pos[0] = flashlightState.m_vecLightOrigin[0];
pos[1] = flashlightState.m_vecLightOrigin[1];
pos[2] = flashlightState.m_vecLightOrigin[2];
pos[3] = 1.0f;
pShaderAPI->SetPixelShaderConstant(23, pos, 1);
pShaderAPI->SetPixelShaderConstant(24, worldToTexture.Base(), 4);
}
}
pShader->Draw();
}
BEGIN_VS_SHADER(VortWarp_DX9, "Help for VortWarp_DX9")
BEGIN_SHADER_PARAMS
SHADER_PARAM(ALBEDO, SHADER_PARAM_TYPE_TEXTURE, "shadertest/BaseTexture",
"albedo (Base texture with no baked lighting)")
SHADER_PARAM(SELFILLUMTINT, SHADER_PARAM_TYPE_COLOR, "[1 1 1]",
"Self-illumination tint")
SHADER_PARAM(DETAIL, SHADER_PARAM_TYPE_TEXTURE, "shadertest/detail",
"detail texture")
SHADER_PARAM(DETAILFRAME, SHADER_PARAM_TYPE_INTEGER, "0",
"frame number for $detail")
SHADER_PARAM(DETAILSCALE, SHADER_PARAM_TYPE_FLOAT, "4",
"scale of the detail texture")
SHADER_PARAM(ENVMAP, SHADER_PARAM_TYPE_TEXTURE, "shadertest/shadertest_env",
"envmap")
SHADER_PARAM(ENVMAPFRAME, SHADER_PARAM_TYPE_INTEGER, "0", "envmap frame number")
SHADER_PARAM(ENVMAPMASK, SHADER_PARAM_TYPE_TEXTURE,
"shadertest/shadertest_envmask", "envmap mask")
SHADER_PARAM(ENVMAPMASKFRAME, SHADER_PARAM_TYPE_INTEGER, "0", "")
SHADER_PARAM(ENVMAPMASKTRANSFORM, SHADER_PARAM_TYPE_MATRIX,
"center .5 .5 scale 1 1 rotate 0 translate 0 0",
"$envmapmask texcoord transform")
SHADER_PARAM(ENVMAPTINT, SHADER_PARAM_TYPE_COLOR, "[1 1 1]", "envmap tint")
SHADER_PARAM(BUMPMAP, SHADER_PARAM_TYPE_TEXTURE,
"models/shadertest/shader1_normal", "bump map")
SHADER_PARAM(BUMPFRAME, SHADER_PARAM_TYPE_INTEGER, "0",
"frame number for $bumpmap")
SHADER_PARAM(BUMPTRANSFORM, SHADER_PARAM_TYPE_MATRIX,
"center .5 .5 scale 1 1 rotate 0 translate 0 0",
"$bumpmap texcoord transform")
SHADER_PARAM(ENVMAPCONTRAST, SHADER_PARAM_TYPE_FLOAT, "0.0",
"contrast 0 == normal 1 == color*color")
SHADER_PARAM(ENVMAPSATURATION, SHADER_PARAM_TYPE_FLOAT, "1.0",
"saturation 0 == greyscale 1 == normal")
SHADER_PARAM(SELFILLUM_ENVMAPMASK_ALPHA, SHADER_PARAM_TYPE_FLOAT, "0.0",
"defines that self illum value comes from env map mask alpha")
// Debugging term for visualizing ambient data on its own
SHADER_PARAM(AMBIENTONLY, SHADER_PARAM_TYPE_INTEGER, "0",
"Control drawing of non-ambient light ()")
// hack hack hack
SHADER_PARAM(ENTITYORIGIN, SHADER_PARAM_TYPE_VEC3, "0.0",
"center if the model in world space")
SHADER_PARAM(WARPPARAM, SHADER_PARAM_TYPE_FLOAT, "0.0",
"animation param between 0 and 1")
SHADER_PARAM(FLOWMAP, SHADER_PARAM_TYPE_TEXTURE, "", "flow map")
SHADER_PARAM(SELFILLUMMAP, SHADER_PARAM_TYPE_TEXTURE, "",
"self-illumination map")
SHADER_PARAM(UNLIT, SHADER_PARAM_TYPE_BOOL, "", "")
SHADER_PARAM(PHONGEXPONENT, SHADER_PARAM_TYPE_FLOAT, "5.0",
"Phong exponent for local specular lights")
SHADER_PARAM(PHONGTINT, SHADER_PARAM_TYPE_VEC3, "5.0",
"Phong tint for local specular lights")
SHADER_PARAM(PHONGALBEDOTINT, SHADER_PARAM_TYPE_BOOL, "1.0",
"Apply tint by albedo (controlled by spec exponent texture")
SHADER_PARAM(LIGHTWARPTEXTURE, SHADER_PARAM_TYPE_TEXTURE,
"shadertest/BaseTexture",
"1D ramp texture for tinting scalar diffuse term")
SHADER_PARAM(PHONGWARPTEXTURE, SHADER_PARAM_TYPE_TEXTURE,
"shadertest/BaseTexture", "warp specular term")
SHADER_PARAM(PHONGFRESNELRANGES, SHADER_PARAM_TYPE_VEC3, "[0 0.5 1]",
"Parameters for remapping fresnel output")
SHADER_PARAM(PHONGBOOST, SHADER_PARAM_TYPE_FLOAT, "1.0",
"Phong overbrightening factor (specular mask channel should be "
"authored to account for this)")
SHADER_PARAM(PHONGEXPONENTTEXTURE, SHADER_PARAM_TYPE_TEXTURE,
"shadertest/BaseTexture", "Phong Exponent map")
SHADER_PARAM(PHONG, SHADER_PARAM_TYPE_BOOL, "0", "enables phong lighting")
END_SHADER_PARAMS
void SetupVars(VortWarp_DX9_Vars_t &info) {
info.m_nBaseTexture = BASETEXTURE;
info.m_nBaseTextureFrame = FRAME;
info.m_nBaseTextureTransform = BASETEXTURETRANSFORM;
info.m_nAlbedo = ALBEDO;
info.m_nSelfIllumTint = SELFILLUMTINT;
info.m_nDetail = DETAIL;
info.m_nDetailFrame = DETAILFRAME;
info.m_nDetailScale = DETAILSCALE;
info.m_nEnvmap = ENVMAP;
info.m_nEnvmapFrame = ENVMAPFRAME;
info.m_nEnvmapMask = ENVMAPMASK;
info.m_nEnvmapMaskFrame = ENVMAPMASKFRAME;
info.m_nEnvmapMaskTransform = ENVMAPMASKTRANSFORM;
info.m_nEnvmapTint = ENVMAPTINT;
info.m_nBumpmap = BUMPMAP;
info.m_nBumpFrame = BUMPFRAME;
info.m_nBumpTransform = BUMPTRANSFORM;
info.m_nEnvmapContrast = ENVMAPCONTRAST;
info.m_nEnvmapSaturation = ENVMAPSATURATION;
info.m_nAlphaTestReference = -1;
info.m_nFlashlightTexture = FLASHLIGHTTEXTURE;
info.m_nFlashlightTextureFrame = FLASHLIGHTTEXTUREFRAME;
info.m_nSelfIllumEnvMapMask_Alpha = SELFILLUM_ENVMAPMASK_ALPHA;
info.m_nAmbientOnly = AMBIENTONLY;
info.m_nEntityOrigin = ENTITYORIGIN;
info.m_nWarpParam = WARPPARAM;
info.m_nFlowMap = FLOWMAP;
info.m_nSelfIllumMap = SELFILLUMMAP;
info.m_nUnlit = UNLIT;
info.m_nPhongExponent = PHONGEXPONENT;
info.m_nPhongExponentTexture = PHONGEXPONENTTEXTURE;
info.m_nDiffuseWarpTexture = LIGHTWARPTEXTURE;
info.m_nPhongWarpTexture = PHONGWARPTEXTURE;
info.m_nPhongBoost = PHONGBOOST;
info.m_nPhongFresnelRanges = PHONGFRESNELRANGES;
info.m_nPhong = PHONG;
}
SHADER_INIT_PARAMS() {
VortWarp_DX9_Vars_t vars;
if (!params[BUMPMAP]->IsDefined()) {
params[BUMPMAP]->SetStringValue("dev/flat_normal");
}
SetupVars(vars);
if (!params[UNLIT]->IsDefined()) {
params[UNLIT]->SetIntValue(0);
}
if (!params[SELFILLUMTINT]->IsDefined()) {
params[SELFILLUMTINT]->SetVecValue(0.0f, 0.0f, 0.0f, 0.0f);
}
InitParamsVertexLitGeneric_DX9(this, params, pMaterialName, true, vars);
}
SHADER_FALLBACK {
if (g_pHardwareConfig->GetDXSupportLevel() < 90) return "vortwarp_DX8";
return 0;
}
SHADER_INIT {
VortWarp_DX9_Vars_t vars;
SetupVars(vars);
InitVertexLitGeneric_DX9(this, params, true, vars);
if (params[FLOWMAP]->IsDefined()) {
LoadTexture(FLOWMAP);
}
if (params[SELFILLUMMAP]->IsDefined()) {
LoadTexture(SELFILLUMMAP);
}
}
SHADER_DRAW {
VortWarp_DX9_Vars_t vars;
SetupVars(vars);
// TODO(d.rattman): Should fix VertexlitGeneric_dx9_helper so that you
// can override the vertex shader/pixel shader used (along with the combo
// vars).
bool bHasFlashlight = UsingFlashlight(params);
if (bHasFlashlight && (IsX360() || r_flashlight_version2.GetInt())) {
DrawVortWarp_DX9(this, params, pShaderAPI, pShaderShadow, true, false, vars,
vertexCompression);
SHADOW_STATE { SetInitialShadowState(); }
}
DrawVortWarp_DX9(this, params, pShaderAPI, pShaderShadow, true,
bHasFlashlight, vars, vertexCompression);
}
END_SHADER
| 39.865625 | 80 | 0.684448 | [
"model",
"transform"
] |
b2fa38f6cb20ac9141f03ae7b32c0f44d95f59b5 | 1,471 | hpp | C++ | CompositeFactory/line.hpp | easaemad14/CST276SRS03 | bc5fb7fcbcde1ef250f288f362895262d7b5078a | [
"MIT"
] | null | null | null | CompositeFactory/line.hpp | easaemad14/CST276SRS03 | bc5fb7fcbcde1ef250f288f362895262d7b5078a | [
"MIT"
] | null | null | null | CompositeFactory/line.hpp | easaemad14/CST276SRS03 | bc5fb7fcbcde1ef250f288f362895262d7b5078a | [
"MIT"
] | null | null | null | #pragma once
/********************************************************************************************
* File: line.hpp
* Author: Easa El Sirgany
* easa.elsirgany@oit.edu
*
* Description: Defines the line shape class
********************************************************************************************/
#include "shape.hpp"
class Line : public Shape {
public:
Line() = default;
Line(struct Coordinates origin, int length, double degree)
{
origin_ = origin;
length_ = length;
degree_ = degree;
name_ = "Line";
contents_ = {
{ "Length", length_ },
{ "Degree", degree_ },
{ "Coordinates", { origin_.x_, origin_.y_ } }
};
}
Line(json contents)
{
if (!parseContents(contents)) {
// Use default values?
Line();
/*struct Coordinates defaultOrigin { 0, 0 };
origin_ = defaultOrigin;
name_ = "Line";
contents_ = {
{ "Length", length_ },
{ "Degree", degree_ },
{ "Coordinates",{ origin_.x_, origin_.y_ } }
};*/
}
}
// Get length and degree
void parseSubContents() override
{
try {
length_ = contents_["Length"].get<int>();
}
catch (json::out_of_range) {
length_ = 0; // Lack of length == length of zero
}
catch (json::type_error) {
length_ = 0;
}
catch (...) {
length_ = 0;
}
try {
degree_ = contents_["Degree"].get<double>();
}
catch (...) {
degree_ = 0;
}
}
private:
int length_;
double degree_; // Orientation from x-axis (horizontal)
}; | 19.878378 | 93 | 0.521414 | [
"shape"
] |
b2fc312e71f03b1b3f392e9933ede2535405da0e | 2,820 | cpp | C++ | VoxelEngine/Classes/ShaderManager.cpp | bsy6766/VoxelEngine | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | [
"FTL",
"BSL-1.0",
"Zlib"
] | null | null | null | VoxelEngine/Classes/ShaderManager.cpp | bsy6766/VoxelEngine | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | [
"FTL",
"BSL-1.0",
"Zlib"
] | null | null | null | VoxelEngine/Classes/ShaderManager.cpp | bsy6766/VoxelEngine | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | [
"FTL",
"BSL-1.0",
"Zlib"
] | null | null | null | // pch
#include "PreCompiled.h"
// voxel
#include "ShaderManager.h"
#include "Logger.h"
#include "Config.h"
using namespace Voxel;
ShaderManager::~ShaderManager()
{
releaseAll();
}
Shader * ShaderManager::createShader(const std::string& name, const std::string & filePath, const Shader::Type shaderType)
{
Shader* newShader = Shader::create(filePath, shaderType);
if (newShader)
{
if (shaderType == Shader::Type::VERTEX)
{
addVertexShader(name, newShader);
}
else if (shaderType == Shader::Type::GEOMETRY)
{
// I don't use geomtry shader yet.
delete newShader;
return nullptr;
}
else if (shaderType == Shader::Type::FRAGMENT)
{
addFragmentShader(name, newShader);
}
else
{
#if V_DEBUG && V_DEBUG_LOG_CONSOLE
auto logger = &Voxel::Logger::getInstance();
logger->consoleWarn("[ShaderManager] Trying to create shader type that is invalid. Shader::Type value: " + std::to_string(static_cast<int>(shaderType)));
#endif
delete newShader;
return nullptr;
}
return newShader;
}
else
{
return nullptr;
}
}
bool ShaderManager::addVertexShader(const std::string & name, Shader * vertexShader)
{
auto find_it = vertexShaders.find(name);
if (find_it == vertexShaders.end())
{
vertexShaders.emplace(name, vertexShader);
#if V_DEBUG && V_DEBUG_LOG_CONSOLE
auto logger = &Voxel::Logger::getInstance();
logger->consoleInfo("[ShaderManager] Successfully added vertex shader: " + name + " with shader object: " + std::to_string(vertexShader->getObject()));
#endif
return true;
}
else
{
return false;
}
}
bool ShaderManager::addFragmentShader(const std::string & name, Shader * fragmentShader)
{
auto find_it = fragmentShaders.find(name);
if (find_it == fragmentShaders.end())
{
fragmentShaders.emplace(name, fragmentShader);
#if V_DEBUG && V_DEBUG_LOG_CONSOLE
auto logger = &Voxel::Logger::getInstance();
logger->consoleInfo("[ShaderManager] Successfully added fragment shader: " + name + " with shader object: " + std::to_string(fragmentShader->getObject()));
#endif
return true;
}
else
{
return false;
}
}
Shader * ShaderManager::getVertexShader(const std::string & name)
{
auto find_it = vertexShaders.find(name);
if (find_it == vertexShaders.end())
{
return nullptr;
}
else
{
return find_it->second;
}
}
Shader * ShaderManager::getFragmentShader(const std::string & name)
{
auto find_it = fragmentShaders.find(name);
if (find_it == fragmentShaders.end())
{
return nullptr;
}
else
{
return find_it->second;
}
}
void Voxel::ShaderManager::releaseAll()
{
for (auto it : vertexShaders)
{
if (it.second != nullptr)
{
delete it.second;
}
}
vertexShaders.clear();
for (auto it : fragmentShaders)
{
if (it.second != nullptr)
{
delete it.second;
}
}
fragmentShaders.clear();
}
| 19.315068 | 157 | 0.692199 | [
"geometry",
"object"
] |
b2fcf112bcabd6f336a0408ff80810e56bd9ee45 | 826 | cpp | C++ | solutions/cpp/Problem83.cpp | tjyiiuan/LeetCode | abd10944c6a1f7a7f36bd9b6218c511cf6c0f53e | [
"MIT"
] | null | null | null | solutions/cpp/Problem83.cpp | tjyiiuan/LeetCode | abd10944c6a1f7a7f36bd9b6218c511cf6c0f53e | [
"MIT"
] | null | null | null | solutions/cpp/Problem83.cpp | tjyiiuan/LeetCode | abd10944c6a1f7a7f36bd9b6218c511cf6c0f53e | [
"MIT"
] | null | null | null | #pragma once
/*
83. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
*/
#include "Source.h"
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL)
{
return head;
}
int last = head->val;
int curVal = 0;
ListNode* result = new ListNode(last);
ListNode* curNode = result;
while (head != NULL)
{
curVal = head->val;
if (curVal != last)
{
curNode->next = new ListNode(curVal);
curNode = curNode->next;
last = curVal;
}
head = head->next;
}
return result;
}
void test() {
std::vector<int> vecTest = { 1,1,2,3,3,6,6,6,6,6,6,7,9 };
ListNode* nodeTest = vecToNode(vecTest);
ListNode* nodeResult = deleteDuplicates(nodeTest);
printListNode(nodeResult);
}
};
| 19.666667 | 90 | 0.646489 | [
"vector"
] |
650046297f873f017933ec0fa0311b08524588ce | 8,064 | cpp | C++ | dungeonCrawler.cpp | Dcooley1350/DungeonCrawler | 9ea7b7e6f06fc24d923b262f002f1528059cd0da | [
"MIT"
] | null | null | null | dungeonCrawler.cpp | Dcooley1350/DungeonCrawler | 9ea7b7e6f06fc24d923b262f002f1528059cd0da | [
"MIT"
] | null | null | null | dungeonCrawler.cpp | Dcooley1350/DungeonCrawler | 9ea7b7e6f06fc24d923b262f002f1528059cd0da | [
"MIT"
] | null | null | null |
#include <iostream>
#include <limits>
#include "dungeonCrawler.hpp"
using std::cin, std::cout, std::endl;
void addObjectsToDungeon(char (&)[MAX_SIZE][MAX_SIZE], char, int);
void addObjectToDungeon(char (&)[MAX_SIZE][MAX_SIZE], char, int []);
void resetStream();
bool validateCharacterInput(char, const char [], int);
void createDungeon(char (&dungeon)[MAX_SIZE][MAX_SIZE], int currentPlayerCoordinates[], int numTraps, int numTreasures)
{
// Fill Dungeon with 'E' for 'empty' areas
for (int i = 0; i < MAX_SIZE; ++i) {
for (int j = 0; j < MAX_SIZE; ++j) {
dungeon[i][j] = EMPTY;
}
}
// Add traps
addObjectsToDungeon(dungeon, TRAP, numTraps);
// Add treasures
addObjectsToDungeon(dungeon, TREASURE, numTreasures);
// Add player start
addObjectToDungeon(dungeon, PLAYER, currentPlayerCoordinates);
// Add exit
addObjectsToDungeon(dungeon, EXIT, 1);
}
void addObjectsToDungeon(char (&dungeon)[MAX_SIZE][MAX_SIZE], char object, int numObjectsToAdd)
{
for (int i = 0; i < numObjectsToAdd;) {
int xCoordinate = rand() % MAX_SIZE;
int yCoordinate = rand() % MAX_SIZE;
if(dungeon[yCoordinate][xCoordinate] == EMPTY){
dungeon[yCoordinate][xCoordinate] = object;
i++;
}
}
}
void addObjectToDungeon(char (&dungeon)[MAX_SIZE][MAX_SIZE], char object, int coordinates[])
{
bool openLocation;
do {
int xCoordinate = rand() % MAX_SIZE;
int yCoordinate = rand() % MAX_SIZE;
if(dungeon[yCoordinate][xCoordinate] == EMPTY){
dungeon[yCoordinate][xCoordinate] = object;
openLocation = true;
coordinates[X_AXIS] = xCoordinate;
coordinates[Y_AXIS] = yCoordinate;
}
} while(!openLocation);
}
void displayDungeon(const char (&dungeon)[MAX_SIZE][MAX_SIZE])
{
for (int i = 0; i < MAX_SIZE; ++i) {
for (int j = 0; j < MAX_SIZE; ++j) {
cout << '[' << dungeon[i][j] << ']';
}
cout << endl;
}
}
void getMove(const int currentPlayerCoordinates[], int nextPlayerCoordinates[])
{
bool validInput;
char userInput;
cout << "Where to next, explorer? (W,A,S,D)" << endl;
do {
cin >> userInput;
// Uppercase the input to allow lower and uppercase entries
userInput = static_cast<char>(toupper(userInput));
// Check input for fail or invalid characters
if(!cin.fail() && validateCharacterInput( userInput, ACCEPTABLE_MOVES, NUM_VALID_INPUTS)){
//Input is valid, must make sure it is in bounds, then record
switch (userInput) {
case UP:
if((currentPlayerCoordinates[Y_AXIS] - 1) >= 0) {
nextPlayerCoordinates[X_AXIS] = currentPlayerCoordinates[X_AXIS];
nextPlayerCoordinates[Y_AXIS] = currentPlayerCoordinates[Y_AXIS] - 1;
validInput = true;
}
else {
validInput = false;
cout << MOVE_OUT_OF_BOUNDS << endl;
}
break;
case DOWN:
if((currentPlayerCoordinates[Y_AXIS] + 1) < MAX_SIZE) {
nextPlayerCoordinates[X_AXIS] = currentPlayerCoordinates[X_AXIS];
nextPlayerCoordinates[Y_AXIS] = currentPlayerCoordinates[Y_AXIS] + 1;
validInput = true;
}
else {
validInput = false;
cout << MOVE_OUT_OF_BOUNDS << endl;
}
break;
case LEFT:
if((currentPlayerCoordinates[X_AXIS] - 1) >= 0) {
nextPlayerCoordinates[X_AXIS] = currentPlayerCoordinates[X_AXIS] - 1;
nextPlayerCoordinates[Y_AXIS] = currentPlayerCoordinates[Y_AXIS];
validInput = true;
}
else {
validInput = false;
cout << MOVE_OUT_OF_BOUNDS << endl;
}
break;
case RIGHT:
if((currentPlayerCoordinates[X_AXIS] + 1) < MAX_SIZE) {
nextPlayerCoordinates[X_AXIS] = currentPlayerCoordinates[X_AXIS] + 1;
nextPlayerCoordinates[Y_AXIS] = currentPlayerCoordinates[Y_AXIS];
validInput = true;
}
else {
validInput = false;
cout << MOVE_OUT_OF_BOUNDS << endl;
}
break;
default:
break;
}
}
else {
//Input is invalid
validInput = false;
cout << "Invalid input detected. Try again (W,A,S,D)" << endl;
}
} while(!validInput);
}
bool checkMove(const char (&dungeon)[MAX_SIZE][MAX_SIZE], const int newPlayerCoordinates[], char objectToCheck)
{
bool spaceContainsObject = false;
if(dungeon[newPlayerCoordinates[Y_AXIS]][newPlayerCoordinates[X_AXIS]] == objectToCheck){
spaceContainsObject = true;
}
return spaceContainsObject;
}
void updateDungeon(char (&dungeon)[MAX_SIZE][MAX_SIZE], const int currentPlayerCoordinate[], const int newPlayerCoordinate[])
{
dungeon[currentPlayerCoordinate[Y_AXIS]][currentPlayerCoordinate[X_AXIS]] = EMPTY;
dungeon[newPlayerCoordinate[Y_AXIS]][newPlayerCoordinate[X_AXIS]] = PLAYER;
}
bool playAgain()
{
char userInput;
bool playAgain, validInput;
cout << "Would you like to play again?(Y/N)" << endl;
do {
cin >> userInput;
// Uppercase the input to allow lower and uppercase entries
userInput = static_cast<char>(toupper(userInput));
if(!cin.fail() && validateCharacterInput(userInput, ACCEPTABLE_INPUT, 2)){
validInput = true;
}
else {
cout << "Invalid input detected. Enter Y/N." << endl;
resetStream();
validInput = false;
}
} while(!validInput);
if(userInput == 'y'){
playAgain = true;
}
else {
playAgain = false;
}
return playAgain;
}
int getInteger(int min, int max)
{
int userInput, validatedInput;
bool validInput;
do {
cin >> userInput;
// Validate input
if( !cin.fail() && userInput >= min && userInput <= max ) {
validInput = true;
validatedInput = userInput;
}
else {
validInput = false;
cout << "Invalid input detected. Try again" << endl;
resetStream();
}
} while(!validInput);
return validatedInput;
}
bool validateCharacterInput(char input, const char validInputs[], int validInputsLength)
{
bool validInput = false;
for (int i = 0; i < validInputsLength; ++i) {
if(validInputs[i] == input) {
validInput = true;
}
}
return validInput;
}
void resetStream()
{
const long large = std::numeric_limits<std::streamsize>::max();
const char endLine = '\n';
// Clear input and errors
cin.clear();
// Flush the buffer
cin.ignore(large,endLine);
}
void displayWelcome()
{
cout << "Welcome to Dungeon Crawler!" << endl
<< "Avoid traps and gather as much gold as you can on the way to the exit!" << endl
<< "----------" << endl
<< "Map Key:" << endl
<< TREASURE << " = Gold" << endl
<< TRAP << " = Trap" << endl
<< PLAYER << " = Player Position" << endl
<< EXIT << " = Dungeon Exit" << endl
<< "----------" << endl
<< "Controls:" << endl
<< LEFT << " = Move player left" << endl
<< RIGHT << " = Move player right" << endl
<< UP << " = Move player up" << endl
<< DOWN << " = Move player down" << endl;
}
| 33.882353 | 125 | 0.543775 | [
"object"
] |
650993404a619ff7cd4f0b87d3617eb493e8bd80 | 4,830 | cpp | C++ | cpp/SynchrO/SynchrO.cpp | kfsone/tinker | 81ed372117bcad691176aac960302f497adf8d82 | [
"MIT"
] | null | null | null | cpp/SynchrO/SynchrO.cpp | kfsone/tinker | 81ed372117bcad691176aac960302f497adf8d82 | [
"MIT"
] | null | null | null | cpp/SynchrO/SynchrO.cpp | kfsone/tinker | 81ed372117bcad691176aac960302f497adf8d82 | [
"MIT"
] | null | null | null | // SynchrO.cpp : Defines the entry point for the application.
//
#include "SynchrO.h"
#include <array>
#include <atomic>
#include <condition_variable>
#include <limits>
#include <memory>
#include <mutex>
#include <vector>
// Flow:
// - Server launches:
// - recursive directory walk discovers files,
// - each file mmap'd into an MMapRead structure,
// - MMapReads forwarded to transmitter,
//
// Three channels are used:
//
// 1. s->c filenames
// 2. s<-c filename request
// 3. s->c filedata
struct Permissions
{
uint64_t m_permissions;
};
struct MMapRead
{
std::string m_filepath{ "" }; //! source-relative path
void* m_data{ nullptr }; //! pointer to the mapped data or 0
size_t m_size{ 0 };
uint64_t m_ctime, m_mtime; //! created and modified time stamps
Permissions m_perms{};
MMapRead(std::string filepath_);
~MMapRead();
void open(std::string filepath_);
void reset(std::string filepath_)
{
close();
if (!filepath_.empty())
open(filepath_);
}
void close();
void* const data() const noexcept { return m_data; }
size_t size() const noexcept { return m_size; }
};
namespace ThreadSafe
{
namespace Mutexed
{
template<typename T, size_t Size>
struct Histogram
{
std::array<T, Size> m_log;
size_t m_readPos{ 0 };
size_t m_writePos{ 0 };
std::mutex m_mutex;
std::condition_variable m_cv{ m_mutex };
static constexpr size_t c_terminator = std::numeric_limits<decltype(m_readPos)>::max();
void wrappingIncrement(size_t& pos)
{
if (++pos == Size)
pos = 0;
}
template<typename... Args>
void push(Args&&... args)
{
std::lock_guard lock(m_mutex);
m_log[m_writePos] = T(std::forward<Args>(args...));
wrappingIncrement(m_writePos);
m_cv.notify_all();
}
void close()
{
std::lock_guard lock(m_mutex);
m_readPos = c_terminator;
m_cv.notify_all();
}
bool pop(T& into)
{
std::lock_guard lock(m_mutex);
m_cv.wait(lock, []() { return m_readPos != m_writePos; });
if (m_readPos == c_terminator)
return false;
into = std::move(m_log[m_readPos]);
wrappingIncrement(m_readPos);
return true;
}
};
// Thread-safe queue of index values.
template <size_t Size>
struct MPSCIndexQueue
{
static constexpr size_t c_Terminator = std::numeric_limits<size_t>::max();
std::string m_name;
// The list of indexes we're hosting.
std::array<size_t, Size> m_indices{};
// To operate as a queue, we push/pop to the back,
// so we need to know our depth.
size_t m_reservation{ 0 };
std::atomic<size_t> m_depth{ 0 };
bool m_closing;
// Not copy or movable
MSPCIndexQueue(const MSPCIndexQueue&) = delete;
MSPCIndexQueue(MSPCIndexQueue&&) = delete;
MSPCIndexQueue(std::string name) : m_name(name) {}
std::mutex m_queueLock{};
std::condition_variable m_queueCv{};
void push(size_t index_)
{
std::lock_guard lock(m_queueLock);
auto reservation = (m_reservation++) % Size;
if (reservation - m_depth >= Size)
{
// Track how long we spend pending
EventTrack scope(m_name.c_str());
m_queueCv.wait(lock, [=]() { return reservation - m_depth >= Size; })
}
m_indices[reservation] = index_;
m_queueCv.notify_all();
}
size_t pop()
{
std::lock_guard lock(m_queueLock);
while (m_depth == m_reservation)
{
m_queueCv.wait(lock, [=]() { return m_depth == m_reservation; })
}
if (m_depth == c_Terminator)
return m_depth;
auto result = m_indices[m_depth++];
if (m_depth == Size)
}
};
}
}
struct Event
{
const char* m_name;
std::chrono::nanoseconds m_duration;
Event(const char* name_, std::chrono::nanoseconds duration_);
};
ThreadSafe::Mutexed::Histogram<Event, 1 << 22> s_eventLog;
struct EventTrack
{
using event_clock = std::chrono::steady_clock;
event_clock::time_point m_start{ event_clock::now() };
const char* m_name;
EventTrack(const char* name) : m_name(name) {}
~EventTrack()
{
s_eventLog.push(m_name, std::chrono::nanoseconds(event_clock::now() - m_start));
}
};
std::atomic<uint64_t>
std::vector<std::unique_ptr<MMapRead>> g_mmaps;
std::vector<uint64_t> g_freeIndexes;
std::vector<uint64_t> g_loadingIndexes;
std::vector<uint64_t>
void source_service()
{
Worker clientFiles; // tell client which files are available
Worker clientReqs; // get client requests
Worker transmitter; // send the data to the client
Worker mmapper{ transmitter }; // send mmaps to the transmitter
DirectoryWalker walker(args.source);
for (auto dir : walker)
{
client.forward(dir);
mapper.forward(dir);
}
mapper.finish();
transmitter.join();
}
int main(int argc, const char* argv[])
{
parse_arguments();
if (args.source)
source_service();
else
destination_service();
return 0;
}
| 21.659193 | 90 | 0.665217 | [
"vector"
] |
650b237ba164752732ffeb418a0c88c52e095cc6 | 16,032 | cpp | C++ | ext/Objects/dictobject.cpp | creativemindplus/skybison | d1740e08d8de85a0a56b650675717da67de171a0 | [
"CNRI-Python-GPL-Compatible"
] | 278 | 2021-08-31T00:46:51.000Z | 2022-02-13T19:43:28.000Z | ext/Objects/dictobject.cpp | creativemindplus/skybison | d1740e08d8de85a0a56b650675717da67de171a0 | [
"CNRI-Python-GPL-Compatible"
] | 9 | 2021-11-05T22:28:43.000Z | 2021-11-23T08:39:04.000Z | ext/Objects/dictobject.cpp | tekknolagi/skybison | bea8fc2af0a70e7203b4c19f36c14a745512a335 | [
"CNRI-Python-GPL-Compatible"
] | 12 | 2021-08-31T07:49:54.000Z | 2021-10-08T01:09:01.000Z | // Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
// dictobject.c implementation
#include "cpython-func.h"
#include "api-handle.h"
#include "dict-builtins.h"
#include "handles.h"
#include "int-builtins.h"
#include "object-builtins.h"
#include "objects.h"
#include "runtime.h"
#include "str-builtins.h"
namespace py {
PY_EXPORT PyTypeObject* PyDictItems_Type_Ptr() {
Runtime* runtime = Thread::current()->runtime();
return reinterpret_cast<PyTypeObject*>(ApiHandle::borrowedReference(
runtime, runtime->typeAt(LayoutId::kDictItems)));
}
PY_EXPORT PyTypeObject* PyDictIterItem_Type_Ptr() {
Runtime* runtime = Thread::current()->runtime();
return reinterpret_cast<PyTypeObject*>(ApiHandle::borrowedReference(
runtime, runtime->typeAt(LayoutId::kDictItemIterator)));
}
PY_EXPORT PyTypeObject* PyDictIterKey_Type_Ptr() {
Runtime* runtime = Thread::current()->runtime();
return reinterpret_cast<PyTypeObject*>(ApiHandle::borrowedReference(
runtime, runtime->typeAt(LayoutId::kDictKeyIterator)));
}
PY_EXPORT PyTypeObject* PyDictIterValue_Type_Ptr() {
Runtime* runtime = Thread::current()->runtime();
return reinterpret_cast<PyTypeObject*>(ApiHandle::borrowedReference(
runtime, runtime->typeAt(LayoutId::kDictValueIterator)));
}
PY_EXPORT PyTypeObject* PyDictKeys_Type_Ptr() {
Runtime* runtime = Thread::current()->runtime();
return reinterpret_cast<PyTypeObject*>(ApiHandle::borrowedReference(
runtime, runtime->typeAt(LayoutId::kDictKeys)));
}
PY_EXPORT PyTypeObject* PyDictValues_Type_Ptr() {
Runtime* runtime = Thread::current()->runtime();
return reinterpret_cast<PyTypeObject*>(ApiHandle::borrowedReference(
runtime, runtime->typeAt(LayoutId::kDictValues)));
}
PY_EXPORT int PyDict_CheckExact_Func(PyObject* obj) {
return ApiHandle::fromPyObject(obj)->asObject().isDict();
}
PY_EXPORT int PyDict_Check_Func(PyObject* obj) {
return Thread::current()->runtime()->isInstanceOfDict(
ApiHandle::fromPyObject(obj)->asObject());
}
PY_EXPORT Py_ssize_t PyDict_GET_SIZE_Func(PyObject* dict) {
HandleScope scope(Thread::current());
Dict dict_obj(&scope, ApiHandle::fromPyObject(dict)->asObject());
return dict_obj.numItems();
}
PY_EXPORT int _PyDict_SetItem_KnownHash(PyObject* pydict, PyObject* key,
PyObject* value, Py_hash_t pyhash) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return -1;
}
Dict dict(&scope, *dict_obj);
Object key_obj(&scope, ApiHandle::fromPyObject(key)->asObject());
Object value_obj(&scope, ApiHandle::fromPyObject(value)->asObject());
word hash = SmallInt::truncate(pyhash);
if (dictAtPut(thread, dict, key_obj, hash, value_obj).isErrorException()) {
return -1;
}
return 0;
}
PY_EXPORT int PyDict_SetItem(PyObject* pydict, PyObject* key, PyObject* value) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
if (!thread->runtime()->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return -1;
}
Dict dict(&scope, *dict_obj);
Object key_obj(&scope, ApiHandle::fromPyObject(key)->asObject());
Object value_obj(&scope, ApiHandle::fromPyObject(value)->asObject());
Object hash_obj(&scope, Interpreter::hash(thread, key_obj));
if (hash_obj.isError()) return -1;
word hash = SmallInt::cast(*hash_obj).value();
if (dictAtPut(thread, dict, key_obj, hash, value_obj).isErrorException()) {
return -1;
}
return 0;
}
PY_EXPORT int PyDict_SetItemString(PyObject* pydict, const char* key,
PyObject* value) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return -1;
}
Dict dict(&scope, *dict_obj);
Str key_obj(&scope, Runtime::internStrFromCStr(thread, key));
Object value_obj(&scope, ApiHandle::fromPyObject(value)->asObject());
word hash = strHash(thread, *key_obj);
if (dictAtPut(thread, dict, key_obj, hash, value_obj).isErrorException()) {
return -1;
}
return 0;
}
PY_EXPORT PyTypeObject* PyDict_Type_Ptr() {
Runtime* runtime = Thread::current()->runtime();
return reinterpret_cast<PyTypeObject*>(
ApiHandle::borrowedReference(runtime, runtime->typeAt(LayoutId::kDict)));
}
PY_EXPORT PyObject* PyDict_New() {
Runtime* runtime = Thread::current()->runtime();
return ApiHandle::newReferenceWithManaged(runtime, runtime->newDict());
}
static PyObject* getItem(Thread* thread, const Object& dict_obj,
const Object& key) {
HandleScope scope(thread);
// For historical reasons, PyDict_GetItem supresses all errors that may occur.
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
return nullptr;
}
Dict dict(&scope, *dict_obj);
Object hash_obj(&scope, Interpreter::hash(thread, key));
if (hash_obj.isError()) {
thread->clearPendingException();
return nullptr;
}
word hash = SmallInt::cast(*hash_obj).value();
Object result(&scope, dictAt(thread, dict, key, hash));
if (result.isErrorException()) {
thread->clearPendingException();
return nullptr;
}
if (result.isErrorNotFound()) {
return nullptr;
}
return ApiHandle::borrowedReference(runtime, *result);
}
PY_EXPORT PyObject* _PyDict_GetItem_KnownHash(PyObject* pydict, PyObject* key,
Py_hash_t pyhash) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dictobj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dictobj)) {
thread->raiseBadInternalCall();
return nullptr;
}
Dict dict(&scope, *dictobj);
Object key_obj(&scope, ApiHandle::fromPyObject(key)->asObject());
word hash = SmallInt::truncate(pyhash);
Object value(&scope, dictAt(thread, dict, key_obj, hash));
if (value.isError()) return nullptr;
return ApiHandle::borrowedReference(runtime, *value);
}
PY_EXPORT PyObject* PyDict_GetItem(PyObject* pydict, PyObject* key) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Object key_obj(&scope, ApiHandle::fromPyObject(key)->asObject());
return getItem(thread, dict, key_obj);
}
PY_EXPORT PyObject* PyDict_GetItemString(PyObject* pydict, const char* key) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Object key_obj(&scope, thread->runtime()->newStrFromCStr(key));
return getItem(thread, dict, key_obj);
}
PY_EXPORT void PyDict_Clear(PyObject* pydict) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Runtime* runtime = thread->runtime();
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
if (!runtime->isInstanceOfDict(*dict_obj)) {
return;
}
Dict dict(&scope, *dict_obj);
dict.setNumItems(0);
dict.setData(runtime->emptyTuple());
}
PY_EXPORT int PyDict_Contains(PyObject* pydict, PyObject* key) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Dict dict(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Object key_obj(&scope, ApiHandle::fromPyObject(key)->asObject());
Object hash_obj(&scope, Interpreter::hash(thread, key_obj));
if (hash_obj.isErrorException()) return -1;
word hash = SmallInt::cast(*hash_obj).value();
Object result(&scope, dictIncludes(thread, dict, key_obj, hash));
if (result.isErrorException()) return -1;
return Bool::cast(*result).value();
}
PY_EXPORT PyObject* PyDict_Copy(PyObject* pydict) {
Thread* thread = Thread::current();
if (pydict == nullptr) {
thread->raiseBadInternalCall();
return nullptr;
}
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return nullptr;
}
Dict dict(&scope, *dict_obj);
return ApiHandle::newReferenceWithManaged(runtime, dictCopy(thread, dict));
}
PY_EXPORT int PyDict_DelItem(PyObject* pydict, PyObject* key) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return -1;
}
Dict dict(&scope, *dict_obj);
Object key_obj(&scope, ApiHandle::fromPyObject(key)->asObject());
Object hash_obj(&scope, Interpreter::hash(thread, key_obj));
if (hash_obj.isErrorException()) return -1;
word hash = SmallInt::cast(*hash_obj).value();
if (dictRemove(thread, dict, key_obj, hash).isError()) {
thread->raise(LayoutId::kKeyError, *key_obj);
return -1;
}
return 0;
}
PY_EXPORT int PyDict_DelItemString(PyObject* pydict, const char* key) {
PyObject* str = PyUnicode_FromString(key);
if (str == nullptr) return -1;
int result = PyDict_DelItem(pydict, str);
Py_DECREF(str);
return result;
}
PY_EXPORT PyObject* PyDict_GetItemWithError(PyObject* pydict, PyObject* key) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return nullptr;
}
Object key_obj(&scope, ApiHandle::fromPyObject(key)->asObject());
Object hash_obj(&scope, Interpreter::hash(thread, key_obj));
if (hash_obj.isErrorException()) return nullptr;
word hash = SmallInt::cast(*hash_obj).value();
Dict dict(&scope, *dict_obj);
Object value(&scope, dictAt(thread, dict, key_obj, hash));
if (value.isError()) {
return nullptr;
}
return ApiHandle::borrowedReference(runtime, *value);
}
PY_EXPORT PyObject* PyDict_Items(PyObject* pydict) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return nullptr;
}
Dict dict(&scope, *dict_obj);
word len = dict.numItems();
if (len == 0) {
return ApiHandle::newReferenceWithManaged(runtime, runtime->newList());
}
List result(&scope, runtime->newList());
MutableTuple items(&scope, runtime->newMutableTuple(len));
Object key(&scope, NoneType::object());
Object value(&scope, NoneType::object());
for (word i = 0, j = 0; dictNextItem(dict, &i, &key, &value);) {
items.atPut(j++, runtime->newTupleWith2(key, value));
}
result.setItems(*items);
result.setNumItems(len);
return ApiHandle::newReferenceWithManaged(runtime, *result);
}
PY_EXPORT PyObject* PyDict_Keys(PyObject* pydict) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return nullptr;
}
Dict dict(&scope, *dict_obj);
return ApiHandle::newReferenceWithManaged(runtime, dictKeys(thread, dict));
}
PY_EXPORT int PyDict_Merge(PyObject* left, PyObject* right,
int override_matching) {
CHECK_BOUND(override_matching, 2);
Thread* thread = Thread::current();
if (left == nullptr || right == nullptr) {
thread->raiseBadInternalCall();
return -1;
}
HandleScope scope(thread);
Object left_obj(&scope, ApiHandle::fromPyObject(left)->asObject());
if (!thread->runtime()->isInstanceOfDict(*left_obj)) {
thread->raiseBadInternalCall();
return -1;
}
Dict left_dict(&scope, *left_obj);
Object right_obj(&scope, ApiHandle::fromPyObject(right)->asObject());
auto merge_func = override_matching ? dictMergeOverride : dictMergeIgnore;
if ((*merge_func)(thread, left_dict, right_obj).isError()) {
return -1;
}
return 0;
}
PY_EXPORT int PyDict_MergeFromSeq2(PyObject* /* d */, PyObject* /* 2 */,
int /* e */) {
UNIMPLEMENTED("PyDict_MergeFromSeq2");
}
PY_EXPORT int _PyDict_Next(PyObject* dict, Py_ssize_t* ppos, PyObject** pkey,
PyObject** pvalue, Py_hash_t* phash) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(dict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
return 0;
}
Dict dict_dict(&scope, *dict_obj);
// Below are all the possible statuses of ppos and what to do in each case.
// * If an index is out of bounds, we should not advance.
// * If an index does not point to a valid bucket, we should try and find the
// next bucket, or fail.
// * Read the contents of that bucket.
// * Advance the index.
Object key(&scope, NoneType::object());
Object value(&scope, NoneType::object());
word hash;
if (!dictNextItemHash(dict_dict, ppos, &key, &value, &hash)) {
return 0;
}
// At this point, we will always have a valid bucket index.
if (pkey != nullptr) *pkey = ApiHandle::borrowedReference(runtime, *key);
if (pvalue != nullptr) {
*pvalue = ApiHandle::borrowedReference(runtime, *value);
}
if (phash != nullptr) *phash = hash;
return true;
}
PY_EXPORT int PyDict_Next(PyObject* dict, Py_ssize_t* ppos, PyObject** pkey,
PyObject** pvalue) {
return _PyDict_Next(dict, ppos, pkey, pvalue, nullptr);
}
PY_EXPORT Py_ssize_t PyDict_Size(PyObject* p) {
Thread* thread = Thread::current();
Runtime* runtime = thread->runtime();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(p)->asObject());
if (!runtime->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return -1;
}
Dict dict(&scope, *dict_obj);
return dict.numItems();
}
PY_EXPORT int PyDict_Update(PyObject* left, PyObject* right) {
return PyDict_Merge(left, right, 1);
}
PY_EXPORT PyObject* PyDict_Values(PyObject* pydict) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object dict_obj(&scope, ApiHandle::fromPyObject(pydict)->asObject());
Runtime* runtime = thread->runtime();
if (!runtime->isInstanceOfDict(*dict_obj)) {
thread->raiseBadInternalCall();
return nullptr;
}
Dict dict(&scope, *dict_obj);
word len = dict.numItems();
if (len == 0) {
return ApiHandle::newReferenceWithManaged(runtime, runtime->newList());
}
List result(&scope, runtime->newList());
MutableTuple values(&scope, runtime->newMutableTuple(len));
Object value(&scope, NoneType::object());
for (word i = 0, j = 0; dictNextValue(dict, &i, &value);) {
values.atPut(j++, *value);
}
result.setItems(*values);
result.setNumItems(len);
return ApiHandle::newReferenceWithManaged(runtime, *result);
}
PY_EXPORT PyObject* PyObject_GenericGetDict(PyObject* obj, void*) {
Thread* thread = Thread::current();
HandleScope scope(thread);
Object object(&scope, ApiHandle::fromPyObject(obj)->asObject());
Runtime* runtime = thread->runtime();
Object name(&scope, runtime->symbols()->at(ID(__dict__)));
Object dict(&scope, objectGetAttribute(thread, object, name));
if (dict.isError()) {
thread->raiseWithFmt(LayoutId::kAttributeError,
"This object has no __dict__");
return nullptr;
}
return ApiHandle::newReference(runtime, *dict);
}
} // namespace py
| 35.004367 | 80 | 0.698291 | [
"object"
] |
650bc57baf54015bc0a965d92a49813ed3a609d0 | 6,267 | cpp | C++ | toolboxes/mri/pmri/gpu/cuBuffer.cpp | roopchansinghv/gadgetron | fb6c56b643911152c27834a754a7b6ee2dd912da | [
"MIT"
] | 1 | 2022-02-22T21:06:36.000Z | 2022-02-22T21:06:36.000Z | toolboxes/mri/pmri/gpu/cuBuffer.cpp | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | toolboxes/mri/pmri/gpu/cuBuffer.cpp | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | #include "cuBuffer.h"
#include "vector_td_utilities.h"
#include "cuNDArray_operators.h"
#include "cuNDArray_elemwise.h"
#include "cuNDArray_utils.h"
namespace Gadgetron{
template<class REAL, unsigned int D>
cuBuffer<REAL,D>::cuBuffer()
{
acc_buffer_ = boost::shared_ptr< cuNDArray<_complext> >(new cuNDArray<_complext>);
cyc_buffer_ = boost::shared_ptr< cuNDArray<_complext> >(new cuNDArray<_complext>);
num_coils_ = 0;
cur_idx_ = cur_sub_idx_ = 0;
cycle_length_ = 0; sub_cycle_length_ = 0;
acc_buffer_empty_ = true;
Gadgetron::clear(matrix_size_);
Gadgetron::clear(matrix_size_os_);
W_ = REAL(0);
}
template<class REAL, unsigned int D>
void cuBuffer<REAL,D>::clear()
{
Gadgetron::clear(acc_buffer_.get());
Gadgetron::clear(cyc_buffer_.get());
cur_idx_ = cur_sub_idx_ = 0;
acc_buffer_empty_ = true;
}
template<class REAL, unsigned int D>
void cuBuffer<REAL,D>
::setup( _uint64d matrix_size, _uint64d matrix_size_os, REAL W,
unsigned int num_coils, unsigned int num_cycles, unsigned int num_sub_cycles )
{
bool matrix_size_changed = (matrix_size_ == matrix_size);
bool matrix_size_os_changed = (matrix_size_os_ == matrix_size_os);
bool kernel_changed = (W_ == W);
bool num_coils_changed = (num_coils_ == num_coils );
bool num_cycles_changed = (cycle_length_ == num_cycles+1);
matrix_size_ = matrix_size;
matrix_size_os_ = matrix_size_os;
W_ = W;
num_coils_ = num_coils;
cycle_length_ = num_cycles+1; // +1 as we need a "working buffer" in a addition to 'cycle_length' full ones
sub_cycle_length_ = num_sub_cycles;
if( !nfft_plan_ || matrix_size_changed || matrix_size_os_changed || kernel_changed ){
nfft_plan_ = NFFT<cuNDArray,REAL,D>::make_plan( matrix_size_, matrix_size_os_, W );
}
std::vector<size_t> dims = to_std_vector(matrix_size_os_);
dims.push_back(num_coils_);
if( acc_buffer_->get_number_of_elements() == 0 || matrix_size_os_changed || num_coils_changed ){
acc_buffer_->create(&dims);
Gadgetron::clear( acc_buffer_.get() );
}
dims.push_back(cycle_length_);
if( cyc_buffer_->get_number_of_elements() == 0 || matrix_size_os_changed || num_coils_changed ){
cyc_buffer_->create(&dims);
Gadgetron::clear( cyc_buffer_.get() );
}
else if( num_cycles_changed ){
// Reuse the old buffer content in this case...
// This happens automatically (in all cases?) with the current design?
}
}
template<class REAL, unsigned int D>
bool cuBuffer<REAL,D>::add_frame_data( cuNDArray<_complext> *samples, cuNDArray<_reald> *trajectory )
{
if( !samples || !trajectory ){
throw std::runtime_error("cuBuffer::add_frame_data: illegal input pointer");
}
if( num_coils_ != samples->get_size(samples->get_number_of_dimensions()-1) ){
throw std::runtime_error("cuBuffer::add_frame_data: unexpected number of coils according to setup");
}
//if( dcw_.get() == 0x0 ){
//throw std::runtime_error("cuBuffer::density compensation weights not set");
//}
// Make array containing the "current" buffer from the cyclic buffer
//
cuNDArray<_complext> cur_buffer(acc_buffer_->get_dimensions().get(),
cyc_buffer_->get_data_ptr()+cur_idx_*acc_buffer_->get_number_of_elements());
// Preprocess frame
//
nfft_plan_->preprocess( trajectory, NFFT_prep_mode::NC2C );
// Convolve to form k-space frame (accumulation mode)
//
{
if (dcw_) {
auto samples_rescaled = *samples;
samples_rescaled *= *dcw_;
nfft_plan_->convolve(samples_rescaled, cur_buffer, NFFT_conv_mode::NC2C, true);
} else {
nfft_plan_->convolve(*samples, cur_buffer, NFFT_conv_mode::NC2C, true);
}
}
// Update the accumulation buffer (if it is time...)
//
bool cycle_completed = false;
if( cur_sub_idx_ == sub_cycle_length_-1 ){
cycle_completed = true;
// Buffer complete, add to accumulation buffer
//
*acc_buffer_ += cur_buffer;
acc_buffer_empty_ = false;
// Start filling the next buffer in the cycle ...
//
cur_idx_++;
if( cur_idx_ == cycle_length_ ) cur_idx_ = 0;
// ... but first subtract this next buffer from the accumulation buffer
//
cur_buffer.create( acc_buffer_->get_dimensions().get(), cyc_buffer_->get_data_ptr()+cur_idx_*acc_buffer_->get_number_of_elements() );
*acc_buffer_ -= cur_buffer;
// Clear new buffer before refilling
//
Gadgetron::clear(&cur_buffer);
}
cur_sub_idx_++;
if( cur_sub_idx_ == sub_cycle_length_ ) cur_sub_idx_ = 0;
return cycle_completed;
}
template<class REAL, unsigned int D>
boost::shared_ptr< cuNDArray<complext<REAL> > > cuBuffer<REAL,D>::get_accumulated_coil_images()
{
std::vector<size_t> dims = to_std_vector(matrix_size_);
dims.push_back(num_coils_);
acc_image_ = boost::shared_ptr< cuNDArray<_complext> >( new cuNDArray<_complext>(&dims) );
// Check if we are ready to reconstruct. If not return an image of ones...
if( acc_buffer_empty_ ){
fill(acc_image_.get(),_complext(1));
return acc_image_;
}
// Finalize gridding of k-space CSM image (convolution has been done already)
//
// Copy accumulation buffer before in-place FFT
cuNDArray<_complext> acc_copy = *acc_buffer_;
// FFT
nfft_plan_->fft( acc_copy, NFFT_fft_mode::BACKWARDS );
// Deapodize
nfft_plan_->deapodize( acc_copy );
// Remove oversampling
crop<_complext,D>( (matrix_size_os_-matrix_size_)>>1, matrix_size_, acc_copy, *acc_image_ );
//if( normalize ){
//REAL scale = REAL(1)/(((REAL)cycle_length_-REAL(1))*(REAL)sub_cycle_length_);
//*acc_image_ *= scale;
//}
return acc_image_;
}
//
// Instantiations
//
template class EXPORTGPUPMRI cuBuffer<float,2>;
template class EXPORTGPUPMRI cuBuffer<float,3>;
template class EXPORTGPUPMRI cuBuffer<float,4>;
template class EXPORTGPUPMRI cuBuffer<double,2>;
template class EXPORTGPUPMRI cuBuffer<double,3>;
template class EXPORTGPUPMRI cuBuffer<double,4>;
}
| 31.335 | 139 | 0.673528 | [
"vector"
] |
6511c1f6e1fda1a5e897b01f5618e1ab15c7c664 | 5,341 | hpp | C++ | examples/mantevo/miniFE-1.1/optional/stk_mesh/base/DataTraitsEnum.hpp | sdressler/objekt | 30ee938f5cb06193871f802be0bbdae6ecd26a33 | [
"BSD-3-Clause"
] | 1 | 2019-11-26T22:24:12.000Z | 2019-11-26T22:24:12.000Z | examples/mantevo/miniFE-1.1/optional/stk_mesh/base/DataTraitsEnum.hpp | sdressler/objekt | 30ee938f5cb06193871f802be0bbdae6ecd26a33 | [
"BSD-3-Clause"
] | null | null | null | examples/mantevo/miniFE-1.1/optional/stk_mesh/base/DataTraitsEnum.hpp | sdressler/objekt | 30ee938f5cb06193871f802be0bbdae6ecd26a33 | [
"BSD-3-Clause"
] | null | null | null | /*------------------------------------------------------------------------*/
/* Copyright 2010 Sandia Corporation. */
/* Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive */
/* license for use of this work by or on behalf of the U.S. Government. */
/* Export of this program may require a license from the */
/* United States Government. */
/*------------------------------------------------------------------------*/
#include <stk_mesh/base/DataTraits.hpp>
#include <stk_util/environment/ReportHandler.hpp>
//----------------------------------------------------------------------
namespace stk {
namespace mesh {
template< typename EnumType > class DataTraitsEnum ;
//----------------------------------------------------------------------
//----------------------------------------------------------------------
namespace {
template< typename T >
class DataTraitsEnum : public DataTraits {
public:
DataTraitsEnum( const char * name , std::size_t n )
: DataTraits( typeid(T) , name , sizeof(T) , sizeof(T) )
{
is_pod = true ;
is_enum = true ;
enum_info.reserve( n );
}
void add_member( const char * n , T v )
{
const std::size_t i = enum_info.size();
enum_info.resize( i + 1 );
enum_info[i].name.assign( n );
enum_info[i].value = static_cast<long>( v );
}
void construct( void * v , std::size_t n ) const
{
const T init = static_cast<T>( enum_info.front().value );
T * x = reinterpret_cast<T*>(v);
T * const x_end = x + n ;
while ( x_end != x ) { *x++ = init ; }
}
void destroy( void * v , std::size_t n ) const {}
void copy( void * vx , const void * vy , std::size_t n ) const
{
const T * y = reinterpret_cast<const T*>(vy);
T * x = reinterpret_cast<T*>(vx);
T * const x_end = x + n ;
while ( x_end != x ) { *x++ = *y++ ; }
}
void max( void * vx , const void * vy , std::size_t n ) const
{
const T * y = reinterpret_cast<const T*>(vy);
T * x = reinterpret_cast<T*>(vx);
T * const x_end = x + n ;
for ( ; x_end != x ; ++x , ++y ) { if ( *x < *y ) { *x = *y ; } }
}
void min( void * vx , const void * vy , std::size_t n ) const
{
const T * y = reinterpret_cast<const T*>(vy);
T * x = reinterpret_cast<T*>(vx);
T * const x_end = x + n ;
for ( ; x_end != x ; ++x , ++y ) { if ( *x > *y ) { *x = *y ; } }
}
void print_one( std::ostream & s , T v ) const
{
std::vector<EnumMember>::const_iterator i = enum_info.begin();
for ( ; i != enum_info.end() && i->value != v ; ++i );
if ( i != enum_info.end() ) {
s << i->name ;
}
else {
s << name << "( " << static_cast<long>( v ) << " VALUE_NOT_VALID )" ;
}
}
void print( std::ostream & s , const void * v , std::size_t n ) const
{
if ( n ) {
const T * x = reinterpret_cast<const T*>(v);
const T * const x_end = x + n ;
print_one( s , *x++ );
while ( x_end != x ) { s << " " ; print_one( s , *x++ ); }
}
}
void pack( CommBuffer & buf , const void * v , std::size_t n ) const
{
const T * x = reinterpret_cast<const T*>(v);
buf.pack<T>( x , n );
}
void unpack( CommBuffer & buf , void * v , std::size_t n ) const
{
T * x = reinterpret_cast<T*>(v);
buf.unpack<T>( x , n );
}
void sum( void * , const void * , std::size_t ) const
{ ThrowErrorMsg( "not supported" ); }
void bit_and( void * , const void * , std::size_t ) const
{ ThrowErrorMsg( "not supported" ); }
void bit_or( void * , const void * , std::size_t ) const
{ ThrowErrorMsg( "not supported" ); }
void bit_xor( void * , const void * , std::size_t ) const
{ ThrowErrorMsg( "not supported" ); }
};
}
//----------------------------------------------------------------------
#define DATA_TRAITS_ENUM_1( T , V1 ) \
namespace { \
class DataTraitsEnum ## T : public DataTraitsEnum<T> { \
public: \
DataTraitsEnum ## T () : DataTraitsEnum<T>( # T , 1 ) \
{ add_member( # V1 , V1 ); } \
}; \
} \
template<> const DataTraits & data_traits< T >() \
{ static const DataTraitsEnum ## T traits ; return traits ; }
//----------------------------------------------------------------------
#define DATA_TRAITS_ENUM_2( T , V1 , V2 ) \
namespace { \
class DataTraitsEnum ## T : public DataTraitsEnum<T> { \
public: \
DataTraitsEnum ## T () : DataTraitsEnum<T>( # T , 2 ) \
{ \
add_member( # V1 , V1 ); \
add_member( # V2 , V2 ); \
} \
}; \
} \
template<> const DataTraits & data_traits< T >() \
{ static const DataTraitsEnum ## T traits ; return traits ; }
//----------------------------------------------------------------------
#define DATA_TRAITS_ENUM_3( T , V1 , V2 , V3 ) \
namespace { \
class DataTraitsEnum ## T : public DataTraitsEnum<T> { \
public: \
DataTraitsEnum ## T () : DataTraitsEnum<T>( # T , 3 ) \
{ \
add_member( # V1 , V1 ); \
add_member( # V2 , V2 ); \
add_member( # V3 , V3 ); \
} \
}; \
} \
template<> const DataTraits & data_traits< T >() \
{ static const DataTraitsEnum ## T traits ; return traits ; }
//----------------------------------------------------------------------
} // namespace mesh
} // namespace stk
| 30.005618 | 76 | 0.478937 | [
"mesh",
"vector"
] |
6517940f7e332086ab5a5bbce9ca8d6943987a82 | 2,657 | cpp | C++ | codeforces/practice/EDU2_76F.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 3 | 2020-02-08T10:34:16.000Z | 2020-02-09T10:23:19.000Z | codeforces/practice/EDU2_76F.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | null | null | null | codeforces/practice/EDU2_76F.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 2 | 2020-10-02T19:05:32.000Z | 2021-09-08T07:01:49.000Z | // Optimise
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/home/shahraaz/bin/debug.h"
#else
#define db(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
#define all(v) v.begin(), v.end()
const int AUX = 5e6 + 5, MOD = 1000000007;
const int NAX = 100, K = 15;
int n, t = 1;
ll a[NAX];
ll a1[NAX];
ll a2[NAX];
int lst[AUX];
map<int, int> nxt[AUX];
vector<int> get_diff(ll *arr, int x)
{
// db("b");
vector<int> cnt(n);
for (size_t i = 0; i < n; i++)
cnt[i] = __builtin_popcount(arr[i] ^ x);
// db("c", n, n - 1);
vector<int> diff(n - 1);
for (size_t i = 0; i + 1 < n; i++)
diff[i] = cnt[i + 1] - cnt[0];
// db("d");
return diff;
}
int get_nxt(int v, int x)
{
if (!nxt[v].count(x))
nxt[v][x] = t++;
return nxt[v][x];
}
void add(vector<int> diff, int x)
{
int v = 0;
for (auto &i : diff)
v = get_nxt(v, i);
lst[v] = x;
}
int try_find(vector<int> diff)
{
int v = 0;
for (auto &i : diff)
{
if (!nxt[v].count(i))
return -1;
v = nxt[v][i];
}
return lst[v];
}
class Solution
{
private:
public:
Solution() {}
~Solution() {}
void solveCase()
{
cin >> n;
for (size_t i = 0; i < n; i++)
{
cin >> a[i];
a1[i] = a[i] >> K;
a2[i] = a[i] ^ (a1[i] << K);
}
// db("a");
for (size_t i = 0; i < 1 << K; i++)
{
auto d = get_diff(a1, i);
add(d, i);
}
// db("a");
for (size_t i = 0; i < 1 << K; i++)
{
auto d = get_diff(a2, i);
for (size_t j = 0; j + 1 < n; j++)
d[j] *= -1;
int x = try_find(d);
if (x != -1)
{
ll res = (ll(x) << K) ^ i;
#ifdef LOCAL
for (size_t i = 0; i < n; i++)
{
cout << __builtin_popcount(a[i] ^ res) << ' ';
}
cout << '\n';
#else
#endif
cout << res << '\n';
return;
}
}
cout << -1 << '\n';
}
};
int32_t main()
{
// db("Start");
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
// cin >> t;
Solution mySolver;
for (int i = 1; i <= t; ++i)
{
mySolver.solveCase();
#ifdef LOCAL
cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n";
TimeStart = chrono::steady_clock::now();
#endif
}
return 0;
}
| 19.536765 | 131 | 0.424915 | [
"vector"
] |
651ab2757d4f7bec541fbb516693b3add92116b4 | 1,583 | cpp | C++ | Algorithms/0883.ProjectionAreaOf3DShapes/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0883.ProjectionAreaOf3DShapes/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0883.ProjectionAreaOf3DShapes/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <vector>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
int projectionArea(std::vector<std::vector<int>> const &grid) const
{
const size_t rowCount = grid.size();
const size_t columnCount = grid.front().size();
int xyProjection = 0;
for (size_t row = 0; row < rowCount; ++row)
{
for (size_t column = 0; column < columnCount; ++column)
{
if (grid[row][column] > 0)
++xyProjection;
}
}
int xzProjection = 0;
for (size_t row = 0; row < rowCount; ++row)
{
xzProjection += (*std::max_element(grid[row].cbegin(), grid[row].cend()));
}
int yzProjection = 0;
for (size_t column = 0; column < columnCount; ++column)
{
int maxValue = 0;
for (size_t row = 0; row < rowCount; ++row)
maxValue = std::max(maxValue, grid[row][column]);
yzProjection += maxValue;
}
return xyProjection + xzProjection + yzProjection;
}
};
}
namespace ProjectionAreaOf3DShapesTask
{
TEST(ProjectionAreaOf3DShapesTaskTests, Examples)
{
const Solution solution;
ASSERT_EQ(17, solution.projectionArea({{1, 2}, {3, 4}}));
ASSERT_EQ(5, solution.projectionArea({{2}}));
ASSERT_EQ(8, solution.projectionArea({{1, 0}, {0, 2}}));
ASSERT_EQ(14, solution.projectionArea({{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}));
ASSERT_EQ(21, solution.projectionArea({{2, 2, 2}, {2, 1, 2}, {2, 2, 2}}));
}
} | 27.77193 | 86 | 0.55338 | [
"vector"
] |
fb974793bebeaded3ea73765fe458c4e39f95df0 | 4,505 | cpp | C++ | Outils/lata2dx/lata2dx/commun_triou/Lata_tools.cpp | cea-trust-platform/trust-code | c4f42d8f8602a8cc5e0ead0e29dbf0be8ac52f72 | [
"BSD-3-Clause"
] | 12 | 2021-06-30T18:50:38.000Z | 2022-03-23T09:03:16.000Z | Outils/lata2dx/lata2dx/commun_triou/Lata_tools.cpp | pledac/trust-code | 46ab5c5da3f674185f53423090f526a38ecdbad1 | [
"BSD-3-Clause"
] | null | null | null | Outils/lata2dx/lata2dx/commun_triou/Lata_tools.cpp | pledac/trust-code | 46ab5c5da3f674185f53423090f526a38ecdbad1 | [
"BSD-3-Clause"
] | 2 | 2021-10-04T09:19:39.000Z | 2021-12-15T14:21:04.000Z | /*****************************************************************************
*
* Copyright (c) 2011 - 2013, CEA
* 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 CEA, 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 REGENTS 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 REGENTS AND 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 <Lata_tools.h>
#include <ArrOfInt.h>
#include <ArrOfDouble.h>
#include <ArrOfFloat.h>
#include <ArrOfBit.h>
#include <sstream>
#include <string.h>
#include <stdlib.h>
static int journal_level = 0;
void set_Journal_level(entier level)
{
if (journal_level==level) return;
journal_level = level;
Journal() << "Changed lata journal level: " << journal_level << endl;
}
static std::ostringstream junk_journal;
std::ostream & Journal(entier level)
{
if (level <= journal_level) {
cerr << "[" << level << "] ";
return cerr;
} else {
junk_journal.seekp(0);
return junk_journal;
}
}
// Description: this method must return the total memory consumption
// of the object (used to compute the size of the data cache)
BigEntier LataObject::compute_memory_size() const
{
Journal() << "Error in LataObject::compute_memory_size(): function not implemented" << endl;
throw;
}
BigEntier memory_size(const ArrOfInt & tab)
{
// On ne tient pas compte du caractere smart_resize ou ref du tableau
// c'est pas tres grave pour l'instant pour ce qu'on en fait...
return ((BigEntier)sizeof(tab)) + ((BigEntier)tab.size_array()) * sizeof(entier);
}
BigEntier memory_size(const ArrOfDouble & tab)
{
// on ne tient pas compte du caractere smart_resize ou ref du tableau
// c'est pas tres grave pour l'instant pour ce qu'on en fait...
return ((BigEntier)sizeof(tab)) + ((BigEntier)tab.size_array()) * sizeof(double);
}
BigEntier memory_size(const ArrOfFloat & tab)
{
// on ne tient pas compte du caractere smart_resize ou ref du tableau
// c'est pas tres grave pour l'instant pour ce qu'on en fait...
return ((BigEntier)sizeof(tab)) + ((BigEntier)tab.size_array()) * sizeof(float);
}
BigEntier memory_size(const ArrOfBit & tab)
{
return ((BigEntier)sizeof(tab)) + ((BigEntier)tab.size_array()) * sizeof(int) / 32;
}
void split_path_filename(const char *s, Nom & path, Nom & filename)
{
int i;
for (i=(int)strlen(s)-1;i>=0;i--)
if ((s[i]==PATH_SEPARATOR) || (s[i]=='\\'))
break;
path = "";
int j;
for (j = 0; j <= i; j++)
path += Nom(s[j]);
// Parse basename : if extension given, remove it
filename = s+i+1;
}
static const ArrOfInt * array_to_sort_ptr = 0;
int compare_indirect(const void *ptr1, const void *ptr2)
{
entier i1 = *(const entier*)ptr1;
entier i2 = *(const entier*)ptr2;
entier diff = (*array_to_sort_ptr)[i1] - (*array_to_sort_ptr)[i2];
return (diff>0) ? 1 : ((diff==0) ? 0 : -1);
}
void array_sort_indirect(const ArrOfInt & array_to_sort, ArrOfInt & index)
{
const entier n = array_to_sort.size_array();
index.set_smart_resize(1);
index.resize_array(n);
for (entier i = 0; i < n; i++)
index[i] = i;
array_to_sort_ptr = &array_to_sort;
qsort(index.addr(), n, sizeof(entier), compare_indirect);
}
| 34.922481 | 94 | 0.683907 | [
"object"
] |
fba2ce3f340e1d71f92b71d020b7dfc3c2e21c4a | 1,001 | cpp | C++ | test/source/postalt.cpp | tigeroses/bwa-postalt | 74bc52e931a03395708c5038394055a29f1babbf | [
"Unlicense"
] | 2 | 2020-10-21T08:24:48.000Z | 2022-01-17T10:04:44.000Z | test/source/postalt.cpp | tigeroses/bwa-postalt | 74bc52e931a03395708c5038394055a29f1babbf | [
"Unlicense"
] | null | null | null | test/source/postalt.cpp | tigeroses/bwa-postalt | 74bc52e931a03395708c5038394055a29f1babbf | [
"Unlicense"
] | null | null | null |
#include <doctest/doctest.h>
#include <postalt/postalt.h>
#include <postalt/version.h>
#include <string>
#include <vector>
TEST_CASE("Postalt") {
using namespace postalt;
Postalt postalt("Tests");
std::vector<std::string> l;
l.push_back("F221 99 chr11 105017764 0 100M = 105018042 378 TAGCAAGGCAGGCCAACATTCAGATTCAGGAAATACAGAGAATGCCACAAAGATACTCCTCGAGAAGAGCAACTCCAAGACACATAATTGTCAGATTCAC FEF;BFFFF?FFFBEFEFEFFDFFD?FEFFFDEEFCFF?F4E9FFFFDFECFBEDFFFBFEFFFFEFEFFFFFF?FDDFFEEFFCFEFCFFEFFFDFEFF NM:i:0 MD:Z:100 AS:i:100 XS:i:100 RG:Z:90");
l.push_back("F221 147 chr11 105018042 0 100M = 105017764 -378 TATCCAGCCAAACTAAGCTTCATAAGTGAAGGAGAAATAAAATACTTTACAGACAAGCAAATGCTGAGAGATTTTGTCACCACCAGGCCTGCCCTAAAAG FEEFFEFFEFFEFEFFFFFFFFEFFFFFFFFFFEFFFFFFFFFFFFFEFFEFFFEEFFFFFFFFFFFFFFEFFFFFFFFFFFFFEFFFFFFFFFFFFFFF NM:i:0 MD:Z:100 AS:i:100 XS:i:100 RG:Z:90");
std::string out;
CHECK(postalt.run(l, out));
}
TEST_CASE("Postalt version") { CHECK(std::string(POSTALT_VERSION) == std::string("1.0.0")); }
| 47.666667 | 310 | 0.805195 | [
"vector"
] |
fba3fa5adaf91bf2738dbd70c3605016a786bc25 | 676 | cpp | C++ | Cplus/StrangePrinter.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | 1 | 2018-01-22T12:06:28.000Z | 2018-01-22T12:06:28.000Z | Cplus/StrangePrinter.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | Cplus/StrangePrinter.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
int strangePrinter(string s)
{
if (s.empty())
return 0;
int N = s.length();
vector<vector<int>> dp(N, vector<int>(N, -1));
return memdp(s, 0, N - 1, dp);
}
int memdp(const string &s, int first, int last, vector<vector<int>> &dp)
{
if (first > last)
return 0;
if (dp[first][last] != -1)
return dp[first][last];
int res = memdp(s, first + 1, last, dp) + 1;
for (int k = first + 1; k <= last; ++k)
{
if (s[k] == s[first])
res = min(res, memdp(s, first, k - 1, dp) + memdp(s, k + 1, last, dp));
}
return dp[first][last] = res;
}
}; | 21.125 | 75 | 0.572485 | [
"vector"
] |
fba6e10e4c65d89f017d2aa919850dfb3a176372 | 16,390 | cpp | C++ | tests/TestFilesystemFunc.cpp | end2endzone/msbuildreorder | 9df4df177092e2ad141692ec7b43eb814b806d9b | [
"MIT"
] | 9 | 2018-12-18T11:56:26.000Z | 2022-01-17T07:51:10.000Z | tests/TestFilesystemFunc.cpp | end2endzone/msbuildreorder | 9df4df177092e2ad141692ec7b43eb814b806d9b | [
"MIT"
] | 15 | 2018-02-09T21:37:10.000Z | 2019-07-20T19:31:41.000Z | tests/TestFilesystemFunc.cpp | end2endzone/msbuildreorder | 9df4df177092e2ad141692ec7b43eb814b806d9b | [
"MIT"
] | 3 | 2018-12-18T11:56:29.000Z | 2022-03-07T09:26:25.000Z | #include "TestFilesystemFunc.h"
#include "filesystemfunc.h"
#include "nativefunc.h"
#include "gtesthelper.h"
using namespace filesystem;
namespace filesystem { namespace test
{
bool createDummyFile(const char * iPath)
{
FILE * f = fopen(iPath, "w");
if (f == NULL)
return false;
fputs("FOO!\n", f);
fputs("&\n", f);
fputs("BAR\n", f);
fclose(f);
return true;
}
int countValues(const std::vector<std::string> & iList, const std::string & iValue)
{
int count = 0;
for(size_t i=0; i<iList.size(); i++)
{
const std::string & value = iList[i];
if (value == iValue)
count++;
}
return count;
}
//--------------------------------------------------------------------------------------------------
void TestFilesystemFunc::SetUp()
{
}
//--------------------------------------------------------------------------------------------------
void TestFilesystemFunc::TearDown()
{
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetFileSize)
{
//test NULL
{
const char * path = NULL;
uint32_t size = filesystem::getFileSize(path);
ASSERT_EQ(0, size);
}
//test actual value
{
//create dummy file
std::string filename = gTestHelper::getInstance().getTestQualifiedName();
ASSERT_TRUE( createDummyFile(filename.c_str()) );
#ifdef WIN32
static const uint32_t EXPECTED = 14;
#elif UNIX
static const uint32_t EXPECTED = 11;
#endif
//test `const char *` api
uint32_t size = filesystem::getFileSize(filename.c_str());
ASSERT_EQ(EXPECTED, size);
size = 0;
//test `FILE*` api
FILE * ptr = fopen(filename.c_str(), "r");
ASSERT_TRUE(ptr != NULL);
size = filesystem::getFileSize(ptr);
fclose(ptr);
ASSERT_EQ(EXPECTED, size);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetFilename)
{
//test NULL
{
static const std::string EXPECTED = "";
std::string filename = filesystem::getFilename(NULL);
ASSERT_EQ(EXPECTED, filename);
}
//test filename only
{
static const std::string EXPECTED = "foo.bar";
std::string filename = filesystem::getFilename("foo.bar");
ASSERT_EQ(EXPECTED, filename);
}
//test full path (unix style)
{
static const std::string EXPECTED = "foo.bar";
std::string filename = filesystem::getFilename("/home/myFolder/foo.bar");
ASSERT_EQ(EXPECTED, filename);
}
//test full path (windows style)
{
static const std::string EXPECTED = "foo.bar";
std::string filename = filesystem::getFilename("C:\\Users\\Antoine\\Desktop\\myFolder\\foo.bar");
ASSERT_EQ(EXPECTED, filename);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testFileExists)
{
//test NULL
{
bool exists = filesystem::fileExists(NULL);
ASSERT_FALSE(exists);
}
//test not found
{
bool exists = filesystem::fileExists("foo.bar.notfound.bang");
ASSERT_FALSE(exists);
}
//test found
{
//create dummy file
std::string filename = gTestHelper::getInstance().getTestQualifiedName();
ASSERT_TRUE( createDummyFile(filename.c_str()) );
bool exists = filesystem::fileExists(filename.c_str());
ASSERT_TRUE(exists);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testFolderExists)
{
//test NULL
{
bool exists = filesystem::folderExists(NULL);
ASSERT_FALSE(exists);
}
//test not found
{
bool exists = filesystem::folderExists("/home/fooBAR");
ASSERT_FALSE(exists);
}
//test found
{
//create dummy file
std::string currentFolder = filesystem::getCurrentFolder();
ASSERT_TRUE( !currentFolder.empty() );
bool exists = filesystem::folderExists(currentFolder.c_str());
ASSERT_TRUE(exists);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetTemporaryFileName)
{
//test not empty
{
std::string filename = filesystem::getTemporaryFileName();
ASSERT_TRUE( !filename.empty() );
}
//test repetitive
{
std::vector<std::string> filenames;
static const size_t numTest = 20;
for(size_t i=0; i<numTest; i++)
{
std::string filename = filesystem::getTemporaryFileName();
filenames.push_back(filename);
}
//assert that all values are unique
for(size_t i=0; i<numTest; i++)
{
const std::string & filename = filenames[i];
int count = countValues(filenames, filename);
ASSERT_EQ(1, count) << "Found value '" << filename << "' " << count << " times in the list.";
}
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetTemporaryFilePath)
{
//test not empty
{
std::string path = filesystem::getTemporaryFilePath();
ASSERT_TRUE( !path.empty() );
}
//test repetitive
{
std::vector<std::string> paths;
static const size_t numTest = 20;
for(size_t i=0; i<numTest; i++)
{
std::string path = filesystem::getTemporaryFilePath();
paths.push_back(path);
}
//assert that all values are unique
for(size_t i=0; i<numTest; i++)
{
const std::string & path = paths[i];
int count = countValues(paths, path);
ASSERT_EQ(1, count) << "Found value '" << path << "' " << count << " times in the list.";
}
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetParentPath)
{
//test no folder
{
static const std::string EXPECTED = "";
std::string parent = filesystem::getParentPath("filename.bar");
ASSERT_EQ(EXPECTED, parent);
}
//test unix style
{
static const std::string EXPECTED = "/home/myFolder";
std::string parent = filesystem::getParentPath("/home/myFolder/foo.bar");
ASSERT_EQ(EXPECTED, parent);
}
//test windows style
{
static const std::string EXPECTED = "C:\\Users\\Antoine\\Desktop\\myFolder";
std::string parent = filesystem::getParentPath("C:\\Users\\Antoine\\Desktop\\myFolder\\foo.bar");
ASSERT_EQ(EXPECTED, parent);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetShortPathForm)
{
//test spaces in filename
{
static const std::string EXPECTED = "ABC~1.TXT";
std::string shortPath = filesystem::getShortPathForm("a b c.txt");
ASSERT_EQ(EXPECTED, shortPath);
}
//test too long file extension
{
static const std::string EXPECTED = "ABCDEF~1.TEX";
std::string shortPath = filesystem::getShortPathForm("abcdefgh.text");
ASSERT_EQ(EXPECTED, shortPath);
}
//test too long filename
{
static const std::string EXPECTED = "ABCDEF~1.TXT";
std::string shortPath = filesystem::getShortPathForm("abcdefghijklmnopqrstuvwxyz.txt");
ASSERT_EQ(EXPECTED, shortPath);
}
//test spaces in file extension
{
static const std::string EXPECTED = "ABCDE~1.TXT";
std::string shortPath = filesystem::getShortPathForm("abcde.t x t");
ASSERT_EQ(EXPECTED, shortPath);
}
//test program files (windows style)
{
static const std::string EXPECTED = "PROGRA~1";
std::string shortPath = filesystem::getShortPathForm("Program Files (x86)");
ASSERT_EQ(EXPECTED, shortPath);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testSplitPath)
{
//test baseline
{
static const std::string EXPECTED_PARENT = "/home/myFolder";
static const std::string EXPECTED_FILENAME = "myFile.txt";
std::string parent, filename;
filesystem::splitPath("/home/myFolder/myFile.txt", parent, filename);
ASSERT_EQ(EXPECTED_PARENT, parent);
ASSERT_EQ(EXPECTED_FILENAME, filename);
}
//test empty
{
static const std::string EXPECTED_PARENT = "";
static const std::string EXPECTED_FILENAME = "";
std::string parent, filename;
filesystem::splitPath("", parent, filename);
ASSERT_EQ(EXPECTED_PARENT, parent);
ASSERT_EQ(EXPECTED_FILENAME, filename);
}
//test single filename
{
static const std::string EXPECTED_PARENT = "";
static const std::string EXPECTED_FILENAME = "myfile.txt";
std::string parent, filename;
filesystem::splitPath("myfile.txt", parent, filename);
ASSERT_EQ(EXPECTED_PARENT, parent);
ASSERT_EQ(EXPECTED_FILENAME, filename);
}
//test spaces in folder
{
static const std::string EXPECTED_PARENT = "/home/my Folder";
static const std::string EXPECTED_FILENAME = "myFile.txt";
std::string parent, filename;
filesystem::splitPath("/home/my Folder/myFile.txt", parent, filename);
ASSERT_EQ(EXPECTED_PARENT, parent);
ASSERT_EQ(EXPECTED_FILENAME, filename);
}
//test filename without extension / folder name
{
static const std::string EXPECTED_PARENT = "/home/myFolder";
static const std::string EXPECTED_FILENAME = "myFile";
std::string parent, filename;
filesystem::splitPath("/home/myFolder/myFile", parent, filename);
ASSERT_EQ(EXPECTED_PARENT, parent);
ASSERT_EQ(EXPECTED_FILENAME, filename);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testSplitPathArray)
{
//test baseline
{
std::vector<std::string> elements;
filesystem::splitPath("/home/myFolder/myFile.txt", elements);
ASSERT_EQ(3, elements.size());
ASSERT_EQ("home", elements[0]);
ASSERT_EQ("myFolder", elements[1]);
ASSERT_EQ("myFile.txt", elements[2]);
}
//test empty
{
std::vector<std::string> elements;
filesystem::splitPath("", elements);
ASSERT_EQ(0, elements.size());
}
//test single filename
{
std::vector<std::string> elements;
filesystem::splitPath("myfile.txt", elements);
ASSERT_EQ(1, elements.size());
ASSERT_EQ("myfile.txt", elements[0]);
}
//test spaces in folder
{
std::vector<std::string> elements;
filesystem::splitPath("/home/my Folder/myFile.txt", elements);
ASSERT_EQ(3, elements.size());
ASSERT_EQ("home", elements[0]);
ASSERT_EQ("my Folder", elements[1]);
ASSERT_EQ("myFile.txt", elements[2]);
}
//test filename without extension / folder name
{
std::vector<std::string> elements;
filesystem::splitPath("/home/myFolder/myFile", elements);
ASSERT_EQ(3, elements.size());
ASSERT_EQ("home", elements[0]);
ASSERT_EQ("myFolder", elements[1]);
ASSERT_EQ("myFile", elements[2]);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetPathSeparator)
{
#ifdef WIN32
ASSERT_EQ('\\', filesystem::getPathSeparator());
#elif UNIX
ASSERT_EQ('/', filesystem::getPathSeparator());
#endif
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetCurrentFolder)
{
std::string curdir = getCurrentFolder();
ASSERT_NE("", curdir);
ASSERT_TRUE(filesystem::folderExists(curdir.c_str()));
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetFileExtention)
{
//test baseline
{
static const std::string EXPECTED = "txt";
std::string ext = filesystem::getFileExtention("myFile.txt");
ASSERT_EQ(EXPECTED, ext);
}
//test empty
{
static const std::string EXPECTED = "";
std::string ext = filesystem::getFileExtention("");
ASSERT_EQ(EXPECTED, ext);
}
//test spaces in extension
{
static const std::string EXPECTED = "foo bar";
std::string ext = filesystem::getFileExtention("/home/my Folder/myFile.foo bar");
ASSERT_EQ(EXPECTED, ext);
}
//test filename without extension / folder name
{
static const std::string EXPECTED = "";
std::string ext = filesystem::getFileExtention("/home/myFolder/myFile");
ASSERT_EQ(EXPECTED, ext);
}
//test folder with an extension and file without extension
{
static const std::string EXPECTED = "";
std::string ext = filesystem::getFileExtention("/home/my.Folder/myFile");
ASSERT_EQ(EXPECTED, ext);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetUserFriendlySize)
{
static const uint64_t MULTIPLICATOR_KB = 1024;
static const uint64_t MULTIPLICATOR_MB = 1024*MULTIPLICATOR_KB;
static const uint64_t MULTIPLICATOR_GB = 1024*MULTIPLICATOR_MB;
static const uint64_t MULTIPLICATOR_TB = 1024*MULTIPLICATOR_GB;
{
static const std::string EXPECTED = "0 bytes";
std::string size = filesystem::getUserFriendlySize(0ull);
ASSERT_EQ(EXPECTED, size);
}
{
static const std::string EXPECTED = "1023 bytes";
std::string size = filesystem::getUserFriendlySize(1023ull);
ASSERT_EQ(EXPECTED, size);
}
{
static const std::string EXPECTED = "1.00 KB";
std::string size = filesystem::getUserFriendlySize(1ull*MULTIPLICATOR_KB);
ASSERT_EQ(EXPECTED, size);
}
{
static const std::string EXPECTED = "0.97 MB";
std::string size = filesystem::getUserFriendlySize(1000ull*MULTIPLICATOR_KB);
ASSERT_EQ(EXPECTED, size);
}
{
static const std::string EXPECTED = "1.00 MB";
std::string size = filesystem::getUserFriendlySize(1ull*MULTIPLICATOR_MB);
ASSERT_EQ(EXPECTED, size);
}
{
static const std::string EXPECTED = "0.97 GB";
std::string size = filesystem::getUserFriendlySize(1000ull*MULTIPLICATOR_MB);
ASSERT_EQ(EXPECTED, size);
}
{
static const std::string EXPECTED = "1.00 GB";
std::string size = filesystem::getUserFriendlySize(1ull*MULTIPLICATOR_GB);
ASSERT_EQ(EXPECTED, size);
}
{
static const std::string EXPECTED = "0.97 TB";
std::string size = filesystem::getUserFriendlySize(1000ull*MULTIPLICATOR_GB);
ASSERT_EQ(EXPECTED, size);
}
{
static const std::string EXPECTED = "1.00 TB";
std::string size = filesystem::getUserFriendlySize(1ull*MULTIPLICATOR_TB);
ASSERT_EQ(EXPECTED, size);
}
}
//--------------------------------------------------------------------------------------------------
TEST_F(TestFilesystemFunc, testGetFileModifiedDate)
{
//assert that unit of return value is seconds
{
static const uint64_t EXPECTED = 3;
const std::string filename1 = gTestHelper::getInstance().getTestQualifiedName() + ".1.txt";
const std::string filename2 = gTestHelper::getInstance().getTestQualifiedName() + ".2.txt";
ASSERT_TRUE( createDummyFile(filename1.c_str()) );
nativefunc::millisleep(1000*EXPECTED + 50); //at least 3 seconds between the files
ASSERT_TRUE( createDummyFile(filename2.c_str()) );
uint64_t time1 = filesystem::getFileModifiedDate(filename1);
uint64_t time2 = filesystem::getFileModifiedDate(filename2);
uint64_t diff = time2 - time1;
ASSERT_GT(diff, EXPECTED-1); //allow 1 seconds of difference
ASSERT_LT(diff, EXPECTED+1); //allow 1 seconds of difference
}
}
//--------------------------------------------------------------------------------------------------
} // End namespace test
} // End namespace filesystem
| 32.137255 | 103 | 0.565101 | [
"vector"
] |
fba8210a925f4df745b57117df30631ac3a38867 | 499 | cpp | C++ | Chapter 22/Definition of class DeckOfCards that represents a deck of playing cards/Definition of class DeckOfCards that represents a deck of playing cards/main.cpp | MarvelousAudio/CPlusPlus-How-to-program-tenth-edition | a667b080938cf964909d79b272f0d863adc300e0 | [
"MIT"
] | null | null | null | Chapter 22/Definition of class DeckOfCards that represents a deck of playing cards/Definition of class DeckOfCards that represents a deck of playing cards/main.cpp | MarvelousAudio/CPlusPlus-How-to-program-tenth-edition | a667b080938cf964909d79b272f0d863adc300e0 | [
"MIT"
] | null | null | null | Chapter 22/Definition of class DeckOfCards that represents a deck of playing cards/Definition of class DeckOfCards that represents a deck of playing cards/main.cpp | MarvelousAudio/CPlusPlus-How-to-program-tenth-edition | a667b080938cf964909d79b272f0d863adc300e0 | [
"MIT"
] | null | null | null | //
// main.cpp
// Definition of class DeckOfCards that represents a deck of playing cards
//
// Created by ben haywood on 5/3/20.
// Copyright © 2020 ben haywood. All rights reserved.
//
#include <iostream>
#include "DeckOfCards.hpp"
int main(int argc, const char * argv[]) {
// insert code here...
DeckOfCards deckOfCards; // create DeckOfCards object
deckOfCards.shuffle(); // shuffle the cards in the deck
deckOfCards.deal(); // deal the cards in the deck
return 0;
}
| 23.761905 | 75 | 0.681363 | [
"object"
] |
fbaa2969ddfe0ec896b61cfc1b07224a87275e20 | 4,935 | hpp | C++ | src/vk-renderer/vk-renderer-common.hpp | itsermo/vk-renderer | bdc1738d2b644e163356982a84dadc164d79ef53 | [
"BSD-3-Clause"
] | 1 | 2019-06-04T10:31:18.000Z | 2019-06-04T10:31:18.000Z | src/vk-renderer/vk-renderer-common.hpp | itsermo/vk-renderer | bdc1738d2b644e163356982a84dadc164d79ef53 | [
"BSD-3-Clause"
] | null | null | null | src/vk-renderer/vk-renderer-common.hpp | itsermo/vk-renderer | bdc1738d2b644e163356982a84dadc164d79ef53 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#ifndef VK_RENDERER_COMMON
#define VK_RENDERER_COMMON
#include <linalg.h>
#include <vector>
#include <string>
using namespace linalg::aliases;
namespace vk_renderer
{
const float DEG_TO_RAD = 0.017453292519943295769236907684886f;
struct vertex
{
float3 pos;
float3 color;
float2 tex_coord;
bool operator==(const vertex& other) const {
return pos == other.pos && color == other.color && tex_coord == other.tex_coord;
}
};
// A value type representing an abstract direction vector in 3D space, independent of any coordinate system
enum class coord_axis { forward, back, left, right, up, down, north = forward, east = right, south = back, west = left };
static constexpr float dot(coord_axis a, coord_axis b)
{
float table[6][6]{ {+1,-1,0,0,0,0},{-1,+1,0,0,0,0},{0,0,+1,-1,0,0},{0,0,-1,+1,0,0},{0,0,0,0,+1,-1},{0,0,0,0,-1,+1} };
return table[static_cast<int>(a)][static_cast<int>(b)];
}
// A concrete 3D coordinate system with defined x, y, and z axes
struct coord_system
{
coord_axis x_axis, y_axis, z_axis;
constexpr float3 get_axis(coord_axis a) const { return { dot(x_axis, a), dot(y_axis, a), dot(z_axis, a) }; }
constexpr float3 get_left() const { return get_axis(coord_axis::left); }
constexpr float3 get_right() const { return get_axis(coord_axis::right); }
constexpr float3 get_up() const { return get_axis(coord_axis::up); }
constexpr float3 get_down() const { return get_axis(coord_axis::down); }
constexpr float3 get_forward() const { return get_axis(coord_axis::forward); }
constexpr float3 get_back() const { return get_axis(coord_axis::back); }
};
inline float3x3 make_transform(const coord_system & from, const coord_system & to) { return { to.get_axis(from.x_axis), to.get_axis(from.y_axis), to.get_axis(from.z_axis) }; }
constexpr coord_system engine_coordinate_system{ coord_axis::right, coord_axis::up, coord_axis::back };
struct model
{
std::string id{};
std::vector<vertex> vertices{};
std::vector<uint32_t> indices{};
std::vector<uint8_t> texture_data{};
int texture_width{};
int texture_height{};
int texture_num_chan{};
uint32_t mip_levels{};
float4x4 transform{ linalg::identity };
model* parent;
};
struct pose
{
float3 pos{ 0,0,0 };
float4 rot{ 0,0,0,1 };
float4x4 matrix_4x4() const { return linalg::pose_matrix(rot, pos); }
float3x4 matrix_3x4() const { return {{linalg::qxdir(rot)}, {linalg::qydir(rot)}, {linalg::qzdir(rot)}, {pos}}; }
static pose from_matrix(const float4x4 & pose_matrix) {
return { { pose_matrix.w.x, pose_matrix.w.y, pose_matrix.w.z }, { linalg::rotation_quat(float3x3 { pose_matrix.x.xyz(), pose_matrix.y.xyz(), pose_matrix.z.xyz() } ) } };
}
static pose from_matrix(const float3x4 & pose_matrix) {
return { { pose_matrix.w.x, pose_matrix.w.y, pose_matrix.w.z }, { linalg::rotation_quat(float3x3 { pose_matrix.x, pose_matrix.y, pose_matrix.z }) } };
}
};
static float4 from_to(const float3 & from, const float3 & to) { return rotation_quat(normalize(cross(from, to)), angle(from, to)); }
struct camera
{
float3 position;
float pitch = 0, yaw = 0;
float fov_deg = 45.0f;
float aspect = 4.0f / 3.0f;
float near = 0.03f, far = 10.0f;
float4 get_orientation() const { return qmul(rotation_quat(engine_coordinate_system.get_up(), yaw), rotation_quat(engine_coordinate_system.get_right(), pitch)); }
pose get_pose() const { return { position, get_orientation() }; }
float4x4 get_pose_matrix() const { return pose_matrix(get_orientation(), position); }
float4x4 get_view_matrix() const { return inverse(get_pose_matrix()); }
float4x4 get_projection_matrix() const { return linalg::perspective_matrix(fov_deg * DEG_TO_RAD, aspect, near, far, linalg::pos_z, linalg::zero_to_one); };
void move_local(const float3 & step)
{
position += qrot(get_orientation(), step);
}
void look_at(const float3 & center)
{
const auto up = engine_coordinate_system.get_up();
const float3 fwd = normalize(center - position);
const float3 flat_fwd = normalize(fwd - up * dot(fwd, up));
const float4 yaw_quat = from_to(engine_coordinate_system.get_forward(), flat_fwd);
const float3 pitch_fwd = qrot(qinv(yaw_quat), fwd);
const float4 pitch_quat = from_to(engine_coordinate_system.get_forward(), pitch_fwd);
pitch = qangle(pitch_quat) * dot(qaxis(pitch_quat), engine_coordinate_system.get_right());
yaw = qangle(yaw_quat) * dot(qaxis(yaw_quat), engine_coordinate_system.get_up());
}
};
struct uniform_buffer_object
{
float4x4 model { linalg::identity };
float4x4 view { linalg::identity };
float4x4 projection { linalg::identity };
};
}
namespace std {
template<> struct hash<vk_renderer::vertex> {
size_t operator()(vk_renderer::vertex const& vertex) const {
return ((hash<float3>()(vertex.pos) ^
(hash<float3>()(vertex.color) << 1)) >> 1) ^
(hash<float2>()(vertex.tex_coord) << 1);
}
};
}
#endif
| 37.105263 | 176 | 0.704559 | [
"vector",
"model",
"transform",
"3d"
] |
fbafb5dfbdf8b0ff552725a7009bf8fc4c5ca478 | 3,419 | cpp | C++ | src/backend/zoo/crop_nd.cpp | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | src/backend/zoo/crop_nd.cpp | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | src/backend/zoo/crop_nd.cpp | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by kier on 2019/4/9.
//
#include "backend/zoo/crop_nd.h"
#include "backend/name.h"
#include "core/tensor_builder.h"
#include "utils/assert.h"
#include "global/operator_factory.h"
#include "utils/ctxmgr_lite.h"
#include "core/device_context.h"
#include "runtime/stack.h"
#include <array>
namespace ts {
namespace zoo {
CropND::CropND() {
field(name::shift, OPTIONAL);
}
void CropND::init() {
supper::init();
m_shift.clear();
if (has(name::shift)) {
m_shift = tensor::array::to_int(this->get(name::shift));
}
auto &context = ctx::ref<DeviceContext>();
m_pad_op = OperatorCreator::Create(context.computing_device.type(), name::layer::pad(), false);
TS_CHECK_NQ(m_pad_op, nullptr) << "Can not find operator: " << name::layer::pad();
m_pad_op->set(name::padding_value, tensor::build(FLOAT32, {0.0f}));
m_pad_op->init();
}
int CropND::infer(Stack &stack, std::vector<Tensor::Prototype> &output) {
TS_AUTO_CHECK(stack.size() == 2);
auto &x = stack[0];
auto &size = stack[1];
auto shape = tensor::array::to_int(size);
output.resize(1);
output[0] = Tensor::Prototype(x.dtype(), shape);
return 1;
}
int CropND::run(Stack &stack) {
TS_AUTO_CHECK(stack.size() == 2);
auto x = *stack.index(0);
auto shape = tensor::cast(INT32, stack[1]);
auto shape_count = shape.count();
auto shape_data = shape.data<int32_t>();
auto &x_size = x.sizes();
auto dims = x.dims();
TS_AUTO_CHECK((m_shift.empty() || m_shift.size() == dims) && shape_count == dims);
std::vector<std::array<int32_t, 2>> padding(dims);
if (m_shift.empty()) {
for (int i = 0; i < dims; ++i) {
if (shape_data[i] <= 0) {
padding[i][0] = 0;
padding[i][1] = 0;
} else {
auto x_padding_top = (shape_data[i] - x_size[i]) / 2;
auto x_padding_bottom = shape_data[i] - x_size[i] - x_padding_top;
padding[i][0] = x_padding_top;
padding[i][1] = x_padding_bottom;
}
}
} else {
for (int i = 0; i < dims; ++i) {
if (shape_data[i] <= 0) {
padding[i][0] = -m_shift[i];
padding[i][1] = m_shift[i];
} else {
auto x_padding_top = -m_shift[i];
auto x_padding_bottom = m_shift[i] + shape_data[i] - x_size[i];
padding[i][0] = x_padding_top;
padding[i][1] = x_padding_bottom;
}
}
}
auto x_padding_tensor = tensor::build(INT32, {int(dims), 2}, padding[0].data());
stack.push(0);
stack.push(x_padding_tensor);
TS_AUTO_CHECK(1 == RunOperator(m_pad_op, stack, 2));
return 1;
}
}
}
using namespace ts;
using namespace zoo;
TS_REGISTER_OPERATOR(CropND, ts::CPU, ts::name::layer::crop_nd());
| 29.730435 | 107 | 0.48172 | [
"shape",
"vector"
] |
fbb0b7c43f8c960c5bd2c491b4f551467b3addf5 | 29,815 | cc | C++ | src/GaIA/pkgs/nmap/nmap-6.40/nse_nmaplib.cc | uninth/UNItools | c8b1fbfd5d3753b5b14fa19033e39737dedefc00 | [
"BSD-3-Clause"
] | null | null | null | src/GaIA/pkgs/nmap/nmap-6.40/nse_nmaplib.cc | uninth/UNItools | c8b1fbfd5d3753b5b14fa19033e39737dedefc00 | [
"BSD-3-Clause"
] | null | null | null | src/GaIA/pkgs/nmap/nmap-6.40/nse_nmaplib.cc | uninth/UNItools | c8b1fbfd5d3753b5b14fa19033e39737dedefc00 | [
"BSD-3-Clause"
] | 1 | 2021-06-08T15:59:26.000Z | 2021-06-08T15:59:26.000Z |
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include <math.h>
#include "nmap.h"
#include "nmap_error.h"
#include "NmapOps.h"
#include "Target.h"
#include "TargetGroup.h"
#include "portlist.h"
#include "service_scan.h"
#include "nmap_dns.h"
#include "osscan.h"
#include "protocols.h"
#include "libnetutil/netutil.h"
#include "nse_nmaplib.h"
#include "nse_utility.h"
#include "nse_nsock.h"
#include "nse_dnet.h"
extern NmapOps o;
static const char *NSE_PROTOCOL_OP[] = {"tcp", "udp", "sctp", NULL};
static const int NSE_PROTOCOL[] = {IPPROTO_TCP, IPPROTO_UDP, IPPROTO_SCTP};
void set_version (lua_State *L, const struct serviceDeductions *sd)
{
nseU_setsfield(L, -1, "name", sd->name);
nseU_setnfield(L, -1, "name_confidence", sd->name_confidence);
nseU_setsfield(L, -1, "product", sd->product);
nseU_setsfield(L, -1, "version", sd->version);
nseU_setsfield(L, -1, "extrainfo", sd->extrainfo);
nseU_setsfield(L, -1, "hostname", sd->hostname);
nseU_setsfield(L, -1, "ostype", sd->ostype);
nseU_setsfield(L, -1, "devicetype", sd->devicetype);
nseU_setsfield(L, -1, "service_tunnel",
sd->service_tunnel == SERVICE_TUNNEL_NONE ? "none" :
sd->service_tunnel == SERVICE_TUNNEL_SSL ? "ssl" :
NULL);
nseU_setsfield(L, -1, "service_fp", sd->service_fp);
nseU_setsfield(L, -1, "service_dtype",
sd->dtype == SERVICE_DETECTION_TABLE ? "table" :
sd->dtype == SERVICE_DETECTION_PROBED ? "probed" :
NULL);
lua_newtable(L);
for (size_t i = 0; i < sd->cpe.size(); i++) {
lua_pushstring(L, sd->cpe[i]);
lua_rawseti(L, -2, i+1);
}
lua_setfield(L, -2, "cpe");
}
/* set some port state information onto the
* table which is currently on the stack
* */
void set_portinfo (lua_State *L, const Target *target, const Port *port)
{
struct serviceDeductions sd;
target->ports.getServiceDeductions(port->portno, port->proto, &sd);
nseU_setnfield(L, -1, "number", port->portno);
nseU_setsfield(L, -1, "service", sd.name);
nseU_setsfield(L, -1, "protocol", IPPROTO2STR(port->proto));
nseU_setsfield(L, -1, "state", statenum2str(port->state));
nseU_setsfield(L, -1, "reason", reason_str(port->reason.reason_id, 1));
lua_newtable(L);
set_version(L, &sd);
lua_setfield(L, -2, "version");
}
/* Push a string containing the binary contents of the given address. If ss has
an unknown address family, push nil. */
static void push_bin_ip(lua_State *L, const struct sockaddr_storage *ss)
{
if (ss->ss_family == AF_INET) {
const struct sockaddr_in *sin;
sin = (struct sockaddr_in *) ss;
lua_pushlstring(L, (char *) &sin->sin_addr.s_addr, IP_ADDR_LEN);
} else if (ss->ss_family == AF_INET6) {
const struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *) ss;
lua_pushlstring(L, (char *) &sin6->sin6_addr.s6_addr, IP6_ADDR_LEN);
} else {
lua_pushnil(L);
}
}
static void set_string_or_nil(lua_State *L, const char *fieldname, const char *value) {
if (value != NULL) {
lua_pushstring(L, value);
lua_setfield(L, -2, fieldname);
}
}
static void push_osclass_table(lua_State *L,
const struct OS_Classification *osclass) {
unsigned int i;
lua_newtable(L);
set_string_or_nil(L, "vendor", osclass->OS_Vendor);
set_string_or_nil(L, "osfamily", osclass->OS_Family);
set_string_or_nil(L, "osgen", osclass->OS_Generation);
set_string_or_nil(L, "type", osclass->Device_Type);
lua_newtable(L);
for (i = 0; i < osclass->cpe.size(); i++) {
lua_pushstring(L, osclass->cpe[i]);
lua_rawseti(L, -2, i + 1);
}
lua_setfield(L, -2, "cpe");
}
static void push_osmatch_table(lua_State *L, const FingerMatch *match,
const OS_Classification_Results *OSR) {
int i;
lua_newtable(L);
lua_pushstring(L, match->OS_name);
lua_setfield(L, -2, "name");
lua_newtable(L);
for (i = 0; i < OSR->OSC_num_matches; i++) {
push_osclass_table(L, OSR->OSC[i]);
lua_rawseti(L, -2, i + 1);
}
lua_setfield(L, -2, "classes");
}
/* set host ip, host name and target name onto the
* table which is currently on the stack
* set name of the os run by the host onto the
* table which is currently on the stack
* the os name is really an array with perfect
* matches
* if an os scan wasn't performed, the array
* points to nil!
* */
void set_hostinfo(lua_State *L, Target *currenths) {
nseU_setsfield(L, -1, "ip", currenths->targetipstr());
nseU_setsfield(L, -1, "name", currenths->HostName());
nseU_setsfield(L, -1, "targetname", currenths->TargetName());
if (currenths->directlyConnectedOrUnset() != -1)
nseU_setbfield(L, -1, "directly_connected", currenths->directlyConnected());
if (currenths->MACAddress())
{
lua_pushlstring(L, (const char *) currenths->MACAddress() , 6);
lua_setfield(L, -2, "mac_addr");
}
if (currenths->NextHopMACAddress())
{
lua_pushlstring(L, (const char *) currenths->NextHopMACAddress() , 6);
lua_setfield(L, -2, "mac_addr_next_hop");
}
if (currenths->SrcMACAddress())
{
lua_pushlstring(L, (const char *) currenths->SrcMACAddress(), 6);
lua_setfield(L, -2, "mac_addr_src");
}
nseU_setsfield(L, -1, "interface", currenths->deviceName());
nseU_setnfield(L, -1, "interface_mtu", currenths->MTU());
push_bin_ip(L, currenths->TargetSockAddr());
lua_setfield(L, -2, "bin_ip");
push_bin_ip(L, currenths->SourceSockAddr());
lua_setfield(L, -2, "bin_ip_src");
lua_newtable(L);
nseU_setnfield(L, -1, "srtt", (lua_Number) currenths->to.srtt / 1000000.0);
nseU_setnfield(L, -1, "rttvar", (lua_Number) currenths->to.rttvar / 1000000.0);
nseU_setnfield(L, -1, "timeout", (lua_Number) currenths->to.timeout / 1000000.0);
lua_setfield(L, -2, "times");
lua_newtable(L);
lua_setfield(L, -2, "registry");
/* add distance (in hops) if traceroute has been performed */
if (currenths->traceroute_hops.size() > 0)
{
std::list<TracerouteHop>::iterator it;
lua_newtable(L);
for (it = currenths->traceroute_hops.begin(); it != currenths->traceroute_hops.end(); it++)
{
lua_newtable(L);
/* fill the table if the hop has not timed out, otherwise an empty table
* is inserted */
if (!it->timedout) {
nseU_setsfield(L, -1, "ip", inet_ntop_ez(&it->addr, sizeof(it->addr)));
if (!it->name.empty())
nseU_setsfield(L, -1, "name", it->name.c_str());
lua_newtable(L);
nseU_setnfield(L, -1, "srtt", it->rtt / 1000.0);
lua_setfield(L, -2, "times");
}
lua_rawseti(L, -2, lua_rawlen(L, -2)+1);
}
lua_setfield(L, -2, "traceroute");
}
FingerPrintResults *FPR = currenths->FPR;
/* if there has been an os scan which returned a pretty certain
* result, we will use it in the scripts
* matches which aren't perfect are not needed in the scripts
*/
if (currenths->osscanPerformed() && FPR != NULL &&
FPR->overall_results == OSSCAN_SUCCESS && FPR->num_perfect_matches > 0 &&
FPR->num_perfect_matches <= 8 )
{
int i;
const OS_Classification_Results *OSR = FPR->getOSClassification();
lua_newtable(L);
for (i = 0; i < FPR->num_perfect_matches; i++) {
push_osmatch_table(L, FPR->matches[i], OSR);
lua_rawseti(L, -2, i + 1);
}
lua_setfield(L, -2, "os");
}
}
static int l_clock_ms (lua_State *L)
{
struct timeval tv;
gettimeofday(&tv, NULL);
/* milliseconds since Epoch */
lua_pushnumber(L,
ceil((lua_Number)tv.tv_sec*1000+(lua_Number)tv.tv_usec/1000));
return 1;
}
static int l_clock (lua_State *L)
{
struct timeval tv;
gettimeofday(&tv, NULL);
/* floating point seconds since Epoch */
lua_pushnumber(L, TIMEVAL_SECS(tv));
return 1;
}
/* The actual mutex returned by the nmap.mutex function.
* This function has 4 upvalues:
* (1) Table (array) of waiting threads.
* (2) The running thread or nil.
* (3) A unique table key used for destructors.
* (4) The destructor function, aux_mutex_done.
*/
static int aux_mutex (lua_State *L)
{
enum what {LOCK, DONE, TRYLOCK, RUNNING};
static const char * op[] = {"lock", "done", "trylock", "running", NULL};
switch (luaL_checkoption(L, 1, NULL, op))
{
case LOCK:
if (lua_isnil(L, lua_upvalueindex(2))) // check running
{
lua_pushthread(L);
lua_replace(L, lua_upvalueindex(2)); // set running
lua_pushvalue(L, lua_upvalueindex(3)); // unique identifier
lua_pushvalue(L, lua_upvalueindex(4)); // aux_mutex_done closure
nse_destructor(L, 'a');
return 0;
}
lua_pushthread(L);
lua_rawseti(L, lua_upvalueindex(1), lua_rawlen(L, lua_upvalueindex(1))+1);
return nse_yield(L, 0, NULL);
case DONE:
lua_pushthread(L);
if (!lua_rawequal(L, -1, lua_upvalueindex(2)))
luaL_error(L, "%s", "do not have a lock on this mutex");
/* remove destructor */
lua_pushvalue(L, lua_upvalueindex(3));
nse_destructor(L, 'r');
/* set new thread to lock the mutex */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, -1, "table");
lua_getfield(L, -1, "remove");
lua_pushvalue(L, lua_upvalueindex(1));
lua_pushinteger(L, 1);
lua_call(L, 2, 1);
lua_replace(L, lua_upvalueindex(2));
if (lua_isthread(L, lua_upvalueindex(2))) // waiting threads had a thread
{
lua_State *thread = lua_tothread(L, lua_upvalueindex(2));
lua_pushvalue(L, lua_upvalueindex(3)); // destructor key
lua_pushvalue(L, lua_upvalueindex(4)); // destructor
luaL_checkstack(thread, 2, "adding destructor");
lua_xmove(L, thread, 2);
nse_destructor(thread, 'a');
nse_restore(thread, 0);
}
return 0;
case TRYLOCK:
if (lua_isnil(L, lua_upvalueindex(2)))
{
lua_pushthread(L);
lua_replace(L, lua_upvalueindex(2));
lua_pushvalue(L, lua_upvalueindex(3)); // unique identifier
lua_pushvalue(L, lua_upvalueindex(4)); // aux_mutex_done closure
nse_destructor(L, 'a');
lua_pushboolean(L, true);
}
else
lua_pushboolean(L, false);
return 1;
case RUNNING:
lua_pushvalue(L, lua_upvalueindex(2));
return 1;
}
return 0;
}
/* This is the mutex destructor called when a thread ends but failed to
* unlock the mutex.
* It has 1 upvalue: The nmap.mutex function closure.
*/
static int aux_mutex_done (lua_State *L)
{
lua_State *thread = lua_tothread(L, 1);
lua_pushvalue(L, lua_upvalueindex(1)); // aux_mutex, actual mutex closure
lua_pushliteral(L, "done");
luaL_checkstack(thread, 2, "aux_mutex_done");
lua_xmove(L, thread, 2);
if (lua_pcall(thread, 1, 0, 0) != 0) lua_pop(thread, 1); // pop error msg
return 0;
}
static int l_mutex (lua_State *L)
{
int t = lua_type(L, 1);
if (t == LUA_TNONE || t == LUA_TNIL || t == LUA_TBOOLEAN || t == LUA_TNUMBER)
luaL_argerror(L, 1, "object expected");
lua_pushvalue(L, 1);
lua_gettable(L, lua_upvalueindex(1));
if (lua_isnil(L, -1))
{
lua_newtable(L); // waiting threads
lua_pushnil(L); // running thread
lua_newtable(L); // unique object as an identifier
lua_pushnil(L); // placeholder for aux_mutex_done
lua_pushcclosure(L, aux_mutex, 4);
lua_pushvalue(L, -1); // mutex closure
lua_pushcclosure(L, aux_mutex_done, 1);
lua_setupvalue(L, -2, 4); // replace nil upvalue with aux_mutex_done
lua_pushvalue(L, 1); // "mutex object"
lua_pushvalue(L, -2); // mutex function
lua_settable(L, lua_upvalueindex(1)); // Add to mutex table
}
return 1; // aux_mutex closure
}
static int aux_condvar (lua_State *L)
{
size_t i, n = 0;
enum {WAIT, SIGNAL, BROADCAST};
static const char * op[] = {"wait", "signal", "broadcast"};
switch (luaL_checkoption(L, 1, NULL, op))
{
case WAIT:
lua_pushthread(L);
lua_rawseti(L, lua_upvalueindex(1), lua_rawlen(L, lua_upvalueindex(1))+1);
return nse_yield(L, 0, NULL);
case SIGNAL:
n = lua_rawlen(L, lua_upvalueindex(1));
if (n == 0)
n = 1;
break;
case BROADCAST:
n = 1;
break;
}
lua_pushvalue(L, lua_upvalueindex(1));
for (i = lua_rawlen(L, -1); i >= n; i--)
{
lua_rawgeti(L, -1, i); /* get the thread */
if (lua_isthread(L, -1))
nse_restore(lua_tothread(L, -1), 0);
lua_pop(L, 1); /* pop the thread */
lua_pushnil(L);
lua_rawseti(L, -2, i);
}
return 0;
}
static int aux_condvar_done (lua_State *L)
{
lua_State *thread = lua_tothread(L, 1);
lua_pushvalue(L, lua_upvalueindex(1)); // aux_condvar closure
lua_pushliteral(L, "broadcast"); // wake up all threads waiting
luaL_checkstack(thread, 2, "aux_condvar_done");
lua_xmove(L, thread, 2);
if (lua_pcall(thread, 1, 0, 0) != 0) lua_pop(thread, 1); // pop error msg
return 0;
}
static int l_condvar (lua_State *L)
{
int t = lua_type(L, 1);
if (t == LUA_TNONE || t == LUA_TNIL || t == LUA_TBOOLEAN || t == LUA_TNUMBER)
luaL_argerror(L, 1, "object expected");
lua_pushvalue(L, 1);
lua_gettable(L, lua_upvalueindex(1));
if (lua_isnil(L, -1))
{
lua_newtable(L); // waiting threads
lua_pushnil(L); // placeholder for aux_mutex_done
lua_pushcclosure(L, aux_condvar, 2);
lua_pushvalue(L, -1); // aux_condvar closure
lua_pushcclosure(L, aux_condvar_done, 1);
lua_setupvalue(L, -2, 2); // replace nil upvalue with aux_condvar_done
lua_pushvalue(L, 1); // "condition variable object"
lua_pushvalue(L, -2); // condvar function
lua_settable(L, lua_upvalueindex(1)); // Add to condition variable table
}
lua_pushvalue(L, -1); // aux_condvar closure
lua_getupvalue(L, -1, 2); // aux_mutex_done closure
nse_destructor(L, 'a');
return 1; // condition variable closure
}
/* Generates an array of port data for the given host and leaves it on
* the top of the stack
*/
static int l_get_ports (lua_State *L)
{
static const char *state_op[] = {"open", "filtered", "unfiltered", "closed",
"open|filtered", "closed|filtered", NULL};
static const int states[] = {PORT_OPEN, PORT_FILTERED, PORT_UNFILTERED,
PORT_CLOSED, PORT_OPENFILTERED, PORT_CLOSEDFILTERED};
Port *p = NULL;
Port port; /* dummy Port for nextPort */
Target *target = nseU_gettarget(L, 1);
int protocol = NSE_PROTOCOL[luaL_checkoption(L, 3, NULL, NSE_PROTOCOL_OP)];
int state = states[luaL_checkoption(L, 4, NULL, state_op)];
if (!lua_isnil(L, 2))
p = nseU_getport(L, target, &port, 2);
if (!(p = target->ports.nextPort(p, &port, protocol, state))) {
lua_pushnil(L);
} else {
lua_newtable(L);
set_portinfo(L, target, p);
}
return 1;
}
/* this function can be called from lua to obtain the port state
* of a port different from the one the script rule is matched
* against
* it retrieves the host.ip of the host on which the script is
* currently running, looks up the host in the table of currently
* processed hosts and returns a table containing the state of
* the port we have been asked for
* this function is useful if we want rules which want to know
* the state of more than one port
* */
static int l_get_port_state (lua_State *L)
{
Target *target;
Port *p;
Port port; /* dummy Port */
target = nseU_gettarget(L, 1);
p = nseU_getport(L, target, &port, 2);
if (p == NULL)
lua_pushnil(L);
else
{
lua_newtable(L);
set_portinfo(L, target, p);
}
return 1;
}
/* this function must be used by version category scripts or any other
* lua code to check if a given port with it's protocol are in the
* exclude directive found in the nmap-service-probes file.
* */
static int l_port_is_excluded (lua_State *L)
{
unsigned short portno = (unsigned short) luaL_checkint(L, 1);
int protocol = NSE_PROTOCOL[luaL_checkoption(L, 2, NULL, NSE_PROTOCOL_OP)];
lua_pushboolean(L, AllProbes::check_excluded_port(portno, protocol));
return 1;
}
/* unlike set_portinfo() this function sets the port state in nmap.
* if for example a udp port was seen by the script as open instead of
* filtered, the script is free to say so.
* */
static int l_set_port_state (lua_State *L)
{
static const int opstate[] = {PORT_OPEN, PORT_CLOSED};
static const char *op[] = {"open", "closed", NULL};
Target *target;
Port *p;
Port port;
target = nseU_gettarget(L, 1);
if ((p = nseU_getport(L, target, &port, 2)) != NULL)
{
switch (opstate[luaL_checkoption(L, 3, NULL, op)])
{
case PORT_OPEN:
if (p->state == PORT_OPEN)
return 0;
target->ports.setPortState(p->portno, p->proto, PORT_OPEN);
break;
case PORT_CLOSED:
if (p->state == PORT_CLOSED)
return 0;
target->ports.setPortState(p->portno, p->proto, PORT_CLOSED);
break;
}
target->ports.setStateReason(p->portno, p->proto, ER_SCRIPT, 0, NULL);
}
return 0;
}
static int l_set_port_version (lua_State *L)
{
static const enum serviceprobestate opversion[] = {
PROBESTATE_FINISHED_HARDMATCHED,
PROBESTATE_FINISHED_SOFTMATCHED,
PROBESTATE_FINISHED_NOMATCH,
PROBESTATE_FINISHED_TCPWRAPPED,
PROBESTATE_INCOMPLETE
};
static const char *ops[] = {
"hardmatched",
"softmatched",
"nomatch",
"tcpwrapped",
"incomplete"
};
Target *target;
Port *p;
Port port;
std::vector<const char *> cpe;
enum service_tunnel_type tunnel = SERVICE_TUNNEL_NONE;
enum serviceprobestate probestate =
opversion[luaL_checkoption(L, 3, "hardmatched", ops)];
target = nseU_gettarget(L, 1);
if ((p = nseU_getport(L, target, &port, 2)) == NULL)
return 0; /* invalid port */
lua_settop(L, 3);
lua_getfield(L, 2, "version"); /* index 4 */
if (!lua_istable(L, -1))
luaL_error(L, "port 'version' field must be a table");
const char
*name = (lua_getfield(L, 4, "name"), lua_tostring(L, -1)),
*product = (lua_getfield(L, 4, "product"), lua_tostring(L, -1)),
*version = (lua_getfield(L, 4, "version"), lua_tostring(L, -1)),
*extrainfo = (lua_getfield(L, 4, "extrainfo"), lua_tostring(L, -1)),
*hostname = (lua_getfield(L, 4, "hostname"), lua_tostring(L, -1)),
*ostype = (lua_getfield(L, 4, "ostype"), lua_tostring(L, -1)),
*devicetype = (lua_getfield(L, 4, "devicetype"), lua_tostring(L, -1)),
*service_tunnel = (lua_getfield(L, 4, "service_tunnel"),
lua_tostring(L, -1));
if (service_tunnel == NULL || strcmp(service_tunnel, "none") == 0)
tunnel = SERVICE_TUNNEL_NONE;
else if (strcmp(service_tunnel, "ssl") == 0)
tunnel = SERVICE_TUNNEL_SSL;
else
luaL_argerror(L, 2, "invalid value for port.version.service_tunnel");
lua_getfield(L, 4, "cpe");
if (lua_isnil(L, -1))
;
else if(lua_istable(L, -1))
for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
cpe.push_back(lua_tostring(L, -1));
}
else
luaL_error(L, "port.version 'cpe' field must be a table");
target->ports.setServiceProbeResults(p->portno, p->proto,
probestate, name, tunnel, product,
version, extrainfo, hostname, ostype, devicetype,
(cpe.size() > 0) ? &cpe : NULL, NULL);
return 0;
}
static int l_log_write (lua_State *L)
{
static const char * const ops[] = {"stdout", "stderr", NULL};
static const int logs[] = {LOG_STDOUT, LOG_STDERR};
int log = logs[luaL_checkoption(L, 1, NULL, ops)];
log_write(log, "%s: %s\n", SCRIPT_ENGINE, luaL_checkstring(L, 2));
log_flush(log);
return 0;
}
static int finalize_cleanup (lua_State *L)
{
lua_settop(L, 2);
return lua_error(L);
}
static int new_try_finalize (lua_State *L)
{
if (!(lua_isboolean(L, 1) || lua_isnoneornil(L, 1)))
error("finalizing a non-conforming function that did not first "
"return a boolean");
if (!lua_toboolean(L, 1))
{
if (!lua_isnil(L, lua_upvalueindex(1)))
{
lua_pushvalue(L, lua_upvalueindex(1));
lua_callk(L, 0, 0, 0, finalize_cleanup);
}
return finalize_cleanup(L);
}
return lua_gettop(L)-1; /* omit first boolean argument */
}
static int l_new_try (lua_State *L)
{
lua_settop(L, 1);
lua_pushcclosure(L, new_try_finalize, 1);
return 1;
}
static int l_get_verbosity (lua_State *L)
{
int verbosity;
verbosity = o.verbose;
/* Check if script is selected by name. When a script is selected by name,
we lie to it and say the verbosity is one higher than it really is. */
verbosity += (nse_selectedbyname(L), lua_toboolean(L, -1) ? 1 : 0);
lua_pushnumber(L, verbosity);
return 1;
}
static int l_get_debugging (lua_State *L)
{
lua_pushnumber(L, o.debugging);
return 1;
}
static int l_get_have_ssl (lua_State *L) {
#if HAVE_OPENSSL
lua_pushboolean(L, true);
#else
lua_pushboolean(L, false);
#endif
return 1;
}
static int l_fetchfile (lua_State *L)
{
char buf[FILENAME_MAX];
if (nmap_fetchfile(buf, sizeof(buf), luaL_checkstring(L, 1)) != 1)
lua_pushnil(L);
else
lua_pushstring(L, buf);
return 1;
}
static int l_get_timing_level (lua_State *L)
{
lua_pushnumber(L, o.timing_level);
return 1;
}
/* Save new discovered targets.
*
* This function can take a Vararg expression:
* A vararg expression that represents targets (IPs or Hostnames).
*
* Returns two values if it receives target arguments:
* The number of targets that were added, or 0 on failures.
* An error message on failures.
*
* If this function was called without an argument then it
* will simply return the number of pending targets that are
* in the queue (waiting to be passed to Nmap).
*
* If the function was only able to add a one target, then we
* consider this success. */
static int l_add_targets (lua_State *L)
{
int n;
unsigned long ntarget = 0;
if (lua_gettop(L) > 0) {
for (n = 1; n <= lua_gettop(L); n++) {
if (!NewTargets::insert(luaL_checkstring(L, n)))
break;
ntarget++;
}
/* was able to add some targets */
if (ntarget) {
lua_pushnumber(L, ntarget);
return 1;
/* errors */
} else {
lua_pushnumber(L, ntarget);
lua_pushstring(L, "failed to add new targets.");
return 2;
}
} else {
/* function called without arguments */
/* push the number of pending targets that are in the queue */
lua_pushnumber(L, NewTargets::insert(""));
return 1;
}
}
/* Return the number of added targets */
static int l_get_new_targets_num (lua_State *L)
{
lua_pushnumber(L, NewTargets::get_number());
return 1;
}
// returns a table with DNS servers known to nmap
static int l_get_dns_servers (lua_State *L)
{
std::list<std::string> servs2 = get_dns_servers();
std::list<std::string>::iterator servI2;
lua_newtable(L);
for (servI2 = servs2.begin(); servI2 != servs2.end(); servI2++)
nseU_appendfstr(L, -1, "%s", servI2->c_str());
return 1;
}
static int l_is_privileged(lua_State *L)
{
lua_pushboolean(L, o.isr00t);
return 1;
}
/* Takes a host and optional address family and returns a table of
* addresses
*/
static int l_resolve(lua_State *L)
{
static const char *fam_op[] = { "inet", "inet6", "unspec", NULL };
static const int fams[] = { AF_INET, AF_INET6, AF_UNSPEC };
struct sockaddr_storage ss;
struct addrinfo *addr, *addrs;
const char *host = luaL_checkstring(L, 1);
int af = fams[luaL_checkoption(L, 2, "unspec", fam_op)];
addrs = resolve_all(host, af);
if (!addrs)
return nseU_safeerror(L, "Failed to resolve");
lua_pushboolean(L, true);
lua_newtable(L);
for (addr = addrs; addr != NULL; addr = addr->ai_next) {
if (af != AF_UNSPEC && addr->ai_family != af)
continue;
if (addr->ai_addrlen > sizeof(ss))
continue;
memcpy(&ss, addr->ai_addr, addr->ai_addrlen);
nseU_appendfstr(L, -1, "%s", inet_socktop(&ss));
}
if (addrs != NULL)
freeaddrinfo(addrs);
return 2;
}
static int l_address_family(lua_State *L)
{
if (o.af() == AF_INET)
lua_pushliteral(L, "inet");
else
lua_pushliteral(L, "inet6");
return 1;
}
/* return the interface name that was specified with
* the -e option
*/
static int l_get_interface (lua_State *L)
{
if (*o.device)
lua_pushstring(L, o.device);
else
lua_pushnil(L);
return 1;
}
/* returns a list of tables where each table contains information about each
* interface.
*/
static int l_list_interfaces (lua_State *L)
{
int numifs = 0;
struct interface_info *iflist;
char errstr[256];
errstr[0]='\0';
char ipstr[INET6_ADDRSTRLEN];
struct addr src, bcast;
iflist = getinterfaces(&numifs, errstr, sizeof(errstr));
int i;
if (iflist==NULL || numifs<=0) {
return nseU_safeerror(L, "%s", errstr);
} else {
memset(ipstr, 0, INET6_ADDRSTRLEN);
memset(&src, 0, sizeof(src));
memset(&bcast, 0, sizeof(bcast));
lua_newtable(L); //base table
for(i=0; i< numifs; i++) {
lua_newtable(L); //interface table
nseU_setsfield(L, -1, "device", iflist[i].devfullname);
nseU_setsfield(L, -1, "shortname", iflist[i].devname);
nseU_setnfield(L, -1, "netmask", iflist[i].netmask_bits);
nseU_setsfield(L, -1, "address", inet_ntop_ez(&(iflist[i].addr),
sizeof(iflist[i].addr) ));
switch (iflist[i].device_type){
case devt_ethernet:
nseU_setsfield(L, -1, "link", "ethernet");
lua_pushlstring(L, (const char *) iflist[i].mac, 6);
lua_setfield(L, -2, "mac");
/* calculate the broadcast address */
if (iflist[i].addr.ss_family == AF_INET) {
src.addr_type = ADDR_TYPE_IP;
src.addr_bits = iflist[i].netmask_bits;
src.addr_ip = ((struct sockaddr_in *)&(iflist[i].addr))->sin_addr.s_addr;
addr_bcast(&src, &bcast);
memset(ipstr, 0, INET6_ADDRSTRLEN);
if (addr_ntop(&bcast, ipstr, INET6_ADDRSTRLEN) != NULL)
nseU_setsfield(L, -1, "broadcast", ipstr);
}
break;
case devt_loopback:
nseU_setsfield(L, -1, "link", "loopback");
break;
case devt_p2p:
nseU_setsfield(L, -1, "link", "p2p");
break;
case devt_other:
default:
nseU_setsfield(L, -1, "link", "other");
}
nseU_setsfield(L, -1, "up", (iflist[i].device_up ? "up" : "down"));
nseU_setnfield(L, -1, "mtu", iflist[i].mtu);
/* After setting the fields, add the interface table to the base table */
lua_rawseti(L, -2, i + 1);
}
}
return 1;
}
/* return the ttl (time to live) specified with the
* --ttl command line option. If a wrong value is
* specified it defaults to 64.
*/
static int l_get_ttl (lua_State *L)
{
if (o.ttl < 0 || o.ttl > 255)
lua_pushnumber(L, 64); //default TTL
else
lua_pushnumber(L, o.ttl);
return 1;
}
/* return the payload length specified by the --data-length
* command line option. If it * isn't specified or the value
* is out of range then the default value (0) is returned.
*/
static int l_get_payload_length(lua_State *L)
{
if (o.extra_payload_length < 0)
lua_pushnumber(L, 0); //default payload length
else
lua_pushnumber(L, o.extra_payload_length);
return 1;
}
int luaopen_nmap (lua_State *L)
{
static const luaL_Reg nmaplib [] = {
{"get_port_state", l_get_port_state},
{"get_ports", l_get_ports},
{"set_port_state", l_set_port_state},
{"set_port_version", l_set_port_version},
{"port_is_excluded", l_port_is_excluded},
{"clock_ms", l_clock_ms},
{"clock", l_clock},
{"log_write", l_log_write},
{"new_try", l_new_try},
{"verbosity", l_get_verbosity},
{"debugging", l_get_debugging},
{"have_ssl", l_get_have_ssl},
{"fetchfile", l_fetchfile},
{"timing_level", l_get_timing_level},
{"add_targets", l_add_targets},
{"new_targets_num",l_get_new_targets_num},
{"get_dns_servers", l_get_dns_servers},
{"is_privileged", l_is_privileged},
{"resolve", l_resolve},
{"address_family", l_address_family},
{"get_interface", l_get_interface},
{"list_interfaces", l_list_interfaces},
{"get_ttl", l_get_ttl},
{"get_payload_length",l_get_payload_length},
{"new_dnet", nseU_placeholder}, /* imported from nmap.dnet */
{"get_interface_info", nseU_placeholder}, /* imported from nmap.dnet */
{"new_socket", nseU_placeholder}, /* imported from nmap.socket */
{"mutex", nseU_placeholder}, /* placeholder */
{"condvar", nseU_placeholder}, /* placeholder */
{NULL, NULL}
};
luaL_newlib(L, nmaplib);
int nmap_idx = lua_gettop(L);
nseU_weaktable(L, 0, 0, "v"); /* allow closures to be collected (see l_mutex) */
lua_pushcclosure(L, l_mutex, 1); /* mutex function */
lua_setfield(L, nmap_idx, "mutex");
nseU_weaktable(L, 0, 0, "v"); /* allow closures to be collected (see l_condvar) */
lua_pushcclosure(L, l_condvar, 1); /* condvar function */
lua_setfield(L, nmap_idx, "condvar");
lua_newtable(L);
lua_setfield(L, nmap_idx, "registry");
/* Pull out some functions from the nmap.socket and nmap.dnet libraries.
http://seclists.org/nmap-dev/2012/q1/299. */
luaL_requiref(L, "nmap.socket", luaopen_nsock, 0);
/* nmap.socket.new -> nmap.new_socket. */
lua_getfield(L, -1, "new");
lua_setfield(L, nmap_idx, "new_socket");
/* Store nmap.socket; used by nse_main.lua. */
lua_setfield(L, nmap_idx, "socket");
luaL_requiref(L, "nmap.dnet", luaopen_dnet, 0);
/* nmap.dnet.new -> nmap.new_dnet. */
lua_getfield(L, -1, "new");
lua_setfield(L, nmap_idx, "new_dnet");
/* nmap.dnet.get_interface_info -> nmap.get_interface_info. */
lua_getfield(L, -1, "get_interface_info");
lua_setfield(L, nmap_idx, "get_interface_info");
/* Store nmap.socket. */
lua_setfield(L, nmap_idx, "dnet");
lua_settop(L, nmap_idx);
return 1;
}
| 30.579487 | 95 | 0.649371 | [
"object",
"vector"
] |
fbbd36263a26314755ac5cc8cf4a67e7be9cba92 | 2,826 | hpp | C++ | src/master/state.hpp | benh/twesos | 194e1976d474005d807f37e7204ea08766e4b42a | [
"BSD-3-Clause"
] | 1 | 2019-02-17T15:56:26.000Z | 2019-02-17T15:56:26.000Z | src/master/state.hpp | benh/twesos | 194e1976d474005d807f37e7204ea08766e4b42a | [
"BSD-3-Clause"
] | null | null | null | src/master/state.hpp | benh/twesos | 194e1976d474005d807f37e7204ea08766e4b42a | [
"BSD-3-Clause"
] | 3 | 2017-07-10T07:28:30.000Z | 2020-07-25T19:48:07.000Z | #ifndef MASTER_STATE_HPP
#define MASTER_STATE_HPP
#include <iostream>
#include <string>
#include <vector>
#include <mesos_types.hpp>
#include "common/foreach.hpp"
#include "config/config.hpp"
namespace mesos { namespace internal { namespace master { namespace state {
struct SlaveResources
{
SlaveID slave_id;
int32_t cpus;
int64_t mem;
SlaveResources(SlaveID _sid, int32_t _cpus, int64_t _mem)
: slave_id(_sid), cpus(_cpus), mem(_mem) {}
};
struct SlotOffer
{
OfferID id;
FrameworkID framework_id;
std::vector<SlaveResources *> resources;
SlotOffer(OfferID _id, FrameworkID _fid)
: id(_id), framework_id(_fid) {}
~SlotOffer()
{
foreach (SlaveResources *sr, resources)
delete sr;
}
};
struct Slave
{
Slave(SlaveID id_, const std::string& host_, const std::string& public_dns_,
int32_t cpus_, int64_t mem_, time_t connect_)
: id(id_), host(host_), public_dns(public_dns_),
cpus(cpus_), mem(mem_), connect_time(connect_) {}
Slave() {}
SlaveID id;
std::string host;
std::string public_dns;
int32_t cpus;
int64_t mem;
int64_t connect_time;
};
struct Task
{
Task(TaskID id_, const std::string& name_, FrameworkID fid_, SlaveID sid_,
TaskState state_, int32_t _cpus, int64_t _mem)
: id(id_), name(name_), framework_id(fid_), slave_id(sid_), state(state_),
cpus(_cpus), mem(_mem) {}
Task() {}
TaskID id;
std::string name;
FrameworkID framework_id;
SlaveID slave_id;
TaskState state;
int32_t cpus;
int64_t mem;
};
struct Framework
{
Framework(FrameworkID id_, const std::string& user_,
const std::string& name_, const std::string& executor_,
int32_t cpus_, int64_t mem_, time_t connect_)
: id(id_), user(user_), name(name_), executor(executor_),
cpus(cpus_), mem(mem_), connect_time(connect_) {}
Framework() {}
~Framework()
{
foreach (Task *task, tasks)
delete task;
foreach (SlotOffer *offer, offers)
delete offer;
}
FrameworkID id;
std::string user;
std::string name;
std::string executor;
int32_t cpus;
int64_t mem;
int64_t connect_time;
std::vector<Task *> tasks;
std::vector<SlotOffer *> offers;
};
struct MasterState
{
MasterState(const std::string& build_date_, const std::string& build_user_,
const std::string& pid_, bool _isFT = false)
: build_date(build_date_), build_user(build_user_), pid(pid_), isFT(_isFT) {}
MasterState() {}
~MasterState()
{
foreach (Slave *slave, slaves)
delete slave;
foreach (Framework *framework, frameworks)
delete framework;
}
std::string build_date;
std::string build_user;
std::string pid;
std::vector<Slave *> slaves;
std::vector<Framework *> frameworks;
bool isFT;
};
}}}} /* namespace */
#endif /* MASTER_STATE_HPP */
| 20.042553 | 81 | 0.675513 | [
"vector"
] |
fbc51fbbfae3d0fc9c03494d609d5d3dfe3fc82b | 2,074 | hpp | C++ | IntrusivePtr.hpp | amikey/music-player-core | d124f8b43362648501d157a67d203d5f4ef008ad | [
"BSD-2-Clause"
] | 56 | 2015-04-21T05:35:38.000Z | 2021-02-16T13:42:45.000Z | IntrusivePtr.hpp | n-peugnet/music-player-core | d124f8b43362648501d157a67d203d5f4ef008ad | [
"BSD-2-Clause"
] | 13 | 2015-05-09T17:36:27.000Z | 2020-02-13T17:44:59.000Z | IntrusivePtr.hpp | n-peugnet/music-player-core | d124f8b43362648501d157a67d203d5f4ef008ad | [
"BSD-2-Clause"
] | 27 | 2015-06-15T14:54:58.000Z | 2021-07-22T09:59:40.000Z | #ifndef MP_INTRUSIVEPTR_HPP
#define MP_INTRUSIVEPTR_HPP
#include <atomic>
// boost::intrusive_ptr but safe/atomic.
// I.e. pointer to an object with an embedded reference count.
// intrusive_ptr_add_ref(T*) and intrusive_ptr_release(T*) must be declared.
// You can also derive from boost::intrusive_ref_counter.
template<typename T>
struct IntrusivePtr {
std::atomic<T*> ptr;
IntrusivePtr(T* _p = NULL) : ptr(NULL) {
if(_p) {
intrusive_ptr_add_ref(_p);
ptr = _p;
}
}
IntrusivePtr(const IntrusivePtr& other) : ptr(NULL) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
}
~IntrusivePtr() {
T* _p = ptr.exchange(NULL);
if(_p)
intrusive_ptr_release(_p);
}
IntrusivePtr& operator=(const IntrusivePtr& other) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
return *this;
}
T* get() const { return ptr; }
T& operator*() const { return *ptr; }
T* operator->() const { return ptr; }
operator bool() const { return ptr; }
operator T*() const { return ptr; }
bool operator==(const IntrusivePtr& other) const { return ptr == other.ptr; }
bool operator!=(const IntrusivePtr& other) const { return ptr != other.ptr; }
IntrusivePtr& swap(IntrusivePtr&& other) {
T* old = ptr.exchange(other.ptr);
other.ptr = old;
return other;
}
IntrusivePtr exchange(T* other) {
IntrusivePtr old = swap(IntrusivePtr(other));
return old;
}
bool compare_exchange(T* expected, T* desired, T** old = NULL) {
bool success = ptr.compare_exchange_strong(expected, desired);
if(success && expected != desired) {
intrusive_ptr_add_ref(desired);
intrusive_ptr_release(expected);
}
if(old)
*old = expected;
return success;
}
void reset(T* _p = NULL) {
swap(IntrusivePtr(_p));
}
};
struct intrusive_ref_counter {
std::atomic<ssize_t> ref_count;
intrusive_ref_counter() : ref_count(0) {}
};
template<typename T>
void intrusive_ptr_add_ref(T* obj) {
obj->ref_count++;
}
template<typename T>
void intrusive_ptr_release(T* obj) {
if(obj->ref_count.fetch_sub(1) <= 1) {
delete obj;
}
}
#endif // INTRUSIVEPTR_HPP
| 22.543478 | 78 | 0.686114 | [
"object"
] |
fbcb065d426ab89e3e4d7ebc87ea5f8b020c5ff7 | 16,914 | hpp | C++ | include/dynamix/message_macros.hpp | area55git/dynamix | c800209c6f467c19065235e87cbfe60171e75d68 | [
"MIT"
] | null | null | null | include/dynamix/message_macros.hpp | area55git/dynamix | c800209c6f467c19065235e87cbfe60171e75d68 | [
"MIT"
] | null | null | null | include/dynamix/message_macros.hpp | area55git/dynamix | c800209c6f467c19065235e87cbfe60171e75d68 | [
"MIT"
] | null | null | null | // DynaMix
// Copyright (c) 2013-2018 Borislav Stanimirov, Zahary Karadjov
//
// Distributed under the MIT Software License
// See accompanying file LICENSE.txt or copy at
// https://opensource.org/licenses/MIT
//
#pragma once
/**
* \file
* Macros used to declare and define messages.
*/
#include "message.hpp"
#include "preprocessor.hpp"
#include "exception.hpp"
#include "domain.hpp"
namespace dynamix
{
namespace internal
{
template <typename Message>
message_registrator<Message>::~message_registrator()
{
internal::domain::safe_instance().
unregister_feature(static_cast<message_t&>(_dynamix_get_mixin_feature_safe(static_cast<Message*>(nullptr))));
}
// classes instantiated by the message macros
// defines calling function
template <typename Ret, typename... Args>
struct msg_caller
{
using caller_func = Ret (*)(void*, Args...);
// makes the actual method call
// the MethodOwner type describes the owner of the method in case it's not
// the mixin but one of its parents
template <typename Mixin, typename MethodOwner, Ret (MethodOwner::*Method)(Args...)>
static Ret caller(void* mixin, Args... args)
{
auto m = reinterpret_cast<Mixin*>(mixin);
return (m->*Method)(std::forward<Args>(args)...);
}
// we need this silly-named alternative because there is no standard way to
// distiguish between constness-based overloads when providing a member function
// as a template argument
// because of this the macro which instantiates the template also constructs this
// function's name based on the message constness
template <typename Mixin, typename MethodOwner, Ret (MethodOwner::*Method)(Args...) const>
static Ret callerconst(void* mixin, Args... args)
{
auto m = reinterpret_cast<const Mixin*>(mixin);
return (m->*Method)(std::forward<Args>(args)...);
}
};
// instead of adding the multi and unicast calls in the same struct, we split it in two
// thus multicast messages, won't also instantiate and compile the unicast call and vice-versa
// caller struct instantiated by message macros
// Derived - the msg class generated by macro, sent via crtp
// Object - dynamix::object but having the appropriate constness
// Ret and Args - message signature
template <typename Derived, typename Object, typename Ret, typename... Args>
struct msg_unicast : public message_t, public msg_caller<Ret, Args...>
{
msg_unicast(const char* message_name)
: message_t(message_name, unicast, false)
{}
static Ret make_call(Object& obj, Args&&... args)
{
const ::dynamix::feature& self = _dynamix_get_mixin_feature_fast(static_cast<Derived*>(nullptr));
DYNAMIX_ASSERT(static_cast<const message_t&>(self).mechanism
== message_t::unicast);
const object_type_info::call_table_entry& call_entry =
obj._type_info->_call_table[self.id];
const message_for_mixin* msg_data = call_entry.top_bid_message;
DYNAMIX_MSG_THROW_UNLESS(msg_data, ::dynamix::bad_message_call);
// unfortunately we can't assert(msg_data->message == &self); since the data might come from a different module
char* mixin_data =
// skipping several function calls, which greatly improves build time
reinterpret_cast<char*>(const_cast<void*>(obj._mixin_data[obj._type_info->_mixin_indices[msg_data->_mixin_id]].mixin()));
auto func = reinterpret_cast<typename msg_caller<Ret, Args...>::caller_func>(msg_data->caller);
return func(mixin_data, std::forward<Args>(args)...);
}
};
// caller struct instantiated by message macros
// Derived - the msg class generated by macro, sent via crtp
// Object - dynamix::object but having the appropriate constness
// Ret and Args - message signature
template <typename Derived, typename Object, typename Ret, typename... Args>
struct msg_multicast : public message_t, public msg_caller<Ret, Args...>
{
msg_multicast(const char* message_name)
: message_t(message_name, message_t::multicast, false)
{}
template <typename Combinator>
static void make_combinator_call(Object& obj, Combinator& combinator, Args&... args)
{
const ::dynamix::feature& self = _dynamix_get_mixin_feature_fast(static_cast<Derived*>(nullptr));
DYNAMIX_ASSERT(static_cast<const message_t&>(self).mechanism
== message_t::multicast);
const object_type_info::call_table_entry& call_entry =
obj._type_info->_call_table[self.id];
auto begin = call_entry.begin;
auto end = call_entry.end;
DYNAMIX_MULTICAST_MSG_THROW_UNLESS(begin, ::dynamix::bad_message_call);
set_num_results_for(combinator, size_t(end - begin));
for (auto iter = begin; iter != end; ++iter)
{
auto msg_data = *iter;
DYNAMIX_ASSERT(msg_data);
// unfortunately we can't assert(msg_data->message == &self); since the data might come from a different module
char* mixin_data =
// skipping several function calls, which greatly improves build time
reinterpret_cast<char*>(const_cast<void*>(obj._mixin_data[obj._type_info->_mixin_indices[msg_data->_mixin_id]].mixin()));
auto func = reinterpret_cast<typename msg_caller<Ret, Args...>::caller_func>(msg_data->caller);
if (!combinator.add_result(func(mixin_data, args...)))
{
return;
}
}
}
// the folowing copy-pasted overload will be obsolete with c++17
// its only point is to support void multicast messages
// otherwise we would be able to use a combinator like this for all
// struct noop_combinator
// {
// template <typename R>
// constexpr bool add_result(R&& r) const { return true; }
// };
// with c++17 we would be able to add if constexpr(is_same(void, Ret)) to make it work
static void make_call(Object& obj, Args&... args)
{
const ::dynamix::feature& self = _dynamix_get_mixin_feature_fast(static_cast<Derived*>(nullptr));
DYNAMIX_ASSERT(static_cast<const message_t&>(self).mechanism
== message_t::multicast);
const object_type_info::call_table_entry& call_entry =
obj._type_info->_call_table[self.id];
auto begin = call_entry.begin;
auto end = call_entry.end;
DYNAMIX_MULTICAST_MSG_THROW_UNLESS(begin, ::dynamix::bad_message_call);
for (auto iter = begin; iter != end; ++iter)
{
auto msg_data = *iter;
DYNAMIX_ASSERT(msg_data);
// unfortunately we can't assert(msg_data->message == &self); since the data might come from a different module
char* mixin_data =
// skipping several function calls, which greatly improves build time
reinterpret_cast<char*>(const_cast<void*>(obj._mixin_data[obj._type_info->_mixin_indices[msg_data->_mixin_id]].mixin()));
auto func = reinterpret_cast<typename msg_caller<Ret, Args...>::caller_func>(msg_data->caller);
func(mixin_data, args...);
}
}
};
}
}
// some macros here have an underscore in front so it doesn't appear as a suggestion in
// ides that support these
// that shows that they're for internal use only
/// \internal
#define I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name) I_DYNAMIX_PP_CAT(dynamix_msg_, message_name)
/// \internal
#define I_DYNAMIX_MESSAGE_TAG(message_name) I_DYNAMIX_PP_CAT(message_name, _msg)
/// \internal
#define I_DYNAMIX_MESSAGE_CALLER_STRUCT(mechanism) I_DYNAMIX_PP_CAT(msg_, mechanism)
// construct the appropriate caller name, based on the message constness
/// \internal
#define I_DYNAMIX_CALLER_NAME(...) I_DYNAMIX_PP_CAT(caller, __VA_ARGS__)
// default impl helper macros
// name of default implementation struct
/// \internal
#define DYNAMIX_DEFAULT_IMPL_STRUCT(message_name) I_DYNAMIX_PP_CAT(message_name, _default_impl_t)
// no-arity macros
// macro which gives out a sensible error if a no-arity macro is called with a bad number of arguments
/// \internal
#define I_DYNAMIX_MESSAGE_ARG_ERROR static_assert(false, "DynaMix macro called with a bad number of arguments")
// a workaround to a visaul c issue which doesn't expand __VA_ARGS__ but inead gives them as a single argument
/// \internal
#define I_DYNAMIX_VA_ARGS_PROXY(MACRO, args) MACRO args
// a macro used in the legacy message macros to get the mixin data directly, skipping function calls
// GREATLY improves message call time
/// \internal
#define I_DYNAMIX_GET_MIXIN_DATA(obj, id) \
reinterpret_cast<char*>(const_cast<void*>(obj._mixin_data[obj._type_info->_mixin_indices[id]].mixin()))
#if defined(DYNAMIX_DOXYGEN)
// use these macros for the docs only
/**
* Macro that declares a message
*
* This generates the stand-alone function which is users should use to call messages.
*
* The calls will throw the exception `bad_message_call` if none of the mixins
* from which the object is composed handles this message. To prevent the message calls
* from Throwing exceptions you can define `DYNAMIX_NO_MSG_THROW` before including
* the library's headers.
*
* \par Variants:
* \code
* DYNAMIX_MESSAGE_N(return_type, message, args)
* DYNAMIX_CONST_MESSAGE_N(return_type, message, args)
* DYNAMIX_MULTICAST_MESSAGE_N(return_type, message, args)
* DYNAMIX_CONST_MULTICAST_MESSAGE_N(return_type, message, args)
* DYNAMIX_EXPORTED_MESSAGE_N(export, return_type, message, args)
* DYNAMIX_EXPORTED_CONST_MESSAGE_N(export, return_type, message, args)
* DYNAMIX_EXPORTED_MULTICAST_MESSAGE_N(export, return_type, message, args)
* DYNAMIX_EXPORTED_CONST_MULTICAST_MESSAGE_N(export, return_type, message, args)
* DYNAMIX_MESSAGE_N_OVERLOAD(message_name, return_type, method_name, args)
* DYNAMIX_CONST_MESSAGE_N_OVERLOAD(message_name, return_type, method_name, args)
* DYNAMIX_MULTICAST_MESSAGE_N_OVERLOAD(message_name, return_type, method_name, args)
* DYNAMIX_CONST_MULTICAST_MESSAGE_N_OVERLOAD(message_name, return_type, method_name, args)
* DYNAMIX_EXPORTED_MESSAGE_N_OVERLOAD(export, message_name, return_type, method_name, args)
* DYNAMIX_EXPORTED_CONST_MESSAGE_N_OVERLOAD(export, message_name, return_type, method_name, args)
* DYNAMIX_EXPORTED_MULTICAST_MESSAGE_N_OVERLOAD(export, message_name, return_type, method_name, args)
* DYNAMIX_EXPORTED_CONST_MULTICAST_MESSAGE_N_OVERLOAD(export, message_name, return_type, method_name, args)
* \endcode
*
* \par Legend:
* - `N` in those variant names is a number that indicates how many parameters the
* message takes. If `N` is 0, then `args` is omitted.
* - `args` is a coma-separated list of the argument types and argument names of
* the message's arguments
* - If `MULTICAST` is a part of a macro, it declares a multicast message. Otherwise
* it declares a unicast message.
* - If `CONST` is part of a macro, then the message works with `const object&` and
* should be bound to const methods of a mixin class. Otherwise it works with simply
* `object&` and should be bound no non-const methods of the mixin class.
* - If `EXPORTED` is part of a macro, then it's used to declare a message that is
* exported from a dynamic library. The `export` parameter should be the appropriate
* export/import symbols for the particular compiler (i.e. `__declspec(dllexport)`)
* - If `OVERLOAD` is part of a macro, it defines a message overload. It splits the
* ways of referring to the message in two. The first - `message_name` - should be
* used when referring to the message - in mixin feature lists, in
* `object::implements`, and in `DYNAMIX_DEFINE_MESSAGE`. The second -
* `method_name` - is the name of the method in the mixin class, and will be the
* name of the message function generated by the macro.
*
* \par Examples:
* \code
*
* // A basic non-const unicast message with no arguments.
* // Should be bound to: void mixin_class::foo()
* DYNAMIX_MESSAGE_0(void, foo);
*
* // A const multicast message with two arguments
* // Should be bound to: void mixin_class::serialize(archive& ar, int flags) const
* DYNAMIX_CONST_MULTICAST_MESSAGE_2(void, serialize, archive&, ar, int, flags);
*
* // Assuming MY_LIB_API is a macro that expands accordingly to the
* // export/import symbols for the compiler you're using, this is
* // a const unicast message with one argument exported from a dynamic library
* // Should be bound to: float mixin_class::size(int dimension) const
* DYNAMIX_EXPORTED_CONST_MESSAGE_1(MY_LIB_API, int, size, int, dimension);
*
* // Two message overloads, that should be bound to:
* // void mixin_class::scale(float uniform);
* // void mixin_class::scale(const vector3& vec);
* // respectively.
* // The macros will generate two functions named scale with the
* // appropriate arguments. In order to bind them to a mixin,
* // you should use scale_uniform_msg and scale_vector_msg
* // in the mixin feature list.
* DYNAMIX_MESSAGE_1_OVERLOAD(scale_uniform, void, scale, float, uniform);
* DYNAMIX_MESSAGE_1_OVERLOAD(scale_vector, void, scale, const vector3&, vec);
* \endcode
*/
#define DYNAMIX_MESSAGE_N(return_type, message, args)
/**
* Macro that defines a message by also providing a default implementation
*
* Use it once per message in a compilation unit (.cpp file)
*
* A default implementation lets the user provide code to be executed if
* a message is called for an object which has no mixin implementing it.
*
* \par Legend:
* - `N` is a number that indicates how many parameters the
* message takes. If `N` is 0, then `args` is omitted.
* - `args` is a coma-separated list of the argument types and argument names of
* the message's arguments
* - `message_name` - is the name of the message
*
* \par Notes:
* - As is the case with the mutation rules, an empty object won't implement default
* message implementations. You'll need at least one mutation to make it do so
* - A default implementation can be treated the same way as your implementation
* in the method for a regular message: ie `dm_this` is valid
* - If any of the mixins in an object implements this message, the default
* implementation will be unreachable. Multicasts won't feature it.
*/
#define DYNAMIX_DEFINE_MESSAGE_N_WITH_DEFAULT_IMPL(return_type, message_name, args)
/**
* The macro for defining a message.
* Use it once per message in a compilation unit (.cpp file)
*/
#define DYNAMIX_DEFINE_MESSAGE(message_name)
#else
// optionally don't include any message macros and let the user decide which
// set they're going to use for each message
#if !defined(DYNAMIX_NO_MESSAGE_MACROS)
// include the generated macros
// choose definition header
// making this choice DOES NOT require you to rebuild the library
// these headers are purely user facing
#if defined(DYNAMIX_USE_LEGACY_MESSAGE_MACROS)
// this file contains the old-style macros which have a lot of the calling code
// in the macros itself. They make it a bit harder to step into messages when
// debugging but in some cases with gcc and clang compile much faster
# include "gen/legacy_message_macros.hpp"
#else
// these are the new-style message macros only a single step into is needed when
// debugging in order to go to debuggable c++ code
// however they may be much slower to compile on gcc and clang
// this is generally the recommended header, but users are encouraged to test
// their compilation times with gcc and clang with the other header as well
# include "gen/template_message_macros.hpp"
#endif
#endif
// define message macro
#define DYNAMIX_DEFINE_MESSAGE(message_name) \
/* create feature getters for the message */ \
::dynamix::feature& _dynamix_get_mixin_feature_safe(const I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name)*) \
{ \
return ::dynamix::internal::feature_instance<I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name)>::the_feature_safe(); \
} \
const ::dynamix::feature& _dynamix_get_mixin_feature_fast(const I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name)*) \
{ \
return ::dynamix::internal::feature_instance<I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name)>::the_feature_fast(); \
} \
/* create a feature registrator */ \
void _dynamix_register_mixin_feature(const I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name)*) \
{ \
::dynamix::internal::domain::safe_instance(). \
register_feature(::dynamix::internal::feature_instance<I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name)>::the_feature_safe()); \
} \
/* instantiate metafunction initializator in case no class registers the message */ \
inline void _dynamix_register_message(I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name)*) \
{ \
::dynamix::internal::message_registrator<I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name)>::registrator.unused = true; \
} \
/* provide a tag instance */ \
I_DYNAMIX_MESSAGE_STRUCT_NAME(message_name) * I_DYNAMIX_MESSAGE_TAG(message_name)
#endif
| 42.928934 | 137 | 0.731938 | [
"object"
] |
fbcbd1fc62ef8dacf6ea207dba5789690d4e54bb | 2,274 | cpp | C++ | CLRS/BitManipulation/Subsets.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | CLRS/BitManipulation/Subsets.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | CLRS/BitManipulation/Subsets.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | /*
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.
*/
// we can use bit manipulation to represent all subsets.
// Note: first push the empty subset first
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
res.push_back({});
int n = nums.size();
for ( int i = 1; i < (1<<n); i++ )
{
vector<int> cur;
for ( int j = 0; j < n; j++ )
{
if ( i & (1<<j) )
cur.push_back(nums[j]);
}
res.push_back(cur);
}
return res;
}
};
// the above method has a problem if it size if larger than 32 or 64 due to the shift position,
// dfs for each position we could either select or not
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> cur;
dfs(0,nums,cur,res);
return res;
}
void dfs(int idx, vector<int> const& nums, vector<int> &cur, vector<vector<int>> &res)
{
if ( idx == nums.size() )
{
res.push_back(cur);
return;
}
cur.push_back(nums[idx]);
dfs(idx+1,nums,cur,res);
cur.pop_back();
dfs(idx+1,nums,cur,res);
}
};
// similar to the dfs idea, but expanding the current subsets by including the next number, while also retaining the existing subsets to
// eumulate the next number not selected
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res(1);
for ( int i = 0; i < nums.size(); i++ )
{
int sz = res.size();
for ( int j = 0; j < sz; j++ )
{
res.push_back(res[j]);
res.back().push_back(nums[i]);
}
}
return res;
}
}; | 24.989011 | 137 | 0.529903 | [
"vector"
] |
fbcbd62ee377e3c045b59e02018e87da49699e5e | 5,260 | cpp | C++ | plugins/committee_api/committee_api.cpp | VIZ-World/viz-core | 634825fcfff9e392a26789f8e23c4cfab2952b71 | [
"MIT"
] | 7 | 2018-03-21T12:56:32.000Z | 2018-04-02T16:06:24.000Z | plugins/committee_api/committee_api.cpp | VIZ-World/viz-core | 634825fcfff9e392a26789f8e23c4cfab2952b71 | [
"MIT"
] | 18 | 2018-03-21T13:29:46.000Z | 2018-05-18T10:56:43.000Z | plugins/committee_api/committee_api.cpp | VIZ-World/VIZ.Core | 634825fcfff9e392a26789f8e23c4cfab2952b71 | [
"MIT"
] | 9 | 2018-10-17T19:02:40.000Z | 2019-02-14T10:35:00.000Z | #include <boost/program_options/options_description.hpp>
#include <graphene/plugins/committee_api/committee_api.hpp>
#include <graphene/chain/index.hpp>
#include <graphene/chain/chain_objects.hpp>
#include <graphene/chain/committee_objects.hpp>
#include <graphene/api/committee_api_object.hpp>
#define CHECK_ARG_SIZE(_S) \
FC_ASSERT( \
args.args->size() == _S, \
"Expected #_S argument(s), was ${n}", \
("n", args.args->size()) );
#define CHECK_ARG_MIN_SIZE(_S, _M) \
FC_ASSERT( \
args.args->size() >= _S && args.args->size() <= _M, \
"Expected #_S (maximum #_M) argument(s), was ${n}", \
("n", args.args->size()) );
#define GET_OPTIONAL_ARG(_I, _T, _D) \
(args.args->size() > _I) ? \
(args.args->at(_I).as<_T>()) : \
static_cast<_T>(_D)
namespace graphene { namespace plugins { namespace committee_api {
struct committee_api::impl final {
impl(): database_(appbase::app().get_plugin<chain::plugin>().db()) {
}
~impl() = default;
graphene::chain::database& database() {
return database_;
}
graphene::chain::database& database() const {
return database_;
}
private:
graphene::chain::database& database_;
};
void committee_api::plugin_startup() {
wlog("committee_api plugin: plugin_startup()");
}
void committee_api::plugin_shutdown() {
wlog("committee_api plugin: plugin_shutdown()");
}
const std::string& committee_api::name() {
static const std::string name = "committee_api";
return name;
}
committee_api::committee_api() = default;
void committee_api::set_program_options(
boost::program_options::options_description&,
boost::program_options::options_description& config_file_options
) {
}
void committee_api::plugin_initialize(const boost::program_options::variables_map& options) {
pimpl = std::make_unique<impl>();
JSON_RPC_REGISTER_API(name());
}
committee_api::~committee_api() = default;
DEFINE_API(committee_api, get_committee_request) {
CHECK_ARG_MIN_SIZE(1, 2)
auto request_id = args.args->at(0).as<uint32_t>();
auto votes_count = GET_OPTIONAL_ARG(1, int32_t, 0);
auto& db = pimpl->database();
return db.with_weak_read_lock([&]() {
const auto &idx = db.get_index<committee_request_index>().indices().get<by_request_id>();
auto itr = idx.find(request_id);
FC_ASSERT(itr != idx.end(), "Committee request id not found.");
committee_api_object result = committee_api_object(*itr);
if(0!=votes_count){
const auto &vote_idx = db.get_index<committee_vote_index>().indices().get<by_request_id>();
auto vote_itr = vote_idx.lower_bound(request_id);
int32_t num = 0;
while (vote_itr != vote_idx.end() &&
vote_itr->request_id == request_id) {
const auto &cur_vote = *vote_itr;
++vote_itr;
committee_vote_state vote=committee_vote_state(cur_vote);
result.votes.emplace_back(vote);
if(-1!=votes_count){
++num;
if(num>=votes_count){
vote_itr=vote_idx.end();
}
}
}
}
return result;
});
}
DEFINE_API(committee_api, get_committee_request_votes) {
CHECK_ARG_MIN_SIZE(1, 1)
auto request_id = args.args->at(0).as<uint32_t>();
auto& db = pimpl->database();
return db.with_weak_read_lock([&]() {
const auto &vote_idx = db.get_index<committee_vote_index>().indices().get<by_request_id>();
auto vote_itr = vote_idx.lower_bound(request_id);
std::vector<committee_vote_state> votes;
while (vote_itr != vote_idx.end() &&
vote_itr->request_id == request_id) {
const auto &cur_vote = *vote_itr;
++vote_itr;
committee_vote_state vote=committee_vote_state(cur_vote);
votes.emplace_back(vote);
}
return votes;
});
}
DEFINE_API(committee_api, get_committee_requests_list) {
CHECK_ARG_MIN_SIZE(1, 1)
auto status = args.args->at(0).as<uint16_t>();
auto& db = pimpl->database();
return db.with_weak_read_lock([&]() {
const auto &idx = db.get_index<committee_request_index>().indices().get<by_status>();
std::vector<uint16_t> requests_list;
auto itr = idx.lower_bound(status);
while (itr != idx.end() &&
itr->status == status) {
requests_list.emplace_back(itr->request_id);
++itr;
}
return requests_list;
});
}
} } } // graphene::plugins::committee_api
| 37.042254 | 107 | 0.553042 | [
"vector"
] |
fbcf2e83bf3b202f27cd6da28a1073e6eaf8a0a2 | 2,789 | cc | C++ | voro++/examples/no_release/lloyd_box.cc | lsmo-epfl/zeoplusplus | b8acd8d08d7256aecdbb92454250760314a00b06 | [
"BSD-3-Clause-LBNL"
] | 2 | 2019-11-14T02:27:33.000Z | 2020-05-05T23:17:47.000Z | voro++/examples/no_release/lloyd_box.cc | lsmo-epfl/zeoplusplus | b8acd8d08d7256aecdbb92454250760314a00b06 | [
"BSD-3-Clause-LBNL"
] | 4 | 2018-10-17T08:20:58.000Z | 2020-12-19T03:28:01.000Z | voro++/examples/no_release/lloyd_box.cc | lsmo-epfl/zeopp-lsmo | b8acd8d08d7256aecdbb92454250760314a00b06 | [
"BSD-3-Clause-LBNL"
] | 3 | 2019-03-04T11:25:44.000Z | 2019-05-29T16:37:12.000Z | // Voronoi calculation example code
//
// Author : Chris H. Rycroft (LBL / UC Berkeley)
// Email : chr@alum.mit.edu
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
#include <vector>
using namespace std;
// Set up constants for the container geometry
const double boxl = 1;
// Set up the number of blocks that the container is divided into
const int bl = 10;
// Set the number of particles that are going to be randomly introduced
const int particles = 4000;
// Set the number of Voronoi faces to bin
const int nface = 40;
// This function returns a random double between 0 and 1
double rnd() { return double(rand()) / RAND_MAX; }
int main() {
int i, l;
double x, y, z, r, dx, dy, dz;
int faces[nface], *fp;
double p[3 * particles];
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block
container con(-boxl, boxl, -boxl, boxl, -boxl, boxl, bl, bl, bl, false, false,
false, 8);
// Randomly add particles into the container
for (i = 0; i < particles; i++) {
x = boxl * (2 * rnd() - 1);
y = boxl * (2 * rnd() - 1);
z = boxl * (2 * rnd() - 1);
con.put(i, x, y, z);
}
for (l = 0; l <= 200; l++) {
c_loop_all vl(con);
voronoicell c;
for (fp = faces; fp < faces + nface; fp++) *fp = 0;
if (vl.start()) do
if (con.compute_cell(c, vl)) {
vl.pos(i, x, y, z, r);
c.centroid(dx, dy, dz);
p[3 * i] = x + dx;
p[3 * i + 1] = y + dy;
p[3 * i + 2] = z + dz;
i = c.number_of_faces() - 4;
if (i < 0) i = 0;
if (i >= nface) i = nface - 1;
faces[i]++;
}
while (vl.inc());
con.clear();
for (i = 0; i < particles; i++)
con.put(i, p[3 * i], p[3 * i + 1], p[3 * i + 2]);
printf("%d", l);
for (fp = faces; fp < faces + nface; fp++) printf(" %d", *fp);
puts("");
}
// Output the particle positions in gnuplot format
con.draw_particles("sphere_mesh_p.gnu");
// Output the Voronoi cells in gnuplot format
con.draw_cells_gnuplot("sphere_mesh_v.gnu");
// Output the neighbor mesh in gnuplot format
FILE *ff = safe_fopen("sphere_mesh.net", "w");
vector<int> vi;
voronoicell_neighbor c;
c_loop_all vl(con);
if (vl.start()) do
if (con.compute_cell(c, vl)) {
i = vl.pid();
c.neighbors(vi);
for (l = 0; l < (signed int)vi.size(); l++)
if (vi[l] > i)
fprintf(ff, "%g %g %g\n%g %g %g\n\n\n", p[3 * i], p[3 * i + 1],
p[3 * i + 2], p[3 * vi[l]], p[3 * vi[l] + 1],
p[3 * vi[l] + 2]);
}
while (vl.inc());
fclose(ff);
}
| 28.459184 | 80 | 0.543564 | [
"mesh",
"geometry",
"vector"
] |
fbd608d13dd8beba3efb86c5502f89010511f8a3 | 2,989 | cc | C++ | examples/cmake/loopback.cc | bolderflight/easycan | 79b5dd0b180af7e187bf6d2e078be733ad891726 | [
"MIT"
] | null | null | null | examples/cmake/loopback.cc | bolderflight/easycan | 79b5dd0b180af7e187bf6d2e078be733ad891726 | [
"MIT"
] | null | null | null | examples/cmake/loopback.cc | bolderflight/easycan | 79b5dd0b180af7e187bf6d2e078be733ad891726 | [
"MIT"
] | null | null | null | /*
* Brian R Taylor
* brian.taylor@bolderflight.com
*
* Copyright (c) 2022 Bolder Flight Systems Inc
*
* 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 "easycan.h"
/* Loopback test from CAN0 to CAN1 and CAN1 to CAN0 on a Teensy 3.6 */
/*
* One object for each CAN bus, 32 CanMsg's can be stored in each RX and TX FIFO
*/
bfs::EasyCan<CAN0, 32, 32> can0;
bfs::EasyCan<CAN1, 32, 32> can1;
/* A CanMsg to send */
bfs::CanMsg msg;
int main() {
/* Start serial for feedback */
Serial.begin(115200);
while (!Serial) {}
Serial.println("STARTING TEST");
/* Enable the CAN transceivers, these will be config dependent */
pinMode(26, OUTPUT);
pinMode(27, OUTPUT);
digitalWriteFast(26, LOW);
digitalWriteFast(27, LOW);
/* Begin the CAN */
can0.Begin(1000000);
can1.Begin(1000000);
/*
* Setup filters on CAN1, enable ID 1 and ID 15 - 20
*/
can1.FilterRejectAll();
can1.SetFilter(0, 1, STD);
can1.SetFilterRange(1, 15, 20, STD);
/* Write messages between the CAN buses, non-blocking, no timeout */
for (std::size_t i = 0; i < 24; i++) {
msg.id = i;
can0.Write(msg, -1, false);
can1.Write(msg, -1, false);
}
/* Delay to let messages propagate */
delay(10);
/* See what each reeceived */
Serial.println("CAN0 Received: ");
std::size_t msg_avail = can0.available();
Serial.print(msg_avail);
Serial.println(" messages:");
while (can0.available()) {
can0.Read(&msg, 1);
Serial.print("ID & Timestamp:\t");
Serial.print(msg.id);
Serial.print("\t");
Serial.println((uint32_t)msg.timestamp_us);
}
Serial.println("\nCAN1 Received: ");
msg_avail = can1.available();
Serial.print(msg_avail);
Serial.println(" messages:");
while (can1.available()) {
bfs::optional<bfs::CanMsg> ret = can1.Read();
if (ret) {
Serial.print("ID & Timestamp:\t");
Serial.print(ret.value().id);
Serial.print("\t");
Serial.println((uint32_t)ret.value().timestamp_us);
}
}
}
| 32.139785 | 79 | 0.688525 | [
"object"
] |
fbd876982475b73013a938c0b1812194bb7e11ee | 6,605 | cc | C++ | solution.cc | mkaminaga/satpass | fc6520dfdb22ffd72da23b2c2d1812df03b239b1 | [
"MIT"
] | null | null | null | solution.cc | mkaminaga/satpass | fc6520dfdb22ffd72da23b2c2d1812df03b239b1 | [
"MIT"
] | 5 | 2017-09-12T02:42:42.000Z | 2017-09-27T09:07:52.000Z | solution.cc | mkaminaga/satpass | fc6520dfdb22ffd72da23b2c2d1812df03b239b1 | [
"MIT"
] | null | null | null | // @file solution.cc
// @brief The functions to solve orbit parameters.
// @author Mamoru Kaminaga
// @date 2017-09-11 16:01:03
// Copyright 2017 Mamoru Kaminaga
#include <assert.h>
#include <wchar.h>
#include <sat/v1.0.2/data.h>
#include <sat/v1.0.2/sat.h>
#include <sat/v1.0.2/util.h>
#include <tle/v2.1.0/tle.h>
#include <cmath>
#include <string>
#include <vector>
#include "./common.h"
#include "./solution.h"
bool Solve(Data* data) {
assert(data);
wprintf(L"--------------------\n");
wprintf(L"Solving orbital problem\n");
// The orbital problem solver is initialized.
if (!sat::InitSat(data->tle, &data->sat)) {
wprintf(L"solver init failed.\n");
return false;
}
// The orbital problem is solved and the ECEF position of the satellite is
// derived for each jd.
double days = data->jd_stop - data->jd_start;
const size_t size = static_cast<size_t>(days * 86400 / SATPASS_DELTA_SEC);
wprintf(L"The time step: %d\n", size);
data->jd.reserve(size);
data->m.reserve(size);
data->ps.reserve(size);
double jd = 0;
for (int i = 0; i < static_cast<int>(size); ++i) {
jd = data->jd_start + (data->jd_stop - data->jd_start) *
i / static_cast<double>(size);
if (!sat::GetSatPos(jd, &data->sat)) {
wprintf(L"The simulation failed at jd = %.8f\n", jd);
return false;
}
// The result is stored.
data->jd.push_back(jd);
data->m.push_back(data->sat.m);
data->ps.push_back(data->sat.p);
}
wprintf(L"Succeed... The orbital problem solver converged\n");
// The satellite position is transformed into the horizontal coordinate
// system for each observation point.
enum HCSSTATUS {
HCSSTATUS_HIDDEN,
HCSSTATUS_VIEWED,
HCSSTATUS_IGNORE_FIRST_PASS,
};
HCSSTATUS status = HCSSTATUS_HIDDEN;
data->vp.reserve(size);
wprintf(L"Calculating...Please wait.\n");
fflush(0);
for (int i = 0; i < static_cast<int>(data->nameo.size()); ++i) {
// Buffers are cleared.
data->vp.clear();
// The exceptional case is checked.
sat::WiewedPoint v;
sat::ViewSat(data->wo[i], data->ps[0], &v);
if (v.el > 0) {
wprintf(L"Warning...%ls AOS in jd start, the first pass is ignored.\n",
data->nameo[i].c_str());
fflush(0);
status = HCSSTATUS_IGNORE_FIRST_PASS;
}
sat::ViewSat(data->wo[i], data->ps[data->ps.size() - 1], &v);
if (v.el > 0) {
wprintf(L"Warning...%ls AOS in jd stop, the last pass is ignored.\n",
data->nameo[i].c_str());
}
// The loop to buffer data->
for (int j = 0; j < static_cast<int>(data->ps.size()); ++j) {
sat::ViewSat(data->wo[i], data->ps[j], &v);
data->vp.push_back(v);
}
// The loop to check AOS, MEL and LOS.
int j_aos_tmp = 0;
int j_mel_tmp = 0;
double el_max = 0.0;
std::vector<int> j_aos;
std::vector<int> j_mel;
std::vector<int> j_los;
for (int j = 0; j < static_cast<int>(data->ps.size()); ++j) {
switch (status) {
case HCSSTATUS_HIDDEN:
// AOS check.
if (data->vp[j].el >= 0) {
j_aos_tmp = j;
el_max = 0.0;
status = HCSSTATUS_VIEWED;
}
break;
case HCSSTATUS_VIEWED:
// MEL check.
if (data->vp[j].el > el_max) {
el_max = data->vp[j].el;
j_mel_tmp = j;
}
// LOS check.
if (data->vp[j].el <= 0) {
j_aos.push_back(j_aos_tmp);
j_mel.push_back(j_mel_tmp);
j_los.push_back(j);
status = HCSSTATUS_HIDDEN;
}
break;
case HCSSTATUS_IGNORE_FIRST_PASS:
// LOS check.
if (data->vp[j].el <= 0) {
status = HCSSTATUS_HIDDEN;
}
break;
default:
// No implementation.
break;
}
}
// The loop to store AOS, MEL and LOS data.
data->m_aos.push_back(std::vector<int>());
data->m_los.push_back(std::vector<int>());
data->jd_aos.push_back(std::vector<double>());
data->jd_mel.push_back(std::vector<double>());
data->jd_los.push_back(std::vector<double>());
data->az_aos.push_back(std::vector<double>());
data->az_mel.push_back(std::vector<double>());
data->az_los.push_back(std::vector<double>());
data->el_mel.push_back(std::vector<double>());
data->duration.push_back(std::vector<double>());
double ma = 0.0;
for (int j = 0; j < static_cast<int>(j_aos.size()); ++j) {
data->jd_aos[i].push_back(data->jd[j_aos[j]]);
data->jd_mel[i].push_back(data->jd[j_mel[j]]);
data->jd_los[i].push_back(data->jd[j_los[j]]);
data->az_aos[i].push_back(SAT_TO_DEGREES(data->vp[j_aos[j]].az));
data->az_mel[i].push_back(SAT_TO_DEGREES(data->vp[j_mel[j]].az));
data->az_los[i].push_back(SAT_TO_DEGREES(data->vp[j_los[j]].az));
data->el_mel[i].push_back(SAT_TO_DEGREES(data->vp[j_mel[j]].el));
data->duration[i].push_back((data->jd_los[i][j] - data->jd_aos[i][j]) *
1440);
// MA is calculated.
ma = data->m[j_aos[j]];
ma = (ma - std::floor(ma)) * 255.0 + 0.5; // 0 to 255, round
data->m_aos[i].push_back(static_cast<int>(ma));
ma = data->m[j_los[j]];
ma = (ma - std::floor(ma)) * 255.0 + 0.5; // 0 to 255, round
data->m_los[i].push_back(static_cast<int>(ma));
}
// The time span is checked and the event row is written.
data->event.push_back(std::vector<std::basic_string<wchar_t>>());
for (int j = 0; j < static_cast<int>(data->jd_aos[i].size()); ++j) {
data->event[i].push_back(L"");
}
// For each events.
for (int e = 0; e < static_cast<int>(data->events.size()); ++e) {
if (data->use_event[e] == TRUE) {
// For each event spans.
for (int k = 0; k < static_cast<int>(data->jd_event_from[e].size());
++k) {
// For each MEL jd of the position.
for (int j = 0; j < static_cast<int>(data->jd_mel[i].size()); ++j) {
// If the MEL is in the span of the event, add the event signature
// to the event raw of the output html file.
if ((data->jd_event_from[e][k] < data->jd_mel[i][j]) &&
(data->jd_mel[i][j] < data->jd_event_to[e][k])) {
if (data->event[i][j].length() != 0) {
data->event[i][j] += L", ";
data->event[i][j] += data->events[e];
} else {
data->event[i][j] = data->events[e];
}
}
}
}
}
}
}
return true;
}
| 35.320856 | 78 | 0.560939 | [
"vector"
] |
fbd9b481946e2a07f34c5289c1dc0db6879e32f9 | 2,729 | cpp | C++ | cpp/tests/src/test_ste_global.cpp | tomerten/steibs | 8d4e994020dd17475ba1371e9c6f365c916828a0 | [
"MIT"
] | null | null | null | cpp/tests/src/test_ste_global.cpp | tomerten/steibs | 8d4e994020dd17475ba1371e9c6f365c916828a0 | [
"MIT"
] | null | null | null | cpp/tests/src/test_ste_global.cpp | tomerten/steibs | 8d4e994020dd17475ba1371e9c6f365c916828a0 | [
"MIT"
] | null | null | null | #include <ibs>
#include <iomanip>
#include <iostream>
#include <ste>
// for testing
template <typename T>
bool RequireVectorEquals(const std::vector<T> &a, const std::vector<T> &b,
T max_error = 0.000000001) {
const auto first_mismatch = std::mismatch(
a.begin(), a.end(), b.begin(), [max_error](T val_a, T val_b) {
// std::cout << val_a << " " << val_b << std::endl;
return val_a == val_b || std::abs(val_a - val_b) < max_error;
});
if (first_mismatch.first != a.end()) {
// std::printf("%s", std::to_string(*first_mismatch.first).c_str());
// std::printf("%s", std::to_string(*first_mismatch.second).c_str());
return false;
} else
return true;
}
bool test_calc_emit(std::vector<std::vector<double>> distribution, double betx,
double bety) {
std::vector<double> expected = {5.10117e-09, 1.04194e-08, 2.52591e-10,
1.42116e-09, 1.66734e-11, 0.00114571};
std::vector<double> actual =
ste_global::CalculateEmittance(distribution, betx, bety);
return RequireVectorEquals(expected, actual, 0.1);
}
int main() {
// set seed
int seed = 123456;
string twissfilename = "../src/b2_design_lattice_1996.twiss";
map<string, double> twheader;
twheader = GetTwissHeader(twissfilename);
// rf settings
std::vector<double> h, v;
h.push_back(400.0);
v.push_back(-1.5e6);
// bunch length
double sigs = 0.005;
// aatom
double aatom = emass / pmass;
// set energy loss per turn manually
// TODO: implement radiation update of twiss
twheader["U0"] = 174e3;
// update twiss header with long parameters
ste_longitudinal::updateTwissHeaderLong(twheader, h, v, aatom, sigs);
int nMacro = 4096;
double betx = twheader["LENGTH"] / (twheader["Q1"] * 2.0 * pi);
double bety = twheader["LENGTH"] / (twheader["Q2"] * 2.0 * pi);
double coupling = 0.05;
double ex = 5e-9;
double ey = coupling * ex;
std::vector<std::vector<double>> distribution =
ste_random::GenerateDistributionMatched(nMacro, betx, ex, bety, ey, h, v,
twheader, seed);
/*
std::vector<double> emit =
ste_global::CalculateEmittance(distribution, betx, bety);
std::printf("%-20s %16.8e\n", "ex", ex);
std::printf("%-20s %16.8e\n", "ey", ey);
std::printf("%-20s %16.8e\n", "betx", betx);
std::printf("%-20s %16.8e\n", "bety", bety);
ste_output::printVector(emit);
*/
// test calc emittance
std::printf("%-30s", "test_calc_emit ");
if (test_calc_emit(distribution, betx, bety)) {
ste_output::green();
std::printf("Passed\n");
} else {
ste_output::red();
std::printf("Failed\n");
}
ste_output::reset();
return 0;
} | 31.011364 | 79 | 0.618908 | [
"vector"
] |
fbe1bab162f8711fb646b120e791bb4bd7c74d39 | 1,158 | cpp | C++ | TopicWiseQuestions/DP/Cses/CoinSChange1/main.cpp | jeevanpuchakay/a2oj | f867e9b2ced6619be3ca6b1a1a1838107322782d | [
"MIT"
] | null | null | null | TopicWiseQuestions/DP/Cses/CoinSChange1/main.cpp | jeevanpuchakay/a2oj | f867e9b2ced6619be3ca6b1a1a1838107322782d | [
"MIT"
] | null | null | null | TopicWiseQuestions/DP/Cses/CoinSChange1/main.cpp | jeevanpuchakay/a2oj | f867e9b2ced6619be3ca6b1a1a1838107322782d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long double ld;
typedef long long int ll;
#define endl "\n"
vector<vector<ll>> adjlist;
ll max(ll x, ll y) { return (x > y) ? x : y; }
ll min(ll x, ll y) { return (x > y) ? y : x; }
#define mod 1000000007
ll cases = 1, n, sum, m;
ll x, y;
// ll getNoOfWays(ll sum, ll pos, vector<ll> &coins, vector<vector<ll>> &dp)
// {
// if (pos >= n || sum <= 0)
// return sum == 0;
// if (dp[sum][pos] != -1)
// return dp[sum][pos];
// return dp[sum][pos] = getNoOfWays(sum - coins[pos], pos, coins, dp) + getNoOfWays(sum, pos + 1, coins, dp);
// }
void solveCase()
{
cin >> n >> m;
vector<ll> coins(n), noOfWay(m + 1, 0);
for (ll &each : coins)
cin >> each;
sort(coins.begin(), coins.end());
noOfWay[0] = 1;
for (ll i = 1; i <= m; i++)
{
for (ll j = 0; j < n && coins[j] <= i; j++)
{
noOfWay[i] += noOfWay[i - coins[j]];
noOfWay[i] %= mod;
}
}
cout << noOfWay[m] << endl;
}
int main()
{
// cin >> cases;
for (ll t = 1; t <= cases; t++)
{
solveCase();
}
return 0;
} | 23.632653 | 114 | 0.48791 | [
"vector"
] |
fbe3400e6f86d47a1b17de883bbbb7c0a3d29fe4 | 1,505 | cpp | C++ | p1025.cpp | ThinkiNOriginal/PTA-Advanced | 55cae28f76102964d0f6fd728dd62d6eba980c49 | [
"MIT"
] | null | null | null | p1025.cpp | ThinkiNOriginal/PTA-Advanced | 55cae28f76102964d0f6fd728dd62d6eba980c49 | [
"MIT"
] | null | null | null | p1025.cpp | ThinkiNOriginal/PTA-Advanced | 55cae28f76102964d0f6fd728dd62d6eba980c49 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
struct Student {
char rn[13];
int grades;
int final_r;
int local_r;
int ln;
};
bool cmp (const Student& s1, const Student& s2) {
if (s1.grades != s2.grades)
return s1.grades > s2.grades;
else
return std::strcmp(s1.rn, s2.rn) < 0;
}
bool cmp2 (const Student& s1, const Student& s2) {
if (s1.grades != s2.grades)
return s1.grades > s2.grades;
else
return std::strcmp(s1.rn, s2.rn) < 0;
}
int main() {
int N;
scanf("%d", &N);
std::vector<std::vector<Student>> v(N);
std::vector<Student> all;
int total_num = 0;
for (int i = 0; i < N; i++) {
int K;
scanf("%d", &K);
total_num += K;
std::vector<Student> tmp(K);
for (int j = 0; j < K; j++) {
scanf("%s %d", tmp[j].rn, &tmp[j].grades);
tmp[j].ln = i + 1;
}
v[i] = tmp;
}
for (auto& x : v) {
std::sort(x.begin(), x.end(), cmp);
int len = x.size();
x[0].local_r = 1;
all.push_back(x[0]);
for (int i = 1; i < len; i++) {
if (x[i].grades == x[i - 1].grades) {
x[i].local_r = x[i - 1].local_r;
} else
x[i].local_r = i + 1;
all.push_back(x[i]);
}}
std::sort(all.begin(), all.end(), cmp2);
all[0].final_r = 1;
for (int i = 1; i < total_num; i++) {
if (all[i].grades == all[i - 1].grades) {
all[i].final_r = all[i - 1].final_r;
} else
all[i].final_r = i + 1;
}
printf("%d\n", total_num);
for (auto x : all)
printf("%s %d %d %d\n", x.rn, x.final_r, x.ln, x.local_r);
return 0;
}
| 18.8125 | 60 | 0.548173 | [
"vector"
] |
fbec473de82285f65178b24d1fa7d5fe723728de | 5,387 | hpp | C++ | modules/cvv/src/qtutil/registerhelper.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 7,158 | 2016-07-04T22:19:27.000Z | 2022-03-31T07:54:32.000Z | modules/cvv/src/qtutil/registerhelper.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 2,184 | 2016-07-05T12:04:14.000Z | 2022-03-30T19:10:12.000Z | modules/cvv/src/qtutil/registerhelper.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 5,535 | 2016-07-06T12:01:10.000Z | 2022-03-31T03:13:24.000Z | #ifndef CVVISUAL_REGISTERHELPER_HPP
#define CVVISUAL_REGISTERHELPER_HPP
// std
#include <map>
#include <vector>
#include <stdexcept>
#include <memory>
#include <functional>
// QT
#include <QWidget>
#include <QString>
#include <QComboBox>
#include <QVBoxLayout>
// cvv
#include "signalslot.hpp"
namespace cvv
{
namespace qtutil
{
/**
* @brief The RegisterHelper class can be inherited to gain a mechanism to
*register fabric functions
* for QWidgets.
*
* The registered functions are shared between all instances of a class.
* A QComboBox is provided for user selection.
* The content of the QComboBox is updated whenever a function is registered.
*
* Inheriting classes have to delete the member comboBox_ on destruction!
* (e.g. by putting it into a layout)
*/
template <class Value, class... Args> class RegisterHelper
{
public:
/**
* @brief Constructor
*/
RegisterHelper()
: comboBox_{ new QComboBox{} }, signElementSelected_{},
slotElementRegistered_{ [&](const QString &name)
{
comboBox_->addItem(name);
} }
{
// elem registered
QObject::connect(&signalElementRegistered(),
&SignalQString::signal,
&slotElementRegistered_, &SlotQString::slot);
// connect
QObject::connect(comboBox_, &QComboBox::currentTextChanged,
&signalElementSelected(),
&SignalQString::signal);
// add current list of elements
for (auto &elem : registeredElementsMap())
{
comboBox_->addItem(elem.first);
}
}
~RegisterHelper()
{
}
/**
* @brief Returns the current selection from the QComboBox
* @return The current selection from the QComboBox
*/
QString selection() const
{
return comboBox_->currentText();
}
/**
* @brief Checks whether a function was registered with the name.
* @param name The name to look up
* @return true if there is a function. false otherwise
*/
static bool has(const QString &name)
{
return registeredElementsMap().find(name) !=
registeredElementsMap().end();
}
/**
* @brief Returns the names of all registered functions.
* @return The names of all registered functions.
*/
static std::vector<QString> registeredElements()
{
std::vector<QString> result{};
for (auto &elem : registeredElementsMap())
{
result.push_back(elem.first);
};
return result;
}
/**
* @brief Registers a function.
* @param name The name.
* @param fabric The fabric function.
* @return true if the function was registered. false if the name was
* taken
* (the function was not registered!)
*/
static bool registerElement(
const QString &name,
const std::function<std::unique_ptr<Value>(Args...)> &fabric)
{
if (has(name))
{
return false;
};
registeredElementsMap().emplace(name, fabric);
signalElementRegistered().emitSignal(name);
return true;
}
/**
* @brief Selects an function according to name.
* @param name The name of the function to select.
* @return true if the function was selected. false if no function has
* name.
*/
bool select(const QString &name)
{
if (!has(name))
{
return false;
}
comboBox_->setCurrentText(name);
return true;
}
/**
* @brief Returns the function according to the current selection of the
* QComboBox.
* @throw std::out_of_range If there is no such function.
* @return The function according to the current selection of the
* QComboBox.
*/
std::function<std::unique_ptr<Value>(Args...)> operator()()
{
return (*this)(selection());
}
/**
* @brief Returns the function according to name.
* @param The name of a registered function.
* @throw std::out_of_range If there is no such function.
* @return The function according to name.
*/
std::function<std::unique_ptr<Value>(Args...)>
operator()(const QString &name)
{
return registeredElementsMap().at(name);
}
/**
* @brief Returns a signal emitted whenever a function is registered.
* @return A signal emitted whenever a function is registered.
*/
static const SignalQString &signalElementRegistered()
{
static const SignalQString signElementRegistered_{};
return signElementRegistered_;
}
/**
* @brief Returns the signal emitted whenever a new element in the
* combobox is selected.
* (passes the selected string)
* @return The signal emitted whenever a new element in the combobox is
* selected.
* (passes the selected string)
*/
const SignalQString &signalElementSelected() const
{
return signElementSelected_;
}
protected:
/**
* @brief QComboBox containing all names of registered functions
*/
QComboBox *comboBox_;
private:
/**
* @brief Signal emitted whenever a new element in the combobox is
* selected.
* (passes the selected string)
*/
const SignalQString signElementSelected_;
/**
* @brief Slot called whenever a function is registered
*/
const SlotQString slotElementRegistered_;
/**
* @brief Returns the map of registered functions and their names.
* @return The map of registered functions and their names.
*/
static std::map<QString,
std::function<std::unique_ptr<Value>(Args...)>> &
registeredElementsMap()
{
static std::map<QString,
std::function<std::unique_ptr<Value>(Args...)>>
map{};
return map;
}
};
}
} // end namespaces qtutil, cvv
#endif // CVVISUAL_REGISTERHELPER_HPP
| 24.049107 | 77 | 0.685911 | [
"vector"
] |
fbf9c78408954d76de5a519dc50c81594a552365 | 1,279 | hpp | C++ | include/notima/internal/stats.hpp | drtconway/notima | fb542096b435bdc3246192fd7e4ba86080952afd | [
"MIT"
] | null | null | null | include/notima/internal/stats.hpp | drtconway/notima | fb542096b435bdc3246192fd7e4ba86080952afd | [
"MIT"
] | null | null | null | include/notima/internal/stats.hpp | drtconway/notima | fb542096b435bdc3246192fd7e4ba86080952afd | [
"MIT"
] | null | null | null | #ifndef NOTIMA_INTERNAL_STATS_HPP
#define NOTIMA_INTERNAL_STATS_HPP
#include <nlohmann/json.hpp>
namespace notima
{
namespace internal
{
template <typename T, typename U = void>
struct gather
{
nlohmann::json operator()(const T& p_ob) const
{
std::string msg = "no specialization for: ";
msg += std::string(typeid(T).name());
throw std::logic_error(msg);
}
};
struct stats
{
template <typename T>
static nlohmann::json gather(const T& p_obj)
{
return notima::internal::gather<T>{}(p_obj);
}
};
template <typename W>
struct gather<std::vector<W>, typename std::enable_if<std::is_arithmetic<W>::value>::type>
{
nlohmann::json operator()(const std::vector<W>& p_obj) const
{
nlohmann::json s;
s["vector"]["W"] = sizeof(W);
s["vector"]["size"] = p_obj.size();
s["vector"]["memory"] = p_obj.capacity()*sizeof(W);
return s;
}
};
}
// namespace internal
}
// namespace notima
#endif // NOTIMA_INTERNAL_STATS_HPP
| 26.102041 | 98 | 0.503518 | [
"vector"
] |
81fc2a2d2ca1a111d02418375797301e26404b20 | 20,696 | cpp | C++ | src/btree.cpp | celinao/Btree | f090f404a3dcd9b9b3204611c12965c479e8ac7e | [
"Apache-2.0"
] | null | null | null | src/btree.cpp | celinao/Btree | f090f404a3dcd9b9b3204611c12965c479e8ac7e | [
"Apache-2.0"
] | null | null | null | src/btree.cpp | celinao/Btree | f090f404a3dcd9b9b3204611c12965c479e8ac7e | [
"Apache-2.0"
] | null | null | null | /**
* Group 24:
* Celina Ough 9074747438
* Atharva Kudkilwar 9081348659
*
* @author See Contributors.txt for code contributors and overview of BadgerDB.
*
* @section LICENSE
* Copyright (c) 2012 Database Group, Computer Sciences Department, University of Wisconsin-Madison.
*/
#include "btree.h"
#include "filescan.h"
#include "exceptions/bad_index_info_exception.h"
#include "exceptions/bad_opcodes_exception.h"
#include "exceptions/bad_scanrange_exception.h"
#include "exceptions/no_such_key_found_exception.h"
#include "exceptions/scan_not_initialized_exception.h"
#include "exceptions/index_scan_completed_exception.h"
#include "exceptions/file_not_found_exception.h"
#include "exceptions/end_of_file_exception.h"
using namespace std;
//#define DEBUG
namespace badgerdb
{
// -----------------------------------------------------------------------------
// BTreeIndex::BTreeIndex -- Constructor
// -----------------------------------------------------------------------------
BTreeIndex::BTreeIndex(const std::string & relationName,
std::string & outIndexName,
BufMgr *bufMgrIn,
const int attrByteOffset,
const Datatype attrType)
{
// Initialize variables
// Assuming all inputs are integers (as specified in assignment document)
bufMgr = bufMgrIn;
leafOccupancy = INTARRAYLEAFSIZE;
nodeOccupancy = INTARRAYNONLEAFSIZE;
this->scanExecuting = false;
this->attrByteOffset = attrByteOffset;
attributeType = attrType;
// Construct indexName and return via outIndexName (code from assignment doc)
std::ostringstream idxStr;
idxStr << relationName << '.' << attrByteOffset;
std::string indexName = idxStr.str();
outIndexName = indexName;
// Create BlobFile
try{
// File Exists:
// Create a disk image of the index file (doesn't create a new file)
file = new BlobFile(indexName, false);
// Get existing header & root pages
Page *headerPage;
headerPageNum = file->getFirstPageNo();
bufMgr->readPage(file, headerPageNum, headerPage);
IndexMetaInfo *metaInfo = (IndexMetaInfo *) headerPage;
rootPageNum = metaInfo->rootPageNo;
// Check meta info for accurate information
std::cout << "metaInfo->relationName: " << metaInfo->relationName << " RelationName: " << relationName.c_str() << std::endl;
if(strcmp(metaInfo->relationName, relationName.c_str()) != 0){
throw BadIndexInfoException("Relation names do not match");
}else if(metaInfo->attrByteOffset != attrByteOffset){
throw BadIndexInfoException("Attribute Byte Offsets do not match");
}else if(metaInfo->attrType != attributeType){
throw BadIndexInfoException("Attribute Types do not match");
}
// UnPinPage once done
bufMgr->unPinPage(file, headerPageNum, false);
}catch(const FileNotFoundException &e){
// File Does Not Exist:
// Create a disk image of the index file
file = new BlobFile(indexName, true);
// Create root & header pages
headerPageNum = 0;
Page *headerPage;
bufMgr->allocPage(file, headerPageNum, headerPage);
rootPageNum = 1;
Page *rootPage;
bufMgr->allocPage(file, rootPageNum, rootPage);
// Create root node and add right sibling
LeafNodeInt *rootNode = (LeafNodeInt *) rootPage;
rootNode->rightSibPageNo = 0;
// Adding Meta Information to headerPage
IndexMetaInfo *metaInfo = (IndexMetaInfo *) headerPage;
strcpy(metaInfo->relationName, relationName.c_str());
metaInfo->attrByteOffset = attrByteOffset;
metaInfo->attrType = attrType;
metaInfo->rootPageNo = rootPageNum;
metaInfo->rootIsLeaf = true;
// UnPinPage once done
bufMgr->unPinPage(file, headerPageNum, true);
bufMgr->unPinPage(file, rootPageNum, true);
// Create new FileScan object
FileScan fscan(relationName, bufMgr);
try
{
// Get all tuples in relation.
RecordId scanRid;
while(1)
{
// Find key
fscan.scanNext(scanRid);
std::string recordStr = fscan.getRecord();
const char *record = recordStr.c_str();
// Insert into BTree
insertEntry(record+attrByteOffset, scanRid);
}
}
catch(const EndOfFileException &e)
{
std::cout << "Print Tree: " << std::endl;
printTree(rootPageNum, true);
bufMgr->flushFile(file);
}
}
}
// -----------------------------------------------------------------------------
// BTreeIndex::~BTreeIndex -- destructor
// -----------------------------------------------------------------------------
BTreeIndex::~BTreeIndex()
{
// Stop scanning
try{
endScan();
}catch(const ScanNotInitializedException &e){
// No Scan has been initialized. Catching Error and closing BTreeIndex
}
// Remove file
bufMgr->flushFile(file);
delete file;
}
// -----------------------------------------------------------------------------
// BTreeIndex::insertEntry
// -----------------------------------------------------------------------------
void BTreeIndex::insertEntry(const void *key, const RecordId rid)
{
// Get headerPage
Page *headerPage;
headerPageNum = file->getFirstPageNo();
bufMgr->readPage(file, headerPageNum, headerPage);
IndexMetaInfo *metaInfo = (IndexMetaInfo *) headerPage;
// Check if root is a leaf or internal node
PageKeyPair<int> pageKey;
if(metaInfo->rootIsLeaf){
// Root is a leaf node
pageKey = insertToLeaf(key, rid, rootPageNum);
// Check if root was split and needs to change into an internal node
if(pageKey.pageNo != 0){
// Create a new internal node for the new root
Page* newRootPage;
PageId newRootNo;
bufMgr->allocPage(file, newRootNo, newRootPage);
NonLeafNodeInt *newRootNode = (NonLeafNodeInt *)newRootPage;
// Initiialize new Root
newRootNode->keyArray[0] = pageKey.key;
newRootNode->pageNoArray[0] = rootPageNum;
newRootNode->pageNoArray[1] = pageKey.pageNo;
newRootNode->level = 1;
// Update header page
metaInfo->rootPageNo = newRootNo;
metaInfo->rootIsLeaf = false;
rootPageNum = newRootNo;
bufMgr->unPinPage(file, newRootNo, true);
}
}else{
insertLeafHelper(key, rootPageNum, rid);
}
// Unpin Header page
bufMgr->unPinPage(file, headerPageNum, true);
}
void BTreeIndex::insertLeafHelper(const void *key, PageId pageNo, const RecordId rid){
// Create internal node
Page* page;
bufMgr->readPage(file, pageNo, page);
NonLeafNodeInt *node = (NonLeafNodeInt *)page;
// Check every key in array for insertion position
PageKeyPair<int> pageKey;
for(int i = 0; i < INTARRAYNONLEAFSIZE+1; i++){
// insert if key is less than node's key, 0 (end of partially filled array), INTARRAYNONLEAFSIZE (end of full array)
if(*(int *)key < node->keyArray[i] || 0 == node->pageNoArray[i+1] || i == INTARRAYNONLEAFSIZE){
// Insert into leaf
if(node->level == 1){
// Insert Page
pageKey = insertToLeaf(key, rid, node->pageNoArray[i]);
// Check if node split and needs to be updated
if(pageKey.pageNo != 0){
insertToNonLeaf(pageKey, pageNo);
}
break;
}else {
insertLeafHelper(key, node->pageNoArray[i], rid);
}
break;
}
}
bufMgr->unPinPage(file, pageNo, false);
}
PageKeyPair<int> BTreeIndex::insertToLeaf(const void *key, const RecordId rid, PageId pageNo) {
// Read Node that is being inserted to
Page* page;
bufMgr->readPage(file, pageNo, page);
LeafNodeInt* node = (LeafNodeInt*)page;
// Check if leaf node is full and keep track of leaf size
bool full = true;
int size = -1;
for (int i = 0; i < INTARRAYLEAFSIZE+1; i++) {
size = i;
if (node->ridArray[i].page_number == 0 && i < INTARRAYLEAFSIZE) {
full = false;
break;
}
}
// Find position for insertion in keyArray
int pos = 0;
for (int i = 0; i < size+1; i++) {
pos = i;
if (*(int*)key < node->keyArray[i]) {
break;
}
}
// if node is not full
if (full == false) {
// shifting keys and rids to right to make space to insert
for (int i = size; i > pos; i--) {
node->keyArray[i] = node->keyArray[i-1];
node->ridArray[i] = node->ridArray[i-1];
}
// Add new record
node->keyArray[pos] = *(int*)key;
node->ridArray[pos] = rid;
bufMgr->unPinPage(this->file, pageNo, true);
}
else {
// Node is full and must be split
PageKeyPair<int> pageKey = splitLeaf(pageNo);
// Check if key belongs in left or right split node
// No need to check return of insertToLeaf since the node was just split and
// therefore not full.
if(pageKey.key < *(int*)key){
insertToLeaf(key, rid, pageKey.pageNo);
}else{
insertToLeaf(key, rid, pageNo);
}
// Unpin pages and return pageKey to be added internally
bufMgr->unPinPage(this->file, pageNo, true);
return pageKey;
}
// Return empty pageKey if no splitting necessary
PageKeyPair<int> pageKey;
pageKey.pageNo = 0;
return pageKey;
}
void BTreeIndex::insertToNonLeaf(PageKeyPair<int> pageKey, PageId pageNo) {
// Create internal node
Page* page;
bufMgr->readPage(file, pageNo, page);
NonLeafNodeInt* node = (NonLeafNodeInt*)page;
// Check if leaf node is full and keep track of leaf size
bool full = true;
int size = -1;
for (int i = 0; i < INTARRAYNONLEAFSIZE; i++) {
size = i;
if(node->pageNoArray[i+1] == 0){
full = false;
// size = i+1;
break;
}
}
// Find position for insertion in keyArray
int pos = -1;
for (int i = 0; i < size+1; i++) {
pos = i;
if (pageKey.key < node->keyArray[i]) {
break;
}
}
// if node is not full
if (full == false) {
// shifting keys and rids to right to make space to insert
for (int i = size; i > pos; i--) {
node->keyArray[i] = node->keyArray[i-1];
node->pageNoArray[i+1] = node->pageNoArray[i];
}
// Add pointer
node->keyArray[pos] = pageKey.key;
node->pageNoArray[pos+1] = pageKey.pageNo;
}
else {
PageKeyPair<int> pushUp = splitNonLeaf(pageNo, pageKey);
// Push up the new node to root or parent node
if(pageNo == rootPageNum){
updateRootNode(pushUp);
}else{
PageId parentId = findParentNode(pushUp, rootPageNum, node->level+1);
insertToNonLeaf(pushUp, parentId);
}
}
bufMgr->unPinPage(file, pageNo, true);
}
PageId BTreeIndex::findParentNode(PageKeyPair<int> pageKey, PageId pageNo, int level){
// Create root node
Page* page;
bufMgr->readPage(file, pageNo, page);
NonLeafNodeInt* node = (NonLeafNodeInt*)page;
// Find position to be inserted
int i = 0;
while(node->pageNoArray[i+1] != 0 && i != INTARRAYNONLEAFSIZE+1){
if(pageKey.key < node->keyArray[i]){
break;
}
i++;
}
bufMgr->unPinPage(file, pageNo, false);
if(node->level == level){
return pageNo;
}else{
return findParentNode(pageKey, node->pageNoArray[i], level);
}
}
void BTreeIndex::updateRootNode(PageKeyPair<int> pageKey){
// Get headerPage
Page *headerPage;
headerPageNum = file->getFirstPageNo();
bufMgr->readPage(file, headerPageNum, headerPage);
IndexMetaInfo *metaInfo = (IndexMetaInfo *) headerPage;
// Create a new internal node for the new root
Page* newRootPage;
PageId newRootNo;
bufMgr->allocPage(file, newRootNo, newRootPage);
NonLeafNodeInt *newRootNode = (NonLeafNodeInt *)newRootPage;
// Get Old Root Page
Page *oldRootPage;
bufMgr->readPage(file, rootPageNum, oldRootPage);
// Update Level
NonLeafNodeInt *oldRootNode = (NonLeafNodeInt *)oldRootPage;
newRootNode->level = oldRootNode->level+1;
bufMgr->unPinPage(file, rootPageNum, false);
// Initiialize new Root
newRootNode->keyArray[0] = pageKey.key;
newRootNode->pageNoArray[0] = rootPageNum;
newRootNode->pageNoArray[1] = pageKey.pageNo;
// Update header page
metaInfo->rootPageNo = newRootNo;
metaInfo->rootIsLeaf = false;
rootPageNum = newRootNo;
bufMgr->unPinPage(file, headerPageNum, true);
bufMgr->unPinPage(file, newRootNo, true);
}
PageKeyPair<int> BTreeIndex::splitNonLeaf(PageId pageNo, PageKeyPair<int> newPageKey){
// Read node to be split
Page* page;
bufMgr->readPage(file, pageNo, page);
NonLeafNodeInt* node = (NonLeafNodeInt*)page;
// Create new Node (will be inserted to the left of node)
Page* newPage;
PageId newPageNo;
bufMgr->allocPage(file, newPageNo, newPage);
NonLeafNodeInt *newNode = (NonLeafNodeInt*)newPage;
newNode->level = node->level;
int mid = INTARRAYNONLEAFSIZE/2;
// PageKey to be pushed to parent
PageKeyPair<int> pageKey;
pageKey.pageNo = newPageNo;
pageKey.key = node->keyArray[mid];
// Fill Arrays
for(int i = 0; i < INTARRAYNONLEAFSIZE; i++){
if(i < mid-1){
// Add
newNode->keyArray[i] = node->keyArray[i+mid+1];
newNode->pageNoArray[i] = node->pageNoArray[i+mid+1];
// Remove
node->keyArray[i+mid+1] = 0;
node->pageNoArray[i+mid+1] = 0;
}else if(i == mid-1){
// Add
newNode->keyArray[i] = newPageKey.key;
newNode->pageNoArray[i] = node->pageNoArray[i+mid+1];
newNode->pageNoArray[i+1] = newPageKey.pageNo;
// Remove
node->pageNoArray[i+mid+1] = 0;
node->keyArray[i+1] = 0;
}
}
// Unpin Pages
bufMgr->unPinPage(file, pageNo, true);
bufMgr->unPinPage(file, newPageNo, true);
return pageKey;
}
PageKeyPair<int> BTreeIndex::splitLeaf(PageId pageNo){
// Read node to be split
Page* page;
bufMgr->readPage(file, pageNo, page);
LeafNodeInt* node = (LeafNodeInt*)page;
// Create new Node (will be inserted to the left of node)
Page* newPage;
PageId newPageNo;
bufMgr->allocPage(file, newPageNo, newPage);
LeafNodeInt *newNode = (LeafNodeInt *) newPage;
// insert newNode into linked list
newNode->rightSibPageNo = node->rightSibPageNo;
node->rightSibPageNo = newPageNo;
// Populate new page with last half of old node records
int idx = 0;
for(int i = INTARRAYLEAFSIZE/2; i < INTARRAYLEAFSIZE; i++){
// Add key and rid to newNode
newNode->keyArray[idx] = node->keyArray[i];
newNode->ridArray[idx] = node->ridArray[i];
// Remove key and rid from node
node->keyArray[i] = 0;
node->ridArray[i].page_number = 0;
idx++;
}
// unpin old and new nodes
bufMgr->unPinPage(file, pageNo, true);
bufMgr->unPinPage(file, newPageNo, true);
// return the new pageNo and key to be inserted to parent node
PageKeyPair<int> pageKey;
pageKey.set(newPageNo, newNode->keyArray[0]);
return pageKey;
}
// -----------------------------------------------------------------------------
// BTreeIndex::startScan
// -----------------------------------------------------------------------------
void BTreeIndex::startScan(const void* lowValParm,
const Operator lowOpParm,
const void* highValParm,
const Operator highOpParm)
{
if (lowOpParm != GT && lowOpParm != GTE) {
throw BadOpcodesException();
}
if (highOpParm != LT && highOpParm != LTE) {
throw BadOpcodesException();
}
if (this->scanExecuting) {
this->endScan();
}
if (*(int*)lowValParm > *(int*)highValParm) {
throw BadScanrangeException();
}
// Initializing private variables
this->scanExecuting = true;
this->lowValInt = *(int*)lowValParm;
this->highValInt = *(int*)highValParm;
this->lowOp = lowOpParm;
this->highOp = highOpParm;
// Get headerPage
Page *headerPage;
headerPageNum = file->getFirstPageNo();
bufMgr->readPage(file, headerPageNum, headerPage);
IndexMetaInfo *metaInfo = (IndexMetaInfo *) headerPage;
bufMgr->unPinPage(file, headerPageNum, false);
if(metaInfo->rootIsLeaf){
this->currentPageNum = this->rootPageNum;
bufMgr->readPage(file, currentPageNum, currentPageData);
LeafNodeInt* root = (LeafNodeInt*)currentPageData;
for(int i = 0; i < INTARRAYLEAFSIZE; i++){
if (this->lowOp == GT && root->keyArray[i] > this->lowValInt) {
nextEntry = i;
break;
} else if (this->lowOp == GTE && root->keyArray[i] >= this->lowValInt) {
nextEntry = i;
break;
}
}
return;
}
scanHelper(rootPageNum);
}
void BTreeIndex::scanHelper(PageId pageNo) {
// Creates Internal node being checked
Page *page;
bufMgr->readPage(this->file, pageNo, page);
NonLeafNodeInt* node = (NonLeafNodeInt*)page;
bufMgr->unPinPage(file, pageNo, false);
// Find the position
int pos = 0;
for (int i = 0; i < INTARRAYNONLEAFSIZE+1; i++) {
if (node->keyArray[i] > this->lowValInt ) {
pos = i;
break;
}else if( node->pageNoArray[i+1] == 0 ){
pos = 1;
break;
}
}
if(node->level == 1){
// Leaf Node found. Set private variables
bufMgr->readPage(file, node->pageNoArray[pos], this->currentPageData);
this->currentPageNum = node->pageNoArray[pos];
LeafNodeInt *leafNode = (LeafNodeInt*)currentPageData;
// Find the the first nextEntry
for(int i = 0; i < INTARRAYLEAFSIZE; i++){
if (this->lowOp == GT && leafNode->keyArray[i] > this->lowValInt) {
nextEntry = i;
break;
} else if (this->lowOp == GTE && leafNode->keyArray[i] >= this->lowValInt) {
nextEntry = i;
break;
}
}
}else{
scanHelper(node->pageNoArray[pos]);
}
}
// -----------------------------------------------------------------------------
// BTreeIndex::scanNext
// -----------------------------------------------------------------------------
void BTreeIndex::scanNext(RecordId& outRid)
{
if (this->scanExecuting == false){
throw ScanNotInitializedException();
}
LeafNodeInt* node = (LeafNodeInt*) this->currentPageData;
// End Scan or go to next node
if(this->nextEntry >= INTARRAYLEAFSIZE || node->ridArray[nextEntry].page_number == 0){
if (node->rightSibPageNo == 0) {
throw IndexScanCompletedException(); // if leaf is over
} else {
bufMgr->unPinPage(this->file, this->currentPageNum, false);
this->nextEntry = 0; //reinitialize nextentry
this->currentPageNum = node->rightSibPageNo;
bufMgr->readPage(this->file, this->currentPageNum, this->currentPageData);
node = (LeafNodeInt*) this->currentPageData;
}
}
// Check if rid is found or if the scan has been completed
if (this->highOp == LT && node->keyArray[this->nextEntry] < this->highValInt) {
outRid = node->ridArray[nextEntry];
} else if (this->highOp == LTE && node->keyArray[this->nextEntry] <= this->highValInt) {
outRid = node->ridArray[nextEntry];
} else {throw IndexScanCompletedException();}
this->nextEntry += 1; //update to next
return;
}
// -----------------------------------------------------------------------------
// BTreeIndex::endScan
// -----------------------------------------------------------------------------
//
void BTreeIndex::endScan()
{
if (!this->scanExecuting){ // if no scan started, throw exception
throw ScanNotInitializedException();
}
// unpin pages if pinned
bufMgr->unPinPage(this->file, this->currentPageNum, false);
scanExecuting = false; // signifies scan complete
return;
}
// -----------------------------------------------------------------------------
// Printing Methods for debugging purposes
// -----------------------------------------------------------------------------
void BTreeIndex::printTree(PageId pageNo, bool leaf){
Page* headerPage;
bufMgr->readPage(file, headerPageNum, headerPage);
IndexMetaInfo* metaInfo = (IndexMetaInfo*)headerPage;
if(metaInfo->rootIsLeaf){
printNode(pageNo);
bufMgr->unPinPage(file, headerPageNum, false);
}else{
bufMgr->unPinPage(file, headerPageNum, false);
Page* page;
bufMgr->readPage(file, pageNo, page);
NonLeafNodeInt* node = (NonLeafNodeInt*)page;
int size = 0;
for (int i = 0; i < INTARRAYNONLEAFSIZE+1; i++) {
size = i;
if(node->pageNoArray[i+1] == 0){
size = i;
break;
}
}
for (int i = 0; i < size+1; i++) {
if(node->level == 1){
std::cout << "." << i << "." << node->pageNoArray[i] << "." << std::endl;
if(i == 0){
printNode(node->pageNoArray[i]);
}else{
std::cout << "[" << i << "]: " << node->keyArray[i-1] << std::endl;
printNode(node->pageNoArray[i]);
}
}else{
if(node->pageNoArray[i] == 0){
break;
}else if(i == 0){
std::cout << pageNo << " Level: " << node->level << std::endl;
printTree(node->pageNoArray[i], false);
}else{
std::cout << pageNo << " Level: " << node->level << " - Key: " << node->keyArray[i-1] << std::endl;
printTree(node->pageNoArray[i], false);
}
}
}
bufMgr->unPinPage(file, pageNo, false);
}
}
void BTreeIndex::printNode(PageId pageNo){
Page* page;
bufMgr->readPage(this->file, pageNo, page);
LeafNodeInt* node = (LeafNodeInt*)page;
int size = -1; // if not, keep track of node's size
for (int i = 0; i < INTARRAYLEAFSIZE+1; i++) {
if(node->ridArray[i].page_number == 0){
size = i;
break;
}
}
std::cout << " Printing Node " << size << std::endl;
for (int i = 0; i < size+1; i++) {
std::cout << " [" << i << "]: " << node->keyArray[i] << "." << node->ridArray[i].page_number << std::endl;
}
bufMgr->unPinPage(file, pageNo, false);
}
}
| 27.484728 | 127 | 0.636741 | [
"object"
] |
c30597b931414bc17a586971af46e2308e2587cd | 4,918 | cpp | C++ | VGP332/01_HelloPathFindingApp/GameState.cpp | amyrhzhao/CooEngine | 8d467cc53fd8fe3806d726cfe4d7482ad0aca06a | [
"MIT"
] | 3 | 2020-07-23T02:50:11.000Z | 2020-10-20T14:49:40.000Z | VGP332/01_HelloPathFindingApp/GameState.cpp | amyrhzhao/CooEngine | 8d467cc53fd8fe3806d726cfe4d7482ad0aca06a | [
"MIT"
] | null | null | null | VGP332/01_HelloPathFindingApp/GameState.cpp | amyrhzhao/CooEngine | 8d467cc53fd8fe3806d726cfe4d7482ad0aca06a | [
"MIT"
] | null | null | null | #include "GameState.h"
TileMap map;
struct GetGCost
{
float operator()(AI::GraphSearch::Context context, size_t parentIndex, size_t nodeIndex)
{
if (parentIndex == InvalidNode)
{
return 0.0f;
}
int columns = map.GetColumns();
size_t parentColumn = parentIndex % columns;
size_t parentRow = parentIndex / columns;
size_t nodeColumn = nodeIndex % columns;
size_t nodeRow = nodeIndex / columns;
float g = context.g[parentIndex] + ((parentColumn != nodeColumn && parentRow != nodeRow) ? 1.414f : 1.0f);
return g;
}
};
struct GetHCost
{
float operator()(AI::GraphSearch::Context& context, size_t nodeIndex)
{
int columns = map.GetColumns();
size_t currColumn = nodeIndex % columns;
size_t currRow = nodeIndex / columns;
size_t nodeColumn = context.end % columns;
size_t nodeRow = context.end / columns;
return sqrtf(static_cast<float>(((nodeColumn - currColumn) * (nodeColumn - currColumn)) + ((nodeRow - currRow) * (nodeRow - currRow))));
}
};
struct CanOpenNode1
{
bool operator() (GraphSearch::Context& context, size_t n)
{
if (context.open[n])
{
return false;
}
if (map.IsWall(n))
{
return false;
}
return true;
//if (!map.IsWall(n) && !context.open[n])
//{
// return true;
//}
//return false;
}
};
struct CanOpenNode2
{
bool operator() (GraphSearch::Context& context, size_t n)
{
if (!map.IsWall(n) && !context.closed[n])
{
return true;
}
return false;
}
};
void GameState::Initialize()
{
mCamera.SetPosition({ 0.0f,0.0f,-10.0f });
mCamera.SetDirection({ 0.0f,0.0f,1.0f });
map.Load();
BuildGraph();
start = 0;
//end = 45;
end = (map.GetColumns() * map.GetColumns()) - 1;
}
void GameState::Terminate()
{
map.Unload();
}
void GameState::Update(float deltaTime)
{
fps = 1.0f / deltaTime;
switch (mCurrMode)
{
case Mode::TileMapEdit:
{
map.Update(deltaTime);
break;
}
case Mode::PathFinding:
{
CheckInput();
break;
}
}
}
void GameState::Render()
{
map.Render();
if (mShowGraph)
{
using std::placeholders::_1;
std::function<bool(size_t)> func = std::bind(&TileMap::IsWall, &map, _1);
RenderGraph(mGraph, func);
}
if (mCurrMode == Mode::PathFinding)
{
if (mShowSearch)
{
RenderSearch(mGraph, context);
}
RenderGoal();
}
Coo::Graphics::SimpleDraw::Render(mCamera);
}
void GameState::DebugUI()
{
ImGui::Begin("Path Finding", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::Text("FPS: %f", fps);
ImGui::Text("Search Time: %f", lastSearchTime);
ImGui::Text("Mode");
if (ImGui::RadioButton("Tile Map Editor", mCurrMode == Mode::TileMapEdit))
mCurrMode = Mode::TileMapEdit;
if (ImGui::RadioButton("Path Finding", mCurrMode == Mode::PathFinding))
mCurrMode = Mode::PathFinding;
ImGui::Checkbox("Show Graph", &mShowGraph);
switch (mCurrMode)
{
case Mode::TileMapEdit:
{
map.DebugUI();
break;
}
case Mode::PathFinding:
{
ImGui::Checkbox("Show Search", &mShowSearch);
ImGui::Text("Path Finding");
if (ImGui::RadioButton("BFS", mCurrSearchType == SearchType::BFS))
mCurrSearchType = SearchType::BFS;
if (ImGui::RadioButton("DFS", mCurrSearchType == SearchType::DFS))
mCurrSearchType = SearchType::DFS;
if (ImGui::RadioButton("Dijkstra", mCurrSearchType == SearchType::Dijkstra))
mCurrSearchType = SearchType::Dijkstra;
if (ImGui::RadioButton("A*", mCurrSearchType == SearchType::AStar))
mCurrSearchType = SearchType::AStar;
if (ImGui::Button("Execute"))
{
context.Init(mGraph.GetSize());
context.Reset();
auto startTime = std::chrono::high_resolution_clock::now();
ExecuteSearch<CanOpenNode1,CanOpenNode2, GetGCost, GetHCost>(mGraph, context, start, end, mCurrSearchType);
auto finishTime = std::chrono::high_resolution_clock::now();
lastSearchTime = std::chrono::duration_cast<std::chrono::milliseconds>(finishTime - startTime).count() / 1000.0f;
}
break;
}
}
ImGui::End();
}
void GameState::BuildGraph()
{
BuildGridBasedGraph(mGraph, map);
}
bool GameState::IsWall(size_t index)
{
return map.IsWall(index);
}
void GameState::CheckInput()
{
if (Coo::Input::InputSystem::Get()->IsMouseDown(Coo::Input::MouseButton::LBUTTON))
{
auto index = map.MousePosToIndex();
if (index >= 0)
start = index;
}
if (Coo::Input::InputSystem::Get()->IsMouseDown(Coo::Input::MouseButton::RBUTTON))
{
auto index = map.MousePosToIndex();
if (index >= 0)
end = index;
}
}
void GameState::RenderGoal()
{
auto max = mGraph.GetSize();
if (start < max)
Coo::Graphics::SimpleDraw::AddScreenCircle(mGraph.GetNode(start).position, 9.0f, Coo::Graphics::Colors::Violet);
if (end < max)
Coo::Graphics::SimpleDraw::AddScreenCircle(mGraph.GetNode(end).position, 9.0f, Coo::Graphics::Colors::Violet);
}
| 24.107843 | 139 | 0.649858 | [
"render"
] |
c30aa8bfe49e38189dce97aaeb04c4f512cdc538 | 3,758 | cpp | C++ | src/UnitTests/WOSTest2.cpp | fsaintjacques/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | 14 | 2016-07-11T04:08:09.000Z | 2022-03-11T05:56:59.000Z | src/UnitTests/WOSTest2.cpp | ibrarahmad/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | null | null | null | src/UnitTests/WOSTest2.cpp | ibrarahmad/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | 13 | 2016-06-01T10:41:15.000Z | 2022-01-06T09:01:15.000Z | /* Copyright (c) 2005, Regents of Massachusetts Institute of Technology,
* Brandeis University, Brown University, and University of Massachusetts
* Boston. 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 Massachusetts Institute of Technology,
* Brandeis University, Brown University, or University of
* Massachusetts Boston 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.
*/
/**
* WOSTest:
*
*/
#include "WOSTest.h"
WOSTest2::WOSTest2() {
}
WOSTest2::~WOSTest2() {
}
/* args is not used here */
bool WOSTest2::run(Globals* g, const vector<string>& args)
{
//Log::writeToLog("WOSTest2", 0, "WOSTest2 is starting...");
bool success=true;
// that's a bad idea if you're trying to teach WOS to recover from
// data on disk...
//system("rm Segment1.wos.*");
// WOS with 5 int columns
ROSWOSSegment *rwseg = new ROSWOSSegment( "Segment1", 5 );
if ( !rwseg->isEmpty() )
return true;
char *tuple = new char[ 6 * sizeof(int) ]; // 5 columns + timestamp
for (int i = 0; i < 17; i ++ )
{
memcpy( tuple+sizeof(int), &i, sizeof(int)); // sort key, col 1, 4 bytes
int ii = (i * 5) % 41; // to make storage key different
memcpy( tuple, &ii, sizeof(int) ); // storage key.
//cout << " Append storage key " << ii << " SortKey " << i << endl;
rwseg->appendTuple( tuple );
}
char *a = NULL;
unsigned int storage_key = 0, sort_key = 0;
// Please not that the boolean says that the iterator should be set
// to that value. Following the first call, all calls should specify false.
//
// 0 returns the pointer to the storage key part of the tuple. The tuple
// is stored continguously [SK][Field1][Field2]...etc.
a = rwseg->getNextFieldByStorageKey( 0, 0, true, NULL );
memcpy( &storage_key, a, sizeof(int ) );
memcpy( &sort_key, a+sizeof(int), sizeof(int ) );
cout << " first Tuple: storage key " << storage_key << " sort key " << sort_key << endl;
while ( ( a = rwseg->getNextFieldByStorageKey( 0, 0, false, NULL )) != NULL )
{
memcpy( &storage_key, a, sizeof(int ) );
memcpy( &sort_key, a+sizeof(int), sizeof(int ) );
cout << " Tuple: storage key " << storage_key << " sort key " << sort_key << endl;
}
cout << " DONE " << endl;
delete rwseg;
return success;
}
| 38.742268 | 90 | 0.675625 | [
"vector"
] |
c30e8b4f84145527781698f2daae0a05d75ded45 | 1,514 | cpp | C++ | LeetCode/Problems/Algorithms/#698_PartitionToKEqualSumSubsets_sol5_memoization_with_vector_O(N2^N)_time_O(2^N)_extra_space_4ms_15MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#698_PartitionToKEqualSumSubsets_sol5_memoization_with_vector_O(N2^N)_time_O(2^N)_extra_space_4ms_15MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#698_PartitionToKEqualSumSubsets_sol5_memoization_with_vector_O(N2^N)_time_O(2^N)_extra_space_4ms_15MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
private:
bool solve(int k, int mask, int sum, const int& PARTITION_SUM, vector<int>& nums, vector<int>& memo){
if(memo[mask] != -1){
return memo[mask];
}
if(k == 1){
memo[mask] = true;
return true;
}
for(int bit = 0; bit < (int)nums.size(); ++bit){
if(((mask >> bit) & 1) && (sum + nums[bit] <= PARTITION_SUM)){
int nextSum = (sum + nums[bit]) % PARTITION_SUM;
int nextMask = mask - (1 << bit);
int nextK = k - (int)(nextSum == 0);
if(solve(nextK, nextMask, nextSum, PARTITION_SUM, nums, memo)){
memo[mask] = true;
return true;
}
}
}
memo[mask] = false;
return false;
}
public:
bool canPartitionKSubsets(vector<int>& nums, int k) {
const int N = nums.size();
const int FULL_MASK = (1 << N) - 1;
const int TOTAL_SUM = accumulate(nums.begin(), nums.end(), 0);
const int PARTITION_SUM = TOTAL_SUM / k;
const int MAX_NUM = *max_element(nums.begin(), nums.end());
if(PARTITION_SUM * k != TOTAL_SUM || PARTITION_SUM < MAX_NUM){
return false;
}
vector<int> memo(FULL_MASK + 1, -1);
bool isPossible = solve(k, FULL_MASK, 0, PARTITION_SUM, nums, memo);
return isPossible;
}
}; | 35.209302 | 106 | 0.47424 | [
"vector"
] |
c31278f2b1c0d3cd98303eb65742f60f3201e60c | 3,752 | cc | C++ | topcoder/671/BearDarts.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | topcoder/671/BearDarts.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | topcoder/671/BearDarts.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
using vi = vector<int>; using vvi = vector<vi>;
using ii = pair<int,int>; using vii = vector<ii>;
using l = long long; using vl = vector<l>; using vvl = vector<vl>;
using lu = unsigned long long; using ll = pair<l, l>;
using vb = vector<bool>; using vvb = vector<vb>;
using vd = vector<double>; using vvd = vector<vd>;
const int INF = numeric_limits<int>::max();
const double EPS = 1e-10;
const l e5 = 100000, e6 = 1000000, e7 = 10000000, e9 = 1000000000;
class BearDarts {
public:
long long count(vector <int> w) {
l n = w.size();
unordered_map<l, set<ll>> M;
for (l i = 0; i < n; i++) {
for (l j = i + 2; j < n; j++) {
l s = w[i];
s *= w[j];
M[s].insert(make_pair(min(w[i], w[j]), max(w[i], w[j])));
}
}
unordered_map<l, l> RI;
for (l a : w) {
if (RI.count(a)) continue;
RI[a] = RI.size() - 1;
}
vvl A(RI.size(), vl(n + 1));
for (l i = 0; i < n; i++) A[RI[w[i]]][i + 1]++;
for (l i = 0; i < A.size(); i++) {
for (l j = 1; j < n; j++) {
A[i][j] += A[i][j - 1];
}
}
l answer = 0;
for (l i = 0; i < n; i++) {
for (l j = i + 2; j < n; j++) {
l s = w[i];
s *= w[j];
for (auto k : M[s]) {
l x = RI[k.first], y = RI[k.second];
answer += (A[x][i] * (A[y][j] - A[y][i + 1]));
if (x != y) {
answer += (A[y][i] * (A[x][j] - A[x][i + 1]));
}
}
}
}
return answer;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {6,8,4,3,6}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 2LL; verify_case(0, Arg1, count(Arg0)); }
void test_case_1() { int Arr0[] = {3,4,12,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 0LL; verify_case(1, Arg1, count(Arg0)); }
void test_case_2() { int Arr0[] = {42,1000000,1000000,42,1000000,1000000}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 3LL; verify_case(2, Arg1, count(Arg0)); }
void test_case_3() { int Arr0[] = {1,1,1,1,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 5LL; verify_case(3, Arg1, count(Arg0)); }
void test_case_4() { int Arr0[] = {1,2,3,4,5,6,5,4,3,2,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 22LL; verify_case(4, Arg1, count(Arg0)); }
void test_case_5() { int Arr0[] = {33554432, 33554432, 67108864, 134217728}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 0LL; verify_case(5, Arg1, count(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
BearDarts ___test;
___test.run_test(-1);
}
// END CUT HERE
| 48.102564 | 320 | 0.526386 | [
"vector"
] |
c315e34dd66afcd6b060ce9fccbbd23503ffdab1 | 574 | cc | C++ | src/openvslam/initialize/base.cc | bumplzz69/openvslam | 6d03050a0f04323adfdf3fcf3693b180abc4553f | [
"BSD-2-Clause",
"MIT"
] | 1 | 2021-06-10T02:16:52.000Z | 2021-06-10T02:16:52.000Z | src/openvslam/initialize/base.cc | PetWorm/openvslam | d746173867f6078007f246b4f1e681a317e6c377 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | src/openvslam/initialize/base.cc | PetWorm/openvslam | d746173867f6078007f246b4f1e681a317e6c377 | [
"BSD-2-Clause",
"MIT"
] | 1 | 2019-10-24T08:42:22.000Z | 2019-10-24T08:42:22.000Z | #include "openvslam/initialize/base.h"
namespace openvslam {
namespace initialize {
base::base(const unsigned int max_num_iters)
: max_num_iters_(max_num_iters) {}
Mat33_t base::get_rotation_ref_to_cur() const {
return rot_ref_to_cur_;
}
Vec3_t base::get_translation_ref_to_cur() const {
return trans_ref_to_cur_;
}
eigen_alloc_vector<Vec3_t> base::get_triangulated_pts() const {
return triangulated_pts_;
}
std::vector<bool> base::get_triangulated_flags() const {
return is_triangulated_;
}
} // namespace initialize
} // namespace openvslam
| 21.259259 | 63 | 0.75784 | [
"vector"
] |
c3280971fed01b4bb997544b73fd3d0d05b52ecc | 8,437 | hpp | C++ | emulation/hel/include/joystick.hpp | HiceS/synthesis | 9dbc6812cd296a04c35d45854e821f76c5890b56 | [
"Apache-2.0"
] | 136 | 2016-07-11T23:31:33.000Z | 2022-03-29T21:14:23.000Z | emulation/hel/include/joystick.hpp | hartisticexpressions/synthesis | 8267cf4c85b5d4236fefeab404afeb6090677f17 | [
"Apache-2.0"
] | 370 | 2016-08-16T22:33:02.000Z | 2022-03-23T23:57:18.000Z | emulation/hel/include/joystick.hpp | hartisticexpressions/synthesis | 8267cf4c85b5d4236fefeab404afeb6090677f17 | [
"Apache-2.0"
] | 62 | 2016-07-28T17:54:17.000Z | 2021-07-15T13:15:59.000Z | #ifndef _JOYSTICK_HPP_
#define _JOYSTICK_HPP_
#include <cstdint>
#include <string>
#include "bounds_checked_array.hpp"
namespace hel{
/**
* \brief A data container for joystick data
* Holds data surrounding joystick inputs and outputs and a description
*/
struct Joystick{
/**
* \brief The maximum number of joysticks supported by WPILib
*/
static constexpr uint8_t MAX_JOYSTICK_COUNT = 6; //kJoystickPorts from frc::DriverStation
/**
* \brief The maximum number of joystick axes supported by HAL
*/
static constexpr uint8_t MAX_AXIS_COUNT = 12; //HAL_kMaxJoystickAxes;
/**
* \brief The maximum number of joystick POVs supported by HAL
*/
static constexpr uint8_t MAX_POV_COUNT = 12; //HAL_kMaxJoystickPOVs;
/**
* \brief The Maximum size of the joystick name string in characters
*/
static constexpr unsigned MAX_JOYSTICK_NAME_SIZE = 256;
private:
/**
* \brief Whether the joystick is an XBox controller or not
*/
bool is_xbox;
/**
* \brief The joystick type
*/
uint8_t type;
/**
* \brief The name of the joystick
*/
std::string name;
/**
* \brief A bit mask of joystick button states
*/
uint32_t buttons;
/**
* \brief The number of buttons on the joystick
*/
uint8_t button_count;
/**
* \brief Array containing joystick axis states
* The states of each axis stored as a byte representing percent offset from rest in either direction
*/
BoundsCheckedArray<int8_t, MAX_AXIS_COUNT> axes;
/**
* \brief The number of axes on the joystick
*/
uint8_t axis_count;
/**
* \brief Array containing joystick axis types
*/
BoundsCheckedArray<uint8_t, MAX_AXIS_COUNT> axis_types; //TODO It is unclear how to interpret the bytes representing axis type
/**
* \brief Array containing joystick POV (aka D-pad) states
* The states of each POV stored as 16-bit integers representing the angle in degrees that is pressed, -1 if none are pressed
*/
BoundsCheckedArray<int16_t, MAX_POV_COUNT> povs;
/**
* \brief The number of POVs on the joystick
*/
uint8_t pov_count;
/**
* \brief A 32-bit mask representing HID outputs
*/
uint32_t outputs;
/**
* \brief A 16-bit mapped percent of output to the left rumble
*/
uint16_t left_rumble;
/**
* \brief A 16-bit mapped percent of output to the right rumble
*/
uint16_t right_rumble;
public:
/**
* \brief Get if the joystick is an XBox controller
* \return True if the joystick is an XBox controller
*/
bool getIsXBox()const noexcept;
/**
* \brief Set if the joystick is an XBox controller
* \param xbox True to set the joystick as an Xbox controller
*/
void setIsXBox(bool)noexcept;
/**
* \brief Get the type of joystick
* \return An integer representing the type of joystick
*/
uint8_t getType()const noexcept;
/**
* \brief Set the type of joystick
* \param t The type to set the joystick type to
*/
void setType(uint8_t)noexcept;
/**
* \brief Get the name of the joystick
* \return The name of the joystick
*/
std::string getName()const noexcept;
/**
* \brief Set the name of the joystick
* \param n The name to set for the joystick
*/
void setName(std::string)noexcept;
/**
* \brief Get the button states of the joystick
* \return An integer bitmask representing the states of the joystick buttons
*/
uint32_t getButtons()const noexcept;
/**
* \brief Set the button states of the joystick
* \param b The integer bitmask of button states to set for the joystick
*/
void setButtons(uint32_t)noexcept;
/**
* \brief Get the number of buttons on the joystick
* \return The number of buttons on the joystick
*/
uint8_t getButtonCount()const noexcept;
/**
* \brief Set the number of buttons on the joystick
* \param b_count The number of buttons to set for the joystick
*/
void setButtonCount(uint8_t)noexcept;
/**
* \brief Get the states of the joystick axes
* \return A BoundsCheckedArray of joystick axes states
*/
BoundsCheckedArray<int8_t, MAX_AXIS_COUNT> getAxes()const;
/**
* \brief Set the states of the joystick axes
* \param a The states of axes to set for the joystick
*/
void setAxes(BoundsCheckedArray<int8_t, MAX_AXIS_COUNT>);
/**
* \brief Get the number of axes on the joystick
* \return The number of axes on the joystick
*/
uint8_t getAxisCount()const noexcept;
/**
* \brief Set the number of axes on the joystick
* \param a_count The number of axes to set for the joystick
*/
void setAxisCount(uint8_t)noexcept;
/**
* \brief Get the axis types of the axes on the joystick
* \return A BoundsCheckedArray of integers representing the axis types on the joystick
*/
BoundsCheckedArray<uint8_t, MAX_AXIS_COUNT> getAxisTypes()const;
/**
* \brief Set the axis types of the axes on the joystick
* \param a_types The axis types to set for the joystick
*/
void setAxisTypes(BoundsCheckedArray<uint8_t, MAX_AXIS_COUNT>);
/**
* \brief Get the states of the POVs on the joystick
* \return The states of the POVs on the joystick
*/
BoundsCheckedArray<int16_t, MAX_POV_COUNT> getPOVs()const;
/**
* \brief Set the states of the POVs on the joystick
* \param p The states of the POVs to set for the joystick
*/
void setPOVs(BoundsCheckedArray<int16_t, MAX_POV_COUNT>);
/**
* \brief Get the number of POVs on the joystick
* \return The number of POVs on the joystick
*/
uint8_t getPOVCount()const noexcept;
/**
* \brief Set the number of POVs on the joystick
* \param p_count The number of POVs to set for the joystick
*/
void setPOVCount(uint8_t)noexcept;
/**
* \brief Get the states of the joystick outputs
* \return An integer bitmask of the joystick outputs
*/
uint32_t getOutputs()const noexcept;
/**
* \brief Set the states of the joystick outputs
* \param out An integer bitmask of outputs to set for the joystick
*/
void setOutputs(uint32_t)noexcept;
/**
* \brief Get the joystick's left rumble state
* \return The joystick's left rumble state
*/
uint16_t getLeftRumble()const noexcept;
/**
* \brief Set the joystick's left rumble state
* \param rumble The state of left rumble to set for the joystick
*/
void setLeftRumble(uint16_t)noexcept;
/**
* \brief Get the joystick's right rumble state
* \return The joystick's right rumble state
*/
uint16_t getRightRumble()const noexcept;
/**
* \brief Set the joystick's right rumble state
* \param rumble The state of right rumble to set for the joystick
*/
void setRightRumble(uint16_t)noexcept;
/**
* \brief Format the Joystick data as a string
* \return The Joystick data in string format
*/
std::string toString()const;
/**
* Constructor for a Joystick
*/
Joystick()noexcept;
/**
* Constructor for Joystick
* \param source A Joystick object to copy
*/
Joystick(const Joystick&)noexcept;
};
}
#endif
| 25.722561 | 134 | 0.576864 | [
"object"
] |
c3339a4eeec06688ff1dccf3d384e14b9b10cb6a | 26,357 | cpp | C++ | llightscene.cpp | Calinou/godot-llightmap | 7815dfb84a6299a4775faf3b306492961c45ed8c | [
"MIT"
] | 49 | 2020-07-16T10:56:22.000Z | 2022-03-07T06:20:14.000Z | llightscene.cpp | Calinou/godot-llightmap | 7815dfb84a6299a4775faf3b306492961c45ed8c | [
"MIT"
] | 3 | 2020-08-01T22:38:52.000Z | 2022-03-08T20:58:13.000Z | llightscene.cpp | Calinou/godot-llightmap | 7815dfb84a6299a4775faf3b306492961c45ed8c | [
"MIT"
] | 3 | 2020-07-24T01:11:17.000Z | 2022-03-07T01:07:03.000Z | #include "llightscene.h"
#include "llightmapper_base.h"
#include "llighttests_simd.h"
#include "llighttypes.h"
#include "scene/3d/mesh_instance.h"
//#define LLIGHTSCENE_VERBOSE
//#define LLIGHTSCENE_TRACE_VERBOSE
using namespace LM;
bool LightScene::TestVoxelHits(const Ray &ray, const PackedRay &pray, const Voxel &voxel, float max_dist, bool bCullBackFaces) {
int quads = voxel.m_PackedTriangles.size();
if (!bCullBackFaces) {
for (int q = 0; q < quads; q++) {
// get pointers to 4 triangles
const PackedTriangles &ptris = voxel.m_PackedTriangles[q];
if (pray.IntersectTest(ptris, max_dist))
return true;
}
} else {
/*
// test backface culling
Tri t;
t.pos[0] = Vector3(0, 0, 0);
t.pos[2] = Vector3(1, 1, 0);
t.pos[1] = Vector3(1, 0, 0);
t.ConvertToEdgeForm();
PackedTriangles pttest;
pttest.Create();
pttest.Set(0, t);
pttest.Set(1, t);
pttest.Set(2, t);
pttest.Set(3, t);
pttest.Finalize(4);
Ray rtest;
rtest.o = Vector3(0.5, 0.4, -1);
rtest.d = Vector3(0, 0, 1);
PackedRay prtest;
prtest.Create(rtest);
prtest.IntersectTest_CullBackFaces(pttest, 10);
*/
for (int q = 0; q < quads; q++) {
// get pointers to 4 triangles
const PackedTriangles &ptris = voxel.m_PackedTriangles[q];
if (pray.IntersectTest_CullBackFaces(ptris, max_dist))
return true;
}
}
return false;
}
void LightScene::ProcessVoxelHits(const Ray &ray, const PackedRay &pray, const Voxel &voxel, float &r_nearest_t, int &r_nearest_tri) //, int ignore_triangle_id_p1)
{
//#define LLIGHTMAPPED_DEBUG_COMPARE_SIMD
// float record_nearest_t = r_nearest_t;
// int record_nearest_tri = r_nearest_tri;
//#ifdef LLIGHTMAPPER_USE_SIMD
if (m_bUseSIMD) {
//LightTests_SIMD simd;
// groups of 4
int quads = voxel.m_PackedTriangles.size();
// special case of ignore triangles being set
// int ignore_quad = -1;
// int ignore_quad_index;
// if (ignore_triangle_id_p1)
// {
// int test_tri_id = ignore_triangle_id_p1-1;
// for (int n=0; n<voxel.m_iNumTriangles; n++)
// {
// if (voxel.m_TriIDs[n] == test_tri_id)
// {
// // found
// ignore_quad = n / 4;
// ignore_quad_index = n % 4;
// }
// }
// }
for (int q = 0; q < quads; q++) {
// get pointers to 4 triangles
const PackedTriangles &ptris = voxel.m_PackedTriangles[q];
// we need to deal with the special case of the ignore_triangle being set. This will normally only occur on the first voxel.
int winner;
// if there is no ignore triangle, or the quad is not the one with the ignore triangle, do the fast path
// if ((!ignore_triangle_id_p1) || (q != ignore_quad))
// {
winner = pray.Intersect(ptris, r_nearest_t);
// }
// else
// {
// // slow path
// PackedTriangles pcopy = ptris;
// pcopy.MakeInactive(ignore_quad_index);
// winner = pray.Intersect(pcopy, r_nearest_t);
// }
#ifdef LLIGHTSCENE_TRACE_VERBOSE
String sz = "\ttesting tris ";
for (int t = 0; t < 4; t++) {
int test_tri = (q * 4) + t;
if (test_tri < voxel.m_TriIDs.size()) {
sz += itos(voxel.m_TriIDs[(q * 4) + t]);
sz += ", ";
}
}
print_line(sz);
#endif
if (winner != 0)
//if (pray.Intersect(ptris, r_nearest_t, winner))
{
winner--;
int winner_tri_index = (q * 4) + winner;
//int winner_tri = m_Tracer.m_TriHits[winner_tri_index];
int winner_tri = voxel.m_TriIDs[winner_tri_index];
#ifdef LLIGHTSCENE_TRACE_VERBOSE
const AABB &tri_bb = m_TriPos_aabbs[winner_tri];
print_line("\t\tWINNER tri : " + itos(winner_tri) + " at dist " + String(Variant(r_nearest_t)) + " aabb " + String(tri_bb));
#endif
/*
// test assert condition
if (winner_tri != ref_winner_tri_id)
{
// do again to debug
float test_nearest_t = FLT_MAX;
simd.TestIntersect4(pTris, ray, test_nearest_t, winner);
// repeat reference test
int ref_start = nStart-4;
for (int n=0; n<4; n++)
{
unsigned int tri_id = m_Tracer.m_TriHits[ref_start++];
float t = 0.0f;
ray.TestIntersect_EdgeForm(m_Tris_EdgeForm[tri_id], t);
}
}
*/
r_nearest_tri = winner_tri;
}
// assert (r_nearest_t <= (nearest_ref_dist+0.001f));
}
// print result
// if (r_nearest_tri != -1)
// print_line("SIMD\tr_nearest_tri " + itos (r_nearest_tri) + " dist " + String(Variant(r_nearest_t)));
return;
} // if use SIMD
//#endif
// trace after every voxel
int nHits = m_Tracer.m_TriHits.size();
int nStart = 0;
// just for debugging do whole test again
// int simd_nearest_tri = r_nearest_tri;
// r_nearest_t = record_nearest_t;
// r_nearest_tri = record_nearest_tri;
// leftovers
for (int n = nStart; n < nHits; n++) {
unsigned int tri_id = m_Tracer.m_TriHits[n];
float t = 0.0f;
// if (ray.TestIntersect(m_Tris[tri_id], t))
if (ray.TestIntersect_EdgeForm(m_Tris_EdgeForm[tri_id], t)) {
if (t < r_nearest_t) {
r_nearest_t = t;
r_nearest_tri = tri_id;
}
}
}
// print result
// if (r_nearest_tri != -1)
// print_line("REF\tr_nearest_tri " + itos (r_nearest_tri) + " dist " + String(Variant(r_nearest_t)));
// assert (r_nearest_tri == simd_nearest_tri);
}
void LightScene::ProcessVoxelHits_Old(const Ray &ray, const Voxel &voxel, float &r_nearest_t, int &r_nearest_tri) {
// trace after every voxel
int nHits = m_Tracer.m_TriHits.size();
int nStart = 0;
//#define LLIGHTMAPPED_DEBUG_COMPARE_SIMD
#ifdef LLIGHTMAPPER_USE_SIMD
if (m_bUseSIMD) {
LightTests_SIMD simd;
// groups of 4
int quads = nHits / 4;
for (int q = 0; q < quads; q++) {
// get pointers to 4 triangles
const Tri *pTris[4];
#if LLIGHTMAPPED_DEBUG_COMPARE_SIMD
float nearest_ref_dist = FLT_MAX;
int ref_winner_tri_id = -1;
int ref_winner_n = -1;
#endif
for (int n = 0; n < 4; n++) {
unsigned int tri_id = m_Tracer.m_TriHits[nStart++];
#if LLIGHTMAPPED_DEBUG_COMPARE_SIMD
float t = 0.0f;
print_line("ref input triangle" + itos(n));
const Tri &ref_input_tri = m_Tris_EdgeForm[tri_id];
String sz = "\t";
for (int abc = 0; abc < 3; abc++) {
sz += "(" + String(Variant(ref_input_tri.pos[abc])) + ") ";
}
print_line(sz);
if (ray.TestIntersect_EdgeForm(ref_input_tri, t)) {
if (t < nearest_ref_dist) {
nearest_ref_dist = t;
ref_winner_tri_id = tri_id;
ref_winner_n = n;
}
}
#endif
pTris[n] = &m_Tris_EdgeForm[tri_id];
}
// compare with old
// test 4
// int test[4];
int winner;
if (simd.TestIntersect4(pTris, ray, r_nearest_t, winner)) {
int winner_tri_index = nStart - 4 + winner;
int winner_tri = m_Tracer.m_TriHits[winner_tri_index];
/*
// test assert condition
if (winner_tri != ref_winner_tri_id)
{
// do again to debug
float test_nearest_t = FLT_MAX;
simd.TestIntersect4(pTris, ray, test_nearest_t, winner);
// repeat reference test
int ref_start = nStart-4;
for (int n=0; n<4; n++)
{
unsigned int tri_id = m_Tracer.m_TriHits[ref_start++];
float t = 0.0f;
ray.TestIntersect_EdgeForm(m_Tris_EdgeForm[tri_id], t);
}
}
*/
r_nearest_tri = winner_tri;
}
// assert (r_nearest_t <= (nearest_ref_dist+0.001f));
}
} // if use SIMD
#endif
// leftovers
for (int n = nStart; n < nHits; n++) {
unsigned int tri_id = m_Tracer.m_TriHits[n];
float t = 0.0f;
// if (ray.TestIntersect(m_Tris[tri_id], t))
if (ray.TestIntersect_EdgeForm(m_Tris_EdgeForm[tri_id], t)) {
if (t < r_nearest_t) {
r_nearest_t = t;
r_nearest_tri = tri_id;
}
}
}
}
bool LightScene::TestIntersect_Line(const Vector3 &a, const Vector3 &b, bool bCullBackFaces) {
Ray r;
r.o = a;
r.d = b - a;
float dist = r.d.length();
if (dist > 0.0f) {
// normalize
r.d /= dist;
bool res = TestIntersect_Ray(r, dist);
/*
// double check
Vector3 bary;
float t;
int tri = FindIntersect_Ray(r, bary, t);
if (res)
{
assert (tri != -1);
assert (t <= dist);
}
else
{
if (tri != -1)
{
assert (t > dist);
}
}
*/
return res;
}
// no distance, no intersection
return false;
}
bool LightScene::TestIntersect_Ray(const Ray &ray, float max_dist, bool bCullBackFaces) {
Vec3i voxel_range;
m_Tracer.GetDistanceInVoxels(max_dist, voxel_range);
return TestIntersect_Ray(ray, max_dist, voxel_range, bCullBackFaces);
}
bool LightScene::TestIntersect_Ray(const Ray &ray, float max_dist, const Vec3i &voxel_range, bool bCullBackFaces) {
Ray voxel_ray;
Vec3i ptVoxel;
// prepare voxel trace
if (!m_Tracer.RayTrace_Start(ray, voxel_ray, ptVoxel))
return false;
//bool bFirstHit = false;
// Vec3i ptVoxelFirstHit;
// if we have specified a (optional) maximum range for the trace in voxels
Vec3i ptVoxelStart = ptVoxel;
// create the packed ray as a once off and reuse it for each voxel
PackedRay pray;
pray.Create(ray);
while (true) {
//Vec3i ptVoxelBefore = ptVoxel;
const Voxel *pVoxel = m_Tracer.RayTrace(voxel_ray, voxel_ray, ptVoxel);
if (!pVoxel)
break;
if (TestVoxelHits(ray, pray, *pVoxel, max_dist, bCullBackFaces))
return true;
// check for voxel range
if (abs(ptVoxel.x - ptVoxelStart.x) > voxel_range.x)
break;
if (abs(ptVoxel.y - ptVoxelStart.y) > voxel_range.y)
break;
if (abs(ptVoxel.z - ptVoxelStart.z) > voxel_range.z)
break;
} // while
return false;
}
int LightScene::FindIntersect_Ray(const Ray &ray, float &u, float &v, float &w, float &nearest_t, const Vec3i *pVoxelRange) //, int ignore_tri_p1)
{
nearest_t = FLT_MAX;
int nearest_tri = -1;
Ray voxel_ray;
Vec3i ptVoxel;
// prepare voxel trace
if (!m_Tracer.RayTrace_Start(ray, voxel_ray, ptVoxel))
return nearest_tri;
bool bFirstHit = false;
Vec3i ptVoxelFirstHit;
// if we have specified a (optional) maximum range for the trace in voxels
Vec3i ptVoxelStart = ptVoxel;
// create the packed ray as a once off and reuse it for each voxel
PackedRay pray;
pray.Create(ray);
// keep track of when we need to expand the bounds of the trace
int nearest_tri_so_far = -1;
int square_length_from_start_to_terminate = INT_MAX;
while (true) {
// Vec3i ptVoxelBefore = ptVoxel;
const Voxel *pVoxel = m_Tracer.RayTrace(voxel_ray, voxel_ray, ptVoxel);
// if (!m_Tracer.RayTrace(voxel_ray, voxel_ray, ptVoxel))
if (!pVoxel)
break;
ProcessVoxelHits(ray, pray, *pVoxel, nearest_t, nearest_tri);
// count number of tests for stats
//int nHits = m_Tracer.m_TriHits.size();
//num_tests += nHits;
// if there is a nearest hit, calculate the voxel in which the hit occurs.
// if we have travelled more than 1 voxel more than this, no need to traverse further.
if (nearest_tri != nearest_tri_so_far) {
nearest_tri_so_far = nearest_tri;
Vector3 ptNearestHit = ray.o + (ray.d * nearest_t);
m_Tracer.FindNearestVoxel(ptNearestHit, ptVoxelFirstHit);
bFirstHit = true;
// length in voxels to nearest hit
Vec3i voxel_diff = ptVoxelFirstHit;
voxel_diff -= ptVoxelStart;
float voxel_length_to_nearest_hit = voxel_diff.Length();
// add a bit
voxel_length_to_nearest_hit += 2.0f;
// square length
voxel_length_to_nearest_hit *= voxel_length_to_nearest_hit;
// plus 1 for rounding up.
square_length_from_start_to_terminate = voxel_length_to_nearest_hit + 1;
}
// first hit?
if (!bFirstHit) {
// check for voxel range
if (pVoxelRange) {
if (abs(ptVoxel.x - ptVoxelStart.x) > pVoxelRange->x)
break;
if (abs(ptVoxel.y - ptVoxelStart.y) > pVoxelRange->y)
break;
if (abs(ptVoxel.z - ptVoxelStart.z) > pVoxelRange->z)
break;
} // if voxel range
} else {
// check the range to this voxel. Have we gone further than the terminate voxel distance?
Vec3i voxel_diff = ptVoxel;
voxel_diff -= ptVoxelStart;
int sl = voxel_diff.SquareLength();
if (sl >= square_length_from_start_to_terminate)
break;
}
/*
// first hit?
if (!bFirstHit)
{
if (nearest_tri != -1)
{
bFirstHit = true;
ptVoxelFirstHit = ptVoxelBefore;
}
else
{
// check for voxel range
if (pVoxelRange)
{
if (abs(ptVoxel.x - ptVoxelStart.x) > pVoxelRange->x)
break;
if (abs(ptVoxel.y - ptVoxelStart.y) > pVoxelRange->y)
break;
if (abs(ptVoxel.z - ptVoxelStart.z) > pVoxelRange->z)
break;
} // if voxel range
}
}
else
{
// out of range of first voxel?
if (abs(ptVoxel.x - ptVoxelFirstHit.x) > 1)
break;
if (abs(ptVoxel.y - ptVoxelFirstHit.y) > 1)
break;
if (abs(ptVoxel.z - ptVoxelFirstHit.z) > 1)
break;
}
*/
#ifdef LIGHTTRACER_IGNORE_VOXELS
break;
#endif
} // while
if (nearest_tri != -1) {
ray.FindIntersect(m_Tris[nearest_tri], nearest_t, u, v, w);
}
return nearest_tri;
}
void LightScene::Reset() {
m_Materials.Reset();
// m_ptPositions.resize(0);
// m_ptNormals.resize(0);
//m_UVs.resize(0);
//m_Inds.resize(0);
m_UVTris.clear(true);
m_TriUVaabbs.clear(true);
m_TriPos_aabbs.clear(true);
m_Tracer.Reset();
m_Tri_TexelSizeWorldSpace.clear(true);
m_Tris.clear(true);
m_TriNormals.clear(true);
m_Tris_EdgeForm.clear(true);
m_TriPlanes.clear(true);
m_EmissionTris.clear(true);
m_Meshes.clear(true);
//m_Tri_MeshIDs.clear(true);
//m_Tri_SurfIDs.clear(true);
m_Tri_LMaterialIDs.clear(true);
m_UVTris_Primary.clear(true);
}
void LightScene::FindMeshes(Spatial *pNode) {
// mesh instance?
MeshInstance *pMI = Object::cast_to<MeshInstance>(pNode);
if (pMI) {
if (IsMeshInstanceSuitable(*pMI)) {
m_Meshes.push_back(pMI);
}
}
for (int n = 0; n < pNode->get_child_count(); n++) {
Spatial *pChild = Object::cast_to<Spatial>(pNode->get_child(n));
if (pChild) {
FindMeshes(pChild);
}
}
}
bool LightScene::Create_FromMeshSurface(int mesh_id, int surf_id, Ref<Mesh> rmesh, int width, int height) {
const MeshInstance &mi = *m_Meshes[mesh_id];
if (rmesh->surface_get_primitive_type(surf_id) != Mesh::PRIMITIVE_TRIANGLES)
return false; //only triangles
Array arrays = rmesh->surface_get_arrays(surf_id);
if (!arrays.size())
return false;
PoolVector<Vector3> verts = arrays[VS::ARRAY_VERTEX];
if (!verts.size())
return false;
PoolVector<Vector3> norms = arrays[VS::ARRAY_NORMAL];
if (!norms.size())
return false;
// uvs for lightmapping
PoolVector<Vector2> uvs = arrays[VS::ARRAY_TEX_UV2];
// optional uvs for albedo etc
PoolVector<Vector2> uvs_primary;
if (!uvs.size()) {
uvs = arrays[VS::ARRAY_TEX_UV];
} else {
uvs_primary = arrays[VS::ARRAY_TEX_UV];
}
if (!uvs.size())
return false;
PoolVector<int> inds = arrays[VS::ARRAY_INDEX];
if (!inds.size())
return false;
// we need to get the vert positions and normals from local space to world space to match up with the
// world space coords in the merged mesh
Transform trans = mi.get_global_transform();
PoolVector<Vector3> positions_world;
PoolVector<Vector3> normals_world;
Transform_Verts(verts, positions_world, trans);
Transform_Norms(norms, normals_world, trans);
// convert to longhand non indexed versions
int nTris = inds.size() / 3;
int nOldTris = m_Tris.size();
int nNewTris = nOldTris + nTris;
m_Tris.resize(nNewTris);
m_TriNormals.resize(nNewTris);
m_Tris_EdgeForm.resize(nNewTris);
m_TriPlanes.resize(nNewTris);
m_UVTris.resize(nNewTris);
m_TriUVaabbs.resize(nNewTris);
m_TriPos_aabbs.resize(nNewTris);
m_Tri_TexelSizeWorldSpace.resize(nNewTris);
//m_Tri_MeshIDs.resize(nNewTris);
//m_Tri_SurfIDs.resize(nNewTris);
m_Tri_LMaterialIDs.resize(nNewTris);
m_UVTris_Primary.resize(nNewTris);
// lmaterial
int lmat_id = m_Materials.FindOrCreateMaterial(mi, rmesh, surf_id);
// emission tri?
bool bEmit = false;
if (lmat_id) {
bEmit = m_Materials.GetMaterial(lmat_id - 1).m_bEmitter;
}
int num_bad_normals = 0;
int i = 0;
for (int n = 0; n < nTris; n++) {
// adjusted n
int an = n + nOldTris;
Tri &t = m_Tris[an];
Tri &tri_norm = m_TriNormals[an];
Tri &tri_edge = m_Tris_EdgeForm[an];
Plane &tri_plane = m_TriPlanes[an];
UVTri &uvt = m_UVTris[an];
Rect2 &rect = m_TriUVaabbs[an];
AABB &aabb = m_TriPos_aabbs[an];
// m_Tri_MeshIDs[an] = mesh_id;
// m_Tri_SurfIDs[an] = surf_id;
m_Tri_LMaterialIDs[an] = lmat_id;
UVTri &uvt_primary = m_UVTris_Primary[an];
int ind = inds[i];
rect = Rect2(uvs[ind], Vector2(0, 0));
aabb.position = positions_world[ind];
aabb.size = Vector3(0, 0, 0);
for (int c = 0; c < 3; c++) {
ind = inds[i++];
t.pos[c] = positions_world[ind];
tri_norm.pos[c] = normals_world[ind];
uvt.uv[c] = uvs[ind];
//rect = Rect2(uvt.uv[0], Vector2(0, 0));
rect.expand_to(uvt.uv[c]);
//aabb.position = t.pos[0];
aabb.expand_to(t.pos[c]);
// store primary uvs if present
if (uvs_primary.size()) {
uvt_primary.uv[c] = uvs_primary[ind];
} else {
uvt_primary.uv[c] = Vector2(0, 0);
}
}
// plane - calculate normal BEFORE changing winding into UV space
// because the normal is determined by the winding in world space
tri_plane = Plane(t.pos[0], t.pos[1], t.pos[2], CLOCKWISE);
// sanity check for bad normals
Vector3 average_normal = (tri_norm.pos[0] + tri_norm.pos[1] + tri_norm.pos[2]) * (1.0f / 3.0f);
if (average_normal.dot(tri_plane.normal) < 0.0f) {
num_bad_normals++;
// flip the face normal
tri_plane = -tri_plane;
}
// calculate edge form
{
// b - a
tri_edge.pos[0] = t.pos[1] - t.pos[0];
// c - a
tri_edge.pos[1] = t.pos[2] - t.pos[0];
// a
tri_edge.pos[2] = t.pos[0];
}
// ALWAYS DO THE UV WINDING LAST!!
// make sure winding is standard in UV space
if (uvt.IsWindingCW()) {
uvt.FlipWinding();
t.FlipWinding();
tri_norm.FlipWinding();
}
if (bEmit) {
EmissionTri et;
et.tri_id = an;
et.area = t.CalculateArea();
m_EmissionTris.push_back(et);
}
#ifdef LLIGHTSCENE_VERBOSE
String sz;
sz = "found triangle : ";
for (int s = 0; s < 3; s++) {
sz += "(" + String(t.pos[s]) + ") ... ";
}
print_line(sz);
sz = "\tnormal : ";
for (int s = 0; s < 3; s++) {
sz += "(" + String(tri_norm.pos[s]) + ") ... ";
}
print_line(sz);
sz = "\t\tUV : ";
for (int s = 0; s < 3; s++) {
sz += "(" + String(uvt.uv[s]) + ") ... ";
}
print_line(sz);
#endif
// convert aabb from 0-1 to texels
// aabb.position.x *= width;
// aabb.position.y *= height;
// aabb.size.x *= width;
// aabb.size.y *= height;
// expand aabb just a tad
rect.expand(Vector2(0.01, 0.01));
CalculateTriTexelSize(an, width, height);
}
if (num_bad_normals) {
print_line("mesh " + itos(mesh_id) + " contains " + itos(num_bad_normals) + " bad normals (face normal and vertex normals are opposite)");
}
return true;
}
bool LightScene::Create_FromMesh(int mesh_id, int width, int height) {
const MeshInstance &mi = *m_Meshes[mesh_id];
Ref<Mesh> rmesh = mi.get_mesh();
int num_surfaces = rmesh->get_surface_count();
for (int surf = 0; surf < num_surfaces; surf++) {
if (!Create_FromMeshSurface(mesh_id, surf, rmesh, width, height)) {
String sz;
sz = "Mesh " + itos(mesh_id) + " surf " + itos(surf) + " cannot be converted.";
WARN_PRINT(sz);
}
}
return true;
}
bool LightScene::Create(Spatial *pMeshesRoot, int width, int height, int voxel_density, int max_material_size, float emission_density) {
m_Materials.Prepare(max_material_size);
m_bUseSIMD = true;
FindMeshes(pMeshesRoot);
if (!m_Meshes.size())
return false;
for (int n = 0; n < m_Meshes.size(); n++) {
if (!Create_FromMesh(n, width, height))
return false;
}
m_Tracer.Create(*this, voxel_density);
// adjust material emission power to take account of sample density,
// to keep brightness the same
m_Materials.AdjustMaterials(emission_density);
return true;
}
// note this is assuming 1:1 aspect ratio lightmaps. This could do x and y size separately,
// but more complex.
void LightScene::CalculateTriTexelSize(int tri_id, int width, int height) {
const Tri &tri = m_Tris[tri_id];
const UVTri &uvtri = m_UVTris[tri_id];
// length of edges in world space
float l0 = (tri.pos[1] - tri.pos[0]).length();
float l1 = (tri.pos[2] - tri.pos[0]).length();
// texel edge lengths
Vector2 te0 = uvtri.uv[1] - uvtri.uv[0];
Vector2 te1 = uvtri.uv[2] - uvtri.uv[0];
// convert texel edges from uvs to texels
te0.x *= width;
te0.y *= height;
te1.x *= width;
te1.y *= height;
// texel edge lengths
float tl0 = te0.length();
float tl1 = te1.length();
// default
float texel_size = 1.0f;
if (tl0 >= tl1) {
// check for divide by zero
if (tl0 > 0.00001f)
texel_size = l0 / tl0;
} else {
if (tl1 > 0.00001f)
texel_size = l1 / tl1;
}
m_Tri_TexelSizeWorldSpace[tri_id] = texel_size;
}
bool LightScene::FindEmissionColor(int tri_id, const Vector3 &bary, Color &texture_col, Color &col) {
Vector2 uvs;
m_UVTris_Primary[tri_id].FindUVBarycentric(uvs, bary.x, bary.y, bary.z);
int mat_id_p1 = m_Tri_LMaterialIDs[tri_id];
// should never happen?
if (!mat_id_p1) {
texture_col = Color(0, 0, 0, 0);
col = Color(0, 0, 0, 0);
return false;
}
const LMaterial &mat = m_Materials.GetMaterial(mat_id_p1 - 1);
if (!mat.m_bEmitter)
return false;
// albedo
// return whether texture found
bool bTransparent;
bool res = m_Materials.FindColors(mat_id_p1, uvs, texture_col, bTransparent);
texture_col *= mat.m_Col_Emission;
// power = mat.m_Power_Emission;
col = mat.m_Col_Emission;
return res;
}
bool LightScene::FindAllTextureColors(int tri_id, const Vector3 &bary, Color &albedo, Color &emission, bool &bTransparent, bool &bEmitter) {
Vector2 uvs;
m_UVTris_Primary[tri_id].FindUVBarycentric(uvs, bary.x, bary.y, bary.z);
int mat_id_p1 = m_Tri_LMaterialIDs[tri_id];
bool res = m_Materials.FindColors(mat_id_p1, uvs, albedo, bTransparent);
if (res) {
const LMaterial &mat = m_Materials.GetMaterial(mat_id_p1 - 1);
// return whether emitter
bEmitter = mat.m_bEmitter;
//emission = albedo * mat.m_Col_Emission;
emission = mat.m_Col_Emission;
} else {
bEmitter = false;
emission = Color(0, 0, 0, 1);
}
return res;
}
bool LightScene::FindPrimaryTextureColors(int tri_id, const Vector3 &bary, Color &albedo, bool &bTransparent) {
Vector2 uvs;
m_UVTris_Primary[tri_id].FindUVBarycentric(uvs, bary.x, bary.y, bary.z);
int mat_id_p1 = m_Tri_LMaterialIDs[tri_id];
return m_Materials.FindColors(mat_id_p1, uvs, albedo, bTransparent);
}
//void LightScene::RasterizeTriangleIDs(LightMapper_Base &base, LightImage<uint32_t> &im_p1, LightImage<uint32_t> &im2_p1, LightImage<Vector3> &im_bary)
void LightScene::RasterizeTriangleIDs(LightMapper_Base &base, LightImage<uint32_t> &im_p1, LightImage<Vector3> &im_bary) {
int width = im_p1.GetWidth();
int height = im_p1.GetHeight();
// create a temporary image of vectors to store the triangles per texel
LightImage<Vector<uint32_t> > temp_image_tris;
if (base.m_Logic_Process_AO)
temp_image_tris.Create(width, height, false);
for (int n = 0; n < m_UVTris.size(); n++) {
const Rect2 &aabb = m_TriUVaabbs[n];
const UVTri &tri = m_UVTris[n];
int min_x = aabb.position.x * width;
int min_y = aabb.position.y * height;
int max_x = (aabb.position.x + aabb.size.x) * width;
int max_y = (aabb.position.y + aabb.size.y) * height;
// add a bit for luck
min_x--;
min_y--;
max_x++;
max_y++;
// clamp
min_x = CLAMP(min_x, 0, width);
min_y = CLAMP(min_y, 0, height);
max_x = CLAMP(max_x, 0, width);
max_y = CLAMP(max_y, 0, height);
int debug_overlap_count = 0;
for (int y = min_y; y < max_y; y++) {
for (int x = min_x; x < max_x; x++) {
float s = (x + 0.5f) / (float)width;
float t = (y + 0.5f) / (float)height;
// if ((x == 26) && (y == 25))
// {
// print_line("testing");
// }
if (tri.ContainsPoint(Vector2(s, t)))
//if (tri.ContainsTexel(x, y, width , height))
{
if (base.m_Logic_Process_AO)
temp_image_tris.GetItem(x, y).push_back(n);
uint32_t &id_p1 = im_p1.GetItem(x, y);
// hopefully this was 0 before
if (id_p1) {
debug_overlap_count++;
// if (debug_overlap_count == 64)
// {
// print_line("overlap detected");
// }
// store the overlapped ID in a second map
//im2_p1.GetItem(x, y) = id_p1;
}
// save new id
id_p1 = n + 1;
// find barycentric coords
float u, v, w;
// note this returns NAN for degenerate triangles!
tri.FindBarycentricCoords(Vector2(s, t), u, v, w);
// assert (!isnan(u));
// assert (!isnan(v));
// assert (!isnan(w));
Vector3 &bary = im_bary.GetItem(x, y);
bary = Vector3(u, v, w);
}
} // for x
} // for y
} // for tri
if (base.m_Logic_Process_AO) {
// translate temporary image vectors into mini lists
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
MiniList &ml = base.m_Image_TriIDs.GetItem(x, y);
ml.first = base.m_TriIDs.size();
const Vector<uint32_t> &vec = temp_image_tris.GetItem(x, y);
for (int n = 0; n < vec.size(); n++) {
base.m_TriIDs.push_back(vec[n]);
ml.num += 1;
}
// if (!ml.num)
// {
// ml.first = base.m_TriIDs.size();
// }
// BUG IS THESE ARE NOT CONTIGUOUS
// ml.num += 1;
// base.m_TriIDs.push_back(n);
} // for x
} // for y
} // only if processing AO
}
void LightScene::Transform_Verts(const PoolVector<Vector3> &ptsLocal, PoolVector<Vector3> &ptsWorld, const Transform &tr) const {
for (int n = 0; n < ptsLocal.size(); n++) {
Vector3 ptWorld = tr.xform(ptsLocal[n]);
ptsWorld.push_back(ptWorld);
}
}
void LightScene::Transform_Norms(const PoolVector<Vector3> &normsLocal, PoolVector<Vector3> &normsWorld, const Transform &tr) const {
int invalid_normals = 0;
for (int n = 0; n < normsLocal.size(); n++) {
// hacky way for normals, we should use transpose of inverse matrix, dunno if godot supports this
Vector3 ptNormA = Vector3(0, 0, 0);
Vector3 ptNormWorldA = tr.xform(ptNormA);
Vector3 ptNormWorldB = tr.xform(normsLocal[n]);
Vector3 ptNorm = ptNormWorldB - ptNormWorldA;
ptNorm = ptNorm.normalized();
if (ptNorm.length_squared() < 0.9f)
invalid_normals++;
normsWorld.push_back(ptNorm);
}
if (invalid_normals) {
WARN_PRINT("Invalid normals detected : " + itos(invalid_normals));
}
}
| 25.490329 | 163 | 0.657283 | [
"mesh",
"object",
"vector",
"transform",
"3d"
] |
c33db6f004e2e1803c92ff179f337f35eb96c0ce | 5,704 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Remoting/HttpWebRequest_BeginGetResponse/CPP/httpwebrequest_begingetresponse.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_Remoting/HttpWebRequest_BeginGetResponse/CPP/httpwebrequest_begingetresponse.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_Remoting/HttpWebRequest_BeginGetResponse/CPP/httpwebrequest_begingetresponse.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z |
// System::Net::HttpWebRequest::BeginGetResponse System::Net::HttpWebRequest::EndGetResponse
/**
* Snippet1, Snippet2, Snippet3 go together.
* This program shows how to use BeginGetResponse and EndGetResponse methods of the
* HttpWebRequest class.
* It uses an asynchronous approach to get the response for the HTTP Web Request.
* The RequestState class is defined to chekc the state of the request.
* After a HttpWebRequest Object* is created, its BeginGetResponse method is used to start
* the asynchronous response phase.
* Finally, the EndGetResponse method is used to end the asynchronous response phase .
*/
#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::IO;
using namespace System::Text;
using namespace System::Threading;
public ref class RequestState
{
private:
// This class stores the State of the request.
const int BUFFER_SIZE;
public:
StringBuilder^ requestData;
array<Byte>^BufferRead;
HttpWebRequest^ request;
HttpWebResponse^ response;
Stream^ streamResponse;
RequestState()
: BUFFER_SIZE( 1024 )
{
BufferRead = gcnew array<Byte>(BUFFER_SIZE);
requestData = gcnew StringBuilder( "" );
request = nullptr;
streamResponse = nullptr;
}
};
ref class HttpWebRequest_BeginGetResponse
{
public:
static ManualResetEvent^ allDone = gcnew ManualResetEvent( false );
static int BUFFER_SIZE = 1024;
// <Snippet1>
// <Snippet2>
static void RespCallback( IAsyncResult^ asynchronousResult )
{
try
{
// State of request is asynchronous.
RequestState^ myRequestState = dynamic_cast<RequestState^>(asynchronousResult->AsyncState);
HttpWebRequest^ myHttpWebRequest2 = myRequestState->request;
myRequestState->response = dynamic_cast<HttpWebResponse^>(myHttpWebRequest2->EndGetResponse( asynchronousResult ));
// Read the response into a Stream object.
Stream^ responseStream = myRequestState->response->GetResponseStream();
myRequestState->streamResponse = responseStream;
// Begin the Reading of the contents of the HTML page and print it to the console.
IAsyncResult^ asynchronousInputRead = responseStream->BeginRead( myRequestState->BufferRead, 0, BUFFER_SIZE, gcnew AsyncCallback( ReadCallBack ), myRequestState );
}
catch ( WebException^ e )
{
Console::WriteLine( "\nException raised!" );
Console::WriteLine( "\nMessage: {0}", e->Message );
Console::WriteLine( "\nStatus: {0}", e->Status );
}
}
static void ReadCallBack( IAsyncResult^ asyncResult )
{
try
{
RequestState^ myRequestState = dynamic_cast<RequestState^>(asyncResult->AsyncState);
Stream^ responseStream = myRequestState->streamResponse;
int read = responseStream->EndRead( asyncResult );
// Read the HTML page and then print it to the console.
if ( read > 0 )
{
myRequestState->requestData->Append( Encoding::ASCII->GetString( myRequestState->BufferRead, 0, read ) );
IAsyncResult^ asynchronousResult = responseStream->BeginRead( myRequestState->BufferRead, 0, BUFFER_SIZE, gcnew AsyncCallback( ReadCallBack ), myRequestState );
}
else
{
Console::WriteLine( "\nThe contents of the Html page are : " );
if ( myRequestState->requestData->Length > 1 )
{
String^ stringContent;
stringContent = myRequestState->requestData->ToString();
Console::WriteLine( stringContent );
}
Console::WriteLine( "Press any key to continue.........." );
Console::ReadLine();
responseStream->Close();
allDone->Set();
}
}
catch ( WebException^ e )
{
Console::WriteLine( "\nException raised!" );
Console::WriteLine( "\nMessage: {0}", e->Message );
Console::WriteLine( "\nStatus: {0}", e->Status );
}
}
};
int main()
{
try
{
// Create a HttpWebrequest object to the desired URL.
HttpWebRequest^ myHttpWebRequest1 = dynamic_cast<HttpWebRequest^>(WebRequest::Create( "http://www.contoso.com" ));
// Create an instance of the RequestState and assign the previous myHttpWebRequest1
// object to its request field.
RequestState^ myRequestState = gcnew RequestState;
myRequestState->request = myHttpWebRequest1;
// Start the asynchronous request.
IAsyncResult^ result = dynamic_cast<IAsyncResult^>(myHttpWebRequest1->BeginGetResponse( gcnew AsyncCallback( HttpWebRequest_BeginGetResponse::RespCallback ), myRequestState ));
HttpWebRequest_BeginGetResponse::allDone->WaitOne();
// Release the HttpWebResponse resource.
myRequestState->response->Close();
}
catch ( WebException^ e )
{
Console::WriteLine( "\nException raised!" );
Console::WriteLine( "\nMessage: {0}", e->Message );
Console::WriteLine( "\nStatus: {0}", e->Status );
Console::WriteLine( "Press any key to continue.........." );
}
catch ( Exception^ e )
{
Console::WriteLine( "\nException raised!" );
Console::WriteLine( "Source : {0} ", e->Source );
Console::WriteLine( "Message : {0} ", e->Message );
Console::WriteLine( "Press any key to continue.........." );
Console::Read();
}
}
// </Snippet2>
// </Snippet1>
| 35.874214 | 183 | 0.632013 | [
"object"
] |
c34e636a6a3160dee82561be6c43cf3c583d1652 | 5,125 | cc | C++ | webkit/fileapi/file_system_origin_database_unittest.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2016-03-10T09:13:57.000Z | 2016-03-10T09:13:57.000Z | webkit/fileapi/file_system_origin_database_unittest.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2022-03-13T08:39:05.000Z | 2022-03-13T08:39:05.000Z | webkit/fileapi/file_system_origin_database_unittest.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2011 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 "testing/gtest/include/gtest/gtest.h"
#include <string>
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "webkit/fileapi/file_system_origin_database.h"
namespace fileapi {
TEST(FileSystemOriginDatabaseTest, BasicTest) {
ScopedTempDir dir;
ASSERT_TRUE(dir.CreateUniqueTempDir());
const FilePath kDBFile = dir.path().AppendASCII("fsod.db");
EXPECT_FALSE(file_util::PathExists(kDBFile));
FileSystemOriginDatabase database(kDBFile);
std::string origin("origin");
EXPECT_FALSE(database.HasOriginPath(origin));
// Double-check to make sure that had no side effects.
EXPECT_FALSE(database.HasOriginPath(origin));
FilePath path0;
FilePath path1;
// Empty strings aren't valid origins.
EXPECT_FALSE(database.GetPathForOrigin(std::string(), &path0));
EXPECT_TRUE(database.GetPathForOrigin(origin, &path0));
EXPECT_TRUE(database.HasOriginPath(origin));
EXPECT_TRUE(database.GetPathForOrigin(origin, &path1));
EXPECT_FALSE(path0.empty());
EXPECT_FALSE(path1.empty());
EXPECT_EQ(path0, path1);
EXPECT_TRUE(file_util::PathExists(kDBFile));
}
TEST(FileSystemOriginDatabaseTest, TwoPathTest) {
ScopedTempDir dir;
ASSERT_TRUE(dir.CreateUniqueTempDir());
const FilePath kDBFile = dir.path().AppendASCII("fsod.db");
EXPECT_FALSE(file_util::PathExists(kDBFile));
FileSystemOriginDatabase database(kDBFile);
std::string origin0("origin0");
std::string origin1("origin1");
EXPECT_FALSE(database.HasOriginPath(origin0));
EXPECT_FALSE(database.HasOriginPath(origin1));
FilePath path0;
FilePath path1;
EXPECT_TRUE(database.GetPathForOrigin(origin0, &path0));
EXPECT_TRUE(database.HasOriginPath(origin0));
EXPECT_FALSE(database.HasOriginPath(origin1));
EXPECT_TRUE(database.GetPathForOrigin(origin1, &path1));
EXPECT_TRUE(database.HasOriginPath(origin1));
EXPECT_FALSE(path0.empty());
EXPECT_FALSE(path1.empty());
EXPECT_NE(path0, path1);
EXPECT_TRUE(file_util::PathExists(kDBFile));
}
TEST(FileSystemOriginDatabaseTest, DropDatabaseTest) {
ScopedTempDir dir;
ASSERT_TRUE(dir.CreateUniqueTempDir());
const FilePath kDBFile = dir.path().AppendASCII("fsod.db");
EXPECT_FALSE(file_util::PathExists(kDBFile));
FileSystemOriginDatabase database(kDBFile);
std::string origin("origin");
EXPECT_FALSE(database.HasOriginPath(origin));
FilePath path0;
EXPECT_TRUE(database.GetPathForOrigin(origin, &path0));
EXPECT_TRUE(database.HasOriginPath(origin));
EXPECT_FALSE(path0.empty());
EXPECT_TRUE(file_util::PathExists(kDBFile));
database.DropDatabase();
FilePath path1;
EXPECT_TRUE(database.HasOriginPath(origin));
EXPECT_TRUE(database.GetPathForOrigin(origin, &path1));
EXPECT_FALSE(path1.empty());
EXPECT_EQ(path0, path1);
}
TEST(FileSystemOriginDatabaseTest, DeleteOriginTest) {
ScopedTempDir dir;
ASSERT_TRUE(dir.CreateUniqueTempDir());
const FilePath kDBFile = dir.path().AppendASCII("fsod.db");
EXPECT_FALSE(file_util::PathExists(kDBFile));
FileSystemOriginDatabase database(kDBFile);
std::string origin("origin");
EXPECT_FALSE(database.HasOriginPath(origin));
EXPECT_TRUE(database.RemovePathForOrigin(origin));
FilePath path0;
EXPECT_TRUE(database.GetPathForOrigin(origin, &path0));
EXPECT_TRUE(database.HasOriginPath(origin));
EXPECT_FALSE(path0.empty());
EXPECT_TRUE(database.RemovePathForOrigin(origin));
EXPECT_FALSE(database.HasOriginPath(origin));
FilePath path1;
EXPECT_TRUE(database.GetPathForOrigin(origin, &path1));
EXPECT_FALSE(path1.empty());
EXPECT_NE(path0, path1);
}
TEST(FileSystemOriginDatabaseTest, ListOriginsTest) {
ScopedTempDir dir;
ASSERT_TRUE(dir.CreateUniqueTempDir());
const FilePath kDBFile = dir.path().AppendASCII("fsod.db");
EXPECT_FALSE(file_util::PathExists(kDBFile));
std::vector<FileSystemOriginDatabase::OriginRecord> origins;
FileSystemOriginDatabase database(kDBFile);
EXPECT_TRUE(database.ListAllOrigins(&origins));
EXPECT_TRUE(origins.empty());
origins.clear();
std::string origin0("origin0");
std::string origin1("origin1");
EXPECT_FALSE(database.HasOriginPath(origin0));
EXPECT_FALSE(database.HasOriginPath(origin1));
FilePath path0;
FilePath path1;
EXPECT_TRUE(database.GetPathForOrigin(origin0, &path0));
EXPECT_TRUE(database.ListAllOrigins(&origins));
EXPECT_EQ(origins.size(), 1UL);
EXPECT_EQ(origins[0].origin, origin0);
EXPECT_EQ(origins[0].path, path0);
origins.clear();
EXPECT_TRUE(database.GetPathForOrigin(origin1, &path1));
EXPECT_TRUE(database.ListAllOrigins(&origins));
EXPECT_EQ(origins.size(), 2UL);
if (origins[0].origin == origin0) {
EXPECT_EQ(origins[0].path, path0);
EXPECT_EQ(origins[1].origin, origin1);
EXPECT_EQ(origins[1].path, path1);
} else {
EXPECT_EQ(origins[0].origin, origin1);
EXPECT_EQ(origins[0].path, path1);
EXPECT_EQ(origins[1].origin, origin0);
EXPECT_EQ(origins[1].path, path0);
}
}
} // namespace fileapi
| 30.688623 | 73 | 0.758634 | [
"vector"
] |
c35575be0ad7fc4af41cb32eb703aa6add84988a | 3,938 | cpp | C++ | RollerCoaster/Roller Coaster/Src/Triangle.cpp | Zhang-Yu-Bo/NTUST-108CG-Project03-RollerCoaster | 7800db3795abd6a960de8f50a7d02b8ae71e8c21 | [
"MIT"
] | null | null | null | RollerCoaster/Roller Coaster/Src/Triangle.cpp | Zhang-Yu-Bo/NTUST-108CG-Project03-RollerCoaster | 7800db3795abd6a960de8f50a7d02b8ae71e8c21 | [
"MIT"
] | null | null | null | RollerCoaster/Roller Coaster/Src/Triangle.cpp | Zhang-Yu-Bo/NTUST-108CG-Project03-RollerCoaster | 7800db3795abd6a960de8f50a7d02b8ae71e8c21 | [
"MIT"
] | null | null | null | #include "Triangle.h"
Triangle::Triangle()
{
}
void Triangle::DimensionTransformation(GLfloat source[],GLfloat target[][4])
{
//for uniform value, transfer 1 dimension to 2 dimension
int i = 0;
for(int j=0;j<4;j++)
for(int k=0;k<4;k++)
{
target[j][k] = source[i];
i++;
}
}
void Triangle::Paint(GLfloat* ProjectionMatrix, GLfloat* ModelViewMatrix)
{
GLfloat P[4][4];
GLfloat MV[4][4];
DimensionTransformation(ProjectionMatrix,P);
DimensionTransformation(ModelViewMatrix,MV);
//Bind the shader we want to draw with
shaderProgram->bind();
//Bind the VAO we want to draw
vao.bind();
//pass projection matrix to shader
shaderProgram->setUniformValue("ProjectionMatrix",P);
//pass modelview matrix to shader
shaderProgram->setUniformValue("ModelViewMatrix",MV);
// Bind the buffer so that it is the current active buffer.
vvbo.bind();
// Enable Attribute 0
shaderProgram->enableAttributeArray(0);
// Set Attribute 0 to be position
shaderProgram->setAttributeArray(0,GL_FLOAT,0,3,NULL);
//unbind buffer
vvbo.release();
// Bind the buffer so that it is the current active buffer
cvbo.bind();
// Enable Attribute 1
shaderProgram->enableAttributeArray(1);
// Set Attribute 0 to be color
shaderProgram->setAttributeArray(1,GL_FLOAT,0,3,NULL);
//unbind buffer
cvbo.release();
//Draw a triangle with 3 indices starting from the 0th index
glDrawArrays(GL_TRIANGLES,0,vertices.size());
//Disable Attribute 0&1
shaderProgram->disableAttributeArray(0);
shaderProgram->disableAttributeArray(1);
//unbind vao
vao.release();
//unbind vao
shaderProgram->release();
}
void Triangle::Init()
{
InitShader("./Shader/Triangle.vs","./Shader/Triangle.fs");
InitVAO();
InitVBO();
}
void Triangle::InitVAO()
{
// Create Vertex Array Object
vao.create();
// Bind the VAO so it is the current active VAO
vao.bind();
}
void Triangle::InitVBO()
{
//Set each vertex's position
vertices<<QVector3D(5.0f, 2.0f, -10.0f)
<<QVector3D(5.0f, 2.0f, 10.0f)
<<QVector3D(15.0f, 2.0f, 0.0f);
// Create Buffer for position
vvbo.create();
// Bind the buffer so that it is the current active buffer.
vvbo.bind();
// Since we will never change the data that we are about to pass the Buffer, we will say that the Usage Pattern is StaticDraw
vvbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
// Allocate and initialize the information
vvbo.allocate(vertices.constData(),vertices.size() * sizeof(QVector3D));
//Set each vertex's color
colors<<QVector3D(0.0f,1.0f,0.0f)
<<QVector3D(1.0f,0.0f,0.0f)
<<QVector3D(0.0f,0.0f,1.0f);
// Create Buffer for color
cvbo.create();
// Bind the buffer so that it is the current active buffer.
cvbo.bind();
// Since we will never change the data that we are about to pass the Buffer, we will say that the Usage Pattern is StaticDraw
cvbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
// Allocate and initialize the information
cvbo.allocate(colors.constData(),colors.size() * sizeof(QVector3D));
}
void Triangle::InitShader(QString vertexShaderPath,QString fragmentShaderPath)
{
// Create Shader
shaderProgram = new QOpenGLShaderProgram();
QFileInfo vertexShaderFile(vertexShaderPath);
if(vertexShaderFile.exists())
{
vertexShader = new QOpenGLShader(QOpenGLShader::Vertex);
if(vertexShader->compileSourceFile(vertexShaderPath))
shaderProgram->addShader(vertexShader);
else
qWarning() << "Vertex Shader Error " << vertexShader->log();
}
else
qDebug()<<vertexShaderFile.filePath()<<" can't be found";
QFileInfo fragmentShaderFile(fragmentShaderPath);
if(fragmentShaderFile.exists())
{
fragmentShader = new QOpenGLShader(QOpenGLShader::Fragment);
if(fragmentShader->compileSourceFile(fragmentShaderPath))
shaderProgram->addShader(fragmentShader);
else
qWarning() << "fragment Shader Error " << fragmentShader->log();
}
else
qDebug()<<fragmentShaderFile.filePath()<<" can't be found";
shaderProgram->link();
} | 29.609023 | 126 | 0.729558 | [
"object"
] |
c364b5d7e8c8f5e4072d2571d455c9b6f4f5beb6 | 5,248 | cpp | C++ | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/TileUpdateScheduler.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/TileUpdateScheduler.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/TileUpdateScheduler.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
#include "pch.h"
#include "TileUpdateScheduler.h"
#include "ThumbnailGenerator.h"
#include "Repository.h"
#include "RandomPhotoSelector.h"
#include "WideFiveImageTile.h"
#include "TaskExceptionsExtensions.h"
#include "ExceptionPolicyFactory.h"
using namespace concurrency;
using namespace Hilo;
using namespace std;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation::Collections;
using namespace Windows::Storage;
using namespace Windows::UI::Notifications;
// See http://go.microsoft.com/fwlink/?LinkId=267275 for info about Hilo's implementation of tiles.
// Specifies the name of the local app folder that holds the thumbnail images.
String^ ThumbnailsFolderName = "thumbnails";
// Specifies the number of photos in a batch. A batch is applied to a single
// tile update.
const unsigned int BatchSize = 5;
// Specifies the number of batches. The Windows Runtime rotates through
// multiple batches.
const unsigned int SetSize = 3;
TileUpdateScheduler::TileUpdateScheduler()
{
}
// Select random pictures from the Pictures library and copy them
// to a local app folder and then update the tile.
task<void> TileUpdateScheduler::ScheduleUpdateAsync(std::shared_ptr<Repository> repository, std::shared_ptr<ExceptionPolicy> policy)
{
// The storage folder that holds the thumbnails.
auto thumbnailStorageFolder = make_shared<StorageFolder^>(nullptr);
return create_task(
// Create a folder to hold the thumbnails.
// The ReplaceExisting option specifies to replace the contents of any existing folder with a new, empty folder.
ApplicationData::Current->LocalFolder->CreateFolderAsync(
ThumbnailsFolderName,
CreationCollisionOption::ReplaceExisting)).then([repository, thumbnailStorageFolder](StorageFolder^ createdFolder)
{
assert(IsBackgroundThread());
(*thumbnailStorageFolder) = createdFolder;
// Collect a multiple of the batch and set size of the most recent photos from the library.
// Later a random set is selected from this collection for thumbnail image generation.
return repository->GetPhotoStorageFilesAsync("", 2 * BatchSize * SetSize);
}, task_continuation_context::use_arbitrary()).then([](IVectorView<StorageFile^>^ files) -> task<IVector<StorageFile^>^>
{
assert(IsBackgroundThread());
// If we received fewer than the number in one batch,
// return the empty collection.
if (files->Size < BatchSize)
{
return create_task_from_result(static_cast<IVector<StorageFile^>^>(
ref new Vector<StorageFile^>()));
}
auto copiedFileInfos = ref new Vector<StorageFile^>(begin(files), end(files));
return RandomPhotoSelector::SelectFilesAsync(copiedFileInfos->GetView(), SetSize * BatchSize);
}, task_continuation_context::use_arbitrary()).then([this, thumbnailStorageFolder, policy](IVector<StorageFile^>^ selectedFiles) -> task<Vector<StorageFile^>^>
{
assert(IsBackgroundThread());
// Return the empty collection if the previous step did not
// produce enough photos.
if (selectedFiles->Size == 0)
{
return create_task_from_result(ref new Vector<StorageFile^>());
}
ThumbnailGenerator thumbnailGenerator(policy);
return thumbnailGenerator.Generate(selectedFiles, *thumbnailStorageFolder);
}, task_continuation_context::use_arbitrary()).then([this](Vector<StorageFile^>^ files)
{
assert(IsBackgroundThread());
// Update the tile.
UpdateTile(files);
}, concurrency::task_continuation_context::use_arbitrary()).then(ObserveException<void>(policy));
}
void TileUpdateScheduler::UpdateTile(IVector<StorageFile^>^ files)
{
// Create a tile updater.
TileUpdater^ tileUpdater = TileUpdateManager::CreateTileUpdaterForApplication();
tileUpdater->Clear();
unsigned int imagesCount = files->Size;
unsigned int imageBatches = imagesCount / BatchSize;
tileUpdater->EnableNotificationQueue(imageBatches > 0);
for(unsigned int batch = 0; batch < imageBatches; batch++)
{
vector<wstring> imageList;
// Add the selected images to the wide tile template.
for(unsigned int image = 0; image < BatchSize; image++)
{
StorageFile^ file = files->GetAt(image + (batch * BatchSize));
wstringstream imageSource;
imageSource << L"ms-appdata:///local/"
<< ThumbnailsFolderName->Data()
<< L"/"
<< file->Name->Data();
imageList.push_back(imageSource.str());
}
WideFiveImageTile wideTile;
wideTile.SetImageFilePaths(imageList);
// Create the notification and update the tile.
auto notification = wideTile.GetTileNotification();
tileUpdater->Update(notification);
}
}
| 41.322835 | 163 | 0.701791 | [
"vector"
] |
c3728705a36f2dab6eed7b237699cc592b1868cf | 7,211 | cpp | C++ | src/activeobject.cpp | EnnoSlunder/PositionBasedDynamics | bba2e1d67262454df425bd4910a173fed979a10f | [
"MIT"
] | null | null | null | src/activeobject.cpp | EnnoSlunder/PositionBasedDynamics | bba2e1d67262454df425bd4910a173fed979a10f | [
"MIT"
] | null | null | null | src/activeobject.cpp | EnnoSlunder/PositionBasedDynamics | bba2e1d67262454df425bd4910a173fed979a10f | [
"MIT"
] | 2 | 2019-08-06T10:24:58.000Z | 2021-06-03T17:11:40.000Z | #include "activeobject.h"
#include "sceneobject.h"
#include "GLWidget.h"
#include "Scene.h"
#include "dynamics/dynamicsWorld.h"
#include "dynamics/particle.h"
ActiveObject::ActiveObject()
{
}
ActiveObject::ActiveObject(GLWidget *_widget)
{
m_GLWidget = _widget;
}
void ActiveObject::notify(int _id)
{
}
void ActiveObject::notify(pSceneOb _sender)
{
if(_sender == nullptr)
{
m_isActive = false;
m_manipulator->setActive(false);
activeSceneObject = nullptr;
return;
}
activeSceneObject = _sender;
m_isActive = true;
m_manipulator->setActive(true);
int var = 0;
if(activeSceneObject->isDynamic())
{
var = activeSceneObject->dynamicObject()->mID;
}
emit transformChanged(_sender->getMatrix(),
_sender->getPos(),
_sender->getPos(),
_sender->getPos(),
var);
m_manipulator->setTranslation(_sender->getTransform().translation());
m_manipulator->setRotation(_sender->getTransform().rotation());
}
void ActiveObject::notify(const Transform &_t)
{
if(activeSceneObject)
{
activeSceneObject->setRotation(_t.rotation());
activeSceneObject->setTranslation(_t.translation());
}
}
void ActiveObject::notify(MouseState _mouseState)
{
}
void ActiveObject::pinConstraintActive()
{
Particle *ptr = nullptr;
auto particleSmartPointer = activeSceneObject->dynamicObject()->pointer(ptr);
auto pinConstraint = std::make_shared<PinConstraint>(particleSmartPointer, activeSceneObject->getPos());
activeSceneObject->setPinConstraint(pinConstraint);
particleSmartPointer->m_Constraints.push_back(pinConstraint);
}
void ActiveObject::updatePinConstraintActive()
{
if(!activeSceneObject)
return;
{
auto pinConstraint = activeSceneObject->getPinConstraint();
if(!pinConstraint)
mlog<<"no Cstr-----------";
pinConstraint->setPositon(activeSceneObject->getPos());
}
}
void ActiveObject::unpinConstraintActive()
{
if(!activeSceneObject)
return;
auto dw = m_GLWidget->scene()->dynamicsWorld();
dw->deleteConstraint(activeSceneObject->getPinConstraint());
}
void ActiveObject::processInput(ActiveObject::AOInput _input)
{
// picking sets SELECTED. Make funciton select that sets selected or pinned.
switch(_input)
{
case LM_CLICKED:
if(inputManager::keyPressed(Qt::Key_Shift) && activeSceneObject->isDynamic()){
Particle* empty = nullptr;
ParticlePtr myP = activeSceneObject->dynamicObject()->pointer(empty);
addParticleToSelection(myP);
}
if(m_state == SELECTED && activeSceneObject->isDynamic()){
if(inputManager::keyPressed(Qt::Key_Shift)){
// addParticleToSelection(activeSceneObject->dynamicObject()->pointer());
Particle* empty = nullptr;
ParticlePtr myP = activeSceneObject->dynamicObject()->pointer(empty);
addParticleToSelection(myP);
}
pinConstraintActive();
activeSceneObject->isPinned(true);
activeSceneObject->isHidden(false);
activeSceneObject->isDynamic(false);
m_state = PICKED;
// mlog<<" SELECTED -> PICKED isHidden: "<<activeSceneObject->isHidden()<< " was: "<<was;
}
if(m_state == PINNED)
activeSceneObject->isDynamic(false);
break;
case LM_PRESSED:
if(m_state == PINNED)
updatePinConstraintActive();
if(m_state == PICKED)
updatePinConstraintActive();
break;
case LM_RELEASED:
if(m_state == PINNED){
bool was = activeSceneObject->isHidden();
activeSceneObject->isDynamic(true);
activeSceneObject->isPinned(true);
activeSceneObject->isHidden(false);
}
if(m_state == PICKED){
unpinConstraintActive();
activeSceneObject->isPinned(false);
if(activeSceneObject->getID() == 2)
activeSceneObject->isHidden(false);
activeSceneObject->isDynamic(true);
m_state = SELECTED;
}
break;
case B_P_PRESSED:
if(m_state == PINNED){
unpinConstraintActive();
activeSceneObject->isPinned(false);
activeSceneObject->isHidden(true);
activeSceneObject->isDynamic(true);
m_state = SELECTED;
break;
}
if(m_state == PICKED){
updatePinConstraintActive();
m_state = PINNED;
break;
}
if(m_state == SELECTED){
pinConstraintActive();
activeSceneObject->isDynamic(true);
m_state = PINNED;
}
break;
case B_T_PRESSED:
addPinTogetherConstraintToSelection();
break;
case B_D_PRESSED:
deletePinTogetherConstraintFromSelection();
break;
}
}
void ActiveObject::addParticleToSelection(const ParticlePtr _p)
{
if( std::find(m_selection.begin(),m_selection.end(), _p) == m_selection.end())
{
m_selection.push_back(_p);
}
else{
}
}
void ActiveObject::addPinTogetherConstraintToSelection()
{
m_GLWidget->scene()->dynamicsWorld()->addPinTogetherConstraint(m_selection);
m_selection.clear();
}
void ActiveObject::deletePinTogetherConstraintFromSelection()
{
if(m_state == SELECTED && activeSceneObject->isDynamic()){
Particle *ptr = nullptr;
ParticlePtr p = activeSceneObject->dynamicObject()->pointer(ptr);
for(auto c : p->m_Constraints)
{
if(c.lock()->type() == AbstractConstraint::PINTOGETHER)
{
m_GLWidget->scene()->dynamicsWorld()->deleteConstraint(c.lock());
}
}
}
}
pSceneOb ActiveObject::currentObject()
{
return activeSceneObject;
}
bool ActiveObject::isActive()
{
return m_isActive;
}
void ActiveObject::select()
{
if(activeSceneObject->isPinned()){
m_state = PINNED;
return;
}
m_state = SELECTED;
}
void ActiveObject::deselect()
{
m_state = NONE_SELECTED;
}
void ActiveObject::setTransform(const QVector3D _t, const QVector3D _r, const QVector3D _s)
{
if(activeSceneObject)
{
activeSceneObject->setTranslation(_t);
activeSceneObject->setRotation(_r);
}
}
void ActiveObject::setManipulator(Manipulator *_manipulator)
{
m_manipulator = _manipulator;
}
void ActiveObject::setState(ActiveObject::AOState _state)
{
m_state = _state;
}
| 26.906716 | 108 | 0.578561 | [
"transform"
] |
c37aebd3c3a2fa769314aaedf18dffc1a5b73fc7 | 1,096 | cpp | C++ | src/JsonWrapper.cpp | ShixiongQi/HElib | 9973ccc68a292d5c52388eca40eac08ae11d0263 | [
"Apache-2.0"
] | 992 | 2019-04-07T01:05:10.000Z | 2022-03-30T22:42:36.000Z | src/JsonWrapper.cpp | maliasadi/HElib | 7b919ce4ff22a04f1fb394d875172b91ae2c4c11 | [
"Apache-2.0"
] | 180 | 2019-04-29T20:19:22.000Z | 2022-03-31T13:11:15.000Z | src/JsonWrapper.cpp | maliasadi/HElib | 7b919ce4ff22a04f1fb394d875172b91ae2c4c11 | [
"Apache-2.0"
] | 289 | 2019-04-08T15:22:21.000Z | 2022-03-28T21:27:52.000Z | #include <helib/JsonWrapper.h>
#include <helib/assertions.h>
#include <string>
#include "io.h"
#include <json.hpp>
using json = ::nlohmann::json;
namespace helib {
std::string JsonWrapper::pretty(long indent) const
{
try {
auto j = std::any_cast<json>(this->json_obj);
return j.dump(indent);
} catch (const std::bad_any_cast& e) {
throw LogicError(std::string("Bad cast to a JSON object: \n\t") + e.what());
}
}
std::string JsonWrapper::toString() const
{
try {
auto j = std::any_cast<json>(this->json_obj);
return j.dump();
} catch (const std::bad_any_cast& e) {
throw LogicError(std::string("Bad cast to a JSON object: \n\t") + e.what());
}
}
JsonWrapper JsonWrapper::at(const std::string& key) const
{
try {
auto j = std::any_cast<json>(this->json_obj);
return wrap(j.at(key));
} catch (const std::bad_any_cast& e) {
throw LogicError(std::string("Bad cast to a JSON object: \n\t") + e.what());
}
}
std::ostream& operator<<(std::ostream& str, const JsonWrapper& wrapper)
{
return str << wrapper.toString();
}
} // namespace helib
| 22.833333 | 80 | 0.648723 | [
"object"
] |
c384a195f8ce6b56039626f9e4634a2474d7b47f | 11,632 | cpp | C++ | ref/src/Chapter11/NEAT Sweepers/phenotype.cpp | kugao222/geneticAlgorithmInLua | 9bfd2a443f9492759027791a2b2b41b9467241b2 | [
"MIT"
] | null | null | null | ref/src/Chapter11/NEAT Sweepers/phenotype.cpp | kugao222/geneticAlgorithmInLua | 9bfd2a443f9492759027791a2b2b41b9467241b2 | [
"MIT"
] | null | null | null | ref/src/Chapter11/NEAT Sweepers/phenotype.cpp | kugao222/geneticAlgorithmInLua | 9bfd2a443f9492759027791a2b2b41b9467241b2 | [
"MIT"
] | null | null | null | #include "phenotype.h"
//------------------------------------Sigmoid function------------------------
//
//----------------------------------------------------------------------------
float Sigmoid(float netinput, float response)
{
return ( 1 / ( 1 + exp(-netinput / response)));
}
//--------------------------------- ctor ---------------------------------
//
//------------------------------------------------------------------------
CNeuralNet::CNeuralNet(vector<SNeuron*> neurons,
int depth):m_vecpNeurons(neurons),
m_iDepth(depth)
{}
//--------------------------------- dtor ---------------------------------
//
//------------------------------------------------------------------------
CNeuralNet::~CNeuralNet()
{
//delete any live neurons
for (int i=0; i<m_vecpNeurons.size(); ++i)
{
if (m_vecpNeurons[i])
{
delete m_vecpNeurons[i];
m_vecpNeurons[i] = NULL;
}
}
}
//----------------------------------Update--------------------------------
// takes a list of doubles as inputs into the network then steps through
// the neurons calculating each neurons next output.
//
// finally returns a std::vector of doubles as the output from the net.
//------------------------------------------------------------------------
vector<double> CNeuralNet::Update(const vector<double> &inputs,
const run_type type)
{
//create a vector to put the outputs into
vector<double> outputs;
//if the mode is snapshot then we require all the neurons to be
//iterated through as many times as the network is deep. If the
//mode is set to active the method can return an output after
//just one iteration
int FlushCount = 0;
if (type == snapshot)
{
FlushCount = m_iDepth;
}
else
{
FlushCount = 1;
}
//iterate through the network FlushCount times
for (int i=0; i<FlushCount; ++i)
{
//clear the output vector
outputs.clear();
//this is an index into the current neuron
int cNeuron = 0;
//first set the outputs of the 'input' neurons to be equal
//to the values passed into the function in inputs
while (m_vecpNeurons[cNeuron]->NeuronType == input)
{
m_vecpNeurons[cNeuron]->dOutput = inputs[cNeuron];
++cNeuron;
}
//set the output of the bias to 1
m_vecpNeurons[cNeuron++]->dOutput = 1;
//then we step through the network a neuron at a time
while (cNeuron < m_vecpNeurons.size())
{
//this will hold the sum of all the inputs x weights
double sum = 0;
//sum this neuron's inputs by iterating through all the links into
//the neuron
for (int lnk=0; lnk<m_vecpNeurons[cNeuron]->vecLinksIn.size(); ++lnk)
{
//get this link's weight
double Weight = m_vecpNeurons[cNeuron]->vecLinksIn[lnk].dWeight;
//get the output from the neuron this link is coming from
double NeuronOutput =
m_vecpNeurons[cNeuron]->vecLinksIn[lnk].pIn->dOutput;
//add to sum
sum += Weight * NeuronOutput;
}
//now put the sum through the activation function and assign the
//value to this neuron's output
m_vecpNeurons[cNeuron]->dOutput =
Sigmoid(sum, m_vecpNeurons[cNeuron]->dActivationResponse);
if (m_vecpNeurons[cNeuron]->NeuronType == output)
{
//add to our outputs
outputs.push_back(m_vecpNeurons[cNeuron]->dOutput);
}
//next neuron
++cNeuron;
}
}//next iteration through the network
//the network needs to be flushed if this type of update is performed
//otherwise it is possible for dependencies to be built on the order
//the training data is presented
if (type == snapshot)
{
for (int n=0; n<m_vecpNeurons.size(); ++n)
{
m_vecpNeurons[n]->dOutput = 0;
}
}
//return the outputs
return outputs;
}
//----------------------------- TidyXSplits -----------------------------
//
// This is a fix to prevent neurons overlapping when they are displayed
//-----------------------------------------------------------------------
void TidyXSplits(vector<SNeuron*> &neurons)
{
//stores the index of any neurons with identical splitY values
vector<int> SameLevelNeurons;
//stores all the splitY values already checked
vector<double> DepthsChecked;
//for each neuron find all neurons of identical ySplit level
for (int n=0; n<neurons.size(); ++n)
{
double ThisDepth = neurons[n]->dSplitY;
//check to see if we have already adjusted the neurons at this depth
bool bAlreadyChecked = false;
for (int i=0; i<DepthsChecked.size(); ++i)
{
if (DepthsChecked[i] == ThisDepth)
{
bAlreadyChecked = true;
break;
}
}
//add this depth to the depths checked.
DepthsChecked.push_back(ThisDepth);
//if this depth has not already been adjusted
if (!bAlreadyChecked)
{
//clear this storage and add the neuron's index we are checking
SameLevelNeurons.clear();
SameLevelNeurons.push_back(n);
//find all the neurons with this splitY depth
for (int i=n+1; i<neurons.size(); ++i)
{
if (neurons[i]->dSplitY == ThisDepth)
{
//add the index to this neuron
SameLevelNeurons.push_back(i);
}
}
//calculate the distance between each neuron
double slice = 1.0/(SameLevelNeurons.size()+1);
//separate all neurons at this level
for (i=0; i<SameLevelNeurons.size(); ++i)
{
int idx = SameLevelNeurons[i];
neurons[idx]->dSplitX = (i+1) * slice;
}
}
}//next neuron to check
}
//----------------------------- DrawNet ----------------------------------
//
// creates a representation of the ANN on a device context
//
//------------------------------------------------------------------------
void CNeuralNet::DrawNet(HDC &surface, int Left, int Right, int Top, int Bottom)
{
//the border width
const int border = 10;
//max line thickness
const int MaxThickness = 5;
TidyXSplits(m_vecpNeurons);
//go through the neurons and assign x/y coords
int spanX = Right - Left;
int spanY = Top - Bottom - (2*border);
for (int cNeuron=0; cNeuron<m_vecpNeurons.size(); ++cNeuron)
{
m_vecpNeurons[cNeuron]->iPosX = Left + spanX*m_vecpNeurons[cNeuron]->dSplitX;
m_vecpNeurons[cNeuron]->iPosY = (Top - border) - (spanY * m_vecpNeurons[cNeuron]->dSplitY);
}
//create some pens and brushes to draw with
HPEN GreyPen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));
HPEN RedPen = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
HPEN GreenPen = CreatePen(PS_SOLID, 1, RGB(0, 200, 0));
HPEN OldPen = NULL;
//create a solid brush
HBRUSH RedBrush = CreateSolidBrush(RGB(255, 0, 0));
HBRUSH OldBrush = NULL;
OldPen = (HPEN) SelectObject(surface, RedPen);
OldBrush = (HBRUSH)SelectObject(surface, GetStockObject(HOLLOW_BRUSH));
//radius of neurons
int radNeuron = spanX/60;
int radLink = radNeuron * 1.5;
//now we have an X,Y pos for every neuron we can get on with the
//drawing. First step through each neuron in the network and draw
//the links
for (cNeuron=0; cNeuron<m_vecpNeurons.size(); ++cNeuron)
{
//grab this neurons position as the start position of each
//connection
int StartX = m_vecpNeurons[cNeuron]->iPosX;
int StartY = m_vecpNeurons[cNeuron]->iPosY;
//is this a bias neuron? If so, draw the link in green
bool bBias = false;
if (m_vecpNeurons[cNeuron]->NeuronType == bias)
{
bBias = true;
}
//now iterate through each outgoing link to grab the end points
for (int cLnk=0; cLnk<m_vecpNeurons[cNeuron]->vecLinksOut.size(); ++ cLnk)
{
int EndX = m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].pOut->iPosX;
int EndY = m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].pOut->iPosY;
//if link is forward draw a straight line
if( (!m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].bRecurrent) && !bBias)
{
int thickness = (int)(fabs(m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].dWeight));
Clamp(thickness, 0, MaxThickness);
HPEN Pen;
//create a yellow pen for inhibitory weights
if (m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].dWeight <= 0)
{
Pen = CreatePen(PS_SOLID, thickness, RGB(240, 230, 170));
}
//grey for excitory
else
{
Pen = CreatePen(PS_SOLID, thickness, RGB(200, 200, 200));
}
HPEN tempPen = (HPEN)SelectObject(surface, Pen);
//draw the link
MoveToEx(surface, StartX, StartY, NULL);
LineTo(surface, EndX, EndY);
SelectObject(surface, tempPen);
DeleteObject(Pen);
}
else if( (!m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].bRecurrent) && bBias)
{
SelectObject(surface, GreenPen);
//draw the link
MoveToEx(surface, StartX, StartY, NULL);
LineTo(surface, EndX, EndY);
}
//recurrent link draw in red
else
{
if ((StartX == EndX) && (StartY == EndY))
{
int thickness = (int)(fabs(m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].dWeight));
Clamp(thickness, 0, MaxThickness);
HPEN Pen;
//blue for inhibitory
if (m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].dWeight <= 0)
{
Pen = CreatePen(PS_SOLID, thickness, RGB(0,0,255));
}
//red for excitory
else
{
Pen = CreatePen(PS_SOLID, thickness, RGB(255, 0, 0));
}
HPEN tempPen = (HPEN)SelectObject(surface, Pen);
//we have a recursive link to the same neuron draw an ellipse
int x = m_vecpNeurons[cNeuron]->iPosX ;
int y = m_vecpNeurons[cNeuron]->iPosY - (1.5 * radNeuron);
Ellipse(surface, x-radLink, y-radLink, x+radLink, y+radLink);
SelectObject(surface, tempPen);
DeleteObject(Pen);
}
else
{
int thickness = (int)(fabs(m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].dWeight));
Clamp(thickness, 0, MaxThickness);
HPEN Pen;
//blue for inhibitory
if (m_vecpNeurons[cNeuron]->vecLinksOut[cLnk].dWeight <= 0)
{
Pen = CreatePen(PS_SOLID, thickness, RGB(0,0,255));
}
//red for excitory
else
{
Pen = CreatePen(PS_SOLID, thickness, RGB(255, 0, 0));
}
HPEN tempPen = (HPEN)SelectObject(surface, Pen);
//draw the link
MoveToEx(surface, StartX, StartY, NULL);
LineTo(surface, EndX, EndY);
SelectObject(surface, tempPen);
DeleteObject(Pen);
}
}
}
}
//now draw the neurons and their IDs
SelectObject(surface, RedBrush);
SelectObject(surface, GetStockObject(BLACK_PEN));
for (cNeuron=0; cNeuron<m_vecpNeurons.size(); ++cNeuron)
{
int x = m_vecpNeurons[cNeuron]->iPosX;
int y = m_vecpNeurons[cNeuron]->iPosY;
//display the neuron
Ellipse(surface, x-radNeuron, y-radNeuron, x+radNeuron, y+radNeuron);
}
//cleanup
SelectObject(surface, OldPen);
SelectObject(surface, OldBrush);
DeleteObject(RedPen);
DeleteObject(GreyPen);
DeleteObject(GreenPen);
DeleteObject(OldPen);
DeleteObject(RedBrush);
DeleteObject(OldBrush);
}
| 27.961538 | 95 | 0.567056 | [
"vector",
"solid"
] |
c38acdbb20e36692f8a999a7ece3a359b7397127 | 5,123 | cpp | C++ | vne/gamecontext.cpp | tuxzz/codebase | a7279a4b1e782811b12d4adc30f7381e7ed94b70 | [
"Unlicense"
] | null | null | null | vne/gamecontext.cpp | tuxzz/codebase | a7279a4b1e782811b12d4adc30f7381e7ed94b70 | [
"Unlicense"
] | null | null | null | vne/gamecontext.cpp | tuxzz/codebase | a7279a4b1e782811b12d4adc30f7381e7ed94b70 | [
"Unlicense"
] | null | null | null | #include "gamecontext.hpp"
#include "commandbase.hpp"
#include "corelib/ratiohub.hpp"
#include <QVariant>
GameContext::GameContext(QObject *parent) : QObject(parent)
{
m_commandTimerRatioHub = new RatioHub();
m_pc = 0;
m_running = false;
m_nextStep = false;
}
GameContext::~GameContext()
{
for(CommandBase *cmd:m_commandList)
{
requestStop();
delete cmd;
}
delete m_commandTimerRatioHub;
}
QVariant GameContext::globalVariable(const QString &name) const
{ return m_globalVariableDict.value(name); }
bool GameContext::hasGlobalVariable(const QString &name) const
{ return m_globalVariableDict.contains(name); }
bool GameContext::removeGlobalVariable(const QString &name)
{ return static_cast<bool>(m_globalVariableDict.remove(name)); }
void GameContext::trySetGlobalVariable(const QString &name, const QVariant &val)
{
if(!hasGlobalVariable(name))
setGlobalVariable(name, val);
}
void GameContext::setGlobalVariable(const QString &name, const QVariant &val)
{ m_localVariableDict.insert(name, val); }
QVariant GameContext::localVariable(const QString &name) const
{ return m_localVariableDict.value(name); }
bool GameContext::hasLocalVariable(const QString &name) const
{ return m_localVariableDict.contains(name); }
bool GameContext::removeLocalVariable(const QString &name)
{ return static_cast<bool>(m_localVariableDict.remove(name)); }
void GameContext::trySetLocalVariable(const QString &name, const QVariant &val)
{
if(!hasLocalVariable(name))
setLocalVariable(name, val);
}
void GameContext::setLocalVariable(const QString &name, const QVariant &val)
{ m_localVariableDict.insert(name, val); }
void GameContext::clearLocalVariable()
{ m_localVariableDict.clear(); }
RatioHub *GameContext::commandTimerRatioHub() const
{ return m_commandTimerRatioHub; }
void GameContext::setView(const QString &name, QObject *object)
{ m_viewDict.insert(name, object); }
QObject *GameContext::view(const QString &name) const
{ return m_viewDict.value(name, nullptr); }
void GameContext::setCommandList(const GameContext::CommandList &l)
{
auto b = l.begin();
auto e = l.end();
for(auto it = b; it < e; ++it)
{
auto cmd = *it;
cmd->setContext(this);
cmd->setPosition(it - b);
}
m_commandList = l;
}
GameContext::CommandList GameContext::commandList() const
{ return m_commandList; }
int GameContext::pc() const
{ return m_pc; }
void GameContext::setPC(int v)
{
Q_ASSERT(v >= 0);
m_pc = v;
}
void GameContext::exec()
{
if(!m_running)
{
m_nextStep = true;
m_running = true;
emit runningStateChanged(true);
CommandBase *cmd = nullptr;
while(m_nextStep && m_pc < m_commandList.size() && (cmd == nullptr || cmd->type() != CommandBase::AsyncWaiting))
{
cmd = m_commandList.at(m_pc);
if(cmd->type() != CommandBase::Sync)
m_unfinishedCommandList.append(cmd);
++m_pc;
m_nextStep = cmd->exec();
if(m_running && m_unfinishedCommandList.isEmpty())
{
m_running = false;
emit runningStateChanged(false);
}
}
}
}
void GameContext::execSingleStep()
{
if(!m_running)
{
m_nextStep = false;
m_running = true;
emit runningStateChanged(true);
CommandBase *cmd = m_commandList.at(m_pc);
if(cmd->type() != CommandBase::Sync)
m_unfinishedCommandList.append(cmd);
++m_pc;
cmd->exec();
if(m_running && m_unfinishedCommandList.isEmpty())
{
m_running = false;
emit runningStateChanged(false);
}
}
}
void GameContext::requestStop()
{
if(m_running)
{
m_nextStep = false;
for(auto cmd:m_unfinishedCommandList)
cmd->requestStop();
}
}
bool GameContext::isRunning() const
{ return m_running; }
void GameContext::onCommandFinished(int pc)
{
for(auto it = m_unfinishedCommandList.begin(); it < m_unfinishedCommandList.end(); ++it)
{
CommandBase *cmd = *it;
if(cmd->position() == pc)
{
m_unfinishedCommandList.erase(it);
break;
}
}
auto cmd = m_commandList.at(pc);
Q_ASSERT(cmd->type() != CommandBase::Sync);
if(cmd->type() == CommandBase::AsyncWaiting)
{
CommandBase *cmd = nullptr;
while(m_nextStep && m_pc < m_commandList.size() && (cmd == nullptr || cmd->type() != CommandBase::AsyncWaiting))
{
cmd = m_commandList.at(m_pc);
if(cmd->type() != CommandBase::Sync)
m_unfinishedCommandList.append(cmd);
++m_pc;
m_nextStep = cmd->exec();
}
}
if(m_running && m_unfinishedCommandList.isEmpty())
{
m_running = false;
emit runningStateChanged(false);
}
}
| 27.395722 | 121 | 0.616436 | [
"object"
] |
c3a675c9ca62a638ee3bb209b1c021e0e2c13baa | 16,686 | cc | C++ | src/libemane/commonphyheader.cc | weston-nrl/emane | 763a703c62693fbbdeec6def3cd05de7fbf4e660 | [
"BSD-3-Clause"
] | 114 | 2015-04-10T18:29:45.000Z | 2022-03-24T20:22:35.000Z | src/libemane/commonphyheader.cc | weston-nrl/emane | 763a703c62693fbbdeec6def3cd05de7fbf4e660 | [
"BSD-3-Clause"
] | 184 | 2015-01-06T15:33:54.000Z | 2022-03-24T22:17:56.000Z | src/libemane/commonphyheader.cc | weston-nrl/emane | 763a703c62693fbbdeec6def3cd05de7fbf4e660 | [
"BSD-3-Clause"
] | 34 | 2015-04-15T14:13:18.000Z | 2022-03-16T11:05:30.000Z | /*
* Copyright (c) 2013,2016 - Adjacent Link LLC, Bridgewater, New Jersey
* 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 Adjacent Link LLC 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 "emane/commonphyheader.h"
#include "commonphyheader.pb.h"
class EMANE::CommonPHYHeader::Implementation
{
public:
Implementation(RegistrationId registrationId,
std::uint16_t u16SubId,
std::uint16_t u16SequenceNumber,
const TimePoint & txTime,
const FrequencyGroups & frequencyGroups,
const Antennas & transmitAntennas,
const Transmitters & transmitters,
const std::pair<FilterData,bool> & optionalFilterData):
registrationId_{registrationId},
u16SubId_{u16SubId},
u16SequenceNumber_{u16SequenceNumber},
txTime_{txTime},
frequencyGroups_{frequencyGroups},
transmitAntennas_{transmitAntennas},
transmitters_{transmitters},
optionalFilterData_{optionalFilterData}{}
RegistrationId getRegistrationId() const
{
return registrationId_;
}
std::uint16_t getSubId() const
{
return u16SubId_;
}
const std::pair<FilterData,bool> & getOptionalFilterData() const
{
return optionalFilterData_;
}
const TimePoint & getTxTime() const
{
return txTime_;
}
std::uint16_t getSequenceNumber() const
{
return u16SequenceNumber_;
}
const FrequencyGroups & getFrequencyGroups() const
{
return frequencyGroups_;
}
const Antennas & getTransmitAntennas() const
{
return transmitAntennas_;
}
const Transmitters & getTransmitters() const
{
return transmitters_;
}
private:
RegistrationId registrationId_;
std::uint16_t u16SubId_;
std::uint16_t u16SequenceNumber_;
TimePoint txTime_;
FrequencyGroups frequencyGroups_;
Antennas transmitAntennas_;
Transmitters transmitters_;
std::pair<FilterData,bool> optionalFilterData_;
};
EMANE::CommonPHYHeader::CommonPHYHeader(UpstreamPacket & pkt)
{
if(pkt.length() >= sizeof(decltype(pkt.stripLengthPrefixFraming())))
{
std::uint16_t u16HeaderLength{pkt.stripLengthPrefixFraming()};
if(pkt.length() >= u16HeaderLength)
{
EMANEMessage::CommonPHYHeader msg;
if(!msg.ParseFromArray(pkt.get(),u16HeaderLength))
{
throw SerializationException("unable to deserialize CommonPHYHeader");
}
Transmitters transmitters{};
for(const auto & transmitter : msg.transmitters())
{
transmitters.push_back({static_cast<NEMId>(transmitter.nemid()),
transmitter.powerdbm()});
}
FrequencyGroups frequencyGroups{};
for(const auto & group : msg.frequencygroups())
{
FrequencySegments frequencySegments{};
for(const auto & segment : group.frequencysegments())
{
if(segment.has_powerdbm())
{
frequencySegments.push_back({segment.frequencyhz(),
segment.powerdbm(),
Microseconds(segment.durationmicroseconds()),
Microseconds(segment.offsetmicroseconds())});
}
else
{
frequencySegments.push_back({segment.frequencyhz(),
Microseconds(segment.durationmicroseconds()),
Microseconds(segment.offsetmicroseconds())});
}
}
frequencyGroups.push_back(frequencySegments);
}
RegistrationId registrationId{static_cast<RegistrationId>(msg.registrationid())};
std::uint16_t u16SubId{static_cast<std::uint16_t>(msg.subid())};
std::uint16_t u16SequenceNumber{static_cast<std::uint16_t>(msg.sequencenumber())};
TimePoint txTime{static_cast<Microseconds>(msg.txtimemicroseconds())};
std::pair<FilterData,bool> optionalFilterData{{},msg.has_filterdata()};
if(optionalFilterData.second)
{
optionalFilterData.first = msg.filterdata();
}
Antennas transmitAntennas{};
for(const auto & transmitAntenna : msg.transmitantennas())
{
if(transmitAntenna.has_fixedgaindbi())
{
auto antenna = Antenna::createIdealOmni(transmitAntenna.antennaindex(),
transmitAntenna.fixedgaindbi());
antenna.setFrequencyGroupIndex(static_cast<FrequencyGroupIndex>(transmitAntenna.frequencygroupindex()));
antenna.setBandwidthHz(transmitAntenna.bandwidthhz());
transmitAntennas.push_back(std::move(antenna));
}
else
{
if(transmitAntenna.has_pointing())
{
const auto & pointing = transmitAntenna.pointing();
auto antenna = Antenna::createProfileDefined(transmitAntenna.antennaindex(),
{static_cast<AntennaProfileId>(pointing.profileid()),
pointing.azimuthdegrees(),
pointing.elevationdegrees()});
antenna.setFrequencyGroupIndex(static_cast<FrequencyGroupIndex>(transmitAntenna.frequencygroupindex()));
antenna.setBandwidthHz(transmitAntenna.bandwidthhz());
transmitAntennas.push_back(std::move(antenna));
}
else
{
auto antenna = Antenna::createProfileDefined(transmitAntenna.antennaindex());
antenna.setFrequencyGroupIndex(static_cast<FrequencyGroupIndex>(transmitAntenna.frequencygroupindex()));
antenna.setBandwidthHz(transmitAntenna.bandwidthhz());
transmitAntennas.push_back(std::move(antenna));
}
}
}
pImpl_.reset(new Implementation{registrationId,
u16SubId,
u16SequenceNumber,
txTime,
frequencyGroups,
transmitAntennas,
transmitters,
optionalFilterData});
}
else
{
throw SerializationException("CommonPHYHeader not large enough for header data");
}
// strip common phy header from pkt
pkt.strip(u16HeaderLength);
}
else
{
throw SerializationException("CommonPHYHeader not large enough for header size data");
}
}
EMANE::CommonPHYHeader::CommonPHYHeader(RegistrationId registrationId,
std::uint16_t u16SubId,
std::uint16_t u16SequenceNumber,
const TimePoint & txTime,
const FrequencyGroups & frequencyGroups,
const Antennas & transmitAntennas,
const Transmitters & transmitters,
const std::pair<FilterData,bool> & optionalFilterData):
pImpl_{new Implementation{registrationId,
u16SubId,
u16SequenceNumber,
txTime,
frequencyGroups,
transmitAntennas,
transmitters,
optionalFilterData}}
{}
EMANE::CommonPHYHeader::CommonPHYHeader(CommonPHYHeader&& rvalue):
pImpl_(std::move(rvalue.pImpl_))
{}
EMANE::CommonPHYHeader::~CommonPHYHeader(){}
EMANE::RegistrationId EMANE::CommonPHYHeader::getRegistrationId() const
{
return pImpl_->getRegistrationId();
}
std::uint16_t EMANE::CommonPHYHeader::getSubId() const
{
return pImpl_->getSubId();
}
const std::pair<EMANE::FilterData,bool> &
EMANE::CommonPHYHeader::getOptionalFilterData() const
{
return pImpl_->getOptionalFilterData();
}
const EMANE::TimePoint & EMANE::CommonPHYHeader::getTxTime() const
{
return pImpl_->getTxTime();
}
EMANE::Durations EMANE::CommonPHYHeader::getDurations() const
{
std::vector<EMANE::Microseconds> durations{};
for(const auto & group : pImpl_->getFrequencyGroups())
{
Microseconds start = Microseconds::zero();
Microseconds end = Microseconds::zero();
for(const auto & segment : group)
{
// the offset
const auto & offset = segment.getOffset();
const auto & duration = segment.getDuration();
// duration position
const auto relative = offset + duration;
// get the begin time
if(offset < start)
{
start = offset;
}
// get the end time
if(relative > end)
{
end = relative;
}
}
// the total duration with gaps/overlap
durations.push_back(end - start);
}
return durations;
}
std::uint16_t EMANE::CommonPHYHeader::getSequenceNumber() const
{
return pImpl_->getSequenceNumber();
}
const EMANE::FrequencyGroups &
EMANE::CommonPHYHeader::getFrequencyGroups() const
{
return pImpl_->getFrequencyGroups();
}
const EMANE::Antennas &
EMANE::CommonPHYHeader::getTransmitAntennas() const
{
return pImpl_->getTransmitAntennas();
}
const EMANE::Transmitters & EMANE::CommonPHYHeader::getTransmitters() const
{
return pImpl_->getTransmitters();
}
void EMANE::CommonPHYHeader::prependTo(DownstreamPacket & pkt) const
{
EMANEMessage::CommonPHYHeader msg{};
msg.set_registrationid(pImpl_->getRegistrationId());
msg.set_subid(pImpl_->getSubId());
msg.set_sequencenumber(pImpl_->getSequenceNumber());
msg.set_txtimemicroseconds(std::chrono::duration_cast<Microseconds>(pImpl_->getTxTime().time_since_epoch()).count());
const auto & optionalFilterData = pImpl_->getOptionalFilterData();
if(optionalFilterData.second)
{
msg.set_filterdata(optionalFilterData.first);
}
for(const auto & transmitter : pImpl_->getTransmitters())
{
auto pTransmitter = msg.add_transmitters();
pTransmitter->set_nemid(transmitter.getNEMId());
pTransmitter->set_powerdbm(transmitter.getPowerdBm());
}
for(const auto & group : pImpl_->getFrequencyGroups())
{
auto pGroup = msg.add_frequencygroups();
for(const auto & segment : group)
{
auto pSegment = pGroup->add_frequencysegments();
pSegment->set_frequencyhz(segment.getFrequencyHz());
pSegment->set_offsetmicroseconds(segment.getOffset().count());
pSegment->set_durationmicroseconds(segment.getDuration().count());
if(segment.getPowerdBm().second)
{
pSegment->set_powerdbm(segment.getPowerdBm().first);
}
}
}
for(const auto & transmitAntenna : pImpl_->getTransmitAntennas())
{
auto pTransmitAntenna = msg.add_transmitantennas();
pTransmitAntenna->set_antennaindex(transmitAntenna.getIndex());
pTransmitAntenna->set_frequencygroupindex(transmitAntenna.getFrequencyGroupIndex());
pTransmitAntenna->set_bandwidthhz(transmitAntenna.getBandwidthHz());
if(transmitAntenna.isIdealOmni())
{
pTransmitAntenna->set_fixedgaindbi(transmitAntenna.getFixedGaindBi().first);
}
else
{
auto pointing = transmitAntenna.getPointing();
if(pointing.second)
{
auto pPointing = pTransmitAntenna->mutable_pointing();
pPointing->set_profileid(pointing.first.getProfileId());
pPointing->set_azimuthdegrees(pointing.first.getAzimuthDegrees());
pPointing->set_elevationdegrees(pointing.first.getElevationDegrees());
}
}
}
std::string sSerialization;
if(!msg.SerializeToString(&sSerialization))
{
throw SerializationException("unable to serialize CommonPHYHeader");
}
// prepend order is important
pkt.prepend(sSerialization.c_str(),sSerialization.size());
pkt.prependLengthPrefixFraming(sSerialization.size());
}
EMANE::Strings EMANE::CommonPHYHeader::format() const
{
Strings sFormat{{"regid: " + std::to_string( pImpl_->getRegistrationId())},
{"seq: " + std::to_string(pImpl_->getSequenceNumber())},
{"tx time: " + std::to_string(std::chrono::duration_cast<DoubleSeconds>(pImpl_->getTxTime().time_since_epoch()).count())}};
int i{};
for(const auto & group : pImpl_->getFrequencyGroups())
{
sFormat.push_back("freq group: " + std::to_string(i++));
for(const auto & segment : group)
{
sFormat.push_back("freq: " + std::to_string(segment.getFrequencyHz()));
sFormat.push_back("duration: " + std::to_string(segment.getDuration().count()));
sFormat.push_back("offset: " + std::to_string(segment.getOffset().count()));
if(segment.getPowerdBm().second)
{
sFormat.push_back("segment power: " + std::to_string(segment.getPowerdBm().first));
}
}
}
for(const auto & transmitAntenna : pImpl_->getTransmitAntennas())
{
sFormat.push_back("antenna: " + std::to_string(transmitAntenna.getIndex()));
sFormat.push_back("freq index: " + std::to_string(transmitAntenna.getFrequencyGroupIndex()));
sFormat.push_back("bandwidth: " + std::to_string(transmitAntenna.getBandwidthHz()));
if(transmitAntenna.isIdealOmni())
{
sFormat.push_back("fixed gain: " + std::to_string(transmitAntenna.getFixedGaindBi().second));
}
else
{
const auto & pointing = transmitAntenna.getPointing();
if(pointing.second)
{
sFormat.push_back("profile id: " + std::to_string(pointing.first.getProfileId()));
sFormat.push_back("azimuth: " + std::to_string(pointing.first.getAzimuthDegrees()));
sFormat.push_back("elevation: " + std::to_string(pointing.first.getElevationDegrees()));
}
}
}
for(const auto & transmitter : pImpl_->getTransmitters())
{
sFormat.push_back("src: " + std::to_string(transmitter.getNEMId()));
sFormat.push_back("transmitter power: " + std::to_string(transmitter.getPowerdBm()));
}
const auto & optionalFilterData = pImpl_->getOptionalFilterData();
if(optionalFilterData.second)
{
sFormat.push_back("fitler data bytes: " + std::to_string(optionalFilterData.first.size()));
}
return sFormat;
}
| 33.845842 | 142 | 0.607575 | [
"vector"
] |
c3a8d09ea02847cfb19a533dfd236b6f00ee7bf4 | 1,882 | cpp | C++ | C++/MakeYourOwnVector/MakeYourOwnVector/main.cpp | znickle24/ZanderProjects | 674d72d2cba888d0605d9bc8230ecee724ec09b1 | [
"MIT"
] | null | null | null | C++/MakeYourOwnVector/MakeYourOwnVector/main.cpp | znickle24/ZanderProjects | 674d72d2cba888d0605d9bc8230ecee724ec09b1 | [
"MIT"
] | null | null | null | C++/MakeYourOwnVector/MakeYourOwnVector/main.cpp | znickle24/ZanderProjects | 674d72d2cba888d0605d9bc8230ecee724ec09b1 | [
"MIT"
] | null | null | null | //
// main.cpp
// MakeYourOwnVector
//
// Created by Zander Nickle on 9/11/17.
// Copyright © 2017 Zander Nickle. All rights reserved.
//
#include <iostream>
#include "StructsAndFunctions.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
// test 1 to make sure a vector is made and to make sure that it is filled with the correct info.
vectorInfo<int> test1 = vectorInfo<int>{5};
test1.pushBack(1);
test1.pushBack(2);
test1.pushBack(3);
cout << test1.getI(0) << endl;
cout << test1.getI(1) << endl;
cout << test1.getI(2) << endl;
//test to see if the value at 3 is changed and reprint that data.
// test1.popBack(3);
// cout << test1.getI(3);
//make sure that the value at index 1 is 2
cout << test1.getI(1) << endl;
vectorInfo<int> test2 = vectorInfo<int>{3};
test2.pushBack(1);
test2.pushBack(3);
test2.pushBack(5);
test2.pushBack(7);
//testing copy method (public)
vectorInfo<int> v1 = vectorInfo<int>{3};
v1.pushBack(2);
v1.pushBack(4);
v1.pushBack(6);
vectorInfo<int> v2 = v1;
cout << v2.getI(2) << endl;
cout << v2.getI(1) << endl;
//testing = operator method (public)
vectorInfo<int> v3 = vectorInfo<int> {25};
v3.pushBack(1);
v3.pushBack(3);
v3.pushBack(5);
v3.pushBack(7);
v3.pushBack(9);
vectorInfo<int> v4 = vectorInfo<int> {25};
v4 = v3;
cout << v4.getI(0) << endl;
cout << v4.getI(1) << endl;
cout << v4.getI(2) << endl;
vectorInfo<int> v6 = vectorInfo<int> {4};
v6.pushBack(3);
v6.pushBack(1);
v6.pushBack(8);
v6.pushBack(2);
v6.sortVec();
cout << v6[0] << endl;
cout << v6[1] << endl;
cout << v6[2] << endl;
cout << v6[3] << endl;
return 0;
}
| 21.632184 | 101 | 0.55898 | [
"vector"
] |
ce82e2da5171fd4ca3db7c914c761d16c0245225 | 19,986 | cpp | C++ | homeworks/HW3Source/HW 3/main.cpp | anshuman1811/cs687-reinforcementlearning | cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481 | [
"MIT"
] | null | null | null | homeworks/HW3Source/HW 3/main.cpp | anshuman1811/cs687-reinforcementlearning | cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481 | [
"MIT"
] | null | null | null | homeworks/HW3Source/HW 3/main.cpp | anshuman1811/cs687-reinforcementlearning | cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481 | [
"MIT"
] | null | null | null | /*
This file includes all of the code for HW3. The lines that you must fill in are in one location, labeled
with "// TODO".
If you are new to C++, please follow some online tutorials to get a feel for C++. Don't worry about "pointers"
or "makefiles", as you won't need to know about them for these assignments.
Some pointers:
1. In C++ you can compile in "release" or "debug" mode In Visual Studio and CLion, you should see a drop-down box
near the top of the IDE that says "Debug" or "Release". Changing this changes the configuration. Debug runs slower
(still more than fast enough for this assignment), but allows you to place break-points in your code, step through
your code as it runs watching variable values change, and also provides more information if your code crashes. Release
results in code that runs *much* faster. However, it will give cryptic errors when it crashes (not telling you the
line that it crashed on for example) and does not allow you to use most of the features of your debugger. Generally,
you use debug mode when soemthing isn't working right or when first running your code, and then switch to release.
2. In visual studio, hit F7 to compile your code. If there are errors, hit F4 to cycle through the errors. Run your code with F5.
If you are in release mode, run with ctrl+F5. Place a breakpoint with F9, step forwards with F10. Right click a breakpoint to set a
condition, like to only break when s=22. F11 will step into a function, while Shift+F11 will step out of the current function. Also, if you
select a variable or function in the editor and hit F12, it will take you to the definition of that function/variable. If you right click a
variable or function, you can click "peek definition" to bring up a small window showing you the definition of that term.
3. In CLion, build by navigating to "build" at the top, and selecting the option "build". Then run with "Run-> Debug 'Project Name'", where
this project's name is "CLion". If you are in release mode, use "Run->Run 'Project Name'". Under the run menu you can also find the commands
for adding breakpoints.
4. I've added comments into the document below so that you can start to get an idea for how this code and C++ work. Start with the function "main"
near the bottom of this file.
5. This code uses "Eigen", a linear algebra library for C++. Once you've looked a bit at C++ in general below, check out the getting started page for Eigen: http://eigen.tuxfamily.org/dox/GettingStarted.html
Specifically, you'll be using VectorXd and MatrixXd objects. Notice that for a VectorXd v, you can reference the i'th element as v[i] or v(i). For a MatrixXd m, you
can reference the i,j'th element as m(i,j), but not m[i,j]. Also, notice that you can call m.row(i), which returns an object essentially like a VectorXd that corresponds to the i'th row.
You can call v.transpose() on a vector to transpose it. You can call v.dot(u) for two vectors v and u. You can call v.maxCoeff() to get the largest element of v, or v.minCoeff() to get the smallest.
Notice that with vector objects v, you must write v[i], not v(i) like you can write with VectorXd objects. Also, you cannot "combine" vector and VectorXd objects - they are entirely different beasts.
E.g., you can't write v.dot(u) if v and u are not both VectorXd objects. Think of vector objects as C++'s standard "array" object, which is not meant for linear algebra.
6. Once you're looked into the code below, notice that P is a vector, each element of which is a matrix. To get P(s,a,s'), you need to write P[s](a,s'). You can grab a whole row with P[s].row(a), for example.
*/
// These statements are saying to include source code that is stored somewhere else (these come with most compilers)
#include <iostream> // For console i/o
#include <vector> // For arrays that we don't use for linear algebra
#include <string> // For strings used in file names
#include <fstream> // For file i/o
#include <iomanip> // For setprecision when printing numbers to the console or files
// This statement includes a library for linear algebra. We included this in the "lib" folder, and have set up your project
// to look in this folder for the library.
#include <Eigen/Dense> // For vectors and matrices that we use for linear algebra
using namespace std; // Some terms below are "inside" std. For example, cout, cin, and endl. Normally you have to write std::cout. This line makes it so that you don't have to write std:: before everything you are using from standard libraries.
using namespace Eigen; // Like the above line, but for the Eigen library that we are using for linear algebra. Instead of Eigen::VectorXd, you can just write VectorXd with this.
/*
This class represents an MDP with a finite number of states and actions.
*/
class MDP
{
public: // You can declare functions and variables to be "private", meaning that you can only reference them inside of the class. This "public" means that anywhere else that you have an MDP object, you can reference these functions and variables.
// Member variables of the MDP class.
int numStates; // States are integers in the range 0 to numStates-1
int numActions; // Actions are integers in the range 0 to numActions-1
vector<MatrixXd> P; // [numStates][numActions][numStates]. We write vector<Foo> to create a vector (C++'s array) of Foo objects. So, this is an array of "MatrixXd" objects. It will have length "numStates", and the matrices it holds will have numActions rows and numStates columns.
MatrixXd R; // [numStates][numActions]
double gamma; // "double" means "floating point, typically 64-bit. "float" means "floating point, typically 32-bit".
// An MDP object has this function, which loads an MDP from the file with the specified file name. Here "void" means this function doesn't return anything, const means that "fileName" cannot be changed within this function, & means that when
// you call this function you don't pass a copy of the string "fileName", you pass the actual object "fileName", so any changes to it within the function would change it outside the function. However, "const" ensures that it won't be changed.
void loadFromFile(const string& fileName)
{
// ifstream = input file stream. This is the object for reading from files.
ifstream in(fileName.c_str()); // This creates an ifstream object and calls the "constructor" for the object - a function called when the object is created with the argument fileName.c_str(). The constructor for ifstream is designed to open the provided fileName. The constructor expects a char* (a default C++ string type). They are a pain to work with, so we are using "string" types. The .c_str() says to convert the string to a char* before passing it.
in >> numStates >> numActions;
cout << "numStates = " << numStates << endl;
// Resize P to be an std::vector containing numStates matrices, each of which has numActions rows and numStates cols. So, P[s](a,sPrime) is the probability of transitioning to sPrime from s when taking action a.
P.resize(numStates); // Make P a vector of length numStates.
// If we do not include brackets, for, while, if, else, etc. statements implicitly have brackets around the next line ONLY. So, the for loop below only includes the P[s] line. C++ doesn't care about white space, so tabs and spaces
// are just to help us see what is going on.
for (int s = 0; s < numStates; s++)
P[s].resize(numActions, numStates);
// Read in the transition probabilities. Notice that the outer loop is over actions. This loop order makes it easier to manually enter transition probabilities for gridworlds like 687Gridworld.txt
for (int a = 0; a < numActions; a++) // This for-loop only includes the next "line", which is really the next command
for (int s = 0; s < numStates; s++) // which is this for loop, which only includes the next line
for (int sPrime = 0; sPrime < numStates; sPrime++) // which is this for loop. So, these loops are all nested. The next for loops below use brackets to show an equivalent way of writing this (that takes more space)
in >> P[s](a, sPrime);
// Load the reward function
R.resize(numStates, numActions);
for (int s = 0; s < numStates; s++)
{
for (int a = 0; a < numActions; a++)
{
in >> R(s, a);
}
}
// Get the reward discount parameter.
in >> gamma;
// Close the input file - we are done reading from it.
in.close();
}
// Run a sanity check on a loaded MDP - can find some errors in a loaded MDP file.
bool sanityCheck()
{
// Make sure the different parameters take reasonable values
if ((numStates <= 0) || (numActions <= 0) || (gamma > 1) || (gamma < 0))
return false;
// Make sure that P(s,a,*) is a probability distribution
for (int s = 0; s < numStates; s++)
{
// Entries must all be in [0,1]
if ((P[s].maxCoeff() > 1) || (P[s].minCoeff() < 0))
return false;
// Sum over next-state probabilities must be one (with some error for floating point issues)
for (int a = 0; a < numActions; a++)
if (fabs(P[s].row(a).sum() - 1.0) > 0.0000001)
return false;
}
// All tests passed
return true;
}
};
/*
Run value iteration on the provided MDP. The output is the optimal value function.
M: MDP to run value iteration on
print: If set to true, valueIteration prints the sequence of value function approximations it produces.
epsilon: Tolerance parameter. We will terminate when every element of v_{k+1} is within epsilon of the corresponding element in v_{k}
The "=" value after epsilon is a default value - if you do not provide the epsilon parameter it will be set to this value automatically. If you do provide this argument to the function, this value will be replaced with the value you provide.
*/
VectorXd valueIteration(const MDP& M, const bool & print = false, const double& epsilon = 0.000000001)
{
// Create arrays for our current and new value function estimates, initialized to zero
VectorXd vCur = VectorXd::Zero(M.numStates), vNew(M.numStates); // VectorXd::Zero(n) is a vector of all zeros, of length n.
// Create array used when computing the max_a in the Bellman operator
VectorXd temp(M.numActions); // Create a vector, filled with unknown values for now, but of length M.numActions.
// Notice above "M.numActions" is how we reference the variable "numActions" in the MDP class we defined above. Similarly, M.sanityCheck() runes the sanityCheck function that we defined.
// Iteration loop:
for (int itCount = 0; true; itCount++)
{
// If the "print" argument is true, print out extra information.
if (print)
{
cout << "Value function estimate number " << itCount << ":" << endl << vCur.transpose() << endl << "Press enter to continue." << endl;
cin.ignore(cin.rdbuf()->in_avail()); getchar(); // Wait until user presses enter. If you're new to C++, don't worry about this line and why it is so complicated...
}
// For each state, compute vNew[s] given vCur.
for (int s = 0; s < M.numStates; s++)
{
// TODO: You must enter the code here. It should load vNew[s] (the value next value function estimate for state s) based on vCur (the previous value function estimate)
// and the information stored in the MDP object M. Hint: read the rest of this code and understand it. This assignment can be completed by inserting one line
// below (mine extends to column 76, including whitespace). The missing line resembles another line somewhere in this code.
// cout << "vCur:\n" << vCur.rows() << "," << vCur.cols()
// << "\nP[s]:\n" << M.P[s].rows() << "," << M.P[s].cols() <<
// endl;
// cout << "Dot product\n" << (M.P[s]*vCur).rows() << ","
// << (M.P[s]*vCur).cols() << endl;
// cout << "R(s)\n" << M.R.transpose().rows() << "," << M.R.transpose().cols() << endl;
vNew[s] = (M.R.transpose().col(s) + M.gamma*M.P[s]*vCur).maxCoeff();
}
// Check for termination. Take element-wise absolute value of (vNew-vCur). If the max element is <= epsilon, we are done.
// Note: Eigen provides the abs() function for array objects, not VectorXd objects. We can view the VectorXd as an array though, with the .array() function.
if ((vNew - vCur).array().abs().maxCoeff() <= epsilon)
{
cout << "Value iteration finished in " << itCount + 1 << " iterations." << endl;
break; // Break out of the while(true) loop
}
// Move vNew into vCur in preparation for next iteration of the while loop
vCur = vNew;
}
// Return the latest value function
return vNew;
}
// This function prints the optimal value function and optimal policies to a file. Epsilon is a tolerance parameter when checking if two
// actions are roughly equally optimal.
void print(const Eigen::VectorXd& vStar, const MDP& M, const string& fileName, const double & epsilon = 0.000000001)
{
ofstream out(fileName); // Open the file for printing
// Print vStar
out << "Optimal value function:" << endl;
out << setprecision(10) << vStar.transpose() << endl << endl; // Here "setprecision" comes from the <iomanip> include, and says how many decimals to include when printing.
// Compute and print the optimal policy for each state
VectorXd temp(M.numActions);
out << "Optimal policies:" << endl;
for (int s = 0; s < M.numStates; s++)
{
// From M, get the s'th row of the reward function, transpose it to be a column vector, add to it gamma (a floating poitn number) times the transition matrix for state s (which is a matrix with numActions rows and numStates cols) times the optmial value function (a column vector of length numStates)
temp = M.R.row(s).transpose() + M.gamma * M.P[s] * vStar; // Compute the expected return if each action is taken from this state and an optimal policy is followed thereafter
double maxActionValue = temp.maxCoeff(); // Get the largest expected return over all possible actions.
// Get all actions that achieve the maxActionValue
vector<int> optimalActions(0); // vector<int> is creating a vector object that holds "int" objects. The (0) here says initialize to length zero.
for (int a = 0; a < M.numActions; a++)
if (fabs(temp[a] -maxActionValue) < epsilon)
optimalActions.push_back(a); // You can treat an std::vector like a stack, pushing and popping.
// Print all actions that are optimal in this state
out << "[";
for (int i = 0; i < (int)optimalActions.size() - 1; i++) // optimalActions.size() is an unsigned int. We write "(int)" to cast this to a regular integer so that we can compare it to i. An alternative is to make i and "unsigned int"
out << optimalActions[i] << ",";
out << optimalActions[optimalActions.size() - 1] << "]\t"; // We handle the last action separately to not print a comma after it
}
// Close the output file.
out.close();
}
// Given a filename, load the file into an MDP, run sanity checks on this MDP, run value iteration, and print the result to a file.
void run(const string& fileName)
{
MDP M; // Where we will store the loaded MDP. This object is defined above in "class MDP".
VectorXd vStar; // Where we will store the optimal value function. This object is from the Eigen linear algebra library.
cout << "Loading " << fileName << " into MDP object..." << endl;
M.loadFromFile("../../../input/" + fileName); // In our MDP class we have a loadFromFile function that is called here. "input/" is a char*, the c++ built-in string. fileName is a standard library string. The + operator appends these and returns a standard library string. When new to C++, try to stick with standard library strings rather than using char*, except when manually entering a string in your code like here.
cout << "Loading complete. Running sanity checks." << endl;
if (M.sanityCheck()) // Without { }, if statements, while loops, for loops, etc. are only over the following line. If you want more than two subsequent lines to be in the if statement (while loop, for loop, else if statement, etc) then use { } as in the if-statement in main.
cout << "Sanity checks on MDP passed." << endl;
else
{
cout << "Sanity checks on MDP failed!" << endl;
cout << "Aborting this run." << endl;
return;
}
cout << "Running value iteration..." << endl;
// Comment out the upper line and uncomment the lower line to have value iteration print the value function estimates and wait for you to hit 'enter' after every iteration (can help when debugging).
vStar = valueIteration(M); // Run the value interation function that you will be writing. It is defined in valueIteration.hpp and implemented in valueIteration.cpp
//vStar = valueIteration(M, true); // Run the value interation function that you will be writing. It is defined in valueIteration.hpp and implemented in valueIteration.cpp
cout << "Printing results to file..." << endl;
print(vStar, M, "../../../output/" + fileName); // Prints the optimal value function and optimal policy to the specified file
cout << "Run on " << fileName << " complete." << endl << endl;
}
// Entry point for the C++ program - it begins execution here.
// argc will be the number of command line arguments + 1, and argv will be the path to the executable followed by
// all of the command line arguments. To complete this assignment you do not need to know about or use command line arguments.
// These are what *we* will use when testing your program.
//
// To provide command line arguments in visual studio (so you don't have to type the file name every time), click
// Project -> ValueIteration Properties -> Configuration Properties -> Debugging -> Command arguments.
// Enter into this box the arguments that you would like to pass, like:
// 687Gridworld.txt myTestMDP.txt
//
// Be sure in the properties box that the top left "Configuration" matches the configuration you are using (or do this for "all configurations", both release and debug).
int main(int argc, char* argv[])
{
if (argc == 1) // Check if there were no command line arguments (the first is the path to the running executable)
{
// Ask the user for a file name and run value iteration on it
string fileName; // This object is from the standard library and can store strings. It's a nice alternative to char*, the default string type in C++.
cout << "Enter file name (within input directory): "; // "cout" means "console out" -- print to the console. The "<<" is used to separate terms that should be printed. See some of the other cout statements above for examples.
cin >> fileName; // "console in" -- get input from the user.
run(fileName); // Above we created a function "run". This calls it. Notice that in C++ you can only call functions defined above your current location in the code. (You can get around this by "defining" a function in one place and then implementing it later - you only need it to be defined before it can be called. For now, if you are new to C++, just ensure that functions you want to call are above where you call them).
}
// else if -- if you want an "else if" block, it would be like this, as two words.
else
{
// Loop over the command line arguments, running value iteration on all of the listed files. Start with i=1 since argv[0] is the path to the running executable
for (int i = 1; i < argc; i++) // This is the format for a for-loop in C++. The first part declares an integer object i, and initializes it to one. The middle bit is the condition that, when satisfied, allows the loop to continue. The final part, i++, is shorthand for i=i+1.
run(argv[i]); // Call our run function.
}
cout << "Done." << endl;
} | 71.378571 | 459 | 0.702141 | [
"object",
"vector"
] |
ce992c3bf6012a511ff9208dbcb447e791e34692 | 25,637 | cpp | C++ | blast/src/objtools/readers/gtf_reader.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objtools/readers/gtf_reader.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objtools/readers/gtf_reader.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | /* $Id: gtf_reader.cpp 632531 2021-06-02 17:25:37Z ivanov $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Frank Ludwig
*
* File Description:
* GFF file reader
*
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbistd.hpp>
#include <util/line_reader.hpp>
#include <objects/general/Object_id.hpp>
#include <objects/general/User_object.hpp>
#include <objects/general/Dbtag.hpp>
#include <objects/seqloc/Seq_id.hpp>
#include <objects/seqloc/Seq_loc.hpp>
#include <objects/seqloc/Seq_interval.hpp>
#include <objects/seqloc/Seq_point.hpp>
#include <objects/seq/Seq_annot.hpp>
#include <objects/seq/Annot_id.hpp>
#include <objects/seq/Annot_descr.hpp>
#include <objects/seqfeat/SeqFeatData.hpp>
#include <objects/seqfeat/SeqFeatXref.hpp>
#include <objects/seqfeat/Seq_feat.hpp>
#include <objects/seqfeat/Gene_ref.hpp>
#include <objects/seqfeat/Genetic_code.hpp>
#include <objects/seqfeat/RNA_ref.hpp>
#include <objects/seqfeat/Gb_qual.hpp>
#include <objects/seqfeat/Feat_id.hpp>
#include <objtools/readers/gtf_reader.hpp>
#include "gtf_location_merger.hpp"
#include "reader_message_handler.hpp"
#include <algorithm>
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
// ----------------------------------------------------------------------------
bool CGtfReadRecord::xAssignAttributesFromGff(
const string& strGtfType,
const string& strRawAttributes )
// ----------------------------------------------------------------------------
{
vector< string > attributes;
xSplitGffAttributes(strRawAttributes, attributes);
for ( size_t u=0; u < attributes.size(); ++u ) {
string key, value;
string attribute(attributes[u]);
if (!NStr::SplitInTwo(attribute, "=", key, value)) {
if (!NStr::SplitInTwo(attribute, " ", key, value)) {
if (strGtfType == "gene") {
mAttributes.AddValue(
"gene_id", xNormalizedAttributeValue(attribute));
continue;
}
if (strGtfType == "transcript") {
string gid, tid;
if (!NStr::SplitInTwo(attribute, ".", gid, tid)) {
return false;
}
mAttributes.AddValue(
"gene_id", xNormalizedAttributeValue(gid));
mAttributes.AddValue(
"transcript_id", xNormalizedAttributeValue(attribute));
continue;
}
}
}
key = xNormalizedAttributeKey(key);
value = xNormalizedAttributeValue(value);
if ( key.empty() && value.empty() ) {
// Probably due to trailing "; ". Sequence Ontology generates such
// things.
continue;
}
if (NStr::StartsWith(value, "\"")) {
value = value.substr(1, string::npos);
}
if (NStr::EndsWith(value, "\"")) {
value = value.substr(0, value.length() - 1);
}
mAttributes.AddValue(key, value);
}
return true;
}
// ----------------------------------------------------------------------------
CGtfReader::CGtfReader(
unsigned int uFlags,
const string& strAnnotName,
const string& strAnnotTitle,
SeqIdResolver resolver,
CReaderListener* pRL):
// ----------------------------------------------------------------------------
CGff2Reader( uFlags, strAnnotName, strAnnotTitle, resolver, pRL)
{
mpLocations.reset(new CGtfLocationMerger(uFlags, resolver));
}
// ----------------------------------------------------------------------------
CGtfReader::CGtfReader(
unsigned int uFlags,
CReaderListener* pRL):
// ----------------------------------------------------------------------------
CGtfReader( uFlags, "", "", CReadUtil::AsSeqId, pRL)
{
}
// ----------------------------------------------------------------------------
CGtfReader::~CGtfReader()
// ----------------------------------------------------------------------------
{
}
// ----------------------------------------------------------------------------
CRef<CSeq_annot>
CGtfReader::ReadSeqAnnot(
ILineReader& lineReader,
ILineErrorListener* pEC )
// ----------------------------------------------------------------------------
{
mCurrentFeatureCount = 0;
return CReaderBase::ReadSeqAnnot(lineReader, pEC);
}
// ----------------------------------------------------------------------------
void
CGtfReader::xProcessData(
const TReaderData& readerData,
CSeq_annot& annot)
// ----------------------------------------------------------------------------
{
for (const auto& lineData: readerData) {
const auto& line = lineData.mData;
if (xIsTrackTerminator(line)) {
continue;
}
if (xParseStructuredComment(line)) {
continue;
}
if (xParseBrowserLine(line, annot)) {
continue;
}
if (xParseFeature(line, annot, nullptr)) {
continue;
}
}
}
// ----------------------------------------------------------------------------
bool CGtfReader::xUpdateAnnotFeature(
const CGff2Record& record,
CSeq_annot& annot,
ILineErrorListener* pEC)
// ----------------------------------------------------------------------------
{
const CGtfReadRecord& gff = dynamic_cast<const CGtfReadRecord&>(record);
auto recType = gff.NormalizedType();
using TYPEHANDLER = bool (CGtfReader::*)(const CGtfReadRecord&, CSeq_annot&);
using HANDLERMAP = map<string, TYPEHANDLER>;
HANDLERMAP typeHandlers = {
{"cds", &CGtfReader::xUpdateAnnotCds},
{"start_codon", &CGtfReader::xUpdateAnnotCds},
{"stop_codon", &CGtfReader::xUpdateAnnotCds},
{"5utr", &CGtfReader::xUpdateAnnotTranscript},
{"3utr", &CGtfReader::xUpdateAnnotTranscript},
{"exon", &CGtfReader::xUpdateAnnotTranscript},
{"initial", &CGtfReader::xUpdateAnnotTranscript},
{"internal", &CGtfReader::xUpdateAnnotTranscript},
{"terminal", &CGtfReader::xUpdateAnnotTranscript},
{"single", &CGtfReader::xUpdateAnnotTranscript},
};
//
// Handle officially recognized GTF types:
//
HANDLERMAP::iterator it = typeHandlers.find(recType);
if (it != typeHandlers.end()) {
TYPEHANDLER handler = it->second;
return (this->*handler)(gff, annot);
}
//
// Every other type is not officially sanctioned GTF, and per spec we are
// supposed to ignore it. In the spirit of being lenient on input we may
// try to salvage some of it anyway.
//
if (recType == "gene") {
return xCreateParentGene(gff, annot);
}
if (recType == "mrna" || recType == "transcript") {
return xCreateParentMrna(gff, annot);
}
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xUpdateAnnotCds(
const CGtfReadRecord& gff,
CSeq_annot& annot )
// ----------------------------------------------------------------------------
{
auto featId = mpLocations->GetFeatureIdFor(gff, "cds");
mpLocations->AddRecordForId(featId, gff) ;
return (xFindFeatById(featId) || xCreateParentCds(gff, annot));
}
// ----------------------------------------------------------------------------
bool CGtfReader::xUpdateAnnotTranscript(
const CGtfReadRecord& gff,
CSeq_annot& annot )
// ----------------------------------------------------------------------------
{
//
// If there is no gene feature to go with this CDS then make one. Otherwise,
// make sure the existing gene feature includes the location of the CDS.
//
auto geneFeatId = mpLocations->GetFeatureIdFor(gff, "gene");
CRef< CSeq_feat > pGene = xFindFeatById(geneFeatId);
if (!pGene) {
if (!xCreateParentGene(gff, annot)) {
return false;
}
mpLocations->AddRecordForId(geneFeatId, gff);
}
else {
mpLocations->AddRecordForId(geneFeatId, gff);
if (!xFeatureTrimQualifiers(gff, *pGene)) {
return false;
}
}
//
// If there is no mRNA feature with this gene_id|transcript_id then make one.
// Otherwise, fix up the location of the existing one.
//
auto transcriptFeatId = mpLocations->GetFeatureIdFor(gff, "transcript");
CRef<CSeq_feat> pMrna = xFindFeatById(transcriptFeatId);
if (!pMrna) {
//
// Create a brand new CDS feature:
//
if (!xCreateParentMrna(gff, annot)) {
return false;
}
mpLocations->AddRecordForId(transcriptFeatId, gff);
}
else {
//
// Update an already existing CDS features:
//
mpLocations->AddRecordForId(transcriptFeatId, gff);
if (!xFeatureTrimQualifiers(gff, *pMrna)) {
return false;
}
}
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xCreateFeatureId(
const CGtfReadRecord& record,
const string& prefix,
CSeq_feat& feature )
// ----------------------------------------------------------------------------
{
static int seqNum(1);
string strFeatureId = prefix;
if (strFeatureId.empty()) {
strFeatureId = "id";
}
strFeatureId += "_";
strFeatureId += NStr::IntToString(seqNum++);
feature.SetId().SetLocal().SetStr(strFeatureId);
return true;
}
// -----------------------------------------------------------------------------
bool CGtfReader::xCreateParentGene(
const CGtfReadRecord& gff,
CSeq_annot& annot )
// -----------------------------------------------------------------------------
{
auto featId = mpLocations->GetFeatureIdFor(gff, "gene");
if (m_MapIdToFeature.find(featId) != m_MapIdToFeature.end()) {
return true;
}
CRef<CSeq_feat> pFeature( new CSeq_feat );
if (!xFeatureSetDataGene(gff, *pFeature)) {
return false;
}
if (!xCreateFeatureId(gff, "gene", *pFeature)) {
return false;
}
if ( !xFeatureSetQualifiersGene(gff, *pFeature)) {
return false;
}
(gff.Type() == "gene") ?
mpLocations->AddRecordForId(featId, gff) :
mpLocations->AddStubForId(featId);
m_MapIdToFeature[featId] = pFeature;
xAddFeatureToAnnot(pFeature, annot);
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xFeatureSetQualifiersGene(
const CGtfReadRecord& record,
CSeq_feat& feature )
// ----------------------------------------------------------------------------
{
list<string> ignoredAttrs = {
"locus_tag", "transcript_id"
};
//
// Create GB qualifiers for the record attributes:
//
const auto& attrs = record.GtfAttributes().Get();
auto it = attrs.begin();
for (/*NOOP*/; it != attrs.end(); ++it) {
auto cit = std::find(ignoredAttrs.begin(), ignoredAttrs.end(), it->first);
if (cit != ignoredAttrs.end()) {
continue;
}
// special case some well-known attributes
if (xProcessQualifierSpecialCase(it->first, it->second, feature)) {
continue;
}
// turn everything else into a qualifier
xFeatureAddQualifiers(it->first, it->second, feature);
}
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xFeatureSetQualifiersRna(
const CGtfReadRecord& record,
CSeq_feat& feature )
// ----------------------------------------------------------------------------
{
list<string> ignoredAttrs = {
"locus_tag"
};
const auto& attrs = record.GtfAttributes().Get();
auto it = attrs.begin();
for (/*NOOP*/; it != attrs.end(); ++it) {
auto cit = std::find(ignoredAttrs.begin(), ignoredAttrs.end(), it->first);
if (cit != ignoredAttrs.end()) {
continue;
}
// special case some well-known attributes
if (xProcessQualifierSpecialCase(it->first, it->second, feature)) {
continue;
}
// turn everything else into a qualifier
xFeatureAddQualifiers(it->first, it->second, feature);
}
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xFeatureSetQualifiersCds(
const CGtfReadRecord& record,
CSeq_feat& feature )
// ----------------------------------------------------------------------------
{
list<string> ignoredAttrs = {
"locus_tag"
};
const auto& attrs = record.GtfAttributes().Get();
auto it = attrs.begin();
for (/*NOOP*/; it != attrs.end(); ++it) {
auto cit = std::find(ignoredAttrs.begin(), ignoredAttrs.end(), it->first);
if (cit != ignoredAttrs.end()) {
continue;
}
// special case some well-known attributes
if (xProcessQualifierSpecialCase(it->first, it->second, feature)) {
continue;
}
// turn everything else into a qualifier
xFeatureAddQualifiers(it->first, it->second, feature);
}
return true;
}
// -----------------------------------------------------------------------------
bool CGtfReader::xCreateParentCds(
const CGtfReadRecord& gff,
CSeq_annot& annot )
// -----------------------------------------------------------------------------
{
auto featId = mpLocations->GetFeatureIdFor(gff, "cds");
if (m_MapIdToFeature.find(featId) != m_MapIdToFeature.end()) {
return true;
}
CRef<CSeq_feat> pFeature(new CSeq_feat);
if (!xFeatureSetDataCds(gff, *pFeature)) {
return false;
}
if (!xCreateFeatureId(gff, "cds", *pFeature)) {
return false;
}
if (!xFeatureSetQualifiersCds(gff, *pFeature)) {
return false;
}
m_MapIdToFeature[featId] = pFeature;
return xAddFeatureToAnnot(pFeature, annot);
}
// -----------------------------------------------------------------------------
bool CGtfReader::xCreateParentMrna(
const CGtfReadRecord& gff,
CSeq_annot& annot )
// -----------------------------------------------------------------------------
{
auto featId = mpLocations->GetFeatureIdFor(gff, "transcript");
if (m_MapIdToFeature.find(featId) != m_MapIdToFeature.end()) {
return true;
}
CRef< CSeq_feat > pFeature( new CSeq_feat );
if (!xFeatureSetDataMrna(gff, *pFeature)) {
return false;
}
if (!xCreateFeatureId(gff, "mrna", *pFeature)) {
return false;
}
if ( ! xFeatureSetQualifiersRna( gff, *pFeature ) ) {
return false;
}
mpLocations->AddStubForId(featId);
m_MapIdToFeature[featId] = pFeature;
return xAddFeatureToAnnot( pFeature, annot );
}
// ----------------------------------------------------------------------------
CRef<CSeq_feat> CGtfReader::xFindFeatById(
const string& featId)
// ----------------------------------------------------------------------------
{
auto featIt = m_MapIdToFeature.find(featId);
if (featIt == m_MapIdToFeature.end()) {
return CRef<CSeq_feat>();
}
return featIt->second;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xFeatureSetDataGene(
const CGtfReadRecord& record,
CSeq_feat& feature )
// ----------------------------------------------------------------------------
{
CGene_ref& gene = feature.SetData().SetGene();
const auto& attributes = record.GtfAttributes();
string geneSynonym = attributes.ValueOf("gene_synonym");
if (!geneSynonym.empty()) {
gene.SetSyn().push_back(geneSynonym);
}
string locusTag = attributes.ValueOf("locus_tag");
if (!locusTag.empty()) {
gene.SetLocus_tag(locusTag);
}
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xFeatureSetDataMrna(
const CGtfReadRecord& record,
CSeq_feat& feature)
// ----------------------------------------------------------------------------
{
if (!xFeatureSetDataRna(record, feature, CSeqFeatData::eSubtype_mRNA)) {
return false;
}
CRNA_ref& rna = feature.SetData().SetRna();
string product = record.GtfAttributes().ValueOf("product");
if (!product.empty()) {
rna.SetExt().SetName(product);
}
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xFeatureSetDataRna(
const CGtfReadRecord& record,
CSeq_feat& feature,
CSeqFeatData::ESubtype subType)
// ----------------------------------------------------------------------------
{
CRNA_ref& rnaRef = feature.SetData().SetRna();
switch (subType){
default:
rnaRef.SetType(CRNA_ref::eType_miscRNA);
break;
case CSeqFeatData::eSubtype_mRNA:
rnaRef.SetType(CRNA_ref::eType_mRNA);
break;
case CSeqFeatData::eSubtype_rRNA:
rnaRef.SetType(CRNA_ref::eType_rRNA);
break;
}
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xFeatureSetDataCds(
const CGtfReadRecord& record,
CSeq_feat& feature )
// ----------------------------------------------------------------------------
{
CCdregion& cdr = feature.SetData().SetCdregion();
const auto& attributes = record.GtfAttributes();
string proteinId = attributes.ValueOf("protein_id");
if (!proteinId.empty()) {
CRef<CSeq_id> pId = mSeqIdResolve(proteinId, m_iFlags, true);
if (pId->IsGenbank()) {
feature.SetProduct().SetWhole(*pId);
}
}
string ribosomalSlippage = attributes.ValueOf("ribosomal_slippage");
if (!ribosomalSlippage.empty()) {
feature.SetExcept( true );
feature.SetExcept_text("ribosomal slippage");
}
string transTable = attributes.ValueOf("transl_table");
if (!transTable.empty()) {
CRef< CGenetic_code::C_E > pGc( new CGenetic_code::C_E );
pGc->SetId(NStr::StringToUInt(transTable));
cdr.SetCode().Set().push_back(pGc);
}
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xFeatureTrimQualifiers(
const CGtfReadRecord& record,
CSeq_feat& feature )
// ----------------------------------------------------------------------------
{
typedef CSeq_feat::TQual TQual;
//task:
// for each attribute of the new piece check if we already got a feature
// qualifier
// if so, and with the same value, then the qualifier is allowed to live
// otherwise it is subfeature specific and hence removed from the feature
TQual& quals = feature.SetQual();
for (TQual::iterator it = quals.begin(); it != quals.end(); /**/) {
const string& qualKey = (*it)->GetQual();
if (NStr::StartsWith(qualKey, "gff_")) {
it++;
continue;
}
if (qualKey == "locus_tag") {
it++;
continue;
}
if (qualKey == "old_locus_tag") {
it++;
continue;
}
if (qualKey == "product") {
it++;
continue;
}
if (qualKey == "protein_id") {
it++;
continue;
}
const string& qualVal = (*it)->GetVal();
if (!record.GtfAttributes().HasValue(qualKey, qualVal)) {
//superfluous qualifier- squish
it = quals.erase(it);
continue;
}
it++;
}
return true;
}
// ----------------------------------------------------------------------------
bool CGtfReader::xProcessQualifierSpecialCase(
const string& key,
const CGtfAttributes::MultiValue& values,
CSeq_feat& feature )
// ----------------------------------------------------------------------------
{
CRef<CGb_qual> pQual(0);
if (0 == NStr::CompareNocase(key, "exon_id")) {
return true;
}
if (0 == NStr::CompareNocase(key, "exon_number")) {
return true;
}
if ( 0 == NStr::CompareNocase(key, "note") ) {
feature.SetComment(NStr::Join(values, ";"));
return true;
}
if ( 0 == NStr::CompareNocase(key, "dbxref") ||
0 == NStr::CompareNocase(key, "db_xref"))
{
for (auto value: values) {
vector< string > tags;
NStr::Split(value, ";", tags );
for (auto it = tags.begin(); it != tags.end(); ++it ) {
feature.SetDbxref().push_back(x_ParseDbtag(*it));
}
}
return true;
}
if ( 0 == NStr::CompareNocase(key, "pseudo")) {
feature.SetPseudo( true );
return true;
}
if ( 0 == NStr::CompareNocase(key, "partial")) {
// RW-1108 - ignore partial attribute in Genbank mode
if (m_iFlags & CGtfReader::fGenbankMode) {
return true;
}
}
return false;
}
// ----------------------------------------------------------------------------
void CGtfReader::xFeatureAddQualifiers(
const string& key,
const CGtfAttributes::MultiValue& values,
CSeq_feat& feature)
// ----------------------------------------------------------------------------
{
for (auto value: values) {
feature.AddQualifier(key, value);
}
};
// ============================================================================
void CGtfReader::xSetAncestorXrefs(
CSeq_feat& descendent,
CSeq_feat& ancestor)
// ============================================================================
{
xSetXrefFromTo(descendent, ancestor);
if (m_iFlags & CGtfReader::fGenerateChildXrefs) {
xSetXrefFromTo(ancestor, descendent);
}
}
// ----------------------------------------------------------------------------
void CGtfReader::xPostProcessAnnot(
CSeq_annot& annot)
// ----------------------------------------------------------------------------
{
//location fixup:
for (auto itLocation: mpLocations->LocationMap()) {
auto id = itLocation.first;
auto itFeature = m_MapIdToFeature.find(id);
if (itFeature == m_MapIdToFeature.end()) {
continue;
}
CRef<CSeq_feat> pFeature = itFeature->second;
auto featSubType = pFeature->GetData().GetSubtype();
CRef<CSeq_loc> pNewLoc = mpLocations->MergeLocation(
featSubType, itLocation.second);
pFeature->SetLocation(*pNewLoc);
}
//generate xrefs:
for (auto itLocation: mpLocations->LocationMap()) {
auto id = itLocation.first;
auto itFeature = m_MapIdToFeature.find(id);
if (itFeature == m_MapIdToFeature.end()) {
continue;
}
CRef<CSeq_feat> pFeature = itFeature->second;
auto featSubType = pFeature->GetData().GetSubtype();
switch(featSubType) {
default: {
break;
}
case CSeqFeatData::eSubtype_mRNA: {
auto parentGeneFeatId = string("gene:") + pFeature->GetNamedQual("gene_id");
CRef<CSeq_feat> pParentGene;
if (x_GetFeatureById(parentGeneFeatId, pParentGene)) {
xSetAncestorXrefs(*pFeature, *pParentGene);
}
break;
}
case CSeqFeatData::eSubtype_cdregion: {
auto parentRnaFeatId = string("transcript:") + pFeature->GetNamedQual("gene_id") +
"_" + pFeature->GetNamedQual("transcript_id");
CRef<CSeq_feat> pParentRna;
if (x_GetFeatureById(parentRnaFeatId, pParentRna)) {
xSetAncestorXrefs(*pFeature, *pParentRna);
}
auto parentGeneFeatId = string("gene:") + pFeature->GetNamedQual("gene_id");
CRef<CSeq_feat> pParentGene;
if (x_GetFeatureById(parentGeneFeatId, pParentGene)) {
xSetAncestorXrefs(*pFeature, *pParentGene);
}
break;
}
}
}
return CGff2Reader::xPostProcessAnnot(annot);
}
END_objects_SCOPE
END_NCBI_SCOPE
| 33.512418 | 98 | 0.506612 | [
"vector"
] |
ce9a559ba5501a35bcb93e5b9541094c177f42db | 4,920 | cxx | C++ | Libraries/Common/niftkMathsUtils.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 13 | 2018-07-28T13:36:38.000Z | 2021-11-01T19:17:39.000Z | Libraries/Common/niftkMathsUtils.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | null | null | null | Libraries/Common/niftkMathsUtils.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 10 | 2018-08-20T07:06:00.000Z | 2021-07-07T07:55:27.000Z | /*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). 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 in the top level directory for details.
=============================================================================*/
#include "niftkMathsUtils.h"
#include <numeric>
#include <algorithm>
#include <functional>
#include <cmath>
#include <sstream>
namespace niftk {
//-----------------------------------------------------------------------------
bool IsCloseToZero(const double& value, const double& tolerance)
{
if (fabs(value) < tolerance)
{
return true;
}
else
{
return false;
}
}
//-----------------------------------------------------------------------------
std::pair <double, double > FindMinimumValues (
std::vector < std::pair < double, double > > inputValues,
std::pair < unsigned int , unsigned int > * indexes )
{
std::pair < double , double > minimumValues;
if ( inputValues.size() > 0 )
{
minimumValues.first = inputValues[0].first;
minimumValues.second = inputValues[0].second;
if ( indexes != NULL )
{
indexes->first = 0;
indexes->second = 0;
}
}
for (unsigned int i = 0; i < inputValues.size(); i++ )
{
if ( inputValues[i].first < minimumValues.first )
{
minimumValues.first = inputValues[i].first;
if ( indexes != NULL )
{
indexes->first = i;
}
}
if ( inputValues[i].second < minimumValues.second )
{
minimumValues.second = inputValues[i].second;
if ( indexes != NULL )
{
indexes->second = i;
}
}
}
return minimumValues;
}
//-----------------------------------------------------------------------------
double RMS(const std::vector<double>& input)
{
double mean = Mean(input);
return sqrt(mean);
}
//-----------------------------------------------------------------------------
double Mean(const std::vector<double>& input)
{
if (input.size() == 0)
{
return 0;
}
double sum = std::accumulate(input.begin(), input.end(), 0.0);
double mean = sum / input.size();
return mean;
}
//-----------------------------------------------------------------------------
double Median(std::vector<double> input)
{
if (input.size() == 0)
{
return 0;
}
else if (input.size() == 1)
{
return input[0];
}
else
{
std::sort(input.begin(), input.end());
if (input.size() % 2 == 1)
{
return input[(input.size() - 1)/2];
}
else
{
return (input[input.size()/2 - 1] + input[input.size()/2])/2.0;
}
}
}
//-----------------------------------------------------------------------------
double StdDev(const std::vector<double>& input)
{
if (input.size() < 2)
{
return 0;
}
double mean = niftk::Mean(input);
std::vector<double> diff(input.size());
std::transform(input.begin(), input.end(), diff.begin(), std::bind2nd(std::minus<double>(), mean));
double squared = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(squared / ((double)(input.size()) - 1.0));
return stdev;
}
//-----------------------------------------------------------------------------
double ModifiedSignum(double value)
{
if ( value < 0.0 )
{
return -1.0;
}
return 1.0;
}
//-----------------------------------------------------------------------------
double SafeSQRT(double value)
{
if ( value < 0 )
{
return 0.0;
}
return sqrt(value);
}
//-----------------------------------------------------------------------------
double MahalanobisDistance ( const std::vector < double >& v1 , const std::vector < double >& v2,
const std::vector < double >& covariance )
{
if ( ( v1.size() != v2.size() ) || ( v1.size() != covariance.size() ) )
{
throw std::logic_error("Unequal vector lengths in niftk::MahalanobisDistance");
}
double distance = 0;
std::vector<double>::const_iterator it1 = v1.begin();
std::vector<double>::const_iterator it2 = v2.begin();
std::vector<double>::const_iterator itCovariance = covariance.begin();
while ( it1 < v1.end() )
{
distance += ( *it1 - *it2 ) * ( *it1 - *it2 ) / *itCovariance;
++it1;
++it2;
++itCovariance;
}
return sqrt (distance);
}
//-----------------------------------------------------------------------------
void CheckDoublesEquals(double expected, double actual, double tol)
{
if (fabs(expected - actual) > tol)
{
std::stringstream errorStream;
errorStream << "Failed:Expected=" << expected << ", actual=" <<
actual <<", tolerance=" << tol;
throw std::logic_error(errorStream.str());
}
}
} // end namespace
| 24.356436 | 101 | 0.489837 | [
"vector",
"transform"
] |
ce9baa0b5e7344ea1acf6579cbbf8131bbd90adb | 849 | cpp | C++ | Reverse words in a given string - GFG/reverse-words-in-a-given-string.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | 1 | 2022-02-27T09:01:07.000Z | 2022-02-27T09:01:07.000Z | Reverse words in a given string - GFG/reverse-words-in-a-given-string.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | Reverse words in a given string - GFG/reverse-words-in-a-given-string.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to reverse words in a given string.
string reverseWords(string S)
{
// code here
vector<string> rev;
string temp="";
for(auto a:S){
if(a=='.'){
rev.emplace_back(temp);
rev.emplace_back(".");
temp.clear();
}
else
temp+=a;
}
for(int i=rev.size()-1;i>=0;--i){
temp+=rev[i];
}
return temp;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
string s;
cin >> s;
Solution obj;
cout<<obj.reverseWords(s)<<endl;
}
} // } Driver Code Ends | 18.456522 | 50 | 0.43934 | [
"vector"
] |
cea02bbee503214a301d65742df8bcb3f5945821 | 11,637 | cpp | C++ | hello_sane.cpp | betamake/intelligence | 3ca68f03a29f54e3cefe28d33c67183488891c27 | [
"Unlicense"
] | 1 | 2021-01-16T02:34:33.000Z | 2021-01-16T02:34:33.000Z | hello_sane.cpp | betamake/intelligence | 3ca68f03a29f54e3cefe28d33c67183488891c27 | [
"Unlicense"
] | null | null | null | hello_sane.cpp | betamake/intelligence | 3ca68f03a29f54e3cefe28d33c67183488891c27 | [
"Unlicense"
] | 1 | 2019-07-16T00:48:29.000Z | 2019-07-16T00:48:29.000Z | #include "hello_sane.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
uint8_t *data;
int width;
int height;
int x;
int y;
}
Image;
#define STRIP_HEIGHT 256
static SANE_Handle device = NULL;
static int verbose;
static int progress = 0;
static SANE_Byte *buffer;
static size_t buffer_size;
static void
auth_callback (SANE_String_Const resource,
SANE_Char * username, SANE_Char * password)
{
}
static void write_pnm_header (SANE_Frame format, int width, int height, int depth, FILE *ofp)
{
switch (format)
{
case SANE_FRAME_RED:
case SANE_FRAME_GREEN:
case SANE_FRAME_BLUE:
case SANE_FRAME_RGB:
fprintf (ofp, "P6\n# SANE data follows\n%d %d\n%d\n", width, height, (depth <= 8) ? 255 : 65535);
break;
default:
if (depth == 1)
fprintf (ofp, "P4\n# SANE data follows\n%d %d\n", width, height);
else
fprintf (ofp, "P5\n# SANE data follows\n%d %d\n%d\n", width, height,(depth <= 8) ? 255 : 65535);
break;
}
}
static SANE_Status scan_it (FILE *ofp)
{
int i, len, first_frame = 1, offset = 0, must_buffer = 0, hundred_percent;
SANE_Byte min = 0xff, max = 0;
SANE_Parameters parm;
SANE_Status status;
Image image = { 0, 0, 0, 0, 0 };
static const char *format_name[] = {"gray", "RGB", "red", "green", "blue"};
SANE_Word total_bytes = 0, expected_bytes;
SANE_Int hang_over = -1;
do
{
if (!first_frame)
{
status = sane_start (device);
if (status != SANE_STATUS_GOOD)
{
goto cleanup;
}
}
status = sane_get_parameters (device, &parm);
if (status != SANE_STATUS_GOOD)
{
goto cleanup;
}
if (first_frame)
{
switch (parm.format)
{
case SANE_FRAME_RED:
case SANE_FRAME_GREEN:
case SANE_FRAME_BLUE:
assert (parm.depth == 8);
must_buffer = 1;
offset = parm.format - SANE_FRAME_RED;
break;
case SANE_FRAME_RGB:
assert ((parm.depth == 8) || (parm.depth == 16));
case SANE_FRAME_GRAY:
assert ((parm.depth == 1) || (parm.depth == 8) || (parm.depth == 16));
if (parm.lines < 0)
{
must_buffer = 1;
offset = 0;
}
else
{
write_pnm_header (parm.format, parm.pixels_per_line,parm.lines, parm.depth, ofp);
}
break;
default:
break;
}
if (must_buffer)
{
image.width = parm.bytes_per_line;
if (parm.lines >= 0)
image.height = parm.lines - STRIP_HEIGHT + 1;
else
image.height = 0;
image.x = image.width - 1;
image.y = -1;
/*if (!advance(&image))
{
status = SANE_STATUS_NO_MEM;
goto cleanup;
}*/
}
}
else
{
assert (parm.format >= SANE_FRAME_RED && parm.format <= SANE_FRAME_BLUE);
offset = parm.format - SANE_FRAME_RED;
image.x = image.y = 0;
}
hundred_percent = parm.bytes_per_line * parm.lines * ((parm.format == SANE_FRAME_RGB || parm.format == SANE_FRAME_GRAY) ? 1:3);
while (1)
{
double progr;
status = sane_read (device, buffer, buffer_size, &len);
total_bytes += (SANE_Word) len;
progr = ((total_bytes * 100.) / (double) hundred_percent);
if (progr > 100.)
progr = 100.;
if (status != SANE_STATUS_GOOD)
{
if (status != SANE_STATUS_EOF)
{
return status;
}
break;
}
if (must_buffer)
{
switch (parm.format)
{
case SANE_FRAME_RED:
case SANE_FRAME_GREEN:
case SANE_FRAME_BLUE:
for (i = 0; i < len; ++i)
{
image.data[offset + 3 * i] = buffer[i];
/*if (!advance (&image))
{
status = SANE_STATUS_NO_MEM;
goto cleanup;
}*/
}
offset += 3 * len;
break;
case SANE_FRAME_RGB:
for (i = 0; i < len; ++i)
{
image.data[offset + i] = buffer[i];
/*if (!advance (&image))
{
status = SANE_STATUS_NO_MEM;
goto cleanup;
}*/
}
offset += len;
break;
case SANE_FRAME_GRAY:
for (i = 0; i < len; ++i)
{
image.data[offset + i] = buffer[i];
/*if (!advance (&image))
{
status = SANE_STATUS_NO_MEM;
goto cleanup;
}*/
}
offset += len;
break;
default:
break;
}
}
else /* ! must_buffer */
{
if ((parm.depth != 16))
fwrite (buffer, 1, len, ofp);
else
{
#if !defined(WORDS_BIGENDIAN)
int i, start = 0;
/* check if we have saved one byte from the last sane_read */
if (hang_over > -1)
{
if (len > 0)
{
fwrite (buffer, 1, 1, ofp);
buffer[0] = (SANE_Byte) hang_over;
hang_over = -1;
start = 1;
}
}
/* now do the byte-swapping */
for (i = start; i < (len - 1); i += 2)
{
unsigned char LSB;
LSB = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = LSB;
}
/* check if we have an odd number of bytes */
if (((len - start) % 2) != 0)
{
hang_over = buffer[len - 1];
len--;
}
#endif
fwrite (buffer, 1, len, ofp);
}
}
if (verbose && parm.depth == 8)
{
for (i = 0; i < len; ++i)
if (buffer[i] >= max)
max = buffer[i];
else if (buffer[i] < min)
min = buffer[i];
}
}
first_frame = 0;
}while (!parm.last_frame);
if (must_buffer)
{
image.height = image.y;
write_pnm_header (parm.format, parm.pixels_per_line,image.height, parm.depth, ofp);
#if !defined(WORDS_BIGENDIAN)
if (parm.depth == 16)
{
int i;
for (i = 0; i < image.height * image.width; i += 2)
{
unsigned char LSB;
LSB = image.data[i];
image.data[i] = image.data[i + 1];
image.data[i + 1] = LSB;
}
}
#endif
fwrite (image.data, 1, image.height * image.width, ofp);
}
fflush( ofp );
cleanup:
if (image.data)
free (image.data);
return status;
}
SANE_Status do_scan(const char *fileName)
{
SANE_Status status;
FILE *ofp = NULL;
char path[PATH_MAX];
char part_path[PATH_MAX];
buffer_size = (32 * 1024);
buffer = (SANE_Byte*)malloc (buffer_size);
do
{
// int dwProcessID = getpid();
// sprintf (path, "%s%d.pnm", fileName, dwProcessID);
sprintf (path, "%s.pnm", fileName);
strcpy (part_path, path);
strcat (part_path, ".part");
status = sane_start (device);
if (status != SANE_STATUS_GOOD)
{
break;
}
if (NULL == (ofp = fopen (part_path, "w")))
{
status = SANE_STATUS_ACCESS_DENIED;
break;
}
status = scan_it (ofp);
switch (status)
{
case SANE_STATUS_GOOD:
case SANE_STATUS_EOF:
{
status = SANE_STATUS_GOOD;
if (!ofp || 0 != fclose(ofp))
{
status = SANE_STATUS_ACCESS_DENIED;
break;
}
else
{
ofp = NULL;
if (rename (part_path, path))
{
status = SANE_STATUS_ACCESS_DENIED;
break;
}
}
}
break;
default:
break;
}
}while (0);
if (SANE_STATUS_GOOD != status)
{
sane_cancel (device);
}
if (ofp)
{
fclose (ofp);
ofp = NULL;
}
if (buffer)
{
free (buffer);
buffer = NULL;
}
return status;
}
// Initialize SANE
void init()
{
SANE_Int version_code = 0;
sane_init (&version_code, auth_callback);
printf("SANE version code: %d\n", version_code);
}
// Get all devices
SANE_Status get_devices( SANE_Device ***device_list)
{
printf("Get all devices...\n");
SANE_Status sane_status = SANE_STATUS_GOOD;
if (sane_status = sane_get_devices (device_list, SANE_FALSE))
{
printf("sane_get_devices status: %s\n", sane_strstatus(sane_status));
}
return sane_status;
}
// Open a device
SANE_Status open_device(SANE_Device *device, SANE_Handle *sane_handle)
{
SANE_Status sane_status = SANE_STATUS_GOOD;
printf("Name: %s, vendor: %s, model: %s, type: %s\n", device->name, device->model, device->vendor, device->type);
if (sane_status = sane_open(device->name, sane_handle))
{
printf("sane_open status: %s\n", sane_strstatus(sane_status));
}
return sane_status;
}
// Start scanning
SANE_Status start_scan(SANE_Handle sane_handle, SANE_String_Const fileName)
{
SANE_Status sane_status = SANE_STATUS_GOOD;
device = sane_handle;
// if (sane_status = sane_start(sane_handle))
// {
// printf("sane_start status: %s\n", sane_strstatus(sane_status));
// }
// return sane_status;
return do_scan(fileName);
}
// Cancel scanning
void cancle_scan(SANE_Handle sane_handle)
{
sane_cancel(sane_handle);
}
// Close SANE device
void close_device(SANE_Handle sane_handle)
{
sane_close(sane_handle);
}
// Release SANE resources
void scan_exit()
{
sane_exit();
}
#ifdef __cplusplus
}
#endif
| 27.77327 | 135 | 0.434476 | [
"model"
] |
cea3f8216f889133f5b766a39a901ed245841c7c | 6,385 | cpp | C++ | resources/provided.cpp | T0T0R/minimax2048 | 53f03c5d0461a0f68f522cf282c185d39ce0052c | [
"MIT"
] | null | null | null | resources/provided.cpp | T0T0R/minimax2048 | 53f03c5d0461a0f68f522cf282c185d39ce0052c | [
"MIT"
] | null | null | null | resources/provided.cpp | T0T0R/minimax2048 | 53f03c5d0461a0f68f522cf282c185d39ce0052c | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <array>
#include "../src/mm2048.h"
#include "../src/GameManager.h"
#include "../src/Grid.h"
#include "../src/Tile.h"
#include "../src/Vec2D.h"
#include "./provided.h"
Vec2D rot90(Vec2D const& M){
/*** Anti-clockwise rotation at 90 degrees. ***/
Vec2D rotatedArray{};
for (unsigned int i{0}; i<4; i++){
for (unsigned int j{0}; j<4; j++){
rotatedArray[3-j][i] = M[i][j];
}
}
return rotatedArray;
}
Vec2D glisse(Vec2D const& position, std::string const& fleche){
/*** fleche est une lettre indiquant dans quelle direction les tuiles
doivent etre glissees. ***/
Vec2D M = position;
// Fait pivoter la grille pour traiter les quatre cas de figure de facon identique.
// La grille traitee sera pivotee dans le sens inverse apres le glissement des tuiles.
if (fleche == "g"){
M = rot90(M);
}else if (fleche == "h"){
M = rot90(rot90(M));
}else if (fleche == "d"){
M = rot90(rot90(rot90(M)));
}
int imax;
int scanner;
for (unsigned int j{0}; j<4; ++j){
imax = 3;
for (int i{2}; i>=0; --i){// Position initiale (dans les trois lignes du haut).
if (M[i][j] != 0){ // Si il y a une tuile ?
scanner = i;
while (scanner < imax){ // on regarde s il y a une tuile compatible en dessous.
++ scanner;
if ( M[scanner][j] == M[scanner-1][j] ){ // Si on trouve une tuile identique, on les combine.
M[scanner][j] = M[scanner][j]*2;
M[scanner-1][j] = 0;
imax = scanner - 1;
}else if ( M[scanner][j] == 0 ){ // Si il n y a pas de tuile en dessous, on la deplace.
M[scanner][j] = M[scanner-1][j];
M[scanner-1][j] = 0;
}else {
imax = scanner-1;
}
}
}
}
}
// La grille est remise en position initiale.
if(fleche == "g"){
M = rot90(rot90(rot90(M)));
}else if (fleche == "h"){
M = rot90(rot90(M));
}else if (fleche == "d"){
M = rot90(M);
}
return M;
}
int fournir_note(Vec2D table){
/* Returns the evaluated mark corresponding to the given grid. */
int mark {0};
int max {0};
std::vector<int> values (16);
Position maxPos{-1,-1};
int nbZeros {0};
int sum {0}; // - Sum of all tiles, and search the position of the highest tile
for (int i{0}; i<4; i++){
for (int j{0}; j<4; j++){
sum += table[i][j];
values.push_back(table[i][j]);
if(table[i][j] > max){
max = table[i][j];
maxPos.x = j ; maxPos.y = i;
}
if(table[i][j]==0){
nbZeros++;
}
}
}
mark = max;
/* STATISTICS */
double mean = sum/16;
double corrMean = sum/(16-nbZeros);
double variance;
int sumSquareDiff {0};
for (int i {0}; i<16;i++) {
sumSquareDiff += (mean - values[i])*(mean - values[i]);
}
variance = sumSquareDiff/16;
if(table[0][0]==max || table[3][0]==max || table[0][3]==max || table[3][3]==max){ // - Bonus : if the highest tile is in the corner,
mark *= 1.7;
}
if (table[2][2]==max || table[1][2]==max || table[1][1]==max || table[2][1]==max) { // - Bonus : if the highest tile is in the corner,
mark *= 0.25;
}
// - Bonus : if both highest tile and second to highest tile are next to each other,
mark *= evalNeighbors(table, maxPos.y, maxPos.x, max);
// - Bonus : value/tile (favor |0|1024| against |512|512|)
return (mark+corrMean)*(nbZeros+1);
}
int evalNeighbors(Vec2D const& table, int const i, int const j, int const childValue){
if(childValue>1 && i<4 && j<4 && i>=0 && j>= 0 && table[i][j]==childValue){ // If the position is in the grid
double alpha = 1;
return alpha
+ evalNeighbors(table, i+1, j, childValue/2)
+ evalNeighbors(table, i, j+1, childValue/2)
+ evalNeighbors(table, i-1, j, childValue/2)
+ evalNeighbors(table, i, j-1, childValue/2);
}else{
return 0;
}
}
bool isInside(std::vector<std::pair<Vec2D, std::string>> const& liste_coups, Vec2D const& coup){
bool output {false};
for (std::pair<Vec2D, std::string> coup_present : liste_coups){
if (coup_present.first==coup){
output = true;
break;
}
}
return output;
}
std::vector<std::pair<Vec2D, std::string>> fournir_coups(Vec2D const& position, bool const& trait){
/*** position est une matrice 4*4 contenant la valeur des tuiles, trait est vrai si le coup suivant
consiste a glisser les tuiles, et faux si le coup suivant consiste a faire apparaitre
un 2 ou un 4 sur la grille.
La sortie est la liste de toutes les positions possibles apres ce coup, associees a la direction
qui a engendre ce coup. ***/
Vec2D grilleActuelle = position;
std::vector<std::pair<Vec2D,std::string>> liste_coups;
Vec2D coup {}; // Construit une grille vierge tampon.
std::array<std::string, 4> directions = {"g", "d", "h", "b"};
std::array<int, 2> valeursTuile = {2, 4};
if (fournir_note(grilleActuelle) != -1){
if (trait){ // Si on glisse les tuiles,
for (std::string fleche : directions){
// On glisse les tuiles dans les quatre sens, et on stocke les quatre
// grilles obtenues.
coup = glisse(position,fleche);
if ( !isInside(liste_coups, coup) && coup!=grilleActuelle){
liste_coups.push_back(std::pair<Vec2D, std::string>(coup, fleche));
}
}
} else { // Si la tuile 2 ou 4 apparait,
for (int i {0}; i<4; ++i){
for (int j {1}; j<4; ++j){
if (grilleActuelle[i][j] == 0){
for (int n : valeursTuile){
// On construit une grille avec la tuile supplementaire et on la stocke.
grilleActuelle[i][j] = n;
liste_coups.push_back(std::pair<Vec2D, std::string>(grilleActuelle, "o"));
}
grilleActuelle[i][j] = 0; // On remet la grille dans son etat initial.
}
}
}
}
}
return liste_coups;
}
| 27.521552 | 140 | 0.541425 | [
"vector"
] |
ceb421a179e636dd1b7015135cf508df30de0f5a | 6,375 | cc | C++ | 3rd_party/vrippack-0.31/src/plytools/plyarea.cc | yuxng/3DVP | 3551a31bc45d49e661f2140ea90b8bd83fe65e3b | [
"MIT"
] | 42 | 2016-07-03T22:16:47.000Z | 2021-03-30T22:23:46.000Z | 3rd_party/vrippack-0.31/src/plytools/plyarea.cc | PeiliangLi/3DVP | 3551a31bc45d49e661f2140ea90b8bd83fe65e3b | [
"MIT"
] | 2 | 2016-11-12T10:36:48.000Z | 2017-09-07T11:32:34.000Z | 3rd_party/vrippack-0.31/src/plytools/plyarea.cc | PeiliangLi/3DVP | 3551a31bc45d49e661f2140ea90b8bd83fe65e3b | [
"MIT"
] | 16 | 2016-08-06T01:20:40.000Z | 2020-07-13T14:59:35.000Z | /*
Compute the area of a triangle mesh
Brian Curless, October 1997
*/
#include <stdio.h>
#include <math.h>
#include <malloc.h>
#include <strings.h>
#include <ply.h>
#include <unistd.h>
#ifdef LINUX
#include <stdlib.h>
#endif
/* user's vertex and face definitions for a polygonal object */
typedef struct Vertex {
float x,y,z;
float nx,ny,nz;
void *other_props; /* other properties */
} Vertex;
typedef struct Face {
unsigned char nverts; /* number of vertex indices in list */
int *verts; /* vertex index list */
void *other_props; /* other properties */
} Face;
char *elem_names[] = { /* list of the kinds of elements in the user's object */
"vertex", "face"
};
PlyProperty vert_props[] = { /* list of property information for a vertex */
{"x", PLY_FLOAT, PLY_FLOAT, offsetof(Vertex,x), 0, 0, 0, 0},
{"y", PLY_FLOAT, PLY_FLOAT, offsetof(Vertex,y), 0, 0, 0, 0},
{"z", PLY_FLOAT, PLY_FLOAT, offsetof(Vertex,z), 0, 0, 0, 0},
{"nx", PLY_FLOAT, PLY_FLOAT, offsetof(Vertex,nx), 0, 0, 0, 0},
{"ny", PLY_FLOAT, PLY_FLOAT, offsetof(Vertex,ny), 0, 0, 0, 0},
{"nz", PLY_FLOAT, PLY_FLOAT, offsetof(Vertex,nz), 0, 0, 0, 0},
};
PlyProperty face_props[] = { /* list of property information for a vertex */
{"vertex_indices", PLY_INT, PLY_INT, offsetof(Face,verts),
1, PLY_UCHAR, PLY_UCHAR, offsetof(Face,nverts)},
};
/*** the PLY object ***/
static int nfaces;
static Vertex **vlist;
static Face **flist;
static int nelems;
static char **elist;
static int num_comments;
static int num_obj_info;
static int file_type;
static int flip_sign = 0; /* flip the sign of the normals? */
static int area_weight = 0; /* use area weighted average */
void usage(char *progname);
void read_file(FILE *inFile);
float compute_area();
/******************************************************************************
Main program.
******************************************************************************/
int
main(int argc, char *argv[])
{
int i,j;
char *s;
char *progname;
char *inName = NULL;
FILE *inFile = NULL;
progname = argv[0];
if (argc == 1) {
inFile = stdin;
} else if (argc == 2 && argv[1][0] != '-') {
/* argument supplied -- assume input filename */
inName = argv[1];
inFile = fopen(inName, "r");
if (inFile == NULL) {
fprintf(stderr, "Error: Could not open input ply file %s\n", inName);
usage(progname);
exit(-1);
}
} else {
usage (progname);
exit (-1);
}
read_file(inFile);
float area = compute_area();
printf("Surface area = %g\n", area);
}
/******************************************************************************
Print out usage information.
******************************************************************************/
void
usage(char *progname)
{
fprintf (stderr, "usage: %s [in.ply]\n", progname);
fprintf (stderr, " or: %s < in.ply\n", progname);
exit(-1);
}
/******************************************************************************
Compute normals at the vertices.
******************************************************************************/
float
compute_area()
{
int i,j;
Face *face;
Vertex *vert;
int *verts;
float x,y,z;
float x0,y0,z0;
float x1,y1,z1;
float area, total_area;
float recip;
total_area = 0;
for (i = 0; i < nfaces; i++) {
face = flist[i];
verts = face->verts;
/* Compute two edge vectors */
x0 = vlist[verts[face->nverts-1]]->x - vlist[verts[0]]->x;
y0 = vlist[verts[face->nverts-1]]->y - vlist[verts[0]]->y;
z0 = vlist[verts[face->nverts-1]]->z - vlist[verts[0]]->z;
x1 = vlist[verts[1]]->x - vlist[verts[0]]->x;
y1 = vlist[verts[1]]->y - vlist[verts[0]]->y;
z1 = vlist[verts[1]]->z - vlist[verts[0]]->z;
/* find cross-product between these vectors */
x = y0 * z1 - z0 * y1;
y = z0 * x1 - x0 * z1;
z = x0 * y1 - y0 * x1;
area = sqrt(x*x + y*y + z*z)/2;
total_area += area;
}
return total_area;
}
/******************************************************************************
Read in the PLY file from standard in.
******************************************************************************/
void
read_file(FILE *inFile)
{
int i,j,k;
PlyFile *ply;
int nprops;
int num_elems;
PlyProperty **plist;
char *elem_name;
float version;
int get_nx,get_ny,get_nz;
/*** Read in the original PLY object ***/
ply = ply_read (inFile, &nelems, &elist);
ply_get_info (ply, &version, &file_type);
for (i = 0; i < nelems; i++) {
/* get the description of the first element */
elem_name = elist[i];
plist = ply_get_element_description (ply, elem_name, &num_elems, &nprops);
if (equal_strings ("vertex", elem_name)) {
/* see if vertex holds any normal information */
get_nx = get_ny = get_nz = 0;
for (j = 0; j < nprops; j++) {
if (equal_strings ("nx", plist[j]->name)) get_nx = 1;
if (equal_strings ("ny", plist[j]->name)) get_ny = 1;
if (equal_strings ("nz", plist[j]->name)) get_nz = 1;
}
/* create a vertex list to hold all the vertices */
vlist = (Vertex **) malloc (sizeof (Vertex *) * num_elems);
/* set up for getting vertex elements */
ply_get_property (ply, elem_name, &vert_props[0]);
ply_get_property (ply, elem_name, &vert_props[1]);
ply_get_property (ply, elem_name, &vert_props[2]);
if (get_nx) ply_get_property (ply, elem_name, &vert_props[3]);
if (get_ny) ply_get_property (ply, elem_name, &vert_props[4]);
if (get_nz) ply_get_property (ply, elem_name, &vert_props[5]);
/* grab all the vertex elements */
for (j = 0; j < num_elems; j++) {
vlist[j] = (Vertex *) malloc (sizeof (Vertex));
ply_get_element (ply, (void *) vlist[j]);
}
}
else if (equal_strings ("face", elem_name)) {
/* create a list to hold all the face elements */
flist = (Face **) malloc (sizeof (Face *) * num_elems);
nfaces = num_elems;
/* set up for getting face elements */
ply_get_property (ply, elem_name, &face_props[0]);
/* grab all the face elements */
for (j = 0; j < num_elems; j++) {
flist[j] = (Face *) malloc (sizeof (Face));
ply_get_element (ply, (void *) flist[j]);
}
}
}
ply_close (ply);
}
| 25.398406 | 79 | 0.542275 | [
"mesh",
"object"
] |
ceb77b1d57fa7630355dd290d01b94e4a0d7b6aa | 10,607 | cpp | C++ | Samples/Step03-Using_Render_Passes.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 5 | 2019-03-02T16:29:15.000Z | 2021-11-07T11:07:53.000Z | Samples/Step03-Using_Render_Passes.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | null | null | null | Samples/Step03-Using_Render_Passes.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 2 | 2018-07-10T18:15:40.000Z | 2020-01-03T04:02:32.000Z | //
// Created by aicdg on 2017/6/24.
//
//
// 03-Using_Render_Passes
#include "CookbookSampleFramework.h"
#include "All_Lib.h"
using namespace VKCookbook;
class Sample : public VulkanCookbookSample {
VkDestroyer<VkCommandPool> CommandPool;
VkCommandBuffer CommandBuffer;
VkDestroyer<VkRenderPass> RenderPass;
VkDestroyer<VkFramebuffer> Framebuffer;
VkDestroyer<VkFence> DrawingFence;
VkDestroyer<VkSemaphore> ImageAcquiredSemaphore;
VkDestroyer<VkSemaphore> ReadyToPresentSemaphore;
virtual bool Initialize( WindowParameters WindowParameters ) override {
if( !InitializeVulkan( WindowParameters ) ) {
return false;
}
// Command buffers creation
InitVkDestroyer( LogicalDevice, CommandPool );
if( !CreateCommandPool( *LogicalDevice, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, GraphicsQueue.FamilyIndex, *CommandPool ) ) {
return false;
}
std::vector<VkCommandBuffer> command_buffers;
if( !AllocateCommandBuffers( *LogicalDevice, *CommandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1, command_buffers ) ) {
return false;
}
CommandBuffer = command_buffers[0];
// Drawing synchronization
InitVkDestroyer( LogicalDevice, DrawingFence );
if( !CreateFence( *LogicalDevice, true, *DrawingFence ) ) {
return false;
}
InitVkDestroyer( LogicalDevice, ImageAcquiredSemaphore );
if ( !CreateSemaphore( *LogicalDevice, *ImageAcquiredSemaphore ) ){
return false;
}
InitVkDestroyer( LogicalDevice, ReadyToPresentSemaphore );
if( !CreateSemaphore( *LogicalDevice, *ReadyToPresentSemaphore ) ) {
return false;
}
// Render pass
std::vector<VkAttachmentDescription> attachment_descriptions = {
{
0, // VkAttachmentDescriptionFlags flags
Swapchain.Format, // VkFormat format
VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples
VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp
VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp
VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp
VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR // VkImageLayout finalLayout
}
};
std::vector<SubpassParameters> subpass_parameters = {
{
VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint PipelineType
{}, // std::vector<VkAttachmentReference> InputAttachments
{
{ // std::vector<VkAttachmentReference> ColorAttachments
0, // uint32_t attachment
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout layout
}
},
{}, // std::vector<VkAttachmentReference> ResolveAttachments
nullptr, // VkAttachmentReference const * DepthStencilAttachment
{} // std::vector<uint32_t> PreserveAttachments
}
};
std::vector<VkSubpassDependency> subpass_dependencies = {
{
VK_SUBPASS_EXTERNAL, // uint32_t srcSubpass
0, // uint32_t dstSubpass
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, // VkPipelineStageFlags srcStageMask
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VkPipelineStageFlags dstStageMask
VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags srcAccessMask
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags dstAccessMask
VK_DEPENDENCY_BY_REGION_BIT // VkDependencyFlags dependencyFlags
},
{
0, // uint32_t srcSubpass
VK_SUBPASS_EXTERNAL, // uint32_t dstSubpass
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VkPipelineStageFlags srcStageMask
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, // VkPipelineStageFlags dstStageMask
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags srcAccessMask
VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags dstAccessMask
VK_DEPENDENCY_BY_REGION_BIT // VkDependencyFlags dependencyFlags
}
};
InitVkDestroyer( LogicalDevice, RenderPass );
if ( !CreateRenderPass( *LogicalDevice, attachment_descriptions, subpass_parameters, subpass_dependencies, *RenderPass ) ){
return false;
}
return true;
}
virtual bool Draw() override {
if( !WaitForFences( *LogicalDevice, { *DrawingFence }, false, 5000000000 ) ) {
return false;
}
if( !ResetFences( *LogicalDevice, { *DrawingFence } ) ) {
return false;
}
uint32_t image_index;
if( !AcquireSwapchainImage( *LogicalDevice, *Swapchain.Handle, *ImageAcquiredSemaphore, VK_NULL_HANDLE, image_index ) ) {
return false;
}
InitVkDestroyer( LogicalDevice, Framebuffer );
if( !CreateFramebuffer( *LogicalDevice, *RenderPass, { *Swapchain.ImageViews[image_index] }, Swapchain.Size.width, Swapchain.Size.height, 1, *Framebuffer ) ) {
return false;
}
if( !BeginCommandBufferRecordingOperation( CommandBuffer, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr ) ) {
return false;
}
if( PresentQueue.FamilyIndex != GraphicsQueue.FamilyIndex ) {
ImageTransition image_transition_before_drawing = {
Swapchain.Images[image_index], // VkImage Image
VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags CurrentAccess
VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags NewAccess
VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout CurrentLayout
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout NewLayout
PresentQueue.FamilyIndex, // uint32_t CurrentQueueFamily
GraphicsQueue.FamilyIndex, // uint32_t NewQueueFamily
VK_IMAGE_ASPECT_COLOR_BIT // VkImageAspectFlags Aspect
};
SetImageMemoryBarrier( CommandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, { image_transition_before_drawing } );
}
// Drawing
BeginRenderPass( CommandBuffer, *RenderPass, *Framebuffer, { { 0, 0 }, Swapchain.Size }, { { 0.2f, 0.5f, 0.8f, 1.0f } }, VK_SUBPASS_CONTENTS_INLINE );
EndRenderPass( CommandBuffer );
if( PresentQueue.FamilyIndex != GraphicsQueue.FamilyIndex ) {
ImageTransition image_transition_before_present = {
Swapchain.Images[image_index], // VkImage Image
VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags CurrentAccess
VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags NewAccess
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // VkImageLayout CurrentLayout
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // VkImageLayout NewLayout
GraphicsQueue.FamilyIndex, // uint32_t CurrentQueueFamily
PresentQueue.FamilyIndex, // uint32_t NewQueueFamily
VK_IMAGE_ASPECT_COLOR_BIT // VkImageAspectFlags Aspect
};
SetImageMemoryBarrier( CommandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, { image_transition_before_present } );
}
if( !EndCommandBufferRecordingOperation( CommandBuffer ) ) {
return false;
}
WaitSemaphoreInfo wait_semaphore_info = {
*ImageAcquiredSemaphore, // VkSemaphore Semaphore
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT // VkPipelineStageFlags WaitingStage
};
if( !SubmitCommandBuffersToQueue( GraphicsQueue.Handle, { wait_semaphore_info }, { CommandBuffer }, { *ReadyToPresentSemaphore }, *DrawingFence ) ) {
return false;
}
PresentInfo present_info = {
*Swapchain.Handle, // VkSwapchainKHR Swapchain
image_index // uint32_t ImageIndex
};
if( !PresentImage( PresentQueue.Handle, { *ReadyToPresentSemaphore }, { present_info } ) ) {
return false;
}
return true;
}
virtual bool Resize() override {
if( !CreateSwapchain() ) {
return false;
}
return true;
}
};
VULKAN_COOKBOOK_SAMPLE_FRAMEWORK( "03 - Using Render Passes", 50, 25, 1280, 800, Sample ) | 52.771144 | 182 | 0.536061 | [
"render",
"vector"
] |
cec5333c0348d985136dbcb9e60678298b6f455c | 1,557 | cc | C++ | cpp/src/graph/numIslands.cc | dacozai/algorithm-diary | 8ed5e119e4450e92e63276047ef19bbf422c2770 | [
"MIT"
] | 1 | 2019-10-17T08:34:55.000Z | 2019-10-17T08:34:55.000Z | cpp/src/graph/numIslands.cc | dacozai/algorithm-diary | 8ed5e119e4450e92e63276047ef19bbf422c2770 | [
"MIT"
] | 1 | 2020-05-24T08:32:13.000Z | 2020-05-24T08:32:13.000Z | cpp/src/graph/numIslands.cc | dacozai/algorithm-diary | 8ed5e119e4450e92e63276047ef19bbf422c2770 | [
"MIT"
] | null | null | null | #include "test.h"
/** Question no 200 medium Number of Islands
* Author : Li-Han, Chen; 陳立瀚
* Date : 9th, February, 2020
* Source : https://leetcode.com/problems/number-of-islands/
*
* Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
* An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
* You may assume all four edges of the grid are all surrounded by water.
*
*/
/** Solution (dfs)
* Runtime 8 ms MeMory 10.8 MB;
* faster than 99.15%, less than 80.9%
* O(r*c) ; O(r*c)
*/
class Solution {
private:
int row, col;
public:
int numIslands_dfs(std::vector<std::vector<char>>& grid) {
this->row = grid.size();
if (this->row == 0) return 0;
this->col = grid[0].size();
if (this->col == 0) return 0;
int ans = 0;
for (int i=0; i<this->row; i++) {
for (int j=0; j<this->col; j++) {
if (grid[i][j] == '1') {
ans++;
dfs(grid, i-1, j );
dfs(grid, i , j-1);
dfs(grid, i , j+1);
dfs(grid, i+1, j );
}
}
}
return ans;
}
bool canNotMove_dfs(int r, int c) {
if (r<0 || r>=this->row) return true;
if (c<0 || c>=this->col) return true;
return false;
}
void dfs(vector<vector<char>>& grid, int r, int c) {
if (canNotMove_dfs(r,c)) return;
if (grid[r][c] == '0') return;
grid[r][c] = '0';
dfs(grid, r-1, c );
dfs(grid, r , c-1);
dfs(grid, r , c+1);
dfs(grid, r+1, c );
}
};
| 23.953846 | 107 | 0.537572 | [
"vector"
] |
ced0f065e75b1f2a4f97ff7f2ac0e86f5d63fa22 | 17,428 | hpp | C++ | src/Providers/UNIXProviders/DatabaseSystem/UNIX_DatabaseSystem_FREEBSD.hpp | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/DatabaseSystem/UNIX_DatabaseSystem_FREEBSD.hpp | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/DatabaseSystem/UNIX_DatabaseSystem_FREEBSD.hpp | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
UNIX_DatabaseSystem::UNIX_DatabaseSystem(void)
{
}
UNIX_DatabaseSystem::~UNIX_DatabaseSystem(void)
{
}
Boolean UNIX_DatabaseSystem::getInstanceID(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
return true;
}
String UNIX_DatabaseSystem::getInstanceID() const
{
return caption;
}
Boolean UNIX_DatabaseSystem::getCaption(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CAPTION, getCaption());
return true;
}
String UNIX_DatabaseSystem::getCaption() const
{
return getInstanceID();
}
Boolean UNIX_DatabaseSystem::getDescription(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
return true;
}
String UNIX_DatabaseSystem::getDescription() const
{
return desc;
}
Boolean UNIX_DatabaseSystem::getElementName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
return true;
}
String UNIX_DatabaseSystem::getElementName() const
{
return String("DatabaseSystem");
}
Boolean UNIX_DatabaseSystem::getGeneration(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_GENERATION, getGeneration());
return true;
}
Uint64 UNIX_DatabaseSystem::getGeneration() const
{
return Uint64(0);
}
Boolean UNIX_DatabaseSystem::getInstallDate(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INSTALL_DATE, getInstallDate());
return true;
}
CIMDateTime UNIX_DatabaseSystem::getInstallDate() const
{
struct tm* clock; // create a time structure
time_t val = time(NULL);
clock = gmtime(&(val)); // Get the last modified time and put it into the time structure
return CIMDateTime(
clock->tm_year + 1900,
clock->tm_mon + 1,
clock->tm_mday,
clock->tm_hour,
clock->tm_min,
clock->tm_sec,
0,0,
clock->tm_gmtoff);
}
Boolean UNIX_DatabaseSystem::getName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_NAME, getName());
return true;
}
String UNIX_DatabaseSystem::getName() const
{
switch(currenttype)
{
case POSTGRESQL:
return String("PostgreSQL Database System");
case MYSQL:
return String("MySQL Database System");
case MARIADB:
return String("MariaDB Database System");
case SQLITE:
return String("Sqlite Engine");
case BDB:
return String("Berklay Database Engine");
case MONGODB:
return String("MongoDB Database System");
case MEMCACHED:
return String("Memory Object Cache System");
}
return String ("");
}
Boolean UNIX_DatabaseSystem::getOperationalStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OPERATIONAL_STATUS, getOperationalStatus());
return true;
}
Array<Uint16> UNIX_DatabaseSystem::getOperationalStatus() const
{
Array<Uint16> as;
if (enabled)
as.append(2); //OK
else
as.append(1); //Not Available
return as;
}
Boolean UNIX_DatabaseSystem::getStatusDescriptions(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STATUS_DESCRIPTIONS, getStatusDescriptions());
return true;
}
Array<String> UNIX_DatabaseSystem::getStatusDescriptions() const
{
Array<String> as;
return as;
}
Boolean UNIX_DatabaseSystem::getStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STATUS, getStatus());
return true;
}
String UNIX_DatabaseSystem::getStatus() const
{
return String(DEFAULT_STATUS);
}
Boolean UNIX_DatabaseSystem::getHealthState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_HEALTH_STATE, getHealthState());
return true;
}
Uint16 UNIX_DatabaseSystem::getHealthState() const
{
return Uint16(DEFAULT_HEALTH_STATE);
}
Boolean UNIX_DatabaseSystem::getCommunicationStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_COMMUNICATION_STATUS, getCommunicationStatus());
return true;
}
Uint16 UNIX_DatabaseSystem::getCommunicationStatus() const
{
return Uint16(DEFAULT_COMMUNICATION_STATUS);
}
Boolean UNIX_DatabaseSystem::getDetailedStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DETAILED_STATUS, getDetailedStatus());
return true;
}
Uint16 UNIX_DatabaseSystem::getDetailedStatus() const
{
return Uint16(0);
}
Boolean UNIX_DatabaseSystem::getOperatingStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OPERATING_STATUS, getOperatingStatus());
return true;
}
Uint16 UNIX_DatabaseSystem::getOperatingStatus() const
{
return Uint16(DEFAULT_OPERATING_STATUS);
}
Boolean UNIX_DatabaseSystem::getPrimaryStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIMARY_STATUS, getPrimaryStatus());
return true;
}
Uint16 UNIX_DatabaseSystem::getPrimaryStatus() const
{
return Uint16(DEFAULT_PRIMARY_STATUS);
}
Boolean UNIX_DatabaseSystem::getEnabledState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ENABLED_STATE, getEnabledState());
return true;
}
Uint16 UNIX_DatabaseSystem::getEnabledState() const
{
if (enabled)
return Uint16(2);
return Uint16(3); /* DISABLED */
}
Boolean UNIX_DatabaseSystem::getOtherEnabledState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OTHER_ENABLED_STATE, getOtherEnabledState());
return true;
}
String UNIX_DatabaseSystem::getOtherEnabledState() const
{
if (enabled)
return String ("");
return String("sysrc reporting system disabled or not activated");
}
Boolean UNIX_DatabaseSystem::getRequestedState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_REQUESTED_STATE, getRequestedState());
return true;
}
Uint16 UNIX_DatabaseSystem::getRequestedState() const
{
return Uint16(0);
}
Boolean UNIX_DatabaseSystem::getEnabledDefault(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ENABLED_DEFAULT, getEnabledDefault());
return true;
}
Uint16 UNIX_DatabaseSystem::getEnabledDefault() const
{
return Uint16(0);
}
Boolean UNIX_DatabaseSystem::getTimeOfLastStateChange(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_TIME_OF_LAST_STATE_CHANGE, getTimeOfLastStateChange());
return true;
}
CIMDateTime UNIX_DatabaseSystem::getTimeOfLastStateChange() const
{
if (enabled)
{
struct tm* clock; // create a time structure
time_t val = time(NULL);
clock = gmtime(&(val)); // Get the last modified time and put it into the time structure
return CIMDateTime(
clock->tm_year + 1900,
clock->tm_mon + 1,
clock->tm_mday,
clock->tm_hour,
clock->tm_min,
clock->tm_sec,
0,0,
clock->tm_gmtoff);
}
return CIMHelper::NullDate;
}
Boolean UNIX_DatabaseSystem::getAvailableRequestedStates(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_AVAILABLE_REQUESTED_STATES, getAvailableRequestedStates());
return true;
}
Array<Uint16> UNIX_DatabaseSystem::getAvailableRequestedStates() const
{
Array<Uint16> as;
return as;
}
Boolean UNIX_DatabaseSystem::getTransitioningToState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_TRANSITIONING_TO_STATE, getTransitioningToState());
return true;
}
Uint16 UNIX_DatabaseSystem::getTransitioningToState() const
{
return Uint16(0);
}
Boolean UNIX_DatabaseSystem::getAllocationState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ALLOCATION_STATE, getAllocationState());
return true;
}
String UNIX_DatabaseSystem::getAllocationState() const
{
return String("");
}
Boolean UNIX_DatabaseSystem::getCreationClassName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CREATION_CLASS_NAME, getCreationClassName());
return true;
}
String UNIX_DatabaseSystem::getCreationClassName() const
{
return String("UNIX_DatabaseSystem");
}
Boolean UNIX_DatabaseSystem::getNameFormat(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_NAME_FORMAT, getNameFormat());
return true;
}
String UNIX_DatabaseSystem::getNameFormat() const
{
return String ("");
}
Boolean UNIX_DatabaseSystem::getPrimaryOwnerName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIMARY_OWNER_NAME, getPrimaryOwnerName());
return true;
}
String UNIX_DatabaseSystem::getPrimaryOwnerName() const
{
return owner;
}
Boolean UNIX_DatabaseSystem::getPrimaryOwnerContact(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIMARY_OWNER_CONTACT, getPrimaryOwnerContact());
return true;
}
String UNIX_DatabaseSystem::getPrimaryOwnerContact() const
{
return String ("");
}
Boolean UNIX_DatabaseSystem::getRoles(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ROLES, getRoles());
return true;
}
Array<String> UNIX_DatabaseSystem::getRoles() const
{
Array<String> as;
if (currenttype == POSTGRESQL ||
currenttype == MYSQL ||
currenttype == MARIADB ||
currenttype == MONGODB ||
currenttype == MEMCACHED)
as.append("Database System");
return as;
}
Boolean UNIX_DatabaseSystem::getOtherIdentifyingInfo(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OTHER_IDENTIFYING_INFO, getOtherIdentifyingInfo());
return true;
}
Array<String> UNIX_DatabaseSystem::getOtherIdentifyingInfo() const
{
Array<String> as;
return as;
}
Boolean UNIX_DatabaseSystem::getIdentifyingDescriptions(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_IDENTIFYING_DESCRIPTIONS, getIdentifyingDescriptions());
return true;
}
Array<String> UNIX_DatabaseSystem::getIdentifyingDescriptions() const
{
Array<String> as;
return as;
}
Boolean UNIX_DatabaseSystem::getDistribution(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DISTRIBUTION, getDistribution());
return true;
}
Uint16 UNIX_DatabaseSystem::getDistribution() const
{
/* Check if we are a cluster */
return Uint16(3);
}
Boolean UNIX_DatabaseSystem::getStartupTime(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STARTUP_TIME, getStartupTime());
return true;
}
CIMDateTime UNIX_DatabaseSystem::getStartupTime() const
{
if (enabled)
{
struct tm* clock; // create a time structure
time_t val = time(NULL);
clock = gmtime(&(val)); // Get the last modified time and put it into the time structure
return CIMDateTime(
clock->tm_year + 1900,
clock->tm_mon + 1,
clock->tm_mday,
clock->tm_hour,
clock->tm_min,
clock->tm_sec,
0,0,
clock->tm_gmtoff);
}
return CIMHelper::NullDate;
}
Boolean UNIX_DatabaseSystem::getServingStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_SERVING_STATUS, getServingStatus());
return true;
}
Uint16 UNIX_DatabaseSystem::getServingStatus() const
{
return Uint16(0);
}
Boolean UNIX_DatabaseSystem::getLastServingStatusUpdate(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_LAST_SERVING_STATUS_UPDATE, getLastServingStatusUpdate());
return true;
}
CIMDateTime UNIX_DatabaseSystem::getLastServingStatusUpdate() const
{
if (enabled)
{
struct tm* clock; // create a time structure
time_t val = time(NULL);
clock = gmtime(&(val)); // Get the last modified time and put it into the time structure
return CIMDateTime(
clock->tm_year + 1900,
clock->tm_mon + 1,
clock->tm_mday,
clock->tm_hour,
clock->tm_min,
clock->tm_sec,
0,0,
clock->tm_gmtoff);
}
return CIMHelper::NullDate;
}
String UNIX_DatabaseSystem::getIdentificationCode() const
{
if (currenttype == POSTGRESQL) return String("POSTGRESQL");
else if (currenttype == MYSQL) return String("MYSQL");
else if (currenttype == MARIADB) return String("MARIADB");
else if (currenttype == SQLITE) return String("SQLITE");
else if (currenttype == BDB) return String("BDB");
else if (currenttype == MONGODB) return String("MONGODB");
else if (currenttype == MEMCACHED) return String("MEMCACHED");
return String("");
}
Boolean UNIX_DatabaseSystem::initialize()
{
return true;
}
Boolean UNIX_DatabaseSystem::isEnabled(DBTYPE type)
{
const char *val;
val = NULL;
if (type == POSTGRESQL)
val = "postgresql_enable";
else if (type == MYSQL)
val = "mysql_enable";
else if (type == MARIADB)
val = "mariadb_enable";
else if (type == MONGODB)
val = "mongodb_enable";
else if (type == MEMCACHED)
val = "memcached_enable";
else
val = NULL;
if (val == NULL) return Boolean(true); // All engine are "enabled" or kind of
char cmd[256];
char ret[256];
sprintf(cmd, "%s %s", "/usr/sbin/sysrc -i", val);
sprintf(ret, "%s: YES", val);
cout << "TESTING: " << cmd << endl;
FILE* pipe = popen(cmd, "r");
if (!pipe) return false;
char buffer[256];
bool isenabled = false;
while(!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
{
if (strstr(buffer, ret) != NULL)
{
isenabled = true;
}
}
break;
}
pclose(pipe);
return Boolean(isenabled);
}
Boolean UNIX_DatabaseSystem::load(int &pIndex)
{
UNIX_SoftwareElement softwareElement;
softwareElement.setScope("UNIX_ComputerSystem");
// check if postgresql is installed
if (pIndex == 0)
{
softwareElement.initialize();
if (softwareElement.get(String("postgresql*-server")))
{
caption = name = softwareElement.getInstanceID();
name = softwareElement.getName();
desc = softwareElement.getDescription();
owner = softwareElement.getPrimaryOwnerName();
currenttype = POSTGRESQL;
enabled = isEnabled(currenttype);
return true;
}
pIndex++;
}
// check if mysql is installed
if (pIndex == 1)
{
softwareElement.initialize();
if (softwareElement.get(String("mysql*-server")))
{
caption = name = softwareElement.getInstanceID();
name = softwareElement.getName();
desc = softwareElement.getDescription();
owner = softwareElement.getPrimaryOwnerName();
currenttype = MYSQL;
enabled = isEnabled(currenttype);
return true;
}
pIndex++;
}
// check if mariadb is installed
if (pIndex == 2)
{
softwareElement.initialize();
if (softwareElement.get(String("mariadb*-server")))
{
caption = name = softwareElement.getInstanceID();
name = softwareElement.getName();
desc = softwareElement.getDescription();
owner = softwareElement.getPrimaryOwnerName();
currenttype = MARIADB;
enabled = isEnabled(currenttype);
return true;
}
pIndex++;
}
//check for sqlite
if (pIndex == 3)
{
softwareElement.initialize();
if (softwareElement.get(String("sqlite")))
{
caption = name = softwareElement.getInstanceID();
name = softwareElement.getName();
desc = softwareElement.getDescription();
owner = softwareElement.getPrimaryOwnerName();
currenttype = SQLITE;
enabled = isEnabled(currenttype);
return true;
}
pIndex++;
}
//check for berkley db
if (pIndex == 4)
{
softwareElement.initialize();
if (softwareElement.get(String("db[0-9]")))
{
caption = name = softwareElement.getInstanceID();
name = softwareElement.getName();
desc = softwareElement.getDescription();
owner = softwareElement.getPrimaryOwnerName();
currenttype = BDB;
enabled = isEnabled(currenttype);
return true;
}
pIndex++;
}
//check for mongo db NoSQL
if (pIndex == 5)
{
softwareElement.initialize();
if (softwareElement.get(String("mongodb")))
{
caption = name = softwareElement.getInstanceID();
name = softwareElement.getName();
desc = softwareElement.getDescription();
owner = softwareElement.getPrimaryOwnerName();
currenttype = MONGODB;
enabled = isEnabled(currenttype);
return true;
}
pIndex++;
}
//check for memcached
if (pIndex == 6)
{
softwareElement.initialize();
if (softwareElement.get(String("memcached")))
{
caption = name = softwareElement.getInstanceID();
name = softwareElement.getName();
desc = softwareElement.getDescription();
currenttype = MEMCACHED;
enabled = isEnabled(currenttype);
return true;
}
}
return false;
}
Boolean UNIX_DatabaseSystem::finalize()
{
return true;
}
Boolean UNIX_DatabaseSystem::find(Array<CIMKeyBinding> &kbArray)
{
CIMKeyBinding kb;
String creationClassNameKey;
String nameKey;
for(Uint32 i = 0; i < kbArray.size(); i++)
{
kb = kbArray[i];
CIMName keyName = kb.getName();
if (keyName.equal(PROPERTY_CREATION_CLASS_NAME)) creationClassNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_NAME)) nameKey = kb.getValue();
}
/* Execute find with extracted keys */
bool found = false;
for(int i = 0; load(i); i++)
{
if (String::equalNoCase(getName(),nameKey))
{
found = true;
break;
}
}
return found;
}
| 23.519568 | 90 | 0.729688 | [
"object"
] |
ced79379141a073398e5418d5296b34b1d5fc4e9 | 1,604 | cc | C++ | src/jit.cc | jlarmstrongiv/libtorchjs | d2466337db2707157f8b402dbefd80e84466e3a1 | [
"BSD-3-Clause"
] | 20 | 2019-01-08T00:45:44.000Z | 2021-05-21T23:38:26.000Z | src/jit.cc | jlarmstrongiv/libtorchjs | d2466337db2707157f8b402dbefd80e84466e3a1 | [
"BSD-3-Clause"
] | 5 | 2020-02-19T14:39:00.000Z | 2021-04-18T20:33:49.000Z | src/jit.cc | jlarmstrongiv/libtorchjs | d2466337db2707157f8b402dbefd80e84466e3a1 | [
"BSD-3-Clause"
] | 4 | 2019-07-14T10:50:08.000Z | 2021-04-10T20:19:52.000Z | #include "jit.h"
#include "script_module.h"
#include <torch/torch.h>
#include <torch/script.h>
#include <stdlib.h>
#include <napi.h>
namespace libtorchjs {
class LoadWorker : public Napi::AsyncWorker {
public:
static void load(const Napi::CallbackInfo &info) {
// first arg is saved script module filename
std::string filename = info[0].As<Napi::String>().Utf8Value();
// 2nd arg is callback
Napi::Function cb = info[1].As<Napi::Function>();
// load async
auto *worker = new LoadWorker(cb, filename);
worker->Queue();
}
protected:
void Execute() override {
// load with torch::jit
module = torch::jit::load(filename);
}
void OnOK() override {
Napi::HandleScope scope(Env());
// create napi ScriptModule
auto scriptModule = ScriptModule::NewInstance();
// set loaded module
Napi::ObjectWrap<ScriptModule>::Unwrap(scriptModule)->setModule(module);
Callback().Call({Env().Undefined(), scriptModule});
}
private:
LoadWorker(Napi::Function cb, std::string &filename)
: Napi::AsyncWorker(cb), filename(filename) {}
torch::jit::script::Module module;
std::string filename;
};
Napi::Object JitInit(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "load"), Napi::Function::New(env, LoadWorker::load));
return exports;
}
} | 32.734694 | 97 | 0.55985 | [
"object"
] |
cee9554b95d1dc1346520069ce218a3db689777d | 1,348 | cpp | C++ | problems/max_area_of_island/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | problems/max_area_of_island/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | problems/max_area_of_island/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
queue<pair<int, int>> Q;
int ans = 0;
auto isFine = [&](int x, int y) {
if (x < 0 || y < 0 || x >= n || y >= m) return false;
return true;
};
vector<int> dx {1, 0, -1, 0};
vector<int> dy {0, 1, 0, -1};
const int N = 4;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
Q.push({i, j});
grid[i][j] = 0;
int res = 0;
while (!Q.empty()) {
int x = Q.front().first, y = Q.front().second;
res++;
Q.pop();
for (int k = 0; k < N; k++) {
int _x = x + dx[k];
int _y = y + dy[k];
if (isFine(_x, _y) && grid[_x][_y] == 1) {
Q.push({_x, _y});
grid[_x][_y] = 0;
}
}
}
ans = max(ans, res);
}
}
}
return ans;
}
}; | 33.7 | 70 | 0.281899 | [
"vector"
] |
ceee4ad2d156b2d384230289084b3065301957a3 | 245 | cpp | C++ | src/base/py.cpp | alexa-infra/negine | d9060a7c83a41c95c361c470b56c2ddab3ba04de | [
"MIT"
] | 4 | 2016-11-11T20:35:34.000Z | 2018-12-24T18:30:16.000Z | src/base/py.cpp | alexa-infra/negine | d9060a7c83a41c95c361c470b56c2ddab3ba04de | [
"MIT"
] | null | null | null | src/base/py.cpp | alexa-infra/negine | d9060a7c83a41c95c361c470b56c2ddab3ba04de | [
"MIT"
] | null | null | null | #include "base/py.h"
#include <cmath>
#include <boost/python.hpp>
#include "math/py_math.h"
#include "render/py_render.h"
using namespace boost::python;
BOOST_PYTHON_MODULE(negine_core)
{
init_py_math();
init_py_render();
} | 18.846154 | 33 | 0.693878 | [
"render"
] |
cef4b3d04099548422ce7190c44587e08fc367c6 | 4,938 | hpp | C++ | WuManber.hpp | ebayboy/WuManber | 2f71780058e774a08299d5da40128cae64c96fd0 | [
"MIT"
] | null | null | null | WuManber.hpp | ebayboy/WuManber | 2f71780058e774a08299d5da40128cae64c96fd0 | [
"MIT"
] | null | null | null | WuManber.hpp | ebayboy/WuManber | 2f71780058e774a08299d5da40128cae64c96fd0 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <unordered_map>
#include <algorithm>
#include <list>
#include <vector>
#include <cstddef>
#include <iostream>
#include <cstdio>
#include <string>
struct WMResult_t {
std::size_t pattern_id;
std::size_t index;
};
class WuManber {
public:
// constructor
WuManber(): initialized(false), B(2), m(0), patterns(), patterns_id(), shift_table(), aux_shift_table(), hash_table() {};
int Init(const std::vector<size_t>& exprs_id, const std::vector<std::string>& exprs)
{
if (exprs_id.size() != exprs.size()) {
std::cout << "Error: exprs.size:" << exprs.size() << " exprs_id.size:" << exprs_id.size() << std::endl;
return -1;
}
patterns.assign(exprs.begin(), exprs.end());
patterns_id.assign(exprs_id.begin(), exprs_id.end());
std::cout << "patterns.size:" << patterns.size() << std::endl;;
std::cout << "patterns_id.size:" << patterns_id.size() << std::endl;
//Init of m
for (auto iter = patterns.begin(); iter != patterns.end(); ++iter) {
m = (m == 0) ? iter->length() : std::min(iter->length(), m);
}
//Init of tables for each block in each pattern
std::size_t pattern_index = 0;
for (auto pattern_iter = patterns.begin();
pattern_iter != patterns.end();
++pattern_iter, ++pattern_index) {
for (std::size_t char_index = 0; char_index < m - B + 1; ++char_index) {
std::string block = pattern_iter->substr(char_index, B);
std::size_t block_pos = m - char_index - B;
std::size_t last_shift = (block_pos == 0) ? m - B + 1 : block_pos;
//Init of SHIFT table
if (shift_table.count(block)) {
last_shift = shift_table[block];
shift_table[block] = std::min(shift_table[block], block_pos);
}
else {
shift_table[block] = block_pos;
}
//Init of HASH table
if (block_pos == 0) {
hash_table[block].push_back(pattern_index);
if (last_shift != 0) {
if (aux_shift_table.count(block))
aux_shift_table[block] = std::min(aux_shift_table[block], last_shift);
else
aux_shift_table[block] = last_shift;
}
}
}
}
initialized = true;
return 0;
}
//contructor end
//destructor
virtual ~WuManber() {};
//FUNCTION:
// Search text with patterns;
//@text:
// intput text
//@wmresults :
// not nullptr: output result_set
// nullptr: not output result_set
//RETURN:
// error: -1
// ok : hit count
int Search(const std::string & text, std::vector<WMResult_t> *wmresults)
{
int hit_count = 0;
if (!initialized) {
std::cerr << "Error: not initialized!!!" << std::endl;
return -1;
}
for (size_t char_index = m - B; char_index < text.length(); ++char_index) {
std::string block = text.substr(char_index, B);
auto shift_value = shift_table.find(block);
if (shift_value != shift_table.end()) {
if (shift_value->second == 0) {//Possible match
auto possibles = hash_table.at(block);
for (auto pattern_iter = possibles.begin(); pattern_iter != possibles.end(); ++pattern_iter) {
std::string_view pattern = patterns[*pattern_iter];
std::size_t char_pos = char_index - m + B;
std::size_t i;
for (i = 0; i < pattern.length(); ++i) {
if (pattern.at(i) != text.at(char_pos + i)) {
break;
}
}
if (i == pattern.length()) {
hit_count++;
if (wmresults) {
WMResult_t r{patterns_id.at(*pattern_iter), char_pos};
wmresults->emplace_back(r);
}
}
}
char_index += aux_shift_table.at(block) - 1;//Shift according to ASHIFT[block]
}
else
char_index += shift_value->second - 1;//Shift according to SHIFT[block]
}
else {
char_index += m - B; //Shift the maximum possible to the right
}
}
return hit_count;
}
friend std::ostream &operator << (std::ostream &output, const WuManber &b) {
std::cout << "initialized:" << b.initialized << std::endl;
if (b.patterns.size() != b.patterns_id.size()) {
std::cerr << "Error: patterns.size:" << b.patterns.size() << " patterns_id.size:" << b.patterns_id.size() << std::endl;
}
std::cout << "Patterns:" << std::endl;
for (size_t i = 0; i < b.patterns.size(); i++ ) {
std::cout << "\t" << b.patterns_id[i] << ":" << b.patterns[i] << std::endl;
}
return output;
}
private:
bool initialized;
//Block size
std::size_t B;
//Patterns minimum length
std::size_t m;
std::vector<std::string> patterns;
std::vector<size_t> patterns_id;
std::unordered_map<std::string, std::size_t> shift_table;
std::unordered_map<std::string, std::size_t> aux_shift_table;
std::unordered_map<std::string, std::list<std::size_t> > hash_table;
};
| 29.218935 | 125 | 0.585662 | [
"vector"
] |
cef7bf47faba1fecaba15e24ff86b5309745dab3 | 24,032 | cpp | C++ | implementations/ugene/src/corelibs/U2Core/src/datatype/msa/MultipleChromatogramAlignment.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/corelibs/U2Core/src/datatype/msa/MultipleChromatogramAlignment.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/corelibs/U2Core/src/datatype/msa/MultipleChromatogramAlignment.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* 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.
*/
#include <typeinfo>
#include <QSet>
#include <U2Core/McaRowInnerData.h>
#include <U2Core/U2OpStatusUtils.h>
#include <U2Core/U2SafePoints.h>
#include "MaStateCheck.h"
#include "MultipleAlignmentInfo.h"
#include "MultipleChromatogramAlignment.h"
namespace U2 {
MultipleChromatogramAlignment::MultipleChromatogramAlignment()
: MultipleAlignment(new MultipleChromatogramAlignmentData()) {
}
MultipleChromatogramAlignment::MultipleChromatogramAlignment(const MultipleAlignment &ma)
: MultipleAlignment(ma) {
SAFE_POINT(NULL != maData.dynamicCast<MultipleChromatogramAlignmentData>(), "Can't cast MultipleAlignment to MultipleChromatogramAlignment", );
}
MultipleChromatogramAlignment::MultipleChromatogramAlignment(MultipleChromatogramAlignmentData *mcaData)
: MultipleAlignment(mcaData) {
}
MultipleChromatogramAlignment::MultipleChromatogramAlignment(const QString &name, const DNAAlphabet *alphabet, const QList<MultipleChromatogramAlignmentRow> &rows)
: MultipleAlignment(new MultipleChromatogramAlignmentData(name, alphabet, rows)) {
}
MultipleChromatogramAlignmentData *MultipleChromatogramAlignment::data() const {
return getMcaData().data();
}
MultipleChromatogramAlignmentData &MultipleChromatogramAlignment::operator*() {
return *getMcaData();
}
const MultipleChromatogramAlignmentData &MultipleChromatogramAlignment::operator*() const {
return *getMcaData();
}
MultipleChromatogramAlignmentData *MultipleChromatogramAlignment::operator->() {
return getMcaData().data();
}
const MultipleChromatogramAlignmentData *MultipleChromatogramAlignment::operator->() const {
return getMcaData().data();
}
MultipleChromatogramAlignment MultipleChromatogramAlignment::clone() const {
return getMcaData()->getCopy();
}
QSharedPointer<MultipleChromatogramAlignmentData> MultipleChromatogramAlignment::getMcaData() const {
return maData.dynamicCast<MultipleChromatogramAlignmentData>();
}
namespace {
QList<MultipleAlignmentRow> convertToMaRows(const QList<MultipleChromatogramAlignmentRow> &mcaRows) {
QList<MultipleAlignmentRow> maRows;
foreach (const MultipleChromatogramAlignmentRow &mcaRow, mcaRows) {
maRows << mcaRow;
}
return maRows;
}
} // namespace
MultipleChromatogramAlignmentData::MultipleChromatogramAlignmentData(const QString &name, const DNAAlphabet *alphabet, const QList<MultipleChromatogramAlignmentRow> &rows)
: MultipleAlignmentData(name, alphabet, convertToMaRows(rows)) {
}
MultipleChromatogramAlignmentData::MultipleChromatogramAlignmentData(const MultipleChromatogramAlignmentData &mcaData)
: MultipleAlignmentData() {
copy(mcaData);
}
MultipleChromatogramAlignmentData &MultipleChromatogramAlignmentData::operator=(const MultipleChromatogramAlignment &mca) {
return *this = *mca;
}
MultipleChromatogramAlignmentData &MultipleChromatogramAlignmentData::operator=(const MultipleChromatogramAlignmentData &mcaData) {
copy(mcaData);
return *this;
}
bool MultipleChromatogramAlignmentData::trim(bool removeLeadingGaps) {
MaStateCheck check(this);
Q_UNUSED(check);
bool result = false;
if (removeLeadingGaps) {
// Verify if there are leading columns of gaps
// by checking the first gap in each row
qint64 leadingGapColumnsNum = 0;
foreach (const MultipleChromatogramAlignmentRow &row, rows) {
if (row->getGapModel().count() > 0) {
const U2MsaGap firstGap = row->getGapModel().first();
if (firstGap.offset > 0) {
leadingGapColumnsNum = 0;
break;
} else {
if (leadingGapColumnsNum == 0) {
leadingGapColumnsNum = firstGap.gap;
} else {
leadingGapColumnsNum = qMin(leadingGapColumnsNum, firstGap.gap);
}
}
} else {
leadingGapColumnsNum = 0;
break;
}
}
// If there are leading gap columns, remove them
U2OpStatus2Log os;
if (leadingGapColumnsNum > 0) {
for (int i = 0; i < getNumRows(); ++i) {
getMcaRow(i)->removeChars(0, leadingGapColumnsNum, os);
CHECK_OP(os, true);
result = true;
}
}
}
// Verify right side of the alignment (trailing gaps and rows' lengths)
qint64 newLength = 0;
foreach (const MultipleChromatogramAlignmentRow &row, rows) {
if (newLength == 0) {
newLength = row->getRowLengthWithoutTrailing();
} else {
newLength = qMax(row->getRowLengthWithoutTrailing(), newLength);
}
}
if (newLength != length) {
length = newLength;
result = true;
}
return result;
}
bool MultipleChromatogramAlignmentData::simplify() {
MaStateCheck check(this);
Q_UNUSED(check);
int newLen = 0;
bool changed = false;
for (int i = 0, n = getNumRows(); i < n; i++) {
changed |= getMcaRow(i)->simplify();
newLen = qMax(newLen, getMcaRow(i)->getCoreEnd());
}
if (!changed) {
assert(length == newLen);
return false;
}
length = newLen;
return true;
}
bool MultipleChromatogramAlignmentData::hasEmptyGapModel() const {
foreach (const MultipleChromatogramAlignmentRow &row, rows) {
if (!row->getGapModel().isEmpty()) {
return false;
}
}
return true;
}
bool MultipleChromatogramAlignmentData::hasEqualLength() const {
const int defaultSequenceLength = -1;
int sequenceLength = defaultSequenceLength;
for (int i = 0, n = rows.size(); i < n; ++i) {
if (defaultSequenceLength != sequenceLength && sequenceLength != getMcaRow(i)->getUngappedLength()) {
return false;
} else {
sequenceLength = getMcaRow(i)->getUngappedLength();
}
}
return true;
}
MultipleChromatogramAlignment MultipleChromatogramAlignmentData::mid(int start, int len) const {
SAFE_POINT(start >= 0 && start + len <= length,
QString("Incorrect parameters were passed to MultipleChromatogramAlignmentData::mid: "
"start '%1', len '%2', the alignment length is '%3'")
.arg(start)
.arg(len)
.arg(length),
MultipleChromatogramAlignment());
MultipleChromatogramAlignment res(getName(), alphabet);
MaStateCheck check(res.data());
Q_UNUSED(check);
U2OpStatus2Log os;
foreach (const MultipleChromatogramAlignmentRow &row, rows) {
MultipleChromatogramAlignmentRow mRow = row->mid(start, len, os);
mRow->setParentAlignment(res);
res->rows << mRow;
}
res->length = len;
return res;
}
MultipleChromatogramAlignmentData &MultipleChromatogramAlignmentData::operator+=(const MultipleChromatogramAlignmentData &mcaData) {
// TODO: it is used in MUSCLE alignment and it should be something like this. But this emthod is incorrect for the MCA
MaStateCheck check(this);
Q_UNUSED(check);
SAFE_POINT(mcaData.alphabet == alphabet, "Different alphabets in MultipleChromatogramAlignmentData::operator+=", *this);
int nSeq = getNumRows();
SAFE_POINT(mcaData.getNumRows() == nSeq, "Different number of rows in MultipleChromatogramAlignmentData::operator+=", *this);
U2OpStatus2Log os;
for (int i = 0; i < nSeq; i++) {
getMcaRow(i)->append(mcaData.getMcaRow(i), length, os);
}
length += mcaData.length;
return *this;
}
bool MultipleChromatogramAlignmentData::operator==(const MultipleChromatogramAlignmentData &other) const {
bool lengthsAreEqual = (length == other.length);
bool alphabetsAreEqual = (alphabet == other.alphabet);
bool rowsAreEqual = (rows == other.rows);
return lengthsAreEqual && alphabetsAreEqual && rowsAreEqual;
}
bool MultipleChromatogramAlignmentData::operator!=(const MultipleChromatogramAlignmentData &other) const {
return !operator==(other);
}
bool MultipleChromatogramAlignmentData::crop(const U2Region ®ion, const QSet<QString> &rowNames, U2OpStatus &os) {
if (!(region.startPos >= 0 && region.length > 0 && region.length < length && region.startPos < length)) {
os.setError(QString("Incorrect region was passed to MultipleChromatogramAlignmentData::crop, "
"startPos '%1', length '%2'")
.arg(region.startPos)
.arg(region.length));
return false;
}
int cropLen = region.length;
if (region.endPos() > length) {
cropLen -= (region.endPos() - length);
}
MaStateCheck check(this);
Q_UNUSED(check);
QList<MultipleChromatogramAlignmentRow> newList;
for (int i = 0; i < rows.size(); i++) {
MultipleChromatogramAlignmentRow row = getMcaRow(i).clone();
const QString rowName = row->getName();
if (rowNames.contains(rowName)) {
row->crop(os, region.startPos, cropLen);
CHECK_OP(os, false);
newList << row;
}
}
setRows(newList);
length = cropLen;
return true;
}
bool MultipleChromatogramAlignmentData::crop(const U2Region ®ion, U2OpStatus &os) {
return crop(region, getRowNames().toSet(), os);
}
bool MultipleChromatogramAlignmentData::crop(int start, int count, U2OpStatus &os) {
return crop(U2Region(start, count), os);
}
MultipleChromatogramAlignmentRow MultipleChromatogramAlignmentData::createRow(const QString &name, const DNAChromatogram &chromatogram, const QByteArray &bytes) {
QByteArray newSequenceBytes;
QList<U2MsaGap> newGapsModel;
MultipleChromatogramAlignmentRowData::splitBytesToCharsAndGaps(bytes, newSequenceBytes, newGapsModel);
DNASequence newSequence(name, newSequenceBytes);
U2MsaRow row;
return MultipleChromatogramAlignmentRow(row, chromatogram, newSequence, newGapsModel, this);
}
MultipleChromatogramAlignmentRow MultipleChromatogramAlignmentData::createRow(const U2MsaRow &rowInDb, const DNAChromatogram &chromatogram, const DNASequence &sequence, const U2MsaRowGapModel &gaps, U2OpStatus &os) {
QString errorDescr = "Failed to create a multiple alignment row";
if (-1 != sequence.constSequence().indexOf(U2Msa::GAP_CHAR)) {
coreLog.trace("Attempted to create an alignment row from a sequence with gaps");
os.setError(errorDescr);
return MultipleChromatogramAlignmentRow();
}
int length = sequence.length();
foreach (const U2MsaGap &gap, gaps) {
if (gap.offset > length || !gap.isValid()) {
coreLog.trace("Incorrect gap model was passed to MultipleChromatogramAlignmentData::createRow");
os.setError(errorDescr);
return MultipleChromatogramAlignmentRow();
}
length += gap.gap;
}
return MultipleChromatogramAlignmentRow(rowInDb, chromatogram, sequence, gaps, this);
}
MultipleChromatogramAlignmentRow MultipleChromatogramAlignmentData::createRow(const MultipleChromatogramAlignmentRow &row) {
return MultipleChromatogramAlignmentRow(row, this);
}
void MultipleChromatogramAlignmentData::setRows(const QList<MultipleChromatogramAlignmentRow> &mcaRows) {
rows = convertToMaRows(mcaRows);
}
void MultipleChromatogramAlignmentData::addRow(const QString &name, const DNAChromatogram &chromatogram, const QByteArray &bytes) {
MultipleChromatogramAlignmentRow newRow = createRow(name, chromatogram, bytes);
addRowPrivate(newRow, bytes.size(), -1);
}
void MultipleChromatogramAlignmentData::addRow(const QString &name, const DNAChromatogram &chromatogram, const QByteArray &bytes, int rowIndex) {
MultipleChromatogramAlignmentRow newRow = createRow(name, chromatogram, bytes);
addRowPrivate(newRow, bytes.size(), rowIndex);
}
void MultipleChromatogramAlignmentData::addRow(const U2MsaRow &rowInDb, const DNAChromatogram &chromatogram, const DNASequence &sequence, U2OpStatus &os) {
MultipleChromatogramAlignmentRow newRow = createRow(rowInDb, chromatogram, sequence, rowInDb.gaps, os);
CHECK_OP(os, );
addRowPrivate(newRow, rowInDb.length, -1);
}
void MultipleChromatogramAlignmentData::addRow(const QString &name, const DNAChromatogram &chromatogram, const DNASequence &sequence, const U2MsaRowGapModel &gaps, U2OpStatus &os) {
U2MsaRow row;
MultipleChromatogramAlignmentRow newRow = createRow(row, chromatogram, sequence, gaps, os);
CHECK_OP(os, );
int len = sequence.length();
foreach (const U2MsaGap &gap, gaps) {
len += gap.gap;
}
newRow->setName(name);
addRowPrivate(newRow, len, -1);
}
void MultipleChromatogramAlignmentData::addRow(const U2MsaRow &rowInDb, const McaRowMemoryData &mcaRowMemoryData, U2OpStatus &os) {
addRow(rowInDb, mcaRowMemoryData.chromatogram, mcaRowMemoryData.sequence, os);
}
void MultipleChromatogramAlignmentData::insertGaps(int row, int pos, int count, U2OpStatus &os) {
if (pos > length) {
length = pos + count;
return;
}
if (row >= getNumRows() || row < 0 || pos < 0 || count < 0) {
coreLog.trace(QString("Internal error: incorrect parameters were passed "
"to MultipleChromatogramAlignmentData::insertGaps: row index '%1', pos '%2', count '%3'")
.arg(row)
.arg(pos)
.arg(count));
os.setError("Failed to insert gaps into an alignment");
return;
}
if (pos == length) {
// add trailing gaps --> just increase alignment len
length += count;
return;
}
MaStateCheck check(this);
Q_UNUSED(check);
if (pos >= rows[row]->getRowLengthWithoutTrailing()) {
length += count;
return;
}
getMcaRow(row)->insertGaps(pos, count, os);
qint64 rowLength = rows[row]->getRowLengthWithoutTrailing();
length = qMax(length, rowLength);
}
void MultipleChromatogramAlignmentData::appendChars(int row, const char *str, int len) {
SAFE_POINT(0 <= row && row < getNumRows(),
QString("Incorrect row index '%1' in MultipleChromatogramAlignmentData::appendChars").arg(row), );
MultipleChromatogramAlignmentRow appendedRow = createRow("", DNAChromatogram(), QByteArray(str, len));
qint64 rowLength = getMcaRow(row)->getRowLength();
U2OpStatus2Log os;
getMcaRow(row)->append(appendedRow, rowLength, os);
CHECK_OP(os, );
length = qMax(length, rowLength + len);
}
void MultipleChromatogramAlignmentData::appendChars(int row, qint64 afterPos, const char *str, int len) {
SAFE_POINT(0 <= row && row < getNumRows(),
QString("Incorrect row index '%1' in MultipleChromatogramAlignmentData::appendChars").arg(row), );
MultipleChromatogramAlignmentRow appendedRow = createRow("", DNAChromatogram(), QByteArray(str, len));
U2OpStatus2Log os;
getMcaRow(row)->append(appendedRow, afterPos, os);
CHECK_OP(os, );
length = qMax(length, afterPos + len);
}
void MultipleChromatogramAlignmentData::removeRegion(int startPos, int startRow, int nBases, int nRows, bool removeEmptyRows) {
SAFE_POINT(startPos >= 0 && startPos + nBases <= length && nBases > 0,
QString("Incorrect parameters were passed to MultipleChromatogramAlignmentData::removeRegion: startPos '%1', "
"nBases '%2', the length is '%3'")
.arg(startPos)
.arg(nBases)
.arg(length), );
SAFE_POINT(startRow >= 0 && startRow + nRows <= getNumRows() && nRows > 0,
QString("Incorrect parameters were passed to MultipleChromatogramAlignmentData::removeRegion: startRow '%1', "
"nRows '%2', the number of rows is '%3'")
.arg(startRow)
.arg(nRows)
.arg(getNumRows()), );
MaStateCheck check(this);
Q_UNUSED(check);
U2OpStatus2Log os;
for (int i = startRow + nRows; --i >= startRow;) {
getMcaRow(i)->removeChars(startPos, nBases, os);
SAFE_POINT_OP(os, );
if (removeEmptyRows && (0 == getMcaRow(i)->getSequence().length())) {
rows.removeAt(i);
}
}
if (nRows == rows.size()) {
// full columns were removed
length -= nBases;
if (length == 0) {
rows.clear();
}
}
}
int MultipleChromatogramAlignmentData::getNumRows() const {
return rows.size();
}
void MultipleChromatogramAlignmentData::renameRow(int row, const QString &name) {
SAFE_POINT(row >= 0 && row < getNumRows(),
QString("Incorrect row index '%1' was passed to MultipleChromatogramAlignmentData::renameRow: "
"the number of rows is '%2'")
.arg(row)
.arg(getNumRows()), );
SAFE_POINT(!name.isEmpty(),
"Incorrect parameter 'name' was passed to MultipleChromatogramAlignmentData::renameRow: "
"Can't set the name of a row to an empty string", );
rows[row]->setName(name);
}
void MultipleChromatogramAlignmentData::replaceChars(int row, char origChar, char resultChar) {
SAFE_POINT(row >= 0 && row < getNumRows(), QString("Incorrect row index '%1' in MultipleChromatogramAlignmentData::replaceChars").arg(row), );
if (origChar == resultChar) {
return;
}
U2OpStatus2Log os;
getMcaRow(row)->replaceChars(origChar, resultChar, os);
}
void MultipleChromatogramAlignmentData::setRowContent(int rowNumber, const DNAChromatogram &chromatogram, const QByteArray &sequence, int offset) {
SAFE_POINT(rowNumber >= 0 && rowNumber < getNumRows(),
QString("Incorrect row index '%1' was passed to MultipleChromatogramAlignmentData::setRowContent: "
"the number of rows is '%2'")
.arg(rowNumber)
.arg(getNumRows()), );
MaStateCheck check(this);
Q_UNUSED(check);
U2OpStatus2Log os;
getMcaRow(rowNumber)->setRowContent(chromatogram, sequence, offset, os);
SAFE_POINT_OP(os, );
length = qMax(length, (qint64)sequence.size() + offset);
}
void MultipleChromatogramAlignmentData::setRowContent(int rowNumber, const DNAChromatogram &chromatogram, const DNASequence &sequence, const U2MsaRowGapModel &gapModel) {
SAFE_POINT(rowNumber >= 0 && rowNumber < getNumRows(),
QString("Incorrect row index '%1' was passed to MultipleChromatogramAlignmentData::setRowContent: "
"the number of rows is '%2'")
.arg(rowNumber)
.arg(getNumRows()), );
MaStateCheck check(this);
Q_UNUSED(check);
U2OpStatus2Log os;
getMcaRow(rowNumber)->setRowContent(chromatogram, sequence, gapModel, os);
SAFE_POINT_OP(os, );
length = qMax(length, (qint64)MsaRowUtils::getRowLength(sequence.seq, gapModel));
}
void MultipleChromatogramAlignmentData::setRowContent(int rowNumber, const McaRowMemoryData &mcaRowMemoryData) {
setRowContent(rowNumber, mcaRowMemoryData.chromatogram, mcaRowMemoryData.sequence, mcaRowMemoryData.gapModel);
}
void MultipleChromatogramAlignmentData::toUpperCase() {
for (int i = 0, n = getNumRows(); i < n; i++) {
getMcaRow(i)->toUpperCase();
}
}
bool MultipleChromatogramAlignmentData::sortRowsBySimilarity(QVector<U2Region> &united) {
QList<MultipleChromatogramAlignmentRow> oldRows = getMcaRows();
QList<MultipleChromatogramAlignmentRow> sortedRows;
while (!oldRows.isEmpty()) {
const MultipleChromatogramAlignmentRow row = oldRows.takeFirst();
sortedRows << row;
int start = sortedRows.size() - 1;
int len = 1;
QMutableListIterator<MultipleChromatogramAlignmentRow> iter(oldRows);
while (iter.hasNext()) {
const MultipleChromatogramAlignmentRow &next = iter.next();
if (next->isRowContentEqual(row)) {
sortedRows << next;
iter.remove();
++len;
}
}
if (len > 1) {
united.append(U2Region(start, len));
}
}
if (getMcaRows() != sortedRows) {
setRows(sortedRows);
return true;
}
return false;
}
const QList<MultipleChromatogramAlignmentRow> MultipleChromatogramAlignmentData::getMcaRows() const {
QList<MultipleChromatogramAlignmentRow> mcaRows;
foreach (const MultipleAlignmentRow &maRow, rows) {
mcaRows << maRow.dynamicCast<MultipleChromatogramAlignmentRow>();
}
return mcaRows;
}
MultipleChromatogramAlignmentRow MultipleChromatogramAlignmentData::getMcaRowByRowId(qint64 rowId, U2OpStatus &os) const {
return getRowByRowId(rowId, os).dynamicCast<MultipleChromatogramAlignmentRow>(os);
}
char MultipleChromatogramAlignmentData::charAt(int rowNumber, int pos) const {
return getMcaRow(rowNumber)->charAt(pos);
}
bool MultipleChromatogramAlignmentData::isGap(int rowNumber, int pos) const {
return getMcaRow(rowNumber)->isGap(pos);
}
bool MultipleChromatogramAlignmentData::isTrailingOrLeadingGap(int rowNumber, int pos) const {
return getMcaRow(rowNumber)->isTrailingOrLeadingGap(pos);
}
void MultipleChromatogramAlignmentData::setRowGapModel(int rowNumber, const QList<U2MsaGap> &gapModel) {
SAFE_POINT(rowNumber >= 0 && rowNumber < getNumRows(), "Invalid row index", );
length = qMax(length, (qint64)MsaRowUtils::getGapsLength(gapModel) + getMcaRow(rowNumber)->sequence.length());
getMcaRow(rowNumber)->setGapModel(gapModel);
}
void MultipleChromatogramAlignmentData::setSequenceId(int rowIndex, const U2DataId &sequenceId) {
SAFE_POINT(rowIndex >= 0 && rowIndex < getNumRows(), "Invalid row index", );
getMcaRow(rowIndex)->setSequenceId(sequenceId);
}
const MultipleChromatogramAlignmentRow MultipleChromatogramAlignmentData::getMcaRow(const QString &name) const {
return getRow(name).dynamicCast<const MultipleChromatogramAlignmentRow>();
}
MultipleAlignment MultipleChromatogramAlignmentData::getCopy() const {
return getExplicitCopy();
}
MultipleChromatogramAlignment MultipleChromatogramAlignmentData::getExplicitCopy() const {
return MultipleChromatogramAlignment(new MultipleChromatogramAlignmentData(*this));
}
void MultipleChromatogramAlignmentData::copy(const MultipleAlignmentData &other) {
try {
copy(dynamic_cast<const MultipleChromatogramAlignmentData &>(other));
} catch (std::bad_cast) {
FAIL("Can't cast MultipleAlignmentData to MultipleChromatogramAlignmentData", );
}
}
void MultipleChromatogramAlignmentData::copy(const MultipleChromatogramAlignmentData &other) {
clear();
alphabet = other.alphabet;
length = other.length;
info = other.info;
for (int i = 0; i < other.rows.size(); i++) {
const MultipleChromatogramAlignmentRow row = createRow(other.rows[i]);
addRowPrivate(row, other.length, i);
}
}
MultipleAlignmentRow MultipleChromatogramAlignmentData::getEmptyRow() const {
return MultipleChromatogramAlignmentRow();
}
} // namespace U2
| 37.201238 | 216 | 0.683505 | [
"model"
] |
cefa1c3a2c453c0c9c4bb75a98e1a7a14994fc16 | 2,863 | cpp | C++ | Gfg/C++/Rotten Oranges.cpp | abdzitter/Daily-Coding-DS-ALGO-Practice | 26ddbf7a3673608039a07d26d812fce31b69871a | [
"MIT"
] | 289 | 2021-05-15T22:56:03.000Z | 2022-03-28T23:13:25.000Z | Gfg/C++/Rotten Oranges.cpp | abdzitter/Daily-Coding-DS-ALGO-Practice | 26ddbf7a3673608039a07d26d812fce31b69871a | [
"MIT"
] | 1,812 | 2021-05-09T13:49:58.000Z | 2022-01-15T19:27:17.000Z | Gfg/C++/Rotten Oranges.cpp | abdzitter/Daily-Coding-DS-ALGO-Practice | 26ddbf7a3673608039a07d26d812fce31b69871a | [
"MIT"
] | 663 | 2021-05-09T16:57:58.000Z | 2022-03-27T14:15:07.000Z | // Link tp problem:
//https://practice.geeksforgeeks.org/problems/rotten-oranges2536/1
/*Algorithm:
First we will push the index of grid having value 2(rotten orange) and count total no of fresh oranges. Then we will keep poping
index from queue and add the adjacent oranges which will get rot. We will keep count of answer and after the queue become empty
we will check that if there is no fresh oranges left we will return the ans else -1(not possible to rot all oranges)
*/
#include<bits/stdc++.h>
using namespace std;
class Solution
{
public:
//Function to find minimum time required to rot all oranges.
int orangesRotting(vector<vector<int>>& grid) {
int r=grid.size(),c=grid[0].size(),i,j,t=0,f=0;
queue<pair<int,int>>q;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
if(grid[i][j]==2)
q.push({i,j}); //stoding in queue
else
{
if(grid[i][j]==1)
f++; //keeping fresh count
}
}
while(!q.empty())
{
int m=q.size();
for(i=0;i<m;i++)
{
int x=q.front().first,y=q.front().second;
q.pop();
//Checking adjacent fresh oranges
if(x>0 && grid[x-1][y]==1)
{
grid[x-1][y]=2;
q.push({x-1,y});
f--;
}
if(x<r-1 && grid[x+1][y]==1)
{
grid[x+1][y]=2;
q.push({x+1,y});
f--;
}
if(y>0 && grid[x][y-1]==1)
{
grid[x][y-1]=2;
q.push({x,y-1});
f--;
}
if(y<c-1 && grid[x][y+1]==1)
{
grid[x][y+1]=2;
q.push({x,y+1});
f--;
}
}
if(!q.empty()) // There is chance to rot more oranges
t++;
}
return (f==0)?t:-1;
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int n, m;
cin >> n >> m;
vector<vector<int>>grid(n, vector<int>(m, -1));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> grid[i][j];
}
}
Solution obj;
int ans = obj.orangesRotting(grid);
cout << ans << "\n";
}
return 0;
} // } Driver Code Ends
/*
Input: grid = {{2,2,0,1}}
Output: -1
Explanation: The grid is-
2 2 0 1
Oranges at (0,0) and (0,1) can't rot orange at
(0,3).
*/ | 24.681034 | 129 | 0.398184 | [
"vector"
] |
3000d4d23398ed3346d635bd36ea39f06be3f808 | 3,038 | cxx | C++ | MassiveNumbers.cxx | jackytck/topcoder | 5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3 | [
"MIT"
] | null | null | null | MassiveNumbers.cxx | jackytck/topcoder | 5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3 | [
"MIT"
] | null | null | null | MassiveNumbers.cxx | jackytck/topcoder | 5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3 | [
"MIT"
] | null | null | null | // BEGIN CUT HERE
// PROBLEM STATEMENT
// Massive numbers can be represented using the exponent notation. For example, 3^100 is 3 raised to the power of 100. 3 is the base and 100 is the exponent.
Suppose we want to compare two massive numbers. Instead of computing the exact value of each number we can rely on a useful mathematical trick. Suppose m = a^b and n = c^d are two massive numbers. Let R be a relationship operator: less, equal or greater. Then we have the following:
If b*Log(a) R d*Log(c) then it is also the case that m R n,
where a, b, c, d, m and n are defined above.
So which is greater: 3^100 or 2^150? Let's do the math. 100*Log(3) = 47.7..., 150*Log(2) = 45.2.... Since 47.7 > 45.2, our rule tells us that 3^100 > 2^150.
Given two numbers numberA and numberB return the larger number formatted exactly the same as the input. numberA and numberB will be formatted as <base>^<exponent>. Constraints will ensure that numberA and numberB are not equal.
DEFINITION
Class:MassiveNumbers
Method:getLargest
Parameters:string, string
Returns:string
Method signature:string getLargest(string numberA, string numberB)
NOTES
-In Java, the log of a number can be found with Math.log().
-In C++, the log of a number can be found with log().
-In C# and VB, the log of a number can be found with Math.Log().
CONSTRAINTS
-numberA and numberB will contain between 3 and 9 characters inclusive.
-numberA and numberB will be formatted as <base>^<exponent>, where <base> and <exponent> are integers between 1 and 1000 inclusive. <base> and <exponent> cannot have leading zeroes.
-The relative difference between b*Log(a) and d*Log(c) (where a, b, c and d are defined in the problem statement) will be at least 1e-6.
EXAMPLES
0)
"3^100"
"2^150"
Returns: "3^100"
Above example.
1)
"1^1000"
"2^1"
Returns: "2^1"
numberA is equal to 1, while numberB is equal to 2.
2)
"893^605"
"396^906"
Returns: "396^906"
3)
"999^1000"
"1000^999"
Returns: "999^1000"
// END CUT HERE
#line 66 "MassiveNumbers.cxx"
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define sz size()
#define PB push_back
#define clr(x) memset(x, 0, sizeof(x))
#define forn(i,n) for(__typeof(n) i = 0; i < (n); i++)
#define ford(i,n) for(int i = (n) - 1; i >= 0; i--)
#define forv(i,v) forn(i, v.sz)
#define For(i, st, en) for(__typeof(en) i = (st); i < (en); i++)
using namespace std;
class MassiveNumbers {
public:
string getLargest(string numberA, string numberB)
{
int ab = 0, ae = 0, bb = 0, be = 0;
sscanf(numberA.c_str(), "%d^%d", &ab, &ae);
sscanf(numberB.c_str(), "%d^%d", &bb, &be);
return ae*log(ab) > be*log(bb) ? numberA : numberB;
}
};
| 28.933333 | 283 | 0.675444 | [
"vector"
] |
30036075db51f3a7496622e35d18eef031b40d48 | 4,481 | hpp | C++ | Source/AllProjects/Drivers/ZWave/ZWaveLevi2/Client/ZWaveLevi2C_ZWIndex.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/Drivers/ZWave/ZWaveLevi2/Client/ZWaveLevi2C_ZWIndex.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/Drivers/ZWave/ZWaveLevi2/Client/ZWaveLevi2C_ZWIndex.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: ZWaveLevi2C_ZWIndex.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 08/26/2014
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the Z-Wave device info index. We load this from the index
// file (which is created via the ZWDIComp program and put into the release.) It
// is divided into manufacturers. We create a few different views of the data to
// make it easier to find something.
//
// We create a small class to hold the actual data we parse from the file, and
// then an index class that holds the list of device info objects and provides some
// different sorted views.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TZWDIInfo
// PREFIX: zwdii
// ---------------------------------------------------------------------------
class TZWDIInfo
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TZWDIInfo();
~TZWDIInfo();
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid ParseFromXML
(
const TString& strMake
, const TXMLTreeElement& xtnodeRoot
);
// -------------------------------------------------------------------
// Public class members
//
// m_strFileName
// The base part of the file name that holds the device info for this
// device. We only get a subset of it in the index and we need to set
// the file name on the unit when it's configured since that's the only
// bit that is persisted.
//
// m_strMake
// m_strModel
// The make/model of the device, which should be a unique key.
//
// m_strName
// The overall name of the device.
//
// m_strType
// The generic device type, bin sensor, thermo, etc.... This is the
// short text from the shared facility's enum, so it can be used to
// alt xlat back to the enum if desired.
// -------------------------------------------------------------------
TString m_strFileName;
TString m_strMake;
TString m_strModel;
TString m_strName;
TString m_strType;
};
// ---------------------------------------------------------------------------
// CLASS: TZDIIndex
// PREFIX: zwdin
// ---------------------------------------------------------------------------
class TZDIIndex
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TZDIIndex();
~TZDIIndex();
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid ParseFromXML
(
TWindow& wndParent
);
// -------------------------------------------------------------------
// Public class members
//
// m_colMakeModel
// The list sorted by make and then model. This is the natural order
// of the index file, so this is the one we initially load. All the
// others are by ref collections that refer to these elements.
// -------------------------------------------------------------------
TVector<TZWDIInfo> m_colMakeModel;
private :
// -------------------------------------------------------------------
// Private, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid ResetLists();
};
#pragma CIDLIB_POPPACK
| 33.192593 | 84 | 0.40058 | [
"model"
] |
300ea2576a08a84a85bc1443677dd1f8fc84d36f | 2,434 | cpp | C++ | src/convertbase.cpp | kylegmaxwell/training | 82def44a0aa453cd988394fd8102c74238e6cb1d | [
"MIT"
] | null | null | null | src/convertbase.cpp | kylegmaxwell/training | 82def44a0aa453cd988394fd8102c74238e6cb1d | [
"MIT"
] | null | null | null | src/convertbase.cpp | kylegmaxwell/training | 82def44a0aa453cd988394fd8102c74238e6cb1d | [
"MIT"
] | null | null | null | #include <math.h>
#include <unordered_map>
#include <sstream>
#include <vector>
#include "convertbase.h"
using namespace std;
UnitTest::TestResult ConvertBase::test()
{
if (mVerbose)
cout << "convert base" << endl;
TestResult state = TestResult::PASS;
string begin = "A08";
string result = convertBase(16, begin, 2);
string expectedResult = "101000001000";
if (!stringEqual(result, expectedResult))
state = TestResult::FAIL;
string result2 = convertBase(2, result, 16);
if (!stringEqual(begin, result2))
state = TestResult::FAIL;
string result3 = convertBase(16, begin, 8);
if (!stringEqual(result3, "5010"))
state = TestResult::FAIL;
string result4 = convertBase(7, "615", 13);
if (!stringEqual(result4, "1A7"))
state = TestResult::FAIL;
return state;
}
// Assumptions
// Number is an integer
// Hex uses capital letters
string ConvertBase::convertBase(int baseIn, string number, int baseOut)
{
// check if the string is a valid number
//TODO
// check if the base is between 2 and 16
//TODO
// check for negative and remove from string
//TODO
std::unordered_map<char, int> charToInt;
std::unordered_map<int, char> intToChar;
for (int i = 0; i < 10; i++) {
char c = i + '0';
charToInt[c] = i;
intToChar[i] = c;
}
for (int i = 0; i < 6; i++) {
char c = i + 'A';
charToInt[c] = i + 10;
intToChar[i + 10] = c;
}
// the value of the number string as an integer
int value = 0;
// convert the number from a string to an int using base
int multiplier = 1;
for (int i = (int)number.size() - 1; i >= 0; i--) {
char c = number[i];
int digitValue = charToInt[c];
value += digitValue * multiplier;
multiplier *= baseIn;
}
// convert the integer to a string in the new base
std::vector<char> numberChars;
multiplier = 1;
int shifted = 0;
do {
shifted = value / multiplier;
int digit = shifted % baseOut;
numberChars.push_back(intToChar[digit]);
multiplier *= baseOut;
} while (shifted > 0);
// reverse
stringstream ss;
// start at one before the last character, to drop extra zero
for (int i = (int)numberChars.size() - 2; i >= 0; i--) {
char digit = numberChars[i];
ss << digit;
}
return ss.str();
} | 24.836735 | 71 | 0.593673 | [
"vector"
] |
3012bb580243f65bd28ce45cedb15c83319b0dbb | 710 | cpp | C++ | solutions/0046.permutations/0046.permutations.1548858296.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 1 | 2021-01-14T06:01:02.000Z | 2021-01-14T06:01:02.000Z | solutions/0046.permutations/0046.permutations.1548858296.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 8 | 2018-03-27T11:47:19.000Z | 2018-11-12T06:02:12.000Z | solutions/0046.permutations/0046.permutations.1548858296.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 2 | 2020-04-30T09:47:01.000Z | 2020-12-03T09:34:08.000Z | class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
if (nums.size() == 1) {
return vector<vector<int>>{{nums[0]}};
}
vector<vector<int>> res;
for (int i = 0; i < nums.size(); i++) {
int n = nums[i];
vector<int> remaining;
for (int j = 0; j < nums.size(); j++) {
if (j != i) {
remaining.push_back(nums[j]);
}
}
vector<vector<int>> perms = permute(remaining);
for (vector<int> perm : perms) {
perm.push_back(n);
res.push_back(perm);
}
}
return res;
}
};
| 28.4 | 59 | 0.415493 | [
"vector"
] |
30198383edb1c4548aa89d8e0dfec13b9cdfa8d5 | 7,251 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/IfcLightSourceGoniometric.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | 1 | 2018-10-23T09:43:07.000Z | 2018-10-23T09:43:07.000Z | IfcPlusPlus/src/ifcpp/IFC4/IfcLightSourceGoniometric.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/IfcLightSourceGoniometric.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <sstream>
#include <limits>
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/model/IfcPPAttributeObject.h"
#include "ifcpp/model/IfcPPGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IfcPPEntityEnums.h"
#include "include/IfcAxis2Placement3D.h"
#include "include/IfcColourRgb.h"
#include "include/IfcLabel.h"
#include "include/IfcLightDistributionDataSourceSelect.h"
#include "include/IfcLightEmissionSourceEnum.h"
#include "include/IfcLightSourceGoniometric.h"
#include "include/IfcLuminousFluxMeasure.h"
#include "include/IfcNormalisedRatioMeasure.h"
#include "include/IfcPresentationLayerAssignment.h"
#include "include/IfcStyledItem.h"
#include "include/IfcThermodynamicTemperatureMeasure.h"
// ENTITY IfcLightSourceGoniometric
IfcLightSourceGoniometric::IfcLightSourceGoniometric() { m_entity_enum = IFCLIGHTSOURCEGONIOMETRIC; }
IfcLightSourceGoniometric::IfcLightSourceGoniometric( int id ) { m_id = id; m_entity_enum = IFCLIGHTSOURCEGONIOMETRIC; }
IfcLightSourceGoniometric::~IfcLightSourceGoniometric() {}
shared_ptr<IfcPPObject> IfcLightSourceGoniometric::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcLightSourceGoniometric> copy_self( new IfcLightSourceGoniometric() );
if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); }
if( m_LightColour ) { copy_self->m_LightColour = dynamic_pointer_cast<IfcColourRgb>( m_LightColour->getDeepCopy(options) ); }
if( m_AmbientIntensity ) { copy_self->m_AmbientIntensity = dynamic_pointer_cast<IfcNormalisedRatioMeasure>( m_AmbientIntensity->getDeepCopy(options) ); }
if( m_Intensity ) { copy_self->m_Intensity = dynamic_pointer_cast<IfcNormalisedRatioMeasure>( m_Intensity->getDeepCopy(options) ); }
if( m_Position ) { copy_self->m_Position = dynamic_pointer_cast<IfcAxis2Placement3D>( m_Position->getDeepCopy(options) ); }
if( m_ColourAppearance ) { copy_self->m_ColourAppearance = dynamic_pointer_cast<IfcColourRgb>( m_ColourAppearance->getDeepCopy(options) ); }
if( m_ColourTemperature ) { copy_self->m_ColourTemperature = dynamic_pointer_cast<IfcThermodynamicTemperatureMeasure>( m_ColourTemperature->getDeepCopy(options) ); }
if( m_LuminousFlux ) { copy_self->m_LuminousFlux = dynamic_pointer_cast<IfcLuminousFluxMeasure>( m_LuminousFlux->getDeepCopy(options) ); }
if( m_LightEmissionSource ) { copy_self->m_LightEmissionSource = dynamic_pointer_cast<IfcLightEmissionSourceEnum>( m_LightEmissionSource->getDeepCopy(options) ); }
if( m_LightDistributionDataSource ) { copy_self->m_LightDistributionDataSource = dynamic_pointer_cast<IfcLightDistributionDataSourceSelect>( m_LightDistributionDataSource->getDeepCopy(options) ); }
return copy_self;
}
void IfcLightSourceGoniometric::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "= IFCLIGHTSOURCEGONIOMETRIC" << "(";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_LightColour ) { stream << "#" << m_LightColour->m_id; } else { stream << "*"; }
stream << ",";
if( m_AmbientIntensity ) { m_AmbientIntensity->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_Intensity ) { m_Intensity->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_Position ) { stream << "#" << m_Position->m_id; } else { stream << "$"; }
stream << ",";
if( m_ColourAppearance ) { stream << "#" << m_ColourAppearance->m_id; } else { stream << "$"; }
stream << ",";
if( m_ColourTemperature ) { m_ColourTemperature->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_LuminousFlux ) { m_LuminousFlux->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_LightEmissionSource ) { m_LightEmissionSource->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_LightDistributionDataSource ) { m_LightDistributionDataSource->getStepParameter( stream, true ); } else { stream << "$" ; }
stream << ");";
}
void IfcLightSourceGoniometric::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcLightSourceGoniometric::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map )
{
const int num_args = (int)args.size();
if( num_args != 10 ){ std::stringstream err; err << "Wrong parameter count for entity IfcLightSourceGoniometric, expecting 10, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); }
m_Name = IfcLabel::createObjectFromSTEP( args[0] );
readEntityReference( args[1], m_LightColour, map );
m_AmbientIntensity = IfcNormalisedRatioMeasure::createObjectFromSTEP( args[2] );
m_Intensity = IfcNormalisedRatioMeasure::createObjectFromSTEP( args[3] );
readEntityReference( args[4], m_Position, map );
readEntityReference( args[5], m_ColourAppearance, map );
m_ColourTemperature = IfcThermodynamicTemperatureMeasure::createObjectFromSTEP( args[6] );
m_LuminousFlux = IfcLuminousFluxMeasure::createObjectFromSTEP( args[7] );
m_LightEmissionSource = IfcLightEmissionSourceEnum::createObjectFromSTEP( args[8] );
m_LightDistributionDataSource = IfcLightDistributionDataSourceSelect::createObjectFromSTEP( args[9], map );
}
void IfcLightSourceGoniometric::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes )
{
IfcLightSource::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "Position", m_Position ) );
vec_attributes.push_back( std::make_pair( "ColourAppearance", m_ColourAppearance ) );
vec_attributes.push_back( std::make_pair( "ColourTemperature", m_ColourTemperature ) );
vec_attributes.push_back( std::make_pair( "LuminousFlux", m_LuminousFlux ) );
vec_attributes.push_back( std::make_pair( "LightEmissionSource", m_LightEmissionSource ) );
vec_attributes.push_back( std::make_pair( "LightDistributionDataSource", m_LightDistributionDataSource ) );
}
void IfcLightSourceGoniometric::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse )
{
IfcLightSource::getAttributesInverse( vec_attributes_inverse );
}
void IfcLightSourceGoniometric::setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self_entity )
{
IfcLightSource::setInverseCounterparts( ptr_self_entity );
}
void IfcLightSourceGoniometric::unlinkFromInverseCounterparts()
{
IfcLightSource::unlinkFromInverseCounterparts();
}
| 63.052174 | 235 | 0.756172 | [
"vector",
"model"
] |
301b37241b50e9fef1df29aaed24500a0869dbfe | 4,601 | cpp | C++ | unittests/blocks_unittest.cpp | dgkimura/dafs | 20273ea13d71bbb9ca8f6e85045c0abb1cf45aba | [
"MIT"
] | 2 | 2018-06-29T05:59:16.000Z | 2018-07-01T05:58:14.000Z | unittests/blocks_unittest.cpp | dgkimura/dafs | 20273ea13d71bbb9ca8f6e85045c0abb1cf45aba | [
"MIT"
] | 7 | 2018-06-04T16:26:37.000Z | 2018-11-03T00:47:08.000Z | unittests/blocks_unittest.cpp | dgkimura/dafs | 20273ea13d71bbb9ca8f6e85045c0abb1cf45aba | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "dafs/blocks.hpp"
TEST(BlocksTest, testRootFieldsAreConstructed)
{
std::string directory = "a_directory";
dafs::Root root(directory);
ASSERT_EQ(directory, root.directory);
}
TEST(BlocksTest, testBlockFieldsAreConstructed)
{
std::string contents = "the_block_contents";
dafs::BlockFormat b;
b.contents = contents;
ASSERT_EQ(contents, b.contents);
}
TEST(BlocksTest, testsBlockInfoFieldsAreConstructed)
{
std::string path = "myfile";
dafs::Identity identity = dafs::Identity("01234567-89ab-cdef-0123-456789abcdef");
dafs::BlockInfo b = dafs::BlockInfo{path, identity};
ASSERT_EQ(path, b.path);
ASSERT_EQ(identity, b.identity);
}
TEST(BlocksTest, testsSplitUpperIndexWithNoWrap)
{
auto index = SplitUpperIndex(
dafs::BlockIndex
{
std::vector<dafs::BlockInfo>
{
dafs::BlockInfo
{
"a_block",
dafs::Identity("10000000-0000-0000-0000-000000000000"),
0
},
dafs::BlockInfo
{
"b_block",
dafs::Identity("10000000-0000-0000-0000-222222222222"),
0
},
dafs::BlockInfo
{
"c_block",
dafs::Identity("10000000-0000-0000-0000-444444444444"),
0
}
}
},
dafs::Identity("10000000-0000-0000-0000-111111111111"),
dafs::Identity("10000000-0000-0000-0000-333333333333"),
dafs::Identity("10000000-0000-0000-0000-555555555555")
);
ASSERT_EQ("10000000-0000-0000-0000-444444444444", index.items[0].identity.id);
}
TEST(BlocksTest, testsSplitUpperIndexWithWrapAfterDivider)
{
auto index = SplitUpperIndex(
dafs::BlockIndex
{
std::vector<dafs::BlockInfo>
{
dafs::BlockInfo
{
"a_block",
dafs::Identity("10000000-0000-0000-0000-000000000000"),
0
},
dafs::BlockInfo
{
"b_block",
dafs::Identity("10000000-0000-0000-0000-222222222222"),
0
},
dafs::BlockInfo
{
"c_block",
dafs::Identity("10000000-0000-0000-0000-444444444444"),
0
}
}
},
dafs::Identity("10000000-0000-0000-0000-333333333333"),
dafs::Identity("10000000-0000-0000-0000-555555555555"),
dafs::Identity("10000000-0000-0000-0000-111111111111")
);
ASSERT_EQ("10000000-0000-0000-0000-000000000000", index.items[0].identity.id);
index = SplitUpperIndex(
dafs::BlockIndex
{
std::vector<dafs::BlockInfo>
{
dafs::BlockInfo
{
"c_block",
dafs::Identity("10000000-0000-0000-0000-666666666666"),
0
}
}
},
dafs::Identity("10000000-0000-0000-0000-333333333333"),
dafs::Identity("10000000-0000-0000-0000-555555555555"),
dafs::Identity("10000000-0000-0000-0000-111111111111")
);
ASSERT_EQ("10000000-0000-0000-0000-666666666666", index.items[0].identity.id);
}
TEST(BlocksTest, testsSplitUpperIndexWithWrapAfterLower)
{
auto index = SplitUpperIndex(
dafs::BlockIndex
{
std::vector<dafs::BlockInfo>
{
dafs::BlockInfo
{
"a_block",
dafs::Identity("10000000-0000-0000-0000-000000000000"),
0
},
dafs::BlockInfo
{
"b_block",
dafs::Identity("10000000-0000-0000-0000-222222222222"),
0
},
dafs::BlockInfo
{
"c_block",
dafs::Identity("10000000-0000-0000-0000-444444444444"),
0
}
}
},
dafs::Identity("10000000-0000-0000-0000-555555555555"),
dafs::Identity("10000000-0000-0000-0000-111111111111"),
dafs::Identity("10000000-0000-0000-0000-333333333333")
);
ASSERT_EQ("10000000-0000-0000-0000-222222222222", index.items[0].identity.id);
}
| 27.884848 | 85 | 0.505108 | [
"vector"
] |
3024565f3807448264858e49daa05b9b08f4850f | 2,035 | hpp | C++ | module-services/service-cellular/service-cellular/requests/Request.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-services/service-cellular/service-cellular/requests/Request.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-services/service-cellular/service-cellular/requests/Request.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include <at/Result.hpp>
#include <at/Commands.hpp>
#include "service-cellular/RequestHandler.hpp"
#include <at/Cmd.hpp>
namespace cellular
{
constexpr inline auto maxGroupsInRequest = 6;
using GroupMatch = std::array<std::reference_wrapper<std::string>, maxGroupsInRequest>;
class IRequest
{
public:
virtual at::Cmd command() = 0;
virtual void handle(RequestHandler &h, at::Result &result) = 0;
virtual void setHandled(bool handled) = 0;
virtual bool checkModemResponse(const at::Result &result) = 0;
[[nodiscard]] virtual bool isHandled() const noexcept = 0;
[[nodiscard]] virtual bool isValid() const noexcept = 0;
virtual ~IRequest(){};
};
class Request : public IRequest
{
public:
Request(const std::string &data) : request(data){};
void setHandled(bool handled) final;
bool isHandled() const noexcept final;
bool checkModemResponse(const at::Result &result) final;
bool isValid() const noexcept override;
protected:
using commandBuilderFunc = std::function<std::string()>;
/**
* Helper command for building output command
* @param atCommand
* @param builderFunctions functions that build parts of the output command in order of execution
* @param trim true to avoid appending commands that evaluate to empty string
* @return formatted command or empty string if input is invalid
*/
auto buildCommand(at::AT atCommand,
const std::vector<commandBuilderFunc> &builderFunctions,
bool trim = true) const -> at::Cmd;
bool isRequestHandled = false;
std::string request;
};
}; // namespace cellular
| 37.685185 | 115 | 0.615233 | [
"vector"
] |
6f7ab889504534cb52990ec1b75f9082a8b838e4 | 864 | cpp | C++ | src/cxx/test/test_separating_hyperplanes.cpp | tardani95/iris-distro | dbb1ebbde2e52b4cc747b4aa2fe88518b238071a | [
"BSD-2-Clause"
] | 82 | 2016-03-30T15:32:47.000Z | 2022-03-28T03:03:08.000Z | src/cxx/test/test_separating_hyperplanes.cpp | tardani95/iris-distro | dbb1ebbde2e52b4cc747b4aa2fe88518b238071a | [
"BSD-2-Clause"
] | 49 | 2015-01-21T16:13:20.000Z | 2021-12-29T02:47:52.000Z | src/cxx/test/test_separating_hyperplanes.cpp | tardani95/iris-distro | dbb1ebbde2e52b4cc747b4aa2fe88518b238071a | [
"BSD-2-Clause"
] | 61 | 2015-03-20T18:49:31.000Z | 2022-01-27T12:35:38.000Z | #include <Eigen/Core>
#include "iris/iris.h"
#include "test_util.h"
int main() {
// A simple example with a sphere centered at the origin
Eigen::MatrixXd C(2,2);
C << 1, 0,
0, 1;
Eigen::VectorXd d(2);
d << 0, 0;
iris::Ellipsoid ellipsoid(C, d);
Eigen::MatrixXd obs(2,4);
obs << 2, 3, 3, 2,
2, 2, 3, 3;
std::vector<Eigen::MatrixXd> obstacles;
obstacles.push_back(obs);
iris::Polyhedron result(2);
bool infeasible_start;
iris::separating_hyperplanes(obstacles, ellipsoid, result, infeasible_start);
valuecheck(infeasible_start, false);
Eigen::MatrixXd A_expected(1, 2);
A_expected << 1/std::sqrt(2), 1/std::sqrt(2);
Eigen::VectorXd b_expected(1);
b_expected << 2.0 * 2.0 * 1.0/std::sqrt(2);
valuecheckMatrix(result.getA(), A_expected, 1e-6);
valuecheckMatrix(result.getB(), b_expected, 1e-6);
return 0;
} | 27 | 79 | 0.657407 | [
"vector"
] |
6f9cf8eb8cced2c4e81d68dd5c0d5dc89b745e2c | 1,629 | cpp | C++ | src/circle.cpp | Nimor111/LearnOpenGL-Engine | 24738fbdbb4e879171b8992a24430db14531369a | [
"MIT"
] | null | null | null | src/circle.cpp | Nimor111/LearnOpenGL-Engine | 24738fbdbb4e879171b8992a24430db14531369a | [
"MIT"
] | null | null | null | src/circle.cpp | Nimor111/LearnOpenGL-Engine | 24738fbdbb4e879171b8992a24430db14531369a | [
"MIT"
] | null | null | null | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "../include/Shader.h"
#include "../include/VertexData.h"
#include "../include/Window.h"
#include <vector>
#define NUMBER_OF_VERTICES 64
int main(int argc, char const** argv)
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
Window window = Window(800, 600, "Circle");
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to init GLAD" << std::endl;
return -1;
}
Shader shaderProg("resources/shaders/circle.vert", "resources/shaders/circle.frag");
float radius = 0.5f;
std::vector<GLfloat> vertexBuffer;
for (GLfloat i = 0; i < 2 * M_PI; i += (2 * M_PI) / NUMBER_OF_VERTICES) {
vertexBuffer.push_back(cos(i) * radius); // x coord
vertexBuffer.push_back(sin(i) * radius); // y coord
vertexBuffer.push_back(0.0f); // z coord (2D)
}
VertexData vData = VertexData();
vData.loadData(vertexBuffer);
while (!glfwWindowShouldClose(window.getWindow())) {
glClearColor(0.337f, 0.301f, 0.301f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
shaderProg.use();
if (glfwGetKey(window.getWindow(), GLFW_KEY_ESCAPE)) {
glfwSetWindowShouldClose(window.getWindow(), true);
}
vData.bindVao();
glDrawArrays(GL_LINE_LOOP, 0, NUMBER_OF_VERTICES);
glfwSwapBuffers(window.getWindow());
glfwPollEvents();
}
glfwTerminate();
return 0;
}
| 26.274194 | 88 | 0.644567 | [
"vector"
] |
6fa1e57fc80916f41637cfa2e915ccc2e4551182 | 8,045 | cpp | C++ | pixetto.cpp | pixetto/pxt-pixetto-16 | b58308ce76800db61a6cc3a7fb0057bd5ed93049 | [
"MIT"
] | null | null | null | pixetto.cpp | pixetto/pxt-pixetto-16 | b58308ce76800db61a6cc3a7fb0057bd5ed93049 | [
"MIT"
] | null | null | null | pixetto.cpp | pixetto/pxt-pixetto-16 | b58308ce76800db61a6cc3a7fb0057bd5ed93049 | [
"MIT"
] | null | null | null | #include "pxt.h"
#include "MicroBit.h"
#include "MicroBitFile.h"
#ifdef CODAL_CONFIG_H
#define MICROBIT_CODAL 1
#else
#define MICROBIT_CODAL 0
#define target_panic(n) microbit_panic(n)
#define target_wait(n) wait_ms(n)
#endif
#define PXT_PACKET_START 0xFD
#define PXT_PACKET_END 0xFE
#define PXT_CMD_GET_VERSION 0xD0
#define PXT_CMD_SET_FUNC 0xD1
#define PXT_CMD_GET_OBJNUM 0xD2
#define PXT_CMD_GET_DATA 0xD4
#define PXT_BUF_SIZE 64
#define PXT_RET_FW_VERSION 0xE3
#define PXT_RET_OBJNUM 0x46 //0xE4
enum PixSerialPin {
P0 = 0,
P1 = 1,
P2 = 2,
P8 = 8,
P12 = 12,
P13 = 13,
P14 = 14,
P15 = 15,
P16 = 16
};
enum PixFunction {
//% block="color detection"
COLOR_DETECTION=1,
//% block="color codes detection"
COLOR_LABEL=2,
//% block="shape detection"
SHAPE_DETECTION=3,
//% block="sphere detection"
SPHERE_DETECTION=4,
//% block="template matching"
TEMPLATE=6,
//% block="keypoint"
KEYPOINT=8,
//% block="neural network"
NEURAL_NETWORK=9,
//% block="apriltag(16h5)"
APRILTAG=10,
//% block="face detection"
FACE_DETECTION=11,
//% block="traffic sign detection"
TRAFFIC_SIGN_DETECTION=12,
//% block="handwritten digits detection"
HANDWRITTEN_DIGITS_DETECTION=13,
//% block="handwritten letters detection"
HANDWRITTEN_LETTERS_DETECTION=14,
//% block="remote computing"
REMOTE_COMPUTING=15,
//% block="lanes detection"
LANES_DETECTION=16,
//% block="digits operation"
DIGITS_OPERATION=17,
//% block="simple classifier"
SIMPLE_CLASSIFIER=18,
//% block="voice commands"
VOICE_COMMANDS=19,
//% block="autonomous driving"
LANE_AND_SIGN=20
};
enum PixDataField {
//% block="current function"
PXTDATA_FUNC_ID=1,
//% block="return code"
PXTDATA_RET_CODE,
//% block="firmware version"
PXTDATA_VERSION,
//% block="object type"
PXTDATA_CLASS_ID,
//% block="object position x"
PXTDATA_X,
//% block="object position y"
PXTDATA_Y,
//% block="object width"
PXTDATA_W,
//% block="object height"
PXTDATA_H
};
//using namespace pxt;
//using namespace codal;
//extern MicroBit uBit;
namespace pixetto {
struct pxt_data {
// head +4
uint8_t head;
uint8_t len;
uint8_t cmd;
uint8_t retcode;
// version +4
uint32_t version; // 0x00010602
// object id and bounding box +8
uint8_t func_id;
uint8_t reserved1;
uint16_t class_id;
uint8_t x;
uint8_t y;
uint8_t w;
uint8_t h;
// extra +32
union {
struct {
float pos_x;
float pos_y;
float pos_z;
float rot_x;
float rot_y;
float rot_z;
float center_x;
float center_y;
} apltag; // +32
struct {
uint8_t left_x1;
uint8_t left_y1;
uint8_t left_x2;
uint8_t left_y2;
uint8_t right_x1;
uint8_t right_y1;
uint8_t right_x2;
uint8_t right_y2;
uint8_t sign_x;
uint8_t sign_y;
uint8_t sign_w;
uint8_t sign_h;
} traffic; // +12
struct {
float result;
char equation[16];
} math; // +20
uint8_t bytes[32];
} extra;
// End +4
uint8_t reserved[2];
uint8_t cksum;
uint8_t tail;
};
MicroBitSerial *serial = nullptr;
int m_funcid = 0;
struct pxt_data* m_p;
bool getPinName(PixSerialPin p, PinName& name) {
switch(p) {
case P0: name = MICROBIT_PIN_P0; return true;
case P1: name = MICROBIT_PIN_P1; return true;
case P2: name = MICROBIT_PIN_P2; return true;
case P8: name = MICROBIT_PIN_P8; return true;
case P12: name = MICROBIT_PIN_P12; return true;
case P13: name = MICROBIT_PIN_P13; return true;
case P14: name = MICROBIT_PIN_P14; return true;
case P15: name = MICROBIT_PIN_P15; return true;
case P16: name = MICROBIT_PIN_P16; return true;
}
return false;
}
void addcksum(uint8_t *buf, int len)
{
uint8_t sum = 0;
for (int i = 1; i < len - 2; i++)
sum += buf[i];
sum %= 256;
buf[len - 2] = sum;
}
bool verifycksum(uint8_t *buf, int len)
{
uint8_t sum = 0;
for (int i=1; i<len-2; i++)
sum += buf[i];
sum %= 256;
return (sum == buf[len-2]);
}
int getdata(uint8_t* buf, int buflen)
{
int loop = 0;
int read_len = 0;
memset(buf, 0, buflen);
do {
read_len = serial->read(buf, 1, ASYNC);
loop++;
} while (buf[0] != PXT_PACKET_START && loop < 200000);
if (read_len == 0 || read_len == MICROBIT_NO_DATA) return 0;
if (buf[0] == PXT_PACKET_START) {
read_len = serial->read(&buf[1], 1);
int n = buf[1];
if (n <= PXT_BUF_SIZE) {
read_len = serial->read(&buf[2], n-2);
if (buf[n-1] == PXT_PACKET_END && verifycksum(buf, n))
return buf[1];
}
}
return 0;
}
//%
uint32_t pxtGetVersion() {
uint32_t vers = 0;
while (vers == 0) {
serial->clearRxBuffer();
// Send command
uint8_t cmd[] = { PXT_PACKET_START, 0x05, PXT_CMD_GET_VERSION, 0, PXT_PACKET_END };
serial->send(cmd, sizeof(cmd), ASYNC);
// Get result
// ex: { FD, 9, E3, 1, 1, 6, 1, F5, FE }
uint8_t buf[PXT_BUF_SIZE];
int len = 0;
if ((len = getdata(buf, PXT_BUF_SIZE)) > 0) {
if (buf[2] == PXT_CMD_GET_VERSION || buf[2] == PXT_RET_FW_VERSION) {
m_p = (struct pxt_data*) buf;
vers = m_p->version;
}
}
}
return vers;
}
void pxtWait()
{
static bool pxt_is_ready = false;
while (!pxt_is_ready) {
if (pxtGetVersion() > 0)
pxt_is_ready = true;
else
uBit.sleep(200);
}
}
//%
bool begin(PixSerialPin rx, PixSerialPin tx){
uint32_t ret = 0;
PinName txn, rxn;
uBit.sleep(3000);
if (getPinName(tx, txn) && getPinName(rx, rxn))
{
if (serial == nullptr)
serial = new MicroBitSerial(txn, rxn, 64, 20);
#if MICROBIT_CODAL
serial->setBaudrate(38400);
#else
serial->baud(38400);
#endif
//serial->setRxBufferSize(64);
//serial->setTxBufferSize(32);
uBit.sleep(1000);
ret = pxtGetVersion();
}
return ret;
}
//%
void pxtSetFunc(int id)
{
pxtWait();
if (m_funcid == id)
return;
uint8_t cmd[] = { PXT_PACKET_START, 0x06, PXT_CMD_SET_FUNC, (uint8_t)id, 0, PXT_PACKET_END };
addcksum(cmd, sizeof(cmd));
serial->send(cmd, sizeof(cmd), ASYNC);
m_funcid = id;
uBit.sleep(20);
}
//%
int pxtAvailable()
{
pxtWait();
uint8_t cmd[] = { PXT_PACKET_START, 0x05, PXT_CMD_GET_OBJNUM, 0, PXT_PACKET_END };
addcksum(cmd, sizeof(cmd));
serial->send(cmd, sizeof(cmd), ASYNC);
uint8_t buf[PXT_BUF_SIZE];
memset(buf, 0, PXT_BUF_SIZE);
m_p = (struct pxt_data*) buf;
int len = 0;
while ((len = getdata(buf, PXT_BUF_SIZE)) > 0) {
if (m_p->cmd == PXT_CMD_GET_OBJNUM || m_p->cmd == PXT_RET_OBJNUM) {
int n = m_p->retcode;
return n;
}
}
return 0;
}
//%
bool pxtGetData()
{
uint8_t cmd[] = { PXT_PACKET_START, 0x05, PXT_CMD_GET_DATA, 0, PXT_PACKET_END };
addcksum(cmd, sizeof(cmd));
serial->send(cmd, sizeof(cmd), ASYNC);
uint8_t buf[PXT_BUF_SIZE];
memset(buf, 0, PXT_BUF_SIZE);
m_p = (struct pxt_data*) buf;
int len;
while ((len = getdata(buf, PXT_BUF_SIZE)) > 0) {
if (m_p->cmd == PXT_CMD_GET_DATA && len != 5)
return true;
}
return false;
}
//%
uint32_t getDataField(int field) {
switch(field) {
case PXTDATA_FUNC_ID:
return m_p->func_id;
case PXTDATA_RET_CODE:
return m_p->retcode;
case PXTDATA_VERSION:
return m_p->version;
case PXTDATA_CLASS_ID:
if (m_p->func_id == DIGITS_OPERATION)
return m_p->extra.math.result;
else
return m_p->class_id;
case PXTDATA_X:
return m_p->x;
case PXTDATA_Y:
return m_p->y;
case PXTDATA_W:
return m_p->w;
case PXTDATA_H:
return m_p->h;
default:
return 0;
}
}
}
| 21.339523 | 95 | 0.602859 | [
"object",
"shape"
] |
6fa4312da011efb630870ac113f8faba44a5b6ba | 730 | cpp | C++ | UCRolling/ucRollingBundle.cpp | jalving/PIPS | 62f664237447c7ce05a62552952c86003d90e68f | [
"BSD-3-Clause-LBNL"
] | 65 | 2016-02-04T18:03:39.000Z | 2022-03-24T08:59:38.000Z | UCRolling/ucRollingBundle.cpp | jalving/PIPS | 62f664237447c7ce05a62552952c86003d90e68f | [
"BSD-3-Clause-LBNL"
] | 34 | 2015-11-17T04:26:51.000Z | 2020-09-24T16:00:22.000Z | UCRolling/ucRollingBundle.cpp | jalving/PIPS | 62f664237447c7ce05a62552952c86003d90e68f | [
"BSD-3-Clause-LBNL"
] | 26 | 2015-10-15T20:27:52.000Z | 2021-07-14T08:13:34.000Z | #include "ucRollingModel.hpp"
#include "CbcLagrangeSolver.hpp"
#include "ClpRecourseSolver.hpp"
#include "conicBundleDriver.hpp"
#include <boost/scoped_ptr.hpp>
using namespace std;
using boost::scoped_ptr;
int main(int argc, char **argv) {
MPI_Init(&argc, &argv);
int mype;
MPI_Comm_rank(MPI_COMM_WORLD,&mype);
if (argc != 3) {
printf("Usage: %s [num scenarios] [time horizon]\n",argv[0]);
return 1;
}
int nscen = atoi(argv[1]);
int T = atoi(argv[2]);
ucRollingModel model("../../../apps/unitcommitment_rolling/Illinois",nscen,0,T);
conicBundleDriver<CbcLagrangeSolver,ClpRecourseSolver>(model);
MPI_Finalize();
return 0;
}
| 21.470588 | 81 | 0.634247 | [
"model"
] |
6fa48ba1a8aa0ba743563890c6a65b1e84662859 | 7,116 | cpp | C++ | mapper/src/mapper/generate_final_map.cpp | anpl-technion/anpl_mrbsp | 973734fd2d1c7bb5e1405922300add489f088e81 | [
"MIT"
] | 1 | 2021-12-03T03:11:20.000Z | 2021-12-03T03:11:20.000Z | mapper/src/mapper/generate_final_map.cpp | anpl-technion/anpl_mrbsp | 973734fd2d1c7bb5e1405922300add489f088e81 | [
"MIT"
] | null | null | null | mapper/src/mapper/generate_final_map.cpp | anpl-technion/anpl_mrbsp | 973734fd2d1c7bb5e1405922300add489f088e81 | [
"MIT"
] | 1 | 2021-12-03T03:11:23.000Z | 2021-12-03T03:11:23.000Z | /* ---------------------------------------------------------------------------
*
* Autonomous Navigation and Perception Lab (ANPL),
* Technion, Israel Institute of Technology,
* Faculty of Aerospace Engineering,
* Haifa, Israel, 32000
* All Rights Reserved
*
* See LICENSE for the license information
*
* -------------------------------------------------------------------------- */
/**
* @file: generate_final_map.cpp
* @brief:
* @author: Asaf Feniger
*/
#include "mapper/robot_map_octomap_laser.h"
#include <mrbsp_utils/gtsam_serialization.h>
#include <mrbsp_utils/mrbsp_types.h>
#include <mrbsp_utils/conversion.h>
#include <ros/ros.h>
#include <rosbag/bag.h>
#include <rosbag/view.h>
#include <octomap_ros/conversions.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>
#include <sensor_msgs/PointCloud2.h>
#include <std_msgs/String.h>
#include "gtsam/base/serialization.h"
#include <gtsam/nonlinear/ISAM2.h>
#include <gtsam/inference/Symbol.h>
#include <octomap/OcTree.h>
void createMapData3D(std::map<std::string, MRBSP::Utils::MapData3D>& map_data_3d, std::string& path_to_values,
std::vector<std::string>& path_to_bagfiles);
void insertPointcloud(std::shared_ptr<octomap::OcTree>& p_octree_map, MRBSP::Utils::MapData3D& map_data_3d);
int main(int argc, char** argv)
{
ros::init(argc, argv, "generateFinalMap");
ros::NodeHandle nh;
// path to files
std::string scenario_folder("/home/asafeniger/ANPL/code/mrbsp_ws/src/mrbsp/mrbsp_scenarios/scenarios");
std::string scenario_name("mr_centralized_laser");
std::string run_name("mr_lc_nn_80_03");
std::string data_folder(scenario_folder + "/" + scenario_name + "/results/" + run_name);
// get gtsam values
std::string serialized_filename("belief_A70_ser_values.txt");
std::string path_to_values_file(data_folder + "/serialized_files/" + serialized_filename);
// get pointcloud data
std::vector<std::string> path_to_bagfiles;
std::string bag_A_filename("Robot_A_keyframe_bag.bag");
std::string path_to_bag_A(data_folder + "/" + bag_A_filename);
path_to_bagfiles.push_back(path_to_bag_A);
std::string bag_B_filename("Robot_B_keyframe_bag.bag");
std::string path_to_bag_B(data_folder + "/" + bag_B_filename);
path_to_bagfiles.push_back(path_to_bag_B);
// arrange data
std::map<std::string, MRBSP::Utils::MapData3D> data_3d_container;
createMapData3D(data_3d_container, path_to_values_file, path_to_bagfiles);
std::cout << "Number of scans: " << data_3d_container.size() << std::endl;
// generate octomap
std::string map_name("final_octomap_3d.ot");
std::string path_to_map(data_folder + "/" + map_name);
double map_resulotion = 0.1;
std::shared_ptr<octomap::OcTree> p_octree_map(new octomap::OcTree(map_resulotion));
std::cout << "map size: " << p_octree_map->size() << std::endl;
unsigned int scan_idx = 1;
for(auto iter = data_3d_container.begin(); iter != data_3d_container.end(); ++iter) {
std::cout << "Adding scan #" << scan_idx << "/" << data_3d_container.size() << " to the map." << std::endl;
insertPointcloud(p_octree_map, iter->second);
++scan_idx;
}
std::cout << "map size: " << p_octree_map->size() << std::endl;
p_octree_map->updateInnerOccupancy();
p_octree_map->write(path_to_map);
return 0;
}
void createMapData3D(std::map<std::string, MRBSP::Utils::MapData3D>& data_3d_container, std::string& path_to_values,
std::vector<std::string>& path_to_bagfiles) {
// arange keyframe poses
std::map<std::string, gtsam::Pose3> keyframes_poses;
gtsam::Values vals;
gtsam::deserializeFromFile(path_to_values, vals);
gtsam::KeyVector keys = vals.keys();
for(auto key : keys) {
gtsam::Symbol symbol(key);
char robot_id = symbol.chr();
size_t index = symbol.index();
std::string index_string((1, robot_id) + std::to_string(index));
gtsam::Pose3 pose(vals.at<gtsam::Pose3>(symbol));
keyframes_poses.insert(std::pair<std::string, gtsam::Pose3>(index_string,pose));
}
// arrange keyframe scans
std::string pointcloud_topic("pointcloud");
std::string index_topic("index");
for(auto iter = path_to_bagfiles.begin(); iter != path_to_bagfiles.end(); ++iter) {
rosbag::Bag bag;
bag.open(*iter, rosbag::bagmode::Read);
rosbag::View view_pointcloud(bag, rosbag::TopicQuery(pointcloud_topic));
rosbag::View view_index(bag, rosbag::TopicQuery(index_topic));
auto index_iter = view_index.begin();
for(auto pointcloud_iter = view_pointcloud.begin(); pointcloud_iter != view_pointcloud.end(); ++pointcloud_iter, ++index_iter) {
auto pt_messageInstance = *pointcloud_iter;
sensor_msgs::PointCloud2ConstPtr pt_const_ptr = pt_messageInstance.instantiate<sensor_msgs::PointCloud2>();
auto idx_messageInstance = *index_iter;
std_msgs::StringConstPtr idx_const_ptr = idx_messageInstance.instantiate<std_msgs::String>();
if (pt_const_ptr != NULL && idx_const_ptr != NULL) {
sensor_msgs::PointCloud2 pointcloud = *pt_const_ptr;
std_msgs::String index = *idx_const_ptr;
std::cout << "index: " << index.data << ", pointcloud size: " << pointcloud.data.size() << std::endl;
gtsam::Pose3 pose = keyframes_poses.at(index.data);
MRBSP::Utils::MapData3D map_data = std::pair<sensor_msgs::PointCloud2, gtsam::Pose3>(pointcloud, pose);
data_3d_container.insert(std::pair<std::string, MRBSP::Utils::MapData3D>(index.data, map_data));
}
}
}
}
void insertPointcloud(std::shared_ptr<octomap::OcTree>& p_octree_map, MRBSP::Utils::MapData3D& map_data_3d) {
sensor_msgs::PointCloud2 cloud = map_data_3d.first;
gtsam::Pose3 pose = map_data_3d.second;
double range_max = 5;
if(cloud.height == 0 || cloud.width == 0) {
std::cout << "Received empty cloud" << std::endl;
return;
}
// cast ros pointcloud to octomap pointcloud
octomap::Pointcloud octomap_scan;
octomap::pointCloud2ToOctomap(cloud, octomap_scan);
octomap::point3d sensor_origin = octomap::point3d(0, 0, 0);
gtsam::Pose3 current_sensor_pose = pose;
/*
auto sensor_pose_iter(m_sensor_pose.find(robot_id));
if (sensor_pose_iter != m_sensor_pose.end()) {
current_sensor_pose = pose.compose(m_sensor_pose.at(robot_id));
}
else {
std::cout << "Map: can't find sensor pose for current robot." << std::endl;
}
*/
std::cout << "convert gtsam object to octomap object..." << std::endl;
octomap::pose6d frame_origin = Conversion<octomap::pose6d>::as(current_sensor_pose);
std::cout << "insert pointcloud to octomap..." << std::endl;
p_octree_map->insertPointCloud(octomap_scan, sensor_origin, frame_origin, range_max);
std::cout << "Update inner occupancy.." << std::endl;
p_octree_map->updateInnerOccupancy();
}
| 38.258065 | 136 | 0.663435 | [
"object",
"vector"
] |
6fb6eef3189f1fabd33d3995e65863f7dec80458 | 618 | cpp | C++ | PHONELST.cpp | Akki5/spoj-solutions | 9169830415eb4f888ba0300eb47a423166b8d938 | [
"MIT"
] | 1 | 2019-05-23T20:03:40.000Z | 2019-05-23T20:03:40.000Z | PHONELST.cpp | Akki5/spoj-solutions | 9169830415eb4f888ba0300eb47a423166b8d938 | [
"MIT"
] | null | null | null | PHONELST.cpp | Akki5/spoj-solutions | 9169830415eb4f888ba0300eb47a423166b8d938 | [
"MIT"
] | 1 | 2021-08-28T16:48:42.000Z | 2021-08-28T16:48:42.000Z | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
int main(void)
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
vector <string> lst;
for( int i=0 ; i<n ; i++ )
{
string s;
cin>>s;
lst.push_back(s);
}
bool flag=false;
sort(lst.begin(),lst.end());
for( int i=0 ; i<n-1 ; i++)
{
if(lst[i+1].find(lst[i])==0)
{
flag=!flag;
break;
}
}
if(!flag)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
| 15.073171 | 51 | 0.459547 | [
"vector"
] |
6fb73afeda94f9572704747981f6a5fc0da09260 | 15,045 | cpp | C++ | vm/llvm/jit_inline_method.cpp | sshao/rubinius | 368df60245471f45f1294b0cd18f769377437246 | [
"BSD-3-Clause"
] | 1 | 2015-11-08T12:37:15.000Z | 2015-11-08T12:37:15.000Z | vm/llvm/jit_inline_method.cpp | sshao/rubinius | 368df60245471f45f1294b0cd18f769377437246 | [
"BSD-3-Clause"
] | null | null | null | vm/llvm/jit_inline_method.cpp | sshao/rubinius | 368df60245471f45f1294b0cd18f769377437246 | [
"BSD-3-Clause"
] | null | null | null | #ifdef ENABLE_LLVM
#include "llvm/jit_inline_method.hpp"
#include "llvm/method_info.hpp"
#include "call_frame.hpp"
using namespace llvm;
namespace rubinius {
namespace jit {
BasicBlock* InlineMethodBuilder::setup_inline(Value* self, Value* blk,
std::vector<Value*>& stack_args)
{
llvm::Value* prev = info_.parent_call_frame();
llvm::Value* args = ConstantExpr::getNullValue(ctx_->ptr_type("Arguments"));
BasicBlock* entry = BasicBlock::Create(ctx_->llvm_context(), "inline_entry", info_.function());
b().SetInsertPoint(entry);
info_.set_args(args);
info_.set_previous(prev);
info_.set_entry(entry);
BasicBlock* body = BasicBlock::Create(ctx_->llvm_context(), "method_body", info_.function());
pass_one(body);
BasicBlock* alloca_block = &info_.function()->getEntryBlock();
Value* cfstk = new AllocaInst(obj_type,
ConstantInt::get(ctx_->Int32Ty,
(sizeof(CallFrame) / sizeof(Object*)) + machine_code_->stack_size),
"cfstk", alloca_block->getTerminator());
call_frame = b().CreateBitCast(
cfstk,
llvm::PointerType::getUnqual(cf_type), "call_frame");
stk = b().CreateConstGEP1_32(cfstk, sizeof(CallFrame) / sizeof(Object*), "stack");
info_.set_call_frame(call_frame);
info_.set_stack(stk);
Value* var_mem = new AllocaInst(obj_type,
ConstantInt::get(ctx_->Int32Ty,
(sizeof(StackVariables) / sizeof(Object*)) + machine_code_->number_of_locals),
"var_mem", alloca_block->getTerminator());
vars = b().CreateBitCast(
var_mem,
llvm::PointerType::getUnqual(stack_vars_type), "vars");
info_.set_variables(vars);
Value* rd = constant(runtime_data_, ctx_->ptr_type("jit::RuntimeData"));
// Setup the CallFrame
//
// previous
b().CreateStore(prev, get_field(call_frame, offset::CallFrame::previous));
// msg
b().CreateStore(
b().CreatePointerCast(rd, ctx_->Int8PtrTy),
get_field(call_frame, offset::CallFrame::dispatch_data));
// compiled_code
method = b().CreateLoad(
b().CreateConstGEP2_32(rd, 0, offset::jit_RuntimeData::method, "method_pos"),
"compiled_code");
Value* code_gep = get_field(call_frame, offset::CallFrame::compiled_code);
b().CreateStore(method, code_gep);
// constant_scope
Value* constant_scope = b().CreateLoad(
b().CreateConstGEP2_32(method, 0, offset::CompiledCode::scope, "constant_scope_pos"),
"constant_scope");
Value* constant_scope_gep = get_field(call_frame, offset::CallFrame::constant_scope);
b().CreateStore(constant_scope, constant_scope_gep);
// flags
int flags = CallFrame::cInlineFrame;
if(!use_full_scope_) flags |= CallFrame::cClosedScope;
b().CreateStore(cint(flags),
get_field(call_frame, offset::CallFrame::flags));
// ip
b().CreateStore(cint(0),
get_field(call_frame, offset::CallFrame::ip));
// scope
b().CreateStore(vars, get_field(call_frame, offset::CallFrame::scope));
nil_stack(machine_code_->stack_size, constant(cNil, obj_type));
Value* mod = b().CreateLoad(
b().CreateConstGEP2_32(rd, 0, offset::jit_RuntimeData::module, "module_pos"),
"module");
setup_inline_scope(self, blk, mod);
// We know the right arguments are present, so we just need to put them
// in the right place.
//
// We don't support splat in an inlined method!
assert(machine_code_->splat_position < 0);
assert(stack_args.size() <= (size_t)machine_code_->total_args);
assign_arguments(stack_args);
b().CreateBr(body);
b().SetInsertPoint(body);
return entry;
}
void InlineMethodBuilder::assign_fixed_arguments(std::vector<Value*>& stack_args,
int local_start, int local_end, int arg_start)
{
for(int l = local_start, a = arg_start; l < local_end; l++, a++) {
Value* idx[] = {
cint(0),
cint(offset::StackVariables::locals),
cint(l)
};
Value* pos = b().CreateGEP(vars, idx, "local_pos");
Value* arg_val = stack_args.at(a);
LocalInfo* li = info_.get_local(l);
li->make_argument();
if(ctx_->llvm_state()->type_optz()) {
if(type::KnownType::has_hint(ctx_, arg_val)) {
type::KnownType kt = type::KnownType::extract(ctx_, arg_val);
li->set_known_type(kt);
}
}
b().CreateStore(arg_val, pos);
}
}
void InlineMethodBuilder::assign_arguments(std::vector<Value*>& stack_args) {
const native_int T = machine_code_->total_args;
const native_int M = machine_code_->required_args;
const native_int SN = stack_args.size();
if(SN == M && M == T) {
assign_fixed_arguments(stack_args, 0, stack_args.size(), 0);
return;
}
const native_int P = machine_code_->post_args;
const native_int H = M - P;
// head arguments
if(H > 0) {
assign_fixed_arguments(stack_args, 0, H, 0);
}
if(!machine_code_->keywords) {
const native_int O = T - M;
const native_int E = SN - M;
native_int X;
const native_int ON = (X = MIN(O, E)) > 0 ? X : 0;
const native_int PI = H + O;
// optional arguments
if(O > 0) {
if(ON > 0) {
assign_fixed_arguments(stack_args, H, MIN(H + O, H + ON), H);
}
if(ON < O) {
// missing optional arguments
Type* undef_type = llvm::PointerType::getUnqual(obj_type);
Object** addr = ctx_->llvm_state()->shared().globals.undefined.object_address();
Value* undef = b().CreateLoad(constant(addr, undef_type));
for(int l = H + ON; l < H + O; l++) {
Value* idx[] = {
cint(0),
cint(offset::StackVariables::locals),
cint(l)
};
Value* pos = b().CreateGEP(vars, idx, "local_pos");
b().CreateStore(undef, pos);
}
}
}
// post arguments
if(P > 0) {
assign_fixed_arguments(stack_args, PI, SN, SN - P);
}
} else {
BasicBlock* alloca_block = &info_.function()->getEntryBlock();
Value* args_array = new AllocaInst(obj_type, cint(SN - H),
"args_array", alloca_block->getTerminator());
for(int i = H; i < SN; i++) {
b().CreateStore(stack_args.at(i),
b().CreateGEP(args_array, cint(i - H), "args_array_pos"));
}
Value* keyword_object = b().CreateAlloca(obj_type, 0, "keyword_object");
Value* local_index = b().CreateAlloca(ctx_->Int32Ty, 0, "local_index");
Value* arg_index = b().CreateAlloca(ctx_->Int32Ty, 0, "args_index");
Value* null = Constant::getNullValue(obj_type);
if(SN > M) {
Signature sig(ctx_, "Object");
sig << "State";
sig << "CallFrame";
sig << "Object";
Value* call_args[] = {
info_.state(),
info_.previous(),
b().CreateLoad(
b().CreateGEP(args_array, cint(SN - H - 1)))
};
Value* keyword_val = sig.call("rbx_check_keyword",
call_args, 3, "keyword_val", b());
b().CreateStore(keyword_val, keyword_object);
} else {
b().CreateStore(null, keyword_object);
}
Value* N = cint(SN);
// K = (keyword_object && N > M) ? 1 : 0;
Value* K = b().CreateSelect(
b().CreateAnd(
b().CreateICmpNE(b().CreateLoad(keyword_object), null),
b().CreateICmpSGT(N, cint(M))),
cint(1), cint(0));
// O = T - M - (mcode->keywords ? 1 : 0);
Value* O = cint(T - M - 1);
// E = N - M - K;
Value* N_M_K = b().CreateSub(N, b().CreateAdd(cint(M), K));
Value* E = b().CreateSelect(b().CreateICmpSGE(N_M_K, cint(0)), N_M_K, cint(0));
// ON = (X = MIN(O, E)) > 0 ? X : 0;
Value* X = b().CreateSelect(b().CreateICmpSLE(O, E), O, E);
Value* ON = b().CreateSelect(b().CreateICmpSGT(X, cint(0)), X, cint(0));
// arg limit = H + ON
Value* H_ON = b().CreateAdd(cint(H), ON);
BasicBlock* pre_opts = info_.new_block("pre_optional_args");
BasicBlock* post_opts = info_.new_block("post_optional_args");
b().CreateCondBr(
b().CreateICmpSGT(O, cint(0)),
pre_opts, post_opts);
// optional arguments
// for(l = a = H; l < H + O && a < H + ON; l++, a++)
b().SetInsertPoint(pre_opts);
// local limit = H + O
Value* H_O = b().CreateAdd(cint(H), O);
{
BasicBlock* top = info_.new_block("opt_arg_loop_top");
BasicBlock* body = info_.new_block("opt_arg_loop_body");
BasicBlock* after = info_.new_block("opt_arg_loop_cont");
// local_index = arg_index = H
b().CreateStore(cint(H), local_index);
b().CreateStore(cint(0), arg_index);
b().CreateBr(top);
b().SetInsertPoint(top);
Value* local_i = b().CreateLoad(local_index, "local_index");
Value* arg_i = b().CreateLoad(arg_index, "arg_index");
// local_index < H + O && arg_index < H + ON
Value* loop_test = b().CreateAnd(
b().CreateICmpSLT(local_i, H_O),
b().CreateICmpSLT(arg_i, ON));
b().CreateCondBr(loop_test, body, after);
b().SetInsertPoint(body);
Value* idx[] = {
cint(0),
cint(offset::StackVariables::locals),
local_i
};
// locals[local_index] = args[local_index]
b().CreateStore(
b().CreateLoad(
b().CreateGEP(args_array, arg_i)),
b().CreateGEP(vars, idx));
// local_index++
b().CreateStore(b().CreateAdd(local_i, cint(1)), local_index);
// arg_index++
b().CreateStore(b().CreateAdd(arg_i, cint(1)), arg_index);
b().CreateBr(top);
b().SetInsertPoint(after);
}
// if ON < O : more optional parameters than arguments available
{
BasicBlock* pre = info_.new_block("missing_opt_arg_loop_pre");
BasicBlock* top = info_.new_block("missing_opt_arg_loop_top");
BasicBlock* body = info_.new_block("missing_opt_arg_loop_body");
BasicBlock* after = info_.new_block("missing_opt_arg_loop_cont");
b().CreateCondBr(
b().CreateICmpSLT(ON, O),
pre, post_opts);
b().SetInsertPoint(pre);
b().CreateStore(H_ON, local_index);
Type* undef_type = llvm::PointerType::getUnqual(obj_type);
Object** addr = ctx_->llvm_state()->shared().globals.undefined.object_address();
Value* undef = b().CreateLoad(constant(addr, undef_type));
b().CreateBr(top);
b().SetInsertPoint(top);
Value* local_i = b().CreateLoad(local_index, "local_index");
b().CreateCondBr(
b().CreateICmpSLT(local_i, H_O),
body, after);
b().SetInsertPoint(body);
Value* idx[] = {
cint(0),
cint(offset::StackVariables::locals),
local_i
};
// locals[local_index] = undefined
b().CreateStore(
undef,
b().CreateGEP(vars, idx));
// local_index++
b().CreateStore(b().CreateAdd(local_i, cint(1)), local_index);
b().CreateBr(top);
b().SetInsertPoint(after);
b().CreateBr(post_opts);
}
b().SetInsertPoint(post_opts);
BasicBlock* post_args = info_.new_block("post_args");
b().CreateBr(post_args);
b().SetInsertPoint(post_args);
BasicBlock* kw_args = info_.new_block("kw_args");
if(P > 0) {
// post arguments
// PI = H + O
Value* PI = H_O;
// l = PI; l < PI + P && a < N - K - H
Value* PI_P = b().CreateAdd(PI, cint(P));
Value* N_K_H = b().CreateSub(b().CreateSub(N, K), cint(H));
// local_index = PI
b().CreateStore(PI, local_index);
// arg_index = N - P - K - H
b().CreateStore(
b().CreateSub(
b().CreateSub(
b().CreateSub(N, cint(P)), K), cint(H)),
arg_index);
{
BasicBlock* top = info_.new_block("post_arg_loop_top");
BasicBlock* body = info_.new_block("post_arg_loop_body");
BasicBlock* after = info_.new_block("post_arg_loop_cont");
b().CreateBr(top);
b().SetInsertPoint(top);
Value* local_i = b().CreateLoad(local_index, "local_index");
Value* arg_i = b().CreateLoad(arg_index, "arg_index");
// l < PI + P && a < N - K
Value* loop_test = b().CreateAnd(
b().CreateICmpSLT(local_i, PI_P),
b().CreateICmpSLT(arg_i, N_K_H));
b().CreateCondBr(loop_test, body, after);
b().SetInsertPoint(body);
Value* idx[] = {
cint(0),
cint(offset::StackVariables::locals),
local_i
};
// locals[local_index] = args[local_index]
b().CreateStore(
b().CreateLoad(
b().CreateGEP(args_array, arg_i)),
b().CreateGEP(vars, idx));
// local_index++
b().CreateStore(b().CreateAdd(local_i, cint(1)), local_index);
// arg_index++
b().CreateStore(b().CreateAdd(arg_i, cint(1)), arg_index);
b().CreateBr(top);
b().SetInsertPoint(after);
}
}
b().CreateBr(kw_args);
b().SetInsertPoint(kw_args);
// keywords
{
BasicBlock* before_kw = info_.new_block("before_keywords");
BasicBlock* after_kw = info_.new_block("after_keywords");
Value* null = Constant::getNullValue(obj_type);
Value* kw_val = b().CreateLoad(keyword_object, "kw_val");
b().CreateCondBr(
b().CreateICmpNE(kw_val, null),
before_kw, after_kw);
b().SetInsertPoint(before_kw);
Value* idx[] = {
cint(0),
cint(offset::StackVariables::locals),
cint(T - 1)
};
b().CreateStore(
b().CreateLoad(keyword_object),
b().CreateGEP(vars, idx));
b().CreateBr(after_kw);
b().SetInsertPoint(after_kw);
}
}
}
void InlineMethodBuilder::setup_inline_scope(Value* self, Value* blk, Value* mod) {
Value* heap_null = ConstantExpr::getNullValue(llvm::PointerType::getUnqual(vars_type));
Value* heap_pos = get_field(vars, offset::StackVariables::on_heap);
b().CreateStore(heap_null, heap_pos);
b().CreateStore(self, get_field(vars, offset::StackVariables::self));
b().CreateStore(mod, get_field(vars, offset::StackVariables::module));
b().CreateStore(blk, get_field(vars, offset::StackVariables::block));
b().CreateStore(Constant::getNullValue(ctx_->ptr_type("VariableScope")),
get_field(vars, offset::StackVariables::parent));
b().CreateStore(constant(cNil, obj_type), get_field(vars, offset::StackVariables::last_match));
nil_locals();
}
}
}
#endif
| 29.674556 | 99 | 0.579993 | [
"object",
"vector"
] |
6fbd14776d3e5370701b839cc2311506179d2d3a | 8,061 | cpp | C++ | src/modules/DopingProfileReader/DopingProfileReaderModule.cpp | bencline1/Allpix_GaAs | c4922dc9d981aca265e076eb5bfe4cefe51913a2 | [
"MIT"
] | 3 | 2019-03-04T22:31:32.000Z | 2021-04-20T11:19:17.000Z | src/modules/DopingProfileReader/DopingProfileReaderModule.cpp | bencline1/Allpix_GaAs | c4922dc9d981aca265e076eb5bfe4cefe51913a2 | [
"MIT"
] | 27 | 2019-04-01T12:25:46.000Z | 2021-09-03T12:20:19.000Z | src/modules/DopingProfileReader/DopingProfileReaderModule.cpp | bencline1/Allpix_GaAs | c4922dc9d981aca265e076eb5bfe4cefe51913a2 | [
"MIT"
] | 15 | 2017-08-08T14:57:51.000Z | 2021-06-26T17:16:21.000Z | /**
* @file
* @brief Implementation of module to read doping concentration maps
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "DopingProfileReaderModule.hpp"
#include <string>
#include <utility>
#include "core/utils/log.h"
using namespace allpix;
DopingProfileReaderModule::DopingProfileReaderModule(Configuration& config, Messenger*, std::shared_ptr<Detector> detector)
: Module(config, detector), detector_(std::move(detector)) {
// Enable multithreading of this module if multithreading is enabled
allow_multithreading();
}
void DopingProfileReaderModule::initialize() {
FieldType type = FieldType::GRID;
// Check field strength
auto field_model = config_.get<DopingProfile>("model");
// set depth of doping profile
auto model = detector_->getModel();
auto doping_depth = config_.get<double>("doping_depth", model->getSensorSize().z());
if(doping_depth - model->getSensorSize().z() > std::numeric_limits<double>::epsilon()) {
throw InvalidValueError(config_, "doping_depth", "doping depth can not be larger than the sensor thickness");
}
auto sensor_max_z = model->getSensorCenter().z() + model->getSensorSize().z() / 2.0;
auto thickness_domain = std::make_pair(sensor_max_z - doping_depth, sensor_max_z);
// Calculate the field depending on the configuration
if(field_model == DopingProfile::MESH) {
// Read the field scales from the configuration, defaulting to 1.0x1.0 pixel cell:
auto scales = config_.get<ROOT::Math::XYVector>("field_scale", {1.0, 1.0});
// FIXME Add sanity checks for scales here
LOG(DEBUG) << "Doping concentration map will be scaled with factors " << scales;
std::array<double, 2> field_scale{{scales.x(), scales.y()}};
// Get the field offset in fractions of the pixel pitch, default is 0.0x0.0, i.e. starting at pixel boundary:
auto offset = config_.get<ROOT::Math::XYVector>("field_offset", {0.0, 0.0});
if(offset.x() > 1.0 || offset.y() > 1.0) {
throw InvalidValueError(
config_,
"field_offset",
"shifting doping concentration map by more than one pixel (offset > 1.0) is not allowed");
}
LOG(DEBUG) << "Doping concentration map starts with offset " << offset << " to pixel boundary";
std::array<double, 2> field_offset{{offset.x(), offset.y()}};
auto field_data = read_field(field_scale);
detector_->setDopingProfileGrid(
field_data.getData(), field_data.getDimensions(), field_scale, field_offset, thickness_domain);
} else if(field_model == DopingProfile::CONSTANT) {
LOG(TRACE) << "Adding constant doping concentration";
type = FieldType::CONSTANT;
auto concentration = config_.get<double>("doping_concentration");
LOG(INFO) << "Set constant doping concentration of " << Units::display(concentration, {"/cm/cm/cm"});
FieldFunction<double> function = [concentration](const ROOT::Math::XYZPoint&) noexcept { return concentration; };
detector_->setDopingProfileFunction(function, type);
} else if(field_model == DopingProfile::REGIONS) {
LOG(TRACE) << "Adding doping concentration depending on sensor region";
type = FieldType::CUSTOM;
auto concentration = config_.getMatrix<double>("doping_concentration");
std::map<double, double> concentration_map;
for(const auto& region : concentration) {
if(region.size() != 2) {
throw InvalidValueError(
config_, "doping_concentration", "expecting two values per row, depth and concentration");
}
concentration_map[region.front()] = region.back();
LOG(INFO) << "Set constant doping concentration of " << Units::display(region.back(), {"/cm/cm/cm"})
<< " at sensor depth " << Units::display(region.front(), {"um", "mm"});
}
FieldFunction<double> function = [concentration_map, thickness = detector_->getModel()->getSensorSize().z()](
const ROOT::Math::XYZPoint& position) {
// Lower bound returns the first element that is *not less* than the given key - in this case, the z position
// should always be *before* the region boundary set in the vector
auto item = concentration_map.lower_bound(thickness / 2 - position.z());
if(item != concentration_map.end()) {
return item->second;
} else {
return concentration_map.rbegin()->second;
}
};
detector_->setDopingProfileFunction(function, type);
}
}
/**
* The field read from the INIT format are shared between module instantiations using the static FieldParser.
*/
FieldParser<double> DopingProfileReaderModule::field_parser_(FieldQuantity::SCALAR);
FieldData<double> DopingProfileReaderModule::read_field(std::array<double, 2> field_scale) {
try {
LOG(TRACE) << "Fetching doping concentration map from mesh file";
// Get field from file
auto field_data = field_parser_.getByFileName(config_.getPath("file_name", true), "/cm/cm/cm");
// Check if electric field matches chip
check_detector_match(field_data.getSize(), field_scale);
LOG(INFO) << "Set doping concentration map with " << field_data.getDimensions().at(0) << "x"
<< field_data.getDimensions().at(1) << "x" << field_data.getDimensions().at(2) << " cells";
// Return the field data
return field_data;
} catch(std::invalid_argument& e) {
throw InvalidValueError(config_, "file_name", e.what());
} catch(std::runtime_error& e) {
throw InvalidValueError(config_, "file_name", e.what());
} catch(std::bad_alloc& e) {
throw InvalidValueError(config_, "file_name", "file too large");
}
}
/**
* @brief Check if the detector matches the file header
*/
void DopingProfileReaderModule::check_detector_match(std::array<double, 3> dimensions, std::array<double, 2> field_scale) {
auto xpixsz = dimensions[0];
auto ypixsz = dimensions[1];
auto thickness = dimensions[2];
auto model = detector_->getModel();
// Do a several checks with the detector model
if(model != nullptr) {
// Check field dimension in z versus the sensor thickness:
if(std::fabs(thickness - model->getSensorSize().z()) > std::numeric_limits<double>::epsilon()) {
LOG(WARNING) << "Thickness of doping concentration map is " << Units::display(thickness, "um")
<< " but sensor thickness is " << Units::display(model->getSensorSize().z(), "um");
}
// Check the field extent along the pixel pitch in x and y:
if(std::fabs(xpixsz - model->getPixelSize().x() * field_scale[0]) > std::numeric_limits<double>::epsilon() ||
std::fabs(ypixsz - model->getPixelSize().y() * field_scale[1]) > std::numeric_limits<double>::epsilon()) {
LOG(WARNING) << "Doping concentration map size is (" << Units::display(xpixsz, {"um", "mm"}) << ","
<< Units::display(ypixsz, {"um", "mm"}) << ") but current configuration results in an map area of ("
<< Units::display(model->getPixelSize().x() * field_scale[0], {"um", "mm"}) << ","
<< Units::display(model->getPixelSize().y() * field_scale[1], {"um", "mm"}) << ")" << std::endl
<< "The size of the area to which the doping concentration is applied can be changes using the "
"field_scale parameter.";
}
}
}
| 49.759259 | 125 | 0.639251 | [
"mesh",
"vector",
"model"
] |
6fcd8b58f86f2b475a385fec0dc803d0c91a6ad3 | 7,271 | cpp | C++ | FrameLib_Objects/Time_Smoothing/FrameLib_MovingAverage.cpp | AlexHarker/FrameLib | 04b9882561c83d3240c6cb07f14861244d1d6272 | [
"BSD-3-Clause"
] | 33 | 2017-08-13T00:02:41.000Z | 2022-03-10T23:02:17.000Z | FrameLib_Objects/Time_Smoothing/FrameLib_MovingAverage.cpp | AlexHarker/FrameLib | 04b9882561c83d3240c6cb07f14861244d1d6272 | [
"BSD-3-Clause"
] | 60 | 2018-02-01T23:33:36.000Z | 2022-03-23T23:25:13.000Z | FrameLib_Objects/Time_Smoothing/FrameLib_MovingAverage.cpp | AlexHarker/FrameLib | 04b9882561c83d3240c6cb07f14861244d1d6272 | [
"BSD-3-Clause"
] | 8 | 2018-02-01T20:18:46.000Z | 2020-07-03T12:53:04.000Z |
#include "FrameLib_MovingAverage.h"
#include "../../FrameLib_Dependencies/Interpolation.hpp"
// Constructor
FrameLib_MovingAverage::FrameLib_MovingAverage(FrameLib_Context context, const FrameLib_Parameters::Serial *serialisedParameters, FrameLib_Proxy *proxy)
: FrameLib_Processor(context, proxy, &sParamInfo, 5, 2)
, mFrameSize(0)
{
mParameters.addDouble(kAlphaUp, "alpha_up", 0.5, 0);
mParameters.setClip(0.0, 1.0);
mParameters.addDouble(kAlphaDown, "alpha_down", 0.5, 1);
mParameters.setClip(0.0, 1.0);
mParameters.addDouble(kAverage, "average", 0.0, 2);
mParameters.addDouble(kDeviation, "deviation", 0.0, 3);
mParameters.set(serialisedParameters);
setParameterInput(4);
}
// Info
std::string FrameLib_MovingAverage::objectInfo(bool verbose)
{
return formatInfo("Calculates per sample moving averages and standard deviations: "
"The moving average and standard deviations are exponentially weighted. "
"An alpha value [0-1] controls the rate of update from static to immediate. "
"Alphas may be set per sample using the corresponding input or by parameters. "
"Parameters allow different alphas when the average increases or decreases. "
"Frames are expected to be of a uniform length. "
"The output is the same length as the input. "
"If the input length changes then the average and standard deviations are reset. "
"These can also be individually reset using the corresponding reset inputs. "
"Frames at the reset inputs set the starting values for calculation. "
"When these are too short they are padded with values provided by parameter.",
"Calculates per sample moving averages and standard deviations.", verbose);
}
std::string FrameLib_MovingAverage::inputInfo(unsigned long idx, bool verbose)
{
switch (idx)
{
case 0: return "Input";
case 1: return "Alphas";
case 2: return formatInfo("Average Reset - resets and sets values", "Average Reset", verbose);
case 3: return formatInfo("Deviation Reset - resets and sets values", "Deviation Reset", verbose);
default: return parameterInputInfo(verbose);
}
}
std::string FrameLib_MovingAverage::outputInfo(unsigned long idx, bool verbose)
{
if (idx)
return "Standard Deviations";
else
return "Averages";
}
// Parameter Info
FrameLib_MovingAverage::ParameterInfo FrameLib_MovingAverage::sParamInfo;
FrameLib_MovingAverage::ParameterInfo::ParameterInfo()
{
add("Sets the alpha value when the average is increasing. "
"Note this is only used if a sufficiently long alpha frame is not present.");
add("Sets the alpha value when the average is increasing. "
"Note this is only used if a sufficiently long alpha frame is not present.");
add("Sets the padding value for averages. "
"Note this is only used if a sufficiently long average reset frame is not present.");
add("Sets the padding value for deviations. "
"Note this is only used if a sufficiently long deviation reset frame is not present.");
}
// Object Reset
void FrameLib_MovingAverage::objectReset()
{
mFrameSize = 0;
mLastAvgResetTime = FrameLib_TimeFormat(0);
mLastDevResetTime = FrameLib_TimeFormat(0);
}
double getAlpha(const double *alphas, unsigned long size, unsigned long idx, double defaultValue)
{
return size ? alphas[std::min(idx, size - 1)] : defaultValue;
}
// Process
void FrameLib_MovingAverage::process()
{
unsigned long sizeIn, sizeOut, sizeAlphas;
const double *input = getInput(0, &sizeIn);
const double *alphas = getInput(1, &sizeAlphas);
double alphaUp = mParameters.getValue(kAlphaUp);
double alphaDown = mParameters.getValue(kAlphaDown);
bool resetAverage = mLastAvgResetTime != getInputFrameTime(2);
bool resetDeviation = mLastDevResetTime != getInputFrameTime(3);
if (mFrameSize != sizeIn)
{
mAverageFrame = allocAutoArray<double>(sizeIn);
mVarianceFrame = allocAutoArray<double>(sizeIn);
mFrameSize = mAverageFrame && mVarianceFrame ? sizeIn : 0;
resetAverage = true;
resetDeviation = true;
}
requestOutputSize(0, mFrameSize);
requestOutputSize(1, mFrameSize);
allocateOutputs();
double *avgOutput = getOutput(0, &sizeOut);
double *stdOutput = getOutput(1, &sizeOut);
// Resets
if (resetAverage)
{
const double *avgDefaults = getInput(2, &sizeIn);
PaddedVector averages(avgDefaults, sizeIn, mParameters.getValue(kAverage));
for (unsigned long i = 0; i < mFrameSize; i++)
mAverageFrame[i] = averages[i];
mLastAvgResetTime = getInputFrameTime(2);
}
if (resetDeviation)
{
const double *devDefaults = getInput(3, &sizeIn);
PaddedVector deviations(devDefaults, sizeIn, mParameters.getValue(kDeviation));
for (unsigned long i = 0; i < mFrameSize; i++)
{
const double deviation = deviations[i];
mVarianceFrame[i] = deviation * deviation;
}
mLastDevResetTime = getInputFrameTime(3);
}
// Calculate outputs
if (!resetAverage && !resetDeviation)
{
for (unsigned long i = 0; i < sizeOut; i++)
{
double defaultAlpha = input[i] > mAverageFrame[i] ? alphaUp : alphaDown;
double alpha = getAlpha(alphas, sizeAlphas, i, defaultAlpha);
double delta = input[i] - mAverageFrame[i];
mAverageFrame[i] += alpha * delta;
mVarianceFrame[i] = (1.0 - alpha) * (mVarianceFrame[i] + alpha * delta * delta);
avgOutput[i] = mAverageFrame[i];
stdOutput[i] = sqrt(mVarianceFrame[i]);
}
}
else if (!resetAverage)
{
for (unsigned long i = 0; i < sizeOut; i++)
{
double defaultAlpha = input[i] > mAverageFrame[i] ? alphaUp : alphaDown;
double alpha = getAlpha(alphas, sizeAlphas, i, defaultAlpha);
mAverageFrame[i] = linear_interp<double>()(alpha, mAverageFrame[i], input[i]);
avgOutput[i] = mAverageFrame[i];
stdOutput[i] = sqrt(mVarianceFrame[i]);
}
}
else if (!resetDeviation)
{
for (unsigned long i = 0; i < sizeOut; i++)
{
double defaultAlpha = input[i] > mAverageFrame[i] ? alphaUp : alphaDown;
double alpha = getAlpha(alphas, sizeAlphas, i, defaultAlpha);
double delta = input[i] - mAverageFrame[i];
mVarianceFrame[i] = (1.0 - alpha) * (mVarianceFrame[i] + alpha * delta * delta);
avgOutput[i] = mAverageFrame[i];
stdOutput[i] = sqrt(mVarianceFrame[i]);
}
}
else
{
for (unsigned long i = 0; i < sizeOut; i++)
{
avgOutput[i] = mAverageFrame[i];
stdOutput[i] = sqrt(mVarianceFrame[i]);
}
}
}
| 35.642157 | 152 | 0.623986 | [
"object"
] |
6fd1cdb569135d871589d2a661959ae1aa52c1e4 | 2,344 | hpp | C++ | source/hougl/include/hou/gl/gl_invalid_context_error.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/hougl/include/hou/gl/gl_invalid_context_error.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/hougl/include/hou/gl/gl_invalid_context_error.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#ifndef HOU_GL_GL_INVALID_CONTEXT_ERROR_HPP
#define HOU_GL_GL_INVALID_CONTEXT_ERROR_HPP
#include "hou/cor/exception.hpp"
#include "hou/gl/open_gl.hpp"
#include "hou/gl/gl_config.hpp"
#include "hou/cor/std_string.hpp"
namespace hou
{
namespace gl
{
class shared_object_handle;
class non_shared_object_handle;
/** Invalid OpenGL context error.
*
* This exception is thrown when an OpenGL call is made using an OpenGL object
* which is not owned by the current context.
*/
class HOU_GL_API invalid_context_error : public exception
{
public:
/** Constructor.
*
* \param path the path to the source file where the error happened.
*
* \param line the line where the error happened.
*
* \throws std::bad_alloc.
*/
invalid_context_error(const std::string& path, uint line);
};
/** Checks if the object is owned by the current context, and throws an
* exception if it is not.
*
* \param o the object whose ownership has to be checked.
*
* \param path the source file path to be written in the exception in case of
* an error.
*
* \param line the source file line to be written in the exception in case of
* an error.
*
* \throws hou::gl::invalid_context_error if the current OpenGL context does
* not own the object.
*/
void HOU_GL_API check_context_ownership(
const shared_object_handle& o, const std::string& path, uint line);
/** Checks if the object is owned by the current context, and throws an
* exception if it is not.
*
* \param o the object whose ownership has to be checked.
*
* \param path the source file path to be written in the exception in case of
* an error.
*
* \param line the source file line to be written in the exception in case of
* an error.
*
* \throws hou::gl::invalid_context_error if the current OpenGL context does
* not own the object.
*/
void HOU_GL_API check_context_ownership(
const non_shared_object_handle& o, const std::string& path, uint line);
} // namespace gl
} // namespace hou
#ifdef HOU_ENABLE_GL_ERROR_CHECKS
#define HOU_GL_CHECK_CONTEXT_OWNERSHIP(objectHandle) \
::hou::gl::check_context_ownership(objectHandle, __FILE__, __LINE__)
#else
#define HOU_GL_CHECK_CONTEXT_OWNERSHIP(objectHandle)
#endif
#endif
| 24.93617 | 80 | 0.731655 | [
"object"
] |
6fd3420a1342483d8fcb65eb8ebe71a0db4f38a5 | 4,936 | cpp | C++ | src/qa.cpp | diogo-aos/CarND-Path-Planning-Project | d7fff1b928621a43630c45953162cd549bf1af86 | [
"MIT"
] | 2 | 2022-02-24T11:04:08.000Z | 2022-02-24T11:04:26.000Z | src/qa.cpp | diogo-aos/CarND-Path-Planning-Project | d7fff1b928621a43630c45953162cd549bf1af86 | [
"MIT"
] | null | null | null | src/qa.cpp | diogo-aos/CarND-Path-Planning-Project | d7fff1b928621a43630c45953162cd549bf1af86 | [
"MIT"
] | null | null | null | int lane = 1;
double ref_speed = 49.5; // mph
prev_size = previous_path_x.size();
if(prev_size > 0){
car_s = end_path_s;
}
bool too_close = false;
//find ref_v to use
for (int i=0; i < sensor_fusion.size(); i++){
//car is in my lane
double d = sensor_fusion[i][6];
double my_lane_center = 2 * 4 * lane;
if (d > my_lane_center - 2 && d < my_lane_center + 2){
double vx = sensor_fusion[i][3];
double vy = sensor_fusion[i][4];
double check_speed = sqrt(vx*vx + vy*vy);
check_car_s = sensor_fusion[i][5];
// if using previous points can project s value out
check_car_s += ((double) prev_size * 0.02 * check_speed);
//check s values greater than mine and s gap
if ((check_car_s > car_s) && (check_car_s-car_s) < 30){
//do some logic here, lower reference velocity so we don't crash
// into the car in front of us, ould also flag to try to change
// lanes
// ref_vel = 29.5; //mph
too_close = true;
if (lane > 0) {
lane = 0;
}
}
} // end if car is in my lane
} // end for sensor fusion
if (too_close){
ref_speed -= .224;
}
else if(ref_speed < 49.5){
ref_speed += .224;
}
// Create a list of widely spaced (x,y) waypoints, evenly spaced at 30m
// later we will interpolate these waypoints with a spline and fill it
// in with more points that control speed.
vector <double> ptsx;
vector <double> ptsy;
// reference x,y, yaw states
// either we will reference the starting point as where the car is or at
// the previous path's end point
double ref_x = car_x;
double ref_y = car_y;
double ref_yaw = deg2rad(car_yaw);
// if previous path's size is almost empty, use the car as starting reference
if (prev_size < 2){
// use two points that make the path tangent to the car,
// projecting bicycle model to the past
double prev_car_x = car_x - cos(car_yaw);
double prev_car_y = car_y + sin(car_yaw);
ptsx.push_back(prev_car_x);
ptsx.push_back(car_x);
ptsy.push_back(prev_car_y);
ptsy.push_back(car_y);
}
// use previous path's end point as starting reference
else {
// redefine reference state to be previous path's end point
ref_x = previous_path_x[prev_size-1];
ref_y = previous_path_y[prev_size-1];
double ref_x_prev = previous_path_x[prev_size-2];
double ref_y_prev = previous_path_y[prev_size-2];
ref_yaw = atan2(ref_y - ref_y_prev,
ref_x - ref_x_prev); // arctan
// use two points that make the path tangent to the previous path's end point
ptsx.push_back(ref_x);
ptsx.push_back(ref_x_prev);
ptsy.push_back(ref_y);
ptsy.push_back(ref_y_prev);
}
// in Frenet add evenly 30m spaced points ahead of the the starting reference
vector double> next_wp0 = getXY(car_s + 30, 2+4*lane, map_waypoints_s, map_waypoints_x, map_waypoints_y);
vector double> next_wp1 = getXY(car_s + 60, 2+4*lane, map_waypoints_s, map_waypoints_x, map_waypoints_y);
vector double> next_wp2 = getXY(car_s + 90, 2+4*lane, map_waypoints_s, map_waypoints_x, map_waypoints_y);
ptsx.push_back(next_wp0[0]);
ptsx.push_back(next_wp1[0]);
ptsx.push_back(next_wp2[0]);
ptsy.push_back(next_wp0[1)];
ptsy.push_back(next_wp1[1]);
ptsy.push_back(next_wp2[1]);
for (int i = 0; i < ptsx.size(); i++){
//shift point to car reference
// i.e. shift point such that car (ref_x, ref_y) is now at origin
double shift_x = ptsx[i]-ref_x;
double shift_y = ptsy[i]-ref_y;
// rotate point so that ref_yaw is 0 degrees
ptsx[i] = shift_x * cos(0 - ref_yaw) - shift_y * sin(0 - ref_yaw);
ptsy[i] = shift_x * sin(0 - ref_yaw) + shift_y * cos(0 - ref_yaw);
}
// create spline
tk::spline s;
// set x,y points to the spline
s.set_points(ptsx, ptsy);
// define the actual (x,y) points we will use for the planner
vector <double> next_x_vals;
vector <double> next_y_vals;
// use all unused points from previous path in next path
for(int i=0; i<prev_size; i++){
next_x_vals.push_back(previous_path_x[i]);
next_y_vals.push_back(previous_path_y[i]);
}
// calculate how to break up spline points so that we travel
// at our desired reference velocity
double target_x = 30.0; // look at a 30m horizon
double target_y = s(target_x);
double target_dist = sqrt(target_x*target_x + target_y*target_y);
double x_add_on = 0;
// fill up the rest of our path planner after filling it with
// previous points, here we will always output 50 points
for (int i=0; i<=50-prev_size; i++){
double N = target_dist / (0.02 * ref_vel / 2.24); // 1 mph / 2.24 -> m/s
double x_point = x_add_on + (target_x) / N;
double y_point = s(x_point);
x_add_on = x_point;
double x_ref = x_point; // not to be confused with ref_x
double y_ref = y_point;
// undo rotation
x_point = x_ref * cos(ref_yaw) - y_ref * sin(ref_yaw);
y_point = x_ref * sin(ref_yaw) + y_ref * cos(ref_yaw);
// undo shift
x_point += ref_x;
y_point += ref_y;
next_x_vals.push_back(x_point);
next_y_vals.push_back(y_point);
}
| 28.045455 | 105 | 0.688209 | [
"vector",
"model"
] |
6fe51861a87e0375ed8ad371d500afaae6dce8e3 | 8,263 | cpp | C++ | kuka_kr6r900_common/kuka_cv/src/CommonCV.cpp | AlexeiOvcharov/kuka_kr6r900_simulation | 0d9125fe0cf56ca0a48aa1be2eb6ec72884bda4c | [
"Apache-2.0"
] | 10 | 2020-06-12T08:00:16.000Z | 2022-03-23T09:54:35.000Z | kuka_kr6r900_common/kuka_cv/src/CommonCV.cpp | airalab/kuka_kr6r900_simulation | 0d9125fe0cf56ca0a48aa1be2eb6ec72884bda4c | [
"Apache-2.0"
] | 7 | 2020-11-17T19:58:58.000Z | 2021-04-19T12:01:24.000Z | kuka_kr6r900_common/kuka_cv/src/CommonCV.cpp | airalab/kuka_kr6r900_simulation | 0d9125fe0cf56ca0a48aa1be2eb6ec72884bda4c | [
"Apache-2.0"
] | 2 | 2020-11-16T14:33:45.000Z | 2021-05-31T02:02:14.000Z | #include <CommonCV.h>
#include <iostream>
#include <math.h>
#define COMMONCV_DEBUG false
bool checkUniqueOfVector(std::vector<cv::Vec2f> & vec, cv::Vec2f critria, cv::Vec2f maxDiff)
{
if (vec.empty())
return true;
for (size_t i = 0; i < vec.size(); ++i)
if (abs(vec[i][0] - critria[0]) < maxDiff[0] && abs(vec[i][1] - critria[1]) < maxDiff[1])
return false;
return true;
}
bool checkUniqueOfVector(std::vector<Quadrilateral> & vec, Quadrilateral critria, cv::Vec2f maxDiff)
{
if (vec.empty())
return true;
for (size_t i = 0; i < vec.size(); ++i)
if (abs(vec[i].center.x - critria.center.x) < maxDiff[0] && abs(vec[i].center.y - critria.center.y) < maxDiff[1])
return false;
return true;
}
void drawQuadrilateral(cv::Mat & image, Quadrilateral & q) {
for (size_t p = 0; p < 4; ++p) {
if (p != 3)
cv::line(image, q.p[p], q.p[p+1], cv::Scalar(0, 200, 200), 2, 8);
else
cv::line(image, q.p[p], q.p[0], cv::Scalar(0, 200, 200), 2, 8);
cv::circle(image, q.p[p], 5, cv::Scalar(0, 0, 200), 2, 8);
cv::putText(image, std::to_string(p), q.p[p], cv::FONT_HERSHEY_SIMPLEX, 1.2, cv::Scalar(0,0,200), 2, CV_AA);
}
cv::circle(image, q.center, 5, cv::Scalar(0, 0, 255), 2, 8);
}
void drawPolarLines(cv::Mat & image, std::vector<cv::Vec2f> & lines)
{
float rho, theta;
double a, b, x0, y0;
cv::Vec4f l;
for (size_t i = 0; i < lines.size(); ++i) {
rho = lines[i][0], theta = lines[i][1];
a = cos(theta); b = sin(theta);
x0 = a*rho; y0 = b*rho;
l[0] = cvRound(x0 + 1000*(-b));
l[1] = cvRound(y0 + 1000*(a));
l[2] = cvRound(x0 - 1000*(-b));
l[3] = cvRound(y0 - 1000*(a));
line(image, cv::Point(l[0], l[1]), cv::Point(l[2], l[3]), cv::Scalar(0, 100, 100), 3, CV_AA);
}
}
std::vector<Quadrilateral> findQuadrilateralByHough(cv::Mat & src)
{
cv::Mat blur, mask;
/// Blur
cv::medianBlur(src, blur, 9);
if (COMMONCV_DEBUG)
imshow("blur", blur);
/// Edge detection
cv::Canny(blur, mask, 60, 3*60, 3);
if (COMMONCV_DEBUG)
imshow("canny", mask);
std::vector<Quadrilateral> rectangles;
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
// cv::findContours(mask, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
// cv::findContours(mask, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
cv::findContours(mask, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
// cv::findContours(mask, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
for(int i = 0; i < contours.size(); ++i) {
if (cv::contourArea(contours[i]) > MIN_AREA) {
cv::Mat drawing = cv::Mat::zeros(mask.size(), CV_8UC1);
std::vector<cv::Vec2f> lines;
std::vector<cv::Vec2f> uniLin;
cv::drawContours(drawing, contours, i, cv::Scalar(255), 1, CV_AA, hierarchy, 0, cv::Point());
cv::HoughLines(drawing, lines, 1, CV_PI/180, 200, 0, 0);
if (COMMONCV_DEBUG) {
cv::imshow("drawing" + std::to_string(i), drawing);
}
for(size_t ln = 0; ln < lines.size(); ln++)
{
if (lines[ln][0] < 0) {
lines[ln][0] = abs(lines[ln][0]);
lines[ln][1] -= CV_PI;
}
if (checkUniqueOfVector(uniLin, lines[ln], cv::Vec2f(20, 0.1))) {
uniLin.push_back(lines[ln]);
}
}
if (COMMONCV_DEBUG) {
std::cout << "Unique lines of contours: " << uniLin.size() << std::endl;
drawPolarLines(src, uniLin);
}
if (uniLin.size() != 4) continue;
// Find Intersections
std::vector<cv::Point> points;
cv::Point pt;
int ln1 = 0, ln1_prev = 0;;
int ln2 = 0, ln2_check = 0;
double det = 0;
bool fullCircle = false;
while(points.size() != 4) {
det = 0;
ln1_prev = ln1;
ln1 = ln2;
ln2 = 0;
--ln2;
do {
++ln2;
if (ln2 == 4) ln2 = 0;
if (ln2 == ln1 || ln2 == ln1_prev) {
if (ln2 == 3) ln2 = 0;
else ++ln2;
}
if (ln2 == ln1 || ln2 == ln1_prev) {
if (ln2 == 3) ln2 = 0;
else ++ln2;
}
if (ln2_check != 0 && ln2 == ln2_check) {
fullCircle = true;
break;
}
if (ln2_check == 0) ln2_check == ln2;
det = sin(uniLin[ln2][1] - uniLin[ln1][1]);
} while (cv::abs(det) < 0.3);
if (fullCircle) {
std::cout << "Error! Ln2 if full circle!" << std::endl;
break;
}
pt.x = uniLin[ln1][0]*sin(uniLin[ln2][1])/det - uniLin[ln2][0]*sin(uniLin[ln1][1])/det;
pt.y = -uniLin[ln1][0]*cos(uniLin[ln2][1])/det + uniLin[ln2][0]*cos(uniLin[ln1][1])/det;
points.push_back(pt);
}
rectangles.push_back(Quadrilateral(points[0], points[1], points[2], points[3]));
}
}
std::vector<Quadrilateral> uniRect;
for (size_t i = 0; i < rectangles.size(); ++i) {
if(checkUniqueOfVector(uniRect, rectangles[i], cv::Vec2f(10, 10))) {
uniRect.push_back(rectangles[i]);
std::cout << "rect " << i << ": \t[" << uniRect[i].p[0] << ", " << uniRect[i].p[1] << ", " << uniRect[i].p[2] << ", " << uniRect[i].p[3] << "]" << std::endl;
std::cout << "center " << i << ": \t" << uniRect[i].center << std::endl;
}
}
return uniRect;
}
void findCirclesByCanny(cv::Mat & src, std::vector<float> & circlesRadii, std::vector<cv::Point> & circlesCenters)
{
cv::Mat dst, gray, edges;
std::vector<std::vector<cv::Point>> contours;
std::vector<std::vector<cv::Point>> contoursPoly;
std::vector<cv::Vec4i> hierarchy;
float radius;
cv::Point2f center;
int ratio = 3;
bool valid = false;
int cannyKernel = 3;
// 1. Bluring
cv::GaussianBlur(src, dst, cv::Size(BLUR_KERNEL, BLUR_KERNEL), 0, 0);
cv::cvtColor(dst, gray, CV_BGR2GRAY);
// Optimal - 80
cv::Canny(gray, edges, 80, 80*ratio, cannyKernel);
/// Find contours
cv::findContours(edges, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
contoursPoly.resize(contours.size());
cv::Scalar color = cv::Scalar(0, 0, 255);
/// Draw contours
for (int i = 0; i < contours.size(); ++i) {
cv::approxPolyDP(cv::Mat(contours[i]), contoursPoly[i], 0.1, true);
// cout << contoursPoly[i].size() << endl;
if ((contoursPoly[i].size() > 30) & (contoursPoly[i].size() < 50) & (contourArea(contours[i]) > 30)) {
cv::drawContours(src, contoursPoly, i, color, 2, 8, hierarchy, 0, cv::Point());
cv::minEnclosingCircle((cv::Mat)contoursPoly[i], center, radius);
if (circlesCenters.empty()) {
std::cout << "Circle: [Center - " << center << "]\t [Radius - " << radius << "]" << std::endl;
circlesCenters.push_back(center);
circlesRadii.push_back(radius);
}
else {
valid = true;
for (int j = 0; j < circlesCenters.size(); ++j) {
valid = valid && (abs(center.x - circlesCenters[j].x) > 2 || abs(center.y - circlesCenters[j].y) > 2);
}
if (valid) {
std::cout << "Circle: [Center - " << center << "]\t [Radius - " << radius << "]" << std::endl;
circlesCenters.push_back(center);
circlesRadii.push_back(radius);
}
}
}
}
}
| 38.078341 | 169 | 0.497519 | [
"vector"
] |
6fe8a44c963390c20b4f531486ac1ef7f54a3117 | 12,134 | cpp | C++ | Editor/UI/AGETransformPanel.cpp | alexshpunt/art_gear | 64a2d001570812690fc8845f694f2bfe1d96c3a2 | [
"MIT"
] | null | null | null | Editor/UI/AGETransformPanel.cpp | alexshpunt/art_gear | 64a2d001570812690fc8845f694f2bfe1d96c3a2 | [
"MIT"
] | null | null | null | Editor/UI/AGETransformPanel.cpp | alexshpunt/art_gear | 64a2d001570812690fc8845f694f2bfe1d96c3a2 | [
"MIT"
] | null | null | null | #include "AGETransformPanel.h"
#include "Managers/AGLogger.h"
#include "Managers/AGEStateManager.h"
#include "Math/AGMath.h"
AGETransformPanel::AGETransformPanel()
{
m_ui.setupUi( this );
this->setFixedWidth( 349 );
m_notifyer = new AGETransformPanelNotifyer( this );
m_nameEdit = new QLineEdit;
m_panelName = new QLabel( "Transform" );
m_nameLabel = new QLabel( "Name: " );
m_layout = new QHBoxLayout;
m_mainLayout = new QVBoxLayout;
m_visiableCheckBox = new QCheckBox;
m_visiableLabel = new QLabel( "Visible: " );
m_layout->addWidget( m_nameLabel );
m_layout->addWidget( m_nameEdit );
m_layout->addWidget( m_visiableLabel );
m_layout->addWidget( m_visiableCheckBox );
m_mainLayout->addLayout( m_layout );
m_mainLayout->addWidget( m_ui.verticalLayoutWidget );
this->setLayout( m_mainLayout );
m_mainLayout->setSizeConstraint(QLayout::SetMinimumSize);
setStyleSheet( "color: white" );
m_gameObject = nullptr;
m_nameEdit->setText( "-" );
m_visiableCheckBox->setCheckState( Qt::Unchecked );
m_ui.spinBoxPosX->setEnabled(false);
m_ui.spinBoxPosY->setEnabled(false);
m_ui.spinBoxPosZ->setEnabled(false);
m_ui.spinBoxRotX->setEnabled(false);
m_ui.spinBoxRotY->setEnabled(false);
m_ui.spinBoxRotZ->setEnabled(false);
m_ui.spinBoxScaleX->setEnabled(false);
m_ui.spinBoxScaleY->setEnabled(false);
m_ui.spinBoxScaleZ->setEnabled(false);
connect( m_nameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( nameChanged( const QString& ) ) );
connect( m_ui.spinBoxPosX, SIGNAL( valueChanged( double ) ), this, SLOT( spinBoxPosXChanged( double ) ) );
connect( m_ui.spinBoxPosY, SIGNAL( valueChanged( double ) ), this, SLOT( spinBoxPosYChanged( double ) ) );
connect( m_ui.spinBoxPosZ, SIGNAL( valueChanged( double ) ), this, SLOT( spinBoxPosZChanged( double ) ) );
connect( m_ui.spinBoxRotX, SIGNAL( valueChanged( double ) ), this, SLOT( spinBoxRotXChanged( double ) ) );
connect( m_ui.spinBoxRotY, SIGNAL( valueChanged( double ) ), this, SLOT( spinBoxRotYChanged( double ) ) );
connect( m_ui.spinBoxRotZ, SIGNAL( valueChanged( double ) ), this, SLOT( spinBoxRotZChanged( double ) ) );
connect( m_ui.spinBoxScaleX, SIGNAL( valueChanged( double ) ), this, SLOT( spinBoxScaleXChanged( double ) ) );
connect( m_ui.spinBoxScaleY, SIGNAL( valueChanged( double ) ), this, SLOT( spinBoxScaleYChanged( double ) ) );
connect( m_ui.spinBoxScaleZ, SIGNAL( valueChanged( double ) ), this, SLOT( spinBoxScaleZChanged( double ) ) );
m_changeGameObject = false;
}
AGETransformPanel::~AGETransformPanel()
{
delete m_notifyer;
}
void AGETransformPanel::setGameObject(AGGameObject* gameObject)
{
if( m_gameObject == gameObject )
return;
if( m_gameObject )
{
m_gameObject->unregisterNotifyFunctor( m_notifyer );
}
m_gameObject = gameObject;
if( !gameObject )
{
m_nameEdit->setText( "-" );
m_visiableCheckBox->setCheckState( Qt::Unchecked );
m_ui.spinBoxPosX->setValue( 0.0 );
m_ui.spinBoxPosY->setValue( 0.0 );
m_ui.spinBoxPosZ->setValue( 0.0 );
m_ui.spinBoxRotX->setValue( 0.0 );
m_ui.spinBoxRotY->setValue( 0.0 );
m_ui.spinBoxRotZ->setValue( 0.0 );
m_ui.spinBoxScaleX->setValue( 0.0 );
m_ui.spinBoxScaleY->setValue( 0.0 );
m_ui.spinBoxScaleZ->setValue( 0.0 );
m_ui.spinBoxPosX->setEnabled(false);
m_ui.spinBoxPosY->setEnabled(false);
m_ui.spinBoxPosZ->setEnabled(false);
m_ui.spinBoxRotX->setEnabled(false);
m_ui.spinBoxRotY->setEnabled(false);
m_ui.spinBoxRotZ->setEnabled(false);
m_ui.spinBoxScaleX->setEnabled(false);
m_ui.spinBoxScaleY->setEnabled(false);
m_ui.spinBoxScaleZ->setEnabled(false);
return;
}
if( !m_ui.spinBoxPosX->isEnabled() )
{
m_ui.spinBoxPosX->setEnabled(true);
m_ui.spinBoxPosY->setEnabled(true);
m_ui.spinBoxPosZ->setEnabled(true);
m_ui.spinBoxRotX->setEnabled(true);
m_ui.spinBoxRotY->setEnabled(true);
m_ui.spinBoxRotZ->setEnabled(true);
m_ui.spinBoxScaleX->setEnabled(true);
m_ui.spinBoxScaleY->setEnabled(true);
m_ui.spinBoxScaleZ->setEnabled(true);
}
m_gameObject->registerNotifyFunctor( m_notifyer );
m_nameEdit->setText( &m_gameObject->getName()[0] );
m_visiableCheckBox->setCheckState( Qt::Checked );
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
AGVec3 pos = coordSystem == AGEStateManager::World ? m_gameObject->getWorldPos() : m_gameObject->getLocalPos();
AGVec3 rot = coordSystem == AGEStateManager::World ? m_gameObject->getWorldRot() : m_gameObject->getLocalRot();
AGVec3 scale = coordSystem == AGEStateManager::World ? m_gameObject->getWorldScale() : m_gameObject->getLocalScale();
m_ui.spinBoxPosX->setValue( pos.x );
m_ui.spinBoxPosY->setValue( pos.y );
m_ui.spinBoxPosZ->setValue( pos.z );
m_ui.spinBoxRotX->setValue( AGMath::toDegrees( rot.x ) );
m_ui.spinBoxRotY->setValue( AGMath::toDegrees( rot.y ) );
m_ui.spinBoxRotZ->setValue( AGMath::toDegrees( rot.z ) );
m_ui.spinBoxScaleX->setValue( scale.x );
m_ui.spinBoxScaleY->setValue( scale.y );
m_ui.spinBoxScaleZ->setValue( scale.z );
}
void AGETransformPanel::nameChanged(const QString& text)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
m_gameObject->setName( text.toLocal8Bit().constData() );
}
void AGETransformPanel::visiableChanged(int state)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
}
void AGETransformPanel::spinBoxPosXChanged(double value)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
switch( coordSystem )
{
case AGEStateManager::Local:
m_gameObject->setLocalXPos( value );
break;
case AGEStateManager::World:
m_gameObject->setWorldXPos( value );
break;
}
}
void AGETransformPanel::spinBoxPosYChanged(double value)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
switch( coordSystem )
{
case AGEStateManager::Local:
m_gameObject->setLocalYPos( value );
break;
case AGEStateManager::World:
m_gameObject->setWorldYPos( value );
break;
}
}
void AGETransformPanel::spinBoxPosZChanged(double value)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
switch( coordSystem )
{
case AGEStateManager::Local:
m_gameObject->setLocalZPos( value );
break;
case AGEStateManager::World:
m_gameObject->setWorldZPos( value );
break;
}
}
void AGETransformPanel::spinBoxRotXChanged(double value)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
switch( coordSystem )
{
case AGEStateManager::Local:
m_gameObject->setLocalXRot( AGMath::toRadians( value ) );
break;
case AGEStateManager::World:
m_gameObject->setWorldXRot( AGMath::toRadians( value ) );
break;
}
}
void AGETransformPanel::spinBoxRotYChanged(double value)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
switch( coordSystem )
{
case AGEStateManager::Local:
m_gameObject->setLocalYRot( AGMath::toRadians( value ) );
break;
case AGEStateManager::World:
m_gameObject->setWorldYRot( AGMath::toRadians( value ) );
break;
}
}
void AGETransformPanel::spinBoxRotZChanged(double value)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
switch( coordSystem )
{
case AGEStateManager::Local:
m_gameObject->setLocalZRot( AGMath::toRadians( value ) );
break;
case AGEStateManager::World:
m_gameObject->setWorldZRot( AGMath::toRadians( value ) );
break;
}
}
void AGETransformPanel::spinBoxScaleXChanged(double value)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
switch( coordSystem )
{
case AGEStateManager::Local:
m_gameObject->setLocalXScale( value );
break;
case AGEStateManager::World:
m_gameObject->setWorldXScale( value );
break;
}
}
void AGETransformPanel::spinBoxScaleYChanged(double value)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
switch( coordSystem )
{
case AGEStateManager::Local:
m_gameObject->setLocalYScale( value );
break;
case AGEStateManager::World:
m_gameObject->setWorldYScale( value );
break;
}
}
void AGETransformPanel::spinBoxScaleZChanged(double value)
{
if( !m_gameObject )
return;
if( !m_changeGameObject )
{
m_changeGameObject = true;
return;
}
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
switch( coordSystem )
{
case AGEStateManager::Local:
m_gameObject->setLocalZScale( value );
break;
case AGEStateManager::World:
m_gameObject->setWorldZScale( value );
break;
}
}
char* AGETransformPanel::getName() const
{
return "Transform";
}
AGETransformPanelNotifyer::AGETransformPanelNotifyer( AGETransformPanel* panel )
{
m_panel = panel;
}
void AGETransformPanelNotifyer::operator()( AGGameObject::Change change )
{
if( !m_panel->m_gameObject )
return;
AGVec3 vec;
AGEStateManager::CoordSystem coordSystem = AGEStateManager::getInstance().getCoordSystem();
if( coordSystem == AGEStateManager::World )
{
switch( change )
{
case AGGameObject::WorldPos:
vec = m_panel->m_gameObject->getWorldPos();
m_panel->m_ui.spinBoxPosX->setValue( vec.x );
m_panel->m_ui.spinBoxPosY->setValue( vec.y );
m_panel->m_ui.spinBoxPosZ->setValue( vec.z );
break;
case AGGameObject::WorldRot:
vec = m_panel->m_gameObject->getWorldRot();
m_panel->m_ui.spinBoxRotX->setValue( AGMath::toDegrees( vec.x ) );
m_panel->m_ui.spinBoxRotY->setValue( AGMath::toDegrees( vec.y ) );
m_panel->m_ui.spinBoxRotZ->setValue( AGMath::toDegrees( vec.z ) );
break;
case AGGameObject::WorldScale:
vec = m_panel->m_gameObject->getWorldScale();
m_panel->m_ui.spinBoxScaleX->setValue( vec.x );
m_panel->m_ui.spinBoxScaleY->setValue( vec.y );
m_panel->m_ui.spinBoxScaleZ->setValue( vec.z );
break;
}
}
else if( coordSystem == AGEStateManager::Local )
{
switch( change )
{
case AGGameObject::LocalPos:
vec = m_panel->m_gameObject->getLocalPos();
m_panel->m_ui.spinBoxPosX->setValue( vec.x );
m_panel->m_ui.spinBoxPosY->setValue( vec.y );
m_panel->m_ui.spinBoxPosZ->setValue( vec.z );
break;
case AGGameObject::LocalRot:
vec = m_panel->m_gameObject->getLocalRot();
m_panel->m_ui.spinBoxRotX->setValue( AGMath::toDegrees( vec.x ) );
m_panel->m_ui.spinBoxRotY->setValue( AGMath::toDegrees( vec.y ) );
m_panel->m_ui.spinBoxRotZ->setValue( AGMath::toDegrees( vec.z ) );
break;
case AGGameObject::LocalScale:
vec = m_panel->m_gameObject->getLocalScale();
m_panel->m_ui.spinBoxScaleX->setValue( vec.x );
m_panel->m_ui.spinBoxScaleY->setValue( vec.y );
m_panel->m_ui.spinBoxScaleZ->setValue( vec.z );
break;
}
}
switch( change )
{
case AGGameObject::Name:
m_panel->m_nameEdit->setText( &(m_panel->m_gameObject->getName())[0] ); //std::string -> char*
break;
case AGGameObject::Visiable:
break;
}
m_panel->m_changeGameObject = true;
}
| 25.707627 | 119 | 0.716499 | [
"transform"
] |
6febc2b22b6f6e30fab852d0c163c3eccb1dcb13 | 46,496 | cpp | C++ | Sankore-3.1/src/core/UBSettings.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/core/UBSettings.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/core/UBSettings.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA)
*
* This file is part of Open-Sankoré.
*
* Open-Sankoré 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 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré 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 Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/
#include "UBSettings.h"
#include <QtGui>
#include "frameworks/UBPlatformUtils.h"
#include "frameworks/UBFileSystemUtils.h"
#include "frameworks/UBCryptoUtils.h"
#include "UB.h"
#include "UBSetting.h"
#include "tools/UBToolsManager.h"
#include "core/memcheck.h"
QPointer<UBSettings> UBSettings::sSingleton = 0;
int UBSettings::pointerDiameter = 40;
int UBSettings::crossSize = 32;
int UBSettings::colorPaletteSize = 4;
int UBSettings::objectFrameWidth = 20;
int UBSettings::boardMargin = 10;
QString UBSettings::documentGroupName = QString("Subject");
QString UBSettings::documentName = QString("Lesson");
QString UBSettings::documentSize = QString("Size");
QString UBSettings::documentIdentifer = QString("ID");
QString UBSettings::documentVersion = QString("Version");
QString UBSettings::documentUpdatedAt = QString("UpdatedAt");
QString UBSettings::sessionTitle = QString("sessionTitle");
QString UBSettings::sessionAuthors = QString("sessionAuthors");
QString UBSettings::sessionObjectives = QString("sessionObjectives");
QString UBSettings::sessionKeywords = QString("sessionKeywords");
QString UBSettings::sessionGradeLevel = QString("sessionGradeLevel");
QString UBSettings::sessionSubjects = QString("sessionSubjects");
QString UBSettings::sessionType = QString("sessionType");
QString UBSettings::sessionLicence = QString("sessionLicence");
QString UBSettings::documentDate = QString("date");
// Issue 1684 - ALTI/AOU - 20131210
QString UBSettings::documentDefaultBackgroundImage = QString("defaultBackgroundImage");
QString UBSettings::documentDefaultBackgroundImageDisposition = QString("defaultBackgroundImageDisposition");
// Fin Issue 1684 - ALTI/AOU - 20131210
//Issue N/C - NNE - 20140526
QString UBSettings::documentTagVersion = QString("versionCreation");
QString UBSettings::trashedDocumentGroupNamePrefix = QString("_Trash:");
QString UBSettings::uniboardDocumentNamespaceUri = "http://uniboard.mnemis.com/document";
QString UBSettings::uniboardApplicationNamespaceUri = "http://uniboard.mnemis.com/application";
const int UBSettings::sDefaultFontPixelSize = 36;
const char *UBSettings::sDefaultFontFamily = "Arial";
QString UBSettings::currentFileVersion = "4.7.0";
QColor UBSettings::crossDarkBackground = QColor(44, 44, 44, 200);
QColor UBSettings::crossLightBackground = QColor(165, 225, 255);
QBrush UBSettings::eraserBrushLightBackground = QBrush(QColor(255, 255, 255, 30));
QBrush UBSettings::eraserBrushDarkBackground = QBrush(QColor(127, 127, 127, 30));
QPen UBSettings::eraserPenDarkBackground = QPen(QColor(255, 255, 255, 63));
QPen UBSettings::eraserPenLightBackground = QPen(QColor(0, 0, 0, 63));
QColor UBSettings::documentSizeMarkColorDarkBackground = QColor(44, 44, 44, 200);
QColor UBSettings::documentSizeMarkColorLightBackground = QColor(241, 241, 241);
QColor UBSettings::paletteColor = QColor(127, 127, 127, 127);
QColor UBSettings::opaquePaletteColor = QColor(66, 66, 66, 200);
QColor UBSettings::documentViewLightColor = QColor(241, 241, 241);
QPointer<QSettings> UBSettings::sAppSettings = 0;
const int UBSettings::maxThumbnailWidth = 400;
const int UBSettings::defaultThumbnailWidth = 150;
const int UBSettings::defaultLibraryIconSize = 80;
const int UBSettings::defaultGipWidth = 150;
const int UBSettings::defaultSoundWidth = 50;
const int UBSettings::defaultImageWidth = 150;
const int UBSettings::defaultShapeWidth = 50;
const int UBSettings::defaultWidgetIconWidth = 110;
const int UBSettings::defaultVideoWidth = 80;
const int UBSettings::thumbnailSpacing = 20;
const int UBSettings::longClickInterval = 1200;
const qreal UBSettings::minScreenRatio = 1.33; // 800/600 or 1024/768
QStringList UBSettings::bitmapFileExtensions;
QStringList UBSettings::vectoFileExtensions;
QStringList UBSettings::imageFileExtensions;
QStringList UBSettings::widgetFileExtensions;
QStringList UBSettings::interactiveContentFileExtensions;
QColor UBSettings::treeViewBackgroundColor = QColor(209, 215, 226); //in synch with css tree view background
int UBSettings::objectInControlViewMargin = 100;
QString UBSettings::appPingMessage = "__uniboard_ping";
UBSettings* UBSettings::settings()
{
if (!sSingleton)
sSingleton = new UBSettings(qApp);
return sSingleton;
}
void UBSettings::destroy()
{
if (sSingleton)
delete sSingleton;
sSingleton = NULL;
}
QSettings* UBSettings::getAppSettings()
{
if (!UBSettings::sAppSettings)
{
QString tmpSettings = QDir::tempPath() + "/Uniboard.config";
QString appSettings = UBPlatformUtils::applicationResourcesDirectory() + "/etc/Uniboard.config";
// tmpSettings exists when upgrading Uniboard on Mac (see UBPlatformUtils_mac.mm updater:willInstallUpdate:)
if (QFile::exists(tmpSettings))
{
QFile::rename(tmpSettings, appSettings);
}
UBSettings::sAppSettings = new QSettings(appSettings, QSettings::IniFormat, 0);
}
return UBSettings::sAppSettings;
}
UBSettings::UBSettings(QObject *parent)
: QObject(parent)
{
InitKeyboardPaletteKeyBtnSizes();
mAppSettings = UBSettings::getAppSettings();
QString userSettingsFile = UBSettings::userDataDirectory() + "/UniboardUser.config";
mUserSettings = new QSettings(userSettingsFile, QSettings::IniFormat, parent);
appPreferredLanguage = new UBSetting(this,"App","PreferredLanguage", "");
// init();
}
UBSettings::~UBSettings()
{
delete mAppSettings;
if(supportedKeyboardSizes)
delete supportedKeyboardSizes;
}
void UBSettings::InitKeyboardPaletteKeyBtnSizes()
{
supportedKeyboardSizes = new QStringList();
supportedKeyboardSizes->append("29x29");
supportedKeyboardSizes->append("41x41");
}
void UBSettings::ValidateKeyboardPaletteKeyBtnSize()
{
// if boardKeyboardPaletteKeyBtnSize is not initialized, or supportedKeyboardSizes not initialized or empty
if( !boardKeyboardPaletteKeyBtnSize ||
!supportedKeyboardSizes ||
supportedKeyboardSizes->size() == 0 ) return;
// get original size value
QString origValue = boardKeyboardPaletteKeyBtnSize->get().toString();
// parse available size values, for make sure original value is valid
for(int i = 0; i < supportedKeyboardSizes->size(); i++)
{
int compareCode = QString::compare(origValue, supportedKeyboardSizes->at(i));
if(compareCode == 0) return;
}
// if original value is invalid, than set it value to first value from avaliable list
boardKeyboardPaletteKeyBtnSize->set(supportedKeyboardSizes->at(0));
}
void UBSettings::init()
{
productWebUrl = new UBSetting(this, "App", "ProductWebAddress", "http://www.sankore.org");
softwareHomeUrl = productWebUrl->get().toString();
// QRect mainScreenGeometry = UBApplication::desktop()->screenGeometry(UBApplication::desktop()->primaryScreen());
// documentSizes.insert(DocumentSizeRatio::Ratio4_3, QSize(mainScreenGeometry.height() * 4.f / 3.f, mainScreenGeometry.height())); // 1.33
// documentSizes.insert(DocumentSizeRatio::Ratio16_10, QSize((mainScreenGeometry.height() * 16.f / 10.f), mainScreenGeometry.height())); // 1.6
// documentSizes.insert(DocumentSizeRatio::Ratio16_9, QSize((mainScreenGeometry.height() * 16.f / 9.f), mainScreenGeometry.height())); // 1.77
documentSizes.insert(DocumentSizeRatio::Ratio4_3, QSize(1280, 960)); // 1.33
documentSizes.insert(DocumentSizeRatio::Ratio16_10, QSize((960 / 10 * 16), 960)); // 1.60
documentSizes.insert(DocumentSizeRatio::Ratio16_9, QSize((960 / 9 * 16), 960)); // 1.77
appToolBarPositionedAtTop = new UBSetting(this, "App", "ToolBarPositionedAtTop", true);
appToolBarDisplayText = new UBSetting(this, "App", "ToolBarDisplayText", true);
appEnableAutomaticSoftwareUpdates = new UBSetting(this, "App", "EnableAutomaticSoftwareUpdates", true);
appEnableSoftwareUpdates = new UBSetting(this, "App", "EnableSoftwareUpdates", true);
appToolBarOrientationVertical = new UBSetting(this, "App", "ToolBarOrientationVertical", false);
appDrawingPaletteOrientationHorizontal = new UBSetting(this, "App", "DrawingPaletteOrientationHorizontal", false);
rightLibPaletteBoardModeWidth = new UBSetting(this, "Board", "RightLibPaletteBoardModeWidth", 270);
rightLibPaletteBoardModeIsCollapsed = new UBSetting(this,"Board", "RightLibPaletteBoardModeIsCollapsed",false);
rightLibPaletteDesktopModeWidth = new UBSetting(this, "Board", "RightLibPaletteDesktopModeWidth", 270);
rightLibPaletteDesktopModeIsCollapsed = new UBSetting(this,"Board", "RightLibPaletteDesktopModeIsCollapsed",false);
rightLibPaletteWebModeWidth = new UBSetting(this, "Board", "RightLibPaletteWebModeWidth", 270);
rightLibPaletteWebModeIsCollapsed = new UBSetting(this,"Board", "RightLibPaletteWebModeIsCollapsed",false);
leftLibPaletteBoardModeWidth = new UBSetting(this, "Board", "LeftLibPaletteBoardModeWidth",270);
leftLibPaletteBoardModeIsCollapsed = new UBSetting(this,"Board","LeftLibPaletteBoardModeIsCollapsed",false);
leftLibPaletteDesktopModeWidth = new UBSetting(this, "Board", "LeftLibPaletteDesktopModeWidth",270);
leftLibPaletteDesktopModeIsCollapsed = new UBSetting(this,"Board","LeftLibPaletteDesktopModeIsCollapsed",false);
userCrossDarkBackground = new UBColorListSetting(this, "Board", "crossDarkBackgroundColor", "127 127 127", 0.75);
userCrossLightBackground = new UBColorListSetting(this, "Board", "crossLightBackgroundColor", "83 173 173", 1);
QColor bgCrossColor;
QStringList colors;
colors = userCrossDarkBackground->get().toString().split(" ", QString::SkipEmptyParts);
if (3 == colors.count())
crossDarkBackground = QColor(colors[0].toInt(),colors[1].toInt(),colors[2].toInt());
if (4 == colors.count())
crossDarkBackground = QColor(colors[0].toInt(),colors[1].toInt(),colors[2].toInt(), colors[3].toInt());
colors = userCrossLightBackground->get().toString().split(" ", QString::SkipEmptyParts);
if (3 == colors.count())
crossLightBackground = QColor(colors[0].toInt(),colors[1].toInt(),colors[2].toInt());
if (4 == colors.count())
crossLightBackground = QColor(colors[0].toInt(),colors[1].toInt(),colors[2].toInt(), colors[3].toInt());
appIsInSoftwareUpdateProcess = new UBSetting(this, "App", "IsInSoftwareUpdateProcess", false);
appLastSessionDocumentUUID = new UBSetting(this, "App", "LastSessionDocumentUUID", "");
appLastSessionPageIndex = new UBSetting(this, "App", "LastSessionPageIndex", 0);
appUseMultiscreen = new UBSetting(this, "App", "UseMusliscreenMode", true);
appStartupHintsEnabled = new UBSetting(this,"App","EnableStartupHints",true);
appStartMode = new UBSetting(this, "App", "StartMode", "");
featureSliderPosition = new UBSetting(this, "Board", "FeatureSliderPosition", 40);
boardPenFineWidth = new UBSetting(this, "Board", "PenFineWidth", 1.5);
boardPenMediumWidth = new UBSetting(this, "Board", "PenMediumWidth", 3.0);
boardPenStrongWidth = new UBSetting(this, "Board", "PenStrongWidth", 8.0);
boardMarkerFineWidth = new UBSetting(this, "Board", "MarkerFineWidth", 12.0);
boardMarkerMediumWidth = new UBSetting(this, "Board", "MarkerMediumWidth", 24.0);
boardMarkerStrongWidth = new UBSetting(this, "Board", "MarkerStrongWidth", 48.0);
boardPenPressureSensitive = new UBSetting(this, "Board", "PenPressureSensitive", true);
boardMarkerPressureSensitive = new UBSetting(this, "Board", "MarkerPressureSensitive", false);
boardUseHighResTabletEvent = new UBSetting(this, "Board", "UseHighResTabletEvent", true);
boardKeyboardPaletteKeyBtnSize = new UBSetting(this, "Board", "KeyboardPaletteKeyBtnSize", "16x16");
cacheKeepAspectRatio = new UBSetting(this, "Cache", "KeepAspectRatio", true);
cacheMode = new UBSetting(this, "Cache", "CasheMode", 0);
casheLastHoleSize = new UBSetting(this, "Cache", "LastHoleSize", QSize(20,20));
cacheColor = new UBColorListSetting(this, "Cache", "Color", "0 0 0", 0.75);
ValidateKeyboardPaletteKeyBtnSize();
// Issue 1684 - CFA - 20131127 : default page size = screen size no ?
pageSize = new UBSetting(this, "Board", "DefaultPageSize", documentSizes.value(DocumentSizeRatio::Ratio4_3));
//pageSize = new UBSetting(this, "Board", "DefaultPageSize", mainScreenGeometry.size());
pageDpi = new UBSetting(this, "Board", "pageDpi", 0);
QStringList penLightBackgroundColors;
penLightBackgroundColors << "#000000" << "#FF0000" <<"#004080" << "#008000" << "#C87400" << "#800040" << "#008080" << "#5F2D0A" << "#FFFFFF";
boardPenLightBackgroundColors = new UBColorListSetting(this, "Board", "PenLightBackgroundColors", penLightBackgroundColors, 1.0);
QStringList penDarkBackgroundColors;
penDarkBackgroundColors << "#FFFFFF" << "#FF3400" <<"#66C0FF" << "#81FF5C" << "#FFFF00" << "#B68360" << "#FF497E" << "#8D69FF" << "#000000";
boardPenDarkBackgroundColors = new UBColorListSetting(this, "Board", "PenDarkBackgroundColors", penDarkBackgroundColors, 1.0);
boardMarkerAlpha = new UBSetting(this, "Board", "MarkerAlpha", 0.5);
QStringList markerLightBackgroundColors;
markerLightBackgroundColors << "#E3FF00" << "#FF0000" <<"#004080" << "#008000" << "#C87400" << "#800040" << "#008080" << "#000000";
boardMarkerLightBackgroundColors = new UBColorListSetting(this, "Board", "MarkerLightBackgroundColors", markerLightBackgroundColors, boardMarkerAlpha->get().toDouble());
QStringList markerDarkBackgroundColors;
markerDarkBackgroundColors << "#FFFF00" << "#FF4400" <<"#66C0FF" << "#81FF5C" << "#B68360" << "#FF497E" << "#8D69FF" << "#FFFFFF";
boardMarkerDarkBackgroundColors = new UBColorListSetting(this, "Board", "MarkerDarkBackgroundColors", markerDarkBackgroundColors, boardMarkerAlpha->get().toDouble());
QStringList penLightBackgroundSelectedColors;
QStringList penDarkBackgroundSelectedColors;
QStringList markerLightBackgroundSelectedColors;
QStringList markerDarkBackgroundSelectedColors;
for (int i = 0; i < colorPaletteSize; i++)
{
penLightBackgroundSelectedColors << penLightBackgroundColors[i];
penDarkBackgroundSelectedColors << penDarkBackgroundColors[i];
markerLightBackgroundSelectedColors << markerLightBackgroundColors[i];
markerDarkBackgroundSelectedColors << markerDarkBackgroundColors[i];
}
boardPenLightBackgroundSelectedColors = new UBColorListSetting(this, "Board", "PenLightBackgroundSelectedColors", penLightBackgroundSelectedColors);
boardPenDarkBackgroundSelectedColors = new UBColorListSetting(this, "Board", "PenDarkBackgroundSelectedColors", penDarkBackgroundSelectedColors);
boardMarkerLightBackgroundSelectedColors = new UBColorListSetting(this, "Board", "MarkerLightBackgroundSelectedColors", markerLightBackgroundSelectedColors, boardMarkerAlpha->get().toDouble());
boardMarkerDarkBackgroundSelectedColors = new UBColorListSetting(this, "Board", "MarkerDarkBackgroundSelectedColors", markerDarkBackgroundSelectedColors, boardMarkerAlpha->get().toDouble());
webUseExternalBrowser = new UBSetting(this, "Web", "UseExternalBrowser", false);
bool defaultShowPageImmediatelyOnMirroredScreen = true;
#if defined(Q_WS_X11)
// screen duplication is very slow on X11
defaultShowPageImmediatelyOnMirroredScreen = false;
#endif
webShowPageImmediatelyOnMirroredScreen = new UBSetting(this, "Web", "ShowPageImediatelyOnMirroredScreen", defaultShowPageImmediatelyOnMirroredScreen);
webHomePage = new UBSetting(this, "Web", "Homepage", softwareHomeUrl);
webBookmarksPage = new UBSetting(this, "Web", "BookmarksPage", "http://www.myuniboard.com");
webAddBookmarkUrl = new UBSetting(this, "Web", "AddBookmarkURL", "http://www.myuniboard.com/bookmarks/save/?url=");
webShowAddBookmarkButton = new UBSetting(this, "Web", "ShowAddBookmarkButton", false);
pageCacheSize = new UBSetting(this, "App", "PageCacheSize", 20);
bitmapFileExtensions << "jpg" << "jpeg" << "png" << "tiff" << "tif" << "bmp" << "gif";
vectoFileExtensions << "svg" << "svgz";
imageFileExtensions << bitmapFileExtensions << vectoFileExtensions;
widgetFileExtensions << "wdgt" << "wgt" << "pwgt";
interactiveContentFileExtensions << widgetFileExtensions << "swf";
boardZoomFactor = new UBSetting(this, "Board", "ZoomFactor", QVariant(1.41));
if (boardZoomFactor->get().toDouble() <= 1.)
boardZoomFactor->set(1.41);
int defaultRefreshRateInFramePerSecond = 8;
#if defined(Q_WS_X11)
// screen duplication is very slow on X11
defaultRefreshRateInFramePerSecond = 2;
#endif
mirroringRefreshRateInFps = new UBSetting(this, "Mirroring", "RefreshRateInFramePerSecond", QVariant(defaultRefreshRateInFramePerSecond));
lastImportFilePath = new UBSetting(this, "Import", "LastImportFilePath", QVariant(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)));
lastImportFolderPath = new UBSetting(this, "Import", "LastImportFolderPath", QVariant(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)));
lastExportFilePath = new UBSetting(this, "Export", "LastExportFilePath", QVariant(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)));
lastExportDirPath = new UBSetting(this, "Export", "LastExportDirPath", QVariant(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)));
lastImportToLibraryPath = new UBSetting(this, "Library", "LastImportToLibraryPath", QVariant(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)));
lastPicturePath = new UBSetting(this, "Library", "LastPicturePath", QVariant(QDesktopServices::storageLocation(QDesktopServices::PicturesLocation)));
lastWidgetPath = new UBSetting(this, "Library", "LastWidgetPath", QVariant(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)));
lastVideoPath = new UBSetting(this, "Library", "LastVideoPath", QVariant(QDesktopServices::storageLocation(QDesktopServices::MoviesLocation)));
appOnlineUserName = new UBSetting(this, "App", "OnlineUserName", "");
boardShowToolsPalette = new UBSetting(this, "Board", "ShowToolsPalette", "false");
magnifierDrawingMode = new UBSetting(this, "Board", "MagnifierDrawingMode", "0");
svgViewBoxMargin = new UBSetting(this, "SVG", "ViewBoxMargin", "50");
pdfMargin = new UBSetting(this, "PDF", "Margin", "20");
pdfPageFormat = new UBSetting(this, "PDF", "PageFormat", "A4");
pdfResolution = new UBSetting(this, "PDF", "Resolution", "300");
podcastFramesPerSecond = new UBSetting(this, "Podcast", "FramesPerSecond", 10);
podcastVideoSize = new UBSetting(this, "Podcast", "VideoSize", "Medium");
podcastAudioRecordingDevice = new UBSetting(this, "Podcast", "AudioRecordingDevice", "Default");
podcastWindowsMediaBitsPerSecond = new UBSetting(this, "Podcast", "WindowsMediaBitsPerSecond", 1700000);
podcastQuickTimeQuality = new UBSetting(this, "Podcast", "QuickTimeQuality", "High");
podcastPublishToYoutube = new UBSetting(this, "Podcast", "PublishToYouTube", false);
youTubeUserEMail = new UBSetting(this, "YouTube", "UserEMail", "");
youTubeCredentialsPersistence = new UBSetting(this,"YouTube", "CredentialsPersistence",false);
uniboardWebEMail = new UBSetting(this, "UniboardWeb", "EMail", "");
uniboardWebAuthor = new UBSetting(this, "UniboardWeb", "Author", "");
uniboardWebGoogleMapApiKey = new UBSetting(this, "UniboardWeb", "GoogleMapAPIKey", "ABQIAAAAsWU4bIbaeCLinpZ30N_erRQEk562OPinwQkG9J-ZXUNAqYhJ5RT_z2EmpfVXiUg8c41BcsD_XM6P5g");
communityUser = new UBSetting(this, "Community", "Username", "");
communityPsw = new UBSetting(this, "Community", "Password", "");
communityCredentialsPersistence = new UBSetting(this,"Community", "CredentialsPersistence",false);
QStringList uris = UBToolsManager::manager()->allToolIDs();
favoritesNativeToolUris = new UBSetting(this, "App", "FavoriteToolURIs", uris);
// removed in version 4.4.b.2
mUserSettings->remove("Podcast/RecordMicrophone");
replyWWSerialPort = new UBSetting(this, "Voting", "ReplyWWSerialPort", 3);
replyPlusConnectionURL = new UBSetting(this, "Voting", "ReplyPlusConnectionURL", "USB");
replyPlusAddressingMode = new UBSetting(this, "Voting", "ReplyPlusAddressingMode", "static");
replyPlusMaxKeypads = new UBSetting(this, "Voting", "ReplyPlusMaxKeypads", "100");
documentThumbnailWidth = new UBSetting(this, "Document", "ThumbnailWidth", UBSettings::defaultThumbnailWidth);
imageThumbnailWidth = new UBSetting(this, "Library", "ImageThumbnailWidth", UBSettings::defaultImageWidth);
videoThumbnailWidth = new UBSetting(this, "Library", "VideoThumbnailWidth", UBSettings::defaultVideoWidth);
shapeThumbnailWidth = new UBSetting(this, "Library", "ShapeThumbnailWidth", UBSettings::defaultShapeWidth);
gipThumbnailWidth = new UBSetting(this, "Library", "ImageThumbnailWidth", UBSettings::defaultGipWidth);
soundThumbnailWidth = new UBSetting(this, "Library", "SoundThumbnailWidth", UBSettings::defaultSoundWidth);;
podcastPublishToIntranet = new UBSetting(this, "IntranetPodcast", "PublishToIntranet", false);
intranetPodcastPublishingUrl = new UBSetting(this, "IntranetPodcast", "PublishingUrl", "");
intranetPodcastAuthor = new UBSetting(this, "IntranetPodcast", "Author", "");
KeyboardLocale = new UBSetting(this, "Board", "StartupKeyboardLocale", 0);
swapControlAndDisplayScreens = new UBSetting(this, "App", "SwapControlAndDisplayScreens", false);
angleTolerance = new UBSetting(this, "App", "AngleTolerance", 4);
historyLimit = new UBSetting(this, "Web", "HistoryLimit", 15);
teacherGuidePageZeroActivated = new UBSetting(this,"DockPalette","TeacherGuideActivatePageZero",true);
teacherGuideLessonPagesActivated = new UBSetting(this,"DockPalette","TeacherGuideActivateLessonPages",true);
libIconSize = new UBSetting(this, "Library", "LibIconSize", defaultLibraryIconSize);
cleanNonPersistentSettings();
}
QVariant UBSettings::value ( const QString & key, const QVariant & defaultValue) const
{
if (!sAppSettings->contains(key) && !(defaultValue == QVariant()))
{
sAppSettings->setValue(key, defaultValue);
}
return mUserSettings->value(key, sAppSettings->value(key, defaultValue));
}
void UBSettings::setValue (const QString & key, const QVariant & value)
{
mUserSettings->setValue(key, value);
}
int UBSettings::penWidthIndex()
{
return value("Board/PenLineWidthIndex", 0).toInt();
}
void UBSettings::setPenWidthIndex(int index)
{
if (index != penWidthIndex())
{
setValue("Board/PenLineWidthIndex", index);
}
}
qreal UBSettings::currentPenWidth()
{
qreal width = 0;
switch (penWidthIndex())
{
case UBWidth::Fine:
width = boardPenFineWidth->get().toDouble();
break;
case UBWidth::Medium:
width = boardPenMediumWidth->get().toDouble();
break;
case UBWidth::Strong:
width = boardPenStrongWidth->get().toDouble();
break;
default:
Q_ASSERT(false);
//failsafe
width = boardPenFineWidth->get().toDouble();
break;
}
return width;
}
int UBSettings::penColorIndex()
{
return value("Board/PenColorIndex", 0).toInt();
}
void UBSettings::setPenColorIndex(int index)
{
if (index != penColorIndex())
{
setValue("Board/PenColorIndex", index);
}
}
QColor UBSettings::currentPenColor()
{
return penColor(isDarkBackground());
}
QColor UBSettings::penColor(bool onDarkBackground)
{
QList<QColor> colors = penColors(onDarkBackground);
return colors.at(penColorIndex());
}
QList<QColor> UBSettings::penColors(bool onDarkBackground)
{
if (onDarkBackground)
{
return boardPenDarkBackgroundSelectedColors->colors();
}
else
{
return boardPenLightBackgroundSelectedColors->colors();
}
}
int UBSettings::markerWidthIndex()
{
return value("Board/MarkerLineWidthIndex", 0).toInt();
}
void UBSettings::setMarkerWidthIndex(int index)
{
if (index != markerWidthIndex())
{
setValue("Board/MarkerLineWidthIndex", index);
}
}
qreal UBSettings::currentMarkerWidth()
{
qreal width = 0;
switch (markerWidthIndex())
{
case UBWidth::Fine:
width = boardMarkerFineWidth->get().toDouble();
break;
case UBWidth::Medium:
width = boardMarkerMediumWidth->get().toDouble();
break;
case UBWidth::Strong:
width = boardMarkerStrongWidth->get().toDouble();
break;
default:
Q_ASSERT(false);
//failsafe
width = boardMarkerFineWidth->get().toDouble();
break;
}
return width;
}
int UBSettings::markerColorIndex()
{
return value("Board/MarkerColorIndex", 0).toInt();
}
void UBSettings::setMarkerColorIndex(int index)
{
if (index != markerColorIndex())
{
setValue("Board/MarkerColorIndex", index);
}
}
QColor UBSettings::currentMarkerColor()
{
return markerColor(isDarkBackground());
}
QColor UBSettings::markerColor(bool onDarkBackground)
{
QList<QColor> colors = markerColors(onDarkBackground);
return colors.at(markerColorIndex());
}
QList<QColor> UBSettings::markerColors(bool onDarkBackground)
{
if (onDarkBackground)
{
return boardMarkerDarkBackgroundSelectedColors->colors();
}
else
{
return boardMarkerLightBackgroundSelectedColors->colors();
}
}
//----------------------------------------//
// eraser
int UBSettings::eraserWidthIndex()
{
return value("Board/EraserCircleWidthIndex", 1).toInt();
}
void UBSettings::setEraserWidthIndex(int index)
{
setValue("Board/EraserCircleWidthIndex", index);
}
qreal UBSettings::eraserFineWidth()
{
return value("Board/EraserFineWidth", 16).toDouble();
}
void UBSettings::setEraserFineWidth(qreal width)
{
setValue("Board/EraserFineWidth", width);
}
qreal UBSettings::eraserMediumWidth()
{
return value("Board/EraserMediumWidth", 64).toDouble();
}
void UBSettings::setEraserMediumWidth(qreal width)
{
setValue("Board/EraserMediumWidth", width);
}
qreal UBSettings::eraserStrongWidth()
{
return value("Board/EraserStrongWidth", 128).toDouble();
}
void UBSettings::setEraserStrongWidth(qreal width)
{
setValue("Board/EraserStrongWidth", width);
}
qreal UBSettings::currentEraserWidth()
{
qreal width = 0;
switch (eraserWidthIndex())
{
case UBWidth::Fine:
width = eraserFineWidth();
break;
case UBWidth::Medium:
width = eraserMediumWidth();
break;
case UBWidth::Strong:
width = eraserStrongWidth();
break;
default:
Q_ASSERT(false);
//failsafe
width = eraserFineWidth();
break;
}
return width;
}
bool UBSettings::isDarkBackground()
{
return value("Board/DarkBackground", 0).toBool();
}
bool UBSettings::isCrossedBackground()
{
return value("Board/CrossedBackground", 0).toBool();
}
void UBSettings::setDarkBackground(bool isDarkBackground)
{
setValue("Board/DarkBackground", isDarkBackground);
emit colorContextChanged();
}
void UBSettings::setCrossedBackground(bool isCrossedBackground)
{
setValue("Board/CrossedBackground", isCrossedBackground);
}
void UBSettings::setPenPressureSensitive(bool sensitive)
{
boardPenPressureSensitive->set(sensitive);
}
void UBSettings::setMarkerPressureSensitive(bool sensitive)
{
boardMarkerPressureSensitive->set(sensitive);
}
bool UBSettings::isStylusPaletteVisible()
{
return value("Board/StylusPaletteIsVisible", true).toBool();
}
void UBSettings::setStylusPaletteVisible(bool visible)
{
setValue("Board/StylusPaletteIsVisible", visible);
}
QString UBSettings::fontFamily()
{
return value("Board/FontFamily", sDefaultFontFamily).toString();
}
void UBSettings::setFontFamily(const QString &family)
{
setValue("Board/FontFamily", family);
}
int UBSettings::fontPixelSize()
{
return value("Board/FontPixelSize", sDefaultFontPixelSize).toInt();
}
void UBSettings::setFontPixelSize(int pixelSize)
{
setValue("Board/FontPixelSize", pixelSize);
}
int UBSettings::fontPointSize()
{
return value("Board/FontPointSize", 12).toInt();
}
void UBSettings::setFontPointSize(int pointSize)
{
setValue("Board/FontPointSize", pointSize);
}
bool UBSettings::isBoldFont()
{
return value("Board/FontIsBold", false).toBool();
}
void UBSettings::setBoldFont(bool bold)
{
setValue("Board/FontIsBold", bold);
}
bool UBSettings::isItalicFont()
{
return value("Board/FontIsItalic", false).toBool();
}
void UBSettings::setItalicFont(bool italic)
{
setValue("Board/FontIsItalic", italic);
}
void UBSettings::setUnderlineFont(bool underline)
{
setValue("Board/FontIsUnderline", underline);
}
bool UBSettings::isUnderlineFont()
{
return value("Board/FontIsUnderline", false).toBool();
}
QString UBSettings::userDataDirectory()
{
static QString dataDirPath = "";
if(dataDirPath.isEmpty()){
if (sAppSettings && getAppSettings()->contains("App/DataDirectory")) {
dataDirPath = getAppSettings()->value("App/DataDirectory").toString();
dataDirPath = replaceWildcard(dataDirPath);
if(checkDirectory(dataDirPath))
return dataDirPath;
else
qCritical() << "Impossible to create datadirpath " << dataDirPath;
}
dataDirPath = UBFileSystemUtils::normalizeFilePath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
dataDirPath.replace("/Open-Sankore", "");
}
return dataDirPath;
}
QString UBSettings::userImageDirectory()
{
static QString imageDirectory = "";
if(imageDirectory.isEmpty()){
if (sAppSettings && getAppSettings()->contains("App/UserImageDirectory")) {
imageDirectory = getAppSettings()->value("App/UserImageDirectory").toString();
imageDirectory = replaceWildcard(imageDirectory);
if(checkDirectory(imageDirectory))
return imageDirectory;
else
qCritical() << "failed to create image directory " << imageDirectory;
}
imageDirectory = QDesktopServices::storageLocation(QDesktopServices::PicturesLocation) + "/Sankore";
checkDirectory(imageDirectory);
}
return imageDirectory;
}
QString UBSettings::userVideoDirectory()
{
static QString videoDirectory = "";
if(videoDirectory.isEmpty()){
if (sAppSettings && getAppSettings()->contains("App/UserVideoDirectory")) {
videoDirectory = getAppSettings()->value("App/UserVideoDirectory").toString();
videoDirectory = replaceWildcard(videoDirectory);
if(checkDirectory(videoDirectory))
return videoDirectory;
else
qCritical() << "failed to create video directory " << videoDirectory;
}
videoDirectory = QDesktopServices::storageLocation(QDesktopServices::MoviesLocation);
if(videoDirectory.isEmpty())
videoDirectory = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation) + "/" + tr("My Movies");
else
videoDirectory = videoDirectory + "/Sankore";
checkDirectory(videoDirectory);
}
return videoDirectory;
}
QString UBSettings::userAudioDirectory()
{
static QString audioDirectory = "";
if(audioDirectory.isEmpty()){
if (sAppSettings && getAppSettings()->contains("App/UserAudioDirectory")) {
audioDirectory = getAppSettings()->value("App/UserAudioDirectory").toString();
audioDirectory = replaceWildcard(audioDirectory);
if(checkDirectory(audioDirectory))
return audioDirectory;
else
qCritical() << "failed to create image directory " << audioDirectory;
}
audioDirectory = QDesktopServices::storageLocation(QDesktopServices::MusicLocation) + "/Sankore";
checkDirectory(audioDirectory);
}
return audioDirectory;
}
QString UBSettings::userPodcastRecordingDirectory()
{
static QString dirPath = "";
if(dirPath.isEmpty()){
if (sAppSettings && getAppSettings()->contains("Podcast/RecordingDirectory"))
{
dirPath = getAppSettings()->value("Podcast/RecordingDirectory").toString();
dirPath = replaceWildcard(dirPath);
if(checkDirectory(dirPath))
return dirPath;
else
qCritical() << "failed to create dir " << dirPath;
}
dirPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
checkDirectory(dirPath);
}
return dirPath;
}
QString UBSettings::userDocumentDirectory()
{
static QString documentDirectory = "";
if(documentDirectory.isEmpty()){
documentDirectory = userDataDirectory() + "/document";
checkDirectory(documentDirectory);
}
return documentDirectory;
}
QString UBSettings::userBookmarkDirectory()
{
static QString bookmarkDirectory = "";
if(bookmarkDirectory.isEmpty()){
bookmarkDirectory = userDataDirectory() + "/bookmark";
checkDirectory(bookmarkDirectory);
}
return bookmarkDirectory;
}
QString UBSettings::userFavoriteListFilePath()
{
static QString filePath = "";
if(filePath.isEmpty()){
QString dirPath = userDataDirectory() + "/libraryPalette";
checkDirectory(dirPath);
filePath = dirPath + "/favorite.dat";
}
return filePath;
}
QString UBSettings::userTrashDirPath()
{
static QString trashPath = "";
if(trashPath.isEmpty()){
trashPath = userDataDirectory() + "/libraryPalette/trash";
checkDirectory(trashPath);
}
return trashPath;
}
QString UBSettings::userGipLibraryDirectory()
{
static QString dirPath = "";
if(dirPath.isEmpty()){
dirPath = userDataDirectory() + "/library/gips";
checkDirectory(dirPath);
}
return dirPath;
}
QString UBSettings::applicationShapeLibraryDirectory()
{
QString defaultRelativePath = QString("./library/shape");
QString configPath = value("Library/ShapeDirectory", QVariant(defaultRelativePath)).toString();
if (configPath.startsWith(".")) {
return UBPlatformUtils::applicationResourcesDirectory() + configPath.right(configPath.size() - 1);
}
else {
return configPath;
}
}
QString UBSettings::applicationCustomizationDirectory()
{
QString defaultRelativePath = QString("/customizations");
return UBPlatformUtils::applicationResourcesDirectory() + defaultRelativePath;
}
QString UBSettings::applicationCustomFontDirectory()
{
QString defaultFontDirectory = "/fonts";
return applicationCustomizationDirectory() + defaultFontDirectory;
}
QString UBSettings::userSearchDirectory()
{
static QString dirPath = "";
if(dirPath.isEmpty()){
dirPath = UBPlatformUtils::applicationResourcesDirectory() + "/library/search";
checkDirectory(dirPath);
}
return dirPath;
}
QString UBSettings::applicationImageLibraryDirectory()
{
QString defaultRelativePath = QString("./library/pictures");
QString configPath = value("Library/ImageDirectory", QVariant(defaultRelativePath)).toString();
if (configPath.startsWith(".")) {
return UBPlatformUtils::applicationResourcesDirectory() + configPath.right(configPath.size() - 1);
}
else {
return configPath;
}
}
QString UBSettings::userAnimationDirectory()
{
static QString animationDirectory = "";
if(animationDirectory.isEmpty()){
animationDirectory = userDataDirectory() + "/animationUserDirectory";
checkDirectory(animationDirectory);
}
return animationDirectory;
}
QString UBSettings::userInteractiveDirectory()
{
static QString interactiveDirectory = "";
if(interactiveDirectory.isEmpty()){
if (sAppSettings && getAppSettings()->contains("App/UserInteractiveContentDirectory")) {
interactiveDirectory = getAppSettings()->value("App/UserInteractiveContentDirectory").toString();
interactiveDirectory = replaceWildcard(interactiveDirectory);
if(checkDirectory(interactiveDirectory))
return interactiveDirectory;
else
qCritical() << "failed to create directory " << interactiveDirectory;
}
interactiveDirectory = userDataDirectory() + "/interactive content";
checkDirectory(interactiveDirectory);
}
return interactiveDirectory;
}
QString UBSettings::userApplicationDirectory()
{
static QString applicationDirectory = "";
if(applicationDirectory.isEmpty()){
if (sAppSettings && getAppSettings()->contains("App/UserApplicationDirectory")) {
applicationDirectory = getAppSettings()->value("App/UserApplicationDirectory").toString();
applicationDirectory = replaceWildcard(applicationDirectory);
if(checkDirectory(applicationDirectory))
return applicationDirectory;
else
qCritical() << "failed to create directory " << applicationDirectory;
}
applicationDirectory = userDataDirectory() + "/application";
checkDirectory(applicationDirectory);
}
return applicationDirectory;
}
QString UBSettings::userWidgetPath()
{
return userInteractiveDirectory() + tr("/Web");
}
QString UBSettings::userRelativeWidgetPath()
{
QString result = userWidgetPath().replace(userInteractiveDirectory(), "");
return result.startsWith("/") ? result.right(result.count() - 1) : result;
}
QString UBSettings::applicationInteractivesDirectory()
{
QString defaultRelativePath = QString("./library/interactivities");
QString configPath = value("Library/InteractivitiesDirectory", QVariant(defaultRelativePath)).toString();
if (configPath.startsWith(".")) {
return UBPlatformUtils::applicationResourcesDirectory() + configPath.right(configPath.size() - 1);
}
else {
return configPath;
}
}
QString UBSettings::applicationApplicationsLibraryDirectory()
{
QString defaultRelativePath = QString("./library/applications");
QString configPath = value("Library/ApplicationsDirectory", QVariant(defaultRelativePath)).toString();
if (configPath.startsWith(".")) {
return UBPlatformUtils::applicationResourcesDirectory() + configPath.right(configPath.size() - 1);
}
else {
return configPath;
}
}
QString UBSettings::applicationAudiosLibraryDirectory()
{
QString defaultRelativePath = QString("./library/audios");
QString configPath = value("Library/AudiosDirectory", QVariant(defaultRelativePath)).toString();
if (configPath.startsWith(".")) {
return UBPlatformUtils::applicationResourcesDirectory() + configPath.right(configPath.size() - 1);
}
else {
return configPath;
}
}
QString UBSettings::applicationVideosLibraryDirectory()
{
QString defaultRelativePath = QString("./library/videos");
QString configPath = value("Library/VideosDirectory", QVariant(defaultRelativePath)).toString();
if (configPath.startsWith(".")) {
return UBPlatformUtils::applicationResourcesDirectory() + configPath.right(configPath.size() - 1);
}
else {
return configPath;
}
}
QString UBSettings::applicationAnimationsLibraryDirectory()
{
QString defaultRelativePath = QString("./library/animations");
QString configPath = value("Library/AnimationsDirectory", QVariant(defaultRelativePath)).toString();
if (configPath.startsWith(".")) {
return UBPlatformUtils::applicationResourcesDirectory() + configPath.right(configPath.size() - 1);
}
else {
return configPath;
}
}
QString UBSettings::applicationStartupHintsDirectory()
{
QString defaultRelativePath = QString("./startupHints");
QString configPath = value("StartupHintsDirectory", QVariant(defaultRelativePath)).toString();
if (configPath.startsWith(".")) {
return UBPlatformUtils::applicationResourcesDirectory() + configPath.right(configPath.size() - 1);
}
else
return configPath;
}
QString UBSettings::userInteractiveFavoritesDirectory()
{
static QString dirPath = "";
if(dirPath.isEmpty()){
if (sAppSettings && getAppSettings()->contains("App/UserInteractiveFavoritesDirectory")) {
dirPath = getAppSettings()->value("App/UserInteractiveFavoritesDirectory").toString();
dirPath = replaceWildcard(dirPath);
if(checkDirectory(dirPath))
return dirPath;
else
qCritical() << "failed to create directory " << dirPath;
}
dirPath = userDataDirectory() + "/interactive favorites";
checkDirectory(dirPath);
}
return dirPath;
}
QNetworkProxy* UBSettings::httpProxy()
{
QNetworkProxy* proxy = 0;
if (mAppSettings->value("Proxy/Enabled", false).toBool()) {
proxy = new QNetworkProxy();
if (mAppSettings->value("Proxy/Type", "HTTP").toString() == "Socks5")
proxy->setType(QNetworkProxy::Socks5Proxy);
else
proxy->setType(QNetworkProxy::HttpProxy);
proxy->setHostName(mAppSettings->value("Proxy/HostName").toString());
proxy->setPort(mAppSettings->value("Proxy/Port", 1080).toInt());
proxy->setUser(mAppSettings->value("Proxy/UserName").toString());
proxy->setPassword(mAppSettings->value("Proxy/Password").toString());
}
return proxy;
}
void UBSettings::setPassword(const QString& id, const QString& password)
{
QString encrypted = UBCryptoUtils::instance()->symetricEncrypt(password);
mUserSettings->setValue(QString("Vault/") + id, encrypted);
}
void UBSettings::removePassword(const QString& id)
{
mUserSettings->remove(QString("Vault/") + id);
}
QString UBSettings::password(const QString& id)
{
QString encrypted = mUserSettings->value(QString("Vault/") + id).toString();
QString result = "";
if (encrypted.length() > 0)
result = UBCryptoUtils::instance()->symetricDecrypt(encrypted);
return result;
}
QString UBSettings::proxyUsername()
{
QString idUsername = "http.proxy.user";
return password(idUsername);
}
void UBSettings::setProxyUsername(const QString& username)
{
QString idUsername = "http.proxy.user";
if (username.length() > 0)
setPassword(idUsername, username);
else
removePassword(idUsername);
}
QString UBSettings::proxyPassword()
{
QString idPassword = "http.proxy.pass";
return password(idPassword);
}
void UBSettings::setProxyPassword(const QString& password)
{
QString idPassword = "http.proxy.pass";
if (password.length() > 0)
setPassword(idPassword, password);
else
removePassword(idPassword);
}
QString UBSettings::communityUsername()
{
return communityUser->get().toString();
}
void UBSettings::setCommunityUsername(const QString &username)
{
communityUser->set(QVariant(username));
}
QString UBSettings::communityPassword()
{
return communityPsw->get().toString();
}
void UBSettings::setCommunityPassword(const QString &password)
{
communityPsw->set(QVariant(password));
}
void UBSettings::setCommunityPersistence(const bool persistence)
{
communityCredentialsPersistence->set(QVariant(persistence));
}
int UBSettings::libraryIconSize(){
return libIconSize->get().toInt();
}
void UBSettings::setLibraryIconsize(const int& size){
libIconSize->set(QVariant(size));
}
bool UBSettings::checkDirectory(QString& dirPath)
{
bool result = true;
QDir dir(dirPath);
if(!dir.exists())
result = dir.mkpath(dirPath);
return result;
}
QString UBSettings::replaceWildcard(QString& path)
{
QString result(path);
if (result.startsWith("{Documents}")) {
result = result.replace("{Documents}", QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation));
}
else if(result.startsWith("{Home}")) {
result = result.replace("{Home}", QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
}
else if(result.startsWith("{Desktop}")) {
result = result.replace("{Desktop}", QDesktopServices::storageLocation(QDesktopServices::DesktopLocation));
}
if(result.contains("{UserLoginName}") && UBPlatformUtils::osUserLoginName().length() > 0) {
result = result.replace("{UserLoginName}", UBPlatformUtils::osUserLoginName());
}
return result;
}
void UBSettings::closing()
{
cleanNonPersistentSettings();
}
void UBSettings::cleanNonPersistentSettings()
{
if(!communityCredentialsPersistence->get().toBool()){
communityPsw->set(QVariant(""));
communityUser->set(QVariant(""));
}
if(!youTubeCredentialsPersistence->get().toBool())
{
if ( ! youTubeUserEMail->get().toString().isEmpty()) // ALTI/AOU - 20140204 : remove only the Youtube credentials if existing, and not the whole "Vault" section.
{
removePassword(youTubeUserEMail->get().toString());
}
youTubeUserEMail->set(QVariant(""));
}
}
| 33.839884 | 197 | 0.71047 | [
"shape"
] |
6fed290add1ddf90c3ef6df81de39c2e34bc8267 | 4,317 | hpp | C++ | include/stc/gl/context.hpp | vtavernier/shadertoy-connector | f458a1216b0910ddbbf570932038e68decb2da26 | [
"MIT"
] | null | null | null | include/stc/gl/context.hpp | vtavernier/shadertoy-connector | f458a1216b0910ddbbf570932038e68decb2da26 | [
"MIT"
] | null | null | null | include/stc/gl/context.hpp | vtavernier/shadertoy-connector | f458a1216b0910ddbbf570932038e68decb2da26 | [
"MIT"
] | null | null | null | #ifndef _STC_GL_CONTEXT_HPP_
#define _STC_GL_CONTEXT_HPP_
#include <memory>
#include <string>
#include <epoxy/gl.h>
#include <GLFW/glfw3.h>
#include <shadertoy.hpp>
#include "stc/core/basic_context.hpp"
namespace stc
{
namespace gl
{
class context : public core::basic_context
{
/// Rendering size
shadertoy::rsize render_size_;
/// Rendering context
shadertoy::render_context context_;
/// Associated swap chain
shadertoy::swap_chain chain_;
/// Number of rendered frames
int frame_count_;
/// The currently rendered image
core::image current_image_;
public:
/**
* Builds a new rendering context for a given Shadertoy.
*
* @param shaderId Identifier of the Shadertoy to render.
* @param width Initial width of the rendering context.
* @param height Initial height of the rendering context.
*/
context(const std::string &shaderId, size_t width, size_t height);
/**
* Builds a multi-buffer rendering context from source.
*
* @param shaderId Identifier for this rendering context.
* @param bufferSources Source for all of the buffers to render. The image
* buffer must be present.
* @param width Initial width of the rendering context.
* @param height Initial height of the rendering context.
* @throws std::runtime_error If an error occurs during the construction of
* the local context, or if the image buffer is
* missing from the definition.
*/
context(const std::string &shaderId, const std::vector<std::pair<std::string, std::string>> &bufferSources,
size_t width, size_t height);
/**
* @brief Gets the number of rendered frames using this context
*
* @return Number of rendered frames
*/
inline int frame_count() const
{ return frame_count_; }
/**
* @brief Renders a new frame at the given resolution
*
* @param frame Number of the frame to render
* @param width Rendering width
* @param height Rendering height
* @param mouse Mouse status
* @param format Rendering format
*/
void perform_render(int frame, size_t width, size_t height, const std::array<float, 4> &mouse, GLenum format);
/**
* @brief Gets the current frame result
*
* @return Handle to the frame result
*/
inline core::image current_image() const
{ return current_image_; }
void set_input(const std::string &buffer, size_t channel, const boost::variant<std::string, std::shared_ptr<core::image>> &data) override;
void set_input_filter(const std::string &buffer, size_t channel, GLint minFilter) override;
void reset_input(const std::string &buffer, size_t channel) override;
private:
/**
* Initialize the rendering context members.
*/
void initialize(const std::string &shaderId, size_t width, size_t height);
/**
* Returns the number of components for a given format.
*
* @param format Format to return the number of components of
*/
int format_depth(GLenum format);
/**
* Returns the PixelDataFormat of a given image depth.
*
* @param depth Depth of the image
*/
static GLint depth_format(int depth);
/**
* Allocates the rendering context
*/
void create_context();
/**
* @brief Find a buffer by name
*
* @param name Name of the buffer to find
*
* @return Pointer to the buffer with the id \p name
*
* @throws std::runtime_error When a suitable buffer could not be found
*/
std::shared_ptr<shadertoy::buffers::toy_buffer> getBuffer(const std::string &name);
class override_input : public shadertoy::inputs::basic_input
{
std::shared_ptr<core::image> data_buffer_;
std::shared_ptr<shadertoy::gl::texture> texture_;
std::shared_ptr<shadertoy::inputs::buffer_input> member_input_;
std::shared_ptr<shadertoy::inputs::basic_input> overriden_input_;
protected:
void load_input() override;
void reset_input() override;
shadertoy::gl::texture *use_input() override;
public:
override_input(std::shared_ptr<shadertoy::inputs::basic_input> overriden_input);
void set(std::shared_ptr<core::image> data_buffer);
void set(std::shared_ptr<shadertoy::inputs::buffer_input> member_input);
inline const std::shared_ptr<shadertoy::inputs::basic_input> &overriden_input() const
{ return overriden_input_; }
};
};
}
}
#endif /* _STC_GL_CONTEXT_HPP_ */
| 26.648148 | 139 | 0.708594 | [
"render",
"vector"
] |
6ff6a71a1b267d61fc00f4052b70e315d598bb54 | 386 | cpp | C++ | 118. Pascal's Triangle.cpp | MadanParth786/LeetcodeSolutions_PracticeQuestions | 8a9c1eb88a6d5214abdb2becf2115a51e317a5c4 | [
"MIT"
] | 1 | 2022-01-19T14:25:36.000Z | 2022-01-19T14:25:36.000Z | 118. Pascal's Triangle.cpp | MadanParth786/LeetcodeSolutions_PracticeQuestions | 8a9c1eb88a6d5214abdb2becf2115a51e317a5c4 | [
"MIT"
] | null | null | null | 118. Pascal's Triangle.cpp | MadanParth786/LeetcodeSolutions_PracticeQuestions | 8a9c1eb88a6d5214abdb2becf2115a51e317a5c4 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> Generate(int numrows) {
vector<vector<int>>r(numRows);
for (int i = 0; i < numrows; i++) {
r[i].resize(i + 1);
r[i][0] = r[i][i] = 1;
for (int j = 1; j < i; j++)
r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
}
return r;
}
};
| 22.705882 | 57 | 0.360104 | [
"vector"
] |
6ff76f8093e2651e3d48decd86d1bc5bca585afd | 3,567 | cpp | C++ | src/SolARNonFreeOpenCVHelper.cpp | SolarFramework/SolARModuleNonFreeOpenCV | d14beef73fcfd7be5baf548ebf93b8c4f3548291 | [
"Apache-2.0"
] | null | null | null | src/SolARNonFreeOpenCVHelper.cpp | SolarFramework/SolARModuleNonFreeOpenCV | d14beef73fcfd7be5baf548ebf93b8c4f3548291 | [
"Apache-2.0"
] | 1 | 2020-02-24T10:44:06.000Z | 2020-02-24T10:44:06.000Z | src/SolARNonFreeOpenCVHelper.cpp | SolarFramework/SolARModuleNonFreeOpenCV | d14beef73fcfd7be5baf548ebf93b8c4f3548291 | [
"Apache-2.0"
] | 2 | 2019-07-25T09:19:48.000Z | 2019-12-09T10:03:33.000Z | /**
* @copyright Copyright (c) 2017 B-com http://www.b-com.com/
*
* 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 "SolARNonFreeOpenCVHelper.h"
#include <map>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include "datastructure/DescriptorBuffer.h"
using namespace org::bcom::xpcf;
namespace SolAR {
using namespace datastructure;
namespace MODULES {
namespace NONFREEOPENCV {
static std::map<DescriptorDataType,uint32_t> solarDescriptor2cvType =
{{ DescriptorDataType::TYPE_8U,CV_8U},{DescriptorDataType::TYPE_32F,CV_32F}};
static std::map<std::tuple<uint32_t,std::size_t,uint32_t>,int> solar2cvTypeConvertMap = {{std::make_tuple(8,1,3),CV_8UC3},{std::make_tuple(8,1,1),CV_8UC1}};
static std::map<int,std::pair<Image::ImageLayout,Image::DataType>> cv2solarTypeConvertMap = {{CV_8UC3,{Image::ImageLayout::LAYOUT_BGR,Image::DataType::TYPE_8U}},
{CV_8UC1,{Image::ImageLayout::LAYOUT_GREY,Image::DataType::TYPE_8U}}};
uint32_t SolARNonFreeOpenCVHelper::deduceOpenDescriptorCVType(DescriptorDataType querytype){
return solarDescriptor2cvType.at(querytype);
}
int SolARNonFreeOpenCVHelper::deduceOpenCVType(SRef<Image> img)
{
// TODO : handle safe mode if missing map entry
// is it ok when destLayout != img->ImageLayout ?
return solar2cvTypeConvertMap.at(std::forward_as_tuple(img->getNbBitsPerComponent(),1,img->getNbChannels()));
}
void SolARNonFreeOpenCVHelper::mapToOpenCV (SRef<Image> imgSrc, cv::Mat& imgDest)
{
cv::Mat imgCV(imgSrc->getHeight(),imgSrc->getWidth(),deduceOpenCVType(imgSrc), imgSrc->data());
imgDest = imgCV;
}
cv::Mat SolARNonFreeOpenCVHelper::mapToOpenCV (SRef<Image> imgSrc)
{
cv::Mat imgCV(imgSrc->getHeight(),imgSrc->getWidth(),deduceOpenCVType(imgSrc), imgSrc->data());
return imgCV;
}
FrameworkReturnCode SolARNonFreeOpenCVHelper::convertToSolar (cv::Mat& imgSrc, SRef<Image>& imgDest)
{
if (cv2solarTypeConvertMap.find(imgSrc.type()) == cv2solarTypeConvertMap.end() || imgSrc.empty()) {
return FrameworkReturnCode::_ERROR_LOAD_IMAGE;
}
std::pair<Image::ImageLayout,Image::DataType> type = cv2solarTypeConvertMap.at(imgSrc.type());
imgDest = utils::make_shared<Image>(imgSrc.ptr(), imgSrc.cols, imgSrc.rows, type.first, Image::PixelOrder::INTERLEAVED, type.second);
return FrameworkReturnCode::_SUCCESS;
}
std::vector<cv::Point2i> SolARNonFreeOpenCVHelper::convertToOpenCV (const Contour2Di &contour)
{
std::vector<cv::Point2i> output;
for (int i = 0; i < contour.size(); i++)
{
output.push_back(cv::Point2i(contour[i]->getX(), contour[i]->getY()));
}
return output;
}
std::vector<cv::Point2f> SolARNonFreeOpenCVHelper::convertToOpenCV (const Contour2Df &contour)
{
std::vector<cv::Point2f> output;
for (int i = 0; i < contour.size(); i++)
{
output.push_back(cv::Point2f(contour[i].getX(), contour[i].getY()));
}
return output;
}
}
}
}
| 35.316832 | 172 | 0.708719 | [
"vector"
] |
6ffe3a478cf0629641f9fe72e10d87da3cc82752 | 32,171 | cc | C++ | installer/util/vivaldi_install_dialog.cc | careylam/vivaldi | bff2a435c35fe2cb3327d8d4a76430d4be5f666e | [
"BSD-3-Clause"
] | null | null | null | installer/util/vivaldi_install_dialog.cc | careylam/vivaldi | bff2a435c35fe2cb3327d8d4a76430d4be5f666e | [
"BSD-3-Clause"
] | null | null | null | installer/util/vivaldi_install_dialog.cc | careylam/vivaldi | bff2a435c35fe2cb3327d8d4a76430d4be5f666e | [
"BSD-3-Clause"
] | 1 | 2020-05-12T23:54:41.000Z | 2020-05-12T23:54:41.000Z | // Copyright (c) 2015 Vivaldi Technologies AS. All rights reserved.
#include "installer/util/vivaldi_install_dialog.h"
#include <Shellapi.h>
#include <Shlwapi.h>
#include <shlobj.h>
#include <windowsx.h>
#include <iterator>
#include <map>
#include <memory>
#include <vector>
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "base/win/registry.h"
#include "base/win/windows_version.h"
#include "chrome/installer/setup/setup_constants.h"
#include "chrome/installer/setup/setup_resource.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/html_dialog.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/l10n_string_util.h"
namespace installer {
namespace {
static const uint32_t kuint32max = 0xFFFFFFFFu;
}
std::map<const std::wstring, const std::wstring> kLanguages = {
// please keep this map alphabetically sorted by language name!
{L"sq", L"Albanian"},
{L"ar", L"Arabic"},
{L"hy", L"Armenian"},
{L"eu", L"Basque"},
{L"be", L"Belarusian"},
{L"bg", L"Bulgarian"},
{L"ca", L"Catalan"},
{L"zh_CN", L"Chinese (Simplified)"},
{L"zh_TW", L"Chinese (Traditional)"},
{L"hr", L"Croatian"},
{L"cs", L"Czech"},
{L"da", L"Danish"},
{L"nl", L"Dutch"},
{L"en-us", L"English"},
{L"en-AU", L"English (Australia)"},
{L"et", L"Estonian"},
{L"eo", L"Esperanto"},
{L"fi", L"Finnish"},
{L"fr", L"French"},
{L"fy", L"Frisian"},
{L"gl", L"Galician"},
{L"ka", L"Georgian"},
{L"de", L"German"},
{L"el", L"Greek"},
{L"hu", L"Hungarian"},
{L"id", L"Indonesian"},
{L"io", L"Ido"},
{L"is", L"Icelandic"},
{L"it", L"Italian"},
{L"ja", L"Japanese"},
{L"ko", L"Korean"},
{L"ku", L"Kurdish"},
{L"lv", L"Latvian"},
{L"lt", L"Lithuanian"},
{L"jbo", L"Lojban"},
{L"mk", L"Macedonian"},
{L"no", L"Norwegian (Bokm\U000000E5l)"},
{L"nn", L"Norwegian (Nynorsk)"},
{L"fa", L"Persian"},
{L"pl", L"Polish"},
{L"pt_BR", L"Portuguese (Brazil)"},
{L"pt_PT", L"Portuguese (Portugal)"},
{L"ro", L"Romanian"},
{L"ru", L"Russian"},
{L"sc", L"Sardinian"},
{L"gd", L"Scots Gaelic"},
{L"sr", L"Serbian"},
{L"sk", L"Slovak"},
{L"sl", L"Slovenian"},
{L"es", L"Spanish"},
{L"es_PE", L"Spanish (Peru)"},
{L"sv", L"Swedish"},
{L"tr", L"Turkish"},
{L"uk", L"Ukrainian"},
{L"vi", L"Vietnamese"}};
void GetDPI(int* dpi_x, int* dpi_y) {
HDC screen_dc = GetDC(NULL);
*dpi_x = GetDeviceCaps(screen_dc, LOGPIXELSX);
*dpi_y = GetDeviceCaps(screen_dc, LOGPIXELSY);
if (screen_dc)
ReleaseDC(NULL, screen_dc);
}
VivaldiInstallDialog* VivaldiInstallDialog::this_ = NULL;
VivaldiInstallDialog::VivaldiInstallDialog(
HINSTANCE instance,
const bool set_as_default_browser,
const InstallType default_install_type,
const base::FilePath& destination_folder)
: install_type_(default_install_type),
set_as_default_browser_(set_as_default_browser),
register_browser_(false),
is_upgrade_(false),
dialog_ended_(false),
advanced_mode_(false),
hdlg_(NULL),
instance_(instance),
dlg_result_(INSTALL_DLG_ERROR),
hbitmap_bkgnd_(NULL),
back_bmp_(NULL),
back_bits_(NULL),
back_bmp_width_(-1),
back_bmp_height_(-1),
syslink_tos_brush_(NULL),
button_browse_brush_(NULL),
button_ok_brush_(NULL),
button_cancel_brush_(NULL),
checkbox_default_brush_(NULL),
button_options_brush_(NULL),
syslink_privacy_brush_(NULL) {
if (destination_folder.empty()) {
SetDefaultDestinationFolder();
} else {
destination_folder_ = destination_folder;
}
if (default_install_type == INSTALL_STANDALONE)
last_standalone_folder_ = destination_folder_;
language_code_ = GetCurrentTranslation();
int dpi_x = 0;
int dpi_y = 0;
GetDPI(&dpi_x, &dpi_y);
if (dpi_x <= 96)
dpi_scale_ = DPI_NORMAL;
else if (dpi_x <= 120)
dpi_scale_ = DPI_MEDIUM;
else if (dpi_x <= 144)
dpi_scale_ = DPI_LARGE;
else if (dpi_x <= 192)
dpi_scale_ = DPI_XL;
else
dpi_scale_ = DPI_XXL;
enable_set_as_default_checkbox_ =
(base::win::GetVersion() < base::win::VERSION_WIN10);
enable_register_browser_checkbox_ = IsRegisterBrowserValid();
}
VivaldiInstallDialog::~VivaldiInstallDialog() {
if (back_bmp_)
DeleteObject(back_bmp_);
if (hbitmap_bkgnd_)
DeleteObject(hbitmap_bkgnd_);
if (syslink_tos_brush_)
DeleteObject(syslink_tos_brush_);
if (button_browse_brush_)
DeleteObject(button_browse_brush_);
if (button_ok_brush_)
DeleteObject(button_ok_brush_);
if (button_cancel_brush_)
DeleteObject(button_cancel_brush_);
if (checkbox_default_brush_)
DeleteObject(checkbox_default_brush_);
if (checkbox_register_brush_)
DeleteObject(checkbox_register_brush_);
if (button_options_brush_)
DeleteObject(button_options_brush_);
if (syslink_privacy_brush_)
DeleteObject(syslink_privacy_brush_);
std::vector<HGLOBAL>::iterator it;
for (it = dibs_.begin(); it != dibs_.end(); it++) {
HGLOBAL hDIB = *it;
GlobalFree(hDIB);
}
}
VivaldiInstallDialog::DlgResult VivaldiInstallDialog::ShowModal() {
GetLastInstallValues();
enable_register_browser_checkbox_ = IsRegisterBrowserValid();
hdlg_ = CreateDialogParam(instance_, MAKEINTRESOURCE(IDD_DIALOG1), NULL,
DlgProc, (LPARAM)this);
InitDialog();
ShowWindow(hdlg_, SW_SHOW);
ShowOptions(hdlg_, advanced_mode_);
DoDialog(); // main message loop
if (dlg_result_ == INSTALL_DLG_INSTALL)
SaveInstallValues();
return dlg_result_;
}
void VivaldiInstallDialog::SetDefaultDestinationFolder() {
wchar_t szPath[MAX_PATH];
int csidl = 0;
switch (install_type_) {
case INSTALL_FOR_ALL_USERS:
csidl = CSIDL_PROGRAM_FILES;
break;
case INSTALL_FOR_CURRENT_USER:
csidl = CSIDL_LOCAL_APPDATA;
break;
case INSTALL_STANDALONE:
destination_folder_ = last_standalone_folder_;
break;
}
if (csidl && (SUCCEEDED(SHGetFolderPath(NULL, csidl, NULL, 0, szPath)))) {
destination_folder_ = base::FilePath(szPath);
destination_folder_ = destination_folder_.Append(L"Vivaldi");
}
if (hdlg_) {
SetDlgItemText(hdlg_, IDC_EDIT_DEST_FOLDER,
destination_folder_.value().c_str());
}
}
bool VivaldiInstallDialog::GetLastInstallValues() {
base::win::RegKey key(HKEY_CURRENT_USER, kVivaldiKey, KEY_QUERY_VALUE);
if (key.Valid()) {
std::wstring str_dest_folder;
if (key.ReadValue(kVivaldiInstallerDestinationFolder, &str_dest_folder) ==
ERROR_SUCCESS) {
destination_folder_ = base::FilePath(str_dest_folder);
}
key.ReadValueDW(kVivaldiInstallerInstallType,
reinterpret_cast<DWORD*>(&install_type_));
key.ReadValueDW(kVivaldiInstallerDefaultBrowser,
reinterpret_cast<DWORD*>(&set_as_default_browser_));
if (install_type_ == INSTALL_STANDALONE)
last_standalone_folder_ = destination_folder_;
return true;
}
return false;
}
void VivaldiInstallDialog::SaveInstallValues() {
base::win::RegKey key(HKEY_CURRENT_USER, kVivaldiKey, KEY_ALL_ACCESS);
if (key.Valid()) {
key.WriteValue(kVivaldiInstallerDestinationFolder,
destination_folder_.value().c_str());
key.WriteValue(kVivaldiInstallerInstallType, (DWORD)install_type_);
key.WriteValue(kVivaldiInstallerDefaultBrowser,
set_as_default_browser_ ? 1 : 0);
key.WriteValue(google_update::kRegLangField, language_code_.c_str());
}
}
bool VivaldiInstallDialog::InternalSelectLanguage(const std::wstring& code) {
LOG(INFO) << "InternalSelectLanguage: code: " << code;
bool found = false;
std::map<const std::wstring, const std::wstring>::iterator it;
for (it = kLanguages.begin(); it != kLanguages.end(); it++) {
if (it->first == code) {
ComboBox_SelectString(GetDlgItem(hdlg_, IDC_COMBO_LANGUAGE), -1,
it->second.c_str());
found = true;
break;
}
}
if (!found)
LOG(WARNING) << "InternalSelectLanguage: language code undefined";
return found;
}
std::wstring VivaldiInstallDialog::GetCurrentTranslation() {
// Special handling for Australian locale. This locale is not supported
// by the Chromium installer.
std::unique_ptr<wchar_t[]> buffer(new wchar_t[LOCALE_NAME_MAX_LENGTH]);
if (buffer.get()) {
::GetUserDefaultLocaleName(buffer.get(), LOCALE_NAME_MAX_LENGTH);
std::wstring locale_name(buffer.get());
if (locale_name.compare(L"en-AU") == 0)
return locale_name;
}
return installer::GetCurrentTranslation();
}
void VivaldiInstallDialog::InitDialog() {
dialog_ended_ = false;
std::map<const std::wstring, const std::wstring>::iterator it;
for (it = kLanguages.begin(); it != kLanguages.end(); it++) {
ComboBox_AddString(GetDlgItem(hdlg_, IDC_COMBO_LANGUAGE),
it->second.c_str());
}
if (!InternalSelectLanguage(language_code_))
InternalSelectLanguage(L"en-us");
ComboBox_AddString(GetDlgItem(hdlg_, IDC_COMBO_INSTALLTYPES),
L"Install for all users"); // TODO(jarle) localize
ComboBox_AddString(GetDlgItem(hdlg_, IDC_COMBO_INSTALLTYPES),
L"Install per user"); // TODO(jarle) localize
ComboBox_AddString(GetDlgItem(hdlg_, IDC_COMBO_INSTALLTYPES),
L"Install standalone"); // TODO(jarle) localize
ComboBox_SetCurSel(GetDlgItem(hdlg_, IDC_COMBO_INSTALLTYPES), install_type_);
SetDlgItemText(hdlg_, IDC_EDIT_DEST_FOLDER,
destination_folder_.value().c_str());
SendMessage(GetDlgItem(hdlg_, IDC_CHECK_DEFAULT), BM_SETCHECK,
set_as_default_browser_ ? BST_CHECKED : BST_UNCHECKED, 0);
SendMessage(GetDlgItem(hdlg_, IDC_CHECK_REGISTER), BM_SETCHECK,
register_browser_ ? BST_CHECKED : BST_UNCHECKED, 0);
}
// Finds the tree view of the SHBrowseForFolder dialog
static BOOL CALLBACK EnumChildProcFindTreeView(HWND hwnd, LPARAM lparam) {
HWND* tree_view = reinterpret_cast<HWND*>(lparam);
DCHECK(tree_view);
const int MAX_BUF_SIZE = 80;
const wchar_t TREE_VIEW_CLASS_NAME[] = L"SysTreeView32";
std::unique_ptr<wchar_t[]> buffer(new wchar_t[MAX_BUF_SIZE]);
GetClassName(hwnd, buffer.get(), MAX_BUF_SIZE - 1);
if (std::wstring(buffer.get()) == TREE_VIEW_CLASS_NAME) {
*tree_view = hwnd;
return FALSE;
}
*tree_view = NULL;
return TRUE;
}
static int CALLBACK BrowseCallbackProc(HWND hwnd,
UINT msg,
LPARAM lparam,
LPARAM lpdata) {
static HWND tree_view = NULL;
switch (msg) {
case BFFM_INITIALIZED:
if (lpdata)
SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpdata);
EnumChildWindows(hwnd, EnumChildProcFindTreeView, (LPARAM)&tree_view);
break;
case BFFM_SELCHANGED:
if (IsWindow(tree_view)) {
// Make sure the current selection is scrolled into view
HTREEITEM item = TreeView_GetSelection(tree_view);
if (item)
TreeView_EnsureVisible(tree_view, item);
}
break;
}
return 0;
}
void VivaldiInstallDialog::ShowBrowseFolderDialog() {
BROWSEINFO bi;
memset(&bi, 0, sizeof(bi));
bi.hwndOwner = hdlg_;
bi.lpszTitle = L"Select a folder"; // TODO(jarle) localize
bi.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS;
bi.lpfn = BrowseCallbackProc;
bi.lParam = (LPARAM)destination_folder_.value().c_str();
OleInitialize(NULL);
LPITEMIDLIST pIDL = SHBrowseForFolder(&bi);
if (pIDL == NULL)
return;
std::unique_ptr<wchar_t[]> buffer(new wchar_t[MAX_PATH]);
if (!SHGetPathFromIDList(pIDL, buffer.get()) != 0) {
CoTaskMemFree(pIDL);
return;
}
destination_folder_ = base::FilePath(buffer.get());
CoTaskMemFree(pIDL);
OleUninitialize();
}
void VivaldiInstallDialog::DoDialog() {
MSG msg;
BOOL ret;
while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
if (ret == -1) {
dlg_result_ = INSTALL_DLG_ERROR;
return;
}
if (!IsDialogMessage(hdlg_, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (dialog_ended_)
return;
}
}
void VivaldiInstallDialog::OnInstallTypeSelection() {
install_type_ = (InstallType)ComboBox_GetCurSel(
GetDlgItem(hdlg_, IDC_COMBO_INSTALLTYPES));
SetDefaultDestinationFolder();
UpdateRegisterCheckboxVisibility();
}
void VivaldiInstallDialog::OnLanguageSelection() {
int i = ComboBox_GetCurSel(GetDlgItem(hdlg_, IDC_COMBO_LANGUAGE));
if (i != CB_ERR) {
const int len =
ComboBox_GetLBTextLen(GetDlgItem(hdlg_, IDC_COMBO_LANGUAGE), i);
if (len <= 0)
return;
std::unique_ptr<wchar_t[]> buf(new wchar_t[len + 1]);
ComboBox_GetLBText(GetDlgItem(hdlg_, IDC_COMBO_LANGUAGE), i, buf.get());
std::map<const std::wstring, const std::wstring>::iterator it;
for (it = kLanguages.begin(); it != kLanguages.end(); it++) {
if (it->second == buf.get()) {
language_code_ = it->first;
break;
}
}
}
}
const bool VivaldiInstallDialog::GetRegisterBrowser() const {
return register_browser_ ||
(set_as_default_browser_ &&
base::win::GetVersion() < base::win::VERSION_WIN10);
}
/* static */
bool VivaldiInstallDialog::IsVivaldiInstalled(const base::FilePath& path,
InstallType* installed_type) {
*installed_type = INSTALL_FOR_CURRENT_USER;
base::FilePath vivaldi_exe_path(path);
vivaldi_exe_path =
vivaldi_exe_path.Append(kInstallBinaryDir).Append(kChromeExe);
bool is_installed = base::PathExists(vivaldi_exe_path);
if (is_installed) {
base::FilePath vivaldi_sa_file_path(path);
vivaldi_sa_file_path = vivaldi_sa_file_path.Append(kInstallBinaryDir)
.Append(kStandaloneProfileHelper);
if (base::PathExists(vivaldi_sa_file_path)) {
*installed_type = INSTALL_STANDALONE;
} else {
base::FilePath program_files_path;
PathService::Get(base::DIR_PROGRAM_FILES, &program_files_path);
if (vivaldi_exe_path.value().size() >=
program_files_path.value().size()) {
DWORD prefix_len =
base::saturated_cast<DWORD>(program_files_path.value().size());
if (::CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE,
vivaldi_exe_path.value().data(), prefix_len,
program_files_path.value().data(),
prefix_len) == CSTR_EQUAL) {
*installed_type = INSTALL_FOR_ALL_USERS;
}
}
}
}
return is_installed;
}
bool VivaldiInstallDialog::IsInstallPathValid(const base::FilePath& path) {
bool path_is_valid = base::PathIsWritable(path);
if (!path_is_valid)
MessageBox(hdlg_,
L"The destination folder is invalid. Please choose another.",
NULL, MB_ICONERROR); // TODO(jarle) localize
return path_is_valid;
}
installer::InstallStatus VivaldiInstallDialog::ShowEULADialog() {
VLOG(1) << "About to show EULA";
base::string16 eula_path = installer::GetLocalizedEulaResource();
if (eula_path.empty()) {
LOG(ERROR) << "No EULA path available";
return installer::EULA_REJECTED;
}
base::string16 inner_frame_path = GetInnerFrameEULAResource();
if (inner_frame_path.empty()) {
LOG(ERROR) << "No EULA inner frame path available";
return installer::EULA_REJECTED;
}
// Newer versions of the caller pass an inner frame parameter that must
// be given to the html page being launched.
installer::EulaHTMLDialog dlg(eula_path, inner_frame_path);
installer::EulaHTMLDialog::Outcome outcome = dlg.ShowModal();
if (installer::EulaHTMLDialog::REJECTED == outcome) {
LOG(ERROR) << "EULA rejected or EULA failure";
return installer::EULA_REJECTED;
}
if (installer::EulaHTMLDialog::ACCEPTED_OPT_IN == outcome) {
VLOG(1) << "EULA accepted (opt-in)";
return installer::EULA_ACCEPTED_OPT_IN;
}
VLOG(1) << "EULA accepted (no opt-in)";
return installer::EULA_ACCEPTED;
}
std::wstring VivaldiInstallDialog::GetInnerFrameEULAResource() {
wchar_t full_exe_path[MAX_PATH];
int len = ::GetModuleFileName(NULL, full_exe_path, MAX_PATH);
if (len == 0 || len == MAX_PATH)
return L"";
const wchar_t* inner_frame_resource = L"IDR_OEM_EULA_VIV.HTML";
if (NULL == FindResource(NULL, inner_frame_resource, RT_HTML))
return L"";
// spaces and DOS paths must be url encoded.
std::wstring url_path = base::StringPrintf(
L"res://%ls/#23/%ls", full_exe_path, inner_frame_resource);
// the cast is safe because url_path has limited length
// (see the definition of full_exe_path and resource).
DCHECK(kuint32max > (url_path.size() * 3));
DWORD count = static_cast<DWORD>(url_path.size() * 3);
std::unique_ptr<wchar_t[]> url_canon(new wchar_t[count]);
HRESULT hr = ::UrlCanonicalizeW(url_path.c_str(), url_canon.get(), &count,
URL_ESCAPE_UNSAFE);
if (SUCCEEDED(hr))
return std::wstring(url_canon.get());
return url_path;
}
void VivaldiInstallDialog::ShowDlgControls(HWND hdlg, bool show) {
HWND hwnd_child = GetWindow(hdlg, GW_CHILD);
while (hwnd_child != NULL) {
EnableWindow(hwnd_child, show ? TRUE : FALSE);
ShowWindow(hwnd_child, show ? SW_SHOW : SW_HIDE);
hwnd_child = GetWindow(hwnd_child, GW_HWNDNEXT);
}
}
void VivaldiInstallDialog::ShowOptions(HWND hdlg, bool show) {
EnableWindow(GetDlgItem(hdlg, IDC_COMBO_INSTALLTYPES), show ? TRUE : FALSE);
EnableWindow(GetDlgItem(hdlg, IDC_EDIT_DEST_FOLDER), show ? TRUE : FALSE);
EnableWindow(GetDlgItem(hdlg, IDC_CHECK_DEFAULT),
(show && enable_set_as_default_checkbox_) ? TRUE : FALSE);
EnableWindow(GetDlgItem(hdlg, IDC_CHECK_REGISTER),
(show && enable_register_browser_checkbox_) ? TRUE : FALSE);
EnableWindow(GetDlgItem(hdlg, IDC_BTN_BROWSE), show ? TRUE : FALSE);
EnableWindow(GetDlgItem(hdlg, IDC_COMBO_LANGUAGE), show ? TRUE : FALSE);
ShowWindow(GetDlgItem(hdlg, IDC_COMBO_INSTALLTYPES),
show ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(hdlg, IDC_EDIT_DEST_FOLDER), show ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(hdlg, IDC_CHECK_DEFAULT),
(show && enable_set_as_default_checkbox_) ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(hdlg, IDC_CHECK_REGISTER),
(show && enable_register_browser_checkbox_) ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(hdlg, IDC_BTN_BROWSE), show ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(hdlg, IDC_COMBO_LANGUAGE), show ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(hdlg, IDC_STATIC_LANGUAGE), show ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(hdlg, IDC_STATIC_INSTALLTYPES),
show ? SW_SHOW : SW_HIDE);
ShowWindow(GetDlgItem(hdlg, IDC_STATIC_DEST_FOLDER),
show ? SW_SHOW : SW_HIDE);
if (is_upgrade_ && show)
EnableWindow(GetDlgItem(hdlg, IDC_COMBO_INSTALLTYPES), FALSE);
if (show)
SetDlgItemText(hdlg, IDC_BTN_MODE, L"Simple"); // TODO(jarle) localize
else
SetDlgItemText(hdlg, IDC_BTN_MODE, L"Advanced"); // TODO(jarle) localize
}
void VivaldiInstallDialog::UpdateRegisterCheckboxVisibility() {
enable_register_browser_checkbox_ = IsRegisterBrowserValid();
EnableWindow(GetDlgItem(hdlg_, IDC_CHECK_REGISTER),
(enable_register_browser_checkbox_) ? TRUE : FALSE);
ShowWindow(GetDlgItem(hdlg_, IDC_CHECK_REGISTER),
(enable_register_browser_checkbox_) ? SW_SHOW : SW_HIDE);
}
const bool VivaldiInstallDialog::IsRegisterBrowserValid() const {
return (install_type_ == INSTALL_STANDALONE &&
base::win::GetVersion() >= base::win::VERSION_WIN10);
}
void VivaldiInstallDialog::InitBkgnd(HWND hdlg, int cx, int cy) {
if ((back_bmp_width_ != cx) || (back_bmp_height_ != cy) ||
(NULL == back_bmp_)) {
if (back_bmp_) {
DeleteObject(back_bmp_);
back_bmp_ = NULL;
back_bits_ = NULL;
}
back_bmp_width_ = cx;
back_bmp_height_ = cy;
HDC hDC = GetDC(NULL);
if (hDC) {
BITMAPINFO bi;
memset(&bi, 0, sizeof(bi));
bi.bmiHeader.biBitCount = 32;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biWidth = back_bmp_width_;
bi.bmiHeader.biHeight = back_bmp_height_;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biSizeImage = back_bmp_width_ * back_bmp_height_ * 4;
back_bmp_ =
CreateDIBSection(hDC, &bi, DIB_RGB_COLORS, &back_bits_, NULL, 0);
if (!back_bmp_) {
ReleaseDC(NULL, hDC);
return;
}
switch (dpi_scale_) {
case DPI_NORMAL:
hbitmap_bkgnd_ =
LoadBitmap(instance_, MAKEINTRESOURCE(IDB_BITMAP_BKGND));
break;
case DPI_MEDIUM:
hbitmap_bkgnd_ =
LoadBitmap(instance_, MAKEINTRESOURCE(IDB_BITMAP_BKGND_125));
break;
case DPI_LARGE:
hbitmap_bkgnd_ =
LoadBitmap(instance_, MAKEINTRESOURCE(IDB_BITMAP_BKGND_150));
break;
case DPI_XL:
hbitmap_bkgnd_ =
LoadBitmap(instance_, MAKEINTRESOURCE(IDB_BITMAP_BKGND_200));
break;
case DPI_XXL:
hbitmap_bkgnd_ =
LoadBitmap(instance_, MAKEINTRESOURCE(IDB_BITMAP_BKGND_250));
break;
}
if (!hbitmap_bkgnd_) {
ReleaseDC(NULL, hDC);
return;
}
GetDIBits(hDC, hbitmap_bkgnd_, 0, back_bmp_height_, back_bits_, &bi,
DIB_RGB_COLORS);
ReleaseDC(NULL, hDC);
}
}
syslink_tos_brush_ = GetCtlBrush(hdlg, IDC_SYSLINK_TOS);
button_browse_brush_ = GetCtlBrush(hdlg, IDC_BTN_BROWSE);
button_ok_brush_ = GetCtlBrush(hdlg, IDOK);
button_cancel_brush_ = GetCtlBrush(hdlg, IDCANCEL);
checkbox_default_brush_ = GetCtlBrush(hdlg, IDC_CHECK_DEFAULT);
checkbox_register_brush_ = GetCtlBrush(hdlg, IDC_CHECK_REGISTER);
button_options_brush_ = GetCtlBrush(hdlg, IDC_BTN_MODE);
syslink_privacy_brush_ = GetCtlBrush(hdlg, IDC_SYSLINK_PRIVACY_POLICY);
}
BOOL VivaldiInstallDialog::OnEraseBkgnd(HDC hdc) {
if (back_bmp_) {
HDC hdc_mem = CreateCompatibleDC(hdc);
RECT rc_client;
GetClientRect(hdlg_, &rc_client);
if ((rc_client.right == back_bmp_width_) &&
(rc_client.bottom == back_bmp_height_)) {
HGDIOBJ old_bmp = SelectObject(hdc_mem, back_bmp_);
BitBlt(hdc, 0, 0, back_bmp_width_, back_bmp_height_, hdc_mem, 0, 0,
SRCCOPY);
SelectObject(hdc_mem, old_bmp);
DeleteDC(hdc_mem);
return TRUE;
}
}
return FALSE;
}
HBRUSH VivaldiInstallDialog::CreateDIBrush(int x, int y, int cx, int cy) {
if ((x < 0) || (y < 0) || (0 == cx) || (0 == cy) ||
((x + cx) > back_bmp_width_) || ((y + cy) > back_bmp_height_) ||
(NULL == back_bits_))
return NULL;
HGLOBAL hDIB = GlobalAlloc(GHND, sizeof(BITMAPINFOHEADER) + cx * cy * 4);
if (NULL == hDIB)
return NULL;
LPVOID lpvBits = GlobalLock(hDIB);
if (NULL == lpvBits) {
GlobalFree(hDIB);
return NULL;
}
BITMAPINFOHEADER* bih = reinterpret_cast<BITMAPINFOHEADER*>(lpvBits);
bih->biBitCount = 32;
bih->biCompression = BI_RGB;
bih->biWidth = cx;
bih->biHeight = cy;
bih->biPlanes = 1;
bih->biSize = sizeof(BITMAPINFOHEADER);
bih->biSizeImage = cx * cy * 4;
PDWORD pdwData = (PDWORD)(bih + 1);
size_t cnt = cx << 2;
int src_start_offset = back_bmp_height_ - 1 - y;
for (int j = 0; j < cy; j++) {
int dst_off = (cy - 1 - j) * cx;
int src_off = (src_start_offset - j) * back_bmp_width_ + x;
PDWORD pdwDst = pdwData + dst_off;
PDWORD pdwSrc = ((PDWORD)back_bits_) + src_off;
memcpy(pdwDst, pdwSrc, cnt);
}
GlobalUnlock(hDIB);
LOGBRUSH lb;
lb.lbStyle = BS_DIBPATTERN;
lb.lbColor = DIB_RGB_COLORS;
lb.lbHatch = (ULONG_PTR)hDIB;
HBRUSH hBrush = CreateBrushIndirect(&lb);
if (NULL == hBrush)
GlobalFree(hDIB);
dibs_.push_back(hDIB);
return hBrush;
}
HBRUSH VivaldiInstallDialog::GetCtlBrush(HWND hdlg, int id_dlg_item) {
RECT rcControl;
GetWindowRect(GetDlgItem(hdlg, id_dlg_item), &rcControl);
int w = rcControl.right - rcControl.left;
int h = rcControl.bottom - rcControl.top;
POINT pt = {rcControl.left, rcControl.top};
ScreenToClient(hdlg, &pt);
return CreateDIBrush(pt.x, pt.y, w, h);
}
HBRUSH VivaldiInstallDialog::OnCtlColor(HWND hwnd_ctl, HDC hdc) {
SetBkMode(hdc, TRANSPARENT);
if (GetDlgItem(hdlg_, IDC_SYSLINK_TOS) == hwnd_ctl)
return syslink_tos_brush_;
else if (GetDlgItem(hdlg_, IDC_BTN_BROWSE) == hwnd_ctl)
return button_browse_brush_;
else if (GetDlgItem(hdlg_, IDOK) == hwnd_ctl)
return button_ok_brush_;
else if (GetDlgItem(hdlg_, IDCANCEL) == hwnd_ctl)
return button_cancel_brush_;
else if (GetDlgItem(hdlg_, IDC_CHECK_DEFAULT) == hwnd_ctl)
return checkbox_default_brush_;
else if (GetDlgItem(hdlg_, IDC_CHECK_REGISTER) == hwnd_ctl)
return checkbox_register_brush_;
else if (GetDlgItem(hdlg_, IDC_BTN_MODE) == hwnd_ctl)
return button_options_brush_;
else if (GetDlgItem(hdlg_, IDC_SYSLINK_PRIVACY_POLICY) == hwnd_ctl)
return syslink_privacy_brush_;
return (HBRUSH)GetStockObject(NULL_BRUSH);
}
const WCHAR TXT_TOS_ACCEPT_AND_INSTALL[] =
L"By clicking on the 'Accept and Install' button you are agreeing to "
L"Vivaldi's <a>Terms of Service</a>";
const WCHAR TXT_TOS_ACCEPT_AND_UPDATE[] =
L"By clicking on the 'Accept and Update' button you are agreeing to "
L"Vivaldi's <a>Terms of Service</a>";
const WCHAR TXT_BTN_ACCEPT_AND_INSTALL[] = L"Accept and Install";
const WCHAR TXT_BTN_ACCEPT_AND_UPDATE[] = L"Accept and Update";
/*static*/
INT_PTR CALLBACK VivaldiInstallDialog::DlgProc(HWND hdlg,
UINT msg,
WPARAM wparam,
LPARAM lparam) {
switch (msg) {
case WM_INITDIALOG:
this_ = reinterpret_cast<VivaldiInstallDialog*>(lparam);
DCHECK(this_);
{
RECT rc_client;
GetClientRect(hdlg, &rc_client);
this_->InitBkgnd(hdlg, rc_client.right, rc_client.bottom);
}
return (INT_PTR)TRUE;
case WM_ERASEBKGND:
if (this_)
return (INT_PTR)this_->OnEraseBkgnd((HDC)wparam);
break;
case WM_CTLCOLORSTATIC:
if (GetDlgItem(hdlg, IDC_STATIC_COPYRIGHT) == (HWND)lparam)
SetTextColor((HDC)wparam, GetSysColor(COLOR_GRAYTEXT));
// fall through
case WM_CTLCOLORBTN:
if (this_)
return (INT_PTR)this_->OnCtlColor((HWND)lparam, (HDC)wparam);
break;
case WM_NOTIFY: {
LPNMHDR pnmh = (LPNMHDR)lparam;
if (pnmh->idFrom == IDC_SYSLINK_TOS) {
if ((pnmh->code == NM_CLICK) || (pnmh->code == NM_RETURN)) {
// TODO(jarle): check the return code and act upon it
/*int exit_code =*/this_->ShowEULADialog();
}
} else if (pnmh->idFrom == IDC_SYSLINK_PRIVACY_POLICY) {
if ((pnmh->code == NM_CLICK) || (pnmh->code == NM_RETURN)) {
ShellExecute(NULL, L"open", L"https://vivaldi.com/privacy", NULL,
NULL, SW_SHOWNORMAL);
}
}
} break;
case WM_COMMAND:
switch (LOWORD(wparam)) {
case IDOK: {
this_->dlg_result_ = INSTALL_DLG_INSTALL;
std::unique_ptr<wchar_t[]> buffer(new wchar_t[MAX_PATH]);
if (buffer.get()) {
GetDlgItemText(hdlg, IDC_EDIT_DEST_FOLDER, buffer.get(),
MAX_PATH - 1);
this_->destination_folder_ = base::FilePath(buffer.get());
}
this_->set_as_default_browser_ =
SendMessage(GetDlgItem(hdlg, IDC_CHECK_DEFAULT), BM_GETCHECK, 0,
0) != 0;
this_->register_browser_ =
SendMessage(GetDlgItem(hdlg, IDC_CHECK_REGISTER), BM_GETCHECK, 0,
0) != 0;
this_->install_type_ = (InstallType)SendMessage(
GetDlgItem(hdlg, IDC_COMBO_INSTALLTYPES), CB_GETCURSEL, 0, 0);
}
EndDialog(hdlg, 0);
this_->dialog_ended_ = true;
break;
case IDCANCEL:
// TODO(jarle) localize
if (MessageBox(
hdlg,
L"The Vivaldi Installer is not finished installing "
L"the Vivaldi Browser. Are you sure you want to exit now?",
L"Vivaldi Installer", MB_YESNO | MB_ICONQUESTION) == IDYES) {
this_->dlg_result_ = INSTALL_DLG_CANCEL;
EndDialog(hdlg, 0);
this_->dialog_ended_ = true;
}
break;
case IDC_BTN_BROWSE: {
std::unique_ptr<wchar_t[]> buffer(new wchar_t[MAX_PATH]);
if (buffer.get()) {
GetDlgItemText(hdlg, IDC_EDIT_DEST_FOLDER, buffer.get(),
MAX_PATH - 1);
this_->destination_folder_ = base::FilePath(buffer.get());
}
this_->ShowBrowseFolderDialog();
SetDlgItemText(hdlg, IDC_EDIT_DEST_FOLDER,
this_->destination_folder_.value().c_str());
} break;
case IDC_BTN_MODE:
this_->advanced_mode_ = !this_->advanced_mode_;
this_->ShowOptions(hdlg, this_->advanced_mode_);
break;
case IDC_COMBO_INSTALLTYPES:
if (HIWORD(wparam) == CBN_SELCHANGE)
this_->OnInstallTypeSelection();
break;
case IDC_COMBO_LANGUAGE:
if (HIWORD(wparam) == CBN_SELCHANGE)
this_->OnLanguageSelection();
break;
case IDC_EDIT_DEST_FOLDER: {
if (HIWORD(wparam) == EN_CHANGE) {
std::unique_ptr<wchar_t[]> buffer(new wchar_t[MAX_PATH]);
if (buffer.get()) {
UINT chars_count = GetDlgItemText(hdlg, IDC_EDIT_DEST_FOLDER,
buffer.get(), MAX_PATH - 1);
base::FilePath new_path(buffer.get());
if (chars_count == 0 && IsWindowEnabled(GetDlgItem(hdlg, IDOK)))
EnableWindow(GetDlgItem(hdlg, IDOK), FALSE);
else if (chars_count > 0 &&
!IsWindowEnabled(GetDlgItem(hdlg, IDOK)))
EnableWindow(GetDlgItem(hdlg, IDOK), TRUE);
InstallType installed_type;
if (IsVivaldiInstalled(new_path, &installed_type)) {
SetDlgItemText(
hdlg, IDC_SYSLINK_TOS,
TXT_TOS_ACCEPT_AND_UPDATE); // TODO(jarle) localize
SetDlgItemText(
hdlg, IDOK,
TXT_BTN_ACCEPT_AND_UPDATE); // TODO(jarle) localize
ShowWindow(GetDlgItem(hdlg, IDC_STATIC_WARN), SW_SHOW);
// If not standalone install selected, override current.
if (this_->install_type_ != INSTALL_STANDALONE) {
this_->install_type_ = installed_type;
ComboBox_SetCurSel(GetDlgItem(hdlg, IDC_COMBO_INSTALLTYPES),
this_->install_type_);
}
this_->UpdateRegisterCheckboxVisibility();
} else {
this_->is_upgrade_ = false;
SetDlgItemText(
hdlg, IDC_SYSLINK_TOS,
TXT_TOS_ACCEPT_AND_INSTALL); // TODO(jarle) localize
SetDlgItemText(
hdlg, IDOK,
TXT_BTN_ACCEPT_AND_INSTALL); // TODO(jarle) localize
EnableWindow(GetDlgItem(hdlg, IDC_COMBO_INSTALLTYPES),
TRUE); // TODO(jarle) VB-1612
ShowWindow(GetDlgItem(hdlg, IDC_STATIC_WARN), SW_HIDE);
}
}
}
} break;
}
break;
}
return (INT_PTR)FALSE;
}
} // namespace installer
| 33.61651 | 79 | 0.649032 | [
"vector"
] |
b5045381c32eca98511b346d76b62e29e186f599 | 8,051 | hpp | C++ | src/Util/ThreadPool.hpp | allen-cell-animated/medyan | 0b5ef64fb338c3961673361e5632980617937ee6 | [
"BSD-4-Clause-UC"
] | null | null | null | src/Util/ThreadPool.hpp | allen-cell-animated/medyan | 0b5ef64fb338c3961673361e5632980617937ee6 | [
"BSD-4-Clause-UC"
] | null | null | null | src/Util/ThreadPool.hpp | allen-cell-animated/medyan | 0b5ef64fb338c3961673361e5632980617937ee6 | [
"BSD-4-Clause-UC"
] | null | null | null | #ifndef MEDYAN_Util_ThreadPool_hpp
#define MEDYAN_Util_ThreadPool_hpp
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef> // size_t
#include <functional>
#include <future>
#include <memory> // unique_ptr
#include <mutex>
#include <ostream>
#include <queue>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
// IMPORTANT
// THIS IMPLEMENTATION OF THREAD POOL IS CURRENTLY NOT USED IN THE MAIN CODE
//
// The implementation for thread pooling in MEDYAN.
//
// Purpose: Increase performance by running computational-heavy work on
// multiple threads (possibly multiple processor cores). Thread pooling helps
// balance work loads according to the avaiable processors, and reduces
// the overhead of creating/destroying threads.
//
// Interface:
// - The thread pool should be globally accessible in MEDYAN, so all the
// interface functions must be thread-safe.
// - Can push tasks to the queue.
// - Can obtain the return value via a future.
// - Can explicitly wait for specific tasks to complete.
// - Tasks waiting for other tasks can work on pending tasks.
// - Can terminate running tasks (via setting and polling shared states).
//
// Possible Additional Features
// [ ] priority queues
// [ ] thread idle/contention stats and recommendations
// [ ] automatic load balancing
//
// Notes:
// - The thread vector is not thread-safe, so no interface is provided for
// managing the number of threads.
class ThreadPool {
private:
// An implementation of function wrapper to store movable objects
// It can be also used to store additional task information
class FuncWrapper_ {
private:
struct Base_ {
virtual ~Base_() = default;
virtual void operator()() = 0;
};
template< typename F >
struct Concrete_ : Base_ {
F f;
Concrete_(F&& f) : f(std::move(f)) {}
void operator()() { f(); }
};
public:
// Default and move constructor
FuncWrapper_() = default;
FuncWrapper_(FuncWrapper_&&) = default;
// Constructor from callable
template< typename F >
FuncWrapper_(F&& f) : f_(new Concrete_<F>(std::forward<F>(f))) {}
// Move assignment operator
FuncWrapper_& operator=(FuncWrapper_&&) = default;
void operator()() const { (*f_)(); }
private:
std::unique_ptr< Base_ > f_;
};
// Wrapper of std::thread to allow for storing meta data of the working thread
class WorkingThread_ {
private:
using TimePoint_ = std::chrono::time_point<std::chrono::steady_clock>;
template< typename IntegralType >
struct ScopeCounter_ {
std::atomic< IntegralType >& c;
ScopeCounter_(std::atomic< IntegralType >& c) : c(c) { ++c; }
~ScopeCounter_() { --c; }
};
struct ScopeTimer_ {
double& t;
TimePoint_ start;
ScopeTimer_(double& t) : t(t), start(std::chrono::steady_clock::now()) {}
~ScopeTimer_() {
using namespace std::chrono;
t += duration_cast<duration<double>>(steady_clock::now() - start).count();
}
};
public:
WorkingThread_(ThreadPool* whichPool) :
t_(&WorkingThread_::work_, this, whichPool),
timeInit_(std::chrono::steady_clock::now())
{}
WorkingThread_(WorkingThread_&&) = default;
~WorkingThread_() { t_.join(); }
// Accessors (could be non-thread-safe)
auto getTimeInit() const { return timeInit_; }
auto getDurWork() const { return durWork_; }
private:
// Working thread
// Note:
// - The thread pool must ensure that it outlives all the working threads.
void work_(ThreadPool* p) {
while(true) {
FuncWrapper_ f;
bool queuePopped = false;
{
std::unique_lock< std::mutex > lk(p->meQueue_);
p->cvWork_.wait(
lk,
[&] {
queuePopped = p->tryPop_(f);
return queuePopped || p->done_;
}
);
}
if(p->done_) return;
if(queuePopped) {
ScopeCounter_<int> sc(p->numWorkingThreads_);
ScopeTimer_ st(durWork_);
f();
}
}
}
std::thread t_;
// Time measurements
TimePoint_ timeInit_; // should not be changed after initialization, to make it thread-safe
double durWork_ = 0.0; // Total duration for working, in seconds
};
struct UsageStats_ {
double totalUpTime = 0.0;
double totalWorkTime = 0.0;
double timeUsageRate = 0.0;
};
public:
// Constructor
ThreadPool(std::size_t numThreads) {
// Create working threads
threads_.reserve(numThreads);
for(int i = 0; i < numThreads; ++i) {
threads_.emplace_back(this);
}
}
// Destructor
~ThreadPool() {
done_ = true;
cvWork_.notify_all();
}
// Submit a new task
//
// Note:
// - When arguments include references or pointers, it is the caller's
// job to ensure that the ref or ptr is valid when the job is running.
template< typename F, typename... Args >
auto submit(F&& f, Args&&... args) {
using ReturnType = std::result_of_t< F(Args...) >;
// Create a task containing the callable and the arguments
std::packaged_task< ReturnType() > task(
std::bind(std::forward<F>(f), std::forward<Args>(args)...) // C++20: change to perfect forwarding lambda
);
auto res = task.get_future();
{
std::lock_guard< std::mutex > guard(meQueue_);
queue_.push(
[task{std::move(task)}]() mutable { task(); }
);
}
cvWork_.notify_one();
return res;
}
// Accessors
auto numThreads() const noexcept { return threads_.size(); }
auto numWorkingThreads() const noexcept { return numWorkingThreads_.load(); }
auto numIdleThreads() const noexcept { return numThreads() - numWorkingThreads(); }
auto numTasks() {
std::lock_guard< std::mutex > guard(meQueue_);
return queue_.size();
}
auto getUsageStats() {
using namespace std::chrono;
UsageStats_ res;
const auto curTime = steady_clock::now();
{
std::lock_guard< std::mutex > guard(meThreads_);
for(const auto& t : threads_) {
res.totalUpTime += duration_cast<duration<double>>(curTime - t.getTimeInit()).count();
res.totalWorkTime += t.getDurWork();
}
}
if(res.totalUpTime) {
res.timeUsageRate = res.totalWorkTime / res.totalUpTime;
}
return res;
}
private:
// Utility function for popping the queue:
// If the queue is empty, then return false
// Else return true and the popped value is written in the parameter x
//
// Note:
// - This function is NOT thread-safe
bool tryPop_(FuncWrapper_& x) {
if(queue_.empty()) return false;
x = std::move(queue_.front());
queue_.pop();
return true;
}
// Member variables
//---------------------------------
// Note: The ordering of the following elements is important
std::atomic_bool done_ {false};
std::condition_variable cvWork_;
std::mutex meQueue_;
std::mutex meThreads_;
std::queue< FuncWrapper_ > queue_; // not thread-safe
std::vector< WorkingThread_ > threads_; // not thread-safe
// Stats
std::atomic_int numWorkingThreads_ {0};
};
#endif
| 29.490842 | 116 | 0.571482 | [
"vector"
] |
b50aebcfca03df244d4c59b42c677c3aa16139d5 | 4,914 | cpp | C++ | heart/src/render/hPipelineStateDesc.cpp | JoJo2nd/Heart | 4b50dfa6cbf87d32768f6c01b578bc1b23c18591 | [
"BSD-3-Clause"
] | 1 | 2016-05-14T09:22:26.000Z | 2016-05-14T09:22:26.000Z | heart/src/render/hPipelineStateDesc.cpp | JoJo2nd/Heart | 4b50dfa6cbf87d32768f6c01b578bc1b23c18591 | [
"BSD-3-Clause"
] | null | null | null | heart/src/render/hPipelineStateDesc.cpp | JoJo2nd/Heart | 4b50dfa6cbf87d32768f6c01b578bc1b23c18591 | [
"BSD-3-Clause"
] | null | null | null | /********************************************************************
Written by James Moran
Please see the file HEART_LICENSE.txt in the source's root directory.
*********************************************************************/
#include "render/hPipelineStateDesc.h"
#include "base/hMemoryUtil.h"
#include "base/hStringUtil.h"
#include "render/hRenderer.h"
#include "render/hProgramReflectionInfo.h"
namespace Heart {
namespace hRenderer {
hPipelineStateDescBase::hPipelineStateDescBase() {
clearDescription();
}
void hPipelineStateDescBase::clearDescription() {
for (auto& s : samplerStates_) {
s.name_ = hStringID();
s.sampler_ = hSamplerStateDesc();
}
hZeroMem(vertexLayout_, sizeof(vertexLayout_));
for (auto& v : vertexLayout_) {
v.bindPoint_ = hStringID();
}
blend_ = hBlendStateDesc();
depthStencil_ = hDepthStencilStateDesc();
rasterizer_ = hRasterizerStateDesc();
indexBuffer_ = nullptr;
vertexBuffer_ = nullptr;
vertex_ = nullptr;
fragment_ = nullptr;
}
void hPipelineStateDescBase::setSampler(hStringID name, const hSamplerStateDesc& ssd) {
for (auto& s : samplerStates_) {
if (s.name_==name) {
s.sampler_=ssd;
return;
} else if (s.name_.is_default()) {
s.name_=name;
s.sampler_=ssd;
return;
}
}
hcAssertFailMsg("Too many sampler states");
}
void hPipelineStateDescBase::setVertexBufferLayout(hVertexBufferLayout* layout, hUint count) {
hcAssert(count < vertexLayoutMax_);
vertexLayoutCount = count;
hMemCpy(vertexLayout_, layout, count*sizeof(hVertexBufferLayout));
}
hInputStateDescBase::hInputStateDescBase() {
clearDescription();
}
void hInputStateDescBase::clearDescription() {
for (auto& t : textureSlots_) {
t.name_ = hStringID();
t.t1D_ = nullptr;
t.texType_ = 0;
}
for (auto& u : uniformBuffers_) {
u.name_ = hStringID();
}
}
void hInputStateDescBase::setTextureSlot(hStringID name, hTexture1D* tex) {
for (auto& t : textureSlots_) {
if (t.name_ == name) {
t.t1D_ = tex;
t.texType_ = 1;
return;
}
else if (t.name_.is_default()) {
t.name_ = name;
t.t1D_ = tex;
t.texType_ = 1;
return;
}
}
hcAssertFailMsg("Too many textures bound");
}
void hInputStateDescBase::setTextureSlotWithOverride(hStringID name, hTexture2D* tex, hUint32 override_slot) {
for (auto& t : textureSlots_) {
if (t.name_ == name) {
t.t2D_ = tex;
t.texType_ = 2;
t.overrideSlot = override_slot;
return;
} else if (t.name_.is_default()) {
t.name_ = name;
t.t2D_ = tex;
t.texType_ = 2;
t.overrideSlot = override_slot;
return;
}
}
hcAssertFailMsg("Too many textures bound");
}
void hInputStateDescBase::setTextureSlot(hStringID name, hTexture3D* tex) {
for (auto& t : textureSlots_) {
if (t.name_ == name) {
t.t3D_ = tex;
t.texType_ = 3;
return;
}
else if (t.name_.is_default()) {
t.name_ = name;
t.t3D_ = tex;
t.texType_ = 3;
return;
}
}
hcAssertFailMsg("Too many textures bound");
}
void hInputStateDescBase::setTextureSlot(hStringID tex_name, hTexture2D* t) {
setTextureSlotWithOverride(tex_name, t, ~0UL);
}
void hInputStateDescBase::setUniformBuffer(hStringID name, const hUniformBuffer* ub) {
for (auto& t : uniformBuffers_) {
if (t.name_ == name) {
t.ub_ = ub;
return;
}
else if (t.name_.is_default()) {
t.name_ = name;
t.ub_ = ub;
return;
}
}
}
bool hInputStateDesc::findNamedParameter(const hChar* pname, hUint* outindex, hUint* outoffset, hUint* outsize, ShaderParamType* outtype) const {
const hChar* fieldname = hStrChr(pname, '.');
if (fieldname) {
++fieldname;
}
else {
fieldname = pname;
}
for (hUint i = 0, n = uniformBufferMax_; i < n && !uniformBuffers_[i].name_.is_default(); ++i) {
hUint count;
auto* layout = hRenderer::getUniformBufferLayoutInfo(uniformBuffers_[i].ub_, &count);
for (hUint loi = 0, lon = count; loi < lon; ++loi) {
if (hStrCmp(layout[loi].fieldName, fieldname) == 0) {
*outindex = i;
*outoffset = layout[loi].dataOffset;
*outsize = getParameterTypeByteSize(layout[loi].type);
*outtype = layout[loi].type;
if (*outsize == -1) {
return false;
}
return true;
}
}
}
return false;
}
}
}
| 28.08 | 145 | 0.56105 | [
"render"
] |
b515213c33630a6b2b036cbb2b0ecf8e4a12be3e | 3,343 | cc | C++ | packages/legacycomponents/mcstas2/lib/share/ref-lib.cc | mcvine/mcvine | 42232534b0c6af729628009bed165cd7d833789d | [
"BSD-3-Clause"
] | 5 | 2017-01-16T03:59:47.000Z | 2020-06-23T02:54:19.000Z | packages/legacycomponents/mcstas2/lib/share/ref-lib.cc | mcvine/mcvine | 42232534b0c6af729628009bed165cd7d833789d | [
"BSD-3-Clause"
] | 293 | 2015-10-29T17:45:52.000Z | 2022-01-07T16:31:09.000Z | packages/legacycomponents/mcstas2/lib/share/ref-lib.cc | mcvine/mcvine | 42232534b0c6af729628009bed165cd7d833789d | [
"BSD-3-Clause"
] | 1 | 2019-05-25T00:53:31.000Z | 2019-05-25T00:53:31.000Z | /****************************************************************************
*
* McStas, neutron ray-tracing package
* Copyright 1997-2006, All rights reserved
* Risoe National Laboratory, Roskilde, Denmark
* Institut Laue Langevin, Grenoble, France
*
* Library: share/ref-lib.c
*
* %Identification
* Written by: Peter Christiansen
* Date: August, 2006
* Origin: RISOE
* Release: McStas 1.10
* Version: $Revision$
*
* Commonly used reflection functions are declared in this file which
* are used by some guide and mirror components.
*
* Variable names have prefix 'mc_ref_' for 'McStas Reflection'
* to avoid conflicts
*
* Usage: within SHARE
* %include "ref-lib"
*
****************************************************************************/
#ifndef REF_LIB_H
#include "ref-lib.h"
#endif
#ifndef READ_TABLE_LIB_H
#include "read_table-lib.h"
#include "read_table-lib.cc"
#endif
/****************************************************************************
* void StdReflecFunc(double q, double *par, double *r)
*
* The McStas standard analytic parametrization of the reflectivity.
* The parameters are:
* R0: [1] Low-angle reflectivity
* Qc: [AA-1] Critical scattering vector
* alpha: [AA] Slope of reflectivity
* m: [1] m-value of material. Zero means completely absorbing.
* W: [AA-1] Width of supermirror cut-off
*****************************************************************************/
void StdReflecFunc(double mc_pol_q, double *mc_pol_par, double *mc_pol_r) {
double R0 = mc_pol_par[0];
double Qc = mc_pol_par[1];
double alpha = mc_pol_par[2];
double m = mc_pol_par[3];
double W = mc_pol_par[4];
double beta = 0;
mc_pol_q = fabs(mc_pol_q);
double arg;
/* Simpler parametrization from Henrik Jacobsen uses these values that depend on m only.
double m_value=m*0.9853+0.1978;
double W=-0.0002*m_value+0.0022;
double alpha=0.2304*m_value+5.0944;
double beta=-7.6251*m_value+68.1137;
If W and alpha are set to 0, use Henrik's approach for estimating these parameters
and apply the formulation:
arg = R0*0.5*(1-tanh(arg))*(1-alpha*(q-Qc)+beta*(q-Qc)*(q-Qc));
*/
if (W==0 && alpha==0) {
m=m*0.9853+0.1978;
W=-0.0002*m+0.0022;
alpha=0.2304*m+5.0944;
beta=-7.6251*m+68.1137;
if (m<=3) {
alpha=m;
beta=0;
}
}
arg = W > 0 ? (mc_pol_q - m*Qc)/W : 11;
if (arg > 10 || m <= 0 || Qc <=0 || R0 <= 0) {
*mc_pol_r = 0;
return;
}
if (m < 1) { Qc *= m; m=1; }
if(mc_pol_q <= Qc) {
*mc_pol_r = R0;
return;
}
*mc_pol_r = R0*0.5*(1 - tanh(arg))*(1 - alpha*(mc_pol_q - Qc) + beta*(mc_pol_q - Qc)*(mc_pol_q - Qc));
return;
}
/****************************************************************************
* void TableReflecFunc(double q, t_Table *par, double *r) {
*
* Looks up the reflectivity in a table using the routines in read_table-lib.
*****************************************************************************/
void TableReflecFunc(double mc_pol_q, t_Table *mc_pol_par, double *mc_pol_r) {
*mc_pol_r = Table_Value(*mc_pol_par, mc_pol_q, 1);
if(*mc_pol_r>1)
*mc_pol_r = 1;
return;
}
/* end of ref-lib.c */
| 29.848214 | 106 | 0.532456 | [
"vector"
] |
dddfdb1cc03bf9ea95b07e50c11b4e1d1e507a0b | 21,582 | cc | C++ | tests/syntax_highlighter_test.cc | kev0960/md2 | f8480b664b1111f3f5d4b5202fb2b5db3ee434bd | [
"MIT"
] | 5 | 2021-01-27T03:55:00.000Z | 2022-03-07T02:35:37.000Z | tests/syntax_highlighter_test.cc | kev0960/md2 | f8480b664b1111f3f5d4b5202fb2b5db3ee434bd | [
"MIT"
] | null | null | null | tests/syntax_highlighter_test.cc | kev0960/md2 | f8480b664b1111f3f5d4b5202fb2b5db3ee434bd | [
"MIT"
] | null | null | null | #include "generators/asm_syntax_highlighter.h"
#include "generators/cpp_syntax_highlighter.h"
#include "generators/generator_context.h"
#include "generators/objdump_highlighter.h"
#include "generators/py_syntax_highlighter.h"
#include "generators/rust_syntax_highlighter.h"
#include "gtest/gtest.h"
#include "logger.h"
#include "metadata_repo.h"
namespace md2 {
namespace {
std::string TokenTypeToString(SyntaxTokenType type) {
switch (type) {
case KEYWORD:
return "KEYWORD";
case TYPE_KEYWORD:
return "TYPE_KEYWORD";
case IDENTIFIER:
return "IDENTIFIER";
case NUMERIC_LITERAL:
return "NUMERIC_LITERAL";
case STRING_LITERAL:
return "STRING_LITERAL";
case BRACKET:
return "BRACKET";
case PARENTHESES:
return "PARENTHESES";
case BRACE:
return "BRACE";
case PUNCTUATION:
return "PUNCTUATION";
case OPERATOR:
return "OPERATOR";
case COMMENT:
return "COMMENT";
case MACRO_HEAD:
return "MACRO_HEAD";
case MACRO_BODY:
return "MACRO_BODY";
case WHITESPACE:
return "WHITESPACE";
case FUNCTION:
return "FUNCTION";
case BUILT_IN:
return "BUILT_IN";
case MAGIC_FUNCTION:
return "MAGIC_FUNCTION";
case REGISTER:
return "REGISTER";
case LABEL:
return "LABEL";
case DIRECTIVE:
return "DIRECTIVE";
case INSTRUCTION:
return "INSTRUCTION";
case FUNCTION_SECTION:
return "FUNCTION_SECTION";
case LIFETIME:
return "LIFETIME";
case NONE:
return "NONE";
}
return "";
}
} // namespace
template <typename Highlighter>
class SyntaxHighlighterTester {
public:
SyntaxHighlighterTester()
: fake_context_(repo_, "", /*use_clang_server=*/false, /*clang_server_port=*/0, nullptr) {}
void CheckSyntaxTokens(std::vector<SyntaxToken> expected) {
const std::vector<SyntaxToken>& actual =
static_cast<Highlighter*>(this)->GetTokenList();
EXPECT_EQ(actual.size(), expected.size());
for (size_t i = 0; i < std::min(actual.size(), expected.size()); i++) {
if (i < actual.size() && i < actual.size()) {
EXPECT_EQ(TokenTypeToString(actual[i].token_type),
TokenTypeToString(expected[i].token_type));
EXPECT_EQ(actual[i].token_start, expected[i].token_start);
EXPECT_EQ(actual[i].token_end, expected[i].token_end);
}
}
}
void PrintTokens() {
const std::vector<SyntaxToken>& token_list =
static_cast<Highlighter*>(this)->GetTokenList();
for (size_t i = 0; i < token_list.size(); i++) {
LOG(0) << TokenTypeToString(token_list[i].token_type);
LOG(0) << " [" << token_list[i].token_start << " , "
<< token_list[i].token_end << "]";
}
}
GeneratorContext fake_context_;
MetadataRepo repo_;
};
class MockSyntaxHighlighter
: public CppSyntaxHighlighter,
public SyntaxHighlighterTester<MockSyntaxHighlighter> {
public:
MockSyntaxHighlighter(std::string_view content)
: CppSyntaxHighlighter(content, "cpp") {}
};
class MockPySyntaxHighlighter
: public PySyntaxHighlighter,
public SyntaxHighlighterTester<MockPySyntaxHighlighter> {
public:
MockPySyntaxHighlighter(std::string_view content)
: PySyntaxHighlighter(content, "py") {}
};
TEST(SyntaxHighlightTest, CppMacro) {
MockSyntaxHighlighter syn("#include <iostream>");
syn.ParseCode();
syn.CheckSyntaxTokens(
{{MACRO_HEAD, 0, 8}, {WHITESPACE, 8, 9}, {MACRO_BODY, 9, 19}});
MockSyntaxHighlighter syn2("#define SOME_FUNC(X, X) \\\nX*X\n");
syn2.ParseCode();
syn2.CheckSyntaxTokens({{MACRO_HEAD, 0, 7},
{WHITESPACE, 7, 9},
{MACRO_BODY, 9, 30},
{WHITESPACE, 30, 31}});
}
TEST(SyntaxHighlightTest, CppMacroComplex) {
MockSyntaxHighlighter syn2("#ifdef AAAA\nhi;\n#endif");
syn2.ParseCode();
syn2.CheckSyntaxTokens({{MACRO_HEAD, 0, 6},
{WHITESPACE, 6, 7},
{MACRO_BODY, 7, 11},
{WHITESPACE, 11, 12},
{IDENTIFIER, 12, 14},
{PUNCTUATION, 14, 15},
{WHITESPACE, 15, 16},
{MACRO_HEAD, 16, 22}});
}
TEST(SyntaxHighlightTest, StringLiterals) {
MockSyntaxHighlighter syn("'a';'b';");
syn.ParseCode();
syn.CheckSyntaxTokens({{STRING_LITERAL, 0, 3},
{PUNCTUATION, 3, 4},
{STRING_LITERAL, 4, 7},
{PUNCTUATION, 7, 8}});
}
TEST(SyntaxHighlightTest, StringLiterals2) {
MockSyntaxHighlighter syn2(R"(string s = "hi \"asdf";)");
syn2.ParseCode();
syn2.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 6},
{WHITESPACE, 6, 7},
{IDENTIFIER, 7, 8},
{WHITESPACE, 8, 9},
{OPERATOR, 9, 10},
{WHITESPACE, 10, 11},
{STRING_LITERAL, 11, 22},
{PUNCTUATION, 22, 23}});
}
TEST(SyntaxHighlightTest, StringLiterals3) {
MockSyntaxHighlighter syn3(R"test(string s = R"(some"") \ \ a)";)test");
syn3.ParseCode();
syn3.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 6},
{WHITESPACE, 6, 7},
{IDENTIFIER, 7, 8},
{WHITESPACE, 8, 9},
{OPERATOR, 9, 10},
{WHITESPACE, 10, 11},
{IDENTIFIER, 11, 12},
{STRING_LITERAL, 12, 29},
{PUNCTUATION, 29, 30}});
MockSyntaxHighlighter syn4(
R"test(string s = R"abc(some")")" \ \ a)abc";)test");
syn4.ParseCode();
syn4.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 6},
{WHITESPACE, 6, 7},
{IDENTIFIER, 7, 8},
{WHITESPACE, 8, 9},
{OPERATOR, 9, 10},
{WHITESPACE, 10, 11},
{IDENTIFIER, 11, 12},
{STRING_LITERAL, 12, 37},
{PUNCTUATION, 37, 38}});
}
TEST(SyntaxHighlightTest, CppNumerals) {
MockSyntaxHighlighter syn("int a = -123;");
syn.ParseCode();
syn.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 5},
{WHITESPACE, 5, 6},
{OPERATOR, 6, 7},
{WHITESPACE, 7, 8},
{OPERATOR, 8, 9},
{NUMERIC_LITERAL, 9, 12},
{PUNCTUATION, 12, 13}});
MockSyntaxHighlighter syn2("float a = 1.2f;");
syn2.ParseCode();
syn2.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 5},
{WHITESPACE, 5, 6},
{IDENTIFIER, 6, 7},
{WHITESPACE, 7, 8},
{OPERATOR, 8, 9},
{WHITESPACE, 9, 10},
{NUMERIC_LITERAL, 10, 14},
{PUNCTUATION, 14, 15}});
MockSyntaxHighlighter syn3("float a = .1E4f;");
syn3.ParseCode();
syn3.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 5},
{WHITESPACE, 5, 6},
{IDENTIFIER, 6, 7},
{WHITESPACE, 7, 8},
{OPERATOR, 8, 9},
{WHITESPACE, 9, 10},
{NUMERIC_LITERAL, 10, 15},
{PUNCTUATION, 15, 16}});
MockSyntaxHighlighter syn4("float a = 0x10.1p0;");
syn4.ParseCode();
syn4.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 5},
{WHITESPACE, 5, 6},
{IDENTIFIER, 6, 7},
{WHITESPACE, 7, 8},
{OPERATOR, 8, 9},
{WHITESPACE, 9, 10},
{NUMERIC_LITERAL, 10, 18},
{PUNCTUATION, 18, 19}});
MockSyntaxHighlighter syn5("float a = 123.456e-67;");
syn5.ParseCode();
syn5.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 5},
{WHITESPACE, 5, 6},
{IDENTIFIER, 6, 7},
{WHITESPACE, 7, 8},
{OPERATOR, 8, 9},
{WHITESPACE, 9, 10},
{NUMERIC_LITERAL, 10, 21},
{PUNCTUATION, 21, 22}});
}
TEST(SyntaxHighlightTest, CppStatements) {
MockSyntaxHighlighter syn(R"(int a;if(a+1>3){a++;})");
syn.ParseCode();
syn.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 5},
{PUNCTUATION, 5, 6},
{KEYWORD, 6, 8},
{PARENTHESES, 8, 9},
{IDENTIFIER, 9, 10},
{OPERATOR, 10, 11},
{NUMERIC_LITERAL, 11, 12},
{OPERATOR, 12, 13},
{NUMERIC_LITERAL, 13, 14},
{PARENTHESES, 14, 15},
{BRACE, 15, 16},
{IDENTIFIER, 16, 17},
{OPERATOR, 17, 19},
{PUNCTUATION, 19, 20},
{BRACE, 20, 21}});
}
TEST(SyntaxHighlightTest, CppComments) {
MockSyntaxHighlighter syn("abc; // Do something\ndef;");
syn.ParseCode();
syn.CheckSyntaxTokens({{IDENTIFIER, 0, 3},
{PUNCTUATION, 3, 4},
{WHITESPACE, 4, 5},
{COMMENT, 5, 20},
{WHITESPACE, 20, 21},
{IDENTIFIER, 21, 24},
{PUNCTUATION, 24, 25}});
MockSyntaxHighlighter syn2("abc; /* this is some comment */ asdf;");
syn2.ParseCode();
syn2.CheckSyntaxTokens({{IDENTIFIER, 0, 3},
{PUNCTUATION, 3, 4},
{WHITESPACE, 4, 5},
{COMMENT, 5, 31},
{WHITESPACE, 31, 32},
{IDENTIFIER, 32, 36},
{PUNCTUATION, 36, 37}});
}
TEST(SyntaxHighlightTest, FunctionTest) {
MockSyntaxHighlighter syn("int x = str.length()");
syn.ParseCode();
syn.CheckSyntaxTokens({{TYPE_KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 5},
{WHITESPACE, 5, 6},
{OPERATOR, 6, 7},
{WHITESPACE, 7, 8},
{IDENTIFIER, 8, 11},
{OPERATOR, 11, 12},
{FUNCTION, 12, 18},
{PARENTHESES, 18, 20}});
MockSyntaxHighlighter syn2("int x ( a ) {}");
syn2.ParseCode();
syn2.CheckSyntaxTokens({
{TYPE_KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{FUNCTION, 4, 5},
{WHITESPACE, 5, 6},
{PARENTHESES, 6, 7},
{WHITESPACE, 7, 8},
{IDENTIFIER, 8, 9},
{WHITESPACE, 9, 10},
{PARENTHESES, 10, 11},
{WHITESPACE, 11, 12},
{BRACE, 12, 14},
});
}
TEST(PySyntaxHighlightTest, BuiltInTest) {
MockPySyntaxHighlighter syn("for i in range(x):");
syn.ParseCode();
syn.CheckSyntaxTokens({{KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 5},
{WHITESPACE, 5, 6},
{KEYWORD, 6, 8},
{WHITESPACE, 8, 9},
{BUILT_IN, 9, 14},
{PARENTHESES, 14, 15},
{IDENTIFIER, 15, 16},
{PARENTHESES, 16, 17},
{OPERATOR, 17, 18}});
}
TEST(PySyntaxHighlightTest, PyComment) {
MockPySyntaxHighlighter syn("print(a) # Comment\nprint(c)");
syn.ParseCode();
syn.CheckSyntaxTokens({{BUILT_IN, 0, 5},
{PARENTHESES, 5, 6},
{IDENTIFIER, 6, 7},
{PARENTHESES, 7, 8},
{WHITESPACE, 8, 9},
{COMMENT, 9, 18},
{WHITESPACE, 18, 19},
{BUILT_IN, 19, 24},
{PARENTHESES, 24, 25},
{IDENTIFIER, 25, 26},
{PARENTHESES, 26, 27}});
}
TEST(PySyntaxHighlightTest, PyLongString) {
MockPySyntaxHighlighter syn("''' this is long string'''\nprint(a)");
syn.ParseCode();
syn.CheckSyntaxTokens({{STRING_LITERAL, 0, 26},
{WHITESPACE, 26, 27},
{BUILT_IN, 27, 32},
{PARENTHESES, 32, 33},
{IDENTIFIER, 33, 34},
{PARENTHESES, 34, 35}});
}
TEST(PySyntaxHighlightTest, PyMagicFunction) {
MockPySyntaxHighlighter syn("def __init__(self):");
syn.ParseCode();
syn.CheckSyntaxTokens({{KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{MAGIC_FUNCTION, 4, 12},
{PARENTHESES, 12, 13},
{KEYWORD, 13, 17},
{PARENTHESES, 17, 18},
{OPERATOR, 18, 19}});
}
TEST(PySyntaxHighlightTest, PyBuiltIn2) {
MockPySyntaxHighlighter syn("return ord('0')");
syn.ParseCode();
syn.CheckSyntaxTokens({{KEYWORD, 0, 6},
{WHITESPACE, 6, 7},
{BUILT_IN, 7, 10},
{PARENTHESES, 10, 11},
{STRING_LITERAL, 11, 14},
{PARENTHESES, 14, 15}});
}
class MockAsmSyntaxHighlighter
: public AsmSyntaxHighlighter,
public SyntaxHighlighterTester<MockAsmSyntaxHighlighter> {
public:
MockAsmSyntaxHighlighter(std::string_view content)
: AsmSyntaxHighlighter(fake_context_, content, "asm") {}
};
TEST(AsmSyntaxHighlighter, LabelTest) {
MockAsmSyntaxHighlighter syn(R"(label1:
label2:
label3:)");
syn.ParseCode();
syn.CheckSyntaxTokens({{LABEL, 0, 7},
{WHITESPACE, 7, 8},
{LABEL, 8, 15},
{WHITESPACE, 15, 16},
{LABEL, 16, 23}});
}
TEST(AsmSyntaxHighlighter, InstructionTest) {
MockAsmSyntaxHighlighter syn(R"(func1:
mov eax, ebp)");
syn.ParseCode();
syn.CheckSyntaxTokens({
{LABEL, 0, 6},
{WHITESPACE, 6, 7},
{INSTRUCTION, 7, 10},
{WHITESPACE, 10, 11},
{REGISTER, 11, 14},
{PUNCTUATION, 14, 15},
{WHITESPACE, 15, 16},
{REGISTER, 16, 19},
});
}
TEST(AsmSyntaxHighlighter, RegisterName) {
MockAsmSyntaxHighlighter syn(R"(mov 0x0(%rip),%eax)");
syn.ParseCode();
syn.CheckSyntaxTokens({
{INSTRUCTION, 0, 3},
{WHITESPACE, 3, 7},
{NUMERIC_LITERAL, 7, 10},
{BRACKET, 10, 11},
{REGISTER, 11, 15},
{BRACKET, 15, 16},
{PUNCTUATION, 16, 17},
{REGISTER, 17, 21},
});
}
TEST(AsmSyntaxHighlighter, RegisterAndIdentifier) {
MockAsmSyntaxHighlighter syn(R"(mov BYTE PTR data[rbx-1], al)");
syn.ParseCode();
syn.CheckSyntaxTokens({
{INSTRUCTION, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 8},
{WHITESPACE, 8, 9},
{IDENTIFIER, 9, 12},
{WHITESPACE, 12, 13},
{IDENTIFIER, 13, 17},
{BRACKET, 17, 18},
{REGISTER, 18, 21},
{OPERATOR, 21, 22},
{NUMERIC_LITERAL, 22, 23},
{BRACKET, 23, 24},
{PUNCTUATION, 24, 25},
{WHITESPACE, 25, 26},
{REGISTER, 26, 28},
});
MockAsmSyntaxHighlighter syn2("imul rax, rax, 1374389535");
syn2.ParseCode();
syn2.CheckSyntaxTokens({{INSTRUCTION, 0, 4},
{WHITESPACE, 4, 5},
{REGISTER, 5, 8},
{PUNCTUATION, 8, 9},
{WHITESPACE, 9, 10},
{REGISTER, 10, 13},
{PUNCTUATION, 13, 14},
{WHITESPACE, 14, 15},
{NUMERIC_LITERAL, 15, 25}});
}
TEST(AsmSyntaxHighlighter, Directive) {
MockAsmSyntaxHighlighter syn("jne .L2");
syn.ParseCode();
syn.CheckSyntaxTokens({
{INSTRUCTION, 0, 3},
{WHITESPACE, 3, 4},
{DIRECTIVE, 4, 7},
});
}
class MockObjdumpHighlighter
: public ObjdumpHighlighter,
public SyntaxHighlighterTester<MockObjdumpHighlighter> {
public:
MockObjdumpHighlighter(std::string_view content)
: ObjdumpHighlighter(fake_context_, content, "objdump") {}
};
TEST(ObjdumpHighlighter, FunctionSection) {
MockObjdumpHighlighter syn("0000000000001290 <__libc_csu_fini>:");
syn.ParseCode();
syn.CheckSyntaxTokens({
{NUMERIC_LITERAL, 0, 16},
{WHITESPACE, 16, 17},
{FUNCTION_SECTION, 17, 35},
});
}
TEST(ObjdumpHighlighter, InstructionSection) {
MockObjdumpHighlighter syn(
" 1294: 48 83 ec 08 sub $0x8,%rsp");
syn.ParseCode();
syn.CheckSyntaxTokens({
{WHITESPACE, 0, 4},
{NUMERIC_LITERAL, 4, 9},
{WHITESPACE, 9, 16},
{NUMERIC_LITERAL, 16, 18},
{WHITESPACE, 18, 19},
{NUMERIC_LITERAL, 19, 21},
{WHITESPACE, 21, 22},
{NUMERIC_LITERAL, 22, 24},
{WHITESPACE, 24, 25},
{NUMERIC_LITERAL, 25, 27},
{WHITESPACE, 27, 40},
{INSTRUCTION, 40, 43},
{WHITESPACE, 43, 47},
{NUMERIC_LITERAL, 47, 51},
{PUNCTUATION, 51, 52},
{REGISTER, 52, 56},
});
}
TEST(ObjdumpHighlighter, InstructionSection2) {
MockObjdumpHighlighter syn(R"(
objdump -S s.o
s.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <_Z4funcv>:
0: f3 0f 1e fa endbr64
4: 55 push %rbp
5: 48 89 e5 mov %rsp,%rbp
8: 90 nop
9: 5d pop %rbp
a: c3 retq
000000000000000b <_ZL5func2v>:
b: f3 0f 1e fa endbr64
f: 55 push %rbp
10: 48 89 e5 mov %rsp,%rbp
13: 90 nop
14: 5d pop %rbp
15: c3 retq
)");
syn.ParseCode();
}
class MockRustSyntaxHighlighter
: public RustSyntaxHighlighter,
public SyntaxHighlighterTester<MockRustSyntaxHighlighter> {
public:
MockRustSyntaxHighlighter(std::string_view content)
: RustSyntaxHighlighter(content, "rust") {}
};
TEST(RustSyntaxHighlighter, Comment) {
MockRustSyntaxHighlighter syn("abc // some comment\nnext");
syn.ParseCode();
syn.CheckSyntaxTokens({
{IDENTIFIER, 0, 3},
{WHITESPACE, 3, 4},
{COMMENT, 4, 19},
{WHITESPACE, 19, 20},
{IDENTIFIER, 20, 24},
});
}
TEST(RustSyntaxHighlighter, RawString) {
MockRustSyntaxHighlighter syn(R"(let a = r#"raw """"#;)");
syn.ParseCode();
syn.CheckSyntaxTokens({
{KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 5},
{WHITESPACE, 5, 6},
{OPERATOR, 6, 7},
{WHITESPACE, 7, 8},
{STRING_LITERAL, 8, 20},
{PUNCTUATION, 20, 21},
});
}
TEST(RustSyntaxHighlighter, RegularString) {
MockRustSyntaxHighlighter syn(R"(let a = "somestring";)");
syn.ParseCode();
syn.CheckSyntaxTokens({
{KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 5},
{WHITESPACE, 5, 6},
{OPERATOR, 6, 7},
{WHITESPACE, 7, 8},
{STRING_LITERAL, 8, 20},
{PUNCTUATION, 20, 21},
});
}
TEST(RustSyntaxHighlighter, RegularStringWithEscaped) {
MockRustSyntaxHighlighter syn(R"(let a = "some\"ring";)");
syn.ParseCode();
syn.CheckSyntaxTokens({
{KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 5},
{WHITESPACE, 5, 6},
{OPERATOR, 6, 7},
{WHITESPACE, 7, 8},
{STRING_LITERAL, 8, 20},
{PUNCTUATION, 20, 21},
});
}
TEST(RustSyntaxHighlighter, Lifetime) {
MockRustSyntaxHighlighter syn(R"(pub fn func<T:'static>(&mut self) -> T {})");
syn.ParseCode();
syn.CheckSyntaxTokens({
{KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{KEYWORD, 4, 6},
{WHITESPACE, 6, 7},
{IDENTIFIER, 7, 11},
{OPERATOR, 11, 12},
{IDENTIFIER, 12, 13},
{OPERATOR, 13, 14},
{LIFETIME, 14, 21},
{OPERATOR, 21, 22},
{PARENTHESES, 22, 23},
{OPERATOR, 23, 24},
{KEYWORD, 24, 27},
{WHITESPACE, 27, 28},
{KEYWORD, 28, 32},
{PARENTHESES, 32, 33},
{WHITESPACE, 33, 34},
{OPERATOR, 34, 36},
{WHITESPACE, 36, 37},
{IDENTIFIER, 37, 38},
{WHITESPACE, 38, 39},
{BRACE, 39, 41},
});
}
TEST(RustSyntaxHighlighter, Char) {
MockRustSyntaxHighlighter syn(R"(let a = 'c';)");
syn.ParseCode();
syn.CheckSyntaxTokens({
{KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 5},
{WHITESPACE, 5, 6},
{OPERATOR, 6, 7},
{WHITESPACE, 7, 8},
{STRING_LITERAL, 8, 11},
{PUNCTUATION, 11, 12},
});
}
TEST(RustSyntaxHighlighter, TypeKeyword) {
MockRustSyntaxHighlighter syn(R"(let a: u64 = 12)");
syn.ParseCode();
syn.CheckSyntaxTokens({
{KEYWORD, 0, 3},
{WHITESPACE, 3, 4},
{IDENTIFIER, 4, 5},
{OPERATOR, 5, 6},
{WHITESPACE, 6, 7},
{TYPE_KEYWORD, 7, 10},
{WHITESPACE, 10, 11},
{OPERATOR, 11, 12},
{WHITESPACE, 12, 13},
{NUMERIC_LITERAL, 13, 15},
});
}
} // namespace md2
| 31.369186 | 97 | 0.509499 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.