hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa8e712b7b0e6b54a17e5b31de3357c0df06dd91 | 1,488 | cpp | C++ | sha3/main.cpp | skapix/sha3 | 6cbec1d0cf6eebe3ce4182da303d70c741cae30c | [
"MIT"
] | 7 | 2018-11-21T20:33:05.000Z | 2022-03-21T16:47:33.000Z | sha3/main.cpp | skapix/sha3 | 6cbec1d0cf6eebe3ce4182da303d70c741cae30c | [
"MIT"
] | null | null | null | sha3/main.cpp | skapix/sha3 | 6cbec1d0cf6eebe3ce4182da303d70c741cae30c | [
"MIT"
] | 4 | 2018-08-30T14:17:45.000Z | 2021-12-03T23:54:39.000Z | #include <iostream>
#include <fstream>
#include <vector>
#include <cassert>
#include <cstdint>
#include <CLI/CLI.hpp>
#include "util.h"
#include "sha3_cpu.h"
#include "sha3_gpu.h"
template<typename T>
std::vector<uint8_t> doCalculation(std::istream &is, size_t digestSize, size_t bufSize)
{
T s(digestSize);
std::vector<uint8_t> data;
data.resize(bufSize);
while (true)
{
is.read(reinterpret_cast<char *>(data.data()), data.size());
std::streamsize nread = is.gcount();
assert(nread >= 0);
if (nread == 0)
{
break;
}
s.add(data.data(), static_cast<size_t>(nread));
}
return s.digest();
}
int main(int argc, const char *argv[])
{
size_t digestSize = 512;
std::string inputFile;
bool isGpu = false;
CLI::App app("SHA3 hash calculation");
app.add_set("-d,--digest", digestSize, {224, 256, 384, 512}, "Digest length", true);
app.add_option("input", inputFile, "File to calculate SHA3")->check(CLI::ExistingFile);
app.add_flag("-g,--gpu", isGpu, "Calculate SHA3 hash usign gpu");
CLI11_PARSE(app, argc, argv);
std::ifstream f(inputFile, std::ifstream::binary);
if (!f.is_open())
{
std::cerr << "Can't open file " << argv[1] << std::endl;
return 1;
}
size_t size = 1024 * 1024;
std::vector<uint8_t> digest;
if (isGpu)
{
digest = doCalculation<SHA3_gpu>(f, digestSize, size);
}
else
{
digest = doCalculation<SHA3_cpu>(f, digestSize, size);
}
std::cout << digest << std::endl;
}
| 21.882353 | 89 | 0.638441 | skapix |
aa8f09e170bee1bcb8708673be76fff5cccd3c10 | 57 | cpp | C++ | src/stb_image.cpp | MickAlmighty/StudyOpenGL | aebebc9e89cca5a00569e7c5876045e36eed0c3b | [
"MIT"
] | null | null | null | src/stb_image.cpp | MickAlmighty/StudyOpenGL | aebebc9e89cca5a00569e7c5876045e36eed0c3b | [
"MIT"
] | null | null | null | src/stb_image.cpp | MickAlmighty/StudyOpenGL | aebebc9e89cca5a00569e7c5876045e36eed0c3b | [
"MIT"
] | null | null | null | #define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" | 28.5 | 34 | 0.824561 | MickAlmighty |
aa955910105940546d3c77a4ed6a0647aec689f1 | 3,373 | cpp | C++ | src/autowiring/CoreThreadMac.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | src/autowiring/CoreThreadMac.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | src/autowiring/CoreThreadMac.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z | // Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "BasicThread.h"
#include "BasicThreadStateBlock.h"
#include <pthread.h>
#include <libproc.h>
#include <mach/thread_info.h>
#include <mach/thread_act.h>
#include <sys/proc_info.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <pthread.h>
#include THREAD_HEADER
// Missing definitions from pthreads.h
#if !defined(PTHREAD_MIN_PRIORITY)
#define PTHREAD_MIN_PRIORITY 0
#endif
#if !defined(PTHREAD_MAX_PRIORITY)
#define PTHREAD_MAX_PRIORITY 63
#endif
using std::chrono::milliseconds;
using std::chrono::nanoseconds;
void BasicThread::SetCurrentThreadName(void) const {
pthread_setname_np(m_name);
}
std::chrono::steady_clock::time_point BasicThread::GetCreationTime(void) {
return std::chrono::steady_clock::time_point::min();
}
void BasicThread::GetThreadTimes(std::chrono::milliseconds& kernelTime, std::chrono::milliseconds& userTime) {
// Obtain the thread port from the Unix pthread wrapper
pthread_t pthread = m_state->m_thisThread.native_handle();
thread_t threadport = pthread_mach_thread_np(pthread);
// Now use the Mac thread type to obtain the kernel thread handle
thread_identifier_info_data_t identifier_info;
mach_msg_type_number_t tident_count = THREAD_IDENTIFIER_INFO_COUNT;
thread_info(threadport, THREAD_IDENTIFIER_INFO, (thread_info_t) &identifier_info, &tident_count);
// Finally, we can obtain the actual thread times the user wants to know about
proc_threadinfo info;
proc_pidinfo(getpid(), PROC_PIDTHREADINFO, identifier_info.thread_handle, &info, sizeof(info));
// User time is in ns increments
kernelTime = std::chrono::duration_cast<milliseconds>(nanoseconds(info.pth_system_time));
userTime = std::chrono::duration_cast<milliseconds>(nanoseconds(info.pth_user_time));
}
void BasicThread::SetThreadPriority(const std::thread::native_handle_type& handle, ThreadPriority threadPriority, SchedulingPolicy schedPolicy) {
struct sched_param param = { 0 };
int policy;
int percent = 0;
switch (schedPolicy) {
case SchedulingPolicy::StandardRoundRobin:
policy = SCHED_OTHER;
break;
case SchedulingPolicy::RealtimeFIFO:
policy = SCHED_FIFO;
break;
case SchedulingPolicy::RealtimeRoundRobin:
policy = SCHED_RR;
break;
default:
throw std::invalid_argument("Attempted to assign an unrecognized scheduling policy");
break;
}
switch (threadPriority) {
case ThreadPriority::Idle:
percent = 0;
break;
case ThreadPriority::Lowest:
percent = 1;
break;
case ThreadPriority::BelowNormal:
percent = 20;
break;
case ThreadPriority::Normal:
case ThreadPriority::Default:
percent = 50;
break;
case ThreadPriority::AboveNormal:
percent = 66;
break;
case ThreadPriority::Highest:
percent = 83;
break;
case ThreadPriority::TimeCritical:
percent = 99;
break;
case ThreadPriority::Multimedia:
percent = 100;
break;
default:
throw std::invalid_argument("Attempted to assign an unrecognized thread priority");
}
int prev_policy;
pthread_getschedparam(handle, &prev_policy, ¶m);
param.sched_priority = PTHREAD_MIN_PRIORITY + (percent*(PTHREAD_MAX_PRIORITY - PTHREAD_MIN_PRIORITY) + 50) / 100;
pthread_setschedparam(handle, policy, ¶m);
}
| 30.944954 | 145 | 0.752149 | CaseyCarter |
aa95867ef96c61515f5499d55034234deded6767 | 230 | cpp | C++ | 3rdparty/build_opencv-4.5.2/modules/core/test/test_intrin128.avx512_skx.cpp | LordOfTheUnicorn/trdrop | 6da4bf1528878e90cf14232dfb4adeec3458ee0f | [
"MIT"
] | null | null | null | 3rdparty/build_opencv-4.5.2/modules/core/test/test_intrin128.avx512_skx.cpp | LordOfTheUnicorn/trdrop | 6da4bf1528878e90cf14232dfb4adeec3458ee0f | [
"MIT"
] | 7 | 2021-05-24T22:57:32.000Z | 2021-08-23T05:32:30.000Z | 3rdparty/build_opencv-4.5.2/modules/core/test/test_intrin128.ssse3.cpp | LordOfTheUnicorn/trdrop | 6da4bf1528878e90cf14232dfb4adeec3458ee0f | [
"MIT"
] | null | null | null |
#include "/Users/unicorn1343/Documents/GitHub/trdrop/3rdParty/opencv-4.5.2/modules/core/test/test_precomp.hpp"
#include "/Users/unicorn1343/Documents/GitHub/trdrop/3rdParty/opencv-4.5.2/modules/core/test/test_intrin128.simd.hpp"
| 57.5 | 117 | 0.817391 | LordOfTheUnicorn |
aa9ccf96cd9a53939bba1cd4e5e5c7e3d4490733 | 2,977 | hpp | C++ | libs/core/render/include/bksge/core/render/inl/texture_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/render/include/bksge/core/render/inl/texture_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/render/include/bksge/core/render/inl/texture_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file texture_inl.hpp
*
* @brief Texture の実装
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_RENDER_INL_TEXTURE_INL_HPP
#define BKSGE_CORE_RENDER_INL_TEXTURE_INL_HPP
#include <bksge/core/render/texture.hpp>
#include <bksge/fnd/memory/make_shared.hpp>
#include <bksge/fnd/assert.hpp>
#include <bksge/fnd/config.hpp>
#include <cstddef>
#include <cstdint>
namespace bksge
{
namespace render
{
BKSGE_INLINE
Texture::Texture(void)
: m_format(TextureFormat::kUndefined)
, m_extent(0, 0)
, m_mipmap_count(0)
, m_pixels(bksge::make_shared<Pixels>())
{}
BKSGE_INLINE
Texture::Texture(
TextureFormat format,
ExtentType const& extent,
std::size_t mipmap_count,
std::uint8_t const* src)
: m_format(format)
, m_extent(extent)
, m_mipmap_count(mipmap_count)
, m_pixels(bksge::make_shared<Pixels>())
{
BKSGE_ASSERT(format != TextureFormat::kUndefined);
BKSGE_ASSERT(extent.width() >= 1u);
BKSGE_ASSERT(extent.height() >= 1u);
BKSGE_ASSERT(mipmap_count >= 1u);
auto const bytes = GetMipmappedSizeInBytes(format, extent.width(), extent.height(), mipmap_count);
BKSGE_ASSERT(bytes >= 1u);
m_pixels->resize(bytes);
if (src)
{
m_pixels->copy(src, bytes);
}
}
BKSGE_INLINE
Texture::Texture(TextureFormat format, ExtentType const& extent, std::size_t mipmap_count)
: Texture(format, extent, mipmap_count, nullptr)
{}
BKSGE_INLINE
Texture::Texture(TextureFormat format, ExtentType const& extent, std::uint8_t const* src)
: Texture(format, extent, 1, src)
{}
BKSGE_INLINE
Texture::Texture(TextureFormat format, ExtentType const& extent)
: Texture(format, extent, 1, nullptr)
{}
BKSGE_INLINE
TextureFormat Texture::format(void) const
{
return m_format;
}
BKSGE_INLINE
auto Texture::extent(void) const
-> ExtentType const&
{
return m_extent;
}
BKSGE_INLINE
std::uint32_t Texture::width(void) const
{
return extent().width();
}
BKSGE_INLINE
std::uint32_t Texture::height(void) const
{
return extent().height();
}
BKSGE_INLINE
std::size_t Texture::mipmap_count(void) const
{
return m_mipmap_count;
}
BKSGE_INLINE
std::size_t Texture::stride(void) const
{
return GetStrideInBytes(format(), width());
}
BKSGE_INLINE
std::uint8_t const* Texture::data(void) const
{
BKSGE_ASSERT(m_pixels != nullptr);
return m_pixels->data();
}
BKSGE_INLINE
auto Texture::pixels(void) const
-> Pixels const&
{
BKSGE_ASSERT(m_pixels != nullptr);
return *m_pixels;
}
BKSGE_INLINE
bool operator==(Texture const& lhs, Texture const& rhs)
{
return
lhs.format() == rhs.format() &&
lhs.extent() == rhs.extent() &&
lhs.mipmap_count() == rhs.mipmap_count() &&
lhs.pixels() == rhs.pixels();
}
BKSGE_INLINE
bool operator!=(Texture const& lhs, Texture const& rhs)
{
return !(lhs == rhs);
}
} // namespace render
} // namespace bksge
#endif // BKSGE_CORE_RENDER_INL_TEXTURE_INL_HPP
| 20.114865 | 100 | 0.689956 | myoukaku |
aaa0dbc846b98e467f10b4031a968212b5c1ab91 | 1,054 | cpp | C++ | src/JImage.cpp | jildertviet/ofxJVisuals | 878c5b0e7a7dda49ddb71b3f5d19c13987706a73 | [
"MIT"
] | null | null | null | src/JImage.cpp | jildertviet/ofxJVisuals | 878c5b0e7a7dda49ddb71b3f5d19c13987706a73 | [
"MIT"
] | 6 | 2021-10-16T07:10:04.000Z | 2021-12-26T13:23:54.000Z | src/JImage.cpp | jildertviet/ofxJVisuals | 878c5b0e7a7dda49ddb71b3f5d19c13987706a73 | [
"MIT"
] | null | null | null | //
// Image.cpp
// Bas
//
// Created by Jildert Viet on 18-03-16.
//
//
#include "JImage.hpp"
JImage::JImage(string filename, ofVec2f loc){
this->loc = loc;
setType("JImage");
bLoadSucces = loadImage(filename);
colors[0] = ofColor(255,255);
}
void JImage::display(){
if(!bLoadSucces)
return;
ofSetColor(colors[0]);
ofPushMatrix();
ofTranslate(loc);
if(zoom != 1.0){
ofTranslate(size.x * 0.5, size.y * 0.5);
ofScale(zoom);
ofTranslate(size.x * -0.5, size.y * -0.5);
}
switch(drawMode){
case DEFAULT:
image.draw(0, 0, size.x, size.y);
break;
}
ofPopMatrix();
}
void JImage::specificFunction(){
}
bool JImage::loadImage(string path){
image.clear();
if(image.load(path)){
cout << "Image " << path << " loaded" << endl;
size = glm::vec2(image.getWidth(), image.getHeight());
return true;
} else{
return false;
}
}
| 19.518519 | 63 | 0.510436 | jildertviet |
aaa30d9fb2ce3aae39446a6b72d2bbb40b24d528 | 9,370 | cc | C++ | Mozc-for-iOS/src/renderer/renderer_style_handler.cc | spanfish/JapaneseKeyboard | 84fa7ef799d145fb9897b6e86bc7bc50610ccb2b | [
"Apache-2.0"
] | 33 | 2015-01-21T09:50:21.000Z | 2022-02-12T15:18:25.000Z | Mozc-for-iOS/src/renderer/renderer_style_handler.cc | spanfish/JapaneseKeyboard | 84fa7ef799d145fb9897b6e86bc7bc50610ccb2b | [
"Apache-2.0"
] | 1 | 2019-03-08T08:07:14.000Z | 2019-03-08T08:07:14.000Z | Mozc-for-iOS/src/renderer/renderer_style_handler.cc | spanfish/JapaneseKeyboard | 84fa7ef799d145fb9897b6e86bc7bc50610ccb2b | [
"Apache-2.0"
] | 8 | 2015-06-08T15:57:25.000Z | 2019-05-15T08:52:58.000Z | // Copyright 2010-2014, Google Inc.
// 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 Google Inc. 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 "renderer/renderer_style_handler.h"
#if defined(OS_WIN)
#include <windows.h>
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _WTL_NO_AUTOMATIC_NAMESPACE
// Workaround against KB813540
#include <atlbase_mozc.h>
#include <atlapp.h>
#include <atlgdi.h>
#endif // OS_WIN
#include "base/singleton.h"
#include "renderer/renderer_style.pb.h"
namespace mozc {
namespace renderer {
namespace {
#if defined(OS_WIN)
const int kDefaultDPI = 96;
#endif // OS_WIN
class RendererStyleHandlerImpl {
public:
RendererStyleHandlerImpl();
~RendererStyleHandlerImpl() {}
bool GetRendererStyle(RendererStyle *style);
bool SetRendererStyle(const RendererStyle &style);
void GetDefaultRendererStyle(RendererStyle *style);
private:
RendererStyle style_;
};
RendererStyleHandlerImpl *GetRendererStyleHandlerImpl() {
return Singleton<RendererStyleHandlerImpl>::get();
}
RendererStyleHandlerImpl::RendererStyleHandlerImpl() {
RendererStyle style;
GetDefaultRendererStyle(&style);
SetRendererStyle(style);
}
bool RendererStyleHandlerImpl::GetRendererStyle(RendererStyle *style) {
style->CopyFrom(this->style_);
return true;
}
bool RendererStyleHandlerImpl::SetRendererStyle(const RendererStyle &style) {
style_.CopyFrom(style);
return true;
}
void RendererStyleHandlerImpl::GetDefaultRendererStyle(
RendererStyle *style) {
double scale_factor_x = 1.0;
double scale_factor_y = 1.0;
RendererStyleHandler::GetDPIScalingFactor(&scale_factor_x,
&scale_factor_y);
// TODO(horo):Change to read from human-readable ASCII format protobuf.
style->Clear();
style->set_window_border(1); // non-scalable
style->set_scrollbar_width(4 * scale_factor_x);
style->set_row_rect_padding(0 * scale_factor_x);
style->mutable_border_color()->set_r(0x96);
style->mutable_border_color()->set_g(0x96);
style->mutable_border_color()->set_b(0x96);
RendererStyle::TextStyle *shortcutStyle = style->add_text_styles();
shortcutStyle->set_font_size(14 * scale_factor_y);
shortcutStyle->mutable_foreground_color()->set_r(0x77);
shortcutStyle->mutable_foreground_color()->set_g(0x77);
shortcutStyle->mutable_foreground_color()->set_b(0x77);
shortcutStyle->mutable_background_color()->set_r(0xf3);
shortcutStyle->mutable_background_color()->set_g(0xf4);
shortcutStyle->mutable_background_color()->set_b(0xff);
shortcutStyle->set_left_padding(8 * scale_factor_x);
shortcutStyle->set_right_padding(8 * scale_factor_x);
RendererStyle::TextStyle *gap1Style = style->add_text_styles();
gap1Style->set_font_size(14 * scale_factor_y);
RendererStyle::TextStyle *candidateStyle = style->add_text_styles();
candidateStyle->set_font_size(14 * scale_factor_y);
RendererStyle::TextStyle *descriptionStyle = style->add_text_styles();
descriptionStyle->set_font_size(12 * scale_factor_y);
descriptionStyle->mutable_foreground_color()->set_r(0x88);
descriptionStyle->mutable_foreground_color()->set_g(0x88);
descriptionStyle->mutable_foreground_color()->set_b(0x88);
descriptionStyle->set_right_padding(8 * scale_factor_x);
// We want to ensure that the candidate window is at least wide
// enough to render "そのほかの文字種 " as a candidate.
style->set_column_minimum_width_string(
"\xE3\x81\x9D\xE3\x81\xAE\xE3\x81\xBB\xE3\x81\x8B\xE3\x81\xAE"
"\xE6\x96\x87\xE5\xAD\x97\xE7\xA8\xAE ");
style->mutable_footer_style()->set_font_size(14 * scale_factor_y);
style->mutable_footer_style()->set_left_padding(4 * scale_factor_x);
style->mutable_footer_style()->set_right_padding(4 * scale_factor_x);
RendererStyle::TextStyle *footer_sub_label_style =
style->mutable_footer_sub_label_style();
footer_sub_label_style->set_font_size(10 * scale_factor_y);
footer_sub_label_style->mutable_foreground_color()->set_r(167);
footer_sub_label_style->mutable_foreground_color()->set_g(167);
footer_sub_label_style->mutable_foreground_color()->set_b(167);
footer_sub_label_style->set_left_padding(4 * scale_factor_x);
footer_sub_label_style->set_right_padding(4 * scale_factor_x);
RendererStyle::RGBAColor *color = style->add_footer_border_colors();
color->set_r(96);
color->set_r(96);
color->set_r(96);
style->mutable_footer_top_color()->set_r(0xff);
style->mutable_footer_top_color()->set_g(0xff);
style->mutable_footer_top_color()->set_b(0xff);
style->mutable_footer_bottom_color()->set_r(0xee);
style->mutable_footer_bottom_color()->set_g(0xee);
style->mutable_footer_bottom_color()->set_b(0xee);
style->set_logo_file_name("candidate_window_logo.tiff");
style->mutable_focused_background_color()->set_r(0xd1);
style->mutable_focused_background_color()->set_g(0xea);
style->mutable_focused_background_color()->set_b(0xff);
style->mutable_focused_border_color()->set_r(0x7f);
style->mutable_focused_border_color()->set_g(0xac);
style->mutable_focused_border_color()->set_b(0xdd);
style->mutable_scrollbar_background_color()->set_r(0xe0);
style->mutable_scrollbar_background_color()->set_g(0xe0);
style->mutable_scrollbar_background_color()->set_b(0xe0);
style->mutable_scrollbar_indicator_color()->set_r(0x75);
style->mutable_scrollbar_indicator_color()->set_g(0x90);
style->mutable_scrollbar_indicator_color()->set_b(0xb8);
RendererStyle::InfolistStyle *infostyle = style->mutable_infolist_style();
// "用例"
infostyle->set_caption_string("\xE7\x94\xA8\xE4\xBE\x8B");
infostyle->set_caption_height(20 * scale_factor_y);
infostyle->set_caption_padding(1);
infostyle->mutable_caption_style()->set_font_size(12 * scale_factor_y);
infostyle->mutable_caption_style()->set_left_padding(2 * scale_factor_x);
infostyle->mutable_caption_background_color()->set_r(0xec);
infostyle->mutable_caption_background_color()->set_g(0xf0);
infostyle->mutable_caption_background_color()->set_b(0xfa);
infostyle->set_window_border(1); // non-scalable
infostyle->set_row_rect_padding(2 * scale_factor_x);
infostyle->set_window_width(300 * scale_factor_x);
infostyle->mutable_title_style()->set_font_size(15 * scale_factor_y);
infostyle->mutable_title_style()->set_left_padding(5 * scale_factor_x);
infostyle->mutable_description_style()->set_font_size(12 * scale_factor_y);
infostyle->mutable_description_style()->set_left_padding(
15 * scale_factor_x);
infostyle->mutable_border_color()->set_r(0x96);
infostyle->mutable_border_color()->set_g(0x96);
infostyle->mutable_border_color()->set_b(0x96);
infostyle->mutable_focused_background_color()->set_r(0xd1);
infostyle->mutable_focused_background_color()->set_g(0xea);
infostyle->mutable_focused_background_color()->set_b(0xff);
infostyle->mutable_focused_border_color()->set_r(0x7f);
infostyle->mutable_focused_border_color()->set_g(0xac);
infostyle->mutable_focused_border_color()->set_b(0xdd);
}
} // namespace
bool RendererStyleHandler::GetRendererStyle(RendererStyle *style) {
return GetRendererStyleHandlerImpl()->GetRendererStyle(style);
}
bool RendererStyleHandler::SetRendererStyle(const RendererStyle &style) {
return GetRendererStyleHandlerImpl()->SetRendererStyle(style);
}
void RendererStyleHandler::GetDefaultRendererStyle(RendererStyle *style) {
return GetRendererStyleHandlerImpl()->GetDefaultRendererStyle(style);
}
void RendererStyleHandler::GetDPIScalingFactor(double *x, double *y) {
#if defined OS_WIN
WTL::CDC desktop_dc(::GetDC(NULL));
const int dpi_x = desktop_dc.GetDeviceCaps(LOGPIXELSX);
const int dpi_y = desktop_dc.GetDeviceCaps(LOGPIXELSY);
if (x != NULL) {
*x = static_cast<double>(dpi_x) / kDefaultDPI;
}
if (y != NULL) {
*y = static_cast<double>(dpi_y) / kDefaultDPI;
}
#else
if (x != NULL) {
*x = 1.0;
}
if (y != NULL) {
*y = 1.0;
}
#endif
}
} // namespace renderer
} // namespace mozc
| 39.87234 | 77 | 0.768303 | spanfish |
aaa4ca36ed97af433734728240dc8aea930980f2 | 21,101 | cpp | C++ | src/planner/planners/MatchVariableLengthPatternIndexScanPlanner.cpp | nevermore3/nebula-graph | 6f24438289c2b20575bc6acdf607cd2a3648d30d | [
"Apache-2.0"
] | null | null | null | src/planner/planners/MatchVariableLengthPatternIndexScanPlanner.cpp | nevermore3/nebula-graph | 6f24438289c2b20575bc6acdf607cd2a3648d30d | [
"Apache-2.0"
] | null | null | null | src/planner/planners/MatchVariableLengthPatternIndexScanPlanner.cpp | nevermore3/nebula-graph | 6f24438289c2b20575bc6acdf607cd2a3648d30d | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "planner/planners/MatchVariableLengthPatternIndexScanPlanner.h"
#include <folly/String.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include "common/base/Status.h"
#include "common/expression/ConstantExpression.h"
#include "common/expression/ContainerExpression.h"
#include "common/expression/Expression.h"
#include "common/expression/FunctionCallExpression.h"
#include "common/expression/LabelAttributeExpression.h"
#include "common/expression/PathBuildExpression.h"
#include "common/expression/PropertyExpression.h"
#include "common/expression/RelationalExpression.h"
#include "common/expression/SubscriptExpression.h"
#include "common/expression/VertexExpression.h"
#include "parser/Clauses.h"
#include "parser/MatchSentence.h"
#include "planner/Logic.h"
#include "planner/Planner.h"
#include "planner/planners/MatchSolver.h"
#include "util/ExpressionUtils.h"
#include "validator/MatchValidator.h"
#include "visitor/RewriteMatchLabelVisitor.h"
using nebula::storage::cpp2::EdgeProp;
using nebula::storage::cpp2::VertexProp;
using PNKind = nebula::graph::PlanNode::Kind;
using EdgeInfo = nebula::graph::MatchValidator::EdgeInfo;
using NodeInfo = nebula::graph::MatchValidator::NodeInfo;
namespace nebula {
namespace graph {
std::unique_ptr<MatchVariableLengthPatternIndexScanPlanner>
MatchVariableLengthPatternIndexScanPlanner::make() {
return std::unique_ptr<MatchVariableLengthPatternIndexScanPlanner>(
new MatchVariableLengthPatternIndexScanPlanner());
}
bool MatchVariableLengthPatternIndexScanPlanner::match(AstContext *astCtx) {
return MatchSolver::match(astCtx);
}
StatusOr<SubPlan> MatchVariableLengthPatternIndexScanPlanner::transform(AstContext *astCtx) {
matchCtx_ = static_cast<MatchAstContext *>(astCtx);
SubPlan plan;
NG_RETURN_IF_ERROR(scanIndex(&plan));
NG_RETURN_IF_ERROR(combinePlans(&plan));
NG_RETURN_IF_ERROR(projectColumnsBySymbols(&plan));
NG_RETURN_IF_ERROR(MatchSolver::buildFilter(matchCtx_, &plan));
NG_RETURN_IF_ERROR(MatchSolver::buildReturn(matchCtx_, plan));
return plan;
}
static std::unique_ptr<std::vector<VertexProp>> genVertexProps() {
return std::make_unique<std::vector<VertexProp>>();
}
static std::unique_ptr<std::vector<EdgeProp>> genEdgeProps(const EdgeInfo &edge) {
auto edgeProps = std::make_unique<std::vector<EdgeProp>>();
if (edge.edgeTypes.empty()) {
return edgeProps;
}
for (auto edgeType : edge.edgeTypes) {
if (edge.direction == MatchValidator::Direction::IN_EDGE) {
edgeType = -edgeType;
} else if (edge.direction == MatchValidator::Direction::BOTH) {
EdgeProp edgeProp;
edgeProp.set_type(-edgeType);
edgeProps->emplace_back(std::move(edgeProp));
}
EdgeProp edgeProp;
edgeProp.set_type(edgeType);
edgeProps->emplace_back(std::move(edgeProp));
}
return edgeProps;
}
static Expression *getLastEdgeDstExprInLastPath(const std::string &colName) {
// expr: __Project_2[-1] => path
auto columnExpr = ExpressionUtils::inputPropExpr(colName);
// expr: endNode(path) => vn
auto args = std::make_unique<ArgumentList>();
args->addArgument(std::move(columnExpr));
auto fn = std::make_unique<std::string>("endNode");
auto endNode = std::make_unique<FunctionCallExpression>(fn.release(), args.release());
// expr: en[_dst] => dst vid
auto vidExpr = std::make_unique<ConstantExpression>(kVid);
return new AttributeExpression(endNode.release(), vidExpr.release());
}
static Expression *getFirstVertexVidInFistPath(const std::string &colName) {
// expr: __Project_2[0] => path
auto columnExpr = ExpressionUtils::inputPropExpr(colName);
// expr: startNode(path) => v1
auto args = std::make_unique<ArgumentList>();
args->addArgument(std::move(columnExpr));
auto fn = std::make_unique<std::string>("startNode");
auto firstVertexExpr = std::make_unique<FunctionCallExpression>(fn.release(), args.release());
// expr: v1[_vid] => vid
return new AttributeExpression(firstVertexExpr.release(), new ConstantExpression(kVid));
}
static Expression *mergePathColumnsExpr(const std::string &lcol, const std::string &rcol) {
auto expr = std::make_unique<PathBuildExpression>();
expr->add(ExpressionUtils::inputPropExpr(lcol));
expr->add(ExpressionUtils::inputPropExpr(rcol));
return expr.release();
}
static Expression *buildPathExpr() {
auto expr = std::make_unique<PathBuildExpression>();
expr->add(std::make_unique<VertexExpression>());
expr->add(std::make_unique<EdgeExpression>());
return expr.release();
}
Status MatchVariableLengthPatternIndexScanPlanner::combinePlans(SubPlan *finalPlan) {
auto &nodeInfos = matchCtx_->nodeInfos;
auto &edgeInfos = matchCtx_->edgeInfos;
DCHECK(!nodeInfos.empty());
if (edgeInfos.empty()) {
return appendFetchVertexPlan(nodeInfos.front().filter, finalPlan);
}
DCHECK_GT(nodeInfos.size(), edgeInfos.size());
SubPlan plan;
NG_RETURN_IF_ERROR(
filterDatasetByPathLength(nodeInfos[0], edgeInfos[0], finalPlan->root, &plan));
std::vector<std::string> joinColNames = {folly::stringPrintf("%s_%d", kPath, 0)};
for (size_t i = 1; i < edgeInfos.size(); ++i) {
SubPlan curr;
NG_RETURN_IF_ERROR(filterDatasetByPathLength(nodeInfos[i], edgeInfos[i], plan.root, &curr));
plan.root = joinDataSet(curr.root, plan.root);
joinColNames.emplace_back(folly::stringPrintf("%s_%lu", kPath, i));
plan.root->setColNames(joinColNames);
}
auto left = plan.root;
NG_RETURN_IF_ERROR(appendFetchVertexPlan(nodeInfos.back().filter, &plan));
finalPlan->root = joinDataSet(plan.root, left);
joinColNames.emplace_back(folly::stringPrintf("%s_%lu", kPath, edgeInfos.size()));
finalPlan->root->setColNames(joinColNames);
return Status::OK();
}
Status MatchVariableLengthPatternIndexScanPlanner::projectColumnsBySymbols(SubPlan *plan) {
auto qctx = matchCtx_->qctx;
auto &nodeInfos = matchCtx_->nodeInfos;
auto &edgeInfos = matchCtx_->edgeInfos;
auto columns = saveObject(new YieldColumns);
auto input = plan->root;
const auto &inColNames = input->colNamesRef();
DCHECK_EQ(inColNames.size(), nodeInfos.size());
std::vector<std::string> colNames;
auto addNode = [&, this](size_t i) {
auto &nodeInfo = nodeInfos[i];
if (nodeInfo.alias != nullptr && !nodeInfo.anonymous) {
columns->addColumn(buildVertexColumn(inColNames[i], *nodeInfo.alias));
colNames.emplace_back(*nodeInfo.alias);
}
};
for (size_t i = 0; i < edgeInfos.size(); i++) {
addNode(i);
auto &edgeInfo = edgeInfos[i];
if (edgeInfo.alias != nullptr && !edgeInfo.anonymous) {
columns->addColumn(buildEdgeColumn(i, inColNames[i]));
colNames.emplace_back(*edgeInfo.alias);
}
}
// last vertex
DCHECK(!nodeInfos.empty());
addNode(nodeInfos.size() - 1);
const auto &aliases = matchCtx_->aliases;
auto iter = std::find_if(aliases.begin(), aliases.end(), [](const auto &alias) {
return alias.second == MatchValidator::AliasType::kPath;
});
std::string alias = iter != aliases.end() ? iter->first : qctx->vctx()->anonColGen()->getCol();
columns->addColumn(buildPathColumn(alias, input));
colNames.emplace_back(alias);
auto project = Project::make(qctx, input, columns);
project->setColNames(std::move(colNames));
plan->root = filterCyclePath(project, alias);
return Status::OK();
}
Status MatchVariableLengthPatternIndexScanPlanner::scanIndex(SubPlan *plan) {
using IQC = nebula::storage::cpp2::IndexQueryContext;
IQC iqctx;
iqctx.set_filter(Expression::encode(*matchCtx_->scanInfo.filter));
auto contexts = std::make_unique<std::vector<IQC>>();
contexts->emplace_back(std::move(iqctx));
auto columns = std::make_unique<std::vector<std::string>>();
auto scan = IndexScan::make(matchCtx_->qctx,
nullptr,
matchCtx_->space.id,
std::move(contexts),
std::move(columns),
false,
matchCtx_->scanInfo.schemaId);
plan->tail = scan;
plan->root = scan;
// initialize start expression in project node
initialExpr_ = ExpressionUtils::newVarPropExpr(kVid);
return Status::OK();
}
PlanNode *MatchVariableLengthPatternIndexScanPlanner::joinDataSet(const PlanNode *right,
const PlanNode *left) {
auto &leftKey = left->colNamesRef().back();
auto &rightKey = right->colNamesRef().front();
auto buildExpr = getLastEdgeDstExprInLastPath(leftKey);
auto probeExpr = getFirstVertexVidInFistPath(rightKey);
auto join = DataJoin::make(matchCtx_->qctx,
const_cast<PlanNode *>(right),
{left->outputVar(), 0},
{right->outputVar(), 0},
{buildExpr},
{probeExpr});
std::vector<std::string> colNames = left->colNames();
const auto &rightColNames = right->colNamesRef();
colNames.insert(colNames.end(), rightColNames.begin(), rightColNames.end());
join->setColNames(std::move(colNames));
return join;
}
Status MatchVariableLengthPatternIndexScanPlanner::appendFetchVertexPlan(
const Expression *nodeFilter,
SubPlan *plan) {
auto qctx = matchCtx_->qctx;
extractAndDedupVidColumn(plan);
auto srcExpr = ExpressionUtils::inputPropExpr(kVid);
auto gv = GetVertices::make(qctx, plan->root, matchCtx_->space.id, srcExpr.release(), {}, {});
PlanNode *root = gv;
if (nodeFilter != nullptr) {
auto filter = nodeFilter->clone().release();
RewriteMatchLabelVisitor visitor([](const Expression *expr) {
DCHECK_EQ(expr->kind(), Expression::Kind::kLabelAttribute);
auto la = static_cast<const LabelAttributeExpression *>(expr);
return new AttributeExpression(new VertexExpression(), la->right()->clone().release());
});
filter->accept(&visitor);
root = Filter::make(matchCtx_->qctx, root, filter);
}
// normalize all columns to one
auto columns = saveObject(new YieldColumns);
auto pathExpr = std::make_unique<PathBuildExpression>();
pathExpr->add(std::make_unique<VertexExpression>());
columns->addColumn(new YieldColumn(pathExpr.release()));
plan->root = Project::make(qctx, root, columns);
plan->root->setColNames({kPath});
return Status::OK();
}
Status MatchVariableLengthPatternIndexScanPlanner::filterDatasetByPathLength(const NodeInfo &node,
const EdgeInfo &edge,
const PlanNode *input,
SubPlan *plan) {
auto qctx = matchCtx_->qctx;
SubPlan curr;
NG_RETURN_IF_ERROR(combineSubPlan(node, edge, input, &curr));
// filter rows whose edges number less than min hop
auto args = std::make_unique<ArgumentList>();
// expr: length(relationships(p)) >= minHop
auto pathExpr = ExpressionUtils::inputPropExpr(kPath);
args->addArgument(std::move(pathExpr));
auto fn = std::make_unique<std::string>("length");
auto edgeExpr = std::make_unique<FunctionCallExpression>(fn.release(), args.release());
auto minHop = edge.range == nullptr ? 1 : edge.range->min();
auto minHopExpr = std::make_unique<ConstantExpression>(minHop);
auto expr = std::make_unique<RelationalExpression>(
Expression::Kind::kRelGE, edgeExpr.release(), minHopExpr.release());
auto filter = Filter::make(qctx, curr.root, saveObject(expr.release()));
filter->setColNames(curr.root->colNames());
plan->root = filter;
plan->tail = curr.tail;
return Status::OK();
}
Status MatchVariableLengthPatternIndexScanPlanner::combineSubPlan(const NodeInfo &node,
const EdgeInfo &edge,
const PlanNode *input,
SubPlan *plan) {
SubPlan subplan;
NG_RETURN_IF_ERROR(expandStep(edge, input, node.filter, true, &subplan));
plan->tail = subplan.tail;
PlanNode *passThrough = subplan.root;
auto maxHop = edge.range ? edge.range->max() : 1;
for (int64_t i = 1; i < maxHop; ++i) {
SubPlan curr;
NG_RETURN_IF_ERROR(expandStep(edge, passThrough, nullptr, false, &curr));
auto rNode = subplan.root;
DCHECK(rNode->kind() == PNKind::kUnion || rNode->kind() == PNKind::kPassThrough);
NG_RETURN_IF_ERROR(collectData(passThrough, curr.root, rNode, &passThrough, &subplan));
}
plan->root = subplan.root;
return Status::OK();
}
// build subplan: Project->Dedup->GetNeighbors->[Filter]->Project
Status MatchVariableLengthPatternIndexScanPlanner::expandStep(const EdgeInfo &edge,
const PlanNode *input,
const Expression *nodeFilter,
bool needPassThrough,
SubPlan *plan) {
DCHECK(input != nullptr);
auto qctx = matchCtx_->qctx;
// Extract dst vid from input project node which output dataset format is: [v1,e1,...,vn,en]
SubPlan curr;
curr.root = const_cast<PlanNode *>(input);
extractAndDedupVidColumn(&curr);
auto gn = GetNeighbors::make(qctx, curr.root, matchCtx_->space.id);
auto srcExpr = ExpressionUtils::inputPropExpr(kVid);
gn->setSrc(srcExpr.release());
gn->setVertexProps(genVertexProps());
gn->setEdgeProps(genEdgeProps(edge));
gn->setEdgeDirection(edge.direction);
PlanNode *root = gn;
if (nodeFilter != nullptr) {
auto filter = nodeFilter->clone().release();
RewriteMatchLabelVisitor visitor([](const Expression *expr) {
DCHECK_EQ(expr->kind(), Expression::Kind::kLabelAttribute);
auto la = static_cast<const LabelAttributeExpression *>(expr);
return new AttributeExpression(new VertexExpression(), la->right()->clone().release());
});
filter->accept(&visitor);
auto filterNode = Filter::make(matchCtx_->qctx, root, filter);
filterNode->setColNames(root->colNames());
root = filterNode;
}
if (edge.filter != nullptr) {
RewriteMatchLabelVisitor visitor([](const Expression *expr) {
DCHECK_EQ(expr->kind(), Expression::Kind::kLabelAttribute);
auto la = static_cast<const LabelAttributeExpression *>(expr);
return new AttributeExpression(new EdgeExpression(), la->right()->clone().release());
});
auto filter = edge.filter->clone().release();
filter->accept(&visitor);
auto filterNode = Filter::make(qctx, root, filter);
filterNode->setColNames(root->colNames());
root = filterNode;
}
auto listColumns = saveObject(new YieldColumns);
listColumns->addColumn(new YieldColumn(buildPathExpr(), new std::string(kPath)));
root = Project::make(qctx, root, listColumns);
root->setColNames({kPath});
if (needPassThrough) {
auto pt = PassThroughNode::make(qctx, root);
pt->setColNames(root->colNames());
pt->setOutputVar(root->outputVar());
root = pt;
}
plan->root = root;
plan->tail = curr.tail;
return Status::OK();
}
Status MatchVariableLengthPatternIndexScanPlanner::collectData(const PlanNode *joinLeft,
const PlanNode *joinRight,
const PlanNode *inUnionNode,
PlanNode **passThrough,
SubPlan *plan) {
auto qctx = matchCtx_->qctx;
auto join = joinDataSet(joinRight, joinLeft);
auto lpath = folly::stringPrintf("%s_%d", kPath, 0);
auto rpath = folly::stringPrintf("%s_%d", kPath, 1);
join->setColNames({lpath, rpath});
plan->tail = join;
auto columns = saveObject(new YieldColumns);
auto listExpr = mergePathColumnsExpr(lpath, rpath);
columns->addColumn(new YieldColumn(listExpr));
auto project = Project::make(qctx, join, columns);
project->setColNames({kPath});
auto filter = filterCyclePath(project, kPath);
auto pt = PassThroughNode::make(qctx, filter);
pt->setOutputVar(filter->outputVar());
pt->setColNames({kPath});
auto uNode = Union::make(qctx, pt, const_cast<PlanNode *>(inUnionNode));
uNode->setColNames({kPath});
*passThrough = pt;
plan->root = uNode;
return Status::OK();
}
PlanNode *MatchVariableLengthPatternIndexScanPlanner::filterCyclePath(PlanNode *input,
const std::string &column) {
auto args = std::make_unique<ArgumentList>();
args->addArgument(ExpressionUtils::inputPropExpr(column));
auto fn = std::make_unique<std::string>("hasSameEdgeInPath");
auto fnCall = std::make_unique<FunctionCallExpression>(fn.release(), args.release());
auto falseConst = std::make_unique<ConstantExpression>(false);
auto cond = std::make_unique<RelationalExpression>(
Expression::Kind::kRelEQ, fnCall.release(), falseConst.release());
auto filter = Filter::make(matchCtx_->qctx, input, saveObject(cond.release()));
filter->setColNames(input->colNames());
return filter;
}
Expression *MatchVariableLengthPatternIndexScanPlanner::initialExprOrEdgeDstExpr(
const PlanNode *node) {
Expression *vidExpr = initialExpr_;
if (vidExpr != nullptr) {
initialExpr_ = nullptr;
} else {
vidExpr = getLastEdgeDstExprInLastPath(node->colNamesRef().back());
}
return vidExpr;
}
void MatchVariableLengthPatternIndexScanPlanner::extractAndDedupVidColumn(SubPlan *plan) {
auto qctx = matchCtx_->qctx;
auto columns = saveObject(new YieldColumns);
auto input = plan->root;
Expression *vidExpr = initialExprOrEdgeDstExpr(input);
columns->addColumn(new YieldColumn(vidExpr));
auto project = Project::make(qctx, input, columns);
project->setColNames({kVid});
auto dedup = Dedup::make(qctx, project);
dedup->setColNames({kVid});
plan->root = dedup;
}
YieldColumn *MatchVariableLengthPatternIndexScanPlanner::buildVertexColumn(
const std::string &colName,
const std::string &alias) const {
auto colExpr = ExpressionUtils::inputPropExpr(colName);
// startNode(path) => head node of path
auto args = std::make_unique<ArgumentList>();
args->addArgument(std::move(colExpr));
auto fn = std::make_unique<std::string>("startNode");
auto firstVertexExpr = std::make_unique<FunctionCallExpression>(fn.release(), args.release());
return new YieldColumn(firstVertexExpr.release(), new std::string(alias));
}
YieldColumn *MatchVariableLengthPatternIndexScanPlanner::buildEdgeColumn(
int colIdx,
const std::string &colName) const {
auto &edge = matchCtx_->edgeInfos[colIdx];
auto colExpr = ExpressionUtils::inputPropExpr(colName);
// relationships(p)
auto args = std::make_unique<ArgumentList>();
args->addArgument(std::move(colExpr));
auto fn = std::make_unique<std::string>("relationships");
auto relExpr = std::make_unique<FunctionCallExpression>(fn.release(), args.release());
Expression *expr = nullptr;
if (edge.range != nullptr) {
expr = relExpr.release();
} else {
// Get first edge in path list [e1, e2, ...]
auto idxExpr = std::make_unique<ConstantExpression>(0);
auto subExpr = std::make_unique<SubscriptExpression>(relExpr.release(), idxExpr.release());
expr = subExpr.release();
}
return new YieldColumn(expr, new std::string(*edge.alias));
}
YieldColumn *MatchVariableLengthPatternIndexScanPlanner::buildPathColumn(
const std::string &alias,
const PlanNode *input) const {
auto pathExpr = std::make_unique<PathBuildExpression>();
for (const auto &colName : input->colNamesRef()) {
pathExpr->add(ExpressionUtils::inputPropExpr(colName));
}
return new YieldColumn(pathExpr.release(), new std::string(alias));
}
} // namespace graph
} // namespace nebula
| 41.619329 | 100 | 0.648927 | nevermore3 |
aaa4e343a803b91d7be91c16c80b30a6aac9a633 | 2,742 | cpp | C++ | Arcane/src/Arcane/Platform/OpenGL/Framebuffer/GBuffer.cpp | flygod1159/Arcane-Engine | bfb95cc6734a25e5737d4195c2b9e92e03117707 | [
"MIT"
] | 387 | 2016-10-04T03:30:38.000Z | 2022-03-31T15:42:29.000Z | Arcane/src/Arcane/Platform/OpenGL/Framebuffer/GBuffer.cpp | flygod1159/Arcane-Engine | bfb95cc6734a25e5737d4195c2b9e92e03117707 | [
"MIT"
] | 9 | 2017-04-04T04:23:47.000Z | 2020-07-11T05:05:54.000Z | Arcane/src/Arcane/Platform/OpenGL/Framebuffer/GBuffer.cpp | flygod1159/Arcane-Engine | bfb95cc6734a25e5737d4195c2b9e92e03117707 | [
"MIT"
] | 36 | 2017-07-02T07:11:40.000Z | 2022-03-08T01:49:24.000Z | #include "arcpch.h"
#include "GBuffer.h"
namespace Arcane
{
GBuffer::GBuffer(unsigned int width, unsigned int height) : Framebuffer(width, height, false) {
Init();
}
GBuffer::~GBuffer() {}
void GBuffer::Init() {
AddDepthStencilTexture(NormalizedDepthStencil);
Bind();
// Render Target 1
{
TextureSettings renderTarget1;
renderTarget1.TextureFormat = GL_RGBA8;
renderTarget1.TextureWrapSMode = GL_CLAMP_TO_EDGE;
renderTarget1.TextureWrapTMode = GL_CLAMP_TO_EDGE;
renderTarget1.TextureMinificationFilterMode = GL_NEAREST;
renderTarget1.TextureMagnificationFilterMode = GL_NEAREST;
renderTarget1.TextureAnisotropyLevel = 1.0f;
renderTarget1.HasMips = false;
m_GBufferRenderTargets[0].SetTextureSettings(renderTarget1);
m_GBufferRenderTargets[0].Generate2DTexture(m_Width, m_Height, GL_RGB);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_GBufferRenderTargets[0].GetTextureId(), 0);
}
// Render Target 2
{
TextureSettings renderTarget2;
renderTarget2.TextureFormat = GL_RGB32F;
renderTarget2.TextureWrapSMode = GL_CLAMP_TO_EDGE;
renderTarget2.TextureWrapTMode = GL_CLAMP_TO_EDGE;
renderTarget2.TextureMinificationFilterMode = GL_NEAREST;
renderTarget2.TextureMagnificationFilterMode = GL_NEAREST;
renderTarget2.TextureAnisotropyLevel = 1.0f;
renderTarget2.HasMips = false;
m_GBufferRenderTargets[1].SetTextureSettings(renderTarget2);
m_GBufferRenderTargets[1].Generate2DTexture(m_Width, m_Height, GL_RGB);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_GBufferRenderTargets[1].GetTextureId(), 0);
}
// Render Target 3
{
TextureSettings renderTarget3;
renderTarget3.TextureFormat = GL_RGBA8;
renderTarget3.TextureWrapSMode = GL_CLAMP_TO_EDGE;
renderTarget3.TextureWrapTMode = GL_CLAMP_TO_EDGE;
renderTarget3.TextureMinificationFilterMode = GL_NEAREST;
renderTarget3.TextureMagnificationFilterMode = GL_NEAREST;
renderTarget3.TextureAnisotropyLevel = 1.0f;
renderTarget3.HasMips = false;
m_GBufferRenderTargets[2].SetTextureSettings(renderTarget3);
m_GBufferRenderTargets[2].Generate2DTexture(m_Width, m_Height, GL_RGB);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_GBufferRenderTargets[2].GetTextureId(), 0);
}
// Finally tell OpenGL that we will be rendering to all of the attachments
unsigned int attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, attachments);
// Check if the creation failed
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
ARC_LOG_FATAL("Could not initialize GBuffer");
return;
}
Unbind();
}
}
| 37.054054 | 124 | 0.78884 | flygod1159 |
aaa6da5ef96b6b36ca4a940e12ee7346d14b08ef | 1,783 | cpp | C++ | main.cpp | ikbo0217/glazkov_lab3_sem2 | eceb826eaa9aeeb5df148682a1398a2bed34bfe7 | [
"MIT"
] | null | null | null | main.cpp | ikbo0217/glazkov_lab3_sem2 | eceb826eaa9aeeb5df148682a1398a2bed34bfe7 | [
"MIT"
] | null | null | null | main.cpp | ikbo0217/glazkov_lab3_sem2 | eceb826eaa9aeeb5df148682a1398a2bed34bfe7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
using namespace std;
int pointState(int cx, int cy, int cr, int x, int y) {
int result = 0;
if(pow(x - cx, 2) + pow(y - cy, 2) == pow(cr, 2)) result = 2;
if(pow(x - cx, 2) + pow(y - cy, 2) < pow(cr, 2)) result = 1;
return result;
}
int quadrilateralState(int cx, int cy, int cr, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
int result = 0;
int p1 = pointState(cx, cy, cr, x1, y1);
int p2 = pointState(cx, cy, cr, x2, y2);
int p3 = pointState(cx, cy, cr, x3, y3);
int p4 = pointState(cx, cy, cr, x4, y4);
if(p1 == 2 && p2 == 2 && p3 == 2 && p4 == 2) return result = 2;
if(p1 && p2 && p3 && p4) return result = 1;
return result;
}
int main() {
int cx = 0;
int cy = 0;
int cr = 0;
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
int x3 = 0;
int y3 = 0;
int x4 = 0;
int y4 = 0;
cout << "Enter circle center coordinates: " << endl;
cout << "Enter x: ";
cin >> cx;
cout << "Enter y: ";
cin >> cy;
cout << "Enter radius: ";
cin >> cr;
cout << endl;
cout << "Enter quadrilateral vertex coordinates: " << endl;
cout << "Enter x1: ";
cin >> x1;
cout << "Enter y1: ";
cin >> y1;
cout << "Enter x2: ";
cin >> x2;
cout << "Enter y2: ";
cin >> y2;
cout << "Enter x3: ";
cin >> x3;
cout << "Enter y3: ";
cin >> y3;
cout << "Enter x4: ";
cin >> x4;
cout << "Enter y4: ";
cin >> y4;
cout << endl;
int result = quadrilateralState(cx, cy, cr, x1, y1, x2, y2, x3, y3, x4, y4);
switch (result) {
case 0:
cout << "Result: OUTSIDE" << endl;
case 1:
cout << "Result: INSIDE" << endl;
case 2:
cout << "Result: TOUCH" << endl;
}
return 0;
}
| 18.572917 | 112 | 0.503085 | ikbo0217 |
aaa7e1bbfd48f2a710c27866bf1126ebd36d3a53 | 3,365 | cpp | C++ | Chess/Logger.cpp | DennisCorvers/ChessCPP | 3a2a4d72066aa0a913095fa0c645d18c6a56cf99 | [
"MIT"
] | 1 | 2021-08-15T17:50:33.000Z | 2021-08-15T17:50:33.000Z | Chess/Logger.cpp | DennisCorvers/ChessCPP | 3a2a4d72066aa0a913095fa0c645d18c6a56cf99 | [
"MIT"
] | null | null | null | Chess/Logger.cpp | DennisCorvers/ChessCPP | 3a2a4d72066aa0a913095fa0c645d18c6a56cf99 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Logger.hpp"
#include <iomanip>
#include <ctime>
Logger::Logger() :
m_loggerSeverity(LoggerSeverity::NONE)
{
initFile();
}
Logger::Logger(LoggerSeverity loggingOptions) :
m_loggerSeverity(loggingOptions)
{
initFile();
}
Logger::Logger(unsigned int loggingOptions) :
m_loggerSeverity(static_cast<LoggerSeverity>(loggingOptions))
{
initFile();
}
Logger::Logger(const std::string & path) :
m_loggerSeverity(LoggerSeverity::NONE)
{
initFile(&path);
}
Logger::Logger(const std::string & path, LoggerSeverity loggingOptions) :
m_loggerSeverity(loggingOptions)
{
initFile(&path);
}
Logger::Logger(const std::string & path, unsigned int loggingOptions) :
m_loggerSeverity(static_cast<LoggerSeverity>(loggingOptions))
{
initFile(&path);
}
Logger::~Logger() {
m_logFile.close();
}
void Logger::log(const std::string& message) {
log(LoggerSeverity::NONE, message);
}
void Logger::log(LoggerSeverity severity, const std::string& message) {
std::string prefix;
switch (severity) {
case LoggerSeverity::DEBUG:
prefix = "Debug: "; break;
case LoggerSeverity::ERROR:
prefix = "[Error]: "; break;
case LoggerSeverity::FATAL:
prefix = "[FATAL]: "; break;
case LoggerSeverity::INFO:
break;
case LoggerSeverity::NONE:
break;
case LoggerSeverity::TRACE:
prefix = "[Trace]: "; break;
case LoggerSeverity::WARNING:
prefix = "[Warning]: "; break;
default:
prefix = ""; break;
}
log_inner(severity, message, prefix);
}
void Logger::trace(const std::string & message)
{
log(LoggerSeverity::TRACE, message);
}
void Logger::debug(const std::string & message)
{
log(LoggerSeverity::DEBUG, message);
}
void Logger::info(const std::string & message)
{
log(LoggerSeverity::INFO, message);
}
void Logger::warning(const std::string & message)
{
log(LoggerSeverity::WARNING, message);
}
void Logger::error(const std::string & message)
{
log(LoggerSeverity::ERROR, message);
}
void Logger::fatal(const std::string & message)
{
log(LoggerSeverity::FATAL, message);
}
void Logger::initFile(const std::string* const path) {
if (path == nullptr) {
m_logFile.close();
return;
}
m_logFile.open(*path, std::fstream::out | std::fstream::app);
//if (m_logFile)
// std::cerr << "Unable to create log file with specified path. Path: " + *path << std::endl;
}
const std::string Logger::getTime() {
auto bt = localtime_xp(std::time(0));
char buf[64];
return { buf, std::strftime(buf, sizeof(buf), DATETIME_FORMAT.c_str(), &bt) };
}
std::tm Logger::localtime_xp(std::time_t timer)
{
std::tm bt{};
#if defined(__unix__)
localtime_r(&timer, &bt);
#elif defined(_MSC_VER)
localtime_s(&bt, &timer);
#else
static std::mutex mtx;
std::lock_guard<std::mutex> lock(mtx);
bt = *std::localtime(&timer);
#endif
return bt;
}
bool Logger::shouldLog(LoggerSeverity severity) {
return m_loggerSeverity == LoggerSeverity::NONE || severity == LoggerSeverity::NONE || m_loggerSeverity & severity;
}
void Logger::log_inner(LoggerSeverity severity, const std::string& message, const std::string& prefix)
{
if (!shouldLog(severity))
return;
auto output = getTime() + prefix + message + '\n';
if (LoggerMode & LogMode::Console)
std::cout << output;
if (LoggerMode & LogMode::File) {
if (m_logFile) {
const std::lock_guard<std::mutex> lock(m_lock);
m_logFile << output;
m_logFile.flush();
}
}
}
| 21.03125 | 116 | 0.700446 | DennisCorvers |
aaa931a496fd6915947ae4b15cc7a6ed746c8d45 | 5,430 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/shared/qbs/src/lib/corelib/tools/launcherpackets.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | Src/shared/qbs/src/lib/corelib/tools/launcherpackets.cpp | kevinlq/QSD | b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a | [
"MIT"
] | null | null | null | Src/shared/qbs/src/lib/corelib/tools/launcherpackets.cpp | kevinlq/QSD | b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "launcherpackets.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qcoreapplication.h>
namespace qbs {
namespace Internal {
LauncherPacket::~LauncherPacket() { }
QByteArray LauncherPacket::serialize() const
{
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
stream << static_cast<int>(0) << static_cast<quint8>(type) << token;
doSerialize(stream);
stream.device()->reset();
stream << static_cast<int>(data.size() - sizeof(int));
return data;
}
void LauncherPacket::deserialize(const QByteArray &data)
{
QDataStream stream(data);
doDeserialize(stream);
}
StartProcessPacket::StartProcessPacket(quintptr token)
: LauncherPacket(LauncherPacketType::StartProcess, token)
{
}
void StartProcessPacket::doSerialize(QDataStream &stream) const
{
stream << command << arguments << workingDir << env;
}
void StartProcessPacket::doDeserialize(QDataStream &stream)
{
stream >> command >> arguments >> workingDir >> env;
}
StopProcessPacket::StopProcessPacket(quintptr token)
: LauncherPacket(LauncherPacketType::StopProcess, token)
{
}
void StopProcessPacket::doSerialize(QDataStream &stream) const
{
Q_UNUSED(stream);
}
void StopProcessPacket::doDeserialize(QDataStream &stream)
{
Q_UNUSED(stream);
}
ProcessErrorPacket::ProcessErrorPacket(quintptr token)
: LauncherPacket(LauncherPacketType::ProcessError, token)
{
}
void ProcessErrorPacket::doSerialize(QDataStream &stream) const
{
stream << static_cast<quint8>(error) << errorString;
}
void ProcessErrorPacket::doDeserialize(QDataStream &stream)
{
quint8 e;
stream >> e;
error = static_cast<QProcess::ProcessError>(e);
stream >> errorString;
}
ProcessFinishedPacket::ProcessFinishedPacket(quintptr token)
: LauncherPacket(LauncherPacketType::ProcessFinished, token)
{
}
void ProcessFinishedPacket::doSerialize(QDataStream &stream) const
{
stream << errorString << stdOut << stdErr
<< static_cast<quint8>(exitStatus) << static_cast<quint8>(error)
<< exitCode;
}
void ProcessFinishedPacket::doDeserialize(QDataStream &stream)
{
stream >> errorString >> stdOut >> stdErr;
quint8 val;
stream >> val;
exitStatus = static_cast<QProcess::ExitStatus>(val);
stream >> val;
error = static_cast<QProcess::ProcessError>(val);
stream >> exitCode;
}
ShutdownPacket::ShutdownPacket() : LauncherPacket(LauncherPacketType::Shutdown, 0) { }
void ShutdownPacket::doSerialize(QDataStream &stream) const { Q_UNUSED(stream); }
void ShutdownPacket::doDeserialize(QDataStream &stream) { Q_UNUSED(stream); }
void PacketParser::setDevice(QIODevice *device)
{
m_stream.setDevice(device);
m_sizeOfNextPacket = -1;
}
bool PacketParser::parse()
{
static const int commonPayloadSize = static_cast<int>(1 + sizeof(quintptr));
if (m_sizeOfNextPacket == -1) {
if (m_stream.device()->bytesAvailable() < static_cast<int>(sizeof m_sizeOfNextPacket))
return false;
m_stream >> m_sizeOfNextPacket;
if (m_sizeOfNextPacket < commonPayloadSize)
throw InvalidPacketSizeException(m_sizeOfNextPacket);
}
if (m_stream.device()->bytesAvailable() < m_sizeOfNextPacket)
return false;
quint8 type;
m_stream >> type;
m_type = static_cast<LauncherPacketType>(type);
m_stream >> m_token;
m_packetData = m_stream.device()->read(m_sizeOfNextPacket - commonPayloadSize);
m_sizeOfNextPacket = -1;
return true;
}
} // namespace Internal
} // namespace qbs
| 31.028571 | 94 | 0.710497 | kevinlq |
aaad34f2d74344a8c641f2b74145ceca9b30b093 | 938 | cpp | C++ | catchMain.cpp | skrtks/ft_containers_tests | a5044a4b559bbbd1292c6f5996dff4ed8b9b599f | [
"BSD-2-Clause"
] | null | null | null | catchMain.cpp | skrtks/ft_containers_tests | a5044a4b559bbbd1292c6f5996dff4ed8b9b599f | [
"BSD-2-Clause"
] | null | null | null | catchMain.cpp | skrtks/ft_containers_tests | a5044a4b559bbbd1292c6f5996dff4ed8b9b599f | [
"BSD-2-Clause"
] | 2 | 2021-02-25T14:25:21.000Z | 2021-11-24T11:32:23.000Z | /* ************************************************************************** */
/* */
/* :::::::: */
/* catchMain.cpp :+: :+: */
/* +:+ */
/* By: skorteka <skorteka@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2020/10/23 14:12:47 by skorteka #+# #+# */
/* Updated: 2020/10/23 14:12:47 by skorteka ######## odam.nl */
/* */
/* ************************************************************************** */
#define CATCH_CONFIG_MAIN
#include "Catch2.h"
| 62.533333 | 80 | 0.158849 | skrtks |
aaada067b38f9be1a996c674c8ff8359931d902c | 8,322 | cpp | C++ | unit_tests/maths/matrix_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 28 | 2021-11-23T11:52:55.000Z | 2022-03-04T01:48:52.000Z | unit_tests/maths/matrix_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | null | null | null | unit_tests/maths/matrix_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 3 | 2022-01-02T12:23:04.000Z | 2022-01-07T04:21:26.000Z | //
// matrix_tests.cpp
// unit_tests
//
// Created by 杨丰 on 2021/11/25.
//
#include "maths/matrix.h"
#include "gtest.h"
#include "gtest_helper.h"
#include "gtest_math_helper.h"
using vox::math::Float3;
using vox::math::Matrix;
using vox::math::Quaternion;
TEST(Matrix, multiply) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto b = Matrix(16, 15, 14, 13, 12, 11, 10, 9, 8.88, 7, 6, 5, 4, 3, 2, 1);
const Matrix out = a * b;
EXPECT_MATRIX_EQ(out,
386,
456.59997558,
506.8,
560,
274,
325,
361.6,
400,
162.88,
195.16000000000003,
219.304,
243.52,
50,
61.8,
71.2,
80);
}
TEST(Matrix, lerp) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
const auto b = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
const auto c = Lerp(a, b, 0.7);
EXPECT_MATRIX_EQ(c, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
}
TEST(Matrix, rotationQuaternion) {
const auto q = Quaternion(1, 2, 3, 4);
const auto out = Matrix::rotationQuaternion(q);
EXPECT_MATRIX_EQ(out, -25, 28, -10, 0, -20, -19, 20, 0, 22, 4, -9, 0, 0, 0, 0, 1);
}
TEST(Matrix, rotationAxisAngle) {
const auto out = Matrix::rotationAxisAngle(Float3(0, 1, 0), M_PI / 3);
EXPECT_MATRIX_EQ(out,
0.5000000000000001,
0,
-0.8660254037844386,
0,
0,
1,
0,
0,
0.8660254037844386,
0,
0.5000000000000001,
0,
0,
0,
0,
1);
}
TEST(Matrix, rotationTranslation) {
const auto q = Quaternion(1, 0.5, 2, 1);
const auto v = Float3(1, 1, 1);
const auto out = Matrix::rotationTranslation(q, v);
EXPECT_MATRIX_EQ(out, -7.5, 5, 3, 0, -3, -9, 4, 0, 5, 0, -1.5, 0, 1, 1, 1, 1);
}
TEST(Matrix, affineTransformation) {
const auto q = Quaternion(1, 0.5, 2, 1);
const auto v = Float3(1, 1, 1);
const auto s = Float3(1, 0.5, 2);
const auto out = Matrix::affineTransformation(s, q, v);
EXPECT_MATRIX_EQ(out, -7.5, 5, 3, 0, -1.5, -4.5, 2, 0, 10, 0, -3, 0, 1, 1, 1, 1);
}
TEST(Matrix, scaling) {
const auto a = Matrix();
const auto out = scale(a, Float3(1, 2, 0.5));
EXPECT_MATRIX_EQ(out, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1);
}
TEST(Matrix, translation) {
const auto v = Float3(1, 2, 0.5);
const auto out = Matrix::translation(v);
EXPECT_MATRIX_EQ(out, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 0.5, 1);
}
TEST(Matrix, invert) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto out = invert(a);
EXPECT_MATRIX_EQ(out,
-1.1111111111111172,
1.3703594207763672,
-0.7407407407407528,
0.1481481481481532,
0,
-0.5555555555555607,
1.1110992431640625,
-0.5555555555555607,
3.3333001136779785,
-4.9999480247497559,
0,
1.6666476726531982,
-2.222196102142334,
4.0601420402526855,
-0.3703703703703687,
-1.1342480182647705
);
}
TEST(Matrix, lookAt) {
auto eye = Float3(0, 0, -8);
auto target = Float3(0, 0, 0);
auto up = Float3(0, 1, 0);
auto out = Matrix::lookAt(eye, target, up);
EXPECT_MATRIX_EQ(out, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, -8, 1);
eye = Float3(0, 0, 0);
target = Float3(0, 1, -1);
up = Float3(0, 1, 0);
out = Matrix::lookAt(eye, target, up);
EXPECT_MATRIX_EQ(out,
1,
0,
0,
0,
0,
0.7071067690849304,
-0.7071067690849304,
0,
0,
0.7071067690849304,
0.7071067690849304,
0,
0,
0,
0,
1
);
}
TEST(Matrix, ortho) {
const auto out = Matrix::ortho(0, 2, -1, 1, 0.1, 100);
EXPECT_MATRIX_EQ(out, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.02002002002002002, 0, -1, 0, -1.002002002002002, 1);
}
TEST(Matrix, perspective) {
const auto out = Matrix::perspective(1, 1.5, 0.1, 100);
EXPECT_MATRIX_EQ(out,
1.2203251478083013,
0,
0,
0,
0,
1.830487721712452,
0,
0,
0,
0,
-1.002002002002002,
-1,
0,
0,
-0.20020020020020018,
0
);
}
TEST(Matrix, rotateAxisAngle) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto out = rotateAxisAngle(a, Float3(0, 1, 0), M_PI / 3);
EXPECT_MATRIX_EQ(out,
-7.294228634059947,
-8.439676901250381,
-7.876279441628824,
-8.392304845413264,
5,
6,
7,
8,
5.366025403784439,
7.182050807568878,
8.357883832488648,
9.464101615137757,
13,
14,
15,
16
);
}
TEST(Matrix, scale) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
const auto out = scale(a, Float3(1, 2, 0.5));
EXPECT_MATRIX_EQ(out, 1, 2, 3, 4, 10, 12, 14, 16, 4.5, 5, 5.5, 6, 13, 14, 15, 16);
}
TEST(Matrix, translate) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto out = translate(a, Float3(1, 2, 0.5));
EXPECT_MATRIX_EQ(out, 1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 28.5, 33.45, 37.8, 42);
}
TEST(Matrix, transpose) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto out = transpose(a);
EXPECT_MATRIX_EQ(out, 1, 5, 9, 13, 2, 6, 10.9, 14, 3.3, 7, 11, 15, 4, 8, 12, 16);
}
TEST(Matrix, determinant) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
EXPECT_FLOAT_EQ(a.determinant(), -6.1035156e-05);
}
TEST(Matrix, decompose) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
// const a = new Matrix(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
auto pos = Float3();
auto quat = Quaternion();
auto scale = Float3();
a.decompose(pos, quat, scale);
EXPECT_FLOAT3_EQ(pos, 13, 14, 15);
EXPECT_QUATERNION_EQ(quat, 0.01879039477474769, -0.09554131404261303, 0.01844761344901482, 0.783179537258594);
EXPECT_FLOAT3_EQ(scale, 3.7416573867739413, 10.488088481701515, 17.91116946723357);
}
TEST(Matrix, getXXX) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
// getRotation
auto quat = a.getRotation();
EXPECT_QUATERNION_EQ(quat, -0.44736068104759547, 0.6882472016116852, -0.3441236008058426, 2.179449471770337);
// getScaling
auto scale = a.getScaling();
EXPECT_FLOAT3_EQ(scale, 3.7416573867739413, 10.488088481701515, 17.911169699380327);
// getTranslation
auto translation = a.getTranslation();
EXPECT_FLOAT3_EQ(translation, 13, 14, 15);
}
| 32.255814 | 114 | 0.451214 | yangfengzzz |
aaae4cc2e61c02950c900c410a97b6c2ad46049c | 2,259 | cpp | C++ | src/Array.cpp | chnlkw/xuanwu | f796e9a851d8fad289ac5a625679e7db6c090a04 | [
"MIT"
] | 1 | 2018-04-09T01:45:17.000Z | 2018-04-09T01:45:17.000Z | src/Array.cpp | chnlkw/xuanwu | f796e9a851d8fad289ac5a625679e7db6c090a04 | [
"MIT"
] | null | null | null | src/Array.cpp | chnlkw/xuanwu | f796e9a851d8fad289ac5a625679e7db6c090a04 | [
"MIT"
] | 1 | 2020-04-14T03:39:20.000Z | 2020-04-14T03:39:20.000Z | //
// Created by chnlkw on 1/16/18.
//
#include "Array.h"
#include "DataCopy.h"
#include "Device.h"
#include "Allocator.h"
#include "Xuanwu.h"
#include "Ptr.h"
namespace Xuanwu {
ArrayBase::ArrayBase(size_t bytes, AllocatorPtr allocator)
: allocator_(allocator), bytes_(bytes), ptr_(allocator->Alloc(bytes)) {
}
// ArrayBase::ArrayBase(const ArrayBase &that) :
// allocator_(Xuanwu::GetDefaultDevice()->GetDefaultAllocator()) {
// Allocate(that.bytes_);
// ArrayCopy(allocator_->GetDevice(), ptr_, that.allocator_->GetDevice(), that.ptr_, that.bytes_);
// }
// ArrayBase::ArrayBase(void *ptr, size_t bytes) : //alias from cpu array
// allocator_(nullptr),
// ptr_(ptr),
// bytes_(bytes) {
// }
ArrayBase::ArrayBase(ArrayBase &&that) :
allocator_(that.allocator_),
bytes_(that.bytes_),
ptr_(that.ptr_) {
that.ptr_ = nullptr;
}
ArrayBase::ArrayBase(const ArrayBase &that, size_t off, size_t bytes)
: allocator_(nullptr),
bytes_(bytes),
ptr_((char *) that.ptr_ + off) {
}
ArrayBase::~ArrayBase() {
Free();
}
void ArrayBase::Free() {
if (allocator_ && ptr_)
allocator_->Free(ptr_);
ptr_ = nullptr;
bytes_ = 0;
}
void ArrayBase::Allocate(size_t bytes) {
bytes_ = bytes;
if (bytes > 0 && allocator_) {
ptr_ = allocator_->Alloc(bytes);
} else {
ptr_ = nullptr;
}
// printf("reallocate ptr %p bytes = %lu\n", ptr_, bytes);
}
// void ArrayBase::CopyFrom(const ArrayBase &that) {
// CopyFromAsync(that, GetDefaultWorker());
// }
//
// void ArrayBase::CopyFromAsync(const ArrayBase &that, WorkerPtr worker) {
// size_t bytes = std::min(this->bytes_, that.bytes_);
// assert(this->bytes_ == that.bytes_);
// worker->Copy(GetPtr(), that.GetPtr(), bytes);
// }
// DevicePtr ArrayBase::GetDevice() const { return allocator_->GetDevice(); }
// AllocatorPtr ArrayBase::GetAllocator() const { return allocator_; }
Ptr ArrayBase::GetPtr() const {
return allocator_->MakePtr(ptr_);
}
}
| 27.54878 | 105 | 0.578132 | chnlkw |
aab0500972a427259f69e429bb8ca96d7c2635e3 | 1,764 | hpp | C++ | drape/vulkan/vulkan_param_descriptor.hpp | sthirvela/organicmaps | 14885ba070ac9d1b7241ebb89eeefa46c9fdc1e4 | [
"Apache-2.0"
] | 3,062 | 2021-04-09T16:51:55.000Z | 2022-03-31T21:02:51.000Z | drape/vulkan/vulkan_param_descriptor.hpp | MAPSWorks/organicmaps | b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f | [
"Apache-2.0"
] | 1,396 | 2021-04-08T07:26:49.000Z | 2022-03-31T20:27:46.000Z | drape/vulkan/vulkan_param_descriptor.hpp | MAPSWorks/organicmaps | b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f | [
"Apache-2.0"
] | 242 | 2021-04-10T17:10:46.000Z | 2022-03-31T13:41:07.000Z | #pragma once
#include "drape/graphics_context.hpp"
#include "drape/vulkan/vulkan_gpu_program.hpp"
#include "drape/vulkan/vulkan_utils.hpp"
#include <array>
#include <cstdint>
#include <string>
#include <vector>
namespace dp
{
namespace vulkan
{
struct ParamDescriptor
{
enum class Type : uint8_t
{
DynamicUniformBuffer = 0,
Texture
};
Type m_type = Type::DynamicUniformBuffer;
VkDescriptorBufferInfo m_bufferDescriptor = {};
uint32_t m_bufferDynamicOffset = 0;
VkDescriptorImageInfo m_imageDescriptor = {};
int8_t m_textureSlot = 0;
uint32_t m_id = 0;
};
size_t constexpr kMaxDescriptorSets = 8;
struct DescriptorSetGroup
{
VkDescriptorSet m_descriptorSet = {};
VkDescriptorPool m_descriptorPool = {};
std::array<uint32_t, kMaxDescriptorSets> m_ids = {};
bool m_updated = false;
explicit operator bool()
{
return m_descriptorSet != VK_NULL_HANDLE &&
m_descriptorPool != VK_NULL_HANDLE;
}
void Update(VkDevice device, std::vector<ParamDescriptor> const & descriptors);
};
class VulkanObjectManager;
class ParamDescriptorUpdater
{
public:
explicit ParamDescriptorUpdater(ref_ptr<VulkanObjectManager> objectManager);
void Update(ref_ptr<dp::GraphicsContext> context);
void Destroy();
VkDescriptorSet GetDescriptorSet() const;
private:
void Reset(uint32_t inflightFrameIndex);
ref_ptr<VulkanObjectManager> m_objectManager;
struct UpdateData
{
std::vector<DescriptorSetGroup> m_descriptorSetGroups;
ref_ptr<VulkanGpuProgram> m_program;
uint32_t m_updateDescriptorFrame = 0;
uint32_t m_descriptorSetIndex = 0;
};
std::array<UpdateData, kMaxInflightFrames> m_updateData;
uint32_t m_currentInflightFrameIndex = 0;
};
} // namespace vulkan
} // namespace dp
| 21.512195 | 81 | 0.751134 | sthirvela |
82b5f4ab94f8152c0c6a2bedc0afdc21292b13f5 | 7,479 | cxx | C++ | main/chart2/source/view/main/PolarLabelPositionHelper.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/chart2/source/view/main/PolarLabelPositionHelper.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/chart2/source/view/main/PolarLabelPositionHelper.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "PolarLabelPositionHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "CommonConverters.hxx"
#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/vector/b2ivector.hxx>
#include <com/sun/star/chart/DataLabelPlacement.hpp>
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
PolarLabelPositionHelper::PolarLabelPositionHelper(
PolarPlottingPositionHelper* pPosHelper
, sal_Int32 nDimensionCount
, const uno::Reference< drawing::XShapes >& xLogicTarget
, ShapeFactory* pShapeFactory )
: LabelPositionHelper( pPosHelper, nDimensionCount, xLogicTarget, pShapeFactory )
, m_pPosHelper(pPosHelper)
{
}
PolarLabelPositionHelper::~PolarLabelPositionHelper()
{
}
awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignmentForLogicValues(
LabelAlignment& rAlignment
, double fLogicValueOnAngleAxis
, double fLogicValueOnRadiusAxis
, double fLogicZ
, sal_Int32 nScreenValueOffsetInRadiusDirection ) const
{
double fUnitCircleAngleDegree = m_pPosHelper->transformToAngleDegree( fLogicValueOnAngleAxis );
double fUnitCircleRadius = m_pPosHelper->transformToRadius( fLogicValueOnRadiusAxis );
return getLabelScreenPositionAndAlignmentForUnitCircleValues(
rAlignment, ::com::sun::star::chart::DataLabelPlacement::OUTSIDE
, fUnitCircleAngleDegree, 0.0
, fUnitCircleRadius, fUnitCircleRadius, fLogicZ, nScreenValueOffsetInRadiusDirection );
}
awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignmentForUnitCircleValues(
LabelAlignment& rAlignment, sal_Int32 nLabelPlacement
, double fUnitCircleStartAngleDegree, double fUnitCircleWidthAngleDegree
, double fUnitCircleInnerRadius, double fUnitCircleOuterRadius
, double fLogicZ
, sal_Int32 nScreenValueOffsetInRadiusDirection ) const
{
bool bCenter = (nLabelPlacement != ::com::sun::star::chart::DataLabelPlacement::OUTSIDE)
&& (nLabelPlacement != ::com::sun::star::chart::DataLabelPlacement::INSIDE);
double fAngleDegree = fUnitCircleStartAngleDegree + fUnitCircleWidthAngleDegree/2.0;
double fRadius = 0.0;
if( !bCenter ) //e.g. for pure pie chart(one ring only) or for angle axis of polyar coordinate system
fRadius = fUnitCircleOuterRadius;
else
fRadius = fUnitCircleInnerRadius + (fUnitCircleOuterRadius-fUnitCircleInnerRadius)/2.0 ;
awt::Point aRet( this->transformSceneToScreenPosition(
m_pPosHelper->transformUnitCircleToScene( fAngleDegree, fRadius, fLogicZ+0.5 ) ) );
if(3==m_nDimensionCount && nLabelPlacement == ::com::sun::star::chart::DataLabelPlacement::OUTSIDE)
{
//check whether the upper or the downer edge is more distant from the center
//take the farest point to put the label to
awt::Point aP0( this->transformSceneToScreenPosition(
m_pPosHelper->transformUnitCircleToScene( 0, 0, fLogicZ ) ) );
awt::Point aP1(aRet);
awt::Point aP2( this->transformSceneToScreenPosition(
m_pPosHelper->transformUnitCircleToScene( fAngleDegree, fRadius, fLogicZ-0.5 ) ) );
::basegfx::B2DVector aV0( aP0.X, aP0.Y );
::basegfx::B2DVector aV1( aP1.X, aP1.Y );
::basegfx::B2DVector aV2( aP2.X, aP2.Y );
double fL1 = ::basegfx::B2DVector(aV1-aV0).getLength();
double fL2 = ::basegfx::B2DVector(aV2-aV0).getLength();
if(fL2>fL1)
aRet = aP2;
//calculate new angle for alignment
double fDX = aRet.X-aP0.X;
double fDY = aRet.Y-aP0.Y;
fDY*=-1.0;//drawing layer has inverse y values
if( fDX != 0.0 )
{
fAngleDegree = atan(fDY/fDX)*180.0/F_PI;
if(fDX<0.0)
fAngleDegree+=180.0;
}
else
{
if(fDY>0.0)
fAngleDegree = 90.0;
else
fAngleDegree = 270.0;
}
}
//------------------------------
//set LabelAlignment
if( !bCenter )
{
while(fAngleDegree>360.0)
fAngleDegree-=360.0;
while(fAngleDegree<0.0)
fAngleDegree+=360.0;
bool bOutside = nLabelPlacement == ::com::sun::star::chart::DataLabelPlacement::OUTSIDE;
if(fAngleDegree==0.0)
rAlignment = LABEL_ALIGN_CENTER;
else if(fAngleDegree<=22.5)
rAlignment = bOutside ? LABEL_ALIGN_RIGHT : LABEL_ALIGN_LEFT;
else if(fAngleDegree<67.5)
rAlignment = bOutside ? LABEL_ALIGN_RIGHT_TOP : LABEL_ALIGN_LEFT_BOTTOM;
else if(fAngleDegree<112.5)
rAlignment = bOutside ? LABEL_ALIGN_TOP : LABEL_ALIGN_BOTTOM;
else if(fAngleDegree<=157.5)
rAlignment = bOutside ? LABEL_ALIGN_LEFT_TOP : LABEL_ALIGN_RIGHT_BOTTOM;
else if(fAngleDegree<=202.5)
rAlignment = bOutside ? LABEL_ALIGN_LEFT : LABEL_ALIGN_RIGHT;
else if(fAngleDegree<247.5)
rAlignment = bOutside ? LABEL_ALIGN_LEFT_BOTTOM : LABEL_ALIGN_RIGHT_TOP;
else if(fAngleDegree<292.5)
rAlignment = bOutside ? LABEL_ALIGN_BOTTOM : LABEL_ALIGN_TOP;
else if(fAngleDegree<337.5)
rAlignment = bOutside ? LABEL_ALIGN_RIGHT_BOTTOM : LABEL_ALIGN_LEFT_TOP;
else
rAlignment = bOutside ? LABEL_ALIGN_RIGHT : LABEL_ALIGN_LEFT;
}
else
{
rAlignment = LABEL_ALIGN_CENTER;
}
//add a scaling independent Offset if requested
if( nScreenValueOffsetInRadiusDirection != 0)
{
awt::Point aOrigin( this->transformSceneToScreenPosition(
m_pPosHelper->transformUnitCircleToScene( 0.0, 0.0, fLogicZ+0.5 ) ) );
basegfx::B2IVector aDirection( aRet.X- aOrigin.X, aRet.Y- aOrigin.Y );
aDirection.setLength(nScreenValueOffsetInRadiusDirection);
aRet.X += aDirection.getX();
aRet.Y += aDirection.getY();
}
return aRet;
}
//.............................................................................
} //namespace chart
//.............................................................................
| 40.427027 | 105 | 0.631234 | Grosskopf |
82b5f763483e02639ac4259a4c32820b43a85c6c | 1,012 | cpp | C++ | Solutions/Search for a Range/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | 1 | 2015-04-13T10:58:30.000Z | 2015-04-13T10:58:30.000Z | Solutions/Search for a Range/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | Solutions/Search for a Range/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> res(2,-1);
int left = 0;
int right = n-1;
while(left <= right) {
int mid = (left + right) / 2;
if (A[mid] == target) {
int i,j;
i = j = mid;
for(; i >= left && A[i] == target; i--);
for(; j <= right && A[j] == target; j++);
res[0] = i+1;
res[1] = j-1;
return res;
}
if (target > A[mid]) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return res;
}
};
int main()
{
int A[] = {};
Solution s;
vector<int> res = s.searchRange(A,sizeof(A)/sizeof(A[0]), 5);
for(auto iter = res.begin(); iter != res.end(); iter++) {
cout<<*iter<<" ";
}
return 0;
}
| 23 | 65 | 0.387352 | Crayzero |
82b7563d6cd6b6805824b8b4ae8f5dcff1882bbb | 878 | hpp | C++ | epoch/lucca_qt/include/lucca_qt/image/image_cache.hpp | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | 47 | 2020-03-30T14:36:46.000Z | 2022-03-06T07:44:54.000Z | epoch/lucca_qt/include/lucca_qt/image/image_cache.hpp | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | null | null | null | epoch/lucca_qt/include/lucca_qt/image/image_cache.hpp | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | 8 | 2020-04-01T01:22:45.000Z | 2022-01-02T13:06:09.000Z | #ifndef LUCCA_IMAGE_CACHE_HPP
#define LUCCA_IMAGE_CACHE_HPP
#include "lucca_qt/config.hpp"
#include "lucca_qt/serialization/image_cache_serializer.hpp"
#include <boost/noncopyable.hpp>
#include <unordered_map>
namespace ayla {
class Image;
}
namespace lucca_qt {
/**
* @author O Programador
*/
class LUCCA_QT_API ImageCache final : boost::noncopyable {
public:
ImageCache();
~ImageCache();
std::shared_ptr<ayla::Image> getImage(const std::string& fileName);
private:
using MapType = std::unordered_map<std::string, std::shared_ptr<ayla::Image> >;
MapType _images;
template <class Archive> friend void boost::serialization::serialize(Archive&, lucca_qt::ImageCache&, const unsigned int);
template <class Archive> friend void boost::serialization::load_construct_data(Archive&, lucca_qt::ImageCache*, const unsigned int);
};
}
#endif // LUCCA_IMAGE_CACHE_HPP | 23.105263 | 133 | 0.766515 | oprogramadorreal |
82bc46df9fd678d43a3c01cfed5eb170d9c6da2c | 272 | cpp | C++ | src/gui/columnize/ColumnDefinitionFactory.cpp | tomvodi/QTail | 2e7acf31664969e6890edede6b60e02b20f33eb2 | [
"MIT"
] | 1 | 2017-04-29T12:17:59.000Z | 2017-04-29T12:17:59.000Z | src/gui/columnize/ColumnDefinitionFactory.cpp | tomvodi/QTail | 2e7acf31664969e6890edede6b60e02b20f33eb2 | [
"MIT"
] | 25 | 2016-06-11T17:35:42.000Z | 2017-07-19T04:19:08.000Z | src/gui/columnize/ColumnDefinitionFactory.cpp | tomvodi/QTail | 2e7acf31664969e6890edede6b60e02b20f33eb2 | [
"MIT"
] | null | null | null | /**
* @author Thomas Baumann <teebaum@ymail.com>
*
* @section LICENSE
* See LICENSE for more informations.
*
*/
#include "ColumnDefinitionFactory.h"
ColumnDefinitionFactory::ColumnDefinitionFactory()
{
}
ColumnDefinitionFactory::~ColumnDefinitionFactory()
{
}
| 13.6 | 51 | 0.735294 | tomvodi |
82c0470a2dbc15b744b23b933a494c7ace723a50 | 4,964 | hpp | C++ | diffsim_torch3d/arcsim/src/util.hpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/util.hpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/util.hpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
Copyright ©2013 The Regents of the University of California
(Regents). All Rights Reserved. Permission to use, copy, modify, and
distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a
signed licensing agreement, is hereby granted, provided that the
above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and
distributions. Contact The Office of Technology Licensing, UC
Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620,
(510) 643-7201, for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#ifndef UTIL_HPP
#define UTIL_HPP
#include <string> // aa: win
#include "mesh.hpp"
#include "spline.hpp"
#include <iostream>
#include <string>
#include <vector>
using torch::Tensor;
#define EPSILON 1e-7f
// i+1 and i-1 modulo 3
// This way of computing it tends to be faster than using %
#define NEXT(i) ((i)<2 ? (i)+1 : (i)-2)
#define PREV(i) ((i)>0 ? (i)-1 : (i)+2)
typedef unsigned int uint;
struct Transformation;
// Quick-and easy statistics
// sprintf for std::strings
std::string stringf (const std::string &format, ...);
// Easy reporting of vertices and faces
std::ostream &operator<< (std::ostream &out, const Vert *vert);
std::ostream &operator<< (std::ostream &out, const Node *node);
std::ostream &operator<< (std::ostream &out, const Edge *edge);
std::ostream &operator<< (std::ostream &out, const Face *face);
// Math utilities
int solve_quadratic (Tensor a, Tensor b, Tensor c, Tensor x[2]);
Tensor solve_cubic(Tensor a, Tensor b, Tensor c, Tensor d);
// Find, replace, and all that jazz
template <typename T> inline int find (const T *x, T* const *xs, int n=3) {
for (int i = 0; i < n; i++) if (xs[i] == x) return i; return -1;}
template <typename T> inline int find (const T &x, const T *xs, int n=3) {
for (int i = 0; i < n; i++) if (xs[i] == x) return i; return -1;}
template <typename T> inline int find (const T &x, const std::vector<T> &xs) {
for (int i = 0; i < xs.size(); i++) if (xs[i] == x) return i; return -1;}
template <typename T> inline bool is_in (const T *x, T* const *xs, int n=3) {
return find(x, xs, n) != -1;}
template <typename T> inline bool is_in (const T &x, const T *xs, int n=3) {
return find(x, xs, n) != -1;}
template <typename T> inline bool is_in (const T &x, const std::vector<T> &xs) {
return find(x, xs) != -1;}
template <typename T> inline void include (const T &x, std::vector<T> &xs) {
if (!is_in(x, xs)) xs.push_back(x);}
template <typename T> inline void remove (int i, std::vector<T> &xs) {
xs[i] = xs.back(); xs.pop_back();}
template <typename T> inline void exclude (const T &x, std::vector<T> &xs) {
int i = find(x, xs); if (i != -1) remove(i, xs);}
template <typename T> inline void replace (const T &v0, const T &v1, T vs[3]) {
int i = find(v0, vs); if (i != -1) vs[i] = v1;}
template <typename T>
inline void replace (const T &x0, const T &x1, std::vector<T> &xs) {
int i = find(x0, xs); if (i != -1) xs[i] = x1;}
template <typename T>
inline bool subset (const std::vector<T> &xs, const std::vector<T> &ys) {
for (int i = 0; i < xs.size(); i++) if (!is_in(xs[i], ys)) return false;
return true;
}
template <typename T>
inline void append (std::vector<T> &xs, const std::vector<T> &ys) {
xs.insert(xs.end(), ys.begin(), ys.end());}
// Comparisons on vectors
// Mesh utilities
bool is_seam_or_boundary (const Vert *v);
bool is_seam_or_boundary (const Node *n);
bool is_seam_or_boundary (const Edge *e);
bool is_seam_or_boundary (const Face *f);
// Debugging
void debug_save_mesh (const Mesh &mesh, const std::string &name, int n=-1);
void debug_save_meshes (const std::vector<Mesh*> &meshes,
const std::string &name, int n=-1);
template <typename T>
std::ostream &operator<< (std::ostream &out, const std::vector<T> &v) {
out << "[";
for (int i = 0; i < v.size(); i++)
out << (i==0 ? "" : ", ") << v[i];
out << "]";
return out;
}
#define ECHO(x) std::cout << #x << std::endl
#define REPORT(x) std::cout << #x << " = " << (x) << std::endl
#define REPORT_ARRAY(x,n) std::cout << #x << "[" << #n << "] = " << vector<double>(&(x)[0], &(x)[n]) << std::endl
#endif
| 33.315436 | 113 | 0.657736 | priyasundaresan |
82c0727e513d791501a29e19d2dccbfe05744376 | 2,398 | cpp | C++ | benchmarks/halide/resize_tiramisu.cpp | akmaru/tiramisu | 8ca4173547b6d12cff10575ef0dc48cf93f7f414 | [
"MIT"
] | 23 | 2017-05-03T13:06:34.000Z | 2018-06-07T07:12:43.000Z | benchmarks/halide/resize_tiramisu.cpp | akmaru/tiramisu | 8ca4173547b6d12cff10575ef0dc48cf93f7f414 | [
"MIT"
] | 2 | 2017-04-25T08:59:09.000Z | 2017-05-11T16:41:55.000Z | benchmarks/halide/resize_tiramisu.cpp | akmaru/tiramisu | 8ca4173547b6d12cff10575ef0dc48cf93f7f414 | [
"MIT"
] | 5 | 2017-02-16T14:26:40.000Z | 2018-05-30T16:49:27.000Z | #include <tiramisu/tiramisu.h>
#include "halide_image_io.h"
using namespace tiramisu;
expr mixf(expr x, expr y, expr a)
{
return cast(p_float32, x) * (1 - a) + cast(p_float32, y) * a;
}
int main(int argc, char **argv)
{
Halide::Buffer<uint8_t> in_image = Halide::Tools::load_image("./utils/images/gray.png");
int IMG_WIDTH = in_image.width();
int IMG_HEIGHT = in_image.height();
int OUT_WIDTH = in_image.width() / 1.5f;
int OUT_HEIGHT = in_image.height() / 1.5f;
init("resize_tiramisu");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
var o_x("o_x", 0, IMG_WIDTH), o_y("o_y", 0, IMG_HEIGHT);
var x("x", 0, OUT_WIDTH), y("y", 0, OUT_HEIGHT);
input c_input("c_input", {o_y, o_x}, p_uint8);
expr o_r((cast(p_float32, y) + 0.5f) * (cast(p_float32, IMG_HEIGHT) / cast(p_float32, OUT_HEIGHT)) - 0.5f);
expr o_c((cast(p_float32, x) + 0.5f) * (cast(p_float32, IMG_WIDTH) / cast(p_float32, OUT_WIDTH)) - 0.5f);
expr r_coeff(expr(o_r) - expr(o_floor, o_r));
expr c_coeff(expr(o_c) - expr(o_floor, o_c));
expr A00_r(cast(p_int32, expr(o_floor, o_r)));
expr A00_c(cast(p_int32, expr(o_floor, o_c)));
computation resize(
"resize",
{y, x},
mixf(
mixf(
c_input(A00_r, A00_c),
c_input(A00_r + 1, A00_c),
r_coeff
),
mixf(
c_input(A00_r, A00_c + 1),
c_input(A00_r + 1, A00_c + 1),
r_coeff
),
c_coeff
)
);
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
resize.tag_parallel_level(y);
resize.vectorize(x, 8);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer output_buf("output_buf", {OUT_HEIGHT, OUT_WIDTH}, p_float32, a_output);
resize.store_in(&output_buf);
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
codegen({
c_input.get_buffer(),
&output_buf
}, "build/generated_fct_resize.o");
return 0;
}
| 29.975 | 111 | 0.449541 | akmaru |
82c0f7cd93a78771fc18805fd2e8c07344645e07 | 2,886 | cc | C++ | project2/solution/solution2.cc | EverNebula/CompilerProject-2020Spring | 513173a74f0062e09adbfba0fdef2a5816ef75b5 | [
"MIT"
] | null | null | null | project2/solution/solution2.cc | EverNebula/CompilerProject-2020Spring | 513173a74f0062e09adbfba0fdef2a5816ef75b5 | [
"MIT"
] | null | null | null | project2/solution/solution2.cc | EverNebula/CompilerProject-2020Spring | 513173a74f0062e09adbfba0fdef2a5816ef75b5 | [
"MIT"
] | null | null | null | // this is a silly solution
// just to show you how different
// components of this framework work
// please bring your wise to write
// a 'real' solution :)
#include <iostream>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include <dirent.h>
#include <json/json.h>
#include "parser.h"
#include "IRVisitor.h"
#include "printer.h"
using std::string;
// debug output
#define VERBOSE
#ifdef VERBOSE
#define dprintf(format, ...) printf(format, ##__VA_ARGS__)
#else
#define dprintf(format, ...)
#endif
void real();
void readjson(std::ifstream &ifile);
int main() {
Printer Mypt;
std::cout << "call real()" << std::endl;
real();
return 0;
}
void real(){
//std::cout << "Try to open directory PROJ_ROOT_DIR/project1/cases" << std::endl;
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("../project2/cases/")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
char jsonfilename[256] = "../project2/cases/";
if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name,"..") == 0)
continue;
strcat(jsonfilename, ent->d_name);
printf ("%s\n", jsonfilename);
std::ifstream ifile(jsonfilename, std::ios::in);
readjson(ifile);
// break;
}
closedir (dir);
} else {
/* could not open directory */
std::cout << "Could not open directory \"cases\"" << std::endl;
return ;
}
}
void readjson(std::ifstream &ifile){
Json::CharReaderBuilder rbuilder;
rbuilder["collectComments"] = false;
Json::Value root_group;
Json::String errs;
bool parse_ok = Json::parseFromStream(rbuilder, ifile, &root_group, &errs);
if(!parse_ok){
std::cout << "Json::parseFromStream failed!" << std::endl;
return;
}
std::string name = root_group["name"].asString();
std::string data_type = root_group["data_type"].asString();
std::string kernel = root_group["kernel"].asString();
std::vector<string> insvec;
std::vector<string> outvec;
std::vector<string> gradto;
for(auto &insval : root_group["ins"])
insvec.push_back(insval.asString());
for(auto &outval : root_group["outs"])
outvec.push_back(outval.asString());
for(auto &gradval : root_group["grad_to"])
gradto.push_back(gradval.asString());
Parser psr(name, insvec, outvec, gradto,data_type, kernel);
psr.build_Kernel();
// Expr tref = psr.parse_RHS("A<4>[k]+B<7,8>[j+1,j+2]");
// parse_P(string("A<16, 32>[i, j] = A<16, 32>[i, j] + alpha<1> * (B<16, 32>[i, k] * C<32, 32>[k, j]); A<16, 32>[i, j] = A<16, 32>[i, j] + beta<1> * D<16, 32>[i, j];"));
}
| 30.0625 | 174 | 0.577963 | EverNebula |
82c2efabff35347dc9d65dbdcc676b2784997b8a | 554 | cpp | C++ | cppcheck/data/c_files/387.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | 2 | 2022-03-23T12:16:20.000Z | 2022-03-31T06:19:40.000Z | cppcheck/data/c_files/387.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | null | null | null | cppcheck/data/c_files/387.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | null | null | null | static int parse_token(char **name, char **value, char **cp)
{
char *end;
if (!name || !value || !cp)
return -BLKID_ERR_PARAM;
if (!(*value = strchr(*cp, '=')))
return 0;
**value = '\0';
*name = strip_line(*cp);
*value = skip_over_blank(*value + 1);
if (**value == '"') {
end = strchr(*value + 1, '"');
if (!end) {
DBG(READ, ul_debug("unbalanced quotes at: %s", *value));
*cp = *value;
return -BLKID_ERR_CACHE;
}
(*value)++;
*end = '\0';
end++;
} else {
end = skip_over_word(*value);
if (*end) {
*end = '\0';
end++;
}
}
*cp = end;
return 1;
}
| 15.388889 | 60 | 0.559567 | awsm-research |
82c6c8b697af5086554092edf799f341264df045 | 2,064 | cpp | C++ | src/_leetcode/leet_1104.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_1104.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_1104.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | /*
* ====================== leet_1104.cpp ==========================
* -- tpr --
* CREATE -- 2020.06.02
* MODIFY --
* ----------------------------------------------------------
* 1104. 二叉树寻路
*/
#include "innLeet.h"
#include "TreeNode1.h"
#include "ListNode.h"
namespace leet_1104 {//~
// 45% 100%
// 先生产 正常完全二叉树的 数组
// 然后把其中,反转的 层,修改下
class S{
std::vector<int> lvlLstIdxs {};//每层尾元素序号(基于1)
void init_lvlLstIdxs( int N ){
lvlLstIdxs.push_back(0);//[0]空置
int v = 1;
for( int i=1; i<=N; i++ ){
v *= 2;
lvlLstIdxs.push_back( v-1 );
}
}
// deep based on 1
int calc_mirror( int v, int deep ){
int l = lvlLstIdxs.at(deep-1)+1;
int r = lvlLstIdxs.at(deep);
return r-(v-l);
}
public:
std::vector<int> pathInZigZagTree( int label ){
//== 如果路径长度为 偶数,说明 最后一位所在的 行,也应该是反的
// 那就应该,先找到 label 对应的行内镜像值,在用这个镜像值,求出表。
int roadN = 0;
for( int i=label; i!=0; i>>=1 ){ roadN++; }
//== 准备好 lvlLstIdxs
init_lvlLstIdxs( roadN );
int target = (roadN&1)==0 ? calc_mirror(label,roadN) : label;
std::deque<int> que {};
for( int i=target; i!=0; i>>=1 ){
que.push_front(i);
}
std::vector<int> road (que.begin(), que.end());
// 将所有 偶数行 都取镜像值
for( int i=1; i<roadN-1; i++ ){// 尾部元素就算是偶数行 也先不管
if( (i&1)==1 ){// 只处理偶数
road.at(i) = calc_mirror( road.at(i), i+1 );
}
}
if( (roadN&1)==0 ){
road.back() = label;
}
return road;
}
};
// 方法2:
// 只计算 label 的镜像点
// 然后同时 生成两个点的 路径数组
// 最后将偶数位 交换一下
// 理论上这个方法会更快...
//=========================================================//
void main_(){
auto ret = S{}.pathInZigZagTree( 26 );
for( int i : ret ){
cout<<i<<", ";
}cout<<endl;
debug::log( "\n~~~~ leet: 1104 :end ~~~~\n" );
}
}//~
| 21.957447 | 69 | 0.419574 | turesnake |
82c947f0467bde2e2a27086163d6cc8616624ef2 | 1,394 | cpp | C++ | boost/libs/phoenix/test/bll_compatibility/ret_test.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | boost/libs/phoenix/test/bll_compatibility/ret_test.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | boost/libs/phoenix/test/bll_compatibility/ret_test.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | // ret_test.cpp - The Boost Lambda Library -----------------------
//
// Copyright (C) 2009 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see www.boost.org
#include <boost/test/minimal.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_same.hpp>
template<class R, class F>
void test_ret(R r, F f) {
typename F::result_type x = f();
BOOST_MPL_ASSERT((boost::is_same<R, typename F::result_type>));
BOOST_CHECK(x == r);
}
template<class R, class F, class T1>
void test_ret(R r, F f, T1& t1) {
typename F::result_type x = f(t1);
BOOST_MPL_ASSERT((boost::is_same<R, typename F::result_type>));
BOOST_CHECK(x == r);
}
class add_result {
public:
add_result(int i = 0) : value(i) {}
friend bool operator==(const add_result& lhs, const add_result& rhs) {
return(lhs.value == rhs.value);
}
private:
int value;
};
class addable {};
add_result operator+(addable, addable) {
return add_result(7);
}
int test_main(int, char*[]) {
addable test;
test_ret(add_result(7), boost::lambda::ret<add_result>(boost::lambda::_1 + test), test);
test_ret(8.0, boost::lambda::ret<double>(boost::lambda::constant(7) + 1));
return 0;
}
| 25.814815 | 92 | 0.659254 | randolphwong |
82c96ffa113d67ab520d70196302937826e83085 | 200 | cpp | C++ | bucket_97/recoll/patches/patch-utils_fileudi.cpp | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 17 | 2017-04-22T21:53:52.000Z | 2021-01-21T16:57:55.000Z | bucket_97/recoll/patches/patch-utils_fileudi.cpp | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 186 | 2017-09-12T20:46:52.000Z | 2021-11-27T18:15:14.000Z | bucket_97/recoll/patches/patch-utils_fileudi.cpp | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 74 | 2017-09-06T14:48:01.000Z | 2021-08-28T02:48:27.000Z | --- utils/fileudi.cpp.orig 2020-09-05 07:43:16 UTC
+++ utils/fileudi.cpp
@@ -18,6 +18,7 @@
#include <cstdlib>
#include <iostream>
+#include <sys/types.h>
#include "fileudi.h"
#include "md5.h"
| 18.181818 | 50 | 0.64 | jrmarino |
82cac00fbe9e4525df27de88947d694f46f7391f | 3,062 | hpp | C++ | include/argumentative/argument/Argument.hpp | ViralTaco/Argumentative | 9dba6cb5de53df75616ec823d8dc211f0ec78296 | [
"MIT"
] | 1 | 2020-10-03T05:09:49.000Z | 2020-10-03T05:09:49.000Z | include/argumentative/argument/Argument.hpp | ViralTaco/Argumentative | 9dba6cb5de53df75616ec823d8dc211f0ec78296 | [
"MIT"
] | null | null | null | include/argumentative/argument/Argument.hpp | ViralTaco/Argumentative | 9dba6cb5de53df75616ec823d8dc211f0ec78296 | [
"MIT"
] | null | null | null | #ifndef VT_ARGUMENT_HPP
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ Argument.hpp: ┃
// ┃ Copyright (c) 2020 viraltaco_ (viraltaco@gmx.com) ┃
// ┃ https://github.com/ViralTaco ┃
// ┃ SPDX-License-Identifier: MIT ┃
// ┃ <http://www.opensource.org/licenses/MIT> ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
#define VT_ARGUMENT_HPP "2.2.1"
#include "../utils/typealias.hpp"
#include "../utils/swap_sign.hpp"
#include "errors/InvalidOption.hpp"
#include <string_view>
#include <string>
#include <iostream>
#include <iomanip>
#include <utility>
#include <algorithm>
namespace argumentative {
enum class ArgKind {
version,
option,
flag,
help
};
struct Argument {
public: // MARK: aliases
using Self = Argument;
public: // MARK: members
static constexpr auto kTag = "--";
ArgKind kind;
String name;
StringView help;
String description;
String value;
bool seen = false;
public: // MARK: init
Argument(ArgKind kind, StringView name, StringView help) noexcept
: kind{ kind }
, name{ String(kTag).append(name) }
, help{ help }
, description{ this->to_string() }
, value{ }
, seen{ kind == ArgKind::help or kind == ArgKind::version }
{}
Argument(StringView name, StringView help) noexcept
: Argument{ ArgKind::flag, name, help }
{}
Argument() noexcept = delete;
Argument(Self const&) noexcept = default;
Argument(Self&&) = default;
Argument& operator =(Self const&) noexcept = default;
virtual ~Argument() = default;
public: // MARK: instance methods
[[nodiscard]] String to_string() const {
auto str = StringStream();
str << '[' << name;
switch (kind) {
case ArgKind::option:
str << " <" << name.substr(2) << ">]";
break;
default:
str << ']';
break;
}
return str.str();
}
bool in(Vector<StringView> const& argv) {
const auto end = std::end(argv);
auto arg = std::find(std::begin(argv), end, this->name);
if (not (this->seen = arg != end)) {
return false;
} else if (kind == ArgKind::option) {
if ((++arg) != end) {
this->value = *arg;
} else {
throw InvalidOption(name);
}
}
return this->seen;
}
public: // MARK: operator overloads
explicit operator bool() const noexcept {
return seen;
}
Argument& operator =(String const& arg) {
value = arg;
return *this;
}
bool operator ==(StringView rhs) const noexcept {
return name == rhs;
}
bool operator ==(Argument const& rhs) const noexcept {
return name == rhs.name;
}
public: // MARK: friend operator overloads
friend std::ostream&
operator <<(std::ostream& out, Self const& self) noexcept {
const auto padding = 20 - self.name.length();
return out << self.name << std::setw((padding > 0) ? padding : 1)
<< std::right << '\t' << self.help;
}
};
} namespace ive = argumentative;
#endif
| 23.921875 | 70 | 0.567929 | ViralTaco |
82cd932e95e55306d18326596ec619fd1d01e2ca | 5,424 | cpp | C++ | extra/facs/cytolib/src/CytoFrameView.cpp | scignscape/PGVM | e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0 | [
"BSL-1.0"
] | null | null | null | extra/facs/cytolib/src/CytoFrameView.cpp | scignscape/PGVM | e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0 | [
"BSL-1.0"
] | null | null | null | extra/facs/cytolib/src/CytoFrameView.cpp | scignscape/PGVM | e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0 | [
"BSL-1.0"
] | null | null | null | // Copyright 2019 Fred Hutchinson Cancer Research Center
// See the included LICENSE file for details on the licence that is granted to the user of this software.
#include <cytolib/CytoFrameView.hpp>
#include <cytolib/global.hpp>
namespace cytolib
{
CytoFramePtr CytoFrameView::get_cytoframe_ptr() const{
if(ptr_)
return ptr_;
else
throw(domain_error("Empty CytoFrameView!"));
}
vector<string> CytoFrameView::get_channels() const{
vector<string> orig = get_cytoframe_ptr()->get_channels();
unsigned n = col_idx_.size();
if(!is_col_indexed_)
return orig;
else if(n == 0)
return vector<string>();
else
{
vector<string> res(n);
for(unsigned i = 0; i < n; i++)
res[i] = orig[col_idx_[i]];
return res;
}
}
vector<string> CytoFrameView::get_markers() const{
vector<string> orig = get_cytoframe_ptr()->get_markers();
unsigned n = col_idx_.size();
if(!is_col_indexed_)
return orig;
else if(n == 0)
return vector<string>();
else
{
vector<string> res(n);
for(unsigned i = 0; i < n; i++)
res[i] = orig[col_idx_[i]];
return res;
}
}
/*subsetting*/
void CytoFrameView::cols_(vector<string> colnames, ColType col_type)
{
uvec col_idx = get_cytoframe_ptr()->get_col_idx(colnames, col_type);//idx from original frame
if(is_col_indexed())//convert abs idex to relative indx
{
for(unsigned i = 0; i < col_idx.size(); i++)
{
auto it = std::find(col_idx_.begin(), col_idx_.end(), col_idx[i]);
if(it == col_idx_.end())
throw(domain_error(colnames[i] + " not present in the current cytoframeView!"));
col_idx[i] = it - col_idx_.begin();
}
}
//update params
CytoFrameView::cols_(col_idx);
}
/**
*
* @param col_idx column index relative to view
*/
void CytoFrameView::cols_(uvec col_idx)
{
if(col_idx.is_empty()){
col_idx_.reset();
}else{
unsigned max_idx = col_idx.max();
unsigned min_idx = col_idx.min();
if(max_idx >= n_cols() || min_idx < 0)
throw(domain_error("The size of the new col index is not within the original mat size!"));
if(is_col_indexed())//covert relative idx to abs idx
{
// cout << "indexing " << endl;
for(auto & i : col_idx)
{
// cout << "relative idx: " << i << " abs: " << col_idx_[i] << endl;
i = col_idx_[i];
}
}
col_idx_ = col_idx;
}
is_col_indexed_ = true;
}
void CytoFrameView::cols_(vector<unsigned> col_idx)
{
cols_(arma::conv_to<uvec>::from(col_idx));
}
void CytoFrameView::rows_(vector<unsigned> row_idx)
{
rows_(arma::conv_to<uvec>::from(row_idx));
}
void CytoFrameView::rows_(uvec row_idx)
{
if(row_idx.is_empty()){
row_idx_.reset();
}else{
unsigned max_idx = row_idx.max();
unsigned min_idx = row_idx.min();
if(max_idx >= n_rows() || min_idx < 0)
throw(domain_error("The size of the new row index ("
+ to_string(min_idx) + "," + to_string(min_idx)
+ ") is not within the original mat size (0, " + to_string(n_rows()) + ")"
)
);
if(is_row_indexed())
{
for(auto & i : row_idx)
i = row_idx_[i];
}
row_idx_ = row_idx;
}
is_row_indexed_ = true;
}
/**
* Corresponding to the original $Pn FCS TEXT
* @return
*/
vector<unsigned> CytoFrameView::get_original_col_ids() const
{
unsigned n = n_cols();
vector<unsigned> res(n);
for(unsigned i = 0; i < n; i++)
if(is_col_indexed())
res[i] = col_idx_[i];
else
res[i] = i;
return res;
}
unsigned CytoFrameView::n_cols() const
{
if(is_col_indexed_)
return col_idx_.size();
else
return get_cytoframe_ptr()->n_cols();
}
/**
* get the number of rows(or events)
* @return
*/
unsigned CytoFrameView::n_rows() const
{
//read nEvents
if(is_row_indexed_)
return row_idx_.size();
else
return get_cytoframe_ptr()->n_rows();
}
void CytoFrameView::set_data(const EVENT_DATA_VEC & data_in){
if(is_empty()){
// Setting empty to empty is an allowed no-op, but not setting empty to non-empty
if(!data_in.is_empty()){
throw(domain_error("Cannot assign non-empty input data to empty CytoFrameView!"));
}
}else{
//fetch the original view of data
EVENT_DATA_VEC data_orig = get_cytoframe_ptr()->get_data();
//update it
if(is_col_indexed_&&is_row_indexed_)
data_orig.submat(row_idx_, col_idx_) = data_in;
else if(is_row_indexed_)
data_orig.rows(row_idx_) = data_in;
else if(is_col_indexed_)
data_orig.cols(col_idx_) = data_in;
else
if(data_orig.n_cols!=data_in.n_cols||data_orig.n_rows!=data_in.n_rows)
throw(domain_error("The size of the input data is different from the cytoframeview!"));
else
data_orig = data_in;
//write back to ptr_
get_cytoframe_ptr()->set_data(data_orig);
}
}
EVENT_DATA_VEC CytoFrameView::get_data() const
{
EVENT_DATA_VEC data;
if(is_empty()){
data = EVENT_DATA_VEC(n_rows(), n_cols());
}else{
auto ptr = get_cytoframe_ptr();
if(is_col_indexed()&&is_row_indexed())
data = ptr->get_data(row_idx_, col_idx_);
else if(is_col_indexed())
{
data = ptr->get_data(col_idx_, true);
}else if(is_row_indexed())
data = ptr->get_data(row_idx_, false);
else
data = ptr->get_data();
}
return data;
}
CytoFrameView CytoFrameView::copy(const string & h5_filename) const
{
CytoFrameView cv(*this);
cv.ptr_ = get_cytoframe_ptr()->copy(h5_filename);
return cv;
}
};
| 24.542986 | 105 | 0.652102 | scignscape |
82d1fc26d7458c48624822d264f6e087ff93ea48 | 2,498 | cpp | C++ | source/core/scene.cpp | acdemiralp/magpie | adc6594784363278e06f1edb1868a72ca6c45612 | [
"MIT"
] | 4 | 2020-03-03T15:16:41.000Z | 2022-02-06T12:03:39.000Z | source/core/scene.cpp | acdemiralp/magpie | adc6594784363278e06f1edb1868a72ca6c45612 | [
"MIT"
] | null | null | null | source/core/scene.cpp | acdemiralp/magpie | adc6594784363278e06f1edb1868a72ca6c45612 | [
"MIT"
] | 1 | 2021-02-24T14:08:00.000Z | 2021-02-24T14:08:00.000Z | #include <magpie/core/scene.hpp>
#include <magpie/core/logger.hpp>
#include <magpie/graphics/transform.hpp>
namespace mp
{
void append_scene(scene* source, scene* target)
{
auto source_entities = source->entities();
auto target_entities = std::vector<entity*>();
const std::function<void(entity*, entity*)> recursive_add_entity = [&] (mp::entity* source_entity, mp::entity* parent)
{
auto entity = target->copy_entity(source_entity);
auto transform = entity->component<mp::transform>();
auto metadata = entity->component<mp::metadata> ();
metadata ->entity = entity;
transform->set_children({});
if (parent) transform->set_parent(parent->component<mp::transform>());
target_entities.push_back(entity);
for (auto child : source_entity->component<mp::transform>()->children())
recursive_add_entity(*std::find_if(
source_entities.begin(),
source_entities.end (),
[&] (mp::entity* iteratee)
{
return child == iteratee->component<mp::transform>();
}),
entity);
};
for (auto& entity : source_entities)
if (!entity->component<transform>()->parent())
recursive_add_entity(entity, nullptr);
}
void print_scene (const scene* scene)
{
const std::function<void(entity*, std::size_t)> recursive_print = [&] (entity* entity, const std::size_t depth)
{
if (entity->has_components<metadata>())
logger->info("{}- {} ({})", depth > 0 ? std::string(depth, ' ') : "", entity->component<metadata>()->name, entity->bitset().to_string());
auto entities = scene ->entities <transform>();
auto children = entity->component<transform>()->children();
for (auto child : children)
recursive_print(*std::find_if(entities.begin(), entities.end(), [&] (mp::entity* iteratee) {return iteratee->component<transform>() == child;}), depth + 1);
};
logger->info("{}", std::string(50, '#'));
logger->info("Transformless Entities");
for (auto entity : scene->entities())
if (!entity->has_components<transform>() && entity->has_components<metadata>())
logger->info("- {} ({})", entity->component<metadata>()->name, entity->bitset().to_string());
logger->info("{}", std::string(50, '#'));
logger->info("Transform Hierarchy");
for (auto entity : scene->entities())
if ( entity->has_components<transform>() && !entity->component<transform>()->parent())
recursive_print(entity, 0);
logger->info("{}", std::string(50, '#'));
}
} | 36.735294 | 162 | 0.640913 | acdemiralp |
82d214d29af3a1269b0a24ccce5077b0da44502c | 7,135 | cpp | C++ | 3DRadSpace/3DRadSpaceDll/Model3D.cpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | 9 | 2017-01-10T11:47:06.000Z | 2021-11-27T14:32:55.000Z | 3DRadSpace/3DRadSpaceDll/Model3D.cpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | null | null | null | 3DRadSpace/3DRadSpaceDll/Model3D.cpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | 6 | 2017-07-08T23:03:43.000Z | 2022-03-08T07:47:13.000Z | #include "Model3D.hpp"
inline Engine3DRadSpace::VertexDeclDeterminantFlag Engine3DRadSpace::operator|(VertexDeclDeterminantFlag a, VertexDeclDeterminantFlag b)
{
return static_cast<VertexDeclDeterminantFlag>(static_cast<int>(a) | static_cast<int>(b));
}
inline Engine3DRadSpace::VertexDeclDeterminantFlag Engine3DRadSpace::operator|=(VertexDeclDeterminantFlag a, VertexDeclDeterminantFlag b)
{
return static_cast<VertexDeclDeterminantFlag>(static_cast<int>(a) | static_cast<int>(b));
}
inline Engine3DRadSpace::VertexDeclDeterminantFlag Engine3DRadSpace::operator&(VertexDeclDeterminantFlag a, VertexDeclDeterminantFlag b)
{
return static_cast<VertexDeclDeterminantFlag>(static_cast<int>(a) & static_cast<int>(b));
}
Engine3DRadSpace::Model3D::Model3D(Game* game, const char* file)
{
this->device = game->GetDevice();
this->context = game->GetDeviceContext();
this->_loaded = false;
Assimp::Importer importer;
aiScene* scene = (aiScene*)importer.ReadFile(file, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_CalcTangentSpace | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials | aiProcess_OptimizeMeshes | aiProcess_MakeLeftHanded | aiProcess_OptimizeGraph);
if (scene == nullptr)
throw ResourceCreationException("Failed to load the file!", typeid(Model3D));
NumMeshes = scene->mNumMeshes;
if (NumMeshes == 0 || !scene->HasMeshes())
throw ResourceCreationException("Attempted to load a model without any meshes!", typeid(Model3D));
Meshes = new MeshPart<void>*[NumMeshes];
MeshFlags = new VertexDeclDeterminantFlag[NumMeshes];
//NumTextures = scene->mNumTextures;
NumTextures = 0;
size_t i;
for (i = 0; i < scene->mNumMaterials; i++)
{
aiString loadpath;
aiReturn r = scene->mMaterials[i]->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &loadpath);
if (r != aiReturn::aiReturn_SUCCESS)
throw ResourceCreationException("Failed to load a model texture!", typeid(Texture2D));
else
NumTextures += 1;
}
Textures = new Texture2D * [NumTextures];
for (i = 0; i < scene->mNumMaterials; i++)
{
aiString loadpath;
aiReturn r = scene->mMaterials[i]->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &loadpath);
if (r == aiReturn::aiReturn_SUCCESS)
{
Textures[i] = new Texture2D(game, loadpath.C_Str());
}
else
throw ResourceCreationException("How did we get here?????", typeid(Texture2D));
}
/*
for (i = 0; i < NumTextures; i++)
{
if (scene->mTextures[i]->mHeight != 0)
{
this->Textures[i] = new Texture2D(game, scene->mTextures[i]->pcData, scene->mTextures[i]->mWidth * scene->mTextures[i]->mHeight);
}
}*/
for (i = 0; i < NumMeshes; i++)
{
//We won't allow creating lines, dots and empty meshes
if (!scene->mMeshes[i]->HasFaces() || scene->mMeshes[i]->mNumVertices < 2)
{
Meshes[i] = nullptr;
continue;
}
//determine the vertex buffer layout
MeshFlags[i] = VertexDeclDeterminantFlag::Position;
if (scene->mMeshes[i]->HasNormals()) MeshFlags[i] |= VertexDeclDeterminantFlag::Normal;
if (scene->mMeshes[i]->HasTangentsAndBitangents()) MeshFlags[i] |= VertexDeclDeterminantFlag::TangentBitangent;
unsigned NumVColors = scene->mMeshes[i]->GetNumUVChannels();
if (NumVColors == 1) MeshFlags[i] |= VertexDeclDeterminantFlag::SingleVertexColor;
else if (NumVColors > 1) throw ResourceCreationException("Multiple color channels not supported", typeid(Model3D));//MeshFlags[i] |= VertexDeclDeterminantFlag::MultipleVertexColors;
unsigned NumUV = scene->mMeshes[i]->GetNumUVChannels();
if (NumUV == 1) MeshFlags[i] |= VertexDeclDeterminantFlag::SingleUV;
else if (NumUV > 1) throw ResourceCreationException("Multiple UV channels not supported", typeid(Model3D));//MeshFlags[i] |= VertexDeclDeterminantFlag::MultipleUVs;
bool hasNormals = CheckVertexDeclDeterminant(MeshFlags[i], VertexDeclDeterminantFlag::Normal);
bool hasVertexColor = CheckVertexDeclDeterminant(MeshFlags[i], VertexDeclDeterminantFlag::SingleVertexColor);
bool hasTangentBitangent = CheckVertexDeclDeterminant(MeshFlags[i], VertexDeclDeterminantFlag::TangentBitangent);
bool hasUV = CheckVertexDeclDeterminant(MeshFlags[i], VertexDeclDeterminantFlag::SingleUV);
//determine vertex buffer size
size_t vertexbuffersize = scene->mMeshes[i]->mNumVertices;
size_t vertexdeclsize = sizeof(Vector4);
if (hasNormals)
vertexdeclsize += sizeof(Vector4);
if (hasVertexColor)
vertexdeclsize += sizeof(ColorShader);
if (hasTangentBitangent)
vertexdeclsize += 2 * sizeof(Vector4);
if (hasUV)
vertexdeclsize += sizeof(Vector4);
//create vertex buffer in memory
size_t finalvertexbuffersize = (vertexdeclsize * vertexbuffersize) / 4;
float* vertexbuffer = new float[finalvertexbuffersize];
//memset(vertexbuffer, 0, sizeof(float) * finalvertexbuffersize);
for (unsigned pos = 0, j = 0; pos < finalvertexbuffersize; j++)
{
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mVertices[j]), sizeof(Vector3));
pos += 4;
if (hasNormals)
{
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mNormals[j]), sizeof(Vector3));
pos += 4;
}
if (hasVertexColor)
{
memcpy_s(vertexbuffer + pos, sizeof(ColorShader), &(scene->mMeshes[i]->mColors[0][j]), sizeof(ColorShader));
pos += 4;
}
if (hasTangentBitangent)
{
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mTangents[j]), sizeof(Vector3));
pos += 4;
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mBitangents[j]), sizeof(Vector3));
pos += 4;
}
if (hasUV)
{
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mTextureCoords[0][j]), sizeof(Vector3));
pos += 4;
}
}
//create index buffer
size_t indexbuffersize = scene->mMeshes[i]->mNumFaces * 3; //faces are triangulated, so multiply with 3
unsigned* indexbuffer = new unsigned[indexbuffersize];
for (unsigned j = 0; j < indexbuffersize; j += 3)
{
memcpy_s(indexbuffer + j, sizeof(unsigned) * 3, scene->mMeshes[i]->mFaces[j].mIndices, sizeof(unsigned) * 3);
}
VertexBuffer<void>* vertexbuffer_f = new VertexBuffer<void>(vertexbuffer, vertexbuffersize, vertexdeclsize);
IndexBuffer* indexbuffer_f = new IndexBuffer(indexbuffer, indexbuffersize);
this->Meshes[i] = new MeshPart<void>(vertexbuffer_f, indexbuffer_f, Textures[scene->mMeshes[i]->mMaterialIndex]);
this->_loaded = true;
}
}
bool Engine3DRadSpace::Model3D::CheckVertexDeclDeterminant(VertexDeclDeterminantFlag flag, VertexDeclDeterminantFlag comp)
{
return (comp == (flag & comp));
}
void Engine3DRadSpace::Model3D::Draw()
{
for (size_t i = 0; i < NumMeshes; i++)
{
this->Meshes[i]->Draw(context);
}
}
Engine3DRadSpace::Model3D::~Model3D()
{
size_t i;
for (i = 0; i < NumMeshes; i++)
{
if (this->Meshes[i] != nullptr) delete this->Meshes[i];
}
delete[] this->Meshes;
delete[] this->MeshFlags;
for (i = 0; i < NumTextures; i++)
{
if (this->Textures[i] != nullptr) delete this->Textures[i];
}
delete[] this->Textures;
this->Meshes = nullptr;
this->MeshFlags = nullptr;
this->Textures = nullptr;
}
| 34.97549 | 288 | 0.723616 | NicusorN5 |
82d5a6fa8fd7b4dec64b4eec6bc738bd3942a30c | 495 | cpp | C++ | app_v01/src/app/main.cpp | azaremde/cpp-opengl-gamedev | f4d02e955b401fc78321a23f91809662fefcda92 | [
"Apache-2.0"
] | null | null | null | app_v01/src/app/main.cpp | azaremde/cpp-opengl-gamedev | f4d02e955b401fc78321a23f91809662fefcda92 | [
"Apache-2.0"
] | null | null | null | app_v01/src/app/main.cpp | azaremde/cpp-opengl-gamedev | f4d02e955b401fc78321a23f91809662fefcda92 | [
"Apache-2.0"
] | null | null | null | #define ENGINE_DEBUG_MODE
#include "environment/window.h"
#include "layers/layer_manager.h"
#include "gui_layer.h"
#include "graphics_layer.h"
int main()
{
window_init();
layers::layer_manager.add_layer(new GUILayer());
layers::layer_manager.add_layer(new GraphicsLayer());
layers::layer_manager.init();
while (!window_should_close())
{
window_poll_events();
layers::layer_manager.update();
window_swap_buffers();
window_clear_state();
}
window_shutdown();
return 0;
} | 15.967742 | 54 | 0.735354 | azaremde |
82d6d7e6ab1bd78c0f800a5ab4cbfd7488b671f2 | 2,237 | cpp | C++ | folly/synchronization/test/BatonBenchmark.cpp | Aoikiseki/folly | df3633c731d08bab0173039a050a30853fb47212 | [
"Apache-2.0"
] | 19,046 | 2015-01-01T17:01:10.000Z | 2022-03-31T23:01:43.000Z | folly/synchronization/test/BatonBenchmark.cpp | Aoikiseki/folly | df3633c731d08bab0173039a050a30853fb47212 | [
"Apache-2.0"
] | 1,493 | 2015-01-11T15:47:13.000Z | 2022-03-28T18:13:58.000Z | folly/synchronization/test/BatonBenchmark.cpp | Aoikiseki/folly | df3633c731d08bab0173039a050a30853fb47212 | [
"Apache-2.0"
] | 4,818 | 2015-01-01T12:28:16.000Z | 2022-03-31T16:22:10.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/synchronization/Baton.h>
#include <thread>
#include <folly/Benchmark.h>
#include <folly/synchronization/NativeSemaphore.h>
#include <folly/synchronization/test/BatonTestHelpers.h>
#include <folly/test/DeterministicSchedule.h>
using namespace folly::test;
using folly::detail::EmulatedFutexAtomic;
BENCHMARK(baton_pingpong_blocking, iters) {
run_pingpong_test<true, std::atomic>(iters);
}
BENCHMARK(baton_pingpong_nonblocking, iters) {
run_pingpong_test<false, std::atomic>(iters);
}
BENCHMARK_DRAW_LINE();
BENCHMARK(baton_pingpong_emulated_futex_blocking, iters) {
run_pingpong_test<true, EmulatedFutexAtomic>(iters);
}
BENCHMARK(baton_pingpong_emulated_futex_nonblocking, iters) {
run_pingpong_test<false, EmulatedFutexAtomic>(iters);
}
BENCHMARK_DRAW_LINE();
BENCHMARK(native_sem_pingpong, iters) {
alignas(folly::hardware_destructive_interference_size)
folly::NativeSemaphore a;
alignas(folly::hardware_destructive_interference_size)
folly::NativeSemaphore b;
auto thr = std::thread([&] {
for (size_t i = 0; i < iters; ++i) {
a.wait();
b.post();
}
});
for (size_t i = 0; i < iters; ++i) {
a.post();
b.wait();
}
thr.join();
}
// I am omitting a benchmark result snapshot because these microbenchmarks
// mainly illustrate that PreBlockAttempts is very effective for rapid
// handoffs. The performance of Baton and sem_t is essentially identical
// to the required futex calls for the blocking case
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
folly::runBenchmarks();
return 0;
}
| 28.679487 | 75 | 0.738936 | Aoikiseki |
82d92d0839449f2e8ddbc75dbf81995fd62d2e80 | 4,706 | cpp | C++ | sensors/SensorBase.cpp | Huawei-mt6737/device | baec9804cf904c17d2abd45a1ecddde384ec22b7 | [
"FTL"
] | 2 | 2018-12-24T09:37:43.000Z | 2019-09-22T13:55:54.000Z | sensors/SensorBase.cpp | Huawei-mt6737/device | baec9804cf904c17d2abd45a1ecddde384ec22b7 | [
"FTL"
] | null | null | null | sensors/SensorBase.cpp | Huawei-mt6737/device | baec9804cf904c17d2abd45a1ecddde384ec22b7 | [
"FTL"
] | 8 | 2017-07-05T17:09:28.000Z | 2019-03-04T09:37:45.000Z | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2012. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>
#include <cutils/log.h>
#include <linux/input.h>
#include "SensorBase.h"
#include <utils/SystemClock.h>
#include <string.h>
#ifdef LOG_TAG
#undef LOG_TAG
#define LOG_TAG "SensorBase"
#endif
/*****************************************************************************/
SensorBase::SensorBase(
const char* dev_name,
const char* data_name)
: dev_name(dev_name), data_name(data_name),
dev_fd(-1), data_fd(-1)
{
//data_fd = openInput(data_name);
}
SensorBase::~SensorBase() {
if (data_fd >= 0) {
close(data_fd);
}
if (dev_fd >= 0) {
close(dev_fd);
}
}
int SensorBase::open_device() {
if (dev_fd<0 && dev_name) {
dev_fd = open(dev_name, O_RDONLY);
ALOGE_IF(dev_fd<0, "Couldn't open %s (%s)", dev_name, strerror(errno));
}
return 0;
}
int SensorBase::close_device() {
if (dev_fd >= 0) {
close(dev_fd);
dev_fd = -1;
}
return 0;
}
int SensorBase::getFd() const {
return data_fd;
}
int SensorBase::setDelay(int32_t handle, int64_t ns) {
ALOGD("handle=%d,ns=%lld\n",handle,ns);
return 0;
}
bool SensorBase::hasPendingEvents() const {
return false;
}
int64_t SensorBase::getTimestamp() {
return android::elapsedRealtimeNano();
}
/*
int SensorBase::openInput(const char* inputName) {
int fd = -1;
const char *dirname = "/dev/input";
char devname[PATH_MAX];
char *filename;
DIR *dir;
struct dirent *de;
dir = opendir(dirname);
if(dir == NULL)
return -1;
strcpy(devname, dirname);
filename = devname + strlen(devname);
*filename++ = '/';
while((de = readdir(dir))) {
if(de->d_name[0] == '.' &&
(de->d_name[1] == '\0' ||
(de->d_name[1] == '.' && de->d_name[2] == '\0')))
continue;
strcpy(filename, de->d_name);
fd = open(devname, O_RDONLY);
if (fd>=0) {
char name[80];
if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) {
name[0] = '\0';
}
if (!strcmp(name, inputName)) {
break;
} else {
close(fd);
fd = -1;
}
}
}
closedir(dir);
ALOGE_IF(fd<0, "couldn't find '%s' input device", inputName);
return fd;
}
*/
| 32.232877 | 95 | 0.649809 | Huawei-mt6737 |
82dc868342959ab731cfcb77da1bec85da90bd70 | 2,054 | cpp | C++ | HazelGameEngine/src/Platform/OpenGL/OpenGLVertexArray.cpp | duo131/Hazel_practice | 04eeec2550b9536e7b8a565d67630c1d2a669991 | [
"Apache-2.0"
] | null | null | null | HazelGameEngine/src/Platform/OpenGL/OpenGLVertexArray.cpp | duo131/Hazel_practice | 04eeec2550b9536e7b8a565d67630c1d2a669991 | [
"Apache-2.0"
] | null | null | null | HazelGameEngine/src/Platform/OpenGL/OpenGLVertexArray.cpp | duo131/Hazel_practice | 04eeec2550b9536e7b8a565d67630c1d2a669991 | [
"Apache-2.0"
] | null | null | null | #include "hzpch.h"
#include "OpenGLVertexArray.h"
#include <glad/glad.h>
namespace Hazel {
//temp function
static GLenum ShaderDataTypeToOpenGLBaseType(ShaderDataType type)
{
switch (type)
{
case ShaderDataType::NONE: break;
case ShaderDataType::FLOAT: return GL_FLOAT;
case ShaderDataType::FLOAT2: return GL_FLOAT;
case ShaderDataType::FLOAT3: return GL_FLOAT;
case ShaderDataType::FLOAT4: return GL_FLOAT;
case ShaderDataType::MAT3: return GL_FLOAT;
case ShaderDataType::MAT4: return GL_FLOAT;
case ShaderDataType::INT: return GL_INT;
case ShaderDataType::INT2: return GL_INT;
case ShaderDataType::INT3: return GL_INT;
case ShaderDataType::INT4: return GL_INT;
case ShaderDataType::BOOL: return GL_BOOL;
default: break;
}
HZ_CORE_ASSERT(false, "Unknow ShaderDataType!");
return 0;
}
OpenGLVertexArray::OpenGLVertexArray()
{
glCreateVertexArrays(1, &m_RendererID);
}
OpenGLVertexArray::~OpenGLVertexArray()
{
glDeleteVertexArrays(1, &m_RendererID);
}
void OpenGLVertexArray::Bind() const
{
glBindVertexArray(m_RendererID);
}
void OpenGLVertexArray::UnBind() const
{
glBindVertexArray(0);
}
void OpenGLVertexArray::AddVertexBuffer(const Ref<VertexBuffer>& vertexBuffer)
{
HZ_CORE_ASSERT(vertexBuffer->GetLaypout().GetElements().size(), "VertexBuffer has no layout");
glBindVertexArray(m_RendererID);
vertexBuffer->Bind();
uint32_t index = 0;
for (const auto& element : vertexBuffer->GetLaypout())
{
glEnableVertexAttribArray(index);
// no normalize
glVertexAttribPointer(index,
element.GetElementCount(),
ShaderDataTypeToOpenGLBaseType(element.Type),
element.Normalized ? GL_TRUE : GL_FALSE,
vertexBuffer->GetLaypout().GetStride(),
(const void*)element.Offset);
index++;
}
m_VertexBuffers.push_back(vertexBuffer);
}
void OpenGLVertexArray::SetIndexBuffer(const Ref<IndexBuffer>& indexBuffer)
{
glBindVertexArray(m_RendererID);
indexBuffer->Bind();
m_IndexBuffer = indexBuffer;
}
} | 24.164706 | 96 | 0.731256 | duo131 |
82dd0a742a3e6f7fd1298001e6f365b5ea428afc | 80,114 | cc | C++ | EnergyPlus/HighTempRadiantSystem.cc | yurigabrich/EnergyPlusShadow | 396ca83aa82b842e6b177ba35c91b3f481dfbbf9 | [
"BSD-3-Clause"
] | null | null | null | EnergyPlus/HighTempRadiantSystem.cc | yurigabrich/EnergyPlusShadow | 396ca83aa82b842e6b177ba35c91b3f481dfbbf9 | [
"BSD-3-Clause"
] | 1 | 2020-07-08T13:32:09.000Z | 2020-07-08T13:32:09.000Z | EnergyPlus/HighTempRadiantSystem.cc | yurigabrich/EnergyPlusShadow | 396ca83aa82b842e6b177ba35c91b3f481dfbbf9 | [
"BSD-3-Clause"
] | null | null | null | // EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois,
// The Regents of the University of California, through Lawrence Berkeley National Laboratory
// (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge
// National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other
// contributors. All rights reserved.
//
// NOTICE: This Software was developed under funding from the U.S. Department of Energy and the
// U.S. Government consequently retains certain rights. As such, the U.S. Government has been
// granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable,
// worldwide license in the Software to reproduce, distribute copies to the public, prepare
// derivative works, and perform publicly and display publicly, and to permit others to do so.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory,
// the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form
// without changes from the version obtained under this License, or (ii) Licensee makes a
// reference solely to the software portion of its product, Licensee must refer to the
// software as "EnergyPlus version X" software, where "X" is the version number Licensee
// obtained under this License and may not use a different name for the software. Except as
// specifically required in this Section (4), Licensee shall not use in a company name, a
// product name, in advertising, publicity, or other promotional activities any name, trade
// name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly
// similar designation, without the U.S. Department of Energy's prior written consent.
//
// 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.
// C++ Headers
#include <cassert>
#include <cmath>
// ObjexxFCL Headers
#include <ObjexxFCL/Array.functions.hh>
// EnergyPlus Headers
#include <DataHVACGlobals.hh>
#include <DataHeatBalFanSys.hh>
#include <DataHeatBalSurface.hh>
#include <DataHeatBalance.hh>
#include <DataIPShortCuts.hh>
#include <DataLoopNode.hh>
#include <DataPrecisionGlobals.hh>
#include <DataSizing.hh>
#include <DataSurfaces.hh>
#include <DataZoneEnergyDemands.hh>
#include <DataZoneEquipment.hh>
#include <General.hh>
#include <GeneralRoutines.hh>
#include <HeatBalanceSurfaceManager.hh>
#include <HighTempRadiantSystem.hh>
#include <InputProcessing/InputProcessor.hh>
#include <OutputProcessor.hh>
#include <ReportSizingManager.hh>
#include <ScheduleManager.hh>
#include <UtilityRoutines.hh>
namespace EnergyPlus {
namespace HighTempRadiantSystem {
// Module containing the routines dealing with the high temperature radiant systems
// MODULE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS MODULE:
// The purpose of this module is to simulate high temperature radiant systems.
// It is the intention of this module to cover all types of high temperature
// radiant systems (gas and electric)
// METHODOLOGY EMPLOYED:
// Based on work done in BLAST, the EnergyPlus low temperature radiant system
// model, this model has similar inherent challenges that are similar to the
// low temperature radiant system. Because it is a system that directly
// effects the surface heat balances, it must be a part of both the heat
// balance routines and linked in with the HVAC system.
// REFERENCES:
// Building Systems Laboratory, BLAST User's Guide/Reference.
// Maloney, Dan. 1987. "Development of a radiant heater model and the
// incorporation of thermal comfort considerations into the BLAST
// energy analysis program", M.S. thesis, University of Illinois at
// Urbana-Champaign (Dept. of Mechanical and Industrial Engineering).
// OTHER NOTES: none
// USE STATEMENTS:
// Use statements for data only modules
// Using/Aliasing
using namespace DataPrecisionGlobals;
using DataGlobals::BeginTimeStepFlag;
using DataGlobals::DisplayExtraWarnings;
using DataGlobals::ScheduleAlwaysOn;
using DataGlobals::SysSizingCalc;
using DataHVACGlobals::SmallLoad;
// Data
// MODULE PARAMETER DEFINITIONS:
std::string const cGas("Gas");
std::string const cNaturalGas("NaturalGas");
std::string const cElectric("Electric");
std::string const cElectricity("Electricity");
int const Gas(1);
int const Electric(2);
std::string const cMATControl("MeanAirTemperature"); // Control for using mean air temperature
std::string const cMRTControl("MeanRadiantTemperature"); // Control for using mean radiant temperature
std::string const cOperativeControl("OperativeTemperature"); // Control for using operative temperature
std::string const cMATSPControl("MeanAirTemperatureSetpoint"); // Control for to MAT setpoint
std::string const cMRTSPControl("MeanRadiantTemperatureSetpoint"); // Control for to MRT setpoint
std::string const cOperativeSPControl("OperativeTemperatureSetpoint"); // Control for operative temperature setpoint
int const MATControl(1001);
int const MRTControl(1002);
int const OperativeControl(1003);
int const MATSPControl(1004);
int const MRTSPControl(1005);
int const OperativeSPControl(1006);
static std::string const BlankString;
// DERIVED TYPE DEFINITIONS:
// MODULE VARIABLE DECLARATIONS:
// Standard, run-of-the-mill variables...
int NumOfHighTempRadSys(0); // Number of hydronic low tempererature radiant systems
Array1D<Real64> QHTRadSource; // Need to keep the last value in case we are still iterating
Array1D<Real64> QHTRadSrcAvg; // Need to keep the last value in case we are still iterating
Array1D<Real64> ZeroSourceSumHATsurf; // Equal to the SumHATsurf for all the walls in a zone with no source
// Record keeping variables used to calculate QHTRadSrcAvg locally
Array1D<Real64> LastQHTRadSrc; // Need to keep the last value in case we are still iterating
Array1D<Real64> LastSysTimeElapsed; // Need to keep the last value in case we are still iterating
Array1D<Real64> LastTimeStepSys; // Need to keep the last value in case we are still iterating
Array1D_bool MySizeFlag;
Array1D_bool CheckEquipName;
// SUBROUTINE SPECIFICATIONS FOR MODULE HighTempRadiantSystem
// Object Data
Array1D<HighTempRadiantSystemData> HighTempRadSys;
Array1D<HighTempRadSysNumericFieldData> HighTempRadSysNumericFields;
// Functions
void clear_state()
{
NumOfHighTempRadSys = 0;
QHTRadSource.deallocate();
QHTRadSrcAvg.deallocate();
ZeroSourceSumHATsurf.deallocate();
LastQHTRadSrc.deallocate();
LastSysTimeElapsed.deallocate();
LastTimeStepSys.deallocate();
MySizeFlag.deallocate();
CheckEquipName.deallocate();
HighTempRadSys.deallocate();
HighTempRadSysNumericFields.deallocate();
}
void SimHighTempRadiantSystem(std::string const &CompName, // name of the low temperature radiant system
bool const FirstHVACIteration, // TRUE if 1st HVAC simulation of system timestep
Real64 &LoadMet, // load met by the radiant system, in Watts
int &CompIndex)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine is the "manager" for the high temperature radiant
// system model. It is called from the outside and controls the
// actions and subroutine calls to lower levels as appropriate.
// METHODOLOGY EMPLOYED:
// Standard EnergyPlus manager subroutine layout
// Using/Aliasing
using General::TrimSigDigits;
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
static bool GetInputFlag(true); // First time, input is "gotten"
bool ErrorsFoundInGet; // Set to true when there are severe errors during the Get routine
int RadSysNum; // Radiant system number/index in local derived types
// FLOW:
if (GetInputFlag) {
ErrorsFoundInGet = false;
GetHighTempRadiantSystem(ErrorsFoundInGet);
if (ErrorsFoundInGet) ShowFatalError("GetHighTempRadiantSystem: Errors found in input. Preceding condition(s) cause termination.");
GetInputFlag = false;
}
// Find the correct ZoneHVAC:HighTemperatureRadiant
if (CompIndex == 0) {
RadSysNum = UtilityRoutines::FindItemInList(CompName, HighTempRadSys);
if (RadSysNum == 0) {
ShowFatalError("SimHighTempRadiantSystem: Unit not found=" + CompName);
}
CompIndex = RadSysNum;
} else {
RadSysNum = CompIndex;
if (RadSysNum > NumOfHighTempRadSys || RadSysNum < 1) {
ShowFatalError("SimHighTempRadiantSystem: Invalid CompIndex passed=" + TrimSigDigits(RadSysNum) +
", Number of Units=" + TrimSigDigits(NumOfHighTempRadSys) + ", Entered Unit name=" + CompName);
}
if (CheckEquipName(RadSysNum)) {
if (CompName != HighTempRadSys(RadSysNum).Name) {
ShowFatalError("SimHighTempRadiantSystem: Invalid CompIndex passed=" + TrimSigDigits(RadSysNum) + ", Unit name=" + CompName +
", stored Unit Name for that index=" + HighTempRadSys(RadSysNum).Name);
}
CheckEquipName(RadSysNum) = false;
}
}
InitHighTempRadiantSystem(FirstHVACIteration, RadSysNum);
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if ((SELECT_CASE_var == MATControl) || (SELECT_CASE_var == MRTControl) || (SELECT_CASE_var == OperativeControl)) {
CalcHighTempRadiantSystem(RadSysNum);
} else if ((SELECT_CASE_var == MATSPControl) || (SELECT_CASE_var == MRTSPControl) || (SELECT_CASE_var == OperativeSPControl)) {
CalcHighTempRadiantSystemSP(FirstHVACIteration, RadSysNum);
}
}
UpdateHighTempRadiantSystem(RadSysNum, LoadMet);
ReportHighTempRadiantSystem(RadSysNum);
}
void GetHighTempRadiantSystem(bool &ErrorsFound // TRUE if errors are found on processing the input
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine reads the input for high temperature radiant systems
// from the user input file. This will contain all of the information
// needed to simulate a high temperature radiant system.
// METHODOLOGY EMPLOYED:
// Standard EnergyPlus methodology.
// Using/Aliasing
using DataHeatBalance::Zone;
using DataSizing::AutoSize;
using DataSizing::CapacityPerFloorArea;
using DataSizing::FractionOfAutosizedHeatingCapacity;
using DataSizing::HeatingDesignCapacity;
using DataSurfaces::Surface;
using General::TrimSigDigits;
using ScheduleManager::GetScheduleIndex;
using namespace DataIPShortCuts;
// SUBROUTINE PARAMETER DEFINITIONS:
Real64 const MaxCombustionEffic(1.00); // Limit the combustion efficiency to perfection
Real64 const MaxFraction(1.0); // Limit the highest allowed fraction for heat transfer parts
Real64 const MinCombustionEffic(0.01); // Limit the minimum combustion efficiency
Real64 const MinFraction(0.0); // Limit the lowest allowed fraction for heat transfer parts
Real64 const MinThrottlingRange(0.5); // Smallest throttling range allowed in degrees Celsius
// INTEGER, PARAMETER :: MaxDistribSurfaces = 20 ! Maximum number of surfaces that a radiant heater can radiate to
static std::string const RoutineName("GetHighTempRadiantSystem: "); // include trailing blank space
int const iHeatCAPMAlphaNum(4); // get input index to High Temperature Radiant system heating capacity sizing method
int const iHeatDesignCapacityNumericNum(1); // get input index to High Temperature Radiant system heating capacity
int const iHeatCapacityPerFloorAreaNumericNum(2); // get input index to High Temperature Radiant system heating capacity per floor area sizing
int const iHeatFracOfAutosizedCapacityNumericNum(
3); // get input index to High Temperature Radiant system heating capacity sizing as fraction of autozized heating capacity
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
Real64 AllFracsSummed; // Sum of the fractions radiant, latent, and lost (must be <= 1)
Real64 FracOfRadPotentiallyLost; // Difference between unity and AllFracsSummed for error reporting
int IOStatus; // Used in GetObjectItem
int Item; // Item to be "gotten"
int NumAlphas; // Number of Alphas for each GetObjectItem call
int NumNumbers; // Number of Numbers for each GetObjectItem call
int SurfNum; // Surface number DO loop counter
Real64 TotalFracToSurfs; // Sum of fractions of radiation to surfaces
// FLOW:
// Initializations and allocations
NumOfHighTempRadSys = inputProcessor->getNumObjectsFound("ZoneHVAC:HighTemperatureRadiant");
HighTempRadSys.allocate(NumOfHighTempRadSys);
CheckEquipName.allocate(NumOfHighTempRadSys);
HighTempRadSysNumericFields.allocate(NumOfHighTempRadSys);
CheckEquipName = true;
// extensible object, do not need max args because using IPShortCuts
cCurrentModuleObject = "ZoneHVAC:HighTemperatureRadiant";
// Obtain all of the user data related to high temperature radiant systems...
for (Item = 1; Item <= NumOfHighTempRadSys; ++Item) {
inputProcessor->getObjectItem(cCurrentModuleObject,
Item,
cAlphaArgs,
NumAlphas,
rNumericArgs,
NumNumbers,
IOStatus,
lNumericFieldBlanks,
lAlphaFieldBlanks,
cAlphaFieldNames,
cNumericFieldNames);
HighTempRadSysNumericFields(Item).FieldNames.allocate(NumNumbers);
HighTempRadSysNumericFields(Item).FieldNames = "";
HighTempRadSysNumericFields(Item).FieldNames = cNumericFieldNames;
UtilityRoutines::IsNameEmpty(cAlphaArgs(1), cCurrentModuleObject, ErrorsFound);
// General user input data
HighTempRadSys(Item).Name = cAlphaArgs(1);
HighTempRadSys(Item).SchedName = cAlphaArgs(2);
if (lAlphaFieldBlanks(2)) {
HighTempRadSys(Item).SchedPtr = ScheduleAlwaysOn;
} else {
HighTempRadSys(Item).SchedPtr = GetScheduleIndex(cAlphaArgs(2));
if (HighTempRadSys(Item).SchedPtr == 0) {
ShowSevereError(cCurrentModuleObject + ": invalid " + cAlphaFieldNames(2) + " entered =" + cAlphaArgs(2) + " for " +
cAlphaFieldNames(1) + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
}
HighTempRadSys(Item).ZoneName = cAlphaArgs(3);
HighTempRadSys(Item).ZonePtr = UtilityRoutines::FindItemInList(cAlphaArgs(3), Zone);
if (HighTempRadSys(Item).ZonePtr == 0) {
ShowSevereError("Invalid " + cAlphaFieldNames(3) + " = " + cAlphaArgs(3));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
// HighTempRadSys( Item ).MaxPowerCapac = rNumericArgs( 1 );
// Determine High Temp Radiant heating design capacity sizing method
if (UtilityRoutines::SameString(cAlphaArgs(iHeatCAPMAlphaNum), "HeatingDesignCapacity")) {
HighTempRadSys(Item).HeatingCapMethod = HeatingDesignCapacity;
if (!lNumericFieldBlanks(iHeatDesignCapacityNumericNum)) {
HighTempRadSys(Item).ScaledHeatingCapacity = rNumericArgs(iHeatDesignCapacityNumericNum);
if (HighTempRadSys(Item).ScaledHeatingCapacity < 0.0 && HighTempRadSys(Item).ScaledHeatingCapacity != AutoSize) {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Illegal " + cNumericFieldNames(iHeatDesignCapacityNumericNum) + " = " +
TrimSigDigits(rNumericArgs(iHeatDesignCapacityNumericNum), 7));
ErrorsFound = true;
}
} else {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Blank field not allowed for " + cNumericFieldNames(iHeatDesignCapacityNumericNum));
ErrorsFound = true;
}
} else if (UtilityRoutines::SameString(cAlphaArgs(iHeatCAPMAlphaNum), "CapacityPerFloorArea")) {
HighTempRadSys(Item).HeatingCapMethod = CapacityPerFloorArea;
if (!lNumericFieldBlanks(iHeatCapacityPerFloorAreaNumericNum)) {
HighTempRadSys(Item).ScaledHeatingCapacity = rNumericArgs(iHeatCapacityPerFloorAreaNumericNum);
if (HighTempRadSys(Item).ScaledHeatingCapacity <= 0.0) {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Illegal " + cNumericFieldNames(iHeatCapacityPerFloorAreaNumericNum) + " = " +
TrimSigDigits(rNumericArgs(iHeatCapacityPerFloorAreaNumericNum), 7));
ErrorsFound = true;
} else if (HighTempRadSys(Item).ScaledHeatingCapacity == AutoSize) {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Illegal " + cNumericFieldNames(iHeatCapacityPerFloorAreaNumericNum) + " = Autosize");
ErrorsFound = true;
}
} else {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Blank field not allowed for " + cNumericFieldNames(iHeatCapacityPerFloorAreaNumericNum));
ErrorsFound = true;
}
} else if (UtilityRoutines::SameString(cAlphaArgs(iHeatCAPMAlphaNum), "FractionOfAutosizedHeatingCapacity")) {
HighTempRadSys(Item).HeatingCapMethod = FractionOfAutosizedHeatingCapacity;
if (!lNumericFieldBlanks(iHeatFracOfAutosizedCapacityNumericNum)) {
HighTempRadSys(Item).ScaledHeatingCapacity = rNumericArgs(iHeatFracOfAutosizedCapacityNumericNum);
if (HighTempRadSys(Item).ScaledHeatingCapacity < 0.0) {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Illegal " + cNumericFieldNames(iHeatFracOfAutosizedCapacityNumericNum) + " = " +
TrimSigDigits(rNumericArgs(iHeatFracOfAutosizedCapacityNumericNum), 7));
ErrorsFound = true;
}
} else {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Blank field not allowed for " + cNumericFieldNames(iHeatFracOfAutosizedCapacityNumericNum));
ErrorsFound = true;
}
} else {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Illegal " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ErrorsFound = true;
}
if (UtilityRoutines::SameString(cAlphaArgs(5), cNaturalGas)) {
HighTempRadSys(Item).HeaterType = Gas;
} else if (UtilityRoutines::SameString(cAlphaArgs(5), cElectricity)) {
HighTempRadSys(Item).HeaterType = Electric;
} else if (UtilityRoutines::SameString(cAlphaArgs(5), cGas)) {
HighTempRadSys(Item).HeaterType = Gas;
} else if (UtilityRoutines::SameString(cAlphaArgs(5), cElectric)) {
HighTempRadSys(Item).HeaterType = Electric;
} else {
ShowSevereError("Invalid " + cAlphaFieldNames(5) + " = " + cAlphaArgs(5));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
if (HighTempRadSys(Item).HeaterType == Gas) {
HighTempRadSys(Item).CombustionEffic = rNumericArgs(4);
// Limit the combustion efficiency to between zero and one...
if (HighTempRadSys(Item).CombustionEffic < MinCombustionEffic) {
HighTempRadSys(Item).CombustionEffic = MinCombustionEffic;
ShowWarningError(cNumericFieldNames(4) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).CombustionEffic > MaxCombustionEffic) {
HighTempRadSys(Item).CombustionEffic = MaxCombustionEffic;
ShowWarningError(cNumericFieldNames(4) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
} else {
HighTempRadSys(Item).CombustionEffic = MaxCombustionEffic; // No inefficiency in the heater
}
HighTempRadSys(Item).FracRadiant = rNumericArgs(5);
if (HighTempRadSys(Item).FracRadiant < MinFraction) {
HighTempRadSys(Item).FracRadiant = MinFraction;
ShowWarningError(cNumericFieldNames(5) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracRadiant > MaxFraction) {
HighTempRadSys(Item).FracRadiant = MaxFraction;
ShowWarningError(cNumericFieldNames(5) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
HighTempRadSys(Item).FracLatent = rNumericArgs(6);
if (HighTempRadSys(Item).FracLatent < MinFraction) {
HighTempRadSys(Item).FracLatent = MinFraction;
ShowWarningError(cNumericFieldNames(6) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracLatent > MaxFraction) {
HighTempRadSys(Item).FracLatent = MaxFraction;
ShowWarningError(cNumericFieldNames(6) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
HighTempRadSys(Item).FracLost = rNumericArgs(7);
if (HighTempRadSys(Item).FracLost < MinFraction) {
HighTempRadSys(Item).FracLost = MinFraction;
ShowWarningError(cNumericFieldNames(7) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracLost > MaxFraction) {
HighTempRadSys(Item).FracLost = MaxFraction;
ShowWarningError(cNumericFieldNames(7) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
// Based on the input for fractions radiant, latent, and lost, determine the fraction convective (remaining fraction)
AllFracsSummed = HighTempRadSys(Item).FracRadiant + HighTempRadSys(Item).FracLatent + HighTempRadSys(Item).FracLost;
if (AllFracsSummed > MaxFraction) {
ShowSevereError("Fractions radiant, latent, and lost sum up to greater than 1 for" + cAlphaArgs(1));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
HighTempRadSys(Item).FracConvect = 0.0;
} else {
HighTempRadSys(Item).FracConvect = 1.0 - AllFracsSummed;
}
// Process the temperature control type
if (UtilityRoutines::SameString(cAlphaArgs(6), cMATControl)) {
HighTempRadSys(Item).ControlType = MATControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cMRTControl)) {
HighTempRadSys(Item).ControlType = MRTControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cOperativeControl)) {
HighTempRadSys(Item).ControlType = OperativeControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cMATSPControl)) {
HighTempRadSys(Item).ControlType = MATSPControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cMRTSPControl)) {
HighTempRadSys(Item).ControlType = MRTSPControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cOperativeSPControl)) {
HighTempRadSys(Item).ControlType = OperativeSPControl;
} else {
ShowWarningError("Invalid " + cAlphaFieldNames(6) + " = " + cAlphaArgs(6));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ShowContinueError("Control reset to OPERATIVE control for this " + cCurrentModuleObject);
HighTempRadSys(Item).ControlType = OperativeControl;
}
HighTempRadSys(Item).ThrottlRange = rNumericArgs(8);
if (HighTempRadSys(Item).ThrottlRange < MinThrottlingRange) {
HighTempRadSys(Item).ThrottlRange = 1.0;
ShowWarningError(cNumericFieldNames(8) + " is below the minimum allowed.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ShowContinueError("Thus, the throttling range value has been reset to 1.0");
}
HighTempRadSys(Item).SetptSched = cAlphaArgs(7);
HighTempRadSys(Item).SetptSchedPtr = GetScheduleIndex(cAlphaArgs(7));
if ((HighTempRadSys(Item).SetptSchedPtr == 0) && (!lAlphaFieldBlanks(7))) {
ShowSevereError(cAlphaFieldNames(7) + " not found: " + cAlphaArgs(7));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
HighTempRadSys(Item).FracDistribPerson = rNumericArgs(9);
if (HighTempRadSys(Item).FracDistribPerson < MinFraction) {
HighTempRadSys(Item).FracDistribPerson = MinFraction;
ShowWarningError(cNumericFieldNames(9) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracDistribPerson > MaxFraction) {
HighTempRadSys(Item).FracDistribPerson = MaxFraction;
ShowWarningError(cNumericFieldNames(9) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
HighTempRadSys(Item).TotSurfToDistrib = NumNumbers - 9;
// IF (HighTempRadSys(Item)%TotSurfToDistrib > MaxDistribSurfaces) THEN
// CALL ShowSevereError('Trying to distribute radiant energy to too many surfaces for heater '//TRIM(cAlphaArgs(1)))
// CALL ShowContinueError('Occurs for '//TRIM(cCurrentModuleObject)//' = '//TRIM(cAlphaArgs(1)))
// ErrorsFound=.TRUE.
// END IF
HighTempRadSys(Item).SurfaceName.allocate(HighTempRadSys(Item).TotSurfToDistrib);
HighTempRadSys(Item).SurfacePtr.allocate(HighTempRadSys(Item).TotSurfToDistrib);
HighTempRadSys(Item).FracDistribToSurf.allocate(HighTempRadSys(Item).TotSurfToDistrib);
AllFracsSummed = HighTempRadSys(Item).FracDistribPerson;
for (SurfNum = 1; SurfNum <= HighTempRadSys(Item).TotSurfToDistrib; ++SurfNum) {
HighTempRadSys(Item).SurfaceName(SurfNum) = cAlphaArgs(SurfNum + 7);
HighTempRadSys(Item).SurfacePtr(SurfNum) = UtilityRoutines::FindItemInList(cAlphaArgs(SurfNum + 7), Surface);
HighTempRadSys(Item).FracDistribToSurf(SurfNum) = rNumericArgs(SurfNum + 9);
// Error trap for surfaces that do not exist or surfaces not in the zone the radiant heater is in
if (HighTempRadSys(Item).SurfacePtr(SurfNum) == 0) {
ShowSevereError(RoutineName + "Invalid Surface name = " + HighTempRadSys(Item).SurfaceName(SurfNum));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
} else if (Surface(HighTempRadSys(Item).SurfacePtr(SurfNum)).Zone != HighTempRadSys(Item).ZonePtr) {
ShowWarningError("Surface referenced in ZoneHVAC:HighTemperatureRadiant not in same zone as Radiant System, surface=" +
HighTempRadSys(Item).SurfaceName(SurfNum));
ShowContinueError("Surface is in Zone=" + Zone(Surface(HighTempRadSys(Item).SurfacePtr(SurfNum)).Zone).Name +
" ZoneHVAC:HighTemperatureRadiant in Zone=" + cAlphaArgs(3));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
// Error trap for fractions that are out of range
if (HighTempRadSys(Item).FracDistribToSurf(SurfNum) < MinFraction) {
HighTempRadSys(Item).FracDistribToSurf(SurfNum) = MinFraction;
ShowWarningError(cNumericFieldNames(SurfNum + 9) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracDistribToSurf(SurfNum) > MaxFraction) {
HighTempRadSys(Item).FracDistribToSurf(SurfNum) = MaxFraction;
ShowWarningError(cNumericFieldNames(SurfNum + 9) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).SurfacePtr(SurfNum) != 0) {
Surface(HighTempRadSys(Item).SurfacePtr(SurfNum)).IntConvSurfGetsRadiantHeat = true;
}
AllFracsSummed += HighTempRadSys(Item).FracDistribToSurf(SurfNum);
} // ...end of DO loop through surfaces that the heater radiates to.
// Error trap if the fractions add up to greater than 1.0
if (AllFracsSummed > (MaxFraction + 0.01)) {
ShowSevereError("Fraction of radiation distributed to surfaces sums up to greater than 1 for " + cAlphaArgs(1));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
if (AllFracsSummed < (MaxFraction - 0.01)) { // User didn't distribute all of the radiation warn that some will be lost
TotalFracToSurfs = AllFracsSummed - HighTempRadSys(Item).FracDistribPerson;
FracOfRadPotentiallyLost = 1.0 - AllFracsSummed;
ShowSevereError("Fraction of radiation distributed to surfaces and people sums up to less than 1 for " + cAlphaArgs(1));
ShowContinueError("This would result in some of the radiant energy delivered by the high temp radiant heater being lost.");
ShowContinueError("The sum of all radiation fractions to surfaces = " + TrimSigDigits(TotalFracToSurfs, 5));
ShowContinueError("The radiant fraction to people = " + TrimSigDigits(HighTempRadSys(Item).FracDistribPerson, 5));
ShowContinueError("So, all radiant fractions including surfaces and people = " + TrimSigDigits(AllFracsSummed, 5));
ShowContinueError(
"This means that the fraction of radiant energy that would be lost from the high temperature radiant heater would be = " +
TrimSigDigits(FracOfRadPotentiallyLost, 5));
ShowContinueError("Please check and correct this so that all radiant energy is accounted for in " + cCurrentModuleObject + " = " +
cAlphaArgs(1));
ErrorsFound = true;
}
} // ...end of DO loop through all of the high temperature radiant heaters
// Set up the output variables for high temperature radiant heaters
// cCurrentModuleObject = "ZoneHVAC:HighTemperatureRadiant"
for (Item = 1; Item <= NumOfHighTempRadSys; ++Item) {
SetupOutputVariable("Zone Radiant HVAC Heating Rate",
OutputProcessor::Unit::W,
HighTempRadSys(Item).HeatPower,
"System",
"Average",
HighTempRadSys(Item).Name);
SetupOutputVariable("Zone Radiant HVAC Heating Energy",
OutputProcessor::Unit::J,
HighTempRadSys(Item).HeatEnergy,
"System",
"Sum",
HighTempRadSys(Item).Name,
_,
"ENERGYTRANSFER",
"HEATINGCOILS",
_,
"System");
if (HighTempRadSys(Item).HeaterType == Gas) {
SetupOutputVariable("Zone Radiant HVAC Gas Rate",
OutputProcessor::Unit::W,
HighTempRadSys(Item).GasPower,
"System",
"Average",
HighTempRadSys(Item).Name);
SetupOutputVariable("Zone Radiant HVAC Gas Energy",
OutputProcessor::Unit::J,
HighTempRadSys(Item).GasEnergy,
"System",
"Sum",
HighTempRadSys(Item).Name,
_,
"Gas",
"Heating",
_,
"System");
} else if (HighTempRadSys(Item).HeaterType == Electric) {
SetupOutputVariable("Zone Radiant HVAC Electric Power",
OutputProcessor::Unit::W,
HighTempRadSys(Item).ElecPower,
"System",
"Average",
HighTempRadSys(Item).Name);
SetupOutputVariable("Zone Radiant HVAC Electric Energy",
OutputProcessor::Unit::J,
HighTempRadSys(Item).ElecEnergy,
"System",
"Sum",
HighTempRadSys(Item).Name,
_,
"ELECTRICITY",
"Heating",
_,
"System");
}
}
}
void InitHighTempRadiantSystem(bool const FirstHVACIteration, // TRUE if 1st HVAC simulation of system timestep
int const RadSysNum // Index for the low temperature radiant system under consideration within the derived types
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine initializes variables relating to high temperature
// radiant heating systems.
// METHODOLOGY EMPLOYED:
// Simply initializes whatever needs initializing.
// REFERENCES:
// na
// Using/Aliasing
using DataGlobals::BeginEnvrnFlag;
using DataGlobals::NumOfZones;
using DataZoneEquipment::CheckZoneEquipmentList;
using DataZoneEquipment::ZoneEquipInputsFilled;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// na
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
static bool firstTime(true); // For one-time initializations
int ZoneNum; // Intermediate variable for keeping track of the zone number
static bool MyEnvrnFlag(true);
static bool ZoneEquipmentListChecked(false); // True after the Zone Equipment List has been checked for items
int Loop;
// FLOW:
if (firstTime) {
ZeroSourceSumHATsurf.dimension(NumOfZones, 0.0);
QHTRadSource.dimension(NumOfHighTempRadSys, 0.0);
QHTRadSrcAvg.dimension(NumOfHighTempRadSys, 0.0);
LastQHTRadSrc.dimension(NumOfHighTempRadSys, 0.0);
LastSysTimeElapsed.dimension(NumOfHighTempRadSys, 0.0);
LastTimeStepSys.dimension(NumOfHighTempRadSys, 0.0);
MySizeFlag.dimension(NumOfHighTempRadSys, true);
firstTime = false;
}
// need to check all units to see if they are on Zone Equipment List or issue warning
if (!ZoneEquipmentListChecked && ZoneEquipInputsFilled) {
ZoneEquipmentListChecked = true;
for (Loop = 1; Loop <= NumOfHighTempRadSys; ++Loop) {
if (CheckZoneEquipmentList("ZoneHVAC:HighTemperatureRadiant", HighTempRadSys(Loop).Name)) continue;
ShowSevereError("InitHighTempRadiantSystem: Unit=[ZoneHVAC:HighTemperatureRadiant," + HighTempRadSys(Loop).Name +
"] is not on any ZoneHVAC:EquipmentList. It will not be simulated.");
}
}
if (!SysSizingCalc && MySizeFlag(RadSysNum)) {
// for each radiant systen do the sizing once.
SizeHighTempRadiantSystem(RadSysNum);
MySizeFlag(RadSysNum) = false;
}
if (BeginEnvrnFlag && MyEnvrnFlag) {
ZeroSourceSumHATsurf = 0.0;
QHTRadSource = 0.0;
QHTRadSrcAvg = 0.0;
LastQHTRadSrc = 0.0;
LastSysTimeElapsed = 0.0;
LastTimeStepSys = 0.0;
MyEnvrnFlag = false;
}
if (!BeginEnvrnFlag) {
MyEnvrnFlag = true;
}
if (BeginTimeStepFlag && FirstHVACIteration) { // This is the first pass through in a particular time step
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
ZeroSourceSumHATsurf(ZoneNum) = SumHATsurf(ZoneNum); // Set this to figure out what part of the load the radiant system meets
QHTRadSrcAvg(RadSysNum) = 0.0; // Initialize this variable to zero (radiant system defaults to off)
LastQHTRadSrc(RadSysNum) = 0.0; // At the beginning of a time step, reset to zero so average calculation can start again
LastSysTimeElapsed(RadSysNum) = 0.0; // At the beginning of a time step, reset to zero so average calculation can start again
LastTimeStepSys(RadSysNum) = 0.0; // At the beginning of a time step, reset to zero so average calculation can start again
}
}
void SizeHighTempRadiantSystem(int const RadSysNum)
{
// SUBROUTINE INFORMATION:
// AUTHOR Fred Buhl
// DATE WRITTEN February 2002
// MODIFIED August 2013 Daeho Kang, add component sizing table entries
// July 2014, B. Nigusse, added scalable sizing
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine is for sizing high temperature radiant components for which max power input has not been
// specified in the input.
// METHODOLOGY EMPLOYED:
// Obtains design heating load from the zone sizing arrays
// REFERENCES:
// na
// Using/Aliasing
using namespace DataSizing;
using DataHeatBalance::Zone;
using DataHVACGlobals::HeatingCapacitySizing;
using General::RoundSigDigits;
using ReportSizingManager::ReportSizingOutput;
using ReportSizingManager::RequestSizing;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
static std::string const RoutineName("SizeHighTempRadiantSystem");
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS
Real64 MaxPowerCapacDes; // Design maximum capacity for reproting
Real64 MaxPowerCapacUser; // User hard-sized maximum capacity for reproting
bool IsAutoSize; // Indicator to autosizing nominal capacity
std::string CompName; // component name
std::string CompType; // component type
std::string SizingString; // input field sizing description (e.g., Nominal Capacity)
Real64 TempSize; // autosized value of coil input field
int FieldNum = 1; // IDD numeric field number where input field description is found
int SizingMethod; // Integer representation of sizing method name (e.g., CoolingAirflowSizing, HeatingAirflowSizing, CoolingCapacitySizing,
// HeatingCapacitySizing, etc.)
bool PrintFlag; // TRUE when sizing information is reported in the eio file
int CapSizingMethod(0); // capacity sizing methods (HeatingDesignCapacity, CapacityPerFloorArea, FractionOfAutosizedCoolingCapacity, and
// FractionOfAutosizedHeatingCapacity )
IsAutoSize = false;
MaxPowerCapacDes = 0.0;
MaxPowerCapacUser = 0.0;
DataScalableCapSizingON = false;
if (CurZoneEqNum > 0) {
CompType = "ZoneHVAC:HighTemperatureRadiant";
CompName = HighTempRadSys(RadSysNum).Name;
DataFracOfAutosizedHeatingCapacity = 1.0;
DataZoneNumber = HighTempRadSys(RadSysNum).ZonePtr;
SizingMethod = HeatingCapacitySizing;
FieldNum = 1;
PrintFlag = true;
SizingString = HighTempRadSysNumericFields(RadSysNum).FieldNames(FieldNum) + " [W]";
CapSizingMethod = HighTempRadSys(RadSysNum).HeatingCapMethod;
ZoneEqSizing(CurZoneEqNum).SizingMethod(SizingMethod) = CapSizingMethod;
if (CapSizingMethod == HeatingDesignCapacity || CapSizingMethod == CapacityPerFloorArea ||
CapSizingMethod == FractionOfAutosizedHeatingCapacity) {
if (CapSizingMethod == HeatingDesignCapacity) {
if (HighTempRadSys(RadSysNum).ScaledHeatingCapacity == AutoSize) {
CheckZoneSizing(CompType, CompName);
ZoneEqSizing(CurZoneEqNum).DesHeatingLoad = FinalZoneSizing(CurZoneEqNum).NonAirSysDesHeatLoad /
(HighTempRadSys(RadSysNum).FracRadiant + HighTempRadSys(RadSysNum).FracConvect);
} else {
ZoneEqSizing(CurZoneEqNum).DesHeatingLoad = HighTempRadSys(RadSysNum).ScaledHeatingCapacity;
}
ZoneEqSizing(CurZoneEqNum).HeatingCapacity = true;
TempSize = ZoneEqSizing(CurZoneEqNum).DesHeatingLoad;
} else if (CapSizingMethod == CapacityPerFloorArea) {
ZoneEqSizing(CurZoneEqNum).HeatingCapacity = true;
ZoneEqSizing(CurZoneEqNum).DesHeatingLoad = HighTempRadSys(RadSysNum).ScaledHeatingCapacity * Zone(DataZoneNumber).FloorArea;
TempSize = ZoneEqSizing(CurZoneEqNum).DesHeatingLoad;
DataScalableCapSizingON = true;
} else if (CapSizingMethod == FractionOfAutosizedHeatingCapacity) {
CheckZoneSizing(CompType, CompName);
ZoneEqSizing(CurZoneEqNum).HeatingCapacity = true;
DataFracOfAutosizedHeatingCapacity = HighTempRadSys(RadSysNum).ScaledHeatingCapacity;
ZoneEqSizing(CurZoneEqNum).DesHeatingLoad = FinalZoneSizing(CurZoneEqNum).NonAirSysDesHeatLoad /
(HighTempRadSys(RadSysNum).FracRadiant + HighTempRadSys(RadSysNum).FracConvect);
TempSize = AutoSize;
DataScalableCapSizingON = true;
} else {
TempSize = HighTempRadSys(RadSysNum).ScaledHeatingCapacity;
}
RequestSizing(CompType, CompName, SizingMethod, SizingString, TempSize, PrintFlag, RoutineName);
HighTempRadSys(RadSysNum).MaxPowerCapac = TempSize;
DataScalableCapSizingON = false;
}
}
}
void CalcHighTempRadiantSystem(int const RadSysNum) // name of the low temperature radiant system
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine does all of the stuff that is necessary to simulate
// a high temperature radiant heating system.
// METHODOLOGY EMPLOYED:
// Follows the methods used by many other pieces of zone equipment except
// that we are controlling the input to the heater element. Note that
// cooling is not allowed for such a system. Controls are very basic at
// this point using just a linear interpolation between being off at
// one end of the throttling range, fully on at the other end, and varying
// linearly in between.
// REFERENCES:
// Other EnergyPlus modules
// Building Systems Laboratory, BLAST User's Guide/Reference.
// Fanger, P.O. "Analysis and Applications in Environmental Engineering",
// Danish Technical Press, 1970.
// Maloney, Dan. 1987. "Development of a radiant heater model and the
// incorporation of thermal comfort considerations into the BLAST
// energy analysis program", M.S. thesis, University of Illinois at
// Urbana-Champaign (Dept. of Mechanical and Industrial Engineering).
// Using/Aliasing
using DataHeatBalance::MRT;
using DataHeatBalFanSys::MAT;
using namespace DataZoneEnergyDemands;
using ScheduleManager::GetCurrentScheduleValue;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// na
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
Real64 HeatFrac; // fraction of maximum energy input to radiant system [dimensionless]
Real64 OffTemp; // Temperature above which the radiant system should be completely off [C]
Real64 OpTemp; // Operative temperature [C]
// REAL(r64) :: QZnReq ! heating or cooling needed by zone [Watts]
Real64 SetPtTemp; // Setpoint temperature [C]
int ZoneNum; // number of zone being served
// FLOW:
// initialize local variables
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
HeatFrac = 0.0;
if (GetCurrentScheduleValue(HighTempRadSys(RadSysNum).SchedPtr) <= 0) {
// Unit is off or has no load upon it; set the flow rates to zero and then
// simulate the components with the no flow conditions
QHTRadSource(RadSysNum) = 0.0;
} else { // Unit might be on-->this section is intended to control the output of the
// high temperature radiant heater (temperature controlled)
// Determine the current setpoint temperature and the temperature at which the unit should be completely off
SetPtTemp = GetCurrentScheduleValue(HighTempRadSys(RadSysNum).SetptSchedPtr);
OffTemp = SetPtTemp + 0.5 * HighTempRadSys(RadSysNum).ThrottlRange;
OpTemp = (MAT(ZoneNum) + MRT(ZoneNum)) / 2.0; // Approximate the "operative" temperature
// Determine the fraction of maximum power to the unit (limiting the fraction range from zero to unity)
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if (SELECT_CASE_var == MATControl) {
HeatFrac = (OffTemp - MAT(ZoneNum)) / HighTempRadSys(RadSysNum).ThrottlRange;
} else if (SELECT_CASE_var == MRTControl) {
HeatFrac = (OffTemp - MRT(ZoneNum)) / HighTempRadSys(RadSysNum).ThrottlRange;
} else if (SELECT_CASE_var == OperativeControl) {
OpTemp = 0.5 * (MAT(ZoneNum) + MRT(ZoneNum));
HeatFrac = (OffTemp - OpTemp) / HighTempRadSys(RadSysNum).ThrottlRange;
}
}
if (HeatFrac < 0.0) HeatFrac = 0.0;
if (HeatFrac > 1.0) HeatFrac = 1.0;
// Set the heat source for the high temperature electric radiant system
QHTRadSource(RadSysNum) = HeatFrac * HighTempRadSys(RadSysNum).MaxPowerCapac;
}
}
void CalcHighTempRadiantSystemSP(
bool const EP_UNUSED(FirstHVACIteration), // true if this is the first HVAC iteration at this system time step !unused1208
int const RadSysNum // name of the low temperature radiant system
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2008
// MODIFIED Sep 2011 LKL/BG - resimulate only zones needing it for Radiant systems
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine does all of the stuff that is necessary to simulate
// a high temperature radiant heating system using setpoint temperature control.
// METHODOLOGY EMPLOYED:
// Follows the methods used by many other pieces of zone equipment except
// that we are controlling the input to the heater element. Note that
// cooling is not allowed for such a system. Controls are very basic and
// use an iterative approach to get close to what we need.
// REFERENCES:
// Other EnergyPlus modules
// Building Systems Laboratory, BLAST User's Guide/Reference.
// Fanger, P.O. "Analysis and Applications in Environmental Engineering",
// Danish Technical Press, 1970.
// Maloney, Dan. 1987. "Development of a radiant heater model and the
// incorporation of thermal comfort considerations into the BLAST
// energy analysis program", M.S. thesis, University of Illinois at
// Urbana-Champaign (Dept. of Mechanical and Industrial Engineering).
// Using/Aliasing
using DataHeatBalance::MRT;
using DataHeatBalFanSys::MAT;
using ScheduleManager::GetCurrentScheduleValue;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
float const TempConvToler(0.1); // Temperature controller tries to converge to within 0.1C
int const MaxIterations(10); // Maximum number of iterations to achieve temperature control
// (10 interval halvings achieves control to 0.1% of capacity)
// These two parameters are intended to achieve reasonable control
// without excessive run times.
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
bool ConvergFlag; // convergence flag for temperature control
// unused INTEGER, SAVE :: ErrIterCount=0 ! number of time max iterations has been exceeded
float HeatFrac; // fraction of maximum energy input to radiant system [dimensionless]
float HeatFracMax; // maximum range of heat fraction
float HeatFracMin; // minimum range of heat fraction
int IterNum; // iteration number
Real64 SetPtTemp; // Setpoint temperature [C]
int ZoneNum; // number of zone being served
Real64 ZoneTemp(0.0); // zone temperature (MAT, MRT, or Operative Temperature, depending on control type) [C]
// FLOW:
// initialize local variables
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
QHTRadSource(RadSysNum) = 0.0;
if (GetCurrentScheduleValue(HighTempRadSys(RadSysNum).SchedPtr) > 0) {
// Unit is scheduled on-->this section is intended to control the output of the
// high temperature radiant heater (temperature controlled)
// Determine the current setpoint temperature and the temperature at which the unit should be completely off
SetPtTemp = GetCurrentScheduleValue(HighTempRadSys(RadSysNum).SetptSchedPtr);
// Now, distribute the radiant energy of all systems to the appropriate
// surfaces, to people, and the air; determine the latent portion
DistributeHTRadGains();
// Now "simulate" the system by recalculating the heat balances
HeatBalanceSurfaceManager::CalcHeatBalanceOutsideSurf(ZoneNum);
HeatBalanceSurfaceManager::CalcHeatBalanceInsideSurf(ZoneNum);
// First determine whether or not the unit should be on
// Determine the proper temperature on which to control
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if (SELECT_CASE_var == MATSPControl) {
ZoneTemp = MAT(ZoneNum);
} else if (SELECT_CASE_var == MRTSPControl) {
ZoneTemp = MRT(ZoneNum);
} else if (SELECT_CASE_var == OperativeSPControl) {
ZoneTemp = 0.5 * (MAT(ZoneNum) + MRT(ZoneNum));
} else {
assert(false);
}
}
if (ZoneTemp < (SetPtTemp - TempConvToler)) {
// Use simple interval halving to find the best operating fraction to achieve proper temperature control
IterNum = 0;
ConvergFlag = false;
HeatFracMax = 1.0;
HeatFracMin = 0.0;
while ((IterNum <= MaxIterations) && (!ConvergFlag)) {
// In the first iteration (IterNum=0), try full capacity and see if that is the best solution
if (IterNum == 0) {
HeatFrac = 1.0;
} else {
HeatFrac = (HeatFracMin + HeatFracMax) / 2.0;
}
// Set the heat source for the high temperature radiant system
QHTRadSource(RadSysNum) = HeatFrac * HighTempRadSys(RadSysNum).MaxPowerCapac;
// Now, distribute the radiant energy of all systems to the appropriate
// surfaces, to people, and the air; determine the latent portion
DistributeHTRadGains();
// Now "simulate" the system by recalculating the heat balances
HeatBalanceSurfaceManager::CalcHeatBalanceOutsideSurf(ZoneNum);
HeatBalanceSurfaceManager::CalcHeatBalanceInsideSurf(ZoneNum);
// Redetermine the current value of the controlling temperature
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if (SELECT_CASE_var == MATControl) {
ZoneTemp = MAT(ZoneNum);
} else if (SELECT_CASE_var == MRTControl) {
ZoneTemp = MRT(ZoneNum);
} else if (SELECT_CASE_var == OperativeControl) {
ZoneTemp = 0.5 * (MAT(ZoneNum) + MRT(ZoneNum));
}
}
if ((std::abs(ZoneTemp - SetPtTemp)) <= TempConvToler) {
// The radiant heater has controlled the zone temperature to the appropriate level--stop iterating
ConvergFlag = true;
} else if (ZoneTemp < SetPtTemp) {
// The zone temperature is too low--try increasing the radiant heater output
if (IterNum == 0) {
// Heater already at capacity--this is the best that we can do
ConvergFlag = true;
} else {
HeatFracMin = HeatFrac;
}
} else { // (ZoneTemp > SetPtTemp)
// The zone temperature is too high--try decreasing the radiant heater output
if (IterNum > 0) HeatFracMax = HeatFrac;
}
++IterNum;
}
}
}
}
void UpdateHighTempRadiantSystem(int const RadSysNum, // Index for the low temperature radiant system under consideration within the derived types
Real64 &LoadMet // load met by the radiant system, in Watts
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine does any updating that needs to be done for high
// temperature radiant heating systems. This routine has two functions.
// First, it needs to keep track of the average high temperature
// radiant source. The method for doing this is similar to low
// temperature systems except that heat input is kept locally on
// a system basis rather than a surface basis. This is because a high
// temperature system affects many surfaces while a low temperature
// system directly affects only one surface. This leads to the second
// function of this subroutine which is to account for the affect of
// all high temperature radiant systems on each surface. This
// distribution must be "redone" every time to be sure that we have
// properly accounted for all of the systems.
// METHODOLOGY EMPLOYED:
// For the source average update, if the system time step elapsed is
// still what it used to be, then either we are still iterating or we
// had to go back and shorten the time step. As a result, we have to
// subtract out the previous value that we added. If the system time
// step elapsed is different, then we just need to add the new values
// to the running average.
// REFERENCES:
// na
// Using/Aliasing
using DataGlobals::BeginEnvrnFlag;
using DataGlobals::TimeStepZone;
using DataHeatBalFanSys::SumConvHTRadSys;
using DataHVACGlobals::SysTimeElapsed;
using DataHVACGlobals::TimeStepSys;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// na
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
int ZoneNum; // Zone index number for the current radiant system
static bool MyEnvrnFlag(true);
// FLOW:
if (BeginEnvrnFlag && MyEnvrnFlag) {
MyEnvrnFlag = false;
}
if (!BeginEnvrnFlag) {
MyEnvrnFlag = true;
}
// First, update the running average if necessary...
if (LastSysTimeElapsed(RadSysNum) == SysTimeElapsed) {
// Still iterating or reducing system time step, so subtract old values which were
// not valid
QHTRadSrcAvg(RadSysNum) -= LastQHTRadSrc(RadSysNum) * LastTimeStepSys(RadSysNum) / TimeStepZone;
}
// Update the running average and the "last" values with the current values of the appropriate variables
QHTRadSrcAvg(RadSysNum) += QHTRadSource(RadSysNum) * TimeStepSys / TimeStepZone;
LastQHTRadSrc(RadSysNum) = QHTRadSource(RadSysNum);
LastSysTimeElapsed(RadSysNum) = SysTimeElapsed;
LastTimeStepSys(RadSysNum) = TimeStepSys;
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if ((SELECT_CASE_var == MATControl) || (SELECT_CASE_var == MRTControl) || (SELECT_CASE_var == OperativeControl)) {
// Only need to do this for the non-SP controls (SP has already done this enough)
// Now, distribute the radiant energy of all systems to the appropriate
// surfaces, to people, and the air; determine the latent portion
DistributeHTRadGains();
// Now "simulate" the system by recalculating the heat balances
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
HeatBalanceSurfaceManager::CalcHeatBalanceOutsideSurf(ZoneNum);
HeatBalanceSurfaceManager::CalcHeatBalanceInsideSurf(ZoneNum);
}
}
if (QHTRadSource(RadSysNum) <= 0.0) {
LoadMet = 0.0; // System wasn't running so it can't meet a load
} else {
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
LoadMet = (SumHATsurf(ZoneNum) - ZeroSourceSumHATsurf(ZoneNum)) + SumConvHTRadSys(ZoneNum);
}
}
void UpdateHTRadSourceValAvg(bool &HighTempRadSysOn) // .TRUE. if the radiant system has run this zone time step
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// To transfer the average value of the heat source over the entire
// zone time step back to the heat balance routines so that the heat
// balance algorithms can simulate one last time with the average source
// to maintain some reasonable amount of continuity and energy balance
// in the temperature and flux histories.
// METHODOLOGY EMPLOYED:
// All of the record keeping for the average term is done in the Update
// routine so the only other thing that this subroutine does is check to
// see if the system was even on. If any average term is non-zero, then
// one or more of the radiant systems was running.
// REFERENCES:
// na
// USE STATEMENTS:
// na
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// na
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
int RadSysNum; // DO loop counter for surface index
// FLOW:
HighTempRadSysOn = false;
// If this was never allocated, then there are no radiant systems in this input file (just RETURN)
if (!allocated(QHTRadSrcAvg)) return;
// If it was allocated, then we have to check to see if this was running at all...
for (RadSysNum = 1; RadSysNum <= NumOfHighTempRadSys; ++RadSysNum) {
if (QHTRadSrcAvg(RadSysNum) != 0.0) {
HighTempRadSysOn = true;
break; // DO loop
}
}
QHTRadSource = QHTRadSrcAvg;
DistributeHTRadGains(); // QHTRadSource has been modified so we need to redistribute gains
}
void DistributeHTRadGains()
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED April 2010 Brent Griffith, max limit to protect surface temperature calcs
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// To distribute the gains from the high temperature radiant heater
// as specified in the user input file. This includes distribution
// of long wavelength radiant gains to surfaces and "people" as well
// as latent, lost, and convective portions of the total gain.
// METHODOLOGY EMPLOYED:
// We must cycle through all of the radiant systems because each
// surface could feel the effect of more than one radiant system.
// Note that the energy radiated to people is assumed to affect them
// but them it is assumed to be convected to the air. This is why
// the convective portion shown below has two parts to it.
// REFERENCES:
// na
// Using/Aliasing
using DataGlobals::NumOfZones;
using DataHeatBalance::Zone;
using DataHeatBalFanSys::MaxRadHeatFlux;
using DataHeatBalFanSys::QHTRadSysSurf;
using DataHeatBalFanSys::QHTRadSysToPerson;
using DataHeatBalFanSys::SumConvHTRadSys;
using DataHeatBalFanSys::SumLatentHTRadSys;
using DataSurfaces::Surface;
using General::RoundSigDigits;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// na
// SUBROUTINE PARAMETER DEFINITIONS:
Real64 const SmallestArea(0.001); // Smallest area in meters squared (to avoid a divide by zero)
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
int RadSurfNum; // Counter for surfaces receiving radiation from radiant heater
int RadSysNum; // Counter for the radiant systems
int SurfNum; // Pointer to the Surface derived type
int ZoneNum; // Pointer to the Zone derived type
Real64 ThisSurfIntensity; // temporary for W/m2 term for rad on a surface
// FLOW:
// Initialize arrays
SumConvHTRadSys = 0.0;
SumLatentHTRadSys = 0.0;
QHTRadSysSurf = 0.0;
QHTRadSysToPerson = 0.0;
for (RadSysNum = 1; RadSysNum <= NumOfHighTempRadSys; ++RadSysNum) {
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
QHTRadSysToPerson(ZoneNum) =
QHTRadSource(RadSysNum) * HighTempRadSys(RadSysNum).FracRadiant * HighTempRadSys(RadSysNum).FracDistribPerson;
SumConvHTRadSys(ZoneNum) += QHTRadSource(RadSysNum) * HighTempRadSys(RadSysNum).FracConvect;
SumLatentHTRadSys(ZoneNum) += QHTRadSource(RadSysNum) * HighTempRadSys(RadSysNum).FracLatent;
for (RadSurfNum = 1; RadSurfNum <= HighTempRadSys(RadSysNum).TotSurfToDistrib; ++RadSurfNum) {
SurfNum = HighTempRadSys(RadSysNum).SurfacePtr(RadSurfNum);
if (Surface(SurfNum).Area > SmallestArea) {
ThisSurfIntensity = (QHTRadSource(RadSysNum) * HighTempRadSys(RadSysNum).FracRadiant *
HighTempRadSys(RadSysNum).FracDistribToSurf(RadSurfNum) / Surface(SurfNum).Area);
QHTRadSysSurf(SurfNum) += ThisSurfIntensity;
if (ThisSurfIntensity > MaxRadHeatFlux) { // CR 8074, trap for excessive intensity (throws off surface balance )
ShowSevereError("DistributeHTRadGains: excessive thermal radiation heat flux intensity detected");
ShowContinueError("Surface = " + Surface(SurfNum).Name);
ShowContinueError("Surface area = " + RoundSigDigits(Surface(SurfNum).Area, 3) + " [m2]");
ShowContinueError("Occurs in ZoneHVAC:HighTemperatureRadiant = " + HighTempRadSys(RadSysNum).Name);
ShowContinueError("Radiation intensity = " + RoundSigDigits(ThisSurfIntensity, 2) + " [W/m2]");
ShowContinueError("Assign a larger surface area or more surfaces in ZoneHVAC:HighTemperatureRadiant");
ShowFatalError("DistributeHTRadGains: excessive thermal radiation heat flux intensity detected");
}
} else { // small surface
ShowSevereError("DistributeHTRadGains: surface not large enough to receive thermal radiation heat flux");
ShowContinueError("Surface = " + Surface(SurfNum).Name);
ShowContinueError("Surface area = " + RoundSigDigits(Surface(SurfNum).Area, 3) + " [m2]");
ShowContinueError("Occurs in ZoneHVAC:HighTemperatureRadiant = " + HighTempRadSys(RadSysNum).Name);
ShowContinueError("Assign a larger surface area or more surfaces in ZoneHVAC:HighTemperatureRadiant");
ShowFatalError("DistributeHTRadGains: surface not large enough to receive thermal radiation heat flux");
}
}
}
// Here an assumption is made regarding radiant heat transfer to people.
// While the QHTRadSysToPerson array will be used by the thermal comfort
// routines, the energy transfer to people would get lost from the perspective
// of the heat balance. So, to avoid this net loss of energy which clearly
// gets added to the zones, we must account for it somehow. This assumption
// that all energy radiated to people is converted to convective energy is
// not very precise, but at least it conserves energy.
for (ZoneNum = 1; ZoneNum <= NumOfZones; ++ZoneNum) {
SumConvHTRadSys(ZoneNum) += QHTRadSysToPerson(ZoneNum);
}
}
void ReportHighTempRadiantSystem(int const RadSysNum) // Index for the low temperature radiant system under consideration within the derived types
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine simply produces output for the high temperature radiant system.
// METHODOLOGY EMPLOYED:
// Standard EnergyPlus methodology.
// REFERENCES:
// na
// Using/Aliasing
using DataGlobals::SecInHour;
using DataHVACGlobals::TimeStepSys;
using DataSurfaces::Surface;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
// na
// FLOW:
if (HighTempRadSys(RadSysNum).HeaterType == Gas) {
HighTempRadSys(RadSysNum).GasPower = QHTRadSource(RadSysNum) / HighTempRadSys(RadSysNum).CombustionEffic;
HighTempRadSys(RadSysNum).GasEnergy = HighTempRadSys(RadSysNum).GasPower * TimeStepSys * SecInHour;
HighTempRadSys(RadSysNum).ElecPower = 0.0;
HighTempRadSys(RadSysNum).ElecEnergy = 0.0;
} else if (HighTempRadSys(RadSysNum).HeaterType == Electric) {
HighTempRadSys(RadSysNum).GasPower = 0.0;
HighTempRadSys(RadSysNum).GasEnergy = 0.0;
HighTempRadSys(RadSysNum).ElecPower = QHTRadSource(RadSysNum);
HighTempRadSys(RadSysNum).ElecEnergy = HighTempRadSys(RadSysNum).ElecPower * TimeStepSys * SecInHour;
} else {
ShowWarningError("Someone forgot to add a high temperature radiant heater type to the reporting subroutine");
}
HighTempRadSys(RadSysNum).HeatPower = QHTRadSource(RadSysNum);
HighTempRadSys(RadSysNum).HeatEnergy = HighTempRadSys(RadSysNum).HeatPower * TimeStepSys * SecInHour;
}
Real64 SumHATsurf(int const ZoneNum) // Zone number
{
// FUNCTION INFORMATION:
// AUTHOR Peter Graham Ellis
// DATE WRITTEN July 2003
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS FUNCTION:
// This function calculates the zone sum of Hc*Area*Tsurf. It replaces the old SUMHAT.
// The SumHATsurf code below is also in the CalcZoneSums subroutine in ZoneTempPredictorCorrector
// and should be updated accordingly.
// METHODOLOGY EMPLOYED:
// na
// REFERENCES:
// na
// Using/Aliasing
using namespace DataSurfaces;
using namespace DataHeatBalance;
using namespace DataHeatBalSurface;
// Return value
Real64 SumHATsurf;
// Locals
// FUNCTION ARGUMENT DEFINITIONS:
// FUNCTION LOCAL VARIABLE DECLARATIONS:
int SurfNum; // Surface number
Real64 Area; // Effective surface area
// FLOW:
SumHATsurf = 0.0;
for (SurfNum = Zone(ZoneNum).SurfaceFirst; SurfNum <= Zone(ZoneNum).SurfaceLast; ++SurfNum) {
if (!Surface(SurfNum).HeatTransSurf) continue; // Skip non-heat transfer surfaces
Area = Surface(SurfNum).Area;
if (Surface(SurfNum).Class == SurfaceClass_Window) {
if (SurfaceWindow(SurfNum).ShadingFlag == IntShadeOn || SurfaceWindow(SurfNum).ShadingFlag == IntBlindOn) {
// The area is the shade or blind area = the sum of the glazing area and the divider area (which is zero if no divider)
Area += SurfaceWindow(SurfNum).DividerArea;
}
if (SurfaceWindow(SurfNum).FrameArea > 0.0) {
// Window frame contribution
SumHATsurf += HConvIn(SurfNum) * SurfaceWindow(SurfNum).FrameArea * (1.0 + SurfaceWindow(SurfNum).ProjCorrFrIn) *
SurfaceWindow(SurfNum).FrameTempSurfIn;
}
if (SurfaceWindow(SurfNum).DividerArea > 0.0 && SurfaceWindow(SurfNum).ShadingFlag != IntShadeOn &&
SurfaceWindow(SurfNum).ShadingFlag != IntBlindOn) {
// Window divider contribution (only from shade or blind for window with divider and interior shade or blind)
SumHATsurf += HConvIn(SurfNum) * SurfaceWindow(SurfNum).DividerArea * (1.0 + 2.0 * SurfaceWindow(SurfNum).ProjCorrDivIn) *
SurfaceWindow(SurfNum).DividerTempSurfIn;
}
}
SumHATsurf += HConvIn(SurfNum) * Area * TempSurfInTmp(SurfNum);
}
return SumHATsurf;
}
} // namespace HighTempRadiantSystem
} // namespace EnergyPlus
| 51.686452 | 150 | 0.613601 | yurigabrich |
82def5e94931116dd81321dc04facd9fd0e00346 | 1,799 | cpp | C++ | external/src/StateMachine/transition.cpp | telekom/LibNbiot | 60655d3d1cfdabfefac229eefee9b2ed0e0f5f73 | [
"Apache-2.0"
] | 18 | 2018-04-20T12:11:37.000Z | 2020-02-25T19:40:41.000Z | external/src/StateMachine/transition.cpp | telekom/LibNbiot | 60655d3d1cfdabfefac229eefee9b2ed0e0f5f73 | [
"Apache-2.0"
] | 2 | 2018-05-21T04:15:00.000Z | 2018-11-27T14:41:11.000Z | external/src/StateMachine/transition.cpp | telekom/LibNbiot | 60655d3d1cfdabfefac229eefee9b2ed0e0f5f73 | [
"Apache-2.0"
] | 6 | 2018-08-09T11:28:37.000Z | 2021-07-20T07:41:08.000Z | /******************************************************************************
* File: transition.cpp
* Author: Edgar Hindemith
* This file is part of the 'Simple Statemachine for Embedded Systems'
* see https://github.com/edgar4k/StateMachine
*
* Copyright (C) 2016,2018 Edgar Hindemith
*
* 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 "stmevent.h"
#include "state.h"
#include "choice.h"
#include "transition.h"
Transition::Transition() :
target(nullptr),
trAction(),
eventType(StmEvent::Invalid)
{
}
void Transition::trigger(StmEvent& e)
{
action(e);
if(nullptr != target)
{
if(NodeTypeTransition == target->type())
{
static_cast<Transition*>(target)->trigger(e);
}
else if (NodeTypeGuard == target->type())
{
static_cast<Choice*>(target)->execute(e);
}
else if (NodeTypeState == target->type())
{
static_cast<State*>(target)->enter(e);
}
else
{
e.setEventState(StmEvent::Aborted);
}
}
else
{
e.setEventState(StmEvent::Aborted);
}
}
| 28.555556 | 80 | 0.556976 | telekom |
82e1cf46c547ee7bd50b783a31f234185a1116b3 | 3,092 | cpp | C++ | tests/cthread/test_bhv_fifo.cpp | hachetman/systemc-compiler | 0cc81ace03336d752c0146340ff5763a20e3cefd | [
"Apache-2.0"
] | 86 | 2020-10-23T15:59:47.000Z | 2022-03-28T18:51:19.000Z | tests/cthread/test_bhv_fifo.cpp | hachetman/systemc-compiler | 0cc81ace03336d752c0146340ff5763a20e3cefd | [
"Apache-2.0"
] | 18 | 2020-12-14T13:11:26.000Z | 2022-03-14T05:34:20.000Z | tests/cthread/test_bhv_fifo.cpp | hachetman/systemc-compiler | 0cc81ace03336d752c0146340ff5763a20e3cefd | [
"Apache-2.0"
] | 17 | 2020-10-29T16:19:43.000Z | 2022-03-11T09:51:05.000Z | /******************************************************************************
* Copyright (c) 2020, Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
*
*****************************************************************************/
#include "systemc.h"
using namespace sc_core;
#define BUFSIZE 4
#define LOGBUFSIZE 2
#define LOGBUFSIZEPLUSONE 3
// Behavioral FIFO example
class Circ_buf : public sc_module
{
public:
sc_in<bool> clk;
sc_in<bool> read_fifo;
sc_in<bool> write_fifo;
sc_in<sc_uint<32>> data_in;
sc_in<bool> reset;
sc_out<sc_uint<32>> data_out;
sc_out<bool> full;
sc_out<bool> empty;
// Internal signals
sc_signal<sc_uint<32>> buffer[BUFSIZE];
sc_uint<LOGBUFSIZE> headp; // FIFO head ptr
sc_uint<LOGBUFSIZE> tailp; // FIFO tail ptr
// Counter for fifo depth
sc_uint<LOGBUFSIZEPLUSONE> num_in_buf;
SC_CTOR(Circ_buf) {
SC_HAS_PROCESS(Circ_buf);
SC_CTHREAD(fifo_rw, clk.pos());
async_reset_signal_is(reset, true);
}
void fifo_rw() {
// Reset operations
headp = 0;
tailp = 0;
num_in_buf = 0;
full = false;
empty = true;
data_out = 0;
for (int i = 0; i < BUFSIZE; i++) {
buffer[i] = 0;
}
wait();
// Main loop
while (true) {
if (read_fifo.read()) {
// Check if FIFO is not empty
if (num_in_buf != 0) {
num_in_buf--;
data_out = buffer[headp++];
full = false;
if (num_in_buf == 0)
empty = true;
}
// Ignore read request otherwise
} else if (write_fifo.read()) {
// Check if FIFO is not full
if (num_in_buf != BUFSIZE) {
buffer[tailp++] = data_in;
num_in_buf++;
empty = false;
if (num_in_buf == BUFSIZE)
full = true;
}
// Ignore write request otherwise
} else {
}
wait();
}
}
};
class B_top: public sc_module
{
public:
sc_in<bool> clk{"clk"};
sc_signal<bool> read_fifo{"read_fifo"};
sc_signal<bool> write_fifo{"write_fifo"};
sc_signal<sc_uint<32>> data_in{"data_in"};
sc_signal<bool> reset{"reset"};
sc_signal<sc_uint<32>> data_out{"data_out"};
sc_signal<bool> full{"full"};
sc_signal<bool> empty{"empty"};
Circ_buf a_mod{"a_mod"};
SC_CTOR(B_top) {
a_mod.clk(clk);
a_mod.read_fifo(read_fifo);
a_mod.write_fifo(write_fifo);
a_mod.data_in(data_in);
a_mod.reset(reset);
a_mod.data_out(data_out);
a_mod.full(full);
a_mod.empty(empty);
}
};
int sc_main(int argc, char* argv[])
{
sc_clock clk { "clk", sc_time(1, SC_NS) };
B_top b_mod{"b_mod"};
b_mod.clk(clk);
sc_start();
return 0;
}
| 24.736 | 79 | 0.502587 | hachetman |
82e236a9dc748b89398c20334b2359958d95cfb8 | 233 | hpp | C++ | source-sdk/classes/net_channel.hpp | BuddDwyer-0x00/csgo-cheat-base | 3103f0e1ba811270f7f862cdfd105f712a6eb700 | [
"MIT"
] | 10 | 2020-06-23T00:44:29.000Z | 2021-11-16T01:52:16.000Z | source-sdk/classes/net_channel.hpp | BuddDwyer-0x00/csgo-cheat-base | 3103f0e1ba811270f7f862cdfd105f712a6eb700 | [
"MIT"
] | 1 | 2020-06-08T17:58:31.000Z | 2021-05-09T17:26:48.000Z | source-sdk/classes/net_channel.hpp | BuddDwyer-0x00/csgo-cheat-base | 3103f0e1ba811270f7f862cdfd105f712a6eb700 | [
"MIT"
] | 3 | 2020-06-08T00:31:44.000Z | 2021-05-27T23:16:13.000Z | #pragma once
class i_net_channel {
public:
uint8_t pad_0x0000[0x17];
bool should_delete;
int out_sequence_nr;
int in_sequence_nr;
int out_sequence_nr_ack;
int out_reliable_state;
int in_reliable_state;
int choked_packets;
}; | 17.923077 | 26 | 0.802575 | BuddDwyer-0x00 |
82e729cadf94428b8eab67a209530dddd04bdd21 | 11,342 | cpp | C++ | ClassicStartSrc/ClassicIE/ClassicIEDLL/DrawCaption.cpp | Duzzy-ExoDuus/Classic-Start | 8b70f64b5bceeadfa4e5599b299a856c1e452e80 | [
"MIT"
] | 1 | 2018-07-19T20:59:32.000Z | 2018-07-19T20:59:32.000Z | ClassicStartSrc/ClassicIE/ClassicIEDLL/DrawCaption.cpp | Duzzy-ExoDuus/Classic-Start | 8b70f64b5bceeadfa4e5599b299a856c1e452e80 | [
"MIT"
] | null | null | null | ClassicStartSrc/ClassicIE/ClassicIEDLL/DrawCaption.cpp | Duzzy-ExoDuus/Classic-Start | 8b70f64b5bceeadfa4e5599b299a856c1e452e80 | [
"MIT"
] | null | null | null | // Classic Shell (c) 2009-2017, Ivo Beltchev
// Classic Start (c) 2017-2018, The Passionate-Coder Team
// Confidential information of Ivo Beltchev. Not for disclosure or distribution without prior written consent from the author
#include "stdafx.h"
#include "ClassicIEDLL.h"
#include "Settings.h"
#include "ResourceHelper.h"
#include "SettingsUIHelper.h"
#include <vssym32.h>
#include <dwmapi.h>
static _declspec(thread) SIZE g_SysButtonSize; // the size of the system buttons (close, minimize) for this thread's window
static WNDPROC g_OldClassCaptionProc;
static HBITMAP g_GlowBmp;
static HBITMAP g_GlowBmpMax;
static LONG g_bInjected; // the process is injected
static int g_DPI;
static UINT g_Message; // private message to detect if the caption is subclassed
static ATOM g_SubclassAtom;
struct CustomCaption
{
int leftPadding;
int topPadding;
int iconPadding;
};
static CustomCaption g_CustomCaption[3]={
{2,3,10}, // Aero
{4,2,10}, // Aero maximized
{4,2,10}, // Basic
};
void GetSysButtonSize( HWND hWnd )
{
TITLEBARINFOEX titleInfo={sizeof(titleInfo)};
SendMessage(hWnd,WM_GETTITLEBARINFOEX,0,(LPARAM)&titleInfo);
int buttonLeft=titleInfo.rgrect[2].left;
if (buttonLeft>titleInfo.rgrect[5].left) buttonLeft=titleInfo.rgrect[5].left;
int buttonRight=titleInfo.rgrect[2].right;
if (buttonRight<titleInfo.rgrect[5].right) buttonRight=titleInfo.rgrect[5].right;
int w=buttonRight-buttonLeft;
int h=titleInfo.rgrect[5].bottom-titleInfo.rgrect[5].top;
g_SysButtonSize.cx=w;
g_SysButtonSize.cy=h;
}
// Subclasses the main IE frame to redraw the caption when the text changes
static LRESULT CALLBACK SubclassFrameProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if (uMsg==g_Message)
{
GetSysButtonSize(hWnd);
HWND caption=FindWindowEx(hWnd,NULL,L"Client Caption",NULL);
if (caption)
InvalidateRect(caption,NULL,FALSE);
return 0;
}
if (uMsg==WM_SETTEXT || uMsg==WM_ACTIVATE)
{
HWND caption=FindWindowEx(hWnd,NULL,L"Client Caption",NULL);
if (caption)
InvalidateRect(caption,NULL,FALSE);
}
if (uMsg==WM_SIZE || uMsg==WM_SETTINGCHANGE)
{
GetSysButtonSize(hWnd);
if (uMsg==WM_SETTINGCHANGE)
{
CSettingsLockWrite lock;
UpdateSettings();
}
}
while (1)
{
WNDPROC proc=(WNDPROC)GetProp(hWnd,MAKEINTATOM(g_SubclassAtom));
if (proc)
return CallWindowProc(proc,hWnd,uMsg,wParam,lParam);
}
}
static LRESULT DefCaptionProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
while (1)
{
WNDPROC proc=(WNDPROC)GetProp(hWnd,MAKEINTATOM(g_SubclassAtom));
if (proc)
return CallWindowProc(proc,hWnd,uMsg,wParam,lParam);
}
}
// Subclasses the caption window to draw the icon and the text
static LRESULT CALLBACK SubclassCaptionProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if (uMsg==g_Message)
return 1;
if (uMsg==WM_ERASEBKGND)
return 0;
if (uMsg==WM_PAINT)
{
HTHEME theme=OpenThemeData(hWnd,L"Window");
if (!theme) return DefCaptionProc(hWnd,uMsg,wParam,lParam);
// get the icon and the text from the parent
HWND parent=GetParent(hWnd);
wchar_t caption[256];
GetWindowText(parent,caption,_countof(caption));
HICON hIcon=(HICON)SendMessage(parent,WM_GETICON,ICON_SMALL,0);
int iconSize=GetSystemMetrics(SM_CXSMICON);
bool bMaximized=IsZoomed(parent)!=0;
bool bActive=(parent==GetActiveWindow());
RECT rc;
GetClientRect(hWnd,&rc);
if (!g_DPI)
{
HDC hdc=GetDC(NULL);
g_DPI=GetDeviceCaps(hdc,LOGPIXELSY);
ReleaseDC(NULL,hdc);
}
// create a font from the user settings
HFONT font=CreateFontSetting(GetSettingString(L"CaptionFont"),g_DPI);
if (!font)
{
LOGFONT lFont;
GetThemeSysFont(theme,TMT_CAPTIONFONT,&lFont);
font=CreateFontIndirect(&lFont);
}
bool bIcon=GetSettingBool(L"ShowIcon");
bool bCenter=GetSettingBool(L"CenterCaption");
bool bGlow=GetSettingBool(bMaximized?L"MaxGlow":L"Glow");
DTTOPTS opts={sizeof(opts),DTT_COMPOSITED|DTT_TEXTCOLOR};
opts.crText=GetSettingInt(bMaximized?(bActive?L"MaxColor":L"InactiveMaxColor"):(bActive?L"TextColor":L"InactiveColor"))&0xFFFFFF;
BOOL bComposition;
if (SUCCEEDED(DwmIsCompositionEnabled(&bComposition)) && bComposition)
{
// Aero Theme
PAINTSTRUCT ps;
HDC hdc=BeginPaint(hWnd,&ps);
BP_PAINTPARAMS paintParams={sizeof(paintParams),BPPF_ERASE};
HDC hdcPaint=NULL;
HPAINTBUFFER hBufferedPaint=BeginBufferedPaint(hdc,&ps.rcPaint,BPBF_TOPDOWNDIB,&paintParams,&hdcPaint);
if (hdcPaint)
{
// exclude the caption buttons
rc.right-=g_SysButtonSize.cx+5;
if (GetWinVersion()==WIN_VER_VISTA) rc.bottom++;
if (!bMaximized)
{
rc.left+=g_CustomCaption[0].leftPadding;
int y=g_CustomCaption[0].topPadding;
if (y>rc.bottom-iconSize) y=rc.bottom-iconSize;
if (bIcon)
{
DrawIconEx(hdcPaint,rc.left,y,hIcon,iconSize,iconSize,0,NULL,DI_NORMAL|DI_NOMIRROR);
rc.left+=iconSize;
}
rc.left+=g_CustomCaption[0].iconPadding;
rc.bottom++;
}
else
{
// when the window is maximized, the caption bar is partially off-screen, so align the icon to the bottom
rc.left+=g_CustomCaption[1].leftPadding;
if (bIcon)
{
DrawIconEx(hdcPaint,rc.left,rc.bottom-iconSize-g_CustomCaption[1].topPadding,hIcon,iconSize,iconSize,0,NULL,DI_NORMAL|DI_NOMIRROR);
rc.left+=iconSize;
}
rc.left+=g_CustomCaption[1].iconPadding;
if (GetWinVersion()>=WIN_VER_WIN10)
rc.bottom++;
}
if (GetWinVersion()<WIN_VER_WIN10)
rc.top=rc.bottom-g_SysButtonSize.cy;
HFONT font0=(HFONT)SelectObject(hdcPaint,font);
RECT rcText={0,0,0,0};
opts.dwFlags|=DTT_CALCRECT;
DrawThemeTextEx(theme,hdcPaint,0,0,caption,-1,DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE|DT_CALCRECT,&rcText,&opts);
int textWidth=rcText.right-rcText.left;
if (bCenter && textWidth<rc.right-rc.left)
{
rc.left+=(rc.right-rc.left-textWidth)/2;
}
if (textWidth>rc.right-rc.left)
textWidth=rc.right-rc.left;
opts.dwFlags&=~DTT_CALCRECT;
if (bGlow)
{
HDC hSrc=CreateCompatibleDC(hdcPaint);
HGDIOBJ bmp0=SelectObject(hSrc,bMaximized?g_GlowBmpMax:g_GlowBmp);
BLENDFUNCTION func={AC_SRC_OVER,0,255,AC_SRC_ALPHA};
AlphaBlend(hdcPaint,rc.left-11,rc.top,11,rc.bottom-rc.top,hSrc,0,0,11,24,func);
AlphaBlend(hdcPaint,rc.left,rc.top,textWidth,rc.bottom-rc.top,hSrc,11,0,2,24,func);
AlphaBlend(hdcPaint,rc.left+textWidth,rc.top,11,rc.bottom-rc.top,hSrc,13,0,11,24,func);
SelectObject(hSrc,bmp0);
DeleteDC(hSrc);
}
DrawThemeTextEx(theme,hdcPaint,0,0,caption,-1,DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE|DT_END_ELLIPSIS,&rc,&opts);
SelectObject(hdcPaint,font0);
EndBufferedPaint(hBufferedPaint,TRUE);
}
EndPaint(hWnd,&ps);
}
else
{
// Basic Theme
// first draw the caption bar
DefCaptionProc(hWnd,uMsg,wParam,lParam);
// then draw the caption directly in the window DC
HDC hdc=GetWindowDC(hWnd);
// exclude the caption buttons
rc.right-=g_SysButtonSize.cx+5;
rc.top=rc.bottom-g_SysButtonSize.cy;
rc.left+=g_CustomCaption[2].leftPadding;
if (bIcon)
{
DrawIconEx(hdc,rc.left,rc.bottom-iconSize-g_CustomCaption[2].topPadding,hIcon,iconSize,iconSize,0,NULL,DI_NORMAL|DI_NOMIRROR);
rc.left+=iconSize;
}
rc.left+=g_CustomCaption[2].iconPadding;
HFONT font0=(HFONT)SelectObject(hdc,font);
RECT rcText={0,0,0,0};
opts.dwFlags|=DTT_CALCRECT;
DrawThemeTextEx(theme,hdc,0,0,caption,-1,DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE|DT_CALCRECT,&rcText,&opts);
int textWidth=rcText.right-rcText.left;
if (bCenter && textWidth<rc.right-rc.left)
{
rc.left+=(rc.right-rc.left-textWidth)/2;
}
if (textWidth>rc.right-rc.left)
textWidth=rc.right-rc.left;
opts.dwFlags&=~DTT_CALCRECT;
if (bGlow)
{
HDC hSrc=CreateCompatibleDC(hdc);
HGDIOBJ bmp0=SelectObject(hSrc,bMaximized?g_GlowBmpMax:g_GlowBmp);
BLENDFUNCTION func={AC_SRC_OVER,0,255,AC_SRC_ALPHA};
AlphaBlend(hdc,rc.left-11,rc.top,11,rc.bottom-rc.top,hSrc,0,0,11,24,func);
AlphaBlend(hdc,rc.left,rc.top,textWidth,rc.bottom-rc.top,hSrc,11,0,2,24,func);
AlphaBlend(hdc,rc.left+textWidth,rc.top,11,rc.bottom-rc.top,hSrc,13,0,11,24,func);
SelectObject(hSrc,bmp0);
DeleteDC(hSrc);
}
DrawThemeTextEx(theme,hdc,0,0,caption,-1,DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE|DT_END_ELLIPSIS,&rc,&opts);
SelectObject(hdc,font0);
ReleaseDC(hWnd,hdc);
}
DeleteObject(font);
CloseThemeData(theme);
return 0;
}
return DefCaptionProc(hWnd,uMsg,wParam,lParam);
}
// Replacement proc for the "Client Caption" class that hooks the main frame and the caption windows
static LRESULT CALLBACK ClassCaptionProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if (uMsg==WM_CREATE)
{
WNDPROC proc=(WNDPROC)SetWindowLongPtr(hWnd,GWLP_WNDPROC,(LONG_PTR)SubclassCaptionProc);
SetProp(hWnd,MAKEINTATOM(g_SubclassAtom),(HANDLE)proc);
HWND frame=GetParent(hWnd);
proc=(WNDPROC)SetWindowLongPtr(frame,GWLP_WNDPROC,(LONG_PTR)SubclassFrameProc);
SetProp(frame,MAKEINTATOM(g_SubclassAtom),(HANDLE)proc);
PostMessage(frame,g_Message,0,0);
}
return CallWindowProc(g_OldClassCaptionProc,hWnd,uMsg,wParam,lParam);
}
static BOOL CALLBACK EnumTopWindows( HWND hwnd, LPARAM lParam )
{
DWORD processId;
DWORD threadId=GetWindowThreadProcessId(hwnd,&processId);
if (processId==GetCurrentProcessId())
{
HWND caption=FindWindowEx(hwnd,NULL,L"Client Caption",NULL);
if (caption)
{
LogToFile(CIE_LOG,L"InitClassicIE: caption=%p",caption);
if (!g_OldClassCaptionProc)
g_OldClassCaptionProc=(WNDPROC)SetClassLongPtr(caption,GCLP_WNDPROC,(LONG_PTR)ClassCaptionProc);
WNDPROC proc=(WNDPROC)SetWindowLongPtr(caption,GWLP_WNDPROC,(LONG_PTR)SubclassCaptionProc);
SetProp(caption,MAKEINTATOM(g_SubclassAtom),(HANDLE)proc);
proc=(WNDPROC)SetWindowLongPtr(hwnd,GWLP_WNDPROC,(LONG_PTR)SubclassFrameProc);
SetProp(hwnd,MAKEINTATOM(g_SubclassAtom),(HANDLE)proc);
PostMessage(hwnd,g_Message,0,0);
}
}
return TRUE;
}
void InitClassicIE( HMODULE hModule )
{
CRegKey regKey;
if (regKey.Open(HKEY_CURRENT_USER,GetSettingsRegPath())==ERROR_SUCCESS)
{
DWORD val;
if (regKey.QueryDWORDValue(L"CustomAero",val)==ERROR_SUCCESS)
{
g_CustomCaption[0].leftPadding=(val&255);
g_CustomCaption[0].topPadding=((val>>8)&255);
g_CustomCaption[0].iconPadding=((val>>16)&255);
}
if (regKey.QueryDWORDValue(L"CustomAeroMax",val)==ERROR_SUCCESS)
{
g_CustomCaption[1].leftPadding=(val&255);
g_CustomCaption[1].topPadding=((val>>8)&255);
g_CustomCaption[1].iconPadding=((val>>16)&255);
}
if (regKey.QueryDWORDValue(L"CustomBasic",val)==ERROR_SUCCESS)
{
g_CustomCaption[2].leftPadding=(val&255);
g_CustomCaption[2].topPadding=((val>>8)&255);
g_CustomCaption[2].iconPadding=((val>>16)&255);
}
}
g_Message=RegisterWindowMessage(L"ClassicIE.Injected");
g_SubclassAtom=GlobalAddAtom(L"ClassicIE.Subclass");
ChangeWindowMessageFilter(g_Message,MSGFLT_ADD);
g_GlowBmp=(HBITMAP)LoadImage(g_Instance,MAKEINTRESOURCE(IDB_GLOW),IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION);
PremultiplyBitmap(g_GlowBmp,GetSettingInt(L"GlowColor"));
g_GlowBmpMax=(HBITMAP)LoadImage(g_Instance,MAKEINTRESOURCE(IDB_GLOW),IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION);
PremultiplyBitmap(g_GlowBmpMax,GetSettingInt(L"MaxGlowColor"));
EnumWindows(EnumTopWindows,0);
}
| 32.685879 | 137 | 0.73629 | Duzzy-ExoDuus |
82ebc3afc48794c55ae6c033eb8b3d02d5e9b2e1 | 1,524 | cpp | C++ | code/920.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 23 | 2020-03-30T05:44:56.000Z | 2021-09-04T16:00:57.000Z | code/920.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 1 | 2020-05-10T15:04:05.000Z | 2020-06-14T01:21:44.000Z | code/920.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 6 | 2020-03-30T05:45:04.000Z | 2020-08-13T10:01:39.000Z | #include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeaf(TreeNode* root) {
return root->left == NULL && root->right == NULL;
}
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ostream& operator << (ostream& os, const vector<int>& vec){
for (int x: vec)
os << x << " ";
os << endl;
return os;
}
ostream& operator << (ostream& os, const vector<vector<int>>& vec){
for (auto& v: vec){
for (int x: v)
os << x << " ";
os << endl;
}
return os;
}
class Solution {
int f[105][105];
public:
int numMusicPlaylists(int N, int L, int K) {
if (L < N) return 0;
const int M = 1000000007;
f[0][0] = 1;
for (int i = 1; i <= L; ++i)
for (int j = 1; j <= N; ++j)
f[i][j] = 1ll * f[i - 1][j - 1] * (N - j + 1) % M +
1ll * f[i - 1][j] * max(j - K, 0) % M,
f[i][j] %= M;
return f[L][N];
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| 20.876712 | 68 | 0.463255 | Nightwish-cn |
82ebed1201a7f4989f1d879d85456272000dd064 | 1,541 | cpp | C++ | KnightmareRemake/GameMain.cpp | pdpdds/knightmare | 25323acb23a0af326cebb6f342e30ccbfe0c2f0d | [
"BSD-2-Clause"
] | null | null | null | KnightmareRemake/GameMain.cpp | pdpdds/knightmare | 25323acb23a0af326cebb6f342e30ccbfe0c2f0d | [
"BSD-2-Clause"
] | null | null | null | KnightmareRemake/GameMain.cpp | pdpdds/knightmare | 25323acb23a0af326cebb6f342e30ccbfe0c2f0d | [
"BSD-2-Clause"
] | null | null | null | #include "GameMain.h"
#include "CGameCore.h"
HINSTANCE g_hInst;
HWND g_hWnd;
#define SPRITE_DIAMETER 30
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
g_hInst = hInstance;
static char Name[] = "Knightmare";
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = CGameCore::WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = (HINSTANCE)GetWindowLong(NULL, GWL_HINSTANCE);
wndclass.hIcon = LoadIcon(NULL, "YUKINO");
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = Name;
RegisterClass(&wndclass);
g_hWnd = CreateWindow(Name,
"Knightmare", WS_POPUP | WS_VISIBLE,
200,
60, SCREEN_WIDTH,
SCREEN_HEIGHT,
NULL,
NULL,
(HINSTANCE)GetWindowLong(NULL, GWL_HINSTANCE),
NULL);
ShowWindow(g_hWnd, SW_SHOW);
UpdateWindow(g_hWnd);
CGameCore::GetInstance()->Initialize(hInstance, g_hWnd, SCREEN_WIDTH, SCREEN_HEIGHT);
SetTimer(g_hWnd, 1, 980, NULL);
while (TRUE)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!GetMessage(&msg, NULL, 0, 0))
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else if (CGameCore::GetInstance()->GetPause())
{
WaitMessage();
}
else
{
CGameCore::GetInstance()->ProcessGame();
}
}
return 0;
}
| 18.129412 | 86 | 0.710578 | pdpdds |
82ede2568f481afb8ea5d7a75b26cea6097b188a | 841 | cpp | C++ | Leetcode/869_reorderedPowerOf2.cpp | ZZh2333/ubuntuProjectFiles | ded3d74e040bf6683b3b67a6956eb6fbe5805155 | [
"MIT"
] | null | null | null | Leetcode/869_reorderedPowerOf2.cpp | ZZh2333/ubuntuProjectFiles | ded3d74e040bf6683b3b67a6956eb6fbe5805155 | [
"MIT"
] | null | null | null | Leetcode/869_reorderedPowerOf2.cpp | ZZh2333/ubuntuProjectFiles | ded3d74e040bf6683b3b67a6956eb6fbe5805155 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool reorderedPowerOf2(int n)
{
vector<int> search = contDigital(n);
vector<vector<int>> allPossible;
for (int i = 0; i < 30; i++)
{
allPossible.push_back(contDigital(pow(2, i)));
}
for (int i = 0; i < allPossible.size(); i++)
{
if (search == allPossible[i])
{
return true;
}
}
return false;
}
vector<int> contDigital(int n)
{
vector<int> count = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
while (n != 0)
{
count[n % 10]++;
n = n / 10;
}
return count;
}
};
int main()
{
Solution solve;
int n = 46;
cout << solve.reorderedPowerOf2(n) << endl;
} | 20.512195 | 59 | 0.450654 | ZZh2333 |
82ededae93c7b0a0e9de59b4981a360c47a25df0 | 242 | hh | C++ | hackt_docker/hackt/src/lexer/input_manager.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/lexer/input_manager.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/lexer/input_manager.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | // aliased to different file name so "parser/lexyacc-prefix.awk"
// won't rename it.
#include "lexer/yyin_manager.hh"
namespace HAC {
namespace lexer {
typedef yyin_manager input_manager;
} // end namespace lexer
} // end namespace HAC
| 22 | 65 | 0.735537 | broken-wheel |
82f2fde8ae28b38d4bf29c8934c452428be9d414 | 3,470 | cpp | C++ | DSP/extensions/TrajectoryLib/sources/Bspline2D.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | null | null | null | DSP/extensions/TrajectoryLib/sources/Bspline2D.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | null | null | null | DSP/extensions/TrajectoryLib/sources/Bspline2D.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | null | null | null | /*
* Bspline Function Unit for TTBlue
* based on the bspline code by Jasch: http://www.jasch.ch/
* ported by Nils Peters
*
*/
#include "Bspline2D.h"
#define thisTTClass Bspline2D
#define thisTTClassName "bspline.2D"
#define thisTTClassTags "audio, trajectory, 2D, spline"
TT_AUDIO_CONSTRUCTOR
{ //addAttribute(A, kTypeFloat64);
addAttribute(Degree, kTypeUInt8);
addAttribute(Steps, kTypeUInt16);
addAttribute(Dimen, kTypeUInt8);
addAttribute(Resolution, kTypeUInt16);//was size
setProcessMethod(processAudio);
// setCalculateMethod(calculateValue);
}
Bspline2D::~Bspline2D()
{
;
}
//TTErr Bspline2D::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
//{
// y = x;
// return kTTErrNone;
//}
void Bspline2D::calculatePoint()
{
TTUInt16 i;
TTFloat64 temp;
point3D[0] = 0;//x
point3D[1] = 0;//y
point3D[2] = 0;//z
for ( i = 0; i <= mResolution; i++) {
temp = calculateBlend(i, mDegree); // same blend is used for each dimension coordinate
b_op[0] += b_control[i*3] * temp;
b_op[1] += b_control[i*3+1] * temp;
b_op[2] += b_control[i*3+2] * temp;
}
}
float Bspline2D::calculateBlend(TTUInt16 k, TTUInt16 t)
{
TTFloat64 value;
TTFloat64 v = interval;
if (t == 1) { // base case for the recursion
if ((b_knots[k] <= v) && (v < b_knots[k+1])) {
value=1;
} else {
value=0;
}
} else {
if ((b_knots[k + t - 1] == b_knots[k]) && (b_knots[k + t] == b_knots[k + 1])) { // check for divide by zero
value = 0;
} else if (b_knots[k + t - 1] == b_knots[k]) { // if a term's denominator is zero, use just the other
value = (b_knots[k + t] - v) / (b_knots[k + t] - b_knots[k + 1]) * calculateBlend(k + 1, t - 1);
} else if (b_knots[k + t] == b_knots[k + 1]) {
value = (v - b_knots[k]) / (b_knots[k + t - 1] - b_knots[k]) * calculateBlend(k, t - 1);
} else {
value = (v - b_knots[k]) / (b_knots[k + t - 1] - b_knots[k]) * calculateBlend(k, t - 1) +
(b_knots[k + t] - v) / (b_knots[k + t] - b_knots[k + 1]) * calculateBlend(k + 1, t - 1);
}
}
return value;
}
void Bspline2D::calculateKnots() // generate knot-vector
{
TTUInt8 i, t, n;
n = mResolution;
t = mDegree;
for (i = 0; i <= (n + t); i++){
if (i < t) {
b_knots[i] = 0;
} else if ((t <= i) && (i <= n)) {
b_knots[i] = i - t + 1;
} else if (i > n) {
b_knots[i] = n - t + 2; // if n - t = -2 then we're screwed, everything goes to 0
}
}
}
TTErr Bspline2D::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 numOutputChannels = out.getNumChannelsAsInt();
if (numOutputChannels != 2) {
TTValue v = 2;
out.setMaxNumChannels(v);
out.setNumChannels(v);
}
TTAudioSignal& in0 = inputs->getSignal(0);
TTUInt16 vs = in0.getVectorSizeAsInt();
TTSampleValuePtr inSampleX = in0.mSampleVectors[0];
TTSampleValuePtr outSampleX = out.mSampleVectors[0];
TTSampleValuePtr outSampleY = out.mSampleVectors[1];
TTFloat64 f;
for (int i=0; i<vs; i++) {
f = inSampleX[i] * 0.5; //0... 1.
if ((f > 0) && (f < 1)){
interval = f * (TTFloat64)((mResolution - mDegree) + 2);
calculatePoint(); // output intermediate point
outSampleX[i] = b_op[0];
outSampleY[i] = b_op[1];
//outSampleZ[i] = b_op[2];
} else if (f <= 0.0){
// output the first point
} else if (f >= 1.0){
// output the last point
}
}
return kTTErrNone;
}
| 25.514706 | 109 | 0.606916 | avilleret |
82f3159b433cb8391baa047bfd5822b211498d07 | 231 | cpp | C++ | tests/codegen/unroll.cpp | casparant/bpftrace | a6823165a521e894b3fb028733131878cf70d3a7 | [
"Apache-2.0"
] | 5,119 | 2018-10-08T15:19:24.000Z | 2022-03-31T15:03:48.000Z | tests/codegen/unroll.cpp | casparant/bpftrace | a6823165a521e894b3fb028733131878cf70d3a7 | [
"Apache-2.0"
] | 1,568 | 2018-10-08T19:14:25.000Z | 2022-03-31T01:44:41.000Z | tests/codegen/unroll.cpp | casparant/bpftrace | a6823165a521e894b3fb028733131878cf70d3a7 | [
"Apache-2.0"
] | 838 | 2018-10-08T20:16:47.000Z | 2022-03-31T06:15:58.000Z | #include "common.h"
namespace bpftrace {
namespace test {
namespace codegen {
TEST(codegen, unroll)
{
test("BEGIN { @i = 0; unroll(5) { @i += 1 } }", NAME);
}
} // namespace codegen
} // namespace test
} // namespace bpftrace
| 15.4 | 56 | 0.636364 | casparant |
82f754ee9aa28f6f0de0465a584b400d631697ae | 36,557 | cpp | C++ | torch/lib/THD/master_worker/worker/dispatch/Tensor.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | 1 | 2019-07-21T02:13:22.000Z | 2019-07-21T02:13:22.000Z | torch/lib/THD/master_worker/worker/dispatch/Tensor.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | torch/lib/THD/master_worker/worker/dispatch/Tensor.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | template<typename... Ts>
static at::Tensor createTensor(RPCType type, Ts &... args) {
if (type == RPCType::UCHAR)
return at::CPU(at::kByte).tensor(std::forward<Ts>(args)...);
else if (type == RPCType::CHAR)
return at::CPU(at::kChar).tensor(std::forward<Ts>(args)...);
else if (type == RPCType::SHORT)
return at::CPU(at::kShort).tensor(std::forward<Ts>(args)...);
else if (type == RPCType::INT)
return at::CPU(at::kInt).tensor(std::forward<Ts>(args)...);
else if (type == RPCType::LONG)
return at::CPU(at::kLong).tensor(std::forward<Ts>(args)...);
else if (type == RPCType::FLOAT)
return at::CPU(at::kFloat).tensor(std::forward<Ts>(args)...);
else if (type == RPCType::DOUBLE)
return at::CPU(at::kDouble).tensor(std::forward<Ts>(args)...);
throw std::invalid_argument("passed character doesn't represent a tensor type");
}
static at::Tensor createTensorWithStorage(RPCType type, at::Storage* storage, ptrdiff_t storageOffset, at::IntList size, at::IntList stride) {
if (type == RPCType::UCHAR)
return at::CPU(at::kByte).tensor(*storage, storageOffset, size, stride);
else if (type == RPCType::CHAR)
return at::CPU(at::kChar).tensor(*storage, storageOffset, size, stride);
else if (type == RPCType::SHORT)
return at::CPU(at::kShort).tensor(*storage, storageOffset, size, stride);
else if (type == RPCType::INT)
return at::CPU(at::kInt).tensor(*storage, storageOffset, size, stride);
else if (type == RPCType::LONG)
return at::CPU(at::kLong).tensor(*storage, storageOffset, size, stride);
else if (type == RPCType::FLOAT)
return at::CPU(at::kFloat).tensor(*storage, storageOffset, size, stride);
else if (type == RPCType::DOUBLE)
return at::CPU(at::kDouble).tensor(*storage, storageOffset, size, stride);
throw std::invalid_argument("passed character doesn't represent a tensor type");
}
static at::Tensor createTensorWithTensor(RPCType type, at::Tensor& tensor) {
if (type == RPCType::UCHAR)
return at::CPU(at::kByte).alias(tensor);
else if (type == RPCType::CHAR)
return at::CPU(at::kChar).alias(tensor);
else if (type == RPCType::SHORT)
return at::CPU(at::kShort).alias(tensor);
else if (type == RPCType::INT)
return at::CPU(at::kInt).alias(tensor);
else if (type == RPCType::LONG)
return at::CPU(at::kLong).alias(tensor);
else if (type == RPCType::FLOAT)
return at::CPU(at::kFloat).alias(tensor);
else if (type == RPCType::DOUBLE)
return at::CPU(at::kDouble).alias(tensor);
throw std::invalid_argument("passed character doesn't represent a tensor type");
}
static void tensorNew(rpc::RPCMessage& raw_message) {
RPCType type = unpackType(raw_message);
thd::object_id_type id = unpackTensor(raw_message);
finalize(raw_message);
workerTensors.emplace(
id,
createTensor(type)
);
}
static void tensorNewWithSize(rpc::RPCMessage& raw_message) {
RPCType type = unpackType(raw_message);
thd::object_id_type id = unpackTensor(raw_message);
THLongStorage *size = unpackTHLongStorage(raw_message);
THLongStorage *stride = unpackTHLongStorage(raw_message);
finalize(raw_message);
at::IntList sz(THLongStorage_data(size), THLongStorage_size(size));
at::IntList str(THLongStorage_data(stride), THLongStorage_size(stride));
workerTensors.emplace(
id,
createTensor(type, sz, str)
);
THLongStorage_free(size);
THLongStorage_free(stride);
}
static void tensorNewWithStorage(rpc::RPCMessage& raw_message) {
RPCType type = unpackType(raw_message);
thd::object_id_type id = unpackTensor(raw_message);
at::Storage *storage = unpackRetrieveStorage(raw_message);
ptrdiff_t storageOffset = unpackInteger(raw_message);
THLongStorage *size = unpackTHLongStorage(raw_message);
THLongStorage *stride = unpackTHLongStorage(raw_message);
finalize(raw_message);
at::IntList sz(THLongStorage_data(size), THLongStorage_size(size));
at::IntList str(THLongStorage_data(stride), THLongStorage_size(stride));
workerTensors.emplace(
id,
createTensorWithStorage(type, storage, storageOffset, sz, str)
);
THLongStorage_free(size);
THLongStorage_free(stride);
}
static void tensorNewWithTensor(rpc::RPCMessage& raw_message) {
RPCType type = unpackType(raw_message);
thd::object_id_type id = unpackTensor(raw_message);
at::Tensor self = unpackRetrieveTensor(raw_message);
finalize(raw_message);
workerTensors.emplace(
id,
createTensorWithTensor(type, self)
);
}
static void tensorNewClone(rpc::RPCMessage& raw_message) {
thd::object_id_type id = unpackTensor(raw_message);
at::Tensor tensor = unpackRetrieveTensor(raw_message);
finalize(raw_message);
workerTensors.emplace(
id,
tensor.clone()
);
}
static void tensorResize(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
THLongStorage *size = unpackTHLongStorage(raw_message);
finalize(raw_message);
at::ArrayRef<int64_t> sizeRef(THLongStorage_data(size), THLongStorage_size(size));
tensor.resize_(sizeRef);
THLongStorage_free(size);
}
static void tensorResizeAs(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
finalize(raw_message);
tensor.resize_as_(src);
}
static void tensorResizeNd(rpc::RPCMessage& raw_message, size_t N) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
std::vector<int64_t> size(N);
for (size_t i = 0; i < N; ++i) {
size[i] = unpackInteger(raw_message);
}
finalize(raw_message);
tensor.resize_(size);
}
static void tensorResize1d(rpc::RPCMessage& raw_message) {
tensorResizeNd(raw_message, 1);
}
static void tensorResize2d(rpc::RPCMessage& raw_message) {
tensorResizeNd(raw_message, 2);
}
static void tensorResize3d(rpc::RPCMessage& raw_message) {
tensorResizeNd(raw_message, 3);
}
static void tensorResize4d(rpc::RPCMessage& raw_message) {
tensorResizeNd(raw_message, 4);
}
static void tensorResize5d(rpc::RPCMessage& raw_message) {
tensorResizeNd(raw_message, 5);
}
static void tensorSet(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
finalize(raw_message);
tensor.set_(src);
}
static void tensorSetStorage(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Storage *storage = unpackRetrieveStorage(raw_message);
ptrdiff_t storageOffset = unpackInteger(raw_message);
THLongStorage *size = unpackTHLongStorage(raw_message);
THLongStorage *stride = unpackTHLongStorage(raw_message);
finalize(raw_message);
at::ArrayRef<int64_t> sizeRef(THLongStorage_data(size), THLongStorage_size(size));
at::ArrayRef<int64_t> strideRef(THLongStorage_data(stride), THLongStorage_size(stride));
tensor.set_(
*storage,
storageOffset,
sizeRef,
strideRef
);
THLongStorage_free(size);
THLongStorage_free(stride);
}
static void tensorSetStorage1d(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Storage *storage = unpackRetrieveStorage(raw_message);
ptrdiff_t storageOffset = unpackInteger(raw_message);
int64_t size0 = unpackInteger(raw_message);
int64_t stride0 = unpackInteger(raw_message);
finalize(raw_message);
at::ArrayRef<int64_t> sizes(size0);
at::ArrayRef<int64_t> strides(stride0);
tensor.set_(
*storage,
storageOffset,
sizes,
strides
);
}
static void tensorSetStorage2d(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Storage *storage = unpackRetrieveStorage(raw_message);
ptrdiff_t storageOffset = unpackInteger(raw_message);
int64_t size0 = unpackInteger(raw_message);
int64_t stride0 = unpackInteger(raw_message);
int64_t size1 = unpackInteger(raw_message);
int64_t stride1 = unpackInteger(raw_message);
finalize(raw_message);
THLongStorage *sizes = THLongStorage_newWithSize2(size0, size1);
THLongStorage *strides = THLongStorage_newWithSize2(stride0, stride1);
at::ArrayRef<int64_t> sizeRef(THLongStorage_data(sizes), THLongStorage_size(sizes));
at::ArrayRef<int64_t> strideRef(THLongStorage_data(strides), THLongStorage_size(strides));
tensor.set_(
*storage,
storageOffset,
sizeRef,
strideRef
);
THLongStorage_free(sizes);
THLongStorage_free(strides);
}
static void tensorSetStorage3d(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Storage *storage = unpackRetrieveStorage(raw_message);
ptrdiff_t storageOffset = unpackInteger(raw_message);
int64_t size0 = unpackInteger(raw_message);
int64_t stride0 = unpackInteger(raw_message);
int64_t size1 = unpackInteger(raw_message);
int64_t stride1 = unpackInteger(raw_message);
int64_t size2 = unpackInteger(raw_message);
int64_t stride2 = unpackInteger(raw_message);
finalize(raw_message);
THLongStorage *sizes = THLongStorage_newWithSize3(size0, size1, size2);
THLongStorage *strides = THLongStorage_newWithSize3(stride0, stride1, stride2);
at::ArrayRef<int64_t> sizeRef(THLongStorage_data(sizes), THLongStorage_size(sizes));
at::ArrayRef<int64_t> strideRef(THLongStorage_data(strides), THLongStorage_size(strides));
tensor.set_(
*storage,
storageOffset,
sizeRef,
strideRef
);
THLongStorage_free(sizes);
THLongStorage_free(strides);
}
static void tensorSetStorage4d(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Storage *storage = unpackRetrieveStorage(raw_message);
ptrdiff_t storageOffset = unpackInteger(raw_message);
int64_t size0 = unpackInteger(raw_message);
int64_t stride0 = unpackInteger(raw_message);
int64_t size1 = unpackInteger(raw_message);
int64_t stride1 = unpackInteger(raw_message);
int64_t size2 = unpackInteger(raw_message);
int64_t stride2 = unpackInteger(raw_message);
int64_t size3 = unpackInteger(raw_message);
int64_t stride3 = unpackInteger(raw_message);
finalize(raw_message);
THLongStorage *sizes = THLongStorage_newWithSize4(size0, size1, size2, size3);
THLongStorage *strides = THLongStorage_newWithSize4(stride0, stride1,
stride2, stride3);
at::ArrayRef<int64_t> sizeRef(THLongStorage_data(sizes), THLongStorage_size(sizes));
at::ArrayRef<int64_t> strideRef(THLongStorage_data(strides), THLongStorage_size(strides));
tensor.set_(
*storage,
storageOffset,
sizeRef,
strideRef
);
THLongStorage_free(sizes);
THLongStorage_free(strides);
}
static void tensorNarrow(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
int64_t firstIndex = unpackInteger(raw_message);
int64_t size = unpackInteger(raw_message);
finalize(raw_message);
tensor = src.narrow(dimension, firstIndex, size);
}
static void tensorSelect(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
int64_t sliceIndex = unpackInteger(raw_message);
finalize(raw_message);
tensor = src.select(dimension, sliceIndex);
}
static void tensorTranspose(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension1 = unpackInteger(raw_message);
int dimension2 = unpackInteger(raw_message);
finalize(raw_message);
tensor = src.transpose(dimension1, dimension2);
}
static void tensorUnfold(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
int64_t size = unpackInteger(raw_message);
int64_t step = unpackInteger(raw_message);
finalize(raw_message);
tensor = src.unfold(dimension, size, step);
}
static void tensorSqueeze(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
finalize(raw_message);
// FIXME: could be at::squeeze_out(tensor, src), but we don't generate
// _out functions for native ATen functions (and may not want to).
tensor.set_(src.squeeze());
}
static void tensorSqueeze1d(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
finalize(raw_message);
// FIXME: could be at::squeeze_out(tensor, src, dimension), but we don't generate
// _out functions for native ATen functions (and may not want to).
tensor.set_(src.squeeze(dimension));
}
static void tensorFree(rpc::RPCMessage& raw_message) {
object_id_type tensor_id = unpackTensor(raw_message);
(void)workerTensors.erase(tensor_id);
}
static void tensorGather(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dim = unpackInteger(raw_message);
at::Tensor index = unpackRetrieveTensor(raw_message);
finalize(raw_message);
at::gather_out(tensor, src, dim, index);
}
static void tensorScatter(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
int dim = unpackInteger(raw_message);
at::Tensor index = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
finalize(raw_message);
tensor.scatter_(dim, index, src);
}
static void tensorScatterFill(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
int dim = unpackInteger(raw_message);
at::Tensor index = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
tensor.scatter_(dim, index, value);
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
tensor.scatter_(dim, index, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorDot(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
finalize(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = tensor.dot(src).toCLong();
sendValueToMaster(value);
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = tensor.dot(src).toCDouble();
sendValueToMaster(value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorMinall(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
finalize(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = tensor.min().toCLong();
sendValueToMaster(value);
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = tensor.min().toCDouble();
sendValueToMaster(value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorMaxall(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
finalize(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = tensor.max().toCLong();
sendValueToMaster(value);
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = tensor.max().toCDouble();
sendValueToMaster(value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorMedianall(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
finalize(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = tensor.median().toCLong();
sendValueToMaster(value);
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = tensor.median().toCDouble();
sendValueToMaster(value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorSumall(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
finalize(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = tensor.sum().toCLong();
sendValueToMaster(value);
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = tensor.sum().toCDouble();
sendValueToMaster(value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorProdall(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
finalize(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = tensor.prod().toCLong();
sendValueToMaster(value);
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = tensor.prod().toCDouble();
sendValueToMaster(value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorAdd(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::add_out(tensor, src, at::Scalar(value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::add_out(tensor, src, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorSub(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::sub_out(tensor, src, at::Scalar((int64_t)value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::sub_out(tensor, src, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorMul(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::mul_out(tensor, src, at::Scalar((int64_t)value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::mul_out(tensor, src, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorDiv(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::div_out(tensor, src, at::Scalar((int64_t)value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::div_out(tensor, src, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorFmod(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::fmod_out(tensor, src, at::Scalar((int64_t)value));
} else {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::fmod_out(tensor, src, value);
}
}
static void tensorRemainder(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::remainder_out(tensor, src, at::Scalar((int64_t)value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::remainder_out(tensor, src, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorClamp(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t min_value = unpackInteger(raw_message);
int64_t max_value = unpackInteger(raw_message);
finalize(raw_message);
at::clamp_out(tensor, src, at::Scalar((int64_t)min_value), at::Scalar((int64_t)max_value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double min_value = unpackFloat(raw_message);
double max_value = unpackFloat(raw_message);
finalize(raw_message);
at::clamp_out(tensor, src, min_value, max_value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorCadd(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::add_out(tensor, src1, src2, at::Scalar((int64_t)value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::add_out(tensor, src1, src2, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorCsub(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::sub_out(tensor, src1, src2, at::Scalar((int64_t)value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::sub_out(tensor, src1, src2, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorCmul(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
finalize(raw_message);
at::mul_out(tensor, src1, src2);
}
static void tensorCpow(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
finalize(raw_message);
at::pow_out(tensor, src1, src2);
}
static void tensorCdiv(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
finalize(raw_message);
at::div_out(tensor, src1, src2);
}
static void tensorCfmod(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
finalize(raw_message);
at::fmod_out(tensor, src1, src2);
}
static void tensorCremainder(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
finalize(raw_message);
at::remainder_out(tensor, src1, src2);
}
static void tensorAddcmul(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
at::Tensor src3 = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::addcmul_out(tensor, src1, src2, src3, at::Scalar((int64_t)value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::addcmul_out(tensor, src1, src2, src3, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorAddcdiv(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
at::Tensor src3 = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = unpackInteger(raw_message);
finalize(raw_message);
at::addcdiv_out(tensor, src1, src2, src3, at::Scalar((int64_t)value));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = unpackFloat(raw_message);
finalize(raw_message);
at::addcdiv_out(tensor, src1, src2, src3, value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorAddmv(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
at::Tensor mat = unpackRetrieveTensor(raw_message);
at::Tensor vec = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t beta = unpackInteger(raw_message);
int64_t alpha = unpackInteger(raw_message);
finalize(raw_message);
at::addmv_out(tensor, src, mat, vec, at::Scalar((int64_t)beta), at::Scalar((int64_t)alpha));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double beta = unpackFloat(raw_message);
double alpha = unpackFloat(raw_message);
finalize(raw_message);
at::addmv_out(tensor, src, mat, vec, beta, alpha);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorAddmm(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
at::Tensor mat1 = unpackRetrieveTensor(raw_message);
at::Tensor mat2 = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t beta = unpackInteger(raw_message);
int64_t alpha = unpackInteger(raw_message);
finalize(raw_message);
at::addmm_out(tensor, src, mat1, mat2, at::Scalar((int64_t)beta), at::Scalar((int64_t)alpha));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double beta = unpackFloat(raw_message);
double alpha = unpackFloat(raw_message);
finalize(raw_message);
at::addmm_out(tensor, src, mat1, mat2, beta, alpha);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorAddr(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
at::Tensor vec1 = unpackRetrieveTensor(raw_message);
at::Tensor vec2 = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t beta = unpackInteger(raw_message);
int64_t alpha = unpackInteger(raw_message);
finalize(raw_message);
at::addr_out(tensor, src, vec1, vec2,at::Scalar((int64_t)beta), at::Scalar((int64_t)alpha));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double beta = unpackFloat(raw_message);
double alpha = unpackFloat(raw_message);
finalize(raw_message);
at::addr_out(tensor, src, vec1, vec2, beta, alpha);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorAddbmm(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
at::Tensor batch1 = unpackRetrieveTensor(raw_message);
at::Tensor batch2 = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t beta = unpackInteger(raw_message);
int64_t alpha = unpackInteger(raw_message);
finalize(raw_message);
at::addbmm_out(tensor, src, batch1, batch2, at::Scalar((int64_t)beta), at::Scalar((int64_t)alpha));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double beta = unpackFloat(raw_message);
double alpha = unpackFloat(raw_message);
finalize(raw_message);
at::addbmm_out(tensor, src, batch1, batch2, beta, alpha);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorBaddbmm(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
at::Tensor batch1 = unpackRetrieveTensor(raw_message);
at::Tensor batch2 = unpackRetrieveTensor(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t beta = unpackInteger(raw_message);
int64_t alpha = unpackInteger(raw_message);
finalize(raw_message);
at::baddbmm_out(tensor, src, batch1, batch2, at::Scalar((int64_t)beta), at::Scalar((int64_t)alpha));
} else if (at::isFloatingType(tensor.type().scalarType())) {
double beta = unpackFloat(raw_message);
double alpha = unpackFloat(raw_message);
finalize(raw_message);
at::baddbmm_out(tensor, src, batch1, batch2, beta, alpha);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorMax(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor indices_ = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
int keepdim = unpackInteger(raw_message);
finalize(raw_message);
at::max_out(tensor, indices_, src, dimension, keepdim);
}
static void tensorMin(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor indices_ = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
int keepdim = unpackInteger(raw_message);
finalize(raw_message);
at::min_out(tensor, indices_, src, dimension, keepdim);
}
static void tensorKthvalue(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor indices_ = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int k = unpackInteger(raw_message);
int dimension = unpackInteger(raw_message);
int keepdim = unpackInteger(raw_message);
finalize(raw_message);
at::kthvalue_out(tensor, indices_, src, k, dimension, keepdim);
}
static void tensorMode(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor indices_ = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
int keepdim = unpackInteger(raw_message);
finalize(raw_message);
at::mode_out(tensor, indices_, src, dimension, keepdim);
}
static void tensorMedian(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor indices_ = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
int keepdim = unpackInteger(raw_message);
finalize(raw_message);
at::median_out(tensor, indices_, src, dimension, keepdim);
}
static void tensorSum(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
int keepdim = unpackInteger(raw_message);
finalize(raw_message);
at::sum_out(tensor, src, dimension, keepdim);
}
static void tensorProd(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
int keepdim = unpackInteger(raw_message);
finalize(raw_message);
at::prod_out(tensor, src, dimension, keepdim);
}
static void tensorCumsum(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
finalize(raw_message);
at::cumsum_out(tensor, src, dimension);
}
static void tensorCumprod(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
finalize(raw_message);
at::cumprod_out(tensor, src, dimension);
}
static void tensorSign(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src = unpackRetrieveTensor(raw_message);
finalize(raw_message);
at::sign_out(tensor, src);
}
static void tensorTrace(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
finalize(raw_message);
if (at::isIntegralType(tensor.type().scalarType())) {
int64_t value = tensor.trace().toCLong();
sendValueToMaster(value);
} else if (at::isFloatingType(tensor.type().scalarType())) {
double value = tensor.trace().toCDouble();
sendValueToMaster(value);
} else {
throw std::invalid_argument("expected scalar type");
}
}
static void tensorCross(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
int dimension = unpackInteger(raw_message);
finalize(raw_message);
at::cross_out(tensor, src1, src2, dimension);
}
static void tensorCmax(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
finalize(raw_message);
at::max_out(tensor, src1, src2);
}
static void tensorCmin(rpc::RPCMessage& raw_message) {
at::Tensor tensor = unpackRetrieveTensor(raw_message);
at::Tensor src1 = unpackRetrieveTensor(raw_message);
at::Tensor src2 = unpackRetrieveTensor(raw_message);
finalize(raw_message);
at::min_out(tensor, src1, src2);
}
/* static void tensorCmaxValue(rpc::RPCMessage& raw_message) { */
/* at::Tensor tensor = unpackRetrieveTensor(raw_message); */
/* at::Tensor src = unpackRetrieveTensor(raw_message); */
/* if (at::isIntegralType(tensor.type().scalarType())) { */
/* int64_t value = unpackInteger(raw_message); */
/* finalize(raw_message); */
/* at::clamp_out(tensor, src, at::Scalar((int64_t)value)); */
/* } else if (at::isFloatingType(tensor.type().scalarType())) { */
/* double value = unpackFloat(raw_message); */
/* finalize(raw_message); */
/* at::clamp_out(tensor, src, value); */
/* } else { */
/* throw std::invalid_argument("expected scalar type"); */
/* } */
/* } */
/* static void tensorCminValue(rpc::RPCMessage& raw_message) { */
/* at::Tensor tensor = unpackRetrieveTensor(raw_message); */
/* at::Tensor src = unpackRetrieveTensor(raw_message); */
/* if (at::isIntegralType(tensor.type().scalarType())) { */
/* int64_t value = unpackInteger(raw_message); */
/* finalize(raw_message); */
/* dynamic_cast<thpp::IntTensor*>(tensor)->cminValue(*src, value); */
/* } else if (at::isFloatingType(tensor.type().scalarType())) { */
/* double value = unpackFloat(raw_message); */
/* finalize(raw_message); */
/* dynamic_cast<thpp::FloatTensor*>(tensor)->cminValue(*src, value); */
/* } else { */
/* throw std::invalid_argument("expected scalar type"); */
/* } */
/* } */
| 37.303061 | 142 | 0.729901 | DavidKo3 |
82fcf6e966ab122b42f408ded600ff7ac4ebc6b5 | 6,802 | cpp | C++ | ssp/ar.cpp | idiap/libssp | 6e7d438a4cf7275ec159a93b27d77d73f61f229e | [
"BSD-3-Clause"
] | 14 | 2015-10-22T15:53:30.000Z | 2021-07-13T00:28:00.000Z | ssp/ar.cpp | idiap/libssp | 6e7d438a4cf7275ec159a93b27d77d73f61f229e | [
"BSD-3-Clause"
] | null | null | null | ssp/ar.cpp | idiap/libssp | 6e7d438a4cf7275ec159a93b27d77d73f61f229e | [
"BSD-3-Clause"
] | 3 | 2016-01-04T03:12:00.000Z | 2019-12-26T07:28:13.000Z | /*
* Copyright 2014 by Idiap Research Institute, http://www.idiap.ch
*
* See the file COPYING for the licence associated with this software.
*
* Author(s):
* Phil Garner, July 2014
*/
#include <cassert>
#include "ar.h"
using namespace ssp;
/**
* Rule-of-thumb order for AR analysis
*/
int ssp::arorder(var iRate)
{
int o = int(iRate.cast<float>() / 1000) + 2;
return o;
}
Levinson::Levinson(int iOrder, var iPrior)
: ssp::UnaryFunctor(iOrder+1)
{
mPrior = iPrior;
}
template <class T>
void levinson(int iSize, T iPrior, T* iAC, T* oT)
{
// Size is order+1
T c[iSize];
T p[iSize];
T* curr = c;
T* prev = p;
curr[0] = (T)1.0;
T error = iAC[0] + iPrior;
for (int i=1; i<iSize; i++)
{
// swap current and previous coefficients
T* tmp = curr;
curr = prev;
prev = tmp;
// Recurse
T k = iAC[i];
for (int j=1; j<i; j++)
k += prev[j] * iAC[i-j];
curr[i] = - k / error;
error *= (T)1.0 - curr[i]*curr[i];
for (int j=1; j<i; j++)
curr[j] = prev[j] + curr[i] * prev[i-j];
}
// Copy. Could get rid of this by checking that order is even and swapping
// curr/prev otherwise.
for (int i=0; i<iSize; i++)
oT[i] = curr[i];
}
void Levinson::vector(
var iVar, ind iOffsetI, var& oVar, ind iOffsetO
) const
{
switch (iVar.atype())
{
case lube::TYPE_FLOAT:
levinson<float>(mSize, mPrior.cast<float>(),
iVar.ptr<float>(iOffsetI),
oVar.ptr<float>(iOffsetO)
);
break;
case lube::TYPE_DOUBLE:
levinson<double>(mSize, mPrior.cast<double>(),
iVar.ptr<double>(iOffsetI),
oVar.ptr<double>(iOffsetO)
);
break;
default:
throw std::runtime_error("Levinson::vector: unknown type");
}
}
Gain::Gain(int iOrder)
: ssp::BinaryFunctor(1)
{
mOrder = iOrder;
}
template <class T>
T gain(int iSize, T* iAC, T* iAR)
{
// This is actually a dot product, i.e., could be optimised
T g = 0.0;
for (int i=0; i<iSize; i++)
g += iAC[i] * iAR[i];
return g;
}
void Gain::vector(
var iVar1, ind iOffset1,
var iVar2, ind iOffset2,
var& oVar, ind iOffsetO
) const
{
switch (iVar1.atype())
{
case lube::TYPE_FLOAT:
*oVar.ptr<float>(iOffsetO) = gain<float>(
mOrder+1, iVar1.ptr<float>(iOffset1), iVar2.ptr<float>(iOffset2)
);
break;
case lube::TYPE_DOUBLE:
*oVar.ptr<double>(iOffsetO) = gain<double>(
mOrder+1, iVar1.ptr<double>(iOffset1), iVar2.ptr<double>(iOffset2)
);
break;
default:
throw std::runtime_error("Gain::vector: unknown type");
}
}
Spectrum::Spectrum(int iOrder, int iSize)
: ssp::BinaryFunctor(iSize)
{
// Set state variables
mOrder = iOrder;
// Pre-compute the "twiddle" factors; saves a lot of CPU
static const float pi = atan(1.0) * 4;
mTwiddle = lube::view({mSize, mOrder+1}, lube::cfloat(0.0f,0.0f));
for (int i=0; i<mSize; i++)
for (int j=0; j<mOrder+1; j++)
mTwiddle(i,j) =
lube::exp(lube::cfloat(0.0,-1.0) * pi *
(float)i * (float)j / (float)mSize);
}
void Spectrum::vector(
var iAR, ind iOffsetAR,
var iGain, ind iOffsetGain,
var& oVar, ind iOffsetO
) const
{
if (!iAR.atype<float>())
throw std::runtime_error("Spectrum::vector: floats only!");
float* a = iAR.ptr<float>(iOffsetAR);
float* g = iGain.ptr<float>(iOffsetGain);
float* o = oVar.ptr<float>(iOffsetO);
for (int i=0; i<mSize; i++)
{
lube::cfloat sm = lube::cfloat(0.0f,0.0f);
for (int j=0; j<mOrder+1; j++)
sm += mTwiddle(i,j).get<lube::cfloat>() * a[j];
float tmp = std::abs(sm);
o[i] = *g / (tmp*tmp);
}
}
void Excitation::vector(var iVar, var& oVar) const
{
// iVar[0]: signal
// iVar[1]: ar coeffs
// iVar[2]: gain
Filter f(iVar[1]);
f(iVar[0] / lube::sqrt(iVar[2]), oVar);
}
void Resynthesis::vector(var iVar, var& oVar) const
{
// iVar[0]: excitation
// iVar[1]: ar coeffs
// iVar[2]: gain
Filter f(lube::nil, iVar[1]);
f(iVar[0] * lube::sqrt(iVar[2]), oVar);
}
/**
* Convert AR polynomial to LSPs
*
* The result includes the values 0 (first) and pi (last). Of course they are
* redundant, but this is in the spirit of the first 1 in the polynomial also
* being redundant.
*/
void ToLSP::vector(var iVar, var& oVar) const
{
int order = mSize-2;
var p(mSize, 1.0f);
var q(mSize, 1.0f);
q[mSize-1] = -1.0f;
for (int i=0; i<order; i++)
{
p[i+1] = iVar(i+1) + iVar(order-i);
q[i+1] = iVar(i+1) - iVar(order-i);
}
// The roots will not be ordered, but conjugate pairs will be together
var pr = lube::roots(p);
var qr = lube::roots(q);
// From wikipedia:
// An antipalindromic polynomial (i.e., Q) has 1 as a root.
// An antipalindromic polynomial of even degree has -1 and 1 as roots
// A palindromic polynomial (i.e., P) of odd degree has -1 as a root.
int j = 0;
for (int i=0; i<mSize-1; i++)
{
if (lube::imag(qr[i]) >= 0.0f)
oVar(j++) = qr[i].arg();
if (lube::imag(pr[i]) >= 0.0f)
oVar(j++) = pr[i].arg();
}
assert(j == mSize);
// We can't rely on roots() being ordered, but it's helpful to have 0 and
// pi at the ends.
lube::sort(oVar, oVar);
}
/**
* Convert LSPs back to AR polynomials
*
* As for ToLSP, assume that the LSPs are redundant in that they contain 0 and
* pi.
*/
void FromLSP::vector(var iVar, var& oVar) const
{
assert(iVar.atype() == lube::TYPE_FLOAT);
int order = mSize-1;
var s = lube::sin(iVar);
var c = lube::cos(iVar);
var pr(order+2, lube::cfloat(0.0f,0.0f));
var qr(order+2, lube::cfloat(0.0f,0.0f));
int qi = 0;
int pi = 0;
bool bq = false;
// Start with (the redundant) iVar(0) = 0
qr[qi++] = 1.0f;
// The conjugate pairs alternate
for (int i=1; i<=order; i++)
{
float cf = c[i].get<float>();
float sf = s[i].get<float>();
if (bq)
{
qr[qi++] = lube::cfloat(cf, sf);
qr[qi++] = lube::cfloat(cf, -sf);
}
else
{
pr[pi++] = lube::cfloat(cf, sf);
pr[pi++] = lube::cfloat(cf, -sf);
}
bq = !bq;
}
// The location of the remaining root depends on the order
if (bq)
qr[qi] = -1.0f;
else
pr[pi] = -1.0f;
var p = lube::poly(pr);
var q = lube::poly(qr);
q += p;
lube::real(q, oVar);
oVar *= 0.5f;
}
| 24.467626 | 79 | 0.537195 | idiap |
d20018025c8f7e3d92446b87f7c8377bd83a3f9a | 8,430 | cpp | C++ | glutapp3dObjLoader/gsim/gs_input.cpp | AmarSaini/Graphics-Project | cad6933d83a67eab87a8222118616f0e0535f977 | [
"Apache-2.0"
] | null | null | null | glutapp3dObjLoader/gsim/gs_input.cpp | AmarSaini/Graphics-Project | cad6933d83a67eab87a8222118616f0e0535f977 | [
"Apache-2.0"
] | null | null | null | glutapp3dObjLoader/gsim/gs_input.cpp | AmarSaini/Graphics-Project | cad6933d83a67eab87a8222118616f0e0535f977 | [
"Apache-2.0"
] | null | null | null | /*=======================================================================
Copyright 2013 Marcelo Kallmann. All Rights Reserved.
This software is distributed for noncommercial use only, without
any warranties, and provided that all copies contain the full copyright
notice licence.txt located at the base folder of the distribution.
=======================================================================*/
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
# include <gsim/gs_input.h>
# include <gsim/gs_string.h>
//# define GS_USE_TRACE1 //Parser
//# define GS_USE_TRACE2 //Init/Open
# include <gsim/gs_trace.h>
# define ISINVALID _type==(gsbyte)TypeInvalid
# define ISFILE _type==(gsbyte)TypeFile
# define ISSTRING _type==(gsbyte)TypeString
# define CHKDATA if ( !_data ) _data = new Data
# define INITDATA if ( _data ) _data->init()
//=============================== GsInput =================================
struct GsInput::Data
{ GsArray<char> ungetstack; // unget buffer of chars
GsString ltoken; // buffer with the last token read
gsbyte ltype; // last token type read
void init () { ungetstack.size(0); ltoken.set(""); ltype=(gsbyte)End; }
};
void GsInput::_init ( char c )
{
_data = 0;
_cur.f = 0;
_curline = 1;
_comchar = c;
_type = (gsbyte) TypeInvalid;
_lowercase = 1; // true
_lnumreal = 0; // false
_maxtoksize = 128;
_filename = 0;
}
GsInput::GsInput ( char com )
{
GS_TRACE2 ("Default Constructor");
_init ( com );
}
GsInput::GsInput ( FILE *file, char com )
{
GS_TRACE2 ("File Constructor");
_init ( com );
if ( file )
{ _cur.f = file;
_type = (gsbyte) TypeFile;
}
}
GsInput::~GsInput ()
{
close (); // close frees _filename
delete _data;
}
void GsInput::init ( const char *buff )
{
GS_TRACE2 ("Init string");
close ();
if ( buff )
{ _cur.s = buff;
_type = (gsbyte) TypeString;
}
}
void GsInput::init ( FILE *file )
{
GS_TRACE2 ("Open file");
close ();
if ( file )
{ _cur.f = file;
_type = (gsbyte) TypeFile;
}
}
bool GsInput::open ( const char* filename )
{
GS_TRACE2 ("Open filename: "<<filename);
FILE* file = fopen ( filename, "r" );
init ( file );
if ( file ) gs_string_set ( _filename, filename );
return file? true:false;
}
void GsInput::close ()
{
INITDATA;
if ( ISFILE ) fclose ( _cur.f );
_curline = 1;
_type = (gsbyte) TypeInvalid;
gs_string_set ( _filename, 0 );
}
void GsInput::abandon ()
{
_type = (gsbyte) TypeInvalid;
close ();
}
bool GsInput::end ()
{
if ( _data ) { if (_data->ungetstack.size()>0) return false; }
if ( ISFILE ) return feof(_cur.f)? true:false;
if ( ISSTRING ) return *(_cur.s)? false:true;
return true;
}
int GsInput::readchar () // comments not handled, unget yes
{
int c = -1;
CHKDATA;
if ( _data->ungetstack.size()>0 )
{ c = _data->ungetstack.pop();
}
else
{ if ( ISFILE ) { c=fgetc(_cur.f); }
else if ( ISSTRING ) c = *_cur.s? *_cur.s++ : -1;
}
if ( c=='\n' ) _curline++;
if ( _lowercase && c>='A' && c<='Z' ) c = c-'A'+'a';
return c;
}
int GsInput::readline ( GsString& buf )
{
int c;
char st[2]; st[1]=0;
buf.len(0);
do { c = readchar();
if ( c==EOF ) break;
st[0] = (char)c;
buf.append(st);
} while ( c!='\n' );
return c;
}
void GsInput::readall ( GsString& buf )
{
if ( ISFILE )
{
long start = ftell(_cur.f);
fseek ( _cur.f, 0, SEEK_END );
int size = (int)(ftell(_cur.f) - start + 1);
fseek ( _cur.f, start, SEEK_SET );
buf.len ( size );
size = fread ( (void*)(&buf[0]), sizeof(char), (size_t)size, _cur.f );
// it seems n<size, probably due nl convertions..., anyway fix this here:
buf.len ( size );
}
else if ( ISSTRING )
{
buf.set ( _cur.s );
_cur.s += buf.len();
}
}
void GsInput::skipline ()
{
int c;
do { c = readchar();
} while ( c!=EOF && c!='\n' );
}
GsInput::TokenType GsInput::check ()
{
// skip white spaces ang get 1st char:
int c;
do { c = readchar();
if ( c==_comchar ) do { c=readchar(); } while ( c!=EOF && c!='\n' );
if ( c=='\n' ) _curline++;
if ( c==EOF ) return End;
} while ( isspace(c) );
// check if delimiter preceeding number:
if ( (c=='.'||c=='+'||c=='-') && isdigit(_peekbyte()) ) { unget(c); return Number; }
// check other cases:
unget(c);
if ( isdigit(c) ) return Number;
if ( isalpha(c) || c=='"' || c=='_' ) return String;
return Delimiter;
}
static char getescape ( char c )
{
switch ( c )
{ case 'n' : return '\n';
case 't' : return '\t';
case '\n': return 0; // Just skip line
default : return c;
}
}
GsInput::TokenType GsInput::get ()
{
TokenType type = check();
_data->ltype = type;
_data->ltoken.len(0);
if ( type==End )
{
GS_TRACE1 ( "Got End..." );
}
else if ( type==String )
{
GsString &s = _data->ltoken;
s.len ( _maxtoksize );
int i, c = readchar();
if ( c=='"' ) // inside quotes mode
{ GS_TRACE1 ( "Got String between quotes..." );
for ( i=0; i<_maxtoksize; i++ )
{ c = readchar();
if ( c=='\\' ) c=getescape(readchar());
if ( c==EOF || c=='"' ) break;
s[i]=c;
}
}
else // normal mode
{ GS_TRACE1 ( "Got String..." );
for ( i=0; i<_maxtoksize; i++ )
{ if ( c==EOF ) break;
if ( !isalnum(c) && c!='_' ) { unget(c); break; }
s[i] = c;
c = readchar();
}
}
s.len(i);
}
else if ( type==Number )
{ GS_TRACE1 ( "Got Number..." );
GsString& s = _data->ltoken;
s.len ( _maxtoksize );
bool pnt=false, exp=false;
int i, c = readchar();
s[0]=c; // we know the 1st is part of a number (can be +/-)
for ( i=1; i<_maxtoksize; i++ )
{ c = readchar();
if ( !isdigit(c) )
{ if ( c=='e' ) c='E';
if ( !pnt && c=='.' ) pnt=true;
else if ( pnt && c=='.' ) break;
else if ( !exp && c=='E' ) exp=pnt=true;
else if ( (c=='+'||c=='-') && s[i-1]=='E' ); // ok
else { unget(c); break; }
}
s[i]=c;
}
s.len(i);
_lnumreal = pnt? 1:0;
}
else // Delimiter
{ GS_TRACE1 ( "Got Delimiter..." );
_data->ltoken.len (1);
_data->ltoken[0] = readchar();
}
GS_TRACE1 ( "Token: "<<_data->ltoken );
return type;
}
char GsInput::getc ()
{
get();
return _data->ltoken[0];
}
const GsString& GsInput::gets ()
{
get();
return _data->ltoken;
}
const GsString& GsInput::getfilename ()
{
GsString fname = gets();
if ( getc()=='.' ) fname << '.' << gets(); else unget();
_data->ltoken = fname;
return _data->ltoken;
}
int GsInput::geti ()
{
return get()==Number? _data->ltoken.atoi():0;
}
int GsInput::getl()
{
return get()==Number? _data->ltoken.atol():0;
}
float GsInput::getf ()
{
return get()==Number? _data->ltoken.atof():0;
}
const GsString& GsInput::ltoken() const
{
CHKDATA;
return _data->ltoken;
}
GsInput::TokenType GsInput::ltype() const
{
CHKDATA;
return (TokenType)_data->ltype;
}
void GsInput::unget ()
{
if ( !_data ) return;
unget ( gspc );
unget ( _data->ltoken );
}
void GsInput::unget ( const char* s )
{
if ( !s ) return;
int i;
for ( i=strlen(s)-1; i>=0; i-- ) unget ( s[i] );
}
void GsInput::unget ( char c )
{
CHKDATA;
_data->ungetstack.push() = c;
if ( c=='\n' ) _curline--;
}
bool GsInput::skip ( int n )
{
while ( n-- )
{ if ( get()==End ) return false;
}
return true;
}
bool GsInput::skipto ( const char *name )
{
while ( get()!=End )
{ if ( _data->ltype==(gsbyte)String )
if ( _data->ltoken==name ) return true;
}
return false;
}
//============================= operators ==================================
GsInput& operator>> ( GsInput& in, GsString& s )
{
s = in.gets();
return in;
}
GsInput& operator>> ( GsInput& in, char* st )
{
strcpy ( st, in.gets() );
return in;
}
//============================ End of File =================================
| 21.839378 | 87 | 0.506762 | AmarSaini |
d201aacc0ade4e8863df807d734fc8b348108d97 | 18,814 | cpp | C++ | src/main.cpp | stephan2nd/cpp-accelerator-settings-evolution | 653990ed991a75db6055790aafb8b628c685763a | [
"MIT"
] | null | null | null | src/main.cpp | stephan2nd/cpp-accelerator-settings-evolution | 653990ed991a75db6055790aafb8b628c685763a | [
"MIT"
] | null | null | null | src/main.cpp | stephan2nd/cpp-accelerator-settings-evolution | 653990ed991a75db6055790aafb8b628c685763a | [
"MIT"
] | null | null | null | #include <iostream>
#include <random>
#include <fstream>
#include <vector>
#include "Genome.hpp"
#include "Population.hpp"
#include "Accelerator.hpp"
#include "DriftTube.hpp"
#include "HKick.hpp"
#include "VKick.hpp"
#include "QuadrupoleMagnet.hpp"
#include "Slit.hpp"
#include "Screen.hpp"
#include "Trafo.hpp"
#include "DipoleMagnet.hpp"
#include "RectangularDipoleMagnet.hpp"
#include "ProfileGrid.hpp"
using namespace std;
Accelerator acc;
Trafo* t0;
Trafo* t1;
Trafo* t2;
Trafo* t3;
Trafo* t4;
Trafo* t5;
Trafo* t6;
Trafo* t7;
Trafo* final_trafo;
vector<Trafo*> trafos;
double fitness_simple_acc(const vector<double>& genes)
{
double sum_off_diff = 0;
acc.setNormValues(genes);
acc.startSimulation(20000);
sum_off_diff += t1->getCounts() + 10*t2->getCounts() + 100*t3->getCounts() + 1000*t4->getCounts() + 100000*final_trafo->getCounts();
return sum_off_diff;
}
void experiment_simple_acc()
{
double width = 0.1;
double height = 0.1;
t1 = new Trafo("T1");
t2 = new Trafo("T2");
t3 = new Trafo("T3");
t4 = new Trafo("T4");
int dpm = 1000;
acc.appendDevice(new DriftTube("Drift1", width, height, 0.25));
acc.appendDevice(t1);
acc.appendDevice(new Screen("Screen1", width, height, dpm));
acc.appendDevice(new HKick("HKick1", -0.1, 0.1));
acc.appendDevice(new DriftTube("Drift2", width, height, 0.25));
acc.appendDevice(t2);
acc.appendDevice(new Screen("Screen2", width, height, dpm));
acc.appendDevice(new QuadrupoleMagnet("QD1", width, height, 0.5, 0.0, 10));
acc.appendDevice(new QuadrupoleMagnet("QD2", width, height, 0.5, -10, 0.0));
acc.appendDevice(new Screen("Screen3", width, height, dpm));
acc.appendDevice(new DriftTube("Drift3", width, height, 4.0));
acc.appendDevice(t3);
acc.appendDevice(new Screen("Screen4", width, height, dpm));
acc.appendDevice(new DipoleMagnet("BEND1", width, height, 2.0, 0.5));
acc.appendDevice(new DriftTube("Drift4", width, height, 2.0));
acc.appendDevice(t4);
acc.appendDevice(new Screen("Screen5", width, height, dpm));
acc.appendDevice(new QuadrupoleMagnet("QD3", width, height, 0.5, 0.0, 10));
acc.appendDevice(new QuadrupoleMagnet("QD4", width, height, 0.5, -10, 0.0));
acc.appendDevice(new DriftTube("Drift5", width, height, 4.0));
acc.appendDevice(new Screen("Screen6", width, height, dpm));
acc.appendDevice(new HKick("HKick2", -0.1, 0.1));
acc.appendDevice(new DriftTube("Drift6", width, height, 2.0));
acc.appendDevice(new HKick("HKick3", -0.1, 0.1));
acc.appendDevice(new DriftTube("Drift7", width, height, 2.0));
acc.appendDevice(new Slit("Slit", -0.05, -0.04, -0.01, 0.01));
acc.appendDevice(new Screen("Screen7", width, height, dpm));
final_trafo = new Trafo("FinalTrafo");
acc.appendDevice(final_trafo);
acc.setScreenIgnore(true);
default_random_engine rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
int number_of_genes = acc.settingSize();
int number_of_genomes = 10;
int number_of_generations = 2000;
EvolutionParameters ep;
ep.n_keep = 2;
ep.sigma_survive = 0.3; // 0.3 scheint ein guter Wert zu sein // 0.1 wirft 60% weg, 0.2 wirft 40% weg
ep.p_mutate_disturbe = 0.7;
ep.p_mutate_replace = 0.05;
ep.p_non_homologous_crossover = 0.10;
ep.b_crossing_over = true;
ep.b_mutate_mutation_rate = true;
ep.n_min_genes_till_cross = 1;
ep.n_max_genes_till_cross = number_of_genes/2;
Population p(number_of_genomes, number_of_genes, rnd);
p.evaluate(fitness_simple_acc);
for( int i=0; i<number_of_generations; i++ ) {
p = p.createOffspring(ep, rnd);
p.evaluate(fitness_simple_acc);
cout << "Generation " << i << ":\t" << p.toString() << endl;
}
cout << p.getBestGenome() << endl;
acc.setScreenIgnore(false);
acc.setNormValues(p.getBestGenome().getGenes());
acc.startSimulation(1000000);
cout << acc.toString() << endl;
((Screen*) acc.getDeviceByName("Screen1"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen2"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen3"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen4"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen5"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen6"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen7"))->exportHistogram();
}
double fitness_m3_beamline(const vector<double>& genes)
{
double f=0;
acc.setNormValues(genes);
acc.startSimulation(80000);
f = t0->getCounts();
f = f * (1 + t1->getCounts() - t1->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UMADG1g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UMADG1g"))->centerY())));
f = f * (1 + t2->getCounts() - t2->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UMADG2g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UMADG2g"))->centerY())));
f = f * (1 + t3->getCounts() - t3->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UMADG3g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UMADG3g"))->centerY())));
f = f * (1 + t4->getCounts() - t4->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UMADG4g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UMADG4g"))->centerY())));
f = f * (1 + t5->getCounts());
f = f * (1 + t6->getCounts() - t6->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UM3DG6g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UM3DG6g"))->centerY())));
f = f * (1 + t7->getCounts() - t7->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENag"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENag"))->centerY())));
f = f * (1 + t7->getCounts() - t7->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENbg"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENbg"))->centerY())));
/* f += t0->getCounts() * (1 + t1->getCounts()) * (1 + t2->getCounts()) * (1 + t3->getCounts()) * (1 + t4->getCounts()) * (1 + t5->getCounts()) * (1 + t6->getCounts()) * (1 + t7->getCounts());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG1g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG1g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG2g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG2g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG3g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG3g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG4g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG4g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UM3DG6g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UM3DG6g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENag"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENag"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENbg"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENbg"))->centerY());*/
return f;
}
double fitness_mix_beamline(const vector<double>& genes)
{
double f=1;
double fmax = 1;
acc.setNormValues(genes);
acc.startSimulation(50000);
for( auto it=trafos.begin(); it<trafos.end(); it++ ){
//f = f * ( 1 + (*it)->getCounts() );
f = f + (*it)->getCounts();
//fmax = fmax * (1 + 10000);
fmax = fmax + 50000;
}
return (f/fmax) - 0.01 * acc.excitation();
}
void experiment_m3_beamline()
{
t0 = new Trafo("T0");
t1 = new Trafo("T1");
t2 = new Trafo("T2");
t3 = new Trafo("T3");
t4 = new Trafo("T4");
t5 = new Trafo("T5");
t6 = new Trafo("T6");
t7 = new Trafo("T7");
IonSource ion_source(12, 6, 2, 1000, 0., 0.00012, 0., 0.00245, 0., 0.00063, 0., 0.00316, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00006, 0., 0.00150, 0., 0.00030, 0., 0.00212, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00003, 0., 0.00050, 0., 0.00015, 0., 0.00050, 0., 0., 0., 0.);
acc.setIonSource(ion_source);
double max_quad_strength = 7;
double drift_width = 0.040;
double grid_width = 0.040;
double dpm = 5000;
acc.appendDevice(new DriftTube("", drift_width, drift_width, 1.1 + 0.1));
acc.appendDevice(t0);
acc.appendDevice(new RectangularDipoleMagnet("UT1MK0", 0.080, 0.040, -10.*M_PI*-4.894/180., -10.*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.1 + 2.3385 + 0.124));
// acc.appendDevice(new Screen("PROBE", grid_width, grid_width, dpm));
acc.appendDevice(new HKick("UMAMS1H", -0.1, 0.1));
acc.appendDevice(new VKick("UMAMS1V", -0.1, 0.1));
// acc.appendDevice(new Screen("PROBE2", grid_width, grid_width, dpm));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.124 + 0.0935 + 0.0335));
// acc.appendDevice(new Screen("PROBE3", grid_width, grid_width, dpm));
acc.appendDevice(new QuadrupoleMagnet("UMAQD11", 0.040, 0.040, 0.318, 0.0, max_quad_strength));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD12", 0.040, 0.040, 0.318, -max_quad_strength, 0.0));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.100));
// acc.appendDevice(new DriftTube("DUMMY", drift_width, drift_width, 4));
acc.appendDevice(new Screen("UMADG1", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UMADG1g", grid_width, grid_width, 100));
acc.appendDevice(t1);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.460));
acc.appendDevice(new RectangularDipoleMagnet("UMAMU1", 0.080, 0.040, -12.5*M_PI*-7.699/180., -12.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.465));
acc.appendDevice(new Screen("UMADG2", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UMADG2g", grid_width, grid_width, 100));
acc.appendDevice(t2);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.465));
acc.appendDevice(new RectangularDipoleMagnet("UMAMU2a", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.3335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD21", 0.040, 0.040, 0.318, 0.0, max_quad_strength));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD22", 0.040, 0.040, 0.318, -max_quad_strength, 0.0));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.3335));
acc.appendDevice(new RectangularDipoleMagnet("UMAMU2b", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.300));
acc.appendDevice(new Screen("UMADG3", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UMADG3g", grid_width, grid_width, 100));
acc.appendDevice(t3);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.300));
acc.appendDevice(new RectangularDipoleMagnet("UMAMU2c", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.3335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD31", 0.040, 0.040, 0.318, 0.0, max_quad_strength));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD32", 0.040, 0.040, 0.318, -max_quad_strength, 0.0));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.491));
acc.appendDevice(new Screen("UMADG4", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UMADG4g", grid_width, grid_width, 100));
acc.appendDevice(t4);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.275));
acc.appendDevice(new HKick("UMAMS2H", -0.1, 0.1));
acc.appendDevice(new VKick("UMAMS2V", -0.1, 0.1));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.124 + 0.3435 + 0.100));
acc.appendDevice(new RectangularDipoleMagnet("UM2MU5", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.700));
acc.appendDevice(new RectangularDipoleMagnet("UM3MU6", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0195 + 0.124));
acc.appendDevice(t5);
acc.appendDevice(new HKick("UM1MS3H", -0.1, 0.1));
acc.appendDevice(new VKick("UM1MS3V", -0.1, 0.1));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.124 + 0.3325 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UM3QD41", 0.040, 0.040, 0.318, 0.0, max_quad_strength));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UM3QD42", 0.040, 0.040, 0.318, -max_quad_strength, 0.0));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.249));
acc.appendDevice(new Screen("UM3DG6", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UM3DG6g", grid_width, grid_width, 100));
acc.appendDevice(t6);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 2.5845 + 2.400));
acc.appendDevice(new Screen("TARGET_SCREENa", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("TARGET_SCREENag", grid_width, grid_width, 100));
acc.appendDevice(new Slit("TARGET_SIZE", -0.002, 0.002, -0.002, 0.002));
acc.appendDevice(new Screen("TARGET_SCREENb", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("TARGET_SCREENbg", grid_width, grid_width, 100));
acc.appendDevice(t7);
acc.setScreenIgnore(true);
// cout << acc.toString() << endl;
default_random_engine rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
int number_of_genes = acc.settingSize();
int number_of_genomes = 30;
int number_of_generations = 300;
EvolutionParameters ep;
ep.n_keep = 2;
ep.sigma_survive = 0.3; // 0.3 scheint ein guter Wert zu sein // 0.1 wirft 60% weg, 0.2 wirft 40% weg
ep.p_mutate_disturbe = 0.80; // 0.60
ep.p_mutate_replace = 0.05; // 0.05
ep.p_non_homologous_crossover = 0.025; // 0.05
ep.b_crossing_over = true;
ep.b_mutate_mutation_rate = true;
ep.n_min_genes_till_cross = 2;
ep.n_max_genes_till_cross = number_of_genes/2;
Population p(number_of_genomes, number_of_genes, rnd);
p.evaluate(fitness_m3_beamline);
ofstream outfile;
outfile.open("fitness.dat", ios::out | ios::trunc );
outfile << "func\n";
for( int i=0; i<number_of_generations; i++ ) {
p = p.createOffspring(ep, rnd);
p.evaluate(fitness_m3_beamline);
outfile << i << "," << p.getBestGenome().fitness() << "\n";
cout << "Generation " << i << ":\t" << p.toString() << endl;
//cout << "Generation " << i << ":\t" << p.toLine() << endl;
}
outfile.close();
cout << p.getBestGenome() << endl;
acc.setScreenIgnore(false);
acc.setNormValues(p.getBestGenome().getGenes());
acc.startSimulation(10000000);
cout << acc.toString() << endl;
acc.writeMirkoMakro("mirko.mak");
((Screen*) acc.getDeviceByName("UMADG1"))->exportHistogram();
((Screen*) acc.getDeviceByName("UMADG2"))->exportHistogram();
((Screen*) acc.getDeviceByName("UMADG3"))->exportHistogram();
((Screen*) acc.getDeviceByName("UMADG4"))->exportHistogram();
((Screen*) acc.getDeviceByName("UM3DG6"))->exportHistogram();
((Screen*) acc.getDeviceByName("TARGET_SCREENa"))->exportHistogram();
((Screen*) acc.getDeviceByName("TARGET_SCREENb"))->exportHistogram();
// ((Screen*) acc.getDeviceByName("PROBE"))->exportHistogram();
// ((Screen*) acc.getDeviceByName("PROBE2"))->exportHistogram();
// ((Screen*) acc.getDeviceByName("PROBE3"))->exportHistogram();
}
void experiment_mix_beamline()
{
IonSource ion_source(12, 6, 2, 1000, 0., 0.0000, 0., 0.0002, 0., 0.0000, 0., 0.0002, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00012, 0., 0.00245, 0., 0.00063, 0., 0.00316, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00006, 0., 0.00150, 0., 0.00030, 0., 0.00212, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00003, 0., 0.00050, 0., 0.00015, 0., 0.00050, 0., 0., 0., 0.);
acc.setIonSource(ion_source);
bool add_trafo_to_each_screen = true;
acc.appendDevicesFromMirkoFile("apertures01.mix", add_trafo_to_each_screen);
acc.appendDevice(new Slit("TARGET_SIZE", -0.002, 0.002, -0.002, 0.002));
acc.appendDevice(new Screen("TARGET", 0.1, 0.1, 1000));
acc.appendDevice(new Trafo("TARGET"));
acc.getTrafos(trafos);
acc.setScreenIgnore(true);
default_random_engine rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
int number_of_genes = acc.settingSize()*2;
int number_of_genomes = 100;
int number_of_generations = 100;
EvolutionParameters ep;
ep.n_keep = 2;
ep.sigma_survive = 0.3; // 0.3 scheint ein guter Wert zu sein // 0.1 wirft 60% weg, 0.2 wirft 40% weg
ep.p_mutate_disturbe = 0.80; // 0.60
ep.p_mutate_replace = 0.05; // 0.05
ep.p_non_homologous_crossover = 0.08; // 0.05
ep.b_crossing_over = true;
ep.b_mutate_mutation_rate = true;
ep.n_min_genes_till_cross = 1; // 2
ep.n_max_genes_till_cross = number_of_genes/2;
Population p(number_of_genomes, number_of_genes, rnd);
p.evaluate(fitness_mix_beamline);
ofstream outfile;
outfile.open("fitness.dat", ios::out | ios::trunc );
outfile << "func\n";
for( int i=0; i<number_of_generations and p.getBestGenome().fitness()<0.99; i++ ) {
p = p.createOffspring(ep, rnd);
p.evaluate(fitness_mix_beamline);
outfile << i << "," << p.getBestGenome().fitness() << "\n";
//cout << "Generation " << i << ":\t" << p.toString() << endl;
cout << "Generation " << i << ":\t" << p.toLine() << endl;
}
outfile.close();
cout << p.getBestGenome() << endl;
acc.setScreenIgnore(false);
acc.setNormValues(p.getBestGenome().getGenes());
acc.startSimulation(10000000);
cout << acc.toString() << endl;
acc.writeMirkoMakro("mirko.mak");
acc.exportHistograms();
}
int main(int argc , char *argv[])
{
cout << "start" << endl;
clock_t begin = clock();
time_t start, finish;
time(&start);
//experiment_simple_acc();
//experiment_m3_beamline();
experiment_mix_beamline();
time(&finish);
float diff = (((float)clock()-(float)begin)/CLOCKS_PER_SEC);
cout << "CPU-time: " << diff << " s" << endl;
cout << "runtime: " << difftime(finish,start) << " s" << endl;
return 0;
}
| 44.372642 | 197 | 0.66695 | stephan2nd |
d201e0518fbb66f8cbf1ac94aea76743d477339c | 4,943 | cpp | C++ | ufora/FORA/Judgment/RandomJOVGenerator.py.cpp | ufora/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 571 | 2015-11-05T20:07:07.000Z | 2022-01-24T22:31:09.000Z | ufora/FORA/Judgment/RandomJOVGenerator.py.cpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 218 | 2015-11-05T20:37:55.000Z | 2021-05-30T03:53:50.000Z | ufora/FORA/Judgment/RandomJOVGenerator.py.cpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 40 | 2015-11-07T21:42:19.000Z | 2021-05-23T03:48:19.000Z | /***************************************************************************
Copyright 2015 Ufora Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#include "RandomJOVGenerator.hppml"
#include <stdint.h>
#include <boost/python.hpp>
#include "../../native/Registrar.hpp"
#include "../../core/python/CPPMLWrapper.hpp"
#include "../../core/python/ScopedPyThreads.hpp"
#include "../../core/python/ValueLikeCPPMLWrapper.hppml"
#include "../Core/ExecutionContext.hppml"
class RandomJOVGeneratorWrapper :
public native::module::Exporter<RandomJOVGeneratorWrapper> {
public:
std::string getModuleName(void)
{
return "FORA";
}
static PolymorphicSharedPtr<RandomJOVGenerator>*
makeClassBySeed(
int seed,
PolymorphicSharedPtr<Fora::Interpreter::ExecutionContext>& context
)
{
return new PolymorphicSharedPtr<RandomJOVGenerator>(
new RandomJOVGenerator(seed, context)
);
}
static PolymorphicSharedPtr<RandomJOVGenerator>*
makeClassByGenerator(
boost::mt19937& generator,
PolymorphicSharedPtr<Fora::Interpreter::ExecutionContext>& context
)
{
return new PolymorphicSharedPtr<RandomJOVGenerator>(
new RandomJOVGenerator(generator, context)
);
}
static boost::python::object RJOVGRandomValue(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
const JOV& jov
)
{
Nullable<ImplValContainer> r = rjovg->RandomValue(jov);
if (!r) return boost::python::object();
return boost::python::object(*r);
}
static boost::python::object RJOVTGRandomValue(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
const JOVT& jovt
)
{
return RJOVGRandomValue(rjovg, JOV::Tuple(jovt));
}
static PolymorphicSharedPtr<RandomJOVGenerator>
RJOVGSymbolStrings(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
boost::python::list symbolStringsList
)
{
std::vector<std::string> symbol_strings;
int length = boost::python::len(symbolStringsList);
for (long k = 0; k < length; k++)
{
if (boost::python::extract<std::string>(symbolStringsList[k]).check())
symbol_strings.push_back(boost::python::extract<std::string>(symbolStringsList[k])());
else
lassert(false);
}
rjovg->setSymbolStrings(symbol_strings);
return rjovg;
}
static PolymorphicSharedPtr<RandomJOVGenerator> RJOVGsetMaxUnsignedInt(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
unsigned int i
)
{
rjovg->setLikelyMaxUnsignedInt(i);
return rjovg;
}
static PolymorphicSharedPtr<RandomJOVGenerator> RJOVGsetMaxReal(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
double d
)
{
rjovg->setMaxReal(d);
return rjovg;
}
static PolymorphicSharedPtr<RandomJOVGenerator> setMaxStringLength(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
int i
)
{
rjovg->setMaxStringLength(i);
return rjovg;
}
static PolymorphicSharedPtr<RandomJOVGenerator> RJOVGsetMinReal(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
double d
)
{
rjovg->setMinReal(d);
return rjovg;
}
void exportPythonWrapper()
{
using namespace boost::python;
class_<PolymorphicSharedPtr<RandomJOVGenerator> >("RandomJOVGenerator", no_init)
.def("__init__", make_constructor(makeClassBySeed))
.def("__init__", make_constructor(makeClassByGenerator))
.def("symbolStrings", &RJOVGSymbolStrings)
.def("randomValue", &RJOVGRandomValue)
.def("randomValue", &RJOVTGRandomValue)
.def("setMaxUnsignedInt", &RJOVGsetMaxUnsignedInt)
.def("setMaxReal", &RJOVGsetMaxReal)
.def("setMinReal", &RJOVGsetMinReal)
.def("setMaxStringLength", &setMaxStringLength)
;
}
};
//explicitly instantiating the registration element causes the linker to need
//this file
template<>
char native::module::Exporter<RandomJOVGeneratorWrapper>::mEnforceRegistration =
native::module::ExportRegistrar<
RandomJOVGeneratorWrapper>::registerWrapper();
| 31.484076 | 91 | 0.644346 | ufora |
d20272ed7b7e9d0d54b18926db4a1c5080b20d29 | 4,938 | cpp | C++ | ivld/src/v20210903/model/AudioInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ivld/src/v20210903/model/AudioInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ivld/src/v20210903/model/AudioInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/ivld/v20210903/model/AudioInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ivld::V20210903::Model;
using namespace std;
AudioInfo::AudioInfo() :
m_contentHasBeenSet(false),
m_startTimeStampHasBeenSet(false),
m_endTimeStampHasBeenSet(false),
m_tagHasBeenSet(false)
{
}
CoreInternalOutcome AudioInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Content") && !value["Content"].IsNull())
{
if (!value["Content"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AudioInfo.Content` IsString=false incorrectly").SetRequestId(requestId));
}
m_content = string(value["Content"].GetString());
m_contentHasBeenSet = true;
}
if (value.HasMember("StartTimeStamp") && !value["StartTimeStamp"].IsNull())
{
if (!value["StartTimeStamp"].IsLosslessDouble())
{
return CoreInternalOutcome(Core::Error("response `AudioInfo.StartTimeStamp` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_startTimeStamp = value["StartTimeStamp"].GetDouble();
m_startTimeStampHasBeenSet = true;
}
if (value.HasMember("EndTimeStamp") && !value["EndTimeStamp"].IsNull())
{
if (!value["EndTimeStamp"].IsLosslessDouble())
{
return CoreInternalOutcome(Core::Error("response `AudioInfo.EndTimeStamp` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_endTimeStamp = value["EndTimeStamp"].GetDouble();
m_endTimeStampHasBeenSet = true;
}
if (value.HasMember("Tag") && !value["Tag"].IsNull())
{
if (!value["Tag"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AudioInfo.Tag` IsString=false incorrectly").SetRequestId(requestId));
}
m_tag = string(value["Tag"].GetString());
m_tagHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void AudioInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_contentHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Content";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_content.c_str(), allocator).Move(), allocator);
}
if (m_startTimeStampHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "StartTimeStamp";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_startTimeStamp, allocator);
}
if (m_endTimeStampHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EndTimeStamp";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_endTimeStamp, allocator);
}
if (m_tagHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Tag";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_tag.c_str(), allocator).Move(), allocator);
}
}
string AudioInfo::GetContent() const
{
return m_content;
}
void AudioInfo::SetContent(const string& _content)
{
m_content = _content;
m_contentHasBeenSet = true;
}
bool AudioInfo::ContentHasBeenSet() const
{
return m_contentHasBeenSet;
}
double AudioInfo::GetStartTimeStamp() const
{
return m_startTimeStamp;
}
void AudioInfo::SetStartTimeStamp(const double& _startTimeStamp)
{
m_startTimeStamp = _startTimeStamp;
m_startTimeStampHasBeenSet = true;
}
bool AudioInfo::StartTimeStampHasBeenSet() const
{
return m_startTimeStampHasBeenSet;
}
double AudioInfo::GetEndTimeStamp() const
{
return m_endTimeStamp;
}
void AudioInfo::SetEndTimeStamp(const double& _endTimeStamp)
{
m_endTimeStamp = _endTimeStamp;
m_endTimeStampHasBeenSet = true;
}
bool AudioInfo::EndTimeStampHasBeenSet() const
{
return m_endTimeStampHasBeenSet;
}
string AudioInfo::GetTag() const
{
return m_tag;
}
void AudioInfo::SetTag(const string& _tag)
{
m_tag = _tag;
m_tagHasBeenSet = true;
}
bool AudioInfo::TagHasBeenSet() const
{
return m_tagHasBeenSet;
}
| 27.131868 | 150 | 0.686108 | suluner |
d2066ec92a515ab33a89cc38bd0cf834677e90e6 | 172 | cpp | C++ | src/np/subset_sum.cpp | zpooky/sputil | 3eddf94655fe4ec5bc2a3b5e487a86d772b038ae | [
"Apache-2.0"
] | null | null | null | src/np/subset_sum.cpp | zpooky/sputil | 3eddf94655fe4ec5bc2a3b5e487a86d772b038ae | [
"Apache-2.0"
] | null | null | null | src/np/subset_sum.cpp | zpooky/sputil | 3eddf94655fe4ec5bc2a3b5e487a86d772b038ae | [
"Apache-2.0"
] | null | null | null | #include "subset_sum.h"
namespace np {
namespace complete {
bool
subset_sum(const sp::Array<int> &) noexcept {
return true;
}
} // namespace complete
} // namespace np
| 14.333333 | 45 | 0.703488 | zpooky |
d2071e73011c882d7d7260a12311e751a08f036e | 859 | cpp | C++ | Source/ThirdPersonShooter/Private/Core/AI/BTService_SetMovementState.cpp | DanialKama/ThirdPersonShooter | 689873bcfcce7ef170df7fc7385d507e71a87a38 | [
"MIT"
] | 7 | 2021-12-03T17:31:34.000Z | 2022-03-16T09:24:46.000Z | Source/ThirdPersonShooter/Private/Core/AI/BTService_SetMovementState.cpp | DanialKama/ThirdPersonShooter | 689873bcfcce7ef170df7fc7385d507e71a87a38 | [
"MIT"
] | 45 | 2021-09-26T12:12:44.000Z | 2022-01-31T07:19:50.000Z | Source/ThirdPersonShooter/Private/Core/AI/BTService_SetMovementState.cpp | DanialKama/ThirdPersonShooter | 689873bcfcce7ef170df7fc7385d507e71a87a38 | [
"MIT"
] | null | null | null | // Copyright 2022 Danial Kamali. All Rights Reserved.
#include "Core/AI/BTService_SetMovementState.h"
#include "Characters/AICharacter.h"
#include "Core/AI/ShooterAIController.h"
UBTService_SetMovementState::UBTService_SetMovementState(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
NodeName = "Set Movement State";
bNotifyTick = false;
bTickIntervals = false;
bNotifyBecomeRelevant = true;
// Initialize variables
MovementState = EMovementState::Walk;
bRelatedToCrouch = false;
bRelatedToProne = false;
}
void UBTService_SetMovementState::OnBecomeRelevant(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
if (const AShooterAIController* Owner = Cast<AShooterAIController>(OwnerComp.GetOwner()))
{
Owner->ControlledPawn->SetMovementState_Implementation(MovementState, bRelatedToCrouch, bRelatedToProne);
}
} | 31.814815 | 107 | 0.80908 | DanialKama |
d20bdee934b63c6dc8b753cff9796ee3a427aa92 | 603 | hpp | C++ | src/RenderSystem.DXGI/DXGIFormatHelper.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | src/RenderSystem.DXGI/DXGIFormatHelper.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | src/RenderSystem.DXGI/DXGIFormatHelper.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#pragma once
#include "Pomdog/Graphics/detail/ForwardDeclarations.hpp"
#include <dxgi.h>
namespace Pomdog {
namespace Detail {
namespace DXGI {
struct DXGIFormatHelper final {
static DXGI_FORMAT ToDXGIFormat(DepthFormat format) noexcept;
static DXGI_FORMAT ToDXGIFormat(SurfaceFormat format) noexcept;
static DXGI_FORMAT ToDXGIFormat(IndexElementSize elementSize) noexcept;
static DXGI_FORMAT ToDXGIFormat(InputElementFormat format) noexcept;
};
} // namespace DXGI
} // namespace Detail
} // namespace Pomdog
| 27.409091 | 75 | 0.78607 | ValtoForks |
d20e1e07ea65e639ef0667b87826a916a61fcefe | 2,280 | cpp | C++ | src/1.4/dom/domGles_texcombiner_commandAlpha_type.cpp | maemo5/android-source-browsing.platform--external--collada | 538700ec332c8306a1283f8dfdb016e493905e6f | [
"MIT"
] | null | null | null | src/1.4/dom/domGles_texcombiner_commandAlpha_type.cpp | maemo5/android-source-browsing.platform--external--collada | 538700ec332c8306a1283f8dfdb016e493905e6f | [
"MIT"
] | null | null | null | src/1.4/dom/domGles_texcombiner_commandAlpha_type.cpp | maemo5/android-source-browsing.platform--external--collada | 538700ec332c8306a1283f8dfdb016e493905e6f | [
"MIT"
] | null | null | null | /*
* Copyright 2006 Sony Computer Entertainment Inc.
*
* Licensed under the MIT Open Source License, for details please see license.txt or the website
* http://www.opensource.org/licenses/mit-license.php
*
*/
#include <dae.h>
#include <dae/daeDom.h>
#include <dom/domGles_texcombiner_commandAlpha_type.h>
#include <dae/daeMetaCMPolicy.h>
#include <dae/daeMetaSequence.h>
#include <dae/daeMetaChoice.h>
#include <dae/daeMetaGroup.h>
#include <dae/daeMetaAny.h>
#include <dae/daeMetaElementAttribute.h>
daeElementRef
domGles_texcombiner_commandAlpha_type::create(DAE& dae)
{
domGles_texcombiner_commandAlpha_typeRef ref = new domGles_texcombiner_commandAlpha_type(dae);
return ref;
}
daeMetaElement *
domGles_texcombiner_commandAlpha_type::registerElement(DAE& dae)
{
daeMetaElement* meta = dae.getMeta(ID());
if ( meta != NULL ) return meta;
meta = new daeMetaElement(dae);
dae.setMeta(ID(), *meta);
meta->setName( "gles_texcombiner_commandAlpha_type" );
meta->registerClass(domGles_texcombiner_commandAlpha_type::create);
daeMetaCMPolicy *cm = NULL;
daeMetaElementAttribute *mea = NULL;
cm = new daeMetaSequence( meta, cm, 0, 1, 1 );
mea = new daeMetaElementArrayAttribute( meta, cm, 0, 1, 3 );
mea->setName( "argument" );
mea->setOffset( daeOffsetOf(domGles_texcombiner_commandAlpha_type,elemArgument_array) );
mea->setElementType( domGles_texcombiner_argumentAlpha_type::registerElement(dae) );
cm->appendChild( mea );
cm->setMaxOrdinal( 0 );
meta->setCMRoot( cm );
// Add attribute: operator
{
daeMetaAttribute *ma = new daeMetaAttribute;
ma->setName( "operator" );
ma->setType( dae.getAtomicTypes().get("Gles_texcombiner_operatorAlpha_enums"));
ma->setOffset( daeOffsetOf( domGles_texcombiner_commandAlpha_type , attrOperator ));
ma->setContainer( meta );
meta->appendAttribute(ma);
}
// Add attribute: scale
{
daeMetaAttribute *ma = new daeMetaAttribute;
ma->setName( "scale" );
ma->setType( dae.getAtomicTypes().get("xsFloat"));
ma->setOffset( daeOffsetOf( domGles_texcombiner_commandAlpha_type , attrScale ));
ma->setContainer( meta );
ma->setIsRequired( false );
meta->appendAttribute(ma);
}
meta->setElementSize(sizeof(domGles_texcombiner_commandAlpha_type));
meta->validate();
return meta;
}
| 28.5 | 96 | 0.752193 | maemo5 |
d2162c55d252d362c48415b6baa06fe572903c9d | 2,754 | cc | C++ | main.cc | sebgiles/pycolmap | 9590ab7b4dbd16348ada8ed63a7e32d30460669f | [
"BSD-3-Clause"
] | null | null | null | main.cc | sebgiles/pycolmap | 9590ab7b4dbd16348ada8ed63a7e32d30460669f | [
"BSD-3-Clause"
] | null | null | null | main.cc | sebgiles/pycolmap | 9590ab7b4dbd16348ada8ed63a7e32d30460669f | [
"BSD-3-Clause"
] | null | null | null | #include <pybind11/pybind11.h>
namespace py = pybind11;
#include "absolute_pose.cc"
#include "sequence_absolute_pose.cc"
#include "generalized_absolute_pose.cc"
#include "essential_matrix.cc"
#include "fundamental_matrix.cc"
#include "transformations.cc"
#include "sift.cc"
PYBIND11_MODULE(pycolmap, m) {
m.doc() = "COLMAP plugin built on " __TIMESTAMP__;
// Absolute pose.
m.def("absolute_pose_estimation", &absolute_pose_estimation,
py::arg("points2D"), py::arg("points3D"),
py::arg("camera_dict"),
py::arg("max_error_px") = 12.0,
"Absolute pose estimation with non-linear refinement.");
// Absolute pose from Sequence.
m.def("sequence_pose_estimation", &sequence_pose_estimation,
py::arg("points3D_0"),
py::arg("points3D_1"),
py::arg("map_points2D_0"),
py::arg("map_points2D_1"),
py::arg("rel1_points2D_0"),
py::arg("rel0_points2D_1"),
py::arg("camera_dict"),
py::arg("max_error_px") = 12.0,
py::arg("rel_max_error_px") = 12.0,
py::arg("rel_weight") = 1000.0,
"Absolute pose estimation with non-linear refinement.");
// Absolute pose from multiple images.
m.def("generalized_absolute_pose_estimation", &generalized_absolute_pose_estimation,
py::arg("points2D"), py::arg("points3D"),
py::arg("cam_idxs"),
py::arg("rel_camera_poses"),
py::arg("camera_dicts"),
py::arg("refinement_parameters"),
py::arg("max_error_px") = 12.0,
"Multi image absolute pose estimation.");
// Essential matrix.
m.def("essential_matrix_estimation", &essential_matrix_estimation,
py::arg("points2D1"), py::arg("points2D2"),
py::arg("camera_dict1"), py::arg("camera_dict2"),
py::arg("max_error_px") = 4.0,
py::arg("do_refinement") = false,
"LORANSAC + 5-point algorithm.");
// Fundamental matrix.
m.def("fundamental_matrix_estimation", &fundamental_matrix_estimation,
py::arg("points2D1"), py::arg("points2D2"),
py::arg("max_error_px") = 4.0,
"LORANSAC + 7-point algorithm.");
// Image-to-world and world-to-image.
m.def("image_to_world", &image_to_world, "Image to world transformation.");
m.def("world_to_image", &world_to_image, "World to image transformation.");
// SIFT.
m.def("extract_sift", &extract_sift,
py::arg("image"),
py::arg("num_octaves") = 4, py::arg("octave_resolution") = 3, py::arg("first_octave") = 0,
py::arg("edge_thresh") = 10.0, py::arg("peak_thresh") = 0.01, py::arg("upright") = false,
"Extract SIFT features.");
}
| 38.25 | 100 | 0.6122 | sebgiles |
d216c874fd8a85cbd55ac716fbc459fdaf3833cd | 978 | cpp | C++ | PAC-MAN_Allegro/imagem.cpp | JP-Clemente/Programming_Projects | 68ff8dccbf6bf70461cc4865840f6a187dadcb5e | [
"MIT"
] | 1 | 2020-11-29T08:06:21.000Z | 2020-11-29T08:06:21.000Z | PAC-MAN_Allegro/imagem.cpp | JP-Clemente/College_Projects | 94478657182e3dbf6ffd0fa425159d857f59a684 | [
"MIT"
] | null | null | null | PAC-MAN_Allegro/imagem.cpp | JP-Clemente/College_Projects | 94478657182e3dbf6ffd0fa425159d857f59a684 | [
"MIT"
] | null | null | null | #include <iostream>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
using namespace std;
int main(int argc, char **argv){
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_BITMAP *image = NULL;
if(!al_init()) {
cout <<"Failed to initialize allegro!" << endl;
return 0;
}
if(!al_init_image_addon()) {
cout <<"Failed to initialize al_init_image_addon!" << endl;
return 0;
}
display = al_create_display(500,550);
if(!display) {
cout <<"Failed to initialize display!" << endl;
return 0;
}
image = al_load_bitmap("map.bmp"); //Carrega imagem do arquivo map.bmp
if(!image) {
cout << "Failed to load image!" << endl;
al_destroy_display(display);
return 0;
}
al_draw_bitmap(image,0,0,0); //Desenha a imagem na posicao (0,0) - canto superior esquerdo
al_flip_display();
al_rest(10);
al_destroy_display(display);
al_destroy_bitmap(image);
return 0;
}
| 20.808511 | 96 | 0.632924 | JP-Clemente |
d217b52f2d76ab6ecb1d3195bb3d6643e39cb260 | 3,160 | hpp | C++ | include/util/geometric.hpp | Adanos020/ErupTrace | 2d359c4d53e758299e8b2d476d945fe2dd2f1c2d | [
"MIT"
] | null | null | null | include/util/geometric.hpp | Adanos020/ErupTrace | 2d359c4d53e758299e8b2d476d945fe2dd2f1c2d | [
"MIT"
] | null | null | null | include/util/geometric.hpp | Adanos020/ErupTrace | 2d359c4d53e758299e8b2d476d945fe2dd2f1c2d | [
"MIT"
] | null | null | null | #pragma once
#include <util/barycentric.hpp>
#include <util/colors.hpp>
#include <util/pairs.hpp>
#include <util/sizes.hpp>
#include <util/vector.hpp>
#include <glm/gtc/constants.hpp>
#include <glm/gtx/quaternion.hpp>
#include <algorithm>
#include <utility>
struct line
{
position_3D origin;
direction_3D direction;
position_3D point_at_distance(const float t) const
{
return origin + t * direction;
}
};
struct sphere
{
position_3D origin;
float radius;
};
inline static barycentric_2D mapping_on_sphere(const position_3D& in_normalized_p, const direction_3D& in_axial_tilt)
{
const direction_3D tilted = glm::clamp(in_normalized_p * glm::rotation(y_axis, in_axial_tilt),
direction_3D{ -1.f }, direction_3D{ 1.f });
return barycentric_2D{
1.f - ((glm::atan(tilted.z, tilted.x) + glm::pi<float>()) * glm::one_over_two_pi<float>()),
1.f - ((glm::asin(tilted.y) + glm::half_pi<float>()) * glm::one_over_pi<float>()),
};
}
struct plane
{
position_3D origin;
displacement_3D right;
displacement_3D up;
plane inverse() const
{
return plane{ this->origin, -this->right, -this->up };
}
};
struct triangle
{
position_3D a, b, c;
float area() const
{
const float ab = glm::distance(this->a, this->b);
const float ac = glm::distance(this->a, this->c);
const float theta = glm::acos(glm::dot(this->b - this->a, this->c - this->a) / (ab * ac));
return 0.5f * ab * ac * glm::sin(theta);
}
};
struct axis_aligned_box
{
position_3D min, max;
float width() const
{
return max.x - min.x;
}
float height() const
{
return max.y - min.y;
}
float depth() const
{
return max.z - min.z;
}
extent_3D<float> size() const
{
return { this->width(), this->height(), this->depth() };
}
position_3D origin() const
{
return this->min + displacement_3D{ this->width() * 0.5f, this->height() * 0.5f, this->depth() * 0.5f };
}
static axis_aligned_box zero()
{
return axis_aligned_box{ position_3D{ 0.f }, position_3D{ 0.f } };
}
static axis_aligned_box cuboid(const position_3D& in_origin, const extent_3D<float> in_half_size)
{
return axis_aligned_box{
in_origin - displacement_3D{ in_half_size.width, in_half_size.height, in_half_size.depth },
in_origin + displacement_3D{ in_half_size.width, in_half_size.height, in_half_size.depth }, };
}
static axis_aligned_box cuboid(const line& in_diagonal, const float in_length)
{
const position_3D a = in_diagonal.origin;
const position_3D b = in_diagonal.point_at_distance(in_length);
return axis_aligned_box{
position_3D{ std::min(a.x, b.x), std::min(a.y, b.y), std::min(a.z, b.z) },
position_3D{ std::max(a.x, b.x), std::max(a.y, b.y), std::max(a.z, b.z) }, };
}
static axis_aligned_box cube(const position_3D& in_origin, const float in_half_size)
{
return cuboid(in_origin, { in_half_size, in_half_size, in_half_size });
}
}; | 26.115702 | 117 | 0.625316 | Adanos020 |
d218f32735cbb059fd098fa344cae9d16cd6ddff | 2,311 | cpp | C++ | src/parser/parser.cpp | fezcode/boxer | 89139da2a93ae55d54bdf57a582d5eb7b1e157b0 | [
"Unlicense"
] | 1 | 2022-02-07T08:58:29.000Z | 2022-02-07T08:58:29.000Z | src/parser/parser.cpp | fezcode/boxer | 89139da2a93ae55d54bdf57a582d5eb7b1e157b0 | [
"Unlicense"
] | null | null | null | src/parser/parser.cpp | fezcode/boxer | 89139da2a93ae55d54bdf57a582d5eb7b1e157b0 | [
"Unlicense"
] | null | null | null | //============================
// Parser.cpp
//============================
//
#include "parser.h"
namespace boxer::parser {
/**
* Ctor
* Preconditions:
* - File exists.
*/
Parser::Parser(string_t path) : filename(path){
working_dir = boxer::string::getParentPath(path);
log_dbg("File:" + filename);
log_dbg("Working Directory:" + working_dir);
commandFactory = std::make_shared<boxer::commands::CommandFactory>();
}
// Start point of processing file.
bool_t Parser::processFile() {
if(!readFile()) {
log_war("Can NOT process file");
exit(1);
}
std::for_each(contentsOfFile.begin(), contentsOfFile.end(),
[&](const string_t& fileline) {
getCommandFromLine(fileline);
});
// start making sense of each line
return true;
}
// private functions
// -----------------
/**
* Reads file line by line and puts them into contentsOfFile string vector
*/
bool_t Parser::readFile() {
// Open the File
ifstream_t in{filename.c_str()};
// Check if object is valid
if(!in) {
log_err("Cannot open the File : " + filename);
return false;
}
string_t str;
// Read the next line from File until it reaches the end.
while (std::getline(in, str)) {
// Line contains string of length > 0 then save it in vector
if(str.size() > 0)
contentsOfFile.push_back(str);
}
//Close The File
in.close();
return true;
}
auto Parser::printContents() -> void {
for (auto const& c : contentsOfFile)
log_dbg(c);
}
auto Parser::getCommandFromLine(string_t line) -> void {
// Ignore line if it is a comment.
if (boxer::string::beginsWith(line, "#")) {
log_dbg("Ignore comment");
return;
}
stringvec_t words = boxer::string::split(line, " ");
if (words.size() <= 0) {
return;
}
log_dbg("Line: " + line);
// log_dbg("Words:");
// std::for_each(words.begin(),words.end(), [](const string_t &s){
// log_dbg(s);
// });
log_dbg("");
if (words.size() < 1) {
return;
}
auto command = commandFactory->createCommand(words, working_dir);
commands_list.push_back(command);
}
auto Parser::retrieveCommands() -> command_list_t {
return commands_list;
}
auto Parser::getWorkingDir() -> string_t {
return working_dir;
}
} // namespace boxer::parser
| 20.633929 | 75 | 0.607529 | fezcode |
d219264448484d31285b858d37eb887a667efaad | 5,731 | hpp | C++ | FDPS-5.0g/src/vector2.hpp | subarutaro/GPLUM | 89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f | [
"MIT"
] | null | null | null | FDPS-5.0g/src/vector2.hpp | subarutaro/GPLUM | 89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f | [
"MIT"
] | null | null | null | FDPS-5.0g/src/vector2.hpp | subarutaro/GPLUM | 89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f | [
"MIT"
] | null | null | null | #pragma once
#include<iostream>
#include<iomanip>
namespace ParticleSimulator{
template <typename T>
class Vector2{
public:
T x, y;
Vector2() : x(T(0)), y(T(0)) {}
Vector2(const T _x, const T _y) : x(_x), y(_y) {}
Vector2(const T s) : x(s), y(s) {}
Vector2(const Vector2 & src) : x(src.x), y(src.y) {}
static const int DIM = 2;
const Vector2 & operator = (const Vector2 & rhs){
x = rhs.x;
y = rhs.y;
return (*this);
}
const Vector2 & operator = (const T s){
x = y = s;
return (*this);
}
Vector2 operator + (const Vector2 & rhs) const{
return Vector2(x + rhs.x, y + rhs.y);
}
const Vector2 & operator += (const Vector2 & rhs){
(*this) = (*this) + rhs;
return (*this);
}
Vector2 operator - (const Vector2 & rhs) const{
return Vector2(x - rhs.x, y - rhs.y);
}
const Vector2 & operator -= (const Vector2 & rhs){
(*this) = (*this) - rhs;
return (*this);
}
// vector scholar products
Vector2 operator * (const T s) const{
return Vector2(x * s, y * s);
}
const Vector2 & operator *= (const T s){
(*this) = (*this) * s;
return (*this);
}
friend Vector2 operator * (const T s, const Vector2 & v){
return (v * s);
}
Vector2 operator / (const T s) const{
return Vector2(x / s, y / s);
}
const Vector2 & operator /= (const T s){
(*this) = (*this) / s;
return (*this);
}
const Vector2 & operator + () const {
return (* this);
}
const Vector2 operator - () const {
return Vector2(-x, -y);
}
// inner product
T operator * (const Vector2 & rhs) const{
return (x * rhs.x) + (y * rhs.y);
}
// outer product (retruned value is scholar)
T operator ^ (const Vector2 & rhs) const{
const T z = (x * rhs.y) - (y * rhs.x);
return z;
}
//cast to Vector2<U>
template <typename U>
operator Vector2<U> () const {
return Vector2<U> (static_cast<U>(x),
static_cast<U>(y));
}
T getMax() const {
return x > y ? x : y;
}
T getMin() const {
return x < y ? x : y;
}
template <class F>
Vector2 applyEach(F f) const {
return Vector2(f(x), f(y));
}
template <class F>
friend Vector2 ApplyEach(F f, const Vector2 & arg1, const Vector2 & arg2){
return Vector2( f(arg1.x, arg2.x), f(arg1.y, arg2.y) );
}
friend std::ostream & operator <<(std::ostream & c, const Vector2 & u){
c<<u.x<<" "<<u.y;
return c;
}
friend std::istream & operator >>(std::istream & c, Vector2 & u){
c>>u.x; c>>u.y;
return c;
}
#if 0
const T & operator[](const int i) const {
#ifdef PARTICLE_SIMULATOR_VECTOR_RANGE_CHECK
if(i >= DIM || i < 0){
std::cout<<"PS_ERROR: Vector invalid access. \n"<<"function: "<<__FUNCTION__<<", line: "<<__LINE__<<", file: "<<__FILE__<<std::endl;
std::cerr<<"Vector element="<<i<<" is not valid."<<std::endl;
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Abort(MPI_COMM_WORLD,-1);
#else
exit(-1);
#endif
}
#endif
return (&x)[i];
}
T & operator[](const int i){
#ifdef PARTICLE_SIMULATOR_VECTOR_RANGE_CHECK
if(i >= DIM || i < 0){
std::cout<<"PS_ERROR: Vector invalid access. \n"<<"function: "<<__FUNCTION__<<", line: "<<__LINE__<<", file: "<<__FILE__<<std::endl;
std::cerr<<"Vector element="<<i<<" is not valid."<<std::endl;
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Abort(MPI_COMM_WORLD,-1);
#else
exit(-1);
#endif
}
#endif
return (&x)[i];
}
#else
const T & operator[](const int i) const {
if(0==i) return x;
if(1==i) return y;
std::cout<<"PS_ERROR: Vector invalid access. \n"<<"function: "<<__FUNCTION__<<", line: "<<__LINE__<<", file: "<<__FILE__<<std::endl;
std::cerr<<"Vector element="<<i<<" is not valid."<<std::endl;
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Abort(MPI_COMM_WORLD,-1);
#endif
exit(-1);
return x; //dummy for avoid warning
}
T & operator[](const int i){
if(0==i) return x;
if(1==i) return y;
std::cout<<"PS_ERROR: Vector invalid access. \n"<<"function: "<<__FUNCTION__<<", line: "<<__LINE__<<", file: "<<__FILE__<<std::endl;
std::cerr<<"Vector element="<<i<<" is not valid."<<std::endl;
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Abort(MPI_COMM_WORLD,-1);
#endif
exit(-1);
return x; //dummy for avoid warning
}
#endif
T getDistanceSQ(const Vector2 & u) const {
T dx = x - u.x;
T dy = y - u.y;
return dx*dx + dy*dy;
}
bool operator == (const Vector2 & u) const {
return ( (x==u.x) && (y==u.y) );
}
bool operator != (const Vector2 & u) const {
return ( (x!=u.x) || (y!=u.y) );
}
};
template <>
inline Vector2<float> Vector2<float>::operator / (const float s) const {
const float inv_s = 1.0f/s;
return Vector2(x * inv_s, y * inv_s);
}
template <>
inline Vector2<double> Vector2<double>::operator / (const double s) const {
const double inv_s = 1.0/s;
return Vector2(x * inv_s, y * inv_s);
}
}
| 29.091371 | 137 | 0.503403 | subarutaro |
d21b4f55d714064edb9c4a1e2569597585a83ca2 | 4,552 | cpp | C++ | table/byte_addressable_RA_iterator.cpp | ruihong123/dLSM | 9158b25349389e0d46a0695ee05534409489412b | [
"BSD-3-Clause"
] | 2 | 2022-03-02T02:44:51.000Z | 2022-03-21T17:29:28.000Z | table/byte_addressable_RA_iterator.cpp | ruihong123/dLSM | 9158b25349389e0d46a0695ee05534409489412b | [
"BSD-3-Clause"
] | null | null | null | table/byte_addressable_RA_iterator.cpp | ruihong123/dLSM | 9158b25349389e0d46a0695ee05534409489412b | [
"BSD-3-Clause"
] | null | null | null | //
// Created by ruihong on 1/20/22.
//
#include "byte_addressable_RA_iterator.h"
#include "dLSM/env.h"
#include "table_memoryside.h"
namespace dLSM {
ByteAddressableRAIterator::ByteAddressableRAIterator(Iterator* index_iter,
KVFunction block_function,
void* arg,
const ReadOptions& options,
bool compute_side)
: compute_side_(compute_side),
mr_addr(nullptr),
kv_function_(block_function),
arg_(arg),
options_(options),
status_(Status::OK()),
index_iter_(index_iter),
valid_(false) {
#ifndef NDEBUG
if (compute_side){
assert(block_function == &Table::KVReader);
} else{
assert(block_function == &Table_Memory_Side::KVReader);
}
#endif
}
ByteAddressableRAIterator::~ByteAddressableRAIterator() {
if (mr_addr != nullptr){
auto rdma_mg = Env::Default()->rdma_mg;
rdma_mg->Deallocate_Local_RDMA_Slot(mr_addr, DataChunk);
}
// DEBUG_arg("TWOLevelIterator destructing, this pointer is %p\n", this);
};
//Note: if the iterator can not seek the same target, it will stop at the key right before or
// right after the data, we need to make it right before
void ByteAddressableRAIterator::Seek(const Slice& target) {
index_iter_.Seek(target);
GetKV();
assert(valid_);
// if ()
// //Todo: delete the things below.
// for (int i = 0; i < target.size(); ++i) {
// assert(key_.GetKey().data()[i] == target.data()[i]);
// }
}
void ByteAddressableRAIterator::SeekToFirst() {
index_iter_.SeekToFirst();
GetKV();
// if (data_iter_.iter() != nullptr) {
// data_iter_.SeekToFirst();
// valid_ = true;
// } else{
// assert(false);
// }
// SkipEmptyDataBlocksForward();
// assert(key().size() >0);
}
void ByteAddressableRAIterator::SeekToLast() {
index_iter_.SeekToLast();
GetKV();
// if (data_iter_.iter() != nullptr){
// data_iter_.SeekToLast();
// valid_ = true;
// }
// SkipEmptyDataBlocksBackward();
}
void ByteAddressableRAIterator::Next() {
index_iter_.Next();
GetKV();
}
void ByteAddressableRAIterator::Prev() {
assert(Valid());
index_iter_.Prev();
GetKV();
}
void ByteAddressableRAIterator::GetKV() {
if (!index_iter_.Valid()) {
// SetDataIterator(nullptr);
valid_ = false;
DEBUG_arg("TwoLevelIterator Index block invalid, error: %s\n", status().ToString().c_str());
} else {
valid_ = true;
// DEBUG("Index block valid\n");
Slice handle = index_iter_.value();
#ifndef NDEBUG
Slice test_handle = handle;
index_handle.DecodeFrom(&test_handle);
// printf("Iterator pointer is %p, Offset is %lu, this data block size is %lu\n", this, bhandle.offset(), bhandle.size());
#endif
if (handle.compare(data_block_handle_) == 0) {
// data_iter_ is already constructed with this iterator, so
// no need to change anything
} else {
if (compute_side_){
//TODO: just reuse the RDMA registered buffer every time, no need to
// allocate and deallocate again. we abandon the function pointer design,
// directly call the static function instead.
if (mr_addr != nullptr){
auto rdma_mg = Env::Default()->rdma_mg;
rdma_mg->Deallocate_Local_RDMA_Slot(mr_addr, DataChunk);
}
Slice KV = (*kv_function_)(arg_, options_, handle);
mr_addr = const_cast<char*>(KV.data());
uint32_t key_size, value_size;
GetFixed32(&KV, &key_size);
GetFixed32(&KV, &value_size);
assert(key_size + value_size == KV.size());
key_.SetKey(Slice(KV.data(), key_size), false /* copy */);
KV.remove_prefix(key_size);
assert(KV.size() == value_size);
value_ = KV;
data_block_handle_.assign(handle.data(), handle.size());
}else{
Slice KV = (*kv_function_)(arg_, options_, handle);
uint32_t key_size, value_size;
GetFixed32(&KV, &key_size);
GetFixed32(&KV, &value_size);
assert(key_size + value_size == KV.size());
// printf("!key is %p, KV.data is %p, the 7 bit is %s \n",
// key_.GetKey().data(), KV.data(), KV.data()+7);
key_.SetKey(Slice(KV.data(), key_size), false /* copy */);
KV.remove_prefix(key_size);
assert(KV.size() == value_size);
value_ = KV;
data_block_handle_.assign(handle.data(), handle.size());
}
}
}
}
} | 30.346667 | 125 | 0.609622 | ruihong123 |
d21ca9721fc9885affa723609c674c99af0be541 | 9,155 | cpp | C++ | src/spells/moppcode.cpp | eckserah/nifskope | 3a85ac55e65cc60abc3434cc4aaca2a5cc712eef | [
"RSA-MD"
] | 434 | 2015-02-06T05:08:20.000Z | 2022-03-28T16:32:15.000Z | src/spells/moppcode.cpp | SpectralPlatypus/nifskope | 7af7af39bfb0b29953024655235fde9fbc97071c | [
"RSA-MD"
] | 155 | 2015-01-10T15:28:01.000Z | 2022-03-05T03:28:09.000Z | src/spells/moppcode.cpp | SpectralPlatypus/nifskope | 7af7af39bfb0b29953024655235fde9fbc97071c | [
"RSA-MD"
] | 205 | 2015-02-07T15:10:16.000Z | 2022-03-12T16:59:05.000Z | #include "spellbook.h"
// Brief description is deliberately not autolinked to class Spell
/*! \file moppcode.cpp
* \brief Havok MOPP spells
*
* Note that this code only works on the Windows platform due an external
* dependency on the Havok SDK, with which NifMopp.dll is compiled.
*
* Most classes here inherit from the Spell class.
*/
// Need to include headers before testing this
#ifdef Q_OS_WIN32
// This code is only intended to be run with Win32 platform.
extern "C" void * __stdcall SetDllDirectoryA( const char * lpPathName );
extern "C" void * __stdcall LoadLibraryA( const char * lpModuleName );
extern "C" void * __stdcall GetProcAddress ( void * hModule, const char * lpProcName );
extern "C" void __stdcall FreeLibrary( void * lpModule );
//! Interface to the external MOPP library
class HavokMoppCode
{
private:
typedef int (__stdcall * fnGenerateMoppCode)( int nVerts, Vector3 const * verts, int nTris, Triangle const * tris );
typedef int (__stdcall * fnGenerateMoppCodeWithSubshapes)( int nShapes, int const * shapes, int nVerts, Vector3 const * verts, int nTris, Triangle const * tris );
typedef int (__stdcall * fnRetrieveMoppCode)( int nBuffer, char * buffer );
typedef int (__stdcall * fnRetrieveMoppScale)( float * value );
typedef int (__stdcall * fnRetrieveMoppOrigin)( Vector3 * value );
void * hMoppLib;
fnGenerateMoppCode GenerateMoppCode;
fnRetrieveMoppCode RetrieveMoppCode;
fnRetrieveMoppScale RetrieveMoppScale;
fnRetrieveMoppOrigin RetrieveMoppOrigin;
fnGenerateMoppCodeWithSubshapes GenerateMoppCodeWithSubshapes;
public:
HavokMoppCode() : hMoppLib( 0 ), GenerateMoppCode( 0 ), RetrieveMoppCode( 0 ), RetrieveMoppScale( 0 ),
RetrieveMoppOrigin( 0 ), GenerateMoppCodeWithSubshapes( 0 )
{
}
~HavokMoppCode()
{
if ( hMoppLib )
FreeLibrary( hMoppLib );
}
bool Initialize()
{
if ( !hMoppLib ) {
SetDllDirectoryA( QCoreApplication::applicationDirPath().toLocal8Bit().constData() );
hMoppLib = LoadLibraryA( "NifMopp.dll" );
GenerateMoppCode = (fnGenerateMoppCode)GetProcAddress( hMoppLib, "GenerateMoppCode" );
RetrieveMoppCode = (fnRetrieveMoppCode)GetProcAddress( hMoppLib, "RetrieveMoppCode" );
RetrieveMoppScale = (fnRetrieveMoppScale)GetProcAddress( hMoppLib, "RetrieveMoppScale" );
RetrieveMoppOrigin = (fnRetrieveMoppOrigin)GetProcAddress( hMoppLib, "RetrieveMoppOrigin" );
GenerateMoppCodeWithSubshapes = (fnGenerateMoppCodeWithSubshapes)GetProcAddress( hMoppLib, "GenerateMoppCodeWithSubshapes" );
}
return (GenerateMoppCode && RetrieveMoppCode && RetrieveMoppScale && RetrieveMoppOrigin);
}
QByteArray CalculateMoppCode( QVector<Vector3> const & verts, QVector<Triangle> const & tris, Vector3 * origin, float * scale )
{
QByteArray code;
if ( Initialize() ) {
int len = GenerateMoppCode( verts.size(), &verts[0], tris.size(), &tris[0] );
if ( len > 0 ) {
code.resize( len );
if ( 0 != RetrieveMoppCode( len, code.data() ) ) {
if ( scale )
RetrieveMoppScale( scale );
if ( origin )
RetrieveMoppOrigin( origin );
} else {
code.clear();
}
}
}
return code;
}
QByteArray CalculateMoppCode( QVector<int> const & subShapesVerts,
QVector<Vector3> const & verts,
QVector<Triangle> const & tris,
Vector3 * origin, float * scale )
{
QByteArray code;
if ( Initialize() ) {
int len;
if ( GenerateMoppCodeWithSubshapes )
len = GenerateMoppCodeWithSubshapes( subShapesVerts.size(), &subShapesVerts[0], verts.size(), &verts[0], tris.size(), &tris[0] );
else
len = GenerateMoppCode( verts.size(), &verts[0], tris.size(), &tris[0] );
if ( len > 0 ) {
code.resize( len );
if ( 0 != RetrieveMoppCode( len, code.data() ) ) {
if ( scale )
RetrieveMoppScale( scale );
if ( origin )
RetrieveMoppOrigin( origin );
} else {
code.clear();
}
}
}
return code;
}
}
TheHavokCode;
//! Update Havok MOPP for a given shape
class spMoppCode final : public Spell
{
public:
QString name() const override final { return Spell::tr( "Update MOPP Code" ); }
QString page() const override final { return Spell::tr( "Havok" ); }
bool isApplicable( const NifModel * nif, const QModelIndex & index ) override final
{
if ( nif->getUserVersion() != 10 && nif->getUserVersion() != 11 )
return false;
if ( TheHavokCode.Initialize() ) {
//QModelIndex iData = nif->getBlock( nif->getLink( index, "Data" ) );
if ( nif->isNiBlock( index, "bhkMoppBvTreeShape" ) ) {
return ( nif->checkVersion( 0x14000004, 0x14000005 )
|| nif->checkVersion( 0x14020007, 0x14020007 ) );
}
}
return false;
}
QModelIndex cast( NifModel * nif, const QModelIndex & iBlock ) override final
{
if ( !TheHavokCode.Initialize() ) {
Message::critical( nullptr, Spell::tr( "Unable to locate NifMopp.dll" ) );
return iBlock;
}
QPersistentModelIndex ibhkMoppBvTreeShape = iBlock;
QModelIndex ibhkPackedNiTriStripsShape = nif->getBlock( nif->getLink( ibhkMoppBvTreeShape, "Shape" ) );
if ( !nif->isNiBlock( ibhkPackedNiTriStripsShape, "bhkPackedNiTriStripsShape" ) ) {
Message::warning( nullptr, Spell::tr( "Only bhkPackedNiTriStripsShape is supported at this time." ) );
return iBlock;
}
QModelIndex ihkPackedNiTriStripsData = nif->getBlock( nif->getLink( ibhkPackedNiTriStripsShape, "Data" ) );
if ( !nif->isNiBlock( ihkPackedNiTriStripsData, "hkPackedNiTriStripsData" ) )
return iBlock;
QVector<int> subshapeVerts;
if ( nif->checkVersion( 0x14000004, 0x14000005 ) ) {
int nSubShapes = nif->get<int>( ibhkPackedNiTriStripsShape, "Num Sub Shapes" );
QModelIndex ihkSubShapes = nif->getIndex( ibhkPackedNiTriStripsShape, "Sub Shapes" );
subshapeVerts.resize( nSubShapes );
for ( int t = 0; t < nSubShapes; t++ ) {
subshapeVerts[t] = nif->get<int>( ihkSubShapes.child( t, 0 ), "Num Vertices" );
}
} else if ( nif->checkVersion( 0x14020007, 0x14020007 ) ) {
int nSubShapes = nif->get<int>( ihkPackedNiTriStripsData, "Num Sub Shapes" );
QModelIndex ihkSubShapes = nif->getIndex( ihkPackedNiTriStripsData, "Sub Shapes" );
subshapeVerts.resize( nSubShapes );
for ( int t = 0; t < nSubShapes; t++ ) {
subshapeVerts[t] = nif->get<int>( ihkSubShapes.child( t, 0 ), "Num Vertices" );
}
}
QVector<Vector3> verts = nif->getArray<Vector3>( ihkPackedNiTriStripsData, "Vertices" );
QVector<Triangle> triangles;
int nTriangles = nif->get<int>( ihkPackedNiTriStripsData, "Num Triangles" );
QModelIndex iTriangles = nif->getIndex( ihkPackedNiTriStripsData, "Triangles" );
triangles.resize( nTriangles );
for ( int t = 0; t < nTriangles; t++ ) {
triangles[t] = nif->get<Triangle>( iTriangles.child( t, 0 ), "Triangle" );
}
if ( verts.isEmpty() || triangles.isEmpty() ) {
Message::critical( nullptr, Spell::tr( "Insufficient data to calculate MOPP code" ),
Spell::tr("Vertices: %1, Triangles: %2").arg( !verts.isEmpty() ).arg( !triangles.isEmpty() )
);
return iBlock;
}
Vector3 origin;
float scale;
QByteArray moppcode = TheHavokCode.CalculateMoppCode( subshapeVerts, verts, triangles, &origin, &scale );
if ( moppcode.size() == 0 ) {
Message::critical( nullptr, Spell::tr( "Failed to generate MOPP code" ) );
} else {
QModelIndex iCodeOrigin = nif->getIndex( ibhkMoppBvTreeShape, "Origin" );
nif->set<Vector3>( iCodeOrigin, origin );
QModelIndex iCodeScale = nif->getIndex( ibhkMoppBvTreeShape, "Scale" );
nif->set<float>( iCodeScale, scale );
QModelIndex iCodeSize = nif->getIndex( ibhkMoppBvTreeShape, "MOPP Data Size" );
QModelIndex iCode = nif->getIndex( ibhkMoppBvTreeShape, "MOPP Data" ).child( 0, 0 );
if ( iCodeSize.isValid() && iCode.isValid() ) {
nif->set<int>( iCodeSize, moppcode.size() );
nif->updateArray( iCode );
nif->set<QByteArray>( iCode, moppcode );
}
}
return iBlock;
}
};
REGISTER_SPELL( spMoppCode )
//! Update MOPP code on all shapes in this model
class spAllMoppCodes final : public Spell
{
public:
QString name() const override final { return Spell::tr( "Update All MOPP Code" ); }
QString page() const override final { return Spell::tr( "Batch" ); }
bool isApplicable( const NifModel * nif, const QModelIndex & idx ) override final
{
if ( nif && nif->getUserVersion() != 10 && nif->getUserVersion() != 11 )
return false;
if ( TheHavokCode.Initialize() ) {
if ( nif && !idx.isValid() ) {
return ( nif->checkVersion( 0x14000004, 0x14000005 )
|| nif->checkVersion( 0x14020007, 0x14020007 ) );
}
}
return false;
}
QModelIndex cast( NifModel * nif, const QModelIndex & ) override final
{
QList<QPersistentModelIndex> indices;
spMoppCode TSpacer;
for ( int n = 0; n < nif->getBlockCount(); n++ ) {
QModelIndex idx = nif->getBlock( n );
if ( TSpacer.isApplicable( nif, idx ) )
indices << idx;
}
for ( const QModelIndex& idx : indices ) {
TSpacer.castIfApplicable( nif, idx );
}
return QModelIndex();
}
};
REGISTER_SPELL( spAllMoppCodes )
#endif // Q_OS_WIN32
| 31.898955 | 163 | 0.681049 | eckserah |
d21e101eeed85d188956e68a8fdf716c924f7cff | 8,259 | cc | C++ | src/game/LoadSaveTacticalStatusType.cc | flex-lab/ja2-stracciatella | 61f8f0445112c5d5ec80d7b3502ac24505f3d20c | [
"BSD-Source-Code"
] | null | null | null | src/game/LoadSaveTacticalStatusType.cc | flex-lab/ja2-stracciatella | 61f8f0445112c5d5ec80d7b3502ac24505f3d20c | [
"BSD-Source-Code"
] | null | null | null | src/game/LoadSaveTacticalStatusType.cc | flex-lab/ja2-stracciatella | 61f8f0445112c5d5ec80d7b3502ac24505f3d20c | [
"BSD-Source-Code"
] | null | null | null | #include <vector>
#include "Debug.h"
#include "FileMan.h"
#include "GameState.h"
#include "LoadSaveData.h"
#include "LoadSaveTacticalStatusType.h"
#include "Overhead.h"
void ExtractTacticalStatusTypeFromFile(HWFILE const f, bool stracLinuxFormat)
{
UINT32 dataSize = stracLinuxFormat ? TACTICAL_STATUS_TYPE_SIZE_STRAC_LINUX : TACTICAL_STATUS_TYPE_SIZE;
std::vector<BYTE> data(dataSize);
FileRead(f, data.data(), dataSize);
TacticalStatusType* const s = &gTacticalStatus;
DataReader d{data.data()};
EXTR_U32(d, s->uiFlags)
FOR_EACH(TacticalTeamType, t, s->Team)
{
EXTR_U8(d, t->bFirstID)
EXTR_U8(d, t->bLastID)
EXTR_SKIP(d, 2)
EXTR_U32(d, t->RadarColor)
EXTR_I8(d, t->bSide)
EXTR_I8(d, t->bMenInSector)
EXTR_SOLDIER(d, t->last_merc_to_radio)
EXTR_SKIP(d, 1)
EXTR_I8(d, t->bAwareOfOpposition)
EXTR_I8(d, t->bHuman)
EXTR_SKIP(d, 2)
}
EXTR_U8(d, s->ubCurrentTeam)
EXTR_SKIP(d, 1)
EXTR_I16(d, s->sSlideTarget)
EXTR_SKIP(d, 4)
EXTR_U32(d, s->uiTimeSinceMercAIStart)
EXTR_I8(d, s->fPanicFlags)
EXTR_SKIP(d, 5)
EXTR_U8(d, s->ubSpottersCalledForBy)
EXTR_SOLDIER(d, s->the_chosen_one)
EXTR_U32(d, s->uiTimeOfLastInput)
EXTR_U32(d, s->uiTimeSinceDemoOn)
EXTR_SKIP(d, 7)
EXTR_BOOLA(d, s->fCivGroupHostile, lengthof(s->fCivGroupHostile))
EXTR_U8(d, s->ubLastBattleSectorX)
EXTR_U8(d, s->ubLastBattleSectorY)
EXTR_BOOL(d, s->fLastBattleWon)
EXTR_SKIP(d, 2)
EXTR_BOOL(d, s->fVirginSector)
EXTR_BOOL(d, s->fEnemyInSector)
EXTR_BOOL(d, s->fInterruptOccurred)
EXTR_I8(d, s->bRealtimeSpeed)
EXTR_SKIP(d, 2)
EXTR_SOLDIER(d, s->enemy_sighting_on_their_turn_enemy)
EXTR_SKIP(d, 1)
EXTR_BOOL(d, s->fEnemySightingOnTheirTurn)
EXTR_BOOL(d, s->fAutoBandageMode)
EXTR_U8(d, s->ubAttackBusyCount)
EXTR_SKIP(d, 1)
EXTR_U8(d, s->ubEngagedInConvFromActionMercID)
EXTR_SKIP(d, 1)
EXTR_U16(d, s->usTactialTurnLimitCounter)
EXTR_BOOL(d, s->fInTopMessage)
EXTR_U8(d, s->ubTopMessageType)
if(stracLinuxFormat)
{
EXTR_SKIP(d, 82);
}
else
{
EXTR_SKIP(d, 40);
}
EXTR_U16(d, s->usTactialTurnLimitMax)
if(stracLinuxFormat)
{
EXTR_SKIP(d, 2);
}
EXTR_U32(d, s->uiTactialTurnLimitClock)
EXTR_BOOL(d, s->fTactialTurnLimitStartedBeep)
EXTR_I8(d, s->bBoxingState)
EXTR_I8(d, s->bConsNumTurnsNotSeen)
EXTR_U8(d, s->ubArmyGuysKilled)
EXTR_I16A(d, s->sPanicTriggerGridNo, lengthof(s->sPanicTriggerGridNo))
EXTR_I8A(d, s->bPanicTriggerIsAlarm, lengthof(s->bPanicTriggerIsAlarm))
EXTR_U8A(d, s->ubPanicTolerance, lengthof(s->ubPanicTolerance))
EXTR_BOOL(d, s->fAtLeastOneGuyOnMultiSelect)
EXTR_SKIP(d, 2)
EXTR_BOOL(d, s->fKilledEnemyOnAttack)
EXTR_SOLDIER(d, s->enemy_killed_on_attack)
EXTR_I8(d, s->bEnemyKilledOnAttackLevel)
EXTR_U16(d, s->ubEnemyKilledOnAttackLocation)
EXTR_BOOL(d, s->fItemsSeenOnAttack)
EXTR_SOLDIER(d, s->items_seen_on_attack_soldier)
EXTR_SKIP(d, 2)
EXTR_U16(d, s->usItemsSeenOnAttackGridNo)
EXTR_BOOL(d, s->fLockItemLocators)
EXTR_U8(d, s->ubLastQuoteSaid)
EXTR_U8(d, s->ubLastQuoteProfileNUm)
EXTR_BOOL(d, s->fCantGetThrough)
EXTR_I16(d, s->sCantGetThroughGridNo)
EXTR_I16(d, s->sCantGetThroughSoldierGridNo)
EXTR_SOLDIER(d, s->cant_get_through)
EXTR_BOOL(d, s->fDidGameJustStart)
EXTR_SKIP(d, 1)
EXTR_U8(d, s->ubLastRequesterTargetID)
EXTR_SKIP(d, 1)
EXTR_U8(d, s->ubNumCrowsPossible)
EXTR_SKIP(d, 4)
EXTR_BOOL(d, s->fUnLockUIAfterHiddenInterrupt)
EXTR_I8A(d, s->bNumFoughtInBattle, lengthof(s->bNumFoughtInBattle))
EXTR_SKIP(d, 1)
EXTR_U32(d, s->uiDecayBloodLastUpdate)
EXTR_U32(d, s->uiTimeSinceLastInTactical)
EXTR_BOOL(d, s->fHasAGameBeenStarted)
EXTR_I8(d, s->bConsNumTurnsWeHaventSeenButEnemyDoes)
EXTR_BOOL(d, s->fSomeoneHit)
EXTR_SKIP(d, 1)
EXTR_U32(d, s->uiTimeSinceLastOpplistDecay)
EXTR_I8(d, s->bMercArrivingQuoteBeingUsed)
EXTR_SOLDIER(d, s->enemy_killed_on_attack_killer)
EXTR_BOOL(d, s->fCountingDownForGuideDescription)
EXTR_I8(d, s->bGuideDescriptionCountDown)
EXTR_U8(d, s->ubGuideDescriptionToUse)
EXTR_I8(d, s->bGuideDescriptionSectorX)
EXTR_I8(d, s->bGuideDescriptionSectorY)
EXTR_I8(d, s->fEnemyFlags)
EXTR_BOOL(d, s->fAutoBandagePending)
EXTR_BOOL(d, s->fHasEnteredCombatModeSinceEntering)
EXTR_BOOL(d, s->fDontAddNewCrows)
EXTR_SKIP(d, 1)
EXTR_U16(d, s->sCreatureTenseQuoteDelay)
EXTR_SKIP(d, 2)
EXTR_U32(d, s->uiCreatureTenseQuoteLastUpdate)
Assert(d.getConsumed() == dataSize);
if (!GameState::getInstance()->debugging())
{
// Prevent restoring of debug UI modes
s->uiFlags &= ~(DEBUGCLIFFS | SHOW_Z_BUFFER);
}
}
void InjectTacticalStatusTypeIntoFile(HWFILE const f)
{
BYTE data[316];
DataWriter d{data};
TacticalStatusType* const s = &gTacticalStatus;
INJ_U32(d, s->uiFlags)
FOR_EACH(TacticalTeamType const, t, s->Team)
{
INJ_U8(d, t->bFirstID)
INJ_U8(d, t->bLastID)
INJ_SKIP(d, 2)
INJ_U32(d, t->RadarColor)
INJ_I8(d, t->bSide)
INJ_I8(d, t->bMenInSector)
INJ_SOLDIER(d, t->last_merc_to_radio)
INJ_SKIP(d, 1)
INJ_I8(d, t->bAwareOfOpposition)
INJ_I8(d, t->bHuman)
INJ_SKIP(d, 2)
}
INJ_U8(d, s->ubCurrentTeam)
INJ_SKIP(d, 1)
INJ_I16(d, s->sSlideTarget)
INJ_SKIP(d, 4)
INJ_U32(d, s->uiTimeSinceMercAIStart)
INJ_I8(d, s->fPanicFlags)
INJ_SKIP(d, 5)
INJ_U8(d, s->ubSpottersCalledForBy)
INJ_SOLDIER(d, s->the_chosen_one)
INJ_U32(d, s->uiTimeOfLastInput)
INJ_U32(d, s->uiTimeSinceDemoOn)
INJ_SKIP(d, 7)
INJ_BOOLA(d, s->fCivGroupHostile, lengthof(s->fCivGroupHostile))
INJ_U8(d, s->ubLastBattleSectorX)
INJ_U8(d, s->ubLastBattleSectorY)
INJ_BOOL(d, s->fLastBattleWon)
INJ_SKIP(d, 2)
INJ_BOOL(d, s->fVirginSector)
INJ_BOOL(d, s->fEnemyInSector)
INJ_BOOL(d, s->fInterruptOccurred)
INJ_I8(d, s->bRealtimeSpeed)
INJ_SKIP(d, 2)
INJ_SOLDIER(d, s->enemy_sighting_on_their_turn_enemy)
INJ_SKIP(d, 1)
INJ_BOOL(d, s->fEnemySightingOnTheirTurn)
INJ_BOOL(d, s->fAutoBandageMode)
INJ_U8(d, s->ubAttackBusyCount)
INJ_SKIP(d, 1)
INJ_U8(d, s->ubEngagedInConvFromActionMercID)
INJ_SKIP(d, 1)
INJ_U16(d, s->usTactialTurnLimitCounter)
INJ_BOOL(d, s->fInTopMessage)
INJ_U8(d, s->ubTopMessageType)
INJ_SKIP(d, 40)
INJ_U16(d, s->usTactialTurnLimitMax)
INJ_U32(d, s->uiTactialTurnLimitClock)
INJ_BOOL(d, s->fTactialTurnLimitStartedBeep)
INJ_I8(d, s->bBoxingState)
INJ_I8(d, s->bConsNumTurnsNotSeen)
INJ_U8(d, s->ubArmyGuysKilled)
INJ_I16A(d, s->sPanicTriggerGridNo, lengthof(s->sPanicTriggerGridNo))
INJ_I8A(d, s->bPanicTriggerIsAlarm, lengthof(s->bPanicTriggerIsAlarm))
INJ_U8A(d, s->ubPanicTolerance, lengthof(s->ubPanicTolerance))
INJ_BOOL(d, s->fAtLeastOneGuyOnMultiSelect)
INJ_SKIP(d, 2)
INJ_BOOL(d, s->fKilledEnemyOnAttack)
INJ_SOLDIER(d, s->enemy_killed_on_attack)
INJ_I8(d, s->bEnemyKilledOnAttackLevel)
INJ_U16(d, s->ubEnemyKilledOnAttackLocation)
INJ_BOOL(d, s->fItemsSeenOnAttack)
INJ_SOLDIER(d, s->items_seen_on_attack_soldier)
INJ_SKIP(d, 2)
INJ_U16(d, s->usItemsSeenOnAttackGridNo)
INJ_BOOL(d, s->fLockItemLocators)
INJ_U8(d, s->ubLastQuoteSaid)
INJ_U8(d, s->ubLastQuoteProfileNUm)
INJ_BOOL(d, s->fCantGetThrough)
INJ_I16(d, s->sCantGetThroughGridNo)
INJ_I16(d, s->sCantGetThroughSoldierGridNo)
INJ_SOLDIER(d, s->cant_get_through)
INJ_BOOL(d, s->fDidGameJustStart)
INJ_SKIP(d, 1)
INJ_U8(d, s->ubLastRequesterTargetID)
INJ_SKIP(d, 1)
INJ_U8(d, s->ubNumCrowsPossible)
INJ_SKIP(d, 4)
INJ_BOOL(d, s->fUnLockUIAfterHiddenInterrupt)
INJ_I8A(d, s->bNumFoughtInBattle, lengthof(s->bNumFoughtInBattle))
INJ_SKIP(d, 1)
INJ_U32(d, s->uiDecayBloodLastUpdate)
INJ_U32(d, s->uiTimeSinceLastInTactical)
INJ_BOOL(d, s->fHasAGameBeenStarted)
INJ_I8(d, s->bConsNumTurnsWeHaventSeenButEnemyDoes)
INJ_BOOL(d, s->fSomeoneHit)
INJ_SKIP(d, 1)
INJ_U32(d, s->uiTimeSinceLastOpplistDecay)
INJ_I8(d, s->bMercArrivingQuoteBeingUsed)
INJ_SOLDIER(d, s->enemy_killed_on_attack_killer)
INJ_BOOL(d, s->fCountingDownForGuideDescription)
INJ_I8(d, s->bGuideDescriptionCountDown)
INJ_U8(d, s->ubGuideDescriptionToUse)
INJ_I8(d, s->bGuideDescriptionSectorX)
INJ_I8(d, s->bGuideDescriptionSectorY)
INJ_I8(d, s->fEnemyFlags)
INJ_BOOL(d, s->fAutoBandagePending)
INJ_BOOL(d, s->fHasEnteredCombatModeSinceEntering)
INJ_BOOL(d, s->fDontAddNewCrows)
INJ_SKIP(d, 1)
INJ_U16(d, s->sCreatureTenseQuoteDelay)
INJ_SKIP(d, 2)
INJ_U32(d, s->uiCreatureTenseQuoteLastUpdate)
Assert(d.getConsumed() == lengthof(data));
FileWrite(f, data, sizeof(data));
}
| 31.643678 | 104 | 0.763531 | flex-lab |
d21e989a93c7bbe63be3d91a88abb98530110963 | 17,295 | cpp | C++ | src/vd_mesh.cpp | 22427/Vertex_Data | 8df9da253dadf21d1c89917f44103e6ed3ab52fa | [
"Unlicense"
] | null | null | null | src/vd_mesh.cpp | 22427/Vertex_Data | 8df9da253dadf21d1c89917f44103e6ed3ab52fa | [
"Unlicense"
] | null | null | null | src/vd_mesh.cpp | 22427/Vertex_Data | 8df9da253dadf21d1c89917f44103e6ed3ab52fa | [
"Unlicense"
] | null | null | null | #include "../include/vd_mesh.h"
#include <glm/geometric.hpp>
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <algorithm>
using namespace glm;
///*****************************************************************************
///* UTILITIES *
///*****************************************************************************
namespace std
{
template<>
struct less<vec4>
{
inline bool eq(const float& a,const float& b) const
{
return std::nextafter(a, std::numeric_limits<float>::lowest()) <= b
&& std::nextafter(a, std::numeric_limits<float>::max()) >= b;
}
size_t operator()(const vec4 &a,const vec4 &b) const
{
for(int i = 0 ; i < 4; i++)
{
if(eq(a[i],b[i])) continue;
return a[i]<b[i];
}
return false;
}
};
}
namespace vd {
static inline void ltrim(std::string &s)
{
s.erase(s.begin(),std::find_if(s.begin(), s.end(),
std::not1(
std::ptr_fun<int,int>(std::isspace))));
}
static inline void rtrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int,int>(std::isspace))).base(),
s.end());
}
static inline void trim(std::string &s){ltrim(s);rtrim(s);}
std::string read_word(std::stringstream& ss)
{
std::string itm;
do
{
std::getline(ss,itm,' ');
trim(itm);
}while(itm.empty() && ss);
return itm;
}
///*****************************************************************************
///* INPUT *
///*****************************************************************************
bool MeshOPS::read(Mesh& m, const std::string& path)
{
std::string ext = path.substr(path.find_last_of('.')+1);
for(char &c : ext) c= toupper(c);
std::ifstream f(path);
if(!f.is_open())
{
m_errcde = CANNOT_OPEN_FILE;
m_errmsg = "Cannot open file '"+path+"'";
return false;
}
else if(ext == "OFF")
return MeshOPS::read_OFF(m,f);
else if(ext == "PLY")
return MeshOPS::read_PLY(m,f);
else if(ext=="OBJ" || ext == "OBJP" || ext == "OBJ+")
return MeshOPS::read_OBJP(m,f);
return false;
}
// OFF-Loader
//------------------------------------------------------------------------------
bool MeshOPS::read_OFF(Mesh &m, std::ifstream &f)
{
std::string line;
vec4 v(0,0,0,1);
Triangle t;
m.active_mask = AM_POSITION;
std::getline(f,line);
trim(line);
if(line != "OFF")
{
m_errcde = PARSING_FILE;
m_errmsg = "OFF files should start with 'OFF'";
return false;
}
std::getline(f,line);
int n_vert = 0;
int n_face = 0;
int n_edge = 0;
std::stringstream ls(line);
ls>>n_vert>>n_face>>n_edge;
m.get_pos_data().reserve(n_vert);
m.triangles.reserve(n_face);
for(int i = 0 ; i< n_vert;i++)
{
if(!std::getline(f,line))
{
m.get_pos_data().clear();
m_errcde = PARSING_FILE;
m_errmsg = "Not enough vertices to read.";
return false;
}
std::stringstream ls(line);
ls>>v.x>>v.y>>v.z;
m.get_pos_data().push_back(v);
}
for( int i = 0 ; i< n_face;i++)
{
if(!std::getline(f,line))
{
m.get_pos_data().clear();
m.triangles.clear();
m_errcde = PARSING_FILE;
m_errmsg = "Not enough faces to read.";
return false;
}
std::stringstream ls(line);
int q=0;
ls>>q;
if(q!=3)
{
m_errcde = NOT_SUPPORTED;
m_errmsg = "Only triangle meshes are supported for now!";
return false;
}
for(int j = 0; j<3;j++)
ls>>t[j].pos_id;
m.triangles.push_back(t);
}
return true;
}
// PLY-Loader
//------------------------------------------------------------------------------
struct ply_prop
{
int elements;
AttributeID id;
std::string type;
};
bool MeshOPS::read_PLY(Mesh &m, std::ifstream &f)
{
std::string line;
m.active_mask = 0;
for(int a = 0 ; a< AID_COUNT;a++)m.attribute_data[a].clear();
m.triangles.clear();
std::getline(f,line);
trim(line);
if(line != "ply")
{
m_errcde = PARSING_FILE;
m_errmsg = "PLY files should start with 'ply'";
return false;
}
int num_verts;
int num_faces;
std::vector<ply_prop> props;
int reading = 0; // 1 is verts 2 is faces
// read header
while (std::getline(f,line))
{
std::stringstream ls(line);
auto first_word = read_word(ls);
if(first_word == "comment")
continue;
if(first_word == "format")
{
if(read_word(ls) != "ascii")
{
m_errcde = PARSING_FILE;
m_errmsg = "Only PLY ASCII is supported!";
return false;
}
continue;
}
if(first_word == "element")
{
const auto ename = read_word(ls);
if(ename == "vertex")
{
ls>>num_verts;
reading = 1;
}
else if(ename == "face")
{
ls>>num_faces;
reading = 2;
}
else
{
m_errcde = PARSING_FILE;
m_errmsg = "element should be vertex or face not '"+ename+"'";
return false;
}
continue;
}
if(first_word == "property" && reading == 1)
{
auto type = read_word(ls);
auto name = read_word(ls);
AttributeID attrib;
switch (name[0])
{
case 'x':case'y':case'z':attrib = AID_POSITION; break;
case 'n':attrib = AID_NORMAL;break;
case 's':case 't': attrib = AID_TEXCOORD;break;
case 'r':case 'g':case 'b': attrib = AID_COLOR;break;
}
if(props.empty() || props.back().id != attrib)
{
ply_prop p;
p.elements = 1;
p.id = attrib;
p.type = type;
props.push_back(p);
m.active_mask |= (1<<attrib);
m.attribute_data[attrib].reserve(num_verts);
}
else
{
props.back().elements++;
props.back().type = type;
}
}
if(first_word == "end_header")
break;
}
// read vertex data
for(int i =0 ; i<num_verts;i++)
{
if(!std::getline(f,line))
{
m_errcde = PARSING_FILE;
m_errmsg = "Not enough vertices to read.";
return false;
}
std::stringstream ls(line);
for(auto& p : props)
{
vec4 v(0,0,0,0);
for(int j = 0 ; j <p.elements;j++)
ls >>v[j];
float scale = 1.0f;
if(p.type == "float")
{}
else if(p.type == "uchar")
{
scale/=static_cast<float>(std::numeric_limits<uint8_t>::max());
}
else if(p.type == "char")
{
scale/=static_cast<float>(std::numeric_limits<int8_t>::max());
}
else if(p.type == "short")
{
scale/=static_cast<float>(std::numeric_limits<int16_t>::max());
}
else if(p.type == "ushort")
{
scale/=static_cast<float>(std::numeric_limits<uint16_t>::max());
}
else if(p.type == "int")
{
scale/=static_cast<float>(std::numeric_limits<int32_t>::max());
}
else if(p.type == "uint")
{
scale/=static_cast<float>(std::numeric_limits<uint32_t>::max());
}
v*=scale;
if(p.id == AID_COLOR || p.id==AID_POSITION)
v.w = 1.0f;
m.attribute_data[p.id].push_back(v);
}
}
// read face data
m.triangles.reserve(num_faces);
for(int i =0 ; i<num_faces;i++)
{
if(!std::getline(f,line))
{
m_errcde = PARSING_FILE;
m_errmsg = "Not enough faces to read.";
return false;
}
std::stringstream ls(line);
int nv;
ls >> nv;
if(nv != 3)
{
m_errcde = NOT_SUPPORTED;
m_errmsg = "Only triangle meshes are supported!";
return false;
}
int q[3];
ls>>q[0]>>q[1]>>q[2];
Triangle t;
for(int v =0 ; v<3;v++)
{
for(int a = 0; a<AID_COUNT;a++)
{
if(m.active_mask & (1<<a))
{
t[v].att_id[a] = q[v];
t[v].active_mask=m.active_mask;
}
}
}
m.triangles.push_back(t);
}
m = MeshOPS::remove_double_attributes(m);
return true;
}
// OBJP-Loader
//------------------------------------------------------------------------------
bool MeshOPS::read_OBJP(Mesh &m, std::ifstream &f)
{
std::string line;
vec4 v;
m.active_mask = AM_POSITION;
int max_attr = 0;
while (std::getline(f,line))
{
auto first_hash = line.find_first_of('#');
if(line[first_hash+1]=='~')
line[first_hash]='~';
line = line.substr(0,line.find_first_of('#')-1);
trim(line);
if(line.empty()) continue;
std::stringstream line_str(line);
v = vec4(0,0,0,0);
std::string lt = read_word(line_str);
int attr_id = -1;
if(lt == "v") attr_id = 0;
else if(lt == "vt") attr_id = 1;
else if(lt == "vn") attr_id = 2;
else if(lt == "~~vc")attr_id = 3;
else if(lt == "~~vtn")attr_id = 4;
else if(lt == "~~vbtn")attr_id = 5;
if(attr_id >=0)
{
if(attr_id != AID_POSITION || AID_COLOR)
v.w =1.0;
m.active_mask |= (1<<attr_id);
line_str>>v.x>>v.y;
if(attr_id != AID_TEXCOORD)
line_str>>v.z;
if(attr_id == AID_COLOR)
line_str>>v.w;
m.attribute_data[attr_id].push_back(v);
max_attr = std::max(max_attr,attr_id);
}
else if(lt == "f")
{
Triangle t;
for( uint32_t v = 0; v < 3; v++)
{
for(int a =0 ; a<std::min(max_attr+1,3);a++)
{
if(m.active_mask & (1<<a))
{
line_str>>t[v].att_id[a];
t[v].att_id[a]-=1;
}
char c = '@';
if(a!= max_attr && a!= 2)
while(c != '/') line_str>>c;
}
t[v].active_mask = m.active_mask ;
}
m.triangles.push_back(t);
}
else if(lt == "~~f")
{
Triangle& t = m.triangles.back();
for( uint32_t v = 0; v < 3; v++)
{
for(int a =3 ; a<=max_attr;a++)
{
if(m.active_mask & (1<<a))
{
line_str>>t[v].att_id[a];
t[v].att_id[a]-=1;
}
char c = '@';
if(a!= max_attr)
while(c != '/') line_str>>c;
}
t[v].active_mask = m.active_mask ;
}
}
}
return true;
}
///*****************************************************************************
/// OUTPUT *
///*****************************************************************************
bool MeshOPS::write(const Mesh&m, const std::string& path)
{
std::string ext = path.substr(path.find_last_of('.')+1);
for(char &c : ext) c= toupper(c);
std::ofstream f(path);
if(!f.is_open())
{
m_errcde = CANNOT_OPEN_FILE;
m_errmsg = "Cannot open file to write '"+path+"'";
return false;
}
if(ext == "OFF")
{
return MeshOPS::write_OFF(m,f);
}
if(ext == "OBJ+" || ext == "OBJP" || ext=="OBJ")
{
return MeshOPS::write_OBJP(m,f);
}
return false;
}
// OFF-Writer
//------------------------------------------------------------------------------
bool MeshOPS::write_OFF(const Mesh &m, std::ofstream &f)
{
f<<"OFF\n"<<m.get_pos_data().size()<<" "<<m.triangles.size()<<" 0\n";
for( const auto& v : m.get_pos_data())
{
f<<v.x<<" "<<v.y<<" "<<v.z<<"\n";
}
for( const auto& t : m.triangles)
{
f<<"3";
for(int i = 0 ; i< 3;i++)
f<<" "<<t[i].pos_id;
f<<"\n";
}
return true;
}
// OBJ+-Writer
//------------------------------------------------------------------------------
void write_OBJp(const Mesh&m, uint32_t active_mask, std::ofstream& f);
bool MeshOPS::write_OBJP(const Mesh &m, std::ofstream &f)
{
f<<"# OBJ+ extends OBJ, there are now six attributes\n";
f<<"# in order make it OBJ compatible '#~' does not indicate a comment "
"anymore\n";
f<<"# v - vertex position\n";
f<<"# vn - vertex normal\n";
f<<"# vt - vertex textrue coord\n";
f<<"# #~vc - vertex color\n";
f<<"# #~vtn - vertex tangent\n";
f<<"# #~vbtn - vertex bitangent\n";
f<<"# a face consists of up to 6 indices, the usual 3 obj indices,\n";
f<<"# followed by the new obj+ indices, introduced by #~ \n";
f<<"# Example:\n";
f<<"# \tf 1/2/3 2/3/3 3/4/3 #~ 1 2 3 # with normals,texcoords & colors\n";
f<<"# \tf 1 2 3 #~f 3 7 2 # with colors\n";
f<<"# \tf 1 2 3 #~f 3/2 7/4 2/12 # with colors & tangents\n\n";
f<<"# Note any .obj is an .obj+, and the other way arround if\n";
f<<"# and _ONLY_ if there are no commends '#~ ...' in the .obj-file\n";
f<<"# But why in the name of everything holy would your write ~ in an obj?"
"\n\n";
write_OBJp(m,m.active_mask,f);
return true;
}
void write_OBJp(const Mesh&m, uint32_t active_mask, std::ofstream& f)
{
std::string a_names[AID_COUNT] = {
std::string("v"),
std::string("vt"),
std::string("vn"),
std::string("#~vc"),
std::string("#~vtn"),
std::string("#~vbtn")};
int max_active =0 ;
for(int a =0 ; a< AID_COUNT;a++)
if(active_mask & (1<<a))
{
for( const auto& v : m.attribute_data[a])
{
f<<a_names[a]<<" "<<v.x<<" "<<v.y;
if(a != AID_TEXCOORD)
f<<" "<<v.z;
if(a == AID_COLOR)
f<<" "<<v.w;
f<<"\n";
}
max_active = a;
}
for(const auto& t : m.triangles)
{
f<<"f";
for(int v = 0 ; v< 3; v++)
{
f<<" ";
for(int a =0 ; a<= max_active && a < 3;a++)
{
if(active_mask & (1<<a))
{
f<<t[v].att_id[a]+1;
}
if(a<max_active && a != 2)
f<<"/";
}
}
if(max_active > 2)
f<<"\n#~f ";
for(int v = 0 ; v< 3; v++)
{
f<<" ";
for(int a =3 ; a<= max_active;a++)
{
if(active_mask & (1<<a))
{
f<<t[v].att_id[a]+1;
}
if(a<max_active )
f<<"/";
}
}
f<<"\n";
}
}
///*****************************************************************************
///* PROCESSING *
///*****************************************************************************
// Normal calculation
//------------------------------------------------------------------------------
vec4 get_weighted_normal(const Mesh&m, const uint32_t t_id)
{
const auto t = m.triangles[t_id];
const auto& pd = m.get_pos_data();
const vec4 A = (pd[t[1].pos_id])-pd[t[0].pos_id];
const vec4 B = (pd[t[2].pos_id])-pd[t[0].pos_id];
const vec3 a(A);
const vec3 b(B);
const vec3 cr = cross(a,b);
float area = 0.5f* length(cr);
auto n = normalize(cr);
const float w = area/((dot(a,a)*dot(b,b)));
return vec4(n*w,0.0f);
}
void MeshOPS::recalculate_normals(Mesh &m)
{
auto& norms = m.get_nrm_data();
norms.clear();
norms.resize(m.get_pos_data().size(), vec4(0.0f));
for(uint i = 0 ; i < m.triangles.size();i++)
{
auto& t = m.triangles[i];
auto n = get_weighted_normal(m,i);
for(uint j = 0 ;j < 3;j++)
{
t[j].nrm_id = t[j].pos_id;
norms[t[j].pos_id] += n;
}
}
for(auto& a : norms)
{
a = normalize(a);
}
m.active_mask |= AM_NORMAL;
}
// Tangent and Bitangent calculation
//------------------------------------------------------------------------------
bool MeshOPS::recalculate_tan_btn(Mesh &m)
{
uint32_t req = AM_TEXCOORD|AM_NORMAL|AM_POSITION;
if((m.active_mask&req) != req)
{
m_errcde = NEED_MORE_DATA;
m_errmsg = "Calculating tangents and bitangents needs texcoords,"
"normals and positions.";
return false;
}
m.get_tan_data().clear();
m.get_btn_data().clear();
std::map<MeshVertex,uint32_t,
vertex_masked_comperator<AM_POSITION|AM_NORMAL|AM_TEXCOORD>> ids;
auto& tans = m.get_tan_data();
auto& btns = m.get_btn_data();
for (auto& t : m.triangles)
{
auto& vtx = t[0];
const vec4& v0 = m.get_pos_data()[vtx.pos_id];
const vec4& uv0 = m.get_tex_data()[vtx.pos_id];
vtx = t[1];
const vec4& v1 = m.get_pos_data()[vtx.pos_id];
const vec4& uv1 = m.get_tex_data()[vtx.pos_id];
vtx = t[2];
const vec4& v2 = m.get_pos_data()[vtx.pos_id];
const vec4& uv2 = m.get_tex_data()[vtx.pos_id];
vec4 dPos1 = v1 - v0;
vec4 dPos2 = v2 - v0;
vec4 dUV1 =uv1 -uv0;
vec4 dUV2 =uv2 -uv0;
float r = 1.0f / (dUV1.x * dUV2.y - dUV1.y * dUV2.x);
vec4 tan = (dPos1 * dUV2.y - dPos2 * dUV1.y)*r;
vec4 btn = (dPos2 * dUV1.x - dPos1 * dUV2.x)*r;
tan.w = btn.w = 0.0f;
for(uint j = 0 ;j < 3;j++)
{
auto it = ids.find(t[j]);
if(it == ids.end())
{
const uint32_t new_id = static_cast<uint32_t>(tans.size());
ids[t[j]] = new_id;
t[j].tan_id = t[j].btn_id = new_id;
tans.push_back(tan);
btns.push_back(btn);
}
else
{
tans[(*it).second] += tan;
btns[(*it).second] += btn;
}
}
}
m.active_mask |= AM_TANGENT | AM_BITANGENT;
return true;
}
uint32_t insert_attrib_value(const vec4& val,
std::map<vec4,uint32_t,std::less<vec4>>& ad,
std::vector<vec4> &attribute_data)
{
auto it = ad.find(val);
if(it != ad.end())
return (*it).second;
const uint32_t id = static_cast<uint32_t>(attribute_data.size());
ad[val] = id;
attribute_data.push_back(val);
return id;
}
Mesh MeshOPS::remove_double_attributes(const Mesh &m)
{
Mesh r;
std::map<vec4,uint32_t,std::less<vec4> > attribute_id[AID_COUNT];
Triangle proto_tri;
for(auto&v:proto_tri)
v.active_mask = m.active_mask;
r.active_mask = m.active_mask;
r.triangles.resize(m.triangles.size(),proto_tri);
for(uint32_t a = 0 ; a < AID_COUNT; a++)
{
if(!(m.active_mask & (1<<a)))
continue;
const auto& ia_array = m.attribute_data[a];
auto& oa_array = r.attribute_data[a];
auto& attrib_map = attribute_id[a];
for(uint t = 0 ; t<m.triangles.size();t++)
{
for(int v = 0 ; v<3;v++)
{
int aeid= m.triangles[t][v].att_id[a];
r.triangles[t][v].att_id[a] = insert_attrib_value(
ia_array[aeid],
attrib_map,
oa_array);
}
}
}
return r;
}
MeshVertex::MeshVertex()
{
for(uint32_t i = 0 ; i < AID_COUNT;i++)
att_id[i] = UINT32_MAX;
active_mask = (1<<AID_COUNT)-1;
}
bool MeshVertex::operator<(const MeshVertex &o) const
{
for(uint32_t i = 0 ; i< AID_COUNT;i++)
{
if(att_id[i] == o.att_id[i])
continue;
else
return att_id[i] < o.att_id[i];
}
return false;
}
std::string MeshOPS::m_errmsg = "";
ErrorCode MeshOPS::m_errcde=NO_ERROR;
}
| 21.837121 | 80 | 0.535184 | 22427 |
d220acfae0348a757cc2c112bd12f5141ed80802 | 1,358 | cc | C++ | pagespeed/system/redis_cache_cluster_setup_main.cc | dimitrilongo/mod_pagespeed | d0d3bc51aa4feddf010b7085872c64cc46b5aae0 | [
"Apache-2.0"
] | 2 | 2019-11-02T07:54:17.000Z | 2020-04-16T09:26:51.000Z | pagespeed/system/redis_cache_cluster_setup_main.cc | dimitrilongo/mod_pagespeed | d0d3bc51aa4feddf010b7085872c64cc46b5aae0 | [
"Apache-2.0"
] | 12 | 2017-03-14T18:26:11.000Z | 2021-10-01T15:33:50.000Z | pagespeed/system/redis_cache_cluster_setup_main.cc | dimitrilongo/mod_pagespeed | d0d3bc51aa4feddf010b7085872c64cc46b5aae0 | [
"Apache-2.0"
] | 1 | 2020-04-16T09:28:30.000Z | 2020-04-16T09:28:30.000Z | /*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: cheesy@google.com (Steve Hill)
*/
#include <vector>
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/system/redis_cache_cluster_setup.h"
// Lint complains if I put 'using namespace net_instaweb' even in main(), so
// adding this instead.
namespace net_instaweb {
namespace {
int SetupRedisCluster() {
StringVector node_ids;
std::vector<int> ports;
ConnectionList connections;
// LOGs errors on failure.
if (RedisCluster::LoadConfiguration(&node_ids, &ports, &connections)) {
RedisCluster::ResetConfiguration(&node_ids, &ports, &connections);
} else {
return 1;
}
return 0;
}
} // namespace
} // namespace net_instaweb
int main(int argc, char** argv) {
return net_instaweb::SetupRedisCluster();
}
| 26.627451 | 76 | 0.726068 | dimitrilongo |
d220fbb93edc8881a4d1c9bf74f10540bf151f6d | 2,521 | cpp | C++ | src/util/log.cpp | mandliya/gameboy_emulator | 5293a014e19af5c0555caa0db6411c8cc3fca7fc | [
"BSD-3-Clause"
] | 13 | 2018-01-11T09:50:38.000Z | 2021-08-02T22:03:20.000Z | src/util/log.cpp | mandliya/gameboy_emulator | 5293a014e19af5c0555caa0db6411c8cc3fca7fc | [
"BSD-3-Clause"
] | 1 | 2019-10-16T12:30:28.000Z | 2020-04-13T12:42:12.000Z | src/util/log.cpp | mandliya/gameboy_emulator | 5293a014e19af5c0555caa0db6411c8cc3fca7fc | [
"BSD-3-Clause"
] | 3 | 2018-01-26T07:56:18.000Z | 2021-01-05T15:11:01.000Z | /*
* Copyright (C) 2015 Alex Smith
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "log.h"
#include "string.h"
Logger global_logger;
const char* COLOR_TRACE = "\033[1;30m"; // Bold Black
const char* COLOR_DEBUG = "\033[1;37m"; // Bold White
const char* COLOR_UNIMPLEMENTED = "\033[1;35m"; // Bold Purple
const char* COLOR_INFO = "\033[1;34m"; // Bold Blue
const char* COLOR_WARNING = "\033[1;33m"; // Bold Yellow
const char* COLOR_ERROR = "\033[1;31m"; // Bold Red
const char* COLOR_RESET = "\033[0m"; // Color Reset
Loggger::Logger() { }
void Logger::log(LogLevel level, const char* fmt, ...)
{
if(!should_log(level)) {
return;
}
va_list args;
va_start(args, fmt);
std::string msg = str_format(fmt, args);
va_end(args);
fprint((level > LogLevel::Error) ? stdout : stderr,
"%s| %s%s\n",
level_color(level), COLOR_RESET, msg.c_str());
}
void Logger::set_level(LogLevel level)
{
current_level = level;
}
void Logger::enable_tracing()
{
tracing_enabled = true;
}
bool Logger::should_log(LogLevel level) const {
if (!tracing_enabled && level == LogLevel::Trace) {
return false;
}
return (enabled && current_level >= level);
}
inline const char* Logger::level_color(LogLevel level) const
{
switch(level) {
case LogLevel::Trace:
return COLOR_TRACE;
case LogLevel::Debug:
return COLOR_DEBUG;
case LogLevel::Unimplemented:
return COLOR_UNIMPLEMENTED;
case LogLevel::Info:
return COLOR_INFO;
case LogLevel::Warning:
return COLOR_WARNING;
case LogLevel::Error:
return COLOR_ERROR;
}
}
void log_set_level(LogLevel level) {
global_logger.set_level(level);
} | 29.658824 | 75 | 0.656882 | mandliya |
d222c61cb480a2cc28b5f6e097a7555e16607d83 | 309 | cpp | C++ | facebook-clang-plugins/libtooling/tests/using_directive.cpp | JacobBarthelmeh/infer | 12c582a69855e17a2cf9c7b6cdf7f8e9c71e5341 | [
"MIT"
] | 14,499 | 2015-06-11T16:00:28.000Z | 2022-03-31T23:43:54.000Z | facebook-clang-plugins/libtooling/tests/using_directive.cpp | JacobBarthelmeh/infer | 12c582a69855e17a2cf9c7b6cdf7f8e9c71e5341 | [
"MIT"
] | 1,529 | 2015-06-11T16:55:30.000Z | 2022-03-27T15:59:46.000Z | facebook-clang-plugins/libtooling/tests/using_directive.cpp | JacobBarthelmeh/infer | 12c582a69855e17a2cf9c7b6cdf7f8e9c71e5341 | [
"MIT"
] | 2,225 | 2015-06-11T16:36:10.000Z | 2022-03-31T05:16:59.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
namespace nsa {
namespace nsb {
int a;
}
} // namespace nsa
using namespace nsa::nsb;
namespace B = nsa::nsb;
int b = a;
| 20.6 | 66 | 0.695793 | JacobBarthelmeh |
d2236f382ef4a8f1d494d1cede58881c17fb936d | 1,010 | hh | C++ | src/Nuxed/Kernel/Extension/SessionExtension.hh | tomoki1337/framework | ff06d260c5bf2a78a99b8d17b041de756550f95a | [
"MIT"
] | null | null | null | src/Nuxed/Kernel/Extension/SessionExtension.hh | tomoki1337/framework | ff06d260c5bf2a78a99b8d17b041de756550f95a | [
"MIT"
] | null | null | null | src/Nuxed/Kernel/Extension/SessionExtension.hh | tomoki1337/framework | ff06d260c5bf2a78a99b8d17b041de756550f95a | [
"MIT"
] | null | null | null | <?hh // strict
namespace Nuxed\Kernel\Extension;
use namespace Nuxed\Http\Session;
use namespace Nuxed\Kernel\ServiceProvider;
use type Nuxed\Container\ServiceProvider\ServiceProviderInterface;
use type Nuxed\Contract\Http\Server\MiddlewarePipeInterface;
use type Nuxed\Http\Server\MiddlewareFactory;
use type Nuxed\Kernel\Configuration;
class SessionExtension extends AbstractExtension {
<<__Override>>
public function services(
Configuration $_configuration,
): Container<ServiceProviderInterface> {
return vec[
new ServiceProvider\SessionServiceProvider(),
];
}
<<__Override>>
public function pipe(
MiddlewarePipeInterface $pipe,
MiddlewareFactory $middlewares,
): void {
/*
* Register the session middleware in the middleware pipeline.
* This middleware register the 'session' attribute containing the
* session implementation.
*/
$pipe->pipe(
$middlewares->prepare(Session\SessionMiddleware::class),
0x9100,
);
}
}
| 26.578947 | 70 | 0.738614 | tomoki1337 |
d22485e744eef16d8fe049beaa4f52075980ade2 | 5,313 | cc | C++ | graveyard/gui/CorrelationWidget.cc | AndrewAnnex/StereoPipeline | 084c3293c3a5382b052177c74388d9beeb79cf0b | [
"Apache-2.0"
] | 323 | 2015-01-10T12:34:24.000Z | 2022-03-24T03:52:22.000Z | graveyard/gui/CorrelationWidget.cc | AndrewAnnex/StereoPipeline | 084c3293c3a5382b052177c74388d9beeb79cf0b | [
"Apache-2.0"
] | 252 | 2015-07-27T16:36:31.000Z | 2022-03-31T02:34:28.000Z | graveyard/gui/CorrelationWidget.cc | AndrewAnnex/StereoPipeline | 084c3293c3a5382b052177c74388d9beeb79cf0b | [
"Apache-2.0"
] | 105 | 2015-02-28T02:37:27.000Z | 2022-03-14T09:17:30.000Z | // __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is 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.
// __END_LICENSE__
#include <QtGui>
#include "CorrelationWidget.h"
CorrelationWidget::CorrelationWidget(StereoGuiSession *cs, QWidget *parent) : QWidget(parent) {
this->blockSignals(true);
m_cs = cs;
m_xImagePreview = new PreviewGLWidget(this);
m_yImagePreview = new PreviewGLWidget(this);
m_leftImagePreview = new PreviewGLWidget(this);
QTabWidget *previewTab = new QTabWidget;
previewTab->addTab(m_xImagePreview, "X Disparity");
previewTab->addTab(m_yImagePreview, "Y Disparity");
previewTab->addTab(m_leftImagePreview, "Left Image");
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(previewTab);
mainLayout->addWidget(genSettingsBox("Search Window Preview Settings"));
this->setLayout(mainLayout);
// m_correlateThread = new QCorrelateThread(this);
// connect(m_correlateThread, SIGNAL(correlationFinished()), this, SLOT(correlationFinished()));
// connect(m_correlateThread, SIGNAL(progressUpdate(int)), m_progressBar, SLOT(setValue(int)));
// connect(m_cancelButton, SIGNAL(clicked()), m_correlateThread, SLOT(abortCorrelation()));
connect(m_cancelButton, SIGNAL(clicked()), m_progressBar, SLOT(reset()));
connect(m_doCorrelateButton, SIGNAL(clicked()), this, SLOT(doCorrelate()));
connect(m_xImagePreview, SIGNAL(imageClicked(int, int)), this, SLOT(imageClicked(int, int)));
connect(m_yImagePreview, SIGNAL(imageClicked(int, int)), this, SLOT(imageClicked(int, int)));
connect(m_leftImagePreview, SIGNAL(imageClicked(int, int)), this, SLOT(imageClicked(int, int)));
connect(previewTab, SIGNAL(currentChanged(int)), m_xImagePreview, SLOT(fitToWindow()));
connect(previewTab, SIGNAL(currentChanged(int)), m_yImagePreview, SLOT(fitToWindow()));
connect(previewTab, SIGNAL(currentChanged(int)), m_leftImagePreview, SLOT(fitToWindow()));
}
QGroupBox *CorrelationWidget::genSettingsBox(QString const& name) {
m_doCorrelateButton = new QPushButton("Correlate!!");
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_doCorrelateButton);
layout->addLayout(genProgressLayout());
QGroupBox *box = new QGroupBox(name);
box->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
box->setLayout(layout);
return box;
}
QHBoxLayout *CorrelationWidget::genProgressLayout() {
m_progressBar = new QProgressBar;
m_progressBar->setRange(0, 100);
m_progressBar->setValue(0);
m_cancelButton = new QPushButton("Cancel");
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(m_progressBar);
layout->addWidget(m_cancelButton);
return layout;
}
void CorrelationWidget::doCorrelate() {
if (m_cs->hasBothImagesLoaded()) {
// m_correlateThread->doCorrelate(m_cs->getCostFunctionObject(), m_cs->searchWindow());
}
}
void CorrelationWidget::updatePreview() {
// m_xImagePreview->setCrosshairPosition(m_cs->searchWindowPreviewPoint());
// m_xImagePreview->setCrosshairEnabled(m_cs->crosshairEnabled());
// m_xImagePreview->updatePreview();
// m_yImagePreview->setCrosshairPosition(m_cs->searchWindowPreviewPoint());
// m_yImagePreview->setCrosshairEnabled(m_cs->crosshairEnabled());
// m_yImagePreview->updatePreview();
// m_leftImagePreview->setCrosshairPosition(m_cs->searchWindowPreviewPoint());
// m_leftImagePreview->setCrosshairEnabled(m_cs->crosshairEnabled());
// m_leftImagePreview->updatePreview();
}
void CorrelationWidget::imageClicked(int x, int y) {
vw::Vector2i loc(x, y);
if (loc == m_cs->searchWindowPreviewPoint() && m_cs->crosshairEnabled()) {
m_cs->setCrosshairEnabled(false);
}
else {
m_cs->setCrosshairEnabled(true);
}
m_cs->setSearchWindowPreviewPoint(vw::Vector2i(x, y));
updatePreview();
}
void CorrelationWidget::updateWidgets() {
// m_leftImagePreview->setImage(m_cs->leftImage(), true);
updatePreview();
}
void CorrelationWidget::correlationFinished() {
// vw::ImageView<vw::PixelDisparity<vw::float32> > disparity_map = m_correlateThread->result();
// vw::ImageView<vw::float32> xResult = clamp(select_channel(disparity_map, 0), m_cs->searchWindow().min().x(), m_cs->searchWindow().max().x());
// vw::ImageView<vw::float32> yResult = clamp(select_channel(disparity_map, 1), m_cs->searchWindow().min().y(), m_cs->searchWindow().max().y());
// m_xImagePreview->setImage(xResult, true);
// m_yImagePreview->setImage(yResult, true);
// m_xImagePreview->fitToWindow();
// m_yImagePreview->fitToWindow();
// m_leftImagePreview->fitToWindow();
// m_cs->setDisparityMap(disparity_map);
updatePreview();
}
| 35.898649 | 146 | 0.743083 | AndrewAnnex |
d227ed7477080fdc07ca1f44790ce2e1267cc918 | 607 | cpp | C++ | src/layer_renderer.cpp | GhostInABottle/octopus_engine | 50429e889493527bdc0e78b307937002e0f2c510 | [
"BSD-2-Clause"
] | 3 | 2017-10-02T03:18:59.000Z | 2020-11-01T09:21:28.000Z | src/layer_renderer.cpp | GhostInABottle/octopus_engine | 50429e889493527bdc0e78b307937002e0f2c510 | [
"BSD-2-Clause"
] | 2 | 2019-04-06T21:48:08.000Z | 2020-05-22T23:38:54.000Z | src/layer_renderer.cpp | GhostInABottle/octopus_engine | 50429e889493527bdc0e78b307937002e0f2c510 | [
"BSD-2-Clause"
] | 1 | 2017-07-17T20:58:26.000Z | 2017-07-17T20:58:26.000Z | #include "../include/layer_renderer.hpp"
#include "../include/layer.hpp"
#include "../include/custom_shaders.hpp"
#include "../include/utility/file.hpp"
#include "../include/log.hpp"
#include <utility>
Layer_Renderer::Layer_Renderer(const Layer& layer, const Camera& camera) :
layer(layer), camera(camera), needs_redraw(false) {
if (!layer.vertex_shader.empty()) {
auto vshader = file_utilities::read_file(layer.vertex_shader);
auto fshader = file_utilities::read_file(layer.fragment_shader);
batch.set_shader(std::make_unique<Custom_Shader>(vshader, fshader));
}
}
| 37.9375 | 76 | 0.711697 | GhostInABottle |
d2288d807dfd0544bdf76dee56337dd52911e511 | 1,252 | cpp | C++ | tools/PsfPlayer/Source/win32_ui/DebugSupport/WinUtils.cpp | Croden1999/Play- | 986648645a716122ece7178003ff106f047708bb | [
"BSD-2-Clause"
] | 1,720 | 2015-01-03T15:53:43.000Z | 2022-03-30T00:38:04.000Z | tools/PsfPlayer/Source/win32_ui/DebugSupport/WinUtils.cpp | Croden1999/Play- | 986648645a716122ece7178003ff106f047708bb | [
"BSD-2-Clause"
] | 1,112 | 2015-01-03T08:45:24.000Z | 2022-03-31T14:06:08.000Z | tools/PsfPlayer/Source/win32_ui/DebugSupport/WinUtils.cpp | Croden1999/Play- | 986648645a716122ece7178003ff106f047708bb | [
"BSD-2-Clause"
] | 329 | 2015-01-27T08:58:06.000Z | 2022-03-28T18:45:05.000Z | #include <cassert>
#include "WinUtils.h"
using namespace Framework;
HBITMAP WinUtils::CreateMask(HBITMAP nBitmap, uint32 nColor)
{
BITMAP bm;
GetObject(nBitmap, sizeof(BITMAP), &bm);
HBITMAP nMask = CreateBitmap(bm.bmWidth, bm.bmHeight, 1, 1, NULL);
HDC hDC1 = CreateCompatibleDC(0);
HDC hDC2 = CreateCompatibleDC(0);
SelectObject(hDC1, nBitmap);
SelectObject(hDC2, nMask);
SetBkColor(hDC1, nColor);
BitBlt(hDC2, 0, 0, bm.bmWidth, bm.bmHeight, hDC1, 0, 0, SRCCOPY);
BitBlt(hDC1, 0, 0, bm.bmWidth, bm.bmHeight, hDC2, 0, 0, SRCINVERT);
DeleteDC(hDC1);
DeleteDC(hDC2);
return nMask;
}
TCHAR WinUtils::FixSlashes(TCHAR nCharacter)
{
return (nCharacter == _T('/')) ? _T('\\') : nCharacter;
}
void WinUtils::CopyStringToClipboard(const std::tstring& stringToCopy)
{
if(!OpenClipboard(NULL))
{
assert(false);
return;
}
EmptyClipboard();
auto memoryHandle = GlobalAlloc(GMEM_MOVEABLE, (stringToCopy.length() + 1) * sizeof(TCHAR));
{
auto memoryPtr = reinterpret_cast<TCHAR*>(GlobalLock(memoryHandle));
_tcscpy(memoryPtr, stringToCopy.c_str());
GlobalUnlock(memoryHandle);
}
#ifdef _UNICODE
SetClipboardData(CF_UNICODETEXT, memoryHandle);
#else
SetClipboardData(CF_TEXT, memoryHandle);
#endif
CloseClipboard();
}
| 21.220339 | 93 | 0.723642 | Croden1999 |
d22aac8fb80d854c44ab859af04e81414a0eddfc | 2,924 | hpp | C++ | include/GaussianProcessSupport.hpp | snowpac/snowpac | ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305 | [
"BSD-2-Clause"
] | 3 | 2019-08-04T20:18:00.000Z | 2021-06-22T23:50:27.000Z | include/GaussianProcessSupport.hpp | snowpac/snowpac | ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305 | [
"BSD-2-Clause"
] | null | null | null | include/GaussianProcessSupport.hpp | snowpac/snowpac | ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305 | [
"BSD-2-Clause"
] | null | null | null | #ifndef HGaussianProcessSupport
#define HGaussianProcessSupport
#include "GaussianProcess.hpp"
#include "BlackBoxData.hpp"
#include "VectorOperations.hpp"
#include <vector>
#include <float.h>
#include <cmath>
#include <iomanip>
#include <assert.h>
class GaussianProcessSupport : protected VectorOperations {
private:
double *delta;
bool do_parameter_estimation = false;
int number_processes;
int nb_values = 0;
std::vector<int> update_at_evaluations;
int update_interval_length;
int next_update = 0;
int last_included = 0;
int best_index;
double delta_tmp;
double variance, mean;
double weight;
std::vector<double> gaussian_process_values;
std::vector<double> gaussian_process_noise;
std::vector< std::vector<double> > gaussian_process_nodes;
std::vector<int> gaussian_process_active_index;
std::vector<std::shared_ptr<GaussianProcess>> gaussian_processes;
std::vector<double> rescaled_node;
std::vector<std::vector<double>> best_index_analytic_information;
bool use_approx_gaussian_process = false;
bool approx_gaussian_process_active = false;
bool use_analytic_smoothing = false;
const double u_ratio = 0.15;
const int min_nb_u = 2;
int cur_nb_u_points = 0;
double gaussian_process_delta_factor = 3.;
std::vector<double> bootstrap_estimate;
int smoothing_ctr;
private:
int NOEXIT;
void update_gaussian_processes_for_agp( BlackBoxData&);
static double fill_width_objective(std::vector<double> const &x,
std::vector<double> &grad,
void *data);
static void ball_constraint(unsigned int m, double* c, unsigned n, const double *x, double *grad, void *data);
//void do_resample_u(); //TODO check if able to remove this one
protected:
virtual double compute_fill_width(BlackBoxData& evaluations);
void update_gaussian_processes ( BlackBoxData& );
void update_gaussian_processes_for_gp (BlackBoxData&);
public:
void initialize ( const int, const int, double&, BlackBoxBaseClass *blackbox,
std::vector<int> const&, int , const std::string, const int exitconst, const bool use_analytic_smoothing);
int smooth_data ( BlackBoxData& );
double evaluate_objective ( BlackBoxData const& );
void evaluate_gaussian_process_at(const int&, std::vector<double> const&, double&, double&);
const std::vector<std::vector<double>> &get_nodes_at(const int&) const;
void get_induced_nodes_at(const int idx, std::vector<std::vector<double>> &induced_nodes);
void set_constraint_ball_center(const std::vector<double>& center);
void set_constraint_ball_radius(const double& radius);
const std::vector<std::vector<double>> &getBest_index_analytic_information() const;
void set_gaussian_process_delta(double gaussian_process_delta);
};
#endif
| 33.227273 | 128 | 0.718878 | snowpac |
d22b9100f1c5259dfe49cfaffa13de14e50b80dc | 430 | hpp | C++ | mainapp/Classes/Common/Controls/DottedRect.hpp | JaagaLabs/GLEXP-Team-KitkitSchool | f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0 | [
"Apache-2.0"
] | 45 | 2019-05-16T20:49:31.000Z | 2021-11-05T21:40:54.000Z | mainapp/Classes/Common/Controls/DottedRect.hpp | rdsmarketing/GLEXP-Team-KitkitSchool | 6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e | [
"Apache-2.0"
] | 10 | 2019-05-17T13:38:22.000Z | 2021-07-31T19:38:27.000Z | mainapp/Classes/Common/Controls/DottedRect.hpp | rdsmarketing/GLEXP-Team-KitkitSchool | 6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e | [
"Apache-2.0"
] | 29 | 2019-05-16T17:49:26.000Z | 2021-12-30T16:36:24.000Z | //
// DottedRect.hpp
// KitkitSchool
//
// Created by Gunho Lee on 1/6/17.
//
//
#ifndef DottedRect_hpp
#define DottedRect_hpp
#include <stdio.h>
#include "cocos2d.h"
using namespace cocos2d;
class DottedRect : public Node
{
public:
static DottedRect* create(Size prefferedSize);
virtual bool init(Size prefferedSize);
private:
Node *_face;
};
#endif /* DottedRect_hpp */
| 11.621622 | 50 | 0.637209 | JaagaLabs |
d22f225f252e9421c36e5091464181bd2aadf2ef | 20 | cpp | C++ | src/cpps_module.cpp | TansuoTro/CPPS | cca35d8dc2128aba7fa4a40cb6d83487e265cf3f | [
"MIT"
] | null | null | null | src/cpps_module.cpp | TansuoTro/CPPS | cca35d8dc2128aba7fa4a40cb6d83487e265cf3f | [
"MIT"
] | null | null | null | src/cpps_module.cpp | TansuoTro/CPPS | cca35d8dc2128aba7fa4a40cb6d83487e265cf3f | [
"MIT"
] | null | null | null | #include "cpps.h"
| 5 | 17 | 0.6 | TansuoTro |
d22fed470e5441b16b47a2389a360706168817c3 | 4,405 | cpp | C++ | uvcpp/uvcpplog.cpp | netmindms/libuvcpp | 1bf84a392ef681c9720ff5f0b3a4a4616da7aa9c | [
"MIT"
] | 7 | 2017-07-18T05:50:51.000Z | 2022-02-22T17:50:57.000Z | uvcpp/uvcpplog.cpp | netmindms/libuvcpp | 1bf84a392ef681c9720ff5f0b3a4a4616da7aa9c | [
"MIT"
] | null | null | null | uvcpp/uvcpplog.cpp | netmindms/libuvcpp | 1bf84a392ef681c9720ff5f0b3a4a4616da7aa9c | [
"MIT"
] | null | null | null | /*
* alog.cpp
*
* Created on: Apr 13, 2015
* Author: netmind
*/
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <vector>
#include <chrono>
#include <sys/time.h>
#include <pthread.h>
#include <thread>
#include <unistd.h>
#include <libgen.h>
#include <limits.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#ifdef _WIN32
#include <fileapi.h>
#endif
#include "uvcpplog.h"
using namespace std;
namespace uvcpp {
LogInst *_gDefLogInst = nullptr;
struct _NMDLOG_MOD_ {
public:
_NMDLOG_MOD_() {
_gDefLogInst = new LogInst;
}
virtual ~_NMDLOG_MOD_() {
if (_gDefLogInst) delete _gDefLogInst;
}
};
static _NMDLOG_MOD_ _LOCAL_MODULE_INST;
LogInst *getDefLogInst() {
return _gDefLogInst;
}
string GetLogTimeNow() {
struct timeval tv;
gettimeofday(&tv, (struct timezone *) nullptr);
struct tm ttm;
localtime_r(&tv.tv_sec, &ttm);
char buf[30];
::sprintf(buf, "%02d:%02d:%02d.%03d", ttm.tm_hour, ttm.tm_min, ttm.tm_sec, (int) (tv.tv_usec / 1000));
return string(buf);
}
void GetLogTimeNow(char *buf) {
struct timeval tv;
gettimeofday(&tv, (struct timezone *) nullptr);
struct tm ttm;
localtime_r(&tv.tv_sec, &ttm);
::sprintf(buf, "%02d:%02d:%02d.%03d", ttm.tm_hour, ttm.tm_min, ttm.tm_sec, (int) (tv.tv_usec / 1000));
}
#if 0
void prtlog(int level, const char* format, fmt::ArgList args) {
if(level<=gPrintLogLevel || level <=gFileLogLevel) {
gNmdLogInst.lock();
fmt::MemoryWriter w;
// w.write(format, args);
fmt::printf(w, (fmt::CStringRef)format, args);
// w << '\n';
if(level<=gPrintLogLevel) std::fwrite(w.data(), 1, w.size(), stdout);
if(level<=gFileLogLevel) gNmdLogInst.fileWrite(w.data(), w.size());
gNmdLogInst.unlock();
}
}
void setOutLogLevel(int level) {
gPrintLogLevel = level;
}
int setFileLog(int level, const char *path) {
gNmdLogInst.lock();
gFileLogLevel = level;
auto ret = gNmdLogInst.openLogFile(path);
gNmdLogInst.unlock();
return ret;
}
#endif
LogInst::LogInst() {
mLevel = UVCLOG_DEBUG;
mFileLevel = -1;
mFd = -1;
mMaxFileSize = 10 * 1024 * 1024; // default 10MB
}
LogInst::~LogInst() {
if (mFd >= 0) {
close(mFd);
}
}
void LogInst::lock() {
mMutex.lock();
}
void LogInst::unlock() {
mMutex.unlock();
}
int LogInst::setLogFile(const char *path, size_t max) {
if (mFd >= 0) {
close(mFd);
mFd = -1;
}
struct stat s;
auto ret = stat(path, &s);
if (!ret) {
// mode_t mode = (S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP | S_IROTH);
int flag = O_APPEND | O_WRONLY;
mFd = open(path, flag);
// mFd = open(path, flag, mode);
} else {
mode_t mode = (S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP | S_IROTH);
int flag;
flag = O_CREAT | O_WRONLY;
mFd = open(path, flag, mode);
}
if (mFd >= 0) {
#ifdef __linux
char *fullpath = realpath(path, nullptr);
#elif _WIN32
char fullpath[512];
GetFullPathName(path, 512, fullpath, nullptr);
#endif
if (fullpath) {
mMaxFileSize = max;
mFilePath = fullpath;
free(fullpath);
}
}
return mFd >= 0 ? 0 : -1;
}
void LogInst::checkSize() {
if (mFd >= 0) {
auto fs = lseek(mFd, 0, SEEK_CUR);
if (fs >= mMaxFileSize) {
close(mFd);
mFd = -1;
backupFile();
setLogFile(mFilePath.data(), mMaxFileSize);
}
}
}
//int LogInst::writeFile(const char *ptr, size_t len) {
// auto wret = write(mFd, ptr, len);
// checkSize();
// return wret;
//}
int LogInst::backupFile() {
if (mBackupFolder.empty()) {
if (mFilePath != "") {
char *tmp = strdup(mFilePath.data());
assert(tmp);
char *base = dirname(tmp);
mBackupFolder = string(base) + "/.backup";
free(tmp);
} else {
return -1;
// char* tmp = get_current_dir_name();
// char* base = basename(tmp);
// mBackupFolder = base;
// free(tmp);
}
}
if (mFilePath != "") {
struct stat s;
auto ret = stat(mBackupFolder.data(), &s);
if (ret) {
#ifdef __linux
ret = mkdir(mBackupFolder.data(), 0775);
#elif _WIN32
ret = mkdir(mBackupFolder.data());
#endif
if (ret) return -1;
}
char *tmp = strdup(mFilePath.data());
char *fn = basename(tmp);
string path = mBackupFolder + "/" + fn;
remove(path.data());
free(tmp);
return rename(mFilePath.data(), path.data());
} else {
return -1;
}
return 0;
}
} // namespace uvcpp
| 20.206422 | 104 | 0.620658 | netmindms |
d230fcc4f1e016884d0b9ab207c200a21082df75 | 949 | cpp | C++ | cpp/p74.cpp | voltrevo/project-euler | 0db5451f72b1353b295e56f928c968801e054444 | [
"MIT"
] | null | null | null | cpp/p74.cpp | voltrevo/project-euler | 0db5451f72b1353b295e56f928c968801e054444 | [
"MIT"
] | null | null | null | cpp/p74.cpp | voltrevo/project-euler | 0db5451f72b1353b295e56f928c968801e054444 | [
"MIT"
] | null | null | null | #include <cassert>
#include <iostream>
int factorials[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
int NonRepeatLength(int n)
{
int count = 0;
while (count != 61)
{
++count;
int nCopy = n;
n = 0;
while (nCopy > 0)
{
n += factorials[nCopy % 10];
nCopy /= 10;
}
if (n == 0 || n == 1 || n == 2 || n == 145)
return count + 1;
else if (n == 169 || n == 1454 || n == 363601)
return count + 3;
else if (n == 871 || n == 872 || n == 45361 || n == 45362)
return count + 2;
}
return -1;
}
int main()
{
int count = 0;
assert(NonRepeatLength(69) == 5);
assert(NonRepeatLength(78) == 4);
for (int i = 3; i != 1000000; ++i)
{
if (NonRepeatLength(i) == 60)
++count;
}
std::cout << count << std::endl;
return 0;
}
| 19.770833 | 69 | 0.42255 | voltrevo |
d23165a566a38bd2b648ef2b69ff4cab9d235301 | 7,215 | cpp | C++ | Source/Renderer.cpp | cstechfoodie/COMP371-Computer-Graphic-Scence-of-End-of-the-World | 91e47546d663e079b756fd90dab14c8954903a5a | [
"MIT"
] | 2 | 2019-08-09T00:54:29.000Z | 2020-11-16T22:49:27.000Z | Source/Renderer.cpp | cstechfoodie/COMP371-Computer-Graphic-Scence-of-End-of-the-World | 91e47546d663e079b756fd90dab14c8954903a5a | [
"MIT"
] | null | null | null | Source/Renderer.cpp | cstechfoodie/COMP371-Computer-Graphic-Scence-of-End-of-the-World | 91e47546d663e079b756fd90dab14c8954903a5a | [
"MIT"
] | 2 | 2019-08-08T13:42:35.000Z | 2019-08-09T22:20:41.000Z | //
// COMP 371 Assignment Framework
//
// Created by Nicolas Bergeron on 8/7/14.
// Updated by Gary Chang on 14/1/15
//
// Copyright (c) 2014-2019 Concordia University. All rights reserved.
//
#include "Renderer.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
#include <stdlib.h>
#include <string.h>
#include "Renderer.h"
#include "EventManager.h"
#include <GLFW/glfw3.h>
#if defined(PLATFORM_OSX)
#define fscanf_s fscanf
#endif
std::vector<unsigned int> Renderer::sShaderProgramID;
unsigned int Renderer::sCurrentShader;
GLFWwindow* Renderer::spWindow = nullptr;
void Renderer::Initialize()
{
spWindow = EventManager::GetWindow();
glfwMakeContextCurrent(spWindow);
// Initialize GLEW
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
getchar();
exit(-1);
}
// Somehow, glewInit triggers a glInvalidEnum... Let's ignore it
glGetError();
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// Enable depth test
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
CheckForErrors();
// Loading Shaders
#if defined(PLATFORM_OSX)
std::string shaderPathPrefix = "Shaders/";
#else
std::string shaderPathPrefix = "../Assets/Shaders/";
#endif
sShaderProgramID.push_back(
LoadShaders(shaderPathPrefix + "SolidColor.vertexshader",
shaderPathPrefix + "SolidColor.fragmentshader")
);
sShaderProgramID.push_back(
LoadShaders(shaderPathPrefix + "PathLines.vertexshader",
shaderPathPrefix + "PathLines.fragmentshader")
);
sShaderProgramID.push_back(
LoadShaders(shaderPathPrefix + "SolidColor.vertexshader",
shaderPathPrefix + "BlueColor.fragmentshader")
);
sShaderProgramID.push_back(
LoadShaders(shaderPathPrefix + "Texture.vertexshader",
shaderPathPrefix + "Texture.fragmentshader")
);
sCurrentShader = 0;
}
void Renderer::Shutdown()
{
// Shaders
for (vector<unsigned int>::iterator it = sShaderProgramID.begin(); it < sShaderProgramID.end(); ++it)
{
glDeleteProgram(*it);
}
sShaderProgramID.clear();
// Managed by EventManager
spWindow = nullptr;
}
void Renderer::BeginFrame()
{
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Renderer::EndFrame()
{
// Swap buffers
glfwSwapBuffers(spWindow);
CheckForErrors();
}
void Renderer::SetShader(ShaderType type)
{
if (type < (int) sShaderProgramID.size())
{
sCurrentShader = type;
}
}
//
// The following code is taken from
// www.opengl-tutorial.org
//
GLuint Renderer::LoadShaders(std::string vertex_shader_path,std::string fragment_shader_path)
{
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream(vertex_shader_path, std::ios::in);
if(VertexShaderStream.is_open()){
std::string Line = "";
while(getline(VertexShaderStream, Line))
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
}else{
printf("Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n", vertex_shader_path.c_str());
getchar();
exit(-1);
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_shader_path, std::ios::in);
if(FragmentShaderStream.is_open()){
std::string Line = "";
while(getline(FragmentShaderStream, Line))
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
}
GLint Result = GL_FALSE;
int InfoLogLength;
// Compile Vertex Shader
printf("Compiling shader : %s\n", vertex_shader_path.c_str());
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer, nullptr);
glCompileShader(VertexShaderID);
// Check Vertex Shader
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> VertexShaderErrorMessage(InfoLogLength+1);
glGetShaderInfoLog(VertexShaderID, InfoLogLength, nullptr, &VertexShaderErrorMessage[0]);
printf("%s\n", &VertexShaderErrorMessage[0]);
}
// Compile Fragment Shader
printf("Compiling shader : %s\n", fragment_shader_path.c_str());
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, nullptr);
glCompileShader(FragmentShaderID);
// Check Fragment Shader
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> FragmentShaderErrorMessage(InfoLogLength+1);
glGetShaderInfoLog(FragmentShaderID, InfoLogLength, nullptr, &FragmentShaderErrorMessage[0]);
printf("%s\n", &FragmentShaderErrorMessage[0]);
}
// Link the program
printf("Linking program\n");
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
// Check the program
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> ProgramErrorMessage(InfoLogLength+1);
glGetProgramInfoLog(ProgramID, InfoLogLength, nullptr, &ProgramErrorMessage[0]);
printf("%s\n", &ProgramErrorMessage[0]);
}
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
bool Renderer::PrintError()
{
static bool checkForErrors = true;
//
if( !checkForErrors )
{
return false;
}
//
const char * errorString = NULL;
bool retVal = false;
switch( glGetError() )
{
case GL_NO_ERROR:
retVal = true;
break;
case GL_INVALID_ENUM:
errorString = "GL_INVALID_ENUM";
break;
case GL_INVALID_VALUE:
errorString = "GL_INVALID_VALUE";
break;
case GL_INVALID_OPERATION:
errorString = "GL_INVALID_OPERATION";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
errorString = "GL_INVALID_FRAMEBUFFER_OPERATION";
break;
case GL_OUT_OF_MEMORY:
errorString = "GL_OUT_OF_MEMORY";
break;
default:
errorString = "UNKNOWN";
break;
}
//
if( !retVal )
{
printf( "%s\n", errorString );
}
//
return retVal;
}
void Renderer::CheckForErrors()
{
while(PrintError() == false)
{
}
}
| 25.052083 | 129 | 0.666112 | cstechfoodie |
d2321a2120d72dc2323e970052e660791f3dfc54 | 12,486 | hxx | C++ | include/idocp/hybrid/hybrid_time_discretization.hxx | z8674558/idocp | 946524db7ae4591b578be2409ca619961572e7be | [
"BSD-3-Clause"
] | 43 | 2020-10-13T03:43:45.000Z | 2021-09-23T05:29:48.000Z | include/idocp/hybrid/hybrid_time_discretization.hxx | z8674558/idocp | 946524db7ae4591b578be2409ca619961572e7be | [
"BSD-3-Clause"
] | 32 | 2020-10-21T09:40:16.000Z | 2021-10-24T00:00:04.000Z | include/idocp/hybrid/hybrid_time_discretization.hxx | z8674558/idocp | 946524db7ae4591b578be2409ca619961572e7be | [
"BSD-3-Clause"
] | 4 | 2020-10-08T05:47:16.000Z | 2021-10-15T12:15:26.000Z | #ifndef IDOCP_HYBRID_TIME_DISCRETIZATION_HXX_
#define IDOCP_HYBRID_TIME_DISCRETIZATION_HXX_
#include "idocp/hybrid/hybrid_time_discretization.hpp"
#include <cassert>
namespace idocp {
inline HybridTimeDiscretization::HybridTimeDiscretization(const double T,
const int N,
const int max_events)
: T_(T),
dt_ideal_(T/N),
max_dt_(dt_ideal_-min_dt),
N_(N),
N_ideal_(N),
N_impulse_(0),
N_lift_(0),
max_events_(max_events),
contact_phase_index_from_time_stage_(N+1, 0),
impulse_index_after_time_stage_(N+1, -1),
lift_index_after_time_stage_(N+1, -1),
time_stage_before_impulse_(max_events+1, -1),
time_stage_before_lift_(max_events+1, -1),
is_time_stage_before_impulse_(N+1, false),
is_time_stage_before_lift_(N+1, false),
t_(N+1, 0),
t_impulse_(max_events+1, 0),
t_lift_(max_events+1, 0),
dt_(N+1, static_cast<double>(T/N)),
dt_aux_(max_events+1, 0),
dt_lift_(max_events+1, 0),
event_types_(2*max_events+1, DiscreteEventType::None),
sto_impulse_(max_events),
sto_lift_(max_events) {
}
inline HybridTimeDiscretization::HybridTimeDiscretization()
: T_(0),
dt_ideal_(0),
max_dt_(0),
N_(0),
N_ideal_(0),
N_impulse_(0),
N_lift_(0),
max_events_(0),
contact_phase_index_from_time_stage_(),
impulse_index_after_time_stage_(),
lift_index_after_time_stage_(),
time_stage_before_impulse_(),
time_stage_before_lift_(),
is_time_stage_before_impulse_(),
is_time_stage_before_lift_(),
t_(),
t_impulse_(),
t_lift_(),
dt_(),
dt_aux_(),
dt_lift_(),
event_types_(),
sto_impulse_(),
sto_lift_() {
}
inline HybridTimeDiscretization::~HybridTimeDiscretization() {
}
inline void HybridTimeDiscretization::discretize(
const ContactSequence& contact_sequence, const double t) {
countDiscreteEvents(contact_sequence, t);
countTimeSteps(t);
countTimeStages();
countContactPhase();
assert(isFormulationTractable());
assert(isSwitchingTimeConsistent());
}
inline int HybridTimeDiscretization::N() const {
return N_;
}
inline int HybridTimeDiscretization::N_impulse() const {
return N_impulse_;
}
inline int HybridTimeDiscretization::N_lift() const {
return N_lift_;
}
inline int HybridTimeDiscretization::N_all() const {
return (N()+1+2*N_impulse()+N_lift());
}
inline int HybridTimeDiscretization::N_ideal() const {
return N_ideal_;
}
inline int HybridTimeDiscretization::contactPhase(const int time_stage) const {
assert(time_stage >= 0);
assert(time_stage <= N());
return contact_phase_index_from_time_stage_[time_stage];
}
inline int HybridTimeDiscretization::contactPhaseAfterImpulse(
const int impulse_index) const {
return contactPhase(timeStageAfterImpulse(impulse_index));
}
inline int HybridTimeDiscretization::contactPhaseAfterLift(
const int lift_index) const {
return contactPhase(timeStageAfterLift(lift_index));
}
inline int HybridTimeDiscretization::impulseIndexAfterTimeStage(
const int time_stage) const {
assert(time_stage >= 0);
assert(time_stage < N());
return impulse_index_after_time_stage_[time_stage];
}
inline int HybridTimeDiscretization::liftIndexAfterTimeStage(
const int time_stage) const {
assert(time_stage >= 0);
assert(time_stage < N());
return lift_index_after_time_stage_[time_stage];
}
inline int HybridTimeDiscretization::timeStageBeforeImpulse(
const int impulse_index) const {
assert(impulse_index >= 0);
assert(impulse_index < N_impulse());
return time_stage_before_impulse_[impulse_index];
}
inline int HybridTimeDiscretization::timeStageAfterImpulse(
const int impulse_index) const {
return timeStageBeforeImpulse(impulse_index) + 1;
}
inline int HybridTimeDiscretization::timeStageBeforeLift(
const int lift_index) const {
assert(lift_index >= 0);
assert(lift_index < N_lift());
return time_stage_before_lift_[lift_index];
}
inline int HybridTimeDiscretization::timeStageAfterLift(
const int lift_index) const {
return timeStageBeforeLift(lift_index) + 1;
}
inline bool HybridTimeDiscretization::isTimeStageBeforeImpulse(
const int time_stage) const {
assert(time_stage >= 0);
assert(time_stage <= N());
return is_time_stage_before_impulse_[time_stage];
}
inline bool HybridTimeDiscretization::isTimeStageAfterImpulse(
const int time_stage) const {
assert(time_stage > 0);
assert(time_stage <= N());
return isTimeStageBeforeImpulse(time_stage-1);
}
inline bool HybridTimeDiscretization::isTimeStageBeforeLift(
const int time_stage) const {
assert(time_stage >= 0);
assert(time_stage <= N());
return is_time_stage_before_lift_[time_stage];
}
inline bool HybridTimeDiscretization::isTimeStageAfterLift(
const int time_stage) const {
assert(time_stage > 0);
assert(time_stage <= N());
return isTimeStageBeforeLift(time_stage-1);
}
inline double HybridTimeDiscretization::t(const int time_stage) const {
assert(time_stage >= 0);
assert(time_stage <= N());
return t_[time_stage];
}
inline double HybridTimeDiscretization::t_impulse(
const int impulse_index) const {
assert(impulse_index >= 0);
assert(impulse_index < N_impulse());
return t_impulse_[impulse_index];
}
inline double HybridTimeDiscretization::t_lift(const int lift_index) const {
assert(lift_index >= 0);
assert(lift_index < N_lift());
return t_lift_[lift_index];
}
inline double HybridTimeDiscretization::dt(const int time_stage) const {
assert(time_stage >= 0);
assert(time_stage < N());
return dt_[time_stage];
}
inline double HybridTimeDiscretization::dt_aux(const int impulse_index) const {
assert(impulse_index >= 0);
assert(impulse_index < N_impulse());
return dt_aux_[impulse_index];
}
inline double HybridTimeDiscretization::dt_lift(const int lift_index) const {
assert(lift_index >= 0);
assert(lift_index < N_lift());
return dt_lift_[lift_index];
}
inline double HybridTimeDiscretization::dt_ideal() const {
return dt_ideal_;
}
inline bool HybridTimeDiscretization::isSTOEnabledImpulse(
const int impulse_index) const {
assert(impulse_index >= 0);
assert(impulse_index < N_impulse());
return sto_impulse_[impulse_index];
}
inline bool HybridTimeDiscretization::isSTOEnabledLift(
const int lift_index) const {
assert(lift_index >= 0);
assert(lift_index < N_lift());
return sto_lift_[lift_index];
}
inline int HybridTimeDiscretization::eventIndexImpulse(
const int impulse_index) const {
assert(impulse_index >= 0);
assert(impulse_index < N_impulse());
return (contactPhaseAfterImpulse(impulse_index)-1);
}
inline int HybridTimeDiscretization::eventIndexLift(
const int lift_index) const {
assert(lift_index >= 0);
assert(lift_index < N_lift());
return (contactPhaseAfterLift(lift_index)-1);
}
inline DiscreteEventType HybridTimeDiscretization::eventType(
const int event_index) const {
assert(event_index < N_impulse()+N_lift());
return event_types_[event_index];
}
inline bool HybridTimeDiscretization::isFormulationTractable() const {
for (int i=0; i<N(); ++i) {
if (isTimeStageBeforeImpulse(i) && isTimeStageBeforeLift(i)) {
return false;
}
}
for (int i=0; i<N()-1; ++i) {
if (isTimeStageBeforeImpulse(i) && isTimeStageBeforeImpulse(i+1)) {
return false;
}
if (isTimeStageBeforeLift(i) && isTimeStageBeforeImpulse(i+1)) {
return false;
}
}
return true;
}
inline bool HybridTimeDiscretization::isSwitchingTimeConsistent() const {
for (int i=0; i<N_impulse(); ++i) {
// if (t_impulse(i) <= t(0) || t_impulse(i) >= t(N())) {
if (t_impulse(i) < t(0)+min_dt || t_impulse(i) >= t(N())-min_dt) {
return false;
}
}
for (int i=0; i<N_lift(); ++i) {
// if (t_lift(i) <= t(0) || t_lift(i) >= t(N())) {
if (t_lift(i) < t(0)+min_dt || t_lift(i) > t(N())-min_dt) {
return false;
}
}
return true;
}
inline void HybridTimeDiscretization::countDiscreteEvents(
const ContactSequence& contact_sequence, const double t) {
N_impulse_ = contact_sequence.numImpulseEvents();
assert(N_impulse_ <= max_events_);
for (int i=0; i<N_impulse_; ++i) {
t_impulse_[i] = contact_sequence.impulseTime(i);
time_stage_before_impulse_[i] = std::floor((t_impulse_[i]-t)/dt_ideal_);
sto_impulse_[i] = contact_sequence.isSTOEnabledImpulse(i);
}
N_lift_ = contact_sequence.numLiftEvents();
assert(N_lift_ <= max_events_);
for (int i=0; i<N_lift_; ++i) {
t_lift_[i] = contact_sequence.liftTime(i);
time_stage_before_lift_[i] = std::floor((t_lift_[i]-t)/dt_ideal_);
sto_lift_[i] = contact_sequence.isSTOEnabledLift(i);
}
N_ = N_ideal_;
for (int i=0; i<N_impulse_+N_lift_; ++i) {
event_types_[i] = contact_sequence.eventType(i);
}
assert(isFormulationTractable());
}
inline void HybridTimeDiscretization::countTimeSteps(const double t) {
int impulse_index = 0;
int lift_index = 0;
int num_events_on_grid = 0;
for (int i=0; i<N_ideal_; ++i) {
const int stage = i - num_events_on_grid;
if (i == time_stage_before_impulse_[impulse_index]) {
dt_[stage] = t_impulse_[impulse_index] - i * dt_ideal_ - t;
assert(dt_[stage] >= -min_dt);
assert(dt_[stage] <= dt_ideal_+min_dt);
if (dt_[stage] <= min_dt) {
time_stage_before_impulse_[impulse_index] = stage - 1;
dt_aux_[impulse_index] = dt_ideal_;
t_[stage] = t + (i-1) * dt_ideal_;
++num_events_on_grid;
++impulse_index;
}
else if (dt_[stage] >= max_dt_) {
time_stage_before_impulse_[impulse_index] = i + 1;
t_[stage] = t + i * dt_ideal_;
}
else {
time_stage_before_impulse_[impulse_index] = stage;
dt_aux_[impulse_index] = dt_ideal_ - dt_[stage];
t_[stage] = t + i * dt_ideal_;
++impulse_index;
}
}
else if (i == time_stage_before_lift_[lift_index]) {
dt_[stage] = t_lift_[lift_index] - i * dt_ideal_ - t;
assert(dt_[stage] >= -min_dt);
assert(dt_[stage] <= dt_ideal_+min_dt);
if (dt_[stage] <= min_dt) {
time_stage_before_lift_[lift_index] = stage - 1;
dt_lift_[lift_index] = dt_ideal_;
t_[stage] = t + (i-1) * dt_ideal_;
++num_events_on_grid;
++lift_index;
}
else if (dt_[stage] >= max_dt_) {
time_stage_before_lift_[lift_index] = i + 1;
t_[stage] = t + i * dt_ideal_;
}
else {
time_stage_before_lift_[lift_index] = stage;
dt_lift_[lift_index] = dt_ideal_ - dt_[stage];
t_[stage] = t + i * dt_ideal_;
++lift_index;
}
}
else {
dt_[stage] = dt_ideal_;
t_[stage] = t + i * dt_ideal_;
}
}
N_ = N_ideal_ - num_events_on_grid;
t_[N_] = t + T_;
}
inline void HybridTimeDiscretization::countTimeStages() {
int impulse_index = 0;
int lift_index = 0;
for (int i=0; i<N(); ++i) {
if (impulse_index < N_impulse()) {
if (i == timeStageBeforeImpulse(impulse_index)) {
is_time_stage_before_impulse_[i] = true;
impulse_index_after_time_stage_[i] = impulse_index;
++impulse_index;
}
else {
is_time_stage_before_impulse_[i] = false;
impulse_index_after_time_stage_[i] = -1;
}
}
else {
is_time_stage_before_impulse_[i] = false;
impulse_index_after_time_stage_[i] = -1;
}
if (lift_index < N_lift()) {
if (i == timeStageBeforeLift(lift_index)) {
is_time_stage_before_lift_[i] = true;
lift_index_after_time_stage_[i] = lift_index;
++lift_index;
}
else {
is_time_stage_before_lift_[i] = false;
lift_index_after_time_stage_[i] = -1;
}
}
else {
is_time_stage_before_lift_[i] = false;
lift_index_after_time_stage_[i] = -1;
}
}
is_time_stage_before_impulse_[N()] = false;
is_time_stage_before_lift_[N()] = false;
}
inline void HybridTimeDiscretization::countContactPhase() {
int num_events = 0;
for (int i=0; i<N(); ++i) {
contact_phase_index_from_time_stage_[i] = num_events;
if (isTimeStageBeforeImpulse(i) || isTimeStageBeforeLift(i)) {
++num_events;
}
}
contact_phase_index_from_time_stage_[N()] = num_events;
}
} // namespace idocp
#endif // IDOCP_HYBRID_TIME_DISCRETIZATION_HXX_ | 27.025974 | 80 | 0.685247 | z8674558 |
d233ce3c377159f4e760f9ceaf0322d6617761c1 | 947 | cpp | C++ | Codeforces/1283C.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | Codeforces/1283C.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | Codeforces/1283C.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int arr[200000];
bool received[200000];
bool notYet[200000];
set<int> ungifted;
set<int> undecided;
int main(){
int n, i;
cin >> n;
for(i=0; i<n; i++){
cin >> arr[i];
if(arr[i]>0){
received[arr[i]-1]=true;
}
}
for(i=0; i<n; i++){
if(!received[i]){
ungifted.insert(i);
}
if(arr[i]==0){
undecided.insert(i);
}
}
auto ungiftedIt = ungifted.begin();
auto undecidedIt = undecided.rbegin();
while(ungiftedIt != ungifted.end()){
int ungifted = *ungiftedIt;
int undecided = *undecidedIt;
//cout << undecided << " to " << ungifted+1 << endl;
arr[undecided]=ungifted+1;
ungiftedIt++;
undecidedIt++;
}
for(i=0; i<n; i++){
if(arr[i]-1==i){
undecidedIt = undecided.rbegin();
if(*undecidedIt == i){
undecidedIt++;
}
arr[i]=arr[*undecidedIt];
arr[*undecidedIt]=i+1;
}
}
for(i=0; i<n; i++){
printf("%d ", arr[i]);
}
printf("\n");
return 0;
} | 18.568627 | 54 | 0.581837 | DT3264 |
d2343fd62ad6f7eaeac1d24879df504a306a0c32 | 63,957 | cpp | C++ | src/formula_object.cpp | gamobink/anura | 410721a174aae98f32a55d71a4e666ad785022fd | [
"CC0-1.0"
] | null | null | null | src/formula_object.cpp | gamobink/anura | 410721a174aae98f32a55d71a4e666ad785022fd | [
"CC0-1.0"
] | null | null | null | src/formula_object.cpp | gamobink/anura | 410721a174aae98f32a55d71a4e666ad785022fd | [
"CC0-1.0"
] | null | null | null | /*
Copyright (C) 2003-2014 by David White <davewx7@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <map>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include "base64.hpp"
#include "code_editor_dialog.hpp"
#include "compress.hpp"
#include "custom_object_functions.hpp"
#include "filesystem.hpp"
#include "formula.hpp"
#include "formula_callable.hpp"
#include "formula_callable_definition.hpp"
#include "formula_object.hpp"
#include "formula_profiler.hpp"
#include "json_parser.hpp"
#include "module.hpp"
#include "preferences.hpp"
#include "string_utils.hpp"
#include "unit_test.hpp"
#include "uuid.hpp"
#include "variant_type.hpp"
#include "variant_utils.hpp"
#ifdef USE_LUA
#include "lua_iface.hpp"
#endif
#if defined(_MSC_VER)
#define strtoll _strtoi64
#endif
PREF_BOOL(ffl_vm_opt_const_library_calls, true, "Optimize library calls");
PREF_BOOL(ffl_allow_obj_api_from_class, false, "Allow classes to have access to custom object api.");
namespace
{
game_logic::FunctionSymbolTable* getClassFunctionSymbolTable()
{
if(g_ffl_allow_obj_api_from_class) {
return &get_custom_object_functions_symbol_table();
}
return nullptr;
}
}
namespace game_logic
{
void invalidate_class_definition(const std::string& class_name);
namespace
{
variant flatten_list_of_maps(variant v) {
if(v.is_list() && v.num_elements() >= 1) {
variant result = flatten_list_of_maps(v[0]);
for(int n = 1; n < v.num_elements(); ++n) {
result = result + flatten_list_of_maps(v[n]);
}
return result;
}
return v;
}
class backup_entry_scope {
FormulaCallableDefinition::Entry backup_;
FormulaCallableDefinition::Entry& target_;
public:
backup_entry_scope(FormulaCallableDefinition::Entry& e) : backup_(e), target_(e) {
}
~backup_entry_scope() {
target_ = backup_;
}
};
ffl::IntrusivePtr<const FormulaClass> get_class(const std::string& type);
struct PropertyEntry {
PropertyEntry() : variable_slot(-1) {
}
PropertyEntry(const std::string& class_name, const std::string& prop_name, variant node, int& state_slot) : variable_slot(-1) {
name = prop_name;
name_variant = variant(name);
FormulaCallableDefinitionPtr class_def = get_class_definition(class_name);
FormulaCallableDefinition::Entry* data_entry = class_def->getEntry(class_def->getSlot("_data"));
FormulaCallableDefinition::Entry* value_entry = class_def->getEntry(class_def->getSlot("value"));
FormulaCallableDefinition::Entry* prop_entry = class_def->getEntry(class_def->getSlot(prop_name));
assert(data_entry);
assert(value_entry);
assert(prop_entry);
backup_entry_scope backup1(*data_entry);
backup_entry_scope backup2(*value_entry);
value_entry->setVariantType(prop_entry->variant_type);
*data_entry = *prop_entry;
const Formula::StrictCheckScope strict_checking;
if(node.is_string()) {
getter = game_logic::Formula::createOptionalFormula(node, getClassFunctionSymbolTable(), get_class_definition(class_name));
ASSERT_LOG(getter, "COULD NOT PARSE CLASS FORMULA " << class_name << "." << prop_name);
ASSERT_LOG(getter->queryVariantType()->is_any() == false, "COULD NOT INFER TYPE FOR CLASS PROPERTY " << class_name << "." << prop_name << ". SET THIS PROPERTY EXPLICITLY");
FormulaCallableDefinition::Entry* entry = class_def->getEntryById(prop_name);
ASSERT_LOG(entry != nullptr, "COULD NOT FIND CLASS PROPERTY ENTRY " << class_name << "." << prop_name);
entry->setVariantType(getter->queryVariantType());
return;
} else if(node.is_map()) {
if(node["variable"].as_bool(true)) {
variable_slot = state_slot++;
}
if(node["get"].is_string()) {
getter = game_logic::Formula::createOptionalFormula(node["get"], getClassFunctionSymbolTable(), get_class_definition(class_name));
}
if(node["set"].is_string()) {
setter = game_logic::Formula::createOptionalFormula(node["set"], getClassFunctionSymbolTable(), get_class_definition(class_name));
}
default_value = node["default"];
if(node["initialize"].is_string()) {
initializer = game_logic::Formula::createOptionalFormula(node["initialize"], getClassFunctionSymbolTable());
} else if(node["init"].is_string()) {
initializer = game_logic::Formula::createOptionalFormula(node["init"], getClassFunctionSymbolTable());
}
variant valid_types = node["type"];
if(valid_types.is_null() && variable_slot != -1) {
variant default_value = node["default"];
if(default_value.is_null() == false) {
valid_types = variant(variant::variant_type_to_string(default_value.type()));
}
}
if(valid_types.is_null() == false) {
get_type = parse_variant_type(valid_types);
set_type = get_type;
}
valid_types = node["set_type"];
if(valid_types.is_null() == false) {
set_type = parse_variant_type(valid_types);
}
} else {
variable_slot = state_slot++;
default_value = node;
set_type = get_type = get_variant_type_from_value(node);
}
}
std::string name;
game_logic::ConstFormulaPtr getter, setter, initializer;
variant name_variant;
variant_type_ptr get_type, set_type;
int variable_slot;
variant default_value;
};
std::map<std::string, std::string>& class_path_map()
{
static std::map<std::string, std::string> mapping;
static bool init = false;
if(!init) {
init = true;
std::map<std::string, std::string> items;
module::get_unique_filenames_under_dir("data/classes/", &items, module::MODULE_NO_PREFIX);
for(auto p : items) {
std::string key = p.first;
if(key.size() > 4 && std::equal(key.end()-4, key.end(), ".cfg")) {
key.resize(key.size()-4);
} else {
continue;
}
if(mapping.count(key) != 0) {
continue;
}
mapping[key] = p.second;
}
}
return mapping;
}
std::map<std::string, variant> class_node_map;
std::map<std::string, variant> unit_test_class_node_map;
void load_class_node(const std::string& type, const variant& node)
{
class_node_map[type] = node;
const variant classes = flatten_list_of_maps(node["classes"]);
if(classes.is_map()) {
for(variant key : classes.getKeys().as_list()) {
load_class_node(type + "." + key.as_string(), classes[key]);
}
}
}
void load_class_nodes(const std::string& type)
{
auto itor = class_path_map().find(type);
ASSERT_LOG(itor != class_path_map().end(), "Could not find FFL class '" << type << "'");
const std::string& path = itor->second;
const std::string real_path = module::map_file(path);
sys::notify_on_file_modification(real_path, std::bind(invalidate_class_definition, type));
variant v = json::parse_from_file_or_die(path);
ASSERT_LOG(v.is_map(), "COULD NOT PARSE FFL CLASS: " << type);
load_class_node(type, v);
}
variant get_class_node(const std::string& type)
{
std::map<std::string, variant>::const_iterator i = class_node_map.find(type);
if(i != class_node_map.end()) {
return i->second;
}
if (unit_test_class_node_map.size()) {
i = unit_test_class_node_map.find(type);
if (i != unit_test_class_node_map.end()) {
return i->second;
}
}
if(std::find(type.begin(), type.end(), '.') != type.end()) {
std::vector<std::string> v = util::split(type, '.');
load_class_nodes(v.front());
} else {
load_class_nodes(type);
}
i = class_node_map.find(type);
ASSERT_LOG(i != class_node_map.end(), "COULD NOT FIND CLASS: " << type);
return i->second;
}
enum CLASS_BASE_FIELDS { FIELD_PRIVATE, FIELD_VALUE, FIELD_SELF, FIELD_ME, FIELD_NEW_IN_UPDATE, FIELD_ORPHANED, FIELD_CLASS, FIELD_LIB, FIELD_UUID, NUM_BASE_FIELDS };
static const std::string BaseFields[] = {"_data", "value", "self", "me", "new_in_update", "orphaned_by_update", "_class", "lib", "_uuid"};
class FormulaClassDefinition : public FormulaCallableDefinition
{
public:
FormulaClassDefinition(const std::string& class_name, const variant& var)
: type_name_("class " + class_name)
{
setStrict();
for(int n = 0; n != NUM_BASE_FIELDS; ++n) {
properties_[BaseFields[n]] = n;
slots_.push_back(Entry(BaseFields[n]));
switch(n) {
case FIELD_PRIVATE:
slots_.back().variant_type = variant_type::get_type(variant::VARIANT_TYPE_MAP);
break;
case FIELD_VALUE:
slots_.back().variant_type = variant_type::get_any();
break;
case FIELD_SELF:
case FIELD_ME:
slots_.back().variant_type = variant_type::get_class(class_name);
break;
case FIELD_NEW_IN_UPDATE:
case FIELD_ORPHANED:
slots_.back().variant_type = variant_type::get_type(variant::VARIANT_TYPE_BOOL);
break;
case FIELD_CLASS:
slots_.back().variant_type = variant_type::get_type(variant::VARIANT_TYPE_STRING);
break;
case FIELD_LIB:
slots_.back().type_definition = get_library_definition().get();
slots_.back().variant_type = variant_type::get_builtin("library");
assert(slots_.back().variant_type);
break;
case FIELD_UUID:
slots_.back().variant_type = variant_type::get_type(variant::VARIANT_TYPE_STRING);
break;
}
}
ASSERT_LOG(var["bases"].is_null() || var["base_type"].is_null(), "MULTIPLE INHERITANT NOT YET SUPPORTED");
std::vector<variant> nodes;
nodes.push_back(var);
while(nodes.back()["bases"].is_list() && nodes.back()["bases"].num_elements() > 0) {
variant nodes_v = nodes.back()["bases"];
ASSERT_LOG(nodes_v.num_elements() == 1, "MULTIPLE INHERITANCE NOT YET SUPPORTED");
variant new_node = get_class_node(nodes_v[0].as_string());
ASSERT_LOG(std::count(nodes.begin(), nodes.end(), new_node) == 0, "RECURSIVE INHERITANCE DETECTED");
nodes.push_back(new_node);
}
std::reverse(nodes.begin(), nodes.end());
variant base_builtin = nodes.back()["base_type"];
if(base_builtin.is_string()) {
std::string builtin = base_builtin.as_string();
auto ctor = game_logic::get_callable_constructor(builtin);
ASSERT_LOG(ctor, "Base type does not have a constructor: " << builtin);
auto base = game_logic::get_formula_callable_definition(builtin);
for(int n = 0; n < base->getNumSlots(); ++n) {
const Entry* e = base->getEntry(n);
properties_[e->id] = static_cast<int>(slots_.size());
slots_.push_back(*e);
}
}
for(const variant& node : nodes) {
variant properties = node["properties"];
if(!properties.is_map()) {
properties = node;
}
for(variant key : properties.getKeys().as_list()) {
ASSERT_LOG(std::count(BaseFields, BaseFields + NUM_BASE_FIELDS, key.as_string()) == 0, "Class " << class_name << " has property '" << key.as_string() << "' which is a reserved word");
ASSERT_LOG(key.as_string() != "", "Class " << class_name << " has property name which is empty");
if(properties_.count(key.as_string()) == 0) {
properties_[key.as_string()] = static_cast<int>(slots_.size());
slots_.push_back(Entry(key.as_string()));
if(key.as_string()[0] == '_') {
slots_.back().private_counter++;
}
}
const int slot = properties_[key.as_string()];
variant prop_node = properties[key];
if(prop_node.is_map()) {
variant access = prop_node["access"];
if(access.is_null() == false) {
if(access.as_string() == "public") {
slots_[slot].private_counter = 0;
} else if(access.as_string() == "private") {
slots_[slot].private_counter = 1;
} else {
ASSERT_LOG(false, "Unknown property access specifier '" << access.as_string() << "' " << access.debug_location());
}
}
variant valid_types = prop_node["type"];
if(valid_types.is_null() && prop_node["variable"].is_bool() && prop_node["variable"].as_bool()) {
variant default_value = prop_node["default"];
if(default_value.is_null() == false) {
valid_types = variant(variant::variant_type_to_string(default_value.type()));
}
}
if(valid_types.is_null() == false) {
slots_[slot].variant_type = parse_variant_type(valid_types);
}
variant set_type = prop_node["set_type"];
if(set_type.is_null() == false) {
slots_[slot].write_type = parse_variant_type(set_type);
}
} else if(prop_node.is_string()) {
variant_type_ptr fn_type = parse_optional_function_type(prop_node);
if(fn_type) {
slots_[slot].variant_type = fn_type;
} else {
variant_type_ptr type = parse_optional_formula_type(prop_node);
if(type) {
slots_[slot].variant_type = type;
} else {
const Formula::StrictCheckScope strict_checking(false);
FormulaPtr f = Formula::createOptionalFormula(prop_node, getClassFunctionSymbolTable());
if(f) {
slots_[slot].variant_type = f->queryVariantType();
}
}
}
} else {
slots_[slot].variant_type = get_variant_type_from_value(prop_node);
}
}
}
}
virtual ~FormulaClassDefinition() {}
void init() {
for(Entry& e : slots_) {
if(e.variant_type && !e.type_definition) {
e.type_definition = e.variant_type->getDefinition();
}
}
}
virtual int getSlot(const std::string& key) const override {
std::map<std::string, int>::const_iterator itor = properties_.find(key);
if(itor != properties_.end()) {
return itor->second;
}
return -1;
}
virtual Entry* getEntry(int slot) override {
if(slot < 0 || static_cast<unsigned>(slot) >= slots_.size()) {
return nullptr;
}
return &slots_[slot];
}
virtual const Entry* getEntry(int slot) const override {
if(slot < 0 || static_cast<unsigned>(slot) >= slots_.size()) {
return nullptr;
}
return &slots_[slot];
}
virtual int getNumSlots() const override {
return static_cast<int>(slots_.size());
}
bool getSymbolIndexForSlot(int slot, int* index) const override {
return false;
}
int getBaseSymbolIndex() const override {
return 0;
}
const std::string* getTypeName() const override {
return &type_name_;
}
void pushPrivateAccess() {
for(Entry& e : slots_) {
e.private_counter--;
}
}
void popPrivateAccess() {
for(Entry& e : slots_) {
e.private_counter++;
}
}
int getSubsetSlotBase(const FormulaCallableDefinition* subset) const override
{
return -1;
}
private:
std::map<std::string, int> properties_;
std::vector<Entry> slots_;
std::string type_name_;
};
struct definition_access_private_in_scope
{
definition_access_private_in_scope(FormulaClassDefinition& def) : def_(def)
{
def_.pushPrivateAccess();
}
~definition_access_private_in_scope()
{
def_.popPrivateAccess();
}
FormulaClassDefinition& def_;
};
typedef std::map<std::string, ffl::IntrusivePtr<FormulaClassDefinition> > class_definition_map;
class_definition_map class_definitions;
typedef std::map<std::string, ffl::IntrusivePtr<FormulaClass> > classes_map;
bool in_unit_test = false;
std::vector<FormulaClass*> unit_test_queue;
}
FormulaCallableDefinitionPtr get_class_definition(const std::string& name)
{
class_definition_map::iterator itor = class_definitions.find(name);
if(itor != class_definitions.end()) {
return itor->second;
}
FormulaClassDefinition* def = new FormulaClassDefinition(name, get_class_node(name));
class_definitions[name].reset(def);
def->init();
return def;
}
class FormulaClass : public reference_counted_object
{
public:
FormulaClass(const std::string& class_name, const variant& node);
const std::function<FormulaCallablePtr(variant)>& getBuiltinCtor() const { return builtin_ctor_; }
int getBuiltinSlots() const { return builtin_slots_; }
const ConstFormulaCallableDefinitionPtr& getBuiltinDef() const { return builtin_def_; }
void setName(const std::string& name);
const std::string& name() const { return name_; }
const variant& nameVariant() const { return name_variant_; }
const variant& privateData() const { return private_data_; }
#if defined(USE_LUA)
bool has_lua() const { return !lua_node_.is_null(); }
const variant & getLuaNode() const { return lua_node_; }
const std::shared_ptr<lua::CompiledChunk> & getLuaInit( lua::LuaContext & ) const ;
#endif
const std::vector<game_logic::ConstFormulaPtr>& constructor() const { return constructor_; }
const std::map<std::string, int>& properties() const { return properties_; }
const std::vector<PropertyEntry>& slots() const { return slots_; }
const std::vector<const PropertyEntry*>& variableSlots() const { return variable_slots_; }
const classes_map& subClasses() const { return sub_classes_; }
bool isA(const std::string& name) const;
int getNstateSlots() const { return nstate_slots_; }
void build_nested_classes();
void run_unit_tests();
bool is_library_only() const { return is_library_only_; }
void update_class(FormulaClass* new_class) {
if(new_class == this) {
return;
}
new_class->previous_version_.reset(this);
for(int i = 0; i < slots_.size() && i < new_class->slots_.size(); ++i) {
if(slots_[i].name == new_class->slots_[i].name &&
slots_[i].variable_slot == new_class->slots_[i].variable_slot) {
slots_[i] = new_class->slots_[i];
}
}
if(previous_version_) {
previous_version_->update_class(this);
}
}
private:
void build_nested_classes(variant obj);
std::function<FormulaCallablePtr(variant)> builtin_ctor_;
ConstFormulaCallableDefinitionPtr builtin_def_;
int builtin_slots_;
std::string name_;
variant name_variant_;
variant private_data_;
std::vector<game_logic::ConstFormulaPtr> constructor_;
std::map<std::string, int> properties_;
std::vector<PropertyEntry> slots_;
std::vector<const PropertyEntry*> variable_slots_;
classes_map sub_classes_;
variant unit_test_;
std::vector<ffl::IntrusivePtr<const FormulaClass> > bases_;
variant nested_classes_;
ffl::IntrusivePtr<FormulaClass> previous_version_;
#if defined(USE_LUA)
// For lua integration
variant lua_node_;
mutable std::shared_ptr<lua::CompiledChunk> lua_compiled_;
#endif
int nstate_slots_;
bool is_library_only_;
};
bool is_class_derived_from(const std::string& derived, const std::string& base)
{
if(derived == base) {
return true;
}
variant v = get_class_node(derived);
if(v.is_map()) {
variant bases = v["bases"];
if(bases.is_list()) {
for(const variant& b : bases.as_list()) {
if(is_class_derived_from(b.as_string(), base)) {
return true;
}
}
}
}
return false;
}
struct DefinitionConstantFunctionResetter {
FormulaCallableDefinitionPtr def_;
DefinitionConstantFunctionResetter(FormulaCallableDefinitionPtr def) : def_(def)
{}
~DefinitionConstantFunctionResetter()
{
reset();
}
void reset() {
if(def_) {
for(int n = 0; n != def_->getNumSlots(); ++n) {
auto entry = def_->getEntry(n);
if(entry == nullptr) {
continue;
}
entry->constant_fn = std::function<bool(variant*)>();
}
def_.reset();
}
}
};
FormulaClass::FormulaClass(const std::string& class_name, const variant& node)
: builtin_slots_(0), name_(class_name), name_variant_(class_name), nstate_slots_(0), is_library_only_(false)
{
if(node["base_type"].is_string()) {
std::string builtin = node["base_type"].as_string();
builtin_ctor_ = game_logic::get_callable_constructor(builtin);
builtin_def_ = game_logic::get_formula_callable_definition(builtin);
builtin_slots_ = builtin_def_->getNumSlots();
}
variant bases_v = node["bases"];
if(bases_v.is_null() == false) {
for(int n = 0; n != bases_v.num_elements(); ++n) {
bases_.push_back(get_class(bases_v[n].as_string()));
}
}
std::map<variant, variant> m;
private_data_ = variant(&m);
for(ffl::IntrusivePtr<const FormulaClass> base : bases_) {
merge_variant_over(&private_data_, base->private_data_);
}
ASSERT_LOG(bases_.size() <= 1, "Multiple inheritance of classes not currently supported");
for(ffl::IntrusivePtr<const FormulaClass> base : bases_) {
slots_ = base->slots();
properties_ = base->properties();
nstate_slots_ = base->nstate_slots_;
builtin_ctor_ = base->builtin_ctor_;
builtin_def_ = base->builtin_def_;
builtin_slots_ = base->builtin_slots_;
}
variant properties = node["properties"];
if(!properties.is_map()) {
properties = node;
}
is_library_only_ = node["is_library"].as_bool(false);
FormulaCallableDefinitionPtr class_def = get_class_definition(class_name);
assert(class_def);
FormulaClassDefinition* class_definition = dynamic_cast<FormulaClassDefinition*>(class_def.get());
assert(class_definition);
std::vector<std::string> entries_loading;
std::map<std::string, PropertyEntry> preloaded_entries;
DefinitionConstantFunctionResetter resetter(class_def);
if(g_ffl_vm_opt_const_library_calls && is_library_only_) {
for(int n = 0; n != class_def->getNumSlots(); ++n) {
auto entry = class_def->getEntry(n);
if(entry == nullptr || entry->id.empty()) {
continue;
}
entry->constant_fn = [n,&class_def,&preloaded_entries,&entries_loading,&class_name,&properties](variant* value) {
auto entry = class_def->getEntry(n);
const std::string& id = entry->id;
if(std::count(entries_loading.begin(), entries_loading.end(), id)) {
return false;
}
int dummy_slot = 0;
const variant prop_node = properties[variant(id)];
if(prop_node.is_string() == false) {
return false;
}
PropertyEntry* e = nullptr;
auto itor = preloaded_entries.find(id);
if(itor != preloaded_entries.end()) {
e = &itor->second;
} else {
entries_loading.push_back(id);
PropertyEntry entry(class_name, id, prop_node, dummy_slot);
e = &preloaded_entries[id];
*e = entry;
entries_loading.pop_back();
}
if(e->getter && e->getter->evaluatesToConstant(*value)) {
return true;
}
return false;
};
}
}
const definition_access_private_in_scope expose_scope(*class_definition);
for(variant key : properties.getKeys().as_list()) {
entries_loading.push_back(key.as_string());
const variant prop_node = properties[key];
PropertyEntry entry;
auto itor = preloaded_entries.find(key.as_string());
if(itor != preloaded_entries.end()) {
entry = itor->second;
} else {
entry = PropertyEntry(class_name, key.as_string(), prop_node, nstate_slots_);
if(is_library_only_) {
preloaded_entries[key.as_string()] = entry;
}
}
if(properties_.count(key.as_string()) == 0) {
properties_[key.as_string()] = static_cast<int>(slots_.size());
slots_.push_back(PropertyEntry());
}
slots_[properties_[key.as_string()]] = entry;
entries_loading.pop_back();
}
resetter.reset();
for(const PropertyEntry& entry : slots_) {
if(entry.variable_slot >= 0) {
if(variable_slots_.size() < entry.variable_slot+1) {
variable_slots_.resize(entry.variable_slot+1);
}
variable_slots_[entry.variable_slot] = &entry;
}
}
ASSERT_LOG(variable_slots_.size() == nstate_slots_, "MISMATCH: " << variable_slots_.size() << " VS " << nstate_slots_);
nested_classes_ = node["classes"];
if(node["constructor"].is_string()) {
const Formula::StrictCheckScope strict_checking;
constructor_.push_back(game_logic::Formula::createOptionalFormula(node["constructor"], getClassFunctionSymbolTable(), class_def));
}
#if defined(USE_LUA)
if(node.has_key("lua")) {
lua_node_ = node["lua"];
}
#endif
unit_test_ = node["test"];
}
void FormulaClass::build_nested_classes()
{
build_nested_classes(nested_classes_);
nested_classes_ = variant();
}
void FormulaClass::build_nested_classes(variant classes)
{
if(classes.is_list()) {
for(const variant& v : classes.as_list()) {
build_nested_classes(v);
}
} else if(classes.is_map()) {
for(variant key : classes.getKeys().as_list()) {
const variant class_node = classes[key];
sub_classes_[key.as_string()].reset(new FormulaClass(name_ + "." + key.as_string(), class_node));
}
}
}
void FormulaClass::setName(const std::string& name)
{
name_ = name;
name_variant_ = variant(name);
for(classes_map::iterator i = sub_classes_.begin(); i != sub_classes_.end(); ++i) {
i->second->setName(name + "." + i->first);
}
}
bool FormulaClass::isA(const std::string& name) const
{
if(name == name_) {
return true;
}
typedef ffl::IntrusivePtr<const FormulaClass> Ptr;
for(const Ptr& base : bases_) {
if(base->isA(name)) {
return true;
}
}
return false;
}
void FormulaClass::run_unit_tests()
{
const Formula::StrictCheckScope strict_checking(false);
const Formula::NonStaticContext NonStaticContext;
if(unit_test_.is_null()) {
return;
}
if(in_unit_test) {
unit_test_queue.push_back(this);
return;
}
variant unit_test = unit_test_;
unit_test_ = variant();
in_unit_test = true;
ffl::IntrusivePtr<game_logic::MapFormulaCallable> callable(new game_logic::MapFormulaCallable);
std::map<variant,variant> attr;
callable->add("vars", variant(&attr));
callable->add("lib", variant(game_logic::get_library_object().get()));
for(int n = 0; n != unit_test.num_elements(); ++n) {
variant test = unit_test[n];
game_logic::FormulaPtr cmd = game_logic::Formula::createOptionalFormula(test["command"], getClassFunctionSymbolTable());
if(cmd) {
variant v = cmd->execute(*callable);
callable->executeCommand(v);
}
game_logic::FormulaPtr predicate = game_logic::Formula::createOptionalFormula(test["assert"]);
if(predicate) {
game_logic::FormulaPtr message = game_logic::Formula::createOptionalFormula(test["message"]);
std::string msg;
if(message) {
msg += ": " + message->execute(*callable).write_json();
}
ASSERT_LOG(predicate->execute(*callable).as_bool(), "UNIT TEST FAILURE FOR CLASS " << name_ << " TEST " << n << " FAILED: " << test["assert"].write_json() << msg << "\n");
}
}
in_unit_test = false;
for(classes_map::iterator i = sub_classes_.begin(); i != sub_classes_.end(); ++i) {
i->second->run_unit_tests();
}
if(unit_test_queue.empty() == false) {
FormulaClass* c = unit_test_queue.back();
unit_test_queue.pop_back();
c->run_unit_tests();
}
}
#ifdef USE_LUA
const std::shared_ptr<lua::CompiledChunk> & FormulaClass::getLuaInit(lua::LuaContext & ctx) const {
if (lua_compiled_) {
return lua_compiled_;
}
if (lua_node_.has_key("init")) {
lua_compiled_.reset(ctx.compileChunk(lua_node_.has_key("debug_name") ? lua_node_["debug_name"].as_string() : ("class " + name() + " lua"), lua_node_["init"].as_string()));
}
return lua_compiled_;
}
#endif
namespace
{
struct private_data_scope
{
explicit private_data_scope(int* r, int new_value) : r_(*r), old_value_(*r) {
r_ = new_value;
}
~private_data_scope() {
r_ = old_value_;
}
private:
int& r_;
int old_value_;
};
classes_map classes_, backup_classes_;
std::set<std::string> known_classes;
void record_classes(const std::string& name, const variant& node)
{
known_classes.insert(name);
const variant classes = flatten_list_of_maps(node["classes"]);
if(classes.is_map()) {
for(variant key : classes.getKeys().as_list()) {
const variant class_node = classes[key];
record_classes(name + "." + key.as_string(), class_node);
}
}
}
ffl::IntrusivePtr<FormulaClass> build_class(const std::string& type)
{
const variant v = get_class_node(type);
record_classes(type, v);
ffl::IntrusivePtr<FormulaClass> result(new FormulaClass(type, v));
result->setName(type);
return result;
}
ffl::IntrusivePtr<const FormulaClass> get_class(const std::string& type)
{
if(std::find(type.begin(), type.end(), '.') != type.end()) {
std::vector<std::string> v = util::split(type, '.');
ffl::IntrusivePtr<const FormulaClass> c = get_class(v.front());
for(unsigned n = 1; n < v.size(); ++n) {
classes_map::const_iterator itor = c->subClasses().find(v[n]);
ASSERT_LOG(itor != c->subClasses().end(), "COULD NOT FIND FFL CLASS: " << type);
c = itor->second.get();
}
return c;
}
classes_map::const_iterator itor = classes_.find(type);
if(itor != classes_.end()) {
return itor->second;
}
ffl::IntrusivePtr<FormulaClass> result;
if(!backup_classes_.empty() && backup_classes_.count(type)) {
try {
result = build_class(type);
} catch(...) {
result = backup_classes_[type];
LOG_ERROR("ERROR LOADING NEW CLASS");
}
} else {
if(preferences::edit_and_continue()) {
assert_recover_scope recover_scope;
try {
result = build_class(type);
} catch(validation_failure_exception& e) {
edit_and_continue_class(type, e.msg);
}
if(!result) {
return get_class(type);
}
} else {
result = build_class(type);
}
}
classes_[type] = result;
result->build_nested_classes();
result->run_unit_tests();
return ffl::IntrusivePtr<const FormulaClass>(result.get());
}
}
void FormulaObject::visitVariantObjects(const variant& node, const std::function<void (FormulaObject*)>& fn)
{
std::vector<FormulaObject*> seen;
visitVariantsInternal(node, fn, &seen);
}
void FormulaObject::visitVariantsInternal(const variant& node, const std::function<void (FormulaObject*)>& fn, std::vector<FormulaObject*>* seen)
{
std::vector<FormulaObject*> seen_buf;
if(!seen) {
seen = &seen_buf;
}
if(node.try_convert<FormulaObject>()) {
FormulaObject* obj = node.try_convert<FormulaObject>();
if(std::count(seen->begin(), seen->end(), obj)) {
return;
}
ConstWmlSerializableFormulaCallablePtr ptr(obj);
fn(obj);
seen->push_back(obj);
for(const variant& v : obj->variables_) {
visitVariantsInternal(v, fn, seen);
}
seen->pop_back();
return;
}
if(node.is_list()) {
for(const variant& item : node.as_list()) {
FormulaObject::visitVariantsInternal(item, fn, seen);
}
} else if(node.is_map()) {
for(const variant_pair& item : node.as_map()) {
FormulaObject::visitVariantsInternal(item.second, fn, seen);
}
}
}
void FormulaObject::visitVariants(const variant& node, const std::function<void (variant)>& fn)
{
std::vector<FormulaObject*> seen;
visitVariantsInternal(node, fn, &seen);
}
void FormulaObject::visitVariantsInternal(const variant& node, const std::function<void (variant)>& fn, std::vector<FormulaObject*>* seen)
{
std::vector<FormulaObject*> seen_buf;
if(!seen) {
seen = &seen_buf;
}
if(node.try_convert<FormulaObject>()) {
FormulaObject* obj = node.try_convert<FormulaObject>();
if(std::count(seen->begin(), seen->end(), obj)) {
return;
}
ConstWmlSerializableFormulaCallablePtr ptr(obj);
fn(node);
seen->push_back(obj);
for(const variant& v : obj->variables_) {
visitVariantsInternal(v, fn, seen);
}
seen->pop_back();
return;
}
fn(node);
if(node.is_list()) {
for(const variant& item : node.as_list()) {
FormulaObject::visitVariantsInternal(item, fn, seen);
}
} else if(node.is_map()) {
for(const variant_pair& item : node.as_map()) {
FormulaObject::visitVariantsInternal(item.second, fn, seen);
}
}
}
void FormulaObject::update(FormulaObject& updated)
{
std::vector<ffl::IntrusivePtr<FormulaObject> > objects;
std::map<boost::uuids::uuid, FormulaObject*> src, dst;
{
formula_profiler::Instrument instrument("UPDATE_A");
visitVariantObjects(variant(this), [&dst,&objects](FormulaObject* obj) {
dst[obj->uuid()] = obj;
objects.push_back(obj);
});
visitVariantObjects(variant(&updated), [&src,&objects](FormulaObject* obj) {
src[obj->uuid()] = obj;
objects.push_back(obj);
});
}
std::map<FormulaObject*, FormulaObject*> mapping;
{
formula_profiler::Instrument instrument("UPDATE_B");
for(auto& i : src) {
auto j = dst.find(i.first);
if(j != dst.end()) {
mapping[i.second] = j->second;
}
}
}
{
formula_profiler::Instrument instrument("UPDATE_C");
std::set<FormulaObject*> seen;
for(auto& i : src) {
variant v(i.second);
mapObjectIntoDifferentTree(v, mapping, seen);
}
}
{
formula_profiler::Instrument instrument("UPDATE_D");
for(auto& i : mapping) {
*i.second = *i.first;
}
for(auto& i : dst) {
if(src.count(i.first) == 0) {
i.second->orphaned_ = true;
i.second->new_in_update_ = false;
}
}
for(auto i = src.begin(); i != src.end(); ++i) {
i->second->new_in_update_ = dst.count(i->first) == 0;
}
}
}
variant FormulaObject::generateDiff(variant before, variant b)
{
variant a = deepClone(before);
std::vector<ffl::IntrusivePtr<FormulaObject> > objects;
std::map<boost::uuids::uuid, FormulaObject*> src, dst;
visitVariants(b, [&dst,&objects](variant v) {
FormulaObject* obj = v.try_convert<FormulaObject>();
if(obj) {
dst[obj->uuid()] = obj;
objects.push_back(obj);
}});
visitVariants(a, [&src,&objects](variant v) {
FormulaObject* obj = v.try_convert<FormulaObject>();
if(obj) {
src[obj->uuid()] = obj;
objects.push_back(obj);
}});
std::map<FormulaObject*, FormulaObject*> mapping;
for(auto i = src.begin(); i != src.end(); ++i) {
auto j = dst.find(i->first);
if(j != dst.end()) {
mapping[i->second] = j->second;
}
}
std::vector<variant> deltas;
std::set<FormulaObject*> seen;
for(auto i = src.begin(); i != src.end(); ++i) {
variant v(i->second);
mapObjectIntoDifferentTree(v, mapping, seen);
auto j = dst.find(i->first);
if(j != dst.end() && i->second->variables_ != j->second->variables_) {
std::map<variant, variant> node_delta;
node_delta[variant("_uuid")] = variant(write_uuid(i->second->uuid()));
if(i->second->variables_.size() < j->second->variables_.size()) {
i->second->variables_.resize(j->second->variables_.size());
}
if(j->second->variables_.size() < i->second->variables_.size()) {
j->second->variables_.resize(i->second->variables_.size());
}
for(int n = 0; n != j->second->variables_.size(); ++n) {
if(i->second->variables_[n] != j->second->variables_[n]) {
for(const PropertyEntry& e : i->second->class_->slots()) {
if(e.variable_slot == n) {
node_delta[e.name_variant] = j->second->variables_[n];
break;
}
}
}
}
deltas.push_back(variant(&node_delta));
}
}
std::vector<variant> new_objects;
for(auto i = dst.begin(); i != dst.end(); ++i) {
if(src.find(i->first) == src.end()) {
new_objects.push_back(i->second->serializeToWml());
}
}
variant_builder builder;
builder.add("deltas", variant(&deltas));
builder.add("objects", variant(&new_objects));
std::string res_doc = builder.build().write_json();
std::vector<char> data(res_doc.begin(), res_doc.end());
std::vector<char> compressed = base64::b64encode(zip::compress(data));
variant_builder result;
result.add("delta", std::string(compressed.begin(), compressed.end()));
result.add("size", static_cast<int>(res_doc.size()));
return result.build();
}
void FormulaObject::applyDiff(variant delta)
{
std::map<boost::uuids::uuid, FormulaObject*> objects;
visitVariants(variant(this), [&objects](variant v) {
FormulaObject* obj = v.try_convert<FormulaObject>();
if(obj) {
objects[obj->uuid()] = obj;
}});
const std::string& data_str = delta["delta"].as_string();
std::vector<char> data_buf(data_str.begin(), data_str.end());
const int data_size = delta["size"].as_int();
std::vector<char> data = zip::decompress_known_size(base64::b64decode(data_buf), data_size);
const game_logic::wmlFormulaCallableReadScope read_scope;
for(auto p : objects) {
game_logic::wmlFormulaCallableReadScope::registerSerializedObject(p.second->uuid(), p.second);
}
variant v = json::parse(std::string(data.begin(), data.end()));
for(variant obj_node : v["objects"].as_list()) {
game_logic::WmlSerializableFormulaCallablePtr obj = obj_node.try_convert<game_logic::WmlSerializableFormulaCallable>();
ASSERT_LOG(obj.get() != NULL, "ILLEGAL OBJECT FOUND IN SERIALIZATION");
game_logic::wmlFormulaCallableReadScope::registerSerializedObject(obj->uuid(), obj);
}
for(variant d : v["deltas"].as_list()) {
boost::uuids::uuid id = read_uuid(d["_uuid"].as_string());
auto obj_itor = objects.find(id);
ASSERT_LOG(obj_itor != objects.end(), "Could not find expected object id when applying delta: " << d.write_json());
for(auto p : d.as_map()) {
const std::string& attr = p.first.as_string();
if(attr == "_uuid") {
continue;
}
auto prop_itor = obj_itor->second->class_->properties().find(attr);
ASSERT_LOG(prop_itor != obj_itor->second->class_->properties().end(), "Unknown property '" << attr << "' in delta: " << d.write_json());
obj_itor->second->variables_[obj_itor->second->class_->slots()[prop_itor->second].variable_slot] = p.second;
}
}
}
void FormulaObject::mapObjectIntoDifferentTree(variant& v, const std::map<FormulaObject*, FormulaObject*>& mapping, std::set<FormulaObject*>& seen)
{
if(v.try_convert<FormulaObject>()) {
FormulaObject* obj = v.try_convert<FormulaObject>();
auto itor = mapping.find(obj);
if(itor != mapping.end()) {
v = variant(itor->second);
}
if(seen.count(obj)) {
return;
}
seen.insert(obj);
for(variant& v : obj->variables_) {
mapObjectIntoDifferentTree(v, mapping, seen);
}
return;
}
if(v.is_list()) {
std::vector<variant> result;
for(const variant& item : v.as_list()) {
result.push_back(item);
FormulaObject::mapObjectIntoDifferentTree(result.back(), mapping, seen);
}
v = variant(&result);
} else if(v.is_map()) {
std::map<variant, variant> result;
for(const variant_pair& item : v.as_map()) {
variant key = item.first;
variant value = item.second;
FormulaObject::mapObjectIntoDifferentTree(key, mapping, seen);
FormulaObject::mapObjectIntoDifferentTree(value, mapping, seen);
result[key] = value;
}
v = variant(&result);
}
}
variant FormulaObject::deepClone(variant v)
{
std::map<FormulaObject*,FormulaObject*> mapping;
return deepClone(v, mapping);
}
variant FormulaObject::deepClone(variant v, std::map<FormulaObject*,FormulaObject*>& mapping)
{
if(v.is_callable()) {
FormulaObject* obj = v.try_convert<FormulaObject>();
if(obj) {
std::map<FormulaObject*,FormulaObject*>::iterator itor = mapping.find(obj);
if(itor != mapping.end()) {
return variant(itor->second);
}
ffl::IntrusivePtr<FormulaObject> duplicate = obj->clone();
mapping[obj] = duplicate.get();
for(int n = 0; n != duplicate->variables_.size(); ++n) {
duplicate->variables_[n] = deepClone(duplicate->variables_[n], mapping);
}
return variant(duplicate.get());
} else {
return v;
}
} else if(v.is_list()) {
std::vector<variant> items;
for(int n = 0; n != v.num_elements(); ++n) {
items.push_back(deepClone(v[n], mapping));
}
return variant(&items);
} else if(v.is_map()) {
std::map<variant, variant> m;
for(const variant::map_pair& p : v.as_map()) {
m[deepClone(p.first, mapping)] = deepClone(p.second, mapping);
}
return variant(&m);
} else {
return v;
}
}
void FormulaObject::deepDestroy(variant v)
{
std::set<FormulaObject*> seen;
deepDestroy(v, seen);
}
void FormulaObject::deepDestroy(variant v, std::set<FormulaObject*>& seen)
{
if(v.is_callable()) {
FormulaObject* obj = v.try_convert<FormulaObject>();
if(obj) {
if(seen.insert(obj).second == false) {
return;
}
for(variant& var : obj->variables_) {
deepDestroy(var, seen);
var = variant();
}
}
} else if(v.is_list()) {
for(int n = 0; n != v.num_elements(); ++n) {
deepDestroy(v[n], seen);
}
} else if(v.is_map()) {
for(auto p : v.as_map()) {
deepDestroy(p.second, seen);
}
}
}
void FormulaObject::reloadClasses()
{
classes_.clear();
}
void FormulaObject::loadAllClasses()
{
for(auto p : class_path_map()) {
variant node = json::parse_from_file(p.second);
if(node["server_only"].as_bool(false) == false) {
get_class(p.first);
}
}
}
void FormulaObject::tryLoadClass(const std::string& name)
{
build_class(name);
}
ffl::IntrusivePtr<FormulaObject> FormulaObject::create(const std::string& type, variant args)
{
const Formula::StrictCheckScope strict_checking;
ffl::IntrusivePtr<FormulaObject> res(new FormulaObject(type, args));
res->callConstructors(args);
res->validate();
return res;
}
FormulaObject::FormulaObject(const std::string& type, variant args)
: new_in_update_(true), orphaned_(false),
class_(get_class(type)), private_data_(-1)
{
ASSERT_LOG(class_->is_library_only() == false || args.is_null(), "Creating instance of library class is illegal: " << type);
}
void FormulaObject::surrenderReferences(GarbageCollector* collector)
{
collector->surrenderVariant(&tmp_value_, "TMP");
const std::vector<const PropertyEntry*>& entries = class_->variableSlots();
int index = 0;
for(variant& v : variables_) {
collector->surrenderVariant(&v, entries[index] ? entries[index]->name.c_str() : nullptr);
++index;
}
}
std::string FormulaObject::debugObjectName() const
{
return "class " + class_->name();
}
std::string FormulaObject::write_id() const
{
std::string result = write_uuid(uuid());
result.resize(15);
return result;
}
bool FormulaObject::isA(const std::string& class_name) const
{
return class_->isA(class_name);
}
const std::string& FormulaObject::getClassName() const
{
return class_->name();
}
void FormulaObject::callConstructors(variant args)
{
if(class_->getBuiltinCtor()) {
builtin_base_ = class_->getBuiltinCtor()(args);
}
variables_.resize(class_->getNstateSlots());
for(const PropertyEntry& slot : class_->slots()) {
if(slot.variable_slot != -1) {
if(slot.initializer) {
variables_[slot.variable_slot] = slot.initializer->execute(*this);
} else {
variables_[slot.variable_slot] = deep_copy_variant(slot.default_value);
}
}
}
#if defined(USE_LUA)
init_lua();
#endif
if(args.is_map()) {
ConstFormulaCallableDefinitionPtr def = get_class_definition(class_->name());
for(const variant& key : args.getKeys().as_list()) {
std::map<std::string, int>::const_iterator itor = class_->properties().find(key.as_string());
if(itor != class_->properties().end() && class_->slots()[itor->second].setter.get() == nullptr && class_->slots()[itor->second].variable_slot == -1) {
if(property_overrides_.size() <= static_cast<unsigned>(itor->second)) {
property_overrides_.resize(itor->second+1);
}
//A read-only property. Set the formula to what is passed in.
FormulaPtr f(new Formula(args[key], getClassFunctionSymbolTable(), def));
const FormulaCallableDefinition::Entry* entry = def->getEntryById(key.as_string());
ASSERT_LOG(entry, "COULD NOT FIND ENTRY IN CLASS DEFINITION: " << key.as_string());
if(entry->variant_type) {
ASSERT_LOG(variant_types_compatible(entry->variant_type, f->queryVariantType()), "ERROR: property override in instance of class " << class_->name() << " has mis-matched type for property " << key.as_string() << ": " << entry->variant_type->to_string() << " doesn't match " << f->queryVariantType()->to_string() << " at " << args[key].debug_location());
}
property_overrides_[itor->second] = f;
} else {
setValue(key.as_string(), args[key]);
}
}
}
for(const game_logic::ConstFormulaPtr f : class_->constructor()) {
executeCommand(f->execute(*this));
}
}
FormulaObject::FormulaObject(variant data)
: WmlSerializableFormulaCallable(data["_uuid"].is_string() ? read_uuid(data["_uuid"].as_string()) : generate_uuid()), new_in_update_(true), orphaned_(false),
class_(get_class(data["@class"].as_string())), private_data_(-1)
{
if(class_->getBuiltinCtor()) {
builtin_base_ = class_->getBuiltinCtor()(data);
}
variables_.resize(class_->getNstateSlots());
if(data.is_map() && data["state"].is_map()) {
const std::map<variant,variant>& state_map = data["state"].as_map();
for(const PropertyEntry& entry : class_->slots()) {
if(entry.variable_slot == -1) {
continue;
}
auto itor = state_map.find(entry.name_variant);
if(itor != state_map.end()) {
variables_[entry.variable_slot] = itor->second;
} else {
variables_[entry.variable_slot] = entry.default_value;
}
}
/*
for(auto& p : state.as_map()) {
std::map<std::string, int>::const_iterator itor = class_->properties().find(p.first.as_string());
ASSERT_LOG(itor != class_->properties().end(), "No property " << p.first.as_string() << " in class " << class_->name());
const PropertyEntry& entry = class_->slots()[itor->second];
ASSERT_NE(entry.variable_slot, -1);
variables_[entry.variable_slot] = p.second;
}
*/
}
if(data.is_map() && data["property_overrides"].is_map()) {
for(const std::pair<const variant,variant>& p : data["property_overrides"].as_map()) {
const std::string& key = p.first.as_string();
std::map<std::string, int>::const_iterator itor = class_->properties().find(key);
ASSERT_LOG(itor != class_->properties().end(), "UNKNOWN PROPERTY ACCESS " << key << " IN CLASS " << class_->name() << "\nFORMULA LOCATION: " << get_call_stack());
if(property_overrides_.size() <= itor->second) {
property_overrides_.resize(itor->second+1);
}
property_overrides_[itor->second] = FormulaPtr(new Formula(p.second, getClassFunctionSymbolTable()));
}
}
#if defined(USE_LUA)
init_lua();
#endif
}
FormulaObject::~FormulaObject()
{}
ffl::IntrusivePtr<FormulaObject> FormulaObject::clone() const
{
ffl::IntrusivePtr<FormulaObject> result(new FormulaObject(*this));
return result;
}
variant FormulaObject::serializeToWml() const
{
std::map<variant, variant> result;
result[variant("@class")] = variant(class_->name());
result[variant("_uuid")] = variant(write_uuid(uuid()));
std::map<variant,variant> state;
for(const PropertyEntry& slot : class_->slots()) {
const int nstate_slot = slot.variable_slot;
if(nstate_slot != -1 && static_cast<unsigned>(nstate_slot) < variables_.size() && variables_[nstate_slot] != slot.default_value) {
state[variant(slot.name)] = variables_[nstate_slot];
}
}
result[variant("state")] = variant(&state);
if(property_overrides_.empty() == false) {
std::map<variant,variant> properties;
for(int n = 0; n < property_overrides_.size(); ++n) {
if(!property_overrides_[n]) {
continue;
}
const PropertyEntry& entry = class_->slots()[n];
auto debug_info = property_overrides_[n]->strVal().get_debug_info();
if(debug_info && debug_info->filename) {
std::ostringstream s;
s << "@str_with_debug " << *debug_info->filename << ":" << debug_info->line << "|" << property_overrides_[n]->str();
properties[entry.name_variant] = variant(s.str());
} else {
properties[entry.name_variant] = variant(property_overrides_[n]->str());
}
}
result[variant("property_overrides")] = variant(&properties);
}
return variant(&result);
}
REGISTER_SERIALIZABLE_CALLABLE(FormulaObject, "@class");
bool FormulaObject::getConstantValue(const std::string& id, variant* result) const
{
std::map<std::string, int>::const_iterator itor = class_->properties().find(id);
if(itor == class_->properties().end()) {
return false;
}
ConstFormulaPtr getter;
if(static_cast<unsigned>(itor->second) < property_overrides_.size()) {
getter = property_overrides_[itor->second];
}
if(!getter) {
const PropertyEntry& entry = class_->slots()[itor->second];
getter = entry.getter;
}
if(getter && getter->evaluatesToConstant(*result)) {
return true;
}
return false;
}
variant FormulaObject::getValue(const std::string& key) const
{
{
if(key == "_data") {
ASSERT_NE(private_data_, -1);
return variables_[private_data_];
} else if(key == "value") {
return tmp_value_;
}
}
if(key == "self" || key == "me") {
return variant(this);
}
if(key == "_class") {
return class_->nameVariant();
}
if(key == "lib") {
return variant(get_library_object().get());
}
if(key == "_uuid") {
return variant(write_uuid(uuid()));
}
auto def = class_->getBuiltinDef();
if(def) {
const int slot = def->getSlot(key);
if(slot >= 0) {
return builtin_base_->queryValueBySlot(slot);
}
}
std::map<std::string, int>::const_iterator itor = class_->properties().find(key);
ASSERT_LOG(itor != class_->properties().end(), "UNKNOWN PROPERTY ACCESS " << key << " IN CLASS " << class_->name() << "\nFORMULA LOCATION: " << get_call_stack());
if(static_cast<unsigned>(itor->second) < property_overrides_.size() && property_overrides_[itor->second]) {
return property_overrides_[itor->second]->execute(*this);
}
const PropertyEntry& entry = class_->slots()[itor->second];
if(entry.getter) {
private_data_scope scope(&private_data_, entry.variable_slot);
return entry.getter->execute(*this);
} else if(entry.variable_slot != -1) {
return variables_[entry.variable_slot];
} else {
ASSERT_LOG(false, "ILLEGAL READ PROPERTY ACCESS OF NON-READABLE VARIABLE " << key << " IN CLASS " << class_->name());
}
}
variant FormulaObject::getValueBySlot(int slot) const
{
switch(slot) {
case FIELD_PRIVATE: {
ASSERT_NE(private_data_, -1);
return variables_[private_data_];
}
case FIELD_VALUE: return tmp_value_;
case FIELD_SELF:
case FIELD_ME: return variant(this);
case FIELD_NEW_IN_UPDATE: return variant::from_bool(new_in_update_);
case FIELD_ORPHANED: return variant::from_bool(orphaned_);
case FIELD_CLASS: return class_->nameVariant();
case FIELD_LIB: return variant(get_library_object().get());
case FIELD_UUID: return variant(write_uuid(uuid()));
default: break;
}
slot -= NUM_BASE_FIELDS;
if(slot < class_->getBuiltinSlots()) {
return builtin_base_->queryValueBySlot(slot);
}
slot -= class_->getBuiltinSlots();
ASSERT_LOG(slot >= 0 && static_cast<unsigned>(slot) < class_->slots().size(), "ILLEGAL VALUE QUERY TO FORMULA OBJECT: " << slot << " IN " << class_->name());
if(static_cast<unsigned>(slot) < property_overrides_.size() && property_overrides_[slot]) {
return property_overrides_[slot]->execute(*this);
}
const PropertyEntry& entry = class_->slots()[slot];
if(entry.getter) {
private_data_scope scope(&private_data_, entry.variable_slot);
return entry.getter->execute(*this);
} else if(entry.variable_slot != -1) {
return variables_[entry.variable_slot];
} else {
ASSERT_LOG(false, "ILLEGAL READ PROPERTY ACCESS OF NON-READABLE VARIABLE IN CLASS " << class_->name());
}
}
void FormulaObject::setValue(const std::string& key, const variant& value)
{
if(private_data_ != -1 && key == "_data") {
variables_[private_data_] = value;
return;
}
auto def = class_->getBuiltinDef();
if(def) {
const int slot = def->getSlot(key);
if(slot >= 0) {
builtin_base_->mutateValueBySlot(slot, value);
return;
}
}
std::map<std::string, int>::const_iterator itor = class_->properties().find(key);
ASSERT_LOG(itor != class_->properties().end(), "UNKNOWN PROPERTY ACCESS " << key << " IN CLASS " << class_->name());
setValueBySlot(itor->second+class_->getBuiltinSlots()+NUM_BASE_FIELDS, value);
return;
}
void FormulaObject::setValueBySlot(int slot, const variant& value)
{
if(slot < NUM_BASE_FIELDS) {
switch(slot) {
case FIELD_PRIVATE:
ASSERT_NE(private_data_, -1);
variables_[private_data_] = value;
return;
default:
ASSERT_LOG(false, "TRIED TO SET ILLEGAL KEY IN CLASS: " << BaseFields[slot]);
}
}
slot -= NUM_BASE_FIELDS;
if(slot < class_->getBuiltinSlots()) {
builtin_base_->mutateValueBySlot(slot, value);
return;
}
slot -= class_->getBuiltinSlots();
ASSERT_LOG(slot >= 0 && static_cast<unsigned>(slot) < class_->slots().size(), "ILLEGAL VALUE SET TO FORMULA OBJECT: " << slot << " IN " << class_->name());
const PropertyEntry& entry = class_->slots()[slot];
if(entry.set_type) {
if(!entry.set_type->match(value)) {
ASSERT_LOG(false, "ILLEGAL WRITE PROPERTY ACCESS: SETTING VARIABLE " << entry.name << " OF TYPE " << entry.set_type->to_string() << " IN CLASS " << class_->name() << " TO INVALID TYPE " << variant::variant_type_to_string(value.type()) << ": " << value.write_json());
}
}
if(entry.setter) {
tmp_value_ = value;
private_data_scope scope(&private_data_, entry.variable_slot);
executeCommand(entry.setter->execute(*this));
} else if(entry.variable_slot != -1) {
variables_[entry.variable_slot] = value;
} else {
ASSERT_LOG(false, "ILLEGAL WRITE PROPERTY ACCESS OF NON-WRITABLE VARIABLE " << entry.name << " IN CLASS " << class_->name());
}
if(entry.get_type && (entry.getter || entry.setter)) {
//now that we've set the value, retrieve it and ensure it matches
//the type we expect.
variant var;
FormulaPtr override;
if(static_cast<unsigned>(slot) < property_overrides_.size()) {
override = property_overrides_[slot];
}
if(override) {
private_data_scope scope(&private_data_, entry.variable_slot);
var = override->execute(*this);
} else if(entry.getter) {
private_data_scope scope(&private_data_, entry.variable_slot);
var = entry.getter->execute(*this);
} else {
ASSERT_NE(entry.variable_slot, -1);
var = variables_[entry.variable_slot];
}
ASSERT_LOG(entry.get_type->match(var), "AFTER WRITE TO " << entry.name << " IN CLASS " << class_->name() << " TYPE IS INVALID. EXPECTED " << entry.get_type->str() << " BUT FOUND " << var.write_json());
}
}
variant_type_ptr FormulaObject::getPropertySetType(const std::string & key) const
{
std::map<std::string, int>::const_iterator itor = class_->properties().find(key);
ASSERT_LOG(itor != class_->properties().end(), "UNKNOWN PROPERTY ACCESS " << key << " IN CLASS " << class_->name());
return class_->slots()[itor->second].set_type;
}
void FormulaObject::validate() const
{
#ifndef NO_FFL_TYPE_SAFETY_CHECKS
if(preferences::type_safety_checks() == false) {
return;
}
int index = 0;
for(const PropertyEntry& entry : class_->slots()) {
if(!entry.get_type) {
++index;
continue;
}
variant value;
FormulaPtr override;
if(static_cast<unsigned>(index) < property_overrides_.size()) {
override = property_overrides_[index];
}
if(override) {
private_data_scope scope(&private_data_, entry.variable_slot);
value = override->execute(*this);
} else if(entry.getter) {
private_data_scope scope(&private_data_, entry.variable_slot);
value = entry.getter->execute(*this);
} else if(entry.variable_slot != -1) {
private_data_scope scope(&private_data_, entry.variable_slot);
value = variables_[entry.variable_slot];
} else {
++index;
continue;
}
++index;
ASSERT_LOG(entry.get_type->match(value), "OBJECT OF CLASS TYPE " << class_->name() << " HAS INVALID PROPERTY " << entry.name << ": " << value.write_json() << " EXPECTED " << entry.get_type->str() << " GIVEN TYPE " << variant::variant_type_to_string(value.type()));
}
#endif
}
void FormulaObject::getInputs(std::vector<FormulaInput>* inputs) const
{
for(const PropertyEntry& entry : class_->slots()) {
FORMULA_ACCESS_TYPE type = FORMULA_ACCESS_TYPE::READ_ONLY;
if((entry.getter && entry.setter) || entry.variable_slot != -1) {
type = FORMULA_ACCESS_TYPE::READ_WRITE;
} else if(entry.getter) {
type = FORMULA_ACCESS_TYPE::READ_ONLY;
} else if(entry.setter) {
type = FORMULA_ACCESS_TYPE::WRITE_ONLY;
} else {
continue;
}
inputs->push_back(FormulaInput(entry.name, type));
}
}
#if defined(USE_LUA)
void FormulaObject::init_lua()
{
if (class_->has_lua())
{
lua_ptr_.reset(new lua::LuaContext(*this)); // sets self object implicitly
if (auto init_script = class_->getLuaInit(*lua_ptr_)) {
init_script->run(*lua_ptr_);
}
}
}
#endif
bool formula_class_valid(const std::string& type)
{
return known_classes.count(type) != false || get_class_node(type).is_map();
}
void invalidate_class_definition(const std::string& name)
{
LOG_DEBUG("INVALIDATE CLASS: " << name);
for(auto i = class_node_map.begin(); i != class_node_map.end(); ) {
const std::string& class_name = i->first;
std::string::const_iterator dot = std::find(class_name.begin(), class_name.end(), '.');
std::string base_class(class_name.begin(), dot);
if(base_class == name) {
class_node_map.erase(i++);
} else {
++i;
}
}
for(auto i = class_definitions.begin(); i != class_definitions.end(); )
{
const std::string& class_name = i->first;
std::string::const_iterator dot = std::find(class_name.begin(), class_name.end(), '.');
std::string base_class(class_name.begin(), dot);
if(base_class == name) {
class_definitions.erase(i++);
} else {
++i;
}
}
classes_map removed_classes;
for(auto i = classes_.begin(); i != classes_.end(); )
{
const std::string& class_name = i->first;
std::string::const_iterator dot = std::find(class_name.begin(), class_name.end(), '.');
std::string base_class(class_name.begin(), dot);
if(base_class == name) {
removed_classes.insert(*i);
known_classes.erase(class_name);
backup_classes_[i->first] = i->second;
classes_.erase(i++);
} else {
++i;
}
}
for(auto p : removed_classes) {
auto new_class = get_class(p.first);
p.second->update_class(const_cast<FormulaClass*>(new_class.get()));
}
}
namespace
{
FormulaCallableDefinitionPtr g_library_definition;
}
FormulaCallableDefinitionPtr get_library_definition()
{
if(!g_library_definition) {
std::vector<std::string> classes;
for(auto p : class_path_map()) {
const std::string& class_name = p.first;
if(std::count(classes.begin(), classes.end(), class_name) == 0) {
variant node;
try {
node = json::parse_from_file(p.second);
} catch(json::ParseError& e) {
ASSERT_LOG(false, "Error parsing " << p.second << ": " << e.errorMessage());
}
if(node["server_only"].as_bool(false) == false) {
classes.push_back(class_name);
}
}
}
std::vector<variant_type_ptr> types;
for(const std::string& class_name : classes) {
types.push_back(variant_type::get_class(class_name));
}
if(!types.empty()) {
g_library_definition = game_logic::execute_command_callable_definition(&classes[0], &classes[0] + classes.size(), nullptr);
game_logic::register_formula_callable_definition("library", g_library_definition);
//first pass we have to just set the basic variant type
//without any definitions.
for(int n = 0; n != g_library_definition->getNumSlots(); ++n) {
g_library_definition->getEntry(n)->variant_type = types[n];
}
//this time we do a full set_variant_type() which looks up the
//definitions of the type. We can only do this after we have
//the first pass done though so lib types can be looked up.
for(int n = 0; n != g_library_definition->getNumSlots(); ++n) {
g_library_definition->getEntry(n)->setVariantType(types[n]);
}
} else {
g_library_definition = game_logic::execute_command_callable_definition(nullptr, nullptr, nullptr, nullptr);
}
}
return g_library_definition;
}
namespace
{
struct SlotsLoadingGuard {
explicit SlotsLoadingGuard(std::vector<int>& v) : v_(v)
{}
~SlotsLoadingGuard() { v_.pop_back(); }
std::vector<int>& v_;
};
class LibraryCallable : public game_logic::FormulaCallable
{
public:
LibraryCallable() {
items_.resize(get_library_definition()->getNumSlots());
}
bool currently_loading_library(const std::string& key) {
FormulaCallableDefinitionPtr def = get_library_definition();
const int slot = def->getSlot(key);
ASSERT_LOG(slot >= 0, "Unknown library: " << key << "\n" << get_full_call_stack());
return std::find(slots_loading_.begin(), slots_loading_.end(), slot) != slots_loading_.end();
}
private:
variant getValue(const std::string& key) const override {
FormulaCallableDefinitionPtr def = get_library_definition();
const int slot = def->getSlot(key);
ASSERT_LOG(slot >= 0, "Unknown library: " << key << "\n" << get_full_call_stack());
return queryValueBySlot(slot);
}
variant getValueBySlot(int slot) const override {
ASSERT_LOG(slot >= 0 && static_cast<unsigned>(slot) < items_.size(), "ILLEGAL LOOK UP IN LIBRARY: " << slot << "/" << items_.size());
if(items_[slot].is_null()) {
FormulaCallableDefinitionPtr def = get_library_definition();
const FormulaCallableDefinition::Entry* entry = def->getEntry(slot);
ASSERT_LOG(entry != nullptr, "INVALID SLOT: " << slot);
std::string class_name;
if(entry->variant_type->is_class(&class_name) == false) {
ASSERT_LOG(false, "ERROR IN LIBRARY");
}
slots_loading_.push_back(slot);
SlotsLoadingGuard guard(slots_loading_);
items_[slot] = variant(FormulaObject::create(class_name).get());
}
return items_[slot];
}
void surrenderReferences(GarbageCollector* collector) override {
for(variant& item : items_) {
collector->surrenderVariant(&item);
}
}
mutable std::vector<variant> items_;
mutable std::vector<int> slots_loading_;
};
}
namespace {
boost::intrusive_ptr<LibraryCallable> g_library_obj;
}
FormulaCallablePtr get_library_object()
{
if(g_library_obj.get() == nullptr) {
g_library_obj.reset(new LibraryCallable);
}
return g_library_obj;
}
bool can_load_library_instance(const std::string& id)
{
get_library_object();
return !g_library_obj->currently_loading_library(id);
}
FormulaCallablePtr get_library_instance(const std::string& id)
{
return FormulaCallablePtr(get_library_object()->queryValue(id).mutable_callable());
}
#if defined(USE_LUA)
formula_class_unit_test_helper::formula_class_unit_test_helper()
{
ASSERT_LOG(unit_test_class_node_map.size() == 0, "Tried to construct multiple helpers?");
}
formula_class_unit_test_helper::~formula_class_unit_test_helper()
{
unit_test_class_node_map.clear();
}
void formula_class_unit_test_helper::add_class_defn(const std::string & name, const variant & node) {
unit_test_class_node_map[name] = node;
}
#endif
}
| 29.338073 | 358 | 0.67106 | gamobink |
d23639af87c1f15f9c808a8fdbe311cfc4f5bd68 | 369 | cpp | C++ | Split the Str Ing.cpp | Rogg-et/codechef-challenges | 7704901eaa3928730124dd43b57f213a82d19392 | [
"MIT"
] | 2 | 2020-10-30T16:22:31.000Z | 2021-10-06T14:30:07.000Z | Split the Str Ing.cpp | Rogg-et/codechef-challenges | 7704901eaa3928730124dd43b57f213a82d19392 | [
"MIT"
] | 2 | 2021-10-08T19:49:53.000Z | 2021-10-08T19:53:56.000Z | Split the Str Ing.cpp | Rogg-et/codechef-challenges | 7704901eaa3928730124dd43b57f213a82d19392 | [
"MIT"
] | 9 | 2020-10-17T19:11:38.000Z | 2021-10-19T01:55:18.000Z | #include<iostream>
using namespace std;
int main()
{ int t;
cin>>t;
for(int i=1;i<=t;i++)
{
int n;
cin>>n;
string s;
cin>>s;
int temp=0;
for(int j=0;j<n-1;j++)
{
if(s[j]==s[n-1]) {cout<<"YES"<<endl; temp++; break;}
}
if(temp==0) cout<<"NO"<<endl;
}
return 0;
}
| 17.571429 | 62 | 0.401084 | Rogg-et |
d237711ad34268858e17823c0c3062a4c6f6f720 | 8,090 | hpp | C++ | dakota-6.3.0.Windows.x86/include/InfoBase.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | null | null | null | dakota-6.3.0.Windows.x86/include/InfoBase.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | null | null | null | dakota-6.3.0.Windows.x86/include/InfoBase.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | 1 | 2022-03-18T14:13:14.000Z | 2022-03-18T14:13:14.000Z | /*
================================================================================
PROJECT:
John Eddy's Genetic Algorithms (JEGA)
CONTENTS:
Definition of class InfoBase.
NOTES:
See notes under section "Class Definition" of this file.
PROGRAMMERS:
John Eddy (jpeddy@sandia.gov) (JE)
ORGANIZATION:
Sandia National Laboratories
COPYRIGHT:
See the LICENSE file in the top level JEGA directory.
VERSION:
1.0.0
CHANGES:
Mon Jun 09 16:33:08 2003 - Original Version (JE)
================================================================================
*/
/*
================================================================================
Document This File
================================================================================
*/
/** \file
* \brief Contains the definition of the InfoBase class.
*/
/*
================================================================================
Prevent Multiple Inclusions
================================================================================
*/
#ifndef JEGA_UTILITIES_INFOBASE_HPP
#define JEGA_UTILITIES_INFOBASE_HPP
/*
================================================================================
Includes
================================================================================
*/
// JEGAConfig.hpp should be the first include in all JEGA files.
#include <../Utilities/include/JEGAConfig.hpp>
#include <string>
#include <utilities/include/int_types.hpp>
/*
================================================================================
Pre-Namespace Forward Declares
================================================================================
*/
/*
================================================================================
Namespace Aliases
================================================================================
*/
/*
================================================================================
Begin Namespace
================================================================================
*/
namespace JEGA {
namespace Utilities {
/*
================================================================================
In-Namespace Forward Declares
================================================================================
*/
class InfoBase;
class DesignTarget;
/*
================================================================================
Class Definition
================================================================================
*/
/// Base class for information objects such as DesignVariableInfo
/**
* This class provides some information and capability common to
* all information objects.
*/
class JEGA_SL_IEDECL InfoBase
{
/*
============================================================================
Member Data Declarations
============================================================================
*/
private:
/// The DesignTarget known by this info object.
DesignTarget& _target;
/// The textual representation of the name of this info object.
std::string _label;
/// The number of this info object in the order of infos.
std::size_t _number;
/*
============================================================================
Mutators
============================================================================
*/
public:
/// Sets the "_label" member data.
/**
* \param text The new label for this info object.
*/
inline
void
SetLabel(
const std::string& text
);
/// Sets the "_number" member data.
/**
* This should generally be used only upon creation or re-ordering
* of the info objects.
*
* \param number The new number for this info object.
*/
inline
void
SetNumber(
std::size_t number
);
/*
============================================================================
Accessors
============================================================================
*/
public:
/// Returns the DesignTarget known by this object (non-const)
/**
* \return The DesignTarget being used by this info object.
*/
inline
DesignTarget&
GetDesignTarget(
);
/// Returns the DesignTarget known by this object (const)
/**
* \return The DesignTarget being used by this info object.
*/
inline
const DesignTarget&
GetDesignTarget(
) const;
/// Gets the "_label" member data.
/**
* \return The label of this information object.
*/
inline
const std::string&
GetLabel(
) const;
/// Gets the "_number" member data.
/**
* \return The number of this information object in the collection of
* all like information objects.
*/
inline
std::size_t
GetNumber(
) const;
/*
============================================================================
Public Methods
============================================================================
*/
public:
/*
============================================================================
Subclass Visible Methods
============================================================================
*/
protected:
/*
============================================================================
Subclass Overridable Methods
============================================================================
*/
public:
protected:
private:
/*
============================================================================
Private Methods
============================================================================
*/
private:
/*
============================================================================
Structors
============================================================================
*/
public:
/// Constructs an InfoBase object knowing "target".
/**
* \param target The DesignTarget for this info object to use.
*/
InfoBase(
DesignTarget& target
);
/// Copy constructs an InfoBase object.
/**
* \param copy The InfoBase object from which to copy properties into
* this.
*/
explicit
InfoBase(
const InfoBase& copy
);
/// Copy constructs an InfoBase object for use in the supplied target.
/**
* \param copy The InfoBase object from which to copy properties into
* this.
* \param target The DesignTarget for this info object to use.
*/
explicit
InfoBase(
const InfoBase& copy,
DesignTarget& target
);
/// Destructs an InfoBase object.
virtual
~InfoBase(
);
}; // class InfoBase
/*
================================================================================
End Namespace
================================================================================
*/
} // namespace Utilities
} // namespace JEGA
/*
================================================================================
Include Inlined Methods File
================================================================================
*/
#include "./inline/InfoBase.hpp.inl"
/*
================================================================================
End of Multiple Inclusion Check
================================================================================
*/
#endif // JEGA_UTILITIES_INFOBASE_HPP
| 21.864865 | 80 | 0.331397 | seakers |
d238b410650a672e3f03549f0f15011e8fcbdb69 | 39,395 | hpp | C++ | tests/functional/coherence/net/messaging/NamedCacheTest.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | tests/functional/coherence/net/messaging/NamedCacheTest.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | tests/functional/coherence/net/messaging/NamedCacheTest.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "cxxtest/TestSuite.h"
#include "coherence/lang.ns"
#include "coherence/net/DefaultOperationalContext.hpp"
#include "coherence/net/OperationalContext.hpp"
#include "coherence/run/xml/XmlElement.hpp"
#include "coherence/util/ArrayList.hpp"
#include "private/coherence/component/net/extend/RemoteNamedCache.hpp"
#include "private/coherence/component/net/extend/protocol/cache/ClearRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/ContainsAllRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/ContainsKeyRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/ContainsValueRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/GetRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/GetAllRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/NamedCacheResponse.hpp"
#include "private/coherence/component/net/extend/protocol/cache/PutRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/PutAllRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/RemoveRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/RemoveAllRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/SizeRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/service/DestroyCacheRequest.hpp"
#include "private/coherence/component/util/Peer.hpp"
#include "private/coherence/component/util/TcpInitiator.hpp"
#include "private/coherence/net/messaging/Connection.hpp"
#include "private/coherence/net/messaging/ConnectionInitiator.hpp"
#include "private/coherence/net/messaging/Message.hpp"
#include "private/coherence/util/logging/Logger.hpp"
using namespace coherence::lang;
using namespace std;
using coherence::net::DefaultOperationalContext;
using coherence::net::OperationalContext;
using coherence::util::ArrayList;
using coherence::component::net::extend::RemoteNamedCache;
using coherence::component::net::extend::protocol::cache::ClearRequest;
using coherence::component::net::extend::protocol::cache::ContainsAllRequest;
using coherence::component::net::extend::protocol::cache::ContainsKeyRequest;
using coherence::component::net::extend::protocol::cache::ContainsValueRequest;
using coherence::component::net::extend::protocol::cache::GetRequest;
using coherence::component::net::extend::protocol::cache::GetAllRequest;
using coherence::component::net::extend::protocol::cache::NamedCacheResponse;
using coherence::component::net::extend::protocol::cache::PutRequest;
using coherence::component::net::extend::protocol::cache::PutAllRequest;
using coherence::component::net::extend::protocol::cache::RemoveRequest;
using coherence::component::net::extend::protocol::cache::RemoveAllRequest;
using coherence::component::net::extend::protocol::cache::SizeRequest;
using coherence::component::net::extend::protocol::cache::service::DestroyCacheRequest;
using coherence::component::util::Peer;
using coherence::component::util::TcpInitiator;
using coherence::net::messaging::Connection;
using coherence::net::messaging::ConnectionInitiator;
using coherence::net::messaging::Message;
using coherence::run::xml::XmlElement;
using coherence::util::logging::Logger;
/**
* NamedCache Test Suite.
*/
class NamedCacheTest : public CxxTest::TestSuite
{
MemberHandle<Connection> m_hConnection;
MemberHandle<ConnectionInitiator> m_hInitiator;
MemberHandle<Channel> hNamedCacheChannel;
MemberView<Protocol::MessageFactory> vNamedCacheFactory;
MemberHandle<RemoteNamedCache::ConverterFromBinary> convFromBinary;
MemberHandle<RemoteNamedCache::ConverterValueToBinary> convToBinary;
MemberHandle<Channel> hCacheServiceChannel;
public:
NamedCacheTest()
: m_hConnection(System::common()),
m_hInitiator(System::common()),
hNamedCacheChannel(System::common()),
vNamedCacheFactory(System::common()),
convFromBinary(System::common()),
convToBinary(System::common()),
hCacheServiceChannel(System::common())
{
}
// ----- test fixtures --------------------------------------------------
public:
/**
* Runs before each test
*/
void setUp()
{
OperationalContext::View vContext = DefaultOperationalContext::create();
// Need to manage logger manually as we are not using CacheFactory
Logger::getLogger()->shutdown();
Logger::Handle hLogger = Logger::getLogger();
hLogger->configure(vContext);
hLogger->start();
stringstream ss;
ss << " <initiator-config>"
<< " <tcp-initiator>"
<< " <remote-addresses>"
<< " <socket-address>"
<< " <address system-property=\"tangosol.coherence.proxy.address\">127.0.0.1</address>"
<< " <port system-property=\"tangosol.coherence.proxy.port\">32000</port>"
<< " </socket-address>"
<< " </remote-addresses>"
<< " </tcp-initiator>"
<< " </initiator-config>";
m_hInitiator = TcpInitiator::create();
m_hInitiator->setOperationalContext(vContext);
XmlElement::Handle hXml = SimpleParser::create()->parseXml(ss);
XmlHelper::replaceSystemProperties(hXml, "system-property");
m_hInitiator->configure(hXml);
m_hInitiator->registerProtocol(CacheServiceProtocol::getInstance());
m_hInitiator->registerProtocol(NamedCacheProtocol::getInstance());
m_hInitiator->start();
m_hConnection = m_hInitiator->ensureConnection();
convFromBinary = RemoteNamedCache::ConverterFromBinary::create();
convToBinary = RemoteNamedCache::ConverterValueToBinary::create();
hCacheServiceChannel = m_hConnection->openChannel(CacheServiceProtocol::getInstance(), "CacheServiceProxy", NULL, NULL);
vNamedCacheFactory = hCacheServiceChannel->getMessageFactory();
EnsureCacheRequest::Handle hEnsureRequest = cast<EnsureCacheRequest::Handle>(vNamedCacheFactory->createMessage(EnsureCacheRequest::type_id));
hEnsureRequest->setCacheName("dist-extend-direct");
URI::View vUri = URI::create(cast<String::View>(hCacheServiceChannel->request(cast<Request::Handle>(hEnsureRequest))));
hNamedCacheChannel = m_hConnection->acceptChannel(vUri, NULL, NULL);
vNamedCacheFactory = hNamedCacheChannel->getMessageFactory();
convToBinary->setSerializer(hNamedCacheChannel->getSerializer());
convFromBinary->setSerializer(hNamedCacheChannel->getSerializer());
}
/**
* Runs after each test
*/
void tearDown()
{
ConnectionInitiator::Handle hInitiator = m_hInitiator;
if (hInitiator != NULL)
{
hInitiator->stop();
m_hInitiator = NULL;
}
Logger::getLogger()->shutdown();
}
public:
/**
* Test MessageFactory.
*/
void testMessageFactory()
{
Message::Handle hGetRequest = vNamedCacheFactory->createMessage(GetRequest::type_id);
TS_ASSERT(instanceof<GetRequest::View>(hGetRequest));
TS_ASSERT(GetRequest::type_id == hGetRequest->getTypeId());
Message::Handle hPutRequest = vNamedCacheFactory->createMessage(PutRequest::type_id);
TS_ASSERT(instanceof<PutRequest::View>(hPutRequest));
TS_ASSERT(PutRequest::type_id == hPutRequest->getTypeId());
Message::Handle hSizeRequest = vNamedCacheFactory->createMessage(SizeRequest::type_id);
TS_ASSERT(instanceof<SizeRequest::View>(hSizeRequest));
TS_ASSERT(SizeRequest::type_id == hSizeRequest->getTypeId());
Message::Handle hGetAllRequest = vNamedCacheFactory->createMessage(GetAllRequest::type_id);
TS_ASSERT(instanceof<GetAllRequest::View>(hGetAllRequest));
TS_ASSERT(GetAllRequest::type_id == hGetAllRequest->getTypeId());
Message::Handle hPutAllRequest = vNamedCacheFactory->createMessage(PutAllRequest::type_id);
TS_ASSERT(instanceof<PutAllRequest::View>(hPutAllRequest));
TS_ASSERT(PutAllRequest::type_id == hPutAllRequest->getTypeId());
Message::Handle hClearRequest = vNamedCacheFactory->createMessage(ClearRequest::type_id);
TS_ASSERT(instanceof<ClearRequest::View>(hClearRequest));
TS_ASSERT(ClearRequest::type_id == hClearRequest->getTypeId());
Message::Handle hContainsKeyRequest = vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id);
TS_ASSERT(instanceof<ContainsKeyRequest::View>(hContainsKeyRequest));
TS_ASSERT(ContainsKeyRequest::type_id == hContainsKeyRequest->getTypeId());
Message::Handle hContainsValueRequest = vNamedCacheFactory->createMessage(ContainsValueRequest::type_id);
TS_ASSERT(instanceof<ContainsValueRequest::View>(hContainsValueRequest));
TS_ASSERT(ContainsValueRequest::type_id == hContainsValueRequest->getTypeId());
Message::Handle hContainsAllRequest = vNamedCacheFactory->createMessage(ContainsAllRequest::type_id);
TS_ASSERT(instanceof<ContainsAllRequest::View>(hContainsAllRequest));
TS_ASSERT(ContainsAllRequest::type_id == hContainsAllRequest->getTypeId());
Message::Handle hRemoveRequest = vNamedCacheFactory->createMessage(RemoveRequest::type_id);
TS_ASSERT(instanceof<RemoveRequest::View>(hRemoveRequest));
TS_ASSERT(RemoveRequest::type_id == hRemoveRequest->getTypeId());
Message::Handle hRemoveAllRequest = vNamedCacheFactory->createMessage(RemoveAllRequest::type_id);
TS_ASSERT(instanceof<RemoveAllRequest::View>(hRemoveAllRequest));
TS_ASSERT(RemoveAllRequest::type_id == hRemoveAllRequest->getTypeId());
}
/**
* Test PutRequest.
*/
void testPutRequest()
{
String::Handle key = "testPutKey";
String::Handle value1 = "testPutValue1";
String::Handle value2 = "testPutValue2";
Object::Holder previousValue;
GetRequest::Handle hGetRequest = cast<GetRequest::Handle>(vNamedCacheFactory->createMessage(GetRequest::type_id));
hGetRequest->setKey(convToBinary->convert(key));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hGetRequest))->waitForResponse(-1);
if (hResponse->isFailure() == false)
{
previousValue = convFromBinary->convert(hResponse->getResult());
}
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value1));
hPutRequest->setReturnRequired(true);
OctetArrayWriteBuffer::Handle hBuf = OctetArrayWriteBuffer::create(1024);
WriteBuffer::BufferOutput::Handle hbout = hBuf->getBufferOutput();
Codec::Handle hCodec = PofCodec::create();
hCodec->encode(hNamedCacheChannel, hPutRequest, hbout);
ReadBuffer::BufferInput::Handle hbin = hBuf->getReadBuffer()->getBufferInput();
PutRequest::Handle hPutRequestResult = cast<PutRequest::Handle>(hCodec->decode(hNamedCacheChannel, hbin));
TS_ASSERT(hPutRequestResult->getExpiryDelay() == hPutRequest->getExpiryDelay());
TS_ASSERT(hPutRequestResult->isReturnRequired() == hPutRequest->isReturnRequired());
TS_ASSERT(hPutRequestResult->getValue()->equals(convToBinary->convert(value1)));
hPutRequest = hPutRequestResult;
Response::Handle hPutResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutRequest))->waitForResponse(-1);
TS_ASSERT(hPutRequest->getTypeId() == PutRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hPutResponse));
TS_ASSERT_EQUALS(7, hPutRequest->getImplVersion());
TS_ASSERT(hPutResponse->isFailure() == false);
TS_ASSERT(hPutRequest->getId() == hPutResponse->getRequestId());
TS_ASSERT(hPutResponse->getTypeId() == 0);
if (hPutRequest->isReturnRequired() == true)
{
if (previousValue == NULL)
{
TS_ASSERT(hPutResponse->getResult() == NULL);
}
else
{
TS_ASSERT(hPutResponse->getResult()->equals(convToBinary->convert(previousValue)));
}
}
hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value2));
hPutRequest->setReturnRequired(true);
hPutResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutRequest))->waitForResponse(-1);
TS_ASSERT(hPutResponse->isFailure() == false);
TS_ASSERT(hPutRequest->getId() == hPutResponse->getRequestId());
TS_ASSERT(hPutResponse->getTypeId() == 0);
if (hPutRequest->isReturnRequired() == true)
{
TS_ASSERT(value1->equals(convFromBinary->convert(hPutResponse->getResult())));
}
}
/**
* Test GetRequest.
*/
void testGetRequest()
{
String::Handle key = "testGetKey";
String::Handle value = "testGetValue";
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value));
hNamedCacheChannel->request(cast<Request::Handle>(hPutRequest));
GetRequest::Handle hGetRequest = cast<GetRequest::Handle>(vNamedCacheFactory->createMessage(GetRequest::type_id));
hGetRequest->setKey(convToBinary->convert(key));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hGetRequest))->waitForResponse(-1);
TS_ASSERT(hPutRequest->getTypeId() == PutRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hResponse));
TS_ASSERT_EQUALS(7, hGetRequest->getImplVersion());
TS_ASSERT(hResponse->isFailure() == false);
TS_ASSERT(hGetRequest->getId() == hResponse->getRequestId());
TS_ASSERT(hResponse->getTypeId() == 0);
TS_ASSERT(value->equals(convFromBinary->convert(hResponse->getResult())));
}
/**
* Test GetRequest and PutAllRequest.
*/
void testGetAndPutAllRequest()
{
ObjectArray::Handle keys = ObjectArray::create(3);
keys[0] = String::create("Goran Milosavljevic");
keys[1] = String::create("Ana Cikic");
keys[2] = String::create("Ivan Cikic");
ObjectArray::Handle values = ObjectArray::create(3);
values[0] = String::create("10.0.0.180");
values[1] = String::create("10.0.0.181");
values[2] = String::create("10.0.0.182");
HashMap::Handle addresses = HashMap::create();
addresses->put(convToBinary->convert(keys[0]), convToBinary->convert(values[0]));
addresses->put(convToBinary->convert(keys[1]), convToBinary->convert(values[1]));
addresses->put(convToBinary->convert(keys[2]), convToBinary->convert(values[2]));
PutAllRequest::Handle hPutAllRequest = cast<PutAllRequest::Handle>(vNamedCacheFactory->createMessage(PutAllRequest::type_id));
hPutAllRequest->setMap(addresses);
OctetArrayWriteBuffer::Handle hBuf = OctetArrayWriteBuffer::create(1024);
WriteBuffer::BufferOutput::Handle hbout = hBuf->getBufferOutput();
Codec::Handle hCodec = PofCodec::create();
hCodec->encode(hNamedCacheChannel, hPutAllRequest, hbout);
ReadBuffer::BufferInput::Handle hbin = hBuf->getReadBuffer()->getBufferInput();
PutAllRequest::Handle hResult = cast<PutAllRequest::Handle>(hCodec->decode(hNamedCacheChannel, hbin));
TS_ASSERT(hResult->getMap()->size() == 3);
TS_ASSERT(addresses->get(convToBinary->convert(keys[0]))->equals(hResult->getMap()->get(convToBinary->convert(keys[0]))));
TS_ASSERT(addresses->get(convToBinary->convert(keys[1]))->equals(hResult->getMap()->get(convToBinary->convert(keys[1]))));
TS_ASSERT(addresses->get(convToBinary->convert(keys[2]))->equals(hResult->getMap()->get(convToBinary->convert(keys[2]))));
hPutAllRequest = cast<PutAllRequest::Handle>(vNamedCacheFactory->createMessage(PutAllRequest::type_id));
hPutAllRequest->setMap(addresses);
Response::Handle hPutAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutAllRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hPutAllResponse));
TS_ASSERT(hPutAllResponse->isFailure() == false);
TS_ASSERT(hPutAllRequest->getId() == hPutAllResponse->getRequestId());
TS_ASSERT(hPutAllResponse->getResult() == NULL);
GetAllRequest::Handle hGetAllRequest = cast<GetAllRequest::Handle>(vNamedCacheFactory->createMessage(GetAllRequest::type_id));
ArrayList::Handle hNames = ArrayList::create();
hNames->add(convToBinary->convert(keys[1]));
hNames->add(convToBinary->convert(keys[2]));
hGetAllRequest->setKeySet(hNames);
Response::Handle hGetAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hGetAllRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hGetAllResponse));
TS_ASSERT(hGetAllResponse->isFailure() == false);
TS_ASSERT(hGetAllRequest->getId() == hGetAllResponse->getRequestId());
TS_ASSERT(hGetAllResponse->getTypeId() == 0);
TS_ASSERT(instanceof<Map::View>(hGetAllResponse->getResult()));
Map::View vResult = cast<Map::View>(hGetAllResponse->getResult());
TS_ASSERT(addresses->get(convToBinary->convert(keys[1]))->equals(vResult->get(convToBinary->convert(keys[1]))));
TS_ASSERT(addresses->get(convToBinary->convert(keys[2]))->equals(vResult->get(convToBinary->convert(keys[2]))));
}
/**
* Test SizeRequest.
*/
void testSizeRequest()
{
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hClearRequest->getTypeId() == ClearRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hResponse));
TS_ASSERT(hClearRequest->getId() == hResponse->getRequestId());
TS_ASSERT(hResponse->isFailure() == false);
SizeRequest::Handle hSizeRequest = cast<SizeRequest::Handle>(vNamedCacheFactory->createMessage(SizeRequest::type_id));
Response::Handle hSizeResponseBefore = hNamedCacheChannel->send(cast<Request::Handle>(hSizeRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hSizeResponseBefore));
TS_ASSERT(hSizeResponseBefore->isFailure() == false);
TS_ASSERT(hSizeRequest->getId() == hSizeResponseBefore->getRequestId());
TS_ASSERT(hSizeResponseBefore->getTypeId() == 0);
TS_ASSERT(instanceof<Integer32::View>(hSizeResponseBefore->getResult()));
Integer32::View sizeBefore = cast<Integer32::View>(hSizeResponseBefore->getResult());
TS_ASSERT(sizeBefore->getInt32Value() == 0);
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(String::create("newKey")));
hPutRequest->setValue(convToBinary->convert(String::create("newValue")));
hNamedCacheChannel->request(cast<Request::Handle>(hPutRequest));
hSizeRequest = cast<SizeRequest::Handle>(vNamedCacheFactory->createMessage(SizeRequest::type_id));
Response::Handle hSizeResponseAfter = hNamedCacheChannel->send(cast<Request::Handle>(hSizeRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hSizeResponseAfter));
TS_ASSERT(hSizeResponseAfter->isFailure() == false);
TS_ASSERT(hSizeRequest->getId() == hSizeResponseAfter->getRequestId());
TS_ASSERT(hSizeResponseAfter->getTypeId() == 0);
TS_ASSERT(instanceof<Integer32::View>(hSizeResponseAfter->getResult()));
Integer32::View sizeAfter = cast<Integer32::View>(hSizeResponseAfter->getResult());
TS_ASSERT(sizeAfter->getInt32Value() == 1);
}
/**
* Test NamedCache Exception.
*/
void testNamedCacheException()
{
ObjectArray::Handle keys = ObjectArray::create(3);
keys[0] = String::create("Goran Milosavljevic");
keys[1] = String::create("Ana Cikic");
keys[2] = String::create("Ivan Cikic");
ObjectArray::Handle values = ObjectArray::create(3);
values[0] = String::create("10.0.0.180");
values[1] = String::create("10.0.0.181");
values[2] = String::create("10.0.0.182");
HashMap::Handle addresses = HashMap::create();
addresses->put(convToBinary->convert(keys[0]), convToBinary->convert(values[0]));
addresses->put(convToBinary->convert(keys[1]), convToBinary->convert(values[1]));
addresses->put(convToBinary->convert(keys[2]), convToBinary->convert(values[2]));
PutAllRequest::Handle hPutAllRequest = cast<PutAllRequest::Handle>(vNamedCacheFactory->createMessage(PutAllRequest::type_id));
hPutAllRequest->setMap(addresses);
hNamedCacheChannel->request(cast<Request::Handle>(hPutAllRequest));
DestroyCacheRequest::Handle hDestroyRequest = cast<DestroyCacheRequest::Handle>(hCacheServiceChannel->getMessageFactory()->createMessage(DestroyCacheRequest::type_id));
hDestroyRequest->setCacheName("dist-extend-direct");
Response::Handle hResponse = hCacheServiceChannel->send(cast<Request::Handle>(hDestroyRequest))->waitForResponse(-1);
// the sleep was added to work around COH-4544
Thread::sleep(5000);
GetAllRequest::Handle hGetAllRequest = cast<GetAllRequest::Handle>(vNamedCacheFactory->createMessage(GetAllRequest::type_id));
ArrayList::Handle hNames = ArrayList::create();
hNames->add(convToBinary->convert(keys[1]));
hNames->add(convToBinary->convert(keys[2]));
hGetAllRequest->setKeySet(hNames);
try
{
hNamedCacheChannel->send(cast<Request::Handle>(hGetAllRequest))->waitForResponse(-1);
// should never reach here - no longer true, due to COH-8696
//TS_ASSERT(1 == 0);
}
catch(Exception::View ve)
{
TS_ASSERT(ve != NULL);
TS_ASSERT(instanceof<PortableException::View>(ve));
}
}
/**
* Test ContainsKeyRequest.
*/
void testContainsKeyRequest()
{
String::Handle key = "testContainsKeyKey";
String::Handle value = "testContainsKeyValue";
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
ContainsKeyRequest::Handle hContainsKeyRequest = cast<ContainsKeyRequest::Handle>(vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id));
hContainsKeyRequest->setKey(convToBinary->convert(key));
Response::Handle hContainsKeyResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsKeyRequest))->waitForResponse(-1);
TS_ASSERT(hContainsKeyRequest->getTypeId() == ContainsKeyRequest::type_id);
TS_ASSERT(hContainsKeyResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsKeyResponse));
TS_ASSERT(hContainsKeyResponse->isFailure() == false);
TS_ASSERT(hContainsKeyRequest->getId() == hContainsKeyResponse->getRequestId());
TS_ASSERT(instanceof<Boolean::View>(hContainsKeyResponse->getResult()));
Boolean::View vBoolResult = cast<Boolean::View>(hContainsKeyResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(false)));
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value));
hNamedCacheChannel->request(cast<Request::Handle>(hPutRequest));
hContainsKeyRequest = cast<ContainsKeyRequest::Handle>(vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id));
hContainsKeyRequest->setKey(convToBinary->convert(key));
hContainsKeyResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsKeyRequest))->waitForResponse(-1);
TS_ASSERT(hContainsKeyRequest->getTypeId() == ContainsKeyRequest::type_id);
TS_ASSERT(hContainsKeyResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsKeyResponse));
TS_ASSERT(hContainsKeyResponse->isFailure() == false);
TS_ASSERT(hContainsKeyRequest->getId() == hContainsKeyResponse->getRequestId());
TS_ASSERT(instanceof<Boolean::View>(hContainsKeyResponse->getResult()));
vBoolResult = cast<Boolean::View>(hContainsKeyResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
}
/**
* Test ContainsValueRequest.
*/
void testContainsValueRequest()
{
String::Handle key = "testContainsValueKey";
String::Handle value = "testContainsValueValue";
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
ContainsValueRequest::Handle hContainsValueRequest = cast<ContainsValueRequest::Handle>(vNamedCacheFactory->createMessage(ContainsValueRequest::type_id));
hContainsValueRequest->setValue(convToBinary->convert(value));
Response::Handle hContainsValueResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsValueRequest))->waitForResponse(-1);
TS_ASSERT(hContainsValueRequest->getTypeId() == ContainsValueRequest::type_id);
TS_ASSERT(hContainsValueResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsValueResponse));
TS_ASSERT(hContainsValueResponse->isFailure() == false);
TS_ASSERT(hContainsValueRequest->getId() == hContainsValueResponse->getRequestId());
TS_ASSERT(instanceof<Boolean::View>(hContainsValueResponse->getResult()));
Boolean::View vBoolResult = cast<Boolean::View>(hContainsValueResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(false)));
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value));
hNamedCacheChannel->request(cast<Request::Handle>(hPutRequest));
hContainsValueRequest = cast<ContainsValueRequest::Handle>(vNamedCacheFactory->createMessage(ContainsValueRequest::type_id));
hContainsValueRequest->setValue(convToBinary->convert(value));
hContainsValueResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsValueRequest))->waitForResponse(-1);
TS_ASSERT(hContainsValueRequest->getTypeId() == ContainsValueRequest::type_id);
TS_ASSERT(hContainsValueResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsValueResponse));
TS_ASSERT(hContainsValueResponse->isFailure() == false);
TS_ASSERT(hContainsValueRequest->getId() == hContainsValueResponse->getRequestId());
TS_ASSERT(instanceof<Boolean::View>(hContainsValueResponse->getResult()));
vBoolResult = cast<Boolean::View>(hContainsValueResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
}
/**
* Test RemoveRequest.
*/
void testRemoveRequest()
{
String::Handle key = "testRemoveKey";
String::Handle value = "testRemoveValue";
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value));
hPutRequest->setReturnRequired(true);
Response::Handle hPutResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutRequest))->waitForResponse(-1);
TS_ASSERT(hPutResponse->isFailure() == false);
TS_ASSERT(convFromBinary->convert(hPutResponse->getResult()) == NULL);
ContainsKeyRequest::Handle hContainsKeyRequest = cast<ContainsKeyRequest::Handle>(vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id));
hContainsKeyRequest->setKey(convToBinary->convert(key));
Response::Handle hContainsKeyResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsKeyRequest))->waitForResponse(-1);
TS_ASSERT(hContainsKeyResponse->isFailure() == false);
Boolean::View vBoolResult = cast<Boolean::View>(hContainsKeyResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
RemoveRequest::Handle hRemoveRequest = cast<RemoveRequest::Handle>(vNamedCacheFactory->createMessage(RemoveRequest::type_id));
hRemoveRequest->setKey(convToBinary->convert(key));
hRemoveRequest->setReturnRequired(true);
Response::Handle hRemoveResponse = hNamedCacheChannel->send(cast<Request::Handle>(hRemoveRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hRemoveResponse));
TS_ASSERT(hRemoveResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(hRemoveRequest->getId() == hRemoveResponse->getRequestId());
TS_ASSERT(hRemoveResponse->isFailure() == false);
if (hRemoveRequest->isReturnRequired() == true)
{
TS_ASSERT(hRemoveResponse->getResult()->equals(convToBinary->convert(value)));
}
hRemoveRequest = cast<RemoveRequest::Handle>(vNamedCacheFactory->createMessage(RemoveRequest::type_id));
OctetArrayWriteBuffer::Handle hBuf = OctetArrayWriteBuffer::create(1024);
WriteBuffer::BufferOutput::Handle hbout = hBuf->getBufferOutput();
Codec::Handle hCodec = PofCodec::create();
hRemoveRequest->setKey(convToBinary->convert(key));
hRemoveRequest->setReturnRequired(true);
hCodec->encode(hNamedCacheChannel, hRemoveRequest, hbout);
ReadBuffer::BufferInput::Handle hbin = hBuf->getReadBuffer()->getBufferInput();
RemoveRequest::Handle hRemoveResult = cast<RemoveRequest::Handle>(hCodec->decode(hNamedCacheChannel, hbin));
hRemoveRequest = cast<RemoveRequest::Handle>(vNamedCacheFactory->createMessage(RemoveRequest::type_id));
hRemoveRequest->setKey(convToBinary->convert(key));
hRemoveRequest->setReturnRequired(true);
TS_ASSERT(hRemoveRequest->isReturnRequired() == hRemoveResult->isReturnRequired());
TS_ASSERT(hRemoveRequest->getKey()->equals(hRemoveResult->getKey()));
TS_ASSERT(hRemoveRequest->getTypeId() == RemoveRequest::type_id);
hContainsKeyRequest = cast<ContainsKeyRequest::Handle>(vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id));
hContainsKeyRequest->setKey(convToBinary->convert(key));
hContainsKeyResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsKeyRequest))->waitForResponse(-1);
TS_ASSERT(hContainsKeyResponse->isFailure() == false);
TS_ASSERT(instanceof<Boolean::View>(hContainsKeyResponse->getResult()));
vBoolResult = cast<Boolean::View>(hContainsKeyResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(false)));
}
/**
* Test ContainsAllRequest and RemoveAllRequest.
*/
void testContainsAllAndRemoveAllRequest()
{
ObjectArray::Handle keys = ObjectArray::create(3);
keys[0] = String::create("Goran Milosavljevic");
keys[1] = String::create("Ana Cikic");
keys[2] = String::create("Ivan Cikic");
ObjectArray::Handle values = ObjectArray::create(3);
values[0] = String::create("10.0.0.180");
values[1] = String::create("10.0.0.181");
values[2] = String::create("10.0.0.182");
HashMap::Handle addresses = HashMap::create();
addresses->put(convToBinary->convert(keys[0]), convToBinary->convert(values[0]));
addresses->put(convToBinary->convert(keys[1]), convToBinary->convert(values[1]));
addresses->put(convToBinary->convert(keys[2]), convToBinary->convert(values[2]));
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
PutAllRequest::Handle hPutAllRequest = cast<PutAllRequest::Handle>(vNamedCacheFactory->createMessage(PutAllRequest::type_id));
hPutAllRequest->setMap(addresses);
hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutAllRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
ContainsAllRequest::Handle hContainsAllRequest = cast<ContainsAllRequest::Handle>(vNamedCacheFactory->createMessage(ContainsAllRequest::type_id));
ArrayList::Handle hList = ArrayList::create();
hList->add(convToBinary->convert(keys[0]));
hList->add(convToBinary->convert(keys[2]));
hList->add(convToBinary->convert(String::create("dummy")));
hContainsAllRequest->setKeySet(hList);
Response::Handle hContainsAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsAllRequest))->waitForResponse(-1);
TS_ASSERT(hContainsAllRequest->getTypeId() == ContainsAllRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsAllResponse));
TS_ASSERT(hContainsAllResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(hContainsAllRequest->getId() == hContainsAllResponse->getRequestId());
TS_ASSERT(hContainsAllResponse->isFailure() == false);
TS_ASSERT(instanceof<Boolean::View>(hContainsAllResponse->getResult()));
Boolean::View vBoolResult = cast<Boolean::View>(hContainsAllResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(false)));
hContainsAllRequest = cast<ContainsAllRequest::Handle>(vNamedCacheFactory->createMessage(ContainsAllRequest::type_id));
hList->remove(convToBinary->convert(String::create("dummy")));
hContainsAllRequest->setKeySet(hList);
hContainsAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsAllRequest))->waitForResponse(-1);
TS_ASSERT(hContainsAllResponse->isFailure() == false);
TS_ASSERT(instanceof<Boolean::View>(hContainsAllResponse->getResult()));
vBoolResult = cast<Boolean::View>(hContainsAllResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
RemoveAllRequest::Handle hRemoveAllRequest = cast<RemoveAllRequest::Handle>(vNamedCacheFactory->createMessage(RemoveAllRequest::type_id));
hRemoveAllRequest->setKeySet(hList);
Response::Handle hRemoveAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hRemoveAllRequest))->waitForResponse(-1);
TS_ASSERT(hRemoveAllRequest->getTypeId() == RemoveAllRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hRemoveAllResponse));
TS_ASSERT(hRemoveAllResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(hRemoveAllRequest->getId() == hRemoveAllResponse->getRequestId());
TS_ASSERT(hRemoveAllResponse->isFailure() == false);
TS_ASSERT(instanceof<Boolean::View>(hRemoveAllResponse->getResult()));
vBoolResult = cast<Boolean::View>(hRemoveAllResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
}
};
| 58.019146 | 180 | 0.666201 | chpatel3 |
d238e6d49bc7b71f72fb3d7b87c9c04e438e9638 | 1,081 | cpp | C++ | graphs/bellman-ford.cpp | KaisatoK/icpc-notebook | a9afbb35e143376947a06bc21339b5eb6b664c99 | [
"MIT"
] | 46 | 2018-01-23T01:43:23.000Z | 2020-10-03T15:16:25.000Z | graphs/bellman-ford.cpp | KaisatoK/icpc-notebook | a9afbb35e143376947a06bc21339b5eb6b664c99 | [
"MIT"
] | 1 | 2019-08-02T16:29:03.000Z | 2020-03-16T22:36:11.000Z | graphs/bellman-ford.cpp | KaisatoK/icpc-notebook | a9afbb35e143376947a06bc21339b5eb6b664c99 | [
"MIT"
] | 16 | 2018-07-12T05:30:49.000Z | 2021-02-19T01:40:49.000Z | /**********************************************************************************
* BELLMAN-FORD ALGORITHM (SHORTEST PATH TO A VERTEX - WITH NEGATIVE COST) *
* Time complexity: O(VE) *
* Usage: dist[node] *
* Notation: m: number of edges *
* n: number of vertices *
* (a, b, w): edge between a and b with weight w *
* s: starting node *
**********************************************************************************/
const int N = 1e4+10; // Maximum number of nodes
vector<int> adj[N], adjw[N];
int dist[N], v, w;
memset(dist, 63, sizeof(dist));
dist[0] = 0;
for (int i = 0; i < n-1; ++i)
for (int u = 0; u < n; ++u)
for (int j = 0; j < adj[u].size(); ++j)
v = adj[u][j], w = adjw[u][j],
dist[v] = min(dist[v], dist[u]+w);
| 51.47619 | 83 | 0.307123 | KaisatoK |
d2396b70e556838a690e2550db916c0dbdfc0a04 | 235 | cxx | C++ | Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CTestTest/SmallAndFast/intentional_compile_warning.cxx | duonglvtnaist/Multi-ROMix-Scrypt-Accelerator | 9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8 | [
"MIT"
] | 107 | 2021-08-28T20:08:42.000Z | 2022-03-22T08:02:16.000Z | Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CTestTest/SmallAndFast/intentional_compile_warning.cxx | duonglvtnaist/Multi-ROMix-Scrypt-Accelerator | 9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8 | [
"MIT"
] | 3 | 2021-09-08T02:18:00.000Z | 2022-03-12T00:39:44.000Z | Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CTestTest/SmallAndFast/intentional_compile_warning.cxx | duonglvtnaist/Multi-ROMix-Scrypt-Accelerator | 9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8 | [
"MIT"
] | 16 | 2021-08-30T06:57:36.000Z | 2022-03-22T08:05:52.000Z | #include <stdio.h>
int main(int argc, const char* argv[])
{
unsigned int i =
0; // "i<argc" should produce a "signed/unsigned comparison" warning
for (; i < argc; ++i) {
fprintf(stdout, "%s\n", argv[i]);
}
return 0;
}
| 19.583333 | 72 | 0.591489 | duonglvtnaist |
d23b45102eb6c362ae2fd611a14c81f7945db8c8 | 2,798 | cc | C++ | squim/image/codecs/webp_decoder_test.cc | baranov1ch/squim | 5bde052735e0dac7c87e8f7939d0168e6ee05857 | [
"Apache-2.0"
] | 2 | 2016-05-06T01:15:49.000Z | 2016-05-06T01:29:00.000Z | squim/image/codecs/webp_decoder_test.cc | baranov1ch/squim | 5bde052735e0dac7c87e8f7939d0168e6ee05857 | [
"Apache-2.0"
] | null | null | null | squim/image/codecs/webp_decoder_test.cc | baranov1ch/squim | 5bde052735e0dac7c87e8f7939d0168e6ee05857 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 Alexey Baranov <me@kotiki.cc>. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "squim/image/codecs/webp_decoder.h"
#include <memory>
#include <vector>
#include "squim/base/logging.h"
#include "squim/base/memory/make_unique.h"
#include "squim/image/test/image_test_util.h"
#include "gtest/gtest.h"
namespace image {
namespace {
const char kWebPTestDir[] = "webp";
std::unique_ptr<ImageDecoder> CreateDecoder(
std::unique_ptr<io::BufReader> source) {
auto decoder = base::make_unique<WebPDecoder>(WebPDecoder::Params::Default(),
std::move(source));
return std::move(decoder);
}
} // namespace
class WebPDecoderTest : public testing::Test {
protected:
void ValidateWebPRandomReads(const std::string& filename,
size_t max_chunk_size,
ReadType read_type) {
std::vector<uint8_t> webp_data;
std::vector<uint8_t> png_data;
ASSERT_TRUE(ReadTestFile(kWebPTestDir, filename, "webp", &webp_data));
ASSERT_TRUE(ReadTestFile(kWebPTestDir, filename, "png", &png_data));
auto read_spec = GenerateFuzzyReads(webp_data.size(), max_chunk_size);
auto ref_reader = [&png_data, filename](ImageInfo* info,
ImageFrame* frame) -> bool {
return LoadReferencePng(filename, png_data, info, frame);
};
ValidateDecodeWithReadSpec(filename, webp_data, CreateDecoder, ref_reader,
read_spec, read_type);
}
void CheckInvalidRead(const std::string& filename) {
std::vector<uint8_t> data;
ASSERT_TRUE(ReadTestFileWithExt(kWebPTestDir, filename, &data));
auto source = base::make_unique<io::BufReader>(
base::make_unique<io::BufferedSource>());
source->source()->AddChunk(
base::make_unique<io::Chunk>(&data[0], data.size()));
source->source()->SendEof();
auto testee = base::make_unique<WebPDecoder>(WebPDecoder::Params::Default(),
std::move(source));
auto result = testee->Decode();
EXPECT_EQ(Result::Code::kDecodeError, result.code()) << filename;
}
};
TEST_F(WebPDecoderTest, ReadSuccessAll) {}
} // namespace image
| 35.417722 | 80 | 0.662974 | baranov1ch |
d23c7bd55965412a621c017d96b564190fa63b5e | 2,281 | cc | C++ | src/Board/Position.cc | rodrigowerberich/simple-terminal-chess | 73c62251c4d130a896270c1e27b297da3ab0933f | [
"MIT"
] | null | null | null | src/Board/Position.cc | rodrigowerberich/simple-terminal-chess | 73c62251c4d130a896270c1e27b297da3ab0933f | [
"MIT"
] | null | null | null | src/Board/Position.cc | rodrigowerberich/simple-terminal-chess | 73c62251c4d130a896270c1e27b297da3ab0933f | [
"MIT"
] | null | null | null | #include "Board/Position.hh"
#include <sstream>
std::ostream& operator<<(std::ostream& os, const Chess::Board::Position& position){
os << position.toString();
return os;
}
namespace Chess{
namespace Board{
std::string column_to_string(Column column){
switch (column){
case Chess::Board::Column::A :
return "A";
case Chess::Board::Column::B :
return "B";
case Chess::Board::Column::C :
return "C";
case Chess::Board::Column::D :
return "D";
case Chess::Board::Column::E :
return "E";
case Chess::Board::Column::F :
return "F";
case Chess::Board::Column::G :
return "G";
case Chess::Board::Column::H :
return "H";
default:
return "Invalid";
}
}
std::vector<Column> column_as_vector(){
return {Column::A, Column::B, Column::C, Column::D, Column::E, Column::F, Column::G, Column::H};
}
int column_to_int(Column column){
switch (column){
case Chess::Board::Column::A :
return 1;
case Chess::Board::Column::B :
return 2;
case Chess::Board::Column::C :
return 3;
case Chess::Board::Column::D :
return 4;
case Chess::Board::Column::E :
return 5;
case Chess::Board::Column::F :
return 6;
case Chess::Board::Column::G :
return 7;
case Chess::Board::Column::H :
return 8;
default:
return 0;
}
}
Chess::Board::Row Chess::Board::Position::row() const{
return m_row;
}
Chess::Board::Column Chess::Board::Position::column() const{
return m_column;
}
bool Chess::Board::Position::isValid() const{
return (m_row != Chess::Board::Position::INVALID_ROW_VALUE) && (m_column != Chess::Board::Column::Invalid);
}
std::string Chess::Board::Position::toString() const{
std::stringstream out;
if(!Chess::Board::Position::isValid()){
out << "Invalid";
}else{
out << column_to_string(m_column);
out << m_row;
}
return out.str();
}
bool Chess::Board::Position::operator==(const Chess::Board::Position& lhs) const{
return (m_row == lhs.m_row) && (m_column == lhs.m_column);
}
}
} // namespace Chess
| 24.265957 | 112 | 0.567295 | rodrigowerberich |
d23ed2fdcfeafde9b72b24cd691149e3469a48b4 | 3,294 | cpp | C++ | Core/Util.cpp | TomasSirgedas/HadwigerNelsonTiling | 2862ef41a2de229eccd9854f283e5424e188f47d | [
"Unlicense"
] | null | null | null | Core/Util.cpp | TomasSirgedas/HadwigerNelsonTiling | 2862ef41a2de229eccd9854f283e5424e188f47d | [
"Unlicense"
] | null | null | null | Core/Util.cpp | TomasSirgedas/HadwigerNelsonTiling | 2862ef41a2de229eccd9854f283e5424e188f47d | [
"Unlicense"
] | null | null | null | #include "Util.h"
#include <string>
int mod( int x, int m ) { return x >= 0 ? x % m : (x+1) % m + m-1; }
Matrix4x4 toMatrix( const XYZ& a, const XYZ& b, const XYZ& c )
{
return Matrix4x4( a.x, b.x, c.x, 0,
a.y, b.y, c.y, 0,
a.z, b.z, c.z, 0,
0, 0, 0 , 1 );
}
Matrix4x4 map( const std::vector<XYZ>& a, const std::vector<XYZ>& b )
{
if ( a.size() == 3 && b.size() == 3 )
return toMatrix( b[0], b[1], b[2] ) * toMatrix( a[0], a[1], a[2] ).inverted();
if ( a.size() == 4 && b.size() == 4 )
{
Matrix4x4 m = ::map( { a[1]-a[0], a[2]-a[0], a[3]-a[0] }, { b[1]-b[0], b[2]-b[0], b[3]-b[0] } );
return Matrix4x4::translation( b[0] ) * m * Matrix4x4::translation( -a[0] );
}
throw 777;
}
Icosahedron::Icosahedron()
{
const double PHI = .5 + sqrt(1.25);
v = { XYZ( -1, 0, -PHI )
, XYZ( 1, 0, -PHI )
, XYZ( 0, PHI, -1 )
, XYZ( -PHI, 1, 0 )
, XYZ( -PHI, -1, 0 )
, XYZ( 0, -PHI, -1 )
, XYZ( 1, 0, PHI )
, XYZ( -1, 0, PHI )
, XYZ( 0, -PHI, 1 )
, XYZ( PHI, -1, 0 )
, XYZ( PHI, 1, 0 )
, XYZ( 0, PHI, 1 ) };
for ( XYZ& p : v )
p = p.normalized();
}
Matrix4x4 Icosahedron::map( const std::vector<int>& a, const std::vector<int>& b ) const
{
return ::map( std::vector<XYZ> { v[a[0]], v[a[1]], v[a[2]] }, std::vector<XYZ> { v[b[0]], v[b[1]], v[b[2]] } );
}
uint64_t matrixHash( const Matrix4x4& m )
{
std::wstring str;
std::vector<double> v = { m[0].x, m[0].y, m[0].z, m[0].w
, m[1].x, m[1].y, m[1].z, m[1].w
, m[2].x, m[2].y, m[2].z, m[2].w
, m[3].x, m[3].y, m[3].z, m[3].w };
static_assert( sizeof(wchar_t) >= 2 );
for ( double x : v )
str += wchar_t( lround( x * 1000 ) );
uint64_t h = std::hash<std::wstring>{}( str );
return h;
}
// rotation matrix that rotates p to the Z-axis
Matrix4x4 matrixRotateToZAxis( XYZ& p )
{
XYZ newZ = p.normalized();
XYZ q = abs(newZ.z) < abs(newZ.y) ? XYZ(0,0,1) : XYZ(0,1,0);
XYZ newX = (newZ ^ q).normalized();
XYZ newY = (newZ ^ newX).normalized();
return Matrix4x4( toMatrix( newX, newY, newZ ) ).inverted();
}
XYZ operator*( const Matrix4x4& m, const XYZ& p )
{
return (m * XYZW( p )).toXYZ();
}
double signedArea( const std::vector<XYZ>& v )
{
if ( v.empty() )
return 0;
double area2 = v.back().x * v[0].y - v[0].x * v.back().y;
for ( int i = 0; i+1 < (int)v.size(); i++ )
area2 += v[i].x * v[i+1].y - v[i+1].x * v[i].y;
return area2 / 2;
}
XYZ centroid( const std::vector<XYZ>& v )
{
if ( v.empty() )
return XYZ();
double A = signedArea( v );
double sumX = (v.back().x + v[0].x) * (v.back().x * v[0].y - v[0].x * v.back().y);
double sumY = (v.back().y + v[0].y) * (v.back().x * v[0].y - v[0].x * v.back().y);
for ( int i = 0; i+1 < (int)v.size(); i++ )
{
sumX += (v[i].x + v[i+1].x) * (v[i].x * v[i+1].y - v[i+1].x * v[i].y);
sumY += (v[i].y + v[i+1].y) * (v[i].x * v[i+1].y - v[i+1].x * v[i].y);
}
return XYZ( sumX / (6*A), sumY / (6*A), 0 );
} | 28.643478 | 114 | 0.440194 | TomasSirgedas |
d24296884e72420dcd0a9c5a2b95e4b4b785e462 | 3,841 | cpp | C++ | lumino/LuminoEngine/src/UI/Controls/UIListBoxItem.cpp | LuminoEngine/Lumino | 370db149da12abbe1c01a3a42b6caf07ca4000fe | [
"MIT"
] | 113 | 2020-03-05T01:27:59.000Z | 2022-03-28T13:20:51.000Z | lumino/LuminoEngine/src/UI/Controls/UIListBoxItem.cpp | LuminoEngine/Lumino | 370db149da12abbe1c01a3a42b6caf07ca4000fe | [
"MIT"
] | 13 | 2020-03-23T20:36:44.000Z | 2022-02-28T11:07:32.000Z | lumino/LuminoEngine/src/UI/Controls/UIListBoxItem.cpp | LuminoEngine/Lumino | 370db149da12abbe1c01a3a42b6caf07ca4000fe | [
"MIT"
] | 12 | 2020-12-21T12:03:59.000Z | 2021-12-15T02:07:49.000Z |
#include "Internal.hpp"
#include <LuminoEngine/Reflection/VMProperty.hpp>
//#include <LuminoEngine/UI/UICommand.hpp>
#include <LuminoEngine/UI/UIStyle.hpp>
//#include <LuminoEngine/UI/Layout/UILayoutPanel.hpp>
#include <LuminoEngine/UI/UIText.hpp>
#include <LuminoEngine/UI/Controls/UIListBox.hpp>
#include <LuminoEngine/UI/Controls/UIListBoxItem.hpp>
namespace ln {
//==============================================================================
// UIListItem
LN_OBJECT_IMPLEMENT(UIListItem, UIControl) {}
UIListItem::UIListItem()
: m_ownerListControl(nullptr)
, m_onSubmit()
, m_isSelected(false)
{
m_objectManagementFlags.unset(detail::ObjectManagementFlags::AutoAddToPrimaryElement);
m_specialElementFlags.set(detail::UISpecialElementFlags::ListItem);
}
bool UIListItem::init()
{
if (!UIControl::init()) return false;
auto vsm = getVisualStateManager();
vsm->registerState(UIVisualStates::SelectionStates, UIVisualStates::Unselected);
vsm->registerState(UIVisualStates::SelectionStates, UIVisualStates::Selected);
vsm->gotoState(UIVisualStates::Unselected);
return true;
}
Ref<EventConnection> UIListItem::connectOnSubmit(Ref<UIGeneralEventHandler> handler)
{
return m_onSubmit.connect(handler);
}
void UIListItem::onSubmit()
{
m_onSubmit.raise(UIEventArgs::create(this, UIEvents::Submitted));
}
void UIListItem::onSelected(UIEventArgs* e)
{
}
void UIListItem::onUnselected(UIEventArgs* e)
{
}
void UIListItem::onRoutedEvent(UIEventArgs* e)
{
if (e->type() == UIEvents::MouseDownEvent) {
const auto* me = static_cast<const UIMouseEventArgs*>(e);
m_ownerListControl->notifyItemClicked(this, me->getClickCount());
e->handled = true;
return;
}
else if (e->type() == UIEvents::MouseMoveEvent) {
if (m_ownerListControl->submitMode() == UIListSubmitMode::Single) {
m_ownerListControl->selectItemExclusive(this);
e->handled = true;
return;
}
}
//if (e->type() == UIEvents::MouseEnterEvent) {
// if (m_ownerListControl->submitMode() == UIListSubmitMode::Single) {
// return;
// }
//}
//else if (e->type() == UIEvents::MouseLeaveEvent) {
// if (m_ownerListControl->submitMode() == UIListSubmitMode::Single) {
// return;
// }
//}
UIControl::onRoutedEvent(e);
}
void UIListItem::setSelectedInternal(bool selected)
{
if (m_isSelected != selected) {
m_isSelected = selected;
if (m_isSelected) {
onSelected(UIEventArgs::create(this, UIEvents::Selected));
getVisualStateManager()->gotoState(UIVisualStates::Selected);
}
else {
onUnselected(UIEventArgs::create(this, UIEvents::Selected));
getVisualStateManager()->gotoState(UIVisualStates::Unselected);
}
}
}
//==============================================================================
// UIListBoxItem
LN_OBJECT_IMPLEMENT(UIListBoxItem, UIListItem) {}
Ref<UIListBoxItem> UIListBoxItem::create(StringRef text)
{
return makeObject<UIListBoxItem>(text);
}
UIListBoxItem::UIListBoxItem()
{
}
bool UIListBoxItem::init()
{
if (!UIListItem::init()) return false;
return true;
}
bool UIListBoxItem::init(StringRef text)
{
if (!init()) return false;
addChild(makeObject<UIText>(text));
return true;
}
bool UIListBoxItem::init(UIElement* content)
{
if (!init()) return false;
addChild(content);
return true;
}
void UIListBoxItem::bind(ObservablePropertyBase* prop)
{
auto textblock = makeObject<UIText>();
auto viewProp = textblock->getViewProperty(_TT("text"));
viewProp->bind(prop);
addChild(textblock);
}
//==============================================================================
// UIListBox::BuilderDetails
void UIListBoxItem::BuilderDetails::apply(UIListBoxItem* p) const
{
UIListItem::BuilderDetails::apply(p);
if (!text.isEmpty()) {
auto textblock = makeObject<UIText>(text);
p->addChild(textblock);
}
if (onSubmit) p->connectOnSubmit(onSubmit);
}
} // namespace ln
| 23.857143 | 87 | 0.690706 | LuminoEngine |
d24449dba655adf423a4d716bd7da54dac97b636 | 11,344 | cpp | C++ | base/win32/fusion/tools/st/st.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/win32/fusion/tools/st/st.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/win32/fusion/tools/st/st.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include "stdinc.h"
#include "st.h"
#include "create.h"
#include "install.h"
#include "csrss.h"
#include "wfp.h"
extern "C" { void (__cdecl * _aexit_rtn)(int); }
CEvent ResumeThreadsEvent;
CEvent StopEvent;
LONG ThreadsWaiting;
LONG TotalThreads;
CStringBuffer BaseDirectory;
PCWSTR g_pszImage = L"st";
FILE *g_pLogFile = NULL;
void ReportFailure(const char szFormat[], ...);
extern "C"
{
BOOL WINAPI SxsDllMain(HINSTANCE hInst, DWORD dwReason, PVOID pvReserved);
void __cdecl wmainCRTStartup();
};
void ExeEntry()
{
if (!::SxsDllMain(GetModuleHandleW(NULL), DLL_PROCESS_ATTACH, NULL))
goto Exit;
::wmainCRTStartup();
Exit:
::SxsDllMain(GetModuleHandleW(NULL), DLL_PROCESS_DETACH, NULL);
}
void
ReportFailure(
const char szFormat[],
...
)
{
const DWORD dwLastError = ::FusionpGetLastWin32Error();
va_list ap;
char rgchBuffer[4096];
WCHAR rgchWin32Error[4096];
va_start(ap, szFormat);
_vsnprintf(rgchBuffer, sizeof(rgchBuffer) / sizeof(rgchBuffer[0]), szFormat, ap);
va_end(ap);
if (!::FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwLastError,
0,
rgchWin32Error,
NUMBER_OF(rgchWin32Error),
&ap))
{
const DWORD dwLastError2 = ::FusionpGetLastWin32Error();
_snwprintf(rgchWin32Error, sizeof(rgchWin32Error) / sizeof(rgchWin32Error[0]), L"Error formatting Win32 error %lu\nError from FormatMessage is %lu", dwLastError, dwLastError2);
}
fprintf(stderr, "%ls: %s\n%ls\n", g_pszImage, rgchBuffer, rgchWin32Error);
if (g_pLogFile != NULL)
fprintf(g_pLogFile, "%ls: %s\n%ls\n", g_pszImage, rgchBuffer, rgchWin32Error);
}
BOOL Win32Cleanup()
{
FN_PROLOG_WIN32
//
// delete the stuff in the registry and under %windir%\winsxs
//
const static PCWSTR StuffToDelete[] =
{
#if !defined(_AMD64_) && !defined(_M_AMD64)
L"amd64_",
#endif
#if !defined(_IA64_) && !defined(_M_IA64)
L"ia64_",
#endif
L"test"
};
ULONG i = 0;
ULONG j = 0;
CRegKey RegKey;
const static WCHAR RegRootBlah[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\SideBySide\\Installations";
CStringBuffer WindowsDirectory;
IFREGFAILED_ORIGINATE_AND_EXIT(
RegOpenKeyExW(
HKEY_LOCAL_MACHINE,
RegRootBlah,
0,
KEY_ALL_ACCESS | FUSIONP_KEY_WOW64_64KEY,
&RegKey
));
for (j = 0 ; j != NUMBER_OF(StuffToDelete); ++j)
{
SIZE_T k = ::wcslen(StuffToDelete[j]);
BOOL Done = FALSE;
for (i = 0 ; !Done; )
{
CStringBuffer SubKeyName;
FILETIME LastWriteTime;
IFW32FALSE_EXIT(RegKey.EnumKey(i, SubKeyName, &LastWriteTime, &Done));
if (Done)
break;
if (::_wcsnicmp(SubKeyName, StuffToDelete[j], k) == 0)
{
CRegKey SubKey;
printf("stresstool : cleanup : deleting HKLM\\%ls\\%ls\n", RegRootBlah, static_cast<PCWSTR>(SubKeyName));
IFW32FALSE_EXIT(RegKey.OpenSubKey(SubKey, SubKeyName, KEY_ALL_ACCESS | FUSIONP_KEY_WOW64_64KEY));
IFW32FALSE_EXIT(SubKey.DestroyKeyTree());
IFW32FALSE_EXIT(RegKey.DeleteKey(SubKeyName));
}
else
{
++i;
}
}
}
IFW32FALSE_EXIT(WindowsDirectory.Win32ResizeBuffer(MAX_PATH, eDoNotPreserveBufferContents));
{
CStringBufferAccessor StringAccessor(&WindowsDirectory);
IFW32FALSE_EXIT(GetSystemDirectoryW(StringAccessor, StringAccessor.GetBufferCchAsUINT()));
}
IFW32FALSE_EXIT(WindowsDirectory.Win32RemoveLastPathElement());
for (j = 0 ; j != NUMBER_OF(StuffToDelete); ++j)
{
SIZE_T k = ::wcslen(StuffToDelete[j]);
CSmallStringBuffer StringBuffer;
CSmallStringBuffer StringBuffer2;
WIN32_FIND_DATAW wfd;
IFW32FALSE_EXIT(StringBuffer.Win32Assign(WindowsDirectory));
#define X L"Winsxs\\Manifests"
IFW32FALSE_EXIT(StringBuffer.Win32AppendPathElement(X, NUMBER_OF(X) - 1));
#undef X
IFW32FALSE_EXIT(StringBuffer2.Win32Assign(StringBuffer));
IFW32FALSE_EXIT(StringBuffer.Win32AppendPathElement(L"*", 1));
IFW32FALSE_EXIT(StringBuffer.Win32Append(StuffToDelete[j], k));
IFW32FALSE_EXIT(StringBuffer.Win32Append(L"*", 1));
{
CFindFile FindFileHandle;
if (FindFileHandle.Win32FindFirstFile(StringBuffer, &wfd))
{
do
{
CSmallStringBuffer StringBuffer3;
IFW32FALSE_EXIT(StringBuffer3.Win32Assign(StringBuffer2));
IFW32FALSE_EXIT(StringBuffer3.Win32AppendPathElement(wfd.cFileName, ::wcslen(wfd.cFileName)));
printf("stresstool : cleanup : deleting %ls\n", static_cast<PCWSTR>(StringBuffer3));
DeleteFileW(StringBuffer3);
} while (::FindNextFileW(FindFileHandle, &wfd));
}
}
IFW32FALSE_EXIT(StringBuffer.Win32Assign(WindowsDirectory));
#define X L"Winsxs"
IFW32FALSE_EXIT(StringBuffer.Win32AppendPathElement(X, NUMBER_OF(X) - 1));
#undef X
IFW32FALSE_EXIT(StringBuffer2.Win32Assign(StringBuffer));
IFW32FALSE_EXIT(StringBuffer.Win32AppendPathElement(L"*", 1));
IFW32FALSE_EXIT(StringBuffer.Win32Append(StuffToDelete[j], k));
IFW32FALSE_EXIT(StringBuffer.Win32Append(L"*", 1));
{
CFindFile FindFileHandle;
if (FindFileHandle.Win32FindFirstFile(StringBuffer, &wfd))
{
do
{
CSmallStringBuffer StringBuffer3;
IFW32FALSE_EXIT(StringBuffer3.Win32Assign(StringBuffer2));
IFW32FALSE_EXIT(StringBuffer3.Win32AppendPathElement(wfd.cFileName, ::wcslen(wfd.cFileName)));
printf("deleting %ls\n", static_cast<PCWSTR>(StringBuffer3));
SxspDeleteDirectory(StringBuffer3);
} while (::FindNextFileW(FindFileHandle, &wfd));
}
}
}
FN_EPILOG
}
//
// If we don't do this, control-c makes us fail assertions.
// Instead, handle it more gracefully.
//
BOOL
WINAPI
ConsoleCtrlHandler(
DWORD Event
)
{
if (IsDebuggerPresent())
{
OutputDebugStringA("hardcoded breakpoint upon control-c while in debugger\n");
DebugBreak();
}
switch (Event)
{
default:
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
::SetEvent(StopEvent); // wake up the controller thread
::SetEvent(ResumeThreadsEvent); // in case control-c pressed near the start
break;
}
return TRUE;
}
extern "C" int __cdecl wmain(int argc, wchar_t** argv)
{
int iReturnStatus = EXIT_FAILURE;
//
// Default of 6 hour runtime? Wow..
//
DWORD iRunTime = 6 * 60;
CWfpJobManager WfpStresser;
CStressJobManager* StressManagers[] = { &WfpStresser };
if ((argc < 2) || (argc > 3))
{
fprintf(stderr,
"%ls: Usage:\n"
" %ls <sourcedir> [minutesofstress]\n",
argv[0], argv[0]);
goto Exit;
}
if ( argc == 3 )
{
int iMaybeRunTime = ::_wtoi(argv[2]);
if ( iMaybeRunTime <= 0 )
{
fprintf(stderr, "%ls: Usage: \n %ls <sourcedir> [minutesofstress]\n",
argv[0],
argv[0]);
goto Exit;
}
iRunTime = iMaybeRunTime;
}
ThreadsWaiting = 0;
if (!ResumeThreadsEvent.Win32CreateEvent(TRUE, FALSE))
{
::ReportFailure("CreateEvent\n");
goto Exit;
}
if (!StopEvent.Win32CreateEvent(TRUE, FALSE))
{
::ReportFailure("CreateEvent\n");
goto Exit;
}
::SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
if (!BaseDirectory.Win32Assign(argv[1], wcslen(argv[1])))
goto Exit;
if (!Win32Cleanup())
goto Exit;
if (!InitializeMSIInstallTest())
goto Exit;
if (!InitializeInstall())
goto Exit;
if (!InitializeCreateActCtx())
goto Exit;
if (!InitializeCsrssStress(BaseDirectory, 0))
goto Exit;
{
ULONG ulThreadsCreated;
if (!CsrssStressStartThreads(ulThreadsCreated))
goto Exit;
else
TotalThreads += ulThreadsCreated;
}
for ( ULONG ul = 0; ul < NUMBER_OF(StressManagers); ul++ )
{
CStressJobManager *pManager = StressManagers[ul];
CSmallStringBuffer buffTestDirPath;
ULONG ulThreads;
if ((!buffTestDirPath.Win32Assign(BaseDirectory)) ||
(!buffTestDirPath.Win32AppendPathElement(
pManager->GetGroupName(),
::wcslen(pManager->GetGroupName()))))
goto Exit;
if ((!pManager->LoadFromDirectory(buffTestDirPath)) ||
(!pManager->CreateWorkerThreads(&ulThreads)))
goto Exit;
}
// wait for them all to get to their starts (should use a semaphore here)
while (ThreadsWaiting != TotalThreads)
{
Sleep(0);
}
OutputDebugStringA("********************************\n");
OutputDebugStringA("* *\n");
OutputDebugStringA("* start *\n");
OutputDebugStringA("* *\n");
OutputDebugStringA("********************************\n");
// Go!
if (!::SetEvent(ResumeThreadsEvent))
{
::ReportFailure("SetEvent(ResumeThreadsEvent)\n");
goto Exit;
}
//
// Start the WFP stresser
//
for ( ULONG ul = 0; ul < NUMBER_OF(StressManagers); ul++ )
{
if (!StressManagers[ul]->StartJobs())
goto Exit;
}
//
// Let them run a while.
//
iRunTime = iRunTime * 60 * 1000;
::WaitForSingleObject(StopEvent, iRunTime);
RequestShutdownMSIInstallTestThreads();
RequestShutdownInstallThreads();
RequestShutdownCreateActCtxThreads();
RequestCsrssStressShutdown();
for ( ULONG ul = 0; ul < NUMBER_OF(StressManagers); ul++ )
{
StressManagers[ul]->StopJobs();
}
::Sleep(1000);
WaitForMSIInstallTestThreads();
WaitForInstallThreads();
WaitForCreateActCtxThreads();
WaitForCsrssStressShutdown();
for ( ULONG ul = 0; ul < NUMBER_OF(StressManagers); ul++ )
{
StressManagers[ul]->WaitForAllJobsComplete();
}
iReturnStatus = EXIT_SUCCESS;
Exit:
CleanupMSIInstallTest();
CleanupCreateActCtx();
CleanupInstall();
CleanupCsrssTests();
for ( ULONG ul = 0; ul < NUMBER_OF(StressManagers); ul++ )
{
StressManagers[ul]->CleanupJobs();
}
Win32Cleanup();
return iReturnStatus;
}
| 29.774278 | 185 | 0.579866 | npocmaka |
d2447998d8c4adfaf82075610bd9930c7d8bc32e | 3,537 | cc | C++ | omaha/statsreport/persistent_iterator-win32_unittest.cc | r3yn0ld4/omaha | 05eeb606c433b7d0622dc95a10afd0c8d7af11b6 | [
"Apache-2.0"
] | 1,975 | 2015-07-03T07:00:50.000Z | 2022-03-31T20:04:04.000Z | omaha/statsreport/persistent_iterator-win32_unittest.cc | rodriguez74745/omaha | a244aea380b48fc488a0555c3fa51a2e03677557 | [
"Apache-2.0"
] | 277 | 2015-07-18T00:13:30.000Z | 2022-03-31T22:18:39.000Z | omaha/statsreport/persistent_iterator-win32_unittest.cc | rodriguez74745/omaha | a244aea380b48fc488a0555c3fa51a2e03677557 | [
"Apache-2.0"
] | 685 | 2015-07-18T11:24:49.000Z | 2022-03-30T20:50:12.000Z | // Copyright 2006-2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
#include <atlbase.h>
#include <atlcom.h>
#include <iterator>
#include <map>
#include "gtest/gtest.h"
#include "omaha/statsreport/aggregator-win32_unittest.h"
#include "omaha/statsreport/const-win32.h"
#include "omaha/statsreport/persistent_iterator-win32.h"
using namespace stats_report;
namespace {
class PersistentMetricsIteratorWin32Test: public MetricsAggregatorWin32Test {
public:
bool WriteStats() {
// put some persistent metrics into the registry
MetricsAggregatorWin32 agg(coll_, kAppName);
AddStats();
bool ret = agg.AggregateMetrics();
// Reset the stats, we should now have the same stats
// in our collection as in registry.
AddStats();
return ret;
}
typedef std::map<std::string, MetricBase*> MetricsMap;
void IndexMetrics(MetricsMap *metrics) {
// build a map over the metrics in our collection
MetricIterator it(coll_), end;
for (; it != end; ++it) {
metrics->insert(std::make_pair(std::string(it->name()), *it));
}
}
};
// compare two metrics instances for equality
bool equals(MetricBase *a, MetricBase *b) {
if (!a || !b)
return false;
if (a->type() != b->type() || 0 != strcmp(a->name(), b->name()))
return false;
switch (a->type()) {
case kCountType:
return a->AsCount().value() == b->AsCount().value();
break;
case kTimingType: {
TimingMetric &at = a->AsTiming();
TimingMetric &bt = b->AsTiming();
return at.count() == bt.count() &&
at.sum() == bt.sum() &&
at.minimum() == bt.minimum() &&
at.maximum() == bt.maximum();
}
break;
case kIntegerType:
return a->AsInteger().value() == b->AsInteger().value();
break;
case kBoolType:
return a->AsBool().value() == b->AsBool().value();
break;
case kInvalidType:
default:
LOG(FATAL) << "Impossible metric type";
}
return false;
}
} // namespace
TEST_F(PersistentMetricsIteratorWin32Test, Basic) {
EXPECT_TRUE(WriteStats());
PersistentMetricsIteratorWin32 a, b, c(kAppName);
EXPECT_TRUE(a == b);
EXPECT_TRUE(b == a);
EXPECT_FALSE(a == c);
EXPECT_FALSE(b == c);
EXPECT_FALSE(c == a);
EXPECT_FALSE(c == b);
++a;
EXPECT_TRUE(a == b);
EXPECT_TRUE(b == a);
}
// Test to see whether we can reliably roundtrip metrics through
// the registry without corruption.
TEST_F(PersistentMetricsIteratorWin32Test, WriteStats) {
EXPECT_TRUE(WriteStats());
MetricsMap metrics;
IndexMetrics(&metrics);
PersistentMetricsIteratorWin32 it(kAppName), end;
int count = 0;
for (; it != end; ++it) {
MetricsMap::iterator found = metrics.find(it->name());
// Make sure we found it, and that it's the correct value.
EXPECT_TRUE(found != metrics.end() && equals(found->second, *it));
count++;
}
// Did we visit all metrics?
EXPECT_EQ(count, metrics.size());
}
| 26.593985 | 77 | 0.647441 | r3yn0ld4 |
d24519581d33bd589a6b3b62855eb25ca603d564 | 896 | cpp | C++ | src/lang/Expression.cpp | matthew-sirman/help2 | 6bd0dfefdb2912d68ce5093258721caad39da2d6 | [
"MIT"
] | null | null | null | src/lang/Expression.cpp | matthew-sirman/help2 | 6bd0dfefdb2912d68ce5093258721caad39da2d6 | [
"MIT"
] | null | null | null | src/lang/Expression.cpp | matthew-sirman/help2 | 6bd0dfefdb2912d68ce5093258721caad39da2d6 | [
"MIT"
] | null | null | null | //
// Created by matthew on 10/11/2020.
//
#include "../../include/lang/Expression.h"
std::shared_ptr<Constructor> Value::constructor() const {
return dataConstructor;
}
const Value &Value::parameter(size_t index) const {
return parameters[index];
}
std::ostream &operator<<(std::ostream &os, const Expression &expr) {
switch (expr.getExpressionType()) {
case ExpressionType::Variable:
break;
case ExpressionType::Value:
os << "Value";
break;
case ExpressionType::Abstraction:
os << "Abstraction";
break;
case ExpressionType::Application:
os << "Application";
break;
case ExpressionType::Builtin:
os << "Builtin";
break;
case ExpressionType::Function:
os << "Function";
break;
}
return os;
} | 24.216216 | 68 | 0.564732 | matthew-sirman |
d2496eee5fa752b776eb501f6c0eca816a12fb13 | 3,644 | cxx | C++ | utils/pcTests/fastrtps/IncludesTest/IncludesTestClientExample.cxx | romain-gimenez/RPC | 8a02d1189d9baeaadb3c3e3d692c2ab77c9d8d3c | [
"Apache-2.0"
] | 39 | 2015-10-21T21:57:22.000Z | 2022-02-28T09:26:26.000Z | utils/pcTests/fastrtps/IncludesTest/IncludesTestClientExample.cxx | romain-gimenez/RPC | 8a02d1189d9baeaadb3c3e3d692c2ab77c9d8d3c | [
"Apache-2.0"
] | 14 | 2015-08-10T23:49:39.000Z | 2021-11-23T01:35:45.000Z | utils/pcTests/fastrtps/IncludesTest/IncludesTestClientExample.cxx | romain-gimenez/RPC | 8a02d1189d9baeaadb3c3e3d692c2ab77c9d8d3c | [
"Apache-2.0"
] | 28 | 2015-08-10T23:40:44.000Z | 2021-11-29T15:18:34.000Z | /*************************************************************************
* Copyright (c) 2012 eProsima. All rights reserved.
*
* This copy of FASTRPC is licensed to you under the terms described in the
* FASTRPC_LICENSE file included in this distribution.
*
*************************************************************************
*
* @file Client.cxx
* This source file shows a simple example of how to create a proxy for an interface.
*
* This file was generated by the tool rpcddsgen.
*/
#include "IncludesTestProxy.h"
#include "IncludesTest.h"
#include "IncludesTestDDSProtocol.h"
#include <fastrpc/transports/dds/RTPSProxyTransport.h>
#include <fastrpc/exceptions/Exceptions.h>
#include <iostream>
#ifdef __linux
#include <unistd.h>
#endif
using namespace eprosima::rpc;
using namespace ::exception;
using namespace ::transport::dds;
using namespace ::protocol::dds;
int main(int argc, char **argv)
{
IncludesTestProtocol *protocol = NULL;
RTPSProxyTransport *transport = NULL;
IncludesTestNS::IncludesTestIfcProxy *proxy = NULL;
// Creation of the proxy for interface "IncludesTestNS::IncludesTestIfc".
try
{
protocol = new IncludesTestProtocol();
transport = new RTPSProxyTransport("IncludesTestService", "Instance");
proxy = new IncludesTestNS::IncludesTestIfcProxy(*transport, *protocol);
}
catch(InitializeException &ex)
{
std::cout << ex.what() << std::endl;
_exit(-1);
}
// Create and initialize parameters.
SameDirectoryNS::SameDirectory sd;
Level2NS::Level2 lvl;
IncludesTestNS::IncludesTest incl;
// Create and initialize return value.
IncludesTestNS::IncludesTest set_ret;
lvl.count(3);
sd.count(100);
// Call to remote procedure "set".
try
{
set_ret = proxy->set(sd, lvl, incl);
if(incl.count() != 3 ||
incl.level().count() != 3 ||
incl.sd().count() != 3 ||
incl.sd().level().count() != 3 ||
lvl.count() != 100 ||
set_ret.count() != 100 ||
set_ret.level().count() != 100 ||
set_ret.sd().count() != 100 ||
set_ret.sd().level().count() != 100)
{
std::cout << "TEST FAILED<set>: Wrong values" << std::endl;
_exit(-1);
}
}
catch(SystemException &ex)
{
std::cout << ex.what() << std::endl;
_exit(-1);
}
UtilNS::Util get_ret;
try
{
get_ret = proxy->get();
if(get_ret.count() != 1010)
{
std::cout << "TEST FAILED<get>: Wrong values" << std::endl;
_exit(-1);
}
}
catch(SystemException &ex)
{
std::cout << ex.what() << std::endl;
_exit(-1);
}
HideNS::Hide h;
HideNS::Hide ho;
h.count(3043);
try
{
proxy->hide(h, ho);
if(ho.count() != 3043)
{
std::cout << "TEST FAILED<hide>: Wrong values" << std::endl;
_exit(-1);
}
}
catch(Exception &ex)
{
std::cout << ex.what() << std::endl;
_exit(-1);
}
ZetaNS::Zeta z, zeta_ret;
z.count(1021);
try
{
zeta_ret = proxy->zeta(z);
if(zeta_ret.count() != 1021)
{
std::cout << "TEST FAILED<zeta>: Wrong values" << std::endl;
_exit(-1);
}
}
catch(Exception &ex)
{
std::cout << ex.what() << std::endl;
_exit(-1);
}
delete proxy;
delete transport;
delete protocol;
return 0;
}
| 23.509677 | 85 | 0.526619 | romain-gimenez |
d24e223eaf1e320a86b4a4f1cdebc94b2e323aab | 5,338 | hpp | C++ | bryllite-core/bcp_server.hpp | bryllite/bcp-concept-prototype | 3ded79a85ee4c876fbbd0c1ee51680346874494e | [
"MIT"
] | null | null | null | bryllite-core/bcp_server.hpp | bryllite/bcp-concept-prototype | 3ded79a85ee4c876fbbd0c1ee51680346874494e | [
"MIT"
] | null | null | null | bryllite-core/bcp_server.hpp | bryllite/bcp-concept-prototype | 3ded79a85ee4c876fbbd0c1ee51680346874494e | [
"MIT"
] | null | null | null | #pragma once
// bcp callback interface
class IBcpServerCallback
{
public:
virtual size_t qualify_votes_count( void ) = 0;
virtual int onBcpNewRoundReady( size_t prevRoundIdx ) = 0;
virtual int onBcpNewRoundStart( size_t roundIdx ) = 0;
virtual int onBcpProposeStart( size_t roundIdx ) = 0;
virtual int onBcpVoteStart( size_t roundIdx ) = 0;
virtual int onBcpCommitStart( size_t roundIdx, CBlockHeader vote_header ) = 0;
virtual bool onBcpVerifyBlock( size_t roundIdx, CBlock verify_block ) = 0;
virtual int onBcpNewBlock( size_t roundIdx, CBlock newBlock ) = 0;
virtual int onBcpTimeout( size_t roundIdx ) = 0;
};
class CBcpServer;
// round storage
class CBcpData
{
friend class CBcpServer;
protected:
// lock objects of CBcpServer
bryllite::lockable& _lock;
// current block idx
size_t _round_idx;
// node candidate block
CBlock _candidate_block;
// user signed headers
std::map< std::string, CBlockHeader > _user_signed_headers;
CBlockHeader _lowest_user_signed_header;
// node proposed headers
std::map< int, CBlockHeader > _proposed_headers;
CBlockHeader _lowest_proposed_header;
// node voted headers
std::map< int, CBlockHeader > _votes_box;
std::map< uint256, CBlockHeader > _votes_headers;
std::map< uint256, size_t > _votes;
CBlockHeader _votes_qualified_header;
bool _votes_completed;
// verify block
CBlock _verify_block;
bool _verify_completed;
// node committed block
CBlock _commit_block;
std::map< int, CBlock > _committed_blocks;
std::map< int, CSecret > _committed_secrets;
bool _commit_completed;
public:
CBcpData( size_t roundIdx, bryllite::lockable& lock );
size_t round_idx( void );
// candidate block
void candidate_block( CBlock block );
CBlock& candidate_block( void );
// user signed header
bool append_user_signed_header( std::string user_address, CBlockHeader signed_header );
bool find_lowest_user_signed_header( CBlockHeader& lowest_header );
bool get_lowest_user_signed_header( CBlockHeader& lowest_header );
size_t get_participated_users( std::vector< std::string >& users );
// proposed header
bool append_proposed_header( int peer_id, CBlockHeader proposed_header );
bool find_lowest_proposed_header( CBlockHeader& lowest_header );
bool get_lowest_proposed_header( CBlockHeader& lowest_header );
// votes headers
bool append_votes_header( int peer_id, CBlockHeader votes_header );
bool find_qualified_votes_header( CBlockHeader& qualified_header, size_t qualify_count );
bool get_qualified_votes_header( CBlockHeader& qualified_header );
// commit block
bool append_commit_block( int peer_id, CBlock commit_block, CSecret commit_secret );
bool find_qualified_commit_block( CBlock& qualified_block, size_t qualify_count );
bool get_qualified_commit_block( CBlock& qualified_block );
// verify block
void verify_block( CBlock block );
CBlock& verify_block( void );
};
#if defined(_DEBUG) && 0
#define _USE_SHORT_BLOCK_TIME_
#endif
// BCP class
class CBcpServer : public ICallbackTimer
{
using callback_timer = bryllite::callback_timer;
// bcp timeout in ms
enum bcp_timeout
{
#ifdef _USE_SHORT_BLOCK_TIME_
bcp_timeout_proof_of_participation = 4000,
bcp_timeout_propose = 6000,
bcp_timeout_vote = 8000,
bcp_timeout_commit = 10000,
#else // _USE_SHORT_BLOCK_TIME_
bcp_timeout_proof_of_participation = 5000,
bcp_timeout_propose = 10000,
bcp_timeout_vote = 20000,
bcp_timeout_commit = 30000,
#endif
bcp_block_time = bcp_timeout_commit
};
protected:
// lock object of CNodeServer
bryllite::lockable& _lock;
// CBcpTimer ref
CBcpTimer& _bcp_timer;
// callback timer
callback_timer _callback_timer;
// BCP callback interface
IBcpServerCallback& _bcp_callback;
// time context
time_t _time_context;
// round idx
size_t _round_idx;
// new round messages
std::map< int, size_t > _new_round_messages;
std::map< size_t, size_t > _new_round_votes;
// < round, CBcpData >
std::map< size_t, std::unique_ptr< CBcpData > > _bcp_data;
public:
CBcpServer( IBcpServerCallback& bcp_callback, bryllite::lockable& lock, CBcpTimer& bcpTimer );
// start/stop bcp
bool start( void );
bool stop( void );
// update bcp
int update( void );
CBcpData* get_bcp_data( size_t round_idx );
CBcpData* get_bcp_data( void );
bool ready( void );
public:
time_t getTime( void );
// timeline in (ms)
time_t timeline( time_t& timeContext );
time_t timeline( void );
protected:
enum
{
timeout_proof_of_participation = 0,
timeout_propose,
timeout_vote,
timeout_commit
};
int onTimeOut(timer_id id, void* pContext) override;
void onTimeOutProofOfParticipation( void );
void onTimeOutPropose( void );
void onTimeOutVote( void );
void onTimeOutCommit( void );
void setTimeOutProofOfParticipation( void );
void setTimeOutPropose( void );
void setTimeOutVote( void );
void killTimeOutVote( void );
void setTimeOutCommit( void );
void killTimeOutCommit( void );
public:
// add new round message
bool new_round_vote( int peer_id, size_t round_idx );
// is new round vote qualified?
bool new_round_vote_qualified( size_t& round_idx );
bool onVote( int peer_id, size_t round_idx, CBlockHeader vote_header );
bool onVerify( int peer_id, size_t round_idx, CBlock verify_block );
bool onCommit( int peer_id, size_t round_idx, CBlock commit_block, CSecret secret );
};
| 25.54067 | 95 | 0.765268 | bryllite |
d24f2e7b5e101a8a7f042fbd470fd4516664eb2a | 8,719 | cpp | C++ | src/phyx-1.01/src/main_contrates.cpp | jlanga/smsk_selection | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 4 | 2021-07-18T05:20:20.000Z | 2022-01-03T10:22:33.000Z | src/phyx-1.01/src/main_contrates.cpp | jlanga/smsk_selection | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 1 | 2017-08-21T07:26:13.000Z | 2018-11-08T13:59:48.000Z | src/phyx-1.01/src/main_contrates.cpp | jlanga/smsk_orthofinder | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 2 | 2021-07-18T05:20:26.000Z | 2022-03-31T18:23:31.000Z |
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstring>
#include <getopt.h>
#include <map>
using namespace std;
#include "string_node_object.h"
#include "utils.h"
#include "sequence.h"
#include "seq_reader.h"
#include "tree_reader.h"
#include "tree.h"
#include "cont_models.h"
#include "optimize_cont_models_nlopt.h"
#include "log.h"
void print_help() {
cout << "Continuous character rate estimation with Brownian and OU." << endl;
cout << "This will take fasta, phylip (and soon nexus) inputs." << endl;
cout << "Can read from stdin or file." << endl;
cout << endl;
cout << "Usage: pxcontrates [OPTION]... " << endl;
cout << endl;
cout << " -c, --charf=FILE input character file, stdin otherwise" << endl;
cout << " -t, --treef=FILE input tree file, stdin otherwise" << endl;
cout << " -a, --analysis=NUM analysis type (0=anc[DEFAULT], 1=ratetest)" << endl;
cout << " -o, --outf=FILE output sequence file, stout otherwise" << endl;
cout << " -h, --help display this help and exit" << endl;
cout << " -V, --version display version and exit" << endl;
cout << endl;
cout << "Report bugs to: <https://github.com/FePhyFoFum/phyx/issues>" << endl;
cout << "phyx home page: <https://github.com/FePhyFoFum/phyx>" << endl;
}
string versionline("pxcontrates 0.1\nCopyright (C) 2013 FePhyFoFum\nLicense GPLv3\nwritten by Joseph W. Brown, Stephen A. Smith (blackrim)");
static struct option const long_options[] =
{
{"char", required_argument, NULL, 'c'},
{"tree", required_argument, NULL, 't'},
{"outf", required_argument, NULL, 'o'},
{"analysis", required_argument, NULL, 'a'},
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'V'},
{NULL, 0, NULL, 0}
};
int main(int argc, char * argv[]) {
log_call(argc, argv);
bool cfileset = false;
bool tfileset = false;
bool outfileset = false;
char * treef = NULL;
char * charf = NULL;
char * outf = NULL;
int analysis = 0;
while (1) {
int oi = -1;
int c = getopt_long(argc, argv, "c:t:o:a:hV", long_options, &oi);
if (c == -1) {
break;
}
switch(c) {
case 'c':
cfileset = true;
charf = strdup(optarg);
check_file_exists(charf);
break;
case 't':
tfileset = true;
treef = strdup(optarg);
check_file_exists(treef);
break;
case 'o':
outfileset = true;
outf = strdup(optarg);
break;
case 'a':
if (optarg[0] == '1') {
analysis = 1;
}
break;
case 'h':
print_help();
exit(0);
case 'V':
cout << versionline << endl;
exit(0);
default:
print_error(argv[0], (char)c);
exit(0);
}
}
istream * pios = NULL;
istream * poos = NULL;
ifstream * cfstr = NULL;
ifstream * tfstr = NULL;
ostream * poouts = NULL;
ofstream * ofstr = NULL;
if (tfileset == true) {
tfstr = new ifstream(treef);
poos = tfstr;
} else {
poos = &cin;
}
if (cfileset == true) {
cfstr = new ifstream(charf);
pios = cfstr;
} else {
cout << "you have to set a character file. Only a tree file can be read in through the stream;" << endl;
}
//out file
//
if (outfileset == true) {
ofstr = new ofstream(outf);
poouts = ofstr;
} else {
poouts = &cout;
}
//
string retstring;
int ft = test_char_filetype_stream(*pios, retstring);
if (ft != 1 && ft != 2) {
cout << "only fasta and phylip (with spaces) supported so far" << endl;
exit(0);
}
Sequence seq;
vector <Sequence> seqs;
map <string, int> seq_map;
int y = 0;
int nchars = 0 ;
while (read_next_seq_char_from_stream(*pios, ft, retstring, seq)) {
seqs.push_back(seq);
nchars = seq.get_num_cont_char();
seq_map[seq.get_id()] = y;
seq.clear_cont_char();
y++;
}
if (ft == 2) {
seqs.push_back(seq);
seq_map[seq.get_id()] = y;
seq.clear_cont_char();
}
//read trees
TreeReader tr;
vector<Tree *> trees;
while (getline(*poos,retstring)) {
trees.push_back(tr.readTree(retstring));
}
//conduct analyses for each character
for (int c=0; c < nchars; c++) {
cerr << "character: " << c << endl;
if (analysis == 0) {
// cout << "Input tree: " << getNewickString(trees[0]) << ";" << endl;
if (c == 0) {
(*poouts) << "#nexus" << endl << "begin trees;" << endl;
}
for (unsigned int x = 0; x < trees.size(); x++){
for (int i=0; i < trees[x]->getExternalNodeCount(); i++) {
vector<Superdouble> tv (1);
tv[0] = seqs[seq_map[trees[x]->getExternalNode(i)->getName()]].get_cont_char(c);
trees[x]->getExternalNode(i)->assocDoubleVector("val",tv);
}
for (int i=0; i < trees[x]->getInternalNodeCount(); i++) {
vector<Superdouble> tv (1);
tv[0] = 0;
trees[x]->getInternalNode(i)->assocDoubleVector("val",tv);
}
calc_square_change_anc_states(trees[x],0); // second character dies here
for (int i=0; i < trees[x]->getInternalNodeCount(); i++) {
double tv = (*trees[x]->getInternalNode(i)->getDoubleVector("val"))[0];
trees[x]->getInternalNode(i)->deleteDoubleVector("val");
std::ostringstream s;
s.precision(9);
s << fixed << tv;
StringNodeObject nob(s.str());
trees[x]->getInternalNode(i)->assocObject("value",nob);
//trees[x]->getInternalNode(i)->setName(s.str());
}
for (int i=0; i < trees[x]->getExternalNodeCount(); i++) {
double tv = (*trees[x]->getExternalNode(i)->getDoubleVector("val"))[0];
trees[x]->getExternalNode(i)->deleteDoubleVector("val");
std::ostringstream s;
s.precision(9);
s << fixed << tv;
StringNodeObject nob(s.str());
trees[x]->getExternalNode(i)->assocObject("value",nob);
//s << fixed << trees[x]->getExternalNode(i)->getName() << "[&value=" << tv << "]";
//trees[x]->getExternalNode(i)->setName(s.str());
}
(*poouts) << "tree tree" << c << " = ";
(*poouts) << getNewickString(trees[x],"value") << endl;
}
if (c == (nchars - 1)) {
(*poouts) << "end;\n" << endl;
}
// remove annotations
remove_annotations(trees[0]);
} else if (analysis == 1) {
mat vcv;
int t_ind = 0; // TODO: do this over trees
int c_ind = c;
calc_vcv(trees[t_ind],vcv);
int n = trees[t_ind]->getExternalNodeCount();
rowvec x = rowvec(n);
for (int i=0; i < n; i++) {
x(i) = seqs[seq_map[trees[t_ind]->getExternalNode(i)->getName()]].get_cont_char(c_ind);
}
vector<double> res = optimize_single_rate_bm_nlopt(x, vcv, true);
double aic = (2*2)-(2*(-res[2]));
double aicc = aic + ((2*2*(2+1))/(n-2-1));
cout << c << " BM " << " state: " << res[0] << " rate: " << res[1]
<< " like: " << -res[2] << " aic: " << aic << " aicc: " << aicc << endl;
vector<double> res2 = optimize_single_rate_bm_ou_nlopt(x, vcv);
aic = (2*3)-(2*(-res2[3]));
aicc = aic + ((2*3*(3+1))/(n-3-1));
cout << c << " OU " << " state: " << res2[0] << " rate: "
<< res2[1] << " alpha: " << res2[2] << " like: " << -res2[3]
<< " aic: " << aic << " aicc: " << aicc << endl;
}
}
if (cfileset) {
cfstr->close();
delete pios;
}
if (tfileset) {
tfstr->close();
delete poos;
}
if (outfileset) {
ofstr->close();
delete poouts;
}
return EXIT_SUCCESS;
}
| 34.058594 | 141 | 0.483886 | jlanga |
d2509887016f78cb99f053b6b3accb548821726a | 9,244 | cpp | C++ | chromium/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 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 "modules/accessibility/InspectorTypeBuilderHelper.h"
#include "core/InspectorTypeBuilder.h"
#include "core/dom/DOMNodeIds.h"
#include "modules/accessibility/AXObject.h"
#include "modules/accessibility/AXObjectCacheImpl.h"
namespace blink {
using TypeBuilder::Accessibility::AXValueNativeSourceType;
using TypeBuilder::Accessibility::AXRelatedNode;
using TypeBuilder::Accessibility::AXValueSourceType;
PassRefPtr<AXProperty> createProperty(String name, PassRefPtr<AXValue> value)
{
RefPtr<AXProperty> property = AXProperty::create().setName(name).setValue(value);
return property;
}
PassRefPtr<AXProperty> createProperty(AXGlobalStates::Enum name, PassRefPtr<AXValue> value)
{
return createProperty(TypeBuilder::getEnumConstantValue(name), value);
}
PassRefPtr<AXProperty> createProperty(AXLiveRegionAttributes::Enum name, PassRefPtr<AXValue> value)
{
return createProperty(TypeBuilder::getEnumConstantValue(name), value);
}
PassRefPtr<AXProperty> createProperty(AXRelationshipAttributes::Enum name, PassRefPtr<AXValue> value)
{
return createProperty(TypeBuilder::getEnumConstantValue(name), value);
}
PassRefPtr<AXProperty> createProperty(AXWidgetAttributes::Enum name, PassRefPtr<AXValue> value)
{
return createProperty(TypeBuilder::getEnumConstantValue(name), value);
}
PassRefPtr<AXProperty> createProperty(AXWidgetStates::Enum name, PassRefPtr<AXValue> value)
{
return createProperty(TypeBuilder::getEnumConstantValue(name), value);
}
String ignoredReasonName(AXIgnoredReason reason)
{
switch (reason) {
case AXActiveModalDialog:
return "activeModalDialog";
case AXAncestorDisallowsChild:
return "ancestorDisallowsChild";
case AXAncestorIsLeafNode:
return "ancestorIsLeafNode";
case AXAriaHidden:
return "ariaHidden";
case AXAriaHiddenRoot:
return "ariaHiddenRoot";
case AXEmptyAlt:
return "emptyAlt";
case AXEmptyText:
return "emptyText";
case AXInert:
return "inert";
case AXInheritsPresentation:
return "inheritsPresentation";
case AXLabelContainer:
return "labelContainer";
case AXLabelFor:
return "labelFor";
case AXNotRendered:
return "notRendered";
case AXNotVisible:
return "notVisible";
case AXPresentationalRole:
return "presentationalRole";
case AXProbablyPresentational:
return "probablyPresentational";
case AXStaticTextUsedAsNameFor:
return "staticTextUsedAsNameFor";
case AXUninteresting:
return "uninteresting";
}
ASSERT_NOT_REACHED();
return "";
}
PassRefPtr<AXProperty> createProperty(IgnoredReason reason)
{
if (reason.relatedObject)
return createProperty(ignoredReasonName(reason.reason), createRelatedNodeListValue(reason.relatedObject, nullptr, AXValueType::Idref));
return createProperty(ignoredReasonName(reason.reason), createBooleanValue(true));
}
PassRefPtr<AXValue> createValue(String value, AXValueType::Enum type)
{
RefPtr<AXValue> axValue = AXValue::create().setType(type);
axValue->setValue(JSONString::create(value));
return axValue;
}
PassRefPtr<AXValue> createValue(int value, AXValueType::Enum type)
{
RefPtr<AXValue> axValue = AXValue::create().setType(type);
axValue->setValue(JSONBasicValue::create(value));
return axValue;
}
PassRefPtr<AXValue> createValue(float value, AXValueType::Enum type)
{
RefPtr<AXValue> axValue = AXValue::create().setType(type);
axValue->setValue(JSONBasicValue::create(value));
return axValue;
}
PassRefPtr<AXValue> createBooleanValue(bool value, AXValueType::Enum type)
{
RefPtr<AXValue> axValue = AXValue::create().setType(type);
axValue->setValue(JSONBasicValue::create(value));
return axValue;
}
PassRefPtr<AXRelatedNode> relatedNodeForAXObject(const AXObject* axObject, String* name = nullptr)
{
Node* node = axObject->node();
if (!node)
return PassRefPtr<AXRelatedNode>();
int backendNodeId = DOMNodeIds::idForNode(node);
if (!backendNodeId)
return PassRefPtr<AXRelatedNode>();
RefPtr<AXRelatedNode> relatedNode = AXRelatedNode::create().setBackendNodeId(backendNodeId);
if (!node->isElementNode())
return relatedNode;
Element* element = toElement(node);
const AtomicString& idref = element->getIdAttribute();
if (!idref.isEmpty())
relatedNode->setIdref(idref);
if (name)
relatedNode->setText(*name);
return relatedNode;
}
PassRefPtr<AXValue> createRelatedNodeListValue(const AXObject* axObject, String* name, AXValueType::Enum valueType)
{
RefPtr<AXValue> axValue = AXValue::create().setType(valueType);
RefPtr<AXRelatedNode> relatedNode = relatedNodeForAXObject(axObject, name);
RefPtr<TypeBuilder::Array<AXRelatedNode>> relatedNodes = TypeBuilder::Array<AXRelatedNode>::create();
relatedNodes->addItem(relatedNode);
axValue->setRelatedNodes(relatedNodes);
return axValue;
}
PassRefPtr<AXValue> createRelatedNodeListValue(AXRelatedObjectVector& relatedObjects, AXValueType::Enum valueType)
{
RefPtr<TypeBuilder::Array<AXRelatedNode>> frontendRelatedNodes = TypeBuilder::Array<AXRelatedNode>::create();
for (unsigned i = 0; i < relatedObjects.size(); i++) {
RefPtr<AXRelatedNode> frontendRelatedNode = relatedNodeForAXObject(relatedObjects[i]->object, &(relatedObjects[i]->text));
if (frontendRelatedNode)
frontendRelatedNodes->addItem(frontendRelatedNode);
}
RefPtr<AXValue> axValue = AXValue::create().setType(valueType);
axValue->setRelatedNodes(frontendRelatedNodes);
return axValue;
}
PassRefPtr<AXValue> createRelatedNodeListValue(AXObject::AXObjectVector& axObjects, AXValueType::Enum valueType)
{
RefPtr<TypeBuilder::Array<AXRelatedNode>> relatedNodes = TypeBuilder::Array<AXRelatedNode>::create();
for (unsigned i = 0; i < axObjects.size(); i++) {
RefPtr<AXRelatedNode> relatedNode = relatedNodeForAXObject(axObjects[i].get());
if (relatedNode)
relatedNodes->addItem(relatedNode);
}
RefPtr<AXValue> axValue = AXValue::create().setType(valueType);
axValue->setRelatedNodes(relatedNodes);
return axValue;
}
AXValueSourceType::Enum valueSourceType(AXNameFrom nameFrom)
{
switch (nameFrom) {
case AXNameFromAttribute:
case AXNameFromTitle:
case AXNameFromValue:
return AXValueSourceType::Attribute;
case AXNameFromContents:
return AXValueSourceType::Contents;
case AXNameFromPlaceholder:
return AXValueSourceType::Placeholder;
case AXNameFromCaption:
case AXNameFromRelatedElement:
return AXValueSourceType::RelatedElement;
default:
return AXValueSourceType::Implicit; // TODO(aboxhall): what to do here?
}
}
AXValueNativeSourceType::Enum nativeSourceType(AXTextFromNativeHTML nativeSource)
{
switch (nativeSource) {
case AXTextFromNativeHTMLFigcaption:
return AXValueNativeSourceType::Figcaption;
case AXTextFromNativeHTMLLabel:
return AXValueNativeSourceType::Label;
case AXTextFromNativeHTMLLabelFor:
return AXValueNativeSourceType::Labelfor;
case AXTextFromNativeHTMLLabelWrapped:
return AXValueNativeSourceType::Labelwrapped;
case AXTextFromNativeHTMLTableCaption:
return AXValueNativeSourceType::Tablecaption;
case AXTextFromNativeHTMLLegend:
return AXValueNativeSourceType::Legend;
case AXTextFromNativeHTMLTitleElement:
return AXValueNativeSourceType::Title;
default:
return AXValueNativeSourceType::Other;
}
}
PassRefPtr<AXValueSource> createValueSource(NameSource& nameSource)
{
String attribute = nameSource.attribute.toString();
AXValueSourceType::Enum type = valueSourceType(nameSource.type);
RefPtr<AXValueSource> valueSource = AXValueSource::create().setType(type);
RefPtr<AXValue> value;
if (!nameSource.relatedObjects.isEmpty()) {
AXValueType::Enum valueType = nameSource.attributeValue.isNull() ? AXValueType::NodeList : AXValueType::IdrefList;
value = createRelatedNodeListValue(nameSource.relatedObjects, valueType);
if (!nameSource.attributeValue.isNull())
value->setValue(JSONString::create(nameSource.attributeValue.string()));
valueSource->setValue(value);
} else if (!nameSource.text.isNull()) {
valueSource->setValue(createValue(nameSource.text));
} else if (!nameSource.attributeValue.isNull()) {
valueSource->setValue(createValue(nameSource.attributeValue));
}
if (nameSource.attribute != QualifiedName::null())
valueSource->setAttribute(nameSource.attribute.localName().string());
if (nameSource.superseded)
valueSource->setSuperseded(true);
if (nameSource.invalid)
valueSource->setInvalid(true);
if (nameSource.nativeSource != AXTextFromNativeHTMLUninitialized)
valueSource->setNativeSource(nativeSourceType(nameSource.nativeSource));
return valueSource;
}
} // namespace blink
| 36.25098 | 143 | 0.738749 | wedataintelligence |
d250b4606b04f42520c3027df8548b1beebfa3ac | 2,300 | hpp | C++ | ThirdParty-mod/java2cpp/android/sax/StartElementListener.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/android/sax/StartElementListener.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/android/sax/StartElementListener.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: android.sax.StartElementListener
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_SAX_STARTELEMENTLISTENER_HPP_DECL
#define J2CPP_ANDROID_SAX_STARTELEMENTLISTENER_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace org { namespace xml { namespace sax { class Attributes; } } } }
#include <java/lang/Object.hpp>
#include <org/xml/sax/Attributes.hpp>
namespace j2cpp {
namespace android { namespace sax {
class StartElementListener;
class StartElementListener
: public object<StartElementListener>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
explicit StartElementListener(jobject jobj)
: object<StartElementListener>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
void start(local_ref< org::xml::sax::Attributes > const&);
}; //class StartElementListener
} //namespace sax
} //namespace android
} //namespace j2cpp
#endif //J2CPP_ANDROID_SAX_STARTELEMENTLISTENER_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_SAX_STARTELEMENTLISTENER_HPP_IMPL
#define J2CPP_ANDROID_SAX_STARTELEMENTLISTENER_HPP_IMPL
namespace j2cpp {
android::sax::StartElementListener::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
void android::sax::StartElementListener::start(local_ref< org::xml::sax::Attributes > const &a0)
{
return call_method<
android::sax::StartElementListener::J2CPP_CLASS_NAME,
android::sax::StartElementListener::J2CPP_METHOD_NAME(0),
android::sax::StartElementListener::J2CPP_METHOD_SIGNATURE(0),
void
>(get_jobject(), a0);
}
J2CPP_DEFINE_CLASS(android::sax::StartElementListener,"android/sax/StartElementListener")
J2CPP_DEFINE_METHOD(android::sax::StartElementListener,0,"start","(Lorg/xml/sax/Attributes;)V")
} //namespace j2cpp
#endif //J2CPP_ANDROID_SAX_STARTELEMENTLISTENER_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 26.436782 | 97 | 0.69913 | kakashidinho |
d25125150261e787abbd4345a79b4659d1d4c03a | 6,255 | cc | C++ | components/web_resource/web_resource_service_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/web_resource/web_resource_service_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/web_resource/web_resource_service_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2016 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 <memory>
#include <utility>
#include "base/bind.h"
#include "base/test/task_environment.h"
#include "base/values.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "components/web_resource/resource_request_allowed_notifier.h"
#include "components/web_resource/web_resource_service.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_network_connection_tracker.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const std::string kTestUrl = "http://www.test.com";
const std::string kCacheUpdatePath = "cache_update_path";
std::string error_message_;
} // namespace
namespace web_resource {
class TestResourceRequestAllowedNotifier
: public ResourceRequestAllowedNotifier {
public:
TestResourceRequestAllowedNotifier(
PrefService* prefs,
const char* disable_network_switch,
network::NetworkConnectionTracker* network_connection_tracker)
: ResourceRequestAllowedNotifier(
prefs,
disable_network_switch,
base::BindOnce(
[](network::NetworkConnectionTracker* tracker) {
return tracker;
},
network_connection_tracker)) {}
ResourceRequestAllowedNotifier::State GetResourceRequestsAllowedState()
override {
return state_;
}
void SetState(ResourceRequestAllowedNotifier::State state) { state_ = state; }
void NotifyState(ResourceRequestAllowedNotifier::State state) {
SetState(state);
SetObserverRequestedForTesting(true);
MaybeNotifyObserver();
}
private:
ResourceRequestAllowedNotifier::State state_;
};
class TestWebResourceService : public WebResourceService {
public:
TestWebResourceService(
PrefService* prefs,
const GURL& web_resource_server,
const std::string& application_locale,
const char* last_update_time_pref_name,
int start_fetch_delay_ms,
int cache_update_delay_ms,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const char* disable_network_switch,
network::NetworkConnectionTracker* network_connection_tracker)
: WebResourceService(prefs,
web_resource_server,
application_locale,
last_update_time_pref_name,
start_fetch_delay_ms,
cache_update_delay_ms,
url_loader_factory,
disable_network_switch,
TRAFFIC_ANNOTATION_FOR_TESTS,
base::BindOnce(
[](network::NetworkConnectionTracker* tracker) {
return tracker;
},
network_connection_tracker)) {}
void Unpack(const base::DictionaryValue& parsed_json) override {}
};
class WebResourceServiceTest : public testing::Test {
public:
void SetUp() override {
test_shared_loader_factory_ =
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory_);
local_state_.reset(new TestingPrefServiceSimple());
local_state_->registry()->RegisterStringPref(kCacheUpdatePath, "0");
test_web_resource_service_.reset(new TestWebResourceService(
local_state_.get(), GURL(kTestUrl), "", kCacheUpdatePath.c_str(), 100,
5000, test_shared_loader_factory_, nullptr,
network::TestNetworkConnectionTracker::GetInstance()));
error_message_ = "";
TestResourceRequestAllowedNotifier* notifier =
new TestResourceRequestAllowedNotifier(
local_state_.get(), nullptr,
network::TestNetworkConnectionTracker::GetInstance());
notifier->SetState(ResourceRequestAllowedNotifier::ALLOWED);
test_web_resource_service_->SetResourceRequestAllowedNotifier(
std::unique_ptr<ResourceRequestAllowedNotifier>(notifier));
}
TestResourceRequestAllowedNotifier* resource_notifier() {
return static_cast<TestResourceRequestAllowedNotifier*>(
test_web_resource_service_->resource_request_allowed_notifier_.get());
}
bool GetFetchScheduled() {
return test_web_resource_service_->GetFetchScheduled();
}
void CallScheduleFetch(int64_t delay_ms) {
return test_web_resource_service_->ScheduleFetch(delay_ms);
}
WebResourceService* web_resource_service() {
return test_web_resource_service_.get();
}
void CallStartFetch() { test_web_resource_service_->StartFetch(); }
private:
base::test::SingleThreadTaskEnvironment task_environment_;
data_decoder::test::InProcessDataDecoder in_process_data_decoder_;
network::TestURLLoaderFactory test_url_loader_factory_;
scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_;
std::unique_ptr<TestingPrefServiceSimple> local_state_;
std::unique_ptr<TestWebResourceService> test_web_resource_service_;
};
TEST_F(WebResourceServiceTest, FetchScheduledAfterStartDelayTest) {
web_resource_service()->StartAfterDelay();
EXPECT_TRUE(GetFetchScheduled());
}
TEST_F(WebResourceServiceTest, FetchScheduledOnScheduleFetchTest) {
web_resource_service()->StartAfterDelay();
resource_notifier()->NotifyState(ResourceRequestAllowedNotifier::ALLOWED);
EXPECT_TRUE(GetFetchScheduled());
}
TEST_F(WebResourceServiceTest, FetchScheduledOnStartFetchTest) {
resource_notifier()->NotifyState(
ResourceRequestAllowedNotifier::DISALLOWED_NETWORK_DOWN);
CallStartFetch();
EXPECT_FALSE(GetFetchScheduled());
resource_notifier()->NotifyState(ResourceRequestAllowedNotifier::ALLOWED);
EXPECT_TRUE(GetFetchScheduled());
}
} // namespace web_resource
| 37.909091 | 82 | 0.731735 | sarang-apps |
d251dbf8042beea6c819de0dc0bf008be59cd1fe | 502 | cpp | C++ | Source Code/Dynamics/Entities/Units/Vehicle.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | 9 | 2018-05-02T19:53:41.000Z | 2021-10-18T18:30:47.000Z | Source Code/Dynamics/Entities/Units/Vehicle.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | 7 | 2018-02-01T12:16:43.000Z | 2019-10-21T14:03:43.000Z | Source Code/Dynamics/Entities/Units/Vehicle.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | 1 | 2020-09-08T03:28:22.000Z | 2020-09-08T03:28:22.000Z | #include "stdafx.h"
#include "Headers/Vehicle.h"
namespace Divide {
Vehicle::Vehicle()
: Unit(UnitType::UNIT_TYPE_VEHICLE),
_vehicleTypeMask(0)
{
_playerControlled = false;
}
void Vehicle::setVehicleTypeMask(const U32 mask) {
assert((mask &
~(to_base(VehicleType::COUNT) - 1)) == 0);
_vehicleTypeMask = mask;
}
bool Vehicle::checkVehicleMask(const VehicleType type) const {
return (_vehicleTypeMask & to_U32(type)) != to_U32(type);
}
} | 20.916667 | 63 | 0.643426 | IonutCava |