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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b979860fb7be67c5d23a72c3138958deea1e5188 | 20,541 | cpp | C++ | sdk/modules/audio/components/decoder/decoder_component.cpp | zenglongGH/spresense | b17578aac9faa417b6f1a6d7ebf8f37c57c5ea68 | [
"Apache-2.0"
] | 1 | 2022-01-28T00:06:29.000Z | 2022-01-28T00:06:29.000Z | sdk/modules/audio/components/decoder/decoder_component.cpp | zenglongGH/spresense | b17578aac9faa417b6f1a6d7ebf8f37c57c5ea68 | [
"Apache-2.0"
] | null | null | null | sdk/modules/audio/components/decoder/decoder_component.cpp | zenglongGH/spresense | b17578aac9faa417b6f1a6d7ebf8f37c57c5ea68 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
* modules/audio/components/decoder/decoder_component.cpp
*
* Copyright 2018 Sony Semiconductor Solutions Corporation
*
* 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 Sony Semiconductor Solutions Corporation 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 <arch/chip/backuplog.h>
#include <sdk/debug.h>
#include "decoder_component.h"
#include "memutils/common_utils/common_assert.h"
#include "audio/audio_message_types.h"
#include "memutils/message/Message.h"
#include "apus/cpuif_cmd.h"
#include "dsp_driver/include/dsp_drv.h"
#include <arch/chip/pm.h>
#include "apus/dsp_audio_version.h"
#include "wien2_internal_packet.h"
#define DBG_MODULE DBG_MODULE_AS
__USING_WIEN2
#ifdef CONFIG_CPUFREQ_RELEASE_LOCK
static struct pm_cpu_freqlock_s g_decode_hvlock;
#endif
#ifdef CONFIG_AUDIOUTILS_DSP_DEBUG_DUMP
#define LOG_ENTRY_NUM 4
static const char g_entry_name[LOG_ENTRY_NUM][LOG_ENTRY_NAME] =
{
"MP3DEC",
"WAVDEC",
"AACDEC",
"OPUSDEC"
};
static uint32_t g_namemap = 0x00000000;
#endif
#ifdef CONFIG_AUDIOUTILS_DECODER_TIME_MEASUREMENT
#include <time.h>
uint64_t g_start_time = 0x0ull;
uint64_t g_end_time = 0x0ull;
static void get_time(uint64_t *time)
{
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
*time = (uint64_t)now.tv_sec * 1000 +
(uint64_t)now.tv_nsec / 1000000;
}
#endif
extern "C" {
/*--------------------------------------------------------------------
C Interface
--------------------------------------------------------------------*/
uint32_t AS_decode_init(const InitDecCompParam *param,
void *p_instance,
uint32_t *dsp_inf)
{
/* Parameter check */
if (param == NULL || p_instance == NULL || dsp_inf == NULL)
{
return AS_ECODE_COMMAND_PARAM_OUTPUT_DATE;
}
/* Init */
return ((DecoderComponent *)p_instance)->init_apu(*param, dsp_inf);
}
/*--------------------------------------------------------------------*/
bool AS_decode_exec(const ExecDecCompParam *param, void *p_instance)
{
/* Parameter check */
if (param == NULL || p_instance == NULL)
{
return false;
}
/* Execute */
return ((DecoderComponent *)p_instance)->exec_apu(*param);
}
/*--------------------------------------------------------------------*/
bool AS_decode_stop(const StopDecCompParam *param, void *p_instance)
{
/* Parameter check */
if (param == NULL || p_instance == NULL)
{
return false;
}
/* Stop */
return ((DecoderComponent *)p_instance)->flush_apu(*param);
}
/*--------------------------------------------------------------------*/
bool AS_decode_setparam(const SetDecCompParam *param, void *p_instance)
{
/* Parameter check */
if (param == NULL || p_instance == NULL)
{
return false;
}
/* Set param */
return ((DecoderComponent *)p_instance)->setparam_apu(*param);
}
/*--------------------------------------------------------------------*/
bool AS_decode_recv_apu(void *p_param, void *p_instance)
{
return ((DecoderComponent *)p_instance)->recv_apu(p_param);
}
/*--------------------------------------------------------------------*/
bool AS_decode_recv_done(void *p_instance)
{
return ((DecoderComponent *)p_instance)->recv_done();
}
/*--------------------------------------------------------------------*/
uint32_t AS_decode_activate(FAR ActDecCompParam *param)
{
if (param->p_instance == NULL)
{
DECODER_ERR(AS_ATTENTION_SUB_CODE_UNEXPECTED_PARAM);
return AS_ECODE_COMMAND_PARAM_OUTPUT_DATE;
}
/* Reply pointer of self instance, which is used for API call. */
*param->p_instance = (void*)(new DecoderComponent(param->apu_pool_id,
param->apu_mid));
if (*param->p_instance == NULL)
{
DECODER_ERR(AS_ATTENTION_SUB_CODE_RESOURCE_ERROR);
return AS_ECODE_COMMAND_PARAM_OUTPUT_DATE;
}
return ((DecoderComponent*)*param->p_instance)->activate(param);
}
/*--------------------------------------------------------------------*/
bool AS_decode_deactivate(void *p_instance)
{
if ((DecoderComponent *)p_instance != NULL)
{
((DecoderComponent *)p_instance)->deactivate();
delete (DecoderComponent*)p_instance;
return true;
}
DECODER_ERR(AS_ATTENTION_SUB_CODE_UNEXPECTED_PARAM);
return false;
}
/*--------------------------------------------------------------------*/
void cbRcvDspRes(void *p_response, void *p_instance)
{
/* Callback from DSP when DSP process is done. */
DspDrvComPrm_t *p_param = (DspDrvComPrm_t *)p_response;
switch (p_param->process_mode)
{
case Apu::CommonMode:
if (p_param->event_type == Apu::BootEvent)
{
err_t er = MsgLib::send<uint32_t>
(((DecoderComponent*)p_instance)->get_apu_mid(),
MsgPriNormal,
MSG_ISR_APU0,
0,
p_param->data.value);
if (er != ERR_OK)
{
F_ASSERT(0);
}
}
else if (p_param->event_type == Apu::ErrorEvent)
{
DECODER_ERR(AS_ATTENTION_SUB_CODE_DSP_ASSETION_FAIL);
}
break;
case Apu::DecMode:
AS_decode_recv_apu(p_response, p_instance);
break;
default:
DECODER_ERR(AS_ATTENTION_SUB_CODE_UNEXPECTED_PARAM);
break;
}
}
} /* extern "C" */
/*--------------------------------------------------------------------
Class Methods
--------------------------------------------------------------------*/
uint32_t DecoderComponent::init_apu(const InitDecCompParam& param,
uint32_t *dsp_inf)
{
DECODER_DBG("INIT: code %d, fs %d, ch num %d, bit len %d, "
"sample num %d, cb %08x, req %08x\n",
param.codec_type, param.input_sampling_rate, param.channel_num,
param.bit_width, param.frame_sample_num, param.callback,
param.p_requester);
m_callback = param.callback;
m_p_requester = param.p_requester;
Apu::Wien2ApuCmd *p_apu_cmd =
reinterpret_cast<Apu::Wien2ApuCmd*>(getApuCmdBuf());
if (p_apu_cmd == NULL)
{
return AS_ECODE_DECODER_LIB_INITIALIZE_ERROR;
}
memset(p_apu_cmd, 0x00, sizeof(Apu::Wien2ApuCmd));
p_apu_cmd->header.process_mode = Apu::DecMode;
p_apu_cmd->header.event_type = Apu::InitEvent;
/* Note: CXD5602 supports only stereo format. */
p_apu_cmd->init_dec_cmd.codec_type = param.codec_type;
p_apu_cmd->init_dec_cmd.channel_num = param.channel_num;
p_apu_cmd->init_dec_cmd.sampling_rate = param.input_sampling_rate;
p_apu_cmd->init_dec_cmd.channel_config =
(param.channel_num == MonoChannels) ?
AUD_PCM_CH_CONFIG_1_0 : AUD_PCM_CH_CONFIG_2_0;
p_apu_cmd->init_dec_cmd.out_pcm_param.bit_length = param.bit_width;
p_apu_cmd->init_dec_cmd.out_pcm_param.channel_format = Aud2ChannelFormat;
p_apu_cmd->init_dec_cmd.out_pcm_param.channel_select = AudChSelThrough;
if ((p_apu_cmd->init_dec_cmd.codec_type == AudCodecLPCM
|| p_apu_cmd->init_dec_cmd.codec_type == AudCodecFLAC)
&& ((p_apu_cmd->init_dec_cmd.sampling_rate == 64000)
|| (p_apu_cmd->init_dec_cmd.sampling_rate == 88200)
|| (p_apu_cmd->init_dec_cmd.sampling_rate == 96000)
|| (p_apu_cmd->init_dec_cmd.sampling_rate == 176400)
|| (p_apu_cmd->init_dec_cmd.sampling_rate == 192000)))
{
p_apu_cmd->init_dec_cmd.out_pcm_param.sampling_rate = 192000;
}
else
{
p_apu_cmd->init_dec_cmd.out_pcm_param.sampling_rate = 48000;
}
p_apu_cmd->init_dec_cmd.work_buffer = param.work_buffer;
if (param.dsp_multi_core)
{
p_apu_cmd->init_dec_cmd.use_slave_cpu = true;
p_apu_cmd->init_dec_cmd.slave_cpu_id = m_slave_cpu_id;
}
else
{
p_apu_cmd->init_dec_cmd.use_slave_cpu = false;
p_apu_cmd->init_dec_cmd.slave_cpu_id = APU_INVALID_CPU_ID;
}
/* Note: CXD5602 supports only stereo format. */
p_apu_cmd->init_dec_cmd.out_pcm_param.channel_config =
AUD_PCM_CH_CONFIG_2_0;
p_apu_cmd->init_dec_cmd.out_pcm_param.decoder_output_sample =
param.frame_sample_num;
p_apu_cmd->init_dec_cmd.debug_dump_info.addr = NULL;
p_apu_cmd->init_dec_cmd.debug_dump_info.size = 0;
#ifdef CONFIG_AUDIOUTILS_DSP_DEBUG_DUMP
/* Initialization for DSP debug dump. */
if (m_debug_log_info.info.addr == NULL)
{
strncpy(m_debug_log_info.info.name,
g_entry_name[param.codec_type],
sizeof(m_debug_log_info.info.name));
m_debug_log_info.namemap_ps = 1 << (param.codec_type * 2);
if ((g_namemap & m_debug_log_info.namemap_ps) == 0)
{
strncat(m_debug_log_info.info.name, "0", sizeof(char));
}
else
{
strncat(m_debug_log_info.info.name, "1", sizeof(char));
m_debug_log_info.namemap_ps <<= 1;
}
g_namemap |= m_debug_log_info.namemap_ps;
m_debug_log_info.info.addr = up_backuplog_alloc
(m_debug_log_info.info.name,
AUDIOUTILS_DSP_DEBUG_DUMP_SIZE);
if (m_debug_log_info.info.addr == NULL)
{
DECODER_ERR(AS_ATTENTION_SUB_CODE_DSP_LOG_ALLOC_ERROR);
return AS_ATTENTION_SUB_CODE_DSP_LOG_ALLOC_ERROR;
}
}
if (m_debug_log_info.info.addr != NULL)
{
p_apu_cmd->init_dec_cmd.debug_dump_info.addr =
m_debug_log_info.info.addr;
p_apu_cmd->init_dec_cmd.debug_dump_info.size =
AUDIOUTILS_DSP_DEBUG_DUMP_SIZE;
}
else
{
memset(m_debug_log_info.info.name,
0,
sizeof(m_debug_log_info.info.name));
}
#endif
send_apu(p_apu_cmd);
/* Wait init completion and receive reply information */
Apu::InternalResult internal_result;
uint32_t rst = dsp_init_check(m_apu_mid, &internal_result);
*dsp_inf = internal_result.value;
return rst;
}
/*--------------------------------------------------------------------*/
bool DecoderComponent::exec_apu(const ExecDecCompParam& param)
{
Apu::Wien2ApuCmd *p_apu_cmd =
reinterpret_cast<Apu::Wien2ApuCmd*>(getApuCmdBuf());
if (p_apu_cmd == NULL)
{
return false;
}
memset(p_apu_cmd, 0x00, sizeof(Apu::Wien2ApuCmd));
p_apu_cmd->header.process_mode = Apu::DecMode;
p_apu_cmd->header.event_type = Apu::ExecEvent;
p_apu_cmd->exec_dec_cmd.input_buffer = param.input_buffer;
p_apu_cmd->exec_dec_cmd.output_buffer = param.output_buffer;
p_apu_cmd->exec_dec_cmd.num_of_au = param.num_of_au;
send_apu(p_apu_cmd);
#ifdef CONFIG_AUDIOUTILS_DECODER_TIME_MEASUREMENT
get_time(&g_start_time);
#endif
return true;
}
/*--------------------------------------------------------------------*/
bool DecoderComponent::flush_apu(const StopDecCompParam& param)
{
/* The number of time to send FLUSH is depend on type of codec or filter */
Apu::Wien2ApuCmd *p_apu_cmd =
reinterpret_cast<Apu::Wien2ApuCmd*>(getApuCmdBuf());
if (p_apu_cmd == NULL)
{
return false;
}
memset(p_apu_cmd, 0x00, sizeof(Apu::Wien2ApuCmd));
p_apu_cmd->header.process_mode = Apu::DecMode;
p_apu_cmd->header.event_type = Apu::FlushEvent;
p_apu_cmd->flush_dec_cmd.output_buffer = param.output_buffer;
send_apu(p_apu_cmd);
return true;
}
/*--------------------------------------------------------------------*/
bool DecoderComponent::setparam_apu(const SetDecCompParam& param)
{
Apu::Wien2ApuCmd *p_apu_cmd =
reinterpret_cast<Apu::Wien2ApuCmd*>(getApuCmdBuf());
if (p_apu_cmd == NULL)
{
return false;
}
memset(p_apu_cmd, 0x00, sizeof(Apu::Wien2ApuCmd));
p_apu_cmd->header.process_mode = Apu::DecMode;
p_apu_cmd->header.event_type = Apu::SetParamEvent;
p_apu_cmd->setparam_dec_cmd.l_gain = param.l_gain;
p_apu_cmd->setparam_dec_cmd.r_gain = param.r_gain;
send_apu(p_apu_cmd);
return true;
}
/*--------------------------------------------------------------------*/
void DecoderComponent::send_apu(Apu::Wien2ApuCmd *p_cmd)
{
DspDrvComPrm_t com_param;
com_param.event_type = p_cmd->header.event_type;
com_param.process_mode = p_cmd->header.process_mode;
com_param.type = DSP_COM_DATA_TYPE_STRUCT_ADDRESS;
com_param.data.pParam = reinterpret_cast<void*>(p_cmd);
int ret = DD_SendCommand(m_dsp_handler, &com_param);
if (ret != DSPDRV_NOERROR)
{
logerr("DD_SendCommand() failure. %d\n", ret);
ENCODER_ERR(AS_ATTENTION_SUB_CODE_DSP_SEND_ERROR);
return;
}
}
/*--------------------------------------------------------------------*/
bool DecoderComponent::recv_apu(void *p_response)
{
DspDrvComPrm_t *p_param = (DspDrvComPrm_t *)p_response;
Apu::Wien2ApuCmd *packet =
static_cast<Apu::Wien2ApuCmd*>(p_param->data.pParam);
if (Apu::ApuExecOK != packet->result.exec_result)
{
switch (packet->header.event_type)
{
case Apu::InitEvent:
logerr("DSP InitEvent failure.\n");
break;
case Apu::ExecEvent:
logerr("DSP ExecEvent failure.\n");
break;
case Apu::FlushEvent:
logerr("DSP FlushEvent failure.\n");
break;
default:
logerr("DSP UnknownEvent receive.\n");
break;
}
logerr(" result = %d\n", packet->result.exec_result);
logerr(" res_src = %d\n", packet->result.internal_result[0].res_src);
logerr(" code = %d\n", packet->result.internal_result[0].code);
logerr(" value = %d\n", packet->result.internal_result[0].value);
DECODER_WARN(AS_ATTENTION_SUB_CODE_DSP_EXEC_ERROR);
}
if (Apu::InitEvent == packet->header.event_type)
{
/* Notify init completion to myself */
Apu::InternalResult internal_result = packet->result.internal_result[0];
dsp_init_complete(m_apu_mid, packet->result.exec_result, &internal_result);
return true;
}
#ifdef CONFIG_AUDIOUTILS_DECODER_TIME_MEASUREMENT
if (Apu::ExecEvent == packet->header.event_type)
{
get_time(&g_end_time);
syslog(LOG_DEBUG, "DEC time %08d ms\n", g_end_time - g_start_time);
}
#endif
/* Notify to requester */
return m_callback(p_param, m_p_requester);
}
/*--------------------------------------------------------------------*/
uint32_t DecoderComponent::activate(FAR ActDecCompParam *param)
{
char filepath[64];
uint32_t decoder_dsp_version;
DECODER_DBG("ACT: codec %d\n", param);
switch (param->codec)
{
case AudCodecMP3:
snprintf(filepath, sizeof(filepath), "%s/MP3DEC", param->path);
decoder_dsp_version = DSP_MP3DEC_VERSION;
break;
case AudCodecLPCM:
snprintf(filepath, sizeof(filepath), "%s/WAVDEC", param->path);
decoder_dsp_version = DSP_WAVDEC_VERSION;
break;
case AudCodecAAC:
snprintf(filepath, sizeof(filepath), "%s/AACDEC", param->path);
decoder_dsp_version = DSP_AACDEC_VERSION;
break;
case AudCodecOPUS:
snprintf(filepath, sizeof(filepath), "%s/OPUSDEC", param->path);
decoder_dsp_version = DSP_OPUSDEC_VERSION;
break;
default:
DECODER_ERR(AS_ATTENTION_SUB_CODE_UNEXPECTED_PARAM);
return AS_ECODE_COMMAND_PARAM_CODEC_TYPE;
}
#ifdef CONFIG_CPUFREQ_RELEASE_LOCK
/* Lock HV performance to avoid loading time becomes too long */
g_decode_hvlock.count = 0;
g_decode_hvlock.info = PM_CPUFREQLOCK_TAG('D', 'C', 0x1199);
g_decode_hvlock.flag = PM_CPUFREQLOCK_FLAG_HV;
up_pm_acquire_freqlock(&g_decode_hvlock);
#endif
/* Load DSP */
int ret = DD_Load(filepath, cbRcvDspRes, (void*)this, &m_dsp_handler, DspBinTypeELFwoBind);
#ifdef CONFIG_CPUFREQ_RELEASE_LOCK
up_pm_release_freqlock(&g_decode_hvlock);
#endif
if (ret != DSPDRV_NOERROR)
{
logerr("DD_Load() failure. %d\n", ret);
DECODER_ERR(AS_ATTENTION_SUB_CODE_DSP_LOAD_ERROR);
return AS_ECODE_DSP_LOAD_ERROR;
}
/* wait for DSP boot up... */
dsp_boot_check(m_apu_mid, param->dsp_inf);
/* DSP version check */
bool is_version_matched = true;
if (decoder_dsp_version != DSP_VERSION_GET_VER(*param->dsp_inf))
{
is_version_matched = false;
logerr("DSP version unmatch. expect %08x / actual %08x",
decoder_dsp_version, DSP_VERSION_GET_VER(*param->dsp_inf));
DECODER_ERR(AS_ATTENTION_SUB_CODE_DSP_VERSION_ERROR);
}
/* If the sampling rate is Hi-Res and bit_length is 24 bits,
* load the SRC slave DSP.
*/
if (param->dsp_multi_core)
{
ret = DD_Load(filepath, cbRcvDspRes, (void*)this, &m_dsp_slave_handler, DspBinTypeELFwoBind);
if (ret != DSPDRV_NOERROR)
{
logerr("DD_Load(%s) failure. %d\n", filepath, ret);
DECODER_ERR(AS_ATTENTION_SUB_CODE_DSP_LOAD_ERROR);
return AS_ECODE_DSP_LOAD_ERROR;
}
/* Wait for slave DSP boot up... */
uint32_t slave_dsp_inf;
dsp_boot_check(m_apu_mid, &slave_dsp_inf);
/* Slave DSP version check */
if (decoder_dsp_version != DSP_VERSION_GET_VER(slave_dsp_inf))
{
logerr("Slave DSP version unmatch. expect %08x / actual %08x",
decoder_dsp_version, DSP_VERSION_GET_VER(slave_dsp_inf));
if (!is_version_matched)
{
DECODER_FATAL(AS_ATTENTION_SUB_CODE_DSP_VERSION_ERROR);
}
else
{
DECODER_ERR(AS_ATTENTION_SUB_CODE_DSP_VERSION_ERROR);
}
}
/* Get slave DSP's cpu id to notify to master's DSP. */
m_slave_cpu_id = DSP_VERSION_GET_CPU_ID(slave_dsp_inf);
}
DECODER_INF(AS_ATTENTION_SUB_CODE_DSP_LOAD_DONE);
#ifdef CONFIG_AUDIOUTILS_DSP_DEBUG_DUMP
memset(&m_debug_log_info, 0, sizeof(m_debug_log_info));
#endif
return AS_ECODE_OK;
}
/*--------------------------------------------------------------------*/
bool DecoderComponent::deactivate(void)
{
bool result = true;
DECODER_DBG("DEACT:\n");
#ifdef CONFIG_AUDIOUTILS_DSP_DEBUG_DUMP
if (m_debug_log_info.info.addr)
{
up_backuplog_free(m_debug_log_info.info.name);
g_namemap &= ~m_debug_log_info.namemap_ps;
}
#endif
int ret = DD_Unload(m_dsp_handler);
if (ret != DSPDRV_NOERROR)
{
logerr("DD_UnLoad() failure. %d\n", ret);
DECODER_ERR(AS_ATTENTION_SUB_CODE_DSP_UNLOAD_ERROR);
result = false;
}
/* Unload if there is Slave dsp. */
if ((m_dsp_slave_handler != NULL) && result)
{
ret = DD_Unload(m_dsp_slave_handler);
if (ret != DSPDRV_NOERROR)
{
logerr("DD_UnLoad() failure on slave dsp. %d\n", ret);
DECODER_ERR(AS_ATTENTION_SUB_CODE_DSP_UNLOAD_ERROR);
result = false;
}
else
{
m_dsp_slave_handler = NULL;
}
}
DECODER_INF(AS_ATTENTION_SUB_CODE_DSP_UNLOAD_DONE);
return result;
}
| 28.930986 | 99 | 0.626162 | zenglongGH |
b97b676ed4602aa2354800f363bcb22a24e05612 | 547 | cpp | C++ | boost/libs/geometry/doc/src/docutils/tools/doxygen_xml2qbk/sample/src/examples/apple_example.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 1,155 | 2015-01-10T19:04:33.000Z | 2022-03-30T12:30:30.000Z | boost/libs/geometry/doc/src/docutils/tools/doxygen_xml2qbk/sample/src/examples/apple_example.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 623 | 2015-01-02T23:45:23.000Z | 2022-03-09T11:15:23.000Z | boost/libs/geometry/doc/src/docutils/tools/doxygen_xml2qbk/sample/src/examples/apple_example.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 228 | 2015-01-13T12:55:42.000Z | 2022-03-30T11:11:05.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// doxygen_xml2qbk Example
// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to 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)
//[apple
//` Call eat for the apple
#include "fruit.hpp"
int main()
{
fruit::apple<> a("my sample apple");
eat(a);
return 0;
}
//]
//[apple_output
/*`
Output:
[pre
my sample apple
]
*/
//]
| 17.09375 | 79 | 0.683729 | randolphwong |
b97be874b857f111ffc17797c5a9d865a1b160ea | 847 | cpp | C++ | tests-lit/tests/options/-strict/01-strict-mode/sample.cpp | OMantere/mull | 0333c4ced2c407e6fffc48f5fda21dc10ab32c8b | [
"Apache-2.0"
] | null | null | null | tests-lit/tests/options/-strict/01-strict-mode/sample.cpp | OMantere/mull | 0333c4ced2c407e6fffc48f5fda21dc10ab32c8b | [
"Apache-2.0"
] | null | null | null | tests-lit/tests/options/-strict/01-strict-mode/sample.cpp | OMantere/mull | 0333c4ced2c407e6fffc48f5fda21dc10ab32c8b | [
"Apache-2.0"
] | null | null | null | int main() {
return 0;
}
/**
; RUN: cd / && %CLANG_EXEC %s -o %s.exe
; RUN: cd %CURRENT_DIR
; RUN: (unset TERM; %MULL_EXEC -test-framework CustomTest %s.exe 2>&1; test $? = 0) | %FILECHECK_EXEC %s --strict-whitespace --match-full-lines --check-prefix=WITHOUT-OPTION
; RUN: (unset TERM; %MULL_EXEC -strict -test-framework CustomTest %s.exe 2>&1; test $? = 1) | %FILECHECK_EXEC %s --strict-whitespace --match-full-lines --check-prefix=WITH-OPTION
; WITHOUT-OPTION:[warning] No bitcode: x86_64
; WITHOUT-OPTION:[info] No mutants found. Mutation score: infinitely high
; WITH-OPTION:[info] Diagnostics: Strict Mode enabled. Warning messages will be treated as fatal errors.
; WITH-OPTION:[warning] No bitcode: x86_64
; WITH-OPTION:[warning] Strict Mode enabled: warning messages are treated as fatal errors. Exiting now.
; WITH-OPTION-EMPTY:
**/
| 44.578947 | 178 | 0.716647 | OMantere |
b97bf29096e378a5954bcb0cec657dfbe37a02f9 | 2,225 | cpp | C++ | tiled_resources/src/tiled_resources/free_camera.cpp | kingofthebongo2008/computer-games-sofia-univeristy | 1d54a02a456b3dde5eb5793e01a99a76daf6f033 | [
"Apache-2.0"
] | 5 | 2019-03-29T16:47:47.000Z | 2019-05-08T18:34:50.000Z | tiled_resources/src/tiled_resources/free_camera.cpp | kingofthebongo2008/computer-games-sofia-univeristy | 1d54a02a456b3dde5eb5793e01a99a76daf6f033 | [
"Apache-2.0"
] | 3 | 2019-04-21T08:05:04.000Z | 2019-04-21T08:05:44.000Z | tiled_resources/src/tiled_resources/free_camera.cpp | kingofthebongo2008/computer-games-sofia-univeristy | 1d54a02a456b3dde5eb5793e01a99a76daf6f033 | [
"Apache-2.0"
] | null | null | null | //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved
#include "pch.h"
#include "free_camera.h"
using namespace DirectX;
namespace sample
{
FreeCamera::FreeCamera()
{
}
void FreeCamera::SetViewParameters(XMFLOAT3 eye, XMFLOAT3 at, XMFLOAT3 up)
{
m_position = eye;
XMVECTOR orientation = XMQuaternionRotationMatrix
(
XMMatrixLookAtRH( XMLoadFloat3(&eye), XMLoadFloat3(&at), XMLoadFloat3(&up) )
);
XMStoreFloat4(&m_orientation, orientation);
}
void FreeCamera::SetProjectionParameters(float width, float height)
{
XMMATRIX projectionMatrix = XMMatrixPerspectiveFovRH(70.0f * XM_PI / 180.0f, width / height, 1.0f / 256.0f, 256.0f);
XMStoreFloat4x4(&m_projectionMatrix, projectionMatrix);
}
void FreeCamera::ApplyTranslation(XMFLOAT3 delta)
{
XMFLOAT4 deltaVector(delta.x, delta.y, delta.z, 1);
XMVECTOR deltaCameraSpace = XMVector4Transform(XMLoadFloat4(&deltaVector), XMMatrixRotationQuaternion(XMQuaternionInverse(XMLoadFloat4(&m_orientation))));
XMStoreFloat3(&m_position, XMVectorAdd(XMLoadFloat3(&m_position), deltaCameraSpace));
}
void FreeCamera::ApplyRotation(XMFLOAT3 delta)
{
XMStoreFloat4(&m_orientation, XMQuaternionMultiply(XMLoadFloat4(&m_orientation), XMQuaternionRotationRollPitchYawFromVector(XMVectorNegate(XMLoadFloat3(&delta)))));
}
XMFLOAT3 FreeCamera::GetPosition() const
{
return m_position;
}
XMFLOAT4X4 FreeCamera::GetViewMatrix() const
{
XMFLOAT4X4 ret;
XMMATRIX viewMatrix = XMMatrixMultiply(
XMMatrixTranslationFromVector(XMVectorNegate(XMLoadFloat3(&m_position))),
XMMatrixRotationQuaternion(XMLoadFloat4(&m_orientation))
);
XMStoreFloat4x4(&ret, viewMatrix);
return ret;
}
XMFLOAT4X4 FreeCamera::GetProjectionMatrix() const
{
return m_projectionMatrix;
}
} | 31.338028 | 172 | 0.69573 | kingofthebongo2008 |
b97c88a0903d0939b4cfcd092ec6c84cb7a20a4d | 13,357 | cpp | C++ | casablanca/Release/tests/functional/http/client/header_tests.cpp | mentionllc/traintracks-cpp-sdk | c294a463ef2d55bc7b27e35fe7f903d51104c6bd | [
"Apache-2.0"
] | null | null | null | casablanca/Release/tests/functional/http/client/header_tests.cpp | mentionllc/traintracks-cpp-sdk | c294a463ef2d55bc7b27e35fe7f903d51104c6bd | [
"Apache-2.0"
] | null | null | null | casablanca/Release/tests/functional/http/client/header_tests.cpp | mentionllc/traintracks-cpp-sdk | c294a463ef2d55bc7b27e35fe7f903d51104c6bd | [
"Apache-2.0"
] | null | null | null | /***
* ==++==
*
* Copyright (c) Microsoft Corporation. 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.
*
* ==--==
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* Tests cases for http_headers.
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#include "stdafx.h"
#include "cpprest/details/http_helpers.h"
using namespace web::http;
using namespace web::http::client;
using namespace tests::functional::http::utilities;
namespace tests { namespace functional { namespace http { namespace client {
SUITE(outside_tests)
{
TEST_FIXTURE(uri_address, request_headers)
{
test_http_server::scoped_server scoped(m_uri);
test_http_server * p_server = scoped.server();
http_client client(m_uri);
http_request msg(methods::POST);
#ifndef __cplusplus_winrt
// The WinRT-based HTTP stack does not support headers that have no
// value, which means that there is no point in making this particular
// header test, it is an unsupported feature on WinRT.
msg.headers().add(U("HEHE"), U(""));
#endif
msg.headers().add(U("MyHeader"), U("hehe;blach"));
msg.headers().add(U("Yo1"), U("You, Too"));
msg.headers().add(U("Yo2"), U("You2"));
msg.headers().add(U("Yo3"), U("You3"));
msg.headers().add(U("Yo4"), U("You4"));
msg.headers().add(U("Yo5"), U("You5"));
msg.headers().add(U("Yo6"), U("You6"));
msg.headers().add(U("Yo7"), U("You7"));
msg.headers().add(U("Yo8"), U("You8"));
msg.headers().add(U("Yo9"), U("You9"));
msg.headers().add(U("Yo10"), U("You10"));
msg.headers().add(U("Yo11"), U("You11"));
msg.headers().add(U("Accept"), U("text/plain"));
VERIFY_ARE_EQUAL(U("You5"), msg.headers()[U("Yo5")]);
p_server->next_request().then([&](test_request *p_request)
{
http_asserts::assert_test_request_equals(p_request, methods::POST, U("/"));
http_asserts::assert_test_request_contains_headers(p_request, msg.headers());
p_request->reply(200);
});
http_asserts::assert_response_equals(client.request(msg).get(), status_codes::OK);
}
TEST_FIXTURE(uri_address, field_name_casing)
{
test_http_server::scoped_server scoped(m_uri);
http_client client(m_uri);
const method mtd = methods::GET;
const utility::string_t field_name1 = U("CustomHeader");
const utility::string_t field_name2 = U("CUSTOMHEADER");
const utility::string_t field_name3 = U("CuSTomHEAdeR");
const utility::string_t value1 = U("value1");
const utility::string_t value2 = U("value2");
const utility::string_t value3 = U("value3");
http_request msg(mtd);
msg.headers()[field_name1] = value1;
msg.headers()[field_name2].append(U(", ") + value2);
msg.headers()[field_name3].append(U(", ") + value3);
scoped.server()->next_request().then([&](test_request *p_request)
{
http_asserts::assert_test_request_equals(p_request, mtd, U("/"));
std::map<utility::string_t, utility::string_t> expected_headers;
expected_headers[field_name1] = value1 + U(", ") + value2 + U(", ") + value3;
http_asserts::assert_test_request_contains_headers(p_request, expected_headers);
p_request->reply(200);
});
http_asserts::assert_response_equals(client.request(msg).get(), status_codes::OK);
}
TEST_FIXTURE(uri_address, field_name_duplicate)
{
test_http_server::scoped_server scoped(m_uri);
http_client client(m_uri);
const method mtd = methods::GET;
const utility::string_t field_name1 = U("CUSTOMHEADER");
const utility::string_t value1 = U("value1");
const utility::string_t value2 = U("value2");
http_request msg(mtd);
msg.headers().add(field_name1, value1);
msg.headers().add(field_name1, value2);
scoped.server()->next_request().then([&](test_request *p_request)
{
http_asserts::assert_test_request_equals(p_request, mtd, U("/"));
std::map<utility::string_t, utility::string_t> expected_headers;
expected_headers[field_name1] = value1 + U(", ") + value2;
http_asserts::assert_test_request_contains_headers(p_request, expected_headers);
p_request->reply(200);
});
http_asserts::assert_response_equals(client.request(msg).get(), status_codes::OK);
}
TEST_FIXTURE(uri_address, field_name_no_multivalue_allowed)
{
test_http_server::scoped_server scoped(m_uri);
http_client client(m_uri);
const method mtd = methods::GET;
http_request msg(mtd);
msg.headers().set_content_type(web::http::details::mime_types::text_plain);
msg.headers().set_content_type(web::http::details::mime_types::application_json);
scoped.server()->next_request().then([&](test_request *p_request)
{
http_asserts::assert_test_request_equals(p_request, mtd, U("/"));
std::map<utility::string_t, utility::string_t> expected_headers;
expected_headers[U("Content-Type")] = web::http::details::mime_types::application_json;
http_asserts::assert_test_request_contains_headers(p_request, expected_headers);
p_request->reply(200);
});
http_asserts::assert_response_equals(client.request(msg).get(), status_codes::OK);
}
TEST_FIXTURE(uri_address, copy_move)
{
// copy constructor
http_headers h1;
h1.add(U("key1"), U("key2"));
http_headers h2(h1);
http_asserts::assert_http_headers_equals(h1, h2);
// move constructor
http_headers h3(std::move(h1));
VERIFY_ARE_EQUAL(1u, h3.size());
VERIFY_ARE_EQUAL(U("key2"), h3[U("key1")]);
// assignment operator
h1 = h3;
VERIFY_ARE_EQUAL(1u, h1.size());
VERIFY_ARE_EQUAL(U("key2"), h1[U("key1")]);
http_asserts::assert_http_headers_equals(h1, h3);
// move assignment operator
h1 = http_headers();
h1 = std::move(h2);
VERIFY_ARE_EQUAL(1u, h1.size());
VERIFY_ARE_EQUAL(U("key2"), h1[U("key1")]);
}
TEST_FIXTURE(uri_address, match_types)
{
// wchar
http_headers h1;
h1[U("key1")] = U("string");
utility::char_t buf[12];
VERIFY_IS_TRUE(h1.match(U("key1"), buf));
VERIFY_ARE_EQUAL(U("string"), utility::string_t(buf));
// utility::string_t
utility::string_t wstr;
VERIFY_IS_TRUE(h1.match(U("key1"), wstr));
VERIFY_ARE_EQUAL(U("string"), wstr);
// int
h1[U("key2")] = U("22");
int i;
VERIFY_IS_TRUE(h1.match(U("key2"), i));
VERIFY_ARE_EQUAL(22, i);
// unsigned long
unsigned long l;
VERIFY_IS_TRUE(h1.match(U("key2"), l));
VERIFY_ARE_EQUAL(22ul, l);
}
TEST_FIXTURE(uri_address, match_edge_cases)
{
// match with empty string
http_headers h;
h[U("here")] = U("");
utility::string_t value(U("k"));
VERIFY_IS_TRUE(h.match(U("HeRE"), value));
VERIFY_ARE_EQUAL(U(""), value);
// match with string containing spaces
h.add(U("blah"), U("spaces ss"));
VERIFY_IS_TRUE(h.match(U("blah"), value));
VERIFY_ARE_EQUAL(U("spaces ss"), value);
// match failing
value = utility::string_t();
VERIFY_IS_FALSE(h.match(U("hahah"), value));
VERIFY_ARE_EQUAL(U(""), value);
}
TEST_FIXTURE(uri_address, headers_find)
{
// Find when empty.
http_headers h;
VERIFY_ARE_EQUAL(h.end(), h.find(U("key1")));
// Find that exists.
h[U("key1")] = U("yes");
VERIFY_ARE_EQUAL(U("yes"), h.find(U("key1"))->second);
// Find that doesn't exist.
VERIFY_ARE_EQUAL(h.end(), h.find(U("key2")));
}
TEST_FIXTURE(uri_address, headers_add)
{
// Add multiple
http_headers h;
h.add(U("key1"), 22);
h.add(U("key2"), U("str2"));
VERIFY_ARE_EQUAL(U("22"), h[U("key1")]);
VERIFY_ARE_EQUAL(U("str2"), h[U("key2")]);
// Add one that already exists
h.add(U("key2"), U("str3"));
VERIFY_ARE_EQUAL(U("str2, str3"), h[U("key2")]);
// Add with different case
h.add(U("KEY2"), U("str4"));
VERIFY_ARE_EQUAL(U("str2, str3, str4"), h[U("keY2")]);
// Add with spaces in string
h.add(U("key3"), U("value with spaces"));
VERIFY_ARE_EQUAL(U("value with spaces"), h[U("key3")]);
}
TEST_FIXTURE(uri_address, headers_iterators)
{
// begin when empty
http_headers h;
VERIFY_ARE_EQUAL(h.begin(), h.end());
// with some values.
h.add(U("key1"), U("value1"));
h.add(U("key2"), U("value2"));
h.add(U("key3"), U("value3"));
http_headers::const_iterator iter = h.begin();
VERIFY_ARE_EQUAL(U("value1"), iter->second);
++iter;
VERIFY_ARE_EQUAL(U("value2"), iter->second);
++iter;
VERIFY_ARE_EQUAL(U("value3"), iter->second);
++iter;
VERIFY_ARE_EQUAL(h.end(), iter);
}
TEST_FIXTURE(uri_address, headers_foreach)
{
// begin when empty
http_headers h;
VERIFY_ARE_EQUAL(h.begin(), h.end());
// with some values.
h.add(U("key1"), U("value"));
h.add(U("key2"), U("value"));
h.add(U("key3"), U("value"));
std::for_each(std::begin(h), std::end(h),
[=](http_headers::const_reference kv)
{
VERIFY_ARE_EQUAL(U("value"), kv.second);
});
std::for_each(std::begin(h), std::end(h),
[=](http_headers::reference kv)
{
VERIFY_ARE_EQUAL(U("value"), kv.second);
});
}
TEST_FIXTURE(uri_address, response_headers)
{
test_http_server::scoped_server scoped(m_uri);
http_client client(m_uri);
std::map<utility::string_t, utility::string_t> headers;
headers[U("H1")] = U("");
headers[U("H2")] = U("hah");
headers[U("H3")] = U("es");
headers[U("H4")] = U("es;kjr");
headers[U("H5")] = U("asb");
headers[U("H6")] = U("abc");
headers[U("H7")] = U("eds");
headers[U("H8")] = U("blue");
headers[U("H9")] = U("sd");
headers[U("H10")] = U("res");
test_server_utilities::verify_request(&client, methods::GET, U("/"), scoped.server(), status_codes::OK, headers);
}
TEST_FIXTURE(uri_address, cache_control_header)
{
http_headers headers;
VERIFY_ARE_EQUAL(headers.cache_control(), U(""));
const utility::string_t value(U("custom value"));
headers.set_cache_control(value);
VERIFY_ARE_EQUAL(headers.cache_control(), value);
utility::string_t foundValue;
VERIFY_IS_TRUE(headers.match(header_names::cache_control, foundValue));
VERIFY_ARE_EQUAL(value, foundValue);
}
TEST_FIXTURE(uri_address, content_length_header)
{
http_headers headers;
VERIFY_ARE_EQUAL(headers.content_length(), 0);
const size_t value = 44;
headers.set_content_length(value);
VERIFY_ARE_EQUAL(headers.content_length(), value);
size_t foundValue;
VERIFY_IS_TRUE(headers.match(header_names::content_length, foundValue));
VERIFY_ARE_EQUAL(value, foundValue);
}
TEST_FIXTURE(uri_address, date_header)
{
http_headers headers;
VERIFY_ARE_EQUAL(headers.date(), U(""));
const utility::datetime value(utility::datetime::utc_now());
headers.set_date(value);
VERIFY_ARE_EQUAL(headers.date(), value.to_string());
utility::string_t foundValue;
VERIFY_IS_TRUE(headers.match(header_names::date, foundValue));
VERIFY_ARE_EQUAL(value.to_string(), foundValue);
}
TEST_FIXTURE(uri_address, parsing_content_type_redundantsemicolon_json)
{
test_http_server::scoped_server scoped(m_uri);
web::json::value body = web::json::value::string(U("Json body"));
scoped.server()->next_request().then([&](test_request *p_request){
std::map<utility::string_t, utility::string_t> headers;
headers[header_names::content_type] = U("application/json; charset=utf-8;;;;");
p_request->reply(200, U("OK"), headers, utility::conversions::to_utf8string(body.serialize()));
});
http_client client(m_uri);
auto resp = client.request(methods::GET).get();
VERIFY_ARE_EQUAL(resp.extract_json().get().serialize(), body.serialize());
}
TEST_FIXTURE(uri_address, parsing_content_type_redundantsemicolon_string)
{
test_http_server::scoped_server scoped(m_uri);
std::string body("Body");
scoped.server()->next_request().then([&](test_request *p_request){
std::map<utility::string_t, utility::string_t> headers;
headers[header_names::content_type] = U("text/plain; charset = UTF-8;;;; ");
p_request->reply(200, U("OK"), headers, body);
});
http_client client(m_uri);
auto resp = client.request(methods::GET).get();
VERIFY_ARE_EQUAL(resp.extract_string().get(), utility::conversions::to_string_t(body));
}
} // SUITE(header_tests)
}}}} | 34.514212 | 118 | 0.629558 | mentionllc |
b97ca4d4c04145b91be6af8b103c3074c841f10b | 4,958 | cpp | C++ | tests/cplusplus/Common/RegStringMap.cpp | sagpant/OSVR-Core | 495648e4c94d6e8a1ffb74aa00b69deada1a9b51 | [
"Apache-2.0"
] | 369 | 2015-03-08T03:12:41.000Z | 2022-02-08T22:15:39.000Z | tests/cplusplus/Common/RegStringMap.cpp | sagpant/OSVR-Core | 495648e4c94d6e8a1ffb74aa00b69deada1a9b51 | [
"Apache-2.0"
] | 486 | 2015-03-09T13:29:00.000Z | 2020-10-16T00:41:26.000Z | tests/cplusplus/Common/RegStringMap.cpp | itguy327/OSVR-Core | 495648e4c94d6e8a1ffb74aa00b69deada1a9b51 | [
"Apache-2.0"
] | 166 | 2015-03-08T12:03:56.000Z | 2021-12-03T13:56:21.000Z | /** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include <osvr/Common/RegisteredStringMap.h>
// Library/third-party includes
#include <catch2/catch.hpp>
// Standard includes
#include <string>
using osvr::common::CorrelatedStringMap;
using osvr::common::RegisteredStringMap;
using osvr::util::PeerStringID;
using osvr::util::StringID;
TEST_CASE("RegisteredStringMap-create") {
RegisteredStringMap regMap;
REQUIRE(0 == regMap.getEntries().size());
REQUIRE_FALSE(regMap.isModified());
}
TEST_CASE("RegisteredStringMap-addNewValues") {
RegisteredStringMap regMap;
StringID regID0 = regMap.registerStringID("RegVal0");
REQUIRE(regMap.isModified());
REQUIRE(1 == regMap.getEntries().size());
StringID regID1 = regMap.registerStringID("RegVal1");
REQUIRE(regMap.isModified());
REQUIRE(2 == regMap.getEntries().size());
StringID regID2 = regMap.registerStringID("RegVal2");
REQUIRE(regMap.isModified());
REQUIRE(3 == regMap.getEntries().size());
}
class RegisteredStringMapTest {
public:
RegisteredStringMapTest() {
regID0 = regMap.registerStringID("RegVal0");
regID1 = regMap.registerStringID("RegVal1");
regID2 = regMap.registerStringID("RegVal2");
corID0 = corMap.registerStringID("CorVal0");
corID1 = corMap.registerStringID("CorVal1");
corID2 = corMap.registerStringID("CorVal2");
}
RegisteredStringMap regMap;
CorrelatedStringMap corMap;
StringID regID0, regID1, regID2;
StringID corID0, corID1, corID2;
};
TEST_CASE_METHOD(RegisteredStringMapTest,
"RegisteredStringMapTest-checkExistingValues") {
regMap.clearModifiedFlag();
StringID regID = regMap.registerStringID("RegVal0");
REQUIRE_FALSE(regMap.isModified());
REQUIRE(3 == regMap.getEntries().size());
REQUIRE(0 == regID.value());
regID = regMap.registerStringID("RegVal1");
REQUIRE_FALSE(regMap.isModified());
REQUIRE(3 == regMap.getEntries().size());
REQUIRE(1 == regID.value());
regID = regMap.registerStringID("RegVal2");
REQUIRE_FALSE(regMap.isModified());
REQUIRE(3 == regMap.getEntries().size());
REQUIRE(2 == regID.value());
}
TEST_CASE_METHOD(RegisteredStringMapTest, "RegisteredStringMapTest-getValues") {
REQUIRE("RegVal0" == regMap.getStringFromId(regID0));
REQUIRE("RegVal1" == regMap.getStringFromId(regID1));
REQUIRE("RegVal2" == regMap.getStringFromId(regID2));
REQUIRE(regMap.getStringFromId(StringID(1000)).empty());
REQUIRE("CorVal0" == corMap.getStringFromId(corID0));
REQUIRE("CorVal1" == corMap.getStringFromId(corID1));
REQUIRE("CorVal2" == corMap.getStringFromId(corID2));
REQUIRE(corMap.getStringFromId(StringID(1000)).empty());
}
TEST_CASE_METHOD(RegisteredStringMapTest,
"RegisteredStringMapTest-getEntries") {
auto entries = regMap.getEntries();
REQUIRE(3 == entries.size());
REQUIRE("RegVal0" == entries[0]);
REQUIRE("RegVal1" == entries[1]);
REQUIRE("RegVal2" == entries[2]);
}
TEST_CASE_METHOD(RegisteredStringMapTest,
"RegisteredStringMapTest-checkModified") {
regMap.clearModifiedFlag();
REQUIRE_FALSE(regMap.isModified());
}
TEST_CASE_METHOD(RegisteredStringMapTest,
"RegisteredStringMapTest-checkOutOfRangePeerID") {
REQUIRE_THROWS_AS(corMap.convertPeerToLocalID(PeerStringID(100)),
std::out_of_range);
}
TEST_CASE_METHOD(RegisteredStringMapTest,
"RegisteredStringMapTest-checkEmptyPeerMapping") {
StringID emptID = corMap.convertPeerToLocalID(PeerStringID());
REQUIRE(emptID.empty());
}
TEST_CASE_METHOD(RegisteredStringMapTest,
"RegisteredStringMapTest-checkSetupPeerMappings") {
auto entries = regMap.getEntries();
corMap.setupPeerMappings(entries);
StringID corID3 = corMap.convertPeerToLocalID(PeerStringID(regID0.value()));
StringID corID4 = corMap.convertPeerToLocalID(PeerStringID(regID1.value()));
StringID corID5 = corMap.convertPeerToLocalID(PeerStringID(regID2.value()));
REQUIRE("RegVal0" == corMap.getStringFromId(corID3));
REQUIRE("RegVal1" == corMap.getStringFromId(corID4));
REQUIRE("RegVal2" == corMap.getStringFromId(corID5));
}
| 31.18239 | 80 | 0.705325 | sagpant |
b980d0bb1e9681aed2897bd6ab4d4309b537c5f9 | 414 | cc | C++ | cpp/src/day-19/main.cc | raphaelmeyer/advent-of-code-2021 | bf6c03d3143e44e4568ce0fa5c694773b5b20972 | [
"MIT"
] | null | null | null | cpp/src/day-19/main.cc | raphaelmeyer/advent-of-code-2021 | bf6c03d3143e44e4568ce0fa5c694773b5b20972 | [
"MIT"
] | null | null | null | cpp/src/day-19/main.cc | raphaelmeyer/advent-of-code-2021 | bf6c03d3143e44e4568ce0fa5c694773b5b20972 | [
"MIT"
] | null | null | null | #include <iostream>
#include "scanner.h"
int main() {
auto const scanners = scanner::parse_file("data/day-19.txt");
auto const corrections = find_scanners(scanners);
auto const beacons = scanner::number_of_beacons(scanners, corrections);
auto const distance = scanner::max_manhatten_distance(corrections);
std::cout << "Part 1: " << beacons << "\n";
std::cout << "Part 2: " << distance << "\n";
}
| 25.875 | 73 | 0.678744 | raphaelmeyer |
b98551ed73488f05e94e6dd62f57562b6462a12e | 1,752 | cpp | C++ | IREMedia/examples/cpp/Example_2_1_SDK.cpp | i4Ds/IRE | 0bb70ae24fd3ad79c9df6fc84b6087ce663624a7 | [
"Apache-2.0"
] | 13 | 2015-03-01T07:03:17.000Z | 2021-11-03T06:33:31.000Z | IREMedia/examples/cpp/Example_2_1_SDK.cpp | i4Ds/IRE | 0bb70ae24fd3ad79c9df6fc84b6087ce663624a7 | [
"Apache-2.0"
] | null | null | null | IREMedia/examples/cpp/Example_2_1_SDK.cpp | i4Ds/IRE | 0bb70ae24fd3ad79c9df6fc84b6087ce663624a7 | [
"Apache-2.0"
] | 3 | 2015-03-10T20:40:31.000Z | 2020-07-16T08:05:42.000Z | #include "Common.h"
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
class Example_SdkInit {
protected:
float fps;
public:
virtual int run() {
/*SAY("Initializing SDK");
ovr_Initialize();
SAY("De-initializing the SDK");
ovr_Shutdown();
SAY("Exiting");*/
CvCapture* cam = cvCaptureFromCAM(700);
//cvSetCaptureProperty(cam, CV_CAP_PROP_FPS, 60);
//cvSetCaptureProperty(cam, CV_CAP_PROP_FRAME_WIDTH, 1280);
//cvSetCaptureProperty(cam, CV_CAP_PROP_FRAME_HEIGHT, 720);
cvSetCaptureProperty(cam, CV_CAP_PROP_FOURCC, CV_FOURCC('M', 'J', 'P', 'G'));
cvSetCaptureProperty(cam, CV_CAP_PROP_FRAME_WIDTH, 1280);
cvSetCaptureProperty(cam, CV_CAP_PROP_FRAME_HEIGHT, 720);
CvCapture* cam2 = cvCaptureFromCAM(701);
//cvSetCaptureProperty(cam2, CV_CAP_PROP_FPS, 60);
//cvSetCaptureProperty(cam2, CV_CAP_PROP_FRAME_WIDTH, 1280);
//cvSetCaptureProperty(cam2, CV_CAP_PROP_FRAME_HEIGHT, 720);
cvSetCaptureProperty(cam2, CV_CAP_PROP_FOURCC, CV_FOURCC('M', 'J', 'P', 'G'));
cvSetCaptureProperty(cam2, CV_CAP_PROP_FRAME_WIDTH, 1280);
cvSetCaptureProperty(cam2, CV_CAP_PROP_FRAME_HEIGHT, 720);
int framecount = 0;
long start = Platform::elapsedMillis();
IplImage* image;
IplImage* iamgeTwo;
while (true) {
image = cvQueryFrame(cam);
iamgeTwo = cvQueryFrame(cam2);
//cvShowImage("One", image);
//cvShowImage("Two", iamgeTwo);
long now = Platform::elapsedMillis();
++framecount;
if ((now - start) >= 2000) {
float elapsed = (now - start) / 1000.f;
fps = (float)framecount / elapsed;
SAY("FPS: %0.2f\n", fps);
start = now;
framecount = 0;
}
//cvWaitKey(1);
//Sleep(100);
}
return 0;
}
};
RUN_APP(Example_SdkInit);
| 26.149254 | 80 | 0.697489 | i4Ds |
b9862267f72f660edbae79206a7407820cc6e9f5 | 1,081 | hpp | C++ | include/boost/safe_float/policy/check_division_underflow.hpp | aTom3333/safefloat | 760a1fa243672d49271836e8c431f002a615eca5 | [
"BSL-1.0"
] | 1 | 2019-08-08T01:24:16.000Z | 2019-08-08T01:24:16.000Z | include/boost/safe_float/policy/check_division_underflow.hpp | aTom3333/safefloat | 760a1fa243672d49271836e8c431f002a615eca5 | [
"BSL-1.0"
] | null | null | null | include/boost/safe_float/policy/check_division_underflow.hpp | aTom3333/safefloat | 760a1fa243672d49271836e8c431f002a615eca5 | [
"BSL-1.0"
] | 2 | 2019-05-28T11:31:09.000Z | 2019-10-12T21:55:25.000Z | #ifndef BOOST_SAFE_FLOAT_POLICY_CHECK_DIVISION_UNDERFLOW_HPP
#define BOOST_SAFE_FLOAT_POLICY_CHECK_DIVISION_UNDERFLOW_HPP
#include <boost/safe_float/policy/check_base_policy.hpp>
#ifdef FENV_AVAILABLE
#pragma STDC FENV_ACCESS ON
#include <fenv.h>
#endif
namespace boost {
namespace safe_float{
namespace policy{
template<class FP>
class check_division_underflow : public check_policy<FP> {
#ifndef FENV_AVAILABLE
bool expect_zero;
#endif
public:
bool pre_division_check(const FP& lhs, const FP& rhs){
#ifndef FENV_AVAILABLE
expect_zero = (lhs==0);
return true;
#else
return ! std::feclearexcept(FE_UNDERFLOW);
#endif
}
bool post_division_check(const FP& rhs){
#ifndef FENV_AVAILABLE
return (std::fpclassify( rhs ) != FP_SUBNORMAL)
&& (rhs != 0 || expect_zero);
#else
return ! std::fetestexcept(FE_UNDERFLOW);
#endif
}
std::string division_failure_message(){
return std::string("Underflow from operation");
}
};
}
}
}
#endif // BOOST_SAFE_FLOAT_POLICY_CHECK_DIVISION_UNDERFLOW_HPP
| 21.62 | 62 | 0.723404 | aTom3333 |
b98a990c934c3475c3f717c25434c26e3f732677 | 7,488 | cpp | C++ | AudioSources/AverageProcessor.cpp | MeijisIrlnd/airwindows | e2818f43711fa8b6f424d31824c35bb47bb82140 | [
"MIT"
] | 2 | 2021-03-02T05:14:39.000Z | 2022-03-19T01:47:57.000Z | Examples/Average/Source/AverageProcessor.cpp | MeijisIrlnd/airwindows | e2818f43711fa8b6f424d31824c35bb47bb82140 | [
"MIT"
] | null | null | null | Examples/Average/Source/AverageProcessor.cpp | MeijisIrlnd/airwindows | e2818f43711fa8b6f424d31824c35bb47bb82140 | [
"MIT"
] | null | null | null | /* ========================================
* Average - Average.h
* Copyright (c) 2016 airwindows, All rights reserved
* ======================================== */
#include "AverageProcessor.h"
AverageProcessor::AverageProcessor()
{
paramBindings =
{
{AVERAGE, &A},
{DRY_WET, &B}
};
A = 0.0;
B = 1.0;
for (int count = 0; count < 11; count++) { bL[count] = 0.0; bR[count] = 0.0; f[count] = 0.0; }
fpNShapeL = 0.0;
fpNShapeR = 0.0;
}
AverageProcessor::~AverageProcessor()
{
}
void AverageProcessor::setParam(PARAMETER p, float v)
{
if (paramBindings.find(p) != paramBindings.end())
{
*paramBindings[p] = v;
}
}
void AverageProcessor::prepareToPlay(int samplesPerBlockExpected, double sampleRate)
{
sr = sampleRate;
}
void AverageProcessor::getNextAudioBlock(const juce::AudioSourceChannelInfo& bufferToFill)
{
auto* rpL = bufferToFill.buffer->getReadPointer(0);
auto* rpR = bufferToFill.buffer->getReadPointer(1);
auto* wpL = bufferToFill.buffer->getWritePointer(0);
auto* wpR = bufferToFill.buffer->getWritePointer(1);
double correctionSample;
double accumulatorSampleL;
double accumulatorSampleR;
double drySampleL;
double drySampleR;
double inputSampleL;
double inputSampleR;
double overallscale = (A * 9.0) + 1.0;
double wet = B;
double dry = 1.0 - wet;
double gain = overallscale;
if (gain > 1.0) { f[0] = 1.0; gain -= 1.0; }
else { f[0] = gain; gain = 0.0; }
if (gain > 1.0) { f[1] = 1.0; gain -= 1.0; }
else { f[1] = gain; gain = 0.0; }
if (gain > 1.0) { f[2] = 1.0; gain -= 1.0; }
else { f[2] = gain; gain = 0.0; }
if (gain > 1.0) { f[3] = 1.0; gain -= 1.0; }
else { f[3] = gain; gain = 0.0; }
if (gain > 1.0) { f[4] = 1.0; gain -= 1.0; }
else { f[4] = gain; gain = 0.0; }
if (gain > 1.0) { f[5] = 1.0; gain -= 1.0; }
else { f[5] = gain; gain = 0.0; }
if (gain > 1.0) { f[6] = 1.0; gain -= 1.0; }
else { f[6] = gain; gain = 0.0; }
if (gain > 1.0) { f[7] = 1.0; gain -= 1.0; }
else { f[7] = gain; gain = 0.0; }
if (gain > 1.0) { f[8] = 1.0; gain -= 1.0; }
else { f[8] = gain; gain = 0.0; }
if (gain > 1.0) { f[9] = 1.0; gain -= 1.0; }
else { f[9] = gain; gain = 0.0; }
//there, now we have a neat little moving average with remainders
if (overallscale < 1.0) overallscale = 1.0;
f[0] /= overallscale;
f[1] /= overallscale;
f[2] /= overallscale;
f[3] /= overallscale;
f[4] /= overallscale;
f[5] /= overallscale;
f[6] /= overallscale;
f[7] /= overallscale;
f[8] /= overallscale;
f[9] /= overallscale;
//and now it's neatly scaled, too
for (auto sample = 0; sample < bufferToFill.numSamples; sample++)
{
long double inputSampleL = *rpL;
long double inputSampleR = *rpR;
if (inputSampleL < 1.2e-38 && -inputSampleL < 1.2e-38) {
static int noisesource = 0;
//this declares a variable before anything else is compiled. It won't keep assigning
//it to 0 for every sample, it's as if the declaration doesn't exist in this context,
//but it lets me add this denormalization fix in a single place rather than updating
//it in three different locations. The variable isn't thread-safe but this is only
//a random seed and we can share it with whatever.
noisesource = noisesource % 1700021; noisesource++;
int residue = noisesource * noisesource;
residue = residue % 170003; residue *= residue;
residue = residue % 17011; residue *= residue;
residue = residue % 1709; residue *= residue;
residue = residue % 173; residue *= residue;
residue = residue % 17;
double applyresidue = residue;
applyresidue *= 0.00000001;
applyresidue *= 0.00000001;
inputSampleL = applyresidue;
}
if (inputSampleR < 1.2e-38 && -inputSampleR < 1.2e-38) {
static int noisesource = 0;
noisesource = noisesource % 1700021; noisesource++;
int residue = noisesource * noisesource;
residue = residue % 170003; residue *= residue;
residue = residue % 17011; residue *= residue;
residue = residue % 1709; residue *= residue;
residue = residue % 173; residue *= residue;
residue = residue % 17;
double applyresidue = residue;
applyresidue *= 0.00000001;
applyresidue *= 0.00000001;
inputSampleR = applyresidue;
//this denormalization routine produces a white noise at -300 dB which the noise
//shaping will interact with to produce a bipolar output, but the noise is actually
//all positive. That should stop any variables from going denormal, and the routine
//only kicks in if digital black is input. As a final touch, if you save to 24-bit
//the silence will return to being digital black again.
}
drySampleL = inputSampleL;
drySampleR = inputSampleR;
bL[9] = bL[8]; bL[8] = bL[7]; bL[7] = bL[6]; bL[6] = bL[5];
bL[5] = bL[4]; bL[4] = bL[3]; bL[3] = bL[2]; bL[2] = bL[1];
bL[1] = bL[0]; bL[0] = accumulatorSampleL = inputSampleL;
bR[9] = bR[8]; bR[8] = bR[7]; bR[7] = bR[6]; bR[6] = bR[5];
bR[5] = bR[4]; bR[4] = bR[3]; bR[3] = bR[2]; bR[2] = bR[1];
bR[1] = bR[0]; bR[0] = accumulatorSampleR = inputSampleR;
//primitive way of doing this: for larger batches of samples, you might
//try using a circular buffer like in a reverb. If you add the new sample
//and subtract the one on the end you can keep a running tally of the samples
//between. Beware of tiny floating-point math errors eventually screwing up
//your system, though!
accumulatorSampleL *= f[0];
accumulatorSampleL += (bL[1] * f[1]);
accumulatorSampleL += (bL[2] * f[2]);
accumulatorSampleL += (bL[3] * f[3]);
accumulatorSampleL += (bL[4] * f[4]);
accumulatorSampleL += (bL[5] * f[5]);
accumulatorSampleL += (bL[6] * f[6]);
accumulatorSampleL += (bL[7] * f[7]);
accumulatorSampleL += (bL[8] * f[8]);
accumulatorSampleL += (bL[9] * f[9]);
accumulatorSampleR *= f[0];
accumulatorSampleR += (bR[1] * f[1]);
accumulatorSampleR += (bR[2] * f[2]);
accumulatorSampleR += (bR[3] * f[3]);
accumulatorSampleR += (bR[4] * f[4]);
accumulatorSampleR += (bR[5] * f[5]);
accumulatorSampleR += (bR[6] * f[6]);
accumulatorSampleR += (bR[7] * f[7]);
accumulatorSampleR += (bR[8] * f[8]);
accumulatorSampleR += (bR[9] * f[9]);
//we are doing our repetitive calculations on a separate value
correctionSample = inputSampleL - accumulatorSampleL;
//we're gonna apply the total effect of all these calculations as a single subtract
inputSampleL -= correctionSample;
correctionSample = inputSampleR - accumulatorSampleR;
inputSampleR -= correctionSample;
//our one math operation on the input data coming in
if (wet < 1.0) {
inputSampleL = (inputSampleL * wet) + (drySampleL * dry);
inputSampleR = (inputSampleR * wet) + (drySampleR * dry);
}
//dry/wet control only applies if you're using it. We don't do a multiply by 1.0
//if it 'won't change anything' but our sample might be at a very different scaling
//in the floating point system.
//stereo 32 bit dither, made small and tidy.
int expon; frexpf((float)inputSampleL, &expon);
long double dither = (rand() / (RAND_MAX * 7.737125245533627e+25)) * pow(2, expon + 62);
inputSampleL += (dither - fpNShapeL); fpNShapeL = dither;
frexpf((float)inputSampleR, &expon);
dither = (rand() / (RAND_MAX * 7.737125245533627e+25)) * pow(2, expon + 62);
inputSampleR += (dither - fpNShapeR); fpNShapeR = dither;
//end 32 bit dither
*wpL = inputSampleL;
*wpR = inputSampleR;
++rpL;
++rpR;
++wpL;
++wpR;
}
}
void AverageProcessor::releaseResources()
{
}
| 34.666667 | 98 | 0.633948 | MeijisIrlnd |
b98b70d92418f5dfb400dec82d785426b7496e85 | 1,553 | cpp | C++ | runa/widgets/button_cfg.cpp | walkinsky8/nana-runner | 103992e07e7e644d349437fdf959364ffe9cb653 | [
"BSL-1.0"
] | 5 | 2017-12-28T08:22:20.000Z | 2022-03-30T01:26:17.000Z | runa/widgets/button_cfg.cpp | walkinsky8/nana-runner | 103992e07e7e644d349437fdf959364ffe9cb653 | [
"BSL-1.0"
] | null | null | null | runa/widgets/button_cfg.cpp | walkinsky8/nana-runner | 103992e07e7e644d349437fdf959364ffe9cb653 | [
"BSL-1.0"
] | null | null | null | /**
* Runa C++ Library
* Copyright (c) 2017-2019 walkinsky:lyh6188(at)hotmail(dot)com
*
* 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)
*/
// Created on 2017/11/15
#include "stdafx.h"
#ifndef __NANA_RUNNER_LIB_ALL_IN_ONE
#include <runa/widgets/button_cfg.h>
#include <runa/foundation/app_base.h>
void runa::button_cfg::init_widget(widget & _w, view_obj* _root_view) const
{
super::init_widget(_w, _root_view);
auto& w = dynamic_cast<ui_type&>(_w);
if (!icon_().empty())
{
w.icon(app::create_image(icon_()));
}
if (!borderless_().empty())
w.borderless(borderless_().value());
if (!enable_pushed_().empty())
w.enable_pushed(enable_pushed_().value());
if (!pushed_().empty())
w.pushed(pushed_().value());
if (!omitted_().empty())
w.omitted(omitted_().value());
if (!enable_focus_color_().empty())
w.enable_focus_color(enable_focus_color_().value());
if (!transparent_().empty())
w.transparent(transparent_().value());
if (!edge_effects_().empty())
w.edge_effects(edge_effects_().value());
if (!_click_().empty())
{
if (_click_() == "quit")
w.events().click(app::quit);
else if (_click_() == "close")
w.events().click([_root_view] {_root_view->close(); });
else
{
w.events().click([&] {app::create_view(_click_()); });
}
}
}
#endif
| 23.892308 | 75 | 0.600773 | walkinsky8 |
b98d1e9d6beb6c36eaa318dbd39b9244d9b19e75 | 6,851 | cpp | C++ | src/gui/graphtitlebar.cpp | evoplex/evoplex | c6e78af5fb0d2fc5a5ce7b02e5e4ec61de8934b6 | [
"Apache-2.0"
] | 101 | 2018-06-21T04:29:18.000Z | 2022-03-09T13:04:15.000Z | src/gui/graphtitlebar.cpp | ElsevierSoftwareX/SOFTX_2018_211 | cbfac5af0ad76b7c88a7ea296d94785692da3048 | [
"Apache-2.0"
] | 30 | 2018-06-26T15:12:03.000Z | 2019-10-10T04:02:13.000Z | src/gui/graphtitlebar.cpp | ElsevierSoftwareX/SOFTX_2018_211 | cbfac5af0ad76b7c88a7ea296d94785692da3048 | [
"Apache-2.0"
] | 23 | 2018-06-23T16:10:24.000Z | 2021-11-03T15:12:51.000Z | /**
* This file is part of Evoplex.
*
* Evoplex is a multi-agent system for networks.
* Copyright (C) 2018 - Marcos Cardinot <marcos@cardinot.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QFileDialog>
#include <QMessageBox>
#include <QProgressDialog>
#include <QtSvg/QSvgGenerator>
#include "core/nodes_p.h"
#include "core/project.h"
#include "core/trial.h"
#include "graphtitlebar.h"
#include "graphwidget.h"
#include "basegraphgl.h"
#include "ui_graphtitlebar.h"
namespace evoplex {
GraphTitleBar::GraphTitleBar(const Experiment* exp, GraphWidget* parent)
: BaseTitleBar(parent),
m_ui(new Ui_GraphTitleBar),
m_graphWidget(parent),
m_exp(exp),
m_bExportNodes(new QtMaterialIconButton(QIcon(":/icons/material/table_white_18"), this)),
m_bSettings(new QtMaterialIconButton(QIcon(":/icons/material/settings_white_18"), this)),
m_bScreenShot(new QtMaterialIconButton(QIcon(":/icons/material/screenshot_white_18"), this))
{
m_ui->setupUi(this);
m_bScreenShot->setToolTip("export as image");
m_bScreenShot->setIconSize(QSize(22,18));
m_bScreenShot->setColor(m_iconColor);
m_ui->btns->addWidget(m_bScreenShot);
connect(m_bScreenShot, SIGNAL(pressed()), SLOT(slotExportImage()));
m_bExportNodes->setToolTip("export nodes to file");
m_bExportNodes->setIconSize(QSize(22,18));
m_bExportNodes->setColor(m_iconColor);
m_ui->btns->addWidget(m_bExportNodes);
connect(m_bExportNodes, SIGNAL(pressed()), SLOT(slotExportNodes()));
m_bSettings->setToolTip("graph settings");
m_bSettings->setIconSize(QSize(22,18));
m_bSettings->setColor(m_iconColor);
m_ui->btns->addWidget(m_bSettings);
connect(m_bSettings, SIGNAL(pressed()), SIGNAL(openSettingsDlg()));
connect(m_ui->cbTrial, QOverload<int>::of(&QComboBox::currentIndexChanged),
[this](int t) {
Q_ASSERT(t >= 0 && t < UINT16_MAX);
emit(trialSelected(static_cast<quint16>(t)));
});
connect(m_exp, SIGNAL(restarted()), SLOT(slotRestarted()));
slotRestarted(); // init
init(qobject_cast<QHBoxLayout*>(layout()));
}
GraphTitleBar::~GraphTitleBar()
{
delete m_ui;
}
void GraphTitleBar::slotExportImage()
{
if (!readyToExport()) {
return;
}
QString path = guessInitialPath(".png");
path = QFileDialog::getSaveFileName(this, "Export Nodes", path,
"Image files (*.svg *.png *.jpg *.jpeg)");
if (path.isEmpty()) {
return;
}
if (path.endsWith(".svg")) {
QSvgGenerator g;
g.setFileName(path);
g.setSize(m_graphWidget->view()->frameSize());
g.setViewBox(m_graphWidget->view()->rect());
g.setTitle("Evoplex");
g.setDescription("Created with Evoplex (https://evoplex.org).");
g.setResolution(300);
m_graphWidget->view()->paint(&g, false);
} else {
QSettings userPrefs;
QImage img(m_graphWidget->view()->frameSize(), QImage::Format_ARGB32);
m_graphWidget->view()->paint(&img, false);
img.save(path, Q_NULLPTR, userPrefs.value("settings/imgQuality", 90).toInt());
}
}
void GraphTitleBar::slotExportNodes()
{
if (!readyToExport()) {
return;
}
QString path = guessInitialPath("_nodes.csv");
path = QFileDialog::getSaveFileName(this, "Export Nodes", path, "Text Files (*.csv)");
if (path.isEmpty()) {
return;
}
auto trial = m_exp->trial(m_ui->cbTrial->currentText().toUShort());
QProgressDialog progressDlg("Exporting nodes", QString(), 0, trial->graph()->numNodes(), this);
progressDlg.setWindowModality(Qt::WindowModal);
progressDlg.setValue(0);
std::function<void(int)> progress = [&progressDlg](int p) { progressDlg.setValue(p); };
if (NodesPrivate::saveToFile(trial->graph()->nodes(), path, progress)) {
QMessageBox::information(this, "Exporting nodes",
"The set of nodes was saved successfully!\n" + path);
} else {
QMessageBox::warning(this, "Exporting nodes",
"ERROR! Unable to save the set of nodes at:\n"
+ path + "\nPlease, make sure this directory is writable.");
}
}
void GraphTitleBar::slotRestarted()
{
const quint16 currTrial = m_ui->cbTrial->currentText().toUShort();
m_ui->cbTrial->blockSignals(true);
m_ui->cbTrial->clear();
for (quint16 trialId = 0; trialId < m_exp->numTrials(); ++trialId) {
m_ui->cbTrial->insertItem(trialId, QString::number(trialId));
}
m_ui->cbTrial->setCurrentText(QString::number(currTrial)); // try to keep the same id
m_ui->cbTrial->blockSignals(false);
const quint16 _currTrial = m_ui->cbTrial->currentText().toUShort();
if (currTrial != _currTrial) {
emit(trialSelected(_currTrial));
}
}
bool GraphTitleBar::readyToExport()
{
if (m_exp->expStatus() == Status::Disabled ||
m_exp->expStatus() == Status::Invalid) {
QMessageBox::warning(this, "Exporting nodes",
"This experiment is invalid or has not been initialized yet.\n"
"Please, initialize the experiment and try again.");
return false;
}
if (m_exp->expStatus() == Status::Running ||
m_exp->expStatus() == Status::Queued) {
QMessageBox::warning(this, "Exporting nodes",
"Please, pause the experiment and try again.");
return false;
}
const quint16 currTrial = m_ui->cbTrial->currentText().toUShort();
auto trial = m_exp->trial(currTrial);
if (!trial || trial->graph()->nodes().empty()) {
QMessageBox::warning(this, "Exporting nodes",
"Could not export the set of nodes.\n"
"Please, make sure this experiment is valid and that "
"there are nodes to be exported!");
return false;
}
return true;
}
QString GraphTitleBar::guessInitialPath(const QString& filename) const
{
QString path = m_exp->project()->filepath();
QDir dir = path.isEmpty() ? QDir::home() : QFileInfo(path).dir();
path = dir.absoluteFilePath(QString("%1_exp%2%3")
.arg(m_exp->project()->name()).arg(m_exp->id()).arg(filename));
return path;
}
} // evoplex
| 34.60101 | 99 | 0.652897 | evoplex |
b98f9c6da292c86c57f277aa1f99a9aaf9c40ad0 | 2,683 | cc | C++ | src/instrumentation/converter/convert_to_string/convergence_to_string.cc | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 12 | 2018-03-14T12:30:53.000Z | 2022-01-23T14:46:44.000Z | src/instrumentation/converter/convert_to_string/convergence_to_string.cc | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 194 | 2017-07-07T01:38:15.000Z | 2021-05-19T18:21:19.000Z | src/instrumentation/converter/convert_to_string/convergence_to_string.cc | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 10 | 2017-07-06T22:58:59.000Z | 2021-03-15T07:01:21.000Z | #include "instrumentation/converter/convert_to_string/convergence_to_string.h"
#include <iomanip>
#include <sstream>
#include "instrumentation/converter/factory.hpp"
namespace bart {
namespace instrumentation {
namespace converter {
namespace convert_to_string {
namespace {
using OutputTerm = ConvergenceToStringOutputTerm;
std::string default_output_format{"Iteration: ${ITERATION_NUM}/${ITERATION_MAX}, delta: ${DELTA}, index: ${INDEX}\n"};
std::map<ConvergenceToStringOutputTerm, std::string>
default_output_term_to_string_map{{OutputTerm::kIterationNum, "${ITERATION_NUM}"},
{OutputTerm::kIterationMax, "${ITERATION_MAX}"},
{OutputTerm::kDelta, "${DELTA}"},
{OutputTerm::kIndex, "${INDEX}"}};
} // namespace
ConvergenceToString::ConvergenceToString()
: ToStringConverter<convergence::Status, ConvergenceToStringOutputTerm>(
default_output_format, default_output_term_to_string_map) {}
std::string ConvergenceToString::Convert(const convergence::Status &to_convert) const {
auto return_string = output_format_;
std::string delta_string{null_character_}, index_string{null_character_};
if (to_convert.delta.has_value()) {
std::ostringstream delta_stream;
delta_stream << std::scientific << std::setprecision(16) << to_convert.delta.value();
delta_string = delta_stream.str();
}
if (to_convert.failed_index.has_value()) {
index_string = std::to_string(to_convert.failed_index.value());
}
std::map<OutputTerm, std::string> output_term_string_map{
{OutputTerm::kIterationNum, std::to_string(to_convert.iteration_number)},
{OutputTerm::kIterationMax, std::to_string(to_convert.max_iterations)},
{OutputTerm::kIndex, index_string},
{OutputTerm::kDelta, delta_string}
};
for (const auto& [term, value] : output_term_string_map) {
std::string string_to_find = output_term_to_string_map_.at(term);
if (auto index = return_string.find(string_to_find);
index != std::string::npos) {
return_string.replace(index, string_to_find.size(), value);
}
}
return return_string;
}
bool ConvergenceToString::is_registered_ =
ConverterIFactory<convergence::Status, std::string>::get()
.RegisterConstructor(converter::ConverterName::kConvergenceToString,
[](){
std::unique_ptr<ConverterI<convergence::Status, std::string>>
return_ptr = std::make_unique<ConvergenceToString>();
return return_ptr;
});
} // namespace convert_to_string
} // namespace converter
} // namespace instrumentation
} // namespace bart
| 33.5375 | 118 | 0.70369 | SlaybaughLab |
b99059c518d91f8ab07aefcbecc05c90d48b8346 | 4,843 | cpp | C++ | Eleusis_sln/Eleusis_UnitTests/tests/Test_Geometry.cpp | bognikol/Eleusis | ee518ede31893689eb6d3c5539e0bd757aeb0294 | [
"MIT"
] | 4 | 2019-05-31T19:55:23.000Z | 2020-10-27T10:00:32.000Z | Eleusis_sln/Eleusis_UnitTests/tests/Test_Geometry.cpp | bognikol/Eleusis | ee518ede31893689eb6d3c5539e0bd757aeb0294 | [
"MIT"
] | null | null | null | Eleusis_sln/Eleusis_UnitTests/tests/Test_Geometry.cpp | bognikol/Eleusis | ee518ede31893689eb6d3c5539e0bd757aeb0294 | [
"MIT"
] | 3 | 2019-04-29T14:09:38.000Z | 2020-10-27T10:00:33.000Z | #include "gtest/gtest.h"
#include "02_geometry/Geometry.h"
#include <string>
#include <iostream>
#include <limits>
#include "cairo.h"
using namespace std;
using namespace Eleusis;
using namespace ::testing;
class GeometryTest : public Test
{
protected:
Geometry* _geometry;
GeometryTest() { }
~GeometryTest() { }
void SetUp()
{
_geometry = new Geometry();
}
void TearDown()
{
delete _geometry;
}
void CHECK_QUADRILATERAL(
double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4,
bool checkOriginalPath = false)
{
cairo_path_data_t* data;
if (checkOriginalPath)
data = _geometry->getOriginalCairoPath()->data;
else
data = _geometry->getCairoPath()->data;
EXPECT_EQ(data[1].point.x, x1);
EXPECT_EQ(data[1].point.y, y1);
EXPECT_EQ(data[3].point.x, x2);
EXPECT_EQ(data[3].point.y, y2);
EXPECT_EQ(data[5].point.x, x3);
EXPECT_EQ(data[5].point.y, y3);
EXPECT_EQ(data[7].point.x, x4);
EXPECT_EQ(data[7].point.y, y4);
}
void CHECK_RECTANGLE(
double x_low, double y_low,
double x_high, double y_high,
bool checkOriginalPath = false)
{
CHECK_QUADRILATERAL(x_low, y_low, x_low, y_high, x_high, y_high, x_high, y_low, checkOriginalPath);
}
void CHECK_EXTENT(
double x1, double y1,
double x2, double y2)
{
EXPECT_EQ(_geometry->getExtent().lowVector.X, x1);
EXPECT_EQ(_geometry->getExtent().lowVector.Y, y1);
EXPECT_EQ(_geometry->getExtent().highVector.X, x2);
EXPECT_EQ(_geometry->getExtent().highVector.Y, y2);
}
};
TEST_F(GeometryTest, setAffineTransformation)
{
_geometry->addRectangle(50, 20, 100, 80, 0);
EXPECT_EQ(_geometry->getCairoPath()->status, CAIRO_STATUS_SUCCESS);
EXPECT_EQ(_geometry->getCairoPath()->num_data, 9);
CHECK_QUADRILATERAL(50, 20, 50, 80, 100, 80, 100, 20);
AffineTransformation transformation;
transformation.applyTranslation({ 40, 30 });
_geometry->setAffineTransformation(&transformation);
CHECK_QUADRILATERAL(90, 50, 90, 110, 140, 110, 140, 50);
CHECK_EXTENT(90, 50, 140, 110);
transformation.setAffineMatrixToIdentity();
transformation.applyScale({ 2, 2 });
_geometry->setAffineTransformation(&transformation);
CHECK_QUADRILATERAL(100, 40, 100, 160, 200, 160, 200, 40);
transformation.setAffineMatrixToIdentity();
transformation.applyScale({ 0.5, 0.5 });
_geometry->multiplyAffineTransformation(&transformation);
CHECK_QUADRILATERAL(50, 20, 50, 80, 100, 80, 100, 20);
transformation.setAffineMatrixToIdentity();
transformation.applyScale({ 2.0, 4.0 });
transformation.applyScale({ 0.5, 0.25 });
_geometry->setAffineTransformation(&transformation);
CHECK_QUADRILATERAL(50, 20, 50, 80, 100, 80, 100, 20);
transformation.setAffineMatrixToIdentity();
transformation.applyTranslation({ 100, 100 });
_geometry->multiplyAffineTransformation(&transformation);
CHECK_QUADRILATERAL(150, 120, 150, 180, 200, 180, 200, 120);
transformation.setAffineMatrixToIdentity();
transformation.applyTranslation({ 100, 100 });
transformation.applyScale({ 2.0, 2.0 });
transformation.applyTranslation({ -40, -40 });
_geometry->setAffineTransformation(&transformation);
CHECK_QUADRILATERAL(120, 60, 120, 180, 220, 180, 220, 60);
CHECK_QUADRILATERAL(50, 20, 50, 80, 100, 80, 100, 20, true);
}
TEST_F(GeometryTest, updatePoint)
{
_geometry->addRectangle(50, 20, 100, 80,0);
cairo_path_t* path;
cairo_path_data_t* data;
path = _geometry->getCairoPath();
data = path->data;
EXPECT_EQ(path->status, CAIRO_STATUS_SUCCESS);
EXPECT_EQ(path->num_data, 9);
CHECK_QUADRILATERAL(50, 20, 50, 80, 100, 80, 100, 20);
_geometry->updatePoint(1, 80, 40);
_geometry->updatePoint(3, 55, 25);
_geometry->updatePoint(5, 75, 30);
_geometry->updatePoint(7, 65, 15);
CHECK_QUADRILATERAL(80, 40, 55, 25, 75, 30, 65, 15);
AffineTransformation transformation;
transformation.setAffineMatrixToIdentity();
transformation.applyTranslation({ 100, 100 });
transformation.applyScale({ 2.0, 2.0 });
transformation.applyTranslation({ -40, -40 });
_geometry->setAffineTransformation(&transformation);
CHECK_QUADRILATERAL(180, 100, 130, 70, 170, 80, 150, 50);
CHECK_QUADRILATERAL(80, 40, 55, 25, 75, 30, 65, 15, true);
transformation.setAffineMatrixToIdentity();
transformation.applyTranslation({ 10, 10 });
_geometry->multiplyAffineTransformation(&transformation);
CHECK_QUADRILATERAL(200, 120, 150, 90, 190, 100, 170, 70);
CHECK_QUADRILATERAL(80, 40, 55, 25, 75, 30, 65, 15, true);
}
| 28.656805 | 101 | 0.667561 | bognikol |
b991bf830eead48add504aeb397cee841497140e | 175 | cpp | C++ | examples/assert/assert.cpp | NAzT/bluetoe | 2348999825d5913e5e1001480a744ce72ad2bf79 | [
"MIT"
] | 138 | 2015-04-11T12:07:19.000Z | 2022-02-11T13:22:36.000Z | examples/assert/assert.cpp | NAzT/bluetoe | 2348999825d5913e5e1001480a744ce72ad2bf79 | [
"MIT"
] | 60 | 2015-08-29T12:32:56.000Z | 2022-03-25T07:20:21.000Z | examples/assert/assert.cpp | NAzT/bluetoe | 2348999825d5913e5e1001480a744ce72ad2bf79 | [
"MIT"
] | 34 | 2015-07-08T22:06:25.000Z | 2021-12-15T13:17:42.000Z | #include <assert.h>
extern "C" void HardFault_Handler() __attribute__ ((noreturn));
extern "C" void __assert_hash_func( assert_hash_type hash )
{
HardFault_Handler();
}
| 19.444444 | 63 | 0.737143 | NAzT |
b991d542f132e27c5c1ea88b0b34c70584fac927 | 364 | cpp | C++ | source/scapes/foundation/shaders/Compiler.cpp | eZii-jester-data/pbr-sandbox | 853aa023f063fd48760a8c3848687976189f3f98 | [
"MIT"
] | null | null | null | source/scapes/foundation/shaders/Compiler.cpp | eZii-jester-data/pbr-sandbox | 853aa023f063fd48760a8c3848687976189f3f98 | [
"MIT"
] | null | null | null | source/scapes/foundation/shaders/Compiler.cpp | eZii-jester-data/pbr-sandbox | 853aa023f063fd48760a8c3848687976189f3f98 | [
"MIT"
] | null | null | null | #include "shaders/spirv/Compiler.h"
#include <cassert>
namespace scapes::foundation::shaders
{
Compiler *Compiler::create(ShaderILType type, io::FileSystem *file_system)
{
switch (type)
{
case ShaderILType::SPIRV: return new spirv::Compiler(file_system);
}
return nullptr;
}
void Compiler::destroy(Compiler *compiler)
{
delete compiler;
}
}
| 16.545455 | 75 | 0.717033 | eZii-jester-data |
b999e370c4ca22535a5423fe1e490d2ab8140d49 | 22,847 | cpp | C++ | libvast/test/format/zeek.cpp | frerich/vast | decac739ea4782ab91a1cee791ecd754b066419f | [
"BSD-3-Clause"
] | null | null | null | libvast/test/format/zeek.cpp | frerich/vast | decac739ea4782ab91a1cee791ecd754b066419f | [
"BSD-3-Clause"
] | null | null | null | libvast/test/format/zeek.cpp | frerich/vast | decac739ea4782ab91a1cee791ecd754b066419f | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/format/zeek.hpp"
#include "vast/type.hpp"
#include <istream>
#include <sstream>
#include <thread>
#include <unistd.h>
#define SUITE format
#include "vast/test/fixtures/actor_system.hpp"
#include "vast/test/fixtures/events.hpp"
#include "vast/test/test.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/schema.hpp"
#include "vast/concept/parseable/vast/type.hpp"
#include "vast/detail/fdinbuf.hpp"
#include "vast/event.hpp"
using namespace vast;
using namespace std::string_literals;
namespace {
template <class Attribute>
bool zeek_parse(const type& t, const std::string& s, Attribute& attr) {
return format::zeek::make_zeek_parser<std::string::const_iterator>(t)(s,
attr);
}
std::string_view capture_loss_10_events = R"__(#separator \x09
#set_separator ,
#empty_field (empty)
#unset_field -
#path capture_loss
#open 2019-06-07-14-30-44
#fields ts ts_delta peer gaps acks percent_lost
#types time interval string count count double
1258532133.914401 930.000003 bro 0 0 0.0
1258533063.914399 929.999998 bro 0 0 0.0
1258533977.316663 913.402264 bro 0 0 0.0
1258534893.914434 916.597771 bro 0 0 0.0
1258535805.364503 911.450069 bro 0 45 0.0
1258536723.914407 918.549904 bro 0 9 0.0
1258537653.914390 929.999983 bro 0 0 0.0
1258538553.914414 900.000024 bro 0 9 0.0
1258539453.914415 900.000001 bro 0 0 0.0
1258540374.060134 920.145719 bro 0 0 0.0
#close 2019-06-07-14-31-01)__";
std::string_view conn_log_10_events = R"__(#separator \x09
#set_separator ,
#empty_field (empty)
#unset_field -
#path conn
#open 2014-05-23-18-02-04
#fields ts uid id.orig_h id.orig_p id.resp_h id.resp_p proto service duration orig_bytes resp_bytes conn_state local_orig missed_bytes history orig_pkts orig_ip_bytes resp_pkts resp_ip_bytes tunnel_parents
#types time string addr port addr port enum string interval count count string bool count string count count count count table[string]
1258531221.486539 Pii6cUUq1v4 192.168.1.102 68 192.168.1.1 67 udp - 0.163820 301 300 SF - 0 Dd 1 329 1 328 (empty)
1258531680.237254 nkCxlvNN8pi 192.168.1.103 137 192.168.1.255 137 udp dns 3.780125 350 0 S0 - 0 D 7 546 0 0 (empty)
1258531693.816224 9VdICMMnxQ7 192.168.1.102 137 192.168.1.255 137 udp dns 3.748647 350 0 S0 - 0 D 7 546 0 0 (empty)
1258531635.800933 bEgBnkI31Vf 192.168.1.103 138 192.168.1.255 138 udp - 46.725380 560 0 S0 - 0 D 3 644 0 0 (empty)
1258531693.825212 Ol4qkvXOksc 192.168.1.102 138 192.168.1.255 138 udp - 2.248589 348 0 S0 - 0 D 2 404 0 0 (empty)
1258531803.872834 kmnBNBtl96d 192.168.1.104 137 192.168.1.255 137 udp dns 3.748893 350 0 S0 - 0 D 7 546 0 0 (empty)
1258531747.077012 CFIX6YVTFp2 192.168.1.104 138 192.168.1.255 138 udp - 59.052898 549 0 S0 - 0 D 3 633 0 0 (empty)
1258531924.321413 KlF6tbPUSQ1 192.168.1.103 68 192.168.1.1 67 udp - 0.044779 303 300 SF - 0 Dd 1 331 1 328 (empty)
1258531939.613071 tP3DM6npTdj 192.168.1.102 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258532046.693816 Jb4jIDToo77 192.168.1.104 68 192.168.1.1 67 udp - 0.002103 311 300 SF - 0 Dd 1 339 1 328 (empty)
)__";
std::string_view conn_log_100_events = R"__(#separator \x09
#set_separator ,
#empty_field (empty)
#unset_field -
#path conn
#open 2014-05-23-18-02-04
#fields ts uid id.orig_h id.orig_p id.resp_h id.resp_p proto service duration orig_bytes resp_bytes conn_state local_orig missed_bytes history orig_pkts orig_ip_bytes resp_pkts resp_ip_bytes tunnel_parents
#types time string addr port addr port enum string interval count count string bool count string count count count count table[string]
1258531221.486539 Pii6cUUq1v4 192.168.1.102 68 192.168.1.1 67 udp - 0.163820 301 300 SF - 0 Dd 1 329 1 328 (empty)
1258531680.237254 nkCxlvNN8pi 192.168.1.103 137 192.168.1.255 137 udp dns 3.780125 350 0 S0 - 0 D 7 546 0 0 (empty)
1258531693.816224 9VdICMMnxQ7 192.168.1.102 137 192.168.1.255 137 udp dns 3.748647 350 0 S0 - 0 D 7 546 0 0 (empty)
1258531635.800933 bEgBnkI31Vf 192.168.1.103 138 192.168.1.255 138 udp - 46.725380 560 0 S0 - 0 D 3 644 0 0 (empty)
1258531693.825212 Ol4qkvXOksc 192.168.1.102 138 192.168.1.255 138 udp - 2.248589 348 0 S0 - 0 D 2 404 0 0 (empty)
1258531803.872834 kmnBNBtl96d 192.168.1.104 137 192.168.1.255 137 udp dns 3.748893 350 0 S0 - 0 D 7 546 0 0 (empty)
1258531747.077012 CFIX6YVTFp2 192.168.1.104 138 192.168.1.255 138 udp - 59.052898 549 0 S0 - 0 D 3 633 0 0 (empty)
1258531924.321413 KlF6tbPUSQ1 192.168.1.103 68 192.168.1.1 67 udp - 0.044779 303 300 SF - 0 Dd 1 331 1 328 (empty)
1258531939.613071 tP3DM6npTdj 192.168.1.102 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258532046.693816 Jb4jIDToo77 192.168.1.104 68 192.168.1.1 67 udp - 0.002103 311 300 SF - 0 Dd 1 339 1 328 (empty)
1258532143.457078 xvWLhxgUmj5 192.168.1.102 1170 192.168.1.1 53 udp dns 0.068511 36 215 SF - 0 Dd 1 64 1 243 (empty)
1258532203.657268 feNcvrZfDbf 192.168.1.104 1174 192.168.1.1 53 udp dns 0.170962 36 215 SF - 0 Dd 1 64 1 243 (empty)
1258532331.365294 aLsTcZJHAwa 192.168.1.1 5353 224.0.0.251 5353 udp dns 0.100381 273 0 S0 - 0 D 2 329 0 0 (empty)
1258532331.365330 EK79I6iD5gl fe80::219:e3ff:fee7:5d23 5353 ff02::fb 5353 udp dns 0.100371 273 0 S0 - 0 D 2 369 0 0 (empty)
1258532404.734264 vLsf6ZHtak9 192.168.1.103 137 192.168.1.255 137 udp dns 3.873818 350 0 S0 - 0 D 7 546 0 0 (empty)
1258532418.272517 Su3RwTCaHL3 192.168.1.102 137 192.168.1.255 137 udp dns 3.748891 350 0 S0 - 0 D 7 546 0 0 (empty)
1258532404.859431 rPM1dfJKPmj 192.168.1.103 138 192.168.1.255 138 udp - 2.257840 348 0 S0 - 0 D 2 404 0 0 (empty)
1258532456.089023 4x5ezf34Rkh 192.168.1.102 1173 192.168.1.1 53 udp dns 0.000267 33 497 SF - 0 Dd 1 61 1 525 (empty)
1258532418.281002 mymcd8Veike 192.168.1.102 138 192.168.1.255 138 udp - 2.248843 348 0 S0 - 0 D 2 404 0 0 (empty)
1258532525.592455 07mJRfg5RU5 192.168.1.1 5353 224.0.0.251 5353 udp dns 0.099824 273 0 S0 - 0 D 2 329 0 0 (empty)
1258532525.592493 V6FODcWHWec fe80::219:e3ff:fee7:5d23 5353 ff02::fb 5353 udp dns 0.099813 273 0 S0 - 0 D 2 369 0 0 (empty)
1258532528.348891 H3qLO3SV0j 192.168.1.104 137 192.168.1.255 137 udp dns 3.748895 350 0 S0 - 0 D 7 546 0 0 (empty)
1258532528.357385 rPqxmvEhfBb 192.168.1.104 138 192.168.1.255 138 udp - 2.248339 348 0 S0 - 0 D 2 404 0 0 (empty)
1258532644.128655 VkSPS0xGKR 192.168.1.1 5353 224.0.0.251 5353 udp - - - - S0 - 0 D 1 154 0 0 (empty)
1258532644.128680 qYIadwKn8wg fe80::219:e3ff:fee7:5d23 5353 ff02::fb 5353 udp - - - - S0 - 0 D 1 174 0 0 (empty)
1258532657.288677 AbCe0UeHRD6 192.168.1.102 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258532683.876479 4xkhfR2BeX2 192.168.1.103 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 240 0 0 (empty)
1258532824.338291 03rnFQ5hJ3f 192.168.1.104 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258533003.551468 3VNZpT9V3G8 192.168.1.102 68 192.168.1.1 67 udp - 0.011807 301 300 SF - 0 Dd 1 329 1 328 (empty)
1258533129.324984 JGyFmSAGkVj 192.168.1.103 137 192.168.1.255 137 udp dns 3.748641 350 0 S0 - 0 D 7 546 0 0 (empty)
1258533142.729062 jH5gXia1V2b 192.168.1.102 137 192.168.1.255 137 udp dns 3.748893 350 0 S0 - 0 D 7 546 0 0 (empty)
1258533129.333980 rnymGcMKJa1 192.168.1.103 138 192.168.1.255 138 udp - 2.248336 348 0 S0 - 0 D 2 404 0 0 (empty)
1258533142.737803 KEbhCATVhq6 192.168.1.102 138 192.168.1.255 138 udp - 2.248086 348 0 S0 - 0 D 2 404 0 0 (empty)
1258533252.824915 43kp69mNH9h 192.168.1.104 137 192.168.1.255 137 udp dns 3.764644 350 0 S0 - 0 D 7 546 0 0 (empty)
1258533252.848161 6IrqIPLkMue 192.168.1.104 138 192.168.1.255 138 udp - 2.249087 348 0 S0 - 0 D 2 404 0 0 (empty)
1258533406.310783 E3V7insZAf3 192.168.1.103 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 240 0 0 (empty)
1258533546.501981 1o9fdj2Mwzk 192.168.1.104 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258533745.340248 BwDhfT4ibLj 192.168.1.1 5353 224.0.0.251 5353 udp - - - - S0 - 0 D 1 105 0 0 (empty)
1258533745.340270 xQ3F7WYDuc9 fe80::219:e3ff:fee7:5d23 5353 ff02::fb 5353 udp - - - - S0 - 0 D 1 125 0 0 (empty)
1258533706.284625 xC73ngEP6t8 192.168.1.103 68 192.168.1.1 67 udp - 0.011605 303 300 SF - 0 Dd 1 331 1 328 (empty)
1258533766.050097 IxBAxd8IHQd 192.168.1.102 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258533853.790491 QHWe1hZptM5 192.168.1.103 137 192.168.1.255 137 udp dns 3.748893 350 0 S0 - 0 D 7 546 0 0 (empty)
1258533867.185568 HzzKOZy8Zl 192.168.1.102 137 192.168.1.255 137 udp dns 3.748900 350 0 S0 - 0 D 7 546 0 0 (empty)
1258533827.650648 O6RgfULxXN3 192.168.1.104 68 192.168.1.1 67 udp - 0.002141 311 300 SF - 0 Dd 1 339 1 328 (empty)
1258533853.799477 U17UR8RLuIh 192.168.1.103 138 192.168.1.255 138 udp - 2.248587 348 0 S0 - 0 D 2 404 0 0 (empty)
1258533867.194313 Z0o7i3H04Mb 192.168.1.102 138 192.168.1.255 138 udp - 2.248337 348 0 S0 - 0 D 2 404 0 0 (empty)
1258533977.316663 mxs3TNKBBy1 192.168.1.104 137 192.168.1.255 137 udp dns 3.748892 350 0 S0 - 0 D 7 546 0 0 (empty)
1258533977.325393 yLnPhusc1Fd 192.168.1.104 138 192.168.1.255 138 udp - 2.248342 348 0 S0 - 0 D 2 404 0 0 (empty)
1258534152.488884 91kNv7QfCzi 192.168.1.102 1180 68.216.79.113 37 tcp - 2.850214 0 0 S0 - 0 S 2 96 0 0 (empty)
1258534152.297748 LOurbPuyqk7 192.168.1.102 59040 192.168.1.1 53 udp dns 0.189140 44 178 SF - 0 Dd 1 72 1 206 (empty)
1258534161.354320 xDClpF8rSJf 192.168.1.102 1180 68.216.79.113 37 tcp - - - - S0 - 0 S 1 48 0 0 (empty)
1258534429.059180 lpnjZjmVs05 192.168.1.103 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 240 0 0 (empty)
1258534488.491105 EEdJBMA9rCk 192.168.1.102 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258534578.255976 omP3BzwITql 192.168.1.103 137 192.168.1.255 137 udp dns 3.764629 350 0 S0 - 0 D 7 546 0 0 (empty)
1258534582.490064 NnB6PYh0Zng 192.168.1.103 1190 192.168.1.1 53 udp dns 0.068749 36 215 SF - 0 Dd 1 64 1 243 (empty)
1258534591.642070 FVtn6tTYXr4 192.168.1.102 137 192.168.1.255 137 udp dns 3.748895 350 0 S0 - 0 D 7 546 0 0 (empty)
1258534545.219226 S5B6OZaxfKa 192.168.1.104 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258534578.280455 Gz2fEwEvO0a 192.168.1.103 138 192.168.1.255 138 udp - 2.248587 348 0 S0 - 0 D 2 404 0 0 (empty)
1258534591.650809 hTD6LLqZ7Y7 192.168.1.102 138 192.168.1.255 138 udp - 2.248337 348 0 S0 - 0 D 2 404 0 0 (empty)
1258534701.792887 zm9y9VwuS0i 192.168.1.104 137 192.168.1.255 137 udp dns 3.748895 350 0 S0 - 0 D 7 546 0 0 (empty)
1258534701.800881 aJiKvjshkn2 192.168.1.104 138 192.168.1.255 138 udp - 2.249081 348 0 S0 - 0 D 2 404 0 0 (empty)
1258534785.460075 sU2LS35B0Wc 192.168.1.102 68 192.168.1.1 67 udp - 0.012542 301 300 SF - 0 Dd 1 329 1 328 (empty)
1258534856.808007 gd5PK3GL6Q4 192.168.1.103 56940 192.168.1.1 53 udp dns 0.000218 44 178 SF - 0 Dd 1 72 1 206 (empty)
1258534856.809509 mkqyZaVMBzf 192.168.1.103 1191 68.216.79.113 37 tcp - 8.963129 0 0 S0 - 0 S 3 144 0 0 (empty)
1258534970.336456 jlEzGSUZMMk 192.168.1.104 1186 68.216.79.113 37 tcp - 3.024594 0 0 S0 - 0 S 2 96 0 0 (empty)
1258534970.334447 LD7p2nKzwUa 192.168.1.104 56041 192.168.1.1 53 udp dns 0.000221 44 178 SF - 0 Dd 1 72 1 206 (empty)
1258534979.376520 FikbEcyi5ud 192.168.1.104 1186 68.216.79.113 37 tcp - - - - S0 - 0 S 1 48 0 0 (empty)
1258535150.337635 r1IqqKncAn1 192.168.1.103 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 240 0 0 (empty)
1258535262.273837 OCdMO0RlDKi 192.168.1.104 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258535302.768650 w7TADZKQmv7 192.168.1.103 137 192.168.1.255 137 udp dns 3.748655 350 0 S0 - 0 D 7 546 0 0 (empty)
1258535316.098533 EhLt4Xfo998 192.168.1.102 137 192.168.1.255 137 udp dns 3.748897 350 0 S0 - 0 D 7 546 0 0 (empty)
1258535302.777651 IZ5pW4ZoObi 192.168.1.103 138 192.168.1.255 138 udp - 2.248077 348 0 S0 - 0 D 2 404 0 0 (empty)
1258535316.107272 DjK0mCmuZKc 192.168.1.102 138 192.168.1.255 138 udp - 2.248339 348 0 S0 - 0 D 2 404 0 0 (empty)
1258535426.269094 j1nshHTZnc2 192.168.1.104 137 192.168.1.255 137 udp dns 3.780124 350 0 S0 - 0 D 7 546 0 0 (empty)
1258535426.309819 HT5yJUMEaba 192.168.1.104 138 192.168.1.255 138 udp - 2.247581 348 0 S0 - 0 D 2 404 0 0 (empty)
1258535488.214929 j5j8aWhnaBl 192.168.1.103 68 192.168.1.1 67 udp - 0.019841 303 300 SF - 0 Dd 1 331 1 328 (empty)
1258535580.253637 8F0S5E1XGh4 192.168.1.102 138 192.168.1.255 138 udp - - - - S0 - 0 D 1 229 0 0 (empty)
1258535653.062408 YW7idMRahdb 192.168.1.104 1191 65.54.95.64 80 tcp http 0.050465 173 297 RSTO - 0 ShADdfR 5 381 3 425 (empty)
1258535650.506019 5txwc6aKNFe 192.168.1.104 56749 192.168.1.1 53 udp dns 0.044610 30 94 SF - 0 Dd 1 58 1 122 (empty)
1258535656.471265 HcFUvhy5Wf6 192.168.1.104 1193 65.54.95.64 80 tcp http 0.050215 195 296 RSTO - 0 ShADdfR 5 403 3 424 (empty)
1258535656.524478 TsaAKxHC8yh 192.168.1.104 1194 65.54.95.64 80 tcp http 0.109682 194 21053 RSTO - 0 ShADdfR 8 522 17 21741 (empty)
1258535652.794076 M6vDMlNtAok 192.168.1.104 52125 192.168.1.1 53 udp dns 0.266791 44 200 SF - 0 Dd 1 72 1 228 (empty)
1258535658.712360 Hiphu7fLcC5 192.168.1.104 1195 65.54.95.64 80 tcp http 0.079452 173 297 RSTO - 0 ShADdfR 5 381 3 425 (empty)
1258535655.387448 GH3I4uYo0l1 192.168.1.104 64790 192.168.1.1 53 udp dns 0.042968 42 179 SF - 0 Dd 1 70 1 207 (empty)
1258535650.551483 04xC2aCJ5i8 192.168.1.104 137 192.168.1.255 137 udp dns 4.084184 300 0 S0 - 0 D 6 468 0 0 (empty)
1258535666.147439 g6mt9RBZkw 192.168.1.104 1197 65.54.95.64 80 tcp http 0.049966 173 297 RSTO - 0 ShADdfR 5 381 3 425 (empty)
1258535697.963212 I8ePTueT9Aj 192.168.1.102 1188 212.227.97.133 80 tcp http 0.898191 1121 342 SF - 0 ShADadfF 5 1329 5 550 (empty)
1258535698.862885 lZ58OyvEYY3 192.168.1.102 1189 87.106.1.47 80 tcp http 0.880456 1118 342 SF - 0 ShADadfF 5 1326 5 546 (empty)
1258535699.744831 D2ERJCFZD1e 192.168.1.102 1190 87.106.1.89 80 tcp http 0.914934 1118 342 SF - 0 ShADadfF 5 1326 5 550 (empty)
1258535696.159584 wIEQmZxJy19 192.168.1.102 1187 192.168.1.1 53 udp dns 0.068537 36 215 SF - 0 Dd 1 64 1 243 (empty)
1258535700.662505 HqW58gj5856 192.168.1.102 1191 87.106.12.47 80 tcp http 0.955409 1160 1264 SF - 0 ShADadfF 5 1368 5 1472 (empty)
1258535701.622151 zCr8XZTRcvh 192.168.1.102 1192 87.106.12.77 80 tcp http 0.514927 1222 367 SF - 0 ShADadfF 6 1470 6 615 (empty)
1258535650.499268 dNSfUrlTwq3 192.168.1.104 68 255.255.255.255 67 udp - - - - S0 - 0 D 1 328 0 0 (empty)
1258535609.607942 qomqwkg9Ddg 192.168.1.104 68 192.168.1.1 67 udp - 40.891774 311 600 SF - 0 Dd 1 339 2 656 (empty)
1258535707.137448 YUUhPmf1G4c 192.168.1.102 1194 87.106.66.233 80 tcp http 0.877448 1128 301 SF - 0 ShADadfF 5 1336 5 505 (empty)
1258535702.138078 yH3dkqFJE8 192.168.1.102 1193 87.106.13.61 80 tcp - 3.061084 0 0 S0 - 0 S 2 96 0 0 (empty)
1258535708.016137 I60NOMgOQxj 192.168.1.102 1195 87.106.9.29 80 tcp http 0.876205 1126 342 SF - 0 ShADadfF 5 1334 5 550 (empty)
1258535655.431418 jM8ATYNKqZg 192.168.1.104 1192 65.55.184.16 80 tcp http 59.712557 172 262 RSTR - 0 ShADdr 4 340 3 390 (empty)
1258535710.855364 YmvKAMrJ6v9 192.168.1.102 1196 192.168.1.1 53 udp dns 0.013042 36 215 SF - 0 Dd 1 64 1 243 (empty)
1258535660.158200 WfzxgFx2lWb 192.168.1.104 1196 65.55.184.16 443 tcp ssl 67.887666 57041 8510 RSTR - 0 ShADdar 54 59209 26 9558 (empty)
#close 2014-05-23-18-02-35)__";
struct fixture : fixtures::deterministic_actor_system {
std::vector<table_slice_ptr>
read(std::unique_ptr<std::istream> input, size_t slice_size,
size_t num_events, bool expect_eof, bool expect_timeout) {
using reader_type = format::zeek::reader;
auto settings = caf::settings{};
caf::put(settings, "import.read-timeout", "200ms");
reader_type reader{defaults::import::table_slice_type, std::move(settings),
std::move(input)};
std::vector<table_slice_ptr> slices;
auto add_slice = [&](table_slice_ptr ptr) {
slices.emplace_back(std::move(ptr));
};
auto [err, num] = reader.read(std::numeric_limits<size_t>::max(),
slice_size, add_slice);
if (expect_eof && err != ec::end_of_input)
FAIL("Zeek reader did not exhaust input: " << sys.render(err));
if (expect_timeout && err != ec::timeout)
FAIL("Zeek reader did not time out: " << sys.render(err));
if (!expect_eof && !expect_timeout && err)
FAIL("Zeek reader failed to parse input: " << sys.render(err));
if (num != num_events)
FAIL("Zeek reader only produced " << num << " events, expected "
<< num_events);
return slices;
}
std::vector<table_slice_ptr>
read(std::string_view input, size_t slice_size, size_t num_events,
bool expect_eof = true, bool expect_timeout = false) {
return read(std::make_unique<std::istringstream>(std::string{input}),
slice_size, num_events, expect_eof, expect_timeout);
}
};
} // namspace <anonymous>
FIXTURE_SCOPE(zeek_reader_tests, fixture)
TEST(zeek data parsing) {
using namespace std::chrono;
data d;
CHECK(zeek_parse(bool_type{}, "T", d));
CHECK(d == true);
CHECK(zeek_parse(integer_type{}, "-49329", d));
CHECK(d == integer{-49329});
CHECK(zeek_parse(count_type{}, "49329"s, d));
CHECK(d == count{49329});
CHECK(zeek_parse(time_type{}, "1258594163.566694", d));
auto ts = duration_cast<vast::duration>(double_seconds{1258594163.566694});
CHECK(d == vast::time{ts});
CHECK(zeek_parse(duration_type{}, "1258594163.566694", d));
CHECK(d == ts);
CHECK(zeek_parse(string_type{}, "\\x2afoo*"s, d));
CHECK(d == "*foo*");
CHECK(zeek_parse(address_type{}, "192.168.1.103", d));
CHECK(d == *to<address>("192.168.1.103"));
CHECK(zeek_parse(subnet_type{}, "10.0.0.0/24", d));
CHECK(d == *to<subnet>("10.0.0.0/24"));
CHECK(zeek_parse(port_type{}, "49329", d));
CHECK(d == port{49329, port::unknown});
CHECK(zeek_parse(list_type{integer_type{}}, "49329", d));
CHECK(d == list{49329});
CHECK(zeek_parse(list_type{string_type{}}, "49329,42", d));
CHECK(d == list{"49329", "42"});
}
TEST(zeek reader - capture loss) {
auto slices = read(capture_loss_10_events, 10, 10);
REQUIRE_EQUAL(slices.size(), 1u);
CHECK_EQUAL(slices[0]->rows(), 10u);
}
TEST(zeek reader - conn log) {
auto slices = read(conn_log_100_events, 20, 100);
CHECK_EQUAL(slices.size(), 5u);
for (auto& slice : slices)
CHECK_EQUAL(slice->rows(), 20u);
}
TEST(zeek reader - custom schema) {
std::string custom = R"__(
type zeek.conn = record{
ts: time #test,
uid: string #index=string, // clashing user attribute
id: record {orig_h: addr, orig_p: port, resp_h: addr, resp_p: port},
proto: string #foo=bar, // user attribute
service: count, // type mismatch
community_id: string // not present in the data
}
)__";
auto sch = unbox(to<schema>(custom));
std::string eref = R"__(record{
ts: time #test #timestamp,
uid: string #index=string,
id: record {orig_h: addr, orig_p: port, resp_h: addr, resp_p: port},
proto: string #foo=bar,
service: string,
duration: duration,
orig_bytes: count,
resp_bytes: count,
conn_state: string,
local_orig: bool,
//local_resp: bool,
missed_bytes: count,
history: string,
orig_pkts: count,
orig_ip_bytes: count,
resp_pkts: count,
resp_ip_bytes: count,
tunnel_parents: list<string>,
})__";
auto expected = flatten(unbox(to<type>(eref)).name("zeek.conn"));
using reader_type = format::zeek::reader;
reader_type reader{
defaults::import::table_slice_type, caf::settings{},
std::make_unique<std::istringstream>(std::string{conn_log_100_events})};
reader.schema(sch);
std::vector<table_slice_ptr> slices;
auto add_slice
= [&](table_slice_ptr ptr) { slices.emplace_back(std::move(ptr)); };
auto [err, num] = reader.read(20, 20, add_slice);
CHECK_EQUAL(slices.size(), 1u);
CHECK_EQUAL(slices[0]->rows(), 20u);
CHECK_EQUAL(slices[0]->layout(), expected);
}
TEST(zeek reader - continous stream with partial slice) {
int pipefds[2];
auto result = ::pipe(pipefds);
REQUIRE_EQUAL(result, 0);
auto [read_end, write_end] = pipefds;
detail::fdinbuf buf(read_end);
std::vector<table_slice_ptr> slices;
std::thread t([&] {
bool expect_eof = false;
bool expect_timeout = true;
slices = read(std::make_unique<std::istream>(&buf), 100, 10, expect_eof,
expect_timeout);
});
// Write less than one full slice, leaving the pipe open.
result
= ::write(write_end, &conn_log_10_events[0], conn_log_10_events.size());
REQUIRE_EQUAL(static_cast<size_t>(result), conn_log_10_events.size());
// Expect that we will see the results before the test times out.
t.join();
CHECK_EQUAL(slices.size(), 1u);
for (auto& slice : slices)
CHECK_EQUAL(slice->rows(), 10u);
::close(pipefds[0]);
::close(pipefds[1]);
}
FIXTURE_SCOPE_END()
FIXTURE_SCOPE(zeek_writer_tests, fixtures::events)
TEST(zeek writer) {
// Sanity check some Zeek events.
CHECK_EQUAL(zeek_conn_log.size(), 20u);
CHECK_EQUAL(zeek_conn_log.front().type().name(), "zeek.conn");
auto record = caf::get_if<list>(&zeek_conn_log.front().data());
REQUIRE(record);
REQUIRE_EQUAL(record->size(), 20u);
CHECK_EQUAL(record->at(6), data{"udp"}); // one after the conn record
CHECK_EQUAL(record->back(), data{list{}}); // table[T] is actually a list
// Perform the writing.
auto dir = path{"vast-unit-test-zeek"};
auto guard = caf::detail::make_scope_guard([&] { rm(dir); });
format::zeek::writer writer{dir};
for (auto& slice : zeek_conn_log_slices)
if (auto err = writer.write(*slice))
FAIL("failed to write conn log");
for (auto& slice : zeek_http_log_slices)
if (auto err = writer.write(*slice))
FAIL("failed to write HTTP log");
CHECK(exists(dir / zeek_conn_log[0].type().name() + ".log"));
CHECK(exists(dir / zeek_http_log[0].type().name() + ".log"));
}
FIXTURE_SCOPE_END()
| 60.602122 | 205 | 0.689631 | frerich |
b99a8b7afd948032f12e2790e6f83c7eb328fbb1 | 1,696 | hpp | C++ | fwd_euler/adapt_euler.hpp | drreynolds/Math6321-codes | 3cce53bbe70bdd00220b5d8888b00b20b4fd521b | [
"CC0-1.0"
] | null | null | null | fwd_euler/adapt_euler.hpp | drreynolds/Math6321-codes | 3cce53bbe70bdd00220b5d8888b00b20b4fd521b | [
"CC0-1.0"
] | null | null | null | fwd_euler/adapt_euler.hpp | drreynolds/Math6321-codes | 3cce53bbe70bdd00220b5d8888b00b20b4fd521b | [
"CC0-1.0"
] | 1 | 2020-08-31T18:04:07.000Z | 2020-08-31T18:04:07.000Z | /* Adaptive forward Euler time stepper class header file.
D.R. Reynolds
Math 6321 @ SMU
Fall 2020 */
#ifndef ADAPT_EULER_DEFINED__
#define ADAPT_EULER_DEFINED__
// Inclusions
#include <cmath>
#include "rhs.hpp"
// Adaptive forward Euler time stepper class
class AdaptEuler {
private:
// private data
RHSFunction *frhs; // pointer to ODE RHS function
arma::vec *atol; // pointer to user-provided absolute tolerance array
arma::vec fn; // local vector storage
arma::vec y1;
arma::vec y2;
arma::vec yerr;
arma::vec w;
double grow; // maximum step size growth factor
double bias; // bias factor for error estimate
double safe; // safety factor for step size estimate
double ONEMSM; // safety factors for
double ONEPSM; // floating-point comparisons
int p; // order of accuracy for the method
public:
// publicly-accesible input parameters
double rtol; // desired relative solution error
long int maxit; // maximum allowed number of steps
// outputs
double error_norm; // current estimate of the local error ratio
double h; // current time step size
long int fails; // number of failed steps
long int steps; // number of successful steps
// constructor (sets RHS function pointer & solver parameters, copies y for local data)
AdaptEuler(RHSFunction& frhs_, double rtol_, arma::vec& atol_, arma::vec& y);
// utility routine to compute the error weight vector
void error_weight(arma::vec& y, arma::vec& w);
// Evolve routine (evolves the solution via adaptive forward Euler)
arma::mat Evolve(arma::vec tspan, arma::vec y);
};
#endif
| 28.745763 | 89 | 0.681014 | drreynolds |
b99a9821cd922cb7c2721ce2bdc20592e18f56ab | 6,173 | cpp | C++ | logdevice/server/IS_LOG_EMPTY_onReceived.cpp | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | 1 | 2021-05-19T23:01:58.000Z | 2021-05-19T23:01:58.000Z | logdevice/server/IS_LOG_EMPTY_onReceived.cpp | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | null | null | null | logdevice/server/IS_LOG_EMPTY_onReceived.cpp | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "IS_LOG_EMPTY_onReceived.h"
#include "logdevice/common/Sender.h"
#include "logdevice/common/configuration/Configuration.h"
#include "logdevice/common/protocol/IS_LOG_EMPTY_REPLY_Message.h"
#include "logdevice/common/stats/Stats.h"
#include "logdevice/server/ServerProcessor.h"
#include "logdevice/server/ServerWorker.h"
#include "logdevice/server/locallogstore/PartitionedRocksDBStore.h"
#include "logdevice/server/read_path/LogStorageStateMap.h"
#include "logdevice/server/storage_tasks/ShardedStorageThreadPool.h"
namespace facebook { namespace logdevice {
static void send_reply(const Address& to,
const IS_LOG_EMPTY_Header& request,
Status status,
bool empty) {
ld_debug("Sending IS_LOG_EMPTY_REPLY: client_rqid=%lu, status=%s, empty=%s",
request.client_rqid.val_,
error_name(status),
empty ? "TRUE" : "FALSE");
if (status == E::OK) {
if (empty) {
WORKER_LOG_STAT_INCR(request.log_id, is_log_empty_reply_true);
} else {
WORKER_LOG_STAT_INCR(request.log_id, is_log_empty_reply_false);
}
} else {
WORKER_LOG_STAT_INCR(request.log_id, is_log_empty_reply_error);
}
IS_LOG_EMPTY_REPLY_Header header = {
request.client_rqid, status, empty, request.shard};
auto msg = std::make_unique<IS_LOG_EMPTY_REPLY_Message>(header);
Worker::onThisThread()->sender().sendMessage(std::move(msg), to);
}
Message::Disposition IS_LOG_EMPTY_onReceived(IS_LOG_EMPTY_Message* msg,
const Address& from) {
const IS_LOG_EMPTY_Header& header = msg->getHeader();
if (header.log_id == LOGID_INVALID) {
ld_error("got IS_LOG_EMPTY message from %s with invalid log ID, ignoring",
Sender::describeConnection(from).c_str());
return Message::Disposition::NORMAL;
}
ServerWorker* worker = ServerWorker::onThisThread();
if (!worker->isAcceptingWork()) {
ld_debug("Ignoring IS_LOG_EMPTY message: not accepting more work");
send_reply(from, header, E::SHUTDOWN, false);
return Message::Disposition::NORMAL;
}
WORKER_LOG_STAT_INCR(header.log_id, is_log_empty_received);
ServerProcessor* processor = worker->processor_;
if (!processor->runningOnStorageNode()) {
send_reply(from, header, E::NOTSTORAGE, false);
return Message::Disposition::NORMAL;
}
auto scfg = worker->getServerConfig();
const shard_size_t n_shards = scfg->getNumShards();
shard_index_t shard_idx = header.shard;
if (shard_idx >= n_shards) {
RATELIMIT_ERROR(std::chrono::seconds(10),
10,
"Got IS_LOG_EMPTY message from client %s with "
"invalid shard %u, this node only has %u shards",
Sender::describeConnection(from).c_str(),
shard_idx,
n_shards);
return Message::Disposition::NORMAL;
}
if (processor->isDataMissingFromShard(shard_idx)) {
send_reply(from, header, E::REBUILDING, false);
return Message::Disposition::NORMAL;
}
LogStorageStateMap& map = processor->getLogStorageStateMap();
LogStorageState* log_state = map.insertOrGet(header.log_id, shard_idx);
if (log_state == nullptr || log_state->hasPermanentError()) {
send_reply(from, header, E::FAILED, false);
return Message::Disposition::NORMAL;
}
folly::Optional<lsn_t> trim_point = log_state->getTrimPoint();
if (!trim_point.hasValue()) {
// Trim point is unknown. Try to find it...
int rv = map.recoverLogState(
header.log_id,
shard_idx,
LogStorageState::RecoverContext::IS_LOG_EMPTY_MESSAGE);
// And in the meantime tell the client to try again in a bit
send_reply(from, header, rv == 0 ? E::AGAIN : E::FAILED, false);
return Message::Disposition::NORMAL;
}
ShardedStorageThreadPool* sstp = processor->sharded_storage_thread_pool_;
LocalLogStore& store = sstp->getByIndex(shard_idx).getLocalLogStore();
lsn_t last_lsn;
int rv = store.getHighestInsertedLSN(header.log_id, &last_lsn);
if (rv == -1) {
if (err != E::NOTSUPPORTED || err != E::NOTSUPPORTEDLOG) {
RATELIMIT_ERROR(std::chrono::seconds(10),
2,
"Unexpected error code from getHighestInsertedLSN(): %s. "
"Changing to FAILED.",
error_name(err));
err = E::FAILED;
}
RATELIMIT_ERROR(std::chrono::seconds(1),
10,
"Unable to get the highest inserted LSN: %s",
error_description(err));
// an error occurred, reply to the client
send_reply(from, header, err, false);
return Message::Disposition::NORMAL;
}
ld_debug("IS_LOG_EMPTY(%lu): last_lsn=%lu, trim_point=%lu",
header.log_id.val_,
last_lsn,
trim_point.value());
bool empty = (last_lsn == LSN_INVALID || last_lsn <= trim_point.value());
if (empty) {
// Make sure we're not waiting for, or in, mini-rebuilding.
auto partitioned_store = dynamic_cast<PartitionedRocksDBStore*>(&store);
if (partitioned_store != nullptr &&
partitioned_store->isUnderReplicated()) {
RATELIMIT_DEBUG(std::chrono::seconds(10),
10,
"IS_LOG_EMPTY(%lu): local log store has dirty "
"partitions, reporting non-empty",
header.log_id.val_);
send_reply(from, header, E::REBUILDING, false);
return Message::Disposition::NORMAL;
}
} else {
// Make sure it's not just pseudorecords, such as bridge records.
auto partitioned_store = dynamic_cast<PartitionedRocksDBStore*>(&store);
empty = partitioned_store != nullptr &&
partitioned_store->isLogEmpty(header.log_id);
}
send_reply(from, header, E::OK, empty);
return Message::Disposition::NORMAL;
}
}} // namespace facebook::logdevice
| 37.186747 | 80 | 0.658675 | mickvav |
b99c2b7c8182bc3db33337ca0001459f1af30a62 | 10,352 | cpp | C++ | Gems/Vegetation/Code/Source/Components/SurfaceSlopeFilterComponent.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-08-08T19:54:51.000Z | 2021-08-08T19:54:51.000Z | Gems/Vegetation/Code/Source/Components/SurfaceSlopeFilterComponent.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-13T04:29:38.000Z | 2022-03-12T01:05:31.000Z | Gems/Vegetation/Code/Source/Components/SurfaceSlopeFilterComponent.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <VegetationProfiler.h>
#include "SurfaceSlopeFilterComponent.h"
#include <AzCore/Component/Entity.h>
#include <AzCore/Math/MathUtils.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <Vegetation/Descriptor.h>
#include <Vegetation/InstanceData.h>
#include <AzCore/Debug/Profiler.h>
#include <LmbrCentral/Dependency/DependencyMonitor.h>
#include <Vegetation/Ebuses/DebugNotificationBus.h>
namespace Vegetation
{
void SurfaceSlopeFilterConfig::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context);
if (serialize)
{
serialize->Class<SurfaceSlopeFilterConfig, AZ::ComponentConfig>()
->Version(0)
->Field("FilterStage", &SurfaceSlopeFilterConfig::m_filterStage)
->Field("AllowOverrides", &SurfaceSlopeFilterConfig::m_allowOverrides)
->Field("SlopeMin", &SurfaceSlopeFilterConfig::m_slopeMin)
->Field("SlopeMax", &SurfaceSlopeFilterConfig::m_slopeMax)
;
AZ::EditContext* edit = serialize->GetEditContext();
if (edit)
{
edit->Class<SurfaceSlopeFilterConfig>(
"Vegetation Slope Filter", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->DataElement(AZ::Edit::UIHandlers::ComboBox, &SurfaceSlopeFilterConfig::m_filterStage, "Filter Stage", "Determines if filter is applied before (PreProcess) or after (PostProcess) modifiers.")
->EnumAttribute(FilterStage::Default, "Default")
->EnumAttribute(FilterStage::PreProcess, "PreProcess")
->EnumAttribute(FilterStage::PostProcess, "PostProcess")
->DataElement(AZ::Edit::UIHandlers::CheckBox, &SurfaceSlopeFilterConfig::m_allowOverrides, "Allow Per-Item Overrides", "Allow per-descriptor parameters to override component parameters.")
->DataElement(AZ::Edit::UIHandlers::Slider, &SurfaceSlopeFilterConfig::m_slopeMin, "Slope Min", "Minimum surface slope angle in degrees.")
->Attribute(AZ::Edit::Attributes::Min, 0.0f)
->Attribute(AZ::Edit::Attributes::Max, 180.0f)
->DataElement(AZ::Edit::UIHandlers::Slider, &SurfaceSlopeFilterConfig::m_slopeMax, "Slope Max", "Maximum surface slope angle in degrees.")
->Attribute(AZ::Edit::Attributes::Min, 0.0f)
->Attribute(AZ::Edit::Attributes::Max, 180.0f)
;
}
}
if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
{
behaviorContext->Class<SurfaceSlopeFilterConfig>()
->Attribute(AZ::Script::Attributes::Category, "Vegetation")
->Constructor()
->Property("filterStage",
[](SurfaceSlopeFilterConfig* config) { return (AZ::u8&)(config->m_filterStage); },
[](SurfaceSlopeFilterConfig* config, const AZ::u8& i) { config->m_filterStage = (FilterStage)i; })
->Property("allowOverrides", BehaviorValueProperty(&SurfaceSlopeFilterConfig::m_allowOverrides))
->Property("slopeMin", BehaviorValueProperty(&SurfaceSlopeFilterConfig::m_slopeMin))
->Property("slopeMax", BehaviorValueProperty(&SurfaceSlopeFilterConfig::m_slopeMax))
;
}
}
void SurfaceSlopeFilterComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services)
{
services.push_back(AZ_CRC("VegetationFilterService", 0x9f97cc97));
services.push_back(AZ_CRC("VegetationSurfaceSlopeFilterService", 0xe052c323));
}
void SurfaceSlopeFilterComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services)
{
services.push_back(AZ_CRC("VegetationSurfaceSlopeFilterService", 0xe052c323));
}
void SurfaceSlopeFilterComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services)
{
services.push_back(AZ_CRC("VegetationAreaService", 0x6a859504));
}
void SurfaceSlopeFilterComponent::Reflect(AZ::ReflectContext* context)
{
SurfaceSlopeFilterConfig::Reflect(context);
AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context);
if (serialize)
{
serialize->Class<SurfaceSlopeFilterComponent, AZ::Component>()
->Version(0)
->Field("Configuration", &SurfaceSlopeFilterComponent::m_configuration)
;
}
if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
{
behaviorContext->Constant("SurfaceSlopeFilterComponentTypeId", BehaviorConstant(SurfaceSlopeFilterComponentTypeId));
behaviorContext->Class<SurfaceSlopeFilterComponent>()->RequestBus("SurfaceSlopeFilterRequestBus");
behaviorContext->EBus<SurfaceSlopeFilterRequestBus>("SurfaceSlopeFilterRequestBus")
->Attribute(AZ::Script::Attributes::Category, "Vegetation")
->Event("GetAllowOverrides", &SurfaceSlopeFilterRequestBus::Events::GetAllowOverrides)
->Event("SetAllowOverrides", &SurfaceSlopeFilterRequestBus::Events::SetAllowOverrides)
->VirtualProperty("AllowOverrides", "GetAllowOverrides", "SetAllowOverrides")
->Event("GetSlopeMin", &SurfaceSlopeFilterRequestBus::Events::GetSlopeMin)
->Event("SetSlopeMin", &SurfaceSlopeFilterRequestBus::Events::SetSlopeMin)
->VirtualProperty("SlopeMin", "GetSlopeMin", "SetSlopeMin")
->Event("GetSlopeMax", &SurfaceSlopeFilterRequestBus::Events::GetSlopeMax)
->Event("SetSlopeMax", &SurfaceSlopeFilterRequestBus::Events::SetSlopeMax)
->VirtualProperty("SlopeMax", "GetSlopeMax", "SetSlopeMax")
;
}
}
SurfaceSlopeFilterComponent::SurfaceSlopeFilterComponent(const SurfaceSlopeFilterConfig& configuration)
: m_configuration(configuration)
{
}
void SurfaceSlopeFilterComponent::Activate()
{
FilterRequestBus::Handler::BusConnect(GetEntityId());
SurfaceSlopeFilterRequestBus::Handler::BusConnect(GetEntityId());
}
void SurfaceSlopeFilterComponent::Deactivate()
{
FilterRequestBus::Handler::BusDisconnect();
SurfaceSlopeFilterRequestBus::Handler::BusDisconnect();
}
bool SurfaceSlopeFilterComponent::ReadInConfig(const AZ::ComponentConfig* baseConfig)
{
if (auto config = azrtti_cast<const SurfaceSlopeFilterConfig*>(baseConfig))
{
m_configuration = *config;
return true;
}
return false;
}
bool SurfaceSlopeFilterComponent::WriteOutConfig(AZ::ComponentConfig* outBaseConfig) const
{
if (auto config = azrtti_cast<SurfaceSlopeFilterConfig*>(outBaseConfig))
{
*config = m_configuration;
return true;
}
return false;
}
bool SurfaceSlopeFilterComponent::Evaluate(const InstanceData& instanceData) const
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity);
const bool useOverrides = m_configuration.m_allowOverrides && instanceData.m_descriptorPtr && instanceData.m_descriptorPtr->m_slopeFilterOverrideEnabled;
const float min = useOverrides ? instanceData.m_descriptorPtr->m_slopeFilterMin : m_configuration.m_slopeMin;
const float max = useOverrides ? instanceData.m_descriptorPtr->m_slopeFilterMax : m_configuration.m_slopeMax;
const AZ::Vector3 up = AZ::Vector3(0.0f, 0.0f, 1.0f);
const float c = instanceData.m_normal.Dot(up);
const float c1 = cosf(AZ::DegToRad(AZ::GetMin(min, max)));
const float c2 = cosf(AZ::DegToRad(AZ::GetMax(min, max)));
const bool result = (c <= c1) && (c >= c2);
if (!result)
{
VEG_PROFILE_METHOD(DebugNotificationBus::TryQueueBroadcast(&DebugNotificationBus::Events::FilterInstance, instanceData.m_id, AZStd::string_view("SurfaceSlopeFilter")));
}
return result;
}
FilterStage SurfaceSlopeFilterComponent::GetFilterStage() const
{
return m_configuration.m_filterStage;
}
void SurfaceSlopeFilterComponent::SetFilterStage(FilterStage filterStage)
{
m_configuration.m_filterStage = filterStage;
LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
}
bool SurfaceSlopeFilterComponent::GetAllowOverrides() const
{
return m_configuration.m_allowOverrides;
}
void SurfaceSlopeFilterComponent::SetAllowOverrides(bool value)
{
m_configuration.m_allowOverrides = value;
LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
}
float SurfaceSlopeFilterComponent::GetSlopeMin() const
{
return m_configuration.m_slopeMin;
}
void SurfaceSlopeFilterComponent::SetSlopeMin(float slopeMin)
{
m_configuration.m_slopeMin = slopeMin;
LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
}
float SurfaceSlopeFilterComponent::GetSlopeMax() const
{
return m_configuration.m_slopeMax;
}
void SurfaceSlopeFilterComponent::SetSlopeMax(float slopeMax)
{
m_configuration.m_slopeMax = slopeMax;
LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
}
}
| 45.403509 | 212 | 0.675328 | sandeel31 |
b99c41002a5bcafde39a2413d21f54106e7e51aa | 6,719 | cpp | C++ | svntrunk/src/BlueMatter/analysis/src/rdgdeviation.cpp | Bhaskers-Blu-Org1/BlueMatter | 1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e | [
"BSD-2-Clause"
] | 7 | 2020-02-25T15:46:18.000Z | 2022-02-25T07:04:47.000Z | svntrunk/src/BlueMatter/analysis/src/rdgdeviation.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | null | null | null | svntrunk/src/BlueMatter/analysis/src/rdgdeviation.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | 5 | 2019-06-06T16:30:21.000Z | 2020-11-16T19:43:01.000Z | /* Copyright 2001, 2019 IBM Corporation
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// **********************************************************************
// File: rdgdeviation.cpp
// Date: May 23, 2003
// Description: Adaptation of rdgdiff.cpp to report the sum of the
// squared differences in position and velocity over all sites for
// each time step in two trajectories.
// **********************************************************************
#include <assert.h>
#include <fcntl.h>
#include <cstdio>
#include <iomanip>
#include <iostream>
using namespace std ;
#include <BlueMatter/ExternalDatagram.hpp>
//#include <pk/fxlogger.hpp>
#include <BlueMatter/DataReceiver.hpp>
#include <BlueMatter/SimulationParser.hpp>
void
PrintUsage(const char* argv0)
{
cout << argv0 << " [-debug -skip1=N -skip2=N -nsteps=N] rdgfile1 rdgfile2" << endl;
}
int
main(int argc, char **argv, char **envp)
{
char *fname1 = NULL;
char *fname2 = NULL;
int NSkip1 = 0;
int NSkip2 = 0;
int NSteps = -1;
int diff = 0;
int debug = 0;
if (argc < 3) {
PrintUsage(argv[0]);
return -1;
}
int ReportMode = 0;
#define SKIP1 "-skip1="
#define SKIP2 "-skip2="
#define NSTEPS "-nsteps="
for (int i=1; i<argc; i++) {
char *s = argv[i];
char *p;
if (*s == '-') {
if (!strncmp(s, SKIP1, strlen(SKIP1)))
NSkip1 = atoi(&s[strlen(SKIP1)]);
else if (!strncmp(s, SKIP2, strlen(SKIP2)))
NSkip2 = atoi(&s[strlen(SKIP2)]);
else if (!strncmp(s, NSTEPS, strlen(NSTEPS)))
NSteps = atoi(&s[strlen(NSTEPS)]);
else if (!strcmp(s, "-debug"))
debug = 1;
else {
cerr << "Command line argument " << s << " not recognized" << endl;
PrintUsage(argv[0]);
exit(-1);
}
} else {
if (!fname1)
fname1 = s;
else if (!fname2)
fname2 = s;
else {
cerr << "Too many files specified: " << fname1 << " " << fname2 << " " << s << endl;
PrintUsage(argv[0]);
exit(-1);
}
}
}
if (!fname1 || !fname2) {
PrintUsage(argv[0]);
exit(-1);
}
Frame *pf1, *pf2;
SimulationParser sp1 = SimulationParser(fname1, 1, 0, 0, debug);
if (!sp1.OK())
cout << "Error opening file " << fname1 << endl;
SimulationParser sp2 = SimulationParser(fname2, 1, 0, 0, debug);
if (!sp2.OK())
cout << "Error opening file " << fname2 << endl;
if (!sp1.OK() || !sp2.OK()) {
return -1;
}
sp1.init();
sp2.init();
while (NSkip1 > 0 && !sp1.done()) {
sp1.getFrame(&pf1);
NSkip1--;
}
while (NSkip2 > 0 && !sp2.done()) {
sp2.getFrame(&pf2);
NSkip2--;
}
while (!sp1.done() && !sp2.done() && NSteps != 0) {
pf1 = pf2 = NULL;
sp1.getFrame(&pf1);
sp2.getFrame(&pf2);
// get the site data
if (pf1->mNSites != pf2->mNSites) {
cerr << "ERROR: site count mismatch at timesteps: "
<< pf1->mOuterTimeStep << " "
<< pf2->mOuterTimeStep << endl;
return(-1);
}
// check to see if both frames contain sites
if ((pf1->mSiteData.getSize() != pf1->mNSites) ||
(pf2->mSiteData.getSize() != pf2->mNSites)) {
continue;
}
if (pf1->mSiteData.hasGaps()) {
cerr << "Site Data has gaps for pf1" << endl;
break;
}
if (pf2->mSiteData.hasGaps()) {
cerr << "Site Data has gaps for pf2" << endl;
break;
}
if (pf1->mOuterTimeStep !=
pf2->mOuterTimeStep) {
continue;
}
const tSiteData* tsd1 = pf1->mSiteData.getArray();
const tSiteData* tsd2 = pf2->mSiteData.getArray();
double sumDeltaPos2 = 0;
double sumDeltaVel2 = 0;
for (int i = 0; i < pf1->mNSites; ++i)
{
double deltaPos2 =
// tsd1->mPosition.DistanceSquared(tsd2->mPosition);
pf1->mSiteData[i].mPosition.DistanceSquared(pf2->mSiteData[i].mPosition);
sumDeltaPos2 += deltaPos2;
double deltaVel2 =
// tsd1->mVelocity.DistanceSquared(tsd2->mVelocity);
pf1->mSiteData[i].mVelocity.DistanceSquared(pf2->mSiteData[i].mVelocity);
sumDeltaVel2 += deltaVel2;
if (debug) {
if ((deltaPos2 != 0) || (deltaVel2 != 0)) {
cout << "ts: " << pf1->mOuterTimeStep << " ";
cout << pf2->mOuterTimeStep << " ";
cout << "site: " << i << " " << endl;
cout << "file1: " << pf1->mSiteData[i].mPosition << " ";
cout << pf1->mSiteData[i].mVelocity << " " << endl;
cout << "file2: " << pf2->mSiteData[i].mPosition << " ";
cout << pf2->mSiteData[i].mVelocity << " " << endl;
cout << "deltaPos2 = " << deltaPos2 << " ";
cout << "deltaVel2 = " << deltaVel2 << " " << endl;
}
}
++tsd1;
++tsd2;
}
cout << setw(10) << pf1->mOuterTimeStep << " ";
cout << setw(10) << pf2->mOuterTimeStep << " ";
cout << setw(20) << setprecision(15) << sumDeltaPos2 << " ";
cout << setw(20) << setprecision(15) << sumDeltaVel2 << " ";
cout << endl;
if (!pf1 || !pf2)
break;
NSteps--;
}
sp1.final();
sp2.final();
return(0);
}
| 30.680365 | 118 | 0.549338 | Bhaskers-Blu-Org1 |
b99dfd6d63016ee46a62f42c622c79a4ef9f09d7 | 9,890 | hpp | C++ | src/xalanc/XPath/XPathExecutionContextDefault.hpp | rherardi/xml-xalan-c-src_1_10_0 | 24e6653a617a244e4def60d67b57e70a192a5d4d | [
"Apache-2.0"
] | null | null | null | src/xalanc/XPath/XPathExecutionContextDefault.hpp | rherardi/xml-xalan-c-src_1_10_0 | 24e6653a617a244e4def60d67b57e70a192a5d4d | [
"Apache-2.0"
] | null | null | null | src/xalanc/XPath/XPathExecutionContextDefault.hpp | rherardi/xml-xalan-c-src_1_10_0 | 24e6653a617a244e4def60d67b57e70a192a5d4d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.
*/
#if !defined(XPATHEXECUTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680)
#define XPATHEXECUTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/XPath/XPathDefinitions.hpp>
#include <xalanc/Include/XalanObjectCache.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
/**
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
// Base class include file.
#include <xalanc/XPath/XPathExecutionContext.hpp>
#include <xalanc/PlatformSupport/XalanDOMStringCache.hpp>
#include <xalanc/XPath/MutableNodeRefList.hpp>
#include <xalanc/XPath/XalanQNameByValue.hpp>
XALAN_CPP_NAMESPACE_BEGIN
class DOMSupport;
class XPathEnvSupport;
class XalanQName;
/**
* A basic implementation of the class XPathExecutionContext.
*/
class XALAN_XPATH_EXPORT XPathExecutionContextDefault : public XPathExecutionContext
{
public:
typedef XalanVector<XalanNode*> CurrentNodeStackType;
typedef XalanVector<const NodeRefListBase*> ContextNodeListStackType;
/**
* Construct an XPathExecutionContextDefault object
*
* @param theXPathEnvSupport XPathEnvSupport class instance
* @param theDOMSupport DOMSupport class instance
* @param theXobjectFactory factory class instance for XObjects
* @param theCurrentNode current node in the source tree
* @param theContextNodeList node list for current context
* @param thePrefixResolver pointer to prefix resolver to use
*/
XPathExecutionContextDefault(
XPathEnvSupport& theXPathEnvSupport,
DOMSupport& theDOMSupport,
XObjectFactory& theXObjectFactory,
XalanNode* theCurrentNode = 0,
const NodeRefListBase* theContextNodeList = 0,
const PrefixResolver* thePrefixResolver = 0);
/**
* Construct an XPathExecutionContextDefault object
*
* @param theXPathEnvSupport XPathEnvSupport class instance
* @param theXObjectFactory factory class instance for XObjects
* @param theCurrentNode current node in the source tree
* @param theContextNodeList node list for current context
* @param thePrefixResolver pointer to prefix resolver to use
*/
explicit
XPathExecutionContextDefault(
MemoryManagerType& theManager,
XalanNode* theCurrentNode = 0,
const NodeRefListBase* theContextNodeList = 0,
const PrefixResolver* thePrefixResolver = 0);
static XPathExecutionContextDefault*
create(
MemoryManagerType& theManager,
XalanNode* theCurrentNode = 0,
const NodeRefListBase* theContextNodeList = 0,
const PrefixResolver* thePrefixResolver = 0);
virtual
~XPathExecutionContextDefault();
/**
* Get the XPathEnvSupport instance.
*
* @return a pointer to the instance.
*/
XPathEnvSupport*
getXPathEnvSupport() const
{
return m_xpathEnvSupport;
}
/**
* Set the XPathEnvSupport instance.
*
* @param theSupport a reference to the instance to use.
*/
void
setXPathEnvSupport(XPathEnvSupport* theSupport)
{
m_xpathEnvSupport = theSupport;
}
/**
* Set the DOMSupport instance.
*
* @param theDOMSupport a reference to the instance to use.
*/
void
setDOMSupport(DOMSupport* theDOMSupport)
{
m_domSupport = theDOMSupport;
}
/**
* Set the XObjectFactory instance.
*
* @param theFactory a reference to the instance to use.
*/
void
setXObjectFactory(XObjectFactory* theXObjectFactory)
{
m_xobjectFactory = theXObjectFactory;
}
/**
* Get a reference to the scratch QNameByValue instance.
*
* @return A reference to a QNameByValue instance.
*/
XalanQNameByValue&
getScratchQName() const
{
#if defined(XALAN_NO_MUTABLE)
return ((XPathExecutionContextDefault*)this)->m_scratchQName;
#else
return m_scratchQName;
#endif
}
virtual void doFormatNumber(
double number,
const XalanDOMString& pattern,
const XalanDecimalFormatSymbols* theDFS,
XalanDOMString& theResult,
const XalanNode* context = 0,
const LocatorType* locator = 0);
// These interfaces are inherited from XPathExecutionContext...
virtual void
reset();
virtual XalanNode*
getCurrentNode() const;
virtual void
pushCurrentNode(XalanNode* theCurrentNode);
virtual void
popCurrentNode();
virtual bool
isNodeAfter(
const XalanNode& node1,
const XalanNode& node2) const;
virtual void
pushContextNodeList(const NodeRefListBase& theList);
virtual void
popContextNodeList();
virtual const NodeRefListBase&
getContextNodeList() const;
virtual size_type
getContextNodeListLength() const;
virtual size_type
getContextNodeListPosition(const XalanNode& contextNode) const;
virtual bool
elementAvailable(const XalanQName& theQName) const;
virtual bool
elementAvailable(
const XalanDOMString& theName,
const LocatorType* locator) const;
virtual bool
functionAvailable(const XalanQName& theQName) const;
virtual bool
functionAvailable(
const XalanDOMString& theName,
const LocatorType* locator) const;
virtual const XObjectPtr
extFunction(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
XalanNode* context,
const XObjectArgVectorType& argVec,
const LocatorType* locator);
virtual XalanDocument*
parseXML(
MemoryManagerType& theManager,
const XalanDOMString& urlString,
const XalanDOMString& base) const;
virtual MutableNodeRefList*
borrowMutableNodeRefList();
virtual bool
returnMutableNodeRefList(MutableNodeRefList* theList);
virtual MutableNodeRefList*
createMutableNodeRefList(MemoryManagerType& theManager) const;
virtual XalanDOMString&
getCachedString();
virtual bool
releaseCachedString(XalanDOMString& theString);
virtual void
getNodeSetByKey(
XalanDocument* doc,
const XalanQName& qname,
const XalanDOMString& ref,
MutableNodeRefList& nodelist);
virtual void
getNodeSetByKey(
XalanDocument* doc,
const XalanDOMString& name,
const XalanDOMString& ref,
const LocatorType* locator,
MutableNodeRefList& nodelist);
virtual const XObjectPtr
getVariable(
const XalanQName& name,
const LocatorType* locator = 0);
virtual const PrefixResolver*
getPrefixResolver() const;
virtual void
setPrefixResolver(const PrefixResolver* thePrefixResolver);
virtual const XalanDOMString*
getNamespaceForPrefix(const XalanDOMString& prefix) const;
virtual const XalanDOMString&
findURIFromDoc(const XalanDocument* owner) const;
virtual const XalanDOMString&
getUnparsedEntityURI(
const XalanDOMString& theName,
const XalanDocument& theDocument) const;
virtual bool
shouldStripSourceNode(const XalanText& node);
virtual XalanDocument*
getSourceDocument(const XalanDOMString& theURI) const;
virtual void
setSourceDocument(
const XalanDOMString& theURI,
XalanDocument* theDocument);
// These interfaces are inherited from ExecutionContext...
virtual void formatNumber(
double number,
const XalanDOMString& pattern,
XalanDOMString& theResult,
const XalanNode* context = 0,
const LocatorType* locator = 0);
virtual void formatNumber(
double number,
const XalanDOMString& pattern,
const XalanDOMString& dfsName,
XalanDOMString& theResult,
const XalanNode* context = 0,
const LocatorType* locator = 0);
virtual void
error(
const XalanDOMString& msg,
const XalanNode* sourceNode = 0,
const LocatorType* locator = 0) const;
virtual void
warn(
const XalanDOMString& msg,
const XalanNode* sourceNode = 0,
const LocatorType* locator = 0) const;
virtual void
message(
const XalanDOMString& msg,
const XalanNode* sourceNode = 0,
const LocatorType* locator = 0) const;
protected:
typedef XalanObjectCache<MutableNodeRefList, DefaultCacheCreateFunctorMemMgr<MutableNodeRefList>, DeleteFunctor<MutableNodeRefList>, ClearCacheResetFunctor<MutableNodeRefList> > NodeListCacheType;
enum { eNodeListCacheListSize = 50 };
struct ContextNodeListPositionCache
{
ContextNodeListPositionCache() :
m_node(0),
m_index(0)
{
}
void
clear()
{
if (m_node != 0)
{
m_node = 0;
}
}
const XalanNode* m_node;
size_type m_index;
};
XPathEnvSupport* m_xpathEnvSupport;
DOMSupport* m_domSupport;
CurrentNodeStackType m_currentNodeStack;
ContextNodeListStackType m_contextNodeListStack;
const PrefixResolver* m_prefixResolver;
XalanDOMString m_currentPattern;
NodeListCacheType m_nodeListCache;
XalanDOMStringCache m_stringCache;
mutable ContextNodeListPositionCache m_cachedPosition;
mutable XalanQNameByValue m_scratchQName;
static const NodeRefList s_dummyList;
};
XALAN_CPP_NAMESPACE_END
#endif // XPATHEXECUTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680
| 24.419753 | 198 | 0.718301 | rherardi |
b99f46cfe30482b2f31b95961356219d62c421e8 | 20,921 | cpp | C++ | src/nodes.cpp | TUM-I5/LinA | 6834d7f0cc283b75c0569f01285ff4ccaa047b37 | [
"BSD-3-Clause"
] | null | null | null | src/nodes.cpp | TUM-I5/LinA | 6834d7f0cc283b75c0569f01285ff4ccaa047b37 | [
"BSD-3-Clause"
] | null | null | null | src/nodes.cpp | TUM-I5/LinA | 6834d7f0cc283b75c0569f01285ff4ccaa047b37 | [
"BSD-3-Clause"
] | null | null | null | /** This file is generated. Do not edit. */
#include "nodes.h"
namespace lina {
#if !defined(CONVERGENCE_ORDER)
#error CONVERGENCE_ORDER must be set.
#elif CONVERGENCE_ORDER == 2
double const LGLNodes[] = {0.00000000000000000000000000000000, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 3
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.50000000000000000000000000000000, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 4
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.27639320225002103035908263312687, 0.72360679774997896964091736687313, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 5
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.17267316464601142810085377187657, 0.50000000000000000000000000000000, 0.82732683535398857189914622812343, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 6
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.11747233803526765357449851302033, 0.35738424175967745184292450297956, 0.64261575824032254815707549702044, 0.88252766196473234642550148697967, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 7
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.08488805186071653506398389301627, 0.26557560326464289309811405904562, 0.50000000000000000000000000000000, 0.73442439673535710690188594095438, 0.91511194813928346493601610698373, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 8
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.06412992574519669233127711938967, 0.20414990928342884892774463430102, 0.39535039104876056561567136982732, 0.60464960895123943438432863017268, 0.79585009071657115107225536569898, 0.93587007425480330766872288061033, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 9
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.05012100229426992134382737779083, 0.16140686024463112327705728645433, 0.31844126808691092064462396564567, 0.50000000000000000000000000000000, 0.68155873191308907935537603435433, 0.83859313975536887672294271354567, 0.94987899770573007865617262220917, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 10
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.04023304591677059308553366958883, 0.13061306744724746249844691257008, 0.26103752509477775216941245363437, 0.41736052116680648768689011702092, 0.58263947883319351231310988297908, 0.73896247490522224783058754636563, 0.86938693255275253750155308742992, 0.95976695408322940691446633041117, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 11
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.03299928479597043283386293195031, 0.10775826316842779068879109194577, 0.21738233650189749676451801526112, 0.35212093220653030428404424222047, 0.50000000000000000000000000000000, 0.64787906779346969571595575777953, 0.78261766349810250323548198473888, 0.89224173683157220931120890805423, 0.96700071520402956716613706804969, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 12
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.02755036388855888829620993084839, 0.09036033917799666082567920914155, 0.18356192348406966116879757277817, 0.30023452951732553386782510421652, 0.43172353357253622256796907213016, 0.56827646642746377743203092786984, 0.69976547048267446613217489578348, 0.81643807651593033883120242722183, 0.90963966082200333917432079085845, 0.97244963611144111170379006915161, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 13
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.02334507667891804405154726762228, 0.07682621767406384156703719645062, 0.15690576545912128696362048021682, 0.25854508945433189912653138318154, 0.37535653494688000371566314981288, 0.50000000000000000000000000000000, 0.62464346505311999628433685018712, 0.74145491054566810087346861681846, 0.84309423454087871303637951978318, 0.92317378232593615843296280354938, 0.97665492332108195594845273237772, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 14
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.02003247736636954932244991899229, 0.06609947308482637449988989854587, 0.13556570045433692970766379973956, 0.22468029853567647234168864707046, 0.32863799332864357747804829817916, 0.44183406555814806617061164513192, 0.55816593444185193382938835486808, 0.67136200667135642252195170182084, 0.77531970146432352765831135292954, 0.86443429954566307029233620026044, 0.93390052691517362550011010145413, 0.97996752263363045067755008100771, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 15
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.01737703674808071360207430396520, 0.05745897788851185058729918425888, 0.11824015502409239964794076201186, 0.19687339726507714443823503068164, 0.28968097264316375953905153063071, 0.39232302231810288088716027686354, 0.50000000000000000000000000000000, 0.60767697768189711911283972313646, 0.71031902735683624046094846936929, 0.80312660273492285556176496931836, 0.88175984497590760035205923798814, 0.94254102211148814941270081574112, 0.98262296325191928639792569603480, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 16
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.01521597686489103352387863081627, 0.05039973345326395350268586924008, 0.10399585406909246803445586451842, 0.17380564855875345526605839017971, 0.25697028905643119410905460707656, 0.35008476554961839595082327263885, 0.44933686323902527607848349747704, 0.55066313676097472392151650252296, 0.64991523445038160404917672736115, 0.74302971094356880589094539292344, 0.82619435144124654473394160982029, 0.89600414593090753196554413548158, 0.94960026654673604649731413075992, 0.98478402313510896647612136918373, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 17
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.01343391168429084292151024906314, 0.04456000204221320218809874680114, 0.09215187438911484644662472338124, 0.15448550968615764730254032131378, 0.22930730033494923043813329624797, 0.31391278321726147904638265963237, 0.40524401324084130584786849262344, 0.50000000000000000000000000000000, 0.59475598675915869415213150737656, 0.68608721678273852095361734036763, 0.77069269966505076956186670375203, 0.84551449031384235269745967868622, 0.90784812561088515355337527661876, 0.95543999795778679781190125319886, 0.98656608831570915707848975093686, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 18
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.01194722129390072856774053782915, 0.03967540732623306308107268728436, 0.08220323239095489314317681883603, 0.13816033535837865934689481734896, 0.20574758284066911941323205340322, 0.28279248154393801232885643162966, 0.36681867356085950791616733398720, 0.45512545325767394448867749495572, 0.54487454674232605551132250504428, 0.63318132643914049208383266601280, 0.71720751845606198767114356837034, 0.79425241715933088058676794659678, 0.86183966464162134065310518265104, 0.91779676760904510685682318116397, 0.96032459267376693691892731271564, 0.98805277870609927143225946217085, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 19
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.01069411688895995242368296844489, 0.03554923592370687814102987060172, 0.07376971110167695345702201497947, 0.12425289872369349291818125518303, 0.18554593136738975111658384688564, 0.25588535715964324861104518118754, 0.33324757608775069485074994807754, 0.41540698829535921431242292327756, 0.50000000000000000000000000000000, 0.58459301170464078568757707672244, 0.66675242391224930514925005192246, 0.74411464284035675138895481881246, 0.81445406863261024888341615311436, 0.87574710127630650708181874481697, 0.92623028889832304654297798502053, 0.96445076407629312185897012939828, 0.98930588311104004757631703155511, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 20
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00962814755304291403727678070788, 0.03203275059366728214190920753468, 0.06656101095502492934507639269186, 0.11231586952397206479284123620266, 0.16811179885484435507679833851442, 0.23250356798405686917593201908551, 0.30382340814304535030676264809209, 0.38022414703850675240879932153646, 0.45972703138058908101202774092022, 0.54027296861941091898797225907978, 0.61977585296149324759120067846354, 0.69617659185695464969323735190791, 0.76749643201594313082406798091449, 0.83188820114515564492320166148558, 0.88768413047602793520715876379734, 0.93343898904497507065492360730814, 0.96796724940633271785809079246532, 0.99037185244695708596272321929212, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 21
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00871385169772598588275936172230, 0.02901185152012723285194867466928, 0.06035262233820476777442320184753, 0.10199903696114379762784370516982, 0.15297448696888838368634180340266, 0.21208401986908465653648906483096, 0.27794210836049894940274182519632, 0.34900507174561755636232406607062, 0.42360724209890726699682083575716, 0.50000000000000000000000000000000, 0.57639275790109273300317916424284, 0.65099492825438244363767593392938, 0.72205789163950105059725817480368, 0.78791598013091534346351093516904, 0.84702551303111161631365819659734, 0.89800096303885620237215629483018, 0.93964737766179523222557679815247, 0.97098814847987276714805132533072, 0.99128614830227401411724063827770, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 22
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00792378077117691172385518889396, 0.02639785800038565973789311669214, 0.05496885490454776473517108711046, 0.09302553619403943197727907597193, 0.13975638001939892094005905180076, 0.19416528085787051438689419706504, 0.25509256240504882509562438215836, 0.32123964493054023096952135987991, 0.39119670742035747910602245326730, 0.46347272999455083261945560476795, 0.53652727000544916738054439523205, 0.60880329257964252089397754673270, 0.67876035506945976903047864012009, 0.74490743759495117490437561784164, 0.80583471914212948561310580293496, 0.86024361998060107905994094819924, 0.90697446380596056802272092402807, 0.94503114509545223526482891288954, 0.97360214199961434026210688330786, 0.99207621922882308827614481110604, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 23
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00723642206063371095926861663095, 0.02412102214464489793218016007428, 0.05027072097982749452491983982632, 0.08517445167435705688839969035500, 0.12815247941396965802741822846650, 0.17836817776993189576192723319862, 0.23484411443157791593494233992385, 0.29648103104276258540202475589245, 0.36207922552710346644656118366043, 0.43036189797966580070406869350862, 0.50000000000000000000000000000000, 0.56963810202033419929593130649138, 0.63792077447289653355343881633957, 0.70351896895723741459797524410755, 0.76515588556842208406505766007615, 0.82163182223006810423807276680138, 0.87184752058603034197258177153350, 0.91482554832564294311160030964500, 0.94972927902017250547508016017368, 0.97587897785535510206781983992572, 0.99276357793936628904073138336905, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 24
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00663472324741955822345663092276, 0.02212588953505682098651143472468, 0.04614716244324673900242350176690, 0.07826796492256397968834748128833, 0.11791475878975334610631235952386, 0.16437994736793565008216757090650, 0.21683432101035234390529522772886, 0.27434181339283869087589075421519, 0.33587619331224454398330541032020, 0.40033937330458366638171373043750, 0.46658100313138571094317909580416, 0.53341899686861428905682090419584, 0.59966062669541633361828626956250, 0.66412380668775545601669458967980, 0.72565818660716130912410924578481, 0.78316567898964765609470477227114, 0.83562005263206434991783242909350, 0.88208524121024665389368764047614, 0.92173203507743602031165251871167, 0.95385283755675326099757649823310, 0.97787411046494317901348856527532, 0.99336527675258044177654336907724, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 25
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00610502753425314536409796456342, 0.02036793087373276057007741058024, 0.04250861463268871083842503313158, 0.07216176708234171123809336991412, 0.10884017037964160980040602388562, 0.15194147559243281661981728310531, 0.20075792636000336595118950140946, 0.25448794259056080869052003871560, 0.31224927107038638338564269386964, 0.37309346791556170991005655915636, 0.43602147025844651364550768745268, 0.50000000000000000000000000000000, 0.56397852974155348635449231254732, 0.62690653208443829008994344084364, 0.68775072892961361661435730613036, 0.74551205740943919130947996128440, 0.79924207363999663404881049859054, 0.84805852440756718338018271689469, 0.89115982962035839019959397611438, 0.92783823291765828876190663008588, 0.95749138536731128916157496686842, 0.97963206912626723942992258941976, 0.99389497246574685463590203543658, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 26
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00563629384426217278537665481435, 0.01881106261614133512466866435894, 0.03928222659122132943743473912566, 0.06673783802043821451277425109512, 0.10076140844628128048160618071483, 0.14083709181866745973729730604804, 0.18635735025384155609974054641939, 0.23663212898506072735087830280950, 0.29089930646687660721815805883308, 0.34833624357037363961297948104894, 0.40807225236497254933939716405712, 0.46920179410904013589725636260912, 0.53079820589095986410274363739088, 0.59192774763502745066060283594288, 0.65166375642962636038702051895106, 0.70910069353312339278184194116692, 0.76336787101493927264912169719050, 0.81364264974615844390025945358061, 0.85916290818133254026270269395196, 0.89923859155371871951839381928517, 0.93326216197956178548722574890488, 0.96071777340877867056256526087434, 0.98118893738385866487533133564106, 0.99436370615573782721462334518565, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 27
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00521951813572468942556267997274, 0.01742579877459054036786659843944, 0.03640827063744211057012661796364, 0.06189895689273876066672847540293, 0.09353975655209385587095406762073, 0.13088642507677004458028638712580, 0.17341466815159524241064756240877, 0.22052746952871940996866596256594, 0.27156346219295879816069367458038, 0.32580620900548566478145671070642, 0.38249425844854093333159920974334, 0.44083183305073947578064586586234, 0.50000000000000000000000000000000, 0.55916816694926052421935413413766, 0.61750574155145906666840079025666, 0.67419379099451433521854328929358, 0.72843653780704120183930632541962, 0.77947253047128059003133403743406, 0.82658533184840475758935243759123, 0.86911357492322995541971361287420, 0.90646024344790614412904593237927, 0.93810104310726123933327152459707, 0.96359172936255788942987338203636, 0.98257420122540945963213340156056, 0.99478048186427531057443732002726, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 28
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00484729869077293724145354406770, 0.01618785707143434782811456042826, 0.03383741643922073753692879069550, 0.05756449139434858079384683087138, 0.08705951497183090197774278690170, 0.12193790299721511742395213736690, 0.16174493553521334114030937746330, 0.20596165508141219676084396011914, 0.25401162303421030978519165852776, 0.30526843121181859603205792239794, 0.35906386668919881402292374554534, 0.41469662234599781955864866112562, 0.47144143915324355118672817421313, 0.52855856084675644881327182578687, 0.58530337765400218044135133887438, 0.64093613331080118597707625445466, 0.69473156878818140396794207760206, 0.74598837696578969021480834147224, 0.79403834491858780323915603988086, 0.83825506446478665885969062253670, 0.87806209700278488257604786263310, 0.91294048502816909802225721309830, 0.94243550860565141920615316912862, 0.96616258356077926246307120930450, 0.98381214292856565217188543957174, 0.99515270130922706275854645593230, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 29
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00451350586571509186062744335022, 0.01507709635603185314379930605609, 0.03152864073950874422898157585832, 0.05366714001195586061788504297346, 0.08122363185910671737896334190659, 0.11386355139676562932291468293178, 0.15119066932181600580301278571146, 0.19275187389828352501454819128782, 0.23804266281401545821059171343820, 0.28651326414325280618121179451582, 0.33757530857904449686999298846058, 0.39060897085786949009547407383750, 0.44497049330220394514610619887216, 0.50000000000000000000000000000000, 0.55502950669779605485389380112784, 0.60939102914213050990452592616250, 0.66242469142095550313000701153942, 0.71348673585674719381878820548418, 0.76195733718598454178940828656180, 0.80724812610171647498545180871218, 0.84880933067818399419698721428854, 0.88613644860323437067708531706822, 0.91877636814089328262103665809341, 0.94633285998804413938211495702654, 0.96847135926049125577101842414168, 0.98492290364396814685620069394391, 0.99548649413428490813937255664978, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 30
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00421302857974985333059088704568, 0.01407669841686537916170352389540, 0.02944760952447145884640522529224, 0.05015039090036157022332858842528, 0.07595025640990094522428808390846, 0.10655482138122645977502023970380, 0.14161730068145743418310070193505, 0.18074041209622079631445325864513, 0.22348086995247357380772488497967, 0.26935440491587965738672138944642, 0.31784124978877550112200744722410, 0.36839202814021310436645026549996, 0.42043397868707476608752571145058, 0.47337744475725666531849608277432, 0.52662255524274333468150391722568, 0.57956602131292523391247428854942, 0.63160797185978689563354973450004, 0.68215875021122449887799255277590, 0.73064559508412034261327861055358, 0.77651913004752642619227511502033, 0.81925958790377920368554674135487, 0.85838269931854256581689929806495, 0.89344517861877354022497976029620, 0.92404974359009905477571191609154, 0.94984960909963842977667141157472, 0.97055239047552854115359477470776, 0.98592330158313462083829647610460, 0.99578697142025014666940911295432, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 31
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00394157782675945570533769217564, 0.01317253209213176258696522576238, 0.02756541489598038509679723117507, 0.04696652427936509342774423837627, 0.07117000235127219481649730880176, 0.09991922840376850536383433300841, 0.13290943184546237893292958258118, 0.16979089869423723833147936270162, 0.21017267139599904349835156890114, 0.25362669045058379714809988346490, 0.29969233085971909684866779030196, 0.34788128436356368952027242618687, 0.39768273537623774942945320713614, 0.44856877561965886145544263834598, 0.50000000000000000000000000000000, 0.55143122438034113854455736165402, 0.60231726462376225057054679286386, 0.65211871563643631047972757381313, 0.70030766914028090315133220969804, 0.74637330954941620285190011653510, 0.78982732860400095650164843109886, 0.83020910130576276166852063729838, 0.86709056815453762106707041741882, 0.90008077159623149463616566699159, 0.92882999764872780518350269119824, 0.95303347572063490657225576162373, 0.97243458510401961490320276882493, 0.98682746790786823741303477423762, 0.99605842217324054429466230782436, 1.00000000000000000000000000000000};
#elif CONVERGENCE_ORDER == 32
double const LGLNodes[] = {0.00000000000000000000000000000000, 0.00369553301361932031422934236128, 0.01235265475864538596877202480592, 0.02585758079138381095833587920578, 0.04407503046813404796273427381296, 0.06682376199366224008459261528773, 0.09387763411127882772658910596371, 0.12496775303166260114136201766085, 0.15978512219222459202880212115058, 0.19798370642578943693141354369406, 0.23918386855921735469670371330399, 0.28297614139907653019834032149680, 0.32892529673055925687309388965064, 0.37657467057489734779187928442056, 0.42545070159317625254280906191498, 0.47506763747670337384685112763579, 0.52493236252329662615314887236421, 0.57454929840682374745719093808502, 0.62342532942510265220812071557944, 0.67107470326944074312690611034936, 0.71702385860092346980165967850320, 0.76081613144078264530329628669601, 0.80201629357421056306858645630594, 0.84021487780777540797119787884942, 0.87503224696833739885863798233915, 0.90612236588872117227341089403629, 0.93317623800633775991540738471227, 0.95592496953186595203726572618704, 0.97414241920861618904166412079422, 0.98764734524135461403122797519408, 0.99630446698638067968577065763872, 1.00000000000000000000000000000000};
#endif
}
| 298.871429 | 1,179 | 0.898666 | TUM-I5 |
b9a46e7464f3b553e1f6c8192ff9a1b876cc056a | 12,021 | cc | C++ | MathUtils/src/Measurement_Arithmetic.cc | yimuchen/UserUtils | 1a5c55d286f325424f4cfd23f22da63cfa6fb6a9 | [
"MIT"
] | null | null | null | MathUtils/src/Measurement_Arithmetic.cc | yimuchen/UserUtils | 1a5c55d286f325424f4cfd23f22da63cfa6fb6a9 | [
"MIT"
] | 1 | 2021-12-10T15:04:04.000Z | 2022-01-10T18:56:53.000Z | MathUtils/src/Measurement_Arithmetic.cc | yimuchen/UserUtils | 1a5c55d286f325424f4cfd23f22da63cfa6fb6a9 | [
"MIT"
] | 1 | 2018-06-05T14:08:08.000Z | 2018-06-05T14:08:08.000Z | /**
* @file Measurement_Arithmetic.cc
* @brief Implementation of measurement arithetics methods
* @author [Yi-Mu "Enoch" Chen](https://github.com/yimuchen)
*/
#ifdef CMSSW_GIT_HASH
#include "UserUtils/MathUtils/interface/Measurement.hpp"
#include "UserUtils/MathUtils/interface/StatisticsUtil.hpp"
#else
#include "UserUtils/MathUtils/Measurement.hpp"
#include "UserUtils/MathUtils/StatisticsUtil.hpp"
#endif
#include <numeric>
#include "Math/Derivator.h"
#include "Math/Functor.h"
using namespace std;
namespace usr {
/**
* @brief interface to the Single variable version of the MinosError() function.
*/
Measurement
MakeMinos(
const ROOT::Math::IGenFunction& nll,
const double min,
const double max,
const double confidencelevel )
{
double central = min + max / 2;
double lowerbound = min;
double upperbound = max;
usr::stat::MinosError( nll, central, lowerbound, upperbound, confidencelevel );
return Measurement( central, upperbound-central, central-lowerbound );
}
/**
* @brief interface to the \f$R^{n}\rightarrow R\f$ version of the MinosError()
* function
*/
Measurement
MakeMinos(
const ROOT::Math::IMultiGenFunction& nllfunction,
const ROOT::Math::IMultiGenFunction& varfunction,
const double* initguess,
const double confidencelevel,
const double* upperguess,
const double* lowerguess )
{
double central;
double upperbound;
double lowerbound;
usr::stat::MinosError( nllfunction
, varfunction
, initguess
, central
, lowerbound
, upperbound
, confidencelevel
, upperguess
, lowerguess );
return Measurement( central
, fabs( upperbound-central )
, fabs( central - lowerbound ) );
}
/**
* @brief Approximate @NLL function for a measurements of
* \f$x^{+\sigma_+}_{-\sigma_i}\f$
*
* The approximation for an @NLL function is a variation of the one recommended
* in [R. Barlow's "Asymmetric statistical
* errors"](https://arxiv.org/abs/physics/0406120), In the form of:
*
* \f[\mathrm{NLL}(x) = \frac{x^{2}}{ 2V(1+Ax)} \f]
*
* with \f$V\f$ being the average variance \f$\frac{\sigma_+ + \sigma_-}{2}\f$,
* and \f$A\f$ being the variance asymmetry \f$\frac{\sigma_{+} -
* \sigma_{-}}{V}\f$.
*
* A few adjustments are made to ensure the stability of the calculations.
* - The ratio between the two uncertainties would have a hard limit of 10. The
* smaller uncertainty would be inflated if extreme asymmetries are present.
* - The average variance would have an minimum value of \f$10^{-16}\f$ which
* should cover most cases where uncertainty calculations are required. Test
* have shown that the calculation would not be affected by such limits if the
* there are some dominate uncertainties.
* - To avoid the singularity at \f$x=-1/A\f$, an exponential function would be
* used instead for the linear function for the denominator in the @NLL
* function when x is past half-way from the central value to the original
* singular point, such that the approximation would be extended to an infinite
* domain. The exponential function is designed such that the denominator and
* its derivative is continuous.
*/
double
LinearVarianceNLL( const double x, const Measurement& m )
{
static const double maxrelerror = 10.;
static double (* AugmentedDenominator)( double, const double, const double )
= []( double x, const double up, const double lo )->double {
static const double minprod = 1e-12;
const double V = std::max( up * lo, minprod );
const double A = ( up-lo ) / V;
double ans = V * ( 1 + x * A );
if( up > lo && A != 0 && x < ( -lo-1/A )/ 2 ){
const double s = ( -lo-1/A )/2;
const double b = A / ( 1+A*s );
const double B = V * ( 1+A*s ) / exp( b*s );
ans = B * exp( b * x );
} else if( lo > up && A != 0 && x > ( up+1/A )/2 ){
ans = AugmentedDenominator( -x, lo, up );
}
return ans;
};
// Getting potentially inflating uncertainties
const double central = m.CentralValue();
const double rawupper = m.AbsUpperError();
const double rawlower = m.AbsLowerError();
const double effupper = std::max( rawupper, rawlower / maxrelerror );
const double efflower = std::max( rawlower, rawupper / maxrelerror );
const double num = ( x- central ) * ( x - central );
const double de = AugmentedDenominator( x-central, effupper, efflower );
const double ans = 0.5 * num / de;
return ans;
}
/**
* @brief given a list of measurements with uncertainties, return the effective
* sum of all measurements as if all measurements are uncorrelated.
*
* Given a list of parameters, a master @NLL function is generated assuming that
* all variables are uncorrelated and uses the same underlying @NLL function
* (specifed with the `nll` argument). The MinosErrors method for
* multidimensional Minos uncertainty calculations is then invoked for the
* calculation. This function also automatically estimates the initial guesses
* for the Minos error calculations using the partial differentials of the
* variable function. For details of this initial guess estimation see the
* usr::LazyEvaluateUncorrelated method.
*/
extern Measurement
EvaluateUncorrelated(
const std::vector<Measurement>& m_list,
const ROOT::Math::IMultiGenFunction& varfunction,
const double confidencelevel,
double (* nll )( double, const Measurement& ) )
{
auto masternll = [&m_list, nll]( const double* x )->double {
double ans = 0;
for( unsigned i = 0; i < m_list.size(); ++i ){
ans = ans + nll( x[i], m_list.at( i ) );
}
return ans;
};
ROOT::Math::Functor nllfunction( masternll, m_list.size() );
std::vector<double> init;
std::vector<double> upperguess;
std::vector<double> lowerguess;
double diff_sqsum = 0;
for( const auto& m : m_list ){
init.push_back( m.CentralValue() );
}
for( unsigned i = 0; i < m_list.size(); ++i ){
const double diff = ROOT::Math::Derivator::Eval( varfunction
, init.data(), i );
diff_sqsum += diff *diff;
}
diff_sqsum = std::sqrt( diff_sqsum );
// Guess for the boundaries for the input required for getting the upper and
// lower uncertainties based on the derivatives of the variable function.
for( unsigned i = 0; i < m_list.size(); ++i ){
const double diff = ROOT::Math::Derivator::Eval( varfunction
, init.data(), i );
const double w = fabs( diff / diff_sqsum );
if( diff > 0 ){
upperguess.push_back( init.at( i ) + w*m_list.at( i ).AbsUpperError() );
lowerguess.push_back( init.at( i ) - w*m_list.at( i ).AbsLowerError() );
} else {
upperguess.push_back( init.at( i ) - w*m_list.at( i ).AbsLowerError() );
lowerguess.push_back( init.at( i ) + w*m_list.at( i ).AbsUpperError() );
}
}
return MakeMinos( nllfunction
, varfunction
, init.data()
, confidencelevel
, upperguess.data()
, lowerguess.data() );
}
/**
* @brief given a list of measurements with uncertainties, return the effective
* sum of all measurements as if all measurements are uncorrelated.
*
* This function also allows the user to define the working confidence level
* for the calculations and also the approximate @NLL function used for the
* individual measurements (by default using the LinearVarianceNLL() function).
*/
Measurement
SumUncorrelated(
const vector<Measurement>& m_list,
const double confidencelevel,
double (* nll )( double, const Measurement& ) )
{
const unsigned dim = m_list.size();
auto Sum = [dim]( const double* x ){
double ans = 0;
for( unsigned i = 0; i < dim; ++i ){
ans += x[i];
}
return ans;
};
return EvaluateUncorrelated( m_list
, ROOT::Math::Functor( Sum, dim )
, confidencelevel
, nll );
}
/**
* @brief given a list of measurements with uncertainties, return the effective
* sum of all measurements as if all measurements are uncorrelated.
*
* This function also allows the user to define the working confidence level
* for the calculations and also the approximate @NLL function used for the
* individual measurements (by default using the LinearVarianceNLL() function).
*/
Measurement
ProdUncorrelated(
const std::vector<Measurement>& m_list,
const double confidencelevel,
double (* nll )( double, const Measurement& ) )
{
const unsigned dim = m_list.size();
auto Prod = [dim]( const double* x ){
double ans = 1;
for( unsigned i = 0; i < dim; ++i ){
ans *= x[i];
}
return ans;
};
double prod = 1.;
vector<Measurement> normlist;
for( const auto& p : m_list ){
prod *= p.CentralValue();
normlist.push_back( p.NormParam() );
}
return prod*EvaluateUncorrelated( normlist
, ROOT::Math::Functor( Prod, dim )
, confidencelevel
, nll );
}
/**
* @brief Give a function of parameters, calculate the error propagation given a
* various a list of symmetric error functions using a lazy method. Assuming all
* parameters are uncorrelated
*
*
* For a function given as:
* \f[
* y = f(x_1 , x_2, x_3,\ldots )
* \f]
*
* With a set of measurements \f$\hat{x}_i{}^{+\sigma^{+}_i}_{-\sigma^{-}_i}\f$,
* The resulting measurement \f$\hat{y}^{+\sigma^{+}_y}_{-\sigma^{-}_y}\f$ is
* evaluted as:
*
* \f[
* \hat{y} = f(\hat{x}_1, \hat{x}_2, \hat{x}_3\ldots)
* \f]
*
* and:
*
* \f[
* y\pm\sigma^{\pm}_{y} = f(\hat{x}_i + \Delta x_i)
* \f]
*
* with
*
* \f[
* \Delta x_i = \frac{ |\partial_i f| }{\sqrt{\sum_i (\partial_i f)^2}}
* \sigma^{k_i}_{i}
* \f]
*
* where \f$k_i = +\f$ if \f$\partial_i f\f$ is positive or else \f$k_i = - \f$
* otherwise.
*
**/
Measurement
LazyEvaluateUncorrelated(
const std::vector<Measurement>& paramlist,
const ROOT::Math::IMultiGenFunction& varfunction )
{
std::vector<double> center;
std::vector<double> upper;
std::vector<double> lower;
double diff_sqsum = 0;
for( const auto& p : paramlist ){
center.push_back( p.CentralValue() );
}
for( unsigned i = 0; i < paramlist.size(); ++i ){
const double diff = ROOT::Math::Derivator::Eval( varfunction
, center.data(), i );
diff_sqsum += diff *diff;
}
diff_sqsum = std::sqrt( diff_sqsum );
for( unsigned i = 0; i < paramlist.size(); ++i ){
const double diff = ROOT::Math::Derivator::Eval( varfunction
, center.data(), i );
const double w = fabs( diff/diff_sqsum );
const auto& p = paramlist.at( i );
if( diff > 0 ){
upper.push_back( p.CentralValue() + w*p.AbsUpperError() );
lower.push_back( p.CentralValue() - w*p.AbsLowerError() );
} else {
upper.push_back( p.CentralValue() - w*p.AbsLowerError() );
lower.push_back( p.CentralValue() + w*p.AbsUpperError() );
}
}
const double cen = varfunction( center.data() );
const double up = varfunction( upper.data() );
const double lo = varfunction( lower.data() );
return Measurement( cen, up-cen, cen-lo );
}
}/* usr */
| 33.391667 | 81 | 0.602945 | yimuchen |
b9a4daf27f425972ca64b0bd2037ef91724c769b | 4,255 | hpp | C++ | include/atl/detail/finite_automaton/copy.hpp | LoringHe/fml | fe4e5341b0f07ffd4d04207b3039cf4157ef3cba | [
"MIT"
] | 2 | 2020-09-02T05:04:52.000Z | 2020-09-04T05:26:33.000Z | include/atl/detail/finite_automaton/copy.hpp | Jinlong-He/fml | fe4e5341b0f07ffd4d04207b3039cf4157ef3cba | [
"MIT"
] | null | null | null | include/atl/detail/finite_automaton/copy.hpp | Jinlong-He/fml | fe4e5341b0f07ffd4d04207b3039cf4157ef3cba | [
"MIT"
] | null | null | null | //
// copy.hpp
// atl
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2020 Jinlong He.
//
#ifndef atl_detail_finite_automaton_copy_hpp
#define atl_detail_finite_automaton_copy_hpp
#include <atl/detail/finite_automaton/finite_automaton.hpp>
#include <atl/detail/finite_automaton/closure.hpp>
namespace atl::detail {
struct copy_fa_impl {
template <FA_PARAMS>
static void
copy_states(const FA& a_in,
FA& a_out,
typename FA::State2Map& state2_map,
typename FA::StateSet const& state_set) {
typedef typename FA::state_property_type StateProperty;
typedef typename FA::State State;
typename FA::StateIter s_it, s_end;
State state_copy = -1;
if (state_set.size() > 0) {
for (auto state : state_set) {
if constexpr (std::is_same<StateProperty, boost::no_property>::value) {
state_copy = add_state(a_out);
} else {
state_copy = add_state(a_out, atl::get_property(a_in, state));
}
state2_map[state] = state_copy;
}
} else {
for (tie(s_it, s_end) = states(a_in); s_it != s_end; s_it++) {
auto state = *s_it;
if constexpr (std::is_same<StateProperty, boost::no_property>::value) {
state_copy = add_state(a_out);
} else {
state_copy = add_state(a_out, atl::get_property(a_in, state));
}
state2_map[state] = state_copy;
}
}
set_initial_state(a_out, state2_map.at(initial_state(a_in)));
for (auto state : final_state_set(a_in)) {
if (state2_map.count(state) > 0) {
set_final_state(a_out, state2_map.at(state));
}
}
}
template <FA_PARAMS>
static void
copy_transitions(const FA& a_in,
FA& a_out,
typename FA::State2Map const& state2_map) {
typename FA::OutTransitionIter t_it, t_end;
for (const auto& [state, source] : state2_map) {
for (tie(t_it, t_end) = out_transitions(a_in, state); t_it != t_end; t_it++) {
auto target = atl::target(a_in, *t_it);
if (state2_map.count(target) > 0) {
auto new_target = state2_map.at(target);
const auto& t = atl::get_property(a_in, *t_it);
add_transition(a_out, source, new_target, t);
}
}
}
}
template <FA_PARAMS>
static void
apply(const FA& a_in,
FA& a_out,
typename FA::State2Map& state2_map,
typename FA::StateSet const& states) {
typedef typename FA::automaton_property_type AutomatonProperty;
atl::clear(a_out);
if (is_empty(a_in)) return;
set_alphabet(a_out, alphabet(a_in));
if constexpr (!std::is_same<AutomatonProperty, boost::no_property>::value) {
atl::set_property(a_out, atl::get_property(a_in));
}
copy_states(a_in, a_out, state2_map, states);
copy_transitions(a_in, a_out, state2_map);
}
};
};
namespace atl {
template <FA_PARAMS>
inline void
copy_fa(const FA& a_in,
FA& a_out,
typename FA::State2Map& state2_map,
typename FA::StateSet const& states = typename FA::StateSet()) {
detail::copy_fa_impl::apply(a_in, a_out, state2_map, states);
}
template <FA_PARAMS>
inline void
copy_fa(const FA& a_in,
FA& a_out,
typename FA::StateSet const& states = typename FA::StateSet()) {
typename FA::State2Map state2_map;
detail::copy_fa_impl::apply(a_in, a_out, state2_map, states);
}
}
#endif /* atl_detail_finite_automaton_copy_hpp */
| 37.324561 | 94 | 0.5349 | LoringHe |
b9a5a0b27723eef5f93f494716089a20e1cd3a50 | 2,107 | cpp | C++ | rmw_coredx_cpp/src/rmw_destroy_wait_set.cpp | rupertholman/rmw_coredx | 1c97655212bfa90b1353f019ae08e8b2c487db8d | [
"Apache-2.0"
] | null | null | null | rmw_coredx_cpp/src/rmw_destroy_wait_set.cpp | rupertholman/rmw_coredx | 1c97655212bfa90b1353f019ae08e8b2c487db8d | [
"Apache-2.0"
] | null | null | null | rmw_coredx_cpp/src/rmw_destroy_wait_set.cpp | rupertholman/rmw_coredx | 1c97655212bfa90b1353f019ae08e8b2c487db8d | [
"Apache-2.0"
] | null | null | null | // Copyright 2015 Twin Oaks Computing, Inc.
// Modifications copyright (C) 2017-2018 Twin Oaks Computing, 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.
#ifdef CoreDX_GLIBCXX_USE_CXX11_ABI_ZERO
#define _GLIBCXX_USE_CXX11_ABI 0
#endif
#include <rmw/rmw.h>
#include <rmw/types.h>
#include <rmw/allocators.h>
#include <rmw/error_handling.h>
#include <rmw/impl/cpp/macros.hpp>
#include <rcutils/logging_macros.h>
#include <dds/dds.hh>
#include <dds/dds_builtinDataReader.hh>
#include "rmw_coredx_cpp/identifier.hpp"
#include "rmw_coredx_types.hpp"
#include "util.hpp"
#if defined(__cplusplus)
extern "C" {
#endif
/* ************************************************
*/
rmw_ret_t
rmw_destroy_wait_set(rmw_wait_set_t * waitset)
{
RCUTILS_LOG_DEBUG_NAMED(
"rmw_coredx_cpp",
"%s[ waitset: %p ]",
__FUNCTION__,
waitset );
if (!waitset) {
RMW_SET_ERROR_MSG("waitset handle is null");
return RMW_RET_ERROR;
}
auto result = RMW_RET_OK;
CoreDXWaitSetInfo * waitset_info = static_cast<CoreDXWaitSetInfo *>(waitset->data);
// Explicitly call destructor since the "placement new" was used
waitset_info->active_conditions.clear();
waitset_info->attached_conditions.clear();
if (waitset_info->wait_set) {
RMW_TRY_DESTRUCTOR(waitset_info->wait_set->~WaitSet(), WaitSet, result = RMW_RET_ERROR)
rmw_free(waitset_info->wait_set);
}
waitset_info = nullptr;
if (waitset->data) {
rmw_free(waitset->data);
waitset->data = nullptr;
}
if (waitset) {
rmw_wait_set_free(waitset);
}
return result;
}
#if defined(__cplusplus)
}
#endif
| 26.670886 | 91 | 0.714286 | rupertholman |
b9a67fb63c8d5d0fc0e03819a0e3d12ad282ee37 | 3,690 | cpp | C++ | tests/ablateLibrary/mathFunctions/functionPointerTests.cpp | mtmcgurn-buffalo/ablate | 35ee9a30277908775a61d78462ea9724ee631a9b | [
"BSD-3-Clause"
] | 3 | 2021-01-19T21:29:10.000Z | 2021-08-20T19:54:49.000Z | tests/ablateLibrary/mathFunctions/functionPointerTests.cpp | mtmcgurn-buffalo/ablate | 35ee9a30277908775a61d78462ea9724ee631a9b | [
"BSD-3-Clause"
] | 124 | 2021-01-14T15:30:48.000Z | 2022-03-28T14:44:31.000Z | tests/ablateLibrary/mathFunctions/functionPointerTests.cpp | mtmcgurn-buffalo/ablate | 35ee9a30277908775a61d78462ea9724ee631a9b | [
"BSD-3-Clause"
] | 17 | 2021-02-10T22:34:57.000Z | 2022-03-21T18:46:06.000Z | #include <memory>
#include "gtest/gtest.h"
#include "mathFunctions/functionPointer.hpp"
namespace ablateTesting::mathFunctions {
TEST(FunctionPointerTests, ShouldEvalToScalarFromXYZ) {
// arrange
auto function = ablate::mathFunctions::FunctionPointer([](auto dim, auto time, auto loc, auto nf, auto u, auto ctx) {
u[0] = loc[0] + loc[1] + loc[2] + time;
return 0;
});
// act/assert
ASSERT_DOUBLE_EQ(10.0, function.Eval(1.0, 2.0, 3.0, 4.0));
ASSERT_DOUBLE_EQ(18.0, function.Eval(9.0, 2.0, 3.0, 4.0));
ASSERT_DOUBLE_EQ(0.0, function.Eval(5.0, 2.0, 3.0, -10.0));
}
TEST(FunctionPointerTests, ShouldEvalToScalarFromCoord) {
// arrange
auto function = ablate::mathFunctions::FunctionPointer([](auto dim, auto time, auto loc, auto nf, auto u, auto ctx) {
switch (dim) {
case 3:
u[0] = loc[0] + loc[1] + loc[2] + time;
break;
case 2:
u[0] = loc[0] + loc[1] + time;
break;
}
return 0;
});
// act/assert
const double array1[3] = {1.0, 2.0, 3.0};
ASSERT_DOUBLE_EQ(10.0, function.Eval(array1, 3, 4.0));
const double array2[2] = {1.0, 2.0};
ASSERT_DOUBLE_EQ(7.0, function.Eval(array2, 2, 4.0));
const double array3[3] = {5, 5, -5};
ASSERT_DOUBLE_EQ(0.0, function.Eval(array3, 3, -5));
}
TEST(FunctionPointerTests, ShouldEvalToVectorFromXYZ) {
// arrange
auto function = ablate::mathFunctions::FunctionPointer([](auto dim, auto time, auto loc, auto nf, auto u, auto ctx) {
if (dim == 3 && nf >= 3) {
u[0] = loc[0] + loc[1] + loc[2] + time;
u[1] = loc[0] * loc[1] * loc[2];
u[2] = time;
}
return 0;
});
// act/assert
std::vector<double> result1 = {0, 0, 0};
function.Eval(1.0, 2.0, 3.0, 4.0, result1);
ASSERT_DOUBLE_EQ(result1[0], 10.0);
ASSERT_DOUBLE_EQ(result1[1], 6.0);
ASSERT_DOUBLE_EQ(result1[2], 4.0);
std::vector<double> result2 = {0, 0, 0, 4};
function.Eval(2.0, 2.0, 3.0, 4.0, result2);
ASSERT_DOUBLE_EQ(result2[0], 11.0);
ASSERT_DOUBLE_EQ(result2[1], 12.0);
ASSERT_DOUBLE_EQ(result2[2], 4.0);
ASSERT_DOUBLE_EQ(result2[3], 4.0);
}
TEST(FunctionPointerTests, ShouldEvalToVectorFromCoord) {
// arrange
auto function = ablate::mathFunctions::FunctionPointer([](auto dim, auto time, auto loc, auto nf, auto u, auto ctx) {
if (dim == 3 && nf >= 3) {
u[0] = loc[0] + loc[1] + loc[2] + time;
u[1] = loc[0] * loc[1] * loc[2];
u[2] = time;
}
return 0;
});
// act/assert
const double array1[3] = {1.0, 2.0, 3.0};
std::vector<double> result1 = {0, 0, 0};
function.Eval(array1, 3, 4.0, result1);
ASSERT_DOUBLE_EQ(result1[0], 10.0);
ASSERT_DOUBLE_EQ(result1[1], 6.0);
ASSERT_DOUBLE_EQ(result1[2], 4.0);
}
TEST(FunctionPointerTests, ShouldProvideAndFunctionWithPetscFunctionWhenSimpleFunction) {
// arrange
auto function = ablate::mathFunctions::FunctionPointer([](auto dim, auto time, auto loc, auto nf, auto u, auto ctx) {
u[0] = loc[0] + loc[1] + loc[2] + time;
u[1] = loc[0] * loc[1] * loc[2];
return 0;
});
auto context = function.GetContext();
auto functionPointer = function.GetPetscFunction();
const PetscReal x[3] = {1.0, 2.0, 3.0};
PetscScalar result[2] = {0.0, 0.0};
// act
auto errorCode = functionPointer(3, 4.0, x, 2, result, context);
// assert
ASSERT_EQ(0, errorCode);
ASSERT_DOUBLE_EQ(10.0, result[0]);
ASSERT_DOUBLE_EQ(6.0, result[1]);
}
} // namespace ablateTesting::mathFunctions | 32.654867 | 121 | 0.582927 | mtmcgurn-buffalo |
b9abec4116c2ceaf0b8a1cff7580494bae07df7e | 2,443 | hpp | C++ | include/vcrate/bytecode/Operations.hpp | VCrate/bytecode-description | c46f61fda817301b6705bc16654c634dc2c3212d | [
"MIT"
] | 1 | 2018-04-14T14:04:39.000Z | 2018-04-14T14:04:39.000Z | include/vcrate/bytecode/Operations.hpp | VCrate/bytecode-description | c46f61fda817301b6705bc16654c634dc2c3212d | [
"MIT"
] | null | null | null | include/vcrate/bytecode/Operations.hpp | VCrate/bytecode-description | c46f61fda817301b6705bc16654c634dc2c3212d | [
"MIT"
] | null | null | null | #pragma once
#include <vcrate/Alias.hpp>
#include <vector>
#include <string>
namespace vcrate { namespace bytecode {
enum class Operations : ui8 {
ADD, // Add (RRW)
SUB, // Subtract (RRW)
MOD, // Modulo (RRW)
MUL, // Multiply (RRW)
MULU, // Multiply unsigned (RRW)
DIV, // Divide (RRW)
DIVU, // Divide unsigned (RRW)
MOV, // Move (RW)
LEA, // Load effective address
POP, // Pop from stack (W)
PUSH, // Push to stack (R)
JMP, // Jump to (R)
JMPE, // Jump to _ if zero flag (R)
JMPNE, // Jump to _ if !zero flag (R)
JMPG, // Jump to _ if greater flag (R)
JMPGE, // Jump to _ if greater and zero flag (R)
AND, // And (RRW)
OR, // Or (RRW)
XOR, // Xor (RRW)
NOT, // Not (RW)
SHL, // Shift left (RRW)
RTL, // Rotate left (RRW)
SHR, // Shift right (RRW)
RTR, // Rotate right (RRW)
SWP, // Swap (WW)
CMP, // set zero/greater flags
CMPU, // Comapre unsigned
INC, // Increment (RW)
DEC, // Decrement (RW)
NEW, // New (RW)
DEL, // Delete (R)
CALL, // Call (R)
RET, // Return
ETR, // Enter
LVE, // Leave
HLT, // Halt the program
OUT, // Print 8 lower bits as char (R)
DBG, // Print integer (R)
ITU, // int to unsigned (RW)
ITF, // int to float (RW)
UTI, // unsigned to int (RW)
UTF, // unsigned to float (RW)
FTI, // float to int (RW)
FTU, // float to unsigned (RW)
ADDF, // Add float (RRW)
SUBF, // Subtract float (RRW)
MODF, // Modulo float (RRW)
MULF, // Multiply float (RRW)
DIVF, // Divide float (RRW)
INCF, // Increment float (RW)
DECF, // Decrement float (RW)
DBGF, // Print float (R)
DBGU, // Print unsigned (R)
};
struct ArgConstraint {
static constexpr ui8 Readable = 0x01;
static constexpr ui8 Writable = 0x02;
static constexpr ui8 Adressable = 0x04;
};
class OpDefinition {
public:
OpDefinition(std::string const& name, Operations ope, std::vector<ui8> const& args_constraints = {});
std::string name;
Operations ope;
std::vector<ui8> args_constraints;
ui32 arg_count() const;
ui8 value() const;
bool should_be_writable(ui32 arg) const;
bool should_be_addressable(ui32 arg) const;
bool should_be_readable(ui32 arg) const;
static const OpDefinition& get(Operations ope);
static const OpDefinition& get(std::string ope);
};
}} | 24.43 | 105 | 0.583299 | VCrate |
b9ac5d1dbe0d12ca27aad1c32e0e0b52d4c5c00a | 74,278 | cpp | C++ | core/indigo-core/molecule/src/cml_loader.cpp | khyurri/Indigo | 82f9ef9f43ca605f7265709e7a9256f1ff468d6c | [
"Apache-2.0"
] | null | null | null | core/indigo-core/molecule/src/cml_loader.cpp | khyurri/Indigo | 82f9ef9f43ca605f7265709e7a9256f1ff468d6c | [
"Apache-2.0"
] | null | null | null | core/indigo-core/molecule/src/cml_loader.cpp | khyurri/Indigo | 82f9ef9f43ca605f7265709e7a9256f1ff468d6c | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
* Copyright (C) from 2009 to Present EPAM Systems.
*
* This file is part of Indigo toolkit.
*
* 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 "molecule/cml_loader.h"
#include "base_cpp/scanner.h"
#include "molecule/elements.h"
#include "molecule/molecule.h"
#include "molecule/molecule_scaffold_detection.h"
#include "tinyxml.h"
using namespace indigo;
static float readFloat(const char* point_str)
{
float res = 0;
if (point_str != 0)
{
BufferScanner strscan(point_str);
res = strscan.readFloat();
}
return res;
}
IMPL_ERROR(CmlLoader, "CML loader");
CmlLoader::CmlLoader(Scanner& scanner)
{
_scanner = &scanner;
_handle = 0;
}
CmlLoader::CmlLoader(TiXmlHandle& handle)
{
_handle = &handle;
_scanner = 0;
}
void CmlLoader::loadMolecule(Molecule& mol)
{
mol.clear();
_bmol = &mol;
_mol = &mol;
_qmol = 0;
_loadMolecule();
mol.setIgnoreBadValenceFlag(ignore_bad_valence);
}
void CmlLoader::loadQueryMolecule(QueryMolecule& mol)
{
mol.clear();
_bmol = &mol;
_mol = 0;
_qmol = &mol;
_loadMolecule();
}
void CmlLoader::_loadMolecule()
{
if (_scanner != 0)
{
QS_DEF(Array<char>, buf);
_scanner->readAll(buf);
buf.push(0);
TiXmlDocument xml;
xml.Parse(buf.ptr());
if (xml.Error())
throw Error("XML parsing error: %s", xml.ErrorDesc());
TiXmlHandle hxml(&xml);
TiXmlNode* node;
if (_findMolecule(hxml.ToNode()))
{
node = _molecule;
TiXmlHandle molecule = _molecule;
_loadMoleculeElement(molecule);
for (node = node->NextSibling(); node != 0; node = node->NextSibling())
{
if (strncmp(node->Value(), "Rgroup", 6) == 0)
{
TiXmlHandle rgroup = node;
_loadRgroupElement(rgroup);
}
}
}
}
else
_loadMoleculeElement(*_handle);
}
bool CmlLoader::_findMolecule(TiXmlNode* elem)
{
TiXmlNode* node;
for (node = elem->FirstChild(); node != 0; node = node->NextSibling())
{
if (strncmp(node->Value(), "molecule", 8) == 0)
{
_molecule = node;
return true;
}
if (_findMolecule(node))
return true;
}
return false;
}
// Atoms
struct Atom
{
std::string id, element_type, label, alias, isotope, formal_charge, spin_multiplicity, radical, valence, rgroupref, attpoint, attorder, query_props,
hydrogen_count, atom_mapping, atom_inversion, atom_exact_change, x, y, z;
};
// This methods splits a space-separated string and writes each values into an arbitrary string
// property of Atom structure for each atom in the specified list
static void splitStringIntoProperties(const char* s, std::vector<Atom>& atoms, std::string Atom::*property)
{
if (s == 0)
return;
std::stringstream stream(s);
size_t i = 0;
std::string token;
while (stream >> token)
{
if (atoms.size() <= i)
atoms.resize(i + 1);
atoms[i].*property = token;
i++;
}
}
void CmlLoader::_loadMoleculeElement(TiXmlHandle& handle)
{
std::unordered_map<std::string, int> atoms_id;
std::unordered_map<std::string, size_t> atoms_id_int;
// Function that mappes atom id as a string to an atom index
auto getAtomIdx = [&](const char* id) {
auto it = atoms_id.find(id);
if (it == atoms_id.end())
throw Error("atom id %s cannot be found", id);
return it->second;
};
QS_DEF(Array<int>, total_h_count);
QS_DEF(Array<int>, query_h_count);
atoms_id.clear();
atoms_id_int.clear();
total_h_count.clear();
query_h_count.clear();
const char* title = handle.Element()->Attribute("title");
if (title != 0)
_bmol->name.readString(title, true);
QS_DEF(std::vector<Atom>, atoms);
atoms.clear();
//
// Read elements into an atoms array first and the parse them
//
TiXmlHandle atom_array = handle.FirstChild("atomArray");
// Read atoms as xml attributes
// <atomArray
// atomID="a1 a2 a3 ... "
// elementType="O C O ..."
// hydrogenCount="1 0 0 ..."
// />
splitStringIntoProperties(atom_array.Element()->Attribute("atomID"), atoms, &Atom::id);
// Fill id if any were found
size_t atom_index;
for (atom_index = 0; atom_index < atoms.size(); atom_index++)
atoms_id_int.emplace(atoms[atom_index].id, atom_index);
splitStringIntoProperties(atom_array.Element()->Attribute("elementType"), atoms, &Atom::element_type);
splitStringIntoProperties(atom_array.Element()->Attribute("mrvPseudo"), atoms, &Atom::label);
splitStringIntoProperties(atom_array.Element()->Attribute("hydrogenCount"), atoms, &Atom::hydrogen_count);
splitStringIntoProperties(atom_array.Element()->Attribute("isotope"), atoms, &Atom::isotope);
splitStringIntoProperties(atom_array.Element()->Attribute("isotopeNumber"), atoms, &Atom::isotope);
splitStringIntoProperties(atom_array.Element()->Attribute("formalCharge"), atoms, &Atom::formal_charge);
splitStringIntoProperties(atom_array.Element()->Attribute("spinMultiplicity"), atoms, &Atom::spin_multiplicity);
splitStringIntoProperties(atom_array.Element()->Attribute("radical"), atoms, &Atom::radical);
splitStringIntoProperties(atom_array.Element()->Attribute("mrvValence"), atoms, &Atom::valence);
splitStringIntoProperties(atom_array.Element()->Attribute("rgroupRef"), atoms, &Atom::rgroupref);
splitStringIntoProperties(atom_array.Element()->Attribute("attachmentPoint"), atoms, &Atom::attpoint);
splitStringIntoProperties(atom_array.Element()->Attribute("attachmentOrder"), atoms, &Atom::attorder);
splitStringIntoProperties(atom_array.Element()->Attribute("mrvQueryProps"), atoms, &Atom::query_props);
splitStringIntoProperties(atom_array.Element()->Attribute("mrvAlias"), atoms, &Atom::alias);
splitStringIntoProperties(atom_array.Element()->Attribute("mrvMap"), atoms, &Atom::atom_mapping);
splitStringIntoProperties(atom_array.Element()->Attribute("reactionStereo"), atoms, &Atom::atom_inversion);
splitStringIntoProperties(atom_array.Element()->Attribute("exactChage"), atoms, &Atom::atom_exact_change);
splitStringIntoProperties(atom_array.Element()->Attribute("x2"), atoms, &Atom::x);
splitStringIntoProperties(atom_array.Element()->Attribute("y2"), atoms, &Atom::y);
splitStringIntoProperties(atom_array.Element()->Attribute("x3"), atoms, &Atom::x);
splitStringIntoProperties(atom_array.Element()->Attribute("y3"), atoms, &Atom::y);
splitStringIntoProperties(atom_array.Element()->Attribute("z3"), atoms, &Atom::z);
// Read atoms as nested xml elements
// <atomArray>
// <atom id="a1" elementType="H" />
for (TiXmlElement* elem = atom_array.FirstChild().Element(); elem; elem = elem->NextSiblingElement())
{
if (strncmp(elem->Value(), "atom", 4) != 0)
continue;
const char* id = elem->Attribute("id");
if (id == 0)
throw Error("atom without an id");
// Check if this atom has already been parsed
auto it = atoms_id_int.find(id);
if (it != end(atoms_id_int))
atom_index = it->second;
else
{
atom_index = atoms.size();
atoms.emplace_back();
atoms_id_int.emplace(id, atom_index);
}
Atom& a = atoms[atom_index];
a.id = id;
const char* element_type = elem->Attribute("elementType");
if (element_type == 0)
throw Error("atom without an elementType");
a.element_type = element_type;
const char* pseudo = elem->Attribute("mrvPseudo");
if (pseudo != 0)
a.label = pseudo;
const char* alias = elem->Attribute("mrvAlias");
if (alias != 0)
a.alias = alias;
const char* isotope = elem->Attribute("isotope");
if (isotope == 0)
isotope = elem->Attribute("isotopeNumber");
if (isotope != 0)
a.isotope = isotope;
const char* charge = elem->Attribute("formalCharge");
if (charge != 0)
a.formal_charge = charge;
const char* spinmultiplicity = elem->Attribute("spinMultiplicity");
if (spinmultiplicity != 0)
a.spin_multiplicity = spinmultiplicity;
const char* radical = elem->Attribute("radical");
if (radical != 0)
a.radical = radical;
const char* valence = elem->Attribute("mrvValence");
if (valence != 0)
a.valence = valence;
const char* hcount = elem->Attribute("hydrogenCount");
if (hcount != 0)
a.hydrogen_count = hcount;
const char* atom_map = elem->Attribute("mrvMap");
if (atom_map != 0)
a.atom_mapping = atom_map;
const char* atom_inv = elem->Attribute("reactionStereo");
if (atom_inv != 0)
a.atom_inversion = atom_inv;
const char* atom_exact = elem->Attribute("exactChange");
if (atom_exact != 0)
a.atom_exact_change = atom_exact;
/*
* Read coordinates
*/
const char* x2 = elem->Attribute("x2");
const char* y2 = elem->Attribute("y2");
if (x2 != 0 && y2 != 0)
{
a.x = x2;
a.y = y2;
}
else
{
const char* x3 = elem->Attribute("x3");
const char* y3 = elem->Attribute("y3");
const char* z3 = elem->Attribute("z3");
if (x3 != 0 && y3 != 0 && z3 != 0)
{
a.x = x3;
a.y = y3;
a.z = z3;
}
}
const char* rgroupref = elem->Attribute("rgroupRef");
if (rgroupref != 0)
a.rgroupref = rgroupref;
const char* attpoint = elem->Attribute("attachmentPoint");
if (attpoint != 0)
a.attpoint = attpoint;
const char* attorder = elem->Attribute("attachmentOrder");
if (attorder != 0)
a.attorder = attorder;
const char* query_props = elem->Attribute("mrvQueryProps");
if (query_props != 0)
{
if (_qmol != 0)
a.query_props = query_props;
else
throw Error("'query features' are allowed only for queries");
}
}
// Parse them
for (auto& a : atoms)
{
int label = Element::fromString2(a.element_type.c_str());
if ((label == -1) && (strncmp(a.element_type.c_str(), "R", 1) == 0))
label = ELEM_RSITE;
else if ((label == -1) && (strncmp(a.element_type.c_str(), "*", 1) == 0))
label = ELEM_ATTPOINT;
else if (!a.label.empty())
{
if (label == -1)
label = ELEM_PSEUDO;
else if (label == ELEM_C)
{
if ((strncmp(a.label.c_str(), "AH", 2) == 0) || (strncmp(a.label.c_str(), "QH", 2) == 0) || (strncmp(a.label.c_str(), "XH", 2) == 0) ||
(strncmp(a.label.c_str(), "MH", 2) == 0) || (strncmp(a.label.c_str(), "X", 1) == 0) || (strncmp(a.label.c_str(), "M", 1) == 0))
{
}
else
label = ELEM_PSEUDO;
}
}
else if (label == -1)
label = ELEM_PSEUDO;
int idx;
if (label == ELEM_ATTPOINT)
{
atoms_id.emplace(a.id, -1);
}
else
{
if (_mol != 0)
{
idx = _mol->addAtom(label);
if (label == ELEM_PSEUDO)
{
if (!a.label.empty())
_mol->setPseudoAtom(idx, a.label.c_str());
else
_mol->setPseudoAtom(idx, a.element_type.c_str());
}
total_h_count.expandFill(idx + 1, -1);
query_h_count.expandFill(idx + 1, -1);
atoms_id.emplace(a.id, idx);
if (!a.isotope.empty())
{
int val;
if (sscanf(a.isotope.c_str(), "%d", &val) != 1)
throw Error("error parsing isotope");
_mol->setAtomIsotope(idx, val);
}
if (!a.formal_charge.empty())
{
int val;
if (sscanf(a.formal_charge.c_str(), "%d", &val) != 1)
throw Error("error parsing charge");
_mol->setAtomCharge(idx, val);
}
if (!a.spin_multiplicity.empty())
{
int val;
if (sscanf(a.spin_multiplicity.c_str(), "%d", &val) != 1)
throw Error("error parsing spin multiplicity");
_mol->setAtomRadical(idx, val);
}
if (!a.radical.empty())
{
int val = 0;
if (strncmp(a.radical.c_str(), "divalent1", 9) == 0)
val = 1;
else if (strncmp(a.radical.c_str(), "monovalent", 10) == 0)
val = 2;
else if ((strncmp(a.radical.c_str(), "divalent3", 9) == 0) || (strncmp(a.radical.c_str(), "divalent", 8) == 0) ||
(strncmp(a.radical.c_str(), "triplet", 7) == 0))
val = 3;
_mol->setAtomRadical(idx, val);
}
if (a.spin_multiplicity.empty() && a.radical.empty())
{
_mol->setAtomRadical(idx, 0);
}
if (!a.valence.empty())
{
int val;
if (sscanf(a.valence.c_str(), "%d", &val) == 1)
_mol->setExplicitValence(idx, val);
}
if (!a.hydrogen_count.empty())
{
int val;
if (sscanf(a.hydrogen_count.c_str(), "%d", &val) != 1)
throw Error("error parsing hydrogen count");
if (val < 0)
throw Error("negative hydrogen count");
total_h_count[idx] = val;
}
}
else
{
AutoPtr<QueryMolecule::Atom> atom;
int qhcount = -1;
if (label == ELEM_PSEUDO)
{
if (!a.label.empty())
atom.reset(new QueryMolecule::Atom(QueryMolecule::ATOM_PSEUDO, a.label.c_str()));
else
atom.reset(new QueryMolecule::Atom(QueryMolecule::ATOM_PSEUDO, a.element_type.c_str()));
}
else if (label == ELEM_RSITE)
atom.reset(new QueryMolecule::Atom(QueryMolecule::ATOM_RSITE, 0));
else
atom.reset(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, label));
if (!a.query_props.empty() && (strncmp(a.query_props.c_str(), "L", 1) == 0)) // _ATOM_LIST
{
AutoPtr<QueryMolecule::Atom> atomlist;
BufferScanner strscan(a.query_props.c_str());
QS_DEF(Array<char>, el);
QS_DEF(Array<char>, delim);
el.clear();
delim.clear();
strscan.skip(1);
delim.push(strscan.readChar());
delim.push(':');
delim.push(0);
while (!strscan.isEOF())
{
strscan.readWord(el, delim.ptr());
_appendQueryAtom(el.ptr(), atomlist);
if (strscan.readChar() == ':')
break;
}
if (delim[0] == '!')
atomlist.reset(QueryMolecule::Atom::nicht(atomlist.release()));
atom.reset(atomlist.release());
}
else if (!a.query_props.empty() && (strncmp(a.query_props.c_str(), "A", 1) == 0)) // _ATOM_A
{
atom.get()->removeConstraints(QueryMolecule::ATOM_NUMBER);
atom.reset(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_H)));
}
else if (!a.query_props.empty() && (strncmp(a.query_props.c_str(), "Q", 1) == 0)) // _ATOM_Q
{
atom.get()->removeConstraints(QueryMolecule::ATOM_NUMBER);
atom.reset(QueryMolecule::Atom::und(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_H)),
QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_C))));
}
if (label == ELEM_C && !a.label.empty())
{
if (strncmp(a.label.c_str(), "AH", 2) == 0)
{
AutoPtr<QueryMolecule::Atom> x_atom(new QueryMolecule::Atom());
x_atom->type = QueryMolecule::OP_NONE;
atom.get()->removeConstraints(QueryMolecule::ATOM_NUMBER);
atom.reset(x_atom.release());
}
else if (strncmp(a.label.c_str(), "QH", 2) == 0)
{
atom.get()->removeConstraints(QueryMolecule::ATOM_NUMBER);
atom.reset(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_C)));
}
else if (strncmp(a.label.c_str(), "XH", 2) == 0)
{
AutoPtr<QueryMolecule::Atom> x_atom(new QueryMolecule::Atom());
x_atom->type = QueryMolecule::OP_OR;
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_F));
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Cl));
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Br));
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_I));
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_At));
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_H));
atom.get()->removeConstraints(QueryMolecule::ATOM_NUMBER);
atom.reset(x_atom.release());
}
else if (strncmp(a.label.c_str(), "X", 1) == 0)
{
AutoPtr<QueryMolecule::Atom> x_atom(new QueryMolecule::Atom());
x_atom->type = QueryMolecule::OP_OR;
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_F));
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Cl));
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Br));
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_I));
x_atom->children.add(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_At));
atom.get()->removeConstraints(QueryMolecule::ATOM_NUMBER);
atom.reset(x_atom.release());
}
else if (strncmp(a.label.c_str(), "MH", 2) == 0)
{
AutoPtr<QueryMolecule::Atom> x_atom(new QueryMolecule::Atom());
x_atom->type = QueryMolecule::OP_AND;
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_C)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_N)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_O)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_F)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_P)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_S)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Cl)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Se)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Br)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_I)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_At)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_He)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Ne)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Ar)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Kr)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Xe)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Rn)));
atom.get()->removeConstraints(QueryMolecule::ATOM_NUMBER);
atom.reset(x_atom.release());
}
else if (strncmp(a.label.c_str(), "M", 1) == 0)
{
AutoPtr<QueryMolecule::Atom> x_atom(new QueryMolecule::Atom());
x_atom->type = QueryMolecule::OP_AND;
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_C)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_N)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_O)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_F)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_P)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_S)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Cl)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Se)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Br)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_I)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_At)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_He)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Ne)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Ar)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Kr)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Xe)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_Rn)));
x_atom->children.add(QueryMolecule::Atom::nicht(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, ELEM_H)));
atom.get()->removeConstraints(QueryMolecule::ATOM_NUMBER);
atom.reset(x_atom.release());
}
}
else if (!a.query_props.empty()) // Query features
{
BufferScanner strscan(a.query_props.c_str());
QS_DEF(Array<char>, qf);
QS_DEF(Array<char>, delim);
qf.clear();
delim.clear();
delim.push(';');
delim.push(0);
while (!strscan.isEOF())
{
strscan.readWord(qf, delim.ptr());
if (strncmp(qf.ptr(), "rb", 2) == 0)
{
BufferScanner qfscan(qf.ptr());
qfscan.skip(2);
int rbcount;
if (qfscan.lookNext() == '*')
rbcount = -2;
else
rbcount = qfscan.readInt1();
if (rbcount > 0)
atom.reset(QueryMolecule::Atom::und(
atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_RING_BONDS, rbcount, (rbcount < 4 ? rbcount : 100))));
else if (rbcount == 0)
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_RING_BONDS, 0)));
else if (rbcount == -2)
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_RING_BONDS_AS_DRAWN, 0)));
}
else if (strncmp(qf.ptr(), "s", 1) == 0)
{
BufferScanner qfscan(qf.ptr());
qfscan.skip(1);
int subst;
if (qfscan.lookNext() == '*')
{
subst = -2;
}
else
{
subst = qfscan.readInt1();
}
if (subst == 0)
{
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_SUBSTITUENTS, 0)));
}
else if (subst == -2)
{
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_SUBSTITUENTS_AS_DRAWN, 0)));
}
else if (subst > 0)
{
atom.reset(QueryMolecule::Atom::und(
atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_SUBSTITUENTS, subst, (subst < 6 ? subst : 100))));
}
}
else if (strncmp(qf.ptr(), "u", 1) == 0)
{
BufferScanner qfscan(qf.ptr());
qfscan.skip(1);
bool unsat = (qfscan.readInt1() > 0);
if (unsat)
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_UNSATURATION, 0)));
}
else if (strncmp(qf.ptr(), "H", 1) == 0)
{
BufferScanner qfscan(qf.ptr());
qfscan.skip(1);
qhcount = qfscan.readInt1();
/*
if (total_h > 0)
atom.reset(QueryMolecule::Atom::und(atom.release(),
new QueryMolecule::Atom(QueryMolecule::ATOM_TOTAL_H, total_h)));
*/
}
if (!strscan.isEOF())
strscan.skip(1);
}
}
if (!a.formal_charge.empty())
{
int val;
if (sscanf(a.formal_charge.c_str(), "%d", &val) != 1)
throw Error("error parsing charge");
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_CHARGE, val)));
}
if (!a.isotope.empty())
{
int val;
if (sscanf(a.isotope.c_str(), "%d", &val) != 1)
throw Error("error parsing isotope");
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_ISOTOPE, val)));
}
if (!a.spin_multiplicity.empty())
{
int val;
if (sscanf(a.spin_multiplicity.c_str(), "%d", &val) != 1)
throw Error("error parsing spin multiplicity");
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_RADICAL, val)));
}
if (!a.radical.empty())
{
int val = 0;
if (strncmp(a.radical.c_str(), "divalent1", 9) == 0)
val = 1;
else if (strncmp(a.radical.c_str(), "monovalent", 10) == 0)
val = 2;
else if ((strncmp(a.radical.c_str(), "divalent3", 9) == 0) || (strncmp(a.radical.c_str(), "divalent", 8) == 0) ||
(strncmp(a.radical.c_str(), "triplet", 7) == 0))
val = 3;
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_RADICAL, val)));
}
if (!a.valence.empty())
{
int val;
if (sscanf(a.valence.c_str(), "%d", &val) == 1)
atom.reset(QueryMolecule::Atom::und(atom.release(), new QueryMolecule::Atom(QueryMolecule::ATOM_VALENCE, val)));
}
idx = _qmol->addAtom(atom.release());
atoms_id.emplace(a.id, idx);
total_h_count.expandFill(idx + 1, -1);
query_h_count.expandFill(idx + 1, -1);
query_h_count[idx] = qhcount;
}
if (!a.rgroupref.empty())
{
int val;
if (sscanf(a.rgroupref.c_str(), "%d", &val) != 1)
throw Error("error parsing R-group reference");
_bmol->allowRGroupOnRSite(idx, val);
}
if (!a.attpoint.empty())
{
int val;
if (strncmp(a.attpoint.c_str(), "both", 4) == 0)
val = 3;
else if (sscanf(a.attpoint.c_str(), "%d", &val) != 1)
throw Error("error parsing Attachment point");
for (int att_idx = 0; (1 << att_idx) <= val; att_idx++)
if (val & (1 << att_idx))
_bmol->addAttachmentPoint(att_idx + 1, idx);
}
Vec3f a_pos;
if (!a.x.empty())
{
a_pos.x = readFloat(a.x.c_str());
}
if (!a.y.empty())
{
a_pos.y = readFloat(a.y.c_str());
}
if (!a.z.empty())
{
a_pos.z = readFloat(a.z.c_str());
}
_bmol->setAtomXyz(idx, a_pos);
if (!a.alias.empty())
{
if (strncmp(a.alias.c_str(), "0", 1) != 0)
{
int sg_idx = _bmol->sgroups.addSGroup(SGroup::SG_TYPE_DAT);
DataSGroup& sgroup = (DataSGroup&)_bmol->sgroups.getSGroup(sg_idx);
sgroup.atoms.push(idx);
sgroup.name.readString("INDIGO_ALIAS", true);
sgroup.data.readString(a.alias.c_str(), true);
sgroup.display_pos.x = _bmol->getAtomXyz(idx).x;
sgroup.display_pos.y = _bmol->getAtomXyz(idx).y;
}
}
if (!a.atom_mapping.empty())
{
int val;
if (sscanf(a.atom_mapping.c_str(), "%d", &val) != 1)
throw Error("error parsing atom-atom mapping");
_bmol->reaction_atom_mapping[idx] = val;
}
if (!a.atom_inversion.empty())
{
if (strncmp(a.atom_inversion.c_str(), "Inv", 3) == 0)
_bmol->reaction_atom_inversion[idx] = 1;
else if (strncmp(a.atom_inversion.c_str(), "Ret", 3) == 0)
_bmol->reaction_atom_inversion[idx] = 2;
}
if (!a.atom_exact_change.empty())
{
int val;
if (sscanf(a.atom_exact_change.c_str(), "%d", &val) != 1)
throw Error("error parsing atom exact change flag");
_bmol->reaction_atom_exact_change[idx] = val;
}
}
/*
if (!a.attorder.empty())
{
int val;
if (sscanf(a.attorder.c_str(), "%d", &val) != 1)
throw Error("error parsing Attachment order");
mol.setRSiteAttachmentOrder(idx, nei_idx - 1, val - 1);
}
*/
}
// Bonds
bool have_cistrans_notation = false;
for (TiXmlElement* elem = handle.FirstChild("bondArray").FirstChild().Element(); elem; elem = elem->NextSiblingElement())
{
if (strncmp(elem->Value(), "bond", 4) != 0)
continue;
const char* atom_refs = elem->Attribute("atomRefs2");
if (atom_refs == 0)
throw Error("bond without atomRefs2");
int idx;
BufferScanner strscan(atom_refs);
QS_DEF(Array<char>, id);
strscan.readWord(id, 0);
int beg = getAtomIdx(id.ptr());
strscan.skipSpace();
strscan.readWord(id, 0);
int end = getAtomIdx(id.ptr());
if ((beg < 0) || (end < 0))
continue;
const char* order = elem->Attribute("order");
if (order == 0)
throw Error("bond without an order");
int order_val;
{
if (order[0] == 'A' && order[1] == 0)
order_val = BOND_AROMATIC;
else if (order[0] == 'S' && order[1] == 0)
order_val = BOND_SINGLE;
else if (order[0] == 'D' && order[1] == 0)
order_val = BOND_DOUBLE;
else if (order[0] == 'T' && order[1] == 0)
order_val = BOND_TRIPLE;
else if (sscanf(order, "%d", &order_val) != 1)
throw Error("error parsing order");
}
const char* query_type = elem->Attribute("queryType");
const char* topology = elem->Attribute("topology");
if (_mol != 0)
{
if ((query_type == 0) && (topology == 0))
idx = _mol->addBond_Silent(beg, end, order_val);
else
throw Error("'query type' bonds are allowed only for queries");
}
else
{
AutoPtr<QueryMolecule::Bond> bond;
if (query_type == 0)
{
if (order_val == BOND_SINGLE || order_val == BOND_DOUBLE || order_val == BOND_TRIPLE || order_val == BOND_AROMATIC)
bond.reset(new QueryMolecule::Bond(QueryMolecule::BOND_ORDER, order_val));
}
else if (strncmp(query_type, "SD", 2) == 0)
bond.reset(QueryMolecule::Bond::und(QueryMolecule::Bond::nicht(new QueryMolecule::Bond(QueryMolecule::BOND_ORDER, BOND_AROMATIC)),
QueryMolecule::Bond::oder(new QueryMolecule::Bond(QueryMolecule::BOND_ORDER, BOND_SINGLE),
new QueryMolecule::Bond(QueryMolecule::BOND_ORDER, BOND_DOUBLE))));
else if (strncmp(query_type, "SA", 2) == 0)
bond.reset(QueryMolecule::Bond::oder(new QueryMolecule::Bond(QueryMolecule::BOND_ORDER, BOND_SINGLE),
new QueryMolecule::Bond(QueryMolecule::BOND_ORDER, BOND_AROMATIC)));
else if (strncmp(query_type, "DA", 2) == 0)
bond.reset(QueryMolecule::Bond::oder(new QueryMolecule::Bond(QueryMolecule::BOND_ORDER, BOND_DOUBLE),
new QueryMolecule::Bond(QueryMolecule::BOND_ORDER, BOND_AROMATIC)));
else if (strncmp(query_type, "Any", 3) == 0)
bond.reset(new QueryMolecule::Bond());
else
throw Error("unknown bond type: %d", order);
const char* topology = elem->Attribute("topology");
if (topology != 0)
{
if (strncmp(topology, "ring", 4) == 0)
bond.reset(QueryMolecule::Bond::und(bond.release(), new QueryMolecule::Bond(QueryMolecule::BOND_TOPOLOGY, TOPOLOGY_RING)));
else if (strncmp(topology, "chain", 5) == 0)
bond.reset(QueryMolecule::Bond::und(bond.release(), new QueryMolecule::Bond(QueryMolecule::BOND_TOPOLOGY, TOPOLOGY_CHAIN)));
else
throw Error("unknown topology: %s", topology);
}
idx = _qmol->addBond(beg, end, bond.release());
}
int dir = 0;
TiXmlElement* bs_elem = elem->FirstChildElement("bondStereo");
if (bs_elem != 0)
{
const char* text = bs_elem->GetText();
if (text != 0)
{
if (text[0] == 'W' && text[1] == 0)
dir = BOND_UP;
if (text[0] == 'H' && text[1] == 0)
dir = BOND_DOWN;
if ((text[0] == 'C' || text[0] == 'T') && text[1] == 0)
have_cistrans_notation = true;
}
else
{
const char* convention = bs_elem->Attribute("convention");
if (convention != 0)
{
have_cistrans_notation = true;
}
}
}
if (dir != 0)
_bmol->setBondDirection(idx, dir);
const char* brcenter = elem->Attribute("mrvReactingCenter");
if (brcenter != 0)
{
int val;
if (sscanf(brcenter, "%d", &val) != 1)
throw Error("error parsing reacting center flag");
_bmol->reaction_bond_reacting_center[idx] = val;
}
}
// Implicit H counts
int i, j;
for (i = _bmol->vertexBegin(); i != _bmol->vertexEnd(); i = _bmol->vertexNext(i))
{
int h = total_h_count[i];
if (h < 0)
continue;
const Vertex& vertex = _bmol->getVertex(i);
for (j = vertex.neiBegin(); j != vertex.neiEnd(); j = vertex.neiNext(j))
if (_bmol->getAtomNumber(vertex.neiVertex(j)) == ELEM_H)
h--;
if (h < 0)
throw Error("hydrogenCount on atom %d is less than the number of explicit hydrogens");
if (_mol != 0)
_mol->setImplicitH(i, h);
}
// Query H counts
if (_qmol != 0)
{
for (i = _bmol->vertexBegin(); i != _bmol->vertexEnd(); i = _bmol->vertexNext(i))
{
int expl_h = 0;
if (query_h_count[i] >= 0)
{
// count explicit hydrogens
const Vertex& vertex = _bmol->getVertex(i);
for (j = vertex.neiBegin(); j != vertex.neiEnd(); j = vertex.neiNext(j))
{
if (_bmol->getAtomNumber(vertex.neiVertex(j)) == ELEM_H)
expl_h++;
}
}
if (query_h_count[i] == 0)
{
// no hydrogens unless explicitly drawn
_qmol->resetAtom(i, QueryMolecule::Atom::und(_qmol->releaseAtom(i), new QueryMolecule::Atom(QueryMolecule::ATOM_TOTAL_H, expl_h)));
}
else if (query_h_count[i] > 0)
{
// (_hcount[k] - 1) or more atoms in addition to explicitly drawn
// no hydrogens unless explicitly drawn
_qmol->resetAtom(
i, QueryMolecule::Atom::und(_qmol->releaseAtom(i), new QueryMolecule::Atom(QueryMolecule::ATOM_TOTAL_H, expl_h + query_h_count[i], 100)));
}
}
}
// Tetrahedral stereocenters
for (TiXmlElement* elem = handle.FirstChild("atomArray").FirstChild().Element(); elem; elem = elem->NextSiblingElement())
{
const char* id = elem->Attribute("id");
if (id == 0)
throw Error("atom without an id");
int idx = getAtomIdx(id);
TiXmlElement* ap_elem = elem->FirstChildElement("atomParity");
if (ap_elem == 0)
continue;
const char* ap_text = ap_elem->GetText();
if (ap_text == 0)
continue;
int val;
if (sscanf(ap_text, "%d", &val) != 1)
throw Error("error parsing atomParity");
const char* refs4 = ap_elem->Attribute("atomRefs4");
if (refs4 != 0)
{
BufferScanner strscan(refs4);
QS_DEF(Array<char>, id);
int pyramid[4];
for (int k = 0; k < 4; k++)
{
strscan.skipSpace();
strscan.readWord(id, 0);
pyramid[k] = getAtomIdx(id.ptr());
if (pyramid[k] == idx)
pyramid[k] = -1;
}
if (val < 0)
std::swap(pyramid[0], pyramid[1]);
MoleculeStereocenters::moveMinimalToEnd(pyramid);
_bmol->stereocenters.add(idx, MoleculeStereocenters::ATOM_ABS, 0, pyramid);
}
}
if (_bmol->stereocenters.size() == 0 && BaseMolecule::hasCoord(*_bmol))
{
QS_DEF(Array<int>, sensible_bond_orientations);
sensible_bond_orientations.clear_resize(_bmol->vertexEnd());
_bmol->stereocenters.buildFromBonds(stereochemistry_options, sensible_bond_orientations.ptr());
if (!stereochemistry_options.ignore_errors)
for (i = 0; i < _bmol->vertexCount(); i++)
if (_bmol->getBondDirection(i) > 0 && !sensible_bond_orientations[i])
throw Error("direction of bond #%d makes no sense", i);
}
// Cis-trans stuff
if (have_cistrans_notation)
{
int bond_idx = -1;
for (TiXmlElement* elem = handle.FirstChild("bondArray").FirstChild().Element(); elem; elem = elem->NextSiblingElement())
{
if (strncmp(elem->Value(), "bond", 4) != 0)
continue;
bond_idx++;
TiXmlElement* bs_elem = elem->FirstChildElement("bondStereo");
if (bs_elem == 0)
continue;
const char* convention = bs_elem->Attribute("convention");
if (convention != 0)
{
const char* convention_value = bs_elem->Attribute("conventionValue");
if (convention_value != 0)
{
if (strncmp(convention, "MDL", 3) == 0)
{
int val;
if (sscanf(convention_value, "%d", &val) != 1)
throw Error("error conventionValue attribute");
if (val == 3)
{
_bmol->cis_trans.ignore(bond_idx);
}
}
}
}
const char* text = bs_elem->GetText();
if (text == 0)
continue;
int parity;
if (text[0] == 'C' && text[1] == 0)
parity = MoleculeCisTrans::CIS;
else if (text[0] == 'T' && text[1] == 0)
parity = MoleculeCisTrans::TRANS;
else
continue;
const char* atom_refs = bs_elem->Attribute("atomRefs4");
// If there are only one substituent then atomRefs4 cano be omitted
bool has_subst = atom_refs != nullptr;
int substituents[4];
if (!MoleculeCisTrans::isGeomStereoBond(*_bmol, bond_idx, substituents, false))
throw Error("cis-trans notation on a non cis-trans bond #%d", bond_idx);
if (!MoleculeCisTrans::sortSubstituents(*_bmol, substituents, 0))
throw Error("cis-trans notation on a non cis-trans bond #%d", bond_idx);
if (has_subst)
{
BufferScanner strscan(atom_refs);
QS_DEF(Array<char>, id);
int refs[4] = {-1, -1, -1, -1};
for (int k = 0; k < 4; k++)
{
strscan.skipSpace();
strscan.readWord(id, 0);
refs[k] = getAtomIdx(id.ptr());
}
const Edge& edge = _bmol->getEdge(bond_idx);
if (refs[1] == edge.beg && refs[2] == edge.end)
;
else if (refs[1] == edge.end && refs[2] == edge.beg)
{
std::swap(refs[0], refs[3]);
std::swap(refs[1], refs[2]);
}
else
throw Error("atomRefs4 in bondStereo do not match the bond ends");
bool invert = false;
if (refs[0] == substituents[0])
;
else if (refs[0] == substituents[1])
invert = !invert;
else
throw Error("atomRefs4 in bondStereo do not match the substituents");
if (refs[3] == substituents[2])
;
else if (refs[3] == substituents[3])
invert = !invert;
else
throw Error("atomRefs4 in bondStereo do not match the substituents");
if (invert)
parity = 3 - parity;
}
_bmol->cis_trans.add(bond_idx, substituents, parity);
}
}
else if (BaseMolecule::hasCoord(*_bmol))
_bmol->cis_trans.build(0);
// Sgroups
for (TiXmlElement* elem = handle.FirstChild().Element(); elem; elem = elem->NextSiblingElement())
{
if (strncmp(elem->Value(), "molecule", 8) != 0)
continue;
_loadSGroupElement(elem, atoms_id, 0);
}
}
void CmlLoader::_loadSGroupElement(TiXmlElement* elem, std::unordered_map<std::string, int>& atoms_id, int sg_parent)
{
auto getAtomIdx = [&](const char* id) {
auto it = atoms_id.find(id);
if (it == atoms_id.end())
throw Error("atom id %s cannot be found", id);
return it->second;
};
MoleculeSGroups* sgroups = &_bmol->sgroups;
DataSGroup* dsg = 0;
SGroup* gen = 0;
RepeatingUnit* sru = 0;
MultipleGroup* mul = 0;
Superatom* sup = 0;
int idx = 0;
if (elem != 0)
{
const char* role = elem->Attribute("role");
if (role == 0)
throw Error("Sgroup without type");
if (strncmp(role, "DataSgroup", 10) == 0)
{
idx = sgroups->addSGroup(SGroup::SG_TYPE_DAT);
dsg = (DataSGroup*)&sgroups->getSGroup(idx);
}
else if (strncmp(role, "GenericSgroup", 13) == 0)
{
idx = sgroups->addSGroup(SGroup::SG_TYPE_GEN);
gen = (SGroup*)&sgroups->getSGroup(idx);
}
else if (strncmp(role, "SruSgroup", 9) == 0)
{
idx = sgroups->addSGroup(SGroup::SG_TYPE_SRU);
sru = (RepeatingUnit*)&sgroups->getSGroup(idx);
}
else if (strncmp(role, "MultipleSgroup", 14) == 0)
{
idx = sgroups->addSGroup(SGroup::SG_TYPE_MUL);
mul = (MultipleGroup*)&sgroups->getSGroup(idx);
}
else if (strncmp(role, "SuperatomSgroup", 15) == 0)
{
idx = sgroups->addSGroup(SGroup::SG_TYPE_SUP);
sup = (Superatom*)&sgroups->getSGroup(idx);
}
if ((dsg == 0) && (gen == 0) && (sru == 0) && (mul == 0) && (sup == 0))
return;
if (dsg != 0)
{
if (sg_parent > 0)
dsg->parent_group = sg_parent;
const char* atom_refs = elem->Attribute("atomRefs");
if (atom_refs != 0)
{
BufferScanner strscan(atom_refs);
QS_DEF(Array<char>, id);
while (!strscan.isEOF())
{
strscan.readWord(id, 0);
dsg->atoms.push(getAtomIdx(id.ptr()));
strscan.skipSpace();
}
}
TiXmlElement* brackets = elem->FirstChildElement("MBracket");
if (brackets != 0)
{
const char* brk_type = brackets->Attribute("type");
if (brk_type != 0)
{
if (strncmp(brk_type, "SQUARE", 6) == 0)
{
dsg->brk_style = 0;
}
else if (strncmp(brk_type, "ROUND", 5) == 0)
{
dsg->brk_style = 1;
}
}
int point_idx = 0;
Vec2f* pbrackets;
TiXmlElement* pPoint;
for (pPoint = brackets->FirstChildElement(); pPoint; pPoint = pPoint->NextSiblingElement())
{
if (strncmp(pPoint->Value(), "MPoint", 6) != 0)
continue;
if (point_idx == 0)
pbrackets = dsg->brackets.push();
const char* point_x = pPoint->Attribute("x");
const char* point_y = pPoint->Attribute("y");
float x = readFloat(point_x);
float y = readFloat(point_y);
pbrackets[point_idx].x = x;
pbrackets[point_idx].y = y;
point_idx++;
if (point_idx == 2)
point_idx = 0;
}
}
const char* fieldname = elem->Attribute("fieldName");
if (fieldname != 0)
dsg->name.readString(fieldname, true);
const char* fielddata = elem->Attribute("fieldData");
if (fieldname != 0)
dsg->data.readString(fielddata, true);
const char* fieldtype = elem->Attribute("fieldType");
if (fieldtype != 0)
dsg->description.readString(fieldtype, true);
const char* disp_x = elem->Attribute("x");
if (disp_x != 0)
{
BufferScanner strscan(disp_x);
dsg->display_pos.x = strscan.readFloat();
}
const char* disp_y = elem->Attribute("y");
if (disp_y != 0)
{
BufferScanner strscan(disp_y);
dsg->display_pos.y = strscan.readFloat();
}
const char* detached = elem->Attribute("dataDetached");
dsg->detached = true;
if (detached != 0)
{
if ((strncmp(detached, "true", 4) == 0) || (strncmp(detached, "on", 2) == 0) || (strncmp(detached, "1", 1) == 0) ||
(strncmp(detached, "yes", 3) == 0))
{
dsg->detached = true;
}
else if ((strncmp(detached, "false", 5) == 0) || (strncmp(detached, "off", 3) == 0) || (strncmp(detached, "0", 1) == 0) ||
(strncmp(detached, "no", 2) == 0))
{
dsg->detached = false;
}
}
const char* relative = elem->Attribute("placement");
dsg->relative = false;
if (relative != 0)
{
if (strncmp(relative, "Relative", 8) == 0)
{
dsg->relative = true;
}
}
const char* disp_units = elem->Attribute("unitsDisplayed");
if (disp_units != 0)
{
if ((strncmp(disp_units, "Unit displayed", 14) == 0) || (strncmp(disp_units, "yes", 3) == 0) || (strncmp(disp_units, "on", 2) == 0) ||
(strncmp(disp_units, "1", 1) == 0) || (strncmp(disp_units, "true", 4) == 0))
{
dsg->display_units = true;
}
}
dsg->num_chars = 0;
const char* disp_chars = elem->Attribute("displayedChars");
if (disp_chars != 0)
{
BufferScanner strscan(disp_chars);
dsg->num_chars = strscan.readInt1();
}
const char* disp_tag = elem->Attribute("tag");
if (disp_tag != 0)
{
BufferScanner strscan(disp_tag);
dsg->tag = strscan.readChar();
}
const char* query_op = elem->Attribute("queryOp");
if (query_op != 0)
dsg->queryoper.readString(query_op, true);
const char* query_type = elem->Attribute("queryType");
if (query_type != 0)
dsg->querycode.readString(query_type, true);
TiXmlNode* pChild;
for (pChild = elem->FirstChild(); pChild != 0; pChild = pChild->NextSibling())
{
if (strncmp(pChild->Value(), "molecule", 8) != 0)
continue;
TiXmlHandle next_mol = pChild;
if (next_mol.Element() != 0)
_loadSGroupElement(next_mol.Element(), atoms_id, idx + 1);
}
}
else if (gen != 0)
{
if (sg_parent > 0)
gen->parent_group = sg_parent;
const char* atom_refs = elem->Attribute("atomRefs");
if (atom_refs != 0)
{
BufferScanner strscan(atom_refs);
QS_DEF(Array<char>, id);
while (!strscan.isEOF())
{
strscan.readWord(id, 0);
gen->atoms.push(getAtomIdx(id.ptr()));
strscan.skipSpace();
}
}
TiXmlElement* brackets = elem->FirstChildElement("MBracket");
if (brackets != 0)
{
const char* brk_type = brackets->Attribute("type");
if (brk_type != 0)
{
if (strncmp(brk_type, "SQUARE", 6) == 0)
{
gen->brk_style = 0;
}
else if (strncmp(brk_type, "ROUND", 5) == 0)
{
gen->brk_style = 1;
}
}
int point_idx = 0;
Vec2f* pbrackets;
TiXmlElement* pPoint;
for (pPoint = brackets->FirstChildElement(); pPoint; pPoint = pPoint->NextSiblingElement())
{
if (strncmp(pPoint->Value(), "MPoint", 6) != 0)
continue;
if (point_idx == 0)
pbrackets = gen->brackets.push();
float x = 0, y = 0;
const char* point_x = pPoint->Attribute("x");
if (point_x != 0)
{
BufferScanner strscan(point_x);
x = strscan.readFloat();
}
const char* point_y = pPoint->Attribute("y");
if (point_y != 0)
{
BufferScanner strscan(point_y);
y = strscan.readFloat();
}
pbrackets[point_idx].x = x;
pbrackets[point_idx].y = y;
point_idx++;
if (point_idx == 2)
point_idx = 0;
}
}
TiXmlNode* pChild;
for (pChild = elem->FirstChild(); pChild != 0; pChild = pChild->NextSibling())
{
if (strncmp(pChild->Value(), "molecule", 8) != 0)
continue;
TiXmlHandle next_mol = pChild;
if (next_mol.Element() != 0)
_loadSGroupElement(next_mol.Element(), atoms_id, idx + 1);
}
}
else if (sru != 0)
{
if (sg_parent > 0)
sru->parent_group = sg_parent;
const char* atom_refs = elem->Attribute("atomRefs");
if (atom_refs != 0)
{
BufferScanner strscan(atom_refs);
QS_DEF(Array<char>, id);
while (!strscan.isEOF())
{
strscan.readWord(id, 0);
sru->atoms.push(getAtomIdx(id.ptr()));
strscan.skipSpace();
}
}
TiXmlElement* brackets = elem->FirstChildElement("MBracket");
if (brackets != 0)
{
const char* brk_type = brackets->Attribute("type");
if (brk_type != 0)
{
if (strncmp(brk_type, "SQUARE", 6) == 0)
{
sru->brk_style = 0;
}
else if (strncmp(brk_type, "ROUND", 5) == 0)
{
sru->brk_style = 1;
}
}
int point_idx = 0;
Vec2f* pbrackets;
TiXmlElement* pPoint;
for (pPoint = brackets->FirstChildElement(); pPoint; pPoint = pPoint->NextSiblingElement())
{
if (strncmp(pPoint->Value(), "MPoint", 6) != 0)
continue;
if (point_idx == 0)
pbrackets = sru->brackets.push();
float x = 0, y = 0;
const char* point_x = pPoint->Attribute("x");
if (point_x != 0)
{
BufferScanner strscan(point_x);
x = strscan.readFloat();
}
const char* point_y = pPoint->Attribute("y");
if (point_y != 0)
{
BufferScanner strscan(point_y);
y = strscan.readFloat();
}
pbrackets[point_idx].x = x;
pbrackets[point_idx].y = y;
point_idx++;
if (point_idx == 2)
point_idx = 0;
}
}
const char* title = elem->Attribute("title");
if (title != 0)
sru->subscript.readString(title, true);
const char* connect = elem->Attribute("connect");
if (connect != 0)
{
if (strncmp(connect, "ht", 2) == 0)
{
sru->connectivity = SGroup::HEAD_TO_TAIL;
}
else if (strncmp(connect, "hh", 2) == 0)
{
sru->connectivity = SGroup::HEAD_TO_HEAD;
}
}
TiXmlNode* pChild;
for (pChild = elem->FirstChild(); pChild != 0; pChild = pChild->NextSibling())
{
if (strncmp(pChild->Value(), "molecule", 8) != 0)
continue;
TiXmlHandle next_mol = pChild;
if (next_mol.Element() != 0)
_loadSGroupElement(next_mol.Element(), atoms_id, idx + 1);
}
}
else if (mul != 0)
{
if (sg_parent > 0)
mul->parent_group = sg_parent;
const char* atom_refs = elem->Attribute("atomRefs");
if (atom_refs != 0)
{
BufferScanner strscan(atom_refs);
QS_DEF(Array<char>, id);
while (!strscan.isEOF())
{
strscan.readWord(id, 0);
mul->atoms.push(getAtomIdx(id.ptr()));
strscan.skipSpace();
}
}
const char* patoms = elem->Attribute("patoms");
if (patoms != 0)
{
BufferScanner strscan(patoms);
QS_DEF(Array<char>, id);
while (!strscan.isEOF())
{
strscan.readWord(id, 0);
mul->parent_atoms.push(getAtomIdx(id.ptr()));
strscan.skipSpace();
}
}
TiXmlElement* brackets = elem->FirstChildElement("MBracket");
if (brackets != 0)
{
const char* brk_type = brackets->Attribute("type");
if (brk_type != 0)
{
if (strncmp(brk_type, "SQUARE", 6) == 0)
{
mul->brk_style = 0;
}
else if (strncmp(brk_type, "ROUND", 5) == 0)
{
mul->brk_style = 1;
}
}
int point_idx = 0;
Vec2f* pbrackets;
TiXmlElement* pPoint;
for (pPoint = brackets->FirstChildElement(); pPoint; pPoint = pPoint->NextSiblingElement())
{
if (strncmp(pPoint->Value(), "MPoint", 6) != 0)
continue;
if (point_idx == 0)
pbrackets = mul->brackets.push();
float x = 0, y = 0;
const char* point_x = pPoint->Attribute("x");
if (point_x != 0)
{
BufferScanner strscan(point_x);
x = strscan.readFloat();
}
const char* point_y = pPoint->Attribute("y");
if (point_y != 0)
{
BufferScanner strscan(point_y);
y = strscan.readFloat();
}
pbrackets[point_idx].x = x;
pbrackets[point_idx].y = y;
point_idx++;
if (point_idx == 2)
point_idx = 0;
}
}
const char* title = elem->Attribute("title");
if (title != 0)
{
BufferScanner strscan(title);
mul->multiplier = strscan.readInt1();
}
TiXmlNode* pChild;
for (pChild = elem->FirstChild(); pChild != 0; pChild = pChild->NextSibling())
{
if (strncmp(pChild->Value(), "molecule", 8) != 0)
continue;
TiXmlHandle next_mol = pChild;
if (next_mol.Element() != 0)
_loadSGroupElement(next_mol.Element(), atoms_id, idx + 1);
}
}
else if (sup != 0)
{
if (sg_parent > 0)
sup->parent_group = sg_parent;
const char* atom_refs = elem->Attribute("atomRefs");
if (atom_refs != 0)
{
BufferScanner strscan(atom_refs);
QS_DEF(Array<char>, id);
while (!strscan.isEOF())
{
strscan.readWord(id, 0);
sup->atoms.push(getAtomIdx(id.ptr()));
strscan.skipSpace();
}
}
TiXmlElement* brackets = elem->FirstChildElement("MBracket");
if (brackets != 0)
{
const char* brk_type = brackets->Attribute("type");
if (brk_type != 0)
{
if (strncmp(brk_type, "SQUARE", 6) == 0)
{
sup->brk_style = 0;
}
else if (strncmp(brk_type, "ROUND", 5) == 0)
{
sup->brk_style = 1;
}
}
int point_idx = 0;
Vec2f* pbrackets;
TiXmlElement* pPoint;
for (pPoint = brackets->FirstChildElement(); pPoint; pPoint = pPoint->NextSiblingElement())
{
if (strncmp(pPoint->Value(), "MPoint", 6) != 0)
continue;
if (point_idx == 0)
pbrackets = sup->brackets.push();
const char* point_x = pPoint->Attribute("x");
const char* point_y = pPoint->Attribute("y");
float x = readFloat(point_x);
float y = readFloat(point_y);
pbrackets[point_idx].x = x;
pbrackets[point_idx].y = y;
point_idx++;
if (point_idx == 2)
point_idx = 0;
}
}
/*
TiXmlElement *atpoints = elem->FirstChildElement("AttachmentPointArray");
if (atpoints != 0)
{
TiXmlElement * aPoint;
for (aPoint = atpoints->FirstChildElement();
aPoint;
aPoint = aPoint->NextSiblingElement())
{
if (strncmp(aPoint->Value(), "attachmentPoint", 15) != 0)
continue;
int idap = sup->attachment_points.add();
Superatom::_AttachmentPoint &ap = sup->attachment_points.at(idap);
const char *a_idx = aPoint->Attribute("atom");
if (a_idx != 0)
{
ap.aidx = getAtomIdx(a_idx);
}
const char *b_idx = aPoint->Attribute("bond");
if (b_idx != 0)
{
ap.aidx = getAtomIdx(a_idx);
}
const char *ap_order = aPoint->Attribute("order");
if (ap_order != 0)
{
ap.aidx = getAtomIdx(a_idx);
}
}
}
*/
const char* title = elem->Attribute("title");
if (title != 0)
sup->subscript.readString(title, true);
TiXmlNode* pChild;
for (pChild = elem->FirstChild(); pChild != 0; pChild = pChild->NextSibling())
{
if (strncmp(pChild->Value(), "molecule", 8) != 0)
continue;
TiXmlHandle next_mol = pChild;
if (next_mol.Element() != 0)
_loadSGroupElement(next_mol.Element(), atoms_id, idx + 1);
}
}
}
}
void CmlLoader::_loadRgroupElement(TiXmlHandle& handle)
{
MoleculeRGroups* rgroups = &_bmol->rgroups;
TiXmlElement* elem = handle.Element();
if (elem != 0)
{
int rg_idx;
const char* rgroup_id = elem->Attribute("rgroupID");
if (rgroup_id == 0)
throw Error("Rgroup without ID");
BufferScanner strscan(rgroup_id);
rg_idx = strscan.readInt1();
RGroup& rgroup = rgroups->getRGroup(rg_idx);
const char* rlogic_range = elem->Attribute("rlogicRange");
if (rlogic_range != 0)
_parseRlogicRange(rlogic_range, rgroup.occurrence);
const char* rgroup_then = elem->Attribute("thenR");
if (rgroup_then != 0)
{
BufferScanner strscan(rgroup_then);
rgroup.if_then = strscan.readInt1();
}
rgroup.rest_h = 0;
const char* rgroup_resth = elem->Attribute("restH");
if (rgroup_resth != 0)
{
if ((strncmp(rgroup_resth, "true", 4) == 0) || (strncmp(rgroup_resth, "on", 2) == 0) || (strncmp(rgroup_resth, "1", 1) == 0))
{
rgroup.rest_h = 1;
}
}
TiXmlNode* pChild;
for (pChild = handle.FirstChild().ToNode(); pChild != 0; pChild = pChild->NextSibling())
{
if (strncmp(pChild->Value(), "molecule", 8) != 0)
continue;
TiXmlHandle molecule = pChild;
if (molecule.Element() != 0)
{
AutoPtr<BaseMolecule> fragment(_bmol->neu());
Molecule* _mol_save;
BaseMolecule* _bmol_save;
QueryMolecule* _qmol_save;
_mol_save = _mol;
_bmol_save = _bmol;
_qmol_save = _qmol;
_bmol = fragment.get();
if (_bmol->isQueryMolecule())
{
_qmol = &_bmol->asQueryMolecule();
_mol = 0;
}
else
{
_mol = &_bmol->asMolecule();
_qmol = 0;
}
_loadMoleculeElement(molecule);
_mol = _mol_save;
_bmol = _bmol_save;
_qmol = _qmol_save;
rgroup.fragments.add(fragment.release());
}
}
}
}
void CmlLoader::_parseRlogicRange(const char* str, Array<int>& ranges)
{
int beg = -1, end = -1;
int add_beg = 0, add_end = 0;
while (*str != 0)
{
if (*str == '>')
{
end = 0xFFFF;
add_beg = 1;
}
else if (*str == '<')
{
beg = 0;
add_end = -1;
}
else if (isdigit(*str))
{
sscanf(str, "%d", beg == -1 ? &beg : &end);
while (isdigit(*str))
str++;
continue;
}
else if (*str == ',')
{
if (end == -1)
end = beg;
else
beg += add_beg, end += add_end;
ranges.push((beg << 16) | end);
beg = end = -1;
add_beg = add_end = 0;
}
str++;
}
if (beg == -1 && end == -1)
return;
if (end == -1)
end = beg;
else
beg += add_beg, end += add_end;
ranges.push((beg << 16) | end);
}
void CmlLoader::_appendQueryAtom(const char* atom_label, AutoPtr<QueryMolecule::Atom>& atom)
{
int atom_number = Element::fromString2(atom_label);
AutoPtr<QueryMolecule::Atom> cur_atom;
if (atom_number != -1)
cur_atom.reset(new QueryMolecule::Atom(QueryMolecule::ATOM_NUMBER, atom_number));
else
cur_atom.reset(new QueryMolecule::Atom(QueryMolecule::ATOM_PSEUDO, atom_label));
if (atom.get() == 0)
atom.reset(cur_atom.release());
else
atom.reset(QueryMolecule::Atom::oder(atom.release(), cur_atom.release()));
}
| 37.916284 | 158 | 0.472037 | khyurri |
b9ad3fcd47fb8e11222cfb3a6931aa67f450eb3c | 610 | cc | C++ | ports/www/chromium-legacy/newport/files/patch-chrome_test_chromedriver_server_chromedriver__server.cc | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 31 | 2015-02-06T17:06:37.000Z | 2022-03-08T19:53:28.000Z | ports/www/chromium-legacy/newport/files/patch-chrome_test_chromedriver_server_chromedriver__server.cc | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 236 | 2015-06-29T19:51:17.000Z | 2021-12-16T22:46:38.000Z | ports/www/chromium-legacy/newport/files/patch-chrome_test_chromedriver_server_chromedriver__server.cc | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 52 | 2015-02-06T17:05:36.000Z | 2021-10-21T12:13:06.000Z | --- chrome/test/chromedriver/server/chromedriver_server.cc.orig 2020-11-13 06:36:39 UTC
+++ chrome/test/chromedriver/server/chromedriver_server.cc
@@ -283,7 +283,7 @@ int main(int argc, char *argv[]) {
base::AtExitManager at_exit;
base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
-#if defined(OS_LINUX) || defined(OS_CHROMEOS)
+#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD)
// Select the locale from the environment by passing an empty string instead
// of the default "C" locale. This is particularly needed for the keycode
// conversion code to work.
| 50.833333 | 87 | 0.736066 | liweitianux |
b9ae8e66380bcd5f2f311589bf33dd45eb7fae9a | 4,478 | cpp | C++ | examples/sys.cpp | davidwed/sqlrelay_rudiments | 6ccffdfc5fa29f8c0226f3edc2aa888aa1008347 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | examples/sys.cpp | davidwed/sqlrelay_rudiments | 6ccffdfc5fa29f8c0226f3edc2aa888aa1008347 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | examples/sys.cpp | davidwed/sqlrelay_rudiments | 6ccffdfc5fa29f8c0226f3edc2aa888aa1008347 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | #include <rudiments/sys.h>
#include <rudiments/charstring.h>
#include <rudiments/stdio.h>
int main(int argc, const char **argv) {
char *osname=sys::getOperatingSystemName();
stdoutput.printf("OS Name : %s\n",osname);
delete[] osname;
char *release=sys::getOperatingSystemRelease();
stdoutput.printf("OS Release : %s\n",release);
delete[] release;
char *version=sys::getOperatingSystemVersion();
stdoutput.printf("OS Version : %s\n",version);
delete[] version;
char *arch=sys::getOperatingSystemArchitecture();
stdoutput.printf("OS Arch : %s\n",arch);
delete[] arch;
char *hostname=sys::getHostName();
stdoutput.printf("Host Name : %s\n",hostname);
delete[] hostname;
double onemin;
double fivemin;
double fifteenmin;
sys::getLoadAverages(&onemin,&fivemin,&fifteenmin);
stdoutput.printf("Load Averages : %0.2f %0.2f %0.2f\n",
onemin,fivemin,fifteenmin);
stdoutput.printf("Max Cmd Line Arg Length"
" : %lld\n",
sys::getMaxCommandLineArgumentLength());
stdoutput.printf("Max Processes Per User"
" : %lld\n",
sys::getMaxProcessesPerUser());
stdoutput.printf("Max Host Name Length"
" : %lld\n",
sys::getMaxHostNameLength());
stdoutput.printf("Max Login Name Length"
" : %lld\n",
sys::getMaxLoginNameLength());
stdoutput.printf("Clock Ticks Per Second"
" : %lld\n",
sys::getClockTicksPerSecond());
stdoutput.printf("Max Open Files Per Process"
" : %lld\n",
sys::getMaxOpenFilesPerProcess());
stdoutput.printf("Page Size"
" : %lld\n",
sys::getPageSize());
stdoutput.printf("Allocation Granularity"
" : %lld\n",
sys::getAllocationGranularity());
stdoutput.printf("Max Open Streams Per Process"
" : %lld\n",
sys::getMaxOpenStreamsPerProcess());
stdoutput.printf("Max Symlink Loops"
" : %lld\n",
sys::getMaxSymlinkLoops());
stdoutput.printf("Max Terminal Device Name Length"
" : %lld\n",
sys::getMaxTerminalDeviceNameLength());
stdoutput.printf("Max Timezone Name Length"
" : %lld\n",
sys::getMaxTimezoneNameLength());
stdoutput.printf("Max Line Length"
" : %lld\n",
sys::getMaxLineLength());
stdoutput.printf("Physical Page Count"
" : %lld\n",
sys::getPhysicalPageCount());
stdoutput.printf("Available Physical Page Count"
" : %lld\n",
sys::getAvailablePhysicalPageCount());
stdoutput.printf("Processor Count"
" : %lld\n",
sys::getProcessorCount());
stdoutput.printf("Max Processor Count"
" : %lld\n",
sys::getMaxProcessorCount());
stdoutput.printf("Processors Online"
" : %lld\n",
sys::getProcessorsOnline());
stdoutput.printf("Max Supplemental Groups Per User"
" : %lld\n",
sys::getMaxSupplementalGroupsPerUser());
stdoutput.printf("Max Delay Timer Expirations"
" : %lld\n",
sys::getMaxDelayTimerExpirations());
stdoutput.printf("Max Realtime Signals"
" : %lld\n",
sys::getMaxRealtimeSignals());
stdoutput.printf("Max Sempahores Per Process"
" : %lld\n",
sys::getMaxSemaphoresPerProcess());
stdoutput.printf("Max Semaphore Value"
" : %lld\n",
sys::getMaxSemaphoreValue());
stdoutput.printf("Max Signal Queue Length"
" : %lld\n",
sys::getMaxSignalQueueLength());
stdoutput.printf("Max Timers Per Process"
" : %lld\n",
sys::getMaxTimersPerProcess());
stdoutput.printf("Suggested Group Entry Buffer Size"
" : %lld\n",
sys::getSuggestedGroupEntryBufferSize());
stdoutput.printf("Suggested Passwd Entry Buffer Size"
" : %lld\n",
sys::getSuggestedPasswordEntryBufferSize());
stdoutput.printf("Min Thread Stack Size"
" : %lld\n",
sys::getMinThreadStackSize());
stdoutput.printf("Max Threads Per Process"
" : %lld\n",
sys::getMaxThreadsPerProcess());
stdoutput.printf("Thread Destructor Iterations"
" : %lld\n",
sys::getThreadDestructorIterations());
stdoutput.printf("Max Thread Keys"
" : %lld\n",
sys::getMaxThreadKeys());
stdoutput.printf("Max At-Exit Functions"
" : %lld\n",
sys::getMaxAtExitFunctions());
stdoutput.printf("CPUSet Size"
" : %lld\n",
sys::getCpuSetSize());
stdoutput.printf("Max Password Length"
" : %lld\n",
sys::getMaxPasswordLength());
stdoutput.printf("Max Log Name Length"
" : %lld\n",
sys::getMaxLogNameLength());
stdoutput.printf("Max Process ID"
" : %lld\n",
sys::getMaxProcessId());
stdoutput.printf("Directory Separator"
" : %c\n",
sys::getDirectorySeparator());
}
| 24.604396 | 58 | 0.667039 | davidwed |
b9af20942ea0eccde72856b692d6e54fbd3658c7 | 1,716 | cpp | C++ | test/pointsTest.cpp | bostonceltics20/phoebe | b7e6294ee32d7f94299cd027ba2e72c3552ab246 | [
"MIT"
] | 30 | 2020-08-24T03:51:05.000Z | 2022-02-26T15:29:38.000Z | test/pointsTest.cpp | bostonceltics20/phoebe | b7e6294ee32d7f94299cd027ba2e72c3552ab246 | [
"MIT"
] | 43 | 2020-08-27T19:34:36.000Z | 2022-02-25T14:09:39.000Z | test/pointsTest.cpp | bostonceltics20/phoebe | b7e6294ee32d7f94299cd027ba2e72c3552ab246 | [
"MIT"
] | 10 | 2020-10-14T23:15:01.000Z | 2022-01-15T18:54:26.000Z | #include "points.h"
#include "gtest/gtest.h"
TEST(PointsTest, PointsHandling) {
Eigen::Matrix3d directUnitCell;
directUnitCell.row(0) << -5.1, 0., 5.1;
directUnitCell.row(1) << 0., 5.1, 5.1;
directUnitCell.row(2) << -5.1, 5.1, 0.;
Eigen::MatrixXd atomicPositions(2, 3);
atomicPositions.row(0) << 0., 0., 0.;
atomicPositions.row(1) << 2.55, 2.55, 2.55;
Eigen::VectorXi atomicSpecies(2);
atomicSpecies << 0, 0;
std::vector<std::string> speciesNames;
speciesNames.emplace_back("Si");
Eigen::VectorXd speciesMasses(1);
speciesMasses(0) = 28.086;
Context context;
Crystal crystal(context, directUnitCell, atomicPositions, atomicSpecies,
speciesNames, speciesMasses);
Eigen::Vector3i mesh;
mesh << 4, 4, 4;
Points points(crystal, mesh);
//-----------------------------------
// check mesh is what I set initially
auto tup = points.getMesh();
auto mesh_ = std::get<0>(tup);
EXPECT_EQ((mesh - mesh_).norm(), 0.);
//----------------------
// check point inversion
auto p1 = points.getPoint(4);
// find the index of the inverted point
int i4 = points.getIndex(-p1.getCoordinates(Points::crystalCoordinates));
// int i4 = points.getIndexInverted(4);
auto p2 = points.getPoint(i4);
auto p3 = p1 + p2;
EXPECT_EQ(p3.getCoordinates(Points::cartesianCoordinates).norm(), 0.);
//-----------------------
// check point inversion
mesh << 2, 2, 2;
points = Points(crystal, mesh);
int iq = 7;
p1 = points.getPoint(iq);
// int iqr = points.getIndexInverted(iq);
int iqr = points.getIndex(-p1.getCoordinates(Points::crystalCoordinates));
p2 = points.getPoint(iqr);
p3 = p1 + p2;
EXPECT_EQ(p3.getCoordinates().norm(), 0.);
}
| 28.6 | 76 | 0.630536 | bostonceltics20 |
b9b7066a97c14ee8064df1578ad4c0e1c528d200 | 1,445 | cpp | C++ | 208. Implement Trie (Prefix Tree).cpp | ivanilos/leetcode | 6b13870a49180eed5c1548410f2c9cca219d1cab | [
"MIT"
] | null | null | null | 208. Implement Trie (Prefix Tree).cpp | ivanilos/leetcode | 6b13870a49180eed5c1548410f2c9cca219d1cab | [
"MIT"
] | null | null | null | 208. Implement Trie (Prefix Tree).cpp | ivanilos/leetcode | 6b13870a49180eed5c1548410f2c9cca219d1cab | [
"MIT"
] | null | null | null | class Trie {
public:
/** Initialize your data structure here. */
Trie() {
trie.push_back(map<char, int>()); // root
word_end.push_back(false);
}
/** Inserts a word into the trie. */
void insert(string word) {
int pos = 0;
for (char c : word) {
if (!trie[pos].count(c)) {
trie[pos][c] = trie.size();
trie.push_back(map<char,int>());
word_end.push_back(false);
}
pos = trie[pos][c];
}
word_end[pos] = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
int pos = 0;
for (char c : word) {
if (!trie[pos].count(c)) { return false; }
pos = trie[pos][c];
}
return word_end[pos];
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
int pos = 0;
for (char c : prefix) {
if (!trie[pos].count(c)) { return false; }
pos = trie[pos][c];
}
return true;
}
private:
vector<map<char, int>> trie;
vector<bool> word_end;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/ | 25.350877 | 86 | 0.491349 | ivanilos |
b9b91a8e68980c00f947366af39e4150cfc392f4 | 6,849 | cpp | C++ | icd/api/llpc/patch/llpcPatchPushConstOp.cpp | alan-baker/xgl | 5c4a9497570200781d054416832f55e8b64d7e58 | [
"MIT"
] | null | null | null | icd/api/llpc/patch/llpcPatchPushConstOp.cpp | alan-baker/xgl | 5c4a9497570200781d054416832f55e8b64d7e58 | [
"MIT"
] | null | null | null | icd/api/llpc/patch/llpcPatchPushConstOp.cpp | alan-baker/xgl | 5c4a9497570200781d054416832f55e8b64d7e58 | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file llpcPatchPushConstOp.cpp
* @brief LLPC source file: contains implementation of class Llpc::PatchPushConstOp.
***********************************************************************************************************************
*/
#define DEBUG_TYPE "llpc-patch-push-const"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "SPIRVInternal.h"
#include "llpcContext.h"
#include "llpcIntrinsDefs.h"
#include "llpcPatchPushConstOp.h"
using namespace llvm;
using namespace Llpc;
namespace Llpc
{
// =====================================================================================================================
// Initializes static members.
char PatchPushConstOp::ID = 0;
// =====================================================================================================================
PatchPushConstOp::PatchPushConstOp()
:
Patch(ID)
{
initializePatchPushConstOpPass(*PassRegistry::getPassRegistry());
}
// =====================================================================================================================
// Executes this SPIR-V lowering pass on the specified LLVM module.
bool PatchPushConstOp::runOnModule(
Module& module) // [in,out] LLVM module to be run on
{
DEBUG(dbgs() << "Run the pass Patch-Push-Const-Op\n");
Patch::Init(&module);
// Invoke handling of "call" instruction
visit(m_pModule);
// Remove unnecessary push constant load calls
for (auto pCallInst: m_pushConstCalls)
{
pCallInst->dropAllReferences();
pCallInst->eraseFromParent();
}
// Remove unnecessary push constant load functions
for (auto pFunc : m_descLoadFuncs)
{
if (pFunc->user_empty())
{
pFunc->dropAllReferences();
pFunc->eraseFromParent();
}
}
LLPC_VERIFY_MODULE_FOR_PASS(module);
return true;
}
// =====================================================================================================================
// Visits "call" instruction.
void PatchPushConstOp::visitCallInst(
CallInst& callInst) // [in] "Call" instruction
{
auto pCallee = callInst.getCalledFunction();
if (pCallee == nullptr)
{
return;
}
auto mangledName = pCallee->getName();
if (mangledName.startswith(LlpcName::PushConstLoad))
{
auto pIntfData = m_pContext->GetShaderInterfaceData(m_shaderStage);
auto pShaderInfo = m_pContext->GetPipelineShaderInfo(m_shaderStage);
uint32_t pushConstNodeIdx = pIntfData->pushConst.resNodeIdx;
LLPC_ASSERT(pushConstNodeIdx != InvalidValue);
auto pPushConstNode = &pShaderInfo->pUserDataNodes[pushConstNodeIdx];
if (pPushConstNode->offsetInDwords < pIntfData->spillTable.offsetInDwords)
{
auto pMemberOffsetInBytes = callInst.getOperand(0);
auto pPushConst = GetFunctionArgument(m_pEntryPoint,
pIntfData->entryArgIdxs.resNodeValues[pushConstNodeIdx]);
// Load push constant per dword
Type* pLoadTy = callInst.getType();
LLPC_ASSERT(pLoadTy->isVectorTy() &&
pLoadTy->getVectorElementType()->isIntegerTy() &&
(pLoadTy->getScalarSizeInBits() == 8));
uint32_t dwordCount = pLoadTy->getVectorNumElements() / 4;
Instruction* pInsertPos = &callInst;
Value* pLoadValue = UndefValue::get(VectorType::get(m_pContext->Int32Ty(), dwordCount));
for (uint32_t i = 0; i < dwordCount; ++i)
{
Value* pDwordIdx = ConstantInt::get(m_pContext->Int32Ty(), i);
Value* pDestIdx = pDwordIdx;
Value* pMemberDwordOffset = BinaryOperator::Create(Instruction::AShr,
pMemberOffsetInBytes,
ConstantInt::get(m_pContext->Int32Ty(), 2),
"",
pInsertPos);
pDwordIdx = BinaryOperator::Create(Instruction::Add, pDwordIdx, pMemberDwordOffset, "", pInsertPos);
Value* pTmp = ExtractElementInst::Create(pPushConst, pDwordIdx, "", pInsertPos);
pLoadValue = InsertElementInst::Create(pLoadValue, pTmp, pDestIdx, "", pInsertPos);
}
pLoadValue = new BitCastInst(pLoadValue,
VectorType::get(m_pContext->Int8Ty(), pLoadTy->getVectorNumElements()),
"",
pInsertPos);
callInst.replaceAllUsesWith(pLoadValue);
m_pushConstCalls.insert(&callInst);
m_descLoadFuncs.insert(pCallee);
}
}
}
} // Llpc
// =====================================================================================================================
// Initializes the pass of LLVM patch operations for push constant operations.
INITIALIZE_PASS(PatchPushConstOp, "Patch-push-const",
"Patch LLVM for push constant operations", false, false)
| 41.259036 | 120 | 0.528982 | alan-baker |
b9b9a4d4f5c2fcaed281f8b8123f3cd3cdd9f392 | 25,992 | cpp | C++ | src/Restart.cpp | allen-cell-animated/medyan | 0b5ef64fb338c3961673361e5632980617937ee6 | [
"BSD-4-Clause-UC"
] | null | null | null | src/Restart.cpp | allen-cell-animated/medyan | 0b5ef64fb338c3961673361e5632980617937ee6 | [
"BSD-4-Clause-UC"
] | null | null | null | src/Restart.cpp | allen-cell-animated/medyan | 0b5ef64fb338c3961673361e5632980617937ee6 | [
"BSD-4-Clause-UC"
] | null | null | null |
//------------------------------------------------------------------
// **MEDYAN** - Simulation Package for the Mechanochemical
// Dynamics of Active Networks, v4.0
//
// Copyright (2015-2018) Papoian Lab, University of Maryland
//
// ALL RIGHTS RESERVED
//
// See the MEDYAN web page for more information:
// http://www.medyan.org
//------------------------------------------------------------------
#include "Restart.h"
void Restart::readNetworkSetup() {
//Flush the filestream pointer
_inputFile.clear();
//Go to the first entry in the file.
_inputFile.seekg(0);
string line;
//get first line
getline(_inputFile, line);
vector<string> lineVector = split<string>(line);
_rsystemdata.time = atof(((lineVector[1]).c_str()));
//get line
while(getline(_inputFile, line)) {
//Continue if commented
if(line.find("#") != string::npos) { continue; }
vector<string> lineVector = split<string>(line);
if(line.size()>0) {
if(lineVector[0] == "NFIL"){
getline(_inputFile, line);
//Split string based on space delimiter
vector<string> lineVector = split<string>(line);
_rsystemdata.Nfil = atoi(((lineVector[0]).c_str()));
_rsystemdata.Ncyl = atoi(((lineVector[1]).c_str()));
_rsystemdata.Nbead = atoi(((lineVector[2]).c_str()));
_rsystemdata.Nlink = atoi(((lineVector[3]).c_str()));
_rsystemdata.Nmotor = atoi(((lineVector[4]).c_str()));
_rsystemdata.Nbranch = atoi(((lineVector[5]).c_str()));
//resize data structures
_rBData.bsidvec.resize(_rsystemdata.Nbead);
_rBData.filidvec.resize(_rsystemdata.Nbead);
_rBData.filpos.resize(_rsystemdata.Nbead);
_rBData.coordvec.resize(3*_rsystemdata.Nbead);
_rBData.forceAuxvec.resize(3*_rsystemdata.Nbead);
}
if (lineVector[0] == "BEAD") {
//Get lines till the line is not empty
getline(_inputFile, line);
while (line.size() > 0) {
//Split string based on space delimiter
vector<string> lineVector = split<string>(line);
//Bead stable ID
auto beadstableid = atoi(((lineVector[0]).c_str()));
_rBData.bsidvec[beadstableid] = beadstableid;
//Filament ID
_rBData.filidvec[beadstableid] = (atoi(lineVector[1].c_str()));
//Filament pos
_rBData.filpos[beadstableid] = (atoi(lineVector[2].c_str()));
//Copy coords & forces
short dim = 0;
for (auto it = lineVector.begin() + 3;
it != lineVector.begin() + 6; it++) {
_rBData.coordvec[3 * beadstableid + dim] = (atof((*it).c_str()));
dim++;
}
dim = 0;
for (auto it = lineVector.begin() + 6;
it != lineVector.begin() + 9; it++){
_rBData.forceAuxvec[3 * beadstableid + dim] = (atof((*it).c_str()));
dim++;
}
getline(_inputFile, line);
}
}
else if (lineVector[0] == "CYLINDER") {
//Get lines till the line is not empty
getline(_inputFile, line);
while (line.size() > 0) {
restartCylData _rcyldata;
//Split string based on space delimiter
vector<string> lineVector = split<string>(line);
//Cylinder stable index
_rcyldata.cylsid = atoi(((lineVector[0]).c_str()));
//Filament ID
_rcyldata.filid = atoi((lineVector[1]).c_str());
_rcyldata.filtype = atoi((lineVector[2]).c_str());
_rcyldata.filpos = atoi((lineVector[3]).c_str());
//Filament pos
//Bead stable indices
_rcyldata.beadsidpairvec[0] = atoi((lineVector[4]).c_str());
_rcyldata.beadsidpairvec[1] = atoi((lineVector[5]).c_str());
//minus end or plus end?
_rcyldata.endstatusvec[0] = atoi((lineVector[6]).c_str());
_rcyldata.endstatusvec[1] = atoi((lineVector[7]).c_str());
//minus/plus end type
_rcyldata.endtypevec[0] = atoi((lineVector[8]).c_str());
_rcyldata.endtypevec[1] = atoi((lineVector[9]).c_str());
//endmonomerpos
_rcyldata.endmonomerpos[0] = atoi((lineVector[10]).c_str());
_rcyldata.endmonomerpos[1] = atoi((lineVector[11]).c_str());
//totalmonomers
_rcyldata.totalmonomers = atoi((lineVector[12]).c_str());
//eqlen
_rcyldata.eqlen = atof((lineVector[13]).c_str());
//append to the vector
_rCDatavec.push_back(_rcyldata);
//get next cylinder data
getline(_inputFile, line);
}
}
else if (lineVector[0] == "FILAMENT") {
//Get lines till the line is not empty
getline(_inputFile, line);
while (line.size() > 0) {
restartFilData _rfildata;
//Split string based on space delimiter
vector<string> lineVector = split<string>(line);
//Filament ID
_rfildata.filid = atoi((lineVector[0]).c_str());
//Filament Type
_rfildata.filType = atoi((lineVector[1]).c_str());
//Cylinder id vec
for (auto it = lineVector.begin() + 2; it != lineVector.end(); it++) {
_rfildata.cylsidvec.push_back(atoi((*it).c_str()));
}
//append to the vector
_rFDatavec.push_back(_rfildata);
//get next filament data
getline(_inputFile, line);
}
}
else if (lineVector[0] == "LINKER") {
//Get lines till the line is not empty
getline(_inputFile, line);
while (line.size() > 0) {
restartLinkerData _rldata;
//Split string based on space delimiter
vector<string> lineVector = split<string>(line);
//Motor ID
_rldata.linkerid = atoi((lineVector[0]).c_str());
//Linker Type
_rldata.linkerType = short(atoi((lineVector[1]).c_str()));
//Cyl ID1
_rldata.cylid1 = atoi((lineVector[2]).c_str());
//Cyl ID2
_rldata.cylid2 = atoi((lineVector[3]).c_str());
//pos1
_rldata.pos1 = atoi((lineVector[4]).c_str());
//pos2
_rldata.pos2 = atoi((lineVector[5]).c_str());
//eqlen
_rldata.eqlen = atof((lineVector[6]).c_str());
//diffusing species name
_rldata.diffusingspeciesname = lineVector[7];
_rLDatavec.push_back(_rldata);
//get next filament data
getline(_inputFile, line);
}
}
else if (lineVector[0] == "MOTOR") {
//Get lines till the line is not empty
getline(_inputFile, line);
while (line.size() > 0) {
restartMotorData _rmdata;
//Split string based on space delimiter
vector<string> lineVector = split<string>(line);
//Motor ID
_rmdata.motorid = atoi((lineVector[0]).c_str());
//Motor Type
_rmdata.motorType = short(atoi((lineVector[1]).c_str()));
//Cyl ID1
_rmdata.cylid1 = atoi((lineVector[2]).c_str());
//Cyl ID2
_rmdata.cylid2 = atoi((lineVector[3]).c_str());
//pos1
_rmdata.pos1 = atoi((lineVector[4]).c_str());
//pos2
_rmdata.pos2 = atoi((lineVector[5]).c_str());
//eqlen
_rmdata.eqlen = atof((lineVector[6]).c_str());
//diffusing species name
_rmdata.diffusingspeciesname = lineVector[7];
if(lineVector.size()>8) {
//numHeads
_rmdata.numHeads = atoi((lineVector[8]).c_str());
//numBoundHeads
_rmdata.numBoundHeads = atof((lineVector[9]).c_str());
}
_rMDatavec.push_back(_rmdata);
//get next filament data
getline(_inputFile, line);
}
}
else if (lineVector[0] == "BRANCHING") {
//Get lines till the line is not empty
getline(_inputFile, line);
while (line.size() > 0) {
restartBrancherData _rbdata;
//Split string based on space delimiter
vector<string> lineVector = split<string>(line);
//Brancher ID
_rbdata.branchid = atoi((lineVector[0]).c_str());
//Brancher Type
_rbdata.branchType = short(atoi((lineVector[1]).c_str()));
//Cyl ID1
_rbdata.cylid1 = atoi((lineVector[2]).c_str());
//Cyl ID2
_rbdata.cylid2 = atoi((lineVector[3]).c_str());
//pos1
_rbdata.pos1 = atoi((lineVector[4]).c_str());
//eqlen
_rbdata.eqlen = atof((lineVector[5]).c_str());
//diffusing species name
_rbdata.diffusingspeciesnamebranch = lineVector[6];
if(lineVector.size() == 8 )
_rbdata.diffusingspeciesnameactin = lineVector[7];
else
_rbdata.diffusingspeciesnameactin = "A";
_rBDatavec.push_back(_rbdata);
//get next filament data
getline(_inputFile, line);
}
}
/* parse diffusing species copy number in each compartment*/
if (lineVector[0] == "COMPARTMENT") {
//Get lines till the line is not empty
getline(_inputFile, line);
while (line.size() > 0) {
restartCompartmentDiffusingData _rcddata;
//Split string based on space delimiter
vector<string> lineVector = split<string>(line);
_rcddata.id = atoi((lineVector[0]).c_str());
//Copy species name
for (auto n = 1; n < lineVector.size(); n = n + 2)
_rcddata.speciesnamevec.push_back(lineVector[n].c_str());
//Copy species copy number
for (auto n = 2; n < lineVector.size(); n = n + 2)
_rcddata.copynumvec.push_back(atoi(lineVector[n].c_str()));
_rCmpDDatavec.push_back(_rcddata);
//get next filament data
getline(_inputFile, line);
}
}
/* parse bulk species copy number*/
if (lineVector[0] == "BULKSPECIES") {
//Get lines till the line is not empty
getline(_inputFile, line);
while (line.size() > 0) {
vector<string> lineVector = split<string>(line);
for (auto n = 0; n < lineVector.size(); n = n + 2)
_rbdata.speciesnamevec.push_back(lineVector[n].c_str());
//Copy species copy number
for (auto n = 1; n < lineVector.size(); n = n + 2)
_rbdata.copynumvec.push_back(atoi(lineVector[n].c_str()));
//get next bulkspecies data
getline(_inputFile, line);
}
}
/* parse total copy number of each species*/
if (lineVector[0] == "TALLY") {
//Get lines till the line is not empty
getline(_inputFile, line);
string delimiter = ":";
while (line.size() > 0) {
vector<string> lineVector = split<string>(line);
auto pos = lineVector[0].find(delimiter);
_rbdata.speciesnamevec.push_back(lineVector[0].substr(0,pos));
_rbdata.copynumvec.push_back(atoi(lineVector[1].c_str()));
//get next bulkspecies data
getline(_inputFile, line);
}
}
}
}
cout<<"numMotors="<<_rMDatavec.size()<<endl;
cout<<"numLinkers="<<_rLDatavec.size()<<endl;
cout<<"numBranchers="<<_rBDatavec.size()<<endl;
}
void Restart::setupInitialNetwork() {
//Step 1. Create dummy filaments
//Step 2. Create Beads
//Step 3. Create cylinders & set plus/minus ends where necessary
//Step 4. Associate cylinders with each filament by adding it to the cylinder vector
// in the appropriate order starting from minus end all the way to plus end cylinder.
map<int, Filament*> filamentmap;//makes it easy to access Filament pointer from
// Filament ID. Filaments do not follow stable index protocol and hence need not have
// continuous ID values.
for(auto &fil : _rFDatavec) {
//Create dummy filament
fil.filamentpointer = _subSystem->addTrackable<Filament>(_subSystem, fil.filType);
//override ID
fil.filamentpointer->overrideId(fil.filid);
//add to map
filamentmap[fil.filid] = fil.filamentpointer;
}
cout<<endl;
cout<<"Num filaments created "<<Filament::getFilaments().size()<<endl;
for(unsigned int b=0;b<_rBData.bsidvec.size();b++){
auto bID = _rBData.bsidvec[b];
auto filptr = filamentmap[_rBData.filidvec[b]];
//Extract part of the vector.
vector<floatingpoint> tempcoord(_rBData.coordvec.begin()+3*bID, _rBData.coordvec
.begin()+3*bID+3);
//Initialize beads
auto pBead = _subSystem->addTrackable<Bead>(tempcoord, filptr, _rBData.filpos[b]);
//Copy Forces
for(unsigned int dim = 0; dim < 3; dim++)
pBead->force[dim] = _rBData.forceAuxvec.data()[3*bID+dim];
}
cout<<"Num beads created "<<Bead::getBeads().size()<<endl;
for(auto &cyl : _rCDatavec){
auto b1 = Bead::getBeads()[cyl.beadsidpairvec[0]];
auto b2 = Bead::getBeads()[cyl.beadsidpairvec[1]];
auto filptr = filamentmap[cyl.filid];
auto _filType = cyl.filtype;
//initialize cylinder
Cylinder* c0 = _subSystem->addTrackable<Cylinder> (filptr, b1, b2, _filType,
cyl.filpos, false, false,
true, cyl.eqlen);
cyl.cylinderpointer = c0;
//set minusend or plusend
if(cyl.endstatusvec[0])
c0->setMinusEnd(true);
else if(cyl.endstatusvec[1])
c0->setPlusEnd(true);
}
cout<<"Num cylinders created "<<Cylinder::getCylinders().size()<<endl;
for(auto fil : _rFDatavec) {
vector<Cylinder*> cylvector;
//Go through cylinder stable indices that should be part of the filament and
// append the Cylinder pointer to a vector.
for(auto cylsid:fil.cylsidvec){
cylvector.push_back(_rCDatavec[cylsid].cylinderpointer);
}
fil.filamentpointer->initializerestart(cylvector, _rCDatavec);
}
}
void Restart::addtoHeapLinkerMotorBrancher(){
//STEP #2. ADD bound Linkers And Motors in inputfile into possible bindings.
//set total number of reactions to fire.
_numChemSteps = _rMDatavec.size() + _rLDatavec.size() + _rBDatavec.size();
//Motors
for(auto m:_rMDatavec) {
int cidx1 = m.cylid1;
int cidx2 = m.cylid2;
int site1 = m.pos1;
int site2 = m.pos2;
Cylinder *c1 = _rCDatavec[cidx1].cylinderpointer;
Cylinder *c2 = _rCDatavec[cidx2].cylinderpointer;
if (c1->getId() > c2->getId()) {
for (auto &Mgr:c1->getCompartment()->getFilamentBindingManagers()) {
if (dynamic_cast<MotorBindingManager *>(Mgr.get())) {
setdiffspeciesnumber(m.diffusingspeciesname,c1);
#ifdef NLORIGINAL
Mgr->appendpossibleBindings(c1->getCCylinder(),
c2->getCCylinder(), site1, site2);
#else
Mgr->appendpossibleBindingsstencil(m.motorType, c1->getCCylinder(),
c2->getCCylinder(), site1, site2);
#endif
}
}
}
else{
for (auto &Mgr:c2->getCompartment()->getFilamentBindingManagers()) {
if (dynamic_cast<MotorBindingManager *>(Mgr.get())) {
setdiffspeciesnumber(m.diffusingspeciesname,c2);
#ifdef NLORIGINAL
Mgr->appendpossibleBindings(c2->getCCylinder(),
c1->getCCylinder(), site2, site1);
#else
Mgr->appendpossibleBindingsstencil(m.motorType, c2->getCCylinder(),
c1->getCCylinder(), site2, site1);
#endif
}
}
}
}
//Linkers
for(auto l:_rLDatavec) {
int cidx1 = l.cylid1;
int cidx2 = l.cylid2;
int site1 = l.pos1;
int site2 = l.pos2;
Cylinder *c1 = _rCDatavec[cidx1].cylinderpointer;
Cylinder *c2 = _rCDatavec[cidx2].cylinderpointer;
if (c1->getId() > c2->getId()) {
for (auto &Mgr:c1->getCompartment()->getFilamentBindingManagers()) {
if (dynamic_cast<LinkerBindingManager *>(Mgr.get())) {
setdiffspeciesnumber(l.diffusingspeciesname,c1);
#ifdef NLORIGINAL
Mgr->appendpossibleBindings(c1->getCCylinder(),
c2->getCCylinder(), site1, site2);
#else
Mgr->appendpossibleBindingsstencil(l.linkerType, c1->getCCylinder(),
c2->getCCylinder(), site1, site2);
#endif
}
}
}
else{
for (auto &Mgr:c2->getCompartment()->getFilamentBindingManagers()) {
if (dynamic_cast<LinkerBindingManager *>(Mgr.get())) {
setdiffspeciesnumber(l.diffusingspeciesname,c2);
#ifdef NLORIGINAL
Mgr->appendpossibleBindings(c2->getCCylinder(),
c1->getCCylinder(), site2, site1);
#else
Mgr->appendpossibleBindingsstencil(l.linkerType, c2->getCCylinder(),
c1->getCCylinder(), site2, site1);
#endif
}
}
}
}
//Brancher
for(auto b:_rBDatavec) {
int cidx1 = b.cylid1;
int cidx2 = b.cylid2;
int site1 = b.pos1;
Cylinder *c1 = _rCDatavec[cidx1].cylinderpointer;
Cylinder *c2 = _rCDatavec[cidx2].cylinderpointer;
/* cout<<"c1 idx "<<c1->getStableIndex()<<endl;
cout<<"c1 cmp "<<c1->getCompartment()->getId()<<", c2 cmp "<<c2->getCompartment()
->getId()<<endl;*/
for (auto &Mgr:c1->getCompartment()->getFilamentBindingManagers()) {
if (dynamic_cast<BranchingManager *>(Mgr.get())) {
setdiffspeciesnumber(b.diffusingspeciesnamebranch,c1);
setdiffspeciesnumber(b.diffusingspeciesnameactin,c1);
#ifdef NLORIGINAL
Mgr->appendpossibleBindings(c1->getCCylinder(),
c2->getCCylinder(), site1, site2);
#else
Mgr->appendpossibleBindingsstencil(b.branchType, c1->getCCylinder(),
c2->getCCylinder(), site1, 0);
#endif
}
}
}
}
void Restart::CBoundinitializerestart(){
//linkers
for(auto l:Linker::getLinkers()) {
int c1 = l->getFirstCylinder()->getStableIndex();
int c2 = l->getSecondCylinder()->getStableIndex();
short ftype1 = l->getFirstCylinder()->getType();
short ftype2 = l->getSecondCylinder()->getType();
short pos1 = l->getFirstPosition()*SysParams::Geometry().cylinderNumMon[ftype1];
short pos2 = l->getSecondPosition()*SysParams::Geometry().cylinderNumMon[ftype2];
for(auto &rldata: _rLDatavec){
if(!rldata.restartcompletion) {
int rc1 = rldata.cylid1;
int rc2 = rldata.cylid2;
short rpos1 = rldata.pos1;
short rpos2 = rldata.pos2;
bool cndn1 = rc1 == c1 && rc2 == c2 && rpos1 == pos1 && rpos2 == pos2;
bool cndn2 = rc1 == c2 && rc2 == c1 && rpos1 == pos2 && rpos2 == pos1;
if(cndn1 || cndn2){
l->initializerestart(rldata.eqlen);
rldata.restartcompletion = true;
}
}
}
}
//motors
for(auto m:MotorGhost::getMotorGhosts()) {
int c1 = m->getFirstCylinder()->getStableIndex();
int c2 = m->getSecondCylinder()->getStableIndex();
short ftype1 = m->getFirstCylinder()->getType();
short ftype2 = m->getSecondCylinder()->getType();
short pos1 = m->getFirstPosition()*SysParams::Geometry().cylinderNumMon[ftype1];
short pos2 = m->getSecondPosition()*SysParams::Geometry().cylinderNumMon[ftype2];
bool foundstatus = false;
for(auto &rmdata: _rMDatavec){
if(!rmdata.restartcompletion) {
int rc1 = rmdata.cylid1;
int rc2 = rmdata.cylid2;
short rpos1 = rmdata.pos1;
short rpos2 = rmdata.pos2;
bool cndn1 = rc1 == c1 && rc2 == c2 && rpos1 == pos1 && rpos2 == pos2;
bool cndn2 = rc1 == c2 && rc2 == c1 && rpos1 == pos2 && rpos2 == pos1;
if(cndn1 || cndn2){
foundstatus = true;
m->initializerestart(rmdata.eqlen, rmdata.numHeads, rmdata.numBoundHeads);
rmdata.restartcompletion = true;
}
}
}
if(!foundstatus)
LOG(ERROR)<<"Motor not found!"<<endl;
}
cout<<endl;
//brancher
for(auto b:BranchingPoint::getBranchingPoints()) {
int c1 = b->getFirstCylinder()->getStableIndex();
int c2 = b->getSecondCylinder()->getStableIndex();
short ftype1 = b->getFirstCylinder()->getType();
short pos1 = b->getPosition()*SysParams::Geometry().cylinderNumMon[ftype1];
for(auto &rbdata: _rLDatavec){
if(!rbdata.restartcompletion) {
int rc1 = rbdata.cylid1;
int rc2 = rbdata.cylid2;
short rpos1 = rbdata.pos1;
if(rc1 == c1 && rc2 == c2 && rpos1 == pos1){
b->initializerestart(rbdata.eqlen);
rbdata.restartcompletion = true;
}
}
}
}
}
bool Restart::crosscheck(){
//Filament data
for(auto &fil : _rFDatavec) {
auto filptr = fil.filamentpointer;
short counter = 0;
auto cylsidvec = fil.cylsidvec;
bool status = true;
int startindex = 0;
for(auto cylinfil:filptr->getCylinderVector()) {
if(counter == 0){
startindex = cylinfil->getPosition();
}
int currindex = cylinfil->getPosition();
if(abs(startindex-currindex) != counter ){
LOG(ERROR) << "Cylinder position does not match" << endl;
LOG(ERROR) << startindex<<" "<<currindex<<endl;
status = false;
break;
}
if (cylinfil->getStableIndex() != cylsidvec[counter]) {
LOG(ERROR) << "Cylinder sidx does not match" << endl;
status = false;
break;
}
counter++;
}
if(!status){
cout<<"Datadump dictates Fil "<<fil.filid<<" be comprised of cylinder "
"sidx ";
for(auto c:cylsidvec)
cout<<c<<" ";
cout<<endl;
cout<<"But Fil "<<filptr->getId()<<" is comprised of cylinder sidx ";
for(auto c:filptr->getCylinderVector())
cout<<c->getStableIndex()<<" ";
cout<<endl;
}
}
//Cylinder data
return true;
} | 44.354949 | 94 | 0.491882 | allen-cell-animated |
b9bc2c7f1ddda22d289596138bc7ee033922bc9a | 2,677 | cpp | C++ | libs/kinematics/src/CVehicleSimul_Holo.cpp | zarmomin/mrpt | 1baff7cf8ec9fd23e1a72714553bcbd88c201966 | [
"BSD-3-Clause"
] | 1 | 2021-12-10T06:24:08.000Z | 2021-12-10T06:24:08.000Z | libs/kinematics/src/CVehicleSimul_Holo.cpp | gao-ouyang/mrpt | 4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7 | [
"BSD-3-Clause"
] | null | null | null | libs/kinematics/src/CVehicleSimul_Holo.cpp | gao-ouyang/mrpt | 4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7 | [
"BSD-3-Clause"
] | 1 | 2019-09-11T02:55:04.000Z | 2019-09-11T02:55:04.000Z | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "kinematics-precomp.h" // Precompiled header
#include <mrpt/kinematics/CVehicleSimul_Holo.h>
#include <mrpt/math/wrap2pi.h>
using namespace mrpt::kinematics;
CVehicleSimul_Holo::CVehicleSimul_Holo()
{
resetStatus();
resetTime();
}
void CVehicleSimul_Holo::internal_simulControlStep(const double dt)
{
// Control:
if (m_vel_ramp_cmd.issue_time >= 0 &&
m_time > m_vel_ramp_cmd.issue_time) // are we executing any cmd?
{
const double t = m_time - m_vel_ramp_cmd.issue_time;
const double T = m_vel_ramp_cmd.ramp_time;
const double vxi = m_vel_ramp_cmd.init_vel.vx;
const double vyi = m_vel_ramp_cmd.init_vel.vy;
const double wi = m_vel_ramp_cmd.init_vel.omega;
const double vxf = m_vel_ramp_cmd.target_vel_x;
const double vyf = m_vel_ramp_cmd.target_vel_y;
// "Blending" for vx,vy
if (t <= m_vel_ramp_cmd.ramp_time)
{
m_odometric_vel.vx = vxi + t * (vxf - vxi) / T;
m_odometric_vel.vy = vyi + t * (vyf - vyi) / T;
}
else
{
m_odometric_vel.vx = m_vel_ramp_cmd.target_vel_x;
m_odometric_vel.vy = m_vel_ramp_cmd.target_vel_y;
}
// Ramp rotvel until aligned:
const double Aang =
mrpt::math::wrapToPi(m_vel_ramp_cmd.dir - m_odometry.phi);
if (std::abs(Aang) < mrpt::DEG2RAD(1.0))
{
m_odometric_vel.omega = .0; // we are aligned.
}
else
{
const double wf =
mrpt::sign(Aang) * std::abs(m_vel_ramp_cmd.rot_speed);
if (t <= m_vel_ramp_cmd.ramp_time)
{
m_odometric_vel.omega = wi + t * (wf - wi) / T;
}
else
{
m_odometric_vel.omega = wf;
}
}
}
}
void CVehicleSimul_Holo::internal_clear() { m_vel_ramp_cmd = TVelRampCmd(); }
void CVehicleSimul_Holo::sendVelRampCmd(
double vel, double dir, double ramp_time, double rot_speed)
{
ASSERT_ABOVE_(ramp_time, 0);
m_vel_ramp_cmd.issue_time = m_time;
m_vel_ramp_cmd.ramp_time = ramp_time;
m_vel_ramp_cmd.rot_speed = rot_speed;
m_vel_ramp_cmd.init_vel = m_odometric_vel;
m_vel_ramp_cmd.target_vel_x = cos(dir) * vel;
m_vel_ramp_cmd.target_vel_y = sin(dir) * vel;
m_vel_ramp_cmd.dir = dir;
}
| 31.127907 | 80 | 0.617482 | zarmomin |
b9bd18a26cb2ea4e7ddbcc52ed0988ce10ed86d1 | 1,183 | hpp | C++ | src/app/preset-window.hpp | mimo31/fluid-sim | 481c3e5a5456350bccb8795aa119a3487dff3021 | [
"MIT"
] | 1 | 2020-11-26T17:20:28.000Z | 2020-11-26T17:20:28.000Z | src/app/preset-window.hpp | mimo31/brandy0 | 481c3e5a5456350bccb8795aa119a3487dff3021 | [
"MIT"
] | null | null | null | src/app/preset-window.hpp | mimo31/brandy0 | 481c3e5a5456350bccb8795aa119a3487dff3021 | [
"MIT"
] | null | null | null | /**
* preset-window.hpp
*
* Author: Viktor Fukala
* Created on 2021/03/07
*/
#ifndef PRESET_WINDOW_HPP
#define PRESET_WINDOW_HPP
#include "gtkmm/button.h"
#include "gtkmm/comboboxtext.h"
#include "gtkmm/grid.h"
#include "gtkmm/label.h"
#include "brandy-window.hpp"
#include "config-state-abstr.hpp"
namespace brandy0
{
/**
* Class representing the window offering a selection of simulation parameters presets
*/
class PresetWindow : public BrandyWindow
{
private:
/// Pointer to the parent (abstract) configuration state
ConfigStateAbstr *parent;
/// Window's main widget grid
Gtk::Grid grid;
/// Label explaining that the combo box shows presets
Gtk::Label presetLabel;
/// Combo box with all the presets
Gtk::ComboBoxText presetSelector;
/// Label with a warning that selecting (confirming) a presets overwrites all current paramters
Gtk::Label warnLabel;
/// Button for confirming preset currently selected in the combo box
Gtk::Button confirmButton;
public:
/**
* Constructs the preset window object
* @param parent pointer to the parent (abstract) configuration state
*/
PresetWindow(ConfigStateAbstr *parent);
};
}
#endif // PRESET_WINDOW_HPP | 23.66 | 96 | 0.748943 | mimo31 |
b9c0186ff3a05cadadeb8ff336fdcbb6a8103d29 | 1,102 | cpp | C++ | 基础算法/manacher算法/acw_3188_2.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | 3 | 2020-11-16T08:58:30.000Z | 2020-11-16T08:58:33.000Z | 基础算法/manacher算法/acw_3188_2.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | 基础算法/manacher算法/acw_3188_2.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/*
复杂度O(N)的根本原因是最后的回文边界mr是单调递增的
从前往后计算每个位置为中心的回文串半径长度
然后用最右边的边界来更新mid
*/
const int N = 2e7 + 10; //double length of original string
int n;
char a[N], b[N];
int p[N]; //max radius of each mid
void init() {
int k = 0;
b[k++] = '$', b[k++] = '#';
for (int i = 0; i < n; i++) b[k++] = a[i], b[k++] = '#';
b[k++] = '^';
n = k;
}
void manacher() {
int mr = 0, mid;
for (int i = 1; i < n; i++) {
if (i < mr) p[i] = min(p[mid * 2 - i], mr - i);
else p[i] = 1;
//这个while循环只有在p[i] = mr-i 的情况才会进行更新p[i]
//如果是p[i] = p[mid * 2 -i],那么直接O(1)计算出p[i],不会在这里while花费复杂度
//所以整个算法的复杂度可以由内层的while决定,但是这个循环的mr是递增的,mr到字符串结尾的时候算法结束,所以是O(N)
while (b[i - p[i]] == b[i + p[i]]) p[i]++;
if (i + p[i] > mr) {
mr = i + p[i];
mid = i;
}
}
}
void solve() {
cin >> a;
n = strlen(a);
init();
manacher();
int res = 0;
for (int i = 0; i < n; i++) res = max(res, p[i]);
cout << res - 1 << endl;
}
int main() {
solve();
return 0;
} | 20.036364 | 71 | 0.465517 | tempure |
b9c4055c46bdfb8290f95d5459c93bdabdeffe4f | 1,357 | hpp | C++ | libs/core/include/fcppt/symbol/class.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/core/include/fcppt/symbol/class.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/core/include/fcppt/symbol/class.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// 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)
#ifndef FCPPT_SYMBOL_CLASS_HPP_INCLUDED
#define FCPPT_SYMBOL_CLASS_HPP_INCLUDED
#include <fcppt/config/compiler.hpp>
#if defined(FCPPT_CONFIG_MSVC_COMPILER)
#define FCPPT_SYMBOL_CLASS_IMPL
#elif defined(FCPPT_CONFIG_GCC_COMPILER)
#include <fcppt/symbol/export.hpp>
#define FCPPT_SYMBOL_CLASS_IMPL FCPPT_SYMBOL_EXPORT
#else
#error "Don't know what FCPPT_DETAIL_SYMBOL_CLASS should be"
#endif
/**
\brief Tells that a classes's vtable should be exported
\ingroup fcpptexport
This macro marks a classes's vtable to be exported, so it can be shared across
dynamic libraries. There are several cases in which this is necessary:
<ul>
<li>The class is thrown as an exception and caught by another library.</li>
<li>The class has virtual methods that will be called directly from another
library.</li>
</ul>
It is not necessary to specify whether the class is currently exported or
imported.
\code
class FCPPT_DETAIL_SYMBOL_CLASS my_exception
{
};
class FCPPT_DETAIL_SYMBOL_CLASS my_base
{
virtual
void
do_something() = 0;
};
\endcode
\see \ref symbol_vtable
*/
#define FCPPT_SYMBOL_CLASS FCPPT_SYMBOL_CLASS_IMPL
#endif
| 23.807018 | 78 | 0.778187 | freundlich |
b9c530d5c6d278efbacd6f3411dff1829cc0cd49 | 1,067 | hpp | C++ | atto/tests/opengl/2-quad/quad.hpp | ubikoo/libfish | 7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39 | [
"MIT"
] | null | null | null | atto/tests/opengl/2-quad/quad.hpp | ubikoo/libfish | 7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39 | [
"MIT"
] | null | null | null | atto/tests/opengl/2-quad/quad.hpp | ubikoo/libfish | 7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39 | [
"MIT"
] | null | null | null | /*
* quad.hpp
*
* Copyright (c) 2020 Carlos Braga
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* See accompanying LICENSE.md or https://opensource.org/licenses/MIT.
*/
#ifndef TEST_ATTO_OPENGL_QUAD_H_
#define TEST_ATTO_OPENGL_QUAD_H_
#include "atto/opengl/opengl.hpp"
/**
* struct Quad
* @brief Minimal drawable object that clears the OpenGL color buffer.
*/
struct Quad : atto::gl::Drawable {
GLuint m_program; /* shader program object */
GLuint m_vao; /* vertex array object */
GLuint m_vbo; /* vertex buffer object */
GLuint m_ebo; /* element buffer object */
/* Handle and draw member functions. */
void handle(const atto::gl::Event &event) override;
void draw(void *data) override;
/* Constructor/destructor. Disable copy semantics. */
Quad();
~Quad() = default;
Quad(const Quad &) = delete;
Quad &operator=(const Quad &) = delete;
};
#endif /* TEST_ATTO_OPENGL_QUAD_H_ */
| 27.358974 | 71 | 0.648547 | ubikoo |
b9c5f5d8285d15d1b895b0401697eebc03f0fe60 | 6,809 | hpp | C++ | include/frg/variant.hpp | czapek1337/frigg | ad1b6947047f492ed42b189fb208e600d9ec6915 | [
"MIT"
] | 37 | 2018-11-05T19:15:46.000Z | 2022-03-09T10:16:28.000Z | include/frg/variant.hpp | czapek1337/frigg | ad1b6947047f492ed42b189fb208e600d9ec6915 | [
"MIT"
] | 13 | 2020-01-05T13:32:27.000Z | 2022-03-09T17:21:07.000Z | include/frg/variant.hpp | czapek1337/frigg | ad1b6947047f492ed42b189fb208e600d9ec6915 | [
"MIT"
] | 16 | 2020-01-01T15:45:02.000Z | 2022-03-06T22:19:58.000Z | #pragma once
#include <frg/eternal.hpp>
#include <frg/macros.hpp>
#include <type_traits>
#include <stddef.h>
namespace frg {
namespace _variant {
// check if S is one of the types T
template<typename S, typename... T>
struct exists : public std::false_type { };
template<typename S, typename... T>
struct exists<S, S, T...> : public std::true_type { };
template<typename S, typename H, typename... T>
struct exists<S, H, T...> : public exists<S, T...> { };
// get the index of S in the argument pack T
template<typename, typename S, typename... T>
struct index_of_helper { };
template<typename S, typename... T>
struct index_of_helper<std::enable_if_t<exists<S, S, T...>::value>, S, S, T...>
: public std::integral_constant<size_t, 0> { };
template<typename S, typename H, typename... T>
struct index_of_helper<std::enable_if_t<exists<S, H, T...>::value>, S, H, T...>
: public std::integral_constant<size_t, index_of_helper<void, S, T...>::value + 1> { };
template<typename S, typename... T>
using index_of = index_of_helper<void, S, T...>;
// get a type with a certain index from the argument pack T
template<size_t Index, typename... T>
struct get_helper { };
template<typename H, typename... T>
struct get_helper<0, H, T...> {
using type = H;
};
template<size_t Index, typename H, typename... T>
struct get_helper<Index, H, T...>
: public get_helper<Index - 1, T...> { };
template<size_t Index, typename... T>
using get = typename get_helper<Index, T...>::type;
};
template<typename... T>
struct variant {
static constexpr size_t invalid_tag = size_t(-1);
template<typename X, size_t Index = _variant::index_of<X, T...>::value>
static constexpr size_t tag_of() {
return Index;
}
variant() : tag_{invalid_tag} { }
template<typename X, size_t Index = _variant::index_of<X, T...>::value>
variant(X object) : variant() {
construct_<Index>(std::move(object));
};
variant(const variant &other) : variant() {
if(other)
copy_construct_<0>(other);
}
variant(variant &&other) : variant() {
if(other)
move_construct_<0>(std::move(other));
}
~variant() {
if(*this)
destruct_<0>();
}
explicit operator bool() const {
return tag_ != invalid_tag;
}
variant &operator= (variant other) {
// Because swap is quite hard to implement for this type we don't use copy-and-swap.
// Instead we perform a destruct-then-move-construct operation on the internal object.
// Note that we take the argument by value so there are no self-assignment problems.
if(tag_ == other.tag_) {
assign_<0>(std::move(other));
} else {
if(*this)
destruct_<0>();
if(other)
move_construct_<0>(std::move(other));
}
return *this;
}
size_t tag() {
return tag_;
}
template<typename X, size_t Index = _variant::index_of<X, T...>::value>
bool is() const {
return tag_ == Index;
}
template<typename X, size_t Index = _variant::index_of<X, T...>::value>
X &get() {
FRG_ASSERT(tag_ == Index);
return *std::launder(reinterpret_cast<X *>(access_()));
}
template<typename X, size_t Index = _variant::index_of<X, T...>::value>
const X &get() const {
FRG_ASSERT(tag_ == Index);
return *std::launder(reinterpret_cast<const X *>(access_()));
}
template<typename X, size_t Index = _variant::index_of<X, T...>::value,
typename... Args>
void emplace(Args &&... args) {
if(tag_ != invalid_tag)
destruct_<0>();
new (access_()) X(std::forward<Args>(args)...);
tag_ = Index;
}
template<typename F>
std::common_type_t<std::invoke_result_t<F, T&>...> apply(F functor) {
return apply_<F, 0>(std::move(functor));
}
template<typename F>
std::common_type_t<std::invoke_result_t<F, const T&>...> const_apply(F functor) const {
return apply_<F, 0>(std::move(functor));
}
private:
void *access_() {
return storage_.buffer;
}
const void *access_() const {
return storage_.buffer;
}
// construct the internal object from one of the summed types
template<size_t Index, typename X = _variant::get<Index, T...>>
void construct_(X object) {
FRG_ASSERT(!*this);
new (access_()) X(std::move(object));
tag_ = Index;
}
// construct the internal object by copying from another variant
template<size_t Index> requires (Index < sizeof...(T))
void copy_construct_(const variant &other) {
using value_type = _variant::get<Index, T...>;
if(other.tag_ == Index) {
FRG_ASSERT(!*this);
new (access_()) value_type(other.get<value_type>());
tag_ = Index;
} else {
copy_construct_<Index + 1>(other);
}
}
template<size_t Index> requires (Index == sizeof...(T))
void copy_construct_(const variant &) {
FRG_ASSERT(!"Copy-construction from variant with illegal tag");
}
// construct the internal object by moving from another variant
template<size_t Index> requires (Index < sizeof...(T))
void move_construct_(variant &&other) {
using value_type = _variant::get<Index, T...>;
if(other.tag_ == Index) {
FRG_ASSERT(!*this);
new (access_()) value_type(std::move(other.get<value_type>()));
tag_ = Index;
} else {
move_construct_<Index + 1>(std::move(other));
}
}
template<size_t Index> requires (Index == sizeof...(T))
void move_construct_(variant &&) {
FRG_ASSERT(!"Move-construction from variant with illegal tag");
}
// destruct the internal object
template<size_t Index> requires (Index < sizeof...(T))
void destruct_() {
using value_type = _variant::get<Index, T...>;
if(tag_ == Index) {
get<value_type>().~value_type();
tag_ = invalid_tag;
} else {
destruct_<Index + 1>();
}
}
template<size_t Index> requires (Index == sizeof...(T))
void destruct_() {
FRG_ASSERT(!"Destruction of variant with illegal tag");
}
// assign the internal object
template<size_t Index> requires (Index < sizeof...(T))
void assign_(variant other) {
using value_type = _variant::get<Index, T...>;
if(tag_ == Index) {
get<value_type>() = std::move(other.get<value_type>());
} else {
assign_<Index + 1>(std::move(other));
}
}
template<size_t Index> requires (Index == sizeof...(T))
void assign_(variant) {
FRG_ASSERT(!"Assignment from variant with illegal tag");
}
// apply a functor to the internal object
template<typename F, size_t Index> requires (Index < sizeof...(T))
std::common_type_t<std::invoke_result_t<F, T&>...>
apply_(F functor) {
using value_type = _variant::get<Index, T...>;
if(tag_ == Index) {
return functor(get<value_type>());
} else {
return apply_<F, Index + 1>(std::move(functor));
}
}
template<typename F, size_t Index> requires (Index == sizeof...(T))
std::common_type_t<std::invoke_result_t<F, T&>...>
apply_(F) {
FRG_ASSERT(!"_apply() on variant with illegal tag");
__builtin_unreachable();
}
size_t tag_;
frg::aligned_union<T...> storage_;
};
} // namespace frg
| 27.12749 | 88 | 0.66368 | czapek1337 |
b9c8382f5af5e59c460f6945834add844ef15325 | 295 | hpp | C++ | AbstractFactory/AbstractProductA.hpp | colorhistory/design-patterns | 854b07c786cc6ceb80b687ed933c6560c288215b | [
"MIT"
] | null | null | null | AbstractFactory/AbstractProductA.hpp | colorhistory/design-patterns | 854b07c786cc6ceb80b687ed933c6560c288215b | [
"MIT"
] | null | null | null | AbstractFactory/AbstractProductA.hpp | colorhistory/design-patterns | 854b07c786cc6ceb80b687ed933c6560c288215b | [
"MIT"
] | null | null | null | #ifndef ABSTRACTPRODUCTA_HPP
#define ABSTRACTPRODUCTA_HPP
namespace DP {
class AbstractProductA {
public:
AbstractProductA();
virtual ~AbstractProductA() = 0;
// ADT
virtual void use() = 0;
};
} // namespace DP
#endif // ABSTRACTPRODUCTA_HPP
| 17.352941 | 40 | 0.623729 | colorhistory |
b9ca906a10d8183ecea31e49c6665bb968557a34 | 1,790 | hpp | C++ | parser.hpp | ultinate/masked-sudoku | 0e0bcdcf6c1701c52cab204ea4ffac392793b92b | [
"MIT"
] | null | null | null | parser.hpp | ultinate/masked-sudoku | 0e0bcdcf6c1701c52cab204ea4ffac392793b92b | [
"MIT"
] | null | null | null | parser.hpp | ultinate/masked-sudoku | 0e0bcdcf6c1701c52cab204ea4ffac392793b92b | [
"MIT"
] | null | null | null | #ifndef PARSER_HPP
#define PARSER_HPP
#include <iostream>
#include <string>
#include <cstring>
const int N = 9;
typedef unsigned short int mask;
class Parser {
private:
std::string inputString;
mask unsolvedBoard[N*N];
public:
/**
* Returns integer if char is a digit, 0 otherwise
*/
static unsigned int inputCharToInt(char c);
static mask inputCharToMask(char c);
/**
* Returns 1-based integer from mask if only one bit is set, 0 otherwise
*/
static unsigned int getIntFromMask(mask m);
/**
* Returns true if only one bit is set, false otherwise
*/
static bool isOnlyOneBit(mask m);
/**
* Returns true if bit of 1-based integer _i_ is set, false otherwise
*/
static bool isBitSet(mask m, unsigned int i);
/**
* Returns number of set bits in mask
*/
static unsigned int countBits(mask m);
/**
* Returns log2 of a number if it is a multiple of 2
*
* log2 expects mask to have only 1 bit set.
* Otherwise, the position (log2) of the LSB of m is returned,
* or 0 if no bits are set.
*/
static unsigned int log2(mask m);
/**
* Returns mask where a single bit for a 1-based integer is set
*/
static mask getMaskFromInt(unsigned int i);
/**
* Returns mask where a single bit is not set
*
* Corresponds to bitwise_not(getMaskFromInt).
*/
static mask getNotMask(unsigned int i);
Parser(std::string inputString);
~Parser() {}
int parse();
mask * getBoard() { return unsolvedBoard; }
};
#endif
| 24.189189 | 80 | 0.56257 | ultinate |
844d895ad5e0be173061f99795e753e96c4c03ef | 6,588 | cc | C++ | cpp/src/arrow/tensor/coo_converter.cc | palmerlao/arrow | 4e680c46ad5aa76ba1dc85574c4e96a51450364f | [
"Apache-2.0"
] | null | null | null | cpp/src/arrow/tensor/coo_converter.cc | palmerlao/arrow | 4e680c46ad5aa76ba1dc85574c4e96a51450364f | [
"Apache-2.0"
] | 2 | 2020-03-12T14:31:34.000Z | 2020-03-26T22:46:19.000Z | cpp/src/arrow/tensor/coo_converter.cc | palmerlao/arrow | 4e680c46ad5aa76ba1dc85574c4e96a51450364f | [
"Apache-2.0"
] | 2 | 2020-12-28T16:59:24.000Z | 2021-02-21T12:33:41.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.
#include "arrow/tensor/converter.h"
#include <cstdint>
#include <memory>
#include <vector>
#include "arrow/buffer.h"
#include "arrow/status.h"
#include "arrow/type.h"
#include "arrow/util/checked_cast.h"
#include "arrow/visitor_inline.h"
namespace arrow {
class MemoryPool;
namespace internal {
namespace {
inline void IncrementIndex(std::vector<int64_t>& coord,
const std::vector<int64_t>& shape) {
const int64_t ndim = shape.size();
++coord[ndim - 1];
if (coord[ndim - 1] == shape[ndim - 1]) {
int64_t d = ndim - 1;
while (d > 0 && coord[d] == shape[d]) {
coord[d] = 0;
++coord[d - 1];
--d;
}
}
}
// ----------------------------------------------------------------------
// SparseTensorConverter for SparseCOOIndex
template <typename TYPE>
class SparseCOOTensorConverter {
public:
using NumericTensorType = NumericTensor<TYPE>;
using value_type = typename NumericTensorType::value_type;
SparseCOOTensorConverter(const NumericTensorType& tensor,
const std::shared_ptr<DataType>& index_value_type,
MemoryPool* pool)
: tensor_(tensor), index_value_type_(index_value_type), pool_(pool) {}
template <typename IndexValueType>
Status Convert() {
using c_index_value_type = typename IndexValueType::c_type;
const int64_t indices_elsize = sizeof(c_index_value_type);
const int64_t ndim = tensor_.ndim();
int64_t nonzero_count = -1;
RETURN_NOT_OK(tensor_.CountNonZero(&nonzero_count));
std::shared_ptr<Buffer> indices_buffer;
RETURN_NOT_OK(
AllocateBuffer(pool_, indices_elsize * ndim * nonzero_count, &indices_buffer));
c_index_value_type* indices =
reinterpret_cast<c_index_value_type*>(indices_buffer->mutable_data());
std::shared_ptr<Buffer> values_buffer;
RETURN_NOT_OK(
AllocateBuffer(pool_, sizeof(value_type) * nonzero_count, &values_buffer));
value_type* values = reinterpret_cast<value_type*>(values_buffer->mutable_data());
if (ndim <= 1) {
const value_type* data = reinterpret_cast<const value_type*>(tensor_.raw_data());
const int64_t count = ndim == 0 ? 1 : tensor_.shape()[0];
for (int64_t i = 0; i < count; ++i, ++data) {
if (*data != 0) {
*indices++ = static_cast<c_index_value_type>(i);
*values++ = *data;
}
}
} else {
const std::vector<int64_t>& shape = tensor_.shape();
std::vector<int64_t> coord(ndim, 0); // The current logical coordinates
for (int64_t n = tensor_.size(); n > 0; n--) {
const value_type x = tensor_.Value(coord);
if (tensor_.Value(coord) != 0) {
*values++ = x;
// Write indices in row-major order.
for (int64_t i = 0; i < ndim; ++i) {
*indices++ = static_cast<c_index_value_type>(coord[i]);
}
}
IncrementIndex(coord, shape);
}
}
// make results
const std::vector<int64_t> indices_shape = {nonzero_count, ndim};
const std::vector<int64_t> indices_strides = {indices_elsize * ndim, indices_elsize};
sparse_index = std::make_shared<SparseCOOIndex>(std::make_shared<Tensor>(
index_value_type_, indices_buffer, indices_shape, indices_strides));
data = values_buffer;
return Status::OK();
}
#define CALL_TYPE_SPECIFIC_CONVERT(TYPE_CLASS) \
case TYPE_CLASS##Type::type_id: \
return Convert<TYPE_CLASS##Type>();
Status Convert() {
switch (index_value_type_->id()) {
ARROW_GENERATE_FOR_ALL_INTEGER_TYPES(CALL_TYPE_SPECIFIC_CONVERT);
// LCOV_EXCL_START: The following invalid causes program failure.
default:
return Status::TypeError("Unsupported SparseTensor index value type");
// LCOV_EXCL_STOP
}
}
#undef CALL_TYPE_SPECIFIC_CONVERT
std::shared_ptr<SparseCOOIndex> sparse_index;
std::shared_ptr<Buffer> data;
private:
const NumericTensorType& tensor_;
const std::shared_ptr<DataType>& index_value_type_;
MemoryPool* pool_;
};
template <typename TYPE>
Status MakeSparseCOOTensorFromTensor(const Tensor& tensor,
const std::shared_ptr<DataType>& index_value_type,
MemoryPool* pool,
std::shared_ptr<SparseIndex>* out_sparse_index,
std::shared_ptr<Buffer>* out_data) {
NumericTensor<TYPE> numeric_tensor(tensor.data(), tensor.shape(), tensor.strides());
SparseCOOTensorConverter<TYPE> converter(numeric_tensor, index_value_type, pool);
RETURN_NOT_OK(converter.Convert());
*out_sparse_index = checked_pointer_cast<SparseIndex>(converter.sparse_index);
*out_data = converter.data;
return Status::OK();
}
} // namespace
#define MAKE_SPARSE_TENSOR_FROM_TENSOR(TYPE_CLASS) \
case TYPE_CLASS##Type::type_id: \
return MakeSparseCOOTensorFromTensor<TYPE_CLASS##Type>( \
tensor, index_value_type, pool, out_sparse_index, out_data);
Status MakeSparseCOOTensorFromTensor(const Tensor& tensor,
const std::shared_ptr<DataType>& index_value_type,
MemoryPool* pool,
std::shared_ptr<SparseIndex>* out_sparse_index,
std::shared_ptr<Buffer>* out_data) {
switch (tensor.type()->id()) {
ARROW_GENERATE_FOR_ALL_NUMERIC_TYPES(MAKE_SPARSE_TENSOR_FROM_TENSOR);
// LCOV_EXCL_START: ignore program failure
default:
return Status::TypeError("Unsupported Tensor value type");
// LCOV_EXCL_STOP
}
}
#undef MAKE_SPARSE_TENSOR_FROM_TENSOR
} // namespace internal
} // namespace arrow
| 35.419355 | 89 | 0.653764 | palmerlao |
844ffcbf7bce6ec7d4cd785e9fbcf199bab776e1 | 1,602 | cpp | C++ | cpp/cpp1/staff/staff.cpp | AlexanderE12345/codeexamples | 32a32a2512f781a90d737990462282ed35881607 | [
"Apache-2.0"
] | 6 | 2021-06-30T20:53:34.000Z | 2022-03-03T04:08:47.000Z | cpp/cpp1/staff/staff.cpp | AlexanderE12345/codeexamples | 32a32a2512f781a90d737990462282ed35881607 | [
"Apache-2.0"
] | null | null | null | cpp/cpp1/staff/staff.cpp | AlexanderE12345/codeexamples | 32a32a2512f781a90d737990462282ed35881607 | [
"Apache-2.0"
] | 11 | 2020-06-23T05:58:26.000Z | 2022-01-22T01:26:49.000Z | // Adapted from an example from Java Foundations
// by John Lewis, Peter DePasquale, & Joe Chase
#include<iostream>
#include<vector>
#include"staffmember.hpp"
#include"salaried.hpp"
#include"hourly.hpp"
#include"volunteer.hpp"
using namespace std;
void print_paystub(const StaffMember * s) {
s->print();
cout << "Current pay : " << s->pay() << endl;
}
int main() {
int counter = 0;
int totalPay = 0;
vector<StaffMember *> staff;
Salaried * bob = new Salaried("Bob Smith", "123 Main", "480-555-8756",
"111-22-3333", 50000);
Volunteer * alice = new Volunteer("Alice Jenkins", "456 4th", "480-555-2351");
Hourly * mitch = new Hourly("Mitch Jenkins", "456 4th", "480-555-2351",
"222-33-2222", 15, 30);
Salaried * john = new Salaried("John Franklin", "222 Bank", "480-555-2343",
"111-22-4444", 75000);
staff.push_back(bob);
staff.push_back(alice);
staff.push_back(mitch);
staff.push_back(john);
for (const StaffMember *s : staff) {
cout << endl << "Employee " << counter << ": " << endl;
print_paystub(s);
totalPay = totalPay + s->pay();
cout << "Bonus: " << s->bonus(500) << endl;
counter ++;
}
cout << endl << "Total payroll: " << totalPay << endl;
cout << endl << "Special bonus for John = " << john->bonus(500);
cout << endl << "Special bonus for Mitch = " << mitch->bonus(500);
cout << endl << "Special bonus for Alice = " << alice->bonus(500) << endl;
return 0;
}
| 29.127273 | 83 | 0.561798 | AlexanderE12345 |
84519821fbf22ef34c7456d85b821515cc453270 | 204 | hpp | C++ | src/cpu.hpp | AsuMagic/fusiongb | b2b61ed3c14bc96d50216d07442a4d5c7c518f6e | [
"MIT"
] | null | null | null | src/cpu.hpp | AsuMagic/fusiongb | b2b61ed3c14bc96d50216d07442a4d5c7c518f6e | [
"MIT"
] | null | null | null | src/cpu.hpp | AsuMagic/fusiongb | b2b61ed3c14bc96d50216d07442a4d5c7c518f6e | [
"MIT"
] | null | null | null | #ifndef CPU_HPP
#define CPU_HPP
#include "register.hpp"
#include <vector>
namespace fusion
{
struct CPU
{
RegisterFile _regs;
std::vector<uint8_t> _ram;
CPU();
void loop();
};
}
#endif // CPU_HPP
| 10.2 | 27 | 0.691176 | AsuMagic |
8453c5120cc662e441dc0623be23a50cc781afd8 | 7,137 | cc | C++ | chrome/browser/ash/login/ui/oobe_dialog_size_utils_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | chrome/browser/ash/login/ui/oobe_dialog_size_utils_unittest.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | chrome/browser/ash/login/ui/oobe_dialog_size_utils_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/login/ui/oobe_dialog_size_utils.h"
#include <stddef.h>
#include "base/macros.h"
#include "base/test/scoped_feature_list.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
namespace ash {
namespace {
constexpr int kShelfHeight = 56;
constexpr int kVirtualKeyboardHeight = 280;
constexpr int kDockedMagnifierHeight = 235;
} // namespace
class OobeDialogSizeUtilsTest : public testing::Test {
public:
OobeDialogSizeUtilsTest() = default;
OobeDialogSizeUtilsTest(const OobeDialogSizeUtilsTest&) = delete;
OobeDialogSizeUtilsTest& operator=(const OobeDialogSizeUtilsTest&) = delete;
~OobeDialogSizeUtilsTest() override = default;
void ValidateDialog(const gfx::Rect& display,
const gfx::Rect& area,
const gfx::Rect& dialog) {
// Dialog should fully fit into the area.
EXPECT_TRUE(area.Contains(dialog));
// Dialog is centered in area.
EXPECT_EQ(area.CenterPoint(), dialog.CenterPoint());
const gfx::Size min_dialog_size = GetMinDialogSize(display);
const gfx::Size max_dialog_size = GetMaxDialogSize(display);
EXPECT_LE(dialog.width(), max_dialog_size.width());
EXPECT_LE(dialog.height(), max_dialog_size.height());
// If there is at least some space, we should have margins.
const gfx::Size margins = ExpectedMargins(display.size());
if (dialog.width() > min_dialog_size.width()) {
EXPECT_EQ(dialog.x() + (area.right() - dialog.right()), margins.width());
}
if (dialog.height() > min_dialog_size.height()) {
EXPECT_EQ(dialog.y() + (area.bottom() - dialog.bottom()),
margins.height());
}
// If dialog size is lesser than minimum size, there should be no margins
if (dialog.width() < min_dialog_size.width()) {
EXPECT_EQ(dialog.x(), area.x());
EXPECT_EQ(dialog.right(), area.right());
}
if (dialog.height() < min_dialog_size.height()) {
EXPECT_EQ(dialog.y(), area.y());
EXPECT_EQ(dialog.bottom(), area.bottom());
}
}
gfx::Size GetMinDialogSize(const gfx::Rect& display) {
if (IsHorizontal(display)) {
return kMinLandscapeDialogSize;
}
return kMinPortraitDialogSize;
}
gfx::Size GetMaxDialogSize(const gfx::Rect& display) {
if (IsHorizontal(display)) {
return kMaxLandscapeDialogSize;
}
return kMaxPortraitDialogSize;
}
gfx::Size ExpectedMargins(const gfx::Size& display_size) {
gfx::Size margin = ScaleToCeiledSize(display_size, 0.08);
gfx::Size margins = margin + margin;
margins.SetToMax(kMinMargins.size());
return margins;
}
gfx::Rect SizeWithoutShelf(const gfx::Rect& area) const {
return gfx::Rect(area.width(), area.height() - kShelfHeight);
}
gfx::Rect SizeWithoutKeyboard(const gfx::Rect& area) const {
return gfx::Rect(area.width(), area.height() - kVirtualKeyboardHeight);
}
gfx::Rect SizeWithoutDockedMagnifier(const gfx::Rect& area) const {
return gfx::Rect(area.width(), area.height() - kDockedMagnifierHeight);
}
bool IsHorizontal(const gfx::Rect& area) const {
return area.width() > area.height();
}
private:
base::test::ScopedFeatureList feature_list_;
};
// We have plenty of space on the screen.
TEST_F(OobeDialogSizeUtilsTest, Chromebook) {
gfx::Rect usual_device(1200, 800);
gfx::Rect dialog;
OobeDialogPaddingMode padding;
CalculateOobeDialogBounds(usual_device, kShelfHeight,
IsHorizontal(usual_device), &dialog, &padding);
ValidateDialog(usual_device, SizeWithoutShelf(usual_device), dialog);
}
// We have plenty of space on the screen, but virtual keyboard takes some space.
TEST_F(OobeDialogSizeUtilsTest, ChromebookVirtualKeyboard) {
gfx::Rect usual_device(1200, 800);
gfx::Rect dialog;
OobeDialogPaddingMode padding;
CalculateOobeDialogBounds(SizeWithoutKeyboard(usual_device), 0,
IsHorizontal(usual_device), &dialog, &padding);
ValidateDialog(usual_device, SizeWithoutKeyboard(usual_device), dialog);
}
// Tablet device can have smaller screen size.
TEST_F(OobeDialogSizeUtilsTest, TabletHorizontal) {
gfx::Rect tablet_device(1080, 675);
gfx::Rect dialog;
OobeDialogPaddingMode padding;
CalculateOobeDialogBounds(tablet_device, kShelfHeight,
IsHorizontal(tablet_device), &dialog, &padding);
ValidateDialog(tablet_device, SizeWithoutShelf(tablet_device), dialog);
}
// Tablet device in horizontal mode with virtual keyboard have restricted
// vertical space.
TEST_F(OobeDialogSizeUtilsTest, TabletHorizontalVirtualKeyboard) {
gfx::Rect tablet_device(1080, 675);
gfx::Rect dialog;
OobeDialogPaddingMode padding;
CalculateOobeDialogBounds(SizeWithoutKeyboard(tablet_device), 0,
IsHorizontal(tablet_device), &dialog, &padding);
ValidateDialog(tablet_device, SizeWithoutKeyboard(tablet_device), dialog);
}
// Tablet device in horizontal mode with docked magnifier have restricted
// vertical space.
TEST_F(OobeDialogSizeUtilsTest, TabletHorizontalDockedMagnifier) {
gfx::Rect tablet_device(1080, 675);
gfx::Rect dialog;
OobeDialogPaddingMode padding;
CalculateOobeDialogBounds(SizeWithoutDockedMagnifier(tablet_device), 0,
IsHorizontal(tablet_device), &dialog, &padding);
ValidateDialog(tablet_device, SizeWithoutDockedMagnifier(tablet_device),
dialog);
}
// Tablet device in horizontal mode with virtual keyboard and docked
// magnifier results in very few vertical space.
TEST_F(OobeDialogSizeUtilsTest, TabletHorizontalVirtualKeyboardMagnifier) {
gfx::Rect tablet_device(1080, 675);
gfx::Rect dialog;
OobeDialogPaddingMode padding;
CalculateOobeDialogBounds(
SizeWithoutDockedMagnifier(SizeWithoutKeyboard(tablet_device)), 0,
IsHorizontal(tablet_device), &dialog, &padding);
ValidateDialog(tablet_device,
SizeWithoutDockedMagnifier(SizeWithoutKeyboard(tablet_device)),
dialog);
}
// Tablet in vertical mode puts some strain on dialog width.
TEST_F(OobeDialogSizeUtilsTest, ChromeTabVertical) {
gfx::Rect tablet_device(461, 738);
gfx::Rect dialog;
OobeDialogPaddingMode padding;
CalculateOobeDialogBounds(tablet_device, kShelfHeight,
IsHorizontal(tablet_device), &dialog, &padding);
ValidateDialog(tablet_device, SizeWithoutShelf(tablet_device), dialog);
}
// Tablet in horizontal mode puts some strain on dialog width.
TEST_F(OobeDialogSizeUtilsTest, ChromeTabHorizontal) {
gfx::Rect tablet_device(738, 461);
gfx::Rect dialog;
OobeDialogPaddingMode padding;
CalculateOobeDialogBounds(tablet_device, kShelfHeight,
IsHorizontal(tablet_device), &dialog, &padding);
ValidateDialog(tablet_device, SizeWithoutShelf(tablet_device), dialog);
}
} // namespace ash
| 34.645631 | 80 | 0.71935 | Yannic |
8456d78544fc118b2adea2da78e6a41cef92e433 | 754 | cpp | C++ | PAT (Advanced Level) Practice/1002.cpp | geek-LHW/PAT | f128f5977569f73c3c0b59cf0397bd94f9dfb205 | [
"Apache-2.0"
] | null | null | null | PAT (Advanced Level) Practice/1002.cpp | geek-LHW/PAT | f128f5977569f73c3c0b59cf0397bd94f9dfb205 | [
"Apache-2.0"
] | null | null | null | PAT (Advanced Level) Practice/1002.cpp | geek-LHW/PAT | f128f5977569f73c3c0b59cf0397bd94f9dfb205 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<iomanip>
using namespace std;
int main(){
double Poly[1001] = {0};
//多项式A
int k;
scanf("%d", &k);
for (int i = 0; i < k;i++){
int exp;
double coef;
scanf("%d%lf", &exp, &coef);
Poly[exp] = coef;
}
//多项式B
scanf("%d", &k);
for (int i = 0; i < k;i++){
int exp;
double coef;
scanf("%d%lf", &exp, &coef);
Poly[exp] += coef;
}
//统计多项式非零项
int num = 0;
for (int i = 0; i <1001;i++){
if(Poly[i]!=0){
num++;
}
}
printf("%d", num);
//打印
for (int i = 1000; i >=0;i--){
if(Poly[i]!=0){
printf(" %d %0.1f", i,Poly[i]);
}
}
return 0;
} | 19.333333 | 43 | 0.393899 | geek-LHW |
84593272e14b93a23e689a04a278d7fed7a0b512 | 24,379 | cpp | C++ | musicplayer/plugins/openmptplugin/openmpt/soundlib/tuning.cpp | Osmose/moseamp | 8357daf2c93bc903c8041cc82bf3567e8d085a60 | [
"MIT"
] | 6 | 2017-04-19T19:06:03.000Z | 2022-01-11T14:44:14.000Z | plugins/openmptplugin/openmpt/soundlib/tuning.cpp | sasq64/musicplayer | 372852c2f4e3231a09db2628fc4b7e7c2bfeec67 | [
"MIT"
] | 4 | 2018-04-04T20:27:32.000Z | 2020-04-25T10:46:21.000Z | musicplayer/plugins/openmptplugin/openmpt/soundlib/tuning.cpp | Osmose/moseamp | 8357daf2c93bc903c8041cc82bf3567e8d085a60 | [
"MIT"
] | 2 | 2018-06-08T15:20:48.000Z | 2020-08-19T14:24:21.000Z | /*
* tuning.cpp
* ----------
* Purpose: Alternative sample tuning.
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "tuning.h"
#include "../common/mptIO.h"
#include "../common/serialization_utils.h"
#include "../common/misc_util.h"
#include <string>
#include <cmath>
OPENMPT_NAMESPACE_BEGIN
namespace Tuning {
namespace CTuningS11n
{
void ReadStr(std::istream& iStrm, std::string& str, const size_t);
void ReadNoteMap(std::istream& iStrm, std::map<NOTEINDEXTYPE, std::string>& m, const size_t);
void ReadRatioTable(std::istream& iStrm, std::vector<RATIOTYPE>& v, const size_t);
void WriteNoteMap(std::ostream& oStrm, const std::map<NOTEINDEXTYPE, std::string>& m);
void WriteStr(std::ostream& oStrm, const std::string& str);
struct RatioWriter
{
RatioWriter(uint16 nWriteCount = s_nDefaultWriteCount) : m_nWriteCount(nWriteCount) {}
void operator()(std::ostream& oStrm, const std::vector<float>& v);
uint16 m_nWriteCount;
enum : uint16 { s_nDefaultWriteCount = (uint16_max >> 2) };
};
}
using namespace CTuningS11n;
/*
Version changes:
3->4: Finetune related internal structure and serialization revamp.
2->3: The type for the size_type in the serialisation changed
from default(size_t, uint32) to unsigned STEPTYPE. (March 2007)
*/
MPT_STATIC_ASSERT(CTuningRTI::s_RatioTableFineSizeMaxDefault < static_cast<USTEPINDEXTYPE>(FINESTEPCOUNT_MAX));
CTuningRTI::CTuningRTI()
: m_TuningType(TT_GENERAL)
, m_FineStepCount(0)
{
{
m_RatioTable.clear();
m_StepMin = s_StepMinDefault;
m_RatioTable.resize(s_RatioTableSizeDefault, 1);
m_GroupSize = 0;
m_GroupRatio = 0;
m_RatioTableFine.clear();
}
}
bool CTuningRTI::ProCreateGroupGeometric(const std::vector<RATIOTYPE>& v, const RATIOTYPE& r, const VRPAIR& vr, const NOTEINDEXTYPE& ratiostartpos)
{
if(v.size() == 0
|| r <= 0
|| vr.second < vr.first
|| ratiostartpos < vr.first)
{
return true;
}
m_StepMin = vr.first;
m_GroupSize = mpt::saturate_cast<NOTEINDEXTYPE>(v.size());
m_GroupRatio = std::fabs(r);
m_RatioTable.resize(vr.second-vr.first+1);
std::copy(v.begin(), v.end(), m_RatioTable.begin() + (ratiostartpos - vr.first));
for(int32 i = ratiostartpos-1; i>=m_StepMin && ratiostartpos > NOTEINDEXTYPE_MIN; i--)
{
m_RatioTable[i-m_StepMin] = m_RatioTable[i - m_StepMin + m_GroupSize] / m_GroupRatio;
}
for(int32 i = ratiostartpos+m_GroupSize; i<=vr.second && ratiostartpos <= (NOTEINDEXTYPE_MAX - m_GroupSize); i++)
{
m_RatioTable[i-m_StepMin] = m_GroupRatio * m_RatioTable[i - m_StepMin - m_GroupSize];
}
return false;
}
bool CTuningRTI::ProCreateGeometric(const UNOTEINDEXTYPE& s, const RATIOTYPE& r, const VRPAIR& vr)
{
if(vr.second - vr.first + 1 > NOTEINDEXTYPE_MAX) return true;
//Note: Setting finestep is handled by base class when CreateGeometric is called.
{
m_RatioTable.clear();
m_StepMin = s_StepMinDefault;
m_RatioTable.resize(s_RatioTableSizeDefault, static_cast<RATIOTYPE>(1.0));
m_GroupSize = 0;
m_GroupRatio = 0;
m_RatioTableFine.clear();
}
m_StepMin = vr.first;
m_GroupSize = mpt::saturate_cast<NOTEINDEXTYPE>(s);
m_GroupRatio = std::fabs(r);
const RATIOTYPE stepRatio = std::pow(m_GroupRatio, static_cast<RATIOTYPE>(1.0)/ static_cast<RATIOTYPE>(m_GroupSize));
m_RatioTable.resize(vr.second - vr.first + 1);
for(int32 i = vr.first; i<=vr.second; i++)
{
m_RatioTable[i-m_StepMin] = std::pow(stepRatio, static_cast<RATIOTYPE>(i));
}
return false;
}
std::string CTuningRTI::GetNoteName(const NOTEINDEXTYPE& x, bool addOctave) const
{
if(!IsValidNote(x))
{
return std::string();
}
if(GetGroupSize() < 1)
{
const auto i = m_NoteNameMap.find(x);
if(i != m_NoteNameMap.end())
return i->second;
else
return mpt::fmt::val(x);
}
else
{
const NOTEINDEXTYPE pos = static_cast<NOTEINDEXTYPE>(mpt::wrapping_modulo(x, m_GroupSize));
const NOTEINDEXTYPE middlePeriodNumber = 5;
std::string rValue;
const auto nmi = m_NoteNameMap.find(pos);
if(nmi != m_NoteNameMap.end())
{
rValue = nmi->second;
if(addOctave)
{
rValue += mpt::fmt::val(middlePeriodNumber + mpt::wrapping_divide(x, m_GroupSize));
}
}
else
{
//By default, using notation nnP for notes; nn <-> note character starting
//from 'A' with char ':' as fill char, and P is period integer. For example:
//C:5, D:3, R:7
if(m_GroupSize <= 26)
{
rValue = std::string(1, static_cast<char>(pos + 'A'));
rValue += ":";
} else
{
rValue = mpt::fmt::HEX0<1>(pos % 16) + mpt::fmt::HEX0<1>((pos / 16) % 16);
if(pos > 0xff)
{
rValue = mpt::ToLowerCaseAscii(rValue);
}
}
if(addOctave)
{
rValue += mpt::fmt::val(middlePeriodNumber + mpt::wrapping_divide(x, m_GroupSize));
}
}
return rValue;
}
}
const RATIOTYPE CTuningRTI::s_DefaultFallbackRatio = 1.0f;
//Without finetune
RATIOTYPE CTuningRTI::GetRatio(const NOTEINDEXTYPE& stepsFromCentre) const
{
if(stepsFromCentre < m_StepMin) return s_DefaultFallbackRatio;
if(stepsFromCentre >= m_StepMin + static_cast<NOTEINDEXTYPE>(m_RatioTable.size())) return s_DefaultFallbackRatio;
return m_RatioTable[stepsFromCentre - m_StepMin];
}
//With finetune
RATIOTYPE CTuningRTI::GetRatio(const NOTEINDEXTYPE& baseNote, const STEPINDEXTYPE& baseStepDiff) const
{
const STEPINDEXTYPE fsCount = static_cast<STEPINDEXTYPE>(GetFineStepCount());
if(fsCount < 0 || fsCount > FINESTEPCOUNT_MAX)
{
return s_DefaultFallbackRatio;
}
if(fsCount == 0 || baseStepDiff == 0)
{
return GetRatio(static_cast<NOTEINDEXTYPE>(baseNote + baseStepDiff));
}
//If baseStepDiff is more than the number of finesteps between notes,
//note is increased. So first figuring out what step and fineStep values to
//actually use. Interpreting finestep -1 on note x so that it is the same as
//finestep GetFineStepCount() on note x-1.
//Note: If finestepcount is n, n+1 steps are needed to get to
//next note.
NOTEINDEXTYPE note;
STEPINDEXTYPE fineStep;
note = static_cast<NOTEINDEXTYPE>(baseNote + mpt::wrapping_divide(baseStepDiff, (fsCount+1)));
fineStep = mpt::wrapping_modulo(baseStepDiff, (fsCount+1));
if(note < m_StepMin) return s_DefaultFallbackRatio;
if(note >= m_StepMin + static_cast<NOTEINDEXTYPE>(m_RatioTable.size())) return s_DefaultFallbackRatio;
if(fineStep) return m_RatioTable[note - m_StepMin] * GetRatioFine(note, fineStep);
else return m_RatioTable[note - m_StepMin];
}
RATIOTYPE CTuningRTI::GetRatioFine(const NOTEINDEXTYPE& note, USTEPINDEXTYPE sd) const
{
if(GetFineStepCount() <= 0 || GetFineStepCount() > static_cast<USTEPINDEXTYPE>(FINESTEPCOUNT_MAX))
{
return s_DefaultFallbackRatio;
}
//Neither of these should happen.
if(sd <= 0) sd = 1;
if(sd > GetFineStepCount()) sd = GetFineStepCount();
if(GetType() != TT_GENERAL && m_RatioTableFine.size() > 0) //Taking fineratio from table
{
if(GetType() == TT_GEOMETRIC)
{
return m_RatioTableFine[sd-1];
}
if(GetType() == TT_GROUPGEOMETRIC)
return m_RatioTableFine[GetRefNote(note) * GetFineStepCount() + sd - 1];
MPT_ASSERT_NOTREACHED();
return m_RatioTableFine[0]; //Shouldn't happen.
}
else //Calculating ratio 'on the fly'.
{
//'Geometric finestepping'.
return std::pow(GetRatio(note+1) / GetRatio(note), static_cast<RATIOTYPE>(sd)/(GetFineStepCount()+1));
}
}
bool CTuningRTI::SetRatio(const NOTEINDEXTYPE& s, const RATIOTYPE& r)
{
if(GetType() != TT_GROUPGEOMETRIC && GetType() != TT_GENERAL)
{
return false;
}
//Creating ratio table if doesn't exist.
if(m_RatioTable.empty())
{
m_RatioTable.assign(s_RatioTableSizeDefault, 1);
m_StepMin = s_StepMinDefault;
}
if(!IsNoteInTable(s))
{
return false;
}
m_RatioTable[s - m_StepMin] = std::fabs(r);
if(GetType() == TT_GROUPGEOMETRIC)
{ // update other groups
for(NOTEINDEXTYPE n = m_StepMin; n < m_StepMin + static_cast<NOTEINDEXTYPE>(m_RatioTable.size()); ++n)
{
if(n == s)
{
// nothing
} else if(mpt::abs(n - s) % m_GroupSize == 0)
{
m_RatioTable[n - m_StepMin] = std::pow(m_GroupRatio, static_cast<RATIOTYPE>(n - s) / static_cast<RATIOTYPE>(m_GroupSize)) * m_RatioTable[s - m_StepMin];
}
}
UpdateFineStepTable();
}
return true;
}
void CTuningRTI::SetFineStepCount(const USTEPINDEXTYPE& fs)
{
m_FineStepCount = mpt::clamp(mpt::saturate_cast<STEPINDEXTYPE>(fs), STEPINDEXTYPE(0), FINESTEPCOUNT_MAX);
UpdateFineStepTable();
}
void CTuningRTI::UpdateFineStepTable()
{
if(m_FineStepCount <= 0)
{
m_RatioTableFine.clear();
return;
}
if(GetType() == TT_GEOMETRIC)
{
if(m_FineStepCount > s_RatioTableFineSizeMaxDefault)
{
m_RatioTableFine.clear();
return;
}
m_RatioTableFine.resize(m_FineStepCount);
const RATIOTYPE q = GetRatio(GetValidityRange().first + 1) / GetRatio(GetValidityRange().first);
const RATIOTYPE rFineStep = std::pow(q, static_cast<RATIOTYPE>(1)/(m_FineStepCount+1));
for(USTEPINDEXTYPE i = 1; i<=m_FineStepCount; i++)
m_RatioTableFine[i-1] = std::pow(rFineStep, static_cast<RATIOTYPE>(i));
return;
}
if(GetType() == TT_GROUPGEOMETRIC)
{
const UNOTEINDEXTYPE p = GetGroupSize();
if(p > s_RatioTableFineSizeMaxDefault / m_FineStepCount)
{
//In case fineratiotable would become too large, not using
//table for it.
m_RatioTableFine.clear();
return;
}
else
{
//Creating 'geometric' finestepping between notes.
m_RatioTableFine.resize(p * m_FineStepCount);
const NOTEINDEXTYPE startnote = GetRefNote(GetValidityRange().first);
for(UNOTEINDEXTYPE i = 0; i<p; i++)
{
const NOTEINDEXTYPE refnote = GetRefNote(startnote+i);
const RATIOTYPE rFineStep = std::pow(GetRatio(refnote+1) / GetRatio(refnote), static_cast<RATIOTYPE>(1)/(m_FineStepCount+1));
for(UNOTEINDEXTYPE j = 1; j<=m_FineStepCount; j++)
{
m_RatioTableFine[m_FineStepCount * refnote + (j-1)] = std::pow(rFineStep, static_cast<RATIOTYPE>(j));
}
}
return;
}
}
if(GetType() == TT_GENERAL)
{
//Not using table with tuning of type general.
m_RatioTableFine.clear();
return;
}
//Should not reach here.
m_RatioTableFine.clear();
m_FineStepCount = 0;
}
NOTEINDEXTYPE CTuningRTI::GetRefNote(const NOTEINDEXTYPE note) const
{
if((GetType() != TT_GROUPGEOMETRIC) && (GetType() != TT_GEOMETRIC)) return 0;
return static_cast<NOTEINDEXTYPE>(mpt::wrapping_modulo(note, GetGroupSize()));
}
SerializationResult CTuningRTI::InitDeserialize(std::istream& iStrm)
{
// Note: OpenMPT since at least r323 writes version number (4<<24)+4 while it
// reads version number (5<<24)+4 or earlier.
// We keep this behaviour.
if(iStrm.fail())
return SerializationResult::Failure;
srlztn::SsbRead ssb(iStrm);
ssb.BeginRead("CTB244RTI", (5 << 24) + 4); // version
ssb.ReadItem(m_TuningName, "0", ReadStr);
uint16 dummyEditMask = 0xffff;
ssb.ReadItem(dummyEditMask, "1");
ssb.ReadItem(m_TuningType, "2");
ssb.ReadItem(m_NoteNameMap, "3", ReadNoteMap);
ssb.ReadItem(m_FineStepCount, "4");
// RTI entries.
ssb.ReadItem(m_RatioTable, "RTI0", ReadRatioTable);
ssb.ReadItem(m_StepMin, "RTI1");
ssb.ReadItem(m_GroupSize, "RTI2");
ssb.ReadItem(m_GroupRatio, "RTI3");
UNOTEINDEXTYPE ratiotableSize = 0;
ssb.ReadItem(ratiotableSize, "RTI4");
// If reader status is ok and m_StepMin is somewhat reasonable, process data.
if(!((ssb.GetStatus() & srlztn::SNT_FAILURE) == 0 && m_StepMin >= -300 && m_StepMin <= 300))
{
return SerializationResult::Failure;
}
// reject unknown types
if(m_TuningType != TT_GENERAL && m_TuningType != TT_GROUPGEOMETRIC && m_TuningType != TT_GEOMETRIC)
{
return SerializationResult::Failure;
}
if(m_GroupSize < 0)
{
return SerializationResult::Failure;
}
m_FineStepCount = mpt::clamp(mpt::saturate_cast<STEPINDEXTYPE>(m_FineStepCount), STEPINDEXTYPE(0), FINESTEPCOUNT_MAX);
if(m_RatioTable.size() > static_cast<size_t>(NOTEINDEXTYPE_MAX))
{
return SerializationResult::Failure;
}
if((GetType() == TT_GROUPGEOMETRIC) || (GetType() == TT_GEOMETRIC))
{
if(ratiotableSize < 1 || ratiotableSize > NOTEINDEXTYPE_MAX)
{
return SerializationResult::Failure;
}
if(GetType() == TT_GEOMETRIC)
{
if(CreateGeometric(GetGroupSize(), GetGroupRatio(), VRPAIR(m_StepMin, static_cast<NOTEINDEXTYPE>(m_StepMin + ratiotableSize - 1))) != false)
{
return SerializationResult::Failure;
}
} else
{
if(CreateGroupGeometric(m_RatioTable, GetGroupRatio(), VRPAIR(m_StepMin, static_cast<NOTEINDEXTYPE>(m_StepMin+ratiotableSize-1)), m_StepMin) != false)
{
return SerializationResult::Failure;
}
}
} else
{
UpdateFineStepTable();
}
return SerializationResult::Success;
}
template<class T, class SIZETYPE, class Tdst>
static bool VectorFromBinaryStream(std::istream& inStrm, std::vector<Tdst>& v, const SIZETYPE maxSize = (std::numeric_limits<SIZETYPE>::max)())
{
if(!inStrm.good()) return true;
SIZETYPE size = 0;
mpt::IO::ReadIntLE<SIZETYPE>(inStrm, size);
if(size > maxSize)
return true;
v.resize(size);
for(std::size_t i = 0; i<size; i++)
{
T tmp = T();
mpt::IO::Read(inStrm, tmp);
v[i] = tmp;
}
if(inStrm.good())
return false;
else
return true;
}
SerializationResult CTuningRTI::InitDeserializeOLD(std::istream& inStrm)
{
if(!inStrm.good())
return SerializationResult::Failure;
const std::streamoff startPos = inStrm.tellg();
//First checking is there expected begin sequence.
char begin[8];
MemsetZero(begin);
inStrm.read(begin, sizeof(begin));
if(std::memcmp(begin, "CTRTI_B.", 8))
{
//Returning stream position if beginmarker was not found.
inStrm.seekg(startPos);
return SerializationResult::Failure;
}
//Version
int16 version = 0;
mpt::IO::ReadIntLE<int16>(inStrm, version);
if(version != 2 && version != 3)
return SerializationResult::Failure;
char begin2[8];
MemsetZero(begin2);
inStrm.read(begin2, sizeof(begin2));
if(std::memcmp(begin2, "CT<sfs>B", 8))
{
return SerializationResult::Failure;
}
int16 version2 = 0;
mpt::IO::ReadIntLE<int16>(inStrm, version2);
if(version2 != 3 && version2 != 4)
{
return SerializationResult::Failure;
}
//Tuning name
if(version2 <= 3)
{
if(!mpt::IO::ReadSizedStringLE<uint32>(inStrm, m_TuningName, 0xffff))
{
return SerializationResult::Failure;
}
} else
{
if(!mpt::IO::ReadSizedStringLE<uint8>(inStrm, m_TuningName))
{
return SerializationResult::Failure;
}
}
//Const mask
int16 em = 0;
mpt::IO::ReadIntLE<int16>(inStrm, em);
//Tuning type
int16 tt = 0;
mpt::IO::ReadIntLE<int16>(inStrm, tt);
m_TuningType = tt;
//Notemap
uint16 size = 0;
if(version2 <= 3)
{
uint32 tempsize = 0;
mpt::IO::ReadIntLE<uint32>(inStrm, tempsize);
if(tempsize > 0xffff)
{
return SerializationResult::Failure;
}
size = mpt::saturate_cast<uint16>(tempsize);
} else
{
mpt::IO::ReadIntLE<uint16>(inStrm, size);
}
for(UNOTEINDEXTYPE i = 0; i<size; i++)
{
std::string str;
int16 n = 0;
mpt::IO::ReadIntLE<int16>(inStrm, n);
if(version2 <= 3)
{
if(!mpt::IO::ReadSizedStringLE<uint32>(inStrm, str, 0xffff))
{
return SerializationResult::Failure;
}
} else
{
if(!mpt::IO::ReadSizedStringLE<uint8>(inStrm, str))
{
return SerializationResult::Failure;
}
}
m_NoteNameMap[n] = str;
}
//End marker
char end2[8];
MemsetZero(end2);
inStrm.read(end2, sizeof(end2));
if(std::memcmp(end2, "CT<sfs>E", 8))
{
return SerializationResult::Failure;
}
// reject unknown types
if(m_TuningType != TT_GENERAL && m_TuningType != TT_GROUPGEOMETRIC && m_TuningType != TT_GEOMETRIC)
{
return SerializationResult::Failure;
}
//Ratiotable
if(version <= 2)
{
if(VectorFromBinaryStream<IEEE754binary32LE, uint32>(inStrm, m_RatioTable, 0xffff))
{
return SerializationResult::Failure;
}
} else
{
if(VectorFromBinaryStream<IEEE754binary32LE, uint16>(inStrm, m_RatioTable))
{
return SerializationResult::Failure;
}
}
//Fineratios
if(version <= 2)
{
if(VectorFromBinaryStream<IEEE754binary32LE, uint32>(inStrm, m_RatioTableFine, 0xffff))
{
return SerializationResult::Failure;
}
} else
{
if(VectorFromBinaryStream<IEEE754binary32LE, uint16>(inStrm, m_RatioTableFine))
{
return SerializationResult::Failure;
}
}
m_FineStepCount = mpt::saturate_cast<USTEPINDEXTYPE>(m_RatioTableFine.size());
//m_StepMin
int16 stepmin = 0;
mpt::IO::ReadIntLE<int16>(inStrm, stepmin);
m_StepMin = stepmin;
if(m_StepMin < -200 || m_StepMin > 200)
{
return SerializationResult::Failure;
}
//m_GroupSize
int16 groupsize = 0;
mpt::IO::ReadIntLE<int16>(inStrm, groupsize);
m_GroupSize = groupsize;
if(m_GroupSize < 0)
{
return SerializationResult::Failure;
}
//m_GroupRatio
IEEE754binary32LE groupratio = IEEE754binary32LE(0.0f);
mpt::IO::Read(inStrm, groupratio);
m_GroupRatio = groupratio;
if(m_GroupRatio < 0)
{
return SerializationResult::Failure;
}
char end[8];
MemsetZero(end);
inStrm.read(reinterpret_cast<char*>(&end), sizeof(end));
if(std::memcmp(end, "CTRTI_E.", 8))
{
return SerializationResult::Failure;
}
// reject corrupt tunings
if(m_RatioTable.size() > static_cast<std::size_t>(NOTEINDEXTYPE_MAX))
{
return SerializationResult::Failure;
}
if((m_GroupSize <= 0 || m_GroupRatio <= 0) && m_TuningType != TT_GENERAL)
{
return SerializationResult::Failure;
}
if(m_TuningType == TT_GROUPGEOMETRIC || m_TuningType == TT_GEOMETRIC)
{
if(m_RatioTable.size() < static_cast<std::size_t>(m_GroupSize))
{
return SerializationResult::Failure;
}
}
// convert old finestepcount
if(m_FineStepCount > 0)
{
m_FineStepCount -= 1;
}
m_FineStepCount = mpt::clamp(mpt::saturate_cast<STEPINDEXTYPE>(m_FineStepCount), STEPINDEXTYPE(0), FINESTEPCOUNT_MAX);
UpdateFineStepTable();
if(m_TuningType == TT_GEOMETRIC)
{
// Convert old geometric to new groupgeometric because old geometric tunings
// can have ratio(0) != 1.0, which would get lost when saving nowadays.
if(mpt::saturate_cast<NOTEINDEXTYPE>(m_RatioTable.size()) >= m_GroupSize - m_StepMin)
{
std::vector<RATIOTYPE> ratios;
for(NOTEINDEXTYPE n = 0; n < m_GroupSize; ++n)
{
ratios.push_back(m_RatioTable[n - m_StepMin]);
}
CreateGroupGeometric(ratios, m_GroupRatio, GetValidityRange(), 0);
}
}
return SerializationResult::Success;
}
Tuning::SerializationResult CTuningRTI::Serialize(std::ostream& outStrm) const
{
// Note: OpenMPT since at least r323 writes version number (4<<24)+4 while it
// reads version number (5<<24)+4.
// We keep this behaviour.
srlztn::SsbWrite ssb(outStrm);
ssb.BeginWrite("CTB244RTI", (4 << 24) + 4); // version
if (m_TuningName.length() > 0)
ssb.WriteItem(m_TuningName, "0", WriteStr);
uint16 dummyEditMask = 0xffff;
ssb.WriteItem(dummyEditMask, "1");
ssb.WriteItem(m_TuningType, "2");
if (m_NoteNameMap.size() > 0)
ssb.WriteItem(m_NoteNameMap, "3", WriteNoteMap);
if (GetFineStepCount() > 0)
ssb.WriteItem(m_FineStepCount, "4");
const TUNINGTYPE tt = GetType();
if (GetGroupRatio() > 0)
ssb.WriteItem(m_GroupRatio, "RTI3");
if (tt == TT_GROUPGEOMETRIC)
ssb.WriteItem(m_RatioTable, "RTI0", RatioWriter(GetGroupSize()));
if (tt == TT_GENERAL)
ssb.WriteItem(m_RatioTable, "RTI0", RatioWriter());
if (tt == TT_GEOMETRIC)
ssb.WriteItem(m_GroupSize, "RTI2");
if(tt == TT_GEOMETRIC || tt == TT_GROUPGEOMETRIC)
{ //For Groupgeometric this data is the number of ratios in ratiotable.
UNOTEINDEXTYPE ratiotableSize = static_cast<UNOTEINDEXTYPE>(m_RatioTable.size());
ssb.WriteItem(ratiotableSize, "RTI4");
}
//m_StepMin
ssb.WriteItem(m_StepMin, "RTI1");
ssb.FinishWrite();
return ((ssb.GetStatus() & srlztn::SNT_FAILURE) != 0) ? Tuning::SerializationResult::Failure : Tuning::SerializationResult::Success;
}
#ifdef MODPLUG_TRACKER
bool CTuningRTI::WriteSCL(std::ostream &f, const mpt::PathString &filename) const
{
mpt::IO::WriteTextCRLF(f, mpt::format("! %1")(mpt::ToCharset(mpt::CharsetISO8859_1, (filename.GetFileName() + filename.GetFileExt()).ToUnicode())));
mpt::IO::WriteTextCRLF(f, "!");
std::string name = mpt::ToCharset(mpt::CharsetISO8859_1, mpt::CharsetLocale, GetName());
for(auto & c : name) { if(static_cast<uint8>(c) < 32) c = ' '; } // remove control characters
if(name.length() >= 1 && name[0] == '!') name[0] = '?'; // do not confuse description with comment
mpt::IO::WriteTextCRLF(f, name);
if(GetType() == TT_GEOMETRIC)
{
mpt::IO::WriteTextCRLF(f, mpt::format(" %1")(m_GroupSize));
mpt::IO::WriteTextCRLF(f, "!");
for(NOTEINDEXTYPE n = 0; n < m_GroupSize; ++n)
{
double ratio = std::pow(static_cast<double>(m_GroupRatio), static_cast<double>(n + 1) / static_cast<double>(m_GroupSize));
double cents = std::log2(ratio) * 1200.0;
mpt::IO::WriteTextCRLF(f, mpt::format(" %1 ! %2")(
mpt::fmt::fix(cents),
mpt::ToCharset(mpt::CharsetISO8859_1, mpt::CharsetLocale, GetNoteName((n + 1) % m_GroupSize, false))
));
}
} else if(GetType() == TT_GROUPGEOMETRIC)
{
mpt::IO::WriteTextCRLF(f, mpt::format(" %1")(m_GroupSize));
mpt::IO::WriteTextCRLF(f, "!");
for(NOTEINDEXTYPE n = 0; n < m_GroupSize; ++n)
{
bool last = (n == (m_GroupSize - 1));
double baseratio = static_cast<double>(GetRatio(0));
double ratio = static_cast<double>(last ? m_GroupRatio : GetRatio(n + 1)) / baseratio;
double cents = std::log2(ratio) * 1200.0;
mpt::IO::WriteTextCRLF(f, mpt::format(" %1 ! %2")(
mpt::fmt::fix(cents),
mpt::ToCharset(mpt::CharsetISO8859_1, mpt::CharsetLocale, GetNoteName((n + 1) % m_GroupSize, false))
));
}
} else if(GetType() == TT_GENERAL)
{
mpt::IO::WriteTextCRLF(f, mpt::format(" %1")(m_RatioTable.size() + 1));
mpt::IO::WriteTextCRLF(f, "!");
double baseratio = 1.0;
for(NOTEINDEXTYPE n = 0; n < mpt::saturate_cast<NOTEINDEXTYPE>(m_RatioTable.size()); ++n)
{
baseratio = std::min(baseratio, static_cast<double>(m_RatioTable[n]));
}
for(NOTEINDEXTYPE n = 0; n < mpt::saturate_cast<NOTEINDEXTYPE>(m_RatioTable.size()); ++n)
{
double ratio = static_cast<double>(m_RatioTable[n]) / baseratio;
double cents = std::log2(ratio) * 1200.0;
mpt::IO::WriteTextCRLF(f, mpt::format(" %1 ! %2")(
mpt::fmt::fix(cents),
mpt::ToCharset(mpt::CharsetISO8859_1, mpt::CharsetLocale, GetNoteName(n + m_StepMin, false))
));
}
mpt::IO::WriteTextCRLF(f, mpt::format(" %1 ! %2")(
mpt::fmt::val(1),
std::string()
));
} else
{
return false;
}
return true;
}
#endif
namespace CTuningS11n
{
void RatioWriter::operator()(std::ostream& oStrm, const std::vector<float>& v)
{
const size_t nWriteCount = MIN(v.size(), m_nWriteCount);
mpt::IO::WriteAdaptiveInt64LE(oStrm, nWriteCount);
for(size_t i = 0; i < nWriteCount; i++)
mpt::IO::Write(oStrm, IEEE754binary32LE(v[i]));
}
void ReadNoteMap(std::istream& iStrm, std::map<NOTEINDEXTYPE,std::string>& m, const size_t)
{
uint64 val;
mpt::IO::ReadAdaptiveInt64LE(iStrm, val);
LimitMax(val, 256u); // Read 256 at max.
for(size_t i = 0; i < val; i++)
{
int16 key;
mpt::IO::ReadIntLE<int16>(iStrm, key);
std::string str;
mpt::IO::ReadSizedStringLE<uint8>(iStrm, str);
m[key] = str;
}
}
void ReadRatioTable(std::istream& iStrm, std::vector<RATIOTYPE>& v, const size_t)
{
uint64 val;
mpt::IO::ReadAdaptiveInt64LE(iStrm, val);
v.resize( static_cast<size_t>(MIN(val, 256u))); // Read 256 vals at max.
for(size_t i = 0; i < v.size(); i++)
{
IEEE754binary32LE tmp(0.0f);
mpt::IO::Read(iStrm, tmp);
v[i] = tmp;
}
}
void ReadStr(std::istream& iStrm, std::string& str, const size_t)
{
uint64 val;
mpt::IO::ReadAdaptiveInt64LE(iStrm, val);
size_t nSize = (val > 255) ? 255 : static_cast<size_t>(val); // Read 255 characters at max.
str.clear();
str.resize(nSize);
for(size_t i = 0; i < nSize; i++)
mpt::IO::ReadIntLE(iStrm, str[i]);
if(str.find_first_of('\0') != std::string::npos)
{ // trim \0 at the end
str.resize(str.find_first_of('\0'));
}
}
void WriteNoteMap(std::ostream& oStrm, const std::map<NOTEINDEXTYPE, std::string>& m)
{
mpt::IO::WriteAdaptiveInt64LE(oStrm, m.size());
for(auto &mi : m)
{
mpt::IO::WriteIntLE<int16>(oStrm, mi.first);
mpt::IO::WriteSizedStringLE<uint8>(oStrm, mi.second);
}
}
void WriteStr(std::ostream& oStrm, const std::string& str)
{
mpt::IO::WriteAdaptiveInt64LE(oStrm, str.size());
oStrm.write(str.c_str(), str.size());
}
} // namespace CTuningS11n.
} // namespace Tuning
OPENMPT_NAMESPACE_END
| 27.392135 | 156 | 0.696706 | Osmose |
845d3417b2378ac3b0e01da64d9a715a46e3fc65 | 2,957 | hpp | C++ | nvgl/appwindowprofiler_gl.hpp | theHamsta/nvpro_core | 46d28f10aac7f951256ed759cf47fc44615a4f81 | [
"Apache-2.0"
] | 123 | 2015-01-06T17:03:34.000Z | 2021-05-15T19:31:40.000Z | nvgl/appwindowprofiler_gl.hpp | theHamsta/nvpro_core | 46d28f10aac7f951256ed759cf47fc44615a4f81 | [
"Apache-2.0"
] | 21 | 2015-04-26T11:41:58.000Z | 2021-03-23T22:26:35.000Z | nvgl/appwindowprofiler_gl.hpp | theHamsta/nvpro_core | 46d28f10aac7f951256ed759cf47fc44615a4f81 | [
"Apache-2.0"
] | 59 | 2015-04-26T05:37:10.000Z | 2021-04-05T18:49:52.000Z | /*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. 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.
*
* SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef NV_WINDOWPROFILER_GL_INCLUDED
#define NV_WINDOWPROFILER_GL_INCLUDED
#include "contextwindow_gl.hpp"
#include "profiler_gl.hpp"
#include <nvh/appwindowprofiler.hpp>
//////////////////////////////////////////////////////////////////////////
/**
\class nvgl::AppWindowProfilerGL
nvgl::AppWindowProfilerGL derives from nvh::AppWindowProfiler
and overrides the context and swapbuffer functions.
To influence the context creation modify
`m_contextInfo` prior running AppWindowProfiler::run,
which triggers window, and context creation etc.
The class comes with a nvgl::ProfilerGL instance that references the
AppWindowProfiler::m_profiler's data.
*/
namespace nvgl {
#define NV_PROFILE_GL_SECTION(name) nvgl::ProfilerGL::Section _tempTimer(m_profilerGL, name)
#define NV_PROFILE_GL_SPLIT() m_profilerGL.accumulationSplit()
class AppWindowProfilerGL : public nvh::AppWindowProfiler
{
public:
AppWindowProfilerGL(bool singleThreaded = true)
: nvh::AppWindowProfiler(singleThreaded)
, m_profilerGL(&m_profiler)
{
m_contextInfo.robust = false;
m_contextInfo.core = false;
#ifdef NDEBUG
m_contextInfo.debug = false;
#else
m_contextInfo.debug = true;
#endif
m_contextInfo.share = NULL;
m_contextInfo.major = 4;
m_contextInfo.minor = 5;
}
nvgl::ContextWindowCreateInfo m_contextInfo;
ContextWindow m_contextWindow;
nvgl::ProfilerGL m_profilerGL;
int run(const std::string& name, int argc, const char** argv, int width, int height)
{
return AppWindowProfiler::run(name, argc, argv, width, height, true);
}
virtual void contextInit() override;
virtual void contextDeinit() override;
virtual void swapResize(int width, int height) override
{
m_windowState.m_swapSize[0] = width;
m_windowState.m_swapSize[1] = height;
}
virtual void swapPrepare() override {}
virtual void swapBuffers() override { m_contextWindow.swapBuffers(); }
virtual void swapVsync(bool state) override { m_contextWindow.swapInterval(state ? 1 : 0); }
virtual const char* contextGetDeviceName() override { return m_contextWindow.m_deviceName.c_str(); }
};
} // namespace nvgl
#endif
| 31.126316 | 102 | 0.722354 | theHamsta |
846108268d520df9571e9f0d4b2f924875875a55 | 76,927 | cpp | C++ | dwarf/SB/Core/x/xLaserBolt.cpp | stravant/bfbbdecomp | 2126be355a6bb8171b850f829c1f2731c8b5de08 | [
"OLDAP-2.7"
] | 1 | 2021-01-05T11:28:55.000Z | 2021-01-05T11:28:55.000Z | dwarf/SB/Core/x/xLaserBolt.cpp | sonich2401/bfbbdecomp | 5f58b62505f8929a72ccf2aa118a1539eb3a5bd6 | [
"OLDAP-2.7"
] | null | null | null | dwarf/SB/Core/x/xLaserBolt.cpp | sonich2401/bfbbdecomp | 5f58b62505f8929a72ccf2aa118a1539eb3a5bd6 | [
"OLDAP-2.7"
] | 1 | 2022-03-30T15:15:08.000Z | 2022-03-30T15:15:08.000Z | typedef struct static_queue_0;
typedef struct RwObjectHasFrame;
typedef struct RxPipelineNode;
typedef struct zEntHangable;
typedef struct static_queue_1;
typedef enum _zPlayerWallJumpState;
typedef struct RpPolygon;
typedef struct xVec3;
typedef struct xLaserBoltEmitter;
typedef struct xEnv;
typedef struct bolt;
typedef struct xMovePointAsset;
typedef struct RwV3d;
typedef struct xEnt;
typedef struct effect_data;
typedef struct RpGeometry;
typedef struct xAnimTable;
typedef struct xAnimPlay;
typedef struct xModelInstance;
typedef struct RpVertexNormal;
typedef struct zPlatform;
typedef struct rxHeapFreeBlock;
typedef struct xMovePoint;
typedef struct RwRaster;
typedef struct iEnv;
typedef struct RxPipelineNodeTopSortData;
typedef struct xAnimEffect;
typedef struct RwV2d;
typedef struct RwTexCoords;
typedef struct xBase;
typedef struct xGridBound;
typedef struct iterator;
typedef enum _tagRumbleType;
typedef struct RxNodeDefinition;
typedef struct _class_0;
typedef struct tagiRenderInput;
typedef enum _zPlayerType;
typedef struct xLightKit;
typedef struct xUpdateCullGroup;
typedef struct zCutsceneMgr;
typedef struct zEnt;
typedef struct xAnimSingle;
typedef struct RwRGBA;
typedef struct rxHeapSuperBlockDescriptor;
typedef struct xJSPNodeInfo;
typedef struct RwTexture;
typedef struct _tagEmitSphere;
typedef struct xAnimState;
typedef struct xEntMechData;
typedef struct RwResEntry;
typedef struct RxPipeline;
typedef struct xMat4x3;
typedef struct RxPipelineCluster;
typedef struct RxObjSpace3DVertex;
typedef struct xEntMotionSplineData;
typedef struct RxPipelineNodeParam;
typedef struct zAssetPickupTable;
typedef struct analog_data;
typedef struct RpMeshHeader;
typedef struct xSpline3;
typedef struct RxHeap;
typedef struct RwBBox;
typedef struct xMemPool;
typedef struct curve_node;
typedef struct xQuat;
typedef struct xGroup;
typedef struct RpTriangle;
typedef struct xEntBoulder;
typedef struct RpAtomic;
typedef struct xClumpCollBSPBranchNode;
typedef struct xEntShadow;
typedef struct rxHeapBlockHeader;
typedef struct xCollis;
typedef struct zCheckPoint;
typedef struct zPlayerGlobals;
typedef struct xModelPool;
typedef struct RxPipelineRequiresCluster;
typedef struct _tagEmitRect;
typedef struct xEntMotionMPData;
typedef struct xJSPHeader;
typedef struct xEntAsset;
typedef struct xEntERData;
typedef struct xUpdateCullMgr;
typedef struct zPlayerCarryInfo;
typedef struct xPortalAsset;
typedef enum fx_when_enum;
typedef struct zPlayerSettings;
typedef struct xScene;
typedef struct xCamera;
typedef struct xAnimFile;
typedef struct _zEnv;
typedef struct RpClump;
typedef struct xVec4;
typedef struct xSurface;
typedef struct xQCData;
typedef struct xCoef;
typedef struct RwSurfaceProperties;
typedef struct xClumpCollBSPTree;
typedef struct RwCamera;
typedef struct RwMatrixTag;
typedef struct xAnimTransition;
typedef struct xAnimTransitionList;
typedef struct xUpdateCullEnt;
typedef struct rxReq;
typedef struct xPEEntBound;
typedef struct xEnvAsset;
typedef struct xLinkAsset;
typedef struct xModelTag;
typedef struct zLasso;
typedef struct xEntMotionMechData;
typedef struct _tagEmitLine;
typedef enum RxClusterValidityReq;
typedef enum RpWorldRenderOrder;
typedef struct xRay3;
typedef struct xEntPenData;
typedef struct _tagxRumble;
typedef struct iFogParams;
typedef struct xCoef3;
typedef struct xEntDrive;
typedef enum RxNodeDefEditable;
typedef struct xBound;
typedef struct RpMaterial;
typedef struct RpSector;
typedef struct xModelBucket;
typedef enum RxClusterValid;
typedef enum fx_type_enum;
typedef struct xEntCollis;
typedef struct xAnimMultiFile;
typedef struct xRot;
typedef struct xEntOrbitData;
typedef struct xVec2;
typedef struct RpWorld;
typedef struct RpWorldSector;
typedef struct RpMorphTarget;
typedef struct xParEmitterAsset;
typedef enum rxEmbeddedPacketState;
typedef struct zPlatFMRunTime;
typedef struct xSphere;
typedef struct _tagEmitVolume;
typedef struct _zPortal;
typedef struct RpLight;
typedef struct xEntMotion;
typedef struct unit_data;
typedef struct xParGroup;
typedef struct xEntFrame;
typedef struct xFFX;
typedef enum RwCameraProjection;
typedef struct xPlatformAsset;
typedef enum _tagPadState;
typedef enum RxClusterForcePresent;
typedef struct xParEmitterPropsAsset;
typedef struct xEntMotionAsset;
typedef struct xCylinder;
typedef enum fx_orient_enum;
typedef struct RxColorUnion;
typedef struct xGlobals;
typedef struct RwFrame;
typedef struct xBox;
typedef struct RxClusterDefinition;
typedef struct xShadowSimplePoly;
typedef struct _tagxPad;
typedef struct xEntSplineData;
typedef struct _tagEmitOffsetPoint;
typedef struct RwSphere;
typedef struct xParEmitter;
typedef struct RwLLLink;
typedef struct tri_data_0;
typedef struct xGroupAsset;
typedef struct _tagPadAnalog;
typedef struct RwTexDictionary;
typedef struct xEntMotionPenData;
typedef struct RxOutputSpec;
typedef struct xDecalEmitter;
typedef struct _tagiPad;
typedef struct xLightKitLight;
typedef struct tri_data_1;
typedef struct xMat3x3;
typedef struct xAnimMultiFileEntry;
typedef struct xAnimActiveEffect;
typedef struct _class_1;
typedef struct xShadowSimpleCache;
typedef struct RxClusterRef;
typedef struct xEntMPData;
typedef struct xParSys;
typedef struct RwObject;
typedef struct xPEVCyl;
typedef struct config_0;
typedef struct RxIoSpec;
typedef enum texture_mode;
typedef struct RpInterpolator;
typedef struct xParInterp;
typedef struct xClumpCollBSPVertInfo;
typedef struct RxNodeMethods;
typedef struct xEntMotionERData;
typedef struct _class_2;
typedef struct xClumpCollBSPTriangle;
typedef struct xAnimMultiFileBase;
typedef struct _class_3;
typedef struct RwFrustumPlane;
typedef struct xBaseAsset;
typedef struct xPEEntBone;
typedef struct RwPlane;
typedef struct config_1;
typedef struct zGlobals;
typedef struct _class_4;
typedef struct RxCluster;
typedef struct zGlobalSettings;
typedef struct RpMaterialList;
typedef struct RxPacket;
typedef struct zPlayerLassoInfo;
typedef struct zScene;
typedef struct _class_5;
typedef struct xBBox;
typedef struct anim_coll_data;
typedef enum RwFogType;
typedef struct iColor_tag;
typedef struct _class_6;
typedef struct zLedgeGrabParams;
typedef struct RwRGBAReal;
typedef struct xPECircle;
typedef struct zJumpParam;
typedef struct xEntMotionOrbitData;
typedef struct RwLinkList;
typedef RwCamera*(*type_0)(RwCamera*);
typedef RpClump*(*type_1)(RpClump*, void*);
typedef int32(*type_2)(RxPipelineNode*);
typedef RwCamera*(*type_4)(RwCamera*);
typedef RwObjectHasFrame*(*type_5)(RwObjectHasFrame*);
typedef void(*type_7)(xEnt*, xScene*, float32, xEntCollis*);
typedef xBase*(*type_8)(uint32);
typedef void(*type_9)(RxPipelineNode*);
typedef uint32(*type_13)(xEnt*, xEnt*, xScene*, float32, xCollis*);
typedef int8*(*type_14)(xBase*);
typedef int8*(*type_16)(uint32);
typedef void(*type_19)(xAnimPlay*, xAnimState*);
typedef int32(*type_20)(RxPipelineNode*, RxPipeline*);
typedef void(*type_21)(xEnt*, xVec3*, xMat4x3*);
typedef uint32(*type_23)(uint32, xAnimActiveEffect*, xAnimSingle*, void*);
typedef void(*type_26)(xAnimPlay*, xQuat*, xVec3*, int32);
typedef uint32(*type_29)(RxPipelineNode*, uint32, uint32, void*);
typedef RpAtomic*(*type_30)(RpAtomic*);
typedef int32(*type_32)(RxPipelineNode*, RxPipelineNodeParam*);
typedef int32(*type_36)(RxNodeDefinition*);
typedef void(*type_40)(RxNodeDefinition*);
typedef uint32(*type_45)(xAnimTransition*, xAnimSingle*, void*);
typedef void(*type_52)(void*);
typedef void(*type_60)(xAnimState*, xAnimSingle*, void*);
typedef RpWorldSector*(*type_63)(RpWorldSector*);
typedef int32(*type_79)(xBase*, xBase*, uint32, float32*, xBase*);
typedef void(*type_80)(xEnt*, xScene*, float32);
typedef void(*type_84)(bolt&, void*);
typedef void(*type_86)(xEnt*, xVec3*);
typedef void(*type_89)(xEnt*, xScene*, float32, xEntFrame*);
typedef void(*type_90)(xEnt*);
typedef void(*type_94)(xMemPool*, void*);
typedef uint32(*type_95)(void*, void*);
typedef void(*type_103)(RwResEntry*);
typedef xVec3 type_3[60];
typedef xCollis type_6[18];
typedef int8 type_10[16];
typedef RwTexCoords* type_11[8];
typedef float32 type_12[22];
typedef xParInterp type_15[1];
typedef float32 type_17[22];
typedef uint8 type_18[2];
typedef int8 type_22[16];
typedef uint32 type_24[15];
typedef uint32 type_25[15];
typedef RwFrustumPlane type_27[6];
typedef uint16 type_28[3];
typedef uint32 type_31[15];
typedef xParInterp type_33[4];
typedef RwV3d type_34[8];
typedef uint32 type_35[72];
typedef int8 type_37[4];
typedef analog_data type_38[2];
typedef xParInterp type_39[4];
typedef xBase* type_41[72];
typedef uint8 type_42[3];
typedef float32 type_43[4];
typedef float32 type_44[2];
typedef uint8 type_46[2];
typedef xVec4 type_47[12];
typedef uint32 type_48[2];
typedef RwTexCoords* type_49[8];
typedef uint8 type_50[2];
typedef float32 type_51[6];
typedef uint8 type_53[3];
typedef float32 type_54[3];
typedef float32 type_55[3];
typedef effect_data* type_56[7];
typedef xModelTag type_57[2];
typedef uint32 type_58[7];
typedef float32 type_59[4];
typedef float32 type_61[4];
typedef float32 type_62[3];
typedef float32 type_64[12];
typedef RpLight* type_65[2];
typedef float32 type_66[12];
typedef RwFrame* type_67[2];
typedef float32 type_68[12];
typedef xEnt* type_69[111];
typedef float32 type_70[12];
typedef float32 type_71[12];
typedef xVec3 type_72[3];
typedef uint32 type_73[4];
typedef float32 type_74[12];
typedef uint8 type_75[3];
typedef uint8 type_76[3];
typedef int8 type_77[128];
typedef int8 type_78[128][6];
typedef uint8 type_81[2];
typedef uint8 type_82[14];
typedef xModelTag type_83[4];
typedef int8 type_85[32];
typedef xModelInstance* type_87[14];
typedef float32 type_88[16];
typedef uint8 type_91[4];
typedef float32 type_92[2];
typedef float32 type_93[2];
typedef uint8 type_96[22];
typedef int8 type_97[32];
typedef uint8 type_98[22];
typedef int8 type_99[32];
typedef xVec3 type_100[4];
typedef uint16 type_101[3];
typedef xVec2 type_102[2];
typedef uint8 type_104[2];
typedef xVec2 type_105[2];
typedef xAnimMultiFileEntry type_106[1];
typedef xVec3 type_107[5];
typedef RxCluster type_108[1];
typedef uint8 type_109[5];
struct static_queue_0
{
uint32 _first;
uint32 _size;
uint32 _max_size;
uint32 _max_size_mask;
bolt* _buffer;
};
struct RwObjectHasFrame
{
RwObject object;
RwLLLink lFrame;
RwObjectHasFrame*(*sync)(RwObjectHasFrame*);
};
struct RxPipelineNode
{
RxNodeDefinition* nodeDef;
uint32 numOutputs;
uint32* outputs;
RxPipelineCluster** slotClusterRefs;
uint32* slotsContinue;
void* privateData;
uint32* inputToClusterSlot;
RxPipelineNodeTopSortData* topSortData;
void* initializationData;
uint32 initializationDataSize;
};
struct zEntHangable
{
};
struct static_queue_1
{
uint32 _first;
uint32 _size;
uint32 _max_size;
uint32 _max_size_mask;
unit_data* _buffer;
};
enum _zPlayerWallJumpState
{
k_WALLJUMP_NOT,
k_WALLJUMP_LAUNCH,
k_WALLJUMP_FLIGHT,
k_WALLJUMP_LAND
};
struct RpPolygon
{
uint16 matIndex;
uint16 vertIndex[3];
};
struct xVec3
{
float32 x;
float32 y;
float32 z;
};
struct xLaserBoltEmitter
{
config_0 cfg;
static_queue_0 bolts;
float32 ialpha;
RwRaster* bolt_raster;
int32 start_collide;
effect_data* fx[7];
uint32 fxsize[7];
void update_fx(bolt& b, float32 prev_dist, float32 dt);
RxObjSpace3DVertex* render(bolt& b, RxObjSpace3DVertex* vert);
void collide_update(bolt& b);
void attach_effects(fx_when_enum when, effect_data* fx, uint32 fxsize);
void render();
void update(float32 dt);
void emit(xVec3& loc, xVec3& dir);
void refresh_config();
void reset();
void set_texture(int8* name);
void init(uint32 max_bolts);
};
struct xEnv
{
iEnv* geom;
iEnv ienv;
xLightKit* lightKit;
};
struct bolt
{
xVec3 origin;
xVec3 dir;
xVec3 loc;
xVec3 hit_norm;
float32 dist;
float32 hit_dist;
float32 prev_dist;
float32 prev_check_dist;
xEnt* hit_ent;
float32 emitted;
void* context;
};
struct xMovePointAsset : xBaseAsset
{
xVec3 pos;
uint16 wt;
uint8 on;
uint8 bezIndex;
uint8 flg_props;
uint8 pad;
uint16 numPoints;
float32 delay;
float32 zoneRadius;
float32 arenaRadius;
};
struct RwV3d
{
float32 x;
float32 y;
float32 z;
};
struct xEnt : xBase
{
xEntAsset* asset;
uint16 idx;
uint16 num_updates;
uint8 flags;
uint8 miscflags;
uint8 subType;
uint8 pflags;
uint8 moreFlags;
uint8 isCulled;
uint8 driving_count;
uint8 num_ffx;
uint8 collType;
uint8 collLev;
uint8 chkby;
uint8 penby;
xModelInstance* model;
xModelInstance* collModel;
xModelInstance* camcollModel;
xLightKit* lightKit;
void(*update)(xEnt*, xScene*, float32);
void(*endUpdate)(xEnt*, xScene*, float32);
void(*bupdate)(xEnt*, xVec3*);
void(*move)(xEnt*, xScene*, float32, xEntFrame*);
void(*render)(xEnt*);
xEntFrame* frame;
xEntCollis* collis;
xGridBound gridb;
xBound bound;
void(*transl)(xEnt*, xVec3*, xMat4x3*);
xFFX* ffx;
xEnt* driver;
int32 driveMode;
xShadowSimpleCache* simpShadow;
xEntShadow* entShadow;
anim_coll_data* anim_coll;
void* user_data;
};
struct effect_data
{
fx_type_enum type;
fx_orient_enum orient;
float32 rate;
_class_2 data;
float32 irate;
};
struct RpGeometry
{
RwObject object;
uint32 flags;
uint16 lockedSinceLastInst;
int16 refCount;
int32 numTriangles;
int32 numVertices;
int32 numMorphTargets;
int32 numTexCoordSets;
RpMaterialList matList;
RpTriangle* triangles;
RwRGBA* preLitLum;
RwTexCoords* texCoords[8];
RpMeshHeader* mesh;
RwResEntry* repEntry;
RpMorphTarget* morphTarget;
};
struct xAnimTable
{
xAnimTable* Next;
int8* Name;
xAnimTransition* TransitionList;
xAnimState* StateList;
uint32 AnimIndex;
uint32 MorphIndex;
uint32 UserFlags;
};
struct xAnimPlay
{
xAnimPlay* Next;
uint16 NumSingle;
uint16 BoneCount;
xAnimSingle* Single;
void* Object;
xAnimTable* Table;
xMemPool* Pool;
xModelInstance* ModelInst;
void(*BeforeAnimMatrices)(xAnimPlay*, xQuat*, xVec3*, int32);
};
struct xModelInstance
{
xModelInstance* Next;
xModelInstance* Parent;
xModelPool* Pool;
xAnimPlay* Anim;
RpAtomic* Data;
uint32 PipeFlags;
float32 RedMultiplier;
float32 GreenMultiplier;
float32 BlueMultiplier;
float32 Alpha;
float32 FadeStart;
float32 FadeEnd;
xSurface* Surf;
xModelBucket** Bucket;
xModelInstance* BucketNext;
xLightKit* LightKit;
void* Object;
uint16 Flags;
uint8 BoneCount;
uint8 BoneIndex;
uint8* BoneRemap;
RwMatrixTag* Mat;
xVec3 Scale;
uint32 modelID;
uint32 shadowID;
RpAtomic* shadowmapAtomic;
_class_1 anim_coll;
};
struct RpVertexNormal
{
int8 x;
int8 y;
int8 z;
uint8 pad;
};
struct zPlatform : zEnt
{
xPlatformAsset* passet;
xEntMotion motion;
uint16 state;
uint16 plat_flags;
float32 tmr;
int32 ctr;
xMovePoint* src;
xModelInstance* am;
xModelInstance* bm;
int32 moving;
xEntDrive drv;
zPlatFMRunTime* fmrt;
float32 pauseMult;
float32 pauseDelta;
};
struct rxHeapFreeBlock
{
uint32 size;
rxHeapBlockHeader* ptr;
};
struct xMovePoint : xBase
{
xMovePointAsset* asset;
xVec3* pos;
xMovePoint** nodes;
xMovePoint* prev;
uint32 node_wt_sum;
uint8 on;
uint8 pad[2];
float32 delay;
xSpline3* spl;
};
struct RwRaster
{
RwRaster* parent;
uint8* cpPixels;
uint8* palette;
int32 width;
int32 height;
int32 depth;
int32 stride;
int16 nOffsetX;
int16 nOffsetY;
uint8 cType;
uint8 cFlags;
uint8 privateFlags;
uint8 cFormat;
uint8* originalPixels;
int32 originalWidth;
int32 originalHeight;
int32 originalStride;
};
struct iEnv
{
RpWorld* world;
RpWorld* collision;
RpWorld* fx;
RpWorld* camera;
xJSPHeader* jsp;
RpLight* light[2];
RwFrame* light_frame[2];
int32 memlvl;
};
struct RxPipelineNodeTopSortData
{
uint32 numIns;
uint32 numInsVisited;
rxReq* req;
};
struct xAnimEffect
{
xAnimEffect* Next;
uint32 Flags;
float32 StartTime;
float32 EndTime;
uint32(*Callback)(uint32, xAnimActiveEffect*, xAnimSingle*, void*);
};
struct RwV2d
{
float32 x;
float32 y;
};
struct RwTexCoords
{
float32 u;
float32 v;
};
struct xBase
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
xLinkAsset* link;
int32(*eventFunc)(xBase*, xBase*, uint32, float32*, xBase*);
};
struct xGridBound
{
void* data;
uint16 gx;
uint16 gz;
uint8 ingrid;
uint8 oversize;
uint8 deleted;
uint8 gpad;
xGridBound** head;
xGridBound* next;
};
struct iterator
{
uint32 _it;
static_queue_0* _owner;
};
enum _tagRumbleType
{
eRumble_Off,
eRumble_Hi,
eRumble_VeryLightHi,
eRumble_VeryLight,
eRumble_LightHi,
eRumble_Light,
eRumble_MediumHi,
eRumble_Medium,
eRumble_HeavyHi,
eRumble_Heavy,
eRumble_VeryHeavyHi,
eRumble_VeryHeavy,
eRumble_Total,
eRumbleForceU32 = 0x7fffffff
};
struct RxNodeDefinition
{
int8* name;
RxNodeMethods nodeMethods;
RxIoSpec io;
uint32 pipelineNodePrivateDataSize;
RxNodeDefEditable editable;
int32 InputPipesCnt;
};
struct _class_0
{
RwTexture* asset;
uint32 units;
xVec2 size;
xVec2 isize;
int32 prev;
};
struct tagiRenderInput
{
uint16* m_index;
RxObjSpace3DVertex* m_vertex;
float32* m_vertexTZ;
uint32 m_mode;
int32 m_vertexType;
int32 m_vertexTypeSize;
int32 m_indexCount;
int32 m_vertexCount;
xMat4x3 m_camViewMatrix;
xVec4 m_camViewR;
xVec4 m_camViewU;
};
enum _zPlayerType
{
ePlayer_SB,
ePlayer_Patrick,
ePlayer_Sandy,
ePlayer_MAXTYPES
};
struct xLightKit
{
uint32 tagID;
uint32 groupID;
uint32 lightCount;
xLightKitLight* lightList;
};
struct xUpdateCullGroup
{
uint32 active;
uint16 startIndex;
uint16 endIndex;
xGroup* groupObject;
};
struct zCutsceneMgr
{
};
struct zEnt : xEnt
{
xAnimTable* atbl;
};
struct xAnimSingle
{
uint32 SingleFlags;
xAnimState* State;
float32 Time;
float32 CurrentSpeed;
float32 BilinearLerp[2];
xAnimEffect* Effect;
uint32 ActiveCount;
float32 LastTime;
xAnimActiveEffect* ActiveList;
xAnimPlay* Play;
xAnimTransition* Sync;
xAnimTransition* Tran;
xAnimSingle* Blend;
float32 BlendFactor;
uint32 pad;
};
struct RwRGBA
{
uint8 red;
uint8 green;
uint8 blue;
uint8 alpha;
};
struct rxHeapSuperBlockDescriptor
{
void* start;
uint32 size;
rxHeapSuperBlockDescriptor* next;
};
struct xJSPNodeInfo
{
int32 originalMatIndex;
int32 nodeFlags;
};
struct RwTexture
{
RwRaster* raster;
RwTexDictionary* dict;
RwLLLink lInDictionary;
int8 name[32];
int8 mask[32];
uint32 filterAddressing;
int32 refCount;
};
struct _tagEmitSphere
{
float32 radius;
};
struct xAnimState
{
xAnimState* Next;
int8* Name;
uint32 ID;
uint32 Flags;
uint32 UserFlags;
float32 Speed;
xAnimFile* Data;
xAnimEffect* Effects;
xAnimTransitionList* Default;
xAnimTransitionList* List;
float32* BoneBlend;
float32* TimeSnap;
float32 FadeRecip;
uint16* FadeOffset;
void* CallbackData;
xAnimMultiFile* MultiFile;
void(*BeforeEnter)(xAnimPlay*, xAnimState*);
void(*StateCallback)(xAnimState*, xAnimSingle*, void*);
void(*BeforeAnimMatrices)(xAnimPlay*, xQuat*, xVec3*, int32);
};
struct xEntMechData
{
xVec3 apos;
xVec3 bpos;
xVec3 dir;
float32 arot;
float32 brot;
float32 ss;
float32 sr;
int32 state;
float32 tsfd;
float32 trfd;
float32 tsbd;
float32 trbd;
float32* rotptr;
};
struct RwResEntry
{
RwLLLink link;
int32 size;
void* owner;
RwResEntry** ownerRef;
void(*destroyNotify)(RwResEntry*);
};
struct RxPipeline
{
int32 locked;
uint32 numNodes;
RxPipelineNode* nodes;
uint32 packetNumClusterSlots;
rxEmbeddedPacketState embeddedPacketState;
RxPacket* embeddedPacket;
uint32 numInputRequirements;
RxPipelineRequiresCluster* inputRequirements;
void* superBlock;
uint32 superBlockSize;
uint32 entryPoint;
uint32 pluginId;
uint32 pluginData;
};
struct xMat4x3 : xMat3x3
{
xVec3 pos;
uint32 pad3;
};
struct RxPipelineCluster
{
RxClusterDefinition* clusterRef;
uint32 creationAttributes;
};
struct RxObjSpace3DVertex
{
RwV3d objVertex;
RxColorUnion c;
RwV3d objNormal;
float32 u;
float32 v;
};
struct xEntMotionSplineData
{
int32 unknown;
};
struct RxPipelineNodeParam
{
void* dataParam;
RxHeap* heap;
};
struct zAssetPickupTable
{
};
struct analog_data
{
xVec2 offset;
xVec2 dir;
float32 mag;
float32 ang;
};
struct RpMeshHeader
{
uint32 flags;
uint16 numMeshes;
uint16 serialNum;
uint32 totalIndicesInMesh;
uint32 firstMeshOffset;
};
struct xSpline3
{
uint16 type;
uint16 flags;
uint32 N;
uint32 allocN;
xVec3* points;
float32* time;
xVec3* p12;
xVec3* bctrl;
float32* knot;
xCoef3* coef;
uint32 arcSample;
float32* arcLength;
};
struct RxHeap
{
uint32 superBlockSize;
rxHeapSuperBlockDescriptor* head;
rxHeapBlockHeader* headBlock;
rxHeapFreeBlock* freeBlocks;
uint32 entriesAlloced;
uint32 entriesUsed;
int32 dirty;
};
struct RwBBox
{
RwV3d sup;
RwV3d inf;
};
struct xMemPool
{
void* FreeList;
uint16 NextOffset;
uint16 Flags;
void* UsedList;
void(*InitCB)(xMemPool*, void*);
void* Buffer;
uint16 Size;
uint16 NumRealloc;
uint32 Total;
};
struct curve_node
{
float32 time;
iColor_tag color;
float32 scale;
};
struct xQuat
{
xVec3 v;
float32 s;
};
struct xGroup : xBase
{
xGroupAsset* asset;
xBase** item;
uint32 last_index;
int32 flg_group;
};
struct RpTriangle
{
uint16 vertIndex[3];
int16 matIndex;
};
struct xEntBoulder
{
};
struct RpAtomic
{
RwObjectHasFrame object;
RwResEntry* repEntry;
RpGeometry* geometry;
RwSphere boundingSphere;
RwSphere worldBoundingSphere;
RpClump* clump;
RwLLLink inClumpLink;
RpAtomic*(*renderCallBack)(RpAtomic*);
RpInterpolator interpolator;
uint16 renderFrame;
uint16 pad;
RwLinkList llWorldSectorsInAtomic;
RxPipeline* pipeline;
};
struct xClumpCollBSPBranchNode
{
uint32 leftInfo;
uint32 rightInfo;
float32 leftValue;
float32 rightValue;
};
struct xEntShadow
{
xVec3 pos;
xVec3 vec;
RpAtomic* shadowModel;
float32 dst_cast;
float32 radius[2];
};
struct rxHeapBlockHeader
{
rxHeapBlockHeader* prev;
rxHeapBlockHeader* next;
uint32 size;
rxHeapFreeBlock* freeEntry;
uint32 pad[4];
};
struct xCollis
{
uint32 flags;
uint32 oid;
void* optr;
xModelInstance* mptr;
float32 dist;
xVec3 norm;
xVec3 tohit;
xVec3 depen;
xVec3 hdng;
union
{
_class_3 tuv;
tri_data_1 tri;
};
};
struct zCheckPoint
{
xVec3 pos;
float32 rot;
uint32 initCamID;
};
struct zPlayerGlobals
{
zEnt ent;
xEntShadow entShadow_embedded;
xShadowSimpleCache simpShadow_embedded;
zGlobalSettings g;
zPlayerSettings* s;
zPlayerSettings sb;
zPlayerSettings patrick;
zPlayerSettings sandy;
xModelInstance* model_spongebob;
xModelInstance* model_patrick;
xModelInstance* model_sandy;
uint32 Visible;
uint32 Health;
int32 Speed;
float32 SpeedMult;
int32 Sneak;
int32 Teeter;
float32 SlipFadeTimer;
int32 Slide;
float32 SlideTimer;
int32 Stepping;
int32 JumpState;
int32 LastJumpState;
float32 JumpTimer;
float32 LookAroundTimer;
uint32 LookAroundRand;
uint32 LastProjectile;
float32 DecelRun;
float32 DecelRunSpeed;
float32 HotsauceTimer;
float32 LeanLerp;
float32 ScareTimer;
xBase* ScareSource;
float32 CowerTimer;
float32 DamageTimer;
float32 SundaeTimer;
float32 ControlOffTimer;
float32 HelmetTimer;
uint32 WorldDisguise;
uint32 Bounced;
float32 FallDeathTimer;
float32 HeadbuttVel;
float32 HeadbuttTimer;
uint32 SpecialReceived;
xEnt* MountChimney;
float32 MountChimOldY;
uint32 MaxHealth;
uint32 DoMeleeCheck;
float32 VictoryTimer;
float32 BadGuyNearTimer;
float32 ForceSlipperyTimer;
float32 ForceSlipperyFriction;
float32 ShockRadius;
float32 ShockRadiusOld;
float32 Face_ScareTimer;
uint32 Face_ScareRandom;
uint32 Face_Event;
float32 Face_EventTimer;
float32 Face_PantTimer;
uint32 Face_AnimSpecific;
uint32 IdleRand;
float32 IdleMinorTimer;
float32 IdleMajorTimer;
float32 IdleSitTimer;
int32 Transparent;
zEnt* FireTarget;
uint32 ControlOff;
uint32 ControlOnEvent;
uint32 AutoMoveSpeed;
float32 AutoMoveDist;
xVec3 AutoMoveTarget;
xBase* AutoMoveObject;
zEnt* Diggable;
float32 DigTimer;
zPlayerCarryInfo carry;
zPlayerLassoInfo lassoInfo;
xModelTag BubbleWandTag[2];
xModelInstance* model_wand;
xEntBoulder* bubblebowl;
float32 bbowlInitVel;
zEntHangable* HangFound;
zEntHangable* HangEnt;
zEntHangable* HangEntLast;
xVec3 HangPivot;
xVec3 HangVel;
float32 HangLength;
xVec3 HangStartPos;
float32 HangStartLerp;
xModelTag HangPawTag[4];
float32 HangPawOffset;
float32 HangElapsed;
float32 Jump_CurrGravity;
float32 Jump_HoldTimer;
float32 Jump_ChangeTimer;
int32 Jump_CanDouble;
int32 Jump_CanFloat;
int32 Jump_SpringboardStart;
zPlatform* Jump_Springboard;
int32 CanJump;
int32 CanBubbleSpin;
int32 CanBubbleBounce;
int32 CanBubbleBash;
int32 IsJumping;
int32 IsDJumping;
int32 IsBubbleSpinning;
int32 IsBubbleBouncing;
int32 IsBubbleBashing;
int32 IsBubbleBowling;
int32 WasDJumping;
int32 IsCoptering;
_zPlayerWallJumpState WallJumpState;
int32 cheat_mode;
uint32 Inv_Shiny;
uint32 Inv_Spatula;
uint32 Inv_PatsSock[15];
uint32 Inv_PatsSock_Max[15];
uint32 Inv_PatsSock_CurrentLevel;
uint32 Inv_LevelPickups[15];
uint32 Inv_LevelPickups_CurrentLevel;
uint32 Inv_PatsSock_Total;
xModelTag BubbleTag;
xEntDrive drv;
xSurface* floor_surf;
xVec3 floor_norm;
int32 slope;
xCollis earc_coll;
xSphere head_sph;
xModelTag center_tag;
xModelTag head_tag;
uint32 TongueFlags[2];
xVec3 RootUp;
xVec3 RootUpTarget;
zCheckPoint cp;
uint32 SlideTrackSliding;
uint32 SlideTrackCount;
xEnt* SlideTrackEnt[111];
uint32 SlideNotGroundedSinceSlide;
xVec3 SlideTrackDir;
xVec3 SlideTrackVel;
float32 SlideTrackDecay;
float32 SlideTrackLean;
float32 SlideTrackLand;
uint8 sb_model_indices[14];
xModelInstance* sb_models[14];
uint32 currentPlayer;
xVec3 PredictRotate;
xVec3 PredictTranslate;
float32 PredictAngV;
xVec3 PredictCurrDir;
float32 PredictCurrVel;
float32 KnockBackTimer;
float32 KnockIntoAirTimer;
};
struct xModelPool
{
xModelPool* Next;
uint32 NumMatrices;
xModelInstance* List;
};
struct RxPipelineRequiresCluster
{
RxClusterDefinition* clusterDef;
RxClusterValidityReq rqdOrOpt;
uint32 slotIndex;
};
struct _tagEmitRect
{
float32 x_len;
float32 z_len;
};
struct xEntMotionMPData
{
uint32 flags;
uint32 mp_id;
float32 speed;
};
struct xJSPHeader
{
int8 idtag[4];
uint32 version;
uint32 jspNodeCount;
RpClump* clump;
xClumpCollBSPTree* colltree;
xJSPNodeInfo* jspNodeList;
};
struct xEntAsset : xBaseAsset
{
uint8 flags;
uint8 subtype;
uint8 pflags;
uint8 moreFlags;
uint8 pad;
uint32 surfaceID;
xVec3 ang;
xVec3 pos;
xVec3 scale;
float32 redMult;
float32 greenMult;
float32 blueMult;
float32 seeThru;
float32 seeThruSpeed;
uint32 modelInfoID;
uint32 animListID;
};
struct xEntERData
{
xVec3 a;
xVec3 b;
xVec3 dir;
float32 et;
float32 wet;
float32 rt;
float32 wrt;
float32 p;
float32 brt;
float32 ert;
int32 state;
};
struct xUpdateCullMgr
{
uint32 entCount;
uint32 entActive;
void** ent;
xUpdateCullEnt** mgr;
uint32 mgrCount;
uint32 mgrCurr;
xUpdateCullEnt* mgrList;
uint32 grpCount;
xUpdateCullGroup* grpList;
void(*activateCB)(void*);
void(*deactivateCB)(void*);
};
struct zPlayerCarryInfo
{
xEnt* grabbed;
uint32 grabbedModelID;
xMat4x3 spin;
xEnt* throwTarget;
xEnt* flyingToTarget;
float32 minDist;
float32 maxDist;
float32 minHeight;
float32 maxHeight;
float32 maxCosAngle;
float32 throwMinDist;
float32 throwMaxDist;
float32 throwMinHeight;
float32 throwMaxHeight;
float32 throwMaxStack;
float32 throwMaxCosAngle;
float32 throwTargetRotRate;
float32 targetRot;
uint32 grabTarget;
xVec3 grabOffset;
float32 grabLerpMin;
float32 grabLerpMax;
float32 grabLerpLast;
uint32 grabYclear;
float32 throwGravity;
float32 throwHeight;
float32 throwDistance;
float32 fruitFloorDecayMin;
float32 fruitFloorDecayMax;
float32 fruitFloorBounce;
float32 fruitFloorFriction;
float32 fruitCeilingBounce;
float32 fruitWallBounce;
float32 fruitLifetime;
xEnt* patLauncher;
};
struct xPortalAsset : xBaseAsset
{
uint32 assetCameraID;
uint32 assetMarkerID;
float32 ang;
uint32 sceneID;
};
enum fx_when_enum
{
FX_WHEN_LAUNCH,
FX_WHEN_IMPACT,
FX_WHEN_BIRTH,
FX_WHEN_DEATH,
FX_WHEN_HEAD,
FX_WHEN_TAIL,
FX_WHEN_KILL,
MAX_FX_WHEN
};
struct zPlayerSettings
{
_zPlayerType pcType;
float32 MoveSpeed[6];
float32 AnimSneak[3];
float32 AnimWalk[3];
float32 AnimRun[3];
float32 JumpGravity;
float32 GravSmooth;
float32 FloatSpeed;
float32 ButtsmashSpeed;
zJumpParam Jump;
zJumpParam Bounce;
zJumpParam Spring;
zJumpParam Wall;
zJumpParam Double;
zJumpParam SlideDouble;
zJumpParam SlideJump;
float32 WallJumpVelocity;
zLedgeGrabParams ledge;
float32 spin_damp_xz;
float32 spin_damp_y;
uint8 talk_anims;
uint8 talk_filter_size;
uint8 talk_filter[4];
};
struct xScene
{
uint32 sceneID;
uint16 flags;
uint16 num_ents;
uint16 num_trigs;
uint16 num_stats;
uint16 num_dyns;
uint16 num_npcs;
uint16 num_act_ents;
uint16 num_nact_ents;
float32 gravity;
float32 drag;
float32 friction;
uint16 num_ents_allocd;
uint16 num_trigs_allocd;
uint16 num_stats_allocd;
uint16 num_dyns_allocd;
uint16 num_npcs_allocd;
xEnt** trigs;
xEnt** stats;
xEnt** dyns;
xEnt** npcs;
xEnt** act_ents;
xEnt** nact_ents;
xEnv* env;
xMemPool mempool;
xBase*(*resolvID)(uint32);
int8*(*base2Name)(xBase*);
int8*(*id2Name)(uint32);
};
struct xCamera : xBase
{
RwCamera* lo_cam;
xMat4x3 mat;
xMat4x3 omat;
xMat3x3 mbasis;
xBound bound;
xMat4x3* tgt_mat;
xMat4x3* tgt_omat;
xBound* tgt_bound;
xVec3 focus;
xScene* sc;
xVec3 tran_accum;
float32 fov;
uint32 flags;
float32 tmr;
float32 tm_acc;
float32 tm_dec;
float32 ltmr;
float32 ltm_acc;
float32 ltm_dec;
float32 dmin;
float32 dmax;
float32 dcur;
float32 dgoal;
float32 hmin;
float32 hmax;
float32 hcur;
float32 hgoal;
float32 pmin;
float32 pmax;
float32 pcur;
float32 pgoal;
float32 depv;
float32 hepv;
float32 pepv;
float32 orn_epv;
float32 yaw_epv;
float32 pitch_epv;
float32 roll_epv;
xQuat orn_cur;
xQuat orn_goal;
xQuat orn_diff;
float32 yaw_cur;
float32 yaw_goal;
float32 pitch_cur;
float32 pitch_goal;
float32 roll_cur;
float32 roll_goal;
float32 dct;
float32 dcd;
float32 dccv;
float32 dcsv;
float32 hct;
float32 hcd;
float32 hccv;
float32 hcsv;
float32 pct;
float32 pcd;
float32 pccv;
float32 pcsv;
float32 orn_ct;
float32 orn_cd;
float32 orn_ccv;
float32 orn_csv;
float32 yaw_ct;
float32 yaw_cd;
float32 yaw_ccv;
float32 yaw_csv;
float32 pitch_ct;
float32 pitch_cd;
float32 pitch_ccv;
float32 pitch_csv;
float32 roll_ct;
float32 roll_cd;
float32 roll_ccv;
float32 roll_csv;
xVec4 frustplane[12];
};
struct xAnimFile
{
xAnimFile* Next;
int8* Name;
uint32 ID;
uint32 FileFlags;
float32 Duration;
float32 TimeOffset;
uint16 BoneCount;
uint8 NumAnims[2];
void** RawData;
};
struct _zEnv : xBase
{
xEnvAsset* easset;
};
struct RpClump
{
RwObject object;
RwLinkList atomicList;
RwLinkList lightList;
RwLinkList cameraList;
RwLLLink inWorldLink;
RpClump*(*callback)(RpClump*, void*);
};
struct xVec4
{
float32 x;
float32 y;
float32 z;
float32 w;
};
struct xSurface : xBase
{
uint32 idx;
uint32 type;
union
{
uint32 mat_idx;
xEnt* ent;
void* obj;
};
float32 friction;
uint8 state;
uint8 pad[3];
void* moprops;
};
struct xQCData
{
int8 xmin;
int8 ymin;
int8 zmin;
int8 zmin_dup;
int8 xmax;
int8 ymax;
int8 zmax;
int8 zmax_dup;
xVec3 min;
xVec3 max;
};
struct xCoef
{
float32 a[4];
};
struct RwSurfaceProperties
{
float32 ambient;
float32 specular;
float32 diffuse;
};
struct xClumpCollBSPTree
{
uint32 numBranchNodes;
xClumpCollBSPBranchNode* branchNodes;
uint32 numTriangles;
xClumpCollBSPTriangle* triangles;
};
struct RwCamera
{
RwObjectHasFrame object;
RwCameraProjection projectionType;
RwCamera*(*beginUpdate)(RwCamera*);
RwCamera*(*endUpdate)(RwCamera*);
RwMatrixTag viewMatrix;
RwRaster* frameBuffer;
RwRaster* zBuffer;
RwV2d viewWindow;
RwV2d recipViewWindow;
RwV2d viewOffset;
float32 nearPlane;
float32 farPlane;
float32 fogPlane;
float32 zScale;
float32 zShift;
RwFrustumPlane frustumPlanes[6];
RwBBox frustumBoundBox;
RwV3d frustumCorners[8];
};
struct RwMatrixTag
{
RwV3d right;
uint32 flags;
RwV3d up;
uint32 pad1;
RwV3d at;
uint32 pad2;
RwV3d pos;
uint32 pad3;
};
struct xAnimTransition
{
xAnimTransition* Next;
xAnimState* Dest;
uint32(*Conditional)(xAnimTransition*, xAnimSingle*, void*);
uint32(*Callback)(xAnimTransition*, xAnimSingle*, void*);
uint32 Flags;
uint32 UserFlags;
float32 SrcTime;
float32 DestTime;
uint16 Priority;
uint16 QueuePriority;
float32 BlendRecip;
uint16* BlendOffset;
};
struct xAnimTransitionList
{
xAnimTransitionList* Next;
xAnimTransition* T;
};
struct xUpdateCullEnt
{
uint16 index;
int16 groupIndex;
uint32(*cb)(void*, void*);
void* cbdata;
xUpdateCullEnt* nextInGroup;
};
struct rxReq
{
};
struct xPEEntBound
{
uint8 flags;
uint8 type;
uint8 pad1;
uint8 pad2;
float32 expand;
float32 deflection;
};
struct xEnvAsset : xBaseAsset
{
uint32 bspAssetID;
uint32 startCameraAssetID;
uint32 climateFlags;
float32 climateStrengthMin;
float32 climateStrengthMax;
uint32 bspLightKit;
uint32 objectLightKit;
float32 padF1;
uint32 bspCollisionAssetID;
uint32 bspFXAssetID;
uint32 bspCameraAssetID;
uint32 bspMapperID;
uint32 bspMapperCollisionID;
uint32 bspMapperFXID;
float32 loldHeight;
};
struct xLinkAsset
{
uint16 srcEvent;
uint16 dstEvent;
uint32 dstAssetID;
float32 param[4];
uint32 paramWidgetAssetID;
uint32 chkAssetID;
};
struct xModelTag
{
xVec3 v;
uint32 matidx;
float32 wt[4];
};
struct zLasso
{
uint32 flags;
float32 secsTotal;
float32 secsLeft;
float32 stRadius;
float32 tgRadius;
float32 crRadius;
xVec3 stCenter;
xVec3 tgCenter;
xVec3 crCenter;
xVec3 stNormal;
xVec3 tgNormal;
xVec3 crNormal;
xVec3 honda;
float32 stSlack;
float32 stSlackDist;
float32 tgSlack;
float32 tgSlackDist;
float32 crSlack;
float32 currDist;
float32 lastDist;
xVec3 lastRefs[5];
uint8 reindex[5];
xVec3 anchor;
xModelTag tag;
xModelInstance* model;
};
struct xEntMotionMechData
{
uint8 type;
uint8 flags;
uint8 sld_axis;
uint8 rot_axis;
float32 sld_dist;
float32 sld_tm;
float32 sld_acc_tm;
float32 sld_dec_tm;
float32 rot_dist;
float32 rot_tm;
float32 rot_acc_tm;
float32 rot_dec_tm;
float32 ret_delay;
float32 post_ret_delay;
};
struct _tagEmitLine
{
xVec3 pos1;
xVec3 pos2;
float32 radius;
};
enum RxClusterValidityReq
{
rxCLREQ_DONTWANT,
rxCLREQ_REQUIRED,
rxCLREQ_OPTIONAL,
rxCLUSTERVALIDITYREQFORCEENUMSIZEINT = 0x7fffffff
};
enum RpWorldRenderOrder
{
rpWORLDRENDERNARENDERORDER,
rpWORLDRENDERFRONT2BACK,
rpWORLDRENDERBACK2FRONT,
rpWORLDRENDERORDERFORCEENUMSIZEINT = 0x7fffffff
};
struct xRay3
{
xVec3 origin;
xVec3 dir;
float32 min_t;
float32 max_t;
int32 flags;
};
struct xEntPenData
{
xVec3 top;
float32 w;
xMat4x3 omat;
};
struct _tagxRumble
{
_tagRumbleType type;
float32 seconds;
_tagxRumble* next;
int16 active;
uint16 fxflags;
};
struct iFogParams
{
RwFogType type;
float32 start;
float32 stop;
float32 density;
RwRGBA fogcolor;
RwRGBA bgcolor;
uint8* table;
};
struct xCoef3
{
xCoef x;
xCoef y;
xCoef z;
};
struct xEntDrive
{
uint32 flags;
float32 otm;
float32 otmr;
float32 os;
float32 tm;
float32 tmr;
float32 s;
xEnt* odriver;
xEnt* driver;
xEnt* driven;
xVec3 op;
xVec3 p;
xVec3 q;
float32 yaw;
xVec3 dloc;
tri_data_0 tri;
};
enum RxNodeDefEditable
{
rxNODEDEFCONST,
rxNODEDEFEDITABLE,
rxNODEDEFEDITABLEFORCEENUMSIZEINT = 0x7fffffff
};
struct xBound
{
xQCData qcd;
uint8 type;
uint8 pad[3];
union
{
xSphere sph;
xBBox box;
xCylinder cyl;
};
xMat4x3* mat;
};
struct RpMaterial
{
RwTexture* texture;
RwRGBA color;
RxPipeline* pipeline;
RwSurfaceProperties surfaceProps;
int16 refCount;
int16 pad;
};
struct RpSector
{
int32 type;
};
struct xModelBucket
{
RpAtomic* Data;
RpAtomic* OriginalData;
xModelInstance* List;
int32 ClipFlags;
uint32 PipeFlags;
};
enum RxClusterValid
{
rxCLVALID_NOCHANGE,
rxCLVALID_VALID,
rxCLVALID_INVALID,
rxCLUSTERVALIDFORCEENUMSIZEINT = 0x7fffffff
};
enum fx_type_enum
{
FX_TYPE_PARTICLE,
FX_TYPE_DECAL,
FX_TYPE_DECAL_DIST,
FX_TYPE_CALLBACK
};
struct xEntCollis
{
uint8 chk;
uint8 pen;
uint8 env_sidx;
uint8 env_eidx;
uint8 npc_sidx;
uint8 npc_eidx;
uint8 dyn_sidx;
uint8 dyn_eidx;
uint8 stat_sidx;
uint8 stat_eidx;
uint8 idx;
xCollis colls[18];
void(*post)(xEnt*, xScene*, float32, xEntCollis*);
uint32(*depenq)(xEnt*, xEnt*, xScene*, float32, xCollis*);
};
struct xAnimMultiFile : xAnimMultiFileBase
{
xAnimMultiFileEntry Files[1];
};
struct xRot
{
xVec3 axis;
float32 angle;
};
struct xEntOrbitData
{
xVec3 orig;
xVec3 c;
float32 a;
float32 b;
float32 p;
float32 w;
};
struct xVec2
{
float32 x;
float32 y;
};
struct RpWorld
{
RwObject object;
uint32 flags;
RpWorldRenderOrder renderOrder;
RpMaterialList matList;
RpSector* rootSector;
int32 numTexCoordSets;
int32 numClumpsInWorld;
RwLLLink* currentClumpLink;
RwLinkList clumpList;
RwLinkList lightList;
RwLinkList directionalLightList;
RwV3d worldOrigin;
RwBBox boundingBox;
RpWorldSector*(*renderCallBack)(RpWorldSector*);
RxPipeline* pipeline;
};
struct RpWorldSector
{
int32 type;
RpPolygon* polygons;
RwV3d* vertices;
RpVertexNormal* normals;
RwTexCoords* texCoords[8];
RwRGBA* preLitLum;
RwResEntry* repEntry;
RwLinkList collAtomicsInWorldSector;
RwLinkList noCollAtomicsInWorldSector;
RwLinkList lightsInWorldSector;
RwBBox boundingBox;
RwBBox tightBoundingBox;
RpMeshHeader* mesh;
RxPipeline* pipeline;
uint16 matListWindowBase;
uint16 numVertices;
uint16 numPolygons;
uint16 pad;
};
struct RpMorphTarget
{
RpGeometry* parentGeom;
RwSphere boundingSphere;
RwV3d* verts;
RwV3d* normals;
};
struct xParEmitterAsset : xBaseAsset
{
uint8 emit_flags;
uint8 emit_type;
uint16 pad;
uint32 propID;
union
{
xPECircle e_circle;
_tagEmitSphere e_sphere;
_tagEmitRect e_rect;
_tagEmitLine e_line;
_tagEmitVolume e_volume;
_tagEmitOffsetPoint e_offsetp;
xPEVCyl e_vcyl;
xPEEntBone e_entbone;
xPEEntBound e_entbound;
};
uint32 attachToID;
xVec3 pos;
xVec3 vel;
float32 vel_angle_variation;
uint32 cull_mode;
float32 cull_dist_sqr;
};
enum rxEmbeddedPacketState
{
rxPKST_PACKETLESS,
rxPKST_UNUSED,
rxPKST_INUSE,
rxPKST_PENDING,
rxEMBEDDEDPACKETSTATEFORCEENUMSIZEINT = 0x7fffffff
};
struct zPlatFMRunTime
{
uint32 flags;
float32 tmrs[12];
float32 ttms[12];
float32 atms[12];
float32 dtms[12];
float32 vms[12];
float32 dss[12];
};
struct xSphere
{
xVec3 center;
float32 r;
};
struct _tagEmitVolume
{
uint32 emit_volumeID;
};
struct _zPortal : xBase
{
xPortalAsset* passet;
};
struct RpLight
{
RwObjectHasFrame object;
float32 radius;
RwRGBAReal color;
float32 minusCosAngle;
RwLinkList WorldSectorsInLight;
RwLLLink inWorld;
uint16 lightFrame;
uint16 pad;
};
struct xEntMotion
{
xEntMotionAsset* asset;
uint8 type;
uint8 pad;
uint16 flags;
float32 t;
float32 tmr;
float32 d;
union
{
xEntERData er;
xEntOrbitData orb;
xEntSplineData spl;
xEntMPData mp;
xEntMechData mech;
xEntPenData pen;
};
xEnt* owner;
xEnt* target;
};
struct unit_data
{
uint8 flags;
uint8 curve_index;
uint8 u;
uint8 v;
float32 frac;
float32 age;
float32 cull_size;
xMat4x3 mat;
};
struct xParGroup
{
};
struct xEntFrame
{
xMat4x3 mat;
xMat4x3 oldmat;
xVec3 oldvel;
xRot oldrot;
xRot drot;
xRot rot;
xVec3 dpos;
xVec3 dvel;
xVec3 vel;
uint32 mode;
};
struct xFFX
{
};
enum RwCameraProjection
{
rwNACAMERAPROJECTION,
rwPERSPECTIVE,
rwPARALLEL,
rwCAMERAPROJECTIONFORCEENUMSIZEINT = 0x7fffffff
};
struct xPlatformAsset
{
};
enum _tagPadState
{
ePad_Disabled,
ePad_DisabledError,
ePad_Enabled,
ePad_Missing,
ePad_Total
};
enum RxClusterForcePresent
{
rxCLALLOWABSENT,
rxCLFORCEPRESENT,
rxCLUSTERFORCEPRESENTFORCEENUMSIZEINT = 0x7fffffff
};
struct xParEmitterPropsAsset : xBaseAsset
{
uint32 parSysID;
union
{
xParInterp rate;
xParInterp value[1];
};
xParInterp life;
xParInterp size_birth;
xParInterp size_death;
xParInterp color_birth[4];
xParInterp color_death[4];
xParInterp vel_scale;
xParInterp vel_angle;
xVec3 vel;
uint32 emit_limit;
float32 emit_limit_reset_time;
};
struct xEntMotionAsset
{
uint8 type;
uint8 use_banking;
uint16 flags;
union
{
xEntMotionERData er;
xEntMotionOrbitData orb;
xEntMotionSplineData spl;
xEntMotionMPData mp;
xEntMotionMechData mech;
xEntMotionPenData pen;
};
};
struct xCylinder
{
xVec3 center;
float32 r;
float32 h;
};
enum fx_orient_enum
{
FX_ORIENT_DEFAULT,
FX_ORIENT_PATH,
FX_ORIENT_IPATH,
FX_ORIENT_HIT_NORM,
FX_ORIENT_HIT_REFLECT,
MAX_FX_ORIENT,
FORCE_INT_FX_ORIENT = 0xffffffff
};
struct RxColorUnion
{
union
{
RwRGBA preLitColor;
RwRGBA color;
};
};
struct xGlobals
{
xCamera camera;
_tagxPad* pad0;
_tagxPad* pad1;
_tagxPad* pad2;
_tagxPad* pad3;
int32 profile;
int8 profFunc[128][6];
xUpdateCullMgr* updateMgr;
int32 sceneFirst;
int8 sceneStart[32];
RpWorld* currWorld;
iFogParams fog;
iFogParams fogA;
iFogParams fogB;
long32 fog_t0;
long32 fog_t1;
int32 option_vibration;
uint32 QuarterSpeed;
float32 update_dt;
int32 useHIPHOP;
uint8 NoMusic;
int8 currentActivePad;
uint8 firstStartPressed;
uint32 minVSyncCnt;
uint8 dontShowPadMessageDuringLoadingOrCutScene;
uint8 autoSaveFeature;
};
struct RwFrame
{
RwObject object;
RwLLLink inDirtyListLink;
RwMatrixTag modelling;
RwMatrixTag ltm;
RwLinkList objectList;
RwFrame* child;
RwFrame* next;
RwFrame* root;
};
struct xBox
{
xVec3 upper;
xVec3 lower;
};
struct RxClusterDefinition
{
int8* name;
uint32 defaultStride;
uint32 defaultAttributes;
int8* attributeSet;
};
struct xShadowSimplePoly
{
xVec3 vert[3];
xVec3 norm;
};
struct _tagxPad
{
uint8 value[22];
uint8 last_value[22];
uint32 on;
uint32 pressed;
uint32 released;
_tagPadAnalog analog1;
_tagPadAnalog analog2;
_tagPadState state;
uint32 flags;
_tagxRumble rumble_head;
int16 port;
int16 slot;
_tagiPad context;
float32 al2d_timer;
float32 ar2d_timer;
float32 d_timer;
float32 up_tmr[22];
float32 down_tmr[22];
analog_data analog[2];
};
struct xEntSplineData
{
int32 unknown;
};
struct _tagEmitOffsetPoint
{
xVec3 offset;
};
struct RwSphere
{
RwV3d center;
float32 radius;
};
struct xParEmitter : xBase
{
xParEmitterAsset* tasset;
xParGroup* group;
xParEmitterPropsAsset* prop;
uint8 rate_mode;
float32 rate;
float32 rate_time;
float32 rate_fraction;
float32 rate_fraction_cull;
uint8 emit_flags;
uint8 emit_pad[3];
uint8 rot[3];
xModelTag tag;
float32 oocull_distance_sqr;
float32 distance_to_cull_sqr;
void* attachTo;
xParSys* parSys;
void* emit_volume;
xVec3 last_attach_loc;
};
struct RwLLLink
{
RwLLLink* next;
RwLLLink* prev;
};
struct tri_data_0 : tri_data_1
{
xVec3 loc;
float32 yaw;
xCollis* coll;
};
struct xGroupAsset : xBaseAsset
{
uint16 itemCount;
uint16 groupFlags;
};
struct _tagPadAnalog
{
int8 x;
int8 y;
};
struct RwTexDictionary
{
RwObject object;
RwLinkList texturesInDict;
RwLLLink lInInstance;
};
struct xEntMotionPenData
{
uint8 flags;
uint8 plane;
uint8 pad[2];
float32 len;
float32 range;
float32 period;
float32 phase;
};
struct RxOutputSpec
{
int8* name;
RxClusterValid* outputClusters;
RxClusterValid allOtherClusters;
};
struct xDecalEmitter
{
config_1 cfg;
_class_0 texture;
static_queue_1 units;
curve_node* curve;
uint32 curve_size;
uint32 curve_index;
float32 ilife;
};
struct _tagiPad
{
int32 port;
};
struct xLightKitLight
{
uint32 type;
RwRGBAReal color;
float32 matrix[16];
float32 radius;
float32 angle;
RpLight* platLight;
};
struct tri_data_1
{
uint32 index;
float32 r;
float32 d;
};
struct xMat3x3
{
xVec3 right;
int32 flags;
xVec3 up;
uint32 pad1;
xVec3 at;
uint32 pad2;
};
struct xAnimMultiFileEntry
{
uint32 ID;
xAnimFile* File;
};
struct xAnimActiveEffect
{
xAnimEffect* Effect;
uint32 Handle;
};
struct _class_1
{
xVec3* verts;
};
struct xShadowSimpleCache
{
uint16 flags;
uint8 alpha;
uint8 pad;
uint32 collPriority;
xVec3 pos;
xVec3 at;
xEnt* castOnEnt;
xShadowSimplePoly poly;
float32 envHeight;
float32 shadowHeight;
uint32 raster;
float32 dydx;
float32 dydz;
xVec3 corner[4];
};
struct RxClusterRef
{
RxClusterDefinition* clusterDef;
RxClusterForcePresent forcePresent;
uint32 reserved;
};
struct xEntMPData
{
float32 curdist;
float32 speed;
xMovePoint* dest;
xMovePoint* src;
xSpline3* spl;
float32 dist;
uint32 padalign;
xQuat aquat;
xQuat bquat;
};
struct xParSys
{
};
struct RwObject
{
uint8 type;
uint8 subType;
uint8 flags;
uint8 privateFlags;
void* parent;
};
struct xPEVCyl
{
float32 height;
float32 radius;
float32 deflection;
};
struct config_0
{
float32 radius;
float32 length;
float32 vel;
float32 fade_dist;
float32 kill_dist;
float32 safe_dist;
float32 hit_radius;
float32 rand_ang;
float32 scar_life;
xVec2 bolt_uv[2];
int32 hit_interval;
float32 damage;
};
struct RxIoSpec
{
uint32 numClustersOfInterest;
RxClusterRef* clustersOfInterest;
RxClusterValidityReq* inputRequirements;
uint32 numOutputs;
RxOutputSpec* outputs;
};
enum texture_mode
{
TM_DEFAULT,
TM_RANDOM,
TM_CYCLE,
MAX_TM,
FORCE_INT_TM = 0xffffffff
};
struct RpInterpolator
{
int32 flags;
int16 startMorphTarget;
int16 endMorphTarget;
float32 time;
float32 recipTime;
float32 position;
};
struct xParInterp
{
float32 val[2];
uint32 interp;
float32 freq;
float32 oofreq;
};
struct xClumpCollBSPVertInfo
{
uint16 atomIndex;
uint16 meshVertIndex;
};
struct RxNodeMethods
{
int32(*nodeBody)(RxPipelineNode*, RxPipelineNodeParam*);
int32(*nodeInit)(RxNodeDefinition*);
void(*nodeTerm)(RxNodeDefinition*);
int32(*pipelineNodeInit)(RxPipelineNode*);
void(*pipelineNodeTerm)(RxPipelineNode*);
int32(*pipelineNodeConfig)(RxPipelineNode*, RxPipeline*);
uint32(*configMsgHandler)(RxPipelineNode*, uint32, uint32, void*);
};
struct xEntMotionERData
{
xVec3 ret_pos;
xVec3 ext_dpos;
float32 ext_tm;
float32 ext_wait_tm;
float32 ret_tm;
float32 ret_wait_tm;
};
struct _class_2
{
union
{
xParEmitter* par;
xDecalEmitter* decal;
_class_4 callback;
};
};
struct xClumpCollBSPTriangle
{
_class_6 v;
uint8 flags;
uint8 platData;
uint16 matIndex;
};
struct xAnimMultiFileBase
{
uint32 Count;
};
struct _class_3
{
float32 t;
float32 u;
float32 v;
};
struct RwFrustumPlane
{
RwPlane plane;
uint8 closestX;
uint8 closestY;
uint8 closestZ;
uint8 pad;
};
struct xBaseAsset
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
};
struct xPEEntBone
{
uint8 flags;
uint8 type;
uint8 bone;
uint8 pad1;
xVec3 offset;
float32 radius;
float32 deflection;
};
struct RwPlane
{
RwV3d normal;
float32 distance;
};
struct config_1
{
uint32 flags;
float32 life_time;
uint32 blend_src;
uint32 blend_dst;
_class_5 texture;
};
struct zGlobals : xGlobals
{
zPlayerGlobals player;
zAssetPickupTable* pickupTable;
zCutsceneMgr* cmgr;
zScene* sceneCur;
zScene* scenePreload;
};
struct _class_4
{
void(*fp)(bolt&, void*);
void* context;
};
struct RxCluster
{
uint16 flags;
uint16 stride;
void* data;
void* currentData;
uint32 numAlloced;
uint32 numUsed;
RxPipelineCluster* clusterRef;
uint32 attributes;
};
struct zGlobalSettings
{
uint16 AnalogMin;
uint16 AnalogMax;
float32 SundaeTime;
float32 SundaeMult;
uint32 InitialShinyCount;
uint32 InitialSpatulaCount;
int32 ShinyValuePurple;
int32 ShinyValueBlue;
int32 ShinyValueGreen;
int32 ShinyValueYellow;
int32 ShinyValueRed;
int32 ShinyValueCombo0;
int32 ShinyValueCombo1;
int32 ShinyValueCombo2;
int32 ShinyValueCombo3;
int32 ShinyValueCombo4;
int32 ShinyValueCombo5;
int32 ShinyValueCombo6;
int32 ShinyValueCombo7;
int32 ShinyValueCombo8;
int32 ShinyValueCombo9;
int32 ShinyValueCombo10;
int32 ShinyValueCombo11;
int32 ShinyValueCombo12;
int32 ShinyValueCombo13;
int32 ShinyValueCombo14;
int32 ShinyValueCombo15;
float32 ComboTimer;
uint32 Initial_Specials;
uint32 TakeDamage;
float32 DamageTimeHit;
float32 DamageTimeSurface;
float32 DamageTimeEGen;
float32 DamageSurfKnock;
float32 DamageGiveHealthKnock;
uint32 CheatSpongeball;
uint32 CheatPlayerSwitch;
uint32 CheatAlwaysPortal;
uint32 CheatFlyToggle;
uint32 DisableForceConversation;
float32 StartSlideAngle;
float32 StopSlideAngle;
float32 RotMatchMaxAngle;
float32 RotMatchMatchTime;
float32 RotMatchRelaxTime;
float32 Gravity;
float32 BBashTime;
float32 BBashHeight;
float32 BBashDelay;
float32 BBashCVTime;
float32 BBounceSpeed;
float32 BSpinMinFrame;
float32 BSpinMaxFrame;
float32 BSpinRadius;
float32 SandyMeleeMinFrame;
float32 SandyMeleeMaxFrame;
float32 SandyMeleeRadius;
float32 BubbleBowlTimeDelay;
float32 BubbleBowlLaunchPosLeft;
float32 BubbleBowlLaunchPosUp;
float32 BubbleBowlLaunchPosAt;
float32 BubbleBowlLaunchVelLeft;
float32 BubbleBowlLaunchVelUp;
float32 BubbleBowlLaunchVelAt;
float32 BubbleBowlPercentIncrease;
float32 BubbleBowlMinSpeed;
float32 BubbleBowlMinRecoverTime;
float32 SlideAccelVelMin;
float32 SlideAccelVelMax;
float32 SlideAccelStart;
float32 SlideAccelEnd;
float32 SlideAccelPlayerFwd;
float32 SlideAccelPlayerBack;
float32 SlideAccelPlayerSide;
float32 SlideVelMaxStart;
float32 SlideVelMaxEnd;
float32 SlideVelMaxIncTime;
float32 SlideVelMaxIncAccel;
float32 SlideAirHoldTime;
float32 SlideAirSlowTime;
float32 SlideAirDblHoldTime;
float32 SlideAirDblSlowTime;
float32 SlideVelDblBoost;
uint8 SlideApplyPhysics;
uint8 PowerUp[2];
uint8 InitialPowerUp[2];
};
struct RpMaterialList
{
RpMaterial** materials;
int32 numMaterials;
int32 space;
};
struct RxPacket
{
uint16 flags;
uint16 numClusters;
RxPipeline* pipeline;
uint32* inputToClusterSlot;
uint32* slotsContinue;
RxPipelineCluster** slotClusterRefs;
RxCluster clusters[1];
};
struct zPlayerLassoInfo
{
xEnt* target;
float32 dist;
uint8 destroy;
uint8 targetGuide;
float32 lassoRot;
xEnt* swingTarget;
xEnt* releasedSwing;
float32 copterTime;
int32 canCopter;
zLasso lasso;
xAnimState* zeroAnim;
};
struct zScene : xScene
{
_zPortal* pendingPortal;
union
{
uint32 num_ents;
uint32 num_base;
};
union
{
xBase** base;
zEnt** ents;
};
uint32 num_update_base;
xBase** update_base;
uint32 baseCount[72];
xBase* baseList[72];
_zEnv* zen;
};
struct _class_5
{
xVec2 uv[2];
uint8 rows;
uint8 cols;
texture_mode mode;
};
struct xBBox
{
xVec3 center;
xBox box;
};
struct anim_coll_data
{
};
enum RwFogType
{
rwFOGTYPENAFOGTYPE,
rwFOGTYPELINEAR,
rwFOGTYPEEXPONENTIAL,
rwFOGTYPEEXPONENTIAL2,
rwFOGTYPEFORCEENUMSIZEINT = 0x7fffffff
};
struct iColor_tag
{
uint8 r;
uint8 g;
uint8 b;
uint8 a;
};
struct _class_6
{
union
{
xClumpCollBSPVertInfo i;
RwV3d* p;
};
};
struct zLedgeGrabParams
{
float32 animGrab;
float32 zdist;
xVec3 tranTable[60];
int32 tranCount;
xEnt* optr;
xMat4x3 omat;
float32 y0det;
float32 dydet;
float32 r0det;
float32 drdet;
float32 thdet;
float32 rtime;
float32 ttime;
float32 tmr;
xVec3 spos;
xVec3 epos;
xVec3 tpos;
int32 nrays;
int32 rrand;
float32 startrot;
float32 endrot;
};
struct RwRGBAReal
{
float32 red;
float32 green;
float32 blue;
float32 alpha;
};
struct xPECircle
{
float32 radius;
float32 deflection;
xVec3 dir;
};
struct zJumpParam
{
float32 PeakHeight;
float32 TimeGravChange;
float32 TimeHold;
float32 ImpulseVel;
};
struct xEntMotionOrbitData
{
xVec3 center;
float32 w;
float32 h;
float32 period;
};
struct RwLinkList
{
RwLLLink link;
};
int8 buffer[16];
int8 buffer[16];
xMat4x3 g_I3;
tagiRenderInput gRenderBuffer;
zGlobals globals;
uint32 gActiveHeap;
void emit_decal_dist(effect_data& effect, bolt& b, float32 from_dist, float32 to_dist);
void emit_decal(effect_data& effect, bolt& b, float32 to_dist);
void emit_particle(effect_data& effect, bolt& b, float32 from_dist, float32 to_dist, float32 dt);
void update_fx(bolt& b, float32 prev_dist, float32 dt);
RxObjSpace3DVertex* render(bolt& b, RxObjSpace3DVertex* vert);
void collide_update(bolt& b);
void attach_effects(fx_when_enum when, effect_data* fx, uint32 fxsize);
void render();
void update(float32 dt);
void emit(xVec3& loc, xVec3& dir);
void refresh_config();
void reset();
void set_texture(int8* name);
void init(uint32 max_bolts);
// emit_decal_dist__17xLaserBoltEmitterFRQ217xLaserBoltEmitter11effect_dataRQ217xLaserBoltEmitter4boltfff
// Start address: 0x3b08d0
void emit_decal_dist(effect_data& effect, bolt& b, float32 from_dist, float32 to_dist)
{
float32 start_dist;
int32 total;
xMat4x3 mat;
xVec3 dloc;
int32 i;
// Line 403, Address: 0x3b08d0, Func Offset: 0
// Line 408, Address: 0x3b08d4, Func Offset: 0x4
// Line 403, Address: 0x3b08d8, Func Offset: 0x8
// Line 409, Address: 0x3b08dc, Func Offset: 0xc
// Line 403, Address: 0x3b08e0, Func Offset: 0x10
// Line 408, Address: 0x3b08f8, Func Offset: 0x28
// Line 403, Address: 0x3b08fc, Func Offset: 0x2c
// Line 409, Address: 0x3b0914, Func Offset: 0x44
// Line 408, Address: 0x3b0918, Func Offset: 0x48
// Line 409, Address: 0x3b0920, Func Offset: 0x50
// Line 410, Address: 0x3b0928, Func Offset: 0x58
// Line 408, Address: 0x3b092c, Func Offset: 0x5c
// Line 410, Address: 0x3b0930, Func Offset: 0x60
// Line 408, Address: 0x3b0934, Func Offset: 0x64
// Line 411, Address: 0x3b0938, Func Offset: 0x68
// Line 409, Address: 0x3b0940, Func Offset: 0x70
// Line 408, Address: 0x3b0944, Func Offset: 0x74
// Line 412, Address: 0x3b0948, Func Offset: 0x78
// Line 415, Address: 0x3b0950, Func Offset: 0x80
// Line 419, Address: 0x3b098c, Func Offset: 0xbc
// Line 420, Address: 0x3b0990, Func Offset: 0xc0
// Line 421, Address: 0x3b0aec, Func Offset: 0x21c
// Line 422, Address: 0x3b0af4, Func Offset: 0x224
// Line 423, Address: 0x3b0af8, Func Offset: 0x228
// Line 429, Address: 0x3b0c54, Func Offset: 0x384
// Line 431, Address: 0x3b0c58, Func Offset: 0x388
// Line 432, Address: 0x3b0c70, Func Offset: 0x3a0
// Line 431, Address: 0x3b0c74, Func Offset: 0x3a4
// Line 432, Address: 0x3b0c78, Func Offset: 0x3a8
// Line 433, Address: 0x3b0c90, Func Offset: 0x3c0
// Line 431, Address: 0x3b0c98, Func Offset: 0x3c8
// Line 432, Address: 0x3b0ce8, Func Offset: 0x418
// Line 433, Address: 0x3b0d98, Func Offset: 0x4c8
// Line 435, Address: 0x3b0dac, Func Offset: 0x4dc
// Line 436, Address: 0x3b0dc0, Func Offset: 0x4f0
// Line 437, Address: 0x3b0dc8, Func Offset: 0x4f8
// Line 438, Address: 0x3b0e00, Func Offset: 0x530
// Func End, Address: 0x3b0e34, Func Offset: 0x564
}
// emit_decal__17xLaserBoltEmitterFRQ217xLaserBoltEmitter11effect_dataRQ217xLaserBoltEmitter4boltfff
// Start address: 0x3b0e40
void emit_decal(effect_data& effect, bolt& b, float32 to_dist)
{
xMat4x3 mat;
// Line 378, Address: 0x3b0e40, Func Offset: 0
// Line 382, Address: 0x3b0e44, Func Offset: 0x4
// Line 378, Address: 0x3b0e48, Func Offset: 0x8
// Line 382, Address: 0x3b0e74, Func Offset: 0x34
// Line 387, Address: 0x3b0eb0, Func Offset: 0x70
// Line 388, Address: 0x3b100c, Func Offset: 0x1cc
// Line 389, Address: 0x3b1014, Func Offset: 0x1d4
// Line 390, Address: 0x3b1018, Func Offset: 0x1d8
// Line 396, Address: 0x3b1174, Func Offset: 0x334
// Line 397, Address: 0x3b1178, Func Offset: 0x338
// Line 398, Address: 0x3b1194, Func Offset: 0x354
// Line 397, Address: 0x3b1198, Func Offset: 0x358
// Line 398, Address: 0x3b1248, Func Offset: 0x408
// Line 399, Address: 0x3b1254, Func Offset: 0x414
// Func End, Address: 0x3b1280, Func Offset: 0x440
}
// emit_particle__17xLaserBoltEmitterFRQ217xLaserBoltEmitter11effect_dataRQ217xLaserBoltEmitter4boltfff
// Start address: 0x3b1280
void emit_particle(effect_data& effect, bolt& b, float32 from_dist, float32 to_dist, float32 dt)
{
xParEmitter& pe;
xParEmitterAsset& pea;
float32 velmag;
xVec3 oldloc;
// Line 327, Address: 0x3b1280, Func Offset: 0
// Line 336, Address: 0x3b1284, Func Offset: 0x4
// Line 327, Address: 0x3b1288, Func Offset: 0x8
// Line 330, Address: 0x3b1294, Func Offset: 0x14
// Line 336, Address: 0x3b1298, Func Offset: 0x18
// Line 331, Address: 0x3b129c, Func Offset: 0x1c
// Line 336, Address: 0x3b12a0, Func Offset: 0x20
// Line 339, Address: 0x3b12d0, Func Offset: 0x50
// Line 340, Address: 0x3b1338, Func Offset: 0xb8
// Line 342, Address: 0x3b1340, Func Offset: 0xc0
// Line 343, Address: 0x3b13ac, Func Offset: 0x12c
// Line 344, Address: 0x3b13b4, Func Offset: 0x134
// Line 346, Address: 0x3b13b8, Func Offset: 0x138
// Line 355, Address: 0x3b1424, Func Offset: 0x1a4
// Line 358, Address: 0x3b1428, Func Offset: 0x1a8
// Line 360, Address: 0x3b1438, Func Offset: 0x1b8
// Line 361, Address: 0x3b1454, Func Offset: 0x1d4
// Line 360, Address: 0x3b1464, Func Offset: 0x1e4
// Line 362, Address: 0x3b149c, Func Offset: 0x21c
// Line 360, Address: 0x3b14a0, Func Offset: 0x220
// Line 361, Address: 0x3b1518, Func Offset: 0x298
// Line 362, Address: 0x3b155c, Func Offset: 0x2dc
// Line 361, Address: 0x3b1560, Func Offset: 0x2e0
// Line 362, Address: 0x3b15d4, Func Offset: 0x354
// Line 363, Address: 0x3b15dc, Func Offset: 0x35c
// Line 366, Address: 0x3b15e8, Func Offset: 0x368
// Line 367, Address: 0x3b15f0, Func Offset: 0x370
// Line 366, Address: 0x3b15f4, Func Offset: 0x374
// Line 367, Address: 0x3b15f8, Func Offset: 0x378
// Line 366, Address: 0x3b15fc, Func Offset: 0x37c
// Line 367, Address: 0x3b1600, Func Offset: 0x380
// Line 368, Address: 0x3b1608, Func Offset: 0x388
// Line 366, Address: 0x3b160c, Func Offset: 0x38c
// Line 367, Address: 0x3b1618, Func Offset: 0x398
// Line 368, Address: 0x3b165c, Func Offset: 0x3dc
// Line 367, Address: 0x3b1660, Func Offset: 0x3e0
// Line 368, Address: 0x3b16ec, Func Offset: 0x46c
// Line 369, Address: 0x3b16f4, Func Offset: 0x474
// Line 370, Address: 0x3b170c, Func Offset: 0x48c
// Line 373, Address: 0x3b1710, Func Offset: 0x490
// Line 374, Address: 0x3b1714, Func Offset: 0x494
// Func End, Address: 0x3b1728, Func Offset: 0x4a8
}
// update_fx__17xLaserBoltEmitterFRQ217xLaserBoltEmitter4boltff
// Start address: 0x3b1730
void xLaserBoltEmitter::update_fx(bolt& b, float32 prev_dist, float32 dt)
{
float32 tail_dist;
effect_data* itfx;
effect_data* endfx;
effect_data* itfx;
effect_data* endfx;
float32 from_dist;
float32 to_dist;
effect_data* itfx;
effect_data* endfx;
effect_data* itfx;
effect_data* endfx;
// Line 297, Address: 0x3b1730, Func Offset: 0
// Line 300, Address: 0x3b1770, Func Offset: 0x40
// Line 302, Address: 0x3b177c, Func Offset: 0x4c
// Line 303, Address: 0x3b1794, Func Offset: 0x64
// Line 304, Address: 0x3b186c, Func Offset: 0x13c
// Line 305, Address: 0x3b1878, Func Offset: 0x148
// Line 307, Address: 0x3b1888, Func Offset: 0x158
// Line 308, Address: 0x3b188c, Func Offset: 0x15c
// Line 307, Address: 0x3b1890, Func Offset: 0x160
// Line 309, Address: 0x3b1894, Func Offset: 0x164
// Line 307, Address: 0x3b1898, Func Offset: 0x168
// Line 309, Address: 0x3b18a4, Func Offset: 0x174
// Line 310, Address: 0x3b18b0, Func Offset: 0x180
// Line 313, Address: 0x3b198c, Func Offset: 0x25c
// Line 315, Address: 0x3b199c, Func Offset: 0x26c
// Line 316, Address: 0x3b19b4, Func Offset: 0x284
// Line 317, Address: 0x3b1a74, Func Offset: 0x344
// Line 318, Address: 0x3b1a80, Func Offset: 0x350
// Line 320, Address: 0x3b1a8c, Func Offset: 0x35c
// Line 321, Address: 0x3b1aa4, Func Offset: 0x374
// Line 322, Address: 0x3b1b64, Func Offset: 0x434
// Line 323, Address: 0x3b1b68, Func Offset: 0x438
// Func End, Address: 0x3b1b94, Func Offset: 0x464
}
// render__17xLaserBoltEmitterFRQ217xLaserBoltEmitter4boltP18RxObjSpace3DVertex
// Start address: 0x3b1ba0
RxObjSpace3DVertex* xLaserBoltEmitter::render(bolt& b, RxObjSpace3DVertex* vert)
{
float32 dist0;
xVec3 loc0;
xVec3 loc1;
xMat4x3& cam_mat;
xVec3 dir;
xVec3 right;
xVec3 half_right;
// Line 242, Address: 0x3b1ba0, Func Offset: 0
// Line 245, Address: 0x3b1ba8, Func Offset: 0x8
// Line 242, Address: 0x3b1bac, Func Offset: 0xc
// Line 244, Address: 0x3b1bcc, Func Offset: 0x2c
// Line 245, Address: 0x3b1bd8, Func Offset: 0x38
// Line 246, Address: 0x3b1bf0, Func Offset: 0x50
// Line 247, Address: 0x3b1c08, Func Offset: 0x68
// Line 253, Address: 0x3b1c20, Func Offset: 0x80
// Line 250, Address: 0x3b1c24, Func Offset: 0x84
// Line 252, Address: 0x3b1c28, Func Offset: 0x88
// Line 250, Address: 0x3b1c2c, Func Offset: 0x8c
// Line 253, Address: 0x3b1c3c, Func Offset: 0x9c
// Line 250, Address: 0x3b1c40, Func Offset: 0xa0
// Line 251, Address: 0x3b1c48, Func Offset: 0xa8
// Line 253, Address: 0x3b1c58, Func Offset: 0xb8
// Line 250, Address: 0x3b1c64, Func Offset: 0xc4
// Line 254, Address: 0x3b1c68, Func Offset: 0xc8
// Line 250, Address: 0x3b1c6c, Func Offset: 0xcc
// Line 252, Address: 0x3b1c70, Func Offset: 0xd0
// Line 250, Address: 0x3b1c74, Func Offset: 0xd4
// Line 254, Address: 0x3b1c78, Func Offset: 0xd8
// Line 250, Address: 0x3b1c7c, Func Offset: 0xdc
// Line 251, Address: 0x3b1d08, Func Offset: 0x168
// Line 253, Address: 0x3b1dac, Func Offset: 0x20c
// Line 254, Address: 0x3b1e50, Func Offset: 0x2b0
// Line 256, Address: 0x3b1e74, Func Offset: 0x2d4
// Line 254, Address: 0x3b1e78, Func Offset: 0x2d8
// Line 256, Address: 0x3b1e7c, Func Offset: 0x2dc
// Line 254, Address: 0x3b1e80, Func Offset: 0x2e0
// Line 256, Address: 0x3b1e94, Func Offset: 0x2f4
// Line 254, Address: 0x3b1e98, Func Offset: 0x2f8
// Line 255, Address: 0x3b1ee0, Func Offset: 0x340
// Line 254, Address: 0x3b1ee4, Func Offset: 0x344
// Line 255, Address: 0x3b1ee8, Func Offset: 0x348
// Line 256, Address: 0x3b1ef8, Func Offset: 0x358
// Line 257, Address: 0x3b1f30, Func Offset: 0x390
// Line 258, Address: 0x3b1f68, Func Offset: 0x3c8
// Line 261, Address: 0x3b1fd0, Func Offset: 0x430
// Line 265, Address: 0x3b2040, Func Offset: 0x4a0
// Line 261, Address: 0x3b2044, Func Offset: 0x4a4
// Line 265, Address: 0x3b2048, Func Offset: 0x4a8
// Line 266, Address: 0x3b211c, Func Offset: 0x57c
// Line 267, Address: 0x3b2120, Func Offset: 0x580
// Func End, Address: 0x3b2148, Func Offset: 0x5a8
}
// collide_update__17xLaserBoltEmitterFRQ217xLaserBoltEmitter4bolt
// Start address: 0x3b2200
void xLaserBoltEmitter::collide_update(bolt& b)
{
xScene& scene;
xRay3 ray;
xCollis player_coll;
xCollis scene_coll;
// Line 200, Address: 0x3b2200, Func Offset: 0
// Line 201, Address: 0x3b2204, Func Offset: 0x4
// Line 200, Address: 0x3b2208, Func Offset: 0x8
// Line 205, Address: 0x3b220c, Func Offset: 0xc
// Line 200, Address: 0x3b2210, Func Offset: 0x10
// Line 208, Address: 0x3b2214, Func Offset: 0x14
// Line 200, Address: 0x3b2218, Func Offset: 0x18
// Line 204, Address: 0x3b2220, Func Offset: 0x20
// Line 201, Address: 0x3b2224, Func Offset: 0x24
// Line 206, Address: 0x3b2228, Func Offset: 0x28
// Line 204, Address: 0x3b222c, Func Offset: 0x2c
// Line 205, Address: 0x3b2240, Func Offset: 0x40
// Line 206, Address: 0x3b2258, Func Offset: 0x58
// Line 207, Address: 0x3b2268, Func Offset: 0x68
// Line 208, Address: 0x3b2270, Func Offset: 0x70
// Line 209, Address: 0x3b2278, Func Offset: 0x78
// Line 213, Address: 0x3b2290, Func Offset: 0x90
// Line 214, Address: 0x3b2294, Func Offset: 0x94
// Line 213, Address: 0x3b2298, Func Offset: 0x98
// Line 214, Address: 0x3b229c, Func Offset: 0x9c
// Line 216, Address: 0x3b22ac, Func Offset: 0xac
// Line 219, Address: 0x3b22c8, Func Offset: 0xc8
// Line 220, Address: 0x3b22cc, Func Offset: 0xcc
// Line 219, Address: 0x3b22d4, Func Offset: 0xd4
// Line 220, Address: 0x3b22d8, Func Offset: 0xd8
// Line 223, Address: 0x3b22e8, Func Offset: 0xe8
// Line 225, Address: 0x3b22f8, Func Offset: 0xf8
// Line 226, Address: 0x3b2300, Func Offset: 0x100
// Line 227, Address: 0x3b2318, Func Offset: 0x118
// Line 228, Address: 0x3b231c, Func Offset: 0x11c
// Line 229, Address: 0x3b2328, Func Offset: 0x128
// Line 231, Address: 0x3b2338, Func Offset: 0x138
// Line 233, Address: 0x3b233c, Func Offset: 0x13c
// Line 231, Address: 0x3b2344, Func Offset: 0x144
// Line 232, Address: 0x3b2348, Func Offset: 0x148
// Line 233, Address: 0x3b2360, Func Offset: 0x160
// Line 234, Address: 0x3b2364, Func Offset: 0x164
// Line 236, Address: 0x3b2368, Func Offset: 0x168
// Line 239, Address: 0x3b2370, Func Offset: 0x170
// Func End, Address: 0x3b2388, Func Offset: 0x188
}
// attach_effects__17xLaserBoltEmitterFQ217xLaserBoltEmitter12fx_when_enumPQ217xLaserBoltEmitter11effect_dataUi
// Start address: 0x3b2390
void xLaserBoltEmitter::attach_effects(fx_when_enum when, effect_data* fx, uint32 fxsize)
{
// Line 167, Address: 0x3b2398, Func Offset: 0x8
// Line 168, Address: 0x3b239c, Func Offset: 0xc
// Line 169, Address: 0x3b23a0, Func Offset: 0x10
// Line 171, Address: 0x3b2408, Func Offset: 0x78
// Func End, Address: 0x3b2410, Func Offset: 0x80
}
// render__17xLaserBoltEmitterFv
// Start address: 0x3b2410
void xLaserBoltEmitter::render()
{
RxObjSpace3DVertex* verts;
RxObjSpace3DVertex* v;
iterator it;
int32 used;
// Line 139, Address: 0x3b2410, Func Offset: 0
// Line 144, Address: 0x3b2414, Func Offset: 0x4
// Line 139, Address: 0x3b2418, Func Offset: 0x8
// Line 150, Address: 0x3b242c, Func Offset: 0x1c
// Line 139, Address: 0x3b2430, Func Offset: 0x20
// Line 144, Address: 0x3b2438, Func Offset: 0x28
// Line 150, Address: 0x3b243c, Func Offset: 0x2c
// Line 151, Address: 0x3b2448, Func Offset: 0x38
// Line 156, Address: 0x3b2458, Func Offset: 0x48
// Line 151, Address: 0x3b2464, Func Offset: 0x54
// Line 156, Address: 0x3b2474, Func Offset: 0x64
// Line 153, Address: 0x3b24a8, Func Offset: 0x98
// Line 156, Address: 0x3b24ac, Func Offset: 0x9c
// Line 153, Address: 0x3b24b0, Func Offset: 0xa0
// Line 154, Address: 0x3b24bc, Func Offset: 0xac
// Line 153, Address: 0x3b24c0, Func Offset: 0xb0
// Line 156, Address: 0x3b24c8, Func Offset: 0xb8
// Line 154, Address: 0x3b24dc, Func Offset: 0xcc
// Line 156, Address: 0x3b24e0, Func Offset: 0xd0
// Line 154, Address: 0x3b24f8, Func Offset: 0xe8
// Line 156, Address: 0x3b2500, Func Offset: 0xf0
// Line 155, Address: 0x3b2508, Func Offset: 0xf8
// Line 156, Address: 0x3b2510, Func Offset: 0x100
// Line 155, Address: 0x3b2514, Func Offset: 0x104
// Line 156, Address: 0x3b2518, Func Offset: 0x108
// Line 155, Address: 0x3b251c, Func Offset: 0x10c
// Line 156, Address: 0x3b2520, Func Offset: 0x110
// Line 155, Address: 0x3b2524, Func Offset: 0x114
// Line 156, Address: 0x3b2528, Func Offset: 0x118
// Line 157, Address: 0x3b2588, Func Offset: 0x178
// Line 160, Address: 0x3b2590, Func Offset: 0x180
// Line 163, Address: 0x3b25d0, Func Offset: 0x1c0
// Func End, Address: 0x3b25f0, Func Offset: 0x1e0
}
// update__17xLaserBoltEmitterFf
// Start address: 0x3b25f0
void xLaserBoltEmitter::update(float32 dt)
{
int32 ci;
iterator it;
bolt& b;
uint8 collided;
float32 prev_dist;
effect_data* itfx;
effect_data* endfx;
effect_data* itfx;
effect_data* endfx;
// Line 85, Address: 0x3b25f0, Func Offset: 0
// Line 89, Address: 0x3b2628, Func Offset: 0x38
// Line 90, Address: 0x3b2654, Func Offset: 0x64
// Line 133, Address: 0x3b2664, Func Offset: 0x74
// Line 90, Address: 0x3b2670, Func Offset: 0x80
// Line 133, Address: 0x3b2680, Func Offset: 0x90
// Line 92, Address: 0x3b26c4, Func Offset: 0xd4
// Line 133, Address: 0x3b26c8, Func Offset: 0xd8
// Line 92, Address: 0x3b26cc, Func Offset: 0xdc
// Line 133, Address: 0x3b26d0, Func Offset: 0xe0
// Line 92, Address: 0x3b26d4, Func Offset: 0xe4
// Line 133, Address: 0x3b26d8, Func Offset: 0xe8
// Line 93, Address: 0x3b26e8, Func Offset: 0xf8
// Line 133, Address: 0x3b26f8, Func Offset: 0x108
// Line 96, Address: 0x3b2708, Func Offset: 0x118
// Line 133, Address: 0x3b2710, Func Offset: 0x120
// Line 98, Address: 0x3b271c, Func Offset: 0x12c
// Line 133, Address: 0x3b2720, Func Offset: 0x130
// Line 98, Address: 0x3b2728, Func Offset: 0x138
// Line 133, Address: 0x3b2734, Func Offset: 0x144
// Line 99, Address: 0x3b2760, Func Offset: 0x170
// Line 133, Address: 0x3b2764, Func Offset: 0x174
// Line 99, Address: 0x3b276c, Func Offset: 0x17c
// Line 133, Address: 0x3b2770, Func Offset: 0x180
// Line 99, Address: 0x3b2778, Func Offset: 0x188
// Line 133, Address: 0x3b277c, Func Offset: 0x18c
// Line 99, Address: 0x3b27b4, Func Offset: 0x1c4
// Line 133, Address: 0x3b27b8, Func Offset: 0x1c8
// Line 99, Address: 0x3b27c8, Func Offset: 0x1d8
// Line 133, Address: 0x3b27cc, Func Offset: 0x1dc
// Line 99, Address: 0x3b27e4, Func Offset: 0x1f4
// Line 133, Address: 0x3b27e8, Func Offset: 0x1f8
// Line 101, Address: 0x3b2828, Func Offset: 0x238
// Line 133, Address: 0x3b282c, Func Offset: 0x23c
// Line 103, Address: 0x3b283c, Func Offset: 0x24c
// Line 133, Address: 0x3b2840, Func Offset: 0x250
// Line 103, Address: 0x3b2844, Func Offset: 0x254
// Line 133, Address: 0x3b2848, Func Offset: 0x258
// Line 104, Address: 0x3b2854, Func Offset: 0x264
// Line 133, Address: 0x3b2858, Func Offset: 0x268
// Line 105, Address: 0x3b285c, Func Offset: 0x26c
// Line 133, Address: 0x3b2860, Func Offset: 0x270
// Line 105, Address: 0x3b2868, Func Offset: 0x278
// Line 133, Address: 0x3b286c, Func Offset: 0x27c
// Line 105, Address: 0x3b2884, Func Offset: 0x294
// Line 133, Address: 0x3b28a0, Func Offset: 0x2b0
// Line 105, Address: 0x3b28a8, Func Offset: 0x2b8
// Line 133, Address: 0x3b28c0, Func Offset: 0x2d0
// Line 105, Address: 0x3b28c8, Func Offset: 0x2d8
// Line 133, Address: 0x3b28e0, Func Offset: 0x2f0
// Line 105, Address: 0x3b28e8, Func Offset: 0x2f8
// Line 133, Address: 0x3b28f0, Func Offset: 0x300
// Line 106, Address: 0x3b2918, Func Offset: 0x328
// Line 133, Address: 0x3b291c, Func Offset: 0x32c
// Line 106, Address: 0x3b2970, Func Offset: 0x380
// Line 133, Address: 0x3b2978, Func Offset: 0x388
// Line 107, Address: 0x3b298c, Func Offset: 0x39c
// Line 108, Address: 0x3b2994, Func Offset: 0x3a4
// Line 110, Address: 0x3b2998, Func Offset: 0x3a8
// Line 133, Address: 0x3b29a0, Func Offset: 0x3b0
// Line 112, Address: 0x3b29b0, Func Offset: 0x3c0
// Line 133, Address: 0x3b29b4, Func Offset: 0x3c4
// Line 114, Address: 0x3b29cc, Func Offset: 0x3dc
// Line 133, Address: 0x3b29d0, Func Offset: 0x3e0
// Line 114, Address: 0x3b29dc, Func Offset: 0x3ec
// Line 133, Address: 0x3b29e4, Func Offset: 0x3f4
// Line 114, Address: 0x3b29f0, Func Offset: 0x400
// Line 133, Address: 0x3b29fc, Func Offset: 0x40c
// Line 114, Address: 0x3b2a0c, Func Offset: 0x41c
// Line 133, Address: 0x3b2a1c, Func Offset: 0x42c
// Line 114, Address: 0x3b2a20, Func Offset: 0x430
// Line 133, Address: 0x3b2a2c, Func Offset: 0x43c
// Line 114, Address: 0x3b2a34, Func Offset: 0x444
// Line 133, Address: 0x3b2a38, Func Offset: 0x448
// Line 116, Address: 0x3b2a3c, Func Offset: 0x44c
// Line 133, Address: 0x3b2a40, Func Offset: 0x450
// Line 123, Address: 0x3b2a5c, Func Offset: 0x46c
// Line 133, Address: 0x3b2a60, Func Offset: 0x470
// Line 123, Address: 0x3b2a6c, Func Offset: 0x47c
// Line 133, Address: 0x3b2a70, Func Offset: 0x480
// Line 127, Address: 0x3b2a90, Func Offset: 0x4a0
// Line 133, Address: 0x3b2a94, Func Offset: 0x4a4
// Line 129, Address: 0x3b2aa4, Func Offset: 0x4b4
// Line 133, Address: 0x3b2aa8, Func Offset: 0x4b8
// Line 129, Address: 0x3b2aac, Func Offset: 0x4bc
// Line 133, Address: 0x3b2ab0, Func Offset: 0x4c0
// Line 130, Address: 0x3b2abc, Func Offset: 0x4cc
// Line 133, Address: 0x3b2ac0, Func Offset: 0x4d0
// Line 131, Address: 0x3b2ac4, Func Offset: 0x4d4
// Line 133, Address: 0x3b2ac8, Func Offset: 0x4d8
// Line 131, Address: 0x3b2ad0, Func Offset: 0x4e0
// Line 133, Address: 0x3b2ad4, Func Offset: 0x4e4
// Line 131, Address: 0x3b2aec, Func Offset: 0x4fc
// Line 133, Address: 0x3b2b08, Func Offset: 0x518
// Line 131, Address: 0x3b2b10, Func Offset: 0x520
// Line 133, Address: 0x3b2b28, Func Offset: 0x538
// Line 131, Address: 0x3b2b30, Func Offset: 0x540
// Line 133, Address: 0x3b2b48, Func Offset: 0x558
// Line 131, Address: 0x3b2b50, Func Offset: 0x560
// Line 133, Address: 0x3b2b58, Func Offset: 0x568
// Line 135, Address: 0x3b2bd0, Func Offset: 0x5e0
// Line 136, Address: 0x3b2bdc, Func Offset: 0x5ec
// Func End, Address: 0x3b2c10, Func Offset: 0x620
}
// emit__17xLaserBoltEmitterFRC5xVec3RC5xVec3
// Start address: 0x3b2c10
void xLaserBoltEmitter::emit(xVec3& loc, xVec3& dir)
{
bolt& b;
effect_data* itfx;
effect_data* endfx;
// Line 63, Address: 0x3b2c10, Func Offset: 0
// Line 64, Address: 0x3b2c2c, Func Offset: 0x1c
// Line 65, Address: 0x3b2c50, Func Offset: 0x40
// Line 68, Address: 0x3b2c60, Func Offset: 0x50
// Line 65, Address: 0x3b2c64, Func Offset: 0x54
// Line 66, Address: 0x3b2c98, Func Offset: 0x88
// Line 65, Address: 0x3b2c9c, Func Offset: 0x8c
// Line 66, Address: 0x3b2cbc, Func Offset: 0xac
// Line 67, Address: 0x3b2ce8, Func Offset: 0xd8
// Line 68, Address: 0x3b2d00, Func Offset: 0xf0
// Line 69, Address: 0x3b2d0c, Func Offset: 0xfc
// Line 70, Address: 0x3b2d14, Func Offset: 0x104
// Line 71, Address: 0x3b2d18, Func Offset: 0x108
// Line 72, Address: 0x3b2d1c, Func Offset: 0x10c
// Line 73, Address: 0x3b2d24, Func Offset: 0x114
// Line 74, Address: 0x3b2dc0, Func Offset: 0x1b0
// Line 77, Address: 0x3b2e70, Func Offset: 0x260
// Line 80, Address: 0x3b2e7c, Func Offset: 0x26c
// Line 81, Address: 0x3b2e94, Func Offset: 0x284
// Line 82, Address: 0x3b2f88, Func Offset: 0x378
// Func End, Address: 0x3b2fa8, Func Offset: 0x398
}
// refresh_config__17xLaserBoltEmitterFv
// Start address: 0x3b2fb0
void xLaserBoltEmitter::refresh_config()
{
// Line 57, Address: 0x3b2fb0, Func Offset: 0
// Line 58, Address: 0x3b2fb8, Func Offset: 0x8
// Line 60, Address: 0x3b2fe8, Func Offset: 0x38
// Func End, Address: 0x3b2ff0, Func Offset: 0x40
}
// reset__17xLaserBoltEmitterFv
// Start address: 0x3b2ff0
void xLaserBoltEmitter::reset()
{
iterator it;
bolt& b;
effect_data* itfx;
effect_data* endfx;
int32 i;
// Line 41, Address: 0x3b2ff0, Func Offset: 0
// Line 42, Address: 0x3b2ff8, Func Offset: 0x8
// Line 41, Address: 0x3b2ffc, Func Offset: 0xc
// Line 42, Address: 0x3b3000, Func Offset: 0x10
// Line 41, Address: 0x3b3004, Func Offset: 0x14
// Line 42, Address: 0x3b3010, Func Offset: 0x20
// Line 41, Address: 0x3b3014, Func Offset: 0x24
// Line 48, Address: 0x3b3018, Func Offset: 0x28
// Line 41, Address: 0x3b301c, Func Offset: 0x2c
// Line 48, Address: 0x3b3020, Func Offset: 0x30
// Line 41, Address: 0x3b3024, Func Offset: 0x34
// Line 42, Address: 0x3b3028, Func Offset: 0x38
// Line 48, Address: 0x3b302c, Func Offset: 0x3c
// Line 42, Address: 0x3b3030, Func Offset: 0x40
// Line 48, Address: 0x3b3040, Func Offset: 0x50
// Line 44, Address: 0x3b307c, Func Offset: 0x8c
// Line 48, Address: 0x3b3080, Func Offset: 0x90
// Line 44, Address: 0x3b308c, Func Offset: 0x9c
// Line 48, Address: 0x3b3090, Func Offset: 0xa0
// Line 44, Address: 0x3b3094, Func Offset: 0xa4
// Line 48, Address: 0x3b3098, Func Offset: 0xa8
// Line 45, Address: 0x3b309c, Func Offset: 0xac
// Line 48, Address: 0x3b30a0, Func Offset: 0xb0
// Line 45, Address: 0x3b30a4, Func Offset: 0xb4
// Line 48, Address: 0x3b30a8, Func Offset: 0xb8
// Line 46, Address: 0x3b30b4, Func Offset: 0xc4
// Line 48, Address: 0x3b30b8, Func Offset: 0xc8
// Line 47, Address: 0x3b30bc, Func Offset: 0xcc
// Line 48, Address: 0x3b30c0, Func Offset: 0xd0
// Line 47, Address: 0x3b30c8, Func Offset: 0xd8
// Line 48, Address: 0x3b30cc, Func Offset: 0xdc
// Line 47, Address: 0x3b30e4, Func Offset: 0xf4
// Line 48, Address: 0x3b3108, Func Offset: 0x118
// Line 47, Address: 0x3b3110, Func Offset: 0x120
// Line 48, Address: 0x3b3130, Func Offset: 0x140
// Line 47, Address: 0x3b3138, Func Offset: 0x148
// Line 48, Address: 0x3b3158, Func Offset: 0x168
// Line 47, Address: 0x3b3160, Func Offset: 0x170
// Line 48, Address: 0x3b3168, Func Offset: 0x178
// Line 50, Address: 0x3b31e0, Func Offset: 0x1f0
// Line 52, Address: 0x3b31e8, Func Offset: 0x1f8
// Line 51, Address: 0x3b31ec, Func Offset: 0x1fc
// Line 53, Address: 0x3b31f0, Func Offset: 0x200
// Line 52, Address: 0x3b31fc, Func Offset: 0x20c
// Line 53, Address: 0x3b3200, Func Offset: 0x210
// Line 54, Address: 0x3b3270, Func Offset: 0x280
// Func End, Address: 0x3b3294, Func Offset: 0x2a4
}
// set_texture__17xLaserBoltEmitterFPCc
// Start address: 0x3b32a0
void xLaserBoltEmitter::set_texture(int8* name)
{
// Line 24, Address: 0x3b32a0, Func Offset: 0
// Func End, Address: 0x3b32f0, Func Offset: 0x50
}
// init__17xLaserBoltEmitterFUiPCc
// Start address: 0x3b32f0
void xLaserBoltEmitter::init(uint32 max_bolts)
{
// Line 16, Address: 0x3b32f0, Func Offset: 0
// Line 18, Address: 0x3b32f4, Func Offset: 0x4
// Line 16, Address: 0x3b32f8, Func Offset: 0x8
// Line 17, Address: 0x3b3308, Func Offset: 0x18
// Line 18, Address: 0x3b3310, Func Offset: 0x20
// Line 19, Address: 0x3b331c, Func Offset: 0x2c
// Line 21, Address: 0x3b3390, Func Offset: 0xa0
// Func End, Address: 0x3b33a4, Func Offset: 0xb4
}
| 21.469997 | 111 | 0.757497 | stravant |
8463bcfbe92f88665f6f45b4ad5b2c2d371da16f | 3,669 | c++ | C++ | 07p/plaut04/src/createBoundingBox.c++ | st970703/AUTO07P-Update-to-Python-3.0 | fb2d2aebf2127fa914064d01ed62c0acb5f6421c | [
"Apache-2.0"
] | null | null | null | 07p/plaut04/src/createBoundingBox.c++ | st970703/AUTO07P-Update-to-Python-3.0 | fb2d2aebf2127fa914064d01ed62c0acb5f6421c | [
"Apache-2.0"
] | null | null | null | 07p/plaut04/src/createBoundingBox.c++ | st970703/AUTO07P-Update-to-Python-3.0 | fb2d2aebf2127fa914064d01ed62c0acb5f6421c | [
"Apache-2.0"
] | null | null | null | #include "createBoundingBox.h"
#include <Inventor/So.h>
///////////////////////////////////////////////////////////////////////////////
//
SoSeparator *
drawLine(SbVec3f pointS, SbVec3f pointE, SbVec3f color, float thickness, bool ticker, bool text, int dir)
//
///////////////////////////////////////////////////////////////////////////////
{
SoSeparator * aSep = new SoSeparator;
SoCylinder * aCylinder = new SoCylinder;
aCylinder->radius = thickness;
aCylinder->height = (pointS-pointE).length();
SoMaterial *aMtl = new SoMaterial;
aMtl->ambientColor.setValue(0.8,0.8,0.8);
aMtl->diffuseColor.setValue(0.8,0.8,0.8);
aMtl->specularColor.setValue(0.5,0.5,0.5);
aMtl->shininess = 0.9;
aMtl->transparency = 0.0;
SoTransform * xTrans = new SoTransform;
if(dir==1)
xTrans->rotation.setValue(SbVec3f(0, 0, 1), M_PI_2);
else if(dir == 2)
xTrans->rotation.setValue(SbVec3f(0, 1, 0), M_PI_2);
else if(dir == 3)
xTrans->rotation.setValue(SbVec3f(1, 0, 0), M_PI_2);
xTrans->translation.setValue((pointE+pointS)/2);
aSep->addChild(xTrans);
aSep->addChild(aMtl);
aSep->addChild(aCylinder);
return aSep;
}
///////////////////////////////////////////////////////////////////////////////
//
SoSeparator *
createBoundingBox()
//
///////////////////////////////////////////////////////////////////////////////
{
SbVec3f pointS, pointE, color;
float thickness = 0.003;
float xMin, yMin, zMin, xMax, yMax, zMax;
xMin = yMin = zMin = -1;
xMax = yMax = zMax = 1;
SoSeparator *bdBoxSep = new SoSeparator;
bdBoxSep->setName("bdBox");
color.setValue(1,1,1);
pointS.setValue(xMin,yMin,zMin);
pointE.setValue(xMax, yMin, zMin);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 1));
pointS.setValue(xMin, yMax, zMin);
pointE.setValue(xMax, yMax, zMin);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 1));
pointS.setValue(xMin, yMax, zMax);
pointE.setValue(xMax, yMax, zMax);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 1));
pointS.setValue(xMin, yMin, zMax);
pointE.setValue(xMax, yMin, zMax);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 1));
pointS.setValue(xMin, yMin, zMin);
pointE.setValue(xMin, yMin, zMax);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 3));
pointS.setValue(xMax, yMin, zMin);
pointE.setValue(xMax, yMin, zMax);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 3));
pointS.setValue(xMax, yMax, zMin);
pointE.setValue(xMax, yMax, zMax);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 3));
pointS.setValue(xMin, yMax, zMin);
pointE.setValue(xMin, yMax, zMax);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 3));
pointS.setValue(xMin, yMin, zMin);
pointE.setValue(xMin, yMax, zMin);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 2));
pointS.setValue(xMax, yMin, zMin);
pointE.setValue(xMax, yMax, zMin);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 2));
pointS.setValue(xMax, yMin, zMax);
pointE.setValue(xMax, yMax, zMax);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 2));
pointS.setValue(xMin, yMin, zMax);
pointE.setValue(xMin, yMax, zMax);
bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 2));
return bdBoxSep;
}
| 33.66055 | 105 | 0.611883 | st970703 |
84665d3c2e7f8a41845f8a470cfb7131d230c737 | 212 | cpp | C++ | solutions/rjKdSzNl.cpp | luyencode/cpp-solutions | 627397fb887654e9f5ee64cfb73d708f6f6706f7 | [
"MIT"
] | 60 | 2021-04-10T11:17:33.000Z | 2022-03-23T06:15:42.000Z | solutions/rjKdSzNl.cpp | letuankiet-29-10-2002/cpp-solutions | 7d9cddf211af54ff207da883b469f4ddd75d5916 | [
"MIT"
] | 1 | 2021-08-13T11:32:27.000Z | 2021-08-13T11:32:27.000Z | solutions/rjKdSzNl.cpp | letuankiet-29-10-2002/cpp-solutions | 7d9cddf211af54ff207da883b469f4ddd75d5916 | [
"MIT"
] | 67 | 2021-04-10T17:32:50.000Z | 2022-03-23T15:50:17.000Z | /*
Sưu tầm bởi @nguyenvanhieuvn
Thực hành nhiều bài tập hơn tại https://luyencode.net/
*/
void Xuat(LIST l)
{
for(NODE* p = l.pHead; p != NULL; p = p->pNext)
{
printf("%4d", p->info);
}
} | 17.666667 | 56 | 0.556604 | luyencode |
8466a016fc3774145b4c54ea2b84665fea9d17ea | 3,361 | cpp | C++ | searchcore/src/tests/proton/documentdb/move_operation_limiter/move_operation_limiter_test.cpp | kashiish/vespa | 307de4bb24463d0f36cd8391a7b8df75bd0949b2 | [
"Apache-2.0"
] | null | null | null | searchcore/src/tests/proton/documentdb/move_operation_limiter/move_operation_limiter_test.cpp | kashiish/vespa | 307de4bb24463d0f36cd8391a7b8df75bd0949b2 | [
"Apache-2.0"
] | null | null | null | searchcore/src/tests/proton/documentdb/move_operation_limiter/move_operation_limiter_test.cpp | kashiish/vespa | 307de4bb24463d0f36cd8391a7b8df75bd0949b2 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/searchcore/proton/server/i_blockable_maintenance_job.h>
#include <vespa/searchcore/proton/server/move_operation_limiter.h>
#include <vespa/vespalib/testkit/testapp.h>
#include <queue>
#include <vespa/log/log.h>
LOG_SETUP("move_operation_limiter_test");
using namespace proton;
struct MyBlockableMaintenanceJob : public IBlockableMaintenanceJob {
bool blocked;
MyBlockableMaintenanceJob()
: IBlockableMaintenanceJob("my_job", 1s, 1s),
blocked(false)
{}
void setBlocked(BlockedReason reason) override {
ASSERT_TRUE(reason == BlockedReason::OUTSTANDING_OPS);
EXPECT_FALSE(blocked);
blocked = true;
}
void unBlock(BlockedReason reason) override {
ASSERT_TRUE(reason == BlockedReason::OUTSTANDING_OPS);
EXPECT_TRUE(blocked);
blocked = false;
}
bool run() override { return true; }
void onStop() override { }
};
struct Fixture {
using OpsQueue = std::queue<std::shared_ptr<vespalib::IDestructorCallback>>;
using MoveOperationLimiterSP = std::shared_ptr<MoveOperationLimiter>;
MyBlockableMaintenanceJob job;
MoveOperationLimiterSP limiter;
OpsQueue ops;
Fixture(uint32_t maxOutstandingOps = 2)
: job(),
limiter(std::make_shared<MoveOperationLimiter>(&job, maxOutstandingOps)),
ops()
{}
void beginOp() { ops.push(limiter->beginOperation()); }
void endOp() { ops.pop(); }
void clearJob() { limiter->clearJob(); }
void clearLimiter() { limiter = MoveOperationLimiterSP(); }
void assertAboveLimit() const {
EXPECT_TRUE(limiter->isAboveLimit());
EXPECT_TRUE(job.blocked);
}
void assertBelowLimit() const {
EXPECT_FALSE(limiter->isAboveLimit());
EXPECT_FALSE(job.blocked);
}
};
TEST_F("require that hasPending reflects if any jobs are outstanding", Fixture)
{
EXPECT_FALSE(f.limiter->hasPending());
f.beginOp();
EXPECT_TRUE(f.limiter->hasPending());
f.endOp();
EXPECT_FALSE(f.limiter->hasPending());
}
TEST_F("require that job is blocked / unblocked when crossing max outstanding ops boundaries", Fixture)
{
f.beginOp();
TEST_DO(f.assertBelowLimit());
f.beginOp();
TEST_DO(f.assertAboveLimit());
f.beginOp();
TEST_DO(f.assertAboveLimit());
f.endOp();
TEST_DO(f.assertAboveLimit());
f.endOp();
TEST_DO(f.assertBelowLimit());
f.endOp();
TEST_DO(f.assertBelowLimit());
}
TEST_F("require that cleared job is not blocked when crossing max ops boundary", Fixture)
{
f.beginOp();
f.clearJob();
f.beginOp();
EXPECT_FALSE(f.job.blocked);
EXPECT_TRUE(f.limiter->isAboveLimit());
}
TEST_F("require that cleared job is not unblocked when crossing max ops boundary", Fixture)
{
f.beginOp();
f.beginOp();
TEST_DO(f.assertAboveLimit());
f.clearJob();
f.endOp();
EXPECT_TRUE(f.job.blocked);
EXPECT_FALSE(f.limiter->isAboveLimit());
}
TEST_F("require that destructor callback has reference to limiter via shared ptr", Fixture)
{
f.beginOp();
f.beginOp();
TEST_DO(f.assertAboveLimit());
f.clearLimiter();
f.endOp();
EXPECT_FALSE(f.job.blocked);
}
TEST_MAIN()
{
TEST_RUN_ALL();
}
| 28.483051 | 118 | 0.678667 | kashiish |
84680ee68589bc89dcfe67faceeb660016ab63f8 | 489 | cpp | C++ | test/is_unsigned.cpp | morrow1nd/mystd | 77281d806c3cc2010b76e38ac236c4036a454d7e | [
"MIT"
] | null | null | null | test/is_unsigned.cpp | morrow1nd/mystd | 77281d806c3cc2010b76e38ac236c4036a454d7e | [
"MIT"
] | null | null | null | test/is_unsigned.cpp | morrow1nd/mystd | 77281d806c3cc2010b76e38ac236c4036a454d7e | [
"MIT"
] | null | null | null | #include "test.h"
#include <inner/type_traits.h>
class A {};
enum E : unsigned {};
enum class Ec : unsigned {};
enum Ecs : signed int {};
int main()
{
assert(is_unsigned_v<A> == false);
assert(is_unsigned_v<float> == false);
assert(is_unsigned_v<signed int> == false);
assert(is_unsigned_v<unsigned int> == true);
assert(is_unsigned_v<E> == false);
assert(is_unsigned_v<Ec> == false);
assert(is_unsigned_v<Ecs> == false);
return 0;
}
| 23.285714 | 49 | 0.619632 | morrow1nd |
846b5bfe272887a9ed614e4913e8b826c6e4a2cd | 18,893 | cc | C++ | rest/testing/rest_collection_test.cc | kstepanmpmg/mldb | f78791cd34d01796705c0f173a14359ec1b2e021 | [
"Apache-2.0"
] | 1 | 2019-04-29T12:39:34.000Z | 2019-04-29T12:39:34.000Z | rest/testing/rest_collection_test.cc | tomzhang/mldb | a09cf2d9ca454d1966b9e49ae69f2fe6bf571494 | [
"Apache-2.0"
] | 2 | 2021-03-20T05:52:26.000Z | 2021-11-15T17:52:54.000Z | rest/testing/rest_collection_test.cc | matebestek/mldb | f78791cd34d01796705c0f173a14359ec1b2e021 | [
"Apache-2.0"
] | 1 | 2018-11-23T20:03:38.000Z | 2018-11-23T20:03:38.000Z | // This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
/* rest_collection_test.cc
Jeremy Barnes, 25 March 2014
Copyright (c) 2014 mldb.ai inc. All rights reserved.
*/
#include "mldb/utils/runner.h"
#include "mldb/utils/vector_utils.h"
#include "mldb/rest/rest_collection.h"
#include "mldb/rest/rest_collection_impl.h"
#include "mldb/types/value_description.h"
#include "mldb/types/structure_description.h"
#include "mldb/types/tuple_description.h"
#include "mldb/types/map_description.h"
#include "mldb/rest/cancellation_exception.h"
#include <thread>
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace MLDB;
struct TestConfig {
std::string id;
std::map<std::string, std::string> params;
};
DECLARE_STRUCTURE_DESCRIPTION(TestConfig);
DEFINE_STRUCTURE_DESCRIPTION(TestConfig);
TestConfigDescription::
TestConfigDescription()
{
addField("id", &TestConfig::id, "");
addField("params", &TestConfig::params, "");
}
struct TestStatus {
std::string id;
std::string state;
Json::Value progress;
};
DECLARE_STRUCTURE_DESCRIPTION(TestStatus);
DEFINE_STRUCTURE_DESCRIPTION(TestStatus);
TestStatusDescription::
TestStatusDescription()
{
addField("id", &TestStatus::id, "");
addField("state", &TestStatus::state, "");
addField("progress", &TestStatus::progress, "");
}
struct TestObject {
std::shared_ptr<TestConfig> config;
};
struct TestCollection
: public RestConfigurableCollection<std::string, TestObject,
TestConfig, TestStatus> {
typedef RestConfigurableCollection<std::string, TestObject,
TestConfig, TestStatus> Base;
TestCollection(RestEntity * owner = nullptr)
: Base("object", "objects", owner ? owner : this)
{
}
TestStatus getStatusFinished(std::string key,
const TestObject & obj) const
{
TestStatus result;
result.state = "ok";
result.id = key;
return result;
}
TestStatus getStatusLoading(std::string key,
const BackgroundTask & task) const
{
TestStatus result;
result.state = "initializing";
result.id = key;
result.progress = task.progress;
return result;
}
std::string getKey(TestConfig & config)
{
return config.id;
}
std::shared_ptr<TestObject>
construct(TestConfig config, const OnProgress & onProgress) const
{
auto result = std::make_shared<TestObject>();
result->config.reset(new TestConfig(std::move(config)));
return result;
}
};
#if 0
BOOST_AUTO_TEST_CASE( test_s3_collection_store )
{
S3CollectionConfigStore config("s3://tests.datacratic.com/unit_tests/rest_collection_test");
cerr << jsonEncode(config.getAll());
config.clear();
BOOST_CHECK_EQUAL(config.keys(), vector<string>());
config.set("hello", "world");
cerr << jsonEncode(config.get("hello")) << endl;
BOOST_CHECK_EQUAL(config.get("hello"), "world");
}
BOOST_AUTO_TEST_CASE( test_s3_collection_config_persistence )
{
// This test makes sure that if we set peristent configuration, create
// an object and then destroy the collection, when we recreate the
// collection the same objects are still there.
auto config = std::make_shared<S3CollectionConfigStore>("s3://tests.datacratic.com/unit_tests/rest_collection_test2");
// Get rid of anything that was hanging around
config->clear();
TestConfig config1{"item1", { { "key1", "value1" } } };
{
TestCollection collection;
collection.attachConfig(config);
collection.handlePost(config1);
// Check that it got correctly into the config store
BOOST_CHECK_EQUAL(collection.getKeys(), vector<string>({"item1"}));
BOOST_CHECK_EQUAL(config->keys(), vector<string>({"item1"}));
BOOST_CHECK_EQUAL(config->get("item1"), jsonEncode(config1));
}
{
TestCollection collection;
collection.attachConfig(config);
// Check that it correctly loaded up its objects from the config
// store
BOOST_CHECK_EQUAL(collection.getKeys(), vector<string>({"item1"}));
BOOST_CHECK_EQUAL(config->keys(), vector<string>({"item1"}));
BOOST_CHECK_EQUAL(config->get("item1"), jsonEncode(config1));
}
}
#endif
BOOST_AUTO_TEST_CASE( test_watching )
{
typedef RestCollection<std::string, std::string> Coll;
RestDirectory dir(&dir, "dir");
Coll collection("item", "items", &dir);
dir.addEntity("items", collection);
WatchT<Coll::ChildEvent> w = dir.watch({"items", "elements:*"},
true /* catchUp */,
string("w1"));
WatchT<Coll::ChildEvent> w2 = dir.watch({"items", "elements:test2"},
true /* catchUp */,
string("w2"));
WatchT<std::vector<Utf8String>, Coll::ChildEvent> w3
= dir.watchWithPathT<Coll::ChildEvent>({"items", "elements:*"},
true /* catchUp */,
string("w3"));
// Wrong watch type should throw immediately
{
MLDB_TRACE_EXCEPTIONS(false);
BOOST_CHECK_THROW(WatchT<int> w4 = dir.watch({"items", "elements:*"},
true /* catchUp */,
string("w4")),
std::exception);
}
BOOST_CHECK(!w.any());
collection.addEntry("test1", std::make_shared<std::string>("hello1"));
BOOST_CHECK(w.any());
BOOST_CHECK(!w2.any());
auto val = w.pop();
BOOST_CHECK_EQUAL(val.key, "test1");
BOOST_CHECK_EQUAL(val.event, CE_NEW);
BOOST_REQUIRE(val.value);
BOOST_CHECK_EQUAL(*val.value, "hello1");
BOOST_CHECK(!w.any());
std::vector<Utf8String> path;
Coll::ChildEvent ev;
std::tie(path, ev) = w3.pop();
BOOST_CHECK_EQUAL(path.size(), 1);
BOOST_CHECK_EQUAL(path, vector<Utf8String>({"items"}));
collection.deleteEntry("test1");
BOOST_CHECK(w.any());
BOOST_CHECK(!w2.any());
val = w.pop();
BOOST_CHECK_EQUAL(val.key, "test1");
BOOST_CHECK_EQUAL(val.event, CE_DELETED);
BOOST_REQUIRE(val.value);
BOOST_CHECK_EQUAL(*val.value, "hello1");
collection.addEntry("test2", std::make_shared<std::string>("hello2"));
BOOST_CHECK(w.any());
BOOST_CHECK(w2.any());
val = w2.pop();
BOOST_CHECK_EQUAL(val.key, "test2");
BOOST_CHECK_EQUAL(val.event, CE_NEW);
BOOST_REQUIRE(val.value);
BOOST_CHECK_EQUAL(*val.value, "hello2");
}
struct ConfigColl: public RestConfigurableCollection<std::string, std::string, std::string, std::string> {
ConfigColl(RestEntity * parent)
: RestConfigurableCollection<std::string, std::string, std::string, std::string>("item", "items", parent)
{
}
virtual std::string
getStatusFinished(std::string key, const std::string & value) const
{
return value;
}
virtual std::string getKey(string & config)
{
return config;
}
virtual std::shared_ptr<std::string>
construct(string config, const OnProgress & onProgress) const
{
return std::make_shared<std::string>(config);
}
};
BOOST_AUTO_TEST_CASE( test_watching_config )
{
ConfigColl collection(&collection);
WatchT<std::string, std::shared_ptr<std::string> > w
= collection.watch({"config:*"}, true /* catchUp */, string("w"));
#if 0
WatchT<Coll::ChildEvent> w2 = dir.watch({"items", "elements:test2"},
true /* catchUp */);
// Wrong watch type should throw immediately
{
MLDB_TRACE_EXCEPTIONS(false);
BOOST_CHECK_THROW(WatchT<int> w3 = dir.watch({"items", "elements:*"},
true /* catchUp */),
std::exception);
}
BOOST_CHECK(!w.any());
collection.addEntry("test1", std::make_shared<std::string>("hello1"));
BOOST_CHECK(w.any());
BOOST_CHECK(!w2.any());
auto val = w.pop();
BOOST_CHECK_EQUAL(val.key, "test1");
BOOST_CHECK_EQUAL(val.event, CE_NEW);
BOOST_REQUIRE(val.value);
BOOST_CHECK_EQUAL(*val.value, "hello1");
BOOST_CHECK(!w.any());
collection.deleteEntry("test1");
BOOST_CHECK(w.any());
BOOST_CHECK(!w2.any());
val = w.pop();
BOOST_CHECK_EQUAL(val.key, "test1");
BOOST_CHECK_EQUAL(val.event, CE_DELETED);
BOOST_REQUIRE(val.value);
BOOST_CHECK_EQUAL(*val.value, "hello1");
collection.addEntry("test2", std::make_shared<std::string>("hello2"));
BOOST_CHECK(w.any());
BOOST_CHECK(w2.any());
val = w2.pop();
BOOST_CHECK_EQUAL(val.key, "test2");
BOOST_CHECK_EQUAL(val.event, CE_NEW);
BOOST_REQUIRE(val.value);
BOOST_CHECK_EQUAL(*val.value, "hello2");
#endif
}
struct RecursiveCollection: public RestCollection<std::string, RecursiveCollection> {
RecursiveCollection(const std::string & name,
RestEntity * parent)
: RestCollection<std::string, RecursiveCollection>("item", "items", parent),
name(name)
{
}
~RecursiveCollection()
{
//cerr << "destroying recursive collection " << name << endl;
}
std::pair<const std::type_info *,
std::shared_ptr<const ValueDescription> >
getWatchBoundType(const ResourceSpec & spec)
{
if (spec.size() > 1) {
if (spec[0].channel == "children")
return getWatchBoundType(ResourceSpec(spec.begin() + 1, spec.end()));
throw MLDB::Exception("only children channel known");
}
if (spec[0].channel == "children")
return make_pair(&typeid(std::tuple<RestEntityChildEvent>),
nullptr);
else if (spec[0].channel == "elements")
return make_pair(&typeid(std::tuple<ChildEvent>), nullptr);
else throw MLDB::Exception("unknown channel");
}
std::string name;
};
BOOST_AUTO_TEST_CASE( test_watching_multi_level )
{
RecursiveCollection coll("coll", &coll);
WatchT<RecursiveCollection::ChildEvent> w
= coll.watch({"*", "elements:*"}, true /* catchUp */, string("w"));
BOOST_CHECK(!w.any());
WatchT<std::string> w2;
// watch is wrong type
{
MLDB_TRACE_EXCEPTIONS(false);
BOOST_CHECK_THROW(w2 = coll.watch({"*", "elements:*"}, true /* catchUp */, string("w2")),
std::exception);
}
auto coll1 = std::make_shared<RecursiveCollection>("coll1", nullptr);
auto coll2 = std::make_shared<RecursiveCollection>("coll2", nullptr);
auto coll11 = std::make_shared<RecursiveCollection>("coll11", coll1.get());
auto coll12 = std::make_shared<RecursiveCollection>("coll12", coll1.get());
auto coll21 = std::make_shared<RecursiveCollection>("coll21", coll2.get());
auto coll22 = std::make_shared<RecursiveCollection>("coll22", coll2.get());
coll.addEntry("coll1", coll1);
BOOST_CHECK(!w.any());
BOOST_CHECK(!w2.any());
coll1->addEntry("coll11", coll11);
BOOST_CHECK(w.any());
auto val = w.pop();
BOOST_CHECK_EQUAL(val.key, "coll11");
BOOST_CHECK_EQUAL(val.event, CE_NEW);
BOOST_CHECK_EQUAL(val.value, coll11);
coll1->addEntry("coll12", coll12);
BOOST_CHECK(w.any());
val = w.pop();
BOOST_CHECK_EQUAL(val.key, "coll12");
BOOST_CHECK_EQUAL(val.event, CE_NEW);
BOOST_CHECK_EQUAL(val.value, coll12);
BOOST_CHECK(!w.any());
coll1->deleteEntry("coll11");
BOOST_CHECK(w.any());
val = w.pop();
BOOST_CHECK_EQUAL(val.key, "coll11");
BOOST_CHECK_EQUAL(val.event, CE_DELETED);
BOOST_CHECK_EQUAL(val.value, coll11);
BOOST_CHECK(!w.any());
// Now delete the parent entry. This should notify us of our child
// entries disappearing.
BOOST_CHECK(coll.deleteEntry("coll1"));
BOOST_CHECK(w.any());
val = w.pop();
BOOST_CHECK_EQUAL(val.key, "coll12");
BOOST_CHECK_EQUAL(val.event, CE_DELETED);
BOOST_CHECK_EQUAL(val.value, coll12);
BOOST_CHECK(!w.any());
// Add a new entry that already has children. We should get notified
// of those children immediately that we add it.
coll2->addEntry("coll21", coll21);
coll2->addEntry("coll22", coll22);
coll.addEntry("coll2", coll2);
BOOST_CHECK(w.any());
val = w.pop();
BOOST_CHECK_EQUAL(val.key, "coll21");
BOOST_CHECK_EQUAL(val.event, CE_NEW);
BOOST_CHECK_EQUAL(val.value, coll21);
val = w.pop();
BOOST_CHECK_EQUAL(val.key, "coll22");
BOOST_CHECK_EQUAL(val.event, CE_NEW);
BOOST_CHECK_EQUAL(val.value, coll22);
BOOST_CHECK(!w.any());
}
struct SlowToCreateTestCollection: public TestCollection {
~SlowToCreateTestCollection()
{
// don't do this to test that we can shutdown from the
// base class without a pure virtual method call
//this->shutdown();
}
std::shared_ptr<TestObject>
construct(TestConfig config, const OnProgress & onProgress) const
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
auto result = std::make_shared<TestObject>();
result->config.reset(new TestConfig(std::move(config)));
return result;
}
};
// Stress test for MLDB-1259
BOOST_AUTO_TEST_CASE ( test_destroying_while_creating )
{
int numTests = 100;
for (unsigned i = 0; i < numTests; ++i) {
cerr << "test " << i << " of " << numTests << endl;
SlowToCreateTestCollection collection;
TestConfig config{"item1", {}};
collection.handlePost("item1", config, true /* must be true */);
// Destroy it while still being created, to test that we
// don't crash
}
}
// Stress test for MLDB-408
BOOST_AUTO_TEST_CASE ( test_cancelling_while_creating )
{
int numTests = 100;
for (unsigned i = 0; i < numTests; ++i) {
SlowToCreateTestCollection collection;
TestConfig config{"item1", {}};
collection.handlePost("item1", config, true /* must be true */);
auto entry = collection.getEntry("item1");
if (entry.second) {
entry.second->cancel();
cerr << entry.second->getState() << endl;
}
else {
BOOST_CHECK(false);
}
}
}
struct SlowToCreateTestCollectionWithCancellation: public TestCollection {
~SlowToCreateTestCollectionWithCancellation()
{
this->shutdown();
}
std::shared_ptr<TestObject>
construct(TestConfig config, const OnProgress & onProgress) const
{
Json::Value progress;
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if (!onProgress(progress)) {
cerr << "cancelledddddd" << endl;
throw CancellationException("cancellation");
}
}
auto result = std::make_shared<TestObject>();
result->config.reset(new TestConfig(std::move(config)));
return result;
}
};
/** This is a stress test of the RestCollection, to ensure that cancelling entries does
not crash MLDB.
*/
BOOST_AUTO_TEST_CASE( stress_test_collection_cancellation )
{
SlowToCreateTestCollectionWithCancellation collection;
std::atomic<bool> shutdown(false);
std::atomic<unsigned int> cancelled(0);
std::atomic<unsigned int> lateCancellation(0);
std::atomic<unsigned int> created(0);
std::atomic<unsigned int> underConstruction(0);
std::atomic<unsigned int> deletedAfterCreation(0);
std::atomic<unsigned int> cancelledBeforeCreation(0);
auto addThread = [&] ()
{
while (!shutdown) {
string key = "item2";
TestConfig config{key, {}};
try {
collection.handlePost(key, config, true /* must be new entry */);
auto entry = collection.getEntry(key);
if (entry.first) {
cerr << "entry created" << endl;
created++;
}
else {
cerr << "entry is under construction" << endl;
underConstruction++;
}
}
catch (AnnotatedException & ex) {
BOOST_ERROR("failed creating an entry or to get "
"the entry while under construction");
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
auto deletedEntry = collection.deleteEntry(key);
if (deletedEntry)
deletedAfterCreation++;
else
cancelledBeforeCreation++;
};
};
auto cancelThread = [&] ()
{
while (!shutdown) {
std::string key = "item2";
try {
auto entry = collection.getEntry(key);
if (entry.second) {
if (entry.second->cancel())
cancelled++;
}
else {
cerr << "failed to cancel the entry because the entry was created" << endl;
lateCancellation++;
}
}
catch (AnnotatedException & ex) {
cerr << "failed to get the entry" << endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
};
};
std::vector<std::thread> threads;
std::thread creater(addThread);
unsigned int numCancellationThreads = 10;
for (unsigned i = 0; i < numCancellationThreads; ++i) {
threads.emplace_back(cancelThread);
}
std::this_thread::sleep_for(std::chrono::seconds(1));
shutdown = true;
for (auto & t: threads)
t.join();
creater.join();
cerr << "created " << created
<< " under construction " << underConstruction
<< " deleted after creation " << deletedAfterCreation
<< " cancelled before creation " << cancelledBeforeCreation
<< " cancelled " << cancelled
<< " late cancellation " << lateCancellation
<< endl;
BOOST_CHECK_EQUAL(created + underConstruction, deletedAfterCreation + cancelledBeforeCreation);
}
| 29.11094 | 122 | 0.59313 | kstepanmpmg |
846b7788b1cbc490a2332944f7c5da71bb009b46 | 40,874 | cc | C++ | src/poly/isl_util.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 286 | 2020-06-23T06:40:44.000Z | 2022-03-30T01:27:49.000Z | src/poly/isl_util.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 10 | 2020-07-31T03:26:59.000Z | 2021-12-27T15:00:54.000Z | src/poly/isl_util.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 30 | 2020-07-17T01:04:14.000Z | 2021-12-27T14:05:19.000Z | /**
* Copyright 2020-2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "poly/isl_util.h"
#include "poly/log_util.h"
namespace akg {
namespace ir {
namespace poly {
////////////////////////////////////////////////////////////////////////////////
// local types
////////////////////////////////////////////////////////////////////////////////
enum isl_schedule_node_fine_adjustment_type {
FINE_ADJUSTMENT_NONE = 0,
FINE_ADJUSTMENT_MOD,
FINE_ADJUSTMENT_SCALE,
FINE_ADJUSTMENT_SCALE_DOWN,
};
struct isl_schedule_node_fine_adjustment_data {
isl_union_pw_aff *result;
const char *name;
isl_val *value;
enum isl_schedule_node_fine_adjustment_type type;
};
////////////////////////////////////////////////////////////////////////////////
// local declarations
////////////////////////////////////////////////////////////////////////////////
static inline __isl_give isl_multi_union_pw_aff *isl_multi_union_pw_aff_collapse(__isl_take isl_multi_union_pw_aff *aff,
int dim, __isl_take isl_val *val);
static inline __isl_give isl_val *isl_schedule_node_band_find_collapse_coeff(__isl_take isl_schedule_node *band,
int dim);
static inline isl_stat isl_pw_aff_fine_adjustment(__isl_take isl_pw_aff *pa, void *user);
static inline isl::multi_union_pw_aff isl_multi_union_pw_aff_collapse(const isl::multi_union_pw_aff &aff, int dim,
const isl::val &value) {
return isl::manage(isl_multi_union_pw_aff_collapse(aff.copy(), dim, value.copy()));
}
static inline isl::val isl_schedule_node_band_find_collapse_coeff(const isl::schedule_node_band &band, int dim) {
return isl::manage(isl_schedule_node_band_find_collapse_coeff(band.copy(), dim));
}
////////////////////////////////////////////////////////////////////////////////
// C++ wrappers for unexposed isl functions
////////////////////////////////////////////////////////////////////////////////
bool isl_aff_is_cst(const isl::aff &a) {
isl_aff *const internal = a.get();
return isl_aff_is_cst(internal);
}
std::string isl_set_get_dim_name(const isl::set &s, enum isl_dim_type type, unsigned int pos) {
const isl::id &id = isl_set_get_dim_id(s, type, pos);
return id.name();
}
isl::id isl_set_get_dim_id(const isl::set &s, enum isl_dim_type type, unsigned int pos) {
isl_id *const id = isl_set_get_dim_id(s.get(), type, pos);
return isl::manage(id);
}
int isl_set_find_dim_by_id(const isl::set &s, enum isl_dim_type type, const isl::id &id) {
return isl_set_find_dim_by_id(s.get(), type, id.get());
}
int isl_set_find_dim_by_name(const isl::set &s, enum isl_dim_type type, const std::string &name) {
return isl_set_find_dim_by_name(s.get(), type, name.c_str());
}
unsigned isl_set_dim(const isl::set &s, enum isl_dim_type type) {
isl_set *const internal = s.get();
const isl_size size = isl_set_dim(internal, type);
return size;
}
long isl_set_plain_get_num_si(const isl::set &s, unsigned int pos) {
const isl::val &value = isl_set_plain_get_val_if_fixed(s, isl_dim_set, pos);
const long result = value.get_num_si();
return result;
}
isl::val isl_set_plain_get_val_if_fixed(const isl::set &s, enum isl_dim_type type, unsigned int pos) {
isl_set *const internal = s.get();
isl_val *const value = isl_set_plain_get_val_if_fixed(internal, type, pos);
return isl::manage(value);
}
isl::set isl_set_move_dims(const isl::set &s, enum isl_dim_type dst_type, unsigned int dst_pos,
enum isl_dim_type src_type, unsigned int src_pos, unsigned int n) {
isl_set *const internal = isl_set_move_dims(s.copy(), dst_type, dst_pos, src_type, src_pos, n);
return isl::manage(internal);
}
std::string isl_map_get_dim_name(const isl::map &m, enum isl_dim_type type, unsigned int pos) {
const isl::id &id = isl_map_get_dim_id(m, type, pos);
return id.name();
}
isl::id isl_map_get_dim_id(const isl::map &m, enum isl_dim_type type, unsigned int pos) {
isl_map *const internal = m.get();
isl_id *const id = isl_map_get_dim_id(internal, type, pos);
return isl::manage(id);
}
bool isl_map_involves_dims(const isl::map &m, enum isl_dim_type type, unsigned int first, unsigned n) {
isl_map *const internal = m.get();
return isl_map_involves_dims(internal, type, first, n);
}
isl::map isl_map_drop_constraints_not_involving_dims(const isl::map &m, enum isl_dim_type type, unsigned int first,
unsigned n) {
isl_map *const internal = isl_map_copy(m.get());
isl_map *const drop = isl_map_drop_constraints_not_involving_dims(internal, type, first, n);
return isl::manage(drop);
}
isl::union_map isl_union_map_align_params(const isl::union_map &map, const isl::space &space) {
isl_union_map *const aligned = isl_union_map_align_params(map.copy(), space.copy());
return isl::manage(aligned);
}
isl::union_pw_aff_list isl_union_pw_aff_list_insert(const isl::union_pw_aff_list &list, unsigned int pos,
const isl::union_pw_aff &aff) {
isl_union_pw_aff *const element = aff.copy();
isl_union_pw_aff_list *result = list.copy();
result = isl_union_pw_aff_list_insert(result, pos, element);
return isl::manage(result);
}
isl::space isl_space_set_alloc(isl::ctx ctx, unsigned int nparam, unsigned int dim) {
isl_space *const internal = isl_space_set_alloc(ctx.get(), nparam, dim);
return isl::manage(internal);
}
isl::id isl_space_get_dim_id(const isl::space &space, enum isl_dim_type type, unsigned int pos) {
isl_space *const internal = space.get();
isl_id *const id = isl_space_get_dim_id(internal, type, pos);
return isl::manage(id);
}
isl::space isl_space_set_dim_id(const isl::space &space, enum isl_dim_type type, unsigned int pos, const isl::id &id) {
isl_id *const internal_id = id.copy();
isl_space *internal_space = space.copy();
internal_space = isl_space_set_dim_id(internal_space, type, pos, internal_id);
return isl::manage(internal_space);
}
////////////////////////////////////////////////////////////////////////////////
// Misc.
////////////////////////////////////////////////////////////////////////////////
std::vector<std::string> isl_set_dim_names(const isl::set &set, enum isl_dim_type type) {
std::vector<std::string> result;
const unsigned int count = isl_set_dim(set, type);
for (unsigned int i = 0; i < count; ++i) {
const std::string ¤t = isl_set_get_dim_name(set, type, i);
result.push_back(current);
}
return result;
}
std::vector<std::string> isl_set_all_names(const isl::set &set) {
std::vector<std::string> result;
const unsigned int set_dimensions = isl_set_dim(set, isl_dim_set);
for (unsigned int i = 0; i < set_dimensions; ++i) {
const std::string ¤t = isl_set_get_dim_name(set, isl_dim_set, i);
result.push_back(current);
}
const unsigned int parameters = isl_set_dim(set, isl_dim_param);
for (unsigned int i = 0; i < parameters; ++i) {
const std::string ¤t = isl_set_get_dim_name(set, isl_dim_param, i);
result.push_back(current);
}
return result;
}
std::vector<int> isl_set_lexmax_extract_upper_bounds(const isl::set &set, const std::vector<std::string> &names) {
std::vector<int> result;
const std::size_t count = names.size();
for (std::size_t i = 0; i < count; ++i) {
const int position = isl_set_find_dim_by_name(set, isl_dim_set, names[i]);
if (position >= 0) {
// The input set is supposed to be a lexmax
const isl::val &lexmax = isl_set_plain_get_val_if_fixed(set, isl_dim_set, position);
const isl::val &upper_bound = lexmax.add(1);
const int value = static_cast<int>(upper_bound.get_num_si());
result.push_back(value);
}
}
return result;
}
std::vector<int> isl_set_lexmax_extract_upper_bounds(const isl::set &s, const std::vector<int> &dimensions) {
std::vector<int> result;
const int size = static_cast<int>(isl_set_dim(s, isl_dim_set));
for (auto dimension : dimensions) {
if (dimension < size) {
// We need to add 1 because the input set is a lexmax
const isl::val &lexmax = isl_set_plain_get_val_if_fixed(s, isl_dim_set, dimension);
const isl::val &upper_bound = lexmax.add(1);
const int value = static_cast<int>(upper_bound.get_num_si());
result.push_back(value);
} else {
log::Warn("cannot retrieve size for dimension " + std::to_string(dimension));
}
}
return result;
}
isl::space isl_space_copy_param_names(const isl::space &space, const isl::space &source) {
isl::space result = space;
const unsigned int params = source.dim(isl_dim_param);
const unsigned int limit = std::min(params, result.dim(isl_dim_param));
if (params > limit) {
log::Warn("destination space is smaller than source space");
}
for (unsigned int i = 0; i < limit; ++i) {
const isl::id &name = isl_space_get_dim_id(source, isl_dim_param, i);
result = isl_space_set_dim_id(result, isl_dim_param, i, name);
}
return result;
}
isl::space isl_space_set_cat(const isl::space &left, const isl::space &right) {
const unsigned int params = left.dim(isl_dim_param);
const unsigned int out = left.dim(isl_dim_out) + right.dim(isl_dim_out);
// No constructor that takes both isl_dim_params and isl_dim_out sizes in the C++ wrapper!
isl_ctx *const ctx = left.ctx().get();
isl_space *const result = isl_space_set_alloc(ctx, params, out);
// Note: we currently do not need to extract dim names if they were named in the input spaces.
return isl::manage(result);
}
isl::multi_union_pw_aff isl_multi_union_pw_aff_cat(const isl::multi_union_pw_aff &left,
const isl::multi_union_pw_aff &right) {
const unsigned int left_count = left.size();
const unsigned int right_count = right.size();
if (!left_count) {
return right;
} else if (!right_count) {
return left;
}
const isl::union_pw_aff_list &left_list = left.union_pw_aff_list();
const isl::union_pw_aff_list &right_list = right.union_pw_aff_list();
const isl::union_pw_aff_list &list = left_list.concat(right_list);
const isl::space &left_space = left.space();
const isl::space &right_space = right.space();
const isl::space &space = isl_space_set_cat(left_space, right_space);
const isl::multi_union_pw_aff &result = isl::multi_union_pw_aff(space, list);
return result;
}
__isl_give isl_multi_union_pw_aff *isl_multi_union_pw_aff_cat(__isl_take isl_multi_union_pw_aff *left,
__isl_take isl_multi_union_pw_aff *right) {
const isl::multi_union_pw_aff &wrapped = isl_multi_union_pw_aff_cat(isl::manage(left), isl::manage(right));
isl_multi_union_pw_aff *const result = isl_multi_union_pw_aff_copy(wrapped.get());
return result;
}
isl::multi_union_pw_aff isl_multi_union_pw_aff_insert(const isl::multi_union_pw_aff &aff, unsigned pos,
const isl::union_pw_aff &el) {
const isl::space &initial_space = aff.space();
const isl::space &space = initial_space.add_dims(isl_dim_out, 1);
const isl::union_pw_aff_list &initial_list = aff.union_pw_aff_list();
const isl::union_pw_aff_list &list = isl_union_pw_aff_list_insert(initial_list, pos, el);
const isl::multi_union_pw_aff &result = isl::multi_union_pw_aff(space, list);
return result;
}
////////////////////////////////////////////////////////////////////////////////
// isl_schedule_node utilities
////////////////////////////////////////////////////////////////////////////////
bool isl_schedule_node_is_band(const isl::schedule_node &node) { return node.isa<isl::schedule_node_band>(); }
bool isl_schedule_node_is_sequence(const isl::schedule_node &node) { return node.isa<isl::schedule_node_sequence>(); }
bool isl_schedule_node_has_single_child(const isl::schedule_node &node) { return node.n_children() == 1; }
bool isl_schedule_node_band_can_unsplit(const isl::schedule_node_band &band) {
return isl_schedule_node_has_single_child(band) && band.child(0).isa<isl::schedule_node_band>();
}
////////////////////////////////////////////////////////////////////////////////
// isl_schedule_node_band utilities
////////////////////////////////////////////////////////////////////////////////
std::vector<bool> isl_schedule_node_band_get_coincidence(const isl::schedule_node_band &band) {
std::vector<bool> result;
const unsigned int members = band.n_member();
if (!members) {
return result;
}
for (unsigned int i = 0; i < members; ++i) {
const bool coincident = band.member_get_coincident(static_cast<int>(i));
result.push_back(coincident);
}
return result;
}
isl::schedule_node_band isl_schedule_node_band_set_coincidence(const isl::schedule_node_band &band,
const std::vector<bool> &coincidence) {
const std::size_t members = static_cast<size_t>(band.n_member());
const std::size_t size = coincidence.size();
const std::size_t limit = std::min(members, size);
if (members != size) {
log::Warn("band size differs from coincidence vector!");
}
isl::schedule_node_band result = band;
for (std::size_t i = 0; i < limit; ++i) {
const int pos = static_cast<int>(i);
const bool coincident = coincidence[i];
result = result.member_set_coincident(pos, coincident);
}
return result;
}
isl::schedule_node_band isl_schedule_node_band_member_copy_properties(const isl::schedule_node_band &band, int pos,
const isl::schedule_node_band &wrapped_original) {
isl_schedule_node *const original = wrapped_original.get();
const isl_bool coincident = isl_schedule_node_band_member_get_coincident(original, pos);
const enum isl_ast_loop_type loop_type = isl_schedule_node_band_member_get_ast_loop_type(original, pos);
const enum isl_ast_loop_type isolate_type = isl_schedule_node_band_member_get_isolate_ast_loop_type(original, pos);
isl_schedule_node *internal = isl_schedule_node_copy(band.get());
internal = isl_schedule_node_band_member_set_coincident(internal, pos, coincident);
internal = isl_schedule_node_band_member_set_ast_loop_type(internal, pos, loop_type);
internal = isl_schedule_node_band_member_set_isolate_ast_loop_type(internal, pos, isolate_type);
const isl::schedule_node &node = isl::manage(internal);
return node.as<isl::schedule_node_band>();
}
isl::schedule_node_band isl_schedule_node_band_copy_properties(const isl::schedule_node &node,
const isl::schedule_node &original) {
return isl_schedule_node_band_copy_properties(node.as<isl::schedule_node_band>(),
original.as<isl::schedule_node_band>());
}
isl::schedule_node_band isl_schedule_node_band_copy_properties(const isl::schedule_node &node,
const isl::schedule_node_band &original) {
return isl_schedule_node_band_copy_properties(node.as<isl::schedule_node_band>(), original);
}
isl::schedule_node_band isl_schedule_node_band_copy_properties(const isl::schedule_node_band &band,
const isl::schedule_node &original) {
return isl_schedule_node_band_copy_properties(band, original.as<isl::schedule_node_band>());
}
isl::schedule_node_band isl_schedule_node_band_copy_properties(const isl::schedule_node_band &band,
const isl::schedule_node_band &original) {
isl::schedule_node_band result = band;
const bool permutable = original.permutable();
const isl::union_set &ast_build_options = original.ast_build_options();
result = result.set_permutable(permutable);
result = result.set_ast_build_options(ast_build_options);
const int limit = static_cast<int>(std::min(band.n_member(), original.n_member()));
for (int i = 0; i < limit; ++i) {
result = isl_schedule_node_band_member_copy_properties(result, i, original);
}
return result;
}
isl::schedule_node_band isl_schedule_node_band_replace_partial_schedule(const isl::schedule_node &node,
const isl::multi_union_pw_aff &partial,
bool keep_properties) {
return isl_schedule_node_band_replace_partial_schedule(node.as<isl::schedule_node_band>(), partial, keep_properties);
}
isl::schedule_node_band isl_schedule_node_band_replace_partial_schedule(const isl::schedule_node_band &band,
const isl::multi_union_pw_aff &partial,
bool keep_properties) {
// The new schedule will be inserted above the current band
isl::schedule_node_band result = band.insert_partial_schedule(partial).as<isl::schedule_node_band>();
if (keep_properties) {
const isl::schedule_node_band &original = result.child(0).as<isl::schedule_node_band>();
result = isl_schedule_node_band_copy_properties(result, original);
}
// Do not forget to delete the previous band node and then move back to the "new" current position!
result = result.child(0).del().parent().as<isl::schedule_node_band>();
return result;
}
isl::set isl_schedule_node_band_lexmax(const isl::schedule_node &node) {
return isl_schedule_node_band_lexmax(node.as<isl::schedule_node_band>());
}
isl::set isl_schedule_node_band_lexmax(const isl::schedule_node_band &band) {
const isl::union_set &domain = band.domain();
const isl::union_map &schedule = band.partial_schedule_union_map();
const isl::union_set &application = domain.apply(schedule);
const isl::union_set &lexmax = application.lexmax();
return isl::set::from_union_set(lexmax);
}
////////////////////////////////////////////////////////////////////////////////
// isl_schedule_node_band transformations
////////////////////////////////////////////////////////////////////////////////
isl::schedule_node_band isl_schedule_node_band_interchange(const isl::schedule_node_band &band, unsigned int first,
unsigned int second) {
isl::multi_union_pw_aff partial = band.get_partial_schedule();
const unsigned int dims = partial.size();
if (first >= dims || second >= dims) {
log::Warn(std::string(__func__) + ": target dimension out of bounds");
return band;
}
const isl::union_pw_aff &aff_1 = partial.at(first);
const isl::union_pw_aff &aff_2 = partial.at(second);
partial = partial.set_at(first, aff_2);
partial = partial.set_at(second, aff_1);
// Save the properties
const bool permutable = band.permutable();
std::vector<bool> coincidence = isl_schedule_node_band_get_coincidence(band);
// Interchange the coincidences
const bool tmp = coincidence[first];
coincidence[first] = coincidence[second];
coincidence[second] = tmp;
isl::schedule_node_band result = isl_schedule_node_band_replace_partial_schedule(band, partial, false);
result = result.set_permutable(permutable);
result = isl_schedule_node_band_set_coincidence(band, coincidence);
return result;
}
isl::schedule_node_band isl_schedule_node_band_stripmine(const isl::schedule_node_band &band, unsigned int dim,
int value) {
isl::ctx ctx = band.ctx();
const isl::val &val = isl::val(ctx, value);
return isl_schedule_node_band_stripmine(band, dim, val);
}
isl::schedule_node_band isl_schedule_node_band_stripmine(const isl::schedule_node_band &band, unsigned int dim,
const isl::val &value) {
const unsigned int members = band.n_member();
if (dim >= members) {
log::Warn(std::string(__func__) + ": cannot stripmine out of bounds dimension");
return band;
}
isl::multi_union_pw_aff schedule = band.partial_schedule();
const isl::union_pw_aff &div = schedule.at(dim).scale_down(value);
const isl::union_pw_aff &mod = schedule.at(dim).mod(value);
schedule = schedule.set_at(dim, div);
schedule = isl_multi_union_pw_aff_insert(schedule, dim + 1, mod);
const bool permutable = band.permutable();
std::vector<bool> coincidence = isl_schedule_node_band_get_coincidence(band);
auto position = coincidence.begin() + dim + 1;
coincidence.insert(position, coincidence[dim]);
isl::schedule_node_band result = isl_schedule_node_band_replace_partial_schedule(band, schedule, true);
result = result.set_permutable(permutable);
result = isl_schedule_node_band_set_coincidence(result, coincidence);
return result;
}
isl::schedule_node_band isl_schedule_node_band_collapse(const isl::schedule_node_band &band, unsigned int dim) {
const unsigned int members = band.n_member();
if (dim >= members) {
return band;
}
const isl::val &coeff = isl_schedule_node_band_find_collapse_coeff(band, dim);
isl::multi_union_pw_aff partial = band.partial_schedule();
partial = isl_multi_union_pw_aff_collapse(partial, dim, coeff);
const bool permutable = band.permutable();
std::vector<bool> coincidence = isl_schedule_node_band_get_coincidence(band);
const bool collapsed_coincidence = coincidence[dim] && coincidence[dim + 1];
coincidence[dim] = collapsed_coincidence;
auto position = coincidence.begin() + dim + 1;
coincidence.erase(position);
isl::schedule_node_band result = isl_schedule_node_band_replace_partial_schedule(band, partial, false);
result = result.set_permutable(permutable);
result = isl_schedule_node_band_set_coincidence(result, coincidence);
return result;
}
isl::schedule_node_band isl_schedule_node_band_fine_adjustment(const isl::schedule_node_band &band,
enum isl_schedule_node_fine_adjustment_type type,
const std::string &name, unsigned int dimension,
const isl::val &value) {
isl::multi_union_pw_aff partial = band.partial_schedule();
const unsigned int dims = partial.size();
if (dimension >= dims) {
log::Warn(std::string(__func__) + ": target dimension out of bounds");
return band;
}
// Save the properties
const bool permutable = band.permutable();
std::vector<bool> coincidence = isl_schedule_node_band_get_coincidence(band);
const isl::union_pw_aff &target = partial.at(dimension);
struct isl_schedule_node_fine_adjustment_data arg = {
.result = NULL,
.name = name.c_str(),
.value = value.get(),
.type = type,
};
isl_union_pw_aff_foreach_pw_aff(target.get(), isl_pw_aff_fine_adjustment, &arg);
isl::union_pw_aff adjusted = isl::manage(arg.result);
// Replace the target in the partial schedule
partial = partial.set_at(dimension, adjusted);
// Insert the new schedule and delete the previous one.
isl::schedule_node_band result = isl_schedule_node_band_replace_partial_schedule(band, partial, false);
result = result.set_permutable(permutable);
result = isl_schedule_node_band_set_coincidence(result, coincidence);
return result;
}
isl::schedule_node_band isl_schedule_node_band_fine_adjustment(const isl::schedule_node_band &band,
enum isl_schedule_node_fine_adjustment_type type,
const std::string &name, unsigned int dimension,
int value) {
isl::ctx ctx = band.ctx();
const isl::val &val = isl::val(ctx, value);
return isl_schedule_node_band_fine_adjustment(band, type, name, dimension, val);
}
////////////////////////////////////////////////////////////////////////////////
// schedule tree transformations (on a schedule_node)
////////////////////////////////////////////////////////////////////////////////
isl::schedule_node_band isl_schedule_node_band_unsplit(const isl::schedule_node_band &band) {
// We assume isl_schedule_node_band_can_unsplit() has been checked
isl::schedule_node_band result = band;
// Insert the new partial schedule at the current position
{
const isl::schedule_node_band &child = result.child(0).as<isl::schedule_node_band>();
const isl::multi_union_pw_aff &top = result.partial_schedule();
const isl::multi_union_pw_aff &bottom = child.partial_schedule();
const isl::multi_union_pw_aff &partial = isl_multi_union_pw_aff_cat(top, bottom);
result = result.insert_partial_schedule(partial).as<isl::schedule_node_band>();
}
// Set the band's properties
// NOTE: we do not set AST loop type or AST build options!
{
const isl::schedule_node_band &first = result.child(0).as<isl::schedule_node_band>();
const isl::schedule_node_band &second = first.child(0).as<isl::schedule_node_band>();
const bool permutable = first.permutable() && second.permutable();
result = result.set_permutable(permutable);
const unsigned int first_size = first.n_member();
for (unsigned int i = 0; i < first_size; ++i) {
const bool coincident = first.member_get_coincident(i);
result = result.member_set_coincident(i, coincident);
}
const unsigned int second_size = second.n_member();
for (unsigned int i = 0; i < second_size; ++i) {
const bool coincident = second.member_get_coincident(i);
const unsigned int member = first_size + i;
result = result.member_set_coincident(member, coincident);
}
}
// Remove the two successive children we merged
{
isl::schedule_node node = result.child(0);
node = node.del();
node = node.del();
result = node.parent().as<isl::schedule_node_band>();
}
return result;
}
isl::schedule_node_band isl_schedule_node_band_fully_unsplit(const isl::schedule_node_band &band) {
isl::schedule_node_band result = band;
while (isl_schedule_node_band_can_unsplit(result)) {
result = isl_schedule_node_band_unsplit(result);
}
return result;
}
isl::schedule_node isl_schedule_node_band_fully_split(const isl::schedule_node_band &band) {
isl::schedule_node_band result = band;
while (result.n_member() > 1) {
const int kept = result.n_member() - 1;
result = result.split(kept);
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
// isl_schedule transformations
////////////////////////////////////////////////////////////////////////////////
isl::schedule isl_schedule_collapse(const isl::schedule &schedule, unsigned int first, unsigned int last) {
if (last < first) {
return schedule;
}
const isl::schedule_node &root = schedule.root();
isl::schedule_node_band band = root.child(0).as<isl::schedule_node_band>();
for (unsigned int dim = last; dim-- > first;) {
band = isl_schedule_node_band_collapse(band, dim);
}
const isl::schedule &result = band.schedule();
return result;
}
////////////////////////////////////////////////////////////////////////////////
// String conversions for wrapped isl objects
////////////////////////////////////////////////////////////////////////////////
std::string to_c_code_string(const isl::schedule &s) { return to_c_code_string(s.get()); }
std::string to_c_code_string(const isl::schedule_constraints &c) { return to_c_code_string(c.get()); }
std::string to_block_string(const isl::schedule &s) { return to_block_string(s.get()); }
std::string to_block_string(const isl::union_map &map) { return to_block_string(map.get()); }
std::string to_block_string(const isl::schedule_constraints &constraints) { return to_block_string(constraints.get()); }
////////////////////////////////////////////////////////////////////////////////
// "Simple" C code string
////////////////////////////////////////////////////////////////////////////////
std::string to_c_code_string(__isl_keep isl_schedule *const schedule) {
isl_ctx *const ctx = isl_schedule_get_ctx(schedule);
isl_ast_build *const build = isl_ast_build_alloc(ctx);
isl_ast_node *const ast = isl_ast_build_node_from_schedule(build, isl_schedule_copy(schedule));
isl_printer *printer = isl_printer_to_str(ctx);
printer = isl_printer_set_output_format(printer, ISL_FORMAT_C);
printer = isl_printer_print_ast_node(printer, ast);
char *const s = isl_printer_get_str(printer);
std::string result(s);
isl_printer_free(printer);
isl_ast_build_free(build);
isl_ast_node_free(ast);
free(s);
return result;
}
std::string to_c_code_string(__isl_keep isl_schedule_constraints *const input) {
isl_schedule_constraints *const constraints = isl_schedule_constraints_copy(input);
isl_ctx *const ctx = isl_schedule_constraints_get_ctx(constraints);
const int previous_behaviour = isl_options_get_on_error(ctx);
isl_options_set_on_error(ctx, ISL_ON_ERROR_CONTINUE);
isl_schedule *const schedule = isl_schedule_constraints_compute_schedule(constraints);
isl_options_set_on_error(ctx, previous_behaviour);
const std::string result = to_c_code_string(schedule);
isl_schedule_free(schedule);
return result;
}
////////////////////////////////////////////////////////////////////////////////
// Strings
////////////////////////////////////////////////////////////////////////////////
template <typename T, __isl_keep isl_ctx *(*ctx_getter)(__isl_keep T),
__isl_give isl_printer *(*printer_function)(__isl_give isl_printer *, __isl_keep T)>
std::string isl_to_block_str(T t) {
isl_ctx *const ctx = ctx_getter(t);
isl_printer *printer = isl_printer_to_str(ctx);
printer = isl_printer_set_yaml_style(printer, ISL_YAML_STYLE_BLOCK);
printer = printer_function(printer, t);
char *const block = isl_printer_get_str(printer);
const std::string result(block);
isl_printer_free(printer);
free(block);
return result;
}
std::string to_block_string(__isl_keep isl_schedule *const schedule) {
return isl_to_block_str<isl_schedule *, isl_schedule_get_ctx, isl_printer_print_schedule>(schedule);
}
static inline isl_stat isl_println_basic_map(__isl_take isl_basic_map *const map, void *user) {
isl_printer **printer = (isl_printer **)user;
*printer = isl_printer_print_basic_map(*printer, map);
*printer = isl_printer_print_str(*printer, "\n");
isl_basic_map_free(map);
return isl_stat_ok;
}
static inline __isl_give isl_printer *isl_printer_print_map_as_block(__isl_give isl_printer *printer,
__isl_keep isl_map *const map) {
isl_map_foreach_basic_map(map, isl_println_basic_map, (void *)&printer);
return printer;
}
static inline isl_stat isl_println_map(__isl_take isl_map *const map, void *user) {
isl_printer **printer = (isl_printer **)user;
*printer = isl_printer_print_map_as_block(*printer, map);
isl_map_free(map);
return isl_stat_ok;
}
static inline __isl_give isl_printer *isl_printer_print_union_map_as_block(__isl_give isl_printer *printer,
__isl_keep isl_union_map *const map) {
isl_union_map_foreach_map(map, isl_println_map, (void *)&printer);
return printer;
}
std::string to_block_string(__isl_keep isl_union_map *const map) {
return isl_to_block_str<isl_union_map *, isl_union_map_get_ctx, isl_printer_print_union_map_as_block>(map);
}
static inline __isl_give isl_printer *isl_printer_print_schedule_constraints_as_block(
__isl_give isl_printer *printer, __isl_keep isl_schedule_constraints *const constraints) {
isl_union_set *const domain = isl_schedule_constraints_get_domain(constraints);
if (domain) {
printer = isl_printer_print_str(printer, "domain:\n");
printer = isl_printer_print_union_set(printer, domain);
printer = isl_printer_print_str(printer, "\n");
isl_union_set_free(domain);
}
isl_set *const context = isl_schedule_constraints_get_context(constraints);
if (context) {
if (!isl_set_plain_is_empty(context)) {
printer = isl_printer_print_str(printer, "context:\n");
printer = isl_printer_print_set(printer, context);
printer = isl_printer_print_str(printer, "\n");
}
isl_set_free(context);
}
#define _print_constraints_union_map(getter, title) \
do { \
isl_union_map *const _target_map = getter(constraints); \
if (_target_map) { \
if (!isl_union_map_plain_is_empty(_target_map)) { \
const std::string &_target_string = to_block_string(_target_map); \
printer = isl_printer_print_str(printer, title ":\n"); \
printer = isl_printer_print_str(printer, _target_string.c_str()); \
} \
isl_union_map_free(_target_map); \
} \
} while (0)
_print_constraints_union_map(isl_schedule_constraints_get_validity, "validity");
_print_constraints_union_map(isl_schedule_constraints_get_proximity, "proximity");
_print_constraints_union_map(isl_schedule_constraints_get_coincidence, "coincidence");
_print_constraints_union_map(isl_schedule_constraints_get_conditional_validity, "conditional validity");
_print_constraints_union_map(isl_schedule_constraints_get_conditional_validity_condition,
"conditional validity condition");
#undef _print_constraints_union_map
return printer;
}
std::string to_block_string(__isl_keep isl_schedule_constraints *const constraints) {
const std::string result = isl_to_block_str<isl_schedule_constraints *, isl_schedule_constraints_get_ctx,
isl_printer_print_schedule_constraints_as_block>(constraints);
return result;
}
////////////////////////////////////////////////////////////////////////////////
// local definitions
////////////////////////////////////////////////////////////////////////////////
__isl_give isl_multi_union_pw_aff *isl_multi_union_pw_aff_collapse(__isl_take isl_multi_union_pw_aff *aff, int dim,
__isl_take isl_val *val) {
if (!aff) {
return aff;
}
const isl_size count = isl_multi_union_pw_aff_size(aff);
if (!count || dim >= count - 1) {
return aff;
}
isl_union_pw_aff *const target_1 = isl_multi_union_pw_aff_get_at(aff, dim);
isl_union_pw_aff *const target_2 = isl_multi_union_pw_aff_get_at(aff, dim + 1);
isl_union_pw_aff_dump(target_1);
isl_union_pw_aff_dump(target_2);
isl_union_pw_aff *const scaled = isl_union_pw_aff_scale_val(target_1, val);
isl_union_pw_aff *const collapsed = isl_union_pw_aff_add(scaled, target_2);
isl_union_pw_aff_dump(collapsed);
const isl_size size = isl_multi_union_pw_aff_size(aff);
isl_union_pw_aff_list *list = NULL;
if (dim != 0) {
isl_union_pw_aff *const first = isl_multi_union_pw_aff_get_at(aff, 0);
list = isl_union_pw_aff_list_from_union_pw_aff(first);
for (isl_size i = 1; i < dim; ++i) {
isl_union_pw_aff *const current = isl_multi_union_pw_aff_get_at(aff, i);
list = isl_union_pw_aff_list_add(list, current);
}
list = isl_union_pw_aff_list_add(list, collapsed);
} else {
list = isl_union_pw_aff_list_from_union_pw_aff(collapsed);
}
for (isl_size i = dim + 2; i < size; ++i) {
isl_union_pw_aff *const current = isl_multi_union_pw_aff_get_at(aff, i);
list = isl_union_pw_aff_list_add(list, current);
}
isl_ctx *const ctx = isl_multi_union_pw_aff_get_ctx(aff);
isl_space *const original_space = isl_multi_union_pw_aff_get_space(aff);
const isl_size params = isl_space_dim(original_space, isl_dim_param);
const isl_size new_size = isl_union_pw_aff_list_size(list);
isl_space *const space = isl_space_set_alloc(ctx, params, new_size);
isl_multi_union_pw_aff *const result = isl_multi_union_pw_aff_from_union_pw_aff_list(space, list);
isl_space_free(original_space);
isl_multi_union_pw_aff_free(aff);
return result;
}
__isl_give isl_val *isl_schedule_node_band_find_collapse_coeff(__isl_take isl_schedule_node *band, int dim) {
isl_union_set *domain = isl_schedule_node_get_domain(band);
isl_multi_union_pw_aff *const prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(band);
const isl_size prefix_size = isl_multi_union_pw_aff_size(prefix);
isl_multi_union_pw_aff *partial = isl_schedule_node_band_get_partial_schedule(band);
isl_multi_union_pw_aff *const schedule = isl_multi_union_pw_aff_cat(prefix, partial);
isl_union_map *const map = isl_union_map_from_multi_union_pw_aff(schedule);
domain = isl_union_set_apply(domain, map);
isl_union_set *const union_lexmax = isl_union_set_lexmax(domain);
isl_set *const lexmax = isl_set_from_union_set(union_lexmax);
const isl_size target = prefix_size + dim + 1;
isl_val *coeff = isl_set_plain_get_val_if_fixed(lexmax, isl_dim_set, target);
coeff = isl_val_add_ui(coeff, 1);
isl_set_free(lexmax);
return coeff;
}
isl_stat isl_pw_aff_fine_adjustment(__isl_take isl_pw_aff *pa, void *user) {
struct isl_schedule_node_fine_adjustment_data *arg = (struct isl_schedule_node_fine_adjustment_data *)user;
isl_id *const id = isl_pw_aff_get_tuple_id(pa, isl_dim_in);
const char *const name = isl_id_get_name(id);
if (!strcmp(name, arg->name)) {
isl_val *const val = isl_val_copy(arg->value);
if (arg->type == FINE_ADJUSTMENT_SCALE_DOWN) {
pa = isl_pw_aff_scale_down_val(pa, val);
} else if (arg->type == FINE_ADJUSTMENT_MOD) {
pa = isl_pw_aff_mod_val(pa, val);
} else if (arg->type == FINE_ADJUSTMENT_SCALE) {
pa = isl_pw_aff_scale_val(pa, val);
} else {
fprintf(stderr, "%s: unknown adjustment operation!\n", __func__);
}
}
isl_id_free(id);
if (arg->result) {
arg->result = isl_union_pw_aff_add_pw_aff(arg->result, pa);
} else {
arg->result = isl_union_pw_aff_from_pw_aff(pa);
}
return isl_stat_ok;
}
////////////////////////////////////////////////////////////////////////////////
// "special" definitions
////////////////////////////////////////////////////////////////////////////////
// clang-format off
#define _define_isl_schedule_node_band_fine(name, type) \
isl::schedule_node_band isl_schedule_node_band_fine_##name( \
const isl::schedule_node_band &band, const std::string &name, unsigned int dim, int value) { \
const isl::schedule_node_band &result = isl_schedule_node_band_fine_adjustment(band, type, name, dim, value); \
return result; \
} \
\
isl::schedule_node_band isl_schedule_node_band_fine_##name( \
const isl::schedule_node_band &band, const std::string &name, unsigned int dim, const isl::val &value) { \
const isl::schedule_node_band &result = isl_schedule_node_band_fine_adjustment(band, type, name, dim, value); \
return result; \
}
_define_isl_schedule_node_band_fine(mod, FINE_ADJUSTMENT_MOD)
_define_isl_schedule_node_band_fine(scale, FINE_ADJUSTMENT_SCALE)
_define_isl_schedule_node_band_fine(scale_down, FINE_ADJUSTMENT_SCALE_DOWN)
#undef _define_isl_schedule_node_band_fine
} // namespace poly
} // namespace ir
} // namespace akg
| 42.488565 | 120 | 0.659588 | KnowingNothing |
846b9f3f9bf7efb24aa2c15eea48bed5a40938e1 | 545 | cpp | C++ | owRenderNew/DX11_Creator.cpp | adan830/OpenWow | 9b6e9c248bd185b1677fe616d2a3a81a35ca8894 | [
"Apache-2.0"
] | null | null | null | owRenderNew/DX11_Creator.cpp | adan830/OpenWow | 9b6e9c248bd185b1677fe616d2a3a81a35ca8894 | [
"Apache-2.0"
] | null | null | null | owRenderNew/DX11_Creator.cpp | adan830/OpenWow | 9b6e9c248bd185b1677fe616d2a3a81a35ca8894 | [
"Apache-2.0"
] | 1 | 2020-05-11T13:32:49.000Z | 2020-05-11T13:32:49.000Z | #include "stdafx.h"
// General
#include "DX11_Creator.h"
// Additional
#include "DX11\\RenderDeviceDX11.h"
#include "DX11\\RenderWindowDX11.h"
RenderDevice* DX11_Creator::CreateRenderDevice()
{
return new RenderDeviceDX11();
}
RenderWindow* DX11_Creator::CreateRenderWindow(HWND hWnd, RenderDevice* device, cstring windowName, int windowWidth, int windowHeight, bool vSync)
{
RenderDeviceDX11* pDevice = dynamic_cast<RenderDeviceDX11*>(device);
return new RenderWindowDX11(hWnd, pDevice, windowName, windowWidth, windowHeight, vSync);
}
| 25.952381 | 146 | 0.785321 | adan830 |
846c94fb21cd5ee6524e9ae4b0c77e222305b806 | 1,883 | cpp | C++ | src/game/shared/neotokyo/neo_controlpoint.cpp | L-Leite/neotokyo-re | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | 4 | 2017-08-29T15:39:53.000Z | 2019-06-04T07:37:48.000Z | src/game/shared/neotokyo/neo_controlpoint.cpp | Ochii/neotokyo | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | null | null | null | src/game/shared/neotokyo/neo_controlpoint.cpp | Ochii/neotokyo | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | 1 | 2021-08-10T20:01:00.000Z | 2021-08-10T20:01:00.000Z | #include "cbase.h"
#include "neo_controlpoint.h"
#include "neo_gamerules.h"
IMPLEMENT_NETWORKCLASS_ALIASED( NeoControlPoint, DT_NeoControlPoint )
BEGIN_NETWORK_TABLE( CNeoControlPoint, DT_NeoControlPoint )
#ifdef CLIENT_DLL
//RecvPropStringT( RECVINFO( m_Name ) ),
RecvPropInt( RECVINFO( m_ID ) ),
RecvPropVector( RECVINFO( m_Position ) ),
RecvPropInt( RECVINFO( m_Icon ) ),
RecvPropInt( RECVINFO( m_Status ) ),
RecvPropInt( RECVINFO( m_Owner ) ),
RecvPropInt( RECVINFO( m_Radius ) ),
#else
//SendPropStringT( SENDINFO( m_Name ) ),
SendPropInt( SENDINFO( m_ID ) ),
SendPropVector( SENDINFO( m_Position ) ),
SendPropInt( SENDINFO( m_Icon ) ),
SendPropInt( SENDINFO( m_Status ) ),
SendPropInt( SENDINFO( m_Owner ) ),
SendPropInt( SENDINFO( m_Radius ) ),
#endif
END_NETWORK_TABLE()
LINK_ENTITY_TO_CLASS( neo_controlpoint, CNeoControlPoint );
#ifdef GAME_DLL
BEGIN_DATADESC( CNeoControlPoint )
END_DATADESC()
#endif
CNeoControlPoint::CNeoControlPoint()
{
m_Status = 0;
m_Owner = 0;
}
#ifdef GAME_DLL
int CNeoControlPoint::UpdateTransmitState()
{
return SetTransmitState( FL_EDICT_ALWAYS );
}
#endif
void CNeoControlPoint::Activate()
{
#ifdef CLIENT_DLL
DevMsg( "Client CP %s Activated\n", m_Name );
#else
DevMsg( "Server CP %s Activated\n", m_Name );
#endif
#ifdef GAME_DLL
m_Position = GetAbsOrigin();
if ( m_Icon < 0 || m_Icon > 11 )
m_Icon = 0;
#endif
NEOGameRules()->AddControlPoint( this );
BaseClass::Activate();
}
bool CNeoControlPoint::UpdatePointOwner()
{
#ifdef GAME_DLL
CBaseEntity* pEntities[ 256 ];
int count = UTIL_EntitiesInBox( pEntities, 256, GetAbsOrigin(), m_Position, 0 );
for ( int i = 0; i < count; i++ )
{
CNEOPlayer* pPlayer = (CNEOPlayer*) pEntities[ i ];
if ( !pPlayer || !pPlayer->IsPlayer() )
continue;
m_Owner = pPlayer->GetTeamNumber();
return true;
}
#endif
return false;
}
| 21.157303 | 81 | 0.713224 | L-Leite |
846d3f976ffdeb9e7c9ed90bc76d471e7f6317c3 | 836 | hpp | C++ | src/providers/ffz/FfzBadges.hpp | 1xelerate/chatterino2 | 57783c7478a955f5224e5025653c0f8549df12fc | [
"MIT"
] | null | null | null | src/providers/ffz/FfzBadges.hpp | 1xelerate/chatterino2 | 57783c7478a955f5224e5025653c0f8549df12fc | [
"MIT"
] | 1 | 2022-01-03T14:43:35.000Z | 2022-01-03T14:43:35.000Z | src/providers/ffz/FfzBadges.hpp | 1xelerate/chatterino2 | 57783c7478a955f5224e5025653c0f8549df12fc | [
"MIT"
] | null | null | null | #pragma once
#include <boost/optional.hpp>
#include <common/Singleton.hpp>
#include "common/Aliases.hpp"
#include "util/QStringHash.hpp"
#include <map>
#include <memory>
#include <shared_mutex>
#include <unordered_map>
#include <vector>
#include <QColor>
namespace chatterino {
struct Emote;
using EmotePtr = std::shared_ptr<const Emote>;
class FfzBadges : public Singleton
{
public:
virtual void initialize(Settings &settings, Paths &paths) override;
FfzBadges() = default;
boost::optional<EmotePtr> getBadge(const UserId &id);
boost::optional<QColor> getBadgeColor(const UserId &id);
private:
void loadFfzBadges();
std::shared_mutex mutex_;
std::unordered_map<QString, int> badgeMap;
std::vector<EmotePtr> badges;
std::unordered_map<int, QColor> colorMap;
};
} // namespace chatterino
| 19.904762 | 71 | 0.726077 | 1xelerate |
846e0bc7693650783f394d5b653d926124b654cf | 4,728 | hxx | C++ | opencascade/StepBasic_ProductDefinitionReference.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | opencascade/StepBasic_ProductDefinitionReference.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 66 | 2019-12-20T16:07:36.000Z | 2022-03-15T21:56:10.000Z | opencascade/StepBasic_ProductDefinitionReference.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | // Created on: 2016-03-30
// Created by: Irina KRYLOVA
// Copyright (c) 2016 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepBasic_ProductDefinitionReference_HeaderFile
#define _StepBasic_ProductDefinitionReference_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Transient.hxx>
class TCollection_HAsciiString;
class StepBasic_ExternalSource;
class StepBasic_ProductDefinitionReference;
DEFINE_STANDARD_HANDLE(StepBasic_ProductDefinitionReference, Standard_Transient)
//! Representation of STEP entity Product_Definition_Reference
class StepBasic_ProductDefinitionReference : public Standard_Transient
{
public:
//! Empty constructor
Standard_EXPORT StepBasic_ProductDefinitionReference();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init (const Handle(StepBasic_ExternalSource)& theSource,
const Handle(TCollection_HAsciiString)& theProductId,
const Handle(TCollection_HAsciiString)& theProductDefinitionFormationId,
const Handle(TCollection_HAsciiString)& theProductDefinitionId,
const Handle(TCollection_HAsciiString)& theIdOwningOrganizationName);
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init (const Handle(StepBasic_ExternalSource)& theSource,
const Handle(TCollection_HAsciiString)& theProductId,
const Handle(TCollection_HAsciiString)& theProductDefinitionFormationId,
const Handle(TCollection_HAsciiString)& theProductDefinitionId);
//! Returns field Source
inline Handle(StepBasic_ExternalSource) Source() const
{
return mySource;
}
//! Set field Source
inline void SetSource (const Handle(StepBasic_ExternalSource)& theSource)
{
mySource = theSource;
}
//! Returns field ProductId
inline Handle(TCollection_HAsciiString) ProductId() const
{
return myProductId;
}
//! Set field ProductId
inline void SetProductId (const Handle(TCollection_HAsciiString)& theProductId)
{
myProductId = theProductId;
}
//! Returns field ProductDefinitionFormationId
inline Handle(TCollection_HAsciiString) ProductDefinitionFormationId() const
{
return myProductDefinitionFormationId;
}
//! Set field ProductDefinitionFormationId
inline void SetProductDefinitionFormationId (const Handle(TCollection_HAsciiString)& theProductDefinitionFormationId)
{
myProductDefinitionFormationId = theProductDefinitionFormationId;
}
//! Returns field ProductDefinitionId
inline Handle(TCollection_HAsciiString) ProductDefinitionId() const
{
return myProductDefinitionId;
}
//! Set field ProductDefinitionId
inline void SetProductDefinitionId (const Handle(TCollection_HAsciiString)& theProductDefinitionId)
{
myProductDefinitionId = theProductDefinitionId;
}
//! Returns field IdOwningOrganizationName
inline Handle(TCollection_HAsciiString) IdOwningOrganizationName() const
{
return myIdOwningOrganizationName;
}
//! Set field IdOwningOrganizationName
inline void SetIdOwningOrganizationName (const Handle(TCollection_HAsciiString)& theIdOwningOrganizationName)
{
myIdOwningOrganizationName = theIdOwningOrganizationName;
hasIdOwningOrganizationName = (!theIdOwningOrganizationName.IsNull());
}
//! Returns true if IdOwningOrganizationName exists
inline Standard_Boolean HasIdOwningOrganizationName() const
{
return hasIdOwningOrganizationName;
}
DEFINE_STANDARD_RTTIEXT(StepBasic_ProductDefinitionReference, Standard_Transient)
private:
Handle(StepBasic_ExternalSource) mySource;
Handle(TCollection_HAsciiString) myProductId;
Handle(TCollection_HAsciiString) myProductDefinitionFormationId;
Handle(TCollection_HAsciiString) myProductDefinitionId;
Handle(TCollection_HAsciiString) myIdOwningOrganizationName;
Standard_Boolean hasIdOwningOrganizationName;
};
#endif // _StepBasic_ProductDefinitionReference_HeaderFile
| 36.091603 | 119 | 0.769247 | valgur |
84706ba1a08ca20f636eaa48a5051da425d7af2e | 3,047 | cpp | C++ | src/components/timer/timer.cpp | elmerucr/E64 | 1f7d57fadc6804948aa832d0f5f6800a8631f622 | [
"MIT"
] | null | null | null | src/components/timer/timer.cpp | elmerucr/E64 | 1f7d57fadc6804948aa832d0f5f6800a8631f622 | [
"MIT"
] | null | null | null | src/components/timer/timer.cpp | elmerucr/E64 | 1f7d57fadc6804948aa832d0f5f6800a8631f622 | [
"MIT"
] | null | null | null | // timer.cpp
// E64
//
// Copyright © 2019-2022 elmerucr. All rights reserved.
#include "timer.hpp"
#include "common.hpp"
E64::timer_ic::timer_ic(exceptions_ic *unit)
{
exceptions = unit;
irq_number = exceptions->connect_device();
}
void E64::timer_ic::reset()
{
registers[0] = 0x00; // No pending irq's
registers[1] = 0x00; // All timers turned off
// load data register with value 1 bpm (may never be zero)
registers[2] = 0x00; // high byte
registers[3] = 0x01; // low byte
for (int i=0; i<8; i++) {
timers[i].bpm = (registers[2] << 8) | registers[3];
timers[i].clock_interval = bpm_to_clock_interval(timers[i].bpm);
timers[i].counter = 0;
}
exceptions->release(irq_number);
}
void E64::timer_ic::run(uint32_t number_of_cycles)
{
for (int i=0; i<8; i++) {
timers[i].counter += number_of_cycles;
if ((timers[i].counter >= timers[i].clock_interval) &&
(registers[1] & (0b1 << i))) {
timers[i].counter -= timers[i].clock_interval;
exceptions->pull(irq_number);
registers[0] |= (0b1 << i);
}
}
}
uint32_t E64::timer_ic::bpm_to_clock_interval(uint16_t bpm)
{
return (60.0 / bpm) * VICV_CLOCK_SPEED;
}
uint8_t E64::timer_ic::read_byte(uint8_t address)
{
return registers[address & 0x03];
}
void E64::timer_ic::write_byte(uint8_t address, uint8_t byte)
{
switch (address & 0x03) {
case 0x00:
/*
* b s r
* 0 0 = 0
* 0 1 = 1
* 1 0 = 0
* 1 1 = 0
*
* b = bit that's written
* s = status (on if an interrupt was caused)
* r = boolean result (acknowledge an interrupt (s=1) if b=1
* r = (~b) & s
*/
registers[0] = (~byte) & registers[0];
if ((registers[0] & 0xff) == 0) {
// no timers left causing interrupts
exceptions->release(irq_number);
}
break;
case 0x01:
{
uint8_t turned_on = byte & (~registers[1]);
for (int i=0; i<8; i++) {
if (turned_on & (0b1 << i)) {
timers[i].bpm = (uint16_t)registers[3] |
(registers[2] << 8);
if (timers[i].bpm == 0)
timers[i].bpm = 1;
timers[i].clock_interval =
bpm_to_clock_interval(timers[i].bpm);
timers[i].counter = 0;
}
}
registers[0x01] = byte;
break;
}
default:
registers[address & 0x03] = byte;
break;
}
}
uint64_t E64::timer_ic::get_timer_counter(uint8_t timer_number)
{
return timers[timer_number & 0x07].counter;
}
uint64_t E64::timer_ic::get_timer_clock_interval(uint8_t timer_number)
{
return timers[timer_number & 0x07].clock_interval;
}
void E64::timer_ic::set(uint8_t timer_no, uint16_t bpm)
{
timer_no &= 0b111; // limit to max 7
write_byte(0x03, bpm & 0xff);
write_byte(0x02, (bpm & 0xff00) >> 8);
uint8_t byte = read_byte(0x01);
write_byte(0x01, (0b1 << timer_no) | byte);
}
void E64::timer_ic::status(char *buffer, uint8_t timer_no)
{
timer_no &= 0b00000111;
snprintf(buffer, 64, "\n%02x:%s/%5u/%08x/%08x",
timer_no,
registers[0x01] & (0b1 << timer_no) ? " on" : "off",
timers[timer_no].bpm,
timers[timer_no].counter,
timers[timer_no].clock_interval);
}
| 23.083333 | 70 | 0.628159 | elmerucr |
84708ed239f1a74e5abb29675b2c7273a13354c2 | 1,459 | cpp | C++ | Windows_Project/Test2/CollideComponent.cpp | Torbjornsson/TDA572-2019 | 7e281b2ac72600db57e0f128eaedccea133f9701 | [
"MIT"
] | null | null | null | Windows_Project/Test2/CollideComponent.cpp | Torbjornsson/TDA572-2019 | 7e281b2ac72600db57e0f128eaedccea133f9701 | [
"MIT"
] | null | null | null | Windows_Project/Test2/CollideComponent.cpp | Torbjornsson/TDA572-2019 | 7e281b2ac72600db57e0f128eaedccea133f9701 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Component.h"
#include "GameObject.h"
#include "avancezlib.h"
void CollideComponent::Create(AvancezLib* engine, GameObject* go, std::set<GameObject*>* game_objects, ObjectPool<GameObject>* coll_objects){
Component::Create(engine, go, game_objects);
this->coll_objects = coll_objects;
}
void CollideComponent::Update(float dt){
for (auto i = 0; i < coll_objects->pool.size(); i++){
GameObject * coll_go = coll_objects->pool[i];
if (coll_go->enabled){
if ((go->verticalPos - go->radius) <= coll_go->verticalPos){
if (circleCollide(go, coll_go)){
go->Receive(HIT);
coll_go->Receive(HIT);
}
}
}
}
}
//Check if 2 boxes overlap
bool CollideComponent::boxCollide(GameObject * go, GameObject * coll_go){
return ((coll_go->horizontalPos > go->horizontalPos - 10) &&
(coll_go->horizontalPos < go->horizontalPos + 10) &&
(coll_go->verticalPos > go->verticalPos - 10) &&
(coll_go->verticalPos < go->verticalPos + 10));
}
//Check if point is iside the circle
bool CollideComponent::circleCollide(GameObject * go, GameObject * coll_go){
double x_diff = (go->horizontalPos + go->radius) - coll_go->horizontalPos;
double y_diff = (go->verticalPos + go->radius) - coll_go->verticalPos;
return (std::sqrt(x_diff * x_diff + y_diff * y_diff) <= go->radius);
} | 36.475 | 141 | 0.627142 | Torbjornsson |
847189942b8ef8644dca43e701b77473773e9657 | 734 | cpp | C++ | src/blink.cpp | Tivian/micro-sci | dd2c1dca912218557c1143028696b844c5ec7578 | [
"MIT"
] | null | null | null | src/blink.cpp | Tivian/micro-sci | dd2c1dca912218557c1143028696b844c5ec7578 | [
"MIT"
] | null | null | null | src/blink.cpp | Tivian/micro-sci | dd2c1dca912218557c1143028696b844c5ec7578 | [
"MIT"
] | null | null | null | #include "blink.hpp"
#include "lcd.hpp"
#include <avr/io.h>
#include <avr/interrupt.h>
namespace Blink {
namespace {
volatile bool blink = false;
volatile uint8_t timeout = 0;
volatile uint8_t delay = 0;
}
void init(uint8_t delay) {
speed(delay);
OCR0A = 0xFF;
TCCR0A |= _BV(WGM01);
TCCR0B |= _BV(CS02) | _BV(CS00);
}
void start() {
TIMSK0 |= _BV(OCIE0A);
blink = true;
timeout = 0;
}
void stop() {
TIMSK0 &= ~_BV(OCIE0A);
}
void speed(uint8_t delay) {
Blink::delay = delay;
}
}
ISR (TIMER0_COMPA_vect) {
if (Blink::timeout++ == Blink::delay) {
LCD::mode(true, Blink::blink = !Blink::blink);
Blink::timeout = 0;
}
} | 17.902439 | 55 | 0.559946 | Tivian |
8472164ceb9fd8bc264bbd92078d0f1576ca5c7f | 511 | cpp | C++ | c10/ex10_24.cpp | qzhang0/CppPrimer | 315ef879bd4d3b51d594e33b049adee0d47e4c11 | [
"MIT"
] | null | null | null | c10/ex10_24.cpp | qzhang0/CppPrimer | 315ef879bd4d3b51d594e33b049adee0d47e4c11 | [
"MIT"
] | null | null | null | c10/ex10_24.cpp | qzhang0/CppPrimer | 315ef879bd4d3b51d594e33b049adee0d47e4c11 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <functional>
using namespace std;
using std::placeholders::_1;
bool check_size(const string& s, int i) {
return s.size() < i;
}
int main() {
vector<int> ivec{0, 1, 2, 3, 4, 5, 6};
auto result = find_if(ivec.begin(), ivec.end(), bind(check_size, "01234567", _1));
if (result != ivec.end()) {
cout << *result << endl;
} else {
cout << "Not found" << endl;
}
return 0;
} | 19.653846 | 86 | 0.577299 | qzhang0 |
84738694d917d7a2ef6d96b5653d1c4c68b9bb5d | 24,101 | cc | C++ | Cxx11/transpose-vector-raja.cc | mjklemm/Kernels | 0131ab2c0451d3fdd4237ed74efc49b85f6ab475 | [
"BSD-3-Clause"
] | null | null | null | Cxx11/transpose-vector-raja.cc | mjklemm/Kernels | 0131ab2c0451d3fdd4237ed74efc49b85f6ab475 | [
"BSD-3-Clause"
] | null | null | null | Cxx11/transpose-vector-raja.cc | mjklemm/Kernels | 0131ab2c0451d3fdd4237ed74efc49b85f6ab475 | [
"BSD-3-Clause"
] | null | null | null | ///
/// Copyright (c) 2013, Intel Corporation
///
/// 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 Intel Corporation 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.
//////////////////////////////////////////////////////////////////////
///
/// NAME: transpose
///
/// PURPOSE: This program measures the time for the transpose of a
/// column-major stored matrix into a row-major stored matrix.
///
/// USAGE: Program input is the matrix order and the number of times to
/// repeat the operation:
///
/// transpose <matrix_size> <# iterations> <variant>
///
/// The output consists of diagnostics to make sure the
/// transpose worked and timing statistics.
///
/// HISTORY: Written by Rob Van der Wijngaart, February 2009.
/// Converted to C++11 by Jeff Hammond, February 2016 and May 2017.
///
//////////////////////////////////////////////////////////////////////
#include "prk_util.h"
const int tile_size = 32;
typedef RAJA::Index_type indx;
typedef RAJA::RangeSegment range;
typedef RAJA::TileList<RAJA::tile_fixed<tile_size>, RAJA::tile_fixed<tile_size>> tile;
typedef RAJA::Tile<tile> tiling;
typedef RAJA::Tile<tile,RAJA::Permute<RAJA::PERM_IJ>> tiling_ij;
typedef RAJA::Tile<tile,RAJA::Permute<RAJA::PERM_JI>> tiling_ji;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::simd_exec>> seq_for_simd;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>> seq_for_seq;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>, tiling> seq_for_seq_tiled;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::simd_exec>, tiling> seq_for_simd_tiled;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>, tiling_ij> seq_for_seq_tiled_ij;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::simd_exec>, tiling_ij> seq_for_simd_tiled_ij;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>, tiling_ji> seq_for_seq_tiled_ji;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::simd_exec>, tiling_ji> seq_for_simd_tiled_ji;
#ifdef RAJA_ENABLE_OPENMP
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::seq_exec>> omp_for_seq;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::simd_exec>> omp_for_simd;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::seq_exec>, tiling> omp_for_seq_tiled;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::simd_exec>, tiling> omp_for_simd_tiled;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::seq_exec>, tiling_ij> omp_for_seq_tiled_ij;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::simd_exec>, tiling_ij> omp_for_simd_tiled_ij;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::seq_exec>, tiling_ji> omp_for_seq_tiled_ji;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::simd_exec>, tiling_ji> omp_for_simd_tiled_ji;
#endif
#ifdef RAJA_ENABLE_TBB
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::seq_exec>> tbb_for_seq;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::simd_exec>> tbb_for_simd;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::seq_exec>, tiling> tbb_for_seq_tiled;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::simd_exec>, tiling> tbb_for_simd_tiled;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::seq_exec>, tiling_ij> tbb_for_seq_tiled_ij;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::simd_exec>, tiling_ij> tbb_for_simd_tiled_ij;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::seq_exec>, tiling_ji> tbb_for_seq_tiled_ji;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::simd_exec>, tiling_ji> tbb_for_simd_tiled_ji;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_dynamic, RAJA::seq_exec>> tbb_for_dynamic_seq;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_dynamic, RAJA::simd_exec>> tbb_for_dynamic_simd;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_dynamic, RAJA::seq_exec>, tiling> tbb_for_dynamic_seq_tiled;
typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_dynamic, RAJA::simd_exec>, tiling> tbb_for_dynamic_simd_tiled;
#endif
template <typename exec_policy, typename LoopBody>
void Lambda(int order, LoopBody body)
{
RAJA::forallN<exec_policy>( range(0, order), range(0, order), body);
}
template <typename exec_policy>
void Initialize(int order, std::vector<double> & A, std::vector<double> & B)
{
Lambda<exec_policy>(order, [=,&A,&B](int i, int j) {
A[i*order+j] = static_cast<double>(i*order+j);
B[i*order+j] = 0.0;
});
}
template <typename exec_policy>
void Transpose(int order, std::vector<double> & A, std::vector<double> & B)
{
Lambda<exec_policy>(order, [=,&A,&B](int i, int j) {
B[i*order+j] += A[j*order+i];
A[j*order+i] += 1.0;
});
}
template <typename outer_policy, typename inner_policy>
void Initialize(int order, std::vector<double> & A, std::vector<double> & B)
{
RAJA::forall<outer_policy>(0, order, [=,&A,&B](int i) {
RAJA::forall<inner_policy>(0, order, [=,&A,&B](int j) {
A[i*order+j] = static_cast<double>(i*order+j);
B[i*order+j] = 0.0;
});
});
}
template <typename outer_policy, typename inner_policy>
void Transpose(int order, std::vector<double> & A, std::vector<double> & B)
{
RAJA::forall<outer_policy>(0, order, [=,&A,&B](int i) {
RAJA::forall<inner_policy>(0, order, [=,&A,&B](int j) {
B[i*order+j] += A[j*order+i];
A[j*order+i] += 1.0;
});
});
}
template <typename loop_policy, typename reduce_policy>
double Error(int iterations, int order, std::vector<double> & B)
{
RAJA::ReduceSum<reduce_policy, double> abserr(0.0);
typedef RAJA::NestedPolicy<RAJA::ExecList<loop_policy, RAJA::seq_exec>> exec_policy;
RAJA::forallN<exec_policy>( range(0, order), range(0, order), [=,&B](int i, int j) {
const auto dij = static_cast<double>(i*order+j);
const auto addit = (iterations+1.) * (0.5*iterations);
const auto reference = dij*(1.+iterations)+addit;
abserr += std::fabs(B[j*order+i] - reference);
});
return abserr;
}
int main(int argc, char * argv[])
{
std::cout << "Parallel Research Kernels version " << PRKVERSION << std::endl;
std::cout << "C++11/RAJA Matrix transpose: B = A^T" << std::endl;
//////////////////////////////////////////////////////////////////////
/// Read and test input parameters
//////////////////////////////////////////////////////////////////////
if (argc < 3) {
std::cerr << "Usage: <# iterations> <matrix order> ";
std::cerr << "<for={seq,omp,tbb,tbbdyn} nested={y,n} tiled={y,n} permute={no,ij,ji} simd={y,n}>\n";
std::cerr << "Caveat: tiled/permute only supported for nested=y.\n";
std::cerr << "Feature: RAJA args (foo=bar) can be given in any order.\n";
return argc;
}
int iterations, order;
std::string use_for="seq", use_permute="no";
auto use_simd=true, use_nested=true, use_tiled=false;
try {
// number of times to do the transpose
iterations = std::atoi(argv[1]);
if (iterations < 1) {
throw "ERROR: iterations must be >= 1";
}
// order of a the matrix
order = std::atoi(argv[2]);
if (order <= 0) {
throw "ERROR: Matrix Order must be greater than 0";
} else if (order > std::floor(std::sqrt(INT_MAX))) {
throw "ERROR: matrix dimension too large - overflow risk";
}
// RAJA implementation variant
for (int i=3; i<argc; ++i) {
//std::cout << "argv[" << i << "] = " << argv[i] << "\n";
auto s = std::string(argv[i]);
auto pf = s.find("for=");
if (pf != std::string::npos) {
auto sf = s.substr(4,s.size());
//std::cout << pf << "," << sf << "\n";
if (sf=="omp" || sf=="openmp") {
#ifdef RAJA_ENABLE_OPENMP
use_for="omp";
#else
std::cerr << "You are trying to use OpenMP but RAJA does not support it!" << std::endl;
#endif
}
if (sf=="tbb") {
#ifdef RAJA_ENABLE_TBB
use_for="tbb";
#else
std::cerr << "You are trying to use TBB but RAJA does not support it!" << std::endl;
#endif
}
if (sf=="tbbdyn") {
#ifdef RAJA_ENABLE_TBB
use_for="tbbdyn";
#else
std::cerr << "You are trying to use TBB but RAJA does not support it!" << std::endl;
#endif
}
}
auto ps = s.find("simd=");
if (ps != std::string::npos) {
auto ss = s.substr(5,s.size());
//std::cout << ps << "," << ss[0] << "\n";
if (ss=="n") use_simd=false;
if (ss=="np") use_simd=false;
}
auto pn = s.find("nested=");
if (pn != std::string::npos) {
auto sn = s.substr(7,s.size());
//std::cout << pn << "," << sn[0] << "\n";
if (sn=="n") use_nested=false;
if (sn=="no") use_nested=false;
}
auto pt = s.find("tiled=");
if (pt != std::string::npos) {
auto st = s.substr(6,s.size());
//std::cout << pt << "," << st[0] << "\n";
if (st=="y") use_tiled=true;
if (st=="yes") use_tiled=true;
}
auto pp = s.find("permute=");
if (pp != std::string::npos) {
auto sp = s.substr(8,s.size());
//std::cout << pp << "," << pp[0] << "\n";
if (sp=="ij") use_permute="ij";
if (sp=="ji") use_permute="ji";
}
}
}
catch (const char * e) {
std::cout << e << std::endl;
return 1;
}
std::string for_name = "Sequential";
if (use_for=="omp") for_name = "OpenMP";
if (use_for=="tbb") for_name = "TBB (static)";
if (use_for=="tbbdyn") for_name = "TBB (dynamic)";
std::cout << "Number of iterations = " << iterations << std::endl;
std::cout << "Matrix order = " << order << std::endl;
std::cout << "Tile size = " << tile_size << "(compile-time constant, unlike other impls)" << std::endl;
std::cout << "RAJA threading = " << for_name << std::endl;
std::cout << "RAJA forallN = " << (use_nested ? "yes" : "no") << std::endl;
std::cout << "RAJA use tiling = " << (use_tiled ? "yes" : "no") << std::endl;
std::cout << "RAJA use permute = " << use_permute << std::endl;
std::cout << "RAJA use simd = " << (use_simd ? "yes" : "no") << std::endl;
//////////////////////////////////////////////////////////////////////
/// Allocate space for the input and transpose matrix
//////////////////////////////////////////////////////////////////////
std::vector<double> A(order*order);
std::vector<double> B(order*order);
if (use_for=="seq") {
if (use_nested) {
if (use_tiled) {
if (use_permute=="no") {
if (use_simd) {
Initialize<seq_for_simd_tiled>(order, A, B);
} else {
Initialize<seq_for_seq_tiled>(order, A, B);
}
}
else if (use_permute=="ij") {
if (use_simd) {
Initialize<seq_for_simd_tiled_ij>(order, A, B);
} else {
Initialize<seq_for_seq_tiled_ij>(order, A, B);
}
}
else if (use_permute=="ji") {
if (use_simd) {
Initialize<seq_for_simd_tiled_ji>(order, A, B);
} else {
Initialize<seq_for_seq_tiled_ji>(order, A, B);
}
}
} else {
if (use_simd) {
Initialize<seq_for_simd>(order, A, B);
} else {
Initialize<seq_for_seq>(order, A, B);
}
}
} else /* !use_nested */ {
if (use_simd) {
Initialize<RAJA::seq_exec,RAJA::simd_exec>(order, A, B);
} else {
Initialize<RAJA::seq_exec,RAJA::seq_exec>(order, A, B);
}
}
}
#ifdef RAJA_ENABLE_OPENMP
else if (use_for=="omp") {
if (use_nested) {
if (use_tiled) {
if (use_permute=="no") {
if (use_simd) {
Initialize<omp_for_simd_tiled>(order, A, B);
} else {
Initialize<omp_for_seq_tiled>(order, A, B);
}
}
else if (use_permute=="ij") {
if (use_simd) {
Initialize<omp_for_simd_tiled_ij>(order, A, B);
} else {
Initialize<omp_for_seq_tiled_ij>(order, A, B);
}
}
else if (use_permute=="ji") {
if (use_simd) {
Initialize<omp_for_simd_tiled_ji>(order, A, B);
} else {
Initialize<omp_for_seq_tiled_ji>(order, A, B);
}
}
} else {
if (use_simd) {
Initialize<omp_for_simd>(order, A, B);
} else {
Initialize<omp_for_seq>(order, A, B);
}
}
} else /* !use_nested */ {
if (use_simd) {
Initialize<RAJA::omp_parallel_for_exec,RAJA::simd_exec>(order, A, B);
} else {
Initialize<RAJA::omp_parallel_for_exec,RAJA::seq_exec>(order, A, B);
}
}
}
#endif
#ifdef RAJA_ENABLE_TBB
else if (use_for=="tbb") {
if (use_nested) {
if (use_tiled) {
if (use_permute=="no") {
if (use_simd) {
Initialize<tbb_for_simd_tiled>(order, A, B);
} else {
Initialize<tbb_for_seq_tiled>(order, A, B);
}
}
else if (use_permute=="ij") {
if (use_simd) {
Initialize<tbb_for_simd_tiled_ij>(order, A, B);
} else {
Initialize<tbb_for_seq_tiled_ij>(order, A, B);
}
}
else if (use_permute=="ji") {
if (use_simd) {
Initialize<tbb_for_simd_tiled_ji>(order, A, B);
} else {
Initialize<tbb_for_seq_tiled_ji>(order, A, B);
}
}
} else {
if (use_simd) {
Initialize<tbb_for_simd>(order, A, B);
} else {
Initialize<tbb_for_seq>(order, A, B);
}
}
} else /* !use_nested */ {
if (use_simd) {
Initialize<RAJA::tbb_for_exec,RAJA::simd_exec>(order, A, B);
} else {
Initialize<RAJA::tbb_for_exec,RAJA::seq_exec>(order, A, B);
}
}
}
else if (use_for=="tbbdyn") {
if (use_nested) {
if (use_tiled) {
if (use_simd) {
Initialize<tbb_for_dynamic_simd_tiled>(order, A, B);
} else {
Initialize<tbb_for_dynamic_seq_tiled>(order, A, B);
}
} else {
if (use_simd) {
Initialize<tbb_for_dynamic_simd>(order, A, B);
} else {
Initialize<tbb_for_dynamic_seq>(order, A, B);
}
}
} else /* !use_nested */ {
if (use_simd) {
Initialize<RAJA::tbb_for_dynamic,RAJA::simd_exec>(order, A, B);
} else {
Initialize<RAJA::tbb_for_dynamic,RAJA::seq_exec>(order, A, B);
}
}
}
#endif
auto trans_time = 0.0;
for (auto iter = 0; iter<=iterations; iter++) {
if (iter==1) trans_time = prk::wtime();
// transpose
if (use_for=="seq") {
if (use_nested) {
if (use_tiled) {
if (use_permute=="no") {
if (use_simd) {
Transpose<seq_for_simd_tiled>(order, A, B);
} else {
Transpose<seq_for_seq_tiled>(order, A, B);
}
}
else if (use_permute=="ij") {
if (use_simd) {
Transpose<seq_for_simd_tiled_ij>(order, A, B);
} else {
Transpose<seq_for_seq_tiled_ij>(order, A, B);
}
}
else if (use_permute=="ji") {
if (use_simd) {
Transpose<seq_for_simd_tiled_ji>(order, A, B);
} else {
Transpose<seq_for_seq_tiled_ji>(order, A, B);
}
}
} else {
if (use_simd) {
Transpose<seq_for_simd>(order, A, B);
} else {
Transpose<seq_for_seq>(order, A, B);
}
}
} else /* !use_nested */ {
if (use_simd) {
Transpose<RAJA::seq_exec,RAJA::simd_exec>(order, A, B);
} else {
Transpose<RAJA::seq_exec,RAJA::seq_exec>(order, A, B);
}
}
}
#ifdef RAJA_ENABLE_OPENMP
else if (use_for=="omp") {
if (use_nested) {
if (use_tiled) {
if (use_permute=="no") {
if (use_simd) {
Transpose<omp_for_simd_tiled>(order, A, B);
} else {
Transpose<omp_for_seq_tiled>(order, A, B);
}
}
else if (use_permute=="ij") {
if (use_simd) {
Transpose<omp_for_simd_tiled_ij>(order, A, B);
} else {
Transpose<omp_for_seq_tiled_ij>(order, A, B);
}
}
else if (use_permute=="ji") {
if (use_simd) {
Transpose<omp_for_simd_tiled_ji>(order, A, B);
} else {
Transpose<omp_for_seq_tiled_ji>(order, A, B);
}
}
} else {
if (use_simd) {
Transpose<omp_for_simd>(order, A, B);
} else {
Transpose<omp_for_seq>(order, A, B);
}
}
} else /* !use_nested */ {
if (use_simd) {
Transpose<RAJA::omp_parallel_for_exec,RAJA::simd_exec>(order, A, B);
} else {
Transpose<RAJA::omp_parallel_for_exec,RAJA::seq_exec>(order, A, B);
}
}
}
#endif
#ifdef RAJA_ENABLE_TBB
else if (use_for=="tbb") {
if (use_nested) {
if (use_tiled) {
if (use_permute=="no") {
if (use_simd) {
Transpose<tbb_for_simd_tiled>(order, A, B);
} else {
Transpose<tbb_for_seq_tiled>(order, A, B);
}
}
else if (use_permute=="ij") {
if (use_simd) {
Transpose<tbb_for_simd_tiled_ij>(order, A, B);
} else {
Transpose<tbb_for_seq_tiled_ij>(order, A, B);
}
}
else if (use_permute=="ji") {
if (use_simd) {
Transpose<tbb_for_simd_tiled_ji>(order, A, B);
} else {
Transpose<tbb_for_seq_tiled_ji>(order, A, B);
}
}
} else {
if (use_simd) {
Transpose<tbb_for_simd>(order, A, B);
} else {
Transpose<tbb_for_seq>(order, A, B);
}
}
} else /* !use_nested */ {
if (use_simd) {
Transpose<RAJA::tbb_for_exec,RAJA::simd_exec>(order, A, B);
} else {
Transpose<RAJA::tbb_for_exec,RAJA::seq_exec>(order, A, B);
}
}
}
else if (use_for=="tbbdyn") {
if (use_nested) {
if (use_tiled) {
if (use_simd) {
Transpose<tbb_for_dynamic_simd_tiled>(order, A, B);
} else {
Transpose<tbb_for_dynamic_seq_tiled>(order, A, B);
}
} else {
if (use_simd) {
Transpose<tbb_for_dynamic_simd>(order, A, B);
} else {
Transpose<tbb_for_dynamic_seq>(order, A, B);
}
}
} else /* !use_nested */ {
if (use_simd) {
Transpose<RAJA::tbb_for_dynamic,RAJA::simd_exec>(order, A, B);
} else {
Transpose<RAJA::tbb_for_dynamic,RAJA::seq_exec>(order, A, B);
}
}
}
#endif
}
trans_time = prk::wtime() - trans_time;
//////////////////////////////////////////////////////////////////////
/// Analyze and output results
//////////////////////////////////////////////////////////////////////
double abserr = 1.0;
if (use_for=="seq") {
abserr = Error<RAJA::seq_exec,RAJA::seq_reduce>(iterations,order,B);
}
#if defined(RAJA_ENABLE_OPENMP)
else if (use_for=="omp") {
abserr = Error<RAJA::omp_parallel_for_exec,RAJA::omp_reduce>(iterations,order,B);
}
#endif
#if defined(RAJA_ENABLE_TBB)
else if (use_for=="tbb") {
abserr = Error<RAJA::tbb_for_exec,RAJA::tbb_reduce>(iterations,order,B);
}
else if (use_for=="tbbdyn") {
abserr = Error<RAJA::tbb_for_dynamic,RAJA::tbb_reduce>(iterations,order,B);
}
#endif
#ifdef VERBOSE
std::cout << "Sum of absolute differences: " << abserr << std::endl;
#endif
const auto epsilon = 1.0e-8;
if (abserr < epsilon) {
std::cout << "Solution validates" << std::endl;
auto avgtime = trans_time/iterations;
auto bytes = (size_t)order * (size_t)order * sizeof(double);
std::cout << "Rate (MB/s): " << 1.0e-6 * (2L*bytes)/avgtime
<< " Avg time (s): " << avgtime << std::endl;
} else {
std::cout << "ERROR: Aggregate squared error " << abserr
<< " exceeds threshold " << epsilon << std::endl;
return 1;
}
return 0;
}
#if 0
RAJA::forallN< RAJA::NestedPolicy< RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>,
RAJA::Permute<RAJA::PERM_JI> > >
( range(0, order), range(0, order),
[=,&A,&B](indx i, indx j) {
B[i*order+j] += A[j*order+i];
A[j*order+i] += 1.0;
});
RAJA::forallN< RAJA::NestedPolicy< RAJA::ExecList<RAJA::simd_exec, RAJA::simd_exec>,
RAJA::Tile< RAJA::TileList<RAJA::tile_fixed<tile_size>, RAJA::tile_fixed<tile_size>>,
RAJA::Permute<RAJA::PERM_IJ> > > >
( range(0, order), range(0, order),
[=,&A,&B](indx i, indx j) {
B[i*order+j] += A[j*order+i];
A[j*order+i] += 1.0;
});
RAJA::forallN< RAJA::NestedPolicy< RAJA::ExecList<RAJA::simd_exec, RAJA::simd_exec>,
RAJA::Tile< RAJA::TileList<RAJA::tile_fixed<tile_size>, RAJA::tile_fixed<tile_size>>,
RAJA::Permute<RAJA::PERM_JI> > > >
( range(0, order), range(0, order),
[=,&A,&B](indx i, indx j) {
B[i*order+j] += A[j*order+i];
A[j*order+i] += 1.0;
});
#endif
| 37.30805 | 128 | 0.552218 | mjklemm |
8474504410cb26a18a9380bb02db4097e59b79c5 | 7,221 | cc | C++ | apps/metgram/metgramx.cc | dtip/magics | 3247535760ca962f859c203295b508d442aca4ed | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | apps/metgram/metgramx.cc | dtip/magics | 3247535760ca962f859c203295b508d442aca4ed | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | apps/metgram/metgramx.cc | dtip/magics | 3247535760ca962f859c203295b508d442aca4ed | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-12-18T17:01:56.000Z | 2019-12-18T17:01:56.000Z | /*
* (C) Copyright 1996-2016 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include <iostream>
#include <ParameterManager.h>
#include <XmlMagics.h>
#include <XmlReader.h>
using namespace std;
using namespace magics;
class MagicsService {
public:
MagicsService() : manager_() {}
void execute(const string& xml) {
try {
manager_.execute(xml);
}
catch (MagicsException& e) {
MagLog::error() << e << endl;
}
}
private:
XmlMagics manager_;
};
static void substitute(string& xml, const string& var, const string& val) {
string name = "$" + var;
string::size_type index = xml.find(name);
int last = 0;
while (index != string::npos) {
xml.replace(index, name.length(), val);
last = index + val.length();
index = xml.find(name, last);
}
}
char nospace(char c) {
if (c == ' ')
return '_';
return c;
}
class TempFile {
public:
TempFile() : filename(tmpnam(0)), ofs(filename) {
if (!ofs)
return;
}
~TempFile() {
ofs.close();
remove(filename);
}
ofstream& operator()() { return ofs; }
string name() { return filename; }
private:
const char* filename;
ofstream ofs;
};
class Station : public XmlNodeVisitor {
public:
Station(const XmlNode& node) {
date_ = node.getAttribute("date");
time_ = node.getAttribute("time");
template_ = node.getAttribute("template");
if (template_.empty())
template_ = string(getenv("MAGPLUS_HOME")) + "/share/templates/10_days_epsgram.xml";
database_ = node.getAttribute("database");
format_ = node.getAttribute("format");
if (format_.empty())
format_ = "a4";
deterministic_ = node.getAttribute("deterministic");
if (deterministic_.empty())
deterministic_ = "on";
whisker_ = node.getAttribute("whisker");
if (whisker_.empty())
whisker_ = "on";
parameters_ = node.attributes();
}
~Station() {}
void visit(const XmlNode& node) {
if (node.name() == "station") {
ostringstream station;
for (XmlNode::DataIterator data = node.firstData(); data != node.lastData(); ++data)
station << *data;
MagLog::dev() << "title-->" << station.str() << endl;
MagLog::dev() << "Plot Station-->" << node.getAttribute("name") << endl;
MagLog::dev() << "Template-->" << template_ << endl;
try {
ifstream test(template_.c_str());
if (!test.good()) {
// Try to look in ethe default template directory :
template_ = string(getenv("MAGPLUS_HOME")) + "/share/templates/" + template_;
MagLog::dev() << "try to find template in system directory-> " << template_ << endl;
ifstream defaut(template_.c_str());
if (!defaut.good()) {
MagLog::error() << "Can not open template file " << template_ << endl;
return;
}
defaut.close();
}
test.close();
ifstream in(template_.c_str());
TempFile file;
ofstream& out = file();
static string s;
s = "";
char c;
while (in.get(c)) {
s += c;
}
ostringstream def;
def << INT_MAX;
string meta = node.getAttribute("metafile");
#ifdef MAGICS_AIX_XLC
meta = "";
#endif
meta = (meta.empty()) ? "nometada" : "meta path=\'" + meta + "\'";
MagLog::dev() << "Meta-->" << meta;
substitute(s, "meta", meta);
string height = (node.getAttribute("height") == "") ? def.str() : node.getAttribute("height");
substitute(s, "height", height);
substitute(s, "latitude", node.getAttribute("latitude"));
substitute(s, "longitude", node.getAttribute("longitude"));
substitute(s, "station", node.getAttribute("name"));
substitute(s, "title", station.str());
substitute(s, "date", date_);
substitute(s, "time", time_);
substitute(s, "format", format_);
substitute(s, "deterministic", deterministic_);
substitute(s, "whisker", whisker_);
for (map<string, string>::iterator param = parameters_.begin(); param != parameters_.end(); ++param)
substitute(s, param->first, param->second);
string ps = node.getAttribute("psfile");
ps = ps.empty() ? "nops" : "ps fullname=\'" + ps + "\'";
substitute(s, "ps", ps);
string pdf = node.getAttribute("pdffile");
pdf = pdf.empty() ? "nopdf" : "pdf fullname=\'" + pdf + "\'";
substitute(s, "pdf", pdf);
string gif = node.getAttribute("giffile");
gif = gif.empty() ? "nogif" : "gif fullname=\'" + gif + "\'";
substitute(s, "gif", gif);
string png = node.getAttribute("pngfile");
png = png.empty() ? "nopng" : "png fullname=\'" + png + "\'";
substitute(s, "png", png);
string svg = node.getAttribute("svgfile");
svg = svg.empty() ? "nosvg" : "svg fullname=\'" + svg + "\'";
substitute(s, "svg", svg);
out << s;
in.close();
out.flush();
magics_.execute(file.name());
}
catch (exception e) {
}
}
}
protected:
string date_;
string time_;
string template_;
string directory_;
string database_;
string format_;
string deterministic_;
string whisker_;
MagicsService magics_;
map<string, string> parameters_;
};
class Eps : public XmlNodeVisitor {
public:
Eps() {}
~Eps() {}
void visit(const XmlNode& node) {
MagLog::dev() << "node-->" << node.name() << endl;
if (node.name() == "eps") {
Station station(node);
node.visit(station);
}
}
};
int main(int argc, char** argv) {
if (argc < 2) {
cout << "Usage: " << argv[0] << " <file.epsml>\n";
exit(1);
}
string xml = argv[1];
XmlReader reader;
XmlTree tree;
try {
reader.interpret(xml, &tree);
}
catch (...) {
cerr << "metgram : error interpreting file " << xml << "\n";
}
Eps metgram;
tree.visit(metgram);
}
| 29.473469 | 116 | 0.502147 | dtip |
847495be05b2fce27e6d132d7a4d4f249383a3cb | 1,488 | hxx | C++ | Validator/GenICam/library/CPP/include/xsde/cxx/parser/validating/inheritance-map.hxx | genicam/GenICamXmlValidator | f3d0873dc2f39e09e98933aee927274a087a2a90 | [
"Apache-2.0"
] | null | null | null | Validator/GenICam/library/CPP/include/xsde/cxx/parser/validating/inheritance-map.hxx | genicam/GenICamXmlValidator | f3d0873dc2f39e09e98933aee927274a087a2a90 | [
"Apache-2.0"
] | 2 | 2020-10-30T16:10:09.000Z | 2020-11-09T01:55:49.000Z | Validator/GenICam/library/CPP/include/xsde/cxx/parser/validating/inheritance-map.hxx | genicam/GenICamXmlValidator | f3d0873dc2f39e09e98933aee927274a087a2a90 | [
"Apache-2.0"
] | null | null | null | // file : xsde/cxx/parser/validating/inheritance-map.hxx
// author : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2005-2011 Code Synthesis Tools CC
// license : GNU GPL v2 + exceptions; see accompanying LICENSE file
#ifndef XSDE_CXX_PARSER_VALIDATING_INHERITANCE_MAP_HXX
#define XSDE_CXX_PARSER_VALIDATING_INHERITANCE_MAP_HXX
#include <stddef.h> // size_t
#include <xsde/cxx/config.hxx>
#include <xsde/cxx/ro-string.hxx>
#include <xsde/cxx/hashmap.hxx>
namespace xsde
{
namespace cxx
{
namespace parser
{
namespace validating
{
struct inheritance_map: hashmap
{
inheritance_map (size_t buckets);
void
insert (const char* derived, const char* base);
bool
check (const char* derived, const char* base) const;
};
// Translation unit initializer.
//
struct inheritance_map_init
{
static inheritance_map* map;
static size_t count;
inheritance_map_init ();
~inheritance_map_init ();
};
inline inheritance_map&
inheritance_map_instance ();
// Map entry initializer.
//
struct inheritance_map_entry
{
inheritance_map_entry (const char* derived, const char* base);
};
}
}
}
}
#include <xsde/cxx/parser/validating/inheritance-map.ixx>
#endif // XSDE_CXX_PARSER_VALIDATING_INHERITANCE_MAP_HXX
| 23.619048 | 72 | 0.637097 | genicam |
8476cdb5bbab5f01c784b4f57571f2ead059dae0 | 34,900 | cpp | C++ | src/nids.cpp | alertflex/altprobe | 1c9f256ef8aa4a015cac1b1c5f990f4c177c8b3d | [
"Apache-2.0"
] | 31 | 2020-10-08T13:16:17.000Z | 2022-03-18T06:38:31.000Z | src/nids.cpp | olegzhr/altprobe | da9597efcf0463f31ea38bf715ed8d5453dfc0e5 | [
"Apache-2.0"
] | 2 | 2020-09-17T15:54:58.000Z | 2021-02-26T07:58:01.000Z | src/nids.cpp | alertflex/altprobe | 1c9f256ef8aa4a015cac1b1c5f990f4c177c8b3d | [
"Apache-2.0"
] | 8 | 2020-11-25T21:29:00.000Z | 2022-02-21T01:37:20.000Z | /*
* Copyright 2021 Oleg Zharkov
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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 "nids.h"
boost::lockfree::spsc_queue<string> q_logs_nids{LOG_QUEUE_SIZE};
int Nids::Open() {
char level[OS_HEADER_SIZE];
if (!sk.Open()) return 0;
if (surilog_status == 1) {
fp = fopen(suri_log, "r");
if(fp == NULL) {
SysLog("failed open suricata log file");
return status = 0;
}
fseek(fp,0,SEEK_END);
stat(suri_log, &buf);
file_size = (unsigned long) buf.st_size;
if (redis_status == 1) {
c = redisConnect(sk.redis_host, sk.redis_port);
if (c != NULL && c->err) {
// handle error
sprintf(level, "failed open redis server interface: %s\n", c->errstr);
SysLog(level);
redis_status = 0;
status = 1;
} else status = 2;
}
} else {
if (redis_status == 1) {
c = redisConnect(sk.redis_host, sk.redis_port);
if (c != NULL && c->err) {
// handle error
sprintf(level, "failed open redis server interface: %s\n", c->errstr);
SysLog(level);
status = 0;
}
} else status = 0;
}
if (maxmind_status) {
gi = GeoIP_open(maxmind_path, GEOIP_INDEX_CACHE);
if (gi == NULL) {
SysLog("error opening maxmind database\n");
maxmind_status = false;
}
}
return status;
}
void Nids::Close() {
sk.Close();
if (status > 0) {
if (surilog_status == 1) {
if (fp != NULL) fclose(fp);
}
if (redis_status == 1) redisFree(c);
status = 0;
}
}
void Nids::IsFileModified() {
int ret = stat(suri_log, &buf);
if (ret == 0) {
unsigned long current_size = (unsigned long) buf.st_size;
if (current_size < file_size) {
if (fp != NULL) fclose(fp);
fp = fopen(suri_log, "r");
if (fp == NULL) return;
else {
fseek(fp,0,SEEK_SET);
int ret = stat(suri_log, &buf);
if (ret != 0) {
fp = NULL;
return;
}
file_size = (unsigned long) buf.st_size;
return;
}
}
file_size = current_size;
return;
}
fp = NULL;
}
int Nids::ReadFile() {
if (fp == NULL) IsFileModified();
else {
if (fgets(file_payload, OS_PAYLOAD_SIZE, fp) != NULL) {
ferror_counter = 0;
return 1;
} else ferror_counter++;
if(ferror_counter > EOF_COUNTER) {
IsFileModified();
ferror_counter = 0;
}
}
return 0;
}
int Nids::Go(void) {
int read_res = 0;
int pars_res = 0;
ClearRecords();
if (status) {
if (surilog_status == 1) {
read_res = ReadFile();
if (read_res == -1) {
SysLog("failed reading suricata events from log");
return 1;
}
if (read_res > 0) {
pars_res = ParsJson(1);
if (pars_res > 0) ProcessEvent(pars_res);
}
}
if (redis_status == 1) {
if (read_res > 0) ClearRecords();
// read Suricata data
reply = (redisReply *) redisCommand( c, (const char *) redis_key.c_str());
if (!reply) {
SysLog("failed reading suricata events from redis");
freeReplyObject(reply);
return 1;
}
if (reply->type == REDIS_REPLY_STRING) {
read_res = 1;
pars_res = ParsJson(2);
if (pars_res > 0) ProcessEvent(pars_res);
}
freeReplyObject(reply);
}
if (read_res == 0) {
usleep(GetGosleepTimer()*60);
alerts_counter = 0;
return 1;
}
}
else usleep(GetGosleepTimer()*60);
return 1;
}
void Nids::ProcessEvent(int pars_res) {
GrayList* gl;
int severity;
IncrementEventsCounter();
boost::shared_lock<boost::shared_mutex> lock(fs.filters_update);
if (fs.filter.nids.log) CreateLogPayload(pars_res);
if (pars_res == 1 && alerts_counter <= sk.alerts_threshold) {
gl = CheckGrayList();
severity = PushIdsRecord(gl);
if (gl != NULL) {
if (gl->rsp.profile.compare("suppress") != 0) {
SendAlert(severity, gl);
}
} else {
if (fs.filter.nids.severity.threshold <= severity) SendAlert(severity, NULL);
}
if (sk.alerts_threshold != 0) {
if (alerts_counter < sk.alerts_threshold) alerts_counter++;
else {
SendAlertMultiple(2);
alerts_counter++;
}
}
}
}
GrayList* Nids::CheckGrayList() {
if (fs.filter.nids.gl.size() != 0) {
std::vector<GrayList*>::iterator i, end;
for (i = fs.filter.nids.gl.begin(), end = fs.filter.nids.gl.end(); i != end; ++i) {
int event_id = std::stoi((*i)->event);
if (event_id == rec.alert.signature_id) {
string host = (*i)->host;
if (host.compare("indef") == 0 || host.compare(rec.dst_ip) == 0 || host.compare(rec.src_ip) == 0) {
string match = (*i)->match;
if (match.compare("indef") == 0) return (*i);
else {
size_t found = jsonPayload.find(match);
if (found != std::string::npos) return (*i);
}
}
}
}
}
return NULL;
}
int Nids::ParsJson (int output_type) {
if (output_type == 1) {
jsonPayload.assign(file_payload, GetBufferSize(file_payload));
} else {
jsonPayload.assign(reply->str, GetBufferSize(reply->str));
}
try {
ss << jsonPayload;
bpt::read_json(ss, pt);
} catch (const std::exception & ex) {
ResetStream();
SysLog((char*) ex.what());
return 0;
}
bool is_aws_firewall = false;
string firewall_name = "indef";
if (output_type == 2) {
firewall_name = pt.get<string>("firewall_name","indef");
if (firewall_name.compare("indef") != 0) {
is_aws_firewall = true;
ss1 << jsonPayload;
bpt::read_json(ss1, pt1);
pt = pt1.get_child("event");
}
if (!is_aws_firewall) firewall_name = pt.get<string>("sensor-name","indef");
rec.sensor = probe_id + "." + firewall_name;
} else {
rec.sensor = probe_id + ".nids";
}
string event_type = pt.get<string>("event_type","");
if (event_type.compare("alert") == 0) {
rec.event_type = 1;
rec.time_stamp = pt.get<string>("timestamp","");
rec.iface = pt.get<string>("in_iface","");
rec.flow_id = pt.get<long>("flow_id",0);
rec.src_ip = pt.get<string>("src_ip","");
rec.src_hostname = GetHostname(rec.src_ip);
SetGeoBySrcIp(rec.src_ip);
rec.src_port = pt.get<int>("src_port",0);
rec.dst_ip = pt.get<string>("dest_ip","");
rec.dst_hostname = GetHostname(rec.dst_ip);
SetGeoByDstIp(rec.dst_ip);
rec.dst_port = pt.get<int>("dest_port",0);
rec.protocol = pt.get<string>("proto","");
// alert record
rec.alert.action = pt.get<string>("alert.action","");
rec.alert.gid = pt.get<int>("alert.gid",0);
rec.alert.signature_id = pt.get<long>("alert.signature_id",0);
rec.alert.signature = pt.get<string>("alert.signature","");
rec.alert.category = pt.get<string>("alert.category","");
rec.alert.severity = pt.get<int>("alert.severity",0);
ResetStream();
if(SuppressAlert(rec.src_ip)) return 0;
if(SuppressAlert(rec.dst_ip)) return 0;
return rec.event_type;
}
if (event_type.compare("dns") == 0) {
rec.event_type = 2;
rec.time_stamp = pt.get<string>("timestamp","");
rec.iface = pt.get<string>("in_iface","");
rec.flow_id = pt.get<long>("flow_id",0);
rec.src_ip = pt.get<string>("src_ip","");
rec.src_hostname = GetHostname(rec.src_ip);
SetGeoBySrcIp(rec.src_ip);
rec.src_port = pt.get<int>("src_port",0);
rec.dst_ip = pt.get<string>("dest_ip","");
rec.dst_hostname = GetHostname(rec.dst_ip);
SetGeoByDstIp(rec.dst_ip);
rec.dst_port = pt.get<int>("dest_port",0);
rec.protocol = pt.get<string>("proto","");
// dns record
rec.dns.type = pt.get<string>("dns.type","");
rec.dns.id = pt.get<int>("dns.id",0);
rec.dns.rrname = pt.get<string>("dns.rrname","");
rec.dns.rrtype = pt.get<string>("dns.rrtype","");
if (!rec.dns.type.compare("answer")) {
rec.dns.ttl = pt.get<int>("dns.ttl",0);
rec.dns.rcode = pt.get<string>("dns.rcode","");
rec.dns.rdata = pt.get<string>("dns.rdata","");
}
else rec.dns.tx_id = pt.get<int>("dns.tx_id",0);
ResetStream();
return rec.event_type;
}
if (event_type.compare("http") == 0) {
rec.event_type = 3;
rec.time_stamp = pt.get<string>("timestamp","");
rec.iface = pt.get<string>("in_iface","");
rec.flow_id = pt.get<long>("flow_id",0);
rec.src_ip = pt.get<string>("src_ip","");
rec.src_hostname = GetHostname(rec.src_ip);
SetGeoBySrcIp(rec.src_ip);
rec.src_port = pt.get<int>("src_port",0);
rec.dst_ip = pt.get<string>("dest_ip","");
rec.dst_hostname = GetHostname(rec.dst_ip);
SetGeoByDstIp(rec.dst_ip);
rec.dst_port = pt.get<int>("dest_port",0);
rec.protocol = pt.get<string>("proto","");
rec.http.hostname = pt.get<string>("http.hostname","indef");
rec.http.url = pt.get<string>("http.url","indef");
rec.http.http_user_agent = pt.get<string>("http.http_user_agent","indef");
rec.http.http_content_type = pt.get<string>("http.http_content_type","indef");
ResetStream();
return rec.event_type;
}
if (event_type.compare("netflow") == 0) {
rec.ref_id = fs.filter.ref_id;
rec.event_type = 4;
rec.time_stamp = pt.get<string>("timestamp","");
rec.iface = pt.get<string>("in_iface","");
rec.flow_id = pt.get<long>("flow_id",0);
rec.src_ip = pt.get<string>("src_ip","");
rec.src_hostname = GetHostname(rec.src_ip);
SetGeoBySrcIp(rec.src_ip);
rec.src_port = pt.get<int>("src_port",0);
rec.dst_ip = pt.get<string>("dest_ip","");
rec.dst_hostname = GetHostname(rec.dst_ip);
SetGeoByDstIp(rec.dst_ip);
rec.dst_port = pt.get<int>("dest_port",0);
rec.protocol = pt.get<string>("proto","");
rec.netflow.app_proto = pt.get<string>("app_proto","indef");
if (rec.netflow.app_proto.compare("") == 0) rec.netflow.app_proto = "indef";
if (rec.netflow.app_proto.compare("failed") == 0) rec.netflow.app_proto = "indef";
rec.netflow.bytes = pt.get<int>("netflow.bytes",0);
rec.netflow.pkts = pt.get<int>("netflow.pkts",0);
rec.netflow.start = pt.get<string>("netflow.start","");
rec.netflow.end = pt.get<string>("netflow.end","");
rec.netflow.age = pt.get<int>("netflow.age",0);
if (fs.filter.netflow.log) {
net_flow.ref_id = rec.ref_id;
net_flow.sensor = rec.sensor;
net_flow.dst_ip = rec.dst_ip;
net_flow.src_ip = rec.src_ip;
net_flow.dst_country = dst_cc;
net_flow.src_country = src_cc;
net_flow.dst_hostname = rec.dst_hostname;
net_flow.src_hostname = rec.src_hostname;
net_flow.bytes = rec.netflow.bytes;
net_flow.sessions = 1;
if (is_aws_firewall) net_flow.type = 1;
else net_flow.type = 0;
q_netflow.push(net_flow);
}
ResetStream();
return rec.event_type;
}
if (event_type.compare("fileinfo") == 0) {
rec.event_type = 5;
rec.time_stamp = pt.get<string>("timestamp","");
rec.iface = pt.get<string>("in_iface","");
rec.flow_id = pt.get<long>("flow_id",0);
rec.src_ip = pt.get<string>("src_ip","");
rec.src_hostname = GetHostname(rec.src_ip);
SetGeoBySrcIp(rec.src_ip);
rec.src_port = pt.get<int>("src_port",0);
rec.dst_ip = pt.get<string>("dest_ip","");
SetGeoByDstIp(rec.dst_ip);
rec.dst_hostname = GetHostname(rec.dst_ip);
rec.dst_port = pt.get<int>("dest_port",0);
rec.protocol = pt.get<string>("proto","");
rec.file.app_proto = pt.get<string>("app_proto","indef");
if (rec.file.app_proto.compare("") == 0) rec.netflow.app_proto = "indef";
if (rec.file.app_proto.compare("failed") == 0) rec.netflow.app_proto = "indef";
rec.file.name = pt.get<string>("fileinfo.filename","");
rec.file.size = pt.get<int>("fileinfo.size",0);
rec.file.state = pt.get<string>("fileinfo.state","");
rec.file.md5 = pt.get<string>("fileinfo.md5","");
ResetStream();
return rec.event_type;
}
if (event_type.compare("stats") == 0) {
net_stat.ids = rec.sensor;
net_stat.ref_id = fs.filter.ref_id;
net_stat.invalid = pt.get<long>("stats.decoder.invalid",0);
net_stat.pkts = pt.get<long>("stats.decoder.pkts",0);
net_stat.bytes = pt.get<long>("stats.decoder.bytes",0);
net_stat.ipv4 = pt.get<long>("stats.decoder.ipv4",0);
net_stat.ipv6 = pt.get<long>("stats.decoder.ipv6",0);
net_stat.ethernet = pt.get<long>("stats.decoder.ethernet",0);
net_stat.tcp = pt.get<long>("stats.decoder.tcp",0);
net_stat.udp = pt.get<long>("stats.decoder.udp",0);
net_stat.sctp = pt.get<long>("stats.decoder.sctp",0);
net_stat.icmpv4 = pt.get<long>("stats.decoder.icmp4",0);
net_stat.icmpv6 = pt.get<long>("stats.decoder.icmp6",0);
net_stat.ppp = pt.get<long>("stats.decoder.ppp",0);
net_stat.pppoe = pt.get<long>("stats.decoder.pppoe",0);
net_stat.gre = pt.get<long>("stats.decoder.gre",0);
net_stat.vlan = pt.get<long>("stats.decoder.vlan",0);
net_stat.vlan_qinq = pt.get<long>("stats.decoder.vlan_qinq",0);
net_stat.teredo = pt.get<long>("stats.decoder.teredo",0);
net_stat.ipv4_in_ipv6 = pt.get<long>("stats.decoder.ipv4_in_ipv6",0);
net_stat.ipv6_in_ipv6 = pt.get<long>("stats.decoder.ipv6_in_ipv6",0);
net_stat.mpls = pt.get<long>("stats.decoder.mpls",0);
q_netstat.push(net_stat);
}
ResetStream();
return 0;
}
void Nids::CreateLogPayload(int r) {
switch (r) {
case 1: // alert record
report = "{\"version\": \"1.1\",\"node\":\"";
report += node_id;
report += "\",\"short_message\":\"alert-nids\"";
report += ",\"full_message\":\"Alert from Suricata NIDS\"";
report += ",\"level\":";
report += std::to_string(7);
report += ",\"source_type\":\"NET\"";
report += ",\"source_name\":\"Suricata\"";
report += ",\"project_id\":\"";
report += fs.filter.ref_id;
report += "\",\"sensor\":\"";
report += rec.sensor;
report += "\",\"event_time\":\"";
report += rec.time_stamp;
report += "\",\"collected_time\":\"";
report += GetGraylogFormat();
report += "\",\"severity\":";
report += std::to_string(rec.alert.severity);
report += ",\"category\":\"";
report += rec.alert.category;
report += "\",\"signature\":\"";
report += rec.alert.signature;
report += "\",\"iface\":\"";
report += rec.iface;
report += "\",\"flow_id\":";
report += std::to_string(rec.flow_id);
report += ",\"srcip\":\"";
report += rec.src_ip;
report += "\",\"dstip\":\"";
report += rec.dst_ip;
report += "\",\"src_ip_geo_country\":\"";
report += src_cc;
report += "\",\"dst_ip_geo_country\":\"";
report += dst_cc;
report += "\",\"src_ip_geo_location\":\"";
report += src_latitude + "," + src_longitude;
report += "\",\"dst_ip_geo_location\":\"";
report += dst_latitude + "," + dst_longitude;
report += "\",\"srchostname\":\"";
report += rec.src_hostname;
report += "\",\"dsthostname\":\"";
report += rec.dst_hostname;
report += "\",\"srcport\":";
report += std::to_string(rec.src_port);
report += ",\"dstport\":";
report += std::to_string(rec.dst_port);
report += ",\"gid\":";
report += std::to_string(rec.alert.gid);
report += ",\"signature_id\":";
report += std::to_string(rec.alert.signature_id);
report += ",\"action\":\"";
report += rec.alert.action;
report += "\"}";
//SysLog((char*) report.str().c_str());
break;
case 2: // dns record
report = "{\"version\": \"1.1\",\"node\":\"";
report += node_id;
report += "\",\"short_message\":\"dns-nids\"";
report += ",\"full_message\":\"DNS event from Suricata NIDS\"";
report += ",\"level\":";
report += std::to_string(7);
report += ",\"source_type\":\"NET\"";
report += ",\"source_name\":\"Suricata\"";
report += ",\"project_id\":\"";
report += fs.filter.ref_id;
report += "\",\"sensor\":\"";
report += rec.sensor;
report += "\",\"event_time\":\"";
report += rec.time_stamp;
report += "\",\"collected_time\":\"";
report += GetGraylogFormat();
report += "\",\"dns_type\":\"";
report += rec.dns.type;
report += "\",\"iface\":\"";
report += rec.iface;
report += "\",\"flow_id\":";
report += std::to_string(rec.flow_id);
report += ",\"srcip\":\"";
report += rec.src_ip;
report += "\",\"dstip\":\"";
report += rec.dst_ip;
report += "\",\"src_ip_geo_country\":\"";
report += src_cc;
report += "\",\"dst_ip_geo_country\":\"";
report += dst_cc;
report += "\",\"src_ip_geo_location\":\"";
report += src_latitude + "," + src_longitude;
report += "\",\"dst_ip_geo_location\":\"";
report += dst_latitude + "," + dst_longitude;
report += "\",\"srchostname\":\"";
report += rec.src_hostname;
report += "\",\"dsthostname\":\"";
report += rec.dst_hostname;
report += "\",\"srcport\":";
report += std::to_string(rec.src_port);
report += ",\"dstport\":";
report += std::to_string(rec.dst_port);
report += ",\"id\":";
report += std::to_string(rec.dns.id);
report += ",\"rrname\":\"";
report += rec.dns.rrname;
report += "\",\"rrtype\":\"";
report += rec.dns.rrtype;
if (!rec.dns.type.compare("answer")) {
report += "\",\"rcode\":\"";
report += rec.dns.rcode;
report += "\",\"rdata\":\"";
report += rec.dns.rdata;
report += "\",\"ttl\":";
report += std::to_string(rec.dns.ttl);
}
else {
report += "\",\"tx_id\":";
report += std::to_string(rec.dns.tx_id);
}
report += "}";
// SysLog((char*) report.c_str());
break;
case 3: // http record
report = "{\"version\": \"1.1\",\"node\":\"";
report += node_id;
report += "\",\"short_message\":\"http-nids\"";
report += ",\"full_message\":\"HTTP event from Suricata NIDS\"";
report += ",\"level\":";
report += std::to_string(7);
report += ",\"source_type\":\"NET\"";
report += ",\"source_name\":\"Suricata\"";
report += ",\"project_id\":\"";
report += fs.filter.ref_id;
report += "\",\"sensor\":\"";
report += rec.sensor;
report += "\",\"event_time\":\"";
report += rec.time_stamp;
report += "\",\"collected_time\":\"";
report += GetGraylogFormat();
report += "\",\"flow_id\":";
report += std::to_string(rec.flow_id);
report += ",\"srcip\":\"";
report += rec.src_ip;
report += "\",\"dstip\":\"";
report += rec.dst_ip;
report += "\",\"src_ip_geo_country\":\"";
report += src_cc;
report += "\",\"dst_ip_geo_country\":\"";
report += dst_cc;
report += "\",\"src_ip_geo_location\":\"";
report += src_latitude + "," + src_longitude;
report += "\",\"dst_ip_geo_location\":\"";
report += dst_latitude + "," + dst_longitude;
report += "\",\"srchostname\":\"";
report += rec.src_hostname;
report += "\",\"dsthostname\":\"";
report += rec.dst_hostname;
report += "\",\"srcport\":";
report += std::to_string(rec.src_port);
report += ",\"dstport\":";
report += std::to_string(rec.dst_port);
report += ",\"url_hostname\":\"";
report += rec.http.hostname;
report += "\",\"url_path\":\"";
report += rec.http.url;
report += "\",\"http_user_agent\":\"";
report += rec.http.http_user_agent;
report += "\",\"http_content_type\":\"";
report += rec.http.http_content_type;
report += "\"}";
break;
case 4: // flow record
report = "{\"version\": \"1.1\",\"node\":\"";
report += node_id;
report += "\",\"short_message\":\"netflow-nids\"";
report += ",\"full_message\":\"Netflow event from Suricata NIDS\"";
report += ",\"level\":";
report += std::to_string(7);
report += ",\"source_type\":\"NET\"";
report += ",\"source_name\":\"Suricata\"";
report += ",\"project_id\":\"";
report += fs.filter.ref_id;
report += "\",\"sensor\":\"";
report += rec.sensor;
report += "\",\"event_time\":\"";
report += rec.time_stamp;
report += "\",\"collected_time\":\"";
report += GetGraylogFormat();
report += "\",\"protocol\":\"";
report += rec.protocol;
report += "\",\"process\":\"";
report += rec.netflow.app_proto;
report += "\",\"srcip\":\"";
report += rec.src_ip;
report += "\",\"src_ip_geo_country\":\"";
report += src_cc;
report += "\",\"src_ip_geo_location\":\"";
report += src_latitude + "," + src_longitude;
report += "\",\"srchostname\":\"";
report += rec.src_hostname;
report += "\",\"srcport\":";
report += std::to_string(rec.src_port);
report += ",\"dstip\":\"";
report += rec.dst_ip;
report += "\",\"dst_ip_geo_country\":\"";
report += dst_cc;
report += "\",\"dst_ip_geo_location\":\"";
report += dst_latitude + "," + dst_longitude;
report += "\",\"dsthostname\":\"";
report += rec.dst_hostname;
report += "\",\"dstport\":";
report += std::to_string(rec.dst_port);
report += ",\"bytes\":";
report += std::to_string(rec.netflow.bytes);
report += ",\"packets\":";
report += std::to_string(rec.netflow.pkts);
report += "}";
break;
case 5: // file record
report = "{\"version\": \"1.1\",\"node\":\"";
report += node_id;
report += "\",\"short_message\":\"file-nids\"";
report += ",\"full_message\":\"File event from Suricata NIDS\"";
report += ",\"level\":";
report += std::to_string(7);
report += ",\"source_type\":\"NET\"";
report += ",\"source_name\":\"Suricata\"";
report += ",\"project_id\":\"";
report += fs.filter.ref_id;
report += "\",\"sensor\":\"";
report += rec.sensor;
report += "\",\"event_time\":\"";
report += rec.time_stamp;
report += "\",\"collected_time\":\"";
report += GetGraylogFormat();
report += "\",\"protocol\":\"";
report += rec.protocol;
report += "\",\"process\":\"";
report += rec.file.app_proto;
report += "\",\"srcip\":\"";
report += rec.src_ip;
report += "\",\"src_ip_geo_country\":\"";
report += src_cc;
report += "\",\"src_ip_geo_location\":\"";
report += src_latitude + "," + src_longitude;
report += "\",\"srchostname\":\"";
report += rec.src_hostname;
report += "\",\"srcport\":";
report += std::to_string(rec.src_port);
report += ",\"dstip\":\"";
report += rec.dst_ip;
report += "\",\"dst_ip_geo_country\":\"";
report += dst_cc;
report += "\",\"dst_ip_geo_location\":\"";
report += dst_latitude + "," + dst_longitude;
report += "\",\"dsthostname\":\"";
report += rec.dst_hostname;
report += "\",\"dstport\":";
report += std::to_string(rec.dst_port);
report += ",\"filename\":\"";
report += rec.file.name;
report += "\",\"size\":";
report += std::to_string(rec.file.size);
report += ",\"state\":\"";
report += rec.file.state;
report += "\",\"md5\":\"";
report += rec.file.md5;
report += "\"}";
break;
}
q_logs_nids.push(report);
report.clear();
}
void Nids::SendAlert(int s, GrayList* gl) {
sk.alert.ref_id = fs.filter.ref_id;
sk.alert.sensor_id = rec.sensor;
sk.alert.alert_severity = s;
sk.alert.alert_source = "Suricata";
sk.alert.alert_type = "NET";
sk.alert.event_severity = rec.alert.severity;
sk.alert.event_id = std::to_string(rec.alert.signature_id);
sk.alert.description = rec.alert.signature;
sk.alert.action = "indef";
sk.alert.location = std::to_string(rec.flow_id);
sk.alert.info = "{\"artifacts\": [{\"dataType\": \"ip\",\"data\":\"";
sk.alert.info += rec.src_ip;
sk.alert.info += "\",\"message\":\"src ip\" }, {\"dataType\": \"ip\",\"data\":\"";
sk.alert.info += rec.dst_ip;
sk.alert.info += "\",\"message\":\"dst ip\" }]}";
sk.alert.status = "processed";
sk.alert.user_name = "indef";
sk.alert.agent_name = probe_id;
sk.alert.filter = fs.filter.name;
sk.alert.list_cats.push_back(rec.alert.category);
sk.alert.event_time = rec.time_stamp;
if (gl != NULL) {
if (gl->rsp.profile.compare("indef") != 0) {
sk.alert.action = gl->rsp.profile;
sk.alert.status = "modified";
}
if (gl->rsp.new_type.compare("indef") != 0) {
sk.alert.alert_type = gl->rsp.new_type;
sk.alert.status = "modified";
}
if (gl->rsp.new_source.compare("indef") != 0) {
sk.alert.alert_source = gl->rsp.new_source;
sk.alert.status = "modified";
}
if (gl->rsp.new_event.compare("indef") != 0) {
sk.alert.event_id = gl->rsp.new_event;
sk.alert.status = "modified";
}
if (gl->rsp.new_severity != 0) {
sk.alert.alert_severity = gl->rsp.new_severity;
sk.alert.status = "modified";
}
if (gl->rsp.new_category.compare("indef") != 0) {
sk.alert.list_cats.push_back(gl->rsp.new_category);
sk.alert.status = "modified";
}
if (gl->rsp.new_description.compare("indef") != 0) {
sk.alert.description = gl->rsp.new_description;
sk.alert.status = "modified";
}
}
sk.alert.src_ip = rec.src_ip;
sk.alert.dst_ip = rec.dst_ip;
sk.alert.src_port = rec.src_port;
sk.alert.dst_port = rec.dst_port;
sk.alert.src_hostname = rec.src_hostname;
sk.alert.dst_hostname = rec.dst_hostname;
sk.alert.reg_value = "indef";
sk.alert.file_name = "indef";
sk.alert.hash_md5 = "indef";
sk.alert.hash_sha1 = "indef";
sk.alert.hash_sha256 = "indef";
sk.alert.process_id = 0;
sk.alert.process_name = "indef";
sk.alert.process_cmdline = "indef";
sk.alert.process_path = "indef";
sk.alert.url_hostname = "indef";
sk.alert.url_path = "indef";
sk.alert.container_id = "indef";
sk.alert.container_name = "indef";
sk.alert.cloud_instance = "indef";
sk.SendAlert();
}
int Nids::PushIdsRecord(GrayList* gl) {
// create new ids record
IdsRecord ids_rec;
ids_rec.ref_id = fs.filter.ref_id;
ids_rec.list_cats.push_back(rec.alert.category);
ids_rec.event = std::to_string(rec.alert.signature_id);
ids_rec.desc = rec.alert.signature;
ids_rec.severity = rec.alert.severity;
switch (rec.alert.severity) {
case 1 :
ids_rec.severity = 3;
break;
case 2 :
ids_rec.severity = 2;
break;
case 3 :
ids_rec.severity = 1;
break;
default :
ids_rec.severity = 0;
break;
}
ids_rec.src_ip = rec.src_ip;
ids_rec.dst_ip = rec.dst_ip;
ids_rec.agent = probe_id;
ids_rec.ids = rec.sensor;
ids_rec.location = rec.dst_hostname;
if (gl != NULL) {
ids_rec.filter = true;
if (gl->agr.reproduced > 0) {
ids_rec.host = gl->host;
ids_rec.match = gl->match;
ids_rec.agr.in_period = gl->agr.in_period;
ids_rec.agr.reproduced = gl->agr.reproduced;
ids_rec.rsp.profile = gl->rsp.profile;
ids_rec.rsp.new_category = gl->rsp.new_category;
ids_rec.rsp.new_description = gl->rsp.new_description;
ids_rec.rsp.new_event = gl->rsp.new_event;
ids_rec.rsp.new_severity = gl->rsp.new_severity;
ids_rec.rsp.new_type = gl->rsp.new_type;
ids_rec.rsp.new_source = gl->rsp.new_source;
}
}
q_nids.push(ids_rec);
return ids_rec.severity;
}
| 30.667838 | 115 | 0.460602 | alertflex |
84791dfe5d8cdbc4917e4d3e1a30a888b4ce0d9f | 1,797 | cpp | C++ | src/GUI.cpp | montoyo/mgpcl | 8e65d01e483124936de3650154e0e7e9586d27c0 | [
"MIT"
] | null | null | null | src/GUI.cpp | montoyo/mgpcl | 8e65d01e483124936de3650154e0e7e9586d27c0 | [
"MIT"
] | 2 | 2018-12-13T09:10:03.000Z | 2018-12-22T13:52:00.000Z | src/GUI.cpp | montoyo/mgpcl | 8e65d01e483124936de3650154e0e7e9586d27c0 | [
"MIT"
] | null | null | null | /* Copyright (C) 2017 BARBOTIN Nicolas
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "mgpcl/GUI.h"
#include "mgpcl/Config.h"
#if defined(MGPCL_NO_GUI)
void m::gui::initialize()
{
}
bool m::gui::hasBeenInitialized()
{
return false;
}
#elif defined(MGPCL_WIN)
void m::gui::initialize()
{
}
bool m::gui::hasBeenInitialized()
{
return true;
}
#else
#include "mgpcl/Mutex.h"
#include <gtk/gtk.h>
static volatile bool g_guiInit = false;
static m::Mutex g_guiLock;
void m::gui::initialize()
{
g_guiLock.lock();
gtk_init(nullptr, nullptr);
g_guiInit = true;
g_guiLock.unlock();
}
bool m::gui::hasBeenInitialized()
{
volatile bool ret;
g_guiLock.lock();
ret = g_guiInit;
g_guiLock.unlock();
return ret;
}
#endif
| 24.958333 | 92 | 0.72621 | montoyo |
847a705867274c9681669a12d56da33ff156735a | 408 | cc | C++ | atcoder/abc/079/a_good_integer.cc | boobam0618/competitive-programming | 0341bd8bb240b1ed0d84cc60db91508242fc867b | [
"MIT"
] | null | null | null | atcoder/abc/079/a_good_integer.cc | boobam0618/competitive-programming | 0341bd8bb240b1ed0d84cc60db91508242fc867b | [
"MIT"
] | 32 | 2019-08-15T09:16:48.000Z | 2020-02-09T16:23:30.000Z | atcoder/abc/079/a_good_integer.cc | boobam0618/competitive-programming | 0341bd8bb240b1ed0d84cc60db91508242fc867b | [
"MIT"
] | null | null | null | #include <iostream>
int main() {
int n;
std::cin >> n;
int thousands = n / 1000;
int hundreds = n / 100 % 10;
int tens = n / 10 % 10;
int ones = n % 10;
std::string is_good_integer;
if (thousands == hundreds && hundreds == tens ||
hundreds == tens && tens == ones) {
is_good_integer = "Yes";
} else {
is_good_integer = "No";
}
std::cout << is_good_integer << std::endl;
}
| 20.4 | 50 | 0.568627 | boobam0618 |
847aa6ce44bce9c20769e558f9fdb47ce6f63fb1 | 416 | cpp | C++ | CSES/Removing Digits.cpp | XitizVerma/Data-Structures-and-Algorithms-Advanced | 610225eeb7e0b4ade229ec86355901ad1ca38784 | [
"MIT"
] | 1 | 2020-08-27T06:59:52.000Z | 2020-08-27T06:59:52.000Z | CSES/Removing Digits.cpp | XitizVerma/Data-Structures-and-Algorithms-Advanced | 610225eeb7e0b4ade229ec86355901ad1ca38784 | [
"MIT"
] | null | null | null | CSES/Removing Digits.cpp | XitizVerma/Data-Structures-and-Algorithms-Advanced | 610225eeb7e0b4ade229ec86355901ad1ca38784 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define M 1000000007
#define N 300010
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
int dp[n+1];
for(int i=0;i<=n;i++)
dp[i]=INT_MAX;
dp[0]=0;
for(int i=1;i<=n;i++){
int num=i;
while(num>0){
int val=num%10;
num/=10;
dp[i]=min(dp[i],dp[i-val]+1);
}
}
cout << dp[n] << endl;
} | 14.344828 | 34 | 0.572115 | XitizVerma |
847b4738437e4552f902362fe840355d554d98c4 | 1,985 | cpp | C++ | controllers/ControllerAdaugaRefill.cpp | xiofurry/magazin-manager-project | bb0c765f87c8f08493cefcaae39ed42639229585 | [
"MIT"
] | null | null | null | controllers/ControllerAdaugaRefill.cpp | xiofurry/magazin-manager-project | bb0c765f87c8f08493cefcaae39ed42639229585 | [
"MIT"
] | null | null | null | controllers/ControllerAdaugaRefill.cpp | xiofurry/magazin-manager-project | bb0c765f87c8f08493cefcaae39ed42639229585 | [
"MIT"
] | null | null | null | //
// Created by xiodine on 4/19/15.
//
#include <sstream>
#include "ControllerAdaugaRefill.h"
#include "../views/ViewConsole.h"
ControllerAdaugaRefill::ControllerAdaugaRefill() : Controller() {
}
ControllerAdaugaRefill::~ControllerAdaugaRefill() {
}
std::size_t ControllerAdaugaRefill::showOptions(ModelStoc &stoc) {
ViewConsole &con = ViewConsole::getSingleton();
// typedefs
typedef ModelBun::trasaturi_t trasaturi_t;
// for each bun
ModelStoc::bunuri_pointer_t bunuri = stoc.getBunuriPointer();
std::size_t nrProduse = 0;
for (ModelStoc::bunuri_pointer_t::const_iterator i = bunuri.begin(); i != bunuri.end(); ++i) {
const ModelBun &bun = **i;
nrProduse++;
con << nrProduse << ". " << bun.getNume() << " (";
const trasaturi_t &trasaturi = bun.getTrasaturi();
for (trasaturi_t::const_iterator j = trasaturi.begin(); j != trasaturi.end(); ++j) {
if (j != trasaturi.begin())
con << ", ";
con << '\'' << *j << '\'';
}
con << ") - " << bun.getStoc() << " in stoc";
}
return nrProduse;
}
void ControllerAdaugaRefill::run(ModelStoc &stoc) {
std::size_t maxSize = showOptions(stoc);
ViewConsole &con = ViewConsole::getSingleton();
std::size_t nr;
do {
con << "\nIntroduceti numarul produsului (0 pentru stop): ";
std::stringstream str(con.getLine());
str >> nr;
if (nr) {
// test for validity
if (nr > maxSize) {
con << "Numar invalid!";
} else {
con << "Numarul de produse de adaugat (numar): ";
std::stringstream nrProdStr(con.getLine());
int nrProd;
nrProdStr >> nrProd;
ModelStoc::bunuri_pointer_t bunuri = stoc.getBunuriPointer();
stoc.addStocToBun(bunuri[nr - 1], nrProd);
}
} // else nr == 0
} while (nr != 0);
}
| 27.569444 | 98 | 0.559194 | xiofurry |
847bf32da15223813d7279e6e8226808fa6e626c | 10,168 | cpp | C++ | Stars45/MsnPkgDlg.cpp | RogerioY/starshatter-open | 3a507e08b1d4e5970b27401a7e6517570d529400 | [
"BSD-3-Clause"
] | null | null | null | Stars45/MsnPkgDlg.cpp | RogerioY/starshatter-open | 3a507e08b1d4e5970b27401a7e6517570d529400 | [
"BSD-3-Clause"
] | 4 | 2019-09-05T22:22:57.000Z | 2021-03-28T02:09:24.000Z | Stars45/MsnPkgDlg.cpp | RogerioY/starshatter-open | 3a507e08b1d4e5970b27401a7e6517570d529400 | [
"BSD-3-Clause"
] | null | null | null | /* Starshatter OpenSource Distribution
Copyright (c) 1997-2004, Destroyer Studios LLC.
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 "Destroyer Studios" nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
SUBSYSTEM: Stars.exe
FILE: MsnPkgDlg.cpp
AUTHOR: John DiCamillo
OVERVIEW
========
Mission Briefing Dialog Active Window class
*/
#include "MemDebug.h"
#include "MsnPkgDlg.h"
#include "PlanScreen.h"
#include "Campaign.h"
#include "Mission.h"
#include "Instruction.h"
#include "Ship.h"
#include "ShipDesign.h"
#include "StarSystem.h"
#include "Game.h"
#include "Mouse.h"
#include "Button.h"
#include "ListBox.h"
#include "Slider.h"
#include "ParseUtil.h"
#include "FormatUtil.h"
#include "Keyboard.h"
// +--------------------------------------------------------------------+
// DECLARE MAPPING FUNCTIONS:
DEF_MAP_CLIENT(MsnPkgDlg, OnPackage);
DEF_MAP_CLIENT(MsnPkgDlg, OnCommit);
DEF_MAP_CLIENT(MsnPkgDlg, OnCancel);
DEF_MAP_CLIENT(MsnPkgDlg, OnTabButton);
// +--------------------------------------------------------------------+
MsnPkgDlg::MsnPkgDlg(Screen* s, FormDef& def, PlanScreen* mgr)
: FormWindow(s, 0, 0, s->Width(), s->Height()), MsnDlg(mgr)
{
campaign = Campaign::GetCampaign();
if (campaign)
mission = campaign->GetMission();
Init(def);
}
MsnPkgDlg::~MsnPkgDlg()
{
}
// +--------------------------------------------------------------------+
void
MsnPkgDlg::RegisterControls()
{
pkg_list = (ListBox*) FindControl(320);
nav_list = (ListBox*) FindControl(330);
for (int i = 0; i < 5; i++)
threat[i] = FindControl(251 + i);
RegisterMsnControls(this);
if (pkg_list)
REGISTER_CLIENT(EID_SELECT, pkg_list, MsnPkgDlg, OnPackage);
if (commit)
REGISTER_CLIENT(EID_CLICK, commit, MsnPkgDlg, OnCommit);
if (cancel)
REGISTER_CLIENT(EID_CLICK, cancel, MsnPkgDlg, OnCancel);
if (sit_button)
REGISTER_CLIENT(EID_CLICK, sit_button, MsnPkgDlg, OnTabButton);
if (pkg_button)
REGISTER_CLIENT(EID_CLICK, pkg_button, MsnPkgDlg, OnTabButton);
if (nav_button)
REGISTER_CLIENT(EID_CLICK, nav_button, MsnPkgDlg, OnTabButton);
if (wep_button)
REGISTER_CLIENT(EID_CLICK, wep_button, MsnPkgDlg, OnTabButton);
}
// +--------------------------------------------------------------------+
void
MsnPkgDlg::Show()
{
FormWindow::Show();
ShowMsnDlg();
DrawPackages();
DrawNavPlan();
DrawThreats();
}
// +--------------------------------------------------------------------+
void
MsnPkgDlg::DrawPackages()
{
if (mission) {
if (pkg_list) {
pkg_list->ClearItems();
int i = 0;
int elem_index = 0;
ListIter<MissionElement> elem = mission->GetElements();
while (++elem) {
// display this element?
if (elem->GetIFF() == mission->Team() &&
!elem->IsSquadron() &&
elem->Region() == mission->GetRegion() &&
elem->GetDesign()->type < Ship::STATION) {
char txt[256];
if (elem->Player() > 0) {
sprintf_s(txt, "==>");
if (pkg_index < 0)
pkg_index = elem_index;
}
else {
strcpy_s(txt, " ");
}
pkg_list->AddItemWithData(txt, elem->ElementID());
pkg_list->SetItemText(i, 1, elem->Name());
pkg_list->SetItemText(i, 2, elem->RoleName());
const ShipDesign* design = elem->GetDesign();
if (elem->Count() > 1)
sprintf_s(txt, "%d %s", elem->Count(), design->abrv);
else
sprintf_s(txt, "%s %s", design->abrv, design->name);
pkg_list->SetItemText(i, 3, txt);
i++;
}
elem_index++;
}
}
}
}
// +--------------------------------------------------------------------+
void
MsnPkgDlg::DrawNavPlan()
{
if (mission) {
if (pkg_index < 0 || pkg_index >= mission->GetElements().size())
pkg_index = 0;
MissionElement* element = mission->GetElements()[pkg_index];
if (nav_list && element) {
nav_list->ClearItems();
Point loc = element->Location();
int i = 0;
ListIter<Instruction> navpt = element->NavList();
while (++navpt) {
char txt[256];
sprintf_s(txt, "%d", i + 1);
nav_list->AddItem(txt);
nav_list->SetItemText(i, 1, Instruction::ActionName(navpt->Action()));
nav_list->SetItemText(i, 2, navpt->RegionName());
double dist = Point(loc - navpt->Location()).length();
FormatNumber(txt, dist);
nav_list->SetItemText(i, 3, txt);
sprintf_s(txt, "%d", navpt->Speed());
nav_list->SetItemText(i, 4, txt);
loc = navpt->Location();
i++;
}
}
}
}
// +--------------------------------------------------------------------+
void
MsnPkgDlg::DrawThreats()
{
for (int i = 0; i < 5; i++)
if (threat[i])
threat[i]->SetText("");
if (!mission) return;
MissionElement* player = mission->GetPlayer();
if (!player) return;
Text rgn0 = player->Region();
Text rgn1;
int iff = player->GetIFF();
ListIter<Instruction> nav = player->NavList();
while (++nav) {
if (rgn0 != nav->RegionName())
rgn1 = nav->RegionName();
}
if (threat[0]) {
Point base_loc = mission->GetElements()[0]->Location();
int i = 0;
ListIter<MissionElement> iter = mission->GetElements();
while (++iter) {
MissionElement* elem = iter.value();
if (elem->GetIFF() == 0 || elem->GetIFF() == iff || elem->IntelLevel() <= Intel::SECRET)
continue;
if (elem->IsSquadron())
continue;
if (elem->IsGroundUnit()) {
if (!elem->GetDesign() ||
elem->GetDesign()->type != Ship::SAM)
continue;
if (elem->Region() != rgn0 &&
elem->Region() != rgn1)
continue;
}
int mission_role = elem->MissionRole();
if (mission_role == Mission::STRIKE ||
mission_role == Mission::INTEL ||
mission_role >= Mission::TRANSPORT)
continue;
char rng[32];
char role[32];
char txt[256];
if (mission_role == Mission::SWEEP ||
mission_role == Mission::INTERCEPT ||
mission_role == Mission::FLEET ||
mission_role == Mission::BOMBARDMENT)
strcpy_s(role, Game::GetText("MsnDlg.ATTACK").data());
else
strcpy_s(role, Game::GetText("MsnDlg.PATROL").data());
double dist = Point(base_loc - elem->Location()).length();
FormatNumber(rng, dist);
sprintf_s(txt, "%s - %d %s - %s", role,
elem->Count(),
elem->GetDesign()->abrv,
rng);
if (threat[i])
threat[i]->SetText(txt);
i++;
if (i >= 5)
break;
}
}
}
// +--------------------------------------------------------------------+
void
MsnPkgDlg::ExecFrame()
{
if (Keyboard::KeyDown(VK_RETURN)) {
OnCommit(0);
}
}
// +--------------------------------------------------------------------+
void
MsnPkgDlg::OnPackage(AWEvent* event)
{
if (!pkg_list || !mission)
return;
int seln = pkg_list->GetListIndex();
int pkg = pkg_list->GetItemData(seln);
int i = 0;
ListIter<MissionElement> elem = mission->GetElements();
while (++elem) {
if (elem->ElementID() == pkg) {
pkg_index = i;
//mission->SetPlayer(elem.value());
}
i++;
}
//DrawPackages();
DrawNavPlan();
}
// +--------------------------------------------------------------------+
void
MsnPkgDlg::OnCommit(AWEvent* event)
{
MsnDlg::OnCommit(event);
}
void
MsnPkgDlg::OnCancel(AWEvent* event)
{
MsnDlg::OnCancel(event);
}
void
MsnPkgDlg::OnTabButton(AWEvent* event)
{
MsnDlg::OnTabButton(event);
}
| 28.166205 | 100 | 0.511802 | RogerioY |
848263edc5cbcdd8136ec1387915b259fa9e0427 | 6,017 | cc | C++ | SimMuon/DTDigitizer/test/DTDigiAnalyzer.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 13 | 2015-11-30T15:49:45.000Z | 2022-02-08T16:11:30.000Z | SimMuon/DTDigitizer/test/DTDigiAnalyzer.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 640 | 2015-02-11T18:55:47.000Z | 2022-03-31T14:12:23.000Z | SimMuon/DTDigitizer/test/DTDigiAnalyzer.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 51 | 2015-08-11T21:01:40.000Z | 2022-03-30T07:31:34.000Z | /** \class DTDigiAnalyzer
* Analyse the the muon-drift-tubes digitizer.
*
* \authors: R. Bellan
*/
#include "DataFormats/MuonDetId/interface/DTLayerId.h"
#include "SimMuon/DTDigitizer/test/DTDigiAnalyzer.h"
#include <DataFormats/DTDigi/interface/DTDigiCollection.h>
#include <FWCore/Framework/interface/Event.h>
// #include "SimMuon/DTDigitizer/test/analysis/DTMCStatistics.h"
// #include "SimMuon/DTDigitizer/test/analysis/DTMuonDigiStatistics.h"
// #include "SimMuon/DTDigitizer/test/analysis/DTHitsAnalysis.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/GeometryVector/interface/LocalPoint.h"
#include "Geometry/DTGeometry/interface/DTGeometry.h"
#include "Geometry/DTGeometry/interface/DTLayer.h"
#include "Geometry/Records/interface/MuonGeometryRecord.h"
#include "DataFormats/MuonDetId/interface/DTLayerId.h"
#include "DataFormats/MuonDetId/interface/DTWireId.h"
#include <iostream>
#include <string>
#include "TFile.h"
#include "SimMuon/DTDigitizer/test/Histograms.h"
using namespace edm;
using namespace std;
DTDigiAnalyzer::DTDigiAnalyzer(const ParameterSet &pset)
: hDigis_global("Global"), hDigis_W0("Wheel0"), hDigis_W1("Wheel1"), hDigis_W2("Wheel2"), hAllHits("AllHits") {
// MCStatistics = new DTMCStatistics();
// MuonDigiStatistics = new DTMuonDigiStatistics();
// HitsAnalysis = new DTHitsAnalysis();
label = pset.getUntrackedParameter<string>("label");
file = new TFile("DTDigiPlots.root", "RECREATE");
file->cd();
DigiTimeBox = new TH1F("DigiTimeBox", "Digi Time Box", 2048, 0, 1600);
if (file->IsOpen())
cout << "file open!" << endl;
else
cout << "*** Error in opening file ***" << endl;
psim_token = consumes<PSimHitContainer>(edm::InputTag("g4SimHits", "MuonDTHits"));
DTd_token = consumes<DTDigiCollection>(edm::InputTag(label));
}
DTDigiAnalyzer::~DTDigiAnalyzer() {}
void DTDigiAnalyzer::endJob() {
// cout<<"Number of analyzed event: "<<nevts<<endl;
// HitsAnalysis->Report();
file->cd();
DigiTimeBox->Write();
hDigis_global.Write();
hDigis_W0.Write();
hDigis_W1.Write();
hDigis_W2.Write();
hAllHits.Write();
file->Close();
// delete file;
// delete DigiTimeBox;
}
void DTDigiAnalyzer::analyze(const Event &event, const EventSetup &eventSetup) {
cout << "--- Run: " << event.id().run() << " Event: " << event.id().event() << endl;
Handle<DTDigiCollection> dtDigis;
event.getByToken(DTd_token, dtDigis);
Handle<PSimHitContainer> simHits;
event.getByToken(psim_token, simHits);
ESHandle<DTGeometry> muonGeom;
eventSetup.get<MuonGeometryRecord>().get(muonGeom);
DTWireIdMap wireMap;
for (vector<PSimHit>::const_iterator hit = simHits->begin(); hit != simHits->end(); hit++) {
// Create the id of the wire, the simHits in the DT known also the wireId
DTWireId wireId(hit->detUnitId());
// Fill the map
wireMap[wireId].push_back(&(*hit));
LocalPoint entryP = hit->entryPoint();
LocalPoint exitP = hit->exitPoint();
int partType = hit->particleType();
float path = (exitP - entryP).mag();
float path_x = fabs((exitP - entryP).x());
hAllHits.Fill(entryP.x(),
exitP.x(),
entryP.y(),
exitP.y(),
entryP.z(),
exitP.z(),
path,
path_x,
partType,
hit->processType(),
hit->pabs());
if (hit->timeOfFlight() > 1e4) {
cout << "PID: " << hit->particleType() << " TOF: " << hit->timeOfFlight() << " Proc Type: " << hit->processType()
<< " p: " << hit->pabs() << endl;
hAllHits.FillTOF(hit->timeOfFlight());
}
}
DTDigiCollection::DigiRangeIterator detUnitIt;
for (detUnitIt = dtDigis->begin(); detUnitIt != dtDigis->end(); ++detUnitIt) {
const DTLayerId &id = (*detUnitIt).first;
const DTDigiCollection::Range &range = (*detUnitIt).second;
// DTLayerId print-out
cout << "--------------" << endl;
cout << "id: " << id;
// Loop over the digis of this DetUnit
for (DTDigiCollection::const_iterator digiIt = range.first; digiIt != range.second; ++digiIt) {
cout << " Wire: " << (*digiIt).wire() << endl << " digi time (ns): " << (*digiIt).time() << endl;
DigiTimeBox->Fill((*digiIt).time());
DTWireId wireId(id, (*digiIt).wire());
int mu = 0;
float theta = 0;
for (vector<const PSimHit *>::iterator hit = wireMap[wireId].begin(); hit != wireMap[wireId].end(); hit++) {
cout << "momentum x: " << (*hit)->momentumAtEntry().x() << endl
<< "momentum z: " << (*hit)->momentumAtEntry().z() << endl;
if (abs((*hit)->particleType()) == 13) {
theta = atan((*hit)->momentumAtEntry().x() / (-(*hit)->momentumAtEntry().z())) * 180 / M_PI;
cout << "atan: " << theta << endl;
mu++;
} else {
// cout<<"PID: "<<(*hit)->particleType()
// <<" TOF: "<<(*hit)->timeOfFlight()
// <<" Proc Type: "<<(*hit)->processType()
// <<" p: " << (*hit)->pabs() <<endl;
}
}
if (mu && theta) {
hDigis_global.Fill((*digiIt).time(), theta, id.superlayer());
// filling digi histos for wheel and for RZ and RPhi
WheelHistos(id.wheel())->Fill((*digiIt).time(), theta, id.superlayer());
}
} // for digis in layer
} // for layers
cout << "--------------" << endl;
}
hDigis *DTDigiAnalyzer::WheelHistos(int wheel) {
switch (abs(wheel)) {
case 0:
return &hDigis_W0;
case 1:
return &hDigis_W1;
case 2:
return &hDigis_W2;
default:
return nullptr;
}
}
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/PluginManager/interface/ModuleDef.h"
DEFINE_FWK_MODULE(DTDigiAnalyzer);
| 32.879781 | 119 | 0.619245 | ckamtsikis |
848317df56ef0f0347b205e49b6e0ac9e30efd4d | 4,861 | cpp | C++ | EjercicioiPud/EjercicioiPud/mainApartadob17-18.cpp | gejors55/Algorithm | 107d6cf4eb8fc7f4d0cebfe9b4e7b2811ac10533 | [
"MIT"
] | null | null | null | EjercicioiPud/EjercicioiPud/mainApartadob17-18.cpp | gejors55/Algorithm | 107d6cf4eb8fc7f4d0cebfe9b4e7b2811ac10533 | [
"MIT"
] | null | null | null | EjercicioiPud/EjercicioiPud/mainApartadob17-18.cpp | gejors55/Algorithm | 107d6cf4eb8fc7f4d0cebfe9b4e7b2811ac10533 | [
"MIT"
] | null | null | null | // Examen junio 2016: Implementacion de un sistema de reproduccion de musica
// APDO B: hay que reducir los costes de deleteSong y play
#include "lista.h"
#include "DiccionarioHash.h"
#include <iostream>
#include <string>
using namespace std;
typedef string Cancion;
typedef string Artista;
class SongInfo {
public:
Artista artist;
int duration;
// APDO B: sustituimos los booleanos por iteradores que apuntan al elemento de las listas
// de reproducción y reproducidas donde están las canciones de las que el correspondiente
// objeto SongInfo es información
//bool inPlaylist;
//bool played;
Lista<Cancion>::Iterator itPlaylist;
Lista<Cancion>::Iterator itPlayed;
// OJO: los constructores de los iteradores son privados
// Definimos el siguiente constructor al que le pasaremos los end() de las listas correspondientes
// cuando creemos un objeto en addSong
SongInfo(const Lista<Cancion>::Iterator& itplaylist, const Lista<Cancion>::Iterator& itplayedlist) :
itPlaylist(itplaylist), itPlayed(itplayedlist) {}
};
// clases excepcion para iPud
class ECancionExistente{};
class ECancionNoExistente{};
// clase iPud
class iPud {
Lista<Cancion> playlist;
Lista<Cancion> played;
int duration;
DiccionarioHash<Cancion,SongInfo> songs;
public:
iPud() : duration(0), playlist(Lista<Cancion>()), played(Lista<Cancion>()), songs(DiccionarioHash<Cancion, SongInfo>()) {}
void addSong(const Cancion& c, const Artista& a, int d);
void addToPlaylist(const Cancion& c);
Cancion current();
void play();
void deleteSong(const Cancion& c);
int totalTime();
Cancion recent();
};
// creación de la información de la canción
// APDO. B: Los iteradores de momento no tienen que apuntar a nada porque lo único
// que estamos haciendo es meter la canción en la colección de canciones existentes
void iPud::addSong(const Cancion& c, const Artista& a, int d){
if (songs.contiene(c)) throw ECancionExistente();
SongInfo i(playlist.end(), played.end());
i.artist = a;
i.duration = d;
// inclusión en el diccionario
songs.inserta(c,i);
}
void iPud::addToPlaylist(const Cancion& c){
if (!songs.contiene(c))throw ECancionNoExistente();
Lista<Cancion>::Iterator it = playlist.end();
if (songs.valorPara(c).itPlaylist == it){
playlist.pon_ppio(c);
Lista<Cancion>::Iterator ite = playlist.begin();
songs.busca(c).valor().itPlaylist = ite;
duration += songs.valorPara(c).duration;
}
}
Cancion iPud::current(){
if (playlist.esVacia()){
cout << "LISTA DE REPRODUCCION VACIA" << endl;
}
else{
return playlist.ultimo();
}
}
void iPud::play(){
if (!playlist.esVacia()){
played.pon_ppio(playlist.ultimo()); //meto en played la cancion
Lista<Cancion>::Iterator it = played.begin();
songs.busca(played.ultimo()).valor().itPlayed = it;// meto el iterador de conde esta en played
duration -= songs.valorPara(playlist.ultimo()).duration;//cambio la duracion
playlist.eliminar(songs.valorPara(playlist.ultimo()).itPlaylist);//borro la cancion de playlist
}
}
void iPud::deleteSong(const Cancion& c){
if (songs.contiene(c)){
Lista<Cancion>::Iterator it = playlist.end();
Lista<Cancion>::Iterator ite = played.end();
if (songs.valorPara(c).itPlaylist != it){
playlist.eliminar(songs.valorPara(c).itPlaylist);
}
if (songs.valorPara(c).itPlayed != ite){
played.eliminar(songs.valorPara(c).itPlayed);
}
songs.borra(c);
}
}
int iPud::totalTime(){
if (!playlist.esVacia()){
return duration;
}
else
return 0;
}
Cancion iPud::recent(){
if (played.esVacia()){
cout << "LISTA DE REPRODUCCION VACIA" << endl;
}
else{
return played.ultimo();
}
}
/////MAIN
void añade(iPud& ip) {
Cancion c;
Artista a;
int d;
cin >> c >> a >> d;
try {
ip.addSong(c, a, d);
cout << "OK" << endl;
}
catch (ECancionExistente) {
cout << "CANCION_EXISTENTE" << endl;
}
}
void añadelista(iPud& ip) {
try {
Cancion c;
cin >> c;
ip.addToPlaylist(c);
cout << "OK" << endl;
}
catch (ECancionNoExistente) {
cout << "CANCION_NO_EXISTENTE" << endl;
}
}
void borra(iPud& ip) {
Cancion c;
cin >> c;
ip.deleteSong(c);
cout << "OK" << endl;
}
void playe(iPud& ip){
ip.play();
}
void current(iPud& ip) {
Cancion c;
c =ip.current();
cout << c << endl;
}
void tiemposs(iPud& ip){
int tiempo;
tiempo = ip.totalTime();
cout << "tiempo total " << tiempo << endl;
}
void rec(iPud& ip){
Cancion c;
c = ip.recent();
cout << c << endl;
}
int main() {
iPud ip;
string comando;
while (cin >> comando) {
if (comando == "anade") añade(ip);
else if (comando == "lista") añadelista(ip);
else if (comando == "play") playe(ip);
else if (comando == "actu") current(ip);
else if (comando == "borra") borra(ip);
else if (comando == "tiempo") tiemposs(ip);
else if (comando == "recent") rec(ip);
}
return 0;
} | 26.708791 | 123 | 0.67517 | gejors55 |
848511b8fca7ca5773692746797029eb92023728 | 19,813 | cpp | C++ | ortc/services/cpp/services_STUNRequester.cpp | ortclib/ortclib-services-cpp | f770d97044b1ffbff04b61fa1488eedc8ddc66e4 | [
"BSD-2-Clause"
] | 2 | 2016-10-12T09:16:32.000Z | 2016-10-13T03:49:47.000Z | ortc/services/cpp/services_STUNRequester.cpp | ortclib/ortclib-services-cpp | f770d97044b1ffbff04b61fa1488eedc8ddc66e4 | [
"BSD-2-Clause"
] | 2 | 2017-11-24T09:18:45.000Z | 2017-11-24T09:20:53.000Z | ortc/services/cpp/services_STUNRequester.cpp | ortclib/ortclib-services-cpp | f770d97044b1ffbff04b61fa1488eedc8ddc66e4 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2014, Hookflash 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:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
#include <ortc/services/internal/services_STUNRequester.h>
#include <ortc/services/internal/services_STUNRequesterManager.h>
#include <ortc/services/internal/services.events.h>
#include <ortc/services/IBackOffTimerPattern.h>
#include <ortc/services/IHelper.h>
#include <zsLib/Exception.h>
#include <zsLib/helpers.h>
#include <zsLib/Log.h>
#include <zsLib/XML.h>
#include <zsLib/Stringize.h>
#define ORTC_SERVICES_STUN_REQUESTER_DEFAULT_BACKOFF_TIMER_MAX_ATTEMPTS (6)
namespace ortc { namespace services { ZS_DECLARE_SUBSYSTEM(ortc_services_stun) } }
namespace ortc
{
namespace services
{
namespace internal
{
ZS_DECLARE_TYPEDEF_PTR(ISTUNRequesterManagerForSTUNRequester, UseSTUNRequesterManager)
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark STUNRequester
#pragma mark
//-----------------------------------------------------------------------
STUNRequester::STUNRequester(
const make_private &,
IMessageQueuePtr queue,
ISTUNRequesterDelegatePtr delegate,
IPAddress serverIP,
STUNPacketPtr stun,
STUNPacket::RFCs usingRFC,
IBackOffTimerPatternPtr pattern
) :
MessageQueueAssociator(queue),
mDelegate(ISTUNRequesterDelegateProxy::createWeak(queue, delegate)),
mSTUNRequest(stun),
mServerIP(serverIP),
mUsingRFC(usingRFC),
mBackOffTimerPattern(pattern)
{
if (!mBackOffTimerPattern) {
mBackOffTimerPattern = IBackOffTimerPattern::create();
mBackOffTimerPattern->setMaxAttempts(ORTC_SERVICES_STUN_REQUESTER_DEFAULT_BACKOFF_TIMER_MAX_ATTEMPTS);
mBackOffTimerPattern->addNextAttemptTimeout(Milliseconds(500));
mBackOffTimerPattern->setMultiplierForLastAttemptTimeout(2.0);
mBackOffTimerPattern->addNextRetryAfterFailureDuration(Milliseconds(1));
}
//ServicesStunRequesterCreate(__func__, mID, serverIP.string(), zsLib::to_underlying(usingRFC), mBackOffTimerPattern->getID());
ZS_EVENTING_4(
x, i, Debug, ServicesStunRequesterCreate, os, StunRequester, Start,
puid, id, mID,
string, serverIp, serverIP.string(),
enum, usingRfc, zsLib::to_underlying(usingRFC),
puid, backoffTimerPatterId, mBackOffTimerPattern->getID()
);
}
//-----------------------------------------------------------------------
STUNRequester::~STUNRequester()
{
if(isNoop()) return;
mThisWeak.reset();
cancel();
//ServicesStunRequesterDestroy(__func__, mID);
ZS_EVENTING_1(x, i, Debug, ServicesStunRequesterDestroy, os, StunRequester, Start, puid, id, mID);
}
//-----------------------------------------------------------------------
void STUNRequester::init()
{
AutoRecursiveLock lock(mLock);
UseSTUNRequesterManagerPtr manager = UseSTUNRequesterManager::singleton();
if (manager) {
manager->monitorStart(mThisWeak.lock(), mSTUNRequest);
}
step();
}
//-----------------------------------------------------------------------
STUNRequesterPtr STUNRequester::convert(ISTUNRequesterPtr object)
{
return ZS_DYNAMIC_PTR_CAST(STUNRequester, object);
}
//-----------------------------------------------------------------------
STUNRequesterPtr STUNRequester::convert(ForSTUNRequesterManagerPtr object)
{
return ZS_DYNAMIC_PTR_CAST(STUNRequester, object);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark STUNRequester => STUNRequester
#pragma mark
//-----------------------------------------------------------------------
STUNRequesterPtr STUNRequester::create(
IMessageQueuePtr queue,
ISTUNRequesterDelegatePtr delegate,
IPAddress serverIP,
STUNPacketPtr stun,
STUNPacket::RFCs usingRFC,
IBackOffTimerPatternPtr pattern
)
{
ZS_THROW_INVALID_USAGE_IF(!delegate)
ZS_THROW_INVALID_USAGE_IF(!stun)
ZS_THROW_INVALID_USAGE_IF(serverIP.isAddressEmpty())
ZS_THROW_INVALID_USAGE_IF(serverIP.isPortEmpty())
STUNRequesterPtr pThis(make_shared<STUNRequester>(make_private{}, queue, delegate, serverIP, stun, usingRFC, pattern));
pThis->mThisWeak = pThis;
pThis->init();
return pThis;
}
//-----------------------------------------------------------------------
bool STUNRequester::isComplete() const
{
AutoRecursiveLock lock(mLock);
if (!mDelegate) return true;
return false;
}
//-----------------------------------------------------------------------
void STUNRequester::cancel()
{
//ServicesStunRequesterCancel(__func__, mID);
ZS_EVENTING_1(x, i, Debug, ServicesStunRequesterCancel, os, StunRequester, Cancel, puid, id, mID);
AutoRecursiveLock lock(mLock);
ZS_LOG_TRACE(log("cancel called") + mSTUNRequest->toDebug())
mServerIP.clear();
if (mDelegate) {
mDelegate.reset();
// tie the lifetime of the monitoring to the delegate
UseSTUNRequesterManagerPtr manager = UseSTUNRequesterManager::singleton();
if (manager) {
manager->monitorStop(*this);
}
}
}
//-----------------------------------------------------------------------
void STUNRequester::retryRequestNow()
{
//ServicesStunRequesterRetryNow(__func__, mID);
ZS_EVENTING_1(x, i, Trace, ServicesStunRequesterRetryNow, os, StunRequester, RetryNow, puid, id, mID);
AutoRecursiveLock lock(mLock);
ZS_LOG_DEBUG(log("retry request now") + mSTUNRequest->toDebug())
if (mBackOffTimer) {
mBackOffTimer->cancel();
mBackOffTimer.reset();
}
step();
}
//-----------------------------------------------------------------------
IPAddress STUNRequester::getServerIP() const
{
AutoRecursiveLock lock(mLock);
return mServerIP;
}
//-----------------------------------------------------------------------
STUNPacketPtr STUNRequester::getRequest() const
{
AutoRecursiveLock lock(mLock);
return mSTUNRequest;
}
//-----------------------------------------------------------------------
IBackOffTimerPatternPtr STUNRequester::getBackOffTimerPattern() const
{
AutoRecursiveLock lock(mLock);
return mBackOffTimerPattern;
}
//-----------------------------------------------------------------------
size_t STUNRequester::getTotalTries() const
{
AutoRecursiveLock lock(mLock);
return mTotalTries;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark STUNRequester => ISTUNRequesterForSTUNRequesterManager
#pragma mark
//-----------------------------------------------------------------------
bool STUNRequester::handleSTUNPacket(
IPAddress fromIPAddress,
STUNPacketPtr packet
)
{
//ServicesStunRequesterReceivedStunPacket(__func__, mID, fromIPAddress.string());
ZS_EVENTING_2(x, i, Debug, ServicesStunRequesterReceivedStunPacket, os, StunRequester, Receive, puid, id, mID, string, fromIpAddress, fromIPAddress.string());
packet->trace(__func__);
ISTUNRequesterDelegatePtr delegate;
// find out if this was truly handled
{
AutoRecursiveLock lock(mLock);
if (!mSTUNRequest) return false;
if (!packet->isValidResponseTo(mSTUNRequest, mUsingRFC)) {
ZS_LOG_TRACE(log("determined this response is not a proper validated response") + packet->toDebug())
return false;
}
delegate = mDelegate;
}
bool success = true;
// we now have a reply, inform the delegate...
// NOTE: We inform the delegate syncrhonously thus we cannot call
// the delegate from inside a lock in case the delegate is
// calling us (that would cause a potential deadlock).
if (delegate) {
try {
success = delegate->handleSTUNRequesterResponse(mThisWeak.lock(), fromIPAddress, packet); // this is a success! yay! inform the delegate
} catch(ISTUNRequesterDelegateProxy::Exceptions::DelegateGone &) {
}
}
if (!success)
return false;
// clear out the request since it's now complete
{
AutoRecursiveLock lock(mLock);
if (ZS_IS_LOGGING(Trace)) {
ZS_LOG_BASIC(log("handled") + ZS_PARAM("ip", mServerIP.string()) + ZS_PARAM("request", mSTUNRequest->toDebug()) + ZS_PARAM("response", packet->toDebug()))
}
cancel();
}
return true;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark STUNRequester => ITimerDelegate
#pragma mark
//-----------------------------------------------------------------------
void STUNRequester::onBackOffTimerStateChanged(
IBackOffTimerPtr timer,
IBackOffTimer::States state
)
{
//ServicesStunRequesterBackOffTimerStateEvent(__func__, mID, timer->getID(), IBackOffTimer::toString(state), mTotalTries);
ZS_EVENTING_4(
x, i, Trace, ServicesStunRequesterBackOffTimerStateEvent, os, StunRequester, InternalEvent,
puid, id, mID,
puid, timerId, timer->getID(),
string, backoffTimerState, IBackOffTimer::toString(state),
ulong, totalTries, mTotalTries
);
AutoRecursiveLock lock(mLock);
ZS_LOG_TRACE(log("backoff timer state changed") + ZS_PARAM("timer id", timer->getID()) + ZS_PARAM("state", IBackOffTimer::toString(state)) + ZS_PARAM("total tries", mTotalTries))
step();
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark STUNRequester => (internal)
#pragma mark
//-----------------------------------------------------------------------
Log::Params STUNRequester::log(const char *message) const
{
ElementPtr objectEl = Element::create("STUNRequester");
IHelper::debugAppend(objectEl, "id", mID);
return Log::Params(message, objectEl);
}
//-----------------------------------------------------------------------
void STUNRequester::step()
{
if (!mDelegate) return; // if there is no delegate then the request has completed or is cancelled
if (mServerIP.isAddressEmpty()) return;
if (!mBackOffTimer) {
mBackOffTimer = IBackOffTimer::create(mBackOffTimerPattern, mThisWeak.lock());
}
if (mBackOffTimer->haveAllAttemptsFailed()) {
try {
mDelegate->onSTUNRequesterTimedOut(mThisWeak.lock());
} catch(ISTUNRequesterDelegateProxy::Exceptions::DelegateGone &) {
ZS_LOG_WARNING(Debug, log("delegate gone"))
}
cancel();
return;
}
if (mBackOffTimer->shouldAttemptNow()) {
mBackOffTimer->notifyAttempting();
ZS_LOG_TRACE(log("sending packet now") + ZS_PARAM("ip", mServerIP.string()) + ZS_PARAM("tries", mTotalTries) + ZS_PARAM("stun packet", mSTUNRequest->toDebug()))
// send off the packet NOW
SecureByteBlockPtr packet = mSTUNRequest->packetize(mUsingRFC);
//ServicesStunRequesterSendPacket(__func__, mID, packet->SizeInBytes(), packet->BytePtr());
ZS_EVENTING_3(
x, i, Trace, ServicesStunRequesterSendPacket, os, StunRequester, Send,
puid, id, mID,
binary, packet, packet->BytePtr(),
size, size, packet->SizeInBytes()
);
mSTUNRequest->trace(__func__);
try {
++mTotalTries;
mDelegate->onSTUNRequesterSendPacket(mThisWeak.lock(), mServerIP, packet);
} catch(ISTUNRequesterDelegateProxy::Exceptions::DelegateGone &) {
ZS_LOG_WARNING(Trace, log("delegate gone thus cancelling requester"))
cancel();
return;
}
}
// nothing more to do... sit back, relax and enjoy the ride!
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#pragma mark
#pragma mark ISTUNRequesterFactory
#pragma mark
//-----------------------------------------------------------------------
ISTUNRequesterFactory &ISTUNRequesterFactory::singleton()
{
return STUNRequesterFactory::singleton();
}
//-----------------------------------------------------------------------
STUNRequesterPtr ISTUNRequesterFactory::create(
IMessageQueuePtr queue,
ISTUNRequesterDelegatePtr delegate,
IPAddress serverIP,
STUNPacketPtr stun,
STUNPacket::RFCs usingRFC,
IBackOffTimerPatternPtr pattern
)
{
if (this) {}
return STUNRequester::create(queue, delegate, serverIP, stun, usingRFC, pattern);
}
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
#pragma mark
#pragma mark ISTUNRequester
#pragma mark
//-------------------------------------------------------------------------
ISTUNRequesterPtr ISTUNRequester::create(
IMessageQueuePtr queue,
ISTUNRequesterDelegatePtr delegate,
IPAddress serverIP,
STUNPacketPtr stun,
STUNPacket::RFCs usingRFC,
IBackOffTimerPatternPtr pattern
)
{
return internal::ISTUNRequesterFactory::singleton().create(queue, delegate, serverIP, stun, usingRFC, pattern);
}
//-------------------------------------------------------------------------
bool ISTUNRequester::handlePacket(
IPAddress fromIPAddress,
const BYTE *packet,
size_t packetLengthInBytes,
const STUNPacket::ParseOptions &options
)
{
return (bool)ISTUNRequesterManager::handlePacket(fromIPAddress, packet, packetLengthInBytes, options);
}
//-------------------------------------------------------------------------
bool ISTUNRequester::handleSTUNPacket(
IPAddress fromIPAddress,
STUNPacketPtr stun
)
{
return (bool)ISTUNRequesterManager::handleSTUNPacket(fromIPAddress, stun);
}
}
}
| 41.976695 | 186 | 0.465704 | ortclib |
84883167c136c85e9d284932f1e8e047fa5e8c5e | 190 | cpp | C++ | Cpp_Programs/races/luogu201809/U38228.cpp | xiazeyu/OI_Resource | 1de0ab9a84ee22ae4edb612ddeddc712c3c38e56 | [
"Apache-2.0"
] | 2 | 2018-10-01T09:03:35.000Z | 2019-05-24T08:53:06.000Z | Cpp_Programs/races/luogu201809/U38228.cpp | xiazeyu/OI_Resource | 1de0ab9a84ee22ae4edb612ddeddc712c3c38e56 | [
"Apache-2.0"
] | null | null | null | Cpp_Programs/races/luogu201809/U38228.cpp | xiazeyu/OI_Resource | 1de0ab9a84ee22ae4edb612ddeddc712c3c38e56 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
long long t = 1, n = 1, m, k;
int main(){
cin>>k>>m;
while(t % m != k){
n++;
t *= 10; t++;
}
cout<<n<<endl;
return 0;
}
| 10 | 29 | 0.463158 | xiazeyu |
848966765ddc582ef5ea38f66ad504d258158e2a | 5,180 | cc | C++ | src/mpasjedi/TlmMPAS.cc | JCSDA/mpas-jedi | e0780d1fd295912ee4cfb758854c52b6764d4ab9 | [
"Apache-2.0"
] | 2 | 2021-09-25T01:20:10.000Z | 2021-12-17T18:44:53.000Z | src/mpasjedi/TlmMPAS.cc | JCSDA/mpas-jedi | e0780d1fd295912ee4cfb758854c52b6764d4ab9 | [
"Apache-2.0"
] | null | null | null | src/mpasjedi/TlmMPAS.cc | JCSDA/mpas-jedi | e0780d1fd295912ee4cfb758854c52b6764d4ab9 | [
"Apache-2.0"
] | null | null | null | /*
* (C) Copyright 2017 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "eckit/config/LocalConfiguration.h"
#include "oops/util/abor1_cpp.h"
#include "oops/util/DateTime.h"
#include "oops/util/Logger.h"
#include "mpasjedi/GeometryMPAS.h"
#include "mpasjedi/IncrementMPAS.h"
#include "mpasjedi/StateMPAS.h"
#include "mpasjedi/TlmMPAS.h"
namespace mpas {
// -----------------------------------------------------------------------------
static oops::interface::LinearModelMaker<MPASTraits, TlmMPAS> makerMPASTLM_("MPASTLM");
// -----------------------------------------------------------------------------
TlmMPAS::TlmMPAS(const GeometryMPAS & resol,
const eckit::Configuration & tlConf)
: keyConfig_(0), tstep_(), resol_(resol), traj_(),
lrmodel_(resol_, eckit::LocalConfiguration(tlConf, "trajectory")),
linvars_(tlConf, "tlm variables")
{
tstep_ = util::Duration(tlConf.getString("tstep"));
mpas_model_setup_f90(tlConf, resol_.toFortran(), keyConfig_);
oops::Log::trace() << "TlmMPAS created" << std::endl;
}
// -----------------------------------------------------------------------------
TlmMPAS::~TlmMPAS() {
mpas_model_delete_f90(keyConfig_);
for (trajIter jtra = traj_.begin(); jtra != traj_.end(); ++jtra) {
mpas_model_wipe_traj_f90(jtra->second);
}
oops::Log::trace() << "TlmMPAS destructed" << std::endl;
}
// -----------------------------------------------------------------------------
void TlmMPAS::setTrajectory(const StateMPAS & xx, StateMPAS & xlr,
const ModelBiasMPAS & bias) {
// StateMPAS xlr(resol_, xx);
xlr.changeResolution(xx);
int ftraj = lrmodel_.saveTrajectory(xlr, bias);
traj_[xx.validTime()] = ftraj;
// should be in print method
std::vector<double> zstat(15);
// mpas_traj_minmaxrms_f90(ftraj, zstat[0]);
oops::Log::debug() << "TlmMPAS trajectory at time " << xx.validTime()
<< std::endl;
for (unsigned int jj = 0; jj < 5; ++jj) {
oops::Log::debug() << " Min=" << zstat[3*jj] << ", Max=" << zstat[3*jj+1]
<< ", RMS=" << zstat[3*jj+2] << std::endl;
}
// should be in print method
}
// -----------------------------------------------------------------------------
void TlmMPAS::initializeTL(IncrementMPAS & dx) const {
mpas_model_prepare_integration_tl_f90(keyConfig_, dx.toFortran());
oops::Log::debug() << "TlmMPAS::initializeTL" << dx << std::endl;
}
// -----------------------------------------------------------------------------
void TlmMPAS::stepTL(IncrementMPAS & dx, const ModelBiasIncrementMPAS &) const {
trajICst itra = traj_.find(dx.validTime());
if (itra == traj_.end()) {
oops::Log::error() << "TlmMPAS: trajectory not available at time "
<< dx.validTime() << std::endl;
ABORT("TlmMPAS: trajectory not available");
}
oops::Log::debug() << "TlmMPAS::stepTL increment in" << dx << std::endl;
mpas_model_propagate_tl_f90(keyConfig_, dx.toFortran(),
itra->second);
oops::Log::debug() << "TlmMPAS::stepTL increment out"<< dx << std::endl;
dx.validTime() += tstep_;
}
// -----------------------------------------------------------------------------
void TlmMPAS::finalizeTL(IncrementMPAS & dx) const {
oops::Log::debug() << "TlmMPAS::finalizeTL" << dx << std::endl;
}
// -----------------------------------------------------------------------------
void TlmMPAS::initializeAD(IncrementMPAS & dx) const {
oops::Log::debug() << "TlmMPAS::initializeAD" << dx << std::endl;
}
// -----------------------------------------------------------------------------
void TlmMPAS::stepAD(IncrementMPAS & dx, ModelBiasIncrementMPAS &) const {
dx.validTime() -= tstep_;
trajICst itra = traj_.find(dx.validTime());
if (itra == traj_.end()) {
oops::Log::error() << "TlmMPAS: trajectory not available at time "
<< dx.validTime() << std::endl;
ABORT("TlmMPAS: trajectory not available");
}
oops::Log::debug() << "TlmMPAS::stepAD increment in" << dx << std::endl;
mpas_model_propagate_ad_f90(keyConfig_, dx.toFortran(),
itra->second);
oops::Log::debug() << "TlmMPAS::stepAD increment out" << dx << std::endl;
}
// -----------------------------------------------------------------------------
void TlmMPAS::finalizeAD(IncrementMPAS & dx) const {
mpas_model_prepare_integration_ad_f90(keyConfig_, dx.toFortran());
oops::Log::debug() << "TlmMPAS::finalizeAD" << dx << std::endl;
}
// -----------------------------------------------------------------------------
void TlmMPAS::print(std::ostream & os) const {
os << "MPAS TLM Trajectory, nstep=" << traj_.size() << std::endl;
typedef std::map< util::DateTime, int >::const_iterator trajICst;
if (traj_.size() > 0) {
os << "MPAS TLM Trajectory: times are:";
for (trajICst jtra = traj_.begin(); jtra != traj_.end(); ++jtra) {
os << " " << jtra->first;
}
}
}
// -----------------------------------------------------------------------------
} // namespace mpas
| 42.113821 | 87 | 0.520849 | JCSDA |
848aa9de0221912244032a4c0cda93accbe765f6 | 4,637 | cpp | C++ | src/winrt/projection_lib/MoObservableObjectClassAdapter.cpp | Bhaskers-Blu-Org2/pmod | 92e3c0ecff25763dcfabab0c1fb86d58e60cbb1a | [
"MIT"
] | 19 | 2019-06-16T02:29:24.000Z | 2022-03-01T23:20:25.000Z | src/winrt/projection_lib/MoObservableObjectClassAdapter.cpp | microsoft/pmod | 92e3c0ecff25763dcfabab0c1fb86d58e60cbb1a | [
"MIT"
] | null | null | null | src/winrt/projection_lib/MoObservableObjectClassAdapter.cpp | microsoft/pmod | 92e3c0ecff25763dcfabab0c1fb86d58e60cbb1a | [
"MIT"
] | 5 | 2019-11-03T11:40:25.000Z | 2020-08-05T14:56:13.000Z | /***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* File:MoObservableObjectClassAdapter.cpp
****/
#include "pch.h"
#include "MoObservableObjectClassAdapter.h"
#include "MoObservableObjectFactory.h"
// This class adapts from code delegate callbkack to the winrt version of it to allow overriding from winrt code.
class CInvokeDelegate :
public foundation::ctl::Implements <pmod::library::IMethodOnInvokeDelegate, &pmod::library::IID_IMethodOnInvokeDelegate >
{
public:
HRESULT _Initialize(ABI::Microsoft::PropertyModel::Library::IInvokeDelegate *pInvokeMethodDelegate)
{
_spMoOnInvokeMethodDelegate = pInvokeMethodDelegate;
return S_OK;
}
static HRESULT GetModernDelegateFromCore(pmod::library::IMethodOnInvokeDelegate *pDelegate,
ABI::Microsoft::PropertyModel::Library::IInvokeDelegate **ppModernDelegate)
{
foundation_assert(ppModernDelegate);
if (pDelegate)
{
CInvokeDelegate * pInternalDelegate = static_cast<CInvokeDelegate *>(pDelegate);
pInternalDelegate->_spMoOnInvokeMethodDelegate.CopyTo(ppModernDelegate);
}
else
{
*ppModernDelegate = nullptr;
}
return S_OK;
}
protected:
STDMETHOD(Invoke) (
_In_ foundation::IMethodInfo *pMethodInfo,
_In_ UINT32 methodId,
_In_ UINT32 size,
_In_ foundation::IInspectable **parameters,
_Outptr_ foundation::IInspectable **ppValue)
{
bool isAsync;
pMethodInfo->GetIsAsync(&isAsync);
if (isAsync)
{
// winRT is not able to see the IAsyncOperation we are passing
std::vector<IInspectable *> parameters_;
IFR_ASSERT(CMoObservableObjectDelegateAdapter::CreateAsyncParameters(size, parameters, *ppValue, parameters_));
foundation::InspectablePtr ignore_result_ptr;
return _spMoOnInvokeMethodDelegate->Invoke(
methodId,
size + 1,
(IInspectable **)¶meters_.front(),
ignore_result_ptr.GetAddressOf());
}
else
{
return _spMoOnInvokeMethodDelegate->Invoke(methodId, size, parameters, ppValue);
}
}
private:
foundation::ComPtr<ABI::Microsoft::PropertyModel::Library::IInvokeDelegate> _spMoOnInvokeMethodDelegate;
};
HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::put_InvokeDelegate(ABI::Microsoft::PropertyModel::Library::IInvokeDelegate* value)
{
foundation::ComPtr<pmod::library::IMethodOnInvokeDelegate> spOnInvokeMethodDelegate;
if (value != nullptr)
{
IFR_ASSERT(foundation::ctl::CreateInstanceWithInitialize<CInvokeDelegate>(spOnInvokeMethodDelegate.GetAddressOf(), value));
}
return m_pInner->SetMethodOnInvokeDelegate(spOnInvokeMethodDelegate);
}
HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::get_InvokeDelegate(ABI::Microsoft::PropertyModel::Library::IInvokeDelegate** value)
{
foundation::ComPtr<pmod::library::IMethodOnInvokeDelegate> spOnInvokeMethodDelegate;
IFR_ASSERT(m_pInner->GetMethodOnInvokeDelegate(spOnInvokeMethodDelegate.GetAddressOf()));
return CInvokeDelegate::GetModernDelegateFromCore(spOnInvokeMethodDelegate, value);
}
HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::SetPropertyInternal(unsigned int propertyId, IInspectable *value)
{
return m_pInner->SetPropertyInternal(propertyId, value, true);
}
HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::FirePropertyChanged(unsigned int propertyId, boolean useCallback)
{
return m_pInner->FirePropertyChanged(propertyId, useCallback ? true : false);
}
HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::FireEventModel(unsigned int eventId, IInspectable *eventArgs)
{
return m_pInner->FireEventModel(eventId, eventArgs);
}
HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::SetBinding(
unsigned int propertyId,
IBindingBase *propertyBinding) {
IFCPTR(propertyBinding);
foundation::ComPtr<pmod::IBindingBase> spPropertyBinding;
IFR(foundation::QueryInterface(propertyBinding, spPropertyBinding.GetAddressOf()));
return m_pInner->SetBinding(propertyId, spPropertyBinding);
}
HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::ClearBinding(
unsigned int propertyId)
{
return m_pInner->ClearBinding(propertyId);
}
| 37.395161 | 143 | 0.717274 | Bhaskers-Blu-Org2 |
848d3ca446afec18d09b4df45250d87f812141c1 | 10,758 | hpp | C++ | Systems/Engine/ComponentHierarchy.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 52 | 2018-09-11T17:18:35.000Z | 2022-03-13T15:28:21.000Z | Systems/Engine/ComponentHierarchy.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 1,409 | 2018-09-19T18:03:43.000Z | 2021-06-09T08:33:33.000Z | Systems/Engine/ComponentHierarchy.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 26 | 2018-09-11T17:16:32.000Z | 2021-11-22T06:21:19.000Z | ///////////////////////////////////////////////////////////////////////////////
///
/// \file ComponentHierarchy.cpp
///
/// Authors: Joshua Claeys
/// Copyright 2015, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Zero
{
//----------------------------------------------------- Component Hierarchy Base
/// Needed for an intrusive link
template <typename ComponentType>
class ComponentHierarchyBase : public Component
{
public:
IntrusiveLink(ComponentHierarchyBase<ComponentType>, HierarchyLink);
};
//---------------------------------------------------------- Component Hierarchy
/// Maintains a hierarchy of specific Components. When a hierarchy of Components
/// is required, this removes the need to manually manage the hierarchy, and
/// also removes the overhead of component lookups while iterating over the
/// hierarchy.
template <typename ComponentType>
class ComponentHierarchy : public ComponentHierarchyBase<ComponentType>
{
public:
ZilchDeclareType(TypeCopyMode::ReferenceType);
// Typedefs.
typedef ComponentHierarchy<ComponentType> self_type;
typedef ComponentHierarchyBase<ComponentType> BaseType;
typedef BaseInList<BaseType, ComponentType, &BaseType::HierarchyLink> ChildList;
typename typedef ChildList::range ChildListRange;
typename typedef ChildList::reverse_range ChildListReverseRange;
/// Constructor.
ComponentHierarchy();
~ComponentHierarchy();
/// Component Interface.
void Initialize(CogInitializer& initializer) override;
void AttachTo(AttachmentInfo& info) override;
void Detached(AttachmentInfo& info) override;
/// When a child is attached or detached, we need to update our child list.
void OnChildAttached(HierarchyEvent* e);
void OnChildDetached(HierarchyEvent* e);
void OnChildrenOrderChanged(Event* e);
/// Tree traversal helpers.
ComponentType* GetPreviousSibling();
ComponentType* GetNextSibling();
ComponentType* GetLastDirectChild();
ComponentType* GetLastDeepestChild();
ComponentType* GetNextInHierarchyOrder();
ComponentType* GetPreviousInHierarchyOrder();
ComponentType* GetRoot();
/// Returns whether or not we are a descendant of the given Cog.
bool IsDescendantOf(ComponentType& ancestor);
/// Returns whether or not we are an ancestor of the given Cog.
bool IsAncestorOf(ComponentType& descendant);
typename ChildListRange GetChildren(){return mChildren.All();}
typename ChildListReverseRange GetChildrenReverse() { return mChildren.ReverseAll(); }
/// Returns the amount of children. Note that this function has to iterate over
/// all children to calculate the count.
uint GetChildCount();
ComponentType* mParent;
ChildList mChildren;
};
//******************************************************************************
template <typename ComponentType>
ZilchDefineType(ComponentHierarchy<ComponentType>, builder, type)
{
ZeroBindDocumented();
ZilchBindGetter(PreviousSibling);
ZilchBindGetter(NextSibling);
ZilchBindGetter(LastDirectChild);
ZilchBindGetter(LastDeepestChild);
ZilchBindGetter(NextInHierarchyOrder);
ZilchBindGetter(PreviousInHierarchyOrder);
ZilchBindFieldGetter(mParent);
ZilchBindGetter(Root);
ZilchBindGetter(ChildCount);
ZilchBindMethod(GetChildren);
ZilchBindMethod(IsDescendantOf);
ZilchBindMethod(IsAncestorOf);
}
//******************************************************************************
template <typename ComponentType>
ComponentHierarchy<ComponentType>::ComponentHierarchy()
: mParent(nullptr)
{
}
//******************************************************************************
template <typename ComponentType>
ComponentHierarchy<ComponentType>::~ComponentHierarchy()
{
forRange(ComponentType& child, GetChildren())
child.mParent = nullptr;
if (mParent)
mParent->mChildren.Erase(this);
mChildren.Clear();
}
//******************************************************************************
template <typename ComponentType>
void ComponentHierarchy<ComponentType>::Initialize(CogInitializer& initializer)
{
// Add ourself to our parent
if(Cog* parent = GetOwner()->GetParent())
{
if(ComponentType* component = parent->has(ComponentType))
{
mParent = component;
mParent->mChildren.PushBack(this);
}
}
// If we were dynamically added, we need to add all of our children. If we
// aren't dynamically added, our children will add themselves to our child list
// in their initialize
if (initializer.Flags & CreationFlags::DynamicallyAdded)
{
forRange(Cog& childCog, GetOwner()->GetChildren())
{
if (ComponentType* child = childCog.has(ComponentType))
{
child->mParent = (ComponentType*)this;
mChildren.PushBack(child);
}
}
}
ConnectThisTo(GetOwner(), Events::ChildAttached, OnChildAttached);
ConnectThisTo(GetOwner(), Events::ChildDetached, OnChildDetached);
ConnectThisTo(GetOwner(), Events::ChildrenOrderChanged, OnChildrenOrderChanged);
}
//******************************************************************************
template <typename ComponentType>
void ComponentHierarchy<ComponentType>::OnChildAttached(HierarchyEvent* e)
{
if(e->Parent != GetOwner())
return;
if(ComponentType* component = e->Child->has(ComponentType))
mChildren.PushBack(component);
}
//******************************************************************************
template <typename ComponentType>
void ComponentHierarchy<ComponentType>::OnChildDetached(HierarchyEvent* e)
{
if(e->Parent != GetOwner())
return;
if(ComponentType* component = e->Child->has(ComponentType))
mChildren.Erase(component);
}
//******************************************************************************
template <typename ComponentType>
void ComponentHierarchy<ComponentType>::OnChildrenOrderChanged(Event* e)
{
// The event isn't currently sent information as to which object moved
// where, so we're just going to re-build the child list
mChildren.Clear();
forRange(Cog& child, GetOwner()->GetChildren())
{
if(ComponentType* childComponent = child.has(ComponentType))
mChildren.PushBack(childComponent);
}
}
//******************************************************************************
template <typename ComponentType>
void ComponentHierarchy<ComponentType>::AttachTo(AttachmentInfo& info)
{
if(info.Child == GetOwner())
mParent = info.Parent->has(ComponentType);
}
//******************************************************************************
template <typename ComponentType>
void ComponentHierarchy<ComponentType>::Detached(AttachmentInfo& info)
{
if(info.Child == GetOwner())
mParent = nullptr;
}
//******************************************************************************
template <typename ComponentType>
ComponentType* ComponentHierarchy<ComponentType>::GetPreviousSibling()
{
ComponentType* prev = (ComponentType*)ChildList::Prev(this);
if(mParent && prev != mParent->mChildren.End())
return prev;
return nullptr;
}
//******************************************************************************
template <typename ComponentType>
ComponentType* ComponentHierarchy<ComponentType>::GetNextSibling()
{
ComponentType* next = (ComponentType*)ChildList::Next(this);
if(mParent && next != mParent->mChildren.End())
return next;
return nullptr;
}
//******************************************************************************
template <typename ComponentType>
ComponentType* ComponentHierarchy<ComponentType>::GetLastDirectChild()
{
if(!mChildren.Empty())
return &mChildren.Back();
return nullptr;
}
//******************************************************************************
template <typename ComponentType>
ComponentType* ComponentHierarchy<ComponentType>::GetLastDeepestChild()
{
if (UiWidget* lastChild = GetLastDirectChild())
return lastChild->GetLastDeepestChild();
else
return (ComponentType*)this;
}
//******************************************************************************
template <typename ComponentType>
ComponentType* ComponentHierarchy<ComponentType>::GetNextInHierarchyOrder()
{
// If this object has children return the first child
if(!mChildren.Empty())
return &mChildren.Front();
// Return next sibling if there is one
ComponentType* nextSibling = GetNextSibling();
if(nextSibling)
return nextSibling;
// Loop until the root or a parent has a sibling
ComponentType* parent = mParent;
while(parent != nullptr)
{
ComponentType* parentSibling = parent->GetNextSibling();
if(parentSibling)
return parentSibling;
else
parent = parent->mParent;
}
return nullptr;
}
//******************************************************************************
template <typename ComponentType>
ComponentType* ComponentHierarchy<ComponentType>::GetPreviousInHierarchyOrder()
{
// Get prev sibling if there is one
ComponentType* prevSibling = GetPreviousSibling();
// If this is first node of a child it is previous node
if(prevSibling == nullptr)
return mParent;
// Return the last child of the sibling
return prevSibling->GetLastDeepestChild();
}
//******************************************************************************
template <typename ComponentType>
ComponentType* ComponentHierarchy<ComponentType>::GetRoot()
{
ComponentType* curr = (ComponentType*)this;
while(curr->mParent)
curr = curr->mParent;
return curr;
}
//******************************************************************************
template <typename ComponentType>
bool ComponentHierarchy<ComponentType>::IsDescendantOf(ComponentType& ancestor)
{
return ancestor.IsAncestorOf(*(ComponentType*)this);
}
//******************************************************************************
template <typename ComponentType>
bool ComponentHierarchy<ComponentType>::IsAncestorOf(ComponentType& descendant)
{
ComponentType* current = &descendant;
while (current)
{
current = current->mParent;
if (current == this)
return true;
}
return false;
}
//******************************************************************************
template <typename ComponentType>
uint ComponentHierarchy<ComponentType>::GetChildCount()
{
uint count = 0;
forRange(ComponentType& child, GetChildren())
++count;
return count;
}
}//namespace Zero
| 32.501511 | 89 | 0.602993 | RachelWilSingh |
848ec0cbce7a22f6d1758bd5042f902fdb55bf09 | 1,454 | cc | C++ | src/common/step/recovery/step_open_recovery_file.cc | tizenorg/platform.core.appfw.app-installers | 54b7b4972c3ab9775856756a5d97220ef344f7e5 | [
"Apache-2.0"
] | null | null | null | src/common/step/recovery/step_open_recovery_file.cc | tizenorg/platform.core.appfw.app-installers | 54b7b4972c3ab9775856756a5d97220ef344f7e5 | [
"Apache-2.0"
] | null | null | null | src/common/step/recovery/step_open_recovery_file.cc | tizenorg/platform.core.appfw.app-installers | 54b7b4972c3ab9775856756a5d97220ef344f7e5 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
// Use of this source code is governed by an apache-2.0 license that can be
// found in the LICENSE file.
#include "common/step/recovery/step_open_recovery_file.h"
#include <cassert>
#include "common/recovery_file.h"
namespace common_installer {
namespace recovery {
Step::Status StepOpenRecoveryFile::process() {
std::unique_ptr<recovery::RecoveryFile> recovery_file =
RecoveryFile::OpenRecoveryFileForPath(context_->file_path.get());
if (!recovery_file) {
LOG(ERROR) << "Failed to open recovery file";
return Status::RECOVERY_ERROR;
}
context_->unpacked_dir_path.set(recovery_file->unpacked_dir());
context_->pkgid.set(recovery_file->pkgid());
switch (recovery_file->type()) {
case RequestType::Install:
LOG(INFO) << "Running recovery for new installation";
break;
case RequestType::Update:
LOG(INFO) << "Running recovery for update installation";
break;
default:
assert(false && "Not reached");
}
context_->recovery_info.set(RecoveryInfo(std::move(recovery_file)));
return Status::OK;
}
Step::Status StepOpenRecoveryFile::undo() {
// Detach object from underlaying file so it will not be removed
// as recovery failed.
if (context_->recovery_info.get().recovery_file)
context_->recovery_info.get().recovery_file->Detach();
return Status::OK;
}
} // namespace recovery
} // namespace common_installer
| 30.291667 | 75 | 0.727648 | tizenorg |
848feca691f89f2c9ead66d1c27759fea7a4b7f7 | 1,602 | cpp | C++ | Chain/Info.cpp | matheuspercario/SI300-POO1 | d071a8cd399e3e9e667c1ce295cbfdcfe4eef796 | [
"MIT"
] | null | null | null | Chain/Info.cpp | matheuspercario/SI300-POO1 | d071a8cd399e3e9e667c1ce295cbfdcfe4eef796 | [
"MIT"
] | null | null | null | Chain/Info.cpp | matheuspercario/SI300-POO1 | d071a8cd399e3e9e667c1ce295cbfdcfe4eef796 | [
"MIT"
] | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include <iostream>
#include "Info.hpp"
using namespace std;
const string Info::institution = "Unicamp - Universidade Estadual de Campinas";
const string Info::dept = "FT - Faculdade de Tecnologia";
const string Info::author = "Prof. Dr. Andre F. de Angelis";
const string Info::date = "Jun/2016";
const string Info::sysName = "FT - Project Chain";
const string Info::sysVersion = "1.0";
const string Info::decoration = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
const string Info::getInstitution()
{
return (institution);
};
const string Info::getDept()
{
return (dept);
};
const string Info::getAuthor()
{
return (author);
};
const string Info::getDate()
{
return (date);
};
const string Info::getSysName()
{
return (sysName);
}
const string Info::getSysVersion()
{
return(sysVersion);
}
const void Info::wellcome()
{
cout << decoration;
cout << Info::getSysName() << "\t Ver. " << Info::getSysVersion() << endl;
cout << decoration;
cout << Info::getInstitution() << "\n" << Info::getDept() << endl;
cout << Info::getAuthor() << "\n" << Info::getDate() << endl;
cout << decoration << endl;
};
const void Info::goodbye()
{
cout << decoration;
cout << Info::getSysName() << "\t Ver. " << Info::getSysVersion() << endl;
cout << decoration;
cout << "\n\n" << endl;
};
| 23.558824 | 117 | 0.59613 | matheuspercario |
84909bb095fa4784f86a33217cf7cd6983e89c45 | 388 | cpp | C++ | FATERUI/common/camera/bobcat/bobcat_gev/share/samples/eBUSPlayer/ChangeSourceTask.cpp | LynnChan706/Fater | dde8e3baaac7be8b0c1f8bee0da628f6e6f2b772 | [
"MIT"
] | 4 | 2018-12-07T02:17:26.000Z | 2020-12-03T05:32:23.000Z | FATERUI/common/camera/bobcat/bobcat_gev/share/samples/eBUSPlayer/ChangeSourceTask.cpp | LynnChan706/Fater | dde8e3baaac7be8b0c1f8bee0da628f6e6f2b772 | [
"MIT"
] | null | null | null | FATERUI/common/camera/bobcat/bobcat_gev/share/samples/eBUSPlayer/ChangeSourceTask.cpp | LynnChan706/Fater | dde8e3baaac7be8b0c1f8bee0da628f6e6f2b772 | [
"MIT"
] | 1 | 2021-12-30T12:14:52.000Z | 2021-12-30T12:14:52.000Z | // *****************************************************************************
//
// Copyright (c) 2013, Pleora Technologies Inc., All rights reserved.
//
// *****************************************************************************
#include "eBUSPlayerShared.h"
#include "ChangeSourceTask.h"
#ifdef _AFXDLL
IMPLEMENT_DYNAMIC( ChangeSourceTask, Task )
#endif // _AFXDLL
| 24.25 | 80 | 0.414948 | LynnChan706 |
84910428c956dcee2663eb045837180f46ac9b40 | 4,066 | hpp | C++ | src/ruby/ruby_observation.hpp | bburns/cppagent | c1891c631465ebc9b63a4b3c627727ca3da14ee8 | [
"Apache-2.0"
] | null | null | null | src/ruby/ruby_observation.hpp | bburns/cppagent | c1891c631465ebc9b63a4b3c627727ca3da14ee8 | [
"Apache-2.0"
] | null | null | null | src/ruby/ruby_observation.hpp | bburns/cppagent | c1891c631465ebc9b63a4b3c627727ca3da14ee8 | [
"Apache-2.0"
] | null | null | null | //
// Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#include "observation/observation.hpp"
#include "ruby_entity.hpp"
#include "ruby_vm.hpp"
namespace mtconnect::ruby {
using namespace mtconnect::observation;
using namespace std;
using namespace Rice;
struct RubyObservation
{
static void initialize(mrb_state *mrb, RClass *module)
{
auto entityClass = mrb_class_get_under(mrb, module, "Entity");
auto observationClass = mrb_define_class_under(mrb, module, "Observation", entityClass);
MRB_SET_INSTANCE_TT(observationClass, MRB_TT_DATA);
mrb_define_method(
mrb, observationClass, "initialize",
[](mrb_state *mrb, mrb_value self) {
using namespace device_model::data_item;
mrb_value di;
mrb_value props;
mrb_value ts;
ErrorList errors;
Timestamp time;
auto count = mrb_get_args(mrb, "oo|o", &di, &props, &ts);
auto dataItem = MRubySharedPtr<Entity>::unwrap<DataItem>(mrb, di);
if (count < 3)
time = std::chrono::system_clock::now();
else
time = timestampFromRuby(mrb, ts);
Properties values;
fromRuby(mrb, props, values);
ObservationPtr obs = Observation::make(dataItem, values, time, errors);
if (errors.size() > 0)
{
ostringstream str;
for (auto &e : errors)
{
str << e->what() << ", ";
}
mrb_raise(mrb, E_ARGUMENT_ERROR, str.str().c_str());
}
MRubySharedPtr<Entity>::replace(mrb, self, obs);
return self;
},
MRB_ARGS_ARG(2, 1));
mrb_define_method(
mrb, observationClass, "dup",
[](mrb_state *mrb, mrb_value self) {
ObservationPtr old = MRubySharedPtr<Entity>::unwrap<Observation>(mrb, self);
RClass *klass = mrb_class(mrb, self);
auto dup = old->copy();
return MRubySharedPtr<Entity>::wrap(mrb, klass, dup);
},
MRB_ARGS_NONE());
mrb_alias_method(mrb, observationClass, mrb_intern_lit(mrb, "copy"),
mrb_intern_lit(mrb, "dup"));
mrb_define_method(
mrb, observationClass, "data_item",
[](mrb_state *mrb, mrb_value self) {
ObservationPtr obs = MRubySharedPtr<Entity>::unwrap<Observation>(mrb, self);
return MRubySharedPtr<Entity>::wrap(mrb, "DataItem", obs->getDataItem());
},
MRB_ARGS_NONE());
mrb_define_method(
mrb, observationClass, "timestamp",
[](mrb_state *mrb, mrb_value self) {
ObservationPtr obs = MRubySharedPtr<Entity>::unwrap<Observation>(mrb, self);
return toRuby(mrb, obs->getTimestamp());
},
MRB_ARGS_NONE());
auto eventClass = mrb_define_class_under(mrb, module, "Event", observationClass);
MRB_SET_INSTANCE_TT(eventClass, MRB_TT_DATA);
auto sampleClass = mrb_define_class_under(mrb, module, "Sample", observationClass);
MRB_SET_INSTANCE_TT(sampleClass, MRB_TT_DATA);
auto conditionClass = mrb_define_class_under(mrb, module, "Condition", observationClass);
MRB_SET_INSTANCE_TT(conditionClass, MRB_TT_DATA);
}
};
} // namespace mtconnect::ruby
| 34.457627 | 95 | 0.615101 | bburns |
8496b23cf8e8b9c5e11e2c3a978e645b71bcecf9 | 3,341 | cpp | C++ | lists/four/spoj-setemar.cpp | joaovicentesouto/INE5452 | 4813630b303a9c6dbd4fb14fae0fb3b850e1aea3 | [
"MIT"
] | null | null | null | lists/four/spoj-setemar.cpp | joaovicentesouto/INE5452 | 4813630b303a9c6dbd4fb14fae0fb3b850e1aea3 | [
"MIT"
] | null | null | null | lists/four/spoj-setemar.cpp | joaovicentesouto/INE5452 | 4813630b303a9c6dbd4fb14fae0fb3b850e1aea3 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
#define MOVE(tx, ty, ch) (tabuleiro[tx][ty] = ch)
//! Variáveis globais
vector<pair<int, int>> inimigos;
pair<int, int> jogador;
char tabuleiro[9][8];
bool destroi_inimigos(int nivel)
{
if (nivel == 10 && inimigos.empty())
return true;
if (nivel == 10)
return false; //! Não consegui matar
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0
|| i == -1 && jogador.first == 0
|| i == 1 && jogador.first == 8
|| j == -1 && jogador.second == 0
|| j == 1 && jogador.second == 7
)
continue;
bool morte = false;
pair<int, int> antigo_jogador = jogador;
vector<pair<int, int>> antigos_inimigos(inimigos.begin(), inimigos.end());
unordered_map<int, int> olds;
inimigos.clear();
jogador = {jogador.first + i, jogador.second + j};
if (tabuleiro[jogador.first][jogador.second] == 'E' || tabuleiro[jogador.first][jogador.second] == '#')
{
morte = true;
goto morte_label;
}
MOVE(antigo_jogador.first, antigo_jogador.second, '.');
MOVE(jogador.first, jogador.second, 'S');
for (auto i : antigos_inimigos)
{
int ix = i.first + (jogador.first < i.first ? -1 : jogador.first > i.first ? 1 : 0);
int iy = i.second + (jogador.second < i.second ? -1 : jogador.second > i.second ? 1 : 0);
if (tabuleiro[ix][iy] == '.')
{
inimigos.push_back({ix, iy});
olds[ix * 100 + iy] = i.first * 100 + i.second;
MOVE(i.first, i.second, '.');
MOVE(ix, iy, 'E');
}
else if (tabuleiro[ix][iy] == 'S')
{
morte = true;
break;
}
}
if (!morte)
if (destroi_inimigos(nivel + 1))
return true;
for (auto p : olds)
{
MOVE(p.first/100, p.first%10, '.');
MOVE(p.second/100, p.second%10, 'E');
}
MOVE(jogador.first, jogador.second, '.');
MOVE(antigo_jogador.first, antigo_jogador.second, 'S');
morte_label:
jogador = antigo_jogador;
inimigos = antigos_inimigos;
}
}
return false;
}
int main(void)
{
int casos;
cin >> casos;
for (int c = 0; c < casos; c++)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 8; j++)
{
cin >> tabuleiro[i][j];
if (tabuleiro[i][j] == 'S')
jogador = {i, j};
else if (tabuleiro[i][j] == 'E')
inimigos.push_back({i, j});
}
}
if (destroi_inimigos(0))
cout << "I'm the king of the Seven Seas!" << endl;
else
cout << "Oh no! I'm a dead man!" << endl;
inimigos.clear();
}
} | 27.841667 | 115 | 0.428315 | joaovicentesouto |
84977923e61ad88c5105008b8aec32f11b56b650 | 16,272 | cpp | C++ | test/unit/ResourceSerializationTest.cpp | dmitryvinn/redex | d5050fbfec8566687dc0f2c977b0aeec2bbc681b | [
"MIT"
] | null | null | null | test/unit/ResourceSerializationTest.cpp | dmitryvinn/redex | d5050fbfec8566687dc0f2c977b0aeec2bbc681b | [
"MIT"
] | null | null | null | test/unit/ResourceSerializationTest.cpp | dmitryvinn/redex | d5050fbfec8566687dc0f2c977b0aeec2bbc681b | [
"MIT"
] | null | null | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <array>
#include <fstream>
#include <gtest/gtest.h>
#include "ApkResources.h"
#include "Debug.h"
#include "RedexMappedFile.h"
#include "RedexResources.h"
#include "RedexTestUtils.h"
#include "SanitizersConfig.h"
#include "androidfw/ResourceTypes.h"
#include "utils/Serialize.h"
#include "utils/Visitor.h"
namespace {
// Chunk of just the ResStringPool, as generated by aapt2 (has 2 UTF8 strings)
const std::array<uint8_t, 84> example_data_8{
{0x01, 0x00, 0x1C, 0x00, 0x54, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00,
0x0C, 0x0C, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x77, 0x6F, 0x72,
0x6C, 0x64, 0x00, 0x1C, 0x1C, 0x72, 0x65, 0x73, 0x2F, 0x6C, 0x61, 0x79,
0x6F, 0x75, 0x74, 0x2F, 0x73, 0x69, 0x6D, 0x70, 0x6C, 0x65, 0x5F, 0x6C,
0x61, 0x79, 0x6F, 0x75, 0x74, 0x2E, 0x78, 0x6D, 0x6C, 0x00, 0x00, 0x00}};
// Another aapt2 generated ResStringPool, encoded as UTF-16.
const std::array<uint8_t, 116> example_data_16{
{0x01, 0x00, 0x1C, 0x00, 0x74, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x00,
0x1C, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
0x05, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x72, 0x00,
0x00, 0x00, 0x05, 0x00, 0x64, 0x00, 0x69, 0x00, 0x6D, 0x00, 0x65, 0x00,
0x6E, 0x00, 0x00, 0x00, 0x02, 0x00, 0x69, 0x00, 0x64, 0x00, 0x00, 0x00,
0x06, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x79, 0x00, 0x6F, 0x00, 0x75, 0x00,
0x74, 0x00, 0x00, 0x00, 0x06, 0x00, 0x73, 0x00, 0x74, 0x00, 0x72, 0x00,
0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00, 0x00}};
std::string make_big_string(size_t len) {
always_assert(len > 4);
std::string result = "aa" + std::string(len - 4, 'x') + "zz";
return result;
}
void assert_u16_string(const std::u16string& actual_str,
const std::string& expected) {
std::u16string expected_str(expected.begin(), expected.end());
ASSERT_EQ(actual_str, expected_str);
}
void assert_serialized_data(const void* original,
size_t length,
android::Vector<char>& serialized) {
ASSERT_EQ(length, serialized.size());
for (size_t i = 0; i < length; i++) {
auto actual = *((const char*)original + i);
ASSERT_EQ(actual, serialized[i]);
}
}
void copy_file(const std::string& from, const std::string& to) {
std::ifstream src_stream(from, std::ios::binary);
std::ofstream dest_stream(to, std::ios::binary);
dest_stream << src_stream.rdbuf();
}
bool are_files_equal(const std::string& p1, const std::string& p2) {
std::ifstream f1(p1, std::ifstream::binary | std::ifstream::ate);
std::ifstream f2(p2, std::ifstream::binary | std::ifstream::ate);
always_assert_log(!f1.fail(), "Failed to read path %s", p1.c_str());
always_assert_log(!f2.fail(), "Failed to read path %s", p2.c_str());
if (f1.tellg() != f2.tellg()) {
std::cerr << "File length mismatch. " << f1.tellg() << " != " << f2.tellg()
<< std::endl;
return false;
}
f1.seekg(0, std::ifstream::beg);
f2.seekg(0, std::ifstream::beg);
return std::equal(std::istreambuf_iterator<char>(f1.rdbuf()),
std::istreambuf_iterator<char>(),
std::istreambuf_iterator<char>(f2.rdbuf()));
}
} // namespace
TEST(ResStringPool, AppendToEmptyTable) {
const size_t header_size = sizeof(android::ResStringPool_header);
android::ResStringPool_header header = {
{htods(android::RES_STRING_POOL_TYPE), htods(header_size),
htodl(header_size)},
0,
0,
htodl(android::ResStringPool_header::UTF8_FLAG |
android::ResStringPool_header::SORTED_FLAG),
0,
0};
android::ResStringPool pool((void*)&header, header_size, false);
pool.appendString(android::String8("Hello, world"));
auto big_string = make_big_string(300);
auto big_chars = big_string.c_str();
pool.appendString(android::String8(big_chars));
pool.appendString(android::String8("€666"));
pool.appendString(android::String8("banana banana"));
android::Vector<char> v;
pool.serialize(v);
auto data = (void*)v.array();
android::ResStringPool after(data, v.size(), false);
// Ensure sort bit was cleared.
auto flags = dtohl(((android::ResStringPool_header*)data)->flags);
ASSERT_FALSE(flags & android::ResStringPool_header::SORTED_FLAG);
size_t out_len;
ASSERT_STREQ(after.string8At(0, &out_len), "Hello, world");
ASSERT_EQ(out_len, 12);
ASSERT_STREQ(after.string8At(1, &out_len), big_chars);
ASSERT_EQ(out_len, 300);
ASSERT_STREQ(after.string8At(2, &out_len), "€666");
ASSERT_STREQ(after.string8At(3, &out_len), "banana banana");
}
TEST(ResStringPool, AppendToExistingUTF8) {
android::ResStringPool pool(&example_data_8, example_data_8.size(), false);
size_t out_len;
ASSERT_STREQ(pool.string8At(0, &out_len), "Hello, world");
pool.appendString(android::String8("this is another string"));
android::Vector<char> v;
pool.serialize(v);
android::ResStringPool after((void*)v.array(), v.size(), false);
// Make sure we still have the original two strings
ASSERT_STREQ(after.string8At(0, &out_len), "Hello, world");
ASSERT_EQ(out_len, 12);
ASSERT_STREQ(after.string8At(1, &out_len), "res/layout/simple_layout.xml");
ASSERT_EQ(out_len, 28);
// And the one appended
ASSERT_STREQ(after.string8At(2, &out_len), "this is another string");
ASSERT_EQ(out_len, 22);
}
TEST(ResStringPool, AppendToExistingUTF16) {
android::ResStringPool pool(&example_data_16, example_data_16.size(), false);
ASSERT_TRUE(!pool.isUTF8());
size_t out_len;
auto s = pool.stringAt(0, &out_len);
assert_u16_string(s, "color");
ASSERT_EQ(out_len, 5);
// Make sure the size encoding works for large values.
auto big_string = make_big_string(35000);
auto big_chars = big_string.c_str();
pool.appendString(android::String8(big_chars));
pool.appendString(android::String8("more more more"));
android::Vector<char> v;
pool.serialize(v);
android::ResStringPool after((void*)v.array(), v.size(), false);
assert_u16_string(after.stringAt(0, &out_len), "color");
ASSERT_EQ(out_len, 5);
assert_u16_string(after.stringAt(1, &out_len), "dimen");
ASSERT_EQ(out_len, 5);
assert_u16_string(after.stringAt(2, &out_len), "id");
ASSERT_EQ(out_len, 2);
assert_u16_string(after.stringAt(3, &out_len), "layout");
ASSERT_EQ(out_len, 6);
assert_u16_string(after.stringAt(4, &out_len), "string");
ASSERT_EQ(out_len, 6);
assert_u16_string(after.stringAt(5, &out_len), big_chars);
ASSERT_EQ(out_len, 35000);
assert_u16_string(after.stringAt(6, &out_len), "more more more");
ASSERT_EQ(out_len, 14);
}
TEST(ResStringPool, ReplaceStringsInXmlLayout) {
// Given layout file should have a series of View subclasses in the XML, which
// we will rename. Parse the resulting binary data, and make sure all tags are
// right.
auto f = RedexMappedFile::open(std::getenv("test_layout_path"));
std::map<std::string, std::string> shortened_names;
shortened_names.emplace("com.example.test.CustomViewGroup", "Z.a");
shortened_names.emplace("com.example.test.CustomTextView", "Z.b");
shortened_names.emplace("com.example.test.CustomButton", "Z.c");
shortened_names.emplace("com.example.test.NotFound", "Z.d");
android::Vector<char> serialized;
size_t num_renamed = 0;
ApkResources resources("");
resources.replace_in_xml_string_pool(
f.const_data(), f.size(), shortened_names, &serialized, &num_renamed);
EXPECT_EQ(num_renamed, 3);
android::ResXMLTree parser;
parser.setTo(&serialized[0], serialized.size());
EXPECT_EQ(android::NO_ERROR, parser.getError())
<< "Error parsing layout after rename";
std::vector<std::string> expected_xml_tags;
expected_xml_tags.push_back("Z.a");
expected_xml_tags.push_back("TextView");
expected_xml_tags.push_back("Z.b");
expected_xml_tags.push_back("Z.c");
expected_xml_tags.push_back("Button");
size_t tag_count = 0;
android::ResXMLParser::event_code_t type;
do {
type = parser.next();
if (type == android::ResXMLParser::START_TAG) {
EXPECT_LT(tag_count, 5);
size_t len;
android::String8 tag(parser.getElementName(&len));
auto actual_chars = tag.string();
auto expected_chars = expected_xml_tags[tag_count].c_str();
EXPECT_STREQ(actual_chars, expected_chars);
tag_count++;
}
} while (type != android::ResXMLParser::BAD_DOCUMENT &&
type != android::ResXMLParser::END_DOCUMENT);
EXPECT_EQ(tag_count, 5);
}
TEST(ResTable, TestRoundTrip) {
auto f = RedexMappedFile::open(std::getenv("test_arsc_path"));
android::ResTable table;
ASSERT_EQ(table.add(f.const_data(), f.size()), 0);
// Just invoke the serialize method to ensure the same data comes back
android::Vector<char> serialized;
table.serialize(serialized, 0);
assert_serialized_data(f.const_data(), f.size(), serialized);
}
TEST(ResTable, AppendNewType) {
auto f = RedexMappedFile::open(std::getenv("test_arsc_path"));
android::ResTable table;
ASSERT_EQ(table.add(f.const_data(), f.size()), 0);
// Read the number of original types.
android::Vector<android::String8> original_type_names;
table.getTypeNamesForPackage(0, &original_type_names);
// Copy some existing entries to a different table, verify serialization
const uint8_t dest_type = 3;
android::Vector<uint32_t> source_ids;
source_ids.push_back(0x7f010000);
size_t num_ids = source_ids.size();
android::Vector<android::Res_value> values;
for (size_t i = 0; i < num_ids; i++) {
android::Res_value val;
table.getResource(source_ids[i], &val);
values.push_back(val);
}
// Initializing the ResTable_config is a pain.
android::ResTable_config config;
memset(&config, 0, sizeof(android::ResTable_config));
config.size = sizeof(android::ResTable_config);
android::Vector<android::ResTable_config> config_vec;
config_vec.push(config);
table.defineNewType(
android::String8("foo"), dest_type, config_vec, source_ids);
android::Vector<char> serialized;
table.serialize(serialized, 0);
android::ResTable round_trip;
ASSERT_EQ(round_trip.add((void*)serialized.array(), serialized.size()), 0);
// Make sure entries exist in 0x7f03xxxx range
for (size_t i = 0; i < num_ids; i++) {
auto old_id = source_ids[i];
auto new_id = 0x7f000000 | (dest_type << 16) | (old_id & 0xFFFF);
android::Res_value expected = values[i];
android::Res_value actual;
round_trip.getResource(new_id, &actual);
ASSERT_EQ(expected.dataType, actual.dataType);
ASSERT_EQ(expected.data, actual.data);
}
// Sanity check values in their original location
{
android::Res_value out_value;
round_trip.getResource(0x7f010000, &out_value);
float val = android::complex_value(out_value.data);
uint32_t unit = android::complex_unit(out_value.data, false);
ASSERT_EQ((int)val, 10);
ASSERT_EQ(unit, android::Res_value::COMPLEX_UNIT_DIP);
}
{
android::Res_value out_value;
round_trip.getResource(0x7f010001, &out_value);
float val = android::complex_value(out_value.data);
uint32_t unit = android::complex_unit(out_value.data, false);
ASSERT_EQ((int)val, 20);
ASSERT_EQ(unit, android::Res_value::COMPLEX_UNIT_DIP);
}
android::Vector<android::String8> type_names;
round_trip.getTypeNamesForPackage(0, &type_names);
ASSERT_EQ(type_names.size(), original_type_names.size() + 1);
}
TEST(ResStringPoolBuilder, TestPoolRebuild8) {
android::ResStringPool pool(&example_data_8, example_data_8.size(), false);
auto flags =
(pool.isUTF8() ? android::ResStringPool_header::UTF8_FLAG : 0) |
(pool.isSorted() ? android::ResStringPool_header::SORTED_FLAG : 0);
auto pool_size = pool.size();
arsc::ResStringPoolBuilder builder(flags);
for (size_t i = 0; i < pool_size; i++) {
size_t out_len;
auto s = pool.string8At(i, &out_len);
builder.add_string(s, out_len);
}
android::Vector<char> serialized;
builder.serialize(&serialized);
assert_serialized_data(&example_data_8, example_data_8.size(), serialized);
}
TEST(ResStringPoolBuilder, TestPoolRebuild16) {
android::ResStringPool pool(&example_data_16, example_data_16.size(), false);
auto flags =
(pool.isUTF8() ? android::ResStringPool_header::UTF8_FLAG : 0) |
(pool.isSorted() ? android::ResStringPool_header::SORTED_FLAG : 0);
auto pool_size = pool.size();
arsc::ResStringPoolBuilder builder(flags);
for (size_t i = 0; i < pool_size; i++) {
size_t out_len;
auto s = pool.stringAt(i, &out_len);
builder.add_string(s, out_len);
}
android::Vector<char> serialized;
builder.serialize(&serialized);
assert_serialized_data(&example_data_16, example_data_16.size(), serialized);
}
TEST(ResStringPoolBuilder, TestPoolRebuildStyle8) {
const std::array<uint8_t, 232> data{
{0x01, 0x00, 0x1c, 0x00, 0xe8, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00,
0x41, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x00,
0x59, 0x00, 0x00, 0x00, 0x5f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1c, 0x00, 0x00, 0x00, 0x11, 0x11, 0x41, 0x6e, 0x20, 0x75, 0x6e, 0x75,
0x73, 0x65, 0x64, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x00,
0x2a, 0x2a, 0x49, 0x20, 0x6c, 0x69, 0x6b, 0x65, 0x20, 0x61, 0x20, 0x66,
0x69, 0x6e, 0x65, 0x20, 0x67, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66,
0x20, 0x48, 0x32, 0x4f, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20,
0x6d, 0x6f, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x21, 0x00, 0x0c, 0x0c, 0x48,
0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x2e, 0x00,
0x01, 0x01, 0x62, 0x00, 0x02, 0x02, 0x65, 0x6d, 0x00, 0x03, 0x03, 0x73,
0x75, 0x62, 0x00, 0x03, 0x03, 0x73, 0x75, 0x70, 0x00, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0x04, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x18, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff}};
android::ResStringPool pool(&data, data.size(), false);
auto flags =
(pool.isUTF8() ? android::ResStringPool_header::UTF8_FLAG : 0) |
(pool.isSorted() ? android::ResStringPool_header::SORTED_FLAG : 0);
auto pool_size = pool.size();
auto style_count = pool.styleCount();
arsc::ResStringPoolBuilder builder(flags);
for (size_t i = 0; i < pool_size; i++) {
size_t out_len;
auto s = pool.string8At(i, &out_len);
if (i < style_count) {
arsc::SpanVector vec;
auto span = (android::ResStringPool_span*)pool.styleAt(i);
arsc::collect_spans(span, &vec);
builder.add_style(s, out_len, vec);
} else {
builder.add_string(s, out_len);
}
}
EXPECT_EQ(pool.size(), builder.string_count());
android::Vector<char> serialized;
builder.serialize(&serialized);
assert_serialized_data(&data, data.size(), serialized);
}
TEST(ResTableParse, TestUnknownPackageChunks) {
// A table with one package, which has a fake chunk that is made up. The chunk
// that is not known/recognized should just be copied as-is to the output.
auto tmp_dir = redex::make_tmp_dir("ResTableParse%%%%%%%%");
auto res_path = tmp_dir.path + "/resources.arsc";
copy_file(std::getenv("resources_unknown_chunk"), res_path);
ResourcesArscFile res_table(res_path);
res_table.remove_unreferenced_strings();
EXPECT_TRUE(
are_files_equal(std::getenv("resources_unknown_chunk"), res_path));
}
| 40.177778 | 80 | 0.688053 | dmitryvinn |
849b1e3e95867137ad36e2f1fdfd61ef035f2452 | 4,758 | cc | C++ | src/shared/ppapi_proxy/plugin_graphics_2d.cc | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | 4 | 2015-10-27T04:43:02.000Z | 2021-08-13T08:21:45.000Z | src/shared/ppapi_proxy/plugin_graphics_2d.cc | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | null | null | null | src/shared/ppapi_proxy/plugin_graphics_2d.cc | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | 1 | 2015-11-08T10:18:42.000Z | 2015-11-08T10:18:42.000Z | /*
* Copyright 2010 The Native Client 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 "native_client/src/shared/ppapi_proxy/plugin_graphics_2d.h"
#include <stdio.h>
#include <string.h>
#include "srpcgen/ppb_rpc.h"
#include "srpcgen/upcall.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/ppapi_proxy/plugin_globals.h"
#include "native_client/src/shared/ppapi_proxy/utility.h"
#include "native_client/src/shared/srpc/nacl_srpc.h"
#include "ppapi/c/ppb_graphics_2d.h"
#include "ppapi/c/pp_completion_callback.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/pp_rect.h"
#include "ppapi/c/pp_size.h"
namespace ppapi_proxy {
namespace {
const nacl_abi_size_t kPpSizeBytes =
static_cast<nacl_abi_size_t>(sizeof(struct PP_Size));
const nacl_abi_size_t kPpPointBytes =
static_cast<nacl_abi_size_t>(sizeof(struct PP_Point));
const nacl_abi_size_t kPpRectBytes =
static_cast<nacl_abi_size_t>(sizeof(struct PP_Rect));
PP_Resource Create(PP_Module module,
const struct PP_Size* size,
PP_Bool is_always_opaque) {
int32_t* size_as_int_ptr =
reinterpret_cast<int32_t*>(const_cast<struct PP_Size*>(size));
int32_t is_always_opaque_as_int = static_cast<int32_t>(is_always_opaque);
int64_t resource;
NaClSrpcError retval =
PpbGraphics2DRpcClient::PPB_Graphics2D_Create(
GetMainSrpcChannel(),
static_cast<int64_t>(module),
kPpSizeBytes,
size_as_int_ptr,
is_always_opaque_as_int,
&resource);
if (retval == NACL_SRPC_RESULT_OK) {
return static_cast<PP_Resource>(resource);
} else {
return kInvalidResourceId;
}
}
PP_Bool IsGraphics2D(PP_Resource resource) {
return PluginResource::GetAs<PluginGraphics2D>(resource).get()
? PP_TRUE : PP_FALSE;
}
PP_Bool Describe(PP_Resource graphics_2d,
struct PP_Size* size,
PP_Bool* is_always_opaque) {
int32_t is_always_opaque_as_int;
nacl_abi_size_t size_ret = kPpSizeBytes;
int32_t result;
NaClSrpcError retval =
PpbGraphics2DRpcClient::PPB_Graphics2D_Describe(
GetMainSrpcChannel(),
static_cast<int64_t>(graphics_2d),
&size_ret,
reinterpret_cast<int32_t*>(size),
&is_always_opaque_as_int,
&result);
if (retval == NACL_SRPC_RESULT_OK || size_ret != kPpSizeBytes) {
*is_always_opaque = is_always_opaque_as_int ? PP_TRUE : PP_FALSE;
return result ? PP_TRUE : PP_FALSE;
} else {
return PP_FALSE;
}
}
void PaintImageData(PP_Resource graphics_2d,
PP_Resource image,
const struct PP_Point* top_left,
const struct PP_Rect* src_rect) {
// TODO(sehr,polina): there is no way to report a failure through this
// interface design other than crash. Let's find one.
(void) PpbGraphics2DRpcClient::PPB_Graphics2D_PaintImageData(
GetMainSrpcChannel(),
static_cast<int64_t>(graphics_2d),
static_cast<int64_t>(image),
kPpPointBytes,
reinterpret_cast<int32_t*>(const_cast<struct PP_Point*>(top_left)),
kPpRectBytes,
reinterpret_cast<int32_t*>(const_cast<struct PP_Rect*>(src_rect)));
}
void Scroll(PP_Resource graphics_2d,
const struct PP_Rect* clip_rect,
const struct PP_Point* amount) {
// TODO(sehr,polina): there is no way to report a failure through this
// interface design other than crash. Let's find one.
(void) PpbGraphics2DRpcClient::PPB_Graphics2D_Scroll(
GetMainSrpcChannel(),
static_cast<int64_t>(graphics_2d),
kPpRectBytes,
reinterpret_cast<int32_t*>(const_cast<struct PP_Rect*>(clip_rect)),
kPpPointBytes,
reinterpret_cast<int32_t*>(const_cast<struct PP_Point*>(amount)));
}
void ReplaceContents(PP_Resource graphics_2d, PP_Resource image) {
(void) PpbGraphics2DRpcClient::PPB_Graphics2D_ReplaceContents(
GetMainSrpcChannel(),
static_cast<int64_t>(graphics_2d),
static_cast<int64_t>(image));
}
int32_t Flush(PP_Resource graphics_2d,
struct PP_CompletionCallback callback) {
UNREFERENCED_PARAMETER(graphics_2d);
UNREFERENCED_PARAMETER(callback);
// TODO(sehr): implement the call on the upcall channel once the completion
// callback implementation is in place.
NACL_UNIMPLEMENTED();
return PP_ERROR_BADRESOURCE;
}
} // namespace
const PPB_Graphics2D* PluginGraphics2D::GetInterface() {
static const PPB_Graphics2D intf = {
Create,
IsGraphics2D,
Describe,
PaintImageData,
Scroll,
ReplaceContents,
Flush,
};
return &intf;
}
} // namespace ppapi_proxy
| 32.589041 | 77 | 0.713535 | eseidel |
849b43732443fa7d940027619759988361f3cbfa | 1,247 | cpp | C++ | test/nmea/Test_nmea_rot.cpp | mfkiwl/marnav | 53a1c987bf72d48df134c12dd1edc44d7f230921 | [
"BSD-4-Clause"
] | 62 | 2015-07-20T03:24:21.000Z | 2022-03-30T10:39:24.000Z | test/nmea/Test_nmea_rot.cpp | mfkiwl/marnav | 53a1c987bf72d48df134c12dd1edc44d7f230921 | [
"BSD-4-Clause"
] | 37 | 2016-03-30T05:38:32.000Z | 2021-12-26T18:11:38.000Z | test/nmea/Test_nmea_rot.cpp | mfkiwl/marnav | 53a1c987bf72d48df134c12dd1edc44d7f230921 | [
"BSD-4-Clause"
] | 39 | 2015-07-20T03:15:44.000Z | 2022-02-03T07:32:23.000Z | #include <marnav/nmea/rot.hpp>
#include "type_traits_helper.hpp"
#include <marnav/nmea/nmea.hpp>
#include <gtest/gtest.h>
namespace
{
using namespace marnav;
class Test_nmea_rot : public ::testing::Test
{
};
TEST_F(Test_nmea_rot, contruction)
{
EXPECT_NO_THROW(nmea::rot rot);
}
TEST_F(Test_nmea_rot, properties)
{
nmea_sentence_traits<nmea::rot>();
}
TEST_F(Test_nmea_rot, parse)
{
auto s = nmea::make_sentence("$GPROT,1.0,A*30");
ASSERT_NE(nullptr, s);
auto rot = nmea::sentence_cast<nmea::rot>(s);
ASSERT_NE(nullptr, rot);
}
TEST_F(Test_nmea_rot, parse_invalid_number_of_arguments)
{
EXPECT_ANY_THROW(
nmea::detail::factory::sentence_parse<nmea::rot>(nmea::talker::none, {1, "@"}));
EXPECT_ANY_THROW(
nmea::detail::factory::sentence_parse<nmea::rot>(nmea::talker::none, {3, "@"}));
}
TEST_F(Test_nmea_rot, empty_to_string)
{
nmea::rot rot;
EXPECT_STREQ("$GPROT,,*5E", nmea::to_string(rot).c_str());
}
TEST_F(Test_nmea_rot, set_deg_per_minute)
{
nmea::rot rot;
rot.set_deg_per_minute(1.0);
EXPECT_STREQ("$GPROT,1.0,*71", nmea::to_string(rot).c_str());
}
TEST_F(Test_nmea_rot, set_data_valid)
{
nmea::rot rot;
rot.set_data_valid(nmea::status::ok);
EXPECT_STREQ("$GPROT,,A*1F", nmea::to_string(rot).c_str());
}
}
| 19.184615 | 82 | 0.714515 | mfkiwl |
849d1a4611202993be04185a261a961e28f549bb | 815 | cpp | C++ | bmc/version-handler/test/version_createhandler_unittest.cpp | pzh2386034/phosphor-ipmi-flash | c557dc1302e46c60431af8b55056c5d24331063b | [
"Apache-2.0"
] | 7 | 2019-01-20T08:36:51.000Z | 2021-09-04T19:03:53.000Z | bmc/version-handler/test/version_createhandler_unittest.cpp | pzh2386034/phosphor-ipmi-flash | c557dc1302e46c60431af8b55056c5d24331063b | [
"Apache-2.0"
] | 9 | 2018-08-06T03:30:47.000Z | 2022-03-08T17:28:07.000Z | bmc/version-handler/test/version_createhandler_unittest.cpp | pzh2386034/phosphor-ipmi-flash | c557dc1302e46c60431af8b55056c5d24331063b | [
"Apache-2.0"
] | 4 | 2019-08-22T21:03:59.000Z | 2021-12-17T10:00:05.000Z | #include "version_handler.hpp"
#include "version_mock.hpp"
#include <array>
#include <utility>
#include <gtest/gtest.h>
namespace ipmi_flash
{
TEST(VersionHandlerCanHandleTest, VerifyGoodInfoMapPasses)
{
constexpr std::array blobs{"blob0", "blob1"};
VersionBlobHandler handler(createMockVersionConfigs(blobs));
EXPECT_THAT(handler.getBlobIds(),
testing::UnorderedElementsAreArray(blobs));
}
TEST(VersionHandlerCanHandleTest, VerifyDuplicatesIgnored)
{
constexpr std::array blobs{"blob0"};
auto configs = createMockVersionConfigs(blobs);
configs.push_back(createMockVersionConfig(blobs[0]));
VersionBlobHandler handler(std::move(configs));
EXPECT_THAT(handler.getBlobIds(),
testing::UnorderedElementsAreArray(blobs));
}
} // namespace ipmi_flash
| 26.290323 | 64 | 0.741104 | pzh2386034 |
849e873e41c7c54aa501e113692a1e59a073ebce | 678 | cpp | C++ | real-app/src/OStreamSink.cpp | rasa/REAL | 077e6fe2e6242f41bf401960562ccfecc6ca6a18 | [
"MIT"
] | 227 | 2018-08-18T00:02:49.000Z | 2022-03-30T00:28:10.000Z | real-app/src/OStreamSink.cpp | rasa/REAL | 077e6fe2e6242f41bf401960562ccfecc6ca6a18 | [
"MIT"
] | 16 | 2018-08-24T20:44:39.000Z | 2021-08-24T20:05:06.000Z | real-app/src/OStreamSink.cpp | rasa/REAL | 077e6fe2e6242f41bf401960562ccfecc6ca6a18 | [
"MIT"
] | 18 | 2018-12-02T16:44:21.000Z | 2022-02-25T23:49:38.000Z | #include "OStreamSink.h"
using namespace miniant::Spdlog;
OStreamSink::OStreamSink(std::shared_ptr<std::ostream> outputStream, bool forceFlush):
m_outputStream(std::move(outputStream)),
m_forceFlush(forceFlush) {}
std::mutex& OStreamSink::GetMutex() {
return mutex_;
}
void OStreamSink::sink_it_(const spdlog::details::log_msg& message) {
fmt::memory_buffer formattedMessage;
sink::formatter_->format(message, formattedMessage);
m_outputStream->write(formattedMessage.data(), static_cast<std::streamsize>(formattedMessage.size()));
if (m_forceFlush)
m_outputStream->flush();
}
void OStreamSink::flush_() {
m_outputStream->flush();
}
| 28.25 | 106 | 0.733038 | rasa |
849ee3eb41d189b2cc0ad4597b63c4a8628ad4d2 | 2,883 | cpp | C++ | hands-on/architecture/pipeline.cpp | Hiigaran/esc21 | d0d7f0fa7079edc124821e96ef677cda2a2235a1 | [
"CC-BY-4.0"
] | 1 | 2021-11-05T14:44:55.000Z | 2021-11-05T14:44:55.000Z | hands-on/architecture/pipeline.cpp | Hiigaran/esc21 | d0d7f0fa7079edc124821e96ef677cda2a2235a1 | [
"CC-BY-4.0"
] | null | null | null | hands-on/architecture/pipeline.cpp | Hiigaran/esc21 | d0d7f0fa7079edc124821e96ef677cda2a2235a1 | [
"CC-BY-4.0"
] | null | null | null | #include <chrono>
#include <array>
#include <iostream>
#include "benchmark.h"
inline
size_t
fib(size_t n)
{
if (n == 0)
return n;
if (n == 1)
return 1;
return fib(n - 1) + fib(n - 2);
}
inline
double perform_computation(int w) {
return fib(w);
}
int main()
{
using namespace std;
auto start = chrono::high_resolution_clock::now();
auto delta = start - start;
int value = 42;
benchmark::touch(value);
double answer = perform_computation(value);
benchmark::keep(answer);
delta = chrono::high_resolution_clock::now() - start;
std::cout << "Answer: " << answer << ". Computation took "
<< chrono::duration_cast<chrono::milliseconds>(delta).count()
<< " ms" << std::endl;
constexpr int N=1025;
std::array<float,N> x,y,z;
benchmark::touch(x);
benchmark::touch(y);
benchmark::touch(z);
for (int i=0; i<N; ++i)
z[i]=y[i]=x[i]=i*1.e-6;
benchmark::keep(z);
delta = start - start;
for (int j=0; j<1000000; ++j) {
delta -= (chrono::high_resolution_clock::now()-start);
benchmark::touch(x);
benchmark::touch(y);
benchmark::touch(z);
for (int i=0; i<N-1; ++i)
z[i]+=y[i]*x[i];
benchmark::keep(z);
delta += (chrono::high_resolution_clock::now()-start);
}
std::cout << z[N-1] << " Computation took "
<< chrono::duration_cast<chrono::milliseconds>(delta).count()
<< " ms" << std::endl;
for (int i=0; i<N-1; ++i)
z[i]=y[i]=x[i]=i*1.e-6;
delta = start - start;
for (int j=0; j<1000000; ++j) {
for (int i=0; i<N; ++i)
z[i]=y[i]=x[i]=i*1.e-6;
delta -= (chrono::high_resolution_clock::now()-start);
benchmark::touch(x);
benchmark::touch(y);
benchmark::touch(z);
for (int i=0; i<N-1; ++i)
z[i+1]+=y[i]*z[i];
benchmark::keep(z);
delta += (chrono::high_resolution_clock::now()-start);
}
std::cout << z[N-1]<<" Computation took "
<< chrono::duration_cast<chrono::milliseconds>(delta).count()
<< " ms" << std::endl;
for (int i=0; i<N; ++i)
z[i]=y[i]=x[i]=i*1.e-6;
delta = start - start;
for (int j=0; j<1000000; ++j) {
for (int i=0; i<N-1; ++i)
z[i]=y[i]=x[i]=i*1.e-6;
delta -= (chrono::high_resolution_clock::now()-start);
benchmark::touch(x);
benchmark::touch(y);
benchmark::touch(z);
for (int i=0; i<N-1; ++i)
z[i]+=y[i]*z[i];
benchmark::keep(z);
delta += (chrono::high_resolution_clock::now()-start);
}
std::cout<< z[N-1] <<" Computation took "
<< chrono::duration_cast<chrono::milliseconds>(delta).count()
<< " ms" << std::endl;
return 0;
}
| 25.741071 | 104 | 0.511967 | Hiigaran |
84a34f1d87359a057b4b7a372dfe0819cbcb3a64 | 55,419 | cpp | C++ | llvm/lib/MC/MCDwarf.cpp | clairechingching/ScaffCC | 737ae90f85d9fe79819d66219747d27efa4fa5b9 | [
"BSD-2-Clause"
] | 3 | 2019-02-12T04:14:39.000Z | 2020-11-05T08:46:20.000Z | llvm/lib/MC/MCDwarf.cpp | clairechingching/ScaffCC | 737ae90f85d9fe79819d66219747d27efa4fa5b9 | [
"BSD-2-Clause"
] | 1 | 2020-02-22T09:59:21.000Z | 2020-02-22T09:59:21.000Z | llvm/lib/MC/MCDwarf.cpp | clairechingching/ScaffCC | 737ae90f85d9fe79819d66219747d27efa4fa5b9 | [
"BSD-2-Clause"
] | 1 | 2020-11-04T06:38:51.000Z | 2020-11-04T06:38:51.000Z | //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/config.h"
using namespace llvm;
// Given a special op, return the address skip amount (in units of
// DWARF2_LINE_MIN_INSN_LENGTH.
#define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
// The maximum address skip amount that can be encoded with a special op.
#define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
// First special line opcode - leave room for the standard opcodes.
// Note: If you want to change this, you'll have to update the
// "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
#define DWARF2_LINE_OPCODE_BASE 13
// Minimum line offset in a special line info. opcode. This value
// was chosen to give a reasonable range of values.
#define DWARF2_LINE_BASE -5
// Range of line offsets in a special line info. opcode.
#define DWARF2_LINE_RANGE 14
// Define the architecture-dependent minimum instruction length (in bytes).
// This value should be rather too small than too big.
#define DWARF2_LINE_MIN_INSN_LENGTH 1
// Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
// this routine is a nop and will be optimized away.
static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) {
if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
return AddrDelta;
if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
// TODO: report this error, but really only once.
;
}
return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
}
//
// This is called when an instruction is assembled into the specified section
// and if there is information from the last .loc directive that has yet to have
// a line entry made for it is made.
//
void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
if (!MCOS->getContext().getDwarfLocSeen())
return;
// Create a symbol at in the current section for use in the line entry.
MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
// Set the value of the symbol to use for the MCLineEntry.
MCOS->EmitLabel(LineSym);
// Get the current .loc info saved in the context.
const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
// Create a (local) line entry with the symbol and the current .loc info.
MCLineEntry LineEntry(LineSym, DwarfLoc);
// clear DwarfLocSeen saying the current .loc info is now used.
MCOS->getContext().ClearDwarfLocSeen();
// Get the MCLineSection for this section, if one does not exist for this
// section create it.
const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
MCOS->getContext().getMCLineSections();
MCLineSection *LineSection = MCLineSections.lookup(Section);
if (!LineSection) {
// Create a new MCLineSection. This will be deleted after the dwarf line
// table is created using it by iterating through the MCLineSections
// DenseMap.
LineSection = new MCLineSection;
// Save a pointer to the new LineSection into the MCLineSections DenseMap.
MCOS->getContext().addMCLineSection(Section, LineSection);
}
// Add the line entry to this section's entries.
LineSection->addLineEntry(LineEntry);
}
//
// This helper routine returns an expression of End - Start + IntVal .
//
static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
const MCSymbol &Start,
const MCSymbol &End,
int IntVal) {
MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
const MCExpr *Res =
MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
const MCExpr *RHS =
MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
const MCExpr *Res1 =
MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
const MCExpr *Res2 =
MCConstantExpr::Create(IntVal, MCOS.getContext());
const MCExpr *Res3 =
MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
return Res3;
}
//
// This emits the Dwarf line table for the specified section from the entries
// in the LineSection.
//
static inline void EmitDwarfLineTable(MCStreamer *MCOS,
const MCSection *Section,
const MCLineSection *LineSection) {
unsigned FileNum = 1;
unsigned LastLine = 1;
unsigned Column = 0;
unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
unsigned Isa = 0;
MCSymbol *LastLabel = NULL;
// Loop through each MCLineEntry and encode the dwarf line number table.
for (MCLineSection::const_iterator
it = LineSection->getMCLineEntries()->begin(),
ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
if (FileNum != it->getFileNum()) {
FileNum = it->getFileNum();
MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
MCOS->EmitULEB128IntValue(FileNum);
}
if (Column != it->getColumn()) {
Column = it->getColumn();
MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
MCOS->EmitULEB128IntValue(Column);
}
if (Isa != it->getIsa()) {
Isa = it->getIsa();
MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
MCOS->EmitULEB128IntValue(Isa);
}
if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
Flags = it->getFlags();
MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
}
if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
MCSymbol *Label = it->getLabel();
// At this point we want to emit/create the sequence to encode the delta in
// line numbers and the increment of the address from the previous Label
// and the current Label.
const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
asmInfo.getPointerSize());
LastLine = it->getLine();
LastLabel = Label;
}
// Emit a DW_LNE_end_sequence for the end of the section.
// Using the pointer Section create a temporary label at the end of the
// section and use that and the LastLabel to compute the address delta
// and use INT64_MAX as the line delta which is the signal that this is
// actually a DW_LNE_end_sequence.
// Switch to the section to be able to create a symbol at its end.
MCOS->SwitchSection(Section);
MCContext &context = MCOS->getContext();
// Create a symbol at the end of the section.
MCSymbol *SectionEnd = context.CreateTempSymbol();
// Set the value of the symbol, as we are at the end of the section.
MCOS->EmitLabel(SectionEnd);
// Switch back the the dwarf line section.
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
asmInfo.getPointerSize());
}
//
// This emits the Dwarf file and the line tables.
//
const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
// Switch to the section where the table will be emitted into.
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
// Create a symbol at the beginning of this section.
MCSymbol *LineStartSym = context.CreateTempSymbol();
// Set the value of the symbol, as we are at the start of the section.
MCOS->EmitLabel(LineStartSym);
// Create a symbol for the end of the section (to be set when we get there).
MCSymbol *LineEndSym = context.CreateTempSymbol();
// The first 4 bytes is the total length of the information for this
// compilation unit (not including these 4 bytes for the length).
MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
4);
// Next 2 bytes is the Version, which is Dwarf 2.
MCOS->EmitIntValue(2, 2);
// Create a symbol for the end of the prologue (to be set when we get there).
MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
// Length of the prologue, is the next 4 bytes. Which is the start of the
// section to the end of the prologue. Not including the 4 bytes for the
// total length, the 2 bytes for the version, and these 4 bytes for the
// length of the prologue.
MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
(4 + 2 + 4)),
4, 0);
// Parameters of the state machine, are next.
MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
// Standard opcode lengths
MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
// Put out the directory and file tables.
// First the directory table.
const std::vector<StringRef> &MCDwarfDirs =
context.getMCDwarfDirs();
for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
}
MCOS->EmitIntValue(0, 1); // Terminate the directory list
// Second the file table.
const std::vector<MCDwarfFile *> &MCDwarfFiles =
MCOS->getContext().getMCDwarfFiles();
for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
// the Directory num
MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
MCOS->EmitIntValue(0, 1); // filesize (always 0)
}
MCOS->EmitIntValue(0, 1); // Terminate the file list
// This is the end of the prologue, so set the value of the symbol at the
// end of the prologue (that was used in a previous expression).
MCOS->EmitLabel(ProEndSym);
// Put out the line tables.
const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
MCOS->getContext().getMCLineSections();
const std::vector<const MCSection *> &MCLineSectionOrder =
MCOS->getContext().getMCLineSectionOrder();
for (std::vector<const MCSection*>::const_iterator it =
MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
++it) {
const MCSection *Sec = *it;
const MCLineSection *Line = MCLineSections.lookup(Sec);
EmitDwarfLineTable(MCOS, Sec, Line);
// Now delete the MCLineSections that were created in MCLineEntry::Make()
// and used to emit the line table.
delete Line;
}
if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
&& MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
// The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
// it requires:
// total_length >= prologue_length + 10
// We are 4 bytes short, since we have total_length = 51 and
// prologue_length = 45
// The regular end_sequence should be sufficient.
MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
}
// This is the end of the section, so set the value of the symbol at the end
// of this section (that was used in a previous expression).
MCOS->EmitLabel(LineEndSym);
return LineStartSym;
}
/// Utility function to write the encoding to an object writer.
void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
uint64_t AddrDelta) {
SmallString<256> Tmp;
raw_svector_ostream OS(Tmp);
MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
OW->WriteBytes(OS.str());
}
/// Utility function to emit the encoding to a streamer.
void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
uint64_t AddrDelta) {
SmallString<256> Tmp;
raw_svector_ostream OS(Tmp);
MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
}
/// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
raw_ostream &OS) {
uint64_t Temp, Opcode;
bool NeedCopy = false;
// Scale the address delta by the minimum instruction length.
AddrDelta = ScaleAddrDelta(AddrDelta);
// A LineDelta of INT64_MAX is a signal that this is actually a
// DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
// end_sequence to emit the matrix entry.
if (LineDelta == INT64_MAX) {
if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
OS << char(dwarf::DW_LNS_const_add_pc);
else {
OS << char(dwarf::DW_LNS_advance_pc);
MCObjectWriter::EncodeULEB128(AddrDelta, OS);
}
OS << char(dwarf::DW_LNS_extended_op);
OS << char(1);
OS << char(dwarf::DW_LNE_end_sequence);
return;
}
// Bias the line delta by the base.
Temp = LineDelta - DWARF2_LINE_BASE;
// If the line increment is out of range of a special opcode, we must encode
// it with DW_LNS_advance_line.
if (Temp >= DWARF2_LINE_RANGE) {
OS << char(dwarf::DW_LNS_advance_line);
MCObjectWriter::EncodeSLEB128(LineDelta, OS);
LineDelta = 0;
Temp = 0 - DWARF2_LINE_BASE;
NeedCopy = true;
}
// Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
if (LineDelta == 0 && AddrDelta == 0) {
OS << char(dwarf::DW_LNS_copy);
return;
}
// Bias the opcode by the special opcode base.
Temp += DWARF2_LINE_OPCODE_BASE;
// Avoid overflow when addr_delta is large.
if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
// Try using a special opcode.
Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
if (Opcode <= 255) {
OS << char(Opcode);
return;
}
// Try using DW_LNS_const_add_pc followed by special op.
Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
if (Opcode <= 255) {
OS << char(dwarf::DW_LNS_const_add_pc);
OS << char(Opcode);
return;
}
}
// Otherwise use DW_LNS_advance_pc.
OS << char(dwarf::DW_LNS_advance_pc);
MCObjectWriter::EncodeULEB128(AddrDelta, OS);
if (NeedCopy)
OS << char(dwarf::DW_LNS_copy);
else
OS << char(Temp);
}
void MCDwarfFile::print(raw_ostream &OS) const {
OS << '"' << getName() << '"';
}
void MCDwarfFile::dump() const {
print(dbgs());
}
// Utility function to write a tuple for .debug_abbrev.
static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
MCOS->EmitULEB128IntValue(Name);
MCOS->EmitULEB128IntValue(Form);
}
// When generating dwarf for assembly source files this emits
// the data for .debug_abbrev section which contains three DIEs.
static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
// DW_TAG_compile_unit DIE abbrev (1).
MCOS->EmitULEB128IntValue(1);
MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
if (!DwarfDebugFlags.empty())
EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
EmitAbbrev(MCOS, 0, 0);
// DW_TAG_label DIE abbrev (2).
MCOS->EmitULEB128IntValue(2);
MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
EmitAbbrev(MCOS, 0, 0);
// DW_TAG_unspecified_parameters DIE abbrev (3).
MCOS->EmitULEB128IntValue(3);
MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
EmitAbbrev(MCOS, 0, 0);
// Terminate the abbreviations for this compilation unit.
MCOS->EmitIntValue(0, 1);
}
// When generating dwarf for assembly source files this emits the data for
// .debug_aranges section. Which contains a header and a table of pairs of
// PointerSize'ed values for the address and size of section(s) with line table
// entries (just the default .text in our case) and a terminating pair of zeros.
static void EmitGenDwarfAranges(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
// Create a symbol at the end of the section that we are creating the dwarf
// debugging info to use later in here as part of the expression to calculate
// the size of the section for the table.
MCOS->SwitchSection(context.getGenDwarfSection());
MCSymbol *SectionEndSym = context.CreateTempSymbol();
MCOS->EmitLabel(SectionEndSym);
context.setGenDwarfSectionEndSym(SectionEndSym);
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
// This will be the length of the .debug_aranges section, first account for
// the size of each item in the header (see below where we emit these items).
int Length = 4 + 2 + 4 + 1 + 1;
// Figure the padding after the header before the table of address and size
// pairs who's values are PointerSize'ed.
const MCAsmInfo &asmInfo = context.getAsmInfo();
int AddrSize = asmInfo.getPointerSize();
int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
if (Pad == 2 * AddrSize)
Pad = 0;
Length += Pad;
// Add the size of the pair of PointerSize'ed values for the address and size
// of the one default .text section we have in the table.
Length += 2 * AddrSize;
// And the pair of terminating zeros.
Length += 2 * AddrSize;
// Emit the header for this section.
// The 4 byte length not including the 4 byte value for the length.
MCOS->EmitIntValue(Length - 4, 4);
// The 2 byte version, which is 2.
MCOS->EmitIntValue(2, 2);
// The 4 byte offset to the compile unit in the .debug_info from the start
// of the .debug_info, it is at the start of that section so this is zero.
MCOS->EmitIntValue(0, 4);
// The 1 byte size of an address.
MCOS->EmitIntValue(AddrSize, 1);
// The 1 byte size of a segment descriptor, we use a value of zero.
MCOS->EmitIntValue(0, 1);
// Align the header with the padding if needed, before we put out the table.
for(int i = 0; i < Pad; i++)
MCOS->EmitIntValue(0, 1);
// Now emit the table of pairs of PointerSize'ed values for the section(s)
// address and size, in our case just the one default .text section.
const MCExpr *Addr = MCSymbolRefExpr::Create(
context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
*context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
MCOS->EmitAbsValue(Addr, AddrSize);
MCOS->EmitAbsValue(Size, AddrSize);
// And finally the pair of terminating zeros.
MCOS->EmitIntValue(0, AddrSize);
MCOS->EmitIntValue(0, AddrSize);
}
// When generating dwarf for assembly source files this emits the data for
// .debug_info section which contains three parts. The header, the compile_unit
// DIE and a list of label DIEs.
static void EmitGenDwarfInfo(MCStreamer *MCOS,
const MCSymbol *AbbrevSectionSymbol,
const MCSymbol *LineSectionSymbol) {
MCContext &context = MCOS->getContext();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
// Create a symbol at the start and end of this section used in here for the
// expression to calculate the length in the header.
MCSymbol *InfoStart = context.CreateTempSymbol();
MCOS->EmitLabel(InfoStart);
MCSymbol *InfoEnd = context.CreateTempSymbol();
// First part: the header.
// The 4 byte total length of the information for this compilation unit, not
// including these 4 bytes.
const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
MCOS->EmitAbsValue(Length, 4);
// The 2 byte DWARF version, which is 2.
MCOS->EmitIntValue(2, 2);
// The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
// it is at the start of that section so this is zero.
if (AbbrevSectionSymbol) {
MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
} else {
MCOS->EmitIntValue(0, 4);
}
const MCAsmInfo &asmInfo = context.getAsmInfo();
int AddrSize = asmInfo.getPointerSize();
// The 1 byte size of an address.
MCOS->EmitIntValue(AddrSize, 1);
// Second part: the compile_unit DIE.
// The DW_TAG_compile_unit DIE abbrev (1).
MCOS->EmitULEB128IntValue(1);
// DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
// which is at the start of that section so this is zero.
if (LineSectionSymbol) {
MCOS->EmitSymbolValue(LineSectionSymbol, 4);
} else {
MCOS->EmitIntValue(0, 4);
}
// AT_low_pc, the first address of the default .text section.
const MCExpr *Start = MCSymbolRefExpr::Create(
context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
MCOS->EmitAbsValue(Start, AddrSize);
// AT_high_pc, the last address of the default .text section.
const MCExpr *End = MCSymbolRefExpr::Create(
context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
MCOS->EmitAbsValue(End, AddrSize);
// AT_name, the name of the source file. Reconstruct from the first directory
// and file table entries.
const std::vector<StringRef> &MCDwarfDirs =
context.getMCDwarfDirs();
if (MCDwarfDirs.size() > 0) {
MCOS->EmitBytes(MCDwarfDirs[0], 0);
MCOS->EmitBytes("/", 0);
}
const std::vector<MCDwarfFile *> &MCDwarfFiles =
MCOS->getContext().getMCDwarfFiles();
MCOS->EmitBytes(MCDwarfFiles[1]->getName(), 0);
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
// AT_comp_dir, the working directory the assembly was done in.
llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
MCOS->EmitBytes(StringRef(CWD.c_str()), 0);
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
// AT_APPLE_flags, the command line arguments of the assembler tool.
StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
if (!DwarfDebugFlags.empty()){
MCOS->EmitBytes(DwarfDebugFlags, 0);
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
}
// AT_producer, the version of the assembler tool.
MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "), 0);
MCOS->EmitBytes(StringRef(PACKAGE_VERSION), 0);
MCOS->EmitBytes(StringRef(")"), 0);
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
// AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
// draft has no standard code for assembler.
MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
// Third part: the list of label DIEs.
// Loop on saved info for dwarf labels and create the DIEs for them.
const std::vector<const MCGenDwarfLabelEntry *> &Entries =
MCOS->getContext().getMCGenDwarfLabelEntries();
for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
Entries.begin(), ie = Entries.end(); it != ie;
++it) {
const MCGenDwarfLabelEntry *Entry = *it;
// The DW_TAG_label DIE abbrev (2).
MCOS->EmitULEB128IntValue(2);
// AT_name, of the label without any leading underbar.
MCOS->EmitBytes(Entry->getName(), 0);
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
// AT_decl_file, index into the file table.
MCOS->EmitIntValue(Entry->getFileNumber(), 4);
// AT_decl_line, source line number.
MCOS->EmitIntValue(Entry->getLineNumber(), 4);
// AT_low_pc, start address of the label.
const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
MCSymbolRefExpr::VK_None, context);
MCOS->EmitAbsValue(AT_low_pc, AddrSize);
// DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
MCOS->EmitIntValue(0, 1);
// The DW_TAG_unspecified_parameters DIE abbrev (3).
MCOS->EmitULEB128IntValue(3);
// Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
MCOS->EmitIntValue(0, 1);
}
// Deallocate the MCGenDwarfLabelEntry classes that saved away the info
// for the dwarf labels.
for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
Entries.begin(), ie = Entries.end(); it != ie;
++it) {
const MCGenDwarfLabelEntry *Entry = *it;
delete Entry;
}
// Add the NULL DIE terminating the Compile Unit DIE's.
MCOS->EmitIntValue(0, 1);
// Now set the value of the symbol at the end of the info section.
MCOS->EmitLabel(InfoEnd);
}
//
// When generating dwarf for assembly source files this emits the Dwarf
// sections.
//
void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
// Create the dwarf sections in this order (.debug_line already created).
MCContext &context = MCOS->getContext();
const MCAsmInfo &AsmInfo = context.getAsmInfo();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
MCSymbol *AbbrevSectionSymbol;
if (AsmInfo.doesDwarfRequireRelocationForSectionOffset()) {
AbbrevSectionSymbol = context.CreateTempSymbol();
MCOS->EmitLabel(AbbrevSectionSymbol);
} else {
AbbrevSectionSymbol = NULL;
LineSectionSymbol = NULL;
}
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
// If there are no line table entries then do not emit any section contents.
if (context.getMCLineSections().empty())
return;
// Output the data for .debug_aranges section.
EmitGenDwarfAranges(MCOS);
// Output the data for .debug_abbrev section.
EmitGenDwarfAbbrev(MCOS);
// Output the data for .debug_info section.
EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
}
//
// When generating dwarf for assembly source files this is called when symbol
// for a label is created. If this symbol is not a temporary and is in the
// section that dwarf is being generated for, save the needed info to create
// a dwarf label.
//
void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
SourceMgr &SrcMgr, SMLoc &Loc) {
// We won't create dwarf labels for temporary symbols or symbols not in
// the default text.
if (Symbol->isTemporary())
return;
MCContext &context = MCOS->getContext();
if (context.getGenDwarfSection() != MCOS->getCurrentSection())
return;
// The dwarf label's name does not have the symbol name's leading
// underbar if any.
StringRef Name = Symbol->getName();
if (Name.startswith("_"))
Name = Name.substr(1, Name.size()-1);
// Get the dwarf file number to be used for the dwarf label.
unsigned FileNumber = context.getGenDwarfFileNumber();
// Finding the line number is the expensive part which is why we just don't
// pass it in as for some symbols we won't create a dwarf label.
int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
// We create a temporary symbol for use for the AT_high_pc and AT_low_pc
// values so that they don't have things like an ARM thumb bit from the
// original symbol. So when used they won't get a low bit set after
// relocation.
MCSymbol *Label = context.CreateTempSymbol();
MCOS->EmitLabel(Label);
// Create and entry for the info and add it to the other entries.
MCGenDwarfLabelEntry *Entry =
new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
}
static int getDataAlignmentFactor(MCStreamer &streamer) {
MCContext &context = streamer.getContext();
const MCAsmInfo &asmInfo = context.getAsmInfo();
int size = asmInfo.getPointerSize();
if (asmInfo.isStackGrowthDirectionUp())
return size;
else
return -size;
}
static unsigned getSizeForEncoding(MCStreamer &streamer,
unsigned symbolEncoding) {
MCContext &context = streamer.getContext();
unsigned format = symbolEncoding & 0x0f;
switch (format) {
default: llvm_unreachable("Unknown Encoding");
case dwarf::DW_EH_PE_absptr:
case dwarf::DW_EH_PE_signed:
return context.getAsmInfo().getPointerSize();
case dwarf::DW_EH_PE_udata2:
case dwarf::DW_EH_PE_sdata2:
return 2;
case dwarf::DW_EH_PE_udata4:
case dwarf::DW_EH_PE_sdata4:
return 4;
case dwarf::DW_EH_PE_udata8:
case dwarf::DW_EH_PE_sdata8:
return 8;
}
}
static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol,
unsigned symbolEncoding, const char *comment = 0) {
MCContext &context = streamer.getContext();
const MCAsmInfo &asmInfo = context.getAsmInfo();
const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol,
symbolEncoding,
streamer);
unsigned size = getSizeForEncoding(streamer, symbolEncoding);
if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
streamer.EmitAbsValue(v, size);
}
static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
unsigned symbolEncoding) {
MCContext &context = streamer.getContext();
const MCAsmInfo &asmInfo = context.getAsmInfo();
const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol,
symbolEncoding,
streamer);
unsigned size = getSizeForEncoding(streamer, symbolEncoding);
streamer.EmitValue(v, size);
}
static const MachineLocation TranslateMachineLocation(
const MCRegisterInfo &MRI,
const MachineLocation &Loc) {
unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ?
MachineLocation::VirtualFP :
unsigned(MRI.getDwarfRegNum(Loc.getReg(), true));
const MachineLocation &NewLoc = Loc.isReg() ?
MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset());
return NewLoc;
}
namespace {
class FrameEmitterImpl {
int CFAOffset;
int CIENum;
bool UsingCFI;
bool IsEH;
const MCSymbol *SectionStart;
public:
FrameEmitterImpl(bool usingCFI, bool isEH)
: CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
SectionStart(0) {}
void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
/// EmitCompactUnwind - Emit the unwind information in a compact way. If
/// we're successful, return 'true'. Otherwise, return 'false' and it will
/// emit the normal CIE and FDE.
bool EmitCompactUnwind(MCStreamer &streamer,
const MCDwarfFrameInfo &frame);
const MCSymbol &EmitCIE(MCStreamer &streamer,
const MCSymbol *personality,
unsigned personalityEncoding,
const MCSymbol *lsda,
bool IsSignalFrame,
unsigned lsdaEncoding);
MCSymbol *EmitFDE(MCStreamer &streamer,
const MCSymbol &cieStart,
const MCDwarfFrameInfo &frame);
void EmitCFIInstructions(MCStreamer &streamer,
const std::vector<MCCFIInstruction> &Instrs,
MCSymbol *BaseLabel);
void EmitCFIInstruction(MCStreamer &Streamer,
const MCCFIInstruction &Instr);
};
} // end anonymous namespace
static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
StringRef Prefix) {
if (Streamer.isVerboseAsm()) {
const char *EncStr;
switch (Encoding) {
default: EncStr = "<unknown encoding>"; break;
case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
EncStr = "pcrel udata4";
break;
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
EncStr = "pcrel sdata4";
break;
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
EncStr = "pcrel udata8";
break;
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
EncStr = "screl sdata8";
break;
case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
EncStr = "indirect pcrel udata4";
break;
case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
EncStr = "indirect pcrel sdata4";
break;
case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
EncStr = "indirect pcrel udata8";
break;
case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
EncStr = "indirect pcrel sdata8";
break;
}
Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
}
Streamer.EmitIntValue(Encoding, 1);
}
void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
const MCCFIInstruction &Instr) {
int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
bool VerboseAsm = Streamer.isVerboseAsm();
switch (Instr.getOperation()) {
case MCCFIInstruction::Move:
case MCCFIInstruction::RelMove: {
const MachineLocation &Dst = Instr.getDestination();
const MachineLocation &Src = Instr.getSource();
const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove;
// If advancing cfa.
if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
if (Src.getReg() == MachineLocation::VirtualFP) {
if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset");
Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
} else {
if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa");
Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
if (VerboseAsm) Streamer.AddComment(Twine("Reg ") +
Twine(Src.getReg()));
Streamer.EmitULEB128IntValue(Src.getReg());
}
if (IsRelative)
CFAOffset += Src.getOffset();
else
CFAOffset = -Src.getOffset();
if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
Streamer.EmitULEB128IntValue(CFAOffset);
return;
}
if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) {
assert(Dst.isReg() && "Machine move not supported yet.");
if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register");
Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg()));
Streamer.EmitULEB128IntValue(Dst.getReg());
return;
}
unsigned Reg = Src.getReg();
int Offset = Dst.getOffset();
if (IsRelative)
Offset -= CFAOffset;
Offset = Offset / dataAlignmentFactor;
if (Offset < 0) {
if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
Streamer.EmitULEB128IntValue(Reg);
if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
Streamer.EmitSLEB128IntValue(Offset);
} else if (Reg < 64) {
if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
Twine(Reg) + ")");
Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
Streamer.EmitULEB128IntValue(Offset);
} else {
if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
Streamer.EmitULEB128IntValue(Reg);
if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
Streamer.EmitULEB128IntValue(Offset);
}
return;
}
case MCCFIInstruction::RememberState:
if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
return;
case MCCFIInstruction::RestoreState:
if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
return;
case MCCFIInstruction::SameValue: {
unsigned Reg = Instr.getDestination().getReg();
if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
Streamer.EmitULEB128IntValue(Reg);
return;
}
case MCCFIInstruction::Restore: {
unsigned Reg = Instr.getDestination().getReg();
if (VerboseAsm) {
Streamer.AddComment("DW_CFA_restore");
Streamer.AddComment(Twine("Reg ") + Twine(Reg));
}
Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
return;
}
case MCCFIInstruction::Escape:
if (VerboseAsm) Streamer.AddComment("Escape bytes");
Streamer.EmitBytes(Instr.getValues(), 0);
return;
}
llvm_unreachable("Unhandled case in switch");
}
/// EmitFrameMoves - Emit frame instructions to describe the layout of the
/// frame.
void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
const std::vector<MCCFIInstruction> &Instrs,
MCSymbol *BaseLabel) {
for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
const MCCFIInstruction &Instr = Instrs[i];
MCSymbol *Label = Instr.getLabel();
// Throw out move if the label is invalid.
if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
// Advance row if new location.
if (BaseLabel && Label) {
MCSymbol *ThisSym = Label;
if (ThisSym != BaseLabel) {
if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
BaseLabel = ThisSym;
}
}
EmitCFIInstruction(streamer, Instr);
}
}
/// EmitCompactUnwind - Emit the unwind information in a compact way. If we're
/// successful, return 'true'. Otherwise, return 'false' and it will emit the
/// normal CIE and FDE.
bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
const MCDwarfFrameInfo &Frame) {
MCContext &Context = Streamer.getContext();
const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
bool VerboseAsm = Streamer.isVerboseAsm();
// range-start range-length compact-unwind-enc personality-func lsda
// _foo LfooEnd-_foo 0x00000023 0 0
// _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
//
// .section __LD,__compact_unwind,regular,debug
//
// # compact unwind for _foo
// .quad _foo
// .set L1,LfooEnd-_foo
// .long L1
// .long 0x01010001
// .quad 0
// .quad 0
//
// # compact unwind for _bar
// .quad _bar
// .set L2,LbarEnd-_bar
// .long L2
// .long 0x01020011
// .quad __gxx_personality
// .quad except_tab1
uint32_t Encoding = Frame.CompactUnwindEncoding;
if (!Encoding) return false;
// The encoding needs to know we have an LSDA.
if (Frame.Lsda)
Encoding |= 0x40000000;
Streamer.SwitchSection(MOFI->getCompactUnwindSection());
// Range Start
unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
if (VerboseAsm) Streamer.AddComment("Range Start");
Streamer.EmitSymbolValue(Frame.Function, Size);
// Range Length
const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
*Frame.End, 0);
if (VerboseAsm) Streamer.AddComment("Range Length");
Streamer.EmitAbsValue(Range, 4);
// Compact Encoding
Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
Twine::utohexstr(Encoding));
Streamer.EmitIntValue(Encoding, Size);
// Personality Function
Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
if (VerboseAsm) Streamer.AddComment("Personality Function");
if (Frame.Personality)
Streamer.EmitSymbolValue(Frame.Personality, Size);
else
Streamer.EmitIntValue(0, Size); // No personality fn
// LSDA
Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
if (VerboseAsm) Streamer.AddComment("LSDA");
if (Frame.Lsda)
Streamer.EmitSymbolValue(Frame.Lsda, Size);
else
Streamer.EmitIntValue(0, Size); // No LSDA
return true;
}
const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
const MCSymbol *personality,
unsigned personalityEncoding,
const MCSymbol *lsda,
bool IsSignalFrame,
unsigned lsdaEncoding) {
MCContext &context = streamer.getContext();
const MCRegisterInfo &MRI = context.getRegisterInfo();
const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
bool verboseAsm = streamer.isVerboseAsm();
MCSymbol *sectionStart;
if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
sectionStart = context.CreateTempSymbol();
else
sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
streamer.EmitLabel(sectionStart);
CIENum++;
MCSymbol *sectionEnd = context.CreateTempSymbol();
// Length
const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
*sectionEnd, 4);
if (verboseAsm) streamer.AddComment("CIE Length");
streamer.EmitAbsValue(Length, 4);
// CIE ID
unsigned CIE_ID = IsEH ? 0 : -1;
if (verboseAsm) streamer.AddComment("CIE ID Tag");
streamer.EmitIntValue(CIE_ID, 4);
// Version
if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
// Augmentation String
SmallString<8> Augmentation;
if (IsEH) {
if (verboseAsm) streamer.AddComment("CIE Augmentation");
Augmentation += "z";
if (personality)
Augmentation += "P";
if (lsda)
Augmentation += "L";
Augmentation += "R";
if (IsSignalFrame)
Augmentation += "S";
streamer.EmitBytes(Augmentation.str(), 0);
}
streamer.EmitIntValue(0, 1);
// Code Alignment Factor
if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
streamer.EmitULEB128IntValue(1);
// Data Alignment Factor
if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
// Return Address Register
if (verboseAsm) streamer.AddComment("CIE Return Address Column");
streamer.EmitULEB128IntValue(MRI.getDwarfRegNum(MRI.getRARegister(), true));
// Augmentation Data Length (optional)
unsigned augmentationLength = 0;
if (IsEH) {
if (personality) {
// Personality Encoding
augmentationLength += 1;
// Personality
augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
}
if (lsda)
augmentationLength += 1;
// Encoding of the FDE pointers
augmentationLength += 1;
if (verboseAsm) streamer.AddComment("Augmentation Size");
streamer.EmitULEB128IntValue(augmentationLength);
// Augmentation Data (optional)
if (personality) {
// Personality Encoding
EmitEncodingByte(streamer, personalityEncoding,
"Personality Encoding");
// Personality
if (verboseAsm) streamer.AddComment("Personality");
EmitPersonality(streamer, *personality, personalityEncoding);
}
if (lsda)
EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
// Encoding of the FDE pointers
EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
"FDE Encoding");
}
// Initial Instructions
const MCAsmInfo &MAI = context.getAsmInfo();
const std::vector<MachineMove> &Moves = MAI.getInitialFrameState();
std::vector<MCCFIInstruction> Instructions;
for (int i = 0, n = Moves.size(); i != n; ++i) {
MCSymbol *Label = Moves[i].getLabel();
const MachineLocation &Dst =
TranslateMachineLocation(MRI, Moves[i].getDestination());
const MachineLocation &Src =
TranslateMachineLocation(MRI, Moves[i].getSource());
MCCFIInstruction Inst(Label, Dst, Src);
Instructions.push_back(Inst);
}
EmitCFIInstructions(streamer, Instructions, NULL);
// Padding
streamer.EmitValueToAlignment(IsEH
? 4 : context.getAsmInfo().getPointerSize());
streamer.EmitLabel(sectionEnd);
return *sectionStart;
}
MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
const MCSymbol &cieStart,
const MCDwarfFrameInfo &frame) {
MCContext &context = streamer.getContext();
MCSymbol *fdeStart = context.CreateTempSymbol();
MCSymbol *fdeEnd = context.CreateTempSymbol();
const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
bool verboseAsm = streamer.isVerboseAsm();
if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
MCSymbol *EHSym =
context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
streamer.EmitEHSymAttributes(frame.Function, EHSym);
streamer.EmitLabel(EHSym);
}
// Length
const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
if (verboseAsm) streamer.AddComment("FDE Length");
streamer.EmitAbsValue(Length, 4);
streamer.EmitLabel(fdeStart);
// CIE Pointer
const MCAsmInfo &asmInfo = context.getAsmInfo();
if (IsEH) {
const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
0);
if (verboseAsm) streamer.AddComment("FDE CIE Offset");
streamer.EmitAbsValue(offset, 4);
} else if (!asmInfo.doesDwarfRequireRelocationForSectionOffset()) {
const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
cieStart, 0);
streamer.EmitAbsValue(offset, 4);
} else {
streamer.EmitSymbolValue(&cieStart, 4);
}
unsigned fdeEncoding = MOFI->getFDEEncoding(UsingCFI);
unsigned size = getSizeForEncoding(streamer, fdeEncoding);
// PC Begin
unsigned PCBeginEncoding = IsEH ? fdeEncoding :
(unsigned)dwarf::DW_EH_PE_absptr;
unsigned PCBeginSize = getSizeForEncoding(streamer, PCBeginEncoding);
EmitSymbol(streamer, *frame.Begin, PCBeginEncoding, "FDE initial location");
// PC Range
const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
*frame.End, 0);
if (verboseAsm) streamer.AddComment("FDE address range");
streamer.EmitAbsValue(Range, size);
if (IsEH) {
// Augmentation Data Length
unsigned augmentationLength = 0;
if (frame.Lsda)
augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
if (verboseAsm) streamer.AddComment("Augmentation size");
streamer.EmitULEB128IntValue(augmentationLength);
// Augmentation Data
if (frame.Lsda)
EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding,
"Language Specific Data Area");
}
// Call Frame Instructions
EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
// Padding
streamer.EmitValueToAlignment(PCBeginSize);
return fdeEnd;
}
namespace {
struct CIEKey {
static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false); }
static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false); }
CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
unsigned LsdaEncoding_, bool IsSignalFrame_) :
Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_) {
}
const MCSymbol* Personality;
unsigned PersonalityEncoding;
unsigned LsdaEncoding;
bool IsSignalFrame;
};
}
namespace llvm {
template <>
struct DenseMapInfo<CIEKey> {
static CIEKey getEmptyKey() {
return CIEKey::getEmptyKey();
}
static CIEKey getTombstoneKey() {
return CIEKey::getTombstoneKey();
}
static unsigned getHashValue(const CIEKey &Key) {
return static_cast<unsigned>(hash_combine(Key.Personality,
Key.PersonalityEncoding,
Key.LsdaEncoding,
Key.IsSignalFrame));
}
static bool isEqual(const CIEKey &LHS,
const CIEKey &RHS) {
return LHS.Personality == RHS.Personality &&
LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
LHS.LsdaEncoding == RHS.LsdaEncoding &&
LHS.IsSignalFrame == RHS.IsSignalFrame;
}
};
}
void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer,
bool UsingCFI,
bool IsEH) {
MCContext &Context = Streamer.getContext();
MCObjectFileInfo *MOFI =
const_cast<MCObjectFileInfo*>(Context.getObjectFileInfo());
FrameEmitterImpl Emitter(UsingCFI, IsEH);
ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
// Emit the compact unwind info if available.
if (IsEH && MOFI->getCompactUnwindSection())
for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) {
const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i);
if (Frame.CompactUnwindEncoding)
Emitter.EmitCompactUnwind(Streamer, Frame);
}
const MCSection &Section = IsEH ? *MOFI->getEHFrameSection() :
*MOFI->getDwarfFrameSection();
Streamer.SwitchSection(&Section);
MCSymbol *SectionStart = Context.CreateTempSymbol();
Streamer.EmitLabel(SectionStart);
Emitter.setSectionStart(SectionStart);
MCSymbol *FDEEnd = NULL;
DenseMap<CIEKey, const MCSymbol*> CIEStarts;
const MCSymbol *DummyDebugKey = NULL;
for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
const MCDwarfFrameInfo &Frame = FrameArray[i];
CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
Frame.LsdaEncoding, Frame.IsSignalFrame);
const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
if (!CIEStart)
CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
Frame.PersonalityEncoding, Frame.Lsda,
Frame.IsSignalFrame,
Frame.LsdaEncoding);
FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
if (i != n - 1)
Streamer.EmitLabel(FDEEnd);
}
Streamer.EmitValueToAlignment(Context.getAsmInfo().getPointerSize());
if (FDEEnd)
Streamer.EmitLabel(FDEEnd);
}
void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
uint64_t AddrDelta) {
SmallString<256> Tmp;
raw_svector_ostream OS(Tmp);
MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS);
Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0);
}
void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta,
raw_ostream &OS) {
// FIXME: Assumes the code alignment factor is 1.
if (AddrDelta == 0) {
} else if (isUIntN(6, AddrDelta)) {
uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
OS << Opcode;
} else if (isUInt<8>(AddrDelta)) {
OS << uint8_t(dwarf::DW_CFA_advance_loc1);
OS << uint8_t(AddrDelta);
} else if (isUInt<16>(AddrDelta)) {
// FIXME: check what is the correct behavior on a big endian machine.
OS << uint8_t(dwarf::DW_CFA_advance_loc2);
OS << uint8_t( AddrDelta & 0xff);
OS << uint8_t((AddrDelta >> 8) & 0xff);
} else {
// FIXME: check what is the correct behavior on a big endian machine.
assert(isUInt<32>(AddrDelta));
OS << uint8_t(dwarf::DW_CFA_advance_loc4);
OS << uint8_t( AddrDelta & 0xff);
OS << uint8_t((AddrDelta >> 8) & 0xff);
OS << uint8_t((AddrDelta >> 16) & 0xff);
OS << uint8_t((AddrDelta >> 24) & 0xff);
}
}
| 37.880383 | 80 | 0.67614 | clairechingching |
84a52c7a97a583936d15231606e92eca3fe64d19 | 824 | cpp | C++ | Geeks For Geeks Solutions/HashMap/Largest subarray with 0 sum.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 169 | 2021-05-30T10:02:19.000Z | 2022-03-27T18:09:32.000Z | Geeks For Geeks Solutions/HashMap/Largest subarray with 0 sum.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 1 | 2021-10-02T14:46:26.000Z | 2021-10-02T14:46:26.000Z | Geeks For Geeks Solutions/HashMap/Largest subarray with 0 sum.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 44 | 2021-05-30T19:56:29.000Z | 2022-03-17T14:49:00.000Z |
#include <bits/stdc++.h>
using namespace std;
int maxLen(int A[], int n);
int main()
{
int T;
cin >> T;
while (T--)
{
int N;
cin >> N;
int A[N];
for (int i = 0; i < N; i++)
cin >> A[i];
cout << maxLen(A, N) << endl;
}
}
// } Driver Code Ends
/*You are required to complete this function*/
int maxLen(int A[], int n)
{
unordered_map<int,int> mp;
int sum =0;
int ans;
int j;
for(int i=0;i<n;i++)
{
sum += A[i];
if(sum == 0)
ans = i+1 ;
else
{
if(mp.find(sum)==mp.end())
{
mp[sum] = i ;
}
else
{
j = mp[sum];
ans = max(ans,i-j);
}
}
}
return ans;
}
| 15.259259 | 46 | 0.368932 | bilwa496 |
84a65e55f53fbee746130190840ca58cb8061132 | 1,923 | cc | C++ | src/fdb5/types/TypeTime.cc | dvuckovic/fdb | c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2 | [
"Apache-2.0"
] | 5 | 2020-01-03T10:23:05.000Z | 2021-10-21T12:52:47.000Z | src/fdb5/types/TypeTime.cc | dvuckovic/fdb | c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2 | [
"Apache-2.0"
] | null | null | null | src/fdb5/types/TypeTime.cc | dvuckovic/fdb | c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2 | [
"Apache-2.0"
] | 1 | 2021-07-08T16:26:06.000Z | 2021-07-08T16:26:06.000Z | /*
* (C) Copyright 1996- ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include <iomanip>
#include "eckit/utils/Translator.h"
#include "eckit/types/Date.h"
#include "metkit/mars/MarsRequest.h"
#include "fdb5/types/TypesFactory.h"
#include "fdb5/types/TypeTime.h"
namespace fdb5 {
//----------------------------------------------------------------------------------------------------------------------
TypeTime::TypeTime(const std::string &name, const std::string &type) :
Type(name, type) {
}
TypeTime::~TypeTime() {
}
std::string TypeTime::tidy(const std::string&,
const std::string& value) const {
eckit::Translator<std::string, long> t;
long n = t(value);
if (n < 100) {
n *= 100;
}
std::ostringstream oss;
oss << std::setfill('0') << std::setw(4) << n;
return oss.str();
}
std::string TypeTime::toKey(const std::string& keyword,
const std::string& value) const {
// if value just contains a digit, add a leading zero to be compliant with eckit::Time
std::string t = value.size() < 2 ? "0"+value : value;
eckit::Time time(t);
std::ostringstream oss;
oss << std::setfill('0') << std::setw(2) << time.hours() << std::setfill('0') << std::setw(2) << time.minutes();
return oss.str();
}
void TypeTime::print(std::ostream &out) const {
out << "TypeTime[name=" << name_ << "]";
}
static TypeBuilder<TypeTime> type("Time");
//----------------------------------------------------------------------------------------------------------------------
} // namespace fdb5
| 28.279412 | 120 | 0.554862 | dvuckovic |
84a7ad34c1b7631dfbce902fcdddbbe570b70d38 | 19,099 | cpp | C++ | SoA/TestBiomeScreen.cpp | Revan1985/SoACode-Public | c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe | [
"MIT"
] | 267 | 2018-06-03T23:05:05.000Z | 2022-03-17T00:28:40.000Z | SoA/TestBiomeScreen.cpp | davidkestering/SoACode-Public | c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe | [
"MIT"
] | 16 | 2018-06-05T18:59:11.000Z | 2021-09-28T05:05:16.000Z | SoA/TestBiomeScreen.cpp | davidkestering/SoACode-Public | c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe | [
"MIT"
] | 113 | 2018-06-03T23:56:13.000Z | 2022-03-21T00:07:16.000Z | #include "stdafx.h"
#include "TestBiomeScreen.h"
#include <Vorb/ui/InputDispatcher.h>
#include <Vorb/colors.h>
#include "App.h"
#include "ChunkRenderer.h"
#include "DevConsole.h"
#include "InputMapper.h"
#include "Inputs.h"
#include "LoadTaskBlockData.h"
#include "RenderUtils.h"
#include "ShaderLoader.h"
#include "SoaEngine.h"
#include "SoAState.h"
#ifdef DEBUG
#define HORIZONTAL_CHUNKS 26
#define VERTICAL_CHUNKS 4
#else
#define HORIZONTAL_CHUNKS 26
#define VERTICAL_CHUNKS 20
#endif
TestBiomeScreen::TestBiomeScreen(const App* app, CommonState* state) :
IAppScreen<App>(app),
m_commonState(state),
m_soaState(m_commonState->state),
m_blockArrayRecycler(1000) {
}
i32 TestBiomeScreen::getNextScreen() const {
return SCREEN_INDEX_NO_SCREEN;
}
i32 TestBiomeScreen::getPreviousScreen() const {
return SCREEN_INDEX_NO_SCREEN;
}
void TestBiomeScreen::build() {
}
void TestBiomeScreen::destroy(const vui::GameTime& gameTime VORB_UNUSED) {
}
void TestBiomeScreen::onEntry(const vui::GameTime& gameTime VORB_MAYBE_UNUSED) {
// Init spritebatch and font
m_sb.init();
m_font.init("Fonts/orbitron_bold-webfont.ttf", 32);
// Init game state
SoaEngine::initState(m_commonState->state);
// Init access
m_accessor.init(&m_allocator);
// Init renderer
m_renderer.init();
{ // Init post processing
Array<vg::GBufferAttachment> attachments;
vg::GBufferAttachment att[2];
// Color
att[0].format = vg::TextureInternalFormat::RGBA16F;
att[0].pixelFormat = vg::TextureFormat::RGBA;
att[0].pixelType = vg::TexturePixelType::UNSIGNED_BYTE;
att[0].number = 1;
// Normals
att[1].format = vg::TextureInternalFormat::RGBA16F;
att[1].pixelFormat = vg::TextureFormat::RGBA;
att[1].pixelType = vg::TexturePixelType::UNSIGNED_BYTE;
att[1].number = 2;
m_hdrTarget.setSize(m_commonState->window->getWidth(), m_commonState->window->getHeight());
m_hdrTarget.init(Array<vg::GBufferAttachment>(att, 2), vg::TextureInternalFormat::RGBA8).initDepth();
// Swapchain
m_swapChain.init(m_commonState->window->getWidth(), m_commonState->window->getHeight(), vg::TextureInternalFormat::RGBA16F);
// Init the FullQuadVBO
m_commonState->quad.init();
// SSAO
m_ssaoStage.init(m_commonState->window, m_commonState->loadContext);
m_ssaoStage.load(m_commonState->loadContext);
m_ssaoStage.hook(&m_commonState->quad, m_commonState->window->getWidth(), m_commonState->window->getHeight());
// HDR
m_hdrStage.init(m_commonState->window, m_commonState->loadContext);
m_hdrStage.load(m_commonState->loadContext);
m_hdrStage.hook(&m_commonState->quad);
}
// Load test planet
PlanetGenLoader planetLoader;
m_iom.setSearchDirectory("StarSystems/Trinity/");
planetLoader.init(&m_iom);
m_genData = planetLoader.loadPlanetGenData("Moons/Aldrin/terrain_gen.yml");
if (m_genData->terrainColorPixels.data) {
m_soaState->clientState.blockTextures->setColorMap("biome", &m_genData->terrainColorPixels);
}
// Load blocks
LoadTaskBlockData blockLoader(&m_soaState->blocks,
&m_soaState->clientState.blockTextureLoader,
&m_commonState->loadContext);
blockLoader.load();
// Uploads all the needed textures
m_soaState->clientState.blockTextures->update();
m_genData->radius = 4500.0;
// Set blocks
SoaEngine::initVoxelGen(m_genData, m_soaState->blocks);
m_chunkGenerator.init(m_genData);
initHeightData();
initChunks();
printf("Generating Meshes...\n");
// Create all chunk meshes
m_mesher.init(&m_soaState->blocks);
for (auto& cv : m_chunks) {
cv.chunkMesh = m_mesher.easyCreateChunkMesh(cv.chunk, MeshTaskType::DEFAULT);
}
{ // Init the camera
m_camera.init(m_commonState->window->getAspectRatio());
m_camera.setPosition(f64v3(16.0, 17.0, 33.0));
m_camera.setDirection(f32v3(0.0f, 0.0f, -1.0f));
m_camera.setRight(f32v3(1.0f, 0.0f, 0.0f));
m_camera.setUp(f32v3(0.0f, 1.0f, 0.0f));
}
initInput();
// Initialize dev console
vui::GameWindow* window = m_commonState->window;
m_devConsoleView.init(&DevConsole::getInstance(), 5,
f32v2(20.0f, window->getHeight() - 400.0f),
window->getWidth() - 40.0f);
// Set GL state
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glClearDepth(1.0);
printf("Done.");
}
void TestBiomeScreen::onExit(const vui::GameTime& gameTime VORB_MAYBE_UNUSED) {
for (auto& cv : m_chunks) {
m_mesher.freeChunkMesh(cv.chunkMesh);
}
m_hdrTarget.dispose();
m_swapChain.dispose();
m_devConsoleView.dispose();
}
void TestBiomeScreen::update(const vui::GameTime& gameTime) {
f32 speed = 10.0f;
if (m_movingFast) speed *= 5.0f;
if (m_movingForward) {
f32v3 offset = m_camera.getDirection() * speed * (f32)gameTime.elapsed;
m_camera.offsetPosition(offset);
}
if (m_movingBack) {
f32v3 offset = m_camera.getDirection() * -speed * (f32)gameTime.elapsed;
m_camera.offsetPosition(offset);
}
if (m_movingLeft) {
f32v3 offset = m_camera.getRight() * -speed * (f32)gameTime.elapsed;
m_camera.offsetPosition(offset);
}
if (m_movingRight) {
f32v3 offset = m_camera.getRight() * speed * (f32)gameTime.elapsed;
m_camera.offsetPosition(offset);
}
if (m_movingUp) {
f32v3 offset = f32v3(0, 1, 0) * speed * (f32)gameTime.elapsed;
m_camera.offsetPosition(offset);
}
if (m_movingDown) {
f32v3 offset = f32v3(0, 1, 0) * -speed * (f32)gameTime.elapsed;
m_camera.offsetPosition(offset);
}
m_camera.update();
}
void TestBiomeScreen::draw(const vui::GameTime& gameTime VORB_UNUSED) {
// Bind the FBO
m_hdrTarget.useGeometry();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (m_wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// Opaque
m_renderer.beginOpaque(m_soaState->clientState.blockTextures->getAtlasTexture(),
f32v3(0.0f, 0.0f, -1.0f), f32v3(1.0f),
f32v3(0.3f));
for (auto& vc : m_chunks) {
if (m_camera.getFrustum().sphereInFrustum(f32v3(vc.chunkMesh->position + f64v3(CHUNK_WIDTH / 2) - m_camera.getPosition()), CHUNK_DIAGONAL_LENGTH)) {
vc.inFrustum = true;
m_renderer.drawOpaque(vc.chunkMesh, m_camera.getPosition(), m_camera.getViewProjectionMatrix());
} else {
vc.inFrustum = false;
}
}
// Cutout
m_renderer.beginCutout(m_soaState->clientState.blockTextures->getAtlasTexture(),
f32v3(0.0f, 0.0f, -1.0f), f32v3(1.0f),
f32v3(0.3f));
for (auto& vc : m_chunks) {
if (vc.inFrustum) {
m_renderer.drawCutout(vc.chunkMesh, m_camera.getPosition(), m_camera.getViewProjectionMatrix());
}
}
m_renderer.end();
if (m_wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// Post processing
m_swapChain.reset(0, m_hdrTarget.getGeometryID(), m_hdrTarget.getGeometryTexture(0), soaOptions.get(OPT_MSAA).value.i > 0, false);
// Render SSAO
m_ssaoStage.set(m_hdrTarget.getDepthTexture(), m_hdrTarget.getGeometryTexture(1), m_hdrTarget.getGeometryTexture(0), m_swapChain.getCurrent().getID());
m_ssaoStage.render(&m_camera);
m_swapChain.swap();
m_swapChain.use(0, false);
// Draw to backbuffer for the last effect
// TODO(Ben): Do we really need to clear depth here...
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDrawBuffer(GL_BACK);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_hdrTarget.getDepthTexture());
m_hdrStage.render();
// Draw UI
char buf[256];
sprintf(buf, "FPS: %.1f", m_app->getFps());
m_sb.begin();
m_sb.drawString(&m_font, buf, f32v2(30.0f), f32v2(1.0f), color::White);
m_sb.end();
m_sb.render(f32v2(m_commonState->window->getViewportDims()));
vg::DepthState::FULL.set(); // Have to restore depth
// Draw dev console
m_devConsoleView.update(0.01f);
m_devConsoleView.render(m_game->getWindow().getViewportDims());
}
void TestBiomeScreen::initHeightData() {
printf("Generating height data...\n");
m_heightData.resize(HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS);
// Init height data
m_heightGenerator.init(m_genData);
for (int z = 0; z < HORIZONTAL_CHUNKS; z++) {
for (int x = 0; x < HORIZONTAL_CHUNKS; x++) {
auto& hd = m_heightData[z * HORIZONTAL_CHUNKS + x];
for (int i = 0; i < CHUNK_WIDTH; i++) {
for (int j = 0; j < CHUNK_WIDTH; j++) {
VoxelPosition2D pos;
pos.pos.x = x * CHUNK_WIDTH + j + 3000;
pos.pos.y = z * CHUNK_WIDTH + i + 3000;
PlanetHeightData& data = hd.heightData[i * CHUNK_WIDTH + j];
m_heightGenerator.generateHeightData(data, pos);
data.temperature = 128;
data.humidity = 128;
}
}
}
}
// Get center height
f32 cHeight = m_heightData[HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS / 2].heightData[CHUNK_LAYER / 2].height;
// Center the heightmap
for (auto& hd : m_heightData) {
for (int i = 0; i < CHUNK_LAYER; i++) {
hd.heightData[i].height -= cHeight;
}
}
}
void TestBiomeScreen::initChunks() {
printf("Generating chunks...\n");
m_chunks.resize(HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS * VERTICAL_CHUNKS);
// Generate chunk data
for (size_t i = 0; i < m_chunks.size(); i++) {
ChunkPosition3D pos;
i32v3 gridPosition;
gridPosition.x = i % HORIZONTAL_CHUNKS;
gridPosition.y = i / (HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS);
gridPosition.z = (i % (HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS)) / HORIZONTAL_CHUNKS;
// Center position about origin
pos.pos.x = gridPosition.x - HORIZONTAL_CHUNKS / 2;
pos.pos.y = gridPosition.y - VERTICAL_CHUNKS / 4;
pos.pos.z = gridPosition.z - HORIZONTAL_CHUNKS / 2;
// Init parameters
ChunkID id(pos.x, pos.y, pos.z);
m_chunks[i].chunk = m_accessor.acquire(id);
m_chunks[i].chunk->init(WorldCubeFace::FACE_TOP);
m_chunks[i].gridPosition = gridPosition;
m_chunks[i].chunk->gridData = &m_heightData[i % (HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS)];
// Generate the chunk
m_chunkGenerator.generateChunk(m_chunks[i].chunk, m_chunks[i].chunk->gridData->heightData);
// Decompress to flat array
m_chunks[i].chunk->blocks.setArrayRecycler(&m_blockArrayRecycler);
m_chunks[i].chunk->blocks.changeState(vvox::VoxelStorageState::FLAT_ARRAY, m_chunks[i].chunk->dataMutex);
}
// Generate flora
std::vector<FloraNode> lNodes;
std::vector<FloraNode> wNodes;
// TODO(Ben): I know this is ugly
PreciseTimer t1;
t1.start();
for (size_t i = 0; i < m_chunks.size(); i++) {
Chunk* chunk = m_chunks[i].chunk;
m_floraGenerator.generateChunkFlora(chunk, m_heightData[i % (HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS)].heightData, lNodes, wNodes);
for (auto& node : wNodes) {
i32v3 gridPos = m_chunks[i].gridPosition;
gridPos.x += FloraGenerator::getChunkXOffset(node.chunkOffset);
gridPos.y += FloraGenerator::getChunkYOffset(node.chunkOffset);
gridPos.z += FloraGenerator::getChunkZOffset(node.chunkOffset);
if (gridPos.x >= 0 && gridPos.y >= 0 && gridPos.z >= 0
&& gridPos.x < HORIZONTAL_CHUNKS && gridPos.y < VERTICAL_CHUNKS && gridPos.z < HORIZONTAL_CHUNKS) {
Chunk* chunk = m_chunks[gridPos.x + gridPos.y * HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS + gridPos.z * HORIZONTAL_CHUNKS].chunk;
chunk->blocks.set(node.blockIndex, node.blockID);
}
}
for (auto& node : lNodes) {
i32v3 gridPos = m_chunks[i].gridPosition;
gridPos.x += FloraGenerator::getChunkXOffset(node.chunkOffset);
gridPos.y += FloraGenerator::getChunkYOffset(node.chunkOffset);
gridPos.z += FloraGenerator::getChunkZOffset(node.chunkOffset);
if (gridPos.x >= 0 && gridPos.y >= 0 && gridPos.z >= 0
&& gridPos.x < HORIZONTAL_CHUNKS && gridPos.y < VERTICAL_CHUNKS && gridPos.z < HORIZONTAL_CHUNKS) {
Chunk* chunk = m_chunks[gridPos.x + gridPos.y * HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS + gridPos.z * HORIZONTAL_CHUNKS].chunk;
if (chunk->blocks.get(node.blockIndex) == 0) {
chunk->blocks.set(node.blockIndex, node.blockID);
}
}
}
std::vector<ui16>().swap(chunk->floraToGenerate);
lNodes.clear();
wNodes.clear();
}
printf("Tree Gen Time %lf\n", t1.stop());
#define GET_INDEX(x, y, z) ((x) + (y) * HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS + (z) * HORIZONTAL_CHUNKS)
// Set neighbor pointers
for (int y = 0; y < VERTICAL_CHUNKS; y++) {
for (int z = 0; z < HORIZONTAL_CHUNKS; z++) {
for (int x = 0; x < HORIZONTAL_CHUNKS; x++) {
Chunk* chunk = m_chunks[GET_INDEX(x, y, z)].chunk;
// TODO(Ben): Release these too.
if (x > 0) {
chunk->neighbor.left = m_chunks[GET_INDEX(x - 1, y, z)].chunk.acquire();
}
if (x < HORIZONTAL_CHUNKS - 1) {
chunk->neighbor.right = m_chunks[GET_INDEX(x + 1, y, z)].chunk.acquire();
}
if (y > 0) {
chunk->neighbor.bottom = m_chunks[GET_INDEX(x, y - 1, z)].chunk.acquire();
}
if (y < VERTICAL_CHUNKS - 1) {
chunk->neighbor.top = m_chunks[GET_INDEX(x, y + 1, z)].chunk.acquire();
}
if (z > 0) {
chunk->neighbor.back = m_chunks[GET_INDEX(x, y, z - 1)].chunk.acquire();
}
if (z < HORIZONTAL_CHUNKS - 1) {
chunk->neighbor.front = m_chunks[GET_INDEX(x, y, z + 1)].chunk.acquire();
}
}
}
}
}
void TestBiomeScreen::initInput() {
m_inputMapper = new InputMapper;
initInputs(m_inputMapper);
m_mouseButtons[0] = false;
m_hooks.addAutoHook(vui::InputDispatcher::mouse.onMotion, [&](Sender s VORB_MAYBE_UNUSED, const vui::MouseMotionEvent& e) {
if (m_mouseButtons[0]) {
m_camera.rotateFromMouseAbsoluteUp(-e.dx, -e.dy, 0.01f, true);
}
});
m_hooks.addAutoHook(vui::InputDispatcher::mouse.onButtonDown, [&](Sender s VORB_MAYBE_UNUSED, const vui::MouseButtonEvent& e) {
if (e.button == vui::MouseButton::LEFT) m_mouseButtons[0] = !m_mouseButtons[0];
if (m_mouseButtons[0]) {
SDL_SetRelativeMouseMode(SDL_TRUE);
}
else {
SDL_SetRelativeMouseMode(SDL_FALSE);
}
});
m_hooks.addAutoHook(vui::InputDispatcher::key.onKeyDown, [&](Sender s VORB_MAYBE_UNUSED, const vui::KeyEvent& e) {
PlanetGenLoader planetLoader;
switch (e.keyCode) {
case VKEY_W:
m_movingForward = true;
break;
case VKEY_S:
m_movingBack = true;
break;
case VKEY_A:
m_movingLeft = true;
break;
case VKEY_D:
m_movingRight = true;
break;
case VKEY_SPACE:
m_movingUp = true;
break;
case VKEY_LSHIFT:
m_movingFast = true;
break;
case VKEY_M:
m_wireFrame = !m_wireFrame;
break;
case VKEY_LEFT:
/* if (m_activeChunk == 0) {
m_activeChunk = m_chunks.size() - 1;
} else {
m_activeChunk--;
}*/
break;
case VKEY_RIGHT:
/* m_activeChunk++;
if (m_activeChunk >= (int)m_chunks.size()) m_activeChunk = 0;*/
break;
case VKEY_F10:
// Reload meshes
// TODO(Ben): Destroy meshes
for (auto& cv : m_chunks) {
m_mesher.freeChunkMesh(cv.chunkMesh);
cv.chunkMesh = m_mesher.easyCreateChunkMesh(cv.chunk, MeshTaskType::DEFAULT);
}
break;
case VKEY_F11:
// Reload shaders
m_renderer.dispose();
m_renderer.init();
m_ssaoStage.reloadShaders();
break;
case VKEY_F12:
// Reload world
delete m_genData;
planetLoader.init(&m_iom);
m_genData = planetLoader.loadPlanetGenData("Planets/Aldrin/terrain_gen.yml");
m_genData->radius = 4500.0;
// Set blocks
SoaEngine::initVoxelGen(m_genData, m_soaState->blocks);
m_chunkGenerator.init(m_genData);
for (auto& cv : m_chunks) {
m_mesher.freeChunkMesh(cv.chunkMesh);
cv.chunk.release();
}
initHeightData();
initChunks();
printf("Generating Meshes...\n");
// Create all chunk meshes
m_mesher.init(&m_soaState->blocks);
for (auto& cv : m_chunks) {
cv.chunkMesh = m_mesher.easyCreateChunkMesh(cv.chunk, MeshTaskType::DEFAULT);
}
break;
}
});
m_hooks.addAutoHook(vui::InputDispatcher::key.onKeyUp, [&](Sender s VORB_MAYBE_UNUSED, const vui::KeyEvent& e) {
switch (e.keyCode) {
case VKEY_W:
m_movingForward = false;
break;
case VKEY_S:
m_movingBack = false;
break;
case VKEY_A:
m_movingLeft = false;
break;
case VKEY_D:
m_movingRight = false;
break;
case VKEY_SPACE:
m_movingUp = false;
break;
case VKEY_LSHIFT:
m_movingFast = false;
break;
}
});
// Dev console
m_hooks.addAutoHook(m_inputMapper->get(INPUT_DEV_CONSOLE).downEvent, [](Sender s VORB_MAYBE_UNUSED, ui32 a VORB_MAYBE_UNUSED) {
DevConsole::getInstance().toggleFocus();
});
m_inputMapper->startInput();
}
| 36.941973 | 156 | 0.591392 | Revan1985 |
84aa2b80d01d0db6875c37daed06be8580d112e4 | 73,265 | cpp | C++ | Unity-Project/App-HL2/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs47.cpp | JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity | 6e13b31a0b053443b9c93267d8f174f1554e79dd | [
"CC-BY-4.0",
"MIT"
] | 1 | 2021-06-01T19:33:53.000Z | 2021-06-01T19:33:53.000Z | Unity-Project/App-HL2/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs47.cpp | JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity | 6e13b31a0b053443b9c93267d8f174f1554e79dd | [
"CC-BY-4.0",
"MIT"
] | null | null | null | Unity-Project/App-HL2/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs47.cpp | JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity | 6e13b31a0b053443b9c93267d8f174f1554e79dd | [
"CC-BY-4.0",
"MIT"
] | null | null | null | #include "pch-cpp.hpp"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <limits>
#include "vm/CachedCCWBase.h"
#include "utils/New.h"
// System.Collections.Generic.IEqualityComparer`1<WindTurbineScriptableObject>
struct IEqualityComparer_1_t754733F7B8BE7D6A482129735D41581DA4211A89;
// System.Collections.Generic.IEqualityComparer`1<System.Xml.XmlQualifiedName>
struct IEqualityComparer_1_tA3F9CEF64ED38FA56ECC5E56165286AE1376D617;
// System.Collections.Generic.Dictionary`2/KeyCollection<WindTurbineScriptableObject,UnityEngine.GameObject>
struct KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9;
// System.Collections.Generic.Dictionary`2/KeyCollection<WindTurbineScriptableObject,SiteOverviewTurbineButton>
struct KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543;
// System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Int32>
struct KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63;
// System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef>
struct KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68;
// System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl>
struct KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987;
// System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity>
struct KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122;
// System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName>
struct KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372;
// System.Collections.Generic.Dictionary`2/ValueCollection<WindTurbineScriptableObject,UnityEngine.GameObject>
struct ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942;
// System.Collections.Generic.Dictionary`2/ValueCollection<WindTurbineScriptableObject,SiteOverviewTurbineButton>
struct ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD;
// System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Int32>
struct ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E;
// System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef>
struct ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42;
// System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl>
struct ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D;
// System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity>
struct ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400;
// System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName>
struct ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E;
// System.Collections.Generic.Dictionary`2/Entry<WindTurbineScriptableObject,UnityEngine.GameObject>[]
struct EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E;
// System.Collections.Generic.Dictionary`2/Entry<WindTurbineScriptableObject,SiteOverviewTurbineButton>[]
struct EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F;
// System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Int32>[]
struct EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604;
// System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef>[]
struct EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE;
// System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl>[]
struct EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F;
// System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity>[]
struct EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221;
// System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName>[]
struct EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0;
// System.Int32[]
struct Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32;
// System.String
struct String_t;
struct IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB;
IL2CPP_EXTERN_C_BEGIN
IL2CPP_EXTERN_C_END
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Windows.UI.Xaml.Interop.IBindableIterable
struct NOVTABLE IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 : Il2CppIInspectable
{
static const Il2CppGuid IID;
virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) = 0;
};
// System.Object
// System.Collections.Generic.Dictionary`2<WindTurbineScriptableObject,UnityEngine.GameObject>
struct Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F : public RuntimeObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::buckets
Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0;
// System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries
EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E* ___entries_1;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_2;
// System.Int32 System.Collections.Generic.Dictionary`2::version
int32_t ___version_3;
// System.Int32 System.Collections.Generic.Dictionary`2::freeList
int32_t ___freeList_4;
// System.Int32 System.Collections.Generic.Dictionary`2::freeCount
int32_t ___freeCount_5;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer
RuntimeObject* ___comparer_6;
// System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys
KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9 * ___keys_7;
// System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values
ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942 * ___values_8;
// System.Object System.Collections.Generic.Dictionary`2::_syncRoot
RuntimeObject * ____syncRoot_9;
public:
inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___buckets_0)); }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; }
inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value)
{
___buckets_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value);
}
inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___entries_1)); }
inline EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E* get_entries_1() const { return ___entries_1; }
inline EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E** get_address_of_entries_1() { return &___entries_1; }
inline void set_entries_1(EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E* value)
{
___entries_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value);
}
inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___count_2)); }
inline int32_t get_count_2() const { return ___count_2; }
inline int32_t* get_address_of_count_2() { return &___count_2; }
inline void set_count_2(int32_t value)
{
___count_2 = value;
}
inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___version_3)); }
inline int32_t get_version_3() const { return ___version_3; }
inline int32_t* get_address_of_version_3() { return &___version_3; }
inline void set_version_3(int32_t value)
{
___version_3 = value;
}
inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___freeList_4)); }
inline int32_t get_freeList_4() const { return ___freeList_4; }
inline int32_t* get_address_of_freeList_4() { return &___freeList_4; }
inline void set_freeList_4(int32_t value)
{
___freeList_4 = value;
}
inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___freeCount_5)); }
inline int32_t get_freeCount_5() const { return ___freeCount_5; }
inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; }
inline void set_freeCount_5(int32_t value)
{
___freeCount_5 = value;
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value);
}
inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___keys_7)); }
inline KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9 * get_keys_7() const { return ___keys_7; }
inline KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9 ** get_address_of_keys_7() { return &___keys_7; }
inline void set_keys_7(KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9 * value)
{
___keys_7 = value;
Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value);
}
inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___values_8)); }
inline ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942 * get_values_8() const { return ___values_8; }
inline ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942 ** get_address_of_values_8() { return &___values_8; }
inline void set_values_8(ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942 * value)
{
___values_8 = value;
Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value);
}
inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ____syncRoot_9)); }
inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; }
inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; }
inline void set__syncRoot_9(RuntimeObject * value)
{
____syncRoot_9 = value;
Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value);
}
};
// System.Collections.Generic.Dictionary`2<WindTurbineScriptableObject,SiteOverviewTurbineButton>
struct Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85 : public RuntimeObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::buckets
Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0;
// System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries
EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F* ___entries_1;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_2;
// System.Int32 System.Collections.Generic.Dictionary`2::version
int32_t ___version_3;
// System.Int32 System.Collections.Generic.Dictionary`2::freeList
int32_t ___freeList_4;
// System.Int32 System.Collections.Generic.Dictionary`2::freeCount
int32_t ___freeCount_5;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer
RuntimeObject* ___comparer_6;
// System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys
KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543 * ___keys_7;
// System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values
ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD * ___values_8;
// System.Object System.Collections.Generic.Dictionary`2::_syncRoot
RuntimeObject * ____syncRoot_9;
public:
inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___buckets_0)); }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; }
inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value)
{
___buckets_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value);
}
inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___entries_1)); }
inline EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F* get_entries_1() const { return ___entries_1; }
inline EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F** get_address_of_entries_1() { return &___entries_1; }
inline void set_entries_1(EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F* value)
{
___entries_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value);
}
inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___count_2)); }
inline int32_t get_count_2() const { return ___count_2; }
inline int32_t* get_address_of_count_2() { return &___count_2; }
inline void set_count_2(int32_t value)
{
___count_2 = value;
}
inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___version_3)); }
inline int32_t get_version_3() const { return ___version_3; }
inline int32_t* get_address_of_version_3() { return &___version_3; }
inline void set_version_3(int32_t value)
{
___version_3 = value;
}
inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___freeList_4)); }
inline int32_t get_freeList_4() const { return ___freeList_4; }
inline int32_t* get_address_of_freeList_4() { return &___freeList_4; }
inline void set_freeList_4(int32_t value)
{
___freeList_4 = value;
}
inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___freeCount_5)); }
inline int32_t get_freeCount_5() const { return ___freeCount_5; }
inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; }
inline void set_freeCount_5(int32_t value)
{
___freeCount_5 = value;
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value);
}
inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___keys_7)); }
inline KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543 * get_keys_7() const { return ___keys_7; }
inline KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543 ** get_address_of_keys_7() { return &___keys_7; }
inline void set_keys_7(KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543 * value)
{
___keys_7 = value;
Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value);
}
inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___values_8)); }
inline ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD * get_values_8() const { return ___values_8; }
inline ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD ** get_address_of_values_8() { return &___values_8; }
inline void set_values_8(ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD * value)
{
___values_8 = value;
Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value);
}
inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ____syncRoot_9)); }
inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; }
inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; }
inline void set__syncRoot_9(RuntimeObject * value)
{
____syncRoot_9 = value;
Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value);
}
};
// System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Int32>
struct Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6 : public RuntimeObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::buckets
Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0;
// System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries
EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604* ___entries_1;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_2;
// System.Int32 System.Collections.Generic.Dictionary`2::version
int32_t ___version_3;
// System.Int32 System.Collections.Generic.Dictionary`2::freeList
int32_t ___freeList_4;
// System.Int32 System.Collections.Generic.Dictionary`2::freeCount
int32_t ___freeCount_5;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer
RuntimeObject* ___comparer_6;
// System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys
KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63 * ___keys_7;
// System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values
ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E * ___values_8;
// System.Object System.Collections.Generic.Dictionary`2::_syncRoot
RuntimeObject * ____syncRoot_9;
public:
inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___buckets_0)); }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; }
inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value)
{
___buckets_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value);
}
inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___entries_1)); }
inline EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604* get_entries_1() const { return ___entries_1; }
inline EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604** get_address_of_entries_1() { return &___entries_1; }
inline void set_entries_1(EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604* value)
{
___entries_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value);
}
inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___count_2)); }
inline int32_t get_count_2() const { return ___count_2; }
inline int32_t* get_address_of_count_2() { return &___count_2; }
inline void set_count_2(int32_t value)
{
___count_2 = value;
}
inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___version_3)); }
inline int32_t get_version_3() const { return ___version_3; }
inline int32_t* get_address_of_version_3() { return &___version_3; }
inline void set_version_3(int32_t value)
{
___version_3 = value;
}
inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___freeList_4)); }
inline int32_t get_freeList_4() const { return ___freeList_4; }
inline int32_t* get_address_of_freeList_4() { return &___freeList_4; }
inline void set_freeList_4(int32_t value)
{
___freeList_4 = value;
}
inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___freeCount_5)); }
inline int32_t get_freeCount_5() const { return ___freeCount_5; }
inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; }
inline void set_freeCount_5(int32_t value)
{
___freeCount_5 = value;
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value);
}
inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___keys_7)); }
inline KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63 * get_keys_7() const { return ___keys_7; }
inline KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63 ** get_address_of_keys_7() { return &___keys_7; }
inline void set_keys_7(KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63 * value)
{
___keys_7 = value;
Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value);
}
inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___values_8)); }
inline ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E * get_values_8() const { return ___values_8; }
inline ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E ** get_address_of_values_8() { return &___values_8; }
inline void set_values_8(ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E * value)
{
___values_8 = value;
Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value);
}
inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ____syncRoot_9)); }
inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; }
inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; }
inline void set__syncRoot_9(RuntimeObject * value)
{
____syncRoot_9 = value;
Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value);
}
};
// System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef>
struct Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58 : public RuntimeObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::buckets
Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0;
// System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries
EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE* ___entries_1;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_2;
// System.Int32 System.Collections.Generic.Dictionary`2::version
int32_t ___version_3;
// System.Int32 System.Collections.Generic.Dictionary`2::freeList
int32_t ___freeList_4;
// System.Int32 System.Collections.Generic.Dictionary`2::freeCount
int32_t ___freeCount_5;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer
RuntimeObject* ___comparer_6;
// System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys
KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68 * ___keys_7;
// System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values
ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42 * ___values_8;
// System.Object System.Collections.Generic.Dictionary`2::_syncRoot
RuntimeObject * ____syncRoot_9;
public:
inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___buckets_0)); }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; }
inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value)
{
___buckets_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value);
}
inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___entries_1)); }
inline EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE* get_entries_1() const { return ___entries_1; }
inline EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE** get_address_of_entries_1() { return &___entries_1; }
inline void set_entries_1(EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE* value)
{
___entries_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value);
}
inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___count_2)); }
inline int32_t get_count_2() const { return ___count_2; }
inline int32_t* get_address_of_count_2() { return &___count_2; }
inline void set_count_2(int32_t value)
{
___count_2 = value;
}
inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___version_3)); }
inline int32_t get_version_3() const { return ___version_3; }
inline int32_t* get_address_of_version_3() { return &___version_3; }
inline void set_version_3(int32_t value)
{
___version_3 = value;
}
inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___freeList_4)); }
inline int32_t get_freeList_4() const { return ___freeList_4; }
inline int32_t* get_address_of_freeList_4() { return &___freeList_4; }
inline void set_freeList_4(int32_t value)
{
___freeList_4 = value;
}
inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___freeCount_5)); }
inline int32_t get_freeCount_5() const { return ___freeCount_5; }
inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; }
inline void set_freeCount_5(int32_t value)
{
___freeCount_5 = value;
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value);
}
inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___keys_7)); }
inline KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68 * get_keys_7() const { return ___keys_7; }
inline KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68 ** get_address_of_keys_7() { return &___keys_7; }
inline void set_keys_7(KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68 * value)
{
___keys_7 = value;
Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value);
}
inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___values_8)); }
inline ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42 * get_values_8() const { return ___values_8; }
inline ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42 ** get_address_of_values_8() { return &___values_8; }
inline void set_values_8(ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42 * value)
{
___values_8 = value;
Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value);
}
inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ____syncRoot_9)); }
inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; }
inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; }
inline void set__syncRoot_9(RuntimeObject * value)
{
____syncRoot_9 = value;
Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value);
}
};
// System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl>
struct Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7 : public RuntimeObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::buckets
Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0;
// System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries
EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F* ___entries_1;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_2;
// System.Int32 System.Collections.Generic.Dictionary`2::version
int32_t ___version_3;
// System.Int32 System.Collections.Generic.Dictionary`2::freeList
int32_t ___freeList_4;
// System.Int32 System.Collections.Generic.Dictionary`2::freeCount
int32_t ___freeCount_5;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer
RuntimeObject* ___comparer_6;
// System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys
KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987 * ___keys_7;
// System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values
ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D * ___values_8;
// System.Object System.Collections.Generic.Dictionary`2::_syncRoot
RuntimeObject * ____syncRoot_9;
public:
inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___buckets_0)); }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; }
inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value)
{
___buckets_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value);
}
inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___entries_1)); }
inline EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F* get_entries_1() const { return ___entries_1; }
inline EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F** get_address_of_entries_1() { return &___entries_1; }
inline void set_entries_1(EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F* value)
{
___entries_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value);
}
inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___count_2)); }
inline int32_t get_count_2() const { return ___count_2; }
inline int32_t* get_address_of_count_2() { return &___count_2; }
inline void set_count_2(int32_t value)
{
___count_2 = value;
}
inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___version_3)); }
inline int32_t get_version_3() const { return ___version_3; }
inline int32_t* get_address_of_version_3() { return &___version_3; }
inline void set_version_3(int32_t value)
{
___version_3 = value;
}
inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___freeList_4)); }
inline int32_t get_freeList_4() const { return ___freeList_4; }
inline int32_t* get_address_of_freeList_4() { return &___freeList_4; }
inline void set_freeList_4(int32_t value)
{
___freeList_4 = value;
}
inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___freeCount_5)); }
inline int32_t get_freeCount_5() const { return ___freeCount_5; }
inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; }
inline void set_freeCount_5(int32_t value)
{
___freeCount_5 = value;
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value);
}
inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___keys_7)); }
inline KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987 * get_keys_7() const { return ___keys_7; }
inline KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987 ** get_address_of_keys_7() { return &___keys_7; }
inline void set_keys_7(KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987 * value)
{
___keys_7 = value;
Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value);
}
inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___values_8)); }
inline ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D * get_values_8() const { return ___values_8; }
inline ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D ** get_address_of_values_8() { return &___values_8; }
inline void set_values_8(ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D * value)
{
___values_8 = value;
Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value);
}
inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ____syncRoot_9)); }
inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; }
inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; }
inline void set__syncRoot_9(RuntimeObject * value)
{
____syncRoot_9 = value;
Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value);
}
};
// System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity>
struct Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523 : public RuntimeObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::buckets
Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0;
// System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries
EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221* ___entries_1;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_2;
// System.Int32 System.Collections.Generic.Dictionary`2::version
int32_t ___version_3;
// System.Int32 System.Collections.Generic.Dictionary`2::freeList
int32_t ___freeList_4;
// System.Int32 System.Collections.Generic.Dictionary`2::freeCount
int32_t ___freeCount_5;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer
RuntimeObject* ___comparer_6;
// System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys
KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122 * ___keys_7;
// System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values
ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400 * ___values_8;
// System.Object System.Collections.Generic.Dictionary`2::_syncRoot
RuntimeObject * ____syncRoot_9;
public:
inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___buckets_0)); }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; }
inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value)
{
___buckets_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value);
}
inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___entries_1)); }
inline EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221* get_entries_1() const { return ___entries_1; }
inline EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221** get_address_of_entries_1() { return &___entries_1; }
inline void set_entries_1(EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221* value)
{
___entries_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value);
}
inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___count_2)); }
inline int32_t get_count_2() const { return ___count_2; }
inline int32_t* get_address_of_count_2() { return &___count_2; }
inline void set_count_2(int32_t value)
{
___count_2 = value;
}
inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___version_3)); }
inline int32_t get_version_3() const { return ___version_3; }
inline int32_t* get_address_of_version_3() { return &___version_3; }
inline void set_version_3(int32_t value)
{
___version_3 = value;
}
inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___freeList_4)); }
inline int32_t get_freeList_4() const { return ___freeList_4; }
inline int32_t* get_address_of_freeList_4() { return &___freeList_4; }
inline void set_freeList_4(int32_t value)
{
___freeList_4 = value;
}
inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___freeCount_5)); }
inline int32_t get_freeCount_5() const { return ___freeCount_5; }
inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; }
inline void set_freeCount_5(int32_t value)
{
___freeCount_5 = value;
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value);
}
inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___keys_7)); }
inline KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122 * get_keys_7() const { return ___keys_7; }
inline KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122 ** get_address_of_keys_7() { return &___keys_7; }
inline void set_keys_7(KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122 * value)
{
___keys_7 = value;
Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value);
}
inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___values_8)); }
inline ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400 * get_values_8() const { return ___values_8; }
inline ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400 ** get_address_of_values_8() { return &___values_8; }
inline void set_values_8(ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400 * value)
{
___values_8 = value;
Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value);
}
inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ____syncRoot_9)); }
inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; }
inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; }
inline void set__syncRoot_9(RuntimeObject * value)
{
____syncRoot_9 = value;
Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value);
}
};
// System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName>
struct Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2 : public RuntimeObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::buckets
Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0;
// System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries
EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0* ___entries_1;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_2;
// System.Int32 System.Collections.Generic.Dictionary`2::version
int32_t ___version_3;
// System.Int32 System.Collections.Generic.Dictionary`2::freeList
int32_t ___freeList_4;
// System.Int32 System.Collections.Generic.Dictionary`2::freeCount
int32_t ___freeCount_5;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer
RuntimeObject* ___comparer_6;
// System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys
KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372 * ___keys_7;
// System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values
ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E * ___values_8;
// System.Object System.Collections.Generic.Dictionary`2::_syncRoot
RuntimeObject * ____syncRoot_9;
public:
inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___buckets_0)); }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; }
inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; }
inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value)
{
___buckets_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value);
}
inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___entries_1)); }
inline EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0* get_entries_1() const { return ___entries_1; }
inline EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0** get_address_of_entries_1() { return &___entries_1; }
inline void set_entries_1(EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0* value)
{
___entries_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value);
}
inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___count_2)); }
inline int32_t get_count_2() const { return ___count_2; }
inline int32_t* get_address_of_count_2() { return &___count_2; }
inline void set_count_2(int32_t value)
{
___count_2 = value;
}
inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___version_3)); }
inline int32_t get_version_3() const { return ___version_3; }
inline int32_t* get_address_of_version_3() { return &___version_3; }
inline void set_version_3(int32_t value)
{
___version_3 = value;
}
inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___freeList_4)); }
inline int32_t get_freeList_4() const { return ___freeList_4; }
inline int32_t* get_address_of_freeList_4() { return &___freeList_4; }
inline void set_freeList_4(int32_t value)
{
___freeList_4 = value;
}
inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___freeCount_5)); }
inline int32_t get_freeCount_5() const { return ___freeCount_5; }
inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; }
inline void set_freeCount_5(int32_t value)
{
___freeCount_5 = value;
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value);
}
inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___keys_7)); }
inline KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372 * get_keys_7() const { return ___keys_7; }
inline KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372 ** get_address_of_keys_7() { return &___keys_7; }
inline void set_keys_7(KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372 * value)
{
___keys_7 = value;
Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value);
}
inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___values_8)); }
inline ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E * get_values_8() const { return ___values_8; }
inline ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E ** get_address_of_values_8() { return &___values_8; }
inline void set_values_8(ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E * value)
{
___values_8 = value;
Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value);
}
inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ____syncRoot_9)); }
inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; }
inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; }
inline void set__syncRoot_9(RuntimeObject * value)
{
____syncRoot_9 = value;
Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
il2cpp_hresult_t IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue);
// COM Callable Wrapper for System.Collections.Generic.Dictionary`2<WindTurbineScriptableObject,UnityEngine.GameObject>
struct Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8
{
inline Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper>(obj) {}
virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE
{
if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0)
{
*object = GetIdentity();
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIManagedObjectHolder*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIMarshal*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIWeakReferenceSource*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
*object = NULL;
return IL2CPP_E_NOINTERFACE;
}
virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE
{
return AddRefImpl();
}
virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE
{
return ReleaseImpl();
}
virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE
{
Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1);
interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID;
*iidCount = 1;
*iids = interfaceIds;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE
{
return GetRuntimeClassNameImpl(className);
}
virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE
{
return ComObjectBase::GetTrustLevel(trustLevel);
}
virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE
{
return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue);
}
};
IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F(RuntimeObject* obj)
{
void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper));
if (memory == NULL)
{
il2cpp_codegen_raise_out_of_memory_exception();
}
return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper(obj));
}
// COM Callable Wrapper for System.Collections.Generic.Dictionary`2<WindTurbineScriptableObject,SiteOverviewTurbineButton>
struct Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8
{
inline Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper>(obj) {}
virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE
{
if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0)
{
*object = GetIdentity();
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIManagedObjectHolder*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIMarshal*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIWeakReferenceSource*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
*object = NULL;
return IL2CPP_E_NOINTERFACE;
}
virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE
{
return AddRefImpl();
}
virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE
{
return ReleaseImpl();
}
virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE
{
Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1);
interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID;
*iidCount = 1;
*iids = interfaceIds;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE
{
return GetRuntimeClassNameImpl(className);
}
virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE
{
return ComObjectBase::GetTrustLevel(trustLevel);
}
virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE
{
return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue);
}
};
IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85(RuntimeObject* obj)
{
void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper));
if (memory == NULL)
{
il2cpp_codegen_raise_out_of_memory_exception();
}
return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper(obj));
}
// COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Int32>
struct Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8
{
inline Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper>(obj) {}
virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE
{
if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0)
{
*object = GetIdentity();
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIManagedObjectHolder*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIMarshal*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIWeakReferenceSource*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
*object = NULL;
return IL2CPP_E_NOINTERFACE;
}
virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE
{
return AddRefImpl();
}
virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE
{
return ReleaseImpl();
}
virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE
{
Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1);
interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID;
*iidCount = 1;
*iids = interfaceIds;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE
{
return GetRuntimeClassNameImpl(className);
}
virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE
{
return ComObjectBase::GetTrustLevel(trustLevel);
}
virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE
{
return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue);
}
};
IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6(RuntimeObject* obj)
{
void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper));
if (memory == NULL)
{
il2cpp_codegen_raise_out_of_memory_exception();
}
return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper(obj));
}
// COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef>
struct Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8
{
inline Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper>(obj) {}
virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE
{
if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0)
{
*object = GetIdentity();
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIManagedObjectHolder*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIMarshal*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIWeakReferenceSource*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
*object = NULL;
return IL2CPP_E_NOINTERFACE;
}
virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE
{
return AddRefImpl();
}
virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE
{
return ReleaseImpl();
}
virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE
{
Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1);
interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID;
*iidCount = 1;
*iids = interfaceIds;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE
{
return GetRuntimeClassNameImpl(className);
}
virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE
{
return ComObjectBase::GetTrustLevel(trustLevel);
}
virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE
{
return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue);
}
};
IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58(RuntimeObject* obj)
{
void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper));
if (memory == NULL)
{
il2cpp_codegen_raise_out_of_memory_exception();
}
return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper(obj));
}
// COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl>
struct Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8
{
inline Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper>(obj) {}
virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE
{
if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0)
{
*object = GetIdentity();
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIManagedObjectHolder*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIMarshal*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIWeakReferenceSource*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
*object = NULL;
return IL2CPP_E_NOINTERFACE;
}
virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE
{
return AddRefImpl();
}
virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE
{
return ReleaseImpl();
}
virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE
{
Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1);
interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID;
*iidCount = 1;
*iids = interfaceIds;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE
{
return GetRuntimeClassNameImpl(className);
}
virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE
{
return ComObjectBase::GetTrustLevel(trustLevel);
}
virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE
{
return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue);
}
};
IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7(RuntimeObject* obj)
{
void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper));
if (memory == NULL)
{
il2cpp_codegen_raise_out_of_memory_exception();
}
return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper(obj));
}
// COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity>
struct Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8
{
inline Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper>(obj) {}
virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE
{
if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0)
{
*object = GetIdentity();
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIManagedObjectHolder*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIMarshal*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIWeakReferenceSource*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
*object = NULL;
return IL2CPP_E_NOINTERFACE;
}
virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE
{
return AddRefImpl();
}
virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE
{
return ReleaseImpl();
}
virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE
{
Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1);
interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID;
*iidCount = 1;
*iids = interfaceIds;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE
{
return GetRuntimeClassNameImpl(className);
}
virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE
{
return ComObjectBase::GetTrustLevel(trustLevel);
}
virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE
{
return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue);
}
};
IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523(RuntimeObject* obj)
{
void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper));
if (memory == NULL)
{
il2cpp_codegen_raise_out_of_memory_exception();
}
return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper(obj));
}
// COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName>
struct Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8
{
inline Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper>(obj) {}
virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE
{
if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0)
{
*object = GetIdentity();
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIManagedObjectHolder*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIMarshal*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIWeakReferenceSource*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
*object = NULL;
return IL2CPP_E_NOINTERFACE;
}
virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE
{
return AddRefImpl();
}
virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE
{
return ReleaseImpl();
}
virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE
{
Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1);
interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID;
*iidCount = 1;
*iids = interfaceIds;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE
{
return GetRuntimeClassNameImpl(className);
}
virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE
{
return ComObjectBase::GetTrustLevel(trustLevel);
}
virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE
{
return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue);
}
};
IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2(RuntimeObject* obj)
{
void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper));
if (memory == NULL)
{
il2cpp_codegen_raise_out_of_memory_exception();
}
return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper(obj));
}
| 47.025032 | 257 | 0.819969 | JBrentJ |
84ad32e1a1e176b44e4c9c1187af7f74d8f815c2 | 679 | cpp | C++ | solved-problems/google-coding-competitions/kick-start/2019/Practice-Round/B.Mural.cpp | developer4fun/competitive_programming | 9e95945ae63d41696ca7b50f026b8fe05aec49de | [
"MIT"
] | 1 | 2022-02-14T14:14:21.000Z | 2022-02-14T14:14:21.000Z | solved-problems/google-coding-competitions/kick-start/2019/Practice-Round/B.Mural.cpp | developer4fun/competitiveProgramming | 9e95945ae63d41696ca7b50f026b8fe05aec49de | [
"MIT"
] | 6 | 2022-01-16T21:15:24.000Z | 2022-03-04T15:59:28.000Z | kick-start/2019/Practice-Round/B.Mural.cpp | ggardusi/google-coding-competitions | 878d0ad0a4abed6862d0667248e1008b8bb56fb5 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
std::mt19937 rng(int(std::chrono::steady_clock::now().time_since_epoch().count()));
int main() {
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
std::cout.tie(0);
int t;
cin >> t;
for (int test = 1; test <= t; test += 1) {
int n;
cin >> n;
string s;
cin >> s;
vector< int > sum(n + 5);
sum[0] = 0;
for (int i = 0; i < n; i += 1) {
sum[i + 1] = sum[i] + (s[i] - '0');
}
int size = (n + 1) / 2;
int ans = 0;
for (int i = size; i <= n; i += 1) {
ans = max(ans, sum[i] - sum[i - size]);
}
cout << "Case #" << test << ": " << ans << '\n';
}
return 0;
} | 22.633333 | 83 | 0.46539 | developer4fun |
84adfe612e28a1f96e52258759f384640de582ba | 277 | cpp | C++ | 0383-Ransom-Note/cpp_0383/main.cpp | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | 12 | 2020-03-18T14:36:23.000Z | 2021-12-19T02:24:33.000Z | 0383-Ransom-Note/cpp_0383/main.cpp | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | 0383-Ransom-Note/cpp_0383/main.cpp | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | #include <iostream>
//#include "Solution1.h"
#include "Solution2.h"
void test(string s1, string s2) {
Solution solution;
cout << solution.canConstruct(s1, s2) << endl;
}
int main() {
test("a", "b"); // 0
test("aa", "ab"); // 0
test("aa", "aab"); // 1
return 0;
}
| 17.3125 | 48 | 0.581227 | ooooo-youwillsee |
84aeafb91e3ce385a621876dfe0a650bb993fd00 | 6,310 | cpp | C++ | KEIHANNA_MAIN-teensy40/src/main.cpp | nakamoto800/Hercules_2022 | e50347fdba847e81ffbc24f3e9a720c460e6b9f3 | [
"MIT"
] | 2 | 2022-03-03T13:51:09.000Z | 2022-03-03T13:51:11.000Z | KEIHANNA_MAIN-teensy40/src/main.cpp | nakamoto800/Hercules_2022 | e50347fdba847e81ffbc24f3e9a720c460e6b9f3 | [
"MIT"
] | null | null | null | KEIHANNA_MAIN-teensy40/src/main.cpp | nakamoto800/Hercules_2022 | e50347fdba847e81ffbc24f3e9a720c460e6b9f3 | [
"MIT"
] | 1 | 2022-01-29T22:19:49.000Z | 2022-01-29T22:19:49.000Z | //ライブラリ読み込み
#include <Arduino.h>
#include <DSR1202.h>
#include <U8g2lib.h>
//ライブラリセットアップ
DSR1202 dsr1202(1);
//AQM1248Aは128 * 48
U8G2_ST7565_AK_AQM1248_F_4W_HW_SPI u8g2(U8G2_R0, 10, 34, 35); //CS, DC(RS), Reset(適当)
//定数置き場
#define buzzer 33 //圧電ブザー
#define button_LCD_R 27 //タクトスイッチ(右)
#define button_LCD_L 32 //タクトスイッチ(左)
#define switch_program 31 //トグルスイッチ
#define button_LCD_C 30 //タクトスイッチ(コマンド)
#define LINE_1 2 //前
#define LINE_2 3 //右
#define LINE_3 4 //後
#define LINE_4 5 //左
#define LED 9
//グローバル変数置き場(本当は減らしたいけど初心者なので当分このまま)
int head_CAM, CAM_angle, CAM_distance, CAM_YellowAngle, CAM_BlueAngle; //OpenMVから受け取るデータ用
int head_USS, USS, USS1, USS2, USS3, USS4; //USSから受け取るデータ用
int IMU; //IMU値
int head_BT, BT_Angle, BT_Power; //無線機
class Status {
public:
int val, old_val;
int state;
};
class Timer {
public:
unsigned long timer, timer_start;
};
Status LCD, LCD_R, LCD_L, LCD_C;
Timer LINE, position, Ball;
int val_I;
int deviation, old_deviation, val_D;
float operation_A, operation_B, operation_C;
int motor[4]; //モーター出力(前向いてるときの各モーターの出力値設定)
int MotorPower[4]; //最終操作量(方向修正による操作量を含めた最終モーター出力値)
//ヘッダファイル読み込み
#include "Serial_receive.h"
#include "print_LCD.h"
#include "pid_parameter.h"
#include "pid.h"
#include "motor.h"
void setup() {
u8g2.begin(); //LCD初期化
u8g2.setFlipMode(1); //反転は1(通常表示は0)
u8g2.clearBuffer(); //内部メモリクリア(毎回表示内容更新前に置く)
u8g2.setFont(u8g2_font_ncenB14_tr); //フォント選択(これは横に14ピクセル、縦に14ピクセル)
u8g2.drawStr(0,31,"Hello World!"); //書き込み内容書くところ(画面左端から横に何ピクセル、縦に何ピクセルか指定。ちなみに、文字の左下が指示座標になる。)
u8g2.sendBuffer(); //ディスプレイに送る(毎回書く)
tone(buzzer, 1568, 100); //通電確認音
//各ピン設定開始
pinMode(button_LCD_R, INPUT);
pinMode(button_LCD_L, INPUT);
pinMode(button_LCD_C, INPUT);
pinMode(switch_program, INPUT);
pinMode(LINE_1, INPUT);
pinMode(LINE_2, INPUT);
pinMode(LINE_3, INPUT);
pinMode(LINE_4, INPUT);
dsr1202.Init(); //MD準備(USBシリアルも同時開始)
Serial2.begin(115200); //OpenMVとのシリアル通信
Serial3.begin(115200); //USSとのシリアル通信
Serial4.begin(115200); //IMUとのシリアル通信
Serial5.begin(115200); //M5Stamp Picoとの通信
tone(buzzer, 2093, 100); //起動確認音
/*Adventurer 3 Lite
tone(buzzer, 1047, 1000); //ド6
delay(1000);
noTone(buzzer);
delay(250);
tone(buzzer, 1319, 150); //ミ6
delay(150);
noTone(buzzer);
delay(100);
tone(buzzer, 1397, 250); //ファ6
delay(250);
noTone(buzzer);
delay(150);
tone(buzzer, 1568, 150); //ソ6
delay(150);
noTone(buzzer);
delay(100);
tone(buzzer, 1760, 300); //ラ6
delay(300);
noTone(buzzer);
delay(100);
tone(buzzer, 1568, 250); //ソ6
delay(250);
noTone(buzzer);
delay(200);
tone(buzzer, 1568, 250); //ソ6
delay(250);
noTone(buzzer);
delay(200);
tone(buzzer, 2093, 250); //ド7
delay(250);
noTone(buzzer);
*/
}
void loop() {
Serial_receive();
pid();
if ((LCD.state == 0) && (LCD_C.state == 1) && (digitalRead(switch_program) == LOW)) {
LINE.timer = millis() - LINE.timer_start;
if (LINE.timer < 150) {
if (IMU == 10) {
LINE.timer = 300;
goto Ball; //Ballラベルまで飛ぶ
}
Move(0, 0);
} else if (LINE.timer < 300) {
if (IMU == 10) {
LINE.timer = 300;
goto Ball; //上に同じ
}
Motor(USS);
} else {
if ((digitalRead(LINE_1) == LOW) || (digitalRead(LINE_2) == LOW) || (digitalRead(LINE_4) == LOW)) {
if (USS == 10) {
goto Ball; //上に同じ
}
for (size_t i = 0; i < 10; i++) {
Serial1.println("1R0002R0003R0004R000");
}
LINE.timer_start = millis();
} else {
Ball: //超音波のパターン次第でライン見ずにここまで飛ぶ
if (CAM_distance > 0) {
position.timer = millis();
position.timer_start = position.timer;
Ball.timer = millis() - Ball.timer_start;
if (Ball.timer <= 500) { //標準速度
if (CAM_distance <= 52) {
if (CAM_angle <= 20) {
Move(CAM_angle, motor_speed);
} else if (CAM_angle <= 180) {
Move((CAM_angle + 90), motor_speed);
Ball.timer_start = millis();
} else if (CAM_angle < 340) {
Move((CAM_angle - 90), motor_speed);
Ball.timer_start = millis();
} else {
Move(CAM_angle, motor_speed);
}
} else {
Move(CAM_angle, motor_speed);
Ball.timer_start = millis();
}
} else { //マキシマムモード(一定時間経過後パワーを上げる)
if (CAM_distance <= 52) {
if (CAM_angle <= 20) {
Move(CAM_angle, (motor_speed + 3));
} else if (CAM_angle <= 180) {
Move((CAM_angle + 90), motor_speed);
Ball.timer_start = millis();
} else if (CAM_angle < 340) {
Move((CAM_angle - 90), motor_speed);
Ball.timer_start = millis();
} else {
Move(CAM_angle, (motor_speed + 3));
}
} else {
Move(CAM_angle, motor_speed);
Ball.timer_start = millis();
}
}
} else {
position.timer = millis() - position.timer_start;
if (position.timer < 2000) {
Move(0, 0);
} else {
if (USS3 > 50) {
if (USS2 < 70) {
if (USS4 < 70) {
Motor(3); //後
} else {
Motor(9); //右後
}
} else if (USS4 < 70) {
Motor(8); //左後
} else {
Motor(3); //後
}
} else if (USS2 < 70) {
if (USS4 < 70) {
Motor(1); //方向修正
} else {
Motor(5); //右
}
} else if (USS4 < 70) {
Motor(4); //左
} else {
Motor(1); //方向修正
}
}
}
}
}
} else if ((LCD.state == 7) && (LCD_C.state == 1) && (digitalRead(switch_program) == LOW)) {
Move(0, 0);
} else if ((LCD.state == 8) && (LCD_C.state == 1) && (digitalRead(switch_program) == LOW)) {
if (BT_Angle > 360) {
Move(0, 0);
} else {
Move(BT_Angle, BT_Power);
}
} else {
print_LCD();
dsr1202.move(0, 0, 0, 0);
}
} | 26.851064 | 105 | 0.538827 | nakamoto800 |