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
109
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
48.5k
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
eec2bae48f0462bba7ca403aec542caa2c837a6d
9,479
cpp
C++
tests/YGAlignSelfTest.cpp
emilsjolander/yoga
02a2309b2a8208e652e351cf8a195c17694b1f01
[ "MIT" ]
null
null
null
tests/YGAlignSelfTest.cpp
emilsjolander/yoga
02a2309b2a8208e652e351cf8a195c17694b1f01
[ "MIT" ]
null
null
null
tests/YGAlignSelfTest.cpp
emilsjolander/yoga
02a2309b2a8208e652e351cf8a195c17694b1f01
[ "MIT" ]
null
null
null
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGAlignSelfTest.html #include <gtest/gtest.h> #include <yoga/Yoga.h> TEST(YogaTest, align_self_center) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetAlignSelf(root_child0, YGAlignCenter); YGNodeStyleSetWidth(root_child0, 10); YGNodeStyleSetHeight(root_child0, 10); YGNodeInsertChild(root, root_child0, 0); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(45, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child0)); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionRTL); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(45, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child0)); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, align_self_flex_end) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetAlignSelf(root_child0, YGAlignFlexEnd); YGNodeStyleSetWidth(root_child0, 10); YGNodeStyleSetHeight(root_child0, 10); YGNodeInsertChild(root, root_child0, 0); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(90, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child0)); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionRTL); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child0)); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, align_self_flex_start) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetAlignSelf(root_child0, YGAlignFlexStart); YGNodeStyleSetWidth(root_child0, 10); YGNodeStyleSetHeight(root_child0, 10); YGNodeInsertChild(root, root_child0, 0); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child0)); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionRTL); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(90, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child0)); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, align_self_flex_end_override_flex_start) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetAlignItems(root, YGAlignFlexStart); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetAlignSelf(root_child0, YGAlignFlexEnd); YGNodeStyleSetWidth(root_child0, 10); YGNodeStyleSetHeight(root_child0, 10); YGNodeInsertChild(root, root_child0, 0); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(90, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child0)); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionRTL); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child0)); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, align_self_baseline) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetAlignSelf(root_child0, YGAlignBaseline); YGNodeStyleSetWidth(root_child0, 50); YGNodeStyleSetHeight(root_child0, 50); YGNodeInsertChild(root, root_child0, 0); const YGNodeRef root_child1 = YGNodeNewWithConfig(config); YGNodeStyleSetAlignSelf(root_child1, YGAlignBaseline); YGNodeStyleSetWidth(root_child1, 50); YGNodeStyleSetHeight(root_child1, 20); YGNodeInsertChild(root, root_child1, 1); const YGNodeRef root_child1_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root_child1_child0, 50); YGNodeStyleSetHeight(root_child1_child0, 10); YGNodeInsertChild(root_child1, root_child1_child0, 0); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetLeft(root_child1)); ASSERT_FLOAT_EQ(40, YGNodeLayoutGetTop(root_child1)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetWidth(root_child1)); ASSERT_FLOAT_EQ(20, YGNodeLayoutGetHeight(root_child1)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child1_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child1_child0)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetWidth(root_child1_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child1_child0)); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionRTL); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child1)); ASSERT_FLOAT_EQ(40, YGNodeLayoutGetTop(root_child1)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetWidth(root_child1)); ASSERT_FLOAT_EQ(20, YGNodeLayoutGetHeight(root_child1)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child1_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child1_child0)); ASSERT_FLOAT_EQ(50, YGNodeLayoutGetWidth(root_child1_child0)); ASSERT_FLOAT_EQ(10, YGNodeLayoutGetHeight(root_child1_child0)); YGNodeFreeRecursive(root); YGConfigFree(config); }
37.916
78
0.805992
emilsjolander
eec324e25d1f9716216d09e009c391beb70f1f50
3,279
cpp
C++
src/caffe/layers/cudnn_batch_norm_layer.cpp
madiken/caffe-CUDNN-fork
6fdbbe9ae7fa0165feb864d122ac92a6a0d0a2f1
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/cudnn_batch_norm_layer.cpp
madiken/caffe-CUDNN-fork
6fdbbe9ae7fa0165feb864d122ac92a6a0d0a2f1
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/cudnn_batch_norm_layer.cpp
madiken/caffe-CUDNN-fork
6fdbbe9ae7fa0165feb864d122ac92a6a0d0a2f1
[ "BSD-2-Clause" ]
null
null
null
#ifdef USE_CUDNN #include <vector> #include "caffe/filler.hpp" #include "caffe/layer.hpp" #include "caffe/util/im2col.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> void CuDNNBatchNormLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { BatchNormLayer<Dtype>::LayerSetUp(bottom, top); cudnn::createTensor4dDesc<Dtype>(&bottom_desc_); cudnn::createTensor4dDesc<Dtype>(&top_desc_); cudnn::createTensor4dDesc<Dtype>(&scale_bias_mean_var_desc_); // currently only SPATIAL mode is supported (most commonly used mode) // If there's enough demand we can implement CUDNN_BATCHNORM_PER_ACTIVATION // though it's not currently implemented for the CPU layer mode_ = CUDNN_BATCHNORM_SPATIAL; if (this->blobs_.size() > 5) { LOG(INFO) << "Skipping parameter initialization"; } else { this->blobs_.resize(5); this->blobs_[0].reset(new Blob<Dtype>(1, bottom[0]->channels(), 1, 1)); this->blobs_[1].reset(new Blob<Dtype>(1, bottom[0]->channels(), 1, 1)); this->blobs_[2].reset(new Blob<Dtype>(1, 1, 1, 1)); this->blobs_[3].reset(new Blob<Dtype>(1, bottom[0]->channels(), 1, 1)); this->blobs_[4].reset(new Blob<Dtype>(1, bottom[0]->channels(), 1, 1)); shared_ptr<Filler<Dtype> > scale_filler( GetFiller<Dtype>(this->layer_param_.batch_norm_param().scale_filler())); scale_filler->Fill(this->blobs_[0].get()); shared_ptr<Filler<Dtype> > bias_filler( GetFiller<Dtype>(this->layer_param_.batch_norm_param().bias_filler())); bias_filler->Fill(this->blobs_[1].get()); for (int i = 2; i < 5; i++) { caffe_set(this->blobs_[i]->count(), Dtype(0), this->blobs_[i]->mutable_cpu_data()); } } handles_setup_ = true; } template <typename Dtype> void CuDNNBatchNormLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { BatchNormLayer<Dtype>::Reshape(bottom, top); // set up main tensors cudnn::setTensor4dDesc<Dtype>( &bottom_desc_, bottom[0]->num(), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()); cudnn::setTensor4dDesc<Dtype>( &top_desc_, bottom[0]->num(), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()); // aux tensors for caching mean & invVar from fwd to bwd pass int C = bottom[0]->channels(); int H = bottom[0]->height(); int W = bottom[0]->width(); if (mode_ == CUDNN_BATCHNORM_SPATIAL) { save_mean_.Reshape(1, C, 1, 1); save_inv_var_.Reshape(1, C, 1, 1); } else if (mode_ == CUDNN_BATCHNORM_PER_ACTIVATION) { save_mean_.Reshape(1, C, H, W); save_inv_var_.Reshape(1, C, H, W); } else { LOG(FATAL) << "Unknown cudnnBatchNormMode_t"; } CUDNN_CHECK(cudnnDeriveBNTensorDescriptor(scale_bias_mean_var_desc_, bottom_desc_, mode_)); } template <typename Dtype> CuDNNBatchNormLayer<Dtype>::~CuDNNBatchNormLayer() { if (!handles_setup_) return; cudnnDestroyTensorDescriptor(bottom_desc_); cudnnDestroyTensorDescriptor(top_desc_); cudnnDestroyTensorDescriptor(scale_bias_mean_var_desc_); } INSTANTIATE_CLASS(CuDNNBatchNormLayer); } // namespace caffe #endif
33.459184
78
0.681
madiken
eec60c3b6bb4f4c06d192c556d259874e31714e6
17,049
cpp
C++
rgcmidcpp/src/midi/smf.cpp
mdsitton/rhythmChartFormat
1e53aaff34603bee258582293d11d29e0bf53bde
[ "BSD-2-Clause" ]
8
2017-09-20T20:24:29.000Z
2019-08-10T22:55:13.000Z
rgcmidcpp/src/midi/smf.cpp
mdsitton/rhythmChartFormat
1e53aaff34603bee258582293d11d29e0bf53bde
[ "BSD-2-Clause" ]
null
null
null
rgcmidcpp/src/midi/smf.cpp
mdsitton/rhythmChartFormat
1e53aaff34603bee258582293d11d29e0bf53bde
[ "BSD-2-Clause" ]
1
2018-08-28T19:28:20.000Z
2018-08-28T19:28:20.000Z
// Copyright (c) 2015-2017 Matthew Sitton <[email protected]> // See LICENSE in the RhythmGameChart root for license information. #include "smf.hpp" #include <iostream> #include <cstring> #include <cmath> namespace RGCCPP::Midi { SmfReader::SmfReader(std::string filename) :m_smfFile(filename, std::ios_base::ate | std::ios_base::binary) { if (m_smfFile) { init_tempo_ts(); read_file(); m_smfFile.close(); } else { throw std::runtime_error("Failed to load midi."); } } std::vector<SmfTrack>& SmfReader::get_tracks() { return m_tracks; } TempoTrack* SmfReader::get_tempo_track() { return &m_tempoTrack; } void SmfReader::release() { m_tracks.clear(); } void SmfReader::read_midi_event(const SmfEventInfo &event) { MidiEvent midiEvent; midiEvent.info = event; midiEvent.message = static_cast<MidiChannelMessage>(event.status & 0xF0); midiEvent.channel = static_cast<uint8_t>(event.status & 0xF); switch (midiEvent.message) { case NoteOff: // note off (2 more bytes) case NoteOn: // note on (2 more bytes) midiEvent.data1 = read_type<uint8_t>(m_smfFile); // note midiEvent.data2 = read_type<uint8_t>(m_smfFile); // velocity break; case KeyPressure: midiEvent.data1 = read_type<uint8_t>(m_smfFile); // note midiEvent.data2 = read_type<uint8_t>(m_smfFile); // pressure break; case ControlChange: midiEvent.data1 = read_type<uint8_t>(m_smfFile); // controller midiEvent.data2 = read_type<uint8_t>(m_smfFile); // cont_value break; case ProgramChange: midiEvent.data1 = read_type<uint8_t>(m_smfFile); // program midiEvent.data2 = 0; // no data break; case ChannelPressure: midiEvent.data1 = read_type<uint8_t>(m_smfFile); // pressure midiEvent.data2 = 0; // no data break; case PitchBend: midiEvent.data1 = read_type<uint8_t>(m_smfFile); // pitch_low midiEvent.data2 = read_type<uint8_t>(m_smfFile); // pitch_high break; default: break; } m_currentTrack->midiEvents.push_back(midiEvent); } void SmfReader::read_meta_event(const SmfEventInfo &eventInfo) { MetaEvent event {eventInfo, read_type<MidiMetaEvent>(m_smfFile), read_vlv<uint32_t>(m_smfFile)}; // In the cases where we dont implement an event type log it, and its data. switch(event.type) { case meta_SequenceNumber: { auto sequenceNumber = read_type<uint16_t>(m_smfFile); break; } case meta_Text: case meta_Copyright: case meta_InstrumentName: case meta_Lyrics: // TODO - Implement ruby parser for lyrics case meta_Marker: case meta_CuePoint: // RP-019 - SMF Device Name and Program Name Meta Events case meta_ProgramName: case meta_DeviceName: // The midi spec says the following text events exist and act the same as meta_Text. case meta_TextReserved3: case meta_TextReserved4: case meta_TextReserved5: case meta_TextReserved6: case meta_TextReserved7: case meta_TextReserved8: { auto textData = std::make_unique<char[]>(event.length+1); textData[event.length] = '\0'; read_type<char>(m_smfFile, textData.get(), event.length); m_currentTrack->textEvents.push_back({event, std::string(textData.get())}); break; } case meta_TrackName: { auto textData = std::make_unique<char[]>(event.length+1); textData[event.length] = '\0'; read_type<char>(m_smfFile, textData.get(), event.length); m_currentTrack->name = std::string(textData.get()); break; } case meta_MIDIChannelPrefix: { // TODO - Add channel auto midiChannel = read_type<uint8_t>(m_smfFile); break; } case meta_EndOfTrack: { m_currentTrack->endTime = event.info.pulseTime; break; } case meta_Tempo: { double absTime = 0.0; uint32_t qnLength = read_type<uint32_t>(m_smfFile, 3); double timePerTick = (qnLength / (m_header.division * 1'000'000.0)); // We calculate the absTime of each tempo event from the previous which will act as a base to calculate other events time. // This is good because it reduces the number of doubles we store reducing memory usage somewhat, and it also reduces // the rounding error overall allowing more accurate timestamps. Thanks FireFox of the RGC discord for this idea from his // .chart/midi parser that is used for his moonscraper project. if (eventInfo.pulseTime == 0 && m_tempoTrack.tempo.size() == 1) { m_tempoTrack.tempo[0] = {event, qnLength, absTime, timePerTick}; } else { auto lastTempo = m_tempoTrack.tempo.back(); absTime = lastTempo.absTime + delta_tick_to_delta_time(&lastTempo, eventInfo.pulseTime - lastTempo.info.info.pulseTime ); m_tempoTrack.tempoOrdering.push_back({TtOrderType::Tempo, static_cast<int>(m_tempoTrack.tempo.size())}); m_tempoTrack.tempo.push_back({event, qnLength, absTime, timePerTick}); } break; } case meta_TimeSignature: { TimeSignatureEvent tsEvent; tsEvent.info = event; tsEvent.numerator = read_type<uint8_t>(m_smfFile); // 4 default tsEvent.denominator = std::pow(2, read_type<uint8_t>(m_smfFile)); // 4 default // This is best described as a bad attempt at supporting meter and is basically useless. // The midi spec examples are also extremely misleading tsEvent.clocksPerBeat = read_type<uint8_t>(m_smfFile); // Standard is 24 // The number of 1/32nd notes per "MIDI quarter note" // This should be used in order to change the note value which a "MIDI quarter note" is considered. // For example changing it to be 0x0C(12) should change tempo to be // defined in. // Note "MIDI quarter note" is defined to always be 24 midi clocks therfor even if // changed to dotted quarter it should still be 24 midi clocks // // Later thoughts, this could also mean to change globally what a quarter note means which basically // would make it totally unrelated to ts... But i still stand by my original interpritation as I have // found a reference that contains the same interpritation as above: // // Beyond MIDI: The Handbook of Musical Codes page 54 tsEvent.thirtySecondPQN = read_type<uint8_t>(m_smfFile); // 8 default if (eventInfo.pulseTime == 0 && m_tempoTrack.timeSignature.size() == 1) { m_tempoTrack.timeSignature[0] = tsEvent; } else { m_tempoTrack.tempoOrdering.push_back({TtOrderType::TimeSignature, static_cast<int>(m_tempoTrack.timeSignature.size())}); m_tempoTrack.timeSignature.push_back(tsEvent); } break; } // These are mainly here to just represent them existing :P case meta_MIDIPort: // obsolete no longer used. case meta_SMPTEOffset: // Not currently implemented, maybe someday. case meta_KeySignature: // Not very useful for us case meta_XMFPatchType: // probably not used case meta_SequencerSpecific: default: { // store data for unused event for later save passthrough. std::vector<char> eventData; for (int i=0;i<event.length;++i) { eventData.emplace_back(read_type<char>(m_smfFile)); } m_currentTrack->miscMeta.push_back({event, eventData}); break; } } } void SmfReader::read_sysex_event(const SmfEventInfo &event) { // TODO - Actually implement sysex events, they arent currently saved anywhere. // This will be needed for open notes, or many of the phase shift midi extensions. auto length = read_vlv<uint32_t>(m_smfFile); std::vector<char> sysex; sysex.resize(length); read_type<char>(m_smfFile, &sysex[0], length); } // Convert from deltaPulses to deltaTime. double SmfReader::delta_tick_to_delta_time(TempoEvent* tempo, uint32_t deltaPulses) { return deltaPulses * tempo->timePerTick; } // Converts a absolute time in pulses to an absolute time in seconds double SmfReader::pulsetime_to_abstime(uint32_t pulseTime) { if (pulseTime == 0) { return 0.0; } // The basic idea here is to start from the most recent tempo event before this time. // Then calculate and add the time since that tempo to the tempo time. // To speed this up further we could store the result of the time per tick calculation in the tempo event and only use it here. TempoEvent* tempo = get_last_tempo_via_pulses(pulseTime); return tempo->absTime + ((pulseTime - tempo->info.info.pulseTime) * tempo->timePerTick); } void SmfReader::init_tempo_ts() { // We initialize the vectors in the tempo track to default 120BPM 4/4 ts as defined by the spec. // However these may be overwritten later. m_tempoTrack.tempoOrdering.push_back({TtOrderType::TimeSignature, 0}); m_tempoTrack.tempoOrdering.push_back({TtOrderType::Tempo, 0}); MetaEvent tsEvent {{meta_TimeSignature,0,0}, meta_Tempo, 3}; m_tempoTrack.timeSignature.push_back({tsEvent, 4, 4, 24, 8}); MetaEvent tempoEvent {{status_MetaEvent,0,0}, meta_Tempo, 3}; m_tempoTrack.tempo.push_back({tempoEvent, 500'000, 0.0}); // ppqn, absTime } TempoEvent* SmfReader::get_last_tempo_via_pulses(uint32_t pulseTime) { static unsigned int value = 0; static uint32_t lastPulseTime = 0; std::vector<TempoEvent> &tempos = m_tempoTrack.tempo; // Ignore the cached last tempo value if the new pulse time is older. if (lastPulseTime > pulseTime) { value = 0; } for (unsigned int i = value; i < tempos.size(); i++) { if (tempos[i].info.info.pulseTime > pulseTime) { value = i-1; lastPulseTime = pulseTime; return &tempos[value]; } } // return last value if nothing else is found return &tempos.back(); } SmfHeaderChunk* SmfReader::get_header() { return &m_header; } void SmfReader::read_events(uint32_t chunkEnd) { uint32_t pulseTime = 0; uint8_t oldRunningStatus = 0; bool runningStatusReset = false; // find a ballpark size estimate for the track uint32_t sizeGuess = (chunkEnd - m_smfFile.tellg()) / 3; m_currentTrack->midiEvents.reserve(sizeGuess); SmfEventInfo eventInfo; while (m_smfFile.tellg() < chunkEnd) { eventInfo.deltaPulses = read_vlv<uint32_t>(m_smfFile); // DO NOT use this for time calculations. // You must convert each deltaPulse to a time // within the currently active tempo. pulseTime += eventInfo.deltaPulses; eventInfo.pulseTime = pulseTime; auto status = peek_type<uint8_t>(m_smfFile); if (status == status_MetaEvent) { if (runningStatusReset == false) { runningStatusReset = true; oldRunningStatus = eventInfo.status; } eventInfo.status = read_type<uint8_t>(m_smfFile); read_meta_event(eventInfo); } else if (status == status_SysexEvent || status == status_SysexEvent2) { if (runningStatusReset == false) { runningStatusReset = true; oldRunningStatus = eventInfo.status; } eventInfo.status = read_type<uint8_t>(m_smfFile); read_sysex_event(eventInfo); } else { // Check if we should use the running status. if ((status & 0xF0) >= 0x80) { eventInfo.status = read_type<uint8_t>(m_smfFile); } else if (runningStatusReset) { eventInfo.status = oldRunningStatus; } runningStatusReset = false; read_midi_event(eventInfo); } } } void SmfReader::read_file() { uint32_t fileEnd = static_cast<uint32_t>(m_smfFile.tellg()); m_smfFile.seekg(0, std::ios::beg); uint32_t fileStart = m_smfFile.tellg(); uint32_t filePos = fileStart; uint32_t fileRemaining = fileEnd; SmfChunkInfo chunk; // set the intial chunk starting position at the beginning of the file. uint32_t chunkStart = fileStart; // The chunk end will be calculated after a chunk is loaded. uint32_t chunkEnd = 0; int trackChunkCount = 0; // We could loop through the number of track chunks given in the header. // However if there are any unknown chunk types inside the midi file // this will likely break. So we just loop until we hit the end of the // file instead... while (filePos < fileEnd) { read_type<char>(m_smfFile, chunk.chunkType, 4); chunk.length = read_type<uint32_t>(m_smfFile); chunkEnd = chunkStart + (8 + chunk.length); // 8 is the length of the type + length fields // MThd chunk is only in the beginning of the file. if (chunkStart == fileStart && strcmp(chunk.chunkType, "MThd") == 0) { // Load header chunk m_header.info = chunk; m_header.format = read_type<uint16_t>(m_smfFile); m_header.trackNum = read_type<uint16_t>(m_smfFile); m_header.division = read_type<int16_t>(m_smfFile); // Make sure we reserve enough space for m_tracks just in-case. m_tracks.reserve(sizeof(SmfTrack) * m_header.trackNum); if (m_header.format == smfType0 && m_header.trackNum != 1) { throw std::runtime_error("Not a valid type 0 midi."); } else if (m_header.format == smfType2) { throw std::runtime_error("Type 2 midi not supported."); } if ((m_header.division & 0x8000) != 0) { throw std::runtime_error("SMPTE time division not supported"); } } else if (strcmp(chunk.chunkType, "MTrk") == 0) { trackChunkCount += 1; m_tracks.emplace_back(); m_currentTrack = &m_tracks.back(); read_events(chunkEnd); } filePos = chunkEnd; chunkStart = filePos; // Make sure that we are in the correct location in the chunk // If not seek to the correct location and output an error in the log. if (static_cast<int>(m_smfFile.tellg()) != filePos) { m_smfFile.seekg(filePos); } fileRemaining = (fileEnd-filePos); if (fileRemaining != 0 && fileRemaining <= 8) { // Skip the rest of the file. break; } } } }
38.659864
141
0.557217
mdsitton
eec853019dbecfe80a98045780511b34cc572681
49,447
cc
C++
src/chirpstack_client.cc
chungphb/chirpstack-client
6a0f80f887776d6270ef821be1ccf99d87aca146
[ "MIT" ]
1
2022-01-20T02:44:29.000Z
2022-01-20T02:44:29.000Z
src/chirpstack_client.cc
chungphb/chirpstack-cpp-client
6a0f80f887776d6270ef821be1ccf99d87aca146
[ "MIT" ]
null
null
null
src/chirpstack_client.cc
chungphb/chirpstack-cpp-client
6a0f80f887776d6270ef821be1ccf99d87aca146
[ "MIT" ]
null
null
null
// // Created by chungphb on 2/6/21. // #include <chirpstack_client/chirpstack_client.h> #include <utility> using namespace api; using namespace grpc; namespace chirpstack_cpp_client { chirpstack_client::chirpstack_client(const std::string& server_address, chirpstack_client_config config) { _channel = CreateChannel(server_address, grpc::InsecureChannelCredentials()); _config = std::move(config); _application_service_stub = ApplicationService::NewStub(_channel); _device_service_stub = DeviceService::NewStub(_channel); _device_profile_service_stub = DeviceProfileService::NewStub(_channel); _device_queue_service_stub = DeviceQueueService::NewStub(_channel); _gateway_service_stub = GatewayService::NewStub(_channel); _gateway_profile_service_stub = GatewayProfileService::NewStub(_channel); _internal_service_stub = InternalService::NewStub(_channel); _multicast_group_service_stub = MulticastGroupService::NewStub(_channel); _network_server_service_stub = NetworkServerService::NewStub(_channel); _organization_service_stub = OrganizationService::NewStub(_channel); _service_profile_service_stub = ServiceProfileService::NewStub(_channel); _user_service_stub = UserService::NewStub(_channel); } // Application Service create_application_response chirpstack_client::create_application(const create_application_request& request) { create_application_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _application_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_application_response{status.error_code()}; } else { return create_application_response{std::move(response)}; } } get_application_response chirpstack_client::get_application(const get_application_request& request) { get_application_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _application_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_application_response{status.error_code()}; } else { return get_application_response{std::move(response)}; } } update_application_response chirpstack_client::update_application(const update_application_request& request) { update_application_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _application_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_application_response{status.error_code()}; } else { return update_application_response{std::move(response)}; } } delete_application_response chirpstack_client::delete_application(const delete_application_request& request) { delete_application_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _application_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_application_response{status.error_code()}; } else { return delete_application_response{std::move(response)}; } } list_application_response chirpstack_client::list_application(const list_application_request& request) { list_application_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _application_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_application_response{status.error_code()}; } else { return list_application_response{std::move(response)}; } } // Device Service create_device_response chirpstack_client::create_device(const create_device_request& request) { create_device_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_device_response{status.error_code()}; } else { return create_device_response{std::move(response)}; } } get_device_response chirpstack_client::get_device(const get_device_request& request) { get_device_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_device_response{status.error_code()}; } else { return get_device_response{std::move(response)}; } } update_device_response chirpstack_client::update_device(const update_device_request& request) { update_device_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_device_response{status.error_code()}; } else { return update_device_response{std::move(response)}; } } delete_device_response chirpstack_client::delete_device(const delete_device_request& request) { delete_device_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_device_response{status.error_code()}; } else { return delete_device_response{std::move(response)}; } } list_device_response chirpstack_client::list_device(const list_device_request& request) { list_device_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_device_response{status.error_code()}; } else { return list_device_response{std::move(response)}; } } create_device_keys_response chirpstack_client::create_device_keys(const create_device_keys_request& request) { create_device_keys_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->CreateKeys(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_device_keys_response{status.error_code()}; } else { return create_device_keys_response{std::move(response)}; } } get_device_keys_response chirpstack_client::get_device_keys(const get_device_keys_request& request) { get_device_keys_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->GetKeys(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_device_keys_response{status.error_code()}; } else { return get_device_keys_response{std::move(response)}; } } update_device_keys_response chirpstack_client::update_device_keys(const update_device_keys_request& request) { update_device_keys_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->UpdateKeys(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_device_keys_response{status.error_code()}; } else { return update_device_keys_response{std::move(response)}; } } delete_device_keys_response chirpstack_client::delete_device_keys(const delete_device_keys_request& request) { delete_device_keys_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->DeleteKeys(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_device_keys_response{status.error_code()}; } else { return delete_device_keys_response{std::move(response)}; } } activate_device_response chirpstack_client::activate_device(const activate_device_request& request) { activate_device_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->Activate(&context, request, &response); if (!status.ok()) { log(status.error_message()); return activate_device_response{status.error_code()}; } else { return activate_device_response{std::move(response)}; } } deactivate_device_response chirpstack_client::deactivate_device(const deactivate_device_request& request) { delete_device_keys_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->Deactivate(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_device_keys_response{status.error_code()}; } else { return delete_device_keys_response{std::move(response)}; } } get_device_activation_response chirpstack_client::get_device_activation(const get_device_activation_request& request) { get_device_activation_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->GetActivation(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_device_activation_response{status.error_code()}; } else { return get_device_activation_response{std::move(response)}; } } get_random_dev_addr_response chirpstack_client::get_random_dev_addr(const get_random_dev_addr_request& request) { get_random_dev_addr_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_service_stub->GetRandomDevAddr(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_random_dev_addr_response{status.error_code()}; } else { return get_random_dev_addr_response{std::move(response)}; } } // Device Profile Service create_device_profile_response chirpstack_client::create_device_profile(const create_device_profile_request& request) { create_device_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_profile_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_device_profile_response{status.error_code()}; } else { return create_device_profile_response{std::move(response)}; } } get_device_profile_response chirpstack_client::get_device_profile(const get_device_profile_request& request) { get_device_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_profile_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_device_profile_response{status.error_code()}; } else { return get_device_profile_response{std::move(response)}; } } update_device_profile_response chirpstack_client::update_device_profile(const update_device_profile_request& request) { update_device_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_profile_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_device_profile_response{status.error_code()}; } else { return update_device_profile_response{std::move(response)}; } } delete_device_profile_response chirpstack_client::delete_device_profile(const delete_device_profile_request& request) { delete_device_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_profile_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_device_profile_response{status.error_code()}; } else { return delete_device_profile_response{std::move(response)}; } } list_device_profile_response chirpstack_client::list_device_profile(const list_device_profile_request& request) { list_device_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_profile_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_device_profile_response{status.error_code()}; } else { return list_device_profile_response{std::move(response)}; } } // Device Queue Service enqueue_device_queue_item_response chirpstack_client::enqueue_device_queue_item(const enqueue_device_queue_item_request& request) { enqueue_device_queue_item_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_queue_service_stub->Enqueue(&context, request, &response); if (!status.ok()) { log(status.error_message()); return enqueue_device_queue_item_response{status.error_code()}; } else { return enqueue_device_queue_item_response{std::move(response)}; } } flush_device_queue_response chirpstack_client::flush_device_queue(const flush_device_queue_request& request) { flush_device_queue_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_queue_service_stub->Flush(&context, request, &response); if (!status.ok()) { log(status.error_message()); return flush_device_queue_response{status.error_code()}; } else { return flush_device_queue_response{std::move(response)}; } } list_device_queue_items_response chirpstack_client::list_device_queue_items(const list_device_queue_items_request& request) { list_device_queue_items_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _device_queue_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_device_queue_items_response{status.error_code()}; } else { return list_device_queue_items_response{std::move(response)}; } } // Gateway Service create_gateway_response chirpstack_client::create_gateway(const create_gateway_request& request) { create_gateway_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_gateway_response{status.error_code()}; } else { return create_gateway_response{std::move(response)}; } } get_gateway_response chirpstack_client::get_gateway(const get_gateway_request& request) { get_gateway_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_gateway_response{status.error_code()}; } else { return get_gateway_response{std::move(response)}; } } update_gateway_response chirpstack_client::update_gateway(const update_gateway_request& request) { create_gateway_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_gateway_response{status.error_code()}; } else { return update_gateway_response{std::move(response)}; } } delete_gateway_response chirpstack_client::delete_gateway(const delete_gateway_request& request) { delete_gateway_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_gateway_response{status.error_code()}; } else { return delete_gateway_response{std::move(response)}; } } list_gateway_response chirpstack_client::list_gateway(const list_gateway_request& request) { list_gateway_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_gateway_response{status.error_code()}; } else { return list_gateway_response{std::move(response)}; } } get_gateway_stats_response chirpstack_client::get_gateway_stats(const get_gateway_stats_request& request) { get_gateway_stats_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_service_stub->GetStats(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_gateway_stats_response{status.error_code()}; } else { return get_gateway_stats_response{std::move(response)}; } } get_last_ping_response chirpstack_client::get_last_ping(const get_last_ping_request& request) { get_last_ping_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_service_stub->GetLastPing(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_last_ping_response{status.error_code()}; } else { return get_last_ping_response{std::move(response)}; } } generate_gateway_client_certificate_response chirpstack_client::generate_gateway_client_certificate(const generate_gateway_client_certificate_request& request) { generate_gateway_client_certificate_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_service_stub->GenerateGatewayClientCertificate(&context, request, &response); if (!status.ok()) { log(status.error_message()); return generate_gateway_client_certificate_response{status.error_code()}; } else { return generate_gateway_client_certificate_response{std::move(response)}; } } // Gateway Profile Service create_gateway_profile_response chirpstack_client::create_gateway_profile(const create_gateway_profile_request& request) { create_gateway_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_profile_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_gateway_profile_response{status.error_code()}; } else { return create_gateway_profile_response{std::move(response)}; } } get_gateway_profile_response chirpstack_client::get_gateway_profile(const get_gateway_profile_request& request) { get_gateway_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_profile_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_gateway_profile_response{status.error_code()}; } else { return get_gateway_profile_response{std::move(response)}; } } update_gateway_profile_response chirpstack_client::update_gateway_profile(const update_gateway_profile_request& request) { update_gateway_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_profile_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_gateway_profile_response{status.error_code()}; } else { return update_gateway_profile_response{std::move(response)}; } } delete_gateway_profile_response chirpstack_client::delete_gateway_profile(const delete_gateway_profile_request& request) { delete_gateway_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_profile_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_gateway_profile_response{status.error_code()}; } else { return delete_gateway_profile_response{std::move(response)}; } } list_gateway_profiles_response chirpstack_client::list_gateway_profiles(const list_gateway_profiles_request& request) { list_gateway_profiles_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _gateway_profile_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_gateway_profiles_response{status.error_code()}; } else { return list_gateway_profiles_response{std::move(response)}; } } // Internal Service login_response chirpstack_client::login(const login_request& request) { login_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->Login(&context, request, &response); if (!status.ok()) { log(status.error_message()); return login_response{status.error_code()}; } else { return login_response{std::move(response)}; } } profile_response chirpstack_client::profile(const profile_request& request) { profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->Profile(&context, request, &response); if (!status.ok()) { log(status.error_message()); return profile_response{status.error_code()}; } else { return profile_response{std::move(response)}; } } global_search_response chirpstack_client::global_search(const global_search_request& request) { global_search_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->GlobalSearch(&context, request, &response); if (!status.ok()) { log(status.error_message()); return global_search_response{status.error_code()}; } else { return global_search_response{std::move(response)}; } } create_api_key_response chirpstack_client::create_api_key(const create_api_key_request& request) { create_api_key_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->CreateAPIKey(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_api_key_response{status.error_code()}; } else { return create_api_key_response{std::move(response)}; } } delete_api_key_response chirpstack_client::delete_api_key(const delete_api_key_request& request) { delete_api_key_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->DeleteAPIKey(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_api_key_response{status.error_code()}; } else { return delete_api_key_response{std::move(response)}; } } list_api_keys_response chirpstack_client::list_api_keys(const list_api_keys_request& request) { list_api_keys_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->ListAPIKeys(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_api_keys_response{status.error_code()}; } else { return list_api_keys_response{std::move(response)}; } } settings_response chirpstack_client::settings(const settings_request& request) { settings_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->Settings(&context, request, &response); if (!status.ok()) { log(status.error_message()); return settings_response{status.error_code()}; } else { return settings_response{std::move(response)}; } } open_id_connect_login_response chirpstack_client::open_id_connect_login(const open_id_connect_login_request& request) { open_id_connect_login_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->OpenIDConnectLogin(&context, request, &response); if (!status.ok()) { log(status.error_message()); return open_id_connect_login_response{status.error_code()}; } else { return open_id_connect_login_response{std::move(response)}; } } get_devices_summary_response chirpstack_client::get_devices_summary(const get_devices_summary_request& request) { get_devices_summary_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->GetDevicesSummary(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_devices_summary_response{status.error_code()}; } else { return get_devices_summary_response{std::move(response)}; } } get_gateways_summary_response chirpstack_client::get_gateways_summary(const get_gateways_summary_request& request) { get_gateways_summary_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _internal_service_stub->GetGatewaysSummary(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_gateways_summary_response{status.error_code()}; } else { return get_gateways_summary_response{std::move(response)}; } } // Multicast Group Service create_multicast_group_response chirpstack_client::create_multicast_group(const create_multicast_group_request& request) { create_multicast_group_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_multicast_group_response{status.error_code()}; } else { return create_multicast_group_response{std::move(response)}; } } get_multicast_group_response chirpstack_client::get_multicast_group(const get_multicast_group_request& request) { get_multicast_group_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_multicast_group_response{status.error_code()}; } else { return get_multicast_group_response{std::move(response)}; } } update_multicast_group_response chirpstack_client::update_multicast_group(const update_multicast_group_request& request) { update_multicast_group_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_multicast_group_response{status.error_code()}; } else { return update_multicast_group_response{std::move(response)}; } } delete_multicast_group_response chirpstack_client::delete_multicast_group(const delete_multicast_group_request& request) { delete_multicast_group_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_multicast_group_response{status.error_code()}; } else { return delete_multicast_group_response{std::move(response)}; } } list_multicast_group_response chirpstack_client::list_multicast_group(const list_multicast_group_request& request) { list_multicast_group_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_multicast_group_response{status.error_code()}; } else { return list_multicast_group_response{std::move(response)}; } } add_device_to_multicast_group_response chirpstack_client::add_device_to_multicast_group(const add_device_to_multicast_group_request& request) { add_device_to_multicast_group_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->AddDevice(&context, request, &response); if (!status.ok()) { log(status.error_message()); return add_device_to_multicast_group_response{status.error_code()}; } else { return add_device_to_multicast_group_response{std::move(response)}; } } remove_device_from_multicast_group_response chirpstack_client::remove_device_from_multicast_group(const remove_device_from_multicast_group_request& request) { remove_device_from_multicast_group_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->RemoveDevice(&context, request, &response); if (!status.ok()) { log(status.error_message()); return remove_device_from_multicast_group_response{status.error_code()}; } else { return remove_device_from_multicast_group_response{std::move(response)}; } } enqueue_multicast_queue_item_response chirpstack_client::enqueue_multicast_queue_item(const enqueue_multicast_queue_item_request& request) { enqueue_multicast_queue_item_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->Enqueue(&context, request, &response); if (!status.ok()) { log(status.error_message()); return enqueue_multicast_queue_item_response{status.error_code()}; } else { return enqueue_multicast_queue_item_response{std::move(response)}; } } flush_multicast_group_queue_items_response chirpstack_client::flush_multicast_group_queue_items(const flush_multicast_group_queue_items_request& request) { flush_multicast_group_queue_items_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->FlushQueue(&context, request, &response); if (!status.ok()) { log(status.error_message()); return flush_multicast_group_queue_items_response{status.error_code()}; } else { return flush_multicast_group_queue_items_response{std::move(response)}; } } list_multicast_group_queue_items_response chirpstack_client::list_multicast_group_queue_items(const list_multicast_group_queue_items_request& request) { list_multicast_group_queue_items_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _multicast_group_service_stub->ListQueue(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_multicast_group_queue_items_response{status.error_code()}; } else { return list_multicast_group_queue_items_response{std::move(response)}; } } // Network Server Service create_network_server_response chirpstack_client::create_network_server(const create_network_server_request& request) { create_network_server_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _network_server_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_network_server_response{status.error_code()}; } else { return create_network_server_response{std::move(response)}; } } get_network_server_response chirpstack_client::get_network_server(const get_network_server_request& request) { get_network_server_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _network_server_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_network_server_response{status.error_code()}; } else { return get_network_server_response{std::move(response)}; } } update_network_server_response chirpstack_client::update_network_server(const update_network_server_request& request) { update_network_server_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _network_server_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_network_server_response{status.error_code()}; } else { return update_network_server_response{std::move(response)}; } } delete_network_server_response chirpstack_client::delete_network_server(const delete_network_server_request& request) { delete_network_server_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _network_server_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_network_server_response{status.error_code()}; } else { return delete_network_server_response{std::move(response)}; } } list_network_server_response chirpstack_client::list_network_server(const list_network_server_request& request) { list_network_server_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _network_server_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_network_server_response{status.error_code()}; } else { return list_network_server_response{std::move(response)}; } } get_adr_algorithms_response chirpstack_client::get_adr_algorithms(const get_adr_algorithms_request& request) { get_adr_algorithms_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _network_server_service_stub->GetADRAlgorithms(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_adr_algorithms_response{status.error_code()}; } else { return get_adr_algorithms_response{std::move(response)}; } } // Organization Service create_organization_response chirpstack_client::create_organization(const create_organization_request& request) { create_organization_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_organization_response{status.error_code()}; } else { return create_organization_response{std::move(response)}; } } get_organization_response chirpstack_client::get_organization(const get_organization_request& request) { get_organization_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_organization_response{status.error_code()}; } else { return get_organization_response{std::move(response)}; } } update_organization_response chirpstack_client::update_organization(const update_organization_request& request) { update_organization_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_organization_response{status.error_code()}; } else { return update_organization_response{std::move(response)}; } } delete_organization_response chirpstack_client::delete_organization(const delete_organization_request& request) { delete_organization_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_organization_response{status.error_code()}; } else { return delete_organization_response{std::move(response)}; } } list_organization_response chirpstack_client::list_organization(const list_organization_request& request) { list_organization_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_organization_response{status.error_code()}; } else { return list_organization_response{std::move(response)}; } } add_organization_user_response chirpstack_client::add_organization_user(const add_organization_user_request& request) { add_organization_user_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->AddUser(&context, request, &response); if (!status.ok()) { log(status.error_message()); return add_organization_user_response{status.error_code()}; } else { return add_organization_user_response{std::move(response)}; } } get_organization_user_response chirpstack_client::get_organization_user(const get_organization_user_request& request) { get_organization_user_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->GetUser(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_organization_user_response{status.error_code()}; } else { return get_organization_user_response{std::move(response)}; } } update_organization_user_response chirpstack_client::update_organization_user(const update_organization_user_request& request) { update_organization_user_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->UpdateUser(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_organization_user_response{status.error_code()}; } else { return update_organization_user_response{std::move(response)}; } } delete_organization_user_response chirpstack_client::delete_organization_user(const delete_organization_user_request& request) { delete_organization_user_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->DeleteUser(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_organization_user_response{status.error_code()}; } else { return delete_organization_user_response{std::move(response)}; } } list_organization_users_response chirpstack_client::list_organization_users(const list_organization_users_request& request) { list_organization_users_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _organization_service_stub->ListUsers(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_organization_users_response{status.error_code()}; } else { return list_organization_users_response{std::move(response)}; } } // Service Profile Service create_service_profile_response chirpstack_client::create_service_profile(const create_service_profile_request& request) { create_service_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _service_profile_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_service_profile_response{status.error_code()}; } else { return create_service_profile_response{std::move(response)}; } } get_service_profile_response chirpstack_client::get_service_profile(const get_service_profile_request& request) { get_service_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _service_profile_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_service_profile_response{status.error_code()}; } else { return get_service_profile_response{std::move(response)}; } } update_service_profile_response chirpstack_client::update_service_profile(const update_service_profile_request& request) { update_service_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _service_profile_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_service_profile_response{status.error_code()}; } else { return update_service_profile_response{std::move(response)}; } } delete_service_profile_response chirpstack_client::delete_service_profile(const delete_service_profile_request& request) { delete_service_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _service_profile_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_service_profile_response{status.error_code()}; } else { return delete_service_profile_response{std::move(response)}; } } list_service_profile_response chirpstack_client::list_service_profile(const list_service_profile_request& request) { list_service_profile_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _service_profile_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_service_profile_response{status.error_code()}; } else { return list_service_profile_response{std::move(response)}; } } // User Service create_user_response chirpstack_client::create_user(const create_user_request& request) { create_user_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _user_service_stub->Create(&context, request, &response); if (!status.ok()) { log(status.error_message()); return create_user_response{status.error_code()}; } else { return create_user_response{std::move(response)}; } } get_user_response chirpstack_client::get_user(const get_user_request& request) { get_user_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _user_service_stub->Get(&context, request, &response); if (!status.ok()) { log(status.error_message()); return get_user_response{status.error_code()}; } else { return get_user_response{std::move(response)}; } } update_user_response chirpstack_client::update_user(const update_user_request& request) { update_user_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _user_service_stub->Update(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_user_response{status.error_code()}; } else { return update_user_response{std::move(response)}; } } delete_user_response chirpstack_client::delete_user(const delete_user_request& request) { delete_user_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _user_service_stub->Delete(&context, request, &response); if (!status.ok()) { log(status.error_message()); return delete_user_response{status.error_code()}; } else { return delete_user_response{std::move(response)}; } } list_user_response chirpstack_client::list_user(const list_user_request& request) { list_user_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _user_service_stub->List(&context, request, &response); if (!status.ok()) { log(status.error_message()); return list_user_response{status.error_code()}; } else { return list_user_response{std::move(response)}; } } update_user_password_response chirpstack_client::update_user_password(const update_user_password_request& request) { update_user_password_response::value_type response; ClientContext context; context.AddMetadata("authorization", _config.jwt_token); auto status = _user_service_stub->UpdatePassword(&context, request, &response); if (!status.ok()) { log(status.error_message()); return update_user_password_response{status.error_code()}; } else { return update_user_password_response{std::move(response)}; } } void chirpstack_client::set_jwt_token(const std::string& jwt_token) { _config.jwt_token = jwt_token; } void chirpstack_client::enable_log() { _config.log_enabled = true; } void chirpstack_client::disable_log() { _config.log_enabled = false; } void chirpstack_client::log(const std::string& error_message) { if (_config.log_enabled) { printf("%s\n", error_message.c_str()); } } }
41.517212
161
0.745647
chungphb
eec9dd2390af11b86e3b6602d5e1f1a80813dcd1
8,315
cpp
C++
src/NIfValid.cpp
justinmann/sj
24d0a75723b024f17de6dab9070979a4f1bf1a60
[ "Apache-2.0" ]
2
2017-01-04T02:27:10.000Z
2017-01-22T05:36:41.000Z
src/NIfValid.cpp
justinmann/sj
24d0a75723b024f17de6dab9070979a4f1bf1a60
[ "Apache-2.0" ]
null
null
null
src/NIfValid.cpp
justinmann/sj
24d0a75723b024f17de6dab9070979a4f1bf1a60
[ "Apache-2.0" ]
1
2020-06-15T12:17:26.000Z
2020-06-15T12:17:26.000Z
#include <sjc.h> bool CIfValidVar::getReturnThis() { return false; } shared_ptr<CType> CIfValidVar::getType(Compiler* compiler) { if (ifVar && elseVar) { return ifVar->getType(compiler); } return compiler->typeVoid; } void CIfValidVar::transpile(Compiler* compiler, TrOutput* trOutput, TrBlock* trBlock, shared_ptr<TrValue> thisValue, shared_ptr<TrStoreValue> storeValue) { if (!storeValue->isVoid) { storeValue->getName(trBlock); // Force capture values to become named } auto ifStoreValue = storeValue; auto elseStoreValue = storeValue; if (ifVar && elseVar) { auto ifType = ifVar->getType(compiler); auto elseType = elseVar->getType(compiler); if (ifType != elseType) { if (!storeValue->isVoid) { compiler->addError(loc, CErrorCode::TypeMismatch, "if block return type '%s' does not match else block return type '%s'", ifType->fullName.c_str(), elseType->fullName.c_str()); return; } else { ifStoreValue = trBlock->createVoidStoreVariable(loc, ifType); elseStoreValue = trBlock->createVoidStoreVariable(loc, elseType); } } } bool isFirst = true; stringstream ifLine; ifLine << "if ("; auto type = getType(compiler); vector<shared_ptr<TrStoreValue>> isValidValues; for (auto optionalVar : optionalVars) { auto trValue = trBlock->createCaptureStoreVariable(loc, nullptr, compiler->typeBool); optionalVar.isValidVar->transpile(compiler, trOutput, trBlock, thisValue, trValue); if (!trValue->hasSetValue) { return; } if (isFirst) { isFirst = false; } else { ifLine << " && "; } ifLine << trValue->getCaptureText(); } ifLine << ")"; auto trIfBlock = make_shared<TrBlock>(trBlock); trIfBlock->hasThis = trBlock->hasThis; trIfBlock->localVarParent = ifLocalVarScope ? nullptr : trBlock; auto trStatement = TrStatement(loc, ifLine.str(), trIfBlock); scope.lock()->pushLocalVarScope(ifLocalVarScope); for (auto optionalVar : optionalVars) { auto localStoreValue = optionalVar.storeVar->getStoreValue(compiler, scope.lock(), trOutput, trIfBlock.get(), thisValue, AssignOp::immutableCreate); optionalVar.getValueVar->transpile(compiler, trOutput, trIfBlock.get(), thisValue, localStoreValue); } ifVar->transpile(compiler, trOutput, trIfBlock.get(), thisValue, ifStoreValue); scope.lock()->popLocalVarScope(ifLocalVarScope); if (elseVar) { auto trElseBlock = make_shared<TrBlock>(trBlock); trElseBlock->localVarParent = elseLocalVarScope ? nullptr : trBlock; trElseBlock->hasThis = trBlock->hasThis; trStatement.elseBlock = trElseBlock; scope.lock()->pushLocalVarScope(elseLocalVarScope); elseVar->transpile(compiler, trOutput, trElseBlock.get(), thisValue, elseStoreValue); scope.lock()->popLocalVarScope(elseLocalVarScope); } else { if (!storeValue->isVoid) { compiler->addError(loc, CErrorCode::NoDefaultValue, "if you store the result of an if clause then you must specify an else clause"); } } trBlock->statements.push_back(trStatement); } void CIfValidVar::dump(Compiler* compiler, map<shared_ptr<CBaseFunction>, string>& functions, stringstream& ss, int level) { ss << "ifValue "; if (ifVar) { ss << " "; scope.lock()->pushLocalVarScope(ifLocalVarScope); ifVar->dump(compiler, functions, ss, level); scope.lock()->popLocalVarScope(ifLocalVarScope); } if (elseVar) { ss << " elseEmpty "; scope.lock()->pushLocalVarScope(elseLocalVarScope); elseVar->dump(compiler, functions, ss, level); scope.lock()->popLocalVarScope(elseLocalVarScope); } } void NIfValid::initFunctionsImpl(Compiler* compiler, vector<pair<string, vector<string>>>& importNamespaces, vector<string>& packageNamespace, shared_ptr<CBaseFunctionDefinition> thisFunction) { if (elseBlock) { elseBlock->initFunctions(compiler, importNamespaces, packageNamespace, thisFunction); } if (ifBlock) { ifBlock->initFunctions(compiler, importNamespaces, packageNamespace, thisFunction); } } void NIfValid::initVarsImpl(Compiler* compiler, shared_ptr<CScope> scope, CTypeMode returnMode) { if (elseBlock) { elseBlock->initVars(compiler, scope, returnMode); } if (ifBlock) { ifBlock->initVars(compiler, scope, returnMode); } } shared_ptr<CVar> NIfValid::getVarImpl(Compiler* compiler, shared_ptr<CScope> scope, shared_ptr<CVar> dotVar, shared_ptr<CType> returnType, CTypeMode returnMode) { vector<CIfParameter> optionalVars; for (auto var : *vars) { if (var->nodeType == NodeType_Assignment) { CIfParameter param; auto cname = TrBlock::nextVarName("ifValue"); auto assignment = static_pointer_cast<NAssignment>(var); auto optionalVar = assignment->rightSide->getVar(compiler, scope, nullptr, CTM_Undefined); if (!optionalVar) { return nullptr; } param.isValidVar = make_shared<CIsEmptyOrValidVar>(loc, scope, optionalVar, false); param.getValueVar = make_shared<CGetValueVar>(loc, scope, optionalVar, true); auto storeType = param.getValueVar->getType(compiler); if (!storeType) { return nullptr; } if (storeType->typeMode == CTM_Stack) { storeType = storeType->getTempType(); } param.storeVar = make_shared<CNormalVar>(loc, scope, storeType, assignment->name, cname, false, CVarType::Var_Local, nullptr); optionalVars.push_back(param); } else if (var->nodeType == NodeType_Variable) { CIfParameter param; auto cname = TrBlock::nextVarName("ifValue"); auto variable = static_pointer_cast<NVariable>(var); auto optionalVar = variable->getVar(compiler, scope, nullptr, nullptr, CTM_Undefined); if (!optionalVar) { return nullptr; } param.isValidVar = make_shared<CIsEmptyOrValidVar>(loc, scope, optionalVar, false); param.getValueVar = make_shared<CGetValueVar>(loc, scope, optionalVar, true); auto storeType = param.getValueVar->getType(compiler); if (!storeType) { return nullptr; } if (storeType->typeMode == CTM_Stack) { storeType = storeType->getTempType(); } param.storeVar = make_shared<CNormalVar>(loc, scope, storeType, variable->name, cname, false, CVarType::Var_Local, nullptr); optionalVars.push_back(param); } else { compiler->addError(loc, CErrorCode::Internal, "ifValue can only have var or assignment"); return nullptr; } } shared_ptr<LocalVarScope> elseLocalVarScope; shared_ptr<CVar> elseVar; if (elseBlock) { elseLocalVarScope = make_shared<LocalVarScope>(); scope->pushLocalVarScope(elseLocalVarScope); elseVar = elseBlock->getVar(compiler, scope, returnType, returnMode); scope->popLocalVarScope(elseLocalVarScope); } shared_ptr<LocalVarScope> ifLocalVarScope; shared_ptr<CVar> ifVar; ifLocalVarScope = make_shared<LocalVarScope>(); scope->pushLocalVarScope(ifLocalVarScope); for (auto optionalVar : optionalVars) { scope->setLocalVar(compiler, loc, optionalVar.storeVar, true); } ifVar = ifBlock->getVar(compiler, scope, returnType, returnMode); scope->popLocalVarScope(ifLocalVarScope); if (ifVar == nullptr) { return nullptr; } auto ifType = ifVar->getType(compiler); if (!ifType) { return nullptr; } if (elseVar) { auto elseType = elseVar->getType(compiler); if (!elseType) { return nullptr; } } return make_shared<CIfValidVar>(loc, ifVar->scope.lock(), optionalVars, ifVar, ifLocalVarScope, elseVar, elseLocalVarScope); }
37.968037
194
0.638364
justinmann
eed0022b11768f6e55a13ec9bb78d4c45a30cee6
19,556
cpp
C++
test/json_printer_stream_test.cpp
gsbecerrag/cppagent
f64b1906be32b43656b905e1f5d17c4e7ccbf094
[ "Apache-2.0" ]
null
null
null
test/json_printer_stream_test.cpp
gsbecerrag/cppagent
f64b1906be32b43656b905e1f5d17c4e7ccbf094
[ "Apache-2.0" ]
null
null
null
test/json_printer_stream_test.cpp
gsbecerrag/cppagent
f64b1906be32b43656b905e1f5d17c4e7ccbf094
[ "Apache-2.0" ]
null
null
null
// // Copyright Copyright 2009-2019, 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. // // Ensure that gtest is the first header otherwise Windows raises an error #include <gtest/gtest.h> // Keep this comment to keep gtest.h above. (clang-format off/on is not working here!) #include "checkpoint.hpp" #include "data_item.hpp" #include "device.hpp" #include "globals.hpp" #include "json_helper.hpp" #include "json_printer.hpp" #include "observation.hpp" #include "test_globals.hpp" #include "xml_parser.hpp" #include "xml_printer.hpp" #include <nlohmann/json.hpp> #include <fstream> #include <iostream> #include <memory> #include <sstream> #include <string> using json = nlohmann::json; using namespace std; using namespace mtconnect; class JsonPrinterStreamTest : public testing::Test { protected: void SetUp() override { m_xmlPrinter = std::make_unique<XmlPrinter>("1.5"); m_printer = std::make_unique<JsonPrinter>("1.5", true); m_config = std::make_unique<XmlParser>(); m_devices = m_config->parseFile(PROJECT_ROOT_DIR "/samples/SimpleDevlce.xml", m_xmlPrinter.get()); } void TearDown() override { m_config.reset(); m_xmlPrinter.reset(); m_printer.reset(); } DataItem *getDataItem(const char *name) { for (auto &device : m_devices) { auto di = device->getDeviceDataItem(name); if (di) return di; } return nullptr; } void addObservationToCheckpoint(Checkpoint &checkpoint, const char *name, uint64_t sequence, string value, string time = "TIME") { const auto d = getDataItem(name); ASSERT_TRUE(d) << "Could not find data item " << name; auto event = new Observation(*d, sequence, time, value); checkpoint.addObservation(event); } protected: std::unique_ptr<JsonPrinter> m_printer; std::unique_ptr<XmlParser> m_config; std::unique_ptr<XmlPrinter> m_xmlPrinter; std::vector<Device *> m_devices; }; TEST_F(JsonPrinterStreamTest, StreamHeader) { Checkpoint checkpoint; ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto it = jdoc.begin(); ASSERT_EQ(string("MTConnectStreams"), it.key()); ASSERT_EQ(123, jdoc.at("/MTConnectStreams/Header/instanceId"_json_pointer).get<int32_t>()); ASSERT_EQ(131072, jdoc.at("/MTConnectStreams/Header/bufferSize"_json_pointer).get<int32_t>()); ASSERT_EQ(uint64_t(10254805), jdoc.at("/MTConnectStreams/Header/nextSequence"_json_pointer).get<uint64_t>()); ASSERT_EQ(uint64_t(10123733), jdoc.at("/MTConnectStreams/Header/firstSequence"_json_pointer).get<uint64_t>()); ASSERT_EQ(uint64_t(10123800), jdoc.at("/MTConnectStreams/Header/lastSequence"_json_pointer).get<uint64_t>()); } TEST_F(JsonPrinterStreamTest, DeviceStream) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "Xpos", 10254804, "100"); ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); // cout << "\n" << doc << endl; auto jdoc = json::parse(doc); json stream = jdoc.at("/MTConnectStreams/Streams/0/DeviceStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("SimpleCnc"), stream.at("/name"_json_pointer).get<string>()); ASSERT_EQ(string("872a3490-bd2d-0136-3eb0-0c85909298d9"), stream.at("/uuid"_json_pointer).get<string>()); } TEST_F(JsonPrinterStreamTest, ComponentStream) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "Xpos", 10254804, "100"); ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); json stream = jdoc.at( "/MTConnectStreams/Streams/0/DeviceStream/ComponentStreams/0/ComponentStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("Linear"), stream.at("/component"_json_pointer).get<string>()); ASSERT_EQ(string("X1"), stream.at("/name"_json_pointer).get<string>()); ASSERT_EQ(string("e373fec0"), stream.at("/componentId"_json_pointer).get<string>()); } TEST_F(JsonPrinterStreamTest, ComponentStreamTwoComponents) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "Xpos", 10254804, "100"); addObservationToCheckpoint(checkpoint, "Sspeed_act", 10254805, "500"); ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto streams = jdoc.at("/MTConnectStreams/Streams/0/DeviceStream/ComponentStreams"_json_pointer); ASSERT_EQ(2_S, streams.size()); json stream1 = streams.at("/0/ComponentStream"_json_pointer); ASSERT_TRUE(stream1.is_object()); ASSERT_EQ(string("Linear"), stream1.at("/component"_json_pointer).get<string>()); ASSERT_EQ(string("e373fec0"), stream1.at("/componentId"_json_pointer).get<string>()); json stream2 = streams.at("/1/ComponentStream"_json_pointer); ASSERT_TRUE(stream2.is_object()); ASSERT_EQ(string("Rotary"), stream2.at("/component"_json_pointer).get<string>()); ASSERT_EQ(string("zf476090"), stream2.at("/componentId"_json_pointer).get<string>()); } TEST_F(JsonPrinterStreamTest, TwoDevices) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "Xpos", 10254804, "100"); addObservationToCheckpoint(checkpoint, "z2143c50", 10254805, "AVAILABLE"); ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto streams = jdoc.at("/MTConnectStreams/Streams"_json_pointer); ASSERT_EQ(2_S, streams.size()); json stream1 = streams.at("/1/DeviceStream"_json_pointer); ASSERT_TRUE(stream1.is_object()); ASSERT_EQ(string("SimpleCnc"), stream1.at("/name"_json_pointer).get<string>()); ASSERT_EQ(string("872a3490-bd2d-0136-3eb0-0c85909298d9"), stream1.at("/uuid"_json_pointer).get<string>()); json stream2 = streams.at("/0/DeviceStream"_json_pointer); ASSERT_TRUE(stream2.is_object()); ASSERT_EQ(string("SampleDevice2"), stream2.at("/name"_json_pointer).get<string>()); ASSERT_EQ(string("f2db97b0-2bd1-0137-91ba-2a0081597801"), stream2.at("/uuid"_json_pointer).get<string>()); } TEST_F(JsonPrinterStreamTest, SampleAndEventDataItem) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "if36ff60", 10254804, "AUTOMATIC"); // Controller Mode addObservationToCheckpoint(checkpoint, "r186cd60", 10254805, "10 20 30"); // Path Position ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto streams = jdoc.at("/MTConnectStreams/Streams/0/DeviceStream/ComponentStreams"_json_pointer); ASSERT_EQ(1_S, streams.size()); auto stream = streams.at("/0/ComponentStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("a4a7bdf0"), stream.at("/componentId"_json_pointer).get<string>()); auto events = stream.at("/Events"_json_pointer); ASSERT_TRUE(events.is_array()); auto mode = events.at(0); ASSERT_TRUE(mode.is_object()); ASSERT_EQ(string("AUTOMATIC"), mode.at("/ControllerMode/value"_json_pointer).get<string>()); ASSERT_EQ(string("if36ff60"), mode.at("/ControllerMode/dataItemId"_json_pointer).get<string>()); ASSERT_EQ(string("mode"), mode.at("/ControllerMode/name"_json_pointer).get<string>()); ASSERT_EQ(string("TIME"), mode.at("/ControllerMode/timestamp"_json_pointer).get<string>()); ASSERT_EQ(uint64_t(10254804), mode.at("/ControllerMode/sequence"_json_pointer).get<uint64_t>()); auto samples = stream.at("/Samples"_json_pointer); ASSERT_TRUE(samples.is_array()); auto pos = samples.at(0); ASSERT_EQ(3_S, pos.at("/PathPosition/value"_json_pointer).size()); ASSERT_EQ(10.0, pos.at("/PathPosition/value/0"_json_pointer).get<double>()); ASSERT_EQ(20.0, pos.at("/PathPosition/value/1"_json_pointer).get<double>()); ASSERT_EQ(30.0, pos.at("/PathPosition/value/2"_json_pointer).get<double>()); ASSERT_EQ(string("r186cd60"), pos.at("/PathPosition/dataItemId"_json_pointer).get<string>()); ASSERT_EQ(string("TIME"), pos.at("/PathPosition/timestamp"_json_pointer).get<string>()); ASSERT_EQ(uint64_t(10254805), pos.at("/PathPosition/sequence"_json_pointer).get<uint64_t>()); } TEST_F(JsonPrinterStreamTest, ConditionDataItem) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "a5b23650", 10254804, "fault|syn|ack|HIGH|Syntax error"); // Motion Program Condition ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto streams = jdoc.at("/MTConnectStreams/Streams/0/DeviceStream/ComponentStreams"_json_pointer); ASSERT_EQ(1_S, streams.size()); auto stream = streams.at("/0/ComponentStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("a4a7bdf0"), stream.at("/componentId"_json_pointer).get<string>()); auto conds = stream.at("/Condition"_json_pointer); ASSERT_TRUE(conds.is_array()); ASSERT_EQ(1_S, conds.size()); auto motion = conds.at(0); ASSERT_TRUE(motion.is_object()); ASSERT_EQ(string("a5b23650"), motion.at("/Fault/dataItemId"_json_pointer).get<string>()); ASSERT_EQ(string("motion"), motion.at("/Fault/name"_json_pointer).get<string>()); ASSERT_EQ(string("TIME"), motion.at("/Fault/timestamp"_json_pointer).get<string>()); ASSERT_EQ(uint64_t(10254804), motion.at("/Fault/sequence"_json_pointer).get<uint64_t>()); ASSERT_EQ(string("HIGH"), motion.at("/Fault/qualifier"_json_pointer).get<string>()); ASSERT_EQ(string("ack"), motion.at("/Fault/nativeSeverity"_json_pointer).get<string>()); ASSERT_EQ(string("syn"), motion.at("/Fault/nativeCode"_json_pointer).get<string>()); ASSERT_EQ(string("Syntax error"), motion.at("/Fault/value"_json_pointer).get<string>()); } TEST_F(JsonPrinterStreamTest, TimeSeries) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "tc9edc70", 10254804, "10|100|1.0 2.0 3 4 5.0 6 7 8.8 9.0 10.2"); // Volt Ampere Time Series ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto streams = jdoc.at("/MTConnectStreams/Streams/0/DeviceStream/ComponentStreams"_json_pointer); ASSERT_EQ(1_S, streams.size()); auto stream = streams.at("/0/ComponentStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("afb91ba0"), stream.at("/componentId"_json_pointer).get<string>()); auto samples = stream.at("/Samples"_json_pointer); ASSERT_TRUE(samples.is_array()); ASSERT_EQ(1_S, samples.size()); auto amps = samples.at(0); ASSERT_TRUE(amps.is_object()); ASSERT_EQ(string("tc9edc70"), amps.at("/VoltAmpereTimeSeries/dataItemId"_json_pointer).get<string>()); ASSERT_EQ(string("pampts"), amps.at("/VoltAmpereTimeSeries/name"_json_pointer).get<string>()); ASSERT_EQ(string("TIME"), amps.at("/VoltAmpereTimeSeries/timestamp"_json_pointer).get<string>()); ASSERT_EQ(uint64_t(10254804), amps.at("/VoltAmpereTimeSeries/sequence"_json_pointer).get<uint64_t>()); ASSERT_EQ(10.0, amps.at("/VoltAmpereTimeSeries/sampleCount"_json_pointer).get<double>()); ASSERT_EQ(100.0, amps.at("/VoltAmpereTimeSeries/sampleRate"_json_pointer).get<double>()); auto value = amps.at("/VoltAmpereTimeSeries/value"_json_pointer); ASSERT_TRUE(value.is_array()); ASSERT_EQ(10_S, value.size()); ASSERT_EQ(1.0, value[0].get<double>()); ASSERT_EQ(2.0, value[1].get<double>()); ASSERT_EQ(3.0, value[2].get<double>()); ASSERT_EQ(4.0, value[3].get<double>()); ASSERT_EQ(5.0, value[4].get<double>()); ASSERT_EQ(6.0, value[5].get<double>()); ASSERT_EQ(7.0, value[6].get<double>()); ASSERT_NEAR(8.8, value[7].get<double>(), 0.0001); ASSERT_EQ(9.0, value[8].get<double>()); ASSERT_NEAR(10.2, value[9].get<double>(), 0.0001); } TEST_F(JsonPrinterStreamTest, AssetChanged) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "e4a300e0", 10254804, "CuttingTool|31d416a0-33c7"); // asset changed addObservationToCheckpoint(checkpoint, "f2df7550", 10254805, "QIF|400477d0-33c7"); // asset removed ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto streams = jdoc.at("/MTConnectStreams/Streams/0/DeviceStream/ComponentStreams"_json_pointer); ASSERT_EQ(1_S, streams.size()); auto stream = streams.at("/0/ComponentStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("x872a3490"), stream.at("/componentId"_json_pointer).get<string>()); auto events = stream.at("/Events"_json_pointer); ASSERT_TRUE(events.is_array()); ASSERT_EQ(2_S, events.size()); auto changed = events.at(0); ASSERT_TRUE(changed.is_object()); ASSERT_EQ(string("e4a300e0"), changed.at("/AssetChanged/dataItemId"_json_pointer).get<string>()); ASSERT_EQ(string("TIME"), changed.at("/AssetChanged/timestamp"_json_pointer).get<string>()); ASSERT_EQ(uint64_t(10254804), changed.at("/AssetChanged/sequence"_json_pointer).get<uint64_t>()); ASSERT_EQ(string("CuttingTool"), changed.at("/AssetChanged/assetType"_json_pointer).get<string>()); ASSERT_EQ(string("31d416a0-33c7"), changed.at("/AssetChanged/value"_json_pointer).get<string>()); auto removed = events.at(1); ASSERT_TRUE(removed.is_object()); ASSERT_EQ(string("f2df7550"), removed.at("/AssetRemoved/dataItemId"_json_pointer).get<string>()); ASSERT_EQ(string("TIME"), removed.at("/AssetRemoved/timestamp"_json_pointer).get<string>()); ASSERT_EQ(uint64_t(10254805), removed.at("/AssetRemoved/sequence"_json_pointer).get<uint64_t>()); ASSERT_EQ(string("QIF"), removed.at("/AssetRemoved/assetType"_json_pointer).get<string>()); ASSERT_EQ(string("400477d0-33c7"), removed.at("/AssetRemoved/value"_json_pointer).get<string>()); } TEST_F(JsonPrinterStreamTest, ResetTrigger) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "qb9212c0", 10254804, "10.0:ACTION_COMPLETE", "[email protected]"); // Amperage ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto streams = jdoc.at("/MTConnectStreams/Streams/0/DeviceStream/ComponentStreams"_json_pointer); ASSERT_EQ(1_S, streams.size()); auto stream = streams.at("/0/ComponentStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("afb91ba0"), stream.at("/componentId"_json_pointer).get<string>()); auto samples = stream.at("/Samples"_json_pointer); ASSERT_TRUE(samples.is_array()); ASSERT_EQ(1_S, samples.size()); auto amp = samples.at(0); ASSERT_TRUE(amp.is_object()); cout << amp.dump(2) << endl; ASSERT_EQ(string("qb9212c0"), amp.at("/Amperage/dataItemId"_json_pointer).get<string>()); ASSERT_EQ(string("TIME"), amp.at("/Amperage/timestamp"_json_pointer).get<string>()); ASSERT_EQ(uint64_t(10254804), amp.at("/Amperage/sequence"_json_pointer).get<uint64_t>()); ASSERT_EQ(string("ACTION_COMPLETE"), amp.at("/Amperage/resetTriggered"_json_pointer).get<string>()); ASSERT_EQ(string("AVERAGE"), amp.at("/Amperage/statistic"_json_pointer).get<string>()); ASSERT_EQ(100.0, amp.at("/Amperage/duration"_json_pointer).get<double>()); ASSERT_EQ(10.0, amp.at("/Amperage/value"_json_pointer).get<double>()); } TEST_F(JsonPrinterStreamTest, Message) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "m17f1750", 10254804, "XXXX|XXX is on the roof"); // asset changed ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto streams = jdoc.at("/MTConnectStreams/Streams/0/DeviceStream/ComponentStreams"_json_pointer); ASSERT_EQ(1_S, streams.size()); auto stream = streams.at("/0/ComponentStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("p5add360"), stream.at("/componentId"_json_pointer).get<string>()); auto events = stream.at("/Events"_json_pointer); ASSERT_TRUE(events.is_array()); ASSERT_EQ(1_S, events.size()); auto message = events.at(0); ASSERT_TRUE(message.is_object()); ASSERT_EQ(string("m17f1750"), message.at("/Message/dataItemId"_json_pointer).get<string>()); ASSERT_EQ(string("TIME"), message.at("/Message/timestamp"_json_pointer).get<string>()); ASSERT_EQ(uint64_t(10254804), message.at("/Message/sequence"_json_pointer).get<uint64_t>()); ASSERT_EQ(string("XXXX"), message.at("/Message/nativeCode"_json_pointer).get<string>()); ASSERT_EQ(string("XXX is on the roof"), message.at("/Message/value"_json_pointer).get<string>()); } TEST_F(JsonPrinterStreamTest, Unavailability) { Checkpoint checkpoint; addObservationToCheckpoint(checkpoint, "m17f1750", 10254804, "|UNAVAILABLE"); // asset changed addObservationToCheckpoint(checkpoint, "a5b23650", 10254804, "unavailable||||"); // Motion Program Condition ObservationPtrArray list; checkpoint.getObservations(list); auto doc = m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list); auto jdoc = json::parse(doc); auto streams = jdoc.at("/MTConnectStreams/Streams/0/DeviceStream/ComponentStreams"_json_pointer); ASSERT_EQ(2_S, streams.size()); auto stream = streams.at("/1/ComponentStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("p5add360"), stream.at("/componentId"_json_pointer).get<string>()); auto events = stream.at("/Events"_json_pointer); ASSERT_TRUE(events.is_array()); ASSERT_EQ(1_S, events.size()); auto message = events.at(0); ASSERT_TRUE(message.is_object()); ASSERT_EQ(string("UNAVAILABLE"), message.at("/Message/value"_json_pointer).get<string>()); stream = streams.at("/0/ComponentStream"_json_pointer); ASSERT_TRUE(stream.is_object()); ASSERT_EQ(string("a4a7bdf0"), stream.at("/componentId"_json_pointer).get<string>()); auto conds = stream.at("/Condition"_json_pointer); ASSERT_TRUE(conds.is_array()); ASSERT_EQ(1_S, conds.size()); auto motion = conds.at(0); ASSERT_TRUE(motion.is_object()); ASSERT_EQ(string("a5b23650"), motion.at("/Unavailable/dataItemId"_json_pointer).get<string>()); }
41.344609
100
0.724637
gsbecerrag
eed47df01d02a26282fc50caeb87e17cb9d2c418
1,080
cpp
C++
app/src/timer.cpp
yohrudkov/Uamp
4ec479156767907b5ae4c35716c1bea0897461cc
[ "MIT" ]
null
null
null
app/src/timer.cpp
yohrudkov/Uamp
4ec479156767907b5ae4c35716c1bea0897461cc
[ "MIT" ]
null
null
null
app/src/timer.cpp
yohrudkov/Uamp
4ec479156767907b5ae4c35716c1bea0897461cc
[ "MIT" ]
null
null
null
#include "timer.h" #include "ui_timer.h" #include "mainwindow.h" Timer::Timer(QWidget *parent) : QDialog(parent), ui(new Ui::Timer) { ui->setupUi(this); m_count = new QTimer(this); m_count->setInterval(60000); ui->Time->setAttribute(Qt::WA_MacShowFocusRect, 0); connect(m_count, &QTimer::timeout, [this, parent]() { ui->Time->setValue(ui->Time->value() - 1); if (ui->Time->value() == 0) qobject_cast<MainWindow *>(parent)->close(); }); connect(ui->Disable, &QPushButton::clicked, [this]() { ui->Time->setValue(0); m_count->stop(); ui->Status->setText("Timer disabled"); }); connect(ui->Activate, &QPushButton::clicked, [this]() { if (ui->Time->value() == 0) { Message("Timer error"); return ; } m_count->stop(); ui->Status->setText("Timer activated"); m_count->start(); }); } Timer::~Timer() { delete ui; delete m_count; } void Timer::showWindow() { setWindowTitle("Timer"); setModal(true); exec(); }
26.341463
68
0.561111
yohrudkov
eed7914c708cfaeaf85f381439b09d47cab05242
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_isZero.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_isZero.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_isZero.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:f7a925aa9d7164224342edf4003f9b299e76ea9cc9f40ba9ef2440665f648ae3 size 215
32
75
0.882813
initialz
4abcd527fecef56501d75df85e2698c148bd3712
3,852
cpp
C++
tests/ECMQtDeclareLoggingCategoryTest/testmain.cpp
pfultz2/extra-cmake-modules
42cbdc856588ac4adc79f28c3c91123aa5a7a307
[ "BSD-3-Clause" ]
null
null
null
tests/ECMQtDeclareLoggingCategoryTest/testmain.cpp
pfultz2/extra-cmake-modules
42cbdc856588ac4adc79f28c3c91123aa5a7a307
[ "BSD-3-Clause" ]
null
null
null
tests/ECMQtDeclareLoggingCategoryTest/testmain.cpp
pfultz2/extra-cmake-modules
42cbdc856588ac4adc79f28c3c91123aa5a7a307
[ "BSD-3-Clause" ]
null
null
null
/* * 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 copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <QCoreApplication> #include "log1.h" #include "log2.h" #include "log3.h" #include <iostream> int main(int argc, char **argv) { QCoreApplication qapp(argc, argv); bool success = true; // NB: we cannot test against QtInfoMsg, as that (a) does not exist before // Qt 5.5, and (b) has incorrect semantics in Qt 5.5, in that it is // treated as more severe than QtCriticalMsg. if (log1().categoryName() != QLatin1String("log.one")) { qWarning("log1 category was \"%s\", expected \"log.one\"", log1().categoryName()); success = false; } #if QT_VERSION < QT_VERSION_CHECK(5, 4, 0) if (!log1().isDebugEnabled()) { qWarning("log1 debug messages were not enabled"); success = false; } #else if (log1().isDebugEnabled()) { qWarning("log1 debug messages were enabled"); success = false; } if (!log1().isWarningEnabled()) { qWarning("log1 warning messages were not enabled"); success = false; } #endif if (foo::bar::log2().categoryName() != QLatin1String("log.two")) { qWarning("log2 category was \"%s\", expected \"log.two\"", foo::bar::log2().categoryName()); success = false; } #if QT_VERSION < QT_VERSION_CHECK(5, 4, 0) if (!foo::bar::log2().isDebugEnabled()) { qWarning("log2 debug messages were not enabled"); success = false; } #else if (foo::bar::log2().isDebugEnabled()) { qWarning("log2 debug messages were enabled"); success = false; } if (!foo::bar::log2().isWarningEnabled()) { qWarning("log2 warning messages were not enabled"); success = false; } #endif if (log3().categoryName() != QLatin1String("three")) { qWarning("log3 category was \"%s\", expected \"three\"", log3().categoryName()); success = false; } #if QT_VERSION < QT_VERSION_CHECK(5, 4, 0) if (!log3().isDebugEnabled()) { qWarning("log3 debug messages were not enabled"); success = false; } #else if (log3().isDebugEnabled()) { qWarning("log3 debug messages were enabled"); success = false; } if (log3().isWarningEnabled()) { qWarning("log3 warning messages were enabled"); success = false; } if (!log3().isCriticalEnabled()) { qWarning("log3 critical messages were not enabled"); success = false; } #endif return success ? 0 : 1; }
35.33945
100
0.65784
pfultz2
4ac41fce61fc7bfdcd9a080a0c89b65b0b6803c7
1,943
hpp
C++
mlog/reference_counter.hpp
Lowdham/mlog
034134ec2048fb78084f4772275b5f67efeec433
[ "MIT" ]
2
2021-06-19T04:14:14.000Z
2021-08-30T15:39:49.000Z
mlog/reference_counter.hpp
Lowdham/mlog
034134ec2048fb78084f4772275b5f67efeec433
[ "MIT" ]
1
2021-06-21T15:58:19.000Z
2021-06-22T02:04:39.000Z
mlog/reference_counter.hpp
Lowdham/mlog
034134ec2048fb78084f4772275b5f67efeec433
[ "MIT" ]
null
null
null
// This file is part of mlog. #ifndef MLOG_REFERENCE_COUNTER_HPP_ #define MLOG_REFERENCE_COUNTER_HPP_ #include <atomic> // std::atomic<> #include <exception> // std::terminate() #include "assert.hpp" #include "fwd.hpp" namespace mlog { template <typename ValueT = long> class ReferenceCounter; template <typename ValueT> class ReferenceCounter { static_assert(is_integral<ValueT>::value && !is_same<ValueT, bool>::value, "invalid reference counter value type"); public: using value_type = ValueT; private: ::std::atomic<value_type> ref_count_; public: constexpr ReferenceCounter() noexcept : ref_count_(1) {} explicit constexpr ReferenceCounter(value_type nref) noexcept : ref_count_(nref) {} constexpr ReferenceCounter(const ReferenceCounter&) noexcept : ReferenceCounter() {} ReferenceCounter& operator=(const ReferenceCounter&) noexcept { return *this; } ~ReferenceCounter() { auto old = this->ref_count_.load(::std::memory_order_relaxed); if (old > 1) ::std::terminate(); } public: bool Unique() const noexcept { return this->ref_count_.load(::std::memory_order_relaxed) == 1; } value_type Get() const noexcept { return this->ref_count_.load(::std::memory_order_relaxed); } bool TryIncrement() noexcept { auto old = this->ref_count_.load(::std::memory_order_relaxed); for (;;) if (old == 0) return false; else if (this->ref_count_.compare_exchange_weak( old, old + 1, ::std::memory_order_relaxed)) return true; } void Increment() noexcept { auto old = this->ref_count_.fetch_add(1, ::std::memory_order_relaxed); MLOG_ASSERT(old >= 1); } bool Decrement() noexcept { auto old = this->ref_count_.fetch_sub(1, ::std::memory_order_acq_rel); MLOG_ASSERT(old >= 1); return old == 1; } }; template class ReferenceCounter<long>; } // namespace mlog #endif
24.2875
76
0.678332
Lowdham
4acb231bbc01af0ebcc6259b488d1ae469c25748
1,933
cpp
C++
imgui_markup/src/objects/panel.cpp
FluxxCode/imgui_layer
0b0b73b132160d483259d88c9b024fdb2e1d3e63
[ "MIT" ]
null
null
null
imgui_markup/src/objects/panel.cpp
FluxxCode/imgui_layer
0b0b73b132160d483259d88c9b024fdb2e1d3e63
[ "MIT" ]
null
null
null
imgui_markup/src/objects/panel.cpp
FluxxCode/imgui_layer
0b0b73b132160d483259d88c9b024fdb2e1d3e63
[ "MIT" ]
null
null
null
#include "impch.h" #include "imgui_markup/objects/panel.h" namespace imgui_markup { Panel::Panel(std::string id, Object* parent) : Object("Panel", id, parent) { this->AddAttribute("title", &this->title_); this->AddAttribute("position", &this->global_position_); this->AddAttribute("size", &this->size_); } Panel& Panel::operator=(const Panel& other) { for (auto& child : this->child_objects_) child->SetParent(other.parent_); return *this; } void Panel::Update() { if (this->init_panel_attributes_) this->InitPanelAttributes(); if (!ImGui::Begin(this->title_)) { ImGui::End(); this->is_hovered_ = false; this->size_ = Float2(); return; } this->is_hovered_ = ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows); this->size_ = ImGui::GetWindowSize(); this->global_position_ = ImGui::GetWindowPos(); for (auto& child : this->child_objects_) { if (!child) continue; child->SetPosition(ImGui::GetCursorPos(), this->global_position_); child->Update(); } ImGui::End(); } void Panel::InitPanelAttributes() { if (this->global_position_.value_changed_) ImGui::SetNextWindowPos(this->global_position_); if (this->size_.value_changed_) ImGui::SetNextWindowSize(this->size_); this->init_panel_attributes_ = false; } bool Panel::Validate(std::string& error_message) const { if (!this->parent_) return true; if (this->parent_->GetType() == "GlobalObject") return true; error_message = "Object of type \"Panel\" can only be created inside the " "global file scope"; return false; } bool Panel::OnProcessEnd(std::string& error_message) { if (this->title_.value.empty()) this->title_ = this->id_.empty() ? "unknown" : this->id_; return true; } } // namespace imgui_markup
22.476744
78
0.630109
FluxxCode
4acedb3a7c286f671ca14090aed2c0c14d44b05b
20,208
cpp
C++
source/Lib/TLibDecoder/TDecGop.cpp
AjayKumarSahu20/SHVC_2
2ce6fe131ab12eadf8d51b3408081529b5ad9366
[ "BSD-3-Clause" ]
2
2019-12-25T07:41:29.000Z
2021-11-25T11:50:12.000Z
source/Lib/TLibDecoder/TDecGop.cpp
AjayKumarSahu20/SHVC_2
2ce6fe131ab12eadf8d51b3408081529b5ad9366
[ "BSD-3-Clause" ]
null
null
null
source/Lib/TLibDecoder/TDecGop.cpp
AjayKumarSahu20/SHVC_2
2ce6fe131ab12eadf8d51b3408081529b5ad9366
[ "BSD-3-Clause" ]
null
null
null
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2014, ITU/ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ITU/ISO/IEC 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. */ /** \file TDecGop.cpp \brief GOP decoder class */ #include "TDecGop.h" #include "TDecCAVLC.h" #include "TDecSbac.h" #include "TDecBinCoder.h" #include "TDecBinCoderCABAC.h" #include "libmd5/MD5.h" #include "TLibCommon/SEI.h" #if SVC_EXTENSION #include "TDecTop.h" #endif #include <time.h> extern Bool g_md5_mismatch; ///< top level flag to signal when there is a decode problem //! \ingroup TLibDecoder //! \{ static void calcAndPrintHashStatus(TComPicYuv& pic, const SEIDecodedPictureHash* pictureHashSEI); #if Q0074_COLOUR_REMAPPING_SEI static Void applyColourRemapping(TComPicYuv& pic, const SEIColourRemappingInfo* colourRemappingInfoSEI, UInt layerId=0 ); static std::vector<SEIColourRemappingInfo> storeCriSEI; //Persistent Colour Remapping Information SEI #endif // ==================================================================================================================== // Constructor / destructor / initialization / destroy // ==================================================================================================================== TDecGop::TDecGop() { m_dDecTime = 0; m_pcSbacDecoders = NULL; m_pcBinCABACs = NULL; } TDecGop::~TDecGop() { } #if SVC_EXTENSION Void TDecGop::create(UInt layerId) { m_layerId = layerId; } #else Void TDecGop::create() { } #endif Void TDecGop::destroy() { } #if SVC_EXTENSION Void TDecGop::init(TDecTop** ppcDecTop, TDecEntropy* pcEntropyDecoder, #else Void TDecGop::init( TDecEntropy* pcEntropyDecoder, #endif TDecSbac* pcSbacDecoder, TDecBinCABAC* pcBinCABAC, TDecCavlc* pcCavlcDecoder, TDecSlice* pcSliceDecoder, TComLoopFilter* pcLoopFilter, TComSampleAdaptiveOffset* pcSAO ) { m_pcEntropyDecoder = pcEntropyDecoder; m_pcSbacDecoder = pcSbacDecoder; m_pcBinCABAC = pcBinCABAC; m_pcCavlcDecoder = pcCavlcDecoder; m_pcSliceDecoder = pcSliceDecoder; m_pcLoopFilter = pcLoopFilter; m_pcSAO = pcSAO; #if SVC_EXTENSION m_ppcTDecTop = ppcDecTop; #endif } // ==================================================================================================================== // Private member functions // ==================================================================================================================== // ==================================================================================================================== // Public member functions // ==================================================================================================================== Void TDecGop::decompressSlice(TComInputBitstream* pcBitstream, TComPic*& rpcPic) { TComSlice* pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx()); // Table of extracted substreams. // These must be deallocated AND their internal fifos, too. TComInputBitstream **ppcSubstreams = NULL; //-- For time output for each slice long iBeforeTime = clock(); m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC ); m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder); UInt uiNumSubstreams = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag() ? pcSlice->getNumEntryPointOffsets()+1 : pcSlice->getPPS()->getNumSubstreams(); // init each couple {EntropyDecoder, Substream} UInt *puiSubstreamSizes = pcSlice->getSubstreamSizes(); ppcSubstreams = new TComInputBitstream*[uiNumSubstreams]; m_pcSbacDecoders = new TDecSbac[uiNumSubstreams]; m_pcBinCABACs = new TDecBinCABAC[uiNumSubstreams]; for ( UInt ui = 0 ; ui < uiNumSubstreams ; ui++ ) { m_pcSbacDecoders[ui].init(&m_pcBinCABACs[ui]); ppcSubstreams[ui] = pcBitstream->extractSubstream(ui+1 < uiNumSubstreams ? puiSubstreamSizes[ui] : pcBitstream->getNumBitsLeft()); } for ( UInt ui = 0 ; ui+1 < uiNumSubstreams; ui++ ) { m_pcEntropyDecoder->setEntropyDecoder ( &m_pcSbacDecoders[uiNumSubstreams - 1 - ui] ); m_pcEntropyDecoder->setBitstream ( ppcSubstreams [uiNumSubstreams - 1 - ui] ); m_pcEntropyDecoder->resetEntropy (pcSlice); } m_pcEntropyDecoder->setEntropyDecoder ( m_pcSbacDecoder ); m_pcEntropyDecoder->setBitstream ( ppcSubstreams[0] ); m_pcEntropyDecoder->resetEntropy (pcSlice); m_pcSbacDecoders[0].load(m_pcSbacDecoder); m_pcSliceDecoder->decompressSlice( ppcSubstreams, rpcPic, m_pcSbacDecoder, m_pcSbacDecoders); m_pcEntropyDecoder->setBitstream( ppcSubstreams[uiNumSubstreams-1] ); // deallocate all created substreams, including internal buffers. for (UInt ui = 0; ui < uiNumSubstreams; ui++) { ppcSubstreams[ui]->deleteFifo(); delete ppcSubstreams[ui]; } delete[] ppcSubstreams; delete[] m_pcSbacDecoders; m_pcSbacDecoders = NULL; delete[] m_pcBinCABACs; m_pcBinCABACs = NULL; m_dDecTime += (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC; } Void TDecGop::filterPicture(TComPic*& rpcPic) { TComSlice* pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx()); //-- For time output for each slice long iBeforeTime = clock(); // deblocking filter Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag(); m_pcLoopFilter->setCfg(bLFCrossTileBoundary); m_pcLoopFilter->loopFilterPic( rpcPic ); if( pcSlice->getSPS()->getUseSAO() ) { m_pcSAO->reconstructBlkSAOParams(rpcPic, rpcPic->getPicSym()->getSAOBlkParam()); m_pcSAO->SAOProcess(rpcPic); m_pcSAO->PCMLFDisableProcess(rpcPic); } rpcPic->compressMotion(); Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B'); if (!pcSlice->isReferenced()) c += 32; //-- For time output for each slice #if SVC_EXTENSION printf("\nPOC %4d LId: %1d TId: %1d ( %c-SLICE %s, QP%3d ) ", pcSlice->getPOC(), rpcPic->getLayerId(), pcSlice->getTLayer(), c, NaluToStr( pcSlice->getNalUnitType() ).data(), pcSlice->getSliceQp() ); #else printf("\nPOC %4d TId: %1d ( %c-SLICE, QP%3d ) ", pcSlice->getPOC(), pcSlice->getTLayer(), c, pcSlice->getSliceQp() ); #endif m_dDecTime += (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC; printf ("[DT %6.3f] ", m_dDecTime ); m_dDecTime = 0; for (Int iRefList = 0; iRefList < 2; iRefList++) { printf ("[L%d ", iRefList); for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++) { #if SVC_EXTENSION #if VPS_EXTN_DIRECT_REF_LAYERS if( pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->isILR( m_layerId ) ) { UInt refLayerId = pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->getLayerId(); UInt refLayerIdc = pcSlice->getReferenceLayerIdc(refLayerId); assert( g_posScalingFactor[refLayerIdc][0] ); assert( g_posScalingFactor[refLayerIdc][1] ); printf( "%d(%d, {%1.2f, %1.2f}x)", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex), refLayerId, 65536.0/g_posScalingFactor[refLayerIdc][0], 65536.0/g_posScalingFactor[refLayerIdc][1] ); } else { printf ("%d", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)); } #endif if( pcSlice->getEnableTMVPFlag() && iRefList == 1 - pcSlice->getColFromL0Flag() && iRefIndex == pcSlice->getColRefIdx() ) { printf( "c" ); } printf( " " ); #else printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)); #endif } printf ("] "); } if (m_decodedPictureHashSEIEnabled) { SEIMessages pictureHashes = getSeisByType(rpcPic->getSEIs(), SEI::DECODED_PICTURE_HASH ); const SEIDecodedPictureHash *hash = ( pictureHashes.size() > 0 ) ? (SEIDecodedPictureHash*) *(pictureHashes.begin()) : NULL; if (pictureHashes.size() > 1) { printf ("Warning: Got multiple decoded picture hash SEI messages. Using first."); } calcAndPrintHashStatus(*rpcPic->getPicYuvRec(), hash); } #if Q0074_COLOUR_REMAPPING_SEI if (m_colourRemapSEIEnabled) { SEIMessages colourRemappingInfo = getSeisByType(rpcPic->getSEIs(), SEI::COLOUR_REMAPPING_INFO ); const SEIColourRemappingInfo *seiColourRemappingInfo = ( colourRemappingInfo.size() > 0 ) ? (SEIColourRemappingInfo*) *(colourRemappingInfo.begin()) : NULL; if (colourRemappingInfo.size() > 1) { printf ("Warning: Got multiple Colour Remapping Information SEI messages. Using first."); } applyColourRemapping(*rpcPic->getPicYuvRec(), seiColourRemappingInfo #if SVC_EXTENSION , rpcPic->getLayerId() #endif ); } #endif #if SETTING_PIC_OUTPUT_MARK rpcPic->setOutputMark(rpcPic->getSlice(0)->getPicOutputFlag() ? true : false); #else rpcPic->setOutputMark(true); #endif rpcPic->setReconMark(true); } /** * Calculate and print hash for pic, compare to picture_digest SEI if * present in seis. seis may be NULL. Hash is printed to stdout, in * a manner suitable for the status line. Theformat is: * [Hash_type:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,(yyy)] * Where, x..x is the hash * yyy has the following meanings: * OK - calculated hash matches the SEI message * ***ERROR*** - calculated hash does not match the SEI message * unk - no SEI message was available for comparison */ static void calcAndPrintHashStatus(TComPicYuv& pic, const SEIDecodedPictureHash* pictureHashSEI) { /* calculate MD5sum for entire reconstructed picture */ UChar recon_digest[3][16]; Int numChar=0; const Char* hashType = "\0"; if (pictureHashSEI) { switch (pictureHashSEI->method) { case SEIDecodedPictureHash::MD5: { hashType = "MD5"; calcMD5(pic, recon_digest); numChar = 16; break; } case SEIDecodedPictureHash::CRC: { hashType = "CRC"; calcCRC(pic, recon_digest); numChar = 2; break; } case SEIDecodedPictureHash::CHECKSUM: { hashType = "Checksum"; calcChecksum(pic, recon_digest); numChar = 4; break; } default: { assert (!"unknown hash type"); } } } /* compare digest against received version */ const Char* ok = "(unk)"; Bool mismatch = false; if (pictureHashSEI) { ok = "(OK)"; for(Int yuvIdx = 0; yuvIdx < 3; yuvIdx++) { for (UInt i = 0; i < numChar; i++) { if (recon_digest[yuvIdx][i] != pictureHashSEI->digest[yuvIdx][i]) { ok = "(***ERROR***)"; mismatch = true; } } } } printf("[%s:%s,%s] ", hashType, digestToString(recon_digest, numChar), ok); if (mismatch) { g_md5_mismatch = true; printf("[rx%s:%s] ", hashType, digestToString(pictureHashSEI->digest, numChar)); } } #if Q0074_COLOUR_REMAPPING_SEI Void xInitColourRemappingLut( const Int bitDepthY, const Int bitDepthC, std::vector<Int>(&preLut)[3], std::vector<Int>(&postLut)[3], const SEIColourRemappingInfo* const pCriSEI ) { for ( Int c=0 ; c<3 ; c++ ) { Int bitDepth = c ? bitDepthC : bitDepthY ; preLut[c].resize(1 << bitDepth); postLut[c].resize(1 << pCriSEI->m_colourRemapBitDepth); Int bitDepthDiff = pCriSEI->m_colourRemapBitDepth - bitDepth; Int iShift1 = (bitDepthDiff>0) ? bitDepthDiff : 0; //bit scale from bitdepth to ColourRemapBitdepth (manage only case colourRemapBitDepth>= bitdepth) if( bitDepthDiff<0 ) printf ("Warning: CRI SEI - colourRemapBitDepth (%d) <bitDepth (%d) - case not handled\n", pCriSEI->m_colourRemapBitDepth, bitDepth); bitDepthDiff = pCriSEI->m_colourRemapBitDepth - pCriSEI->m_colourRemapInputBitDepth; Int iShift2 = (bitDepthDiff>0) ? bitDepthDiff : 0; //bit scale from ColourRemapInputBitdepth to ColourRemapBitdepth (manage only case colourRemapBitDepth>= colourRemapInputBitDepth) if( bitDepthDiff<0 ) printf ("Warning: CRI SEI - colourRemapBitDepth (%d) <colourRemapInputBitDepth (%d) - case not handled\n", pCriSEI->m_colourRemapBitDepth, pCriSEI->m_colourRemapInputBitDepth); //Fill preLut for ( Int k=0 ; k<(1<<bitDepth) ; k++ ) { Int iSample = k << iShift1 ; for ( Int iPivot=0 ; iPivot<=pCriSEI->m_preLutNumValMinus1[c] ; iPivot++ ) { Int iCodedPrev = pCriSEI->m_preLutCodedValue[c][iPivot] << iShift2; //Coded in CRInputBitdepth Int iCodedNext = pCriSEI->m_preLutCodedValue[c][iPivot+1] << iShift2; //Coded in CRInputBitdepth Int iTargetPrev = pCriSEI->m_preLutTargetValue[c][iPivot]; //Coded in CRBitdepth Int iTargetNext = pCriSEI->m_preLutTargetValue[c][iPivot+1]; //Coded in CRBitdepth if ( iCodedPrev <= iSample && iSample <= iCodedNext ) { Float fInterpol = (Float)( (iCodedNext - iSample)*iTargetPrev + (iSample - iCodedPrev)*iTargetNext ) * 1.f / (Float)(iCodedNext - iCodedPrev); preLut[c][k] = (Int)( 0.5f + fInterpol ); iPivot = pCriSEI->m_preLutNumValMinus1[c] + 1; } } } //Fill postLut for ( Int k=0 ; k<(1<<pCriSEI->m_colourRemapBitDepth) ; k++ ) { Int iSample = k; for ( Int iPivot=0 ; iPivot<=pCriSEI->m_postLutNumValMinus1[c] ; iPivot++ ) { Int iCodedPrev = pCriSEI->m_postLutCodedValue[c][iPivot]; //Coded in CRBitdepth Int iCodedNext = pCriSEI->m_postLutCodedValue[c][iPivot+1]; //Coded in CRBitdepth Int iTargetPrev = pCriSEI->m_postLutTargetValue[c][iPivot]; //Coded in CRBitdepth Int iTargetNext = pCriSEI->m_postLutTargetValue[c][iPivot+1]; //Coded in CRBitdepth if ( iCodedPrev <= iSample && iSample <= iCodedNext ) { Float fInterpol = (Float)( (iCodedNext - iSample)*iTargetPrev + (iSample - iCodedPrev)*iTargetNext ) * 1.f / (Float)(iCodedNext - iCodedPrev) ; postLut[c][k] = (Int)( 0.5f + fInterpol ); iPivot = pCriSEI->m_postLutNumValMinus1[c] + 1; } } } } } static void applyColourRemapping(TComPicYuv& pic, const SEIColourRemappingInfo* pCriSEI, UInt layerId ) { if( !storeCriSEI.size() ) #if SVC_EXTENSION storeCriSEI.resize(MAX_LAYERS); #else storeCriSEI.resize(1); #endif if ( pCriSEI ) //if a CRI SEI has just been retrieved, keep it in memory (persistence management) storeCriSEI[layerId] = *pCriSEI; if( !storeCriSEI[layerId].m_colourRemapCancelFlag ) { Int iHeight = pic.getHeight(); Int iWidth = pic.getWidth(); Int iStride = pic.getStride(); Int iCStride = pic.getCStride(); Pel *YUVIn[3], *YUVOut[3]; YUVIn[0] = pic.getLumaAddr(); YUVIn[1] = pic.getCbAddr(); YUVIn[2] = pic.getCrAddr(); TComPicYuv picColourRemapped; #if SVC_EXTENSION #if AUXILIARY_PICTURES picColourRemapped.create( pic.getWidth(), pic.getHeight(), pic.getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, NULL ); #else picColourRemapped.create( pic.getWidth(), pic.getHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, NULL ); #endif #else picColourRemapped.create( pic.getWidth(), pic.getHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth ); #endif YUVOut[0] = picColourRemapped.getLumaAddr(); YUVOut[1] = picColourRemapped.getCbAddr(); YUVOut[2] = picColourRemapped.getCrAddr(); #if SVC_EXTENSION Int bitDepthY = g_bitDepthYLayer[layerId]; Int bitDepthC = g_bitDepthCLayer[layerId]; assert( g_bitDepthY == bitDepthY ); assert( g_bitDepthC == bitDepthC ); #else Int bitDepthY = g_bitDepthY; Int bitDepthC = g_bitDepthC; #endif std::vector<Int> preLut[3]; std::vector<Int> postLut[3]; xInitColourRemappingLut( bitDepthY, bitDepthC, preLut, postLut, &storeCriSEI[layerId] ); Int roundingOffset = (storeCriSEI[layerId].m_log2MatrixDenom==0) ? 0 : (1 << (storeCriSEI[layerId].m_log2MatrixDenom - 1)); for( Int y = 0; y < iHeight ; y++ ) { for( Int x = 0; x < iWidth ; x++ ) { Int YUVPre[3], YUVMat[3]; YUVPre[0] = preLut[0][ YUVIn[0][x] ]; YUVPre[1] = preLut[1][ YUVIn[1][x>>1] ]; YUVPre[2] = preLut[2][ YUVIn[2][x>>1] ]; YUVMat[0] = ( storeCriSEI[layerId].m_colourRemapCoeffs[0][0]*YUVPre[0] + storeCriSEI[layerId].m_colourRemapCoeffs[0][1]*YUVPre[1] + storeCriSEI[layerId].m_colourRemapCoeffs[0][2]*YUVPre[2] + roundingOffset ) >> ( storeCriSEI[layerId].m_log2MatrixDenom ); YUVMat[0] = Clip3( 0, (1<<storeCriSEI[layerId].m_colourRemapBitDepth)-1, YUVMat[0] ); YUVOut[0][x] = postLut[0][ YUVMat[0] ]; if( (y&1) && (x&1) ) { for(Int c=1 ; c<3 ; c++) { YUVMat[c] = ( storeCriSEI[layerId].m_colourRemapCoeffs[c][0]*YUVPre[0] + storeCriSEI[layerId].m_colourRemapCoeffs[c][1]*YUVPre[1] + storeCriSEI[layerId].m_colourRemapCoeffs[c][2]*YUVPre[2] + roundingOffset ) >> ( storeCriSEI[layerId].m_log2MatrixDenom ); YUVMat[c] = Clip3( 0, (1<<storeCriSEI[layerId].m_colourRemapBitDepth)-1, YUVMat[c] ); YUVOut[c][x>>1] = postLut[c][ YUVMat[c] ]; } } } YUVIn[0] += iStride; YUVOut[0] += iStride; if( y&1 ) { YUVIn[1] += iCStride; YUVIn[2] += iCStride; YUVOut[1] += iCStride; YUVOut[2] += iCStride; } } //Write remapped picture in decoding order Char cTemp[255]; sprintf(cTemp, "seiColourRemappedPic_L%d_%dx%d_%dbits.yuv", layerId, iWidth, iHeight, storeCriSEI[layerId].m_colourRemapBitDepth ); picColourRemapped.dump( cTemp, true, storeCriSEI[layerId].m_colourRemapBitDepth ); picColourRemapped.destroy(); storeCriSEI[layerId].m_colourRemapCancelFlag = !storeCriSEI[layerId].m_colourRemapPersistenceFlag; //Handling persistence } } #endif //! \}
38.345351
197
0.627771
AjayKumarSahu20
4ad45318918416fe8d6e9b0f6e03f7fae5c120dc
151
cc
C++
UnitTests/LoopHelixBFieldTest_unit.cc
brownd1978/KinKal
e7bf9dc4d793e9f089c30ae9defb4add8bf1657b
[ "Apache-1.1" ]
null
null
null
UnitTests/LoopHelixBFieldTest_unit.cc
brownd1978/KinKal
e7bf9dc4d793e9f089c30ae9defb4add8bf1657b
[ "Apache-1.1" ]
null
null
null
UnitTests/LoopHelixBFieldTest_unit.cc
brownd1978/KinKal
e7bf9dc4d793e9f089c30ae9defb4add8bf1657b
[ "Apache-1.1" ]
null
null
null
#include "KinKal/LoopHelix.hh" #include "UnitTests/BFieldMapTest.hh" int main(int argc, char **argv) { return BFieldMapTest<LoopHelix>(argc,argv); }
25.166667
45
0.748344
brownd1978
4ad576b8bc66773e1114ebac32ae19b8e18ee3d7
1,667
hpp
C++
include/toy/math/Vector4.hpp
ToyAuthor/ToyBoxNote
accc792f5ab2fa8911dc1a70ffbfc6dfd02db9a6
[ "Unlicense" ]
4
2017-07-06T22:18:41.000Z
2021-05-24T21:28:37.000Z
include/toy/math/Vector4.hpp
ToyAuthor/ToyBoxNote
accc792f5ab2fa8911dc1a70ffbfc6dfd02db9a6
[ "Unlicense" ]
null
null
null
include/toy/math/Vector4.hpp
ToyAuthor/ToyBoxNote
accc792f5ab2fa8911dc1a70ffbfc6dfd02db9a6
[ "Unlicense" ]
1
2020-08-02T13:00:38.000Z
2020-08-02T13:00:38.000Z
#pragma once #include "toy/math/General.hpp" namespace toy{ namespace math{ template <typename Type> class Vector4 { public: union { struct { Type x,y,z,w; }; Type data[4]; }; Vector4():x(Type(0)),y(Type(0)),z(Type(0)),w(Type(0)){} Vector4(const Type xx,const Type yy,const Type zz,const Type ww):x(xx),y(yy),z(zz),w(ww){} ~Vector4(){} void set(const Type xx,const Type yy,const Type zz,const Type ww) { x = xx; y = yy; z = zz; w = ww; } Type length() const { return ::toy::math::Sqrt<Type>(x*x+y*y+z*z+w*w); } void normalize() { Type len = length(); x /= len; y /= len; z /= len; w /= len; } Vector4<Type> operator +(const Vector4<Type>& v) const { return Vector4<Type>( x+v.x, y+v.y, z+v.z, w+v.w ); } Vector4<Type> operator -(const Vector4<Type>& v) const { return Vector4<Type>( x-v.x, y-v.y, z-v.z, w-v.w ); } Vector4<Type> operator +=(const Vector4<Type>& v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } Vector4<Type> operator -=(const Vector4<Type>& v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } void invert() { x = -x; y = -y; z = -z; w = -w; } Vector4(const Vector4<Type>& v) { x = v.x; y = v.y; z = v.z; w = v.w; } Vector4<Type> operator =(const Vector4<Type>& v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; } }; }//namespace math }//namespace toy
14.752212
92
0.460708
ToyAuthor
4ad95451b82cd4bc441327ee4c8e9bfc376b8596
6,005
cpp
C++
manager/src/app_profile_frame.cpp
lunixoid/sys-clk
731d0de5f580a7fa853804e0c776ba2f1623c932
[ "Beerware" ]
492
2019-02-14T16:10:55.000Z
2022-03-31T00:01:27.000Z
manager/src/app_profile_frame.cpp
lunixoid/sys-clk
731d0de5f580a7fa853804e0c776ba2f1623c932
[ "Beerware" ]
51
2019-02-14T17:31:08.000Z
2022-03-24T00:10:09.000Z
manager/src/app_profile_frame.cpp
lunixoid/sys-clk
731d0de5f580a7fa853804e0c776ba2f1623c932
[ "Beerware" ]
75
2019-02-14T17:46:32.000Z
2022-03-28T07:19:25.000Z
/* sys-clk manager, a sys-clk frontend homebrew Copyright (C) 2019 natinusala Copyright (C) 2019 p-sam Copyright (C) 2019 m4xw 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 <https://www.gnu.org/licenses/>. */ #include "app_profile_frame.h" #include <borealis.hpp> #include "utils.h" #include "ipc/client.h" #include <cstring> AppProfileFrame::AppProfileFrame(Title* title) : ThumbnailFrame(), title(title) { this->setTitle("Edit application profile"); this->setIcon(new brls::MaterialIcon("\uE315")); // Get the freqs Result rc = sysclkIpcGetProfiles(title->tid, &this->profiles); if (R_FAILED(rc)) errorResult("sysclkIpcGetProfiles", rc); // Setup the right sidebar this->getSidebar()->setThumbnail(title->icon, sizeof(title->icon)); this->getSidebar()->setTitle(std::string(title->name)); this->getSidebar()->setSubtitle(formatTid(title->tid)); this->getSidebar()->getButton()->setState(brls::ButtonState::DISABLED); this->getSidebar()->getButton()->getClickEvent()->subscribe([this, title](brls::View* view) { SysClkTitleProfileList profiles; memcpy(&profiles, &this->profiles, sizeof(SysClkTitleProfileList)); for (int p = 0; p < SysClkProfile_EnumMax; p++) { for (int m = 0; m < SysClkModule_EnumMax; m++) profiles.mhzMap[p][m] /= 1000000; } Result rc = sysclkIpcSetProfiles(title->tid, &profiles); if (R_SUCCEEDED(rc)) { // TODO: set the tick mark color to blue/green once borealis has rich text support brls::Application::notify("\uE14B Profile saved"); brls::Application::popView(brls::ViewAnimation::SLIDE_RIGHT); } else { errorResult("sysclkIpcSetProfiles", rc); brls::Application::notify("An error occured while saving the profile - see logs for more details"); } }); // Setup the list brls::List* list = new brls::List(); this->addFreqs(list, SysClkProfile_Docked); this->addFreqs(list, SysClkProfile_Handheld); this->addFreqs(list, SysClkProfile_HandheldCharging); this->addFreqs(list, SysClkProfile_HandheldChargingOfficial); this->addFreqs(list, SysClkProfile_HandheldChargingUSB); this->setContentView(list); } void AppProfileFrame::addFreqs(brls::List* list, SysClkProfile profile) { // Get the freqs list->addView(new brls::Header(std::string(sysclkFormatProfile(profile, true)))); // CPU brls::SelectListItem* cpuListItem = createFreqListItem(SysClkModule_CPU, this->profiles.mhzMap[profile][SysClkModule_CPU]); this->profiles.mhzMap[profile][SysClkModule_CPU] *= 1000000; cpuListItem->getValueSelectedEvent()->subscribe([this, profile](int result) { this->onProfileChanged(); this->profiles.mhzMap[profile][SysClkModule_CPU] = result == 0 ? result : sysclk_g_freq_table_cpu_hz[result - 1]; brls::Logger::debug("Caching freq for module %d and profile %d to %" PRIu32, SysClkModule_CPU, profile, this->profiles.mhzMap[profile][SysClkModule_CPU]); }); list->addView(cpuListItem); // GPU brls::SelectListItem* gpuListItem = createFreqListItem(SysClkModule_GPU, this->profiles.mhzMap[profile][SysClkModule_GPU]); this->profiles.mhzMap[profile][SysClkModule_GPU] *= 1000000; gpuListItem->getValueSelectedEvent()->subscribe([this, profile](int result) { this->onProfileChanged(); this->profiles.mhzMap[profile][SysClkModule_GPU] = result == 0 ? result : sysclk_g_freq_table_gpu_hz[result - 1]; brls::Logger::debug("Caching freq for module %d and profile %d to %" PRIu32, SysClkModule_GPU, profile, this->profiles.mhzMap[profile][SysClkModule_GPU]); }); list->addView(gpuListItem); // MEM brls::SelectListItem* memListItem = createFreqListItem(SysClkModule_MEM, this->profiles.mhzMap[profile][SysClkModule_MEM]); this->profiles.mhzMap[profile][SysClkModule_MEM] *= 1000000; memListItem->getValueSelectedEvent()->subscribe([this, profile](int result) { this->onProfileChanged(); this->profiles.mhzMap[profile][SysClkModule_MEM] = result == 0 ? result : sysclk_g_freq_table_mem_hz[result - 1]; brls::Logger::debug("Caching freq for module %d and profile %d to %" PRIu32, SysClkModule_MEM, profile, this->profiles.mhzMap[profile][SysClkModule_MEM]); }); list->addView(memListItem); } void AppProfileFrame::onProfileChanged() { this->getSidebar()->getButton()->setState(brls::ButtonState::ENABLED); this->updateActionHint(brls::Key::B, "Cancel"); } bool AppProfileFrame::onCancel() { if (this->hasProfileChanged()) { brls::Dialog* dialog = new brls::Dialog("You have unsaved changes to this profile!\nAre you sure you want to discard them?"); dialog->addButton("No", [dialog](brls::View* view){ dialog->close(); }); dialog->addButton("Yes", [dialog](brls::View* view){ dialog->close([](){ brls::Application::popView(brls::ViewAnimation::SLIDE_RIGHT); }); }); dialog->open(); } else { brls::Application::popView(brls::ViewAnimation::SLIDE_RIGHT); } return true; } bool AppProfileFrame::hasProfileChanged() { return this->getSidebar()->getButton()->getState() == brls::ButtonState::ENABLED; }
35.958084
162
0.675271
lunixoid
4ad9ce4c75b84db5a099b4379c339793d290d8b1
542
cpp
C++
tests/ClassFactoryTestInterface.cpp
duhone/core
16b1880a79ce53f8e132a9d576d5c0b64788d865
[ "MIT" ]
null
null
null
tests/ClassFactoryTestInterface.cpp
duhone/core
16b1880a79ce53f8e132a9d576d5c0b64788d865
[ "MIT" ]
null
null
null
tests/ClassFactoryTestInterface.cpp
duhone/core
16b1880a79ce53f8e132a9d576d5c0b64788d865
[ "MIT" ]
null
null
null
#include "ClassFactoryTestInterface.h" #include "core/ClassFactory.h" using namespace CR::Core; using namespace std; auto& GetInstance() { static ClassFactory<unique_ptr<TestInterface>, TestClasses, int> instance; return instance; } bool RegisterCreator(TestClasses classType, function<unique_ptr<TestInterface>(int)> creater) { GetInstance().RegisterCreator(classType, move(creater)); return true; } std::unique_ptr<TestInterface> CreateInstance(TestClasses classType, int value) { return GetInstance().Create(classType, value); }
27.1
95
0.787823
duhone
4adc3f1e3030018504a4cad9666c434b403d91d3
3,013
cpp
C++
Uva-OnlineJudge/ACMContestAndBlackout.cpp
Maqui-LP/resolucion-de-problemas
e3c81e0f1230bf609fe2ee30f978265a9a97465c
[ "MIT" ]
null
null
null
Uva-OnlineJudge/ACMContestAndBlackout.cpp
Maqui-LP/resolucion-de-problemas
e3c81e0f1230bf609fe2ee30f978265a9a97465c
[ "MIT" ]
null
null
null
Uva-OnlineJudge/ACMContestAndBlackout.cpp
Maqui-LP/resolucion-de-problemas
e3c81e0f1230bf609fe2ee30f978265a9a97465c
[ "MIT" ]
null
null
null
/* * name: ACM Contest And Blackout * link: https://vjudge.net/problem/UVA-10600 * status: Wrong Answer * date: 15/11/2020 */ #include <iostream> #include <string> #include <vector> #include <utility> #include <algorithm> using namespace std; const int INF = 1 << 30; struct UFDS { vector<int> p, rank; //también pueden usarse arreglos estáticos UFDS (int size) { p.clear(); rank.clear(); for (int i=0; i < size; i++) { p.push_back(i); rank.push_back(0); } } int find_set (int i) { return (i == p[i]) ? i : (p[i] = find_set(p[i])); } bool same_set (int i, int j) { return find_set(i) == find_set(j); } bool union_set (int i, int j) { if (!same_set(i, j)) { int x = find_set(i); int y = find_set(j); if (rank[x] > rank[y]) { p[y] = x; } else { p[x] = y; if (rank[x] == rank[y]) rank[y]++; } return true; } return false; } }; struct Conexion { int eA, eB, c; }; //Esto es para que me lo ordene con el criterio que yo quiero bool operator < (const Conexion a, const Conexion b) { return a.c < b.c; } vector<Conexion> Kruskal(int V, vector<Conexion> aristas){ vector<Conexion> MST; UFDS ds(V); int sets = V; sort(aristas.begin(), aristas.end()); for(int i = 0; i < (int)aristas.size(); i++) { if (ds.union_set(aristas[i].eA, aristas[i].eB)) { MST.push_back(aristas[i]); } } return MST; } int Kruskal2(int V, vector<Conexion> aristas, int escA, int escB){ UFDS ds(V); int total=0; int sets=V; for(int i=0; i < (int)aristas.size(); i++){ if(aristas[i].eA == escA && aristas[i].eB == escB){ continue; } if(ds.union_set(aristas[i].eA, aristas[i].eB)){ total+=aristas[i].c; sets--; } } if(sets != 1) { return INF; } return total; } int main(){ int TC, escuelaA, escuelaB, costo, escuelas, num_conexiones, suma1, suma2, tamanio; vector<Conexion> conexiones; vector<Conexion> MST; cin >> TC; while(TC--){ cin >> escuelas >> num_conexiones; conexiones.clear(); //incializo las conexiones. escuelas + conexiones = grafo while(num_conexiones--){ cin >> escuelaA >> escuelaB >> costo; conexiones.push_back(Conexion{--escuelaA, --escuelaB, costo}); } MST = Kruskal(escuelas, conexiones); tamanio = (int) MST.size(); //suma1 = sumo las aristas de MST (es el minimo peso total) suma1 = 0; for (int i=0; i < tamanio; i++){ suma1+=MST[i].c; } suma2 = INF; //Para cada una de las aristas del MST: segundo kruskal for (int i=0; i < tamanio; i++){ suma2 = min(suma2, Kruskal2(escuelas, conexiones, MST[i].eA, MST[i].eB)); } if (suma2==INF){ suma2=suma1; } cout << suma1 << " " << suma2 << endl;; } return 0; }
22.825758
87
0.538666
Maqui-LP
4adce75d5329154c2834c66a217d6df01afb2170
753
cpp
C++
solutions/29.divide-two-integers.377323112.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/29.divide-two-integers.377323112.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/29.divide-two-integers.377323112.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: int divide(int dividend, int divisor) { if (dividend == -2147483648 && divisor == -1) return 2147483647; int lol = (divisor < 0); divisor = abs(divisor); lol ^= (dividend < 0); dividend = abs(dividend); int lol2 = 1; if (lol) lol2 = -1; vector<long long> vals; vals.push_back(divisor); for (int i = 1; i < 32; i++) { long long nxt = vals.back() + vals.back(); vals.push_back(nxt); } long long ans = 0; long long current = dividend; for (int i = 31; i >= 0; i--) { if (current - vals[i] >= 0) { current -= vals[i]; ans += (1LL << i); } } cout << lol2 << " " << ans << endl; return 1LL * lol2 * ans; } };
23.53125
49
0.501992
satu0king
4adf65195fe875e638756800ed672043045ce38c
931
hpp
C++
old_projects/SuspendedPlotterIoT/UploadHandler.hpp
renato-grottesi/microbit
728df27704211397b27a098445e68f8de52e8e4e
[ "Apache-2.0" ]
3
2018-10-26T09:32:57.000Z
2018-11-04T18:15:03.000Z
old_projects/SuspendedPlotterIoT/UploadHandler.hpp
renato-grottesi/microbit
728df27704211397b27a098445e68f8de52e8e4e
[ "Apache-2.0" ]
null
null
null
old_projects/SuspendedPlotterIoT/UploadHandler.hpp
renato-grottesi/microbit
728df27704211397b27a098445e68f8de52e8e4e
[ "Apache-2.0" ]
null
null
null
#ifndef UPLOAD_HANDLER_H #define UPLOAD_HANDLER_H #include "HTTPRequestHandler.h" #include "SuspendedPlotter.h" class UploadHandler : public HTTPRequestHandler { public: UploadHandler(const char* rootPath, const char* path, TCPSocket* pTcpSocket); virtual ~UploadHandler(); static inline HTTPRequestHandler* inst(const char* rootPath, const char* path, TCPSocket* pTcpSocket) { return new UploadHandler(rootPath, path, pTcpSocket); } protected: virtual void doGet(); virtual void doPost(); virtual void doHead(); virtual void onReadable(); //Data has been read virtual void onWriteable(); //Data has been written & buf is free virtual void onClose(); //Connection is closing private: FILE* m_fp; int m_total_read; int m_post_size; static const float orig_x = 0.5; static const float orig_y = 0.5; float m_x; float m_y; }; #endif
25.861111
105
0.692803
renato-grottesi
4ae0370dbe3021ef55b83f3070b77d7df0637ce5
4,470
cpp
C++
src/MentalPitchShift.cpp
miRackModular/Strums_Mental_VCV_Modules
1660a55bfc1c2df098bcf028713e1f7ffbe110ab
[ "BSD-3-Clause" ]
76
2017-10-13T10:39:48.000Z
2021-12-20T14:15:45.000Z
src/MentalPitchShift.cpp
miRackModular/Strums_Mental_VCV_Modules
1660a55bfc1c2df098bcf028713e1f7ffbe110ab
[ "BSD-3-Clause" ]
54
2017-10-13T14:40:07.000Z
2022-02-01T14:48:46.000Z
src/MentalPitchShift.cpp
miRackModular/Strums_Mental_VCV_Modules
1660a55bfc1c2df098bcf028713e1f7ffbe110ab
[ "BSD-3-Clause" ]
27
2017-10-21T15:45:12.000Z
2021-01-15T12:27:51.000Z
/////////////////////////////////////////////////// // // Mental Plugin // Pitch Shifter - shift pitch by octaves or semitones // // Strum 2017-19 // [email protected] // /////////////////////////////////////////////////// #include "mental.hpp" ////////////////////////////////////////////////////// struct MentalPitchShift : Module { enum ParamIds { OCTAVE_SHIFT_1, OCTAVE_SHIFT_2, SEMITONE_SHIFT_1, SEMITONE_SHIFT_2, NUM_PARAMS }; enum InputIds { OCTAVE_SHIFT_1_INPUT, OCTAVE_SHIFT_2_INPUT, SEMITONE_SHIFT_1_INPUT, SEMITONE_SHIFT_2_INPUT, OCTAVE_SHIFT_1_CVINPUT, OCTAVE_SHIFT_2_CVINPUT, SEMITONE_SHIFT_1_CVINPUT, SEMITONE_SHIFT_2_CVINPUT, NUM_INPUTS }; enum OutputIds { OCTAVE_SHIFT_1_OUTPUT, OCTAVE_SHIFT_2_OUTPUT, SEMITONE_SHIFT_1_OUTPUT, SEMITONE_SHIFT_2_OUTPUT, NUM_OUTPUTS }; MentalPitchShift() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS); configParam(MentalPitchShift::OCTAVE_SHIFT_1, -4.5, 4.5, 0.0, ""); configParam(MentalPitchShift::OCTAVE_SHIFT_2, -4.5, 4.5, 0.0, ""); configParam(MentalPitchShift::SEMITONE_SHIFT_1, -6.5, 6.5, 0.0, ""); configParam(MentalPitchShift::SEMITONE_SHIFT_2, -6.5, 6.5, 0.0, ""); } float octave_1_out = 0.0; float octave_2_out = 0.0; float semitone_1_out = 0.0; float semitone_2_out = 0.0; void process(const ProcessArgs& args) override; }; ///////////////////////////////////////////////////// void MentalPitchShift::process(const ProcessArgs& args) { octave_1_out = inputs[OCTAVE_SHIFT_1_INPUT].getVoltage() + round(params[OCTAVE_SHIFT_1].getValue()) + round(inputs[OCTAVE_SHIFT_1_CVINPUT].getVoltage()/2); octave_2_out = inputs[OCTAVE_SHIFT_2_INPUT].getVoltage() + round(params[OCTAVE_SHIFT_2].getValue()) + round(inputs[OCTAVE_SHIFT_1_CVINPUT].getVoltage()/2); semitone_1_out = inputs[SEMITONE_SHIFT_1_INPUT].getVoltage() + round(params[SEMITONE_SHIFT_1].getValue())*(1.0/12.0) + round(inputs[SEMITONE_SHIFT_1_CVINPUT].getVoltage()/2)*(1.0/12.0); semitone_2_out = inputs[SEMITONE_SHIFT_2_INPUT].getVoltage() + round(params[SEMITONE_SHIFT_2].getValue())*(1.0/12.0) + round(inputs[SEMITONE_SHIFT_2_CVINPUT].getVoltage()/2)*(1.0/12.0); outputs[OCTAVE_SHIFT_1_OUTPUT].setVoltage(octave_1_out); outputs[OCTAVE_SHIFT_2_OUTPUT].setVoltage(octave_2_out); outputs[SEMITONE_SHIFT_1_OUTPUT].setVoltage(semitone_1_out); outputs[SEMITONE_SHIFT_2_OUTPUT].setVoltage(semitone_2_out); } ////////////////////////////////////////////////////////////////// struct MentalPitchShiftWidget : ModuleWidget { MentalPitchShiftWidget(MentalPitchShift *module) { setModule(module); setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/MentalPitchShift.svg"))); addParam(createParam<MedKnob>(Vec(2, 20), module, MentalPitchShift::OCTAVE_SHIFT_1)); addParam(createParam<MedKnob>(Vec(2, 80), module, MentalPitchShift::OCTAVE_SHIFT_2)); addParam(createParam<MedKnob>(Vec(2, 140), module, MentalPitchShift::SEMITONE_SHIFT_1)); addParam(createParam<MedKnob>(Vec(2, 200), module, MentalPitchShift::SEMITONE_SHIFT_2)); addInput(createInput<CVInPort>(Vec(3, 50), module, MentalPitchShift::OCTAVE_SHIFT_1_INPUT)); addInput(createInput<CVInPort>(Vec(3, 110), module, MentalPitchShift::OCTAVE_SHIFT_2_INPUT)); addInput(createInput<CVInPort>(Vec(3, 170), module, MentalPitchShift::SEMITONE_SHIFT_1_INPUT)); addInput(createInput<CVInPort>(Vec(3, 230), module, MentalPitchShift::SEMITONE_SHIFT_2_INPUT)); addInput(createInput<CVInPort>(Vec(33, 20), module, MentalPitchShift::OCTAVE_SHIFT_1_CVINPUT)); addInput(createInput<CVInPort>(Vec(33, 80), module, MentalPitchShift::OCTAVE_SHIFT_2_CVINPUT)); addInput(createInput<CVInPort>(Vec(33, 140), module, MentalPitchShift::SEMITONE_SHIFT_1_CVINPUT)); addInput(createInput<CVInPort>(Vec(33, 200), module, MentalPitchShift::SEMITONE_SHIFT_2_CVINPUT)); addOutput(createOutput<CVOutPort>(Vec(33, 50), module, MentalPitchShift::OCTAVE_SHIFT_1_OUTPUT)); addOutput(createOutput<CVOutPort>(Vec(33, 110), module, MentalPitchShift::OCTAVE_SHIFT_2_OUTPUT)); addOutput(createOutput<CVOutPort>(Vec(33, 170), module, MentalPitchShift::SEMITONE_SHIFT_1_OUTPUT)); addOutput(createOutput<CVOutPort>(Vec(33, 230), module, MentalPitchShift::SEMITONE_SHIFT_2_OUTPUT)); } }; Model *modelMentalPitchShift = createModel<MentalPitchShift, MentalPitchShiftWidget>("MentalPitchShift");
41.775701
187
0.707606
miRackModular
4ae062c357f69cb35ddcc76a3cca5261a114e2f5
2,049
cpp
C++
Examples/CPP/WorkingWithProjects/ImportingAndExporting/ImportDataFromMPXFileFormats.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2022-03-16T14:31:36.000Z
2022-03-16T14:31:36.000Z
Examples/CPP/WorkingWithProjects/ImportingAndExporting/ImportDataFromMPXFileFormats.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
null
null
null
Examples/CPP/WorkingWithProjects/ImportingAndExporting/ImportDataFromMPXFileFormats.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2020-07-01T01:26:17.000Z
2020-07-01T01:26:17.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/tasks */ #include "WorkingWithProjects/ImportingAndExporting/ImportDataFromMPXFileFormats.h" #include <system/type_info.h> #include <system/string.h> #include <system/shared_ptr.h> #include <system/reflection/method_base.h> #include <system/object_ext.h> #include <system/object.h> #include <system/console.h> #include <ProjectFileInfo.h> #include <Project.h> #include <enums/FileFormat.h> #include "RunExamples.h" namespace Aspose { namespace Tasks { namespace Examples { namespace CPP { namespace WorkingWithProjects { namespace ImportingAndExporting { RTTI_INFO_IMPL_HASH(3498962390u, ::Aspose::Tasks::Examples::CPP::WorkingWithProjects::ImportingAndExporting::ImportDataFromMPXFileFormats, ThisTypeBaseTypesInfo); void ImportDataFromMPXFileFormats::Run() { // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName()); // ExStart:ImportDataFromMPXFileFormats System::SharedPtr<Project> project = System::MakeObject<Project>(dataDir + u"Primavera1.mpx"); System::SharedPtr<ProjectFileInfo> info = Project::GetProjectFileInfo(dataDir + u"primavera1.mpx"); System::Console::WriteLine(System::ObjectExt::Box<FileFormat>(info->get_ProjectFileFormat())); // ExEnd:ImportDataFromMPXFileFormats } } // namespace ImportingAndExporting } // namespace WorkingWithProjects } // namespace CPP } // namespace Examples } // namespace Tasks } // namespace Aspose
37.254545
164
0.781357
aspose-tasks
4ae0befef910ae6f16a4f0ce916bca5d5c30bfb0
1,017
cpp
C++
Src/MapEditor/lightedit.cpp
vox-1/MapEditor
f1b8a3df64c91e9c3aef7ee21e997f4f1163fa0e
[ "MIT" ]
23
2018-12-02T01:08:39.000Z
2022-03-19T02:28:56.000Z
Src/MapEditor/lightedit.cpp
vox-1/MapEditor
f1b8a3df64c91e9c3aef7ee21e997f4f1163fa0e
[ "MIT" ]
null
null
null
Src/MapEditor/lightedit.cpp
vox-1/MapEditor
f1b8a3df64c91e9c3aef7ee21e997f4f1163fa0e
[ "MIT" ]
15
2018-12-07T06:33:55.000Z
2022-03-26T13:27:25.000Z
#include "stdafx.h" #include "lightedit.h" using namespace graphic; cLightEdit::cLightEdit() : m_showLightDir(true) , m_openLightEdit(false) { } cLightEdit::~cLightEdit() { } bool cLightEdit::Init(graphic::cRenderer &renderer) { m_lightDir = GetMainLight().m_direction; return true; } void cLightEdit::Render(graphic::cRenderer &renderer) { m_openLightEdit = false; //ImGui::SetNextTreeNodeOpen(true, ImGuiSetCond_FirstUseEver); if (ImGui::CollapsingHeader("Light Edit")) { m_openLightEdit = true; ImGui::Checkbox("Show Light Direction", &m_showLightDir); float v[2] = { m_lightDir.x, m_lightDir.z }; if (ImGui::DragFloat2("Direction X - Z", v, 0.01f)) { m_lightDir.x = v[0]; m_lightDir.z = v[1]; m_lightDir.Normalize(); GetMainLight().m_direction = m_lightDir; } ImGui::ColorEdit3("Ambient", (float*)&GetMainLight().m_ambient); ImGui::ColorEdit3("Diffuse", (float*)&GetMainLight().m_diffuse); ImGui::ColorEdit3("Specular", (float*)&GetMainLight().m_specular); } }
19.941176
68
0.702065
vox-1
4ae281caf0afe4adb10a5aba5ad5b9af692c6b8e
1,633
cpp
C++
src/interprocess/basic_publisher/publisher.cpp
ashish-boss/goby3-examples
686b290bf84a10f02ba169a8f1363dba43c9ed95
[ "MIT" ]
3
2017-08-03T19:00:29.000Z
2019-12-15T04:47:26.000Z
src/interprocess/basic_publisher/publisher.cpp
ashish-boss/goby3-examples
686b290bf84a10f02ba169a8f1363dba43c9ed95
[ "MIT" ]
3
2020-05-14T15:49:57.000Z
2021-04-15T19:02:07.000Z
src/interprocess/basic_publisher/publisher.cpp
ashish-boss/goby3-examples
686b290bf84a10f02ba169a8f1363dba43c9ed95
[ "MIT" ]
2
2020-04-27T20:12:17.000Z
2021-08-17T01:58:56.000Z
#include <goby/middleware/marshalling/protobuf.h> // provides serializer / parser for Google Protocol Buffers #include <goby/zeromq/application/single_thread.h> // provides SingleThreadApplication #include "messages/groups.h" // defines publish/subscribe groups #include "messages/nav.pb.h" // Protobuf, defines NavigationReport #include "config.pb.h" // Protobuf, defines BasicPublisherConfig // optional "using" declaration (reduces verbiage) using Base = goby::zeromq::SingleThreadApplication<BasicPublisherConfig>; using protobuf::NavigationReport; class BasicPublisher : public Base { public: BasicPublisher() : Base(10 /*hertz*/) { // all configuration defined in BasicPublisherConfig is available using cfg(); std::cout << "My configuration int is: " << cfg().my_value() << std::endl; } // virtual method in goby::zeromq::SingleThreadApplication called at the frequency given to Base(freq) void loop() override { NavigationReport nav; nav.set_x(95 + std::rand() % 20); nav.set_y(195 + std::rand() % 20); nav.set_z(-305 + std::rand() % 10); std::cout << "Tx: " << nav.DebugString() << std::flush; interprocess().publish<groups::nav>(nav); } }; // reads command line parameters based on BasicPublisherConfig definition // these can be set on the command line (try "basic_publisher --help" to see parameters) // or in a configuration file (use "basic_publisher --example_config" for the correct syntax) // edit "config.proto" to add parameters int main(int argc, char* argv[]) { return goby::run<BasicPublisher>(argc, argv); }
39.829268
109
0.699939
ashish-boss
4ae4332272da3f90a2734c73e6e5212de96ef9ce
420
cpp
C++
sources/GameEngine/getColor.cpp
gillioa/Bomberman
5e21c317a4b3d00533acdddb99b98c08b102fe45
[ "MIT" ]
null
null
null
sources/GameEngine/getColor.cpp
gillioa/Bomberman
5e21c317a4b3d00533acdddb99b98c08b102fe45
[ "MIT" ]
null
null
null
sources/GameEngine/getColor.cpp
gillioa/Bomberman
5e21c317a4b3d00533acdddb99b98c08b102fe45
[ "MIT" ]
null
null
null
#include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> glm::vec4 getColor(unsigned int num, unsigned int total) { unsigned int ec1 = 2 * (total / (num + 1) + 1 + (total % (num + 1)) * 55) % 0xFF; unsigned int ec2 = 3 * (ec1 + total % (num + ((num + 1) % 8))) % 0xFF; unsigned int ec3 = 4 * (ec2 + total / (num + (total / 2) + 1)) % 0xFF; return (glm::vec4(ec1 / 255.0, ec2 / 255.0, ec3 / 255.0, 1)); }
38.181818
83
0.571429
gillioa
4aeb1785c46d095ced534989f8487601767d32dd
838
inl
C++
gle/vao.inl
zacklukem/gle
b643eb9f418df7c80c96abf5521a92589fa17ab3
[ "MIT" ]
null
null
null
gle/vao.inl
zacklukem/gle
b643eb9f418df7c80c96abf5521a92589fa17ab3
[ "MIT" ]
null
null
null
gle/vao.inl
zacklukem/gle
b643eb9f418df7c80c96abf5521a92589fa17ab3
[ "MIT" ]
null
null
null
GLE_NAMESPACE_BEGIN inline VAO::VAO() : handle(0) {} inline VAO::~VAO() { if (handle) glDeleteVertexArrays(1, &handle); } inline void VAO::init() { glGenVertexArrays(1, &handle); } inline void VAO::bind() const { glBindVertexArray(handle); } template <class T> inline void VAO::attr(GLuint index, const VBO<T> &vbo) const { bind(); vbo.bind(); switch (VBO<T>::gl_value_type) { case GL_BYTE: case GL_UNSIGNED_BYTE: case GL_SHORT: case GL_UNSIGNED_SHORT: case GL_INT: case GL_UNSIGNED_INT: glVertexAttribIPointer(index, VBO<T>::gl_value_size, VBO<T>::gl_value_type, sizeof(T), (void *)0); break; default: glVertexAttribPointer(index, VBO<T>::gl_value_size, VBO<T>::gl_value_type, GL_FALSE, sizeof(T), (void *)0); break; } } GLE_NAMESPACE_END
24.647059
79
0.649165
zacklukem
4afc58bd3678ce6f61cfd0fbc7cedaa91bbc8af6
2,481
cxx
C++
event/cyan/event.cxx
sayan-chaliha/cyan
4e653d08ecfec0f2b4c6c077359f5a66787197a4
[ "MIT" ]
3
2021-10-30T14:59:38.000Z
2022-02-21T03:17:48.000Z
event/cyan/event.cxx
sayan-chaliha/cyan
4e653d08ecfec0f2b4c6c077359f5a66787197a4
[ "MIT" ]
null
null
null
event/cyan/event.cxx
sayan-chaliha/cyan
4e653d08ecfec0f2b4c6c077359f5a66787197a4
[ "MIT" ]
null
null
null
/** * The MIT License (MIT) * * Copyright (c) 2020, Sayan Chaliha * * 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 <mutex> #include <thread> #include <memory> #include <cyan/event.h> #include <cyan/event/basic_loop.txx> #include <cyan/event/basic_async.txx> #include <cyan/event/basic_io.txx> namespace { static std::thread::id main_thread_id = std::this_thread::get_id(); } namespace cyan::event { inline namespace v1 { std::shared_ptr<event::loop> get_main_loop() { static std::shared_ptr<event::loop> loop; static std::once_flag once_flag; std::call_once(once_flag, [&] { loop = std::make_shared<event::loop>(); }); return loop; } template class basic_loop<default_backend_traits>; template class basic_async<default_backend_traits>; template class basic_idle<default_backend_traits>; template class basic_timer<default_backend_traits>; template class basic_timer_wheel<default_backend_traits>; template class basic_io<default_backend_traits>; } // v1 } // cyan::event namespace cyan::this_thread { inline namespace v1 { std::shared_ptr<event::loop> get_event_loop() { if (std::this_thread::get_id() == main_thread_id) { return cyan::event::get_main_loop(); } static thread_local std::shared_ptr<event::loop> loop; static thread_local std::once_flag once_flag; std::call_once(once_flag, [&] { loop = std::make_shared<event::loop>(); }); return loop; } } // v1 } // cyan::this_thread
29.891566
81
0.742846
sayan-chaliha
ab101573c1620ad335809ee1c7f27afdeab4d3d8
596
cpp
C++
Project1/Collision.cpp
RyunosukeKawakami/SlimeHunter
bf9c496fefc59bb68756249400ac9cba253597be
[ "IJG", "Unlicense" ]
null
null
null
Project1/Collision.cpp
RyunosukeKawakami/SlimeHunter
bf9c496fefc59bb68756249400ac9cba253597be
[ "IJG", "Unlicense" ]
null
null
null
Project1/Collision.cpp
RyunosukeKawakami/SlimeHunter
bf9c496fefc59bb68756249400ac9cba253597be
[ "IJG", "Unlicense" ]
null
null
null
#include "Collision.h" Collision::Collision() { } Collision::~Collision() { } bool Collision::Main(Point a, Point b) { if (Distance(a,b)) return Temp(a,b); else return false; } bool Collision::Distance(Point a, Point b) { bool x; bool y; x = a.x - 32 * 4 < b.x < a.x + 32 * 4; y = a.y - 32 * 4 < b.y < a.y + 32 * 4; if (x == true && y == true) return true; else return false; } bool Collision::Temp(Point a, Point b) { bool x; bool y; x = a.x2 >= b.x && a.x <= b.x2; y = a.y2 >= b.y && a.y <= b.y2; if (x == true && y == true) return true; else return false; }
12.956522
42
0.545302
RyunosukeKawakami
ab1321bb924c0c4163be90d2c196ba4de3f9fa17
1,572
cpp
C++
src/platform/opengl/graphics_gl_context.cpp
104-Berlin/usk-graphics
537dd48aa354b18b68424120a3aa64a246fefaf6
[ "MIT" ]
null
null
null
src/platform/opengl/graphics_gl_context.cpp
104-Berlin/usk-graphics
537dd48aa354b18b68424120a3aa64a246fefaf6
[ "MIT" ]
null
null
null
src/platform/opengl/graphics_gl_context.cpp
104-Berlin/usk-graphics
537dd48aa354b18b68424120a3aa64a246fefaf6
[ "MIT" ]
null
null
null
#include "graphics_opengl.h" using namespace GL; void GLContext::Init(void* initData) { if (!initData) { printf("Please provide the GLADloadproc to the OpenGL context init"); return; } int gladStatus = gladLoadGLLoader((GLADloadproc)initData); printf("Glad Init Status: %d\n", gladStatus); printf("%s\n", glGetString(GL_VERSION)); EnableDepthTest(true); } void GLContext::Clear(float r, float g, float b, unsigned char GCLEAROPTIONS) { GLuint clearOption = 0; clearOption |= GCLEAROPTIONS & GCLEAROPTION_COLOR_BUFFER ? GL_COLOR_BUFFER_BIT : 0; clearOption |= GCLEAROPTIONS & GCLEAROPTION_DEPTH_BUFFER ? GL_DEPTH_BUFFER_BIT : 0; clearOption |= GCLEAROPTIONS & GCLEAROPTION_STENCIL_BUFFER ? GL_STENCIL_BUFFER_BIT : 0; clearOption |= GCLEAROPTIONS & GCLEAROPTION_ACCUM_BUFFER ? GL_ACCUM_BUFFER_BIT : 0; glCall(glClearColor(r, g, b, 1)); glCall(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); } void GLContext::EnableDepthTest(bool enable) { glCall(glDisable(GL_SCISSOR_TEST)); if (fDepthTestEnabled) { glCall(glEnable(GL_DEPTH_TEST)); } else { glCall(glDisable(GL_DEPTH_TEST)); } } void GLContext::DrawElements(size_t count, Graphics::GIndexType indexType, Graphics::GDrawMode drawMode) { glCall(glDrawElements(DrawModeToOpenGLMode(drawMode), count, IndexTypeToOpenGLType(indexType), NULL)); } void GLContext::DrawArrays(size_t start, size_t count, Graphics::GDrawMode drawMode) { glCall(glDrawArrays(DrawModeToOpenGLMode(drawMode), start, count)); }
32.75
106
0.73028
104-Berlin
ab1b41fc425059e49a59526fcc3ee6e4b776a49b
28,467
cxx
C++
src/libserver/symcache/symcache_impl.cxx
msuslu/rspamd
95764f816a9e1251a755c6edad339637345cfe28
[ "Apache-2.0" ]
null
null
null
src/libserver/symcache/symcache_impl.cxx
msuslu/rspamd
95764f816a9e1251a755c6edad339637345cfe28
[ "Apache-2.0" ]
null
null
null
src/libserver/symcache/symcache_impl.cxx
msuslu/rspamd
95764f816a9e1251a755c6edad339637345cfe28
[ "Apache-2.0" ]
null
null
null
/*- * Copyright 2022 Vsevolod Stakhov * * 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 "lua/lua_common.h" #include "symcache_internal.hxx" #include "symcache_item.hxx" #include "symcache_runtime.hxx" #include "unix-std.h" #include "libutil/cxx/locked_file.hxx" #include "fmt/core.h" #include "contrib/t1ha/t1ha.h" #include <cmath> namespace rspamd::symcache { INIT_LOG_MODULE_PUBLIC(symcache) auto symcache::init() -> bool { auto res = true; reload_time = cfg->cache_reload_time; if (cfg->cache_filename != nullptr) { res = load_items(); } /* Deal with the delayed dependencies */ for (const auto &delayed_dep: *delayed_deps) { auto virt_item = get_item_by_name(delayed_dep.from, false); auto real_item = get_item_by_name(delayed_dep.from, true); if (virt_item == nullptr || real_item == nullptr) { msg_err_cache("cannot register delayed dependency between %s and %s: " "%s is missing", delayed_dep.from.data(), delayed_dep.to.data(), delayed_dep.from.data()); } else { msg_debug_cache("delayed between %s(%d:%d) -> %s", delayed_dep.from.data(), real_item->id, virt_item->id, delayed_dep.to.data()); add_dependency(real_item->id, delayed_dep.to, virt_item != real_item ? virt_item->id : -1); } } /* Remove delayed dependencies, as they are no longer needed at this point */ delayed_deps.reset(); /* Deal with the delayed conditions */ for (const auto &delayed_cond: *delayed_conditions) { auto it = get_item_by_name_mut(delayed_cond.sym, true); if (it == nullptr) { msg_err_cache ( "cannot register delayed condition for %s", delayed_cond.sym.c_str()); luaL_unref(delayed_cond.L, LUA_REGISTRYINDEX, delayed_cond.cbref); } else { if (!it->add_condition(delayed_cond.L, delayed_cond.cbref)) { msg_err_cache ( "cannot register delayed condition for %s: virtual parent; qed", delayed_cond.sym.c_str()); g_abort(); } } } delayed_conditions.reset(); for (auto &it: items_by_id) { it->process_deps(*this); } /* Sorting stuff */ auto postfilters_cmp = [](const auto &it1, const auto &it2) -> int { if (it1->priority > it2->priority) { return 1; } else if (it1->priority == it2->priority) { return 0; } return -1; }; auto prefilters_cmp = [](const auto &it1, const auto &it2) -> int { if (it1->priority > it2->priority) { return -1; } else if (it1->priority == it2->priority) { return 0; } return 1; }; std::stable_sort(std::begin(connfilters), std::end(connfilters), prefilters_cmp); std::stable_sort(std::begin(prefilters), std::end(prefilters), prefilters_cmp); std::stable_sort(std::begin(postfilters), std::end(postfilters), postfilters_cmp); std::stable_sort(std::begin(idempotent), std::end(idempotent), postfilters_cmp); resort(); /* Connect metric symbols with symcache symbols */ if (cfg->symbols) { g_hash_table_foreach(cfg->symbols, symcache::metric_connect_cb, (void *) this); } return res; } auto symcache::load_items() -> bool { auto cached_map = util::raii_mmaped_locked_file::mmap_shared(cfg->cache_filename, O_RDONLY, PROT_READ); if (!cached_map.has_value()) { msg_info_cache("%s", cached_map.error().c_str()); return false; } if (cached_map->get_size() < (gint) sizeof(symcache_header)) { msg_info_cache("cannot use file %s, truncated: %z", cfg->cache_filename, errno, strerror(errno)); return false; } const auto *hdr = (struct symcache_header *) cached_map->get_map(); if (memcmp(hdr->magic, symcache_magic, sizeof(symcache_magic)) != 0) { msg_info_cache("cannot use file %s, bad magic", cfg->cache_filename); return false; } auto *parser = ucl_parser_new(0); const auto *p = (const std::uint8_t *) (hdr + 1); if (!ucl_parser_add_chunk(parser, p, cached_map->get_size() - sizeof(*hdr))) { msg_info_cache ("cannot use file %s, cannot parse: %s", cfg->cache_filename, ucl_parser_get_error(parser)); ucl_parser_free(parser); return false; } auto *top = ucl_parser_get_object(parser); ucl_parser_free(parser); if (top == nullptr || ucl_object_type(top) != UCL_OBJECT) { msg_info_cache ("cannot use file %s, bad object", cfg->cache_filename); ucl_object_unref(top); return false; } auto it = ucl_object_iterate_new(top); const ucl_object_t *cur; while ((cur = ucl_object_iterate_safe(it, true)) != nullptr) { auto item_it = items_by_symbol.find(ucl_object_key(cur)); if (item_it != items_by_symbol.end()) { auto item = item_it->second; /* Copy saved info */ /* * XXX: don't save or load weight, it should be obtained from the * metric */ #if 0 elt = ucl_object_lookup (cur, "weight"); if (elt) { w = ucl_object_todouble (elt); if (w != 0) { item->weight = w; } } #endif const auto *elt = ucl_object_lookup(cur, "time"); if (elt) { item->st->avg_time = ucl_object_todouble(elt); } elt = ucl_object_lookup(cur, "count"); if (elt) { item->st->total_hits = ucl_object_toint(elt); item->last_count = item->st->total_hits; } elt = ucl_object_lookup(cur, "frequency"); if (elt && ucl_object_type(elt) == UCL_OBJECT) { const ucl_object_t *freq_elt; freq_elt = ucl_object_lookup(elt, "avg"); if (freq_elt) { item->st->avg_frequency = ucl_object_todouble(freq_elt); } freq_elt = ucl_object_lookup(elt, "stddev"); if (freq_elt) { item->st->stddev_frequency = ucl_object_todouble(freq_elt); } } if (item->is_virtual() && !item->is_ghost()) { const auto &parent = item->get_parent(*this); if (parent) { if (parent->st->weight < item->st->weight) { parent->st->weight = item->st->weight; } } /* * We maintain avg_time for virtual symbols equal to the * parent item avg_time */ item->st->avg_time = parent->st->avg_time; } total_weight += fabs(item->st->weight); total_hits += item->st->total_hits; } } ucl_object_iterate_free(it); ucl_object_unref(top); return true; } template<typename T> static constexpr auto round_to_hundreds(T x) { return (::floor(x) * 100.0) / 100.0; } bool symcache::save_items() const { if (cfg->cache_filename == nullptr) { return false; } auto file_sink = util::raii_file_sink::create(cfg->cache_filename, O_WRONLY | O_TRUNC, 00644); if (!file_sink.has_value()) { if (errno == EEXIST) { /* Some other process is already writing data, give up silently */ return false; } msg_err_cache("%s", file_sink.error().c_str()); return false; } struct symcache_header hdr; memset(&hdr, 0, sizeof(hdr)); memcpy(hdr.magic, symcache_magic, sizeof(symcache_magic)); if (write(file_sink->get_fd(), &hdr, sizeof(hdr)) == -1) { msg_err_cache("cannot write to file %s, error %d, %s", cfg->cache_filename, errno, strerror(errno)); return false; } auto *top = ucl_object_typed_new(UCL_OBJECT); for (const auto &it: items_by_symbol) { auto item = it.second; auto elt = ucl_object_typed_new(UCL_OBJECT); ucl_object_insert_key(elt, ucl_object_fromdouble(round_to_hundreds(item->st->weight)), "weight", 0, false); ucl_object_insert_key(elt, ucl_object_fromdouble(round_to_hundreds(item->st->time_counter.mean)), "time", 0, false); ucl_object_insert_key(elt, ucl_object_fromint(item->st->total_hits), "count", 0, false); auto *freq = ucl_object_typed_new(UCL_OBJECT); ucl_object_insert_key(freq, ucl_object_fromdouble(round_to_hundreds(item->st->frequency_counter.mean)), "avg", 0, false); ucl_object_insert_key(freq, ucl_object_fromdouble(round_to_hundreds(item->st->frequency_counter.stddev)), "stddev", 0, false); ucl_object_insert_key(elt, freq, "frequency", 0, false); ucl_object_insert_key(top, elt, it.first.data(), 0, true); } auto fp = fdopen(file_sink->get_fd(), "a"); auto *efunc = ucl_object_emit_file_funcs(fp); auto ret = ucl_object_emit_full(top, UCL_EMIT_JSON_COMPACT, efunc, nullptr); ucl_object_emit_funcs_free(efunc); ucl_object_unref(top); fclose(fp); return ret; } auto symcache::metric_connect_cb(void *k, void *v, void *ud) -> void { auto *cache = (symcache *) ud; const auto *sym = (const char *) k; auto *s = (struct rspamd_symbol *) v; auto weight = *s->weight_ptr; auto *item = cache->get_item_by_name_mut(sym, false); if (item) { item->st->weight = weight; s->cache_item = (void *) item; } } auto symcache::get_item_by_id(int id, bool resolve_parent) const -> const cache_item * { if (id < 0 || id >= items_by_id.size()) { msg_err_cache("internal error: requested item with id %d, when we have just %d items in the cache", id, (int) items_by_id.size()); return nullptr; } auto &ret = items_by_id[id]; if (!ret) { msg_err_cache("internal error: requested item with id %d but it is empty; qed", id); return nullptr; } if (resolve_parent && ret->is_virtual()) { return ret->get_parent(*this); } return ret.get(); } auto symcache::get_item_by_name(std::string_view name, bool resolve_parent) const -> const cache_item * { auto it = items_by_symbol.find(name); if (it == items_by_symbol.end()) { return nullptr; } if (resolve_parent && it->second->is_virtual()) { return it->second->get_parent(*this); } return it->second.get(); } auto symcache::get_item_by_name_mut(std::string_view name, bool resolve_parent) const -> cache_item * { auto it = items_by_symbol.find(name); if (it == items_by_symbol.end()) { return nullptr; } if (resolve_parent && it->second->is_virtual()) { return (cache_item *) it->second->get_parent(*this); } return it->second.get(); } auto symcache::add_dependency(int id_from, std::string_view to, int virtual_id_from) -> void { g_assert (id_from >= 0 && id_from < (gint) items_by_id.size()); const auto &source = items_by_id[id_from]; g_assert (source.get() != nullptr); source->deps.emplace_back(cache_item_ptr{nullptr}, std::string(to), id_from, -1); if (virtual_id_from >= 0) { g_assert (virtual_id_from < (gint) items_by_id.size()); /* We need that for settings id propagation */ const auto &vsource = items_by_id[virtual_id_from]; g_assert (vsource.get() != nullptr); vsource->deps.emplace_back(cache_item_ptr{nullptr}, std::string(to), -1, virtual_id_from); } } auto symcache::resort() -> void { auto ord = std::make_shared<order_generation>(filters.size(), cur_order_gen); for (auto &it: filters) { if (it) { total_hits += it->st->total_hits; it->order = 0; ord->d.emplace_back(it); } } enum class tsort_mask { PERM, TEMP }; constexpr auto tsort_unmask = [](cache_item *it) -> auto { return (it->order & ~((1u << 31) | (1u << 30))); }; /* Recursive topological sort helper */ const auto tsort_visit = [&](cache_item *it, unsigned cur_order, auto &&rec) { constexpr auto tsort_mark = [](cache_item *it, tsort_mask how) { switch (how) { case tsort_mask::PERM: it->order |= (1u << 31); break; case tsort_mask::TEMP: it->order |= (1u << 30); break; } }; constexpr auto tsort_is_marked = [](cache_item *it, tsort_mask how) { switch (how) { case tsort_mask::PERM: return (it->order & (1u << 31)); case tsort_mask::TEMP: return (it->order & (1u << 30)); } return 100500u; /* Because fuck compilers, that's why */ }; if (tsort_is_marked(it, tsort_mask::PERM)) { if (cur_order > tsort_unmask(it)) { /* Need to recalculate the whole chain */ it->order = cur_order; /* That also removes all masking */ } else { /* We are fine, stop DFS */ return; } } else if (tsort_is_marked(it, tsort_mask::TEMP)) { msg_err_cache("cyclic dependencies found when checking '%s'!", it->symbol.c_str()); return; } tsort_mark(it, tsort_mask::TEMP); msg_debug_cache("visiting node: %s (%d)", it->symbol.c_str(), cur_order); for (const auto &dep: it->deps) { msg_debug_cache ("visiting dep: %s (%d)", dep.item->symbol.c_str(), cur_order + 1); rec(dep.item.get(), cur_order + 1, rec); } it->order = cur_order; tsort_mark(it, tsort_mask::PERM); }; /* * Topological sort */ total_hits = 0; auto used_items = ord->d.size(); for (const auto &it: ord->d) { if (it->order == 0) { tsort_visit(it.get(), 0, tsort_visit); } } /* Main sorting comparator */ constexpr auto score_functor = [](auto w, auto f, auto t) -> auto { auto time_alpha = 1.0, weight_alpha = 0.1, freq_alpha = 0.01; return ((w > 0.0 ? w : weight_alpha) * (f > 0.0 ? f : freq_alpha) / (t > time_alpha ? t : time_alpha)); }; auto cache_order_cmp = [&](const auto &it1, const auto &it2) -> auto { auto o1 = tsort_unmask(it1.get()), o2 = tsort_unmask(it2.get()); double w1 = 0., w2 = 0.; if (o1 == o2) { /* No topological order */ if (it1->priority == it2->priority) { auto avg_freq = ((double) total_hits / used_items); auto avg_weight = (total_weight / used_items); auto f1 = (double) it1->st->total_hits / avg_freq; auto f2 = (double) it2->st->total_hits / avg_freq; auto weight1 = std::fabs(it1->st->weight) / avg_weight; auto weight2 = std::fabs(it2->st->weight) / avg_weight; auto t1 = it1->st->avg_time; auto t2 = it2->st->avg_time; w1 = score_functor(weight1, f1, t1); w2 = score_functor(weight2, f2, t2); } else { /* Strict sorting */ w1 = std::abs(it1->priority); w2 = std::abs(it2->priority); } } else { w1 = o1; w2 = o2; } if (w2 > w1) { return 1; } else if (w2 < w1) { return -1; } return 0; }; std::stable_sort(std::begin(ord->d), std::end(ord->d), cache_order_cmp); /* * Here lives some ugly legacy! * We have several filters classes, connfilters, prefilters, filters... etc * * Our order is meaningful merely for filters, but we have to add other classes * to understand if those symbols are checked or disabled. * We can disable symbols for almost everything but not for virtual symbols. * The rule of thumb is that if a symbol has explicit parent, then it is a * virtual symbol that follows it's special rules */ /* * We enrich ord with all other symbol types without any sorting, * as it is done in another place */ constexpr auto append_items_vec = [](const auto &vec, auto &out) { for (const auto &it: vec) { if (it) { out.emplace_back(it); } } }; append_items_vec(connfilters, ord->d); append_items_vec(prefilters, ord->d); append_items_vec(postfilters, ord->d); append_items_vec(idempotent, ord->d); append_items_vec(composites, ord->d); append_items_vec(classifiers, ord->d); /* After sorting is done, we can assign all elements in the by_symbol hash */ for (auto i = 0; i < ord->size(); i++) { const auto &it = ord->d[i]; ord->by_symbol[it->get_name()] = i; ord->by_cache_id[it->id] = i; } /* Finally set the current order */ std::swap(ord, items_by_order); } auto symcache::add_symbol_with_callback(std::string_view name, int priority, symbol_func_t func, void *user_data, enum rspamd_symbol_type flags_and_type) -> int { auto real_type_pair_maybe = item_type_from_c(flags_and_type); if (!real_type_pair_maybe.has_value()) { msg_err_cache("incompatible flags when adding %s: %s", name.data(), real_type_pair_maybe.error().c_str()); return -1; } auto real_type_pair = real_type_pair_maybe.value(); if (real_type_pair.first != symcache_item_type::FILTER) { real_type_pair.second |= SYMBOL_TYPE_NOSTAT; } if (real_type_pair.second & (SYMBOL_TYPE_GHOST | SYMBOL_TYPE_CALLBACK)) { real_type_pair.second |= SYMBOL_TYPE_NOSTAT; } if (real_type_pair.first == symcache_item_type::VIRTUAL) { msg_err_cache("trying to add virtual symbol %s as real (no parent)", name.data()); return -1; } if ((real_type_pair.second & SYMBOL_TYPE_FINE) && priority == 0) { /* Adjust priority for negative weighted symbols */ priority = 1; } std::string static_string_name; if (name.empty()) { static_string_name = fmt::format("AUTO_{}", (void *) func); } else { static_string_name = name; } if (items_by_symbol.contains(static_string_name)) { msg_err_cache("duplicate symbol name: %s", static_string_name.data()); return -1; } auto id = items_by_id.size(); auto item = cache_item::create_with_function(static_pool, id, std::move(static_string_name), priority, func, user_data, real_type_pair.first, real_type_pair.second); items_by_symbol[item->get_name()] = item; get_item_specific_vector(*item).push_back(item); items_by_id.push_back(item); if (!(real_type_pair.second & SYMBOL_TYPE_NOSTAT)) { cksum = t1ha(name.data(), name.size(), cksum); stats_symbols_count++; } return id; } auto symcache::add_virtual_symbol(std::string_view name, int parent_id, enum rspamd_symbol_type flags_and_type) -> int { if (name.empty()) { msg_err_cache("cannot register a virtual symbol with no name; qed"); return -1; } auto real_type_pair_maybe = item_type_from_c(flags_and_type); if (!real_type_pair_maybe.has_value()) { msg_err_cache("incompatible flags when adding %s: %s", name.data(), real_type_pair_maybe.error().c_str()); return -1; } auto real_type_pair = real_type_pair_maybe.value(); if (items_by_symbol.contains(name)) { msg_err_cache("duplicate symbol name: %s", name.data()); return -1; } auto id = items_by_id.size(); auto item = cache_item::create_with_virtual(static_pool, id, std::string{name}, parent_id, real_type_pair.first, real_type_pair.second); items_by_symbol[item->get_name()] = item; get_item_specific_vector(*item).push_back(item); items_by_id.push_back(item); return id; } auto symcache::set_peak_cb(int cbref) -> void { if (peak_cb != -1) { luaL_unref(L, LUA_REGISTRYINDEX, peak_cb); } peak_cb = cbref; msg_info_cache("registered peak callback"); } auto symcache::add_delayed_condition(std::string_view sym, int cbref) -> void { delayed_conditions->emplace_back(sym, cbref, (lua_State *) cfg->lua_state); } auto symcache::validate(bool strict) -> bool { total_weight = 1.0; for (auto &pair: items_by_symbol) { auto &item = pair.second; auto ghost = item->st->weight == 0 ? true : false; auto skipped = !ghost; if (item->is_scoreable() && g_hash_table_lookup(cfg->symbols, item->symbol.c_str()) == nullptr) { if (!std::isnan(cfg->unknown_weight)) { item->st->weight = cfg->unknown_weight; auto *s = rspamd_mempool_alloc0_type(static_pool, struct rspamd_symbol); /* Legit as we actually never modify this data */ s->name = (char *) item->symbol.c_str(); s->weight_ptr = &item->st->weight; g_hash_table_insert(cfg->symbols, (void *) s->name, (void *) s); msg_info_cache ("adding unknown symbol %s with weight: %.2f", item->symbol.c_str(), cfg->unknown_weight); ghost = false; skipped = false; } else { skipped = true; } } else { skipped = false; } if (!ghost && skipped) { if (!(item->flags & SYMBOL_TYPE_SKIPPED)) { item->flags |= SYMBOL_TYPE_SKIPPED; msg_warn_cache("symbol %s has no score registered, skip its check", item->symbol.c_str()); } } if (ghost) { msg_debug_cache ("symbol %s is registered as ghost symbol, it won't be inserted " "to any metric", item->symbol.c_str()); } if (item->st->weight < 0 && item->priority == 0) { item->priority++; } if (item->is_virtual()) { if (!(item->flags & SYMBOL_TYPE_GHOST)) { auto *parent = const_cast<cache_item *>(item->get_parent(*this)); if (parent == nullptr) { item->resolve_parent(*this); parent = const_cast<cache_item *>(item->get_parent(*this)); } if (::fabs(parent->st->weight) < ::fabs(item->st->weight)) { parent->st->weight = item->st->weight; } auto p1 = ::abs(item->priority); auto p2 = ::abs(parent->priority); if (p1 != p2) { parent->priority = MAX(p1, p2); item->priority = parent->priority; } } } total_weight += fabs(item->st->weight); } /* Now check each metric item and find corresponding symbol in a cache */ auto ret = true; GHashTableIter it; void *k, *v; g_hash_table_iter_init(&it, cfg->symbols); while (g_hash_table_iter_next(&it, &k, &v)) { auto ignore_symbol = false; auto sym_def = (struct rspamd_symbol *) v; if (sym_def && (sym_def->flags & (RSPAMD_SYMBOL_FLAG_IGNORE_METRIC | RSPAMD_SYMBOL_FLAG_DISABLED))) { ignore_symbol = true; } if (!ignore_symbol) { if (!items_by_symbol.contains((const char *) k)) { msg_warn_cache ( "symbol '%s' has its score defined but there is no " "corresponding rule registered", k); if (strict) { ret = FALSE; } } } else if (sym_def->flags & RSPAMD_SYMBOL_FLAG_DISABLED) { auto item = get_item_by_name_mut((const char *) k, false); if (item) { item->enabled = FALSE; } } } return ret; } auto symcache::counters() const -> ucl_object_t * { auto *top = ucl_object_typed_new(UCL_ARRAY); constexpr const auto round_float = [](const auto x, const int digits) -> auto { const auto power10 = ::pow(10, digits); return (::floor(x * power10) / power10); }; for (auto &pair: items_by_symbol) { auto &item = pair.second; auto symbol = pair.first; auto *obj = ucl_object_typed_new(UCL_OBJECT); ucl_object_insert_key(obj, ucl_object_fromlstring(symbol.data(), symbol.size()), "symbol", 0, false); if (item->is_virtual()) { if (!(item->flags & SYMBOL_TYPE_GHOST)) { const auto *parent = item->get_parent(*this); ucl_object_insert_key(obj, ucl_object_fromdouble(round_float(item->st->weight, 3)), "weight", 0, false); ucl_object_insert_key(obj, ucl_object_fromdouble(round_float(parent->st->avg_frequency, 3)), "frequency", 0, false); ucl_object_insert_key(obj, ucl_object_fromint(parent->st->total_hits), "hits", 0, false); ucl_object_insert_key(obj, ucl_object_fromdouble(round_float(parent->st->avg_time, 3)), "time", 0, false); } else { ucl_object_insert_key(obj, ucl_object_fromdouble(round_float(item->st->weight, 3)), "weight", 0, false); ucl_object_insert_key(obj, ucl_object_fromdouble(0.0), "frequency", 0, false); ucl_object_insert_key(obj, ucl_object_fromdouble(0.0), "hits", 0, false); ucl_object_insert_key(obj, ucl_object_fromdouble(0.0), "time", 0, false); } } else { ucl_object_insert_key(obj, ucl_object_fromdouble(round_float(item->st->weight, 3)), "weight", 0, false); ucl_object_insert_key(obj, ucl_object_fromdouble(round_float(item->st->avg_frequency, 3)), "frequency", 0, false); ucl_object_insert_key(obj, ucl_object_fromint(item->st->total_hits), "hits", 0, false); ucl_object_insert_key(obj, ucl_object_fromdouble(round_float(item->st->avg_time, 3)), "time", 0, false); } ucl_array_append(top, obj); } return top; } auto symcache::periodic_resort(struct ev_loop *ev_loop, double cur_time, double last_resort) -> void { for (const auto &item: filters) { if (item->update_counters_check_peak(L, ev_loop, cur_time, last_resort)) { auto cur_value = (item->st->total_hits - item->last_count) / (cur_time - last_resort); auto cur_err = (item->st->avg_frequency - cur_value); cur_err *= cur_err; msg_debug_cache ("peak found for %s is %.2f, avg: %.2f, " "stddev: %.2f, error: %.2f, peaks: %d", item->symbol.c_str(), cur_value, item->st->avg_frequency, item->st->stddev_frequency, cur_err, item->frequency_peaks); if (peak_cb != -1) { struct ev_loop **pbase; lua_rawgeti(L, LUA_REGISTRYINDEX, peak_cb); pbase = (struct ev_loop **) lua_newuserdata(L, sizeof(*pbase)); *pbase = ev_loop; rspamd_lua_setclass(L, "rspamd{ev_base}", -1); lua_pushlstring(L, item->symbol.c_str(), item->symbol.size()); lua_pushnumber(L, item->st->avg_frequency); lua_pushnumber(L, ::sqrt(item->st->stddev_frequency)); lua_pushnumber(L, cur_value); lua_pushnumber(L, cur_err); if (lua_pcall(L, 6, 0, 0) != 0) { msg_info_cache ("call to peak function for %s failed: %s", item->symbol.c_str(), lua_tostring(L, -1)); lua_pop (L, 1); } } } } } symcache::~symcache() { if (peak_cb != -1) { luaL_unref(L, LUA_REGISTRYINDEX, peak_cb); } } auto symcache::maybe_resort() -> bool { if (items_by_order->generation_id != cur_order_gen) { /* * Cache has been modified, need to resort it */ msg_info_cache("symbols cache has been modified since last check:" " old id: %ud, new id: %ud", items_by_order->generation_id, cur_order_gen); resort(); return true; } return false; } auto symcache::get_item_specific_vector(const cache_item &it) -> symcache::items_ptr_vec & { switch (it.get_type()) { case symcache_item_type::CONNFILTER: return connfilters; case symcache_item_type::FILTER: return filters; case symcache_item_type::IDEMPOTENT: return idempotent; case symcache_item_type::PREFILTER: return prefilters; case symcache_item_type::POSTFILTER: return postfilters; case symcache_item_type::COMPOSITE: return composites; case symcache_item_type::CLASSIFIER: return classifiers; case symcache_item_type::VIRTUAL: return virtual_symbols; } RSPAMD_UNREACHABLE; } auto symcache::process_settings_elt(struct rspamd_config_settings_elt *elt) -> void { auto id = elt->id; if (elt->symbols_disabled) { /* Process denied symbols */ ucl_object_iter_t iter = nullptr; const ucl_object_t *cur; while ((cur = ucl_object_iterate(elt->symbols_disabled, &iter, true)) != NULL) { const auto *sym = ucl_object_key(cur); auto *item = get_item_by_name_mut(sym, false); if (item != nullptr) { if (item->is_virtual()) { /* * Virtual symbols are special: * we ignore them in symcache but prevent them from being * inserted. */ item->forbidden_ids.add_id(id, static_pool); msg_debug_cache("deny virtual symbol %s for settings %ud (%s); " "parent can still be executed", sym, id, elt->name); } else { /* Normal symbol, disable it */ item->forbidden_ids.add_id(id, static_pool); msg_debug_cache ("deny symbol %s for settings %ud (%s)", sym, id, elt->name); } } else { msg_warn_cache ("cannot find a symbol to disable %s " "when processing settings %ud (%s)", sym, id, elt->name); } } } if (elt->symbols_enabled) { ucl_object_iter_t iter = nullptr; const ucl_object_t *cur; while ((cur = ucl_object_iterate (elt->symbols_enabled, &iter, true)) != nullptr) { /* Here, we resolve parent and explicitly allow it */ const auto *sym = ucl_object_key(cur); auto *item = get_item_by_name_mut(sym, false); if (item != nullptr) { if (item->is_virtual()) { if (!(item->flags & SYMBOL_TYPE_GHOST)) { auto *parent = get_item_by_name_mut(sym, true); if (parent) { if (elt->symbols_disabled && ucl_object_lookup(elt->symbols_disabled, parent->symbol.data())) { msg_err_cache ("conflict in %s: cannot enable disabled symbol %s, " "wanted to enable symbol %s", elt->name, parent->symbol.data(), sym); continue; } parent->exec_only_ids.add_id(id, static_pool); msg_debug_cache ("allow just execution of symbol %s for settings %ud (%s)", parent->symbol.data(), id, elt->name); } } /* Ignore ghosts */ } item->allowed_ids.add_id(id, static_pool); msg_debug_cache ("allow execution of symbol %s for settings %ud (%s)", sym, id, elt->name); } else { msg_warn_cache ("cannot find a symbol to enable %s " "when processing settings %ud (%s)", sym, id, elt->name); } } } } }
26.779868
118
0.661503
msuslu
ab1dc4e6454038b4ccff155e208246910064f794
574
cpp
C++
Lab4/Integrals/Integrals/PolynomialThirdDegree.cpp
ladaegorova18/CalculationMethods
7b1967cbaf0d6d6a8e744e99160f41138d40fe52
[ "Apache-2.0" ]
1
2021-09-01T20:24:35.000Z
2021-09-01T20:24:35.000Z
Lab4/Integrals/Integrals/PolynomialThirdDegree.cpp
ladaegorova18/CalculationMethods
7b1967cbaf0d6d6a8e744e99160f41138d40fe52
[ "Apache-2.0" ]
null
null
null
Lab4/Integrals/Integrals/PolynomialThirdDegree.cpp
ladaegorova18/CalculationMethods
7b1967cbaf0d6d6a8e744e99160f41138d40fe52
[ "Apache-2.0" ]
null
null
null
#include "PolynomialThirdDegree.h" #include <cmath> double PolynomialThirdDegree::func(double x) { return pow(x, 3) * (-17) + 0.3 * pow(x, 2) - x + 5; } double PolynomialThirdDegree::integral(double x) { return pow(x, 4) * (-4.25) + pow(x, 3) * 0.1 - pow(x, 2) / 2 + 5 * x; } double PolynomialThirdDegree::derivative(double x) { return -54 * pow(x, 2) + 0.6 * x - 1; } double PolynomialThirdDegree::sndDerivative(double x) { return -108 * x + 0.6; } double PolynomialThirdDegree::fourthDerivative(double x) { return 0.0; }
21.259259
75
0.609756
ladaegorova18
ab1e8e2ac93fd1c6f85770db9e0c6fde10217450
27,604
hh
C++
dune/fem/oseen/modeldefault.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
dune/fem/oseen/modeldefault.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
dune/fem/oseen/modeldefault.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
#ifndef MODELDEFAULT_HH #define MODELDEFAULT_HH #include <dune/common/fvector.hh> #include <dune/fem/function/adaptivefunction/adaptivefunction.hh> #include <dune/fem/space/dgspace.hh> #include <dune/fem/oseen/functionspacewrapper.hh> #include <dune/fem/oseen/boundaryinfo.hh> #include <dune/fem/oseen/stab_coeff.hh> #ifndef NLOG #include <dune/stuff/common/print.hh> #include <dune/stuff/common/logging.hh> #endif #include <dune/stuff/common/misc.hh> #include <algorithm> // include this file after all other includes because some of them might undef // the macros we want to use #include <dune/common/bartonnackmanifcheck.hh> #include "modelinterface.hh" namespace Dune { /** * \brief A default implementation of a discrete stokes model. * * Implements the fluxes needed for the LDG method * (see Dune::DiscreteOseenModelInterface for details).\n * The fluxes \f$\hat{u}_{\sigma}\f$, \f$\hat{\sigma}\f$, * \f$\hat{p}\f$ and \f$\hat{u}_{p}\f$ are implemented as proposed in * B. Cockburn, G. Kanschat, D. Schötzau, C. Schwab: <EM>Local * Discontinuous Galerkin Methodsfor the Stokes System</EM> (2000).\n\n * To use this model, a user has to implement the analytical force * \f$f\f$ and the dirichlet data \f$g_{D}\f$ as a Dune::Fem::Function * (only the method evaluate( arg, ret ) is needed) and specify the * types of this functions as template arguments for the traits class * DiscreteOseenModelDefaultTraits.\n * * <b>Notation:</b> Given simplices \f$T_{+}\f$ and * \f$T_{-}\f$ and a face \f$\varepsilon\f$ between them, the values * of a function \f$u\f$ on the face \f$\varepsilon\f$ are denoted by \f$u^{+}\f$, * if seen from \f$T_{+}\f$ and \f$u^{-}\f$, if seen from \f$T_{-}\f$. * The outer normals of \f$T_{+,-}\f$ in a given point on * the face \f$\varepsilon\f$ are denoted by \f$n_{+,-}\f$, * accordingly.\n * * We define the <b>mean values</b>\n * - \f$\{\{p\}\}\in R\f$ for a \f$p\in R\f$ as * \f[ * \{\{p\}\}:=\frac{1}{2}\left(p^{+}+p^{-}\right), * \f] * - \f$\{\{u\}\}\in R^{d}\f$ for a \f$u\in R^{d}\f$ as * \f[ * \{\{u\}\}:=\frac{1}{2}\left(u^{+}+u^{-}\right), * \f] * - \f$\{\{\sigma\}\}\in R^{d\times d}\f$ for a \f$\sigma\in R^{d\times d}\f$ as * \f[ * \{\{\sigma\}\}:=\frac{1}{2}\left(\sigma^{+}+\sigma^{-}\right) * \f] * * and the <b>jumps</b>\n * - \f$\left[\left[p\right]\right]\in R^{d}\f$ for a \f$p\in R\f$ as * \f[ * \left[\left[p\right]\right]:=p^{+}n^{+}+p^{-}n^{-}, * \f] * - \f$\left[\left[u\right]\right]\in R\f$ for a \f$u\in R^{d}\f$ as * \f[ * \left[\left[u\right]\right]:=u^{+}\cdot n^{+}+u^{-}\cdot n^{-}, * \f] * - \f$\underline{\left[\left[u\right]\right]}\in R^{d\times d}\f$ for a \f$u\in R^{d}\f$ as * \f[ * \underline{\left[\left[u\right]\right]}:=u^{+}\otimes n^{+}+u^{-}\otimes n^{-}, * \f] * - \f$\left[\left[\sigma\right]\right]\in R^{d}\f$ for a \f$\sigma\in R^{d\times d}\f$ as * \f[ * \left[\left[\sigma\right]\right]:=\sigma^{+}\cdot n^{+}+\sigma^{-}\cdot n^{-}. * \f] * * We also denote by \f$\mathcal{E}_{D}\f$ the set of those faces * \f$\varepsilon\f$ that lie on the boundary \f$\partial\Omega\f$ and * by \f$\mathcal{E}_{I}\f$ those which are inside \f$\Omega\f$.\n * For a detailed definition of this notation see B. Cockburn, G. Kanschat, D. Schötzau, C. Schwab: <EM>Local * Discontinuous Galerkin Methodsfor the Stokes System</EM> (2000), again.\n * * <b>Attention:</b> For reasons of simplicity the assumtion \f$n^{-}=-1\cdot n^{+}\f$ is used. * This may be not true for nonconforming grids.\n * * With this notation at hand the fluxes can de described as * - \f$\hat{u}_{\sigma}:\Omega\rightarrow R^{d}\f$ for an inner face * \f[ * \hat{u}_{\sigma}(u):=\{\{u\}\}-\underline{\left[\left[u\right]\right]}\cdot C_{12}\quad\quad\varepsilon\in\mathcal{E}_{I}, * \f] * - \f$\hat{u}_{\sigma}:\Omega\rightarrow R^{d}\f$ for a boundary face * \f[ * \hat{u}_{\sigma}(u):=g_{D}\quad\quad\varepsilon\in\mathcal{E}_{D}, * \f] * - \f$\hat{\sigma}:\Omega\rightarrow R^{d\times d}\f$ for an inner face * \f[ * \hat{\sigma}(u,\sigma):=\{\{\sigma\}\}-C_{11}\underline{\left[\left[u\right]\right]}-\left[\left[\sigma\right]\right]\otimes C_{12}\quad\quad\varepsilon\in\mathcal{E}_{I}, * \f] * - \f$\hat{\sigma}:\Omega\rightarrow R^{d\times d}\f$ for a boundary face * \f[ * \hat{\sigma}(u,\sigma):=\sigma^{+}-C_{11}\left(u^{+}-g_{D}\right)\otimes n^{+}\quad\quad\varepsilon\in\mathcal{E}_{D}, * \f] * - \f$\hat{p}:\Omega\rightarrow R\f$ for an inner face * \f[ * \hat{p}(p):=\{\{p\}\}-D_{12}\left[\left[p\right]\right]\quad\quad\varepsilon\in\mathcal{E}_{I}, * \f] * - \f$\hat{p}:\Omega\rightarrow R\f$ for a boundary face * \f[ * \hat{p}(p):=p^{+}\quad\quad\varepsilon\in\mathcal{E}_{D}, * \f] * - \f$\hat{u}_{p}:\Omega\rightarrow R^{d}\f$ for an inner face * \f[ * \hat{u}_{p}(u,p):=\{\{u\}\}+D_{11}\left[\left[p\right]\right]+D_{12}\left[\left[u\right]\right]\quad\quad\varepsilon\in\mathcal{E}_{I}, * \f] * - \f$\hat{u}_{p}:\Omega\rightarrow R^{d}\f$ for a boundary face * \f[ * \hat{u}_{p}(u,p):=g_{D}\quad\quad\varepsilon\in\mathcal{E}_{D}, * \f] * * where \f$C_{11},\;\;D_{11}\in R\f$ are the stability coefficients * and \f$C_{12},\;\;D_{12}\in R^{d}\f$ are the coefficients * concerning efficiency and accuracy.\n * * These fluxes are then decomposed into several numerical fluxes (see * Dune::DiscreteOseenModelInterface for details):\n * * \f {tabular} {l||l} * on $\mathcal{E}_{I}$ & on $\mathcal{E}_{I}$ \\ * \hline\hline * $\boldsymbol{\hat{u}_{\sigma}^{U^{+}}(u)} := \frac{1}{2} u + \left( u \otimes n^{+} \right) \cdot C_{12}$ * & $\boldsymbol{\hat{u}_{\sigma}^{U^{+}}(u)} := 0$ \\ * $\boldsymbol{\hat{u}_{\sigma}^{U^{-}}(u)} := \frac{1}{2} u + \left( u \otimes n^{-} \right) \cdot C_{12}$ * & $\boldsymbol{\hat{u}_{\sigma}^{RHS}} := g_{D}$ \\ * \hline * $\boldsymbol{\hat{u}_{p}^{U^{+}}(u)} := \frac{1}{2} u + D_{12} u \cdot n^{+}$ * & $\boldsymbol{\hat{u}_{p}^{U^{+}}(u)} := 0$ \\ * $\boldsymbol{\hat{u}_{p}^{U^{-}}(u)} := \frac{1}{2} u + D_{12} u \cdot n^{-}$ * & $\quad$ \\ * $\boldsymbol{\hat{u}_{p}^{P^{+}}(p)} := D_{11} p n^{+}$ * & $\boldsymbol{\hat{u}_{p}^{P^{+}}(p)} := 0$ \\ * $\boldsymbol{\hat{u}_{p}^{P^{-}}(p)} := D_{11} p n^{-}$ * & $\boldsymbol{\hat{u}_{p}^{RHS}} := g_{D}$\\ * \hline * $\boldsymbol{\hat{p}^{P^{+}}(p)} := \frac{1}{2} p - p D_{12} \cdot n^{+}$ * & $\boldsymbol{\hat{p}^{P^{+}}(p)} := p$ \\ * $\boldsymbol{\hat{p}^{P^{-}}(p)} := \frac{1}{2} p - p D_{12} \cdot n^{-}$ * & $\boldsymbol{\hat{p}^{RHS}} := 0$ \\ * \hline * $\boldsymbol{\hat{\sigma}^{U^{+}}(u)} := -C_{11} u \otimes n^{+}$ * & $\boldsymbol{\hat{\sigma}^{U^{+}}(u)} := -C_{11} u \otimes n^{+}$ \\ * $\boldsymbol{\hat{\sigma}^{U^{-}}(u)} := -C_{11} u \otimes n^{-}$ * & $\quad$ \\ * $\boldsymbol{\hat{\sigma}^{\sigma^{+}}(u)} := \frac{1}{2} \sigma - \left( \sigma \cdot n^{+} \right)$ * & $\boldsymbol{\hat{\sigma}^{\sigma^{+}}(u)} := \sigma$ \\ * $\boldsymbol{\hat{\sigma}^{\sigma^{-}}(u)} := \frac{1}{2} \sigma - \left( \sigma \cdot n^{-} \right)$ * & $\boldsymbol{\hat{\sigma}^{RHS}} := -C_{11} g_{D} \otimes n^{+}$ * \f} * * The implementation is as follows:\n * * - \f$\hat{u}_{\sigma}(u):\Omega\rightarrow R^{d}\f$\n * - for inner faces * - \f$\hat{u}_{\sigma}^{U^{+}}\f$ and * \f$\hat{u}_{\sigma}^{U^{-}}\f$ are implemented in * velocitySigmaFlux() (const IntersectionIteratorType& it, const * double time, const FaceDomainType& x, const Side side, const * VelocityRangeType& u, VelocityRangeType& uReturn), where * <b>side</b> determines, whether \f$\hat{u}_{\sigma}^{U^{+}}\f$ * (side=inside) or \f$\hat{u}_{\sigma}^{U^{-}}\f$ * (side=outside) is returned * - for faces on the boundary of \f$\Omega\f$ * - \f$\hat{u}_{\sigma}^{U^{+}}\f$ is implemented in * velocitySigmaBoundaryFlux() ( const IntersectionIteratorType& * it, const double time, const FaceDomainType& x, * const VelocityRangeType& <b>u</b>, VelocityRangeType& * <b>uReturn</b> ) * - \f$\hat{u}_{\sigma}^{RHS}\f$ is implemented in * velocitySigmaBoundaryFlux() ( const IntersectionIteratorType& * it, const double time, const FaceDomainType& x, * VelocityRangeType& <b>rhsReturn</b> ) * - \f$\hat{u}_{p}(u,p):\Omega\rightarrow R^{d}\f$\n * - for inner faces * - \f$\hat{u}_{p}^{U^{+}}\f$ and \f$\hat{u}_{p}^{U^{-}}\f$ are * implemented in velocityPressureFlux() ( const * IntersectionIteratorType& it, const double time, const * FaceDomainType& x, const Side side, const VelocityRangeType& * <b>u</b>, VelocityRangeType& <b>uReturn</b> ), where * <b>side</b> determines, whether \f$\hat{u}_{p}^{U^{+}}\f$ * (side=inside) or \f$\hat{u}_{p}^{U^{-}}\f$ * (side=outside) is returned * - \f$\hat{u}_{p}^{P^{+}}\f$ and \f$\hat{u}_{p}^{P^{+}}\f$ are * implemented by velocityPressureFlux() ( const * IntersectionIteratorType& it, const double time, const * FaceDomainType& x, const Side side, const PressureRangeType& * <b>p</b>, VelocityRangeType& <b>pReturn</b> ), where * <b>side</b> determines, whether \f$\hat{u}_{p}^{P^{+}}\f$ * (side=inside) or \f$\hat{u}_{p}^{P^{+}}\f$ * (side=outside) is returned * - for faces on the boundary of \f$\Omega\f$ * - \f$\hat{u}_{p}^{U^{+}}\f$ is implemented in * velocityPressureBoundaryFlux() ( const * IntersectionIteratorType& it, const double time, const * FaceDomainType& x, const VelocityRangeType& <b>u</b>, * VelocityRangeType& <b>uReturn</b> ) * - \f$\hat{u}_{p}^{P^{+}}\f$ is implemented in * velocityPressureBoundaryFlux() ( const * IntersectionIteratorType& it, const double time, const * FaceDomainType& x, const PressureRangeType& <b>p</b>, * VelocityRangeType& <b>pReturn</b> ) * - \f$\hat{u}_{p}^{RHS}\f$ is implemented in * velocityPressureBoundaryFlux() ( const * IntersectionIteratorType& it, const double time, const * FaceDomainType& x, VelocityRangeType& <b>rhsReturn</b> ) * - \f$\hat{p}(p):\Omega\rightarrow R\f$\n * - for inner faces * - \f$\hat{p}^{P^{+}}\f$ and \f$\hat{p}^{P^{-}}\f$ are * implemented in pressureFlux() ( const * IntersectionIteratorType& it, const double time, const * FaceDomainType& x, const Side side, const PressureRangeType& * p, PressureRangeType& pReturn ), where * <b>side</b> determines, whether \f$\hat{p}^{P^{+}}\f$ * (side=inside) or \f$\hat{p}^{P^{-}}\f$ * (side=outside) is returned * - for faces on the boundary of \f$\Omega\f$ * - \f$\hat{p}^{P^{+}}\f$ is implemented in pressureBoundaryFlux() ( * const IntersectionIteratorType& it, const double time, const * FaceDomainType& x, const PressureRangeType& <b>p</b>, * PressureRangeType& <b>pReturn</b> ) * - \f$\hat{p}^{RHS}\f$ is implemented in pressureBoundaryFlux() ( * const IntersectionIteratorType& it, const double time, const * FaceDomainType& x, PressureRangeType& <b>rhsReturn</b> ) * - \f$\hat{\sigma}(u,\sigma):\Omega\rightarrow R^{d\times d}\f$\n * - for inner faces * - \f$\hat{\sigma}^{U^{+}}\f$ and \f$\hat{\sigma}^{U^{-}}\f$ are * implemented in sigmaFlux() ( const IntersectionIteratorType& * it, const double time, const FaceDomainType& x, const Side * side, const VelocityRangeType& <b>u</b>, SigmaRangeType& * <b>uReturn</b> ), where * <b>side</b> determines, whether \f$\hat{\sigma}^{U^{+}}\f$ * (side=inside) or \f$\hat{\sigma}^{U^{-}}\f$ * (side=outside) is returned * - \f$\hat{\sigma}^{\sigma^{+}}\f$ and * \f$\hat{\sigma}^{\sigma^{-}}\f$ are implemented in sigmaFlux() * ( const IntersectionIteratorType& it, const double time, const * FaceDomainType& x, const Side side, const SigmaRangeType& * <b>sigma</b>, SigmaRangeType& <b>sigmaReturn</b> ), where * <b>side</b> determines, whether * \f$\hat{\sigma}^{\sigma^{+}}\f$ (side=inside) or * \f$\hat{\sigma}^{\sigma^{-}}\f$ (side=outside) is returned * - for faces on the boundary of \f$\Omega\f$ * - \f$\hat{\sigma}^{U^{+}}\f$ is implemented in * sigmaBoundaryFlux() ( const IntersectionIteratorType& it, * const double time, const FaceDomainType& x, const * VelocityRangeType& <b>u</b>, SigmaRangeType& <b>uReturn</b> ) * - \f$\hat{\sigma}^{\sigma^{+}}\f$ is implemented in * sigmaBoundaryFlux() ( const IntersectionIteratorType& it, * const double time, const FaceDomainType& x, const * SigmaRangeType& <b>sigma</b>, SigmaRangeType& * <b>sigmaReturn</b> ) * - \f$\hat{\sigma}^{RHS}\f$ is implemented in sigmaBoundaryFlux() * ( const IntersectionIteratorType& it, const double time, const * FaceDomainType& x, SigmaRangeType& <b>rhsReturn</b> ) **/ template < class DiscreteOseenModelTraitsImp > class DiscreteOseenModelDefault : public DiscreteOseenModelInterface< DiscreteOseenModelTraitsImp > { private: //! interface class typedef DiscreteOseenModelInterface< DiscreteOseenModelTraitsImp > BaseType; //! \copydoc Dune::DiscreteOseenModelInterface::IntersectionIteratorType typedef typename BaseType::IntersectionIteratorType IntersectionIteratorType; public: //! \copydoc Dune::DiscreteOseenModelInterface::VolumeQuadratureType typedef typename BaseType::VolumeQuadratureType VolumeQuadratureType; //! \copydoc Dune::DiscreteOseenModelInterface::FaceQuadratureType typedef typename BaseType::FaceQuadratureType FaceQuadratureType; //! \copydoc Dune::DiscreteOseenModelInterface::DiscreteOseenFunctionSpaceWrapperType typedef typename BaseType::DiscreteOseenFunctionSpaceWrapperType DiscreteOseenFunctionSpaceWrapperType; //! \copydoc Dune::DiscreteOseenModelInterface::DiscreteOseenFunctionSpaceWrapperType typedef typename BaseType::DiscreteOseenFunctionWrapperType DiscreteOseenFunctionWrapperType; //! \copydoc Dune::DiscreteOseenModelInterface::DiscreteSigmaFunctionType typedef typename BaseType::DiscreteSigmaFunctionType DiscreteSigmaFunctionType; //! \copydoc Dune::DiscreteOseenModelInterface::sigmaSpaceOrder static const int sigmaSpaceOrder = BaseType::sigmaSpaceOrder; //! \copydoc Dune::DiscreteOseenModelInterface::velocitySpaceOrder static const int velocitySpaceOrder = BaseType::velocitySpaceOrder; //! \copydoc Dune::DiscreteOseenModelInterface::pressureSpaceOrder static const int pressureSpaceOrder = BaseType::pressureSpaceOrder; //! type of analytical force (usually Dune::Fem::Function) typedef typename BaseType::AnalyticalForceType AnalyticalForceType; private: //! Vector type of the velocity's discrete function space's range typedef typename BaseType::VelocityRangeType VelocityRangeType; //! Matrix type of the sigma's discrete function space's range typedef typename BaseType::SigmaRangeType SigmaRangeType; //! Vector type of the pressure's discrete function space's range typedef typename BaseType::PressureRangeType PressureRangeType; //! type of analytical dirichlet data (usually Dune::Fem::Function) typedef typename BaseType::AnalyticalDirichletDataType AnalyticalDirichletDataType; public: //! \copydoc Dune::DiscreteOseenModelInterface::Side typedef enum BaseType::Side Side; /** * \brief constructor * * sets the coefficients and analytical data * \param[in] C_11 * \f$C_{11}\in R\f$ * \param[in] C_12 * \f$C_{12}\in R^{d}\f$ * \param[in] D_11 * \f$D_{11}\in R\f$ * \param[in] D_12 * \f$D_{12}\in R^{d}\f$ * \param[in] force * analytical force * \param[in] dirichletData * analytical dirichlet data * \param[in] viscosity * viscosity of the fluid **/ DiscreteOseenModelDefault( const StabilizationCoefficients stab_coeff_in, const AnalyticalForceType force_in, const AnalyticalDirichletDataType dirichletData_in, const double viscosity_in = 1.0, const double alpha_in = 0.0, const double convection_scaling_in = 1.0, const double pressure_gradient_scaling_in = 1.0 ) : viscosity_( viscosity_in ), alpha_( alpha_in ), convection_scaling_( convection_scaling_in ), pressure_gradient_scaling_( pressure_gradient_scaling_in ), stabil_coeff_( stab_coeff_in ), force_( force_in ), dirichletData_( dirichletData_in ) { // if ( !isGeneralized() ) { // if ( ( alpha_ < 0.0 ) || ( alpha_ > 0.0 ) ) { // assert( !"isGeneralized() returns false, but alpha is not zero!" ); // } // } } /** * \brief destructor * * does nothing **/ virtual ~DiscreteOseenModelDefault() {} const StabilizationCoefficients& getStabilizationCoefficients() const { return stabil_coeff_; } /** * \brief returns true * * since problem has a \f$\hat{u}_{\sigma}\f$ contribution * \return true **/ bool hasVelocitySigmaFlux() const { return true; } /** * \brief returns true * * since problem has a \f$\hat{u}_{p}\f$ contribution * \return true **/ bool hasVelocityPressureFlux() const { return true; } /** * \brief returns true * * since problem has a \f$\hat{p}\f$ contribution * \return true **/ bool hasPressureFlux() const { return true; } /** * \brief returns true * * since problem has a \f$\hat{\sigma}\f$ contribution * \return true **/ bool hasSigmaFlux() const { return true; } /** * \brief returns true * * since problem has a \f$f\f$ contribution * \return true **/ bool hasForce() const { return true; } /** * \brief Implementation of \f$f\f$. * * Evaluates the analytical force given by the constructor * * \tparam DomainType * domain type in entity (codim 0) * \param[in] time * global time * \param[in] x * point to evaluate at (in world coordinates) * \param[out] forceReturn * value of \f$f\f$ in \f$x\f$ **/ template < class DomainType > void force( const double /*time*/, const DomainType& x, VelocityRangeType& forceReturn ) const { force_.evaluate( x, forceReturn ); } template < class IntersectionType, class DomainType > void dirichletData( const IntersectionType& intIt, const double /*time*/, const DomainType& x, VelocityRangeType& dirichletDataReturn ) const { assert( ( !intIt.neighbor() && intIt.boundary() ) || !"this intersection does not lie on the boundary" ); dirichletData_.evaluate( x, dirichletDataReturn, intIt ); } /** * \brief Returns the viscosity \f$\mu\f$ of the fluid. * \return \f$\mu\f$ **/ double viscosity() const { return viscosity_; } /** * \brief constant for generalized stokes * * \todo doc **/ double alpha() const { return alpha_; } bool isGeneralized() const { return false; } //! ZAF double convection_scaling() const { return convection_scaling_; } //! ZAF double pressure_gradient_scaling() const { return pressure_gradient_scaling_; } const AnalyticalForceType& forceF() const { return force_; } private: const double viscosity_; const double alpha_; const double convection_scaling_; const double pressure_gradient_scaling_; StabilizationCoefficients stabil_coeff_; const AnalyticalForceType force_; const AnalyticalDirichletDataType dirichletData_; /** * \brief dyadic product * * Implements \f$\left(arg_{1} \otimes arg_{2}\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\f$ **/ SigmaRangeType dyadicProduct( const VelocityRangeType& arg1, const VelocityRangeType& arg2 ) const { SigmaRangeType ret( 0.0 ); typedef typename SigmaRangeType::RowIterator MatrixRowIteratorType; typedef typename VelocityRangeType::ConstIterator ConstVectorIteratorType; typedef typename VelocityRangeType::Iterator VectorIteratorType; MatrixRowIteratorType rItEnd = ret.end(); ConstVectorIteratorType arg1It = arg1.begin(); for ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) { ConstVectorIteratorType arg2It = arg2.begin(); VectorIteratorType vItEnd = rIt->end(); for ( VectorIteratorType vIt = rIt->begin(); vIt != vItEnd; ++vIt ) { *vIt = *arg1It * *arg2It; ++arg2It; } ++arg1It; } } //! avoid code duplication by doing calculations for C_1X and D_1X here template < class LocalPoint > double getStabScalar( const LocalPoint& /*x*/ , const IntersectionIteratorType& it, const std::string coeffName ) const { const StabilizationCoefficients::PowerType power = stabil_coeff_.Power ( coeffName ); const StabilizationCoefficients::FactorType factor = stabil_coeff_.Factor ( coeffName ); if ( power == StabilizationCoefficients::invalid_power ) { return 0.0; } // return std::pow( it.geometry().integrationElement( x ), param ); return factor * std::pow( getLenghtOfIntersection( *it ), power ); } }; } // end of namespace Dune /** Copyright (c) 2012, Felix Albrecht, Rene Milk * 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. **/ #endif // MODELDEFAULT_HH
45.104575
191
0.528438
renemilk
ab20485e646e88acf9173125f322bcfdf5889021
1,228
cpp
C++
src/Shaders/SunShader.cpp
jaafersheriff/Clouds
00de0a33f6e6fe43c3287de5cba9228c70693110
[ "MIT" ]
6
2019-06-30T20:20:52.000Z
2022-01-07T06:31:18.000Z
src/Shaders/SunShader.cpp
jaafersheriff/Clouds
00de0a33f6e6fe43c3287de5cba9228c70693110
[ "MIT" ]
null
null
null
src/Shaders/SunShader.cpp
jaafersheriff/Clouds
00de0a33f6e6fe43c3287de5cba9228c70693110
[ "MIT" ]
3
2020-10-08T16:37:07.000Z
2022-01-07T06:31:22.000Z
#include "SunShader.hpp" #include "Sun.hpp" #include "Camera.hpp" #include "Library.hpp" void SunShader::render() { /* Bind shader */ bind(); /* Bind sun params */ loadVector(getUniform("center"), Sun::position); loadVector(getUniform("innerColor"), Sun::innerColor); loadFloat(getUniform("innerRadius"), Sun::innerRadius); loadVector(getUniform("outerColor"), Sun::outerColor); loadFloat(getUniform("outerRadius"), Sun::outerRadius); /* Bind projeciton, view, inverse view matrices */ loadMatrix(getUniform("P"), &Camera::getP()); loadMatrix(getUniform("V"), &Camera::getV()); glm::mat4 Vi = Camera::getV(); Vi[3][0] = Vi[3][1] = Vi[3][2] = 0.f; Vi = glm::transpose(Vi); loadMatrix(getUniform("Vi"), &Vi); /* Bind mesh */ /* VAO */ CHECK_GL_CALL(glBindVertexArray(Library::quad->vaoId)); /* M */ glm::mat4 M = glm::mat4(1.f); M *= glm::translate(glm::mat4(1.f), Sun::position); M *= glm::scale(glm::mat4(1.f), glm::vec3(Sun::outerRadius)); loadMatrix(getUniform("M"), &M); /* Draw */ CHECK_GL_CALL(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)); /* Clean up */ CHECK_GL_CALL(glBindVertexArray(0)); unbind(); }
27.909091
65
0.614821
jaafersheriff
ab21554e50c831173b7ce7242a133a06b6c51146
2,438
cpp
C++
Sample/Sample_WebSocketSvr/timer/TimerMgr.cpp
sherry0319/YTSvrLib
5dda75aba927c4bf5c6a727592660bfc2619a063
[ "MIT" ]
61
2016-10-13T09:24:31.000Z
2022-03-26T09:59:34.000Z
Sample/Sample_WebSocketSvr/timer/TimerMgr.cpp
sherry0319/YTSvrLib
5dda75aba927c4bf5c6a727592660bfc2619a063
[ "MIT" ]
3
2018-05-15T10:42:22.000Z
2021-07-02T01:38:08.000Z
Sample/Sample_WebSocketSvr/timer/TimerMgr.cpp
sherry0319/YTSvrLib
5dda75aba927c4bf5c6a727592660bfc2619a063
[ "MIT" ]
36
2016-12-28T04:54:41.000Z
2021-12-15T06:02:56.000Z
#include "stdafx.h" #include "TimerMgr.h" void CTimerMgr::SetEvent() { YTSvrLib::CServerApplication::GetInstance()->SetEvent(EAppEvent::eAppTimerMgrOnTimer); } CTimerMgr::CTimerMgr(void) { m_tNow = time32(); SYSTEMTIME st; GetLocalTime(&st); m_nToday = st.wYear * 10000 + st.wMonth * 100 + st.wDay; m_wCurday = st.wDay; m_wCurHour = st.wHour; m_wCurDayOfWeek = st.wDayOfWeek; st.wHour = 0; st.wMinute = 0; st.wSecond = 0; st.wMilliseconds = 0; m_tTodayZero = SystemTimeToTime_t(&st); m_tTimeZone = GetLocalTimeZone(); m_nTomorrow = CalcTomorrowYYYYMMDD(); m_tNextHour = (m_tNow / 3600 + 1) * 3600; m_tNext5Minute = (m_tNow / 300 + 1) * 300; m_tNext10Minute = (m_tNow / 600 + 1) * 600; m_tNextLegion10Minute = m_tNow + 600; m_tNextMinute = (m_tNow / 60 + 1) * 60; m_tNext15Minute = m_tNow + 900; m_tNext30Sec = m_tNow + 30; m_tNext10Sec = m_tNow + 10; LOG("TM_Init Now=%d TodayZero=%d LocalTimeZoneSeconds=%d", m_tNow, m_tTodayZero, m_tTimeZone); } CTimerMgr::~CTimerMgr(void) { } void CTimerMgr::OnTimerCheckQueue() { m_tNow = time32(); CheckTimer((DOUBLE) m_tNow); if (m_tNow >= m_tNext10Sec) { CServerParser::GetInstance()->CheckSvrSocket(); m_tNext10Sec += 10; char szTitle[127] = { 0 }; _snprintf_s(szTitle, 127, "WSGatewaySvr=P[%d] L[%d] Online Client=%d ...", CConfig::GetInstance()->m_nPublicSvrID, CConfig::GetInstance()->m_nLocalSvrID, CPkgParser::GetInstance()->GetCurClientCount()); SetConsoleTitleA(szTitle); } if (m_tNow >= m_tNextMinute) { m_tNextMinute += 60; if (m_tNow >= m_tNext5Minute) { m_tNext5Minute += 300; } if (m_tNow >= m_tNext10Minute) { SYSTEMTIME st; GetLocalTime(&st); if (m_tNow >= m_tNextHour) { if (st.wHour != m_wCurHour) { m_wCurHour = st.wHour; if (st.wDay != m_wCurday) { m_wCurday = st.wDay; m_wCurDayOfWeek = st.wDayOfWeek; m_nToday = st.wYear * 10000 + st.wMonth * 100 + st.wDay; m_nTomorrow = CalcTomorrowYYYYMMDD(); } ReOpenLogFile(); LOG("Timer New Day=%d Hour=%d", m_wCurday, m_wCurHour); } m_tNextHour += 3600; ArrangeTimer(); }//if( tNow >= m_tNextHour ) m_tNext10Minute += 600; } //if( tNow >= m_tNext10Minute ) CPkgParser::GetInstance()->CheckIdleSocket(m_tNow); }//if( m_tNow >= m_tNextMinute ) } void CTimerMgr::OnTimer(YTSvrLib::LPSTimerInfo pTimer) { } DOUBLE CTimerMgr::GetNearTime() { return (DOUBLE) m_tNextHour; }
23.669903
204
0.669811
sherry0319
ab28d35b02607fcbbed2179e99d9c1e8ed5f9d3a
3,160
cpp
C++
code/utils/xrDXT/tga.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/utils/xrDXT/tga.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/utils/xrDXT/tga.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
5
2020-10-18T11:55:26.000Z
2022-03-28T07:21:35.000Z
// file: targasaver.cpp #include "stdafx.h" #pragma hdrstop #include "tga.h" void tga_save(LPCSTR name, u32 w, u32 h, void* data, BOOL alpha) { TGAdesc tga; tga.data = data; tga.format = alpha ? IMG_32B : IMG_24B; tga.height = h; tga.width = w; tga.scanlength = w * 4; int hf = _open(name, O_CREAT | O_WRONLY | O_BINARY, S_IREAD | S_IWRITE); tga.maketga(hf); _close(hf); } void TGAdesc::maketga(IWriter& fs) { R_ASSERT(data); R_ASSERT(width); R_ASSERT(height); tgaHeader hdr = {0}; hdr.tgaImgType = 2; hdr.tgaImgSpec.tgaXSize = u16(width); hdr.tgaImgSpec.tgaYSize = u16(height); if (format == IMG_24B) { hdr.tgaImgSpec.tgaDepth = 24; hdr.tgaImgSpec.tgaImgDesc = 32; // flip } else { hdr.tgaImgSpec.tgaDepth = 32; hdr.tgaImgSpec.tgaImgDesc = 0x0f | 32; // flip } fs.w(&hdr, sizeof(hdr)); if (format == IMG_24B) { BYTE ab_buffer[4] = { 0, 0, 0, 0 }; int real_sl = ((width * 3)) & 3; int ab_size = real_sl ? 4 - real_sl : 0; for (int j = 0; j<height; j++) { BYTE *p = (LPBYTE)data + scanlength*j; for (int i = 0; i < width; i++) { BYTE buffer[3] = { p[0], p[1], p[2] }; fs.w(buffer, 3); p += 4; } if (ab_size) { fs.w(ab_buffer, ab_size); } } } else { if (width * 4 == scanlength) { fs.w(data, width*height * 4); } else { // bad pitch, it seems :( for (int j = 0; j < height; j++) { BYTE *p = (LPBYTE)data + scanlength*j; for (int i = 0; i < width; i++) { BYTE buffer[4] = { p[0], p[1], p[2], p[3] }; fs.w(buffer, 4); p += 4; } } } } } void TGAdesc::maketga(int hf) { R_ASSERT(data); R_ASSERT(width); R_ASSERT(height); tgaHeader hdr = {0}; hdr.tgaImgType = 2; hdr.tgaImgSpec.tgaXSize = u16(width); hdr.tgaImgSpec.tgaYSize = u16(height); if (format == IMG_24B) { hdr.tgaImgSpec.tgaDepth = 24; hdr.tgaImgSpec.tgaImgDesc = 32; // flip } else { hdr.tgaImgSpec.tgaDepth = 32; hdr.tgaImgSpec.tgaImgDesc = 0x0f | 32; // flip } _write(hf, &hdr, sizeof(hdr)); if (format == IMG_24B) { BYTE ab_buffer[4] = { 0, 0, 0, 0 }; int real_sl = ((width * 3)) & 3; int ab_size = real_sl ? 4 - real_sl : 0; for (int j = 0; j < height; j++) { BYTE* p = (LPBYTE)data + scanlength*j; for (int i = 0; i < width; i++) { BYTE buffer[3] = { p[0], p[1], p[2] }; _write(hf, buffer, 3); p += 4; } if (ab_size) { _write(hf, ab_buffer, ab_size); } } } else { _write(hf, data, width*height * 4); } }
24.6875
76
0.446835
Rikoshet-234
ab2a947c4fe40048966908ab4adeff4b8919ae28
1,370
cpp
C++
Implementations/12 - Graphs Hard (4)/12.4 - Tarjan BCC.cpp
wangdongx/USACO
b920acd85e1d1e633333b14b424026a4dfe42234
[ "MIT" ]
null
null
null
Implementations/12 - Graphs Hard (4)/12.4 - Tarjan BCC.cpp
wangdongx/USACO
b920acd85e1d1e633333b14b424026a4dfe42234
[ "MIT" ]
null
null
null
Implementations/12 - Graphs Hard (4)/12.4 - Tarjan BCC.cpp
wangdongx/USACO
b920acd85e1d1e633333b14b424026a4dfe42234
[ "MIT" ]
null
null
null
/** * Description: computes biconnected components * Source: GeeksForGeeks (corrected) * Verification: USACO December 2017, Push a Box * https://pastebin.com/yUWuzTH8 */ template<int SZ> struct BCC { int N; vpi adj[SZ], ed; void addEdge(int u, int v) { adj[u].pb({v,sz(ed)}), adj[v].pb({u,sz(ed)}); ed.pb({u,v}); } int ti = 0, disc[SZ]; vi st; vector<vi> fin; int bcc(int u, int p = -1) { // return lowest disc disc[u] = ++ti; int low = disc[u]; int child = 0; trav(i,adj[u]) if (i.s != p) if (!disc[i.f]) { child ++; st.pb(i.s); int LOW = bcc(i.f,i.s); ckmin(low,LOW); // disc[u] < LOW -> bridge if (disc[u] <= LOW) { // if (p != -1 || child > 1) -> u is articulation point vi tmp; while (st.back() != i.s) tmp.pb(st.back()), st.pop_back(); tmp.pb(st.back()), st.pop_back(); fin.pb(tmp); } } else if (disc[i.f] < disc[u]) { ckmin(low,disc[i.f]); st.pb(i.s); } return low; } void init(int _N) { N = _N; FOR(i,1,N+1) disc[i] = 0; FOR(i,1,N+1) if (!disc[i]) bcc(i); // st should be empty after each iteration } };
29.148936
86
0.439416
wangdongx
ab2d34a412149658399468c2f7aae2a8c7815f5f
926
cpp
C++
3641/7910679_AC_16MS_144K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
3641/7910679_AC_16MS_144K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
3641/7910679_AC_16MS_144K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#define _CRT_SECURE_NO_WARNINGS #include<cstdio> int powMod(int base,int exp,int mod){ __int64 powRemainder[32],pos=0,remainder=1; for(int pos=0;exp;pos++){ if(pos==0) powRemainder[pos]=base%mod; else powRemainder[pos]=(powRemainder[pos-1]*powRemainder[pos-1])%mod; if(exp&1) remainder=(remainder*powRemainder[pos])%mod; exp>>=1; } return (int)remainder; } bool isPrime(int n){ int primes[25]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97}; for(int i=0;i<25 && primes[i]<n;i++){ int a=powMod(primes[i],n-1,n); if(a!=1) return false; } return true; } bool isPseudoprime(int base,int exp){ if(powMod(base,exp,exp)!=base%exp) return false; return !isPrime(exp); } int main(){ int exp,base; while(true){ scanf("%d%d",&exp,&base); if(!exp && !base) return 0; printf(isPseudoprime(base,exp)?"yes\n":"no\n"); } }
21.534884
90
0.62095
vandreas19
ab2de24b4d3597ccc2b3ed3814f695e7fa7a0315
9,051
cpp
C++
OpenGL/src/Layers/Implementation/AdvancedLayer.cpp
scooper/OpenGL
605bc9210013e27df320de8b6bdc10522d09142d
[ "Apache-2.0" ]
null
null
null
OpenGL/src/Layers/Implementation/AdvancedLayer.cpp
scooper/OpenGL
605bc9210013e27df320de8b6bdc10522d09142d
[ "Apache-2.0" ]
null
null
null
OpenGL/src/Layers/Implementation/AdvancedLayer.cpp
scooper/OpenGL
605bc9210013e27df320de8b6bdc10522d09142d
[ "Apache-2.0" ]
null
null
null
#include "AdvancedLayer.h" #include "Util/Logger.h" #include <string> #include <imgui.h> float AdvancedLayer::m_CubeVertices[] = { // positions // texture coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; float AdvancedLayer::m_QuadVertices[] = { // positions // texCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; AdvancedLayer::AdvancedLayer(GLFWwindow* window) : Layer(window, "Advanced OpenGL") { } AdvancedLayer::~AdvancedLayer() { } void AdvancedLayer::OnActivate() { m_FrameShader = new Shader("D:/Projects/OpenGL/OpenGL/res/Advanced/FramebufferShaders/framebuffer_vs.glsl", "D:/Projects/OpenGL/OpenGL/res/Advanced/FramebufferShaders/framebuffer_fs.glsl"); m_ScreenShader = new Shader("D:/Projects/OpenGL/OpenGL/res/Advanced/FramebufferShaders/screen_vs.glsl", "D:/Projects/OpenGL/OpenGL/res/Advanced/FramebufferShaders/screen_fs.glsl"); int width, height; glfwGetWindowSize(m_Window, &width, &height); m_Camera = new FlyCamera(ProjectionParameters{ width, height, CameraProjection::PERSPECTIVE }, glm::vec3(0.0f, 0.0f, 3.0f)); m_LastX = width / 2; m_LastY = height / 2; m_Container = Texture::Create(GL_TEXTURE_2D, "D:/Projects/OpenGL/OpenGL/res/LightingTutorial/container-diffuse-map.png", true); // VBO unsigned int VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(m_CubeVertices), m_CubeVertices, GL_STATIC_DRAW); // container/box glGenVertexArrays(1, &m_BoxVAO); glBindVertexArray(m_BoxVAO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // screen quad unsigned int quadVBO; glGenVertexArrays(1, &m_QuadVAO); glGenBuffers(1, &quadVBO); glBindVertexArray(m_QuadVAO); glBindBuffer(GL_ARRAY_BUFFER, quadVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(m_QuadVertices), &m_QuadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float))); // framebuffer glGenFramebuffers(1, &m_FBO); glBindFramebuffer(GL_FRAMEBUFFER, m_FBO); glGenTextures(1, &m_texColourBufferRBO); glBindTexture(GL_TEXTURE_2D, m_texColourBufferRBO); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texColourBufferRBO, 0); glGenRenderbuffers(1, &m_depthStencilRBO); glBindRenderbuffer(GL_RENDERBUFFER, m_depthStencilRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_depthStencilRBO); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) LOG_ERROR("Framebuffer is not complete"); // TODO: complete the framebuffers tutorial } void AdvancedLayer::OnDeactivate() { glDeleteVertexArrays(1, &m_BoxVAO); glDeleteFramebuffers(1, &m_FBO); delete m_ScreenShader; delete m_FrameShader; delete m_Camera; Shader::Reset(); glBindVertexArray(0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void AdvancedLayer::OnMouseEvent(double xpos, double ypos) { if (m_MouseMode) { float xoffset = xpos - m_LastX; float yoffset = m_LastY - ypos; // reversed since y-coordinates go from bottom to top m_Camera->MouseInput(xoffset, yoffset); } m_LastX = xpos; m_LastY = ypos; } void AdvancedLayer::OnWindowResize(int width, int height) { // resize framebuffer texture buffer and render buffer object (stencil and depth) glBindRenderbuffer(GL_RENDERBUFFER, m_depthStencilRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); glBindTexture(GL_TEXTURE_2D, m_texColourBufferRBO); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); // update projection matrix m_Camera->UpdateProjectionMatrix(width, height); } void AdvancedLayer::ProcessKeyEvent() { // mouse mode on or off if (glfwGetMouseButton(m_Window, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS) { m_MouseMode = true; glfwSetInputMode(m_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } if (glfwGetKey(m_Window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { m_MouseMode = false; glfwSetInputMode(m_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } if (glfwGetKey(m_Window, GLFW_KEY_W) == GLFW_PRESS) m_Camera->KeyInput(TranslateDirection::FORWARDS, m_DeltaTime); if (glfwGetKey(m_Window, GLFW_KEY_S) == GLFW_PRESS) m_Camera->KeyInput(TranslateDirection::BACKWARDS, m_DeltaTime); if (glfwGetKey(m_Window, GLFW_KEY_A) == GLFW_PRESS) m_Camera->KeyInput(TranslateDirection::LEFT, m_DeltaTime); if (glfwGetKey(m_Window, GLFW_KEY_D) == GLFW_PRESS) m_Camera->KeyInput(TranslateDirection::RIGHT, m_DeltaTime); } void AdvancedLayer::Update(float deltaTime) { m_DeltaTime = deltaTime; ProcessKeyEvent(); glBindFramebuffer(GL_FRAMEBUFFER, m_FBO); glEnable(GL_DEPTH_TEST); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_FrameShader->Use(); Texture::Activate(0); glm::mat4 model = glm::mat4(1.0f); glm::mat4 vp = m_Camera->GetViewProjectionMatrix(); glm::mat4 mvp = vp * model; m_FrameShader->SetUniform<glm::mat4&>("mvp", mvp); glBindVertexArray(m_BoxVAO); Texture::Bind(m_Container); glDrawArrays(GL_TRIANGLES, 0, 36); glBindFramebuffer(GL_FRAMEBUFFER, 0); glDisable(GL_DEPTH_TEST); // clear all relevant buffers glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); m_ScreenShader->Use(); for(int i = 0; i < 9; i++) { auto index = std::to_string(i); m_ScreenShader->SetUniform("kernel[" + index + "]", m_Kernel[i]); }; m_ScreenShader->SetUniform("greyscale", m_Greyscale); glBindVertexArray(m_QuadVAO); glBindTexture(GL_TEXTURE_2D, m_texColourBufferRBO); glDrawArrays(GL_TRIANGLES, 0, 6); } void AdvancedLayer::ImGuiDisplay() { ImGui::Text("Kernel Array"); ImGui::Columns(3, NULL); ImGui::Separator(); // kernel controls float* ptr = &m_Kernel[0]; for (int i = 0; i < m_Kernel.size(); i++) { // we want the kernel to be displayed from left to right if (i != 0) ImGui::NextColumn(); ImGui::InputFloat(("i=" + std::to_string(i)).c_str(), ptr, 0.1f, 0.5f, "%.1f"); ptr++; } ImGui::Separator(); ImGui::Columns(1); ImGui::Text("Preset Kernels"); ImGui::NewLine(); ImGui::SameLine(); // buttons to load a preset kernel that demonstrates some concept if (ImGui::Button("Edge Kernel")) m_Kernel = Kernel_Edge; ImGui::SameLine(); if (ImGui::Button("Blur Kernel")) m_Kernel = Kernel_Blur; ImGui::Separator(); ImGui::Text("Options"); ImGui::Checkbox("Greyscale", &m_Greyscale); }
31.427083
131
0.644459
scooper
ab2f502ac0c07ce17c4542ab792fb032089b2abd
8,339
cpp
C++
src/cache/node/node_manager.cpp
EmanuelHerrendorf/mapping-core
d28d85547e8ed08df37dad1da142594d3f07a366
[ "MIT" ]
null
null
null
src/cache/node/node_manager.cpp
EmanuelHerrendorf/mapping-core
d28d85547e8ed08df37dad1da142594d3f07a366
[ "MIT" ]
10
2018-03-02T13:58:32.000Z
2020-06-05T11:12:42.000Z
src/cache/node/node_manager.cpp
EmanuelHerrendorf/mapping-core
d28d85547e8ed08df37dad1da142594d3f07a366
[ "MIT" ]
3
2018-02-26T14:01:43.000Z
2019-12-09T10:03:17.000Z
/* * util.cpp * * Created on: 03.12.2015 * Author: mika */ #include "cache/node/node_manager.h" #include "cache/node/manager/local_manager.h" #include "cache/node/manager/remote_manager.h" #include "cache/node/manager/hybrid_manager.h" #include "cache/node/puzzle_util.h" #include "cache/priv/connection.h" #include "datatypes/raster.h" #include "datatypes/pointcollection.h" #include "datatypes/linecollection.h" #include "datatypes/polygoncollection.h" #include "datatypes/plot.h" #include "util/log.h" //////////////////////////////////////////////////////////// // // ActiveQueryStats // //////////////////////////////////////////////////////////// void ActiveQueryStats::add_single_local_hit() { std::lock_guard<std::mutex> g(mtx); single_local_hits++; } void ActiveQueryStats::add_multi_local_hit() { std::lock_guard<std::mutex> g(mtx); multi_local_hits++; } void ActiveQueryStats::add_multi_local_partial() { std::lock_guard<std::mutex> g(mtx); multi_local_partials++; } void ActiveQueryStats::add_single_remote_hit() { std::lock_guard<std::mutex> g(mtx); single_remote_hits++; } void ActiveQueryStats::add_multi_remote_hit() { std::lock_guard<std::mutex> g(mtx); multi_remote_hits++; } void ActiveQueryStats::add_multi_remote_partial() { std::lock_guard<std::mutex> g(mtx); multi_remote_partials++; } void ActiveQueryStats::add_miss() { std::lock_guard<std::mutex> g(mtx); misses++; } void ActiveQueryStats::add_result_bytes(uint64_t bytes) { std::lock_guard<std::mutex> g(mtx); result_bytes+=bytes; } void ActiveQueryStats::add_lost_put() { std::lock_guard<std::mutex> g(mtx); lost_puts++; } QueryStats ActiveQueryStats::get() const { std::lock_guard<std::mutex> g(mtx); return QueryStats(*this); } void ActiveQueryStats::add_query(double ratio) { std::lock_guard<std::mutex> g(mtx); QueryStats::add_query(ratio); } QueryStats ActiveQueryStats::get_and_reset() { std::lock_guard<std::mutex> g(mtx); auto res = QueryStats(*this); reset(); return res; } //////////////////////////////////////////////////////////// // // WorkerContext // //////////////////////////////////////////////////////////// WorkerContext::WorkerContext() : puzzling(0), index_connection(nullptr) { } BlockingConnection& WorkerContext::get_index_connection() const { if ( index_connection == nullptr ) throw IllegalStateException("No index-connection configured for this thread"); return *index_connection; } void WorkerContext::set_index_connection(BlockingConnection *con) { index_connection = con; } //////////////////////////////////////////////////////////// // // NodeCacheWrapper // //////////////////////////////////////////////////////////// template<typename T> NodeCacheWrapper<T>::NodeCacheWrapper( NodeCacheManager &mgr, size_t size, CacheType type ) : mgr(mgr), cache(type,size) { } template<typename T> std::shared_ptr<const NodeCacheEntry<T>> NodeCacheWrapper<T>::get(const NodeCacheKey &key) const { Log::debug("Getting item from local cache. Key: %s", key.to_string().c_str()); return cache.get(key); } template<typename T> QueryStats NodeCacheWrapper<T>::get_and_reset_query_stats() { return stats.get_and_reset(); } template<typename T> CacheType NodeCacheWrapper<T>::get_type() const { return cache.type; } template<typename T> CacheCube NodeCacheWrapper<T>::get_bounds(const T& item, const QueryRectangle& rect) const { return CacheCube(item); } template<> CacheCube NodeCacheWrapper<GenericPlot>::get_bounds(const GenericPlot& item, const QueryRectangle& rect) const { return CacheCube(rect); } template<> CacheCube NodeCacheWrapper<ProvenanceCollection>::get_bounds(const ProvenanceCollection& item, const QueryRectangle& rect) const { return CacheCube(rect); } //////////////////////////////////////////////////////////// // // NodeCacheManager // //////////////////////////////////////////////////////////// thread_local WorkerContext NodeCacheManager::context; NodeCacheManager::NodeCacheManager( const std::string &strategy, std::unique_ptr<NodeCacheWrapper<GenericRaster>> raster_wrapper, std::unique_ptr<NodeCacheWrapper<PointCollection>> point_wrapper, std::unique_ptr<NodeCacheWrapper<LineCollection>> line_wrapper, std::unique_ptr<NodeCacheWrapper<PolygonCollection>> polygon_wrapper, std::unique_ptr<NodeCacheWrapper<GenericPlot>> plot_wrapper, std::unique_ptr<NodeCacheWrapper<ProvenanceCollection>> provenance_wrapper) : raster_wrapper( std::move(raster_wrapper) ), point_wrapper( std::move(point_wrapper) ), line_wrapper( std::move(line_wrapper) ), polygon_wrapper( std::move(polygon_wrapper) ), plot_wrapper( std::move(plot_wrapper) ), provenance_wrapper( std::move(provenance_wrapper) ), strategy( CachingStrategy::by_name(strategy)), my_port(0) { } NodeCacheWrapper<GenericRaster>& NodeCacheManager::get_raster_cache() { return *raster_wrapper; } NodeCacheWrapper<PointCollection>& NodeCacheManager::get_point_cache() { return *point_wrapper; } NodeCacheWrapper<LineCollection>& NodeCacheManager::get_line_cache() { return *line_wrapper; } NodeCacheWrapper<PolygonCollection>& NodeCacheManager::get_polygon_cache() { return *polygon_wrapper; } NodeCacheWrapper<GenericPlot>& NodeCacheManager::get_plot_cache() { return *plot_wrapper; } NodeCacheWrapper<ProvenanceCollection>& NodeCacheManager::get_provenance_cache() { return *provenance_wrapper; } std::unique_ptr<NodeCacheManager> NodeCacheManager::from_config( const NodeConfig &config ) { std::string mgrlc; mgrlc.resize(config.mgr_impl.size()); std::transform(config.mgr_impl.cbegin(),config.mgr_impl.cend(),mgrlc.begin(),::tolower); if ( mgrlc == "remote" ) return std::make_unique<RemoteCacheManager>(config.caching_strategy, config.raster_size, config.point_size, config.line_size, config.polygon_size, config.plot_size, config.provenance_size); else if ( mgrlc == "local" ) return std::make_unique<LocalCacheManager>(config.caching_strategy, config.local_replacement, config.raster_size, config.point_size, config.line_size, config.polygon_size, config.plot_size, config.provenance_size); else if ( mgrlc == "hybrid" ) return std::make_unique<HybridCacheManager>(config.caching_strategy, config.raster_size, config.point_size, config.line_size, config.polygon_size, config.plot_size, config.provenance_size); else throw ArgumentException(concat("Unknown manager impl: ", config.mgr_impl)); } void NodeCacheManager::set_self_port(uint32_t port) { my_port = port; } void NodeCacheManager::set_self_host(const std::string& host) { my_host = host; } NodeHandshake NodeCacheManager::create_handshake() const { std::vector<CacheHandshake> hs { raster_wrapper->cache.get_all(), point_wrapper->cache.get_all(), line_wrapper->cache.get_all(), polygon_wrapper->cache.get_all(), plot_wrapper->cache.get_all() }; return NodeHandshake(my_port, std::move(hs) ); } NodeStats NodeCacheManager::get_stats_delta() const { QueryStats qs; qs += raster_wrapper->get_and_reset_query_stats(); qs += point_wrapper->get_and_reset_query_stats(); qs += line_wrapper->get_and_reset_query_stats(); qs += polygon_wrapper->get_and_reset_query_stats(); qs += plot_wrapper->get_and_reset_query_stats(); cumulated_stats += qs; std::vector<CacheStats> stats { raster_wrapper->cache.get_stats(), point_wrapper->cache.get_stats(), line_wrapper->cache.get_stats(), polygon_wrapper->cache.get_stats(), plot_wrapper->cache.get_stats() }; return NodeStats( qs, std::move(stats) ); } QueryStats NodeCacheManager::get_cumulated_query_stats() const { return cumulated_stats; } WorkerContext& NodeCacheManager::get_worker_context() { return NodeCacheManager::context; } const CachingStrategy& NodeCacheManager::get_strategy() const { return *strategy; } template class NodeCacheWrapper<GenericRaster>; template class NodeCacheWrapper<PointCollection>; template class NodeCacheWrapper<LineCollection>; template class NodeCacheWrapper<PolygonCollection>; template class NodeCacheWrapper<GenericPlot> ; template class NodeCacheWrapper<ProvenanceCollection> ; bool WorkerContext::is_puzzling() const { return puzzling > 0; } int WorkerContext::get_puzzle_depth() const { return puzzling; } PuzzleGuard::PuzzleGuard(WorkerContext& ctx) : ctx(ctx) { ctx.puzzling++; } PuzzleGuard::~PuzzleGuard() { ctx.puzzling--; }
27.796667
216
0.725507
EmanuelHerrendorf
ab33ae2ba1db21e870773b128a0ab5647796cae6
3,916
hpp
C++
include/Org/BouncyCastle/Crypto/Parameters/ParametersWithID.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/Org/BouncyCastle/Crypto/Parameters/ParametersWithID.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/Org/BouncyCastle/Crypto/Parameters/ParametersWithID.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Org::BouncyCastle::Crypto namespace Org::BouncyCastle::Crypto { // Forward declaring type: ICipherParameters class ICipherParameters; } // Completed forward declares // Type namespace: Org.BouncyCastle.Crypto.Parameters namespace Org::BouncyCastle::Crypto::Parameters { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: Org.BouncyCastle.Crypto.Parameters.ParametersWithID // [TokenAttribute] Offset: FFFFFFFF class ParametersWithID : public ::Il2CppObject { public: // private readonly Org.BouncyCastle.Crypto.ICipherParameters parameters // Size: 0x8 // Offset: 0x10 Org::BouncyCastle::Crypto::ICipherParameters* parameters; // Field size check static_assert(sizeof(Org::BouncyCastle::Crypto::ICipherParameters*) == 0x8); // private readonly System.Byte[] id // Size: 0x8 // Offset: 0x18 ::Array<uint8_t>* id; // Field size check static_assert(sizeof(::Array<uint8_t>*) == 0x8); // Creating value type constructor for type: ParametersWithID ParametersWithID(Org::BouncyCastle::Crypto::ICipherParameters* parameters_ = {}, ::Array<uint8_t>* id_ = {}) noexcept : parameters{parameters_}, id{id_} {} // Get instance field reference: private readonly Org.BouncyCastle.Crypto.ICipherParameters parameters Org::BouncyCastle::Crypto::ICipherParameters*& dyn_parameters(); // Get instance field reference: private readonly System.Byte[] id ::Array<uint8_t>*& dyn_id(); // public Org.BouncyCastle.Crypto.ICipherParameters get_Parameters() // Offset: 0x127A9AC Org::BouncyCastle::Crypto::ICipherParameters* get_Parameters(); // public System.Byte[] GetID() // Offset: 0x127A9A4 ::Array<uint8_t>* GetID(); }; // Org.BouncyCastle.Crypto.Parameters.ParametersWithID #pragma pack(pop) static check_size<sizeof(ParametersWithID), 24 + sizeof(::Array<uint8_t>*)> __Org_BouncyCastle_Crypto_Parameters_ParametersWithIDSizeCheck; static_assert(sizeof(ParametersWithID) == 0x20); } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(Org::BouncyCastle::Crypto::Parameters::ParametersWithID*, "Org.BouncyCastle.Crypto.Parameters", "ParametersWithID"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Parameters::ParametersWithID::get_Parameters // Il2CppName: get_Parameters template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Org::BouncyCastle::Crypto::ICipherParameters* (Org::BouncyCastle::Crypto::Parameters::ParametersWithID::*)()>(&Org::BouncyCastle::Crypto::Parameters::ParametersWithID::get_Parameters)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Parameters::ParametersWithID*), "get_Parameters", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Parameters::ParametersWithID::GetID // Il2CppName: GetID template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Array<uint8_t>* (Org::BouncyCastle::Crypto::Parameters::ParametersWithID::*)()>(&Org::BouncyCastle::Crypto::Parameters::ParametersWithID::GetID)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Parameters::ParametersWithID*), "GetID", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
54.388889
256
0.723698
Fernthedev
ab3540c6933bd0de3a05adaa2555f5a21fd6cf53
500
hpp
C++
TE2502/src/graphics/transfer_queue.hpp
ferthu/TE2502
de801f886713c0b2ef3ce6aa1e41e3fd9a58483e
[ "MIT" ]
null
null
null
TE2502/src/graphics/transfer_queue.hpp
ferthu/TE2502
de801f886713c0b2ef3ce6aa1e41e3fd9a58483e
[ "MIT" ]
null
null
null
TE2502/src/graphics/transfer_queue.hpp
ferthu/TE2502
de801f886713c0b2ef3ce6aa1e41e3fd9a58483e
[ "MIT" ]
null
null
null
#pragma once #include "queue.hpp" class VulkanContext; // Represents a hardware queue used for transfer commands class TransferQueue : public Queue { public: TransferQueue() {}; TransferQueue(VulkanContext& context, VkCommandPool command_pool, VkQueue queue); virtual ~TransferQueue(); TransferQueue(TransferQueue&& other); TransferQueue& operator=(TransferQueue&& other); private: // Move other into this void move_from(TransferQueue&& other); // Destroys object void destroy(); };
19.230769
82
0.756
ferthu
ab38c6989f1e7876b85b36d27381a598adf9c48e
3,778
cpp
C++
spearmint/spearmint.cpp
chopralab/spear
d45ffc907ab1730789413dd04afb347a26f35154
[ "BSD-3-Clause" ]
2
2019-07-28T07:57:02.000Z
2019-10-28T13:58:37.000Z
spearmint/spearmint.cpp
chopralab/spear
d45ffc907ab1730789413dd04afb347a26f35154
[ "BSD-3-Clause" ]
null
null
null
spearmint/spearmint.cpp
chopralab/spear
d45ffc907ab1730789413dd04afb347a26f35154
[ "BSD-3-Clause" ]
null
null
null
#include <memory> #include "spearmint.h" #include "chemfiles/Trajectory.hpp" #include "spear/Molecule.hpp" #include "spear/Grid.hpp" #include "spear/ScoringFunction.hpp" #include "spear/atomtypes/IDATM.hpp" #include "spear/scoringfunctions/Bernard12.hpp" std::unique_ptr<Spear::Molecule> receptor; std::unique_ptr<Spear::Molecule> ligand; std::unique_ptr<Spear::ScoringFunction> score; std::unique_ptr<Spear::Grid> gridrec; static thread_local std::string error_string = ""; const char* spear_get_error() { auto cstring = error_string.c_str(); char* copy = new char[error_string.size() + 1]; strcpy(copy, cstring); return copy; } void set_error(const std::string& error) { error_string = "[Spearmint] " + error; } uint64_t get_atom_positions(const Spear::Molecule& mol, float* pos) { try { size_t current = 0; for (auto& rpos : mol.positions()) { pos[current * 3 + 0] = static_cast<float>(rpos[0]); pos[current * 3 + 1] = static_cast<float>(rpos[1]); pos[current * 3 + 2] = static_cast<float>(rpos[2]); current++; } return 1; } catch (std::exception& e) { set_error(std::string("Error creating atom arrays: ") + e.what()); return 0; } } uint64_t get_bonds(Spear::Molecule& mol, size_t* bonds) { try { size_t i = 0; auto& bos = mol.topology().bond_orders(); for (auto& a : mol.topology().bonds()) { bonds[i * 3 + 0] = a[0]; bonds[i * 3 + 1] = a[1]; bonds[i * 3 + 2] = static_cast<size_t>(bos[i]); ++i; } return 1; } catch (std::exception& e) { set_error(std::string("Error setting bond arrays: ") + e.what()); return 0; } } uint64_t set_positions(Spear::Molecule& mol, const float* positions) { auto size = mol.size(); std::vector<Eigen::Vector3d> posvector; posvector.reserve(size / 3); for (size_t i = 0; i < size; ++i) { posvector.emplace_back( positions[i * 3 + 0], positions[i * 3 + 1], positions[i * 3 + 2] ); } mol.set_positions(std::move(posvector)); return 1; } uint64_t spear_initialize_scoring(const char* data_dir) { if (ligand == nullptr || receptor == nullptr) { set_error("You must initialize ligand and receptor first"); return 0; } try { auto atomtype_name = receptor->add_atomtype<Spear::IDATM>(Spear::AtomType::GEOMETRY); auto atomtype_name2 = ligand->add_atomtype<Spear::IDATM>(Spear::AtomType::GEOMETRY); receptor->atomtype(atomtype_name); ligand->atomtype(atomtype_name); std::ifstream csd_distrib((std::string(data_dir) + "/csd_distributions.dat").c_str()); if (!csd_distrib) { set_error("Could not open distribution file."); return 0; } Spear::AtomicDistributions atomic_distrib = Spear::read_atomic_distributions<Spear::IDATM>(csd_distrib); using Spear::Bernard12; auto options = Bernard12::Options(Bernard12::RADIAL | Bernard12::MEAN | Bernard12::COMPLETE); score = std::make_unique<Bernard12>(options, 15.0, atomic_distrib, atomtype_name); } catch (const std::exception& e) { set_error(std::string("Error in loading ligand ") + e.what()); return 0; } return 1; } float spear_calculate_score() { if (ligand == nullptr || receptor == nullptr) { set_error("You must initialize ligand and receptor first"); return 0.000; } if (score == nullptr) { set_error("You must run initialize_score first."); return 0.000; } return static_cast<float>(score->score(*gridrec, *receptor, *ligand)); }
29.515625
112
0.607729
chopralab
ab41678ebf9fc75067453305997eaecf12b40c09
2,351
cpp
C++
lib/host/wasi_crypto/signature/signature.cpp
sonder-joker/WasmEdge
3a522b4e242af1870bdd963f631fc8308b53bad7
[ "Apache-2.0" ]
null
null
null
lib/host/wasi_crypto/signature/signature.cpp
sonder-joker/WasmEdge
3a522b4e242af1870bdd963f631fc8308b53bad7
[ "Apache-2.0" ]
null
null
null
lib/host/wasi_crypto/signature/signature.cpp
sonder-joker/WasmEdge
3a522b4e242af1870bdd963f631fc8308b53bad7
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 #include "host/wasi_crypto/signature/signature.h" #include "host/wasi_crypto/signature/ecdsa.h" #include "host/wasi_crypto/signature/eddsa.h" #include "host/wasi_crypto/signature/rsa.h" namespace WasmEdge { namespace Host { namespace WASICrypto { namespace Signatures { WasiCryptoExpect<std::unique_ptr<Signature>> Signature::import(SignatureAlgorithm Alg, Span<const uint8_t> Encoded, __wasi_signature_encoding_e_t Encoding) { switch (Alg) { case SignatureAlgorithm::ECDSA_P256_SHA256: return EcdsaP256::Signature::import(Encoded, Encoding); case SignatureAlgorithm::ECDSA_K256_SHA256: return EcdsaK256::Signature::import(Encoded, Encoding); case SignatureAlgorithm::Ed25519: return EddsaSignature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PKCS1_2048_SHA256: return RsaPkcs12048SHA256::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PKCS1_2048_SHA384: return RsaPkcs12048SHA384::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PKCS1_2048_SHA512: return RsaPkcs12048SHA512::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PKCS1_3072_SHA384: return RsaPkcs13072SHA384::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PKCS1_3072_SHA512: return RsaPkcs13072SHA512::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PKCS1_4096_SHA512: return RsaPkcs14096SHA512::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PSS_2048_SHA256: return RsaPss2048SHA256::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PSS_2048_SHA384: return RsaPss2048SHA384::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PSS_2048_SHA512: return RsaPss2048SHA512::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PSS_3072_SHA384: return RsaPss3072SHA384::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PSS_3072_SHA512: return RsaPss3072SHA512::Signature::import(Encoded, Encoding); case SignatureAlgorithm::RSA_PSS_4096_SHA512: return RsaPss4096SHA512::Signature::import(Encoded, Encoding); default: assumingUnreachable(); } } } // namespace Signatures } // namespace WASICrypto } // namespace Host } // namespace WasmEdge
42.745455
70
0.792003
sonder-joker
ab41be26b1679bddb4179f28ff8e34468424d58f
7,340
hpp
C++
libraries/db/include/graphene/db/object_database.hpp
VinChain/VINchain-blockchain
c52ec3bf67c6d4700bbaf5ec903185d31a2d63ec
[ "MIT" ]
15
2018-04-13T18:40:35.000Z
2021-03-17T00:11:00.000Z
libraries/db/include/graphene/db/object_database.hpp
VinChain/VINchain-blockchain
c52ec3bf67c6d4700bbaf5ec903185d31a2d63ec
[ "MIT" ]
null
null
null
libraries/db/include/graphene/db/object_database.hpp
VinChain/VINchain-blockchain
c52ec3bf67c6d4700bbaf5ec903185d31a2d63ec
[ "MIT" ]
3
2018-05-15T18:38:53.000Z
2022-01-14T18:36:04.000Z
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/db/object.hpp> #include <graphene/db/index.hpp> #include <graphene/db/undo_database.hpp> #include <fc/log/logger.hpp> #include <map> namespace graphene { namespace db { /** * @class object_database * @brief maintains a set of indexed objects that can be modified with multi-level rollback support */ class object_database { public: object_database(); ~object_database(); void reset_indexes() { _index.clear(); _index.resize(255); } void open(const fc::path &data_dir); /** * Saves the complete state of the object_database to disk, this could take a while */ void flush(); void wipe(const fc::path &data_dir); // remove from disk void close(); template<typename T, typename F> const T &create(F &&constructor) { auto &idx = get_mutable_index<T>(); return static_cast<const T &>( idx.create([&](object &o) { assert(dynamic_cast<T *>(&o)); constructor(static_cast<T &>(o)); })); } ///These methods are used to retrieve indexes on the object_database. All public index accessors are const-access only. /// @{ template<typename IndexType> const IndexType &get_index_type() const { static_assert(std::is_base_of<index, IndexType>::value, "Type must be an index type"); return static_cast<const IndexType &>( get_index(IndexType::object_type::space_id, IndexType::object_type::type_id)); } template<typename T> const index &get_index() const { return get_index(T::space_id, T::type_id); } const index &get_index(uint8_t space_id, uint8_t type_id) const; const index &get_index(object_id_type id) const { return get_index(id.space(), id.type()); } /// @} const object &get_object(object_id_type id) const; const object *find_object(object_id_type id) const; /// These methods are mutators of the object_database. You must use these methods to make changes to the object_database, /// in order to maintain proper undo history. ///@{ const object &insert(object &&obj) { return get_mutable_index(obj.id).insert(std::move(obj)); } void remove(const object &obj) { get_mutable_index(obj.id).remove(obj); } template<typename T, typename Lambda> void modify(const T &obj, const Lambda &m) { get_mutable_index(obj.id).modify(obj, m); } ///@} template<typename T> static const T &cast(const object &obj) { assert(nullptr != dynamic_cast<const T *>(&obj)); return static_cast<const T &>(obj); } template<typename T> static T &cast(object &obj) { assert(nullptr != dynamic_cast<T *>(&obj)); return static_cast<T &>(obj); } template<typename T> const T &get(object_id_type id) const { const object &obj = get_object(id); assert(nullptr != dynamic_cast<const T *>(&obj)); return static_cast<const T &>(obj); } template<typename T> const T *find(object_id_type id) const { const object *obj = find_object(id); assert(!obj || nullptr != dynamic_cast<const T *>(obj)); return static_cast<const T *>(obj); } template<uint8_t SpaceID, uint8_t TypeID, typename T> const T *find(object_id <SpaceID, TypeID, T> id) const { return find<T>(id); } template<uint8_t SpaceID, uint8_t TypeID, typename T> const T &get(object_id <SpaceID, TypeID, T> id) const { return get<T>(id); } template<typename IndexType> IndexType *add_index() { typedef typename IndexType::object_type ObjectType; if (_index[ObjectType::space_id].size() <= ObjectType::type_id) _index[ObjectType::space_id].resize(255); assert(!_index[ObjectType::space_id][ObjectType::type_id]); unique_ptr <index> indexptr(new IndexType(*this)); _index[ObjectType::space_id][ObjectType::type_id] = std::move(indexptr); return static_cast<IndexType *>(_index[ObjectType::space_id][ObjectType::type_id].get()); } void pop_undo(); fc::path get_data_dir() const { return _data_dir; } /** public for testing purposes only... should be private in practice. */ undo_database _undo_db; protected: template<typename IndexType> IndexType &get_mutable_index_type() { static_assert(std::is_base_of<index, IndexType>::value, "Type must be an index type"); return static_cast<IndexType &>( get_mutable_index(IndexType::object_type::space_id, IndexType::object_type::type_id)); } template<typename T> index &get_mutable_index() { return get_mutable_index(T::space_id, T::type_id); } index &get_mutable_index(object_id_type id) { return get_mutable_index(id.space(), id.type()); } index &get_mutable_index(uint8_t space_id, uint8_t type_id); private: friend class base_primary_index; friend class undo_database; void save_undo(const object &obj); void save_undo_add(const object &obj); void save_undo_remove(const object &obj); fc::path _data_dir; vector <vector<unique_ptr < index>> > _index; }; } } // graphene::db
38.229167
133
0.585014
VinChain
ab4ad0701b8784476901667af4898b4831043630
2,728
hpp
C++
include/gba/util/tiles.hpp
felixjones/gba-hpp
66c84e2261c9a2d8e678e8cefb4f43f8c1c13cf3
[ "Zlib" ]
5
2022-03-12T19:16:58.000Z
2022-03-24T20:35:45.000Z
include/gba/util/tiles.hpp
felixjones/gba-hpp
66c84e2261c9a2d8e678e8cefb4f43f8c1c13cf3
[ "Zlib" ]
null
null
null
include/gba/util/tiles.hpp
felixjones/gba-hpp
66c84e2261c9a2d8e678e8cefb4f43f8c1c13cf3
[ "Zlib" ]
null
null
null
/* =============================================================================== Copyright (C) 2022 gba-hpp contributors For conditions of distribution and use, see copyright notice in LICENSE.md =============================================================================== */ #ifndef GBAXX_UTIL_TILES_HPP #define GBAXX_UTIL_TILES_HPP #include <array> #include <cstddef> #include <gba/vectype.hpp> #include <gba/util/array_traits.hpp> #include <gba/util/byte_array.hpp> namespace gba::util { namespace detail { consteval auto tile_next_row(auto x) noexcept { return (x + 7) & -8; } template <std::size_t Bits> requires IsPowerOfTwo<Bits> && (Bits <= 8) consteval auto make_tile(const ArrayOf<char> auto& palette, const ArrayOf<char> auto& bitmap) noexcept { constexpr auto palLen = util::array_size<decltype(palette)> - 1; // Exclude null byte static_assert(palLen <= (1u << Bits)); std::size_t len = 0; std::array<std::byte, 8 * 8> tile{}; for (const auto& pixel : bitmap) { if (pixel == 0) { break; } if (pixel == '\n') { len = detail::tile_next_row(len); continue; } for (std::size_t i = 0; i < palLen; ++i) { if (palette[i] == 0) { break; } if (palette[i] == pixel) { tile[len++] = std::byte(i); break; } } } if constexpr (Bits == 8) { return tile; } const auto steps = 8u / Bits; std::array<std::byte, Bits * 8> data{}; for (std::size_t i = 0; i < data.size(); ++i) { std::byte accum{}; for (std::size_t j = 0; j < steps; ++j) { accum |= tile[i * steps + j] << (j * Bits); } data[i] = accum; } return data; } } // namespace detail consteval auto make_tile_1bpp(const ArrayOf<char> auto& palette, const ArrayOf<char> auto& bitmap) noexcept { return detail::make_tile<1>(palette, bitmap); } consteval auto make_tile_2bpp(const ArrayOf<char> auto& palette, const ArrayOf<char> auto& bitmap) noexcept { return detail::make_tile<2>(palette, bitmap); } consteval auto make_tile_4bpp(const ArrayOf<char> auto& palette, const ArrayOf<char> auto& bitmap) noexcept { return detail::make_tile<4>(palette, bitmap); } consteval auto make_tile_8bpp(const ArrayOf<char> auto& palette, const ArrayOf<char> auto& bitmap) noexcept { return detail::make_tile<8>(palette, bitmap); } } // namespace gba::util #endif // define GBAXX_UTIL_TILES_HPP
28.715789
109
0.533358
felixjones
ab4eb62f71ac3f2af1500cc72b368bf6b982cb62
659
cpp
C++
samples/dnnMmodFaceLandmarkDetection/src/dnnMmodFaceLandmarkDetectionApp.cpp
kino-dome/Cinder-dlib
79601367cd6761566911ce6a0ea33b45507359b9
[ "BSD-2-Clause" ]
1
2019-03-07T09:12:32.000Z
2019-03-07T09:12:32.000Z
samples/dnnMmodFaceLandmarkDetection/src/dnnMmodFaceLandmarkDetectionApp.cpp
kino-dome/Cinder-dlib
79601367cd6761566911ce6a0ea33b45507359b9
[ "BSD-2-Clause" ]
null
null
null
samples/dnnMmodFaceLandmarkDetection/src/dnnMmodFaceLandmarkDetectionApp.cpp
kino-dome/Cinder-dlib
79601367cd6761566911ce6a0ea33b45507359b9
[ "BSD-2-Clause" ]
null
null
null
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" using namespace ci; using namespace ci::app; using namespace std; class dnnMmodFaceLandmarkDetectionApp : public App { public: void setup() override; void mouseDown( MouseEvent event ) override; void update() override; void draw() override; }; void dnnMmodFaceLandmarkDetectionApp::setup() { } void dnnMmodFaceLandmarkDetectionApp::mouseDown( MouseEvent event ) { } void dnnMmodFaceLandmarkDetectionApp::update() { } void dnnMmodFaceLandmarkDetectionApp::draw() { gl::clear( Color( 0, 0, 0 ) ); } CINDER_APP( dnnMmodFaceLandmarkDetectionApp, RendererGl )
18.828571
67
0.758725
kino-dome
ab503cf1985127b70b5978ccc29657a9d3ccb5a8
4,913
cpp
C++
SysInfo/CpuModelNumber.cpp
eyalfishler/CrystalCPUID
eb6692e2b563351ecdf7f8f247a4f71dc6456738
[ "BSD-2-Clause" ]
19
2016-02-19T02:14:16.000Z
2021-01-25T23:57:13.000Z
SysInfo/CpuModelNumber.cpp
eyalfishler/CrystalCPUID
eb6692e2b563351ecdf7f8f247a4f71dc6456738
[ "BSD-2-Clause" ]
1
2018-10-26T03:28:23.000Z
2018-10-27T03:32:03.000Z
SysInfo/CpuModelNumber.cpp
eyalfishler/CrystalCPUID
eb6692e2b563351ecdf7f8f247a4f71dc6456738
[ "BSD-2-Clause" ]
10
2015-06-01T03:39:34.000Z
2020-07-19T01:40:04.000Z
/*---------------------------------------------------------------------------*/ // Author : hiyohiyo // Mail : [email protected] // Web : http://crystalmark.info/ // License : The modified BSD license // // Copyright 2007 hiyohiyo, All rights reserved. /*---------------------------------------------------------------------------*/ #include "CpuInfo.h" /* ////////////////////////////////////////////////////////////////////// // Set Model Number for Pentium 4/D / Celeron D (P4 core) ////////////////////////////////////////////////////////////////////// void CCpuInfo::SetModelNumberP4() { } ////////////////////////////////////////////////////////////////////// // Set Model Number for Pentium M / Celeron M (P6 core) ////////////////////////////////////////////////////////////////////// void CCpuInfo::SetModelNumberP6() { } ////////////////////////////////////////////////////////////////////// // Set Model Number for Core/Core 2 ////////////////////////////////////////////////////////////////////// void CCpuInfo::SetModelNumberCore2() { if(PhysicalCoreNum == 4){ if(ClockOri == 2400.00){ wsprintf(ModelNumber, " Q6600"); }else if(ClockOri == 2666.66){ wsprintf(ModelNumber, " Q6700"); } }else if(PhysicalCoreNum == 2){ }else{ } } */ ////////////////////////////////////////////////////////////////////// // Set Model Number for K8 ////////////////////////////////////////////////////////////////////// void CCpuInfo::SetModelNumberK8() { if(ModelEx >=4){ if(SocketID == 0x0){ // Socket S1g1 switch(BrandID) { case 0x2: if(PhysicalCoreNum == 2){ wsprintf(ModelNumber, " TL-%d", 29 + BrandIDNN); }else{ wsprintf(ModelNumber, " MK-%d", 29 + BrandIDNN); } break; case 0x3: break; default: break; } }else if(SocketID == 0x1){ // Socket F switch(BrandID) { case 0x1: wsprintf(ModelNumber, " 22%d", -1 + BrandIDNN); if(PwrLmt == 0x6){ strcat(ModelNumber, " HE"); }else if(PwrLmt == 0xC){ strcat(ModelNumber, " SE"); } break; case 0x4: wsprintf(ModelNumber, " 82%d", -1 + BrandIDNN); if(PwrLmt == 0x6){ strcat(ModelNumber, " HE"); }else if(PwrLmt == 0xC){ strcat(ModelNumber, " SE"); } break; default: break; } }else{ // if(SocketID == 0x3) Socket AM2 switch(BrandID) { case 0x1: wsprintf(ModelNumber, " 12%d", -1 + BrandIDNN); if(PwrLmt == 0x6){ // undefined strcat(ModelNumber, " HE"); }else if(PwrLmt == 0xC){ strcat(ModelNumber, " SE"); } break; case 0x4: // Athlon 64, Athlon 64 X2 if(BrandIDNN < 9){ // < Athlon 64 X2 3400+ BrandIDNN += 32; // bit15 = 1 } wsprintf(ModelNumber, " %d00+", 15 + CmpCap * 10 + BrandIDNN); break; case 0x6: // Sempron wsprintf(ModelNumber, " %d00+", 15 + CmpCap * 10 + BrandIDNN); break; case 0x5: // Athlon 64 FX wsprintf(ModelNumber, "-%d", 57 + BrandIDNN); break; default: strcpy(NameSysInfo, "Engineering Sample"); break; } } return ; } switch(BrandID) { case 0: break; case 0x6: if(MultiplierOri == 14.0){ wsprintf(ModelNumber, "-62"); }else if(MultiplierOri == 13.0){ wsprintf(ModelNumber, "-60"); }else{ wsprintf(ModelNumber, ""); } break; /* Type XX */ case 0x4: case 0x5: case 0x8: case 0x9: case 0x1D: case 0x1E: case 0x20: wsprintf(ModelNumber, " %d00+", BrandIDNN + 22); break; case 0xA: case 0xB: wsprintf(ModelNumber, "-%d", BrandIDNN + 22); break; /* Type YY */ case 0xC: case 0xD: case 0xE: case 0xF: wsprintf(ModelNumber, " 1%d", 2 * BrandIDNN + 38); break; case 0x10: case 0x11: case 0x12: case 0x13: wsprintf(ModelNumber, " 2%d", 2 * BrandIDNN + 38); break; case 0x14: case 0x15: case 0x16: case 0x17: wsprintf(ModelNumber, " 8%d", 2 * BrandIDNN + 38); break; /* Type EE */ case 0x18: wsprintf(ModelNumber, " %d00+", BrandIDNN + 9); break; /* Type TT */ case 0x21: case 0x22: case 0x23: case 0x26: wsprintf(ModelNumber, " %d00+", BrandIDNN + 24); break; /* Type ZZ */ case 0x24: wsprintf(ModelNumber, "-%d", BrandIDNN + 24); break; /* Type RR */ case 0x29: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x38: wsprintf(ModelNumber, " 1%d", 5 * BrandIDNN + 45); break; case 0x2A: case 0x30: case 0x31: case 0x32: case 0x33: case 0x39: wsprintf(ModelNumber, " 2%d", 5 * BrandIDNN + 45); break; case 0x2B: case 0x34: case 0x35: case 0x36: case 0x37: case 0x3A: wsprintf(ModelNumber, " 8%d", 5 * BrandIDNN + 45); break; default: wsprintf(ModelNumber, ""); break; } }
22.536697
80
0.478526
eyalfishler
ab51f1443d5a6f07c13a4eb20e865dac61498b50
20,766
cpp
C++
qhexview.cpp
xmikula/QHexView
ac74ab5aee8c43b4b0701496b86d8a02c898edf4
[ "MIT" ]
null
null
null
qhexview.cpp
xmikula/QHexView
ac74ab5aee8c43b4b0701496b86d8a02c898edf4
[ "MIT" ]
null
null
null
qhexview.cpp
xmikula/QHexView
ac74ab5aee8c43b4b0701496b86d8a02c898edf4
[ "MIT" ]
null
null
null
#include "qhexview.h" #include "document/buffer/qmemorybuffer.h" #include <QApplication> #include <QDebug> #include <QFontDatabase> #include <QHelpEvent> #include <QPaintEvent> #include <QPainter> #include <QScrollBar> #include <QToolTip> #include <cmath> #define CURSOR_BLINK_INTERVAL 500 // ms #define DOCUMENT_WHEEL_LINES 10 QHexView::QHexView (QWidget *parent) : QAbstractScrollArea (parent), m_document (nullptr), m_renderer (nullptr), m_readonly (false) { QFont f = QFontDatabase::systemFont (QFontDatabase::FixedFont); if (f.styleHint () != QFont::TypeWriter) { f.setFamily ("Monospace"); // Force Monospaced font f.setStyleHint (QFont::TypeWriter); } this->setFont (f); this->setFocusPolicy (Qt::StrongFocus); this->setMouseTracking (true); this->verticalScrollBar ()->setSingleStep (1); this->verticalScrollBar ()->setPageStep (1); m_blinktimer = new QTimer (this); m_blinktimer->setInterval (CURSOR_BLINK_INTERVAL); connect (m_blinktimer, &QTimer::timeout, this, &QHexView::blinkCursor); this->setDocument ( QHexDocument::fromMemory<QMemoryBuffer> (QByteArray (), this)); } QHexDocument * QHexView::document () { return m_document; } void QHexView::setDocument (QHexDocument *document) { if (m_renderer) m_renderer->deleteLater (); if (m_document) m_document->deleteLater (); m_document = document; m_renderer = new QHexRenderer (m_document, this->fontMetrics (), this); connect (m_document, &QHexDocument::documentChanged, this, [&] () { this->adjustScrollBars (); this->viewport ()->update (); }); connect (m_document->cursor (), &QHexCursor::positionChanged, this, &QHexView::moveToSelection); connect (m_document->cursor (), &QHexCursor::insertionModeChanged, this, &QHexView::renderCurrentLine); this->adjustScrollBars (); this->viewport ()->update (); } void QHexView::setReadOnly (bool b) { m_readonly = b; if (m_document) m_document->cursor ()->setInsertionMode (QHexCursor::OverwriteMode); } bool QHexView::event (QEvent *e) { if (m_document && m_renderer && (e->type () == QEvent::ToolTip)) { QHelpEvent *helpevent = static_cast<QHelpEvent *> (e); QHexPosition position; QPoint abspos = absolutePosition (helpevent->pos ()); if (m_renderer->hitTest (abspos, &position, this->firstVisibleLine ())) { QString comments = m_document->metadata ()->comments ( position.line, position.column); if (!comments.isEmpty ()) QToolTip::showText (helpevent->globalPos (), comments, this); } return true; } return QAbstractScrollArea::event (e); } void QHexView::keyPressEvent (QKeyEvent *e) { if (!m_renderer || !m_document) { QAbstractScrollArea::keyPressEvent (e); return; } QHexCursor *cur = m_document->cursor (); m_blinktimer->stop (); m_renderer->enableCursor (); bool handled = this->processMove (cur, e); if (!handled) handled = this->processAction (cur, e); if (!handled) handled = this->processTextInput (cur, e); if (!handled) QAbstractScrollArea::keyPressEvent (e); m_blinktimer->start (); } QPoint QHexView::absolutePosition (const QPoint &pos) const { QPoint shift (horizontalScrollBar ()->value (), 0); QPoint abs = pos + shift; return abs; } void QHexView::mousePressEvent (QMouseEvent *e) { QAbstractScrollArea::mousePressEvent (e); if (!m_renderer || (e->buttons () != Qt::LeftButton)) return; QHexPosition position; QPoint abspos = absolutePosition (e->pos ()); if (!m_renderer->hitTest (abspos, &position, this->firstVisibleLine ())) return; m_renderer->selectArea (abspos); if (m_renderer->editableArea (m_renderer->selectedArea ())) { m_document->cursor ()->moveTo (position); } e->accept (); } void QHexView::mouseMoveEvent (QMouseEvent *e) { QAbstractScrollArea::mouseMoveEvent (e); if (!m_renderer || !m_document) return; QPoint abspos = absolutePosition (e->pos ()); if (e->buttons () == Qt::LeftButton) { if (m_blinktimer->isActive ()) { m_blinktimer->stop (); m_renderer->enableCursor (false); } QHexCursor *cursor = m_document->cursor (); QHexPosition position; if (!m_renderer->hitTest (abspos, &position, this->firstVisibleLine ())) return; cursor->select (position.line, position.column, 0); e->accept (); } if (e->buttons () != Qt::NoButton) return; int hittest = m_renderer->hitTestArea (abspos); if (m_renderer->editableArea (hittest)) this->setCursor (Qt::IBeamCursor); else this->setCursor (Qt::ArrowCursor); } void QHexView::mouseReleaseEvent (QMouseEvent *e) { QAbstractScrollArea::mouseReleaseEvent (e); if (e->button () != Qt::LeftButton) return; if (!m_blinktimer->isActive ()) m_blinktimer->start (); e->accept (); } void QHexView::focusInEvent (QFocusEvent *e) { QAbstractScrollArea::focusInEvent (e); if (!m_renderer) return; m_renderer->enableCursor (); m_blinktimer->start (); } void QHexView::focusOutEvent (QFocusEvent *e) { QAbstractScrollArea::focusOutEvent (e); if (!m_renderer) return; m_blinktimer->stop (); m_renderer->enableCursor (false); } void QHexView::wheelEvent (QWheelEvent *e) { if (e->angleDelta ().y () == 0) { int value = this->verticalScrollBar ()->value (); qDebug () << "Current value: " << value; if (e->angleDelta ().x () < 0) // Scroll Down this->verticalScrollBar ()->setValue (value + DOCUMENT_WHEEL_LINES); else if (e->angleDelta ().x () > 0) // Scroll Up this->verticalScrollBar ()->setValue (value - DOCUMENT_WHEEL_LINES); return; } QAbstractScrollArea::wheelEvent (e); } void QHexView::resizeEvent (QResizeEvent *e) { QAbstractScrollArea::resizeEvent (e); this->adjustScrollBars (); } void QHexView::paintEvent (QPaintEvent *e) { if (!m_document) return; QPainter painter (this->viewport ()); painter.setFont (this->font ()); const QRect &r = e->rect (); const quint64 firstVisible = this->firstVisibleLine (); const int lineHeight = m_renderer->lineHeight (); const int headerCount = m_renderer->headerLineCount (); // these are lines from the point of view of the visible rect // where the first "headerCount" are taken by the header const int first = (r.top () / lineHeight); // included const int lastPlusOne = (r.bottom () / lineHeight) + 1; // excluded // compute document lines, adding firstVisible and removing the header // the max is necessary if the rect covers the header const quint64 begin = firstVisible + std::max (first - headerCount, 0); const quint64 end = firstVisible + std::max (lastPlusOne - headerCount, 0); painter.save (); painter.translate (-this->horizontalScrollBar ()->value (), 0); m_renderer->render (&painter, begin, end, firstVisible); m_renderer->renderFrame (&painter); painter.restore (); } void QHexView::moveToSelection () { QHexCursor *cur = m_document->cursor (); if (!this->isLineVisible (cur->currentLine ())) { QScrollBar *vscrollbar = this->verticalScrollBar (); int scrollPos = static_cast<int> ( std::max (quint64 (0), (cur->currentLine () - this->visibleLines () / 2)) / documentSizeFactor ()); vscrollbar->setValue (scrollPos); } else this->viewport ()->update (); } void QHexView::blinkCursor () { if (!m_renderer) return; m_renderer->blinkCursor (); this->renderCurrentLine (); } void QHexView::moveNext (bool select) { QHexCursor *cur = m_document->cursor (); quint64 line = cur->currentLine (); int column = cur->currentColumn (); bool lastcell = (line >= m_renderer->documentLastLine ()) && (column >= m_renderer->documentLastColumn ()); if ((m_renderer->selectedArea () == QHexRenderer::AsciiArea) && lastcell) return; int nibbleindex = cur->currentNibble (); if (m_renderer->selectedArea () == QHexRenderer::HexArea) { if (lastcell && !nibbleindex) return; if (cur->position ().offset () >= m_document->length () && nibbleindex) return; } if ((m_renderer->selectedArea () == QHexRenderer::HexArea)) { nibbleindex++; nibbleindex %= 2; if (nibbleindex) column++; } else { nibbleindex = 1; column++; } if (column > m_renderer->hexLineWidth () - 1) { line = std::min (m_renderer->documentLastLine (), line + 1); column = 0; nibbleindex = 1; } if (select) cur->select (line, std::min (m_renderer->hexLineWidth () - 1, column), nibbleindex); else cur->moveTo (line, std::min (m_renderer->hexLineWidth () - 1, column), nibbleindex); } void QHexView::movePrevious (bool select) { QHexCursor *cur = m_document->cursor (); quint64 line = cur->currentLine (); int column = cur->currentColumn (); bool firstcell = !line && !column; if ((m_renderer->selectedArea () == QHexRenderer::AsciiArea) && firstcell) return; int nibbleindex = cur->currentNibble (); if ((m_renderer->selectedArea () == QHexRenderer::HexArea) && firstcell && nibbleindex) return; if ((m_renderer->selectedArea () == QHexRenderer::HexArea)) { nibbleindex--; nibbleindex %= 2; if (!nibbleindex) column--; } else { nibbleindex = 1; column--; } if (column < 0) { line = std::max (quint64 (0), line - 1); column = m_renderer->hexLineWidth () - 1; nibbleindex = 0; } if (select) cur->select (line, std::max (0, column), nibbleindex); else cur->moveTo (line, std::max (0, column), nibbleindex); } void QHexView::renderCurrentLine () { if (!m_document) return; this->renderLine (m_document->cursor ()->currentLine ()); } bool QHexView::processAction (QHexCursor *cur, QKeyEvent *e) { if (m_readonly) return false; if (e->modifiers () != Qt::NoModifier) { if (e->matches (QKeySequence::SelectAll)) { m_document->cursor ()->moveTo (0, 0); m_document->cursor ()->select (m_renderer->documentLastLine (), m_renderer->documentLastColumn () - 1); } else if (e->matches (QKeySequence::Undo)) m_document->undo (); else if (e->matches (QKeySequence::Redo)) m_document->redo (); else if (e->matches (QKeySequence::Cut)) m_document->cut ( (m_renderer->selectedArea () == QHexRenderer::HexArea)); else if (e->matches (QKeySequence::Copy)) m_document->copy ( (m_renderer->selectedArea () == QHexRenderer::HexArea)); else if (e->matches (QKeySequence::Paste)) m_document->paste ( (m_renderer->selectedArea () == QHexRenderer::HexArea)); else return false; return true; } if ((e->key () == Qt::Key_Backspace) || (e->key () == Qt::Key_Delete)) { if (!cur->hasSelection ()) { const QHexPosition &pos = cur->position (); if (pos.offset () <= 0) return true; if (e->key () == Qt::Key_Backspace) m_document->remove (cur->position ().offset () - 1, 1); else m_document->remove (cur->position ().offset (), 1); } else { QHexPosition oldpos = cur->selectionStart (); m_document->removeSelection (); cur->moveTo (oldpos.line, oldpos.column + 1); } if (e->key () == Qt::Key_Backspace) { if (m_renderer->selectedArea () == QHexRenderer::HexArea) this->movePrevious (); this->movePrevious (); } } else if (e->key () == Qt::Key_Insert) cur->switchInsertionMode (); else return false; return true; } bool QHexView::processMove (QHexCursor *cur, QKeyEvent *e) { if (e->matches (QKeySequence::MoveToNextChar) || e->matches (QKeySequence::SelectNextChar)) this->moveNext (e->matches (QKeySequence::SelectNextChar)); else if (e->matches (QKeySequence::MoveToPreviousChar) || e->matches (QKeySequence::SelectPreviousChar)) this->movePrevious (e->matches (QKeySequence::SelectPreviousChar)); else if (e->matches (QKeySequence::MoveToNextLine) || e->matches (QKeySequence::SelectNextLine)) { if (m_renderer->documentLastLine () == cur->currentLine ()) return true; int nextline = cur->currentLine () + 1; if (e->matches (QKeySequence::MoveToNextLine)) cur->moveTo (nextline, cur->currentColumn ()); else cur->select (nextline, cur->currentColumn ()); } else if (e->matches (QKeySequence::MoveToPreviousLine) || e->matches (QKeySequence::SelectPreviousLine)) { if (!cur->currentLine ()) return true; quint64 prevline = cur->currentLine () - 1; if (e->matches (QKeySequence::MoveToPreviousLine)) cur->moveTo (prevline, cur->currentColumn ()); else cur->select (prevline, cur->currentColumn ()); } else if (e->matches (QKeySequence::MoveToNextPage) || e->matches (QKeySequence::SelectNextPage)) { if (m_renderer->documentLastLine () == cur->currentLine ()) return true; int pageline = std::min (m_renderer->documentLastLine (), cur->currentLine () + this->visibleLines ()); if (e->matches (QKeySequence::MoveToNextPage)) cur->moveTo (pageline, cur->currentColumn ()); else cur->select (pageline, cur->currentColumn ()); } else if (e->matches (QKeySequence::MoveToPreviousPage) || e->matches (QKeySequence::SelectPreviousPage)) { if (!cur->currentLine ()) return true; quint64 pageline = std::max (quint64 (0), cur->currentLine () - this->visibleLines ()); if (e->matches (QKeySequence::MoveToPreviousPage)) cur->moveTo (pageline, cur->currentColumn ()); else cur->select (pageline, cur->currentColumn ()); } else if (e->matches (QKeySequence::MoveToStartOfDocument) || e->matches (QKeySequence::SelectStartOfDocument)) { if (!cur->currentLine ()) return true; if (e->matches (QKeySequence::MoveToStartOfDocument)) cur->moveTo (0, 0); else cur->select (0, 0); } else if (e->matches (QKeySequence::MoveToEndOfDocument) || e->matches (QKeySequence::SelectEndOfDocument)) { if (m_renderer->documentLastLine () == cur->currentLine ()) return true; if (e->matches (QKeySequence::MoveToEndOfDocument)) cur->moveTo (m_renderer->documentLastLine (), m_renderer->documentLastColumn ()); else cur->select (m_renderer->documentLastLine (), m_renderer->documentLastColumn ()); } else if (e->matches (QKeySequence::MoveToStartOfLine) || e->matches (QKeySequence::SelectStartOfLine)) { if (e->matches (QKeySequence::MoveToStartOfLine)) cur->moveTo (cur->currentLine (), 0); else cur->select (cur->currentLine (), 0); } else if (e->matches (QKeySequence::MoveToEndOfLine) || e->matches (QKeySequence::SelectEndOfLine)) { if (e->matches (QKeySequence::MoveToEndOfLine)) { if (cur->currentLine () == m_renderer->documentLastLine ()) cur->moveTo (cur->currentLine (), m_renderer->documentLastColumn ()); else cur->moveTo (cur->currentLine (), m_renderer->hexLineWidth () - 1, 0); } else { if (cur->currentLine () == m_renderer->documentLastLine ()) cur->select (cur->currentLine (), m_renderer->documentLastColumn ()); else cur->select (cur->currentLine (), m_renderer->hexLineWidth () - 1, 0); } } else return false; return true; } bool QHexView::processTextInput (QHexCursor *cur, QKeyEvent *e) { if (m_readonly || (e->modifiers () & Qt::ControlModifier)) return false; uchar key = static_cast<uchar> (e->text ()[0].toLatin1 ()); if ((m_renderer->selectedArea () == QHexRenderer::HexArea)) { if (!((key >= '0' && key <= '9') || (key >= 'a' && key <= 'f'))) // Check if is a Hex Char return false; uchar val = static_cast<uchar> ( QString (static_cast<char> (key)).toUInt (nullptr, 16)); m_document->removeSelection (); if (m_document->atEnd () || (cur->currentNibble () && (cur->insertionMode () == QHexCursor::InsertMode))) { m_document->insert (cur->position ().offset (), val << 4); // X0 byte this->moveNext (); return true; } uchar ch = static_cast<uchar> (m_document->at (cur->position ().offset ())); if (cur->currentNibble ()) // X0 val = (ch & 0x0F) | (val << 4); else // 0X val = (ch & 0xF0) | val; m_document->replace (cur->position ().offset (), val); this->moveNext (); return true; } if ((m_renderer->selectedArea () == QHexRenderer::AsciiArea)) { if (!(key >= 0x20 && key <= 0x7E)) // Check if is a Printable Char return false; m_document->removeSelection (); if (!m_document->atEnd () && (cur->insertionMode () == QHexCursor::OverwriteMode)) m_document->replace (cur->position ().offset (), key); else m_document->insert (cur->position ().offset (), key); QKeyEvent keyevent (QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier); qApp->sendEvent (this, &keyevent); return true; } return false; } void QHexView::adjustScrollBars () { QScrollBar *vscrollbar = this->verticalScrollBar (); int sizeFactor = this->documentSizeFactor (); vscrollbar->setSingleStep (sizeFactor); quint64 docLines = m_renderer->documentLines (); quint64 visLines = this->visibleLines (); if (docLines > visLines) { this->setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOn); vscrollbar->setMaximum ( static_cast<int> ((docLines - visLines) / sizeFactor + 1)); } else { this->setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff); vscrollbar->setValue (0); vscrollbar->setMaximum (static_cast<int> (docLines)); } QScrollBar *hscrollbar = this->horizontalScrollBar (); int documentWidth = m_renderer->documentWidth (); int viewportWidth = viewport ()->width (); if (documentWidth > viewportWidth) { this->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOn); // +1 to see the rightmost vertical line, +2 seems more pleasant to the // eyes hscrollbar->setMaximum (documentWidth - viewportWidth + 2); } else { this->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff); hscrollbar->setValue (0); hscrollbar->setMaximum (documentWidth); } } void QHexView::renderLine (quint64 line) { if (!this->isLineVisible (line)) return; this->viewport ()->update ( /*m_renderer->getLineRect(line, this->firstVisibleLine())*/); } quint64 QHexView::firstVisibleLine () const { quint64 value = quint64 (this->verticalScrollBar ()->value ()) * documentSizeFactor (); return value; } quint64 QHexView::lastVisibleLine () const { return this->firstVisibleLine () + this->visibleLines () - 1; } quint64 QHexView::visibleLines () const { int visLines = std::ceil (this->height () / m_renderer->lineHeight ()) - m_renderer->headerLineCount (); return std::min (quint64 (visLines), m_renderer->documentLines ()); } bool QHexView::isLineVisible (quint64 line) const { if (!m_document) return false; if (line < this->firstVisibleLine ()) return false; if (line > this->lastVisibleLine ()) return false; return true; } int QHexView::documentSizeFactor () const { int factor = 1; if (m_document) { quint64 docLines = m_renderer->documentLines (); if (docLines >= INT_MAX) { factor = static_cast<int> (docLines / INT_MAX) + 1; } } return factor; } void QHexView::offset_jump (quint64 value) { this->verticalScrollBar ()->setValue ( static_cast<int> (value / 16 / documentSizeFactor ())); }
26.022556
79
0.608446
xmikula
ab52169cfe7b90242ba9110652f1da45dfb2c856
9,397
cpp
C++
core/lib/soci_sqlite3/session.cpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
92
2016-11-13T01:28:34.000Z
2022-03-25T01:11:37.000Z
core/lib/soci_sqlite3/session.cpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
242
2016-11-28T11:13:09.000Z
2022-03-04T13:02:53.000Z
core/lib/soci_sqlite3/session.cpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
91
2017-06-20T10:35:28.000Z
2022-03-09T14:15:40.000Z
// // Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney // 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) // #include "soci-sqlite3.h" #include <connection-parameters.h> #include <sstream> #include <string> #include <cstdio> #include <cstring> #ifdef _MSC_VER #pragma warning(disable:4355) #endif using namespace soci; using namespace soci::details; using namespace sqlite_api; namespace // anonymous { // helper function for hardcoded queries void execute_hardcoded(sqlite_api::sqlite3* conn, char const* const query, char const* const errMsg) { char *zErrMsg = 0; int const res = sqlite3_exec(conn, query, 0, 0, &zErrMsg); if (res != SQLITE_OK) { std::ostringstream ss; ss << errMsg << " " << zErrMsg; sqlite3_free(zErrMsg); throw sqlite3_soci_error(ss.str(), res); } } void check_sqlite_err(sqlite_api::sqlite3* conn, int res, char const* const errMsg) { if (SQLITE_OK != res) { const char *zErrMsg = sqlite3_errmsg(conn); std::ostringstream ss; ss << errMsg << zErrMsg; throw sqlite3_soci_error(ss.str(), res); } } void post_connection_helper(sqlite_api::sqlite3* conn, const std::string &dbname, int connection_flags, int timeout, const std::string &synchronous) { int res = sqlite3_open_v2(dbname.c_str(), &conn, connection_flags, NULL); check_sqlite_err(conn, res, "Cannot establish connection to the database. "); if (!synchronous.empty()) { std::string const query("pragma synchronous=" + synchronous); std::string const errMsg("Query failed: " + query); execute_hardcoded(conn, query.c_str(), errMsg.c_str()); } res = sqlite3_busy_timeout(conn, timeout * 1000); check_sqlite_err(conn, res, "Failed to set busy timeout for connection. "); } void sqlcipher_export(sqlite_api::sqlite3* conn, int flags, int timeout, const std::string &synchronous, const std::string &exportQuery, const std::string &dbName, const std::string &newDbName, const std::string &msgError, const std::string &newPassKey) { execute_hardcoded(conn, exportQuery.c_str(), msgError.c_str()); auto r = sqlite3_close_v2(conn); if (r == SQLITE_OK) { // correctly closed, rename the file if (std::remove(dbName.c_str()) == 0) { if (std::rename(newDbName.c_str(), dbName.c_str()) == 0) { r = sqlite3_open_v2(dbName.c_str(), &conn, flags, NULL); check_sqlite_err(conn, r, "Cannot establish connection to the database. "); post_connection_helper(conn, dbName, flags, timeout, synchronous); if (!newPassKey.empty()) { r = sqlite3_key_v2(conn, dbName.c_str(), newPassKey.c_str(), strlen(newPassKey.c_str())); check_sqlite_err(conn, r, "Cannot establish connection to the database with newly set password. "); } } else { // old DB removed but cannot rename the new one: bad throw sqlite3_soci_error("Cannot rename new SQLCipher database", r); } } else { // cannot remove the old database throw sqlite3_soci_error("Cannot remove old SQLCipher database", r); } } else { // likely a still busy database throw sqlite3_soci_error("Cannot close SQLCipher database", r); } } } // namespace anonymous sqlite3_session_backend::sqlite3_session_backend( connection_parameters const & parameters) { int timeout = 0; int connection_flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; std::string synchronous, passKey, newPassKey; bool disableEncryption = false; std::string const & connectString = parameters.get_connect_string(); std::string dbname(connectString); std::stringstream ssconn(connectString); while (!ssconn.eof() && ssconn.str().find('=') != std::string::npos) { std::string key, val; std::getline(ssconn, key, '='); std::getline(ssconn, val, ' '); if (val.size()>0 && val[0]=='\"') { std::string quotedVal = val.erase(0, 1); if (quotedVal[quotedVal.size()-1] == '\"') { quotedVal.erase(val.size()-1); } else // space inside value string { std::getline(ssconn, val, '\"'); quotedVal = quotedVal + " " + val; std::string keepspace; std::getline(ssconn, keepspace, ' '); } val = quotedVal; } if ("dbname" == key || "db" == key) { dbname = val; } else if ("timeout" == key) { std::istringstream converter(val); converter >> timeout; } else if ("synchronous" == key) { synchronous = val; } else if ("shared_cache" == key && "true" == val) { connection_flags |= SQLITE_OPEN_SHAREDCACHE; } else if ("key" == key) { passKey = val; } else if ("new_key" == key) { newPassKey = val; } else if ("disable_encryption" == key && val == "true") { disableEncryption = true; } } int res = sqlite3_open_v2(dbname.c_str(), &conn_, connection_flags, NULL); check_sqlite_err(conn_, res, "Cannot establish connection to the database. "); post_connection(dbname, connection_flags, timeout, synchronous); //Set password if (!passKey.empty() || !newPassKey.empty()) { if (!passKey.empty()){ res = sqlite3_key_v2(conn_, dbname.c_str(), passKey.c_str(), strlen(passKey.c_str())); check_sqlite_err(conn_, res, "Failed to encrypt database. "); } if (!passKey.empty() && !newPassKey.empty()) { //Set new password res = sqlite3_rekey_v2(conn_, dbname.c_str(), newPassKey.c_str(), strlen(newPassKey.c_str())); check_sqlite_err(conn_, res, "Failed to change database's password. "); } else if (!newPassKey.empty()) { std::string const dbNameEncrypted = dbname + ".encrypt"; std::string const query( "ATTACH DATABASE '" + dbNameEncrypted + "' AS encrypted KEY '" + newPassKey +"';" "SELECT sqlcipher_export('encrypted');" "DETACH DATABASE encrypted;" ); std::string const errMsg("Unable to enable encryption"); sqlcipher_export(conn_, connection_flags, timeout, synchronous, query, dbname, dbNameEncrypted, errMsg, newPassKey); } else if (disableEncryption) { // FIXME: security concerns: maybe we want to sanitize? :D // convert back to plain text; this method copies the current database in plaintext // mode; once it’s done, we must close the connection, rename the database and re-open // connection std::string const dbnamePlain = dbname + ".plain"; std::string const query( "PRAGMA key = '" + passKey + "';" "ATTACH DATABASE '" + dbnamePlain + "' AS plaintext KEY '';" // empty key = plaintext "SELECT sqlcipher_export('plaintext');" "DETACH DATABASE plaintext;" ); std::string const errMsg("Unable to disabling encryption"); sqlcipher_export(conn_, connection_flags, timeout, synchronous, query, dbname, dbnamePlain, errMsg, newPassKey); } } } sqlite3_session_backend::~sqlite3_session_backend() { clean_up(); } void sqlite3_session_backend::begin() { execute_hardcoded(conn_, "BEGIN", "Cannot begin transaction."); } void sqlite3_session_backend::commit() { execute_hardcoded(conn_, "COMMIT", "Cannot commit transaction."); } void sqlite3_session_backend::rollback() { execute_hardcoded(conn_, "ROLLBACK", "Cannot rollback transaction."); } void sqlite3_session_backend::post_connection(std::string const& dbname, int connection_flags, int timeout, std::string const& synchronous) { post_connection_helper(conn_, dbname, connection_flags, timeout, synchronous); } void sqlite3_session_backend::clean_up() { sqlite3_close(conn_); } sqlite3_statement_backend * sqlite3_session_backend::make_statement_backend() { return new sqlite3_statement_backend(*this); } sqlite3_rowid_backend * sqlite3_session_backend::make_rowid_backend() { return new sqlite3_rowid_backend(*this); } sqlite3_blob_backend * sqlite3_session_backend::make_blob_backend() { return new sqlite3_blob_backend(*this); } bool sqlite3_session_backend::isAlive() const { return true; }
34.547794
152
0.582952
RomanWlm
ab5d5c911c98f1a043baf0cd01c29bd9cd2a0db7
185
cpp
C++
Sources/functions.cpp
Gabriel-Barbosa-Pereira/vilut
626ba392297552a15ced328a1f0fd4912b374faf
[ "MIT" ]
null
null
null
Sources/functions.cpp
Gabriel-Barbosa-Pereira/vilut
626ba392297552a15ced328a1f0fd4912b374faf
[ "MIT" ]
null
null
null
Sources/functions.cpp
Gabriel-Barbosa-Pereira/vilut
626ba392297552a15ced328a1f0fd4912b374faf
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cmath> void net(){ system("ping www.google.com"); } double pit(double b, double c){ double a; a = sqrt(pow(b, 2) + pow(c, 2)); return a; }
15.416667
36
0.578378
Gabriel-Barbosa-Pereira
ab5dae9226c70ba540d9ab235c33a55b1e031d63
2,830
hpp
C++
modules/scene_manager/include/lifecycle_msgs/srv/get_available_states__response__rosidl_typesupport_opensplice_cpp.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
modules/scene_manager/include/lifecycle_msgs/srv/get_available_states__response__rosidl_typesupport_opensplice_cpp.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
3
2019-11-14T12:20:06.000Z
2020-08-07T13:51:10.000Z
modules/scene_manager/include/lifecycle_msgs/srv/get_available_states__response__rosidl_typesupport_opensplice_cpp.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
// generated from // rosidl_typesupport_opensplice_cpp/resource/msg__rosidl_typesupport_opensplice_cpp.hpp.em // generated code does not contain a copyright notice #ifndef LIFECYCLE_MSGS__SRV__GET_AVAILABLE_STATES__RESPONSE__ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_HPP_ #define LIFECYCLE_MSGS__SRV__GET_AVAILABLE_STATES__RESPONSE__ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_HPP_ #include "lifecycle_msgs/srv/get_available_states__response__struct.hpp" #include "lifecycle_msgs/srv/dds_opensplice/ccpp_GetAvailableStates_Response_.h" #include "rosidl_generator_c/message_type_support_struct.h" #include "rosidl_typesupport_interface/macros.h" #include "lifecycle_msgs/msg/rosidl_typesupport_opensplice_cpp__visibility_control.h" namespace DDS { class DomainParticipant; class DataReader; class DataWriter; } // namespace DDS namespace lifecycle_msgs { namespace srv { namespace typesupport_opensplice_cpp { ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_lifecycle_msgs extern void register_type__GetAvailableStates_Response( DDS::DomainParticipant * participant, const char * type_name); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_lifecycle_msgs extern void convert_ros_message_to_dds( const lifecycle_msgs::srv::GetAvailableStates_Response & ros_message, lifecycle_msgs::srv::dds_::GetAvailableStates_Response_ & dds_message); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_lifecycle_msgs extern void publish__GetAvailableStates_Response( DDS::DataWriter * topic_writer, const void * untyped_ros_message); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_lifecycle_msgs extern void convert_dds_message_to_ros( const lifecycle_msgs::srv::dds_::GetAvailableStates_Response_ & dds_message, lifecycle_msgs::srv::GetAvailableStates_Response & ros_message); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_lifecycle_msgs extern bool take__GetAvailableStates_Response( DDS::DataReader * topic_reader, bool ignore_local_publications, void * untyped_ros_message, bool * taken); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_EXPORT_lifecycle_msgs const char * serialize__GetAvailableStates_Response( const void * untyped_ros_message, void * serialized_data); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_EXPORT_lifecycle_msgs const char * deserialize__GetAvailableStates_Response( const uint8_t * buffer, unsigned length, void * untyped_ros_message); } // namespace typesupport_opensplice_cpp } // namespace srv } // namespace lifecycle_msgs #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_lifecycle_msgs const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_opensplice_cpp, lifecycle_msgs, srv, GetAvailableStates_Response)(); #ifdef __cplusplus } #endif #endif // LIFECYCLE_MSGS__SRV__GET_AVAILABLE_STATES__RESPONSE__ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_HPP_
30.430108
139
0.863604
Omnirobotic
ab5f1c641901a8ba056bddb959ce47d644460973
13,525
cpp
C++
src/Plugins/MoviePlugin/Movie2Data.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Plugins/MoviePlugin/Movie2Data.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Plugins/MoviePlugin/Movie2Data.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "Movie2Data.h" #include "Interface/ResourceServiceInterface.h" #include "Interface/MaterialEnumInterface.h" #include "Kernel/Materialable.h" #include "Kernel/Logger.h" #include "Kernel/DocumentHelper.h" #include "Kernel/AssertionMemoryPanic.h" #include "Kernel/ConstStringHelper.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// Movie2Data::Movie2Data() : m_movieData( nullptr ) { } ////////////////////////////////////////////////////////////////////////// Movie2Data::~Movie2Data() { if( m_movieData != nullptr ) { ae_delete_movie_data( m_movieData ); m_movieData = nullptr; } } ////////////////////////////////////////////////////////////////////////// bool Movie2Data::acquire() { //Empty return true; } ////////////////////////////////////////////////////////////////////////// void Movie2Data::release() { //Empty } ////////////////////////////////////////////////////////////////////////// static ae_bool_t __ae_movie_resource_image_acquire( const aeMovieResourceImage * _resource, const Movie2Data * _data ) { MENGINE_UNUSED( _data ); ae_userdata_t resource_ud = ae_get_movie_resource_userdata( (const aeMovieResource *)_resource ); Movie2Data::ImageDesc * image_desc = reinterpret_cast<Movie2Data::ImageDesc *>(resource_ud); ResourceImage * resourceImage = image_desc->resourceImage; if( resourceImage->compile() == false ) { return AE_FALSE; } if( ++image_desc->refcount == 1 ) { image_desc->materials[EMB_NORMAL] = Helper::makeImageMaterial( ResourceImagePtr::from( resourceImage ), ConstString::none(), EMB_NORMAL, false, false, MENGINE_DOCUMENT_FORWARD_PTR( _data ) ); image_desc->materials[EMB_ADD] = Helper::makeImageMaterial( ResourceImagePtr::from( resourceImage ), ConstString::none(), EMB_ADD, false, false, MENGINE_DOCUMENT_FORWARD_PTR( _data ) ); image_desc->materials[EMB_SCREEN] = Helper::makeImageMaterial( ResourceImagePtr::from( resourceImage ), ConstString::none(), EMB_SCREEN, false, false, MENGINE_DOCUMENT_FORWARD_PTR( _data ) ); image_desc->materials[EMB_MULTIPLY] = Helper::makeImageMaterial( ResourceImagePtr::from( resourceImage ), ConstString::none(), EMB_MULTIPLY, false, false, MENGINE_DOCUMENT_FORWARD_PTR( _data ) ); } return AE_TRUE; } ////////////////////////////////////////////////////////////////////////// static ae_bool_t __ae_movie_layer_data_visitor_acquire( const aeMovieCompositionData * _compositionData, const aeMovieLayerData * _layer, ae_userdata_t _ud ) { AE_UNUSED( _compositionData ); const Movie2Data * data = reinterpret_cast<const Movie2Data *>(_ud); aeMovieResourceTypeEnum resource_type = ae_get_movie_layer_data_resource_type( _layer ); switch( resource_type ) { case AE_MOVIE_RESOURCE_SEQUENCE: { const aeMovieResource * resource = ae_get_movie_layer_data_resource( _layer ); const aeMovieResourceSequence * resource_sequence = (const aeMovieResourceSequence *)resource; for( ae_uint32_t index = 0; index != resource_sequence->image_count; ++index ) { const aeMovieResourceImage * resource_image = resource_sequence->images[index]; if( __ae_movie_resource_image_acquire( resource_image, data ) == AE_FALSE ) { return AE_FALSE; } } return AE_TRUE; }break; case AE_MOVIE_RESOURCE_IMAGE: { const aeMovieResource * resource = ae_get_movie_layer_data_resource( _layer ); const aeMovieResourceImage * resource_image = reinterpret_cast<const aeMovieResourceImage *>(resource); if( __ae_movie_resource_image_acquire( resource_image, data ) == AE_FALSE ) { return AE_FALSE; } return AE_TRUE; }break; case AE_MOVIE_RESOURCE_VIDEO: case AE_MOVIE_RESOURCE_SOUND: case AE_MOVIE_RESOURCE_PARTICLE: { ae_userdata_t resource_ud = ae_get_movie_layer_data_resource_userdata( _layer ); if( resource_ud == AE_USERDATA_NULL ) { return AE_TRUE; } Resource * resource = reinterpret_cast<Resource *>(resource_ud); if( resource->compile() == false ) { return AE_FALSE; } return AE_TRUE; }break; default: break; } return AE_TRUE; } ////////////////////////////////////////////////////////////////////////// bool Movie2Data::acquireCompositionData( const aeMovieCompositionData * _compositionData ) { if( ae_visit_composition_layer_data( _compositionData, &__ae_movie_layer_data_visitor_acquire, this ) == AE_FALSE ) { return false; } return true; } ////////////////////////////////////////////////////////////////////////// static void __ae_movie_resource_image_release( const aeMovieResourceImage * _resource ) { ae_userdata_t resource_ud = ae_get_movie_resource_userdata( (const aeMovieResource *)_resource ); Movie2Data::ImageDesc * image_desc = reinterpret_cast<Movie2Data::ImageDesc *>(resource_ud); ResourceImage * resourceImage = image_desc->resourceImage; resourceImage->release(); if( --image_desc->refcount == 0 ) { image_desc->materials[EMB_NORMAL] = nullptr; image_desc->materials[EMB_ADD] = nullptr; image_desc->materials[EMB_SCREEN] = nullptr; image_desc->materials[EMB_MULTIPLY] = nullptr; } } ////////////////////////////////////////////////////////////////////////// static ae_bool_t __ae_movie_layer_data_visitor_release( const aeMovieCompositionData * _compositionData, const aeMovieLayerData * _layer, ae_userdata_t _ud ) { AE_UNUSED( _compositionData ); AE_UNUSED( _ud ); aeMovieResourceTypeEnum resource_type = ae_get_movie_layer_data_resource_type( _layer ); switch( resource_type ) { case AE_MOVIE_RESOURCE_SEQUENCE: { const aeMovieResource * resource = ae_get_movie_layer_data_resource( _layer ); const aeMovieResourceSequence * resource_sequence = (const aeMovieResourceSequence *)resource; for( ae_uint32_t index = 0; index != resource_sequence->image_count; ++index ) { const aeMovieResourceImage * resource_image = resource_sequence->images[index]; __ae_movie_resource_image_release( resource_image ); } return AE_TRUE; }break; case AE_MOVIE_RESOURCE_IMAGE: { const aeMovieResource * resource = ae_get_movie_layer_data_resource( _layer ); const aeMovieResourceImage * resource_image = reinterpret_cast<const aeMovieResourceImage *>(resource); __ae_movie_resource_image_release( resource_image ); return AE_TRUE; }break; case AE_MOVIE_RESOURCE_VIDEO: case AE_MOVIE_RESOURCE_SOUND: case AE_MOVIE_RESOURCE_PARTICLE: { ae_userdata_t resource_ud = ae_get_movie_layer_data_resource_userdata( _layer ); if( resource_ud == AE_USERDATA_NULL ) { return AE_TRUE; } Resource * resource = reinterpret_cast<Resource *>(resource_ud); resource->release(); return AE_TRUE; }break; default: break; } return AE_TRUE; } ////////////////////////////////////////////////////////////////////////// void Movie2Data::releaseCompositionData( const aeMovieCompositionData * _compositionData ) { ae_visit_composition_layer_data( _compositionData, &__ae_movie_layer_data_visitor_release, this ); } ////////////////////////////////////////////////////////////////////////// static ae_bool_t __ae_movie_layer_data_visitor_get( const aeMovieCompositionData * _compositionData, const aeMovieLayerData * _layer, ae_userdata_t _ud ) { AE_UNUSED( _compositionData ); const Movie2DataInterface::LambdaResource * lambda = reinterpret_cast<const Movie2DataInterface::LambdaResource *>(_ud); aeMovieResourceTypeEnum resource_type = ae_get_movie_layer_data_resource_type( _layer ); switch( resource_type ) { case AE_MOVIE_RESOURCE_SEQUENCE: { const aeMovieResource * resource = ae_get_movie_layer_data_resource( _layer ); const aeMovieResourceSequence * resource_sequence = (const aeMovieResourceSequence *)resource; for( ae_uint32_t index = 0; index != resource_sequence->image_count; ++index ) { const aeMovieResourceImage * resource_image = resource_sequence->images[index]; ae_userdata_t resource_ud = ae_get_movie_resource_userdata( (const aeMovieResource *)resource_image ); Movie2Data::ImageDesc * image_desc = reinterpret_cast<Movie2Data::ImageDesc *>(resource_ud); ResourceImage * resourceImage = image_desc->resourceImage; (*lambda)(ResourcePtr::from( resourceImage )); } return AE_TRUE; }break; case AE_MOVIE_RESOURCE_IMAGE: { const aeMovieResource * resource = ae_get_movie_layer_data_resource( _layer ); const aeMovieResourceImage * resource_image = reinterpret_cast<const aeMovieResourceImage *>(resource); ae_userdata_t resource_ud = ae_get_movie_resource_userdata( (const aeMovieResource *)resource_image ); Movie2Data::ImageDesc * image_desc = reinterpret_cast<Movie2Data::ImageDesc *>(resource_ud); ResourceImage * resourceImage = image_desc->resourceImage; (*lambda)(ResourcePtr::from( resourceImage )); return AE_TRUE; }break; case AE_MOVIE_RESOURCE_VIDEO: case AE_MOVIE_RESOURCE_SOUND: case AE_MOVIE_RESOURCE_PARTICLE: { ae_userdata_t resource_ud = ae_get_movie_layer_data_resource_userdata( _layer ); if( resource_ud == AE_USERDATA_NULL ) { return AE_TRUE; } Resource * resource = reinterpret_cast<Resource *>(resource_ud); (*lambda)(ResourcePtr::from( resource )); return AE_TRUE; }break; default: break; } return AE_TRUE; } ////////////////////////////////////////////////////////////////////////// void Movie2Data::visitCompositionDataResources( const aeMovieCompositionData * _compositionData, const LambdaResource & _lambda ) { ae_visit_composition_layer_data( _compositionData, &__ae_movie_layer_data_visitor_get, const_cast<void *>(reinterpret_cast<const void *>(&_lambda)) ); } ////////////////////////////////////////////////////////////////////////// void Movie2Data::setGroupName( const ConstString & _groupName ) { m_groupName = _groupName; } ////////////////////////////////////////////////////////////////////////// const ConstString & Movie2Data::getGroupName() const { return m_groupName; } ////////////////////////////////////////////////////////////////////////// void Movie2Data::setMovieData( const aeMovieData * _movieData ) { m_movieData = _movieData; } ////////////////////////////////////////////////////////////////////////// const aeMovieData * Movie2Data::getMovieData() const { return m_movieData; } ////////////////////////////////////////////////////////////////////////// const ResourcePtr & Movie2Data::getResource( const Char * _resourceName ) { const ResourcePtr & resource = RESOURCE_SERVICE() ->getResourceReference( m_groupName, Helper::stringizeString( _resourceName ) ); MENGINE_ASSERTION_MEMORY_PANIC( resource, "not found resource '%s'" , _resourceName ); return resource; } ////////////////////////////////////////////////////////////////////////// Movie2Data::ImageDesc * Movie2Data::makeImageDesc( const ResourcePtr & _resource ) { ImageDesc * desc = m_poolImageDesc.createT(); desc->refcount = 0; desc->resourceImage = Helper::staticResourceCast<ResourceImage *>( _resource.get() ); return desc; } ////////////////////////////////////////////////////////////////////////// void Movie2Data::removeImageDesc( ImageDesc * _desc ) { m_poolImageDesc.destroyT( _desc ); } ////////////////////////////////////////////////////////////////////////// }
38.642857
207
0.553789
irov
ab601c9dfd7974cee110faf31abd8da455ea5cf0
176
hpp
C++
hiro/cocoa/header.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
hiro/cocoa/header.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
hiro/cocoa/header.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#include <nall/macos/guard.hpp> #include <Cocoa/Cocoa.h> #include <Carbon/Carbon.h> #include <IOKit/pwr_mgt/IOPMLib.h> #include <nall/macos/guard.hpp> #include <nall/run.hpp>
22
34
0.738636
CasualPokePlayer
ab615e780f7777cf5c6c44d984acc61e5a9e108c
977
cxx
C++
1.4 Sortland/main.cxx
SemenMartynov/openedu-itmo-algorithms
93697a1ac4de2300a9140d8752de7851743c0426
[ "MIT" ]
null
null
null
1.4 Sortland/main.cxx
SemenMartynov/openedu-itmo-algorithms
93697a1ac4de2300a9140d8752de7851743c0426
[ "MIT" ]
null
null
null
1.4 Sortland/main.cxx
SemenMartynov/openedu-itmo-algorithms
93697a1ac4de2300a9140d8752de7851743c0426
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <algorithm> #include <vector> struct citizen_t { long id; double account; }; int main(int argc, char **argv) { std::ifstream fin("input.txt"); std::ofstream fout("output.txt"); size_t citezens_c; fin >> citezens_c; std::vector<citizen_t> citezens(citezens_c); // read data for (size_t i = 0; i != citezens_c; ++i) { fin >> citezens[i].account; citezens[i].id = static_cast<long>(i) + 1; } // sort for (size_t i = 1; i < citezens_c; ++i) { for (size_t j = i; j > 0; --j) { if (citezens[j].account < citezens[j - 1].account) { std::swap(citezens[j], citezens[j - 1]); continue; } break; } } // show results fout << citezens[0].id << " " << citezens[citezens_c / 2].id << " " << citezens[citezens_c - 1].id << std::endl; return 0; }
20.787234
116
0.511771
SemenMartynov
ab6283662cdfbfa4d3e34bd586015f639bdc1b2c
17,722
cpp
C++
src/cmfd_solver.cpp
HunterBelanger/openmc
7f7977091df7552449cff6c3b96a1166e4b43e45
[ "MIT" ]
1
2020-12-18T16:09:59.000Z
2020-12-18T16:09:59.000Z
src/cmfd_solver.cpp
HunterBelanger/openmc
7f7977091df7552449cff6c3b96a1166e4b43e45
[ "MIT" ]
null
null
null
src/cmfd_solver.cpp
HunterBelanger/openmc
7f7977091df7552449cff6c3b96a1166e4b43e45
[ "MIT" ]
null
null
null
#include "openmc/cmfd_solver.h" #include <vector> #include <cmath> #ifdef _OPENMP #include <omp.h> #endif #include "xtensor/xtensor.hpp" #include "openmc/bank.h" #include "openmc/error.h" #include "openmc/constants.h" #include "openmc/capi.h" #include "openmc/mesh.h" #include "openmc/message_passing.h" #include "openmc/tallies/filter_energy.h" #include "openmc/tallies/filter_mesh.h" #include "openmc/tallies/tally.h" namespace openmc { namespace cmfd { //============================================================================== // Global variables //============================================================================== std::vector<int> indptr; std::vector<int> indices; int dim; double spectral; int nx, ny, nz, ng; xt::xtensor<int, 2> indexmap; int use_all_threads; StructuredMesh* mesh; std::vector<double> egrid; double norm; } // namespace cmfd //============================================================================== // GET_CMFD_ENERGY_BIN returns the energy bin for a source site energy //============================================================================== int get_cmfd_energy_bin(const double E) { // Check if energy is out of grid bounds if (E < cmfd::egrid[0]) { // throw warning message warning("Detected source point below energy grid"); return 0; } else if (E >= cmfd::egrid[cmfd::ng]) { // throw warning message warning("Detected source point above energy grid"); return cmfd::ng - 1; } else { // Iterate through energy grid to find matching bin for (int g = 0; g < cmfd::ng; g++) { if (E >= cmfd::egrid[g] && E < cmfd::egrid[g+1]) { return g; } } } // Return -1 by default return -1; } //============================================================================== // COUNT_BANK_SITES bins fission sites according to CMFD mesh and energy //============================================================================== xt::xtensor<double, 1> count_bank_sites(xt::xtensor<int, 1>& bins, bool* outside) { // Determine shape of array for counts std::size_t cnt_size = cmfd::nx * cmfd::ny * cmfd::nz * cmfd::ng; std::vector<std::size_t> cnt_shape = {cnt_size}; // Create array of zeros xt::xarray<double> cnt {cnt_shape, 0.0}; bool outside_ = false; auto bank_size = simulation::source_bank.size(); for (int i = 0; i < bank_size; i++) { const auto& site = simulation::source_bank[i]; // determine scoring bin for CMFD mesh int mesh_bin = cmfd::mesh->get_bin(site.r); // if outside mesh, skip particle if (mesh_bin < 0) { outside_ = true; continue; } // determine scoring bin for CMFD energy int energy_bin = get_cmfd_energy_bin(site.E); // add to appropriate bin cnt(mesh_bin*cmfd::ng+energy_bin) += site.wgt; // store bin index which is used again when updating weights bins[i] = mesh_bin*cmfd::ng+energy_bin; } // Create copy of count data. Since ownership will be acquired by xtensor, // std::allocator must be used to avoid Valgrind mismatched free() / delete // warnings. int total = cnt.size(); double* cnt_reduced = std::allocator<double>{}.allocate(total); #ifdef OPENMC_MPI // collect values from all processors MPI_Reduce(cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm); // Check if there were sites outside the mesh for any processor MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm); #else std::copy(cnt.data(), cnt.data() + total, cnt_reduced); *outside = outside_; #endif // Adapt reduced values in array back into an xarray auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), cnt_shape); xt::xarray<double> counts = arr; return counts; } //============================================================================== // OPENMC_CMFD_REWEIGHT performs reweighting of particles in source bank //============================================================================== extern "C" void openmc_cmfd_reweight(const bool feedback, const double* cmfd_src) { // Get size of source bank and cmfd_src auto bank_size = simulation::source_bank.size(); std::size_t src_size = cmfd::nx * cmfd::ny * cmfd::nz * cmfd::ng; // count bank sites for CMFD mesh, store bins in bank_bins for reweighting xt::xtensor<int, 1> bank_bins({bank_size}, 0); bool sites_outside; xt::xtensor<double, 1> sourcecounts = count_bank_sites(bank_bins, &sites_outside); // Compute CMFD weightfactors xt::xtensor<double, 1> weightfactors = xt::xtensor<double, 1>({src_size}, 1.); if (mpi::master) { if (sites_outside) { fatal_error("Source sites outside of the CMFD mesh"); } double norm = xt::sum(sourcecounts)()/cmfd::norm; for (int i = 0; i < src_size; i++) { if (sourcecounts[i] > 0 && cmfd_src[i] > 0) { weightfactors[i] = cmfd_src[i] * norm / sourcecounts[i]; } } } if (!feedback) return; #ifdef OPENMC_MPI // Send weightfactors to all processors MPI_Bcast(weightfactors.data(), src_size, MPI_DOUBLE, 0, mpi::intracomm); #endif // Iterate through fission bank and update particle weights for (int64_t i = 0; i < bank_size; i++) { auto& site = simulation::source_bank[i]; site.wgt *= weightfactors(bank_bins(i)); } } //============================================================================== // OPENMC_INITIALIZE_MESH_EGRID sets the mesh and energy grid for CMFD reweight //============================================================================== extern "C" void openmc_initialize_mesh_egrid(const int meshtally_id, const int* cmfd_indices, const double norm) { // Make sure all CMFD memory is freed free_memory_cmfd(); // Set CMFD indices cmfd::nx = cmfd_indices[0]; cmfd::ny = cmfd_indices[1]; cmfd::nz = cmfd_indices[2]; cmfd::ng = cmfd_indices[3]; // Set CMFD reweight properties cmfd::norm = norm; // Find index corresponding to tally id int32_t tally_index; openmc_get_tally_index(meshtally_id, &tally_index); // Get filters assocaited with tally const auto& tally_filters = model::tallies[tally_index]->filters(); // Get mesh filter index auto meshfilter_index = tally_filters[0]; // Store energy filter index if defined, otherwise set to -1 auto energy_index = (tally_filters.size() == 2) ? tally_filters[1] : -1; // Get mesh index from mesh filter index int32_t mesh_index; openmc_mesh_filter_get_mesh(meshfilter_index, &mesh_index); // Get mesh from mesh index cmfd::mesh = dynamic_cast<StructuredMesh*>(model::meshes[mesh_index].get()); // Get energy bins from energy index, otherwise use default if (energy_index != -1) { auto efilt_base = model::tally_filters[energy_index].get(); auto* efilt = dynamic_cast<EnergyFilter*>(efilt_base); cmfd::egrid = efilt->bins(); } else { cmfd::egrid = {0.0, INFTY}; } } //============================================================================== // MATRIX_TO_INDICES converts a matrix index to spatial and group // indices //============================================================================== void matrix_to_indices(int irow, int& g, int& i, int& j, int& k) { g = irow % cmfd::ng; i = cmfd::indexmap(irow/cmfd::ng, 0); j = cmfd::indexmap(irow/cmfd::ng, 1); k = cmfd::indexmap(irow/cmfd::ng, 2); } //============================================================================== // GET_DIAGONAL_INDEX returns the index in CSR index array corresponding to // the diagonal element of a specified row //============================================================================== int get_diagonal_index(int row) { for (int j = cmfd::indptr[row]; j < cmfd::indptr[row+1]; j++) { if (cmfd::indices[j] == row) return j; } // Return -1 if not found return -1; } //============================================================================== // SET_INDEXMAP sets the elements of indexmap based on input coremap //============================================================================== void set_indexmap(const int* coremap) { for (int z = 0; z < cmfd::nz; z++) { for (int y = 0; y < cmfd::ny; y++) { for (int x = 0; x < cmfd::nx; x++) { int idx = (z*cmfd::ny*cmfd::nx) + (y*cmfd::nx) + x; if (coremap[idx] != CMFD_NOACCEL) { int counter = coremap[idx]; cmfd::indexmap(counter, 0) = x; cmfd::indexmap(counter, 1) = y; cmfd::indexmap(counter, 2) = z; } } } } } //============================================================================== // CMFD_LINSOLVER_1G solves a one group CMFD linear system //============================================================================== int cmfd_linsolver_1g(const double* A_data, const double* b, double* x, double tol) { // Set overrelaxation parameter double w = 1.0; // Perform Gauss-Seidel iterations for (int igs = 1; igs <= 10000; igs++) { double err = 0.0; // Copy over x vector std::vector<double> tmpx {x, x+cmfd::dim}; // Perform red/black Gauss-Seidel iterations for (int irb = 0; irb < 2; irb++) { // Loop around matrix rows #pragma omp parallel for reduction (+:err) if(cmfd::use_all_threads) for (int irow = 0; irow < cmfd::dim; irow++) { int g, i, j, k; matrix_to_indices(irow, g, i, j, k); // Filter out black cells if ((i+j+k) % 2 != irb) continue; // Get index of diagonal for current row int didx = get_diagonal_index(irow); // Perform temporary sums, first do left of diag, then right of diag double tmp1 = 0.0; for (int icol = cmfd::indptr[irow]; icol < didx; icol++) tmp1 += A_data[icol] * x[cmfd::indices[icol]]; for (int icol = didx + 1; icol < cmfd::indptr[irow + 1]; icol++) tmp1 += A_data[icol] * x[cmfd::indices[icol]]; // Solve for new x double x1 = (b[irow] - tmp1) / A_data[didx]; // Perform overrelaxation x[irow] = (1.0 - w) * x[irow] + w * x1; // Compute residual and update error double res = (tmpx[irow] - x[irow]) / tmpx[irow]; err += res * res; } } // Check convergence err = std::sqrt(err / cmfd::dim); if (err < tol) return igs; // Calculate new overrelaxation parameter w = 1.0/(1.0 - 0.25 * cmfd::spectral * w); } // Throw error, as max iterations met fatal_error("Maximum Gauss-Seidel iterations encountered."); // Return -1 by default, although error thrown before reaching this point return -1; } //============================================================================== // CMFD_LINSOLVER_2G solves a two group CMFD linear system //============================================================================== int cmfd_linsolver_2g(const double* A_data, const double* b, double* x, double tol) { // Set overrelaxation parameter double w = 1.0; // Perform Gauss-Seidel iterations for (int igs = 1; igs <= 10000; igs++) { double err = 0.0; // Copy over x vector std::vector<double> tmpx {x, x+cmfd::dim}; // Perform red/black Gauss-Seidel iterations for (int irb = 0; irb < 2; irb++) { // Loop around matrix rows #pragma omp parallel for reduction (+:err) if(cmfd::use_all_threads) for (int irow = 0; irow < cmfd::dim; irow+=2) { int g, i, j, k; matrix_to_indices(irow, g, i, j, k); // Filter out black cells if ((i+j+k) % 2 != irb) continue; // Get index of diagonals for current row and next row int d1idx = get_diagonal_index(irow); int d2idx = get_diagonal_index(irow+1); // Get block diagonal double m11 = A_data[d1idx]; // group 1 diagonal double m12 = A_data[d1idx + 1]; // group 1 right of diagonal (sorted by col) double m21 = A_data[d2idx - 1]; // group 2 left of diagonal (sorted by col) double m22 = A_data[d2idx]; // group 2 diagonal // Analytically invert the diagonal double dm = m11*m22 - m12*m21; double d11 = m22/dm; double d12 = -m12/dm; double d21 = -m21/dm; double d22 = m11/dm; // Perform temporary sums, first do left of diag, then right of diag double tmp1 = 0.0; double tmp2 = 0.0; for (int icol = cmfd::indptr[irow]; icol < d1idx; icol++) tmp1 += A_data[icol] * x[cmfd::indices[icol]]; for (int icol = cmfd::indptr[irow+1]; icol < d2idx-1; icol++) tmp2 += A_data[icol] * x[cmfd::indices[icol]]; for (int icol = d1idx + 2; icol < cmfd::indptr[irow + 1]; icol++) tmp1 += A_data[icol] * x[cmfd::indices[icol]]; for (int icol = d2idx + 1; icol < cmfd::indptr[irow + 2]; icol++) tmp2 += A_data[icol] * x[cmfd::indices[icol]]; // Adjust with RHS vector tmp1 = b[irow] - tmp1; tmp2 = b[irow + 1] - tmp2; // Solve for new x double x1 = d11*tmp1 + d12*tmp2; double x2 = d21*tmp1 + d22*tmp2; // Perform overrelaxation x[irow] = (1.0 - w) * x[irow] + w * x1; x[irow + 1] = (1.0 - w) * x[irow + 1] + w * x2; // Compute residual and update error double res = (tmpx[irow] - x[irow]) / tmpx[irow]; err += res * res; } } // Check convergence err = std::sqrt(err / cmfd::dim); if (err < tol) return igs; // Calculate new overrelaxation parameter w = 1.0/(1.0 - 0.25 * cmfd::spectral * w); } // Throw error, as max iterations met fatal_error("Maximum Gauss-Seidel iterations encountered."); // Return -1 by default, although error thrown before reaching this point return -1; } //============================================================================== // CMFD_LINSOLVER_NG solves a general CMFD linear system //============================================================================== int cmfd_linsolver_ng(const double* A_data, const double* b, double* x, double tol) { // Set overrelaxation parameter double w = 1.0; // Perform Gauss-Seidel iterations for (int igs = 1; igs <= 10000; igs++) { double err = 0.0; // Copy over x vector std::vector<double> tmpx {x, x+cmfd::dim}; // Loop around matrix rows for (int irow = 0; irow < cmfd::dim; irow++) { // Get index of diagonal for current row int didx = get_diagonal_index(irow); // Perform temporary sums, first do left of diag, then right of diag double tmp1 = 0.0; for (int icol = cmfd::indptr[irow]; icol < didx; icol++) tmp1 += A_data[icol] * x[cmfd::indices[icol]]; for (int icol = didx + 1; icol < cmfd::indptr[irow + 1]; icol++) tmp1 += A_data[icol] * x[cmfd::indices[icol]]; // Solve for new x double x1 = (b[irow] - tmp1) / A_data[didx]; // Perform overrelaxation x[irow] = (1.0 - w) * x[irow] + w * x1; // Compute residual and update error double res = (tmpx[irow] - x[irow]) / tmpx[irow]; err += res * res; } // Check convergence err = std::sqrt(err / cmfd::dim); if (err < tol) return igs; // Calculate new overrelaxation parameter w = 1.0/(1.0 - 0.25 * cmfd::spectral * w); } // Throw error, as max iterations met fatal_error("Maximum Gauss-Seidel iterations encountered."); // Return -1 by default, although error thrown before reaching this point return -1; } //============================================================================== // OPENMC_INITIALIZE_LINSOLVER sets the fixed variables that are used for the // linear solver //============================================================================== extern "C" void openmc_initialize_linsolver(const int* indptr, int len_indptr, const int* indices, int n_elements, int dim, double spectral, const int* map, bool use_all_threads) { // Store elements of indptr for (int i = 0; i < len_indptr; i++) cmfd::indptr.push_back(indptr[i]); // Store elements of indices for (int i = 0; i < n_elements; i++) cmfd::indices.push_back(indices[i]); // Set dimenion of CMFD problem and specral radius cmfd::dim = dim; cmfd::spectral = spectral; // Set indexmap if 1 or 2 group problem if (cmfd::ng == 1 || cmfd::ng == 2) { // Resize indexmap and set its elements cmfd::indexmap.resize({static_cast<size_t>(dim), 3}); set_indexmap(map); } // Use all threads allocated to OpenMC simulation to run CMFD solver cmfd::use_all_threads = use_all_threads; } //============================================================================== // OPENMC_RUN_LINSOLVER runs a Gauss Seidel linear solver to solve CMFD matrix // equations //============================================================================== extern "C" int openmc_run_linsolver(const double* A_data, const double* b, double* x, double tol) { switch (cmfd::ng) { case 1: return cmfd_linsolver_1g(A_data, b, x, tol); case 2: return cmfd_linsolver_2g(A_data, b, x, tol); default: return cmfd_linsolver_ng(A_data, b, x, tol); } } void free_memory_cmfd() { // Clear std::vectors cmfd::indptr.clear(); cmfd::indices.clear(); cmfd::egrid.clear(); // Resize xtensors to be empty cmfd::indexmap.resize({0}); // Set pointers to null cmfd::mesh = nullptr; } } // namespace openmc
31.091228
84
0.548584
HunterBelanger
036cbd9d2e99f378768e00e52d456c3fef8c1f6c
4,073
hpp
C++
Libraries/Support/FileSupport.hpp
jodavis42/WelderEngineRevamp
1b8776c53857e66b2c933321e965bbe12f0df61e
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Code/Foundation/Support/FileSupport.hpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
null
null
null
Code/Foundation/Support/FileSupport.hpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once namespace Zero { inline u32 EndianSwap(u32 x) { return (x >> 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x << 24); } inline u64 EndianSwap(u64 x) { return (x >> 56) | ((x << 40) & 0x00FF000000000000ULL) | ((x << 24) & 0x0000FF0000000000ULL) | ((x << 8) & 0x000000FF00000000ULL) | ((x >> 8) & 0x00000000FF000000ULL) | ((x >> 24) & 0x0000000000FF0000ULL) | ((x >> 40) & 0x000000000000FF00ULL) | (x << 56); } template <typename bufferType, typename type> void Read(bufferType& buffer, type& data) { Status status; buffer.Read(status, (byte*)&data, sizeof(type)); } template <typename bufferType, typename type> void Write(bufferType& buffer, type& data) { buffer.Write((byte*)&data, sizeof(type)); } template <typename bufferType, typename stringType> void ReadString(bufferType& buffer, uint size, stringType& str) { Status status; byte* data = (byte*)alloca(size + 1); buffer.Read(status, data, size); data[size] = '\0'; str = (char*)data; } template <typename bufferType, typename type> void PeekType(bufferType& buffer, type& data) { Read(buffer, data); int offset = (int)sizeof(data); buffer.Seek(-offset, SeekOrigin::Current); } void WriteStringRangeToFile(StringParam path, StringRange range); DeclareEnum2(FilterResult, Ignore, Include); class FileFilter { public: virtual FilterResult::Enum Filter(StringParam filename) = 0; }; class FilterFileRegex : public FileFilter { public: String mAccept; String mIgnore; FilterFileRegex(StringParam accept, StringParam ignore) : mAccept(accept), mIgnore(ignore) { } FilterResult::Enum Filter(StringParam filename) override; }; class ExtensionFilterFile : public FileFilter { public: String mExtension; bool mCaseSensative; ExtensionFilterFile(StringParam extension, bool caseSensative = false) : mExtension(extension), mCaseSensative(caseSensative) { } FilterResult::Enum Filter(StringParam filename) override; }; // Move the contents of a folder. bool MoveFolderContents(StringParam dest, StringParam source, FileFilter* filter = 0); // Copy the contents of a folder. void CopyFolderContents(StringParam dest, StringParam source, FileFilter* filter = 0); // Finds all files in the given path void FindFilesRecursively(StringParam path, Array<String>& foundFiles); // Finds files matching a filter in the given path void FindFilesRecursively(StringParam path, Array<String>& foundFiles, FileFilter* filter); // Get a time stamp. String GetTimeAndDateStamp(); // Get the date String GetDate(); // Make a time stamped backup of a file. void BackUpFile(StringParam backupPath, StringParam fileName); // Data Block // Allocate a Data Block DataBlock AllocateBlock(size_t size); // Free memory in data block void FreeBlock(DataBlock& block); // Clone (not just copy) new memory will be allocated void CloneBlock(DataBlock& destBlock, const DataBlock& source); u64 ComputeFolderSizeRecursive(StringParam folder); String HumanReadableFileSize(u64 bytes); // A callback that we use with the Platform FileSystemInitializer for // platforms that don't have an actual file system, so we use memory instead. void PopulateVirtualFileSystemWithZip(void* userData); // Download a single file. void Download(StringParam fileName, const Array<byte>& binaryData); // Download a single file. void Download(StringParam fileName, const DataBlock& binaryData); // Download a single file. void Download(StringParam fileName, StringParam binaryData); // Download a single file. void Download(StringParam fileName, const ByteBufferBlock& binaryData); // Download a single file or if it is a directory download a zip of the directory. void Download(StringParam filePath); // If we're passed a single file, download the file individually. // If we're passed a directory or a set of files or directories, then zip them and download as one. void Download(StringParam suggestedNameWithoutExtension, StringParam workingDirectory, const Array<String>& filePaths); } // namespace Zero
28.886525
120
0.741959
jodavis42
0370c4933d3ba9c646169dda13548168167fe6ee
5,104
cpp
C++
private/tst/avb_streamhandler/src/IasTestAvbRxStreamClockDomain.cpp
tnishiok/AVBStreamHandler
7621daf8c9238361e030fe35188b921ee8ea2466
[ "BSL-1.0", "BSD-3-Clause" ]
13
2018-09-26T13:32:35.000Z
2021-05-20T10:01:12.000Z
private/tst/avb_streamhandler/src/IasTestAvbRxStreamClockDomain.cpp
keerockl/AVBStreamHandler
c0c9aa92656ae0acd0f57492d4f325eee2f7d13b
[ "BSD-3-Clause" ]
23
2018-10-03T22:45:21.000Z
2020-03-05T23:40:12.000Z
private/tst/avb_streamhandler/src/IasTestAvbRxStreamClockDomain.cpp
keerockl/AVBStreamHandler
c0c9aa92656ae0acd0f57492d4f325eee2f7d13b
[ "BSD-3-Clause" ]
22
2018-09-14T03:55:34.000Z
2021-12-07T01:13:27.000Z
/* * Copyright (C) 2018 Intel Corporation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /** * @file IasTestAvbRxStreamClockDomain.cpp * @date 2018 * @brief This file contains the unit tests of the IasAvbRxStreamClockDomain class. */ #include "gtest/gtest.h" #define private public #define protected public #include "avb_streamhandler/IasAvbRxStreamClockDomain.hpp" #include "avb_streamhandler/IasAvbStreamHandlerEnvironment.hpp" #undef protected #undef private #include "test_common/IasSpringVilleInfo.hpp" extern size_t heapSpaceLeft; extern size_t heapSpaceInitSize; namespace IasMediaTransportAvb { class IasTestAvbRxStreamClockDomain : public ::testing::Test { protected: IasTestAvbRxStreamClockDomain(): mRxClockDomain(NULL), mEnvironment(NULL) { } virtual ~IasTestAvbRxStreamClockDomain() {} // Sets up the test fixture. virtual void SetUp() { // needed only for :Update" test // but // needs to be set up here due to ClockDomain gets Ptp on its CTor ASSERT_TRUE(LocalSetup()); heapSpaceLeft = heapSpaceInitSize; mRxClockDomain = new IasAvbRxStreamClockDomain; } virtual void TearDown() { delete mEnvironment; mEnvironment = NULL; delete mRxClockDomain; mRxClockDomain = NULL; heapSpaceLeft = heapSpaceInitSize; } bool LocalSetup() { mEnvironment = new IasAvbStreamHandlerEnvironment(DLT_LOG_INFO); if (mEnvironment) { mEnvironment->setDefaultConfigValues(); if (IasSpringVilleInfo::fetchData()) { IasSpringVilleInfo::printDebugInfo(); mEnvironment->setConfigValue(IasRegKeys::cNwIfName, IasSpringVilleInfo::getInterfaceName()); if (eIasAvbProcOK == mEnvironment->createIgbDevice()) { if (eIasAvbProcOK == mEnvironment->createPtpProxy()) { if (IasAvbStreamHandlerEnvironment::getIgbDevice()) { if (IasAvbStreamHandlerEnvironment::getPtpProxy()) { return true; } } } } } } return false; } IasAvbRxStreamClockDomain* mRxClockDomain; IasAvbStreamHandlerEnvironment* mEnvironment; }; TEST_F(IasTestAvbRxStreamClockDomain, Reset) { ASSERT_TRUE(NULL != mRxClockDomain); IasAvbSrClass cl = IasAvbSrClass::eIasAvbSrClassHigh; uint32_t callsPerSecond = IasAvbTSpec::getPacketsPerSecondByClass(cl); uint64_t skipTime = 0u; uint32_t timestamp = 1u; uint32_t eventRate = 48000u; mEnvironment->setConfigValue(IasRegKeys::cRxClkUpdateInterval, skipTime); // IasAvbStreamHandlerEnvironment::getConfigValue(IasRegKeys::cRxClkUpdateInterval, skipTime) (T) // && (0u != skipTime) (F) mRxClockDomain->reset(cl, timestamp, eventRate); ASSERT_EQ(callsPerSecond, mRxClockDomain->mAvgCallsPerSec); mEnvironment->setConfigValue(IasRegKeys::cRxClkUpdateInterval, "skipTime"); // IasAvbStreamHandlerEnvironment::getConfigValue(IasRegKeys::cRxClkUpdateInterval, skipTime) (F) // && (0u != skipTime) (F) mRxClockDomain->reset(cl, timestamp, eventRate); ASSERT_EQ(callsPerSecond, mRxClockDomain->mAvgCallsPerSec); callsPerSecond = 1E6; skipTime = 1u; mEnvironment->setConfigValue(IasRegKeys::cRxClkUpdateInterval, skipTime); // IasAvbStreamHandlerEnvironment::getConfigValue(IasRegKeys::cRxClkUpdateInterval, skipTime) (T) // && (0u != skipTime) (T) mRxClockDomain->reset(cl, timestamp, eventRate); ASSERT_EQ(callsPerSecond, mRxClockDomain->mAvgCallsPerSec); } TEST_F(IasTestAvbRxStreamClockDomain, Update) { ASSERT_TRUE(NULL != mRxClockDomain); uint32_t deltaMediaClock = 0; uint32_t deltaWallClock = 0; uint32_t events = 6u; uint32_t timestamp = 0u; mRxClockDomain->update(events, timestamp, deltaMediaClock, deltaWallClock); deltaMediaClock = 1; timestamp = 125000; mRxClockDomain->update(events, timestamp, deltaMediaClock, deltaWallClock); } TEST_F(IasTestAvbRxStreamClockDomain, CTor_setSwDeviation) { ASSERT_TRUE(NULL != mRxClockDomain); mEnvironment->setConfigValue(IasRegKeys::cClkRxDeviationLongterm, 1000u); mEnvironment->setConfigValue(IasRegKeys::cClkRxDeviationUnlock, 1000u); delete mRxClockDomain; mRxClockDomain = new IasAvbRxStreamClockDomain(); ASSERT_EQ(1.0f, mRxClockDomain->mFactorLong); ASSERT_EQ(1.0f, mRxClockDomain->mFactorUnlock); } TEST_F(IasTestAvbRxStreamClockDomain, invalidate) { ASSERT_TRUE(NULL != mRxClockDomain); mRxClockDomain->mTimeConstant = 1.0f; mRxClockDomain->mAvgCallsPerSec = 0; mRxClockDomain->mLockState = IasAvbClockDomain::IasAvbLockState::eIasAvbLockStateInit; mRxClockDomain->invalidate(); ASSERT_EQ(1, mRxClockDomain->mAvgCallsPerSec); ASSERT_EQ(1.0f, mRxClockDomain->mTimeConstant); ASSERT_EQ(IasAvbClockDomain::IasAvbLockState::eIasAvbLockStateInit, mRxClockDomain->mLockState); } } // IasMediaTransportAvb
29.674419
100
0.706505
tnishiok
03730e9cc9e6dbb959be34cb8bb22cee50224346
253
cpp
C++
src/cbag/layout/via_wrapper.cpp
ayan-biswas/cbag
0d08394cf39e90bc3acb4a94fd7b5a6560cf103c
[ "BSD-3-Clause" ]
1
2020-01-07T04:44:17.000Z
2020-01-07T04:44:17.000Z
src/cbag/layout/via_wrapper.cpp
skyworksinc/cbag
0d08394cf39e90bc3acb4a94fd7b5a6560cf103c
[ "BSD-3-Clause" ]
null
null
null
src/cbag/layout/via_wrapper.cpp
skyworksinc/cbag
0d08394cf39e90bc3acb4a94fd7b5a6560cf103c
[ "BSD-3-Clause" ]
1
2020-01-07T04:45:13.000Z
2020-01-07T04:45:13.000Z
#include <cbag/layout/via_wrapper.h> namespace cbag { namespace layout { via_wrapper::via_wrapper() = default; via_wrapper::via_wrapper(via &&v, bool add_layers) : v(std::move(v)), add_layers(add_layers) {} } // namespace layout } // namespace cbag
21.083333
95
0.72332
ayan-biswas
0378476e6f80c8f11254a3fe6ec963be47c226ea
719
hpp
C++
src/scene/BVH.hpp
huang-jl/Graphics-Renderer
947c145330aeec9fe127c168e9629aeab84e416e
[ "MIT" ]
null
null
null
src/scene/BVH.hpp
huang-jl/Graphics-Renderer
947c145330aeec9fe127c168e9629aeab84e416e
[ "MIT" ]
null
null
null
src/scene/BVH.hpp
huang-jl/Graphics-Renderer
947c145330aeec9fe127c168e9629aeab84e416e
[ "MIT" ]
null
null
null
#ifndef BVH_HPP #define BVH_HPP #include "AABB.hpp" #include "Hitable.hpp" #include "Ray.hpp" #include <vector> /* * 层次包围体BHV:用AABB实现 * 这里认为层次包围盒也是一个Hitable * 其作用是一个容器,能够高效处理光线和物体是否相交 */ class BVHNode : public Hitable { public: BVHNode() {} // BVHNode(Hitable **l, int n, float time0, float time1); BVHNode(std::vector<shared_ptr<Hitable>> &l,size_t start, size_t end, float time0, float time1); virtual bool bounding_box(float t0, float t1, AABB &output_box) const override; virtual bool hit(const Ray &r, float t_min, float t_max, Hit &rec) const override; /*data*/ shared_ptr<Hitable> left_c; //左孩子,为了通用性,指针为Hitbale shared_ptr<Hitable> right_c; //右孩子 AABB box; }; #endif
25.678571
100
0.698192
huang-jl
0378b92d9bbc2a0decd7fa86b24800700a175488
3,500
hpp
C++
sdl/Util/LogInfo.hpp
sdl-research/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
29
2015-01-26T21:49:51.000Z
2021-06-18T18:09:42.000Z
sdl/Util/LogInfo.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
1
2015-12-08T15:03:15.000Z
2016-01-26T14:31:06.000Z
sdl/Util/LogInfo.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
4
2015-11-21T14:25:38.000Z
2017-10-30T22:22:00.000Z
// Copyright 2014-2015 SDL plc // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** \file StringConsumer (fn accepting string) for log4cxx LOG_INFO. */ #ifndef LOGINFO_JG2012813_HPP #define LOGINFO_JG2012813_HPP #pragma once #include <sdl/Util/LogLevel.hpp> #include <sdl/Log.hpp> #include <sdl/StringConsumer.hpp> #ifndef NLOG #include <log4cxx/logger.h> #endif namespace sdl { namespace Util { struct LogInfo { explicit LogInfo(std::string const& logname) : logname(logname) {} std::string logname; // TODO: save log4cxx object? for now, let logging cfg change and we reflect that // always. this is used for infos only so perf. shouldn't matter. would use: // LoggerPtr plog; void operator()(std::string const& msg) const { #ifdef NLOG std::cerr << logname << ": " << msg << '\n'; #else LOG4CXX_INFO(log4cxx::Logger::getLogger(logname), msg); #endif } }; inline StringConsumer logInfo(std::string const& module, std::string const& prefix = "sdl.") { return LogInfo(prefix + module); } struct LogAtLevel { explicit LogAtLevel(std::string const& logname_, LogLevel level = kLogInfo) { set(logname_, level); } LogAtLevel(std::string const& logname_, LogLevelPtr levelptr) { set(logname_, levelptr); } LogAtLevel(std::string const& logname_, std::string const& levelName, LogLevel fallbacklevel = kLogInfo) { set(logname_, levelName, fallbacklevel); } void setLevel(std::string const& name, LogLevel fallbacklevel = kLogInfo) { plevel = logLevel(name, fallbacklevel); } void setLevel(LogLevel level = kLogInfo) { plevel = logLevel(level); } void set(std::string logname_) { logname = logname_; #ifndef NLOG plog = log4cxx::Logger::getLogger(logname); #endif } void set(std::string const& logname_, std::string const& logLevelName, LogLevel fallbacklevel = kLogInfo) { set(logname_); setLevel(logLevelName, fallbacklevel); } void set(std::string const& logname_, LogLevel level) { set(logname_); setLevel(level); } void set(std::string const& logname_, LogLevelPtr levelptr) { set(logname_); plevel = levelptr; } std::string logname; // TODO: save log4cxx object? for now, let logging cfg change and we reflect that // always. this is used for warnings only so perf. shouldn't matter. would use: LoggerPtr plog; LogLevelPtr plevel; void operator()(std::string const& msg) const { #ifdef NLOG std::cerr << logname << ": " << msg << '\n'; #else LOG4CXX_LOG(plog, plevel, msg); #endif } }; inline StringConsumer logAtLevel(std::string const& module, std::string const& level, std::string const& prefix = SDL_LOG_PREFIX_STR, LogLevel fallback = kLogInfo) { return LogAtLevel(prefix + module, level, fallback); } inline StringConsumer logAtLevel(std::string const& module, LogLevel level = kLogInfo, std::string const& prefix = SDL_LOG_PREFIX_STR) { return LogAtLevel(prefix + module, level); } }} #endif
33.653846
112
0.702857
sdl-research
0387f3344dc39e9b5d3d54312b7cacccdef236d1
2,970
cpp
C++
src/Dengo/Init_MemAllocate_Dengo.cpp
hisunnytang/gamer-fork
8ca0cd1dd3ffd5bbd04049a4af5bdf63103b0df9
[ "BSD-3-Clause" ]
null
null
null
src/Dengo/Init_MemAllocate_Dengo.cpp
hisunnytang/gamer-fork
8ca0cd1dd3ffd5bbd04049a4af5bdf63103b0df9
[ "BSD-3-Clause" ]
null
null
null
src/Dengo/Init_MemAllocate_Dengo.cpp
hisunnytang/gamer-fork
8ca0cd1dd3ffd5bbd04049a4af5bdf63103b0df9
[ "BSD-3-Clause" ]
null
null
null
#include "GAMER.h" #ifdef SUPPORT_DENGO // global variables for accessing h_Che_Array[] // --> also used by Dengo_Prepare.cpp and Dengo_Close.cpp // --> they are not declared in "Global.h" simply because they are only used by a few Dengo routines int Che_NField = NULL_INT; int CheIdx_Dens = Idx_Undefined; int CheIdx_sEint = Idx_Undefined; int CheIdx_Ek = Idx_Undefined; int CheIdx_e = Idx_Undefined; int CheIdx_HI = Idx_Undefined; int CheIdx_HII = Idx_Undefined; int CheIdx_HeI = Idx_Undefined; int CheIdx_HeII = Idx_Undefined; int CheIdx_HeIII = Idx_Undefined; int CheIdx_HM = Idx_Undefined; int CheIdx_H2I = Idx_Undefined; int CheIdx_H2II = Idx_Undefined; int CheIdx_CoolingTime = Idx_Undefined; int CheIdx_Gamma = Idx_Undefined; int CheIdx_MolecularWeight = Idx_Undefined; int CheIdx_Temperature = Idx_Undefined; //------------------------------------------------------------------------------------------------------- // Function : Init_MemAllocate_Dengo // Description : Allocate the CPU memory for the Dengo solver // // Note : 1. Work even when GPU is enabled // 2. Invoked by Init_MemAllocate() // 3. Also set global variables for accessing h_Che_Array[] // --> Declared on the top of this file // // Parameter : Che_NPG : Number of patch groups to be evaluated at a time //------------------------------------------------------------------------------------------------------- void Init_MemAllocate_Dengo( const int Che_NPG ) { // nothing to do if Dengo is disabled if ( !DENGO_ACTIVATE ) return; // set global variables related to h_Che_Array[] Che_NField = 0; CheIdx_Dens = Che_NField ++; CheIdx_sEint = Che_NField ++; CheIdx_Ek = Che_NField ++; //if ( DENGO_PRIMORDIAL >= DENGO_PRI_CHE_NSPE6 ) { CheIdx_e = Che_NField ++; CheIdx_HI = Che_NField ++; CheIdx_HII = Che_NField ++; CheIdx_HeI = Che_NField ++; CheIdx_HeII = Che_NField ++; CheIdx_HeIII = Che_NField ++; //} //if ( DENGO_PRIMORDIAL >= DENGO_PRI_CHE_NSPE9 ) { CheIdx_HM = Che_NField ++; CheIdx_H2I = Che_NField ++; CheIdx_H2II = Che_NField ++; //} /* if ( DENGO_PRIMORDIAL >= DENGO_PRI_CHE_NSPE12 ) { CheIdx_DI = Che_NField ++; CheIdx_DII = Che_NField ++; CheIdx_HDI = Che_NField ++; } if ( DENGO_METAL ) CheIdx_Metal = Che_NField ++; */ CheIdx_CoolingTime = Che_NField++; CheIdx_Gamma = Che_NField++; CheIdx_MolecularWeight = Che_NField++; CheIdx_Temperature = Che_NField++; fprintf(stderr, "done creating array in MemAllocate_Denngo %d, %d, %d \n", Che_NField, Che_NPG, PS2); // allocate the input/output array for the Dengo solver for (int t=0; t<2; t++) h_Che_Array[t] = new real [ (long)Che_NField*(long)Che_NPG*(long)CUBE(PS2) ]; } // FUNCTION : Init_MemAllocate_Dengo #endif // #ifdef SUPPORT_DENGO
30.618557
105
0.622896
hisunnytang
038b11d5956e807a02dc734015bd8dda3048d7b6
3,780
cpp
C++
source/styles/conditional_format.cpp
wuganhao/xlnt
4acfa185c0891e64b044ddac16046baee011bdf5
[ "Unlicense" ]
null
null
null
source/styles/conditional_format.cpp
wuganhao/xlnt
4acfa185c0891e64b044ddac16046baee011bdf5
[ "Unlicense" ]
null
null
null
source/styles/conditional_format.cpp
wuganhao/xlnt
4acfa185c0891e64b044ddac16046baee011bdf5
[ "Unlicense" ]
1
2021-11-22T10:07:34.000Z
2021-11-22T10:07:34.000Z
// Copyright (c) 2014-2021 Thomas Fussell // Copyright (c) 2010-2015 openpyxl // // 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 // // @license: http://www.opensource.org/licenses/mit-license.php // @author: see AUTHORS file #include <xlnt/styles/border.hpp> #include <xlnt/styles/conditional_format.hpp> #include <xlnt/styles/fill.hpp> #include <xlnt/styles/font.hpp> #include <detail/implementations/conditional_format_impl.hpp> #include <detail/implementations/stylesheet.hpp> namespace xlnt { condition condition::text_starts_with(const std::string &text) { condition c; c.type_ = type::contains_text; c.operator_ = condition_operator::starts_with; c.text_comparand_ = text; return c; } condition condition::text_ends_with(const std::string &text) { condition c; c.type_ = type::contains_text; c.operator_ = condition_operator::ends_with; c.text_comparand_ = text; return c; } condition condition::text_contains(const std::string &text) { condition c; c.type_ = type::contains_text; c.operator_ = condition_operator::contains; c.text_comparand_ = text; return c; } condition condition::text_does_not_contain(const std::string &text) { condition c; c.type_ = type::contains_text; c.operator_ = condition_operator::does_not_contain; c.text_comparand_ = text; return c; } conditional_format::conditional_format(detail::conditional_format_impl *d) : d_(d) { } bool conditional_format::operator==(const conditional_format &other) const { return d_ == other.d_; } bool conditional_format::operator!=(const conditional_format &other) const { return !(*this == other); } bool conditional_format::has_border() const { return d_->border_id.is_set(); } xlnt::border conditional_format::border() const { return d_->parent->borders.at(d_->border_id.get()); } conditional_format conditional_format::border(const xlnt::border &new_border) { d_->border_id = d_->parent->find_or_add(d_->parent->borders, new_border); return *this; } bool conditional_format::has_fill() const { return d_->fill_id.is_set(); } xlnt::fill conditional_format::fill() const { return d_->parent->fills.at(d_->fill_id.get()); } conditional_format conditional_format::fill(const xlnt::fill &new_fill) { d_->fill_id = d_->parent->find_or_add(d_->parent->fills, new_fill); return *this; } bool conditional_format::has_font() const { return d_->font_id.is_set(); } xlnt::font conditional_format::font() const { return d_->parent->fonts.at(d_->font_id.get()); } conditional_format conditional_format::font(const xlnt::font &new_font) { d_->font_id = d_->parent->find_or_add(d_->parent->fonts, new_font); return *this; } } // namespace xlnt
28.208955
80
0.73254
wuganhao
039044f2605a851c5273020b1f45d670c8279b18
3,166
cpp
C++
cpp02/ex03/Fixed.cpp
ostef/42-cpp
59853e5252793e8aef9a7dfe31d2888304146e90
[ "Unlicense" ]
1
2022-02-16T18:07:02.000Z
2022-02-16T18:07:02.000Z
cpp02/ex03/Fixed.cpp
ostef/42-cpp
59853e5252793e8aef9a7dfe31d2888304146e90
[ "Unlicense" ]
null
null
null
cpp02/ex03/Fixed.cpp
ostef/42-cpp
59853e5252793e8aef9a7dfe31d2888304146e90
[ "Unlicense" ]
null
null
null
#include "Fixed.hpp" #include <iostream> #include <cmath> // | integral | fractional | // 32 ... 8 ... 0 const int Fixed::FRACT_BITS = 8; Fixed::Fixed () : m_raw (0) { std::cout << "Default constructor called... Yay..." << std::endl; } Fixed::Fixed (const int i) : m_raw (0) { std::cout << "Constructor (const int i) called... Yay..." << std::endl; m_raw = i << FRACT_BITS; } Fixed::Fixed (const float f) : m_raw (0) { std::cout << "Constructor (const float f) called... Yay..." << std::endl; m_raw = roundf (f * (1 << FRACT_BITS)); } Fixed::Fixed (const Fixed &other) : m_raw (other.m_raw) { std::cout << "Copy constructor called... Yay..." << std::endl; } Fixed::~Fixed () { std::cout << "Destructor called... Yay..." << std::endl; } Fixed &Fixed::operator = (const Fixed &other) { std::cout << "Assignment operator called... Yay..." << std::endl; m_raw = other.m_raw; return *this; } Fixed &Fixed::min (Fixed &a, Fixed &b) { if (a < b) return a; return b; } const Fixed &Fixed::min (const Fixed &a, const Fixed &b) { if (a < b) return a; return b; } Fixed &Fixed::max (Fixed &a, Fixed &b) { if (a > b) return a; return b; } const Fixed &Fixed::max (const Fixed &a, const Fixed &b) { if (a > b) return a; return b; } int Fixed::getRawBits () const { std::cout << "getRawBits member function called... Yay..." << std::endl; return m_raw; } void Fixed::setRawBits (const int raw) { std::cout << "setRawBits member function called... Yay..." << std::endl; m_raw = raw; } float Fixed::toFloat () const { return (float)m_raw / (float)(1 << FRACT_BITS); } int Fixed::toInt () const { return m_raw >> FRACT_BITS; } Fixed Fixed::operator + (const Fixed &other) const { Fixed result; result.m_raw = m_raw + other.m_raw; return result; } Fixed Fixed::operator - (const Fixed &other) const { Fixed result; result.m_raw = m_raw - other.m_raw; return result; } Fixed Fixed::operator * (const Fixed &other) const { Fixed result; result.m_raw = (m_raw * other.m_raw) / (1 << FRACT_BITS); return result; } Fixed Fixed::operator / (const Fixed &other) const { Fixed result; result.m_raw = (m_raw * (1 << FRACT_BITS)) / other.m_raw; return result; } Fixed &Fixed::operator ++ () { m_raw += 1; return *this; } Fixed Fixed::operator ++ (int) { Fixed temp = *this; m_raw += 1; return temp; } Fixed &Fixed::operator -- () { m_raw -= 1; return *this; } Fixed Fixed::operator -- (int) { Fixed temp = *this; m_raw -= 1; return temp; } bool Fixed::operator < (const Fixed &other) const { return m_raw < other.m_raw; } bool Fixed::operator <= (const Fixed &other) const { return m_raw <= other.m_raw; } bool Fixed::operator > (const Fixed &other) const { return m_raw > other.m_raw; } bool Fixed::operator >= (const Fixed &other) const { return m_raw >= other.m_raw; } bool Fixed::operator == (const Fixed &other) const { return m_raw == other.m_raw; } bool Fixed::operator != (const Fixed &other) const { return m_raw != other.m_raw; } std::ostream &operator << (std::ostream &out, const Fixed &fixed) { return out << fixed.toFloat (); }
16.575916
74
0.618446
ostef
0392611ba04118daee7bc62ab7989233c6d5535c
706
cpp
C++
Competitve Programming & Online Problems/Coding-Interview/Chapter 3 - Stacks and Queues/3.5 sort_stack.cpp
srini1392/Programming-in-Cpp
099f44d65cbe976b27625e5806b32ab88414b019
[ "MIT" ]
1
2019-01-02T21:52:49.000Z
2019-01-02T21:52:49.000Z
Competitve Programming & Online Problems/Coding-Interview/Chapter 3 - Stacks and Queues/3.5 sort_stack.cpp
srini1392/Programming-in-Cpp
099f44d65cbe976b27625e5806b32ab88414b019
[ "MIT" ]
1
2019-04-05T00:00:13.000Z
2019-04-05T00:00:13.000Z
Competitve Programming & Online Problems/Coding-Interview/Chapter 3 - Stacks and Queues/3.5 sort_stack.cpp
srini1392/Programming-in-Cpp
099f44d65cbe976b27625e5806b32ab88414b019
[ "MIT" ]
5
2019-02-18T08:42:32.000Z
2021-04-27T12:11:43.000Z
#include <bits/stdc++.h> using namespace std; template <class T> void sort_stack(vector<T> *s) { vector<T> r; while ((*s).size()) { T temp = (*s).back(); (*s).pop_back(); while (r.size() && r.back() > temp) { (*s).push_back(r.back()); r.pop_back(); } r.push_back(temp); } while (r.size()) { (*s).push_back(r.back()); r.pop_back(); } } int main() { vector<int> v; v.push_back(5); v.push_back(3); v.push_back(1); v.push_back(4); v.push_back(2); sort_stack(&v); while (v.size()) { cout << v.back() << " "; v.pop_back(); } return 0; }
18.102564
43
0.446176
srini1392
0396df5b6a69bf857f9697957de56037943d4780
3,068
cpp
C++
LeetCode/941.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
1
2021-12-22T12:37:36.000Z
2021-12-22T12:37:36.000Z
LeetCode/941.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
LeetCode/941.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
class Solution { public: bool validMountainArray(vector<int>& arr) { int n=arr.size(); int count1=0; int count2=0; if(arr.size() < 3) return false; //check any any element is same in array return false for(int i = 0; i < arr.size() - 1; i++) { if(arr[i] == arr[i+1]) return false; } //find max element in array and its index int max_index = 0; int max_element = arr[0]; for(int i = 0; i < arr.size(); i++) { if(arr[i] > max_element) { max_element = arr[i]; max_index = i; } } //check before max index is increasing or not for(int i = 0; i < max_index; i++) { if(arr[i] > arr[i+1]) return false; count1++; } //check after max index is decreasing or not for(int i = max_index; i < arr.size() - 1; i++) { if(arr[i] < arr[i+1]) return false; count2++; } if(count1<1 || count2<1) return false; return true; // for(int i=0;i<max_index;i++) // { // if(arr[i]>arr[i+1]) // { // return false; // } // } // for(int i=max_index+1;i<n;i++) // { // if(arr[i]<arr[i-1]) // { // return false; // } // } //create two loop one for left to right and one for right to left // for(int i=0;i<n;i++){ // while(arr[i+1] > arr[i]){ // continue; // i++; // } // break; // int j=i; // //check arr[i] to arr[n-1] is decreasing // while(arr[j] < arr[j+1]){ // continue; // j++; // } // if(j==n-1) return true; // else return false; // } // for(int j=n-1;j>i;j--){ // } // } // check this condition arr[0] < arr[1] < ... < arr[i - 1] < arr[i] // and also this condition arr[i] > arr[i + 1] > ... > arr[arr.length - 1] // int i = 0; // while(i < arr.size() - 1 && arr[i] < arr[i+1]) // { // i++; // } // if(i == 0 || i == arr.size() - 1) return false; //check if any element is grater than both side return true // for(int i = 0; i < arr.size() - 1; i++) // { // if(arr[i] > arr[i+1]) return true; // } // for(int i = 0; i < arr.size() - 1; i++) // { // if((arr[i] > arr[i-1]) && (arr[i+1]> arr[i]) ) return true; // } //check arr[0] to arr[i] is increasing // for(int i = 0; i < arr.size() - 1; i++) // { // if(arr[i] > arr[i+1]) return false; // } //check arr[i] to arr[n-1] is decreasing // for(int i = 0; i < arr.size() - 1; i++) // { // if(arr[i] < arr[i+1]) return false; // } // return true; } };
22.558824
75
0.390156
jnvshubham7
0397526a8bc73b4e3f64ed5cd6ea08b8aef7d6eb
1,254
hpp
C++
Animator/src/Debug.hpp
Trequend/Animator
583d1d76d4e25a2840d1e122654c80f794f91d51
[ "MIT" ]
null
null
null
Animator/src/Debug.hpp
Trequend/Animator
583d1d76d4e25a2840d1e122654c80f794f91d51
[ "MIT" ]
null
null
null
Animator/src/Debug.hpp
Trequend/Animator
583d1d76d4e25a2840d1e122654c80f794f91d51
[ "MIT" ]
null
null
null
#pragma once #include <ctime> #include <cstdio> #include <vector> #include <imgui/imgui.h> #include "window/DebugWindow.hpp" #ifndef MESSAGE_BUFFER_SIZE #define MESSAGE_BUFFER_SIZE 2000 #endif // !MESSAGE_BUFFER_SIZE class Debug { friend class DebugWindow; public: enum class MessageType { Info, Warning, Error }; struct Message { char* Content; size_t ContentLength; MessageType Type; char Time[11]; Message() = default; Message(char* content, size_t size, MessageType type) : Content(content), ContentLength(size), Type(type) { std::time_t t = std::time(nullptr); std::tm tm; localtime_s(&tm, &t); std::strftime(Time, 11, "[%H:%M:%S]", &tm); } }; private: static std::vector<Message> messages; static size_t GetMessagesCount() { return messages.size(); } static const Message& GetMessage(int index) { return messages[index]; } static void Clear(); public: static void Log(const char* message, Debug::MessageType type = Debug::MessageType::Info); static void LogWarning(const char* message); static void LogError(const char* message); static void LogFormat(MessageType type, const char* fmt, ...); static void LogFormat(MessageType type, size_t bufferSize, const char* fmt, ...); };
19.292308
90
0.703349
Trequend
039b753bf1d4f56f250fb5527fd17d860af561fc
11,782
cpp
C++
src/all/frm/core/TextureAtlas.cpp
CPau/GfxSampleFramework
aa32d505d7ad6b53691daa2805a1b6c408e6c34a
[ "MIT" ]
null
null
null
src/all/frm/core/TextureAtlas.cpp
CPau/GfxSampleFramework
aa32d505d7ad6b53691daa2805a1b6c408e6c34a
[ "MIT" ]
null
null
null
src/all/frm/core/TextureAtlas.cpp
CPau/GfxSampleFramework
aa32d505d7ad6b53691daa2805a1b6c408e6c34a
[ "MIT" ]
null
null
null
#include "TextureAtlas.h" #include <frm/core/Texture.h> #include <apt/Image.h> #ifdef frm_TextureAtlas_DEBUG #include <imgui/imgui.h> static eastl::vector<frm::TextureAtlas::Region*> s_dbgRegionList; #endif using namespace frm; using namespace apt; /******************************************************************************* TextureAtlas *******************************************************************************/ struct TextureAtlas::Node { Node* m_parent; Node* m_children[4]; bool m_isEmpty; uint16 m_sizeX, m_sizeY; uint16 m_startX, m_startY; Node(Node* _parent) : m_parent(_parent) , m_isEmpty(true) { m_children[0] = 0; m_children[1] = 0; m_children[2] = 0; m_children[3] = 0; } bool isLeaf() const { return m_children[0] == 0; } bool isEmpty() const { return m_isEmpty; } }; // PUBLIC TextureAtlas* TextureAtlas::Create(GLsizei _width, GLsizei _height, GLenum _format, GLsizei _mipCount) { uint64 id = GetUniqueId(); APT_ASSERT(!Find(id)); // id collision TextureAtlas* ret = new TextureAtlas(id, "", _format, _width, _height, _mipCount); ret->setNamef("%llu", id); Use((Texture*&)ret); return ret; } void TextureAtlas::Destroy(TextureAtlas*& _inst_) { APT_ASSERT(_inst_); TextureAtlas* inst = _inst_; // make a copy because Unuse will nullify _inst_ Release((Texture*&)_inst_); if (inst->getRefCount() == 0) { APT_ASSERT(false); // \todo this is a double delete - Release() is also deleting the object delete inst; } } TextureAtlas::Region* TextureAtlas::alloc(GLsizei _width, GLsizei _height) { Node* node = insert(m_root, _width, _height); if (node) { Region* ret = m_regionPool.alloc(); ret->m_uvScale = vec2(_width, _height) * m_rsize; // note it's the requested size, not the node size ret->m_uvBias = vec2(node->m_startX, node->m_startY) * m_rsize; if (isCompressed()) { // compressed atlas, the smallest usable region is 4x4, hence the max lod is log2(w/4) ret->m_lodMax = APT_MIN((int)log2((double)(_width / 4)), (int)log2((double)(_height / 4))); } else { // uncompressed, the smallest usable region is log2(w) ret->m_lodMax = APT_MIN((int)log2((double)(_width)), (int)log2((double)(_height))); } #ifdef frm_TextureAtlas_DEBUG s_dbgRegionList.push_back(ret); #endif return ret; } return 0; } TextureAtlas::Region* TextureAtlas::alloc(const apt::Image& _img, RegionId _id) { APT_ASSERT(_img.getType() == Image::Type_2d); Region* ret = alloc((GLsizei)_img.getWidth(), (GLsizei)_img.getHeight()); GLenum srcFormat; switch (_img.getLayout()) { case Image::Layout_R: srcFormat = GL_RED; break; case Image::Layout_RG: srcFormat = GL_RG; break; case Image::Layout_RGB: srcFormat = GL_RGB; break; case Image::Layout_RGBA: srcFormat = GL_RGBA; break; default: APT_ASSERT(false); return false; }; GLenum srcType = _img.isCompressed() ? GL_UNSIGNED_BYTE : internal::DataTypeToGLenum(_img.getImageDataType()); int mipMax = APT_MIN(APT_MIN((int)getMipCount(), (int)_img.getMipmapCount()), ret->m_lodMax + 1); for (int mip = 0; mip < mipMax; ++mip) { if (_img.isCompressed()) { // \hack, see Texture.h srcType = (GLenum)_img.getRawImageSize(mip); } upload(*ret, _img.getRawImage(0, mip), srcFormat, srcType, mip); } if (_id != 0) { m_regionMap.push_back(RegionRef()); m_regionMap.back().m_id = _id; m_regionMap.back().m_region = ret; m_regionMap.back().m_refCount = 1; } return ret; } void TextureAtlas::free(Region*& _region_) { APT_ASSERT(_region_); #ifdef APT_DEBUG for (auto it = m_regionMap.begin(); it != m_regionMap.end(); ++it) { if (it->m_region == _region_) { APT_ASSERT(false); // named regions must be freed via unuseFree() } } #endif Node* node = find(*_region_); APT_ASSERT(node); remove(node); m_regionPool.free(_region_); _region_ = 0; } TextureAtlas::Region* TextureAtlas::findUse(RegionId _id) { for (auto it = m_regionMap.begin(); it != m_regionMap.end(); ++it) { if (it->m_id == _id) { ++it->m_refCount; return it->m_region; } } return 0; // not found } void TextureAtlas::unuseFree(Region*& _region_) { for (auto it = m_regionMap.begin(); it != m_regionMap.end(); ++it) { if (it->m_region == _region_) { if (--it->m_refCount == 0) { m_regionMap.erase(it); free(_region_); } _region_ = 0; // always null the ptr return; } } APT_ASSERT(false); // region not found, didn't set the region name via alloc()? } void TextureAtlas::upload(const Region& _region, const void* _data, GLenum _dataFormat, GLenum _dataType, GLint _mip) { APT_ASSERT(_mip < getMipCount()); GLsizei x = (GLsizei)(_region.m_uvBias.x * (float)getWidth()); GLsizei y = (GLsizei)(_region.m_uvBias.y * (float)getHeight()); GLsizei w = (GLsizei)(_region.m_uvScale.x * (float)getWidth()); GLsizei h = (GLsizei)(_region.m_uvScale.y * (float)getHeight()); GLsizei div = (GLsizei)pow(2.0, (double)_mip); w = w / div; h = h / div; x = x / div; y = y / div; setSubData(x, y, 0, w, h, 0, _data, _dataFormat, _dataType, _mip); } // PROTECTED TextureAtlas::TextureAtlas( uint64 _id, const char* _name, GLenum _format, GLsizei _width, GLsizei _height, GLsizei _mipCount ) : Texture(_id, _name, GL_TEXTURE_2D, _width, _height, 0, 0, _mipCount, _format) , m_regionPool(256) { m_rsize = 1.0f / vec2(getWidth(), getHeight()); // init allocator m_nodePool = new Pool<Node>(128); m_root = m_nodePool->alloc(Node(0)); m_root->m_startX = m_root->m_startY = 0; m_root->m_sizeX = getWidth(); m_root->m_sizeY = getHeight(); } TextureAtlas::~TextureAtlas() { // destroy allocator m_nodePool->free(m_root); delete m_nodePool; } // PRIVATE TextureAtlas::Node* TextureAtlas::insert(Node* _root, uint16 _sizeX, uint16 _sizeY) { if (!_root->isEmpty()) { return 0; } if (_root->isLeaf()) { // node is too small if (_root->m_sizeX < _sizeX || _root->m_sizeY < _sizeY) { return 0; } // node is best fit uint16 nextSizeX = _root->m_sizeX / 2; uint16 nextSizeY = _root->m_sizeY / 2; if (nextSizeX < _sizeX || nextSizeY < _sizeY) { _root->m_isEmpty = false; return _root; } // subdivide the node // +---+---+ // | 0 | 1 | // +---+---+ // | 3 | 2 | // +---+---+ for (int i = 0; i < 4; ++i) { _root->m_children[i] = m_nodePool->alloc(Node(_root)); _root->m_children[i]->m_sizeX = nextSizeX; _root->m_children[i]->m_sizeY = nextSizeY; } _root->m_children[0]->m_startX = _root->m_startX; _root->m_children[0]->m_startY = _root->m_startY; _root->m_children[1]->m_startX = _root->m_startX + nextSizeX; _root->m_children[1]->m_startY = _root->m_startY; _root->m_children[2]->m_startX = _root->m_startX + nextSizeX; _root->m_children[2]->m_startY = _root->m_startY + nextSizeY; _root->m_children[3]->m_startX = _root->m_startX; _root->m_children[3]->m_startY = _root->m_startY + nextSizeY; return insert(_root->m_children[0], _sizeX, _sizeY); } else { Node* ret = 0; for (int i = 0; i < 4; ++i) { ret = insert(_root->m_children[i], _sizeX, _sizeY); if (ret != 0) { break; } } return ret; } } void TextureAtlas::remove(Node*& _node_) { APT_ASSERT(_node_->isLeaf()); _node_->m_isEmpty = true; Node* parent = _node_->m_parent; // remove parent if all children are empty leaves for (int i = 0; i < 4; ++i) { bool canRemove = parent->m_children[i]->isEmpty() && parent->m_children[i]->isLeaf(); if (!canRemove) { return; } } for (int i = 0; i < 4; ++i) { m_nodePool->free(parent->m_children[i]); parent->m_children[i] = 0; } if (parent != m_root) { remove(parent); } } // \todo improve find(), search for the node corner rather than the node center TextureAtlas::Node* TextureAtlas::find(const Region& _region) { // convert region -> node center uint16 startX = (uint16)(_region.m_uvBias.x * (float)getWidth()); uint16 startY = (uint16)(_region.m_uvBias.y * (float)getHeight()); uint16 sizeX = (uint16)(_region.m_uvScale.x * (float)getWidth()); uint16 sizeY = (uint16)(_region.m_uvScale.y * (float)getHeight()); uint16 originX = startX + sizeX / 2; uint16 originY = startY + sizeY / 2; return find(m_root, originX, originY); } TextureAtlas::Node* TextureAtlas::find(Node* _root, uint16 _originX, uint16 _originY) { uint16 x0 = _root->m_startX; uint16 y0 = _root->m_startY; uint16 x1 = x0 + _root->m_sizeX; uint16 y1 = y0 + _root->m_sizeY; if (_originX >= x0 && _originX <= x1 && _originY >= y0 && _originY <= y1) { if (_root->isLeaf()) { return _root; } for (int i = 0; i < 4; ++i) { Node* ret = find(_root->m_children[i], _originX, _originY); if (ret) { return ret; } } } return 0; } #ifdef frm_TextureAtlas_DEBUG static const ImU32 kDbgColorBackground = ImColor(0.1f, 0.1f, 0.1f, 1.0f); static const ImU32 kDbgColorLines = ImColor(1.0f, 1.0f, 1.0f, 1.0f); static const float kDbgLineThickness = 1.0f; void TextureAtlas::debug() { ImDrawList* drawList = ImGui::GetWindowDrawList(); const vec2 drawSize = ImGui::GetContentRegionAvail(); const vec2 drawStart = vec2(ImGui::GetWindowPos()) + vec2(ImGui::GetCursorPos()); const vec2 drawEnd = drawStart + drawSize; drawList->AddRectFilled(drawStart, drawStart + drawSize, kDbgColorBackground); const vec2 txSize = vec2(getWidth(), getHeight()); const vec2 buttonStart = ImGui::GetCursorPos(); for (int i = 0; i < s_dbgRegionList.size(); ++i) { ImGui::PushID(i); vec2 start = s_dbgRegionList[i]->m_uvBias * drawSize; vec2 size = s_dbgRegionList[i]->m_uvScale * drawSize; ImGui::SetCursorPos(buttonStart + start); if (ImGui::Button("", size)) { free(s_dbgRegionList[i]); s_dbgRegionList.erase(s_dbgRegionList.begin() + i); } else { if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text("Uv Bias: %1.2f, %1.2f", s_dbgRegionList[i]->m_uvBias.x, s_dbgRegionList[i]->m_uvBias.y); ImGui::Text("Uv Scale: %1.2f, %1.2f", s_dbgRegionList[i]->m_uvScale.x, s_dbgRegionList[i]->m_uvScale.y); ImGui::Text("Max Lod: %d", s_dbgRegionList[i]->m_lodMax); ImGui::EndTooltip(); } } ImGui::PopID(); } drawList->AddLine(vec2(drawStart.x, drawStart.y), vec2(drawEnd.x, drawStart.y), kDbgColorLines, kDbgLineThickness); drawList->AddLine(vec2(drawEnd.x, drawStart.y), vec2(drawEnd.x, drawEnd.y), kDbgColorLines, kDbgLineThickness); drawList->AddLine(vec2(drawEnd.x, drawEnd.y), vec2(drawStart.x, drawEnd.y), kDbgColorLines, kDbgLineThickness); drawList->AddLine(vec2(drawStart.x, drawEnd.y), vec2(drawStart.x, drawStart.y), kDbgColorLines, kDbgLineThickness); debugDrawNode(m_root, drawStart, drawSize); } void TextureAtlas::debugDrawNode(const Node* _node, const vec2& _drawStart, const vec2& _drawSize) { if (!_node->isLeaf()) { ImDrawList* drawList = ImGui::GetWindowDrawList(); vec2 a, b; a = vec2((float)(_node->m_startX + _node->m_sizeX / 2), (float)(_node->m_startY )) * m_rsize; b = vec2((float)(_node->m_startX + _node->m_sizeX / 2), (float)(_node->m_startY + _node->m_sizeY)) * m_rsize; drawList->AddLine(_drawStart + a * _drawSize, _drawStart + b * _drawSize, kDbgColorLines, kDbgLineThickness); a = vec2((float)(_node->m_startX ), (float)(_node->m_startY + _node->m_sizeY / 2)) * m_rsize; b = vec2((float)(_node->m_startX + _node->m_sizeX), (float)(_node->m_startY + _node->m_sizeY / 2)) * m_rsize; drawList->AddLine(_drawStart + a * _drawSize, _drawStart + b * _drawSize, kDbgColorLines, kDbgLineThickness); for (int i = 0; i < 4; ++i) { debugDrawNode(_node->m_children[i], _drawStart, _drawSize); } } } #endif // frm_TextureAtlas_DEBUG
29.827848
119
0.652775
CPau
039ddd9c06d91ad456c52f2731f6fe4ddb61526c
765
cpp
C++
tests/lexy/input/base.cpp
netcan/lexy
775e3d6bf1169ce13b08598d774e707c253f0792
[ "BSL-1.0" ]
null
null
null
tests/lexy/input/base.cpp
netcan/lexy
775e3d6bf1169ce13b08598d774e707c253f0792
[ "BSL-1.0" ]
null
null
null
tests/lexy/input/base.cpp
netcan/lexy
775e3d6bf1169ce13b08598d774e707c253f0792
[ "BSL-1.0" ]
null
null
null
// Copyright (C) 2020 Jonathan Müller <[email protected]> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #include <lexy/input/base.hpp> #include <doctest/doctest.h> #include <lexy/input/string_input.hpp> TEST_CASE("partial_reader()") { auto input = lexy::zstring_input("abc"); auto end = input.end() - 1; auto partial = lexy::partial_reader(input.reader(), end); CHECK(partial.cur() == input.begin()); CHECK(partial.peek() == 'a'); CHECK(!partial.eof()); partial.bump(); CHECK(partial.peek() == 'b'); CHECK(!partial.eof()); partial.bump(); CHECK(partial.peek() == lexy::default_encoding::eof()); CHECK(partial.eof()); }
26.37931
69
0.654902
netcan
03a26d793d446d7efba14b9a7df18e1e3221ec17
1,060
cpp
C++
example-8/src/ClientWin.cpp
GGolbik/basics-cpp
37466e7fa03b428093055a269e2ee96b8e685b82
[ "MIT" ]
null
null
null
example-8/src/ClientWin.cpp
GGolbik/basics-cpp
37466e7fa03b428093055a269e2ee96b8e685b82
[ "MIT" ]
null
null
null
example-8/src/ClientWin.cpp
GGolbik/basics-cpp
37466e7fa03b428093055a269e2ee96b8e685b82
[ "MIT" ]
null
null
null
#ifdef _WIN32 // _WIN32 marco is defined for both 32-bit and 64-bit environments // windows code goes here #include <iostream> #include "Client.h" namespace ggolbik { namespace cpp { namespace tls { Client::Client(std::string serverAddress, unsigned short port) : serverAddress{serverAddress}, port{port} {} Client::~Client() { this->close(); } bool Client::open() { std::cerr << "NOT IMPLEMENTED" << std::endl; return false; } void Client::close() {} bool Client::closeSocket() { return false; } /** * ssize_t write(int fd, const void *buf, size_t count); */ bool Client::write(const byte data[], size_t length) { return false; } bool Client::readString(std::string &message) { return false; } int Client::tryReadString(std::string &message) { return -1; } int Client::tryReadStringTls(std::string &message) { return -1; } bool Client::readStringTls(std::string &message) { return false; } bool Client::writeTls(const byte data[], size_t length) { return false; } } // namespace tls } // namespace cpp } // namespace ggolbik #endif
23.555556
73
0.695283
GGolbik
03a64b7c25c08d22ff6ef2a03d9014ce1515f1fe
700
hpp
C++
link.hpp
helm100/2d-cdt
e79044451f0f84c1b0ff5c3290a61b5f24df45c0
[ "MIT" ]
3
2021-01-11T14:28:27.000Z
2022-02-08T14:19:30.000Z
link.hpp
helm100/2d-cdt
e79044451f0f84c1b0ff5c3290a61b5f24df45c0
[ "MIT" ]
1
2021-02-26T12:40:53.000Z
2021-02-26T12:40:53.000Z
link.hpp
helm100/2d-cdt
e79044451f0f84c1b0ff5c3290a61b5f24df45c0
[ "MIT" ]
1
2021-03-02T16:03:14.000Z
2021-03-02T16:03:14.000Z
// Copyright 2020 Joren Brunekreef and Andrzej Görlich #ifndef LINK_HPP_ #define LINK_HPP_ #include "pool.hpp" class Vertex; class Triangle; class Link : public Pool<Link> { public: static const unsigned pool_size = 10000000; Pool<Vertex>::Label getVertexFinal(); Pool<Vertex>::Label getVertexInitial(); Pool<Triangle>::Label getTrianglePlus(); Pool<Triangle>::Label getTriangleMinus(); void setVertices(Pool<Vertex>::Label vi, Pool<Vertex>::Label vf); void setTriangles(Pool<Triangle>::Label tp, Pool<Triangle>::Label tm); bool isTimelike(); bool isSpacelike(); private: Pool<Vertex>::Label vi, vf; // vertices Pool<Triangle>::Label tp, tm; // triangles }; #endif // LINK_HPP_
22.580645
71
0.732857
helm100
03a7a16d727583b5c47cc642f4e617a104217942
1,141
cpp
C++
examples/Primitives/src/main.cpp
jamjarlabs/JamJarNative
ed8aea9cbd3f1eed3eb49c7da0df50eea87e880e
[ "MIT" ]
1
2022-03-28T02:26:23.000Z
2022-03-28T02:26:23.000Z
examples/Primitives/src/main.cpp
jamjarlabs/JamJarNative
ed8aea9cbd3f1eed3eb49c7da0df50eea87e880e
[ "MIT" ]
103
2020-02-24T23:52:58.000Z
2021-04-18T21:00:50.000Z
examples/Primitives/src/main.cpp
jamjarlabs/JamJarNative
ed8aea9cbd3f1eed3eb49c7da0df50eea87e880e
[ "MIT" ]
1
2021-05-20T22:29:44.000Z
2021-05-20T22:29:44.000Z
#include "emscripten/html5.h" #include "entity/entity_manager.hpp" #include "game.hpp" #include "message/message_bus.hpp" #include "message/message_payload.hpp" #include "primitives.hpp" #include "standard/2d/interpolation/interpolation_system.hpp" #include "standard/2d/primitive/primitive_system.hpp" #include "standard/2d/webgl2/webgl2_system.hpp" #include "standard/file_texture/file_texture_system.hpp" #include "standard/sdl2_input/sdl2_input_system.hpp" #include "window.hpp" #include <SDL2/SDL.h> #include <iostream> #include <memory> #include <stdlib.h> #include <string> int main(int argc, char *argv[]) { auto window = JamJar::GetWindow("Primitives"); auto context = JamJar::GetCanvasContext(); auto messageBus = new JamJar::MessageBus(); new JamJar::EntityManager(messageBus); auto game = new Primitives(messageBus); new JamJar::Standard::_2D::WebGL2System(messageBus, window, context); new JamJar::Standard::_2D::InterpolationSystem(messageBus); new JamJar::Standard::_2D::PrimitiveSystem(messageBus); new JamJar::Standard::SDL2InputSystem(messageBus); game->Start(); return 0; }
32.6
73
0.751096
jamjarlabs
03a91fe7f6ffd57ba51261e671bb6adbae3f5b27
73,798
cpp
C++
2006/samples/reactors/DWFMetaData/DWFAPI.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
1
2021-06-25T02:58:47.000Z
2021-06-25T02:58:47.000Z
2006/samples/reactors/DWFMetaData/DWFAPI.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
null
null
null
2006/samples/reactors/DWFMetaData/DWFAPI.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
3
2020-05-23T02:47:44.000Z
2020-10-27T01:26:53.000Z
// (C) Copyright 2004 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // DWFAPI.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include "DWFAPI.h" #include "U:\develop\global\src\coreapps\acmgdreverse\mgPublishUtils.h" #include "dbents.h" #include <stack> #include "AcDMMapi.h" #include "steelSect.h" // this is required for the custom entity CSteelSection #include "dynprops.h" TdDMMReactor *g_pDMMReactor = NULL; //TdPublishReactor *g_pPubReactor = NULL; //TdPublishUIReactor *g_pPubUIReactor = NULL; CCW_AcPublishMgdServices* g_pDxServices; bool g_bIncludeBlockInfo; std::stack<int>g_NodeStack; std::vector<unsigned long>g_entIdVec; int BlockNo = 0; bool invalidTest = true; #ifdef _DEBUG #define new DEBUG_NEW #endif CString OUTFILE(L"C:\\Current Project\\DWFAPI\\DWFs\\OutFile.txt"); HINSTANCE _hdllInstance = NULL; // // Note! // // If this DLL is dynamically linked against the MFC // DLLs, any functions exported from this DLL which // call into MFC must have the AFX_MANAGE_STATE macro // added at the very beginning of the function. // // For example: // // extern "C" BOOL PASCAL EXPORT ExportedFunction() // { // AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // normal function body here // } // // It is very important that this macro appear in each // function, prior to any calls into MFC. This means that // it must appear as the first statement within the // function, even before any object variable declarations // as their constructors may generate calls into the MFC // DLL. // // Please see MFC Technical Notes 33 and 58 for additional // details. // // CDWFAPIApp BEGIN_MESSAGE_MAP(CDWFAPIApp, CWinApp) END_MESSAGE_MAP() // CDWFAPIApp construction CDWFAPIApp::CDWFAPIApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CDWFAPIApp object CDWFAPIApp theApp; // CDWFAPIApp initialization BOOL CDWFAPIApp::InitInstance() { CWinApp::InitInstance(); return TRUE; } // This functions registers an ARX command. // It can be used to read the localized command name // from a string table stored in the resources. void AddCommand(const char* cmdGroup, const char* cmdInt, const char* cmdLoc, const int cmdFlags, const AcRxFunctionPtr cmdProc, const int idLocal=-1) { char cmdLocRes[65]; // If idLocal is not -1, it's treated as an ID for // a string stored in the resources. if (idLocal != -1) { // Load strings from the string table and register the command. ::LoadString(_hdllInstance, idLocal, cmdLocRes, 64); acedRegCmds->addCommand(cmdGroup, cmdInt, cmdLocRes, cmdFlags, cmdProc); } else // idLocal is -1, so the 'hard coded' // localized function name is used. acedRegCmds->addCommand(cmdGroup, cmdInt, cmdLoc, cmdFlags, cmdProc); } // Init this application. Register your // commands, reactors... void InitApplication() { // NOTE: DO NOT edit the following lines. //{{AFX_ARX_INIT AddCommand("DWFAPI", "dwfapi", "DWFAPI", ACRX_CMD_TRANSPARENT | ACRX_CMD_USEPICKSET,DWFAPI); //}}AFX_ARX_INIT // TODO: add your initialization functions acedPostCommandPrompt(); } // Unload this application. Unregister all objects // registered in InitApplication. void UnloadApplication() { // NOTE: DO NOT edit the following lines. //{{AFX_ARX_EXIT acedRegCmds->removeGroup("ASDKPROPERTY_INS"); //}}AFX_ARX_EXIT // TODO: clean up your application } //////////////////////////////////////////////////////////////////////////// // ObjectARX EntryPoint extern "C" AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode msg, void* pkt) { switch (msg) { case AcRx::kInitAppMsg: // Comment out the following line if your // application should be locked into memory acrxDynamicLinker->unlockApplication(pkt); acrxDynamicLinker->registerAppMDIAware(pkt); InitApplication(); acutPrintf("\nType 'DWFAPI' to run the app."); break; case AcRx::kUnloadAppMsg: UnloadApplication(); break; } return AcRx::kRetOK; } // print functions. void myPrintf(CString text, CString filename) { if (filename != "") { FILE *stream; if((stream = fopen(filename, "a+")) == NULL) { printf("\n...Output file could not be created!"); exit(0); } // write the text. fprintf(stream, text); // close the file output if opened. if(fclose(stream)) printf("\n...Output file could not be closed!"); } else printf(text); } void myPrintf(CString text) { printf(text); } //TdDMMReactor class implementation. TdDMMReactor::TdDMMReactor() { A1=false; A2=false; A3=false; A4=false; } TdDMMReactor::~TdDMMReactor() { A1=false; A2=false; A3=false; A4=false; } //wchar_t* TdDMMReactor::D2W(double value) //{ // CString str; // str.Format("%g",value); // USES_CONVERSION; // m_wchar = A2W(str); // return m_wchar; //} void TdDMMReactor::OnBeginEntity(AcDMMEntityReactorInfo * pInfo) //#4 { if (A1 == false) { myPrintf("\nTdDMMReactor::OnBeginEntity", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nTdDMMReactor::OnBeginEntity"); A1 = true; } if (g_bIncludeBlockInfo) { AcDbEntity* pEntity = pInfo->entity(); AcDbObjectId objId = pEntity->objectId(); long oldId = objId.asOldId(); unsigned long front = 0; // this is a custom entity. // assigning a property to the custom entity. if (pEntity->isKindOf(CSteelSection::desc())) { myPrintf("\nCSteelSection FOUND, assigning metadata properties to it.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nCSteelSection FOUND, assigning metadata properties to it."); CSteelSection* pSteelEnt = (CSteelSection*)pEntity; AcDMMEPlotProperties props0; AcDMMEPlotProperty prop0; prop0.SetCategory(L"Steel Section"); USES_CONVERSION; prop0.SetName(L"Section Type"); //Adesk::Int16 SType; //(CSteelSection*)pEntity->getSectionType(SType); prop0.SetValue(L"W Section"); props0.AddProperty(&prop0); prop0.SetName(L"Section Depth"); //Adesk::Int16 SType; double depth = pSteelEnt->getDepth(); m_cstr.Format("%g",depth); m_wchar = A2W(m_cstr); prop0.SetValue(m_wchar); props0.AddProperty(&prop0); prop0.SetName(L"Section Length"); //Adesk::Int16 SType; double length = pSteelEnt->getLength(); m_cstr.Format("%g",length); m_wchar = A2W(m_cstr); prop0.SetValue(m_wchar); props0.AddProperty(&prop0); prop0.SetName(L"Section Flange Width"); //Adesk::Int16 SType; double fWidth = pSteelEnt->getFlangeWidth(); m_cstr.Format("%g",fWidth); m_wchar = A2W(m_cstr); prop0.SetValue(m_wchar); props0.AddProperty(&prop0); prop0.SetName(L"Section Flange Thickness"); //Adesk::Int16 SType; double fThick = pSteelEnt->getFlangeThickness(); m_cstr.Format("%g",fThick); m_wchar = A2W(m_cstr); prop0.SetValue(m_wchar); props0.AddProperty(&prop0); prop0.SetName(L"Section Web Thickness"); //Adesk::Int16 SType; double wThick = pSteelEnt->getWebThickness(); m_cstr.Format("%g",wThick); m_wchar = A2W(m_cstr); prop0.SetValue(m_wchar); props0.AddProperty(&prop0); const wchar_t* wsUnique0 = pInfo->UniqueEntityId(); AcDMMWideString wsPropId0; // need an unique ID for properties. wsPropId0 = L"CUSTOM_ENTITY-"; wsPropId0 += wsUnique0; delete wsUnique0; props0.SetId(PCWIDESTR(wsPropId0)); pInfo->AddProperties(&props0); // add props obj to cache // Invalid value test. if (invalidTest == true) { AcDMMEPlotProperties props100; AcDMMEPlotProperty prop100; props100.AddProperty(&prop100); props100.AddProperty(NULL); pInfo->AddProperties(&props100); //DID 607332 //pInfo->AddProperties(NULL); } // to test different AcDMMProperty methods. // SetType, SetUnit, SetName, SetValue AcDMMEPlotProperty* prop00 = new AcDMMEPlotProperty(); prop00->SetName(L"Test Name"); prop00->SetValue(L"Test Value"); prop00->SetType(L"Test Type"); prop00->SetUnits(L"Test Unit"); AcDMMEPlotProperty* prop01 = prop00; // GetType, GetUnit, GetName, GetValue if(strcmp(OLE2A(prop00->GetName()), "Test Name") == 0) myPrintf("\nPassed: AcDMMEPlotProperty::SetName(), GetName() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMEPlotProperty::SetName(), GetName() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMEPlotProperty::SetName(), GetName()."); if(strcmp(OLE2A(prop00->GetValue()), "Test Value") == 0) myPrintf("\nPassed: AcDMMEPlotProperty::SetValue(), GetValue() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMEPlotProperty::SetValue(), GetValue() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMEPlotProperty::SetValue(), GetValue()"); if(strcmp(OLE2A(prop00->GetType()), "Test Type") == 0) myPrintf("\nPassed: AcDMMEPlotProperty::SetType(), GetType() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMEPlotProperty::SetType(), GetType() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMEPlotProperty::SetType(), GetType()"); if(strcmp(OLE2A(prop00->GetUnits()), "Test Unit") == 0) myPrintf("\nPassed: AcDMMEPlotProperty::SetUnits(), GetUnits() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMEPlotProperty::SetUnits(), GetUnits() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMEPlotProperty::SetUnits(), GetUnits()"); // to test different AcDMMProperties methods for testing. AcDMMEPlotProperties props00 = props0; const AcDMMEPlotPropertyVec propVec = props00.GetProperties(); //AcDMMEPlotProperty* tempProp; int noProp = propVec.size(); for (int i=0; i<=noProp; i++) { const AcDMMEPlotProperty* tempProp = props00.GetProperty(i); } // Invalid value test. if (invalidTest == true) { const AcDMMEPlotProperty* tempProp100 = props00.GetProperty(0); const AcDMMEPlotProperty* tempProp101 = props00.GetProperty(123456); const AcDMMEPlotProperty* tempProp102 = props00.GetProperty(-34); } props00.SetId(L"Partha ID"); props00.SetNamespace(L"http:\\www.autodesk.com", L"Partha Location"); AcDMMStringVec IdVec00; IdVec00.push_back(wsPropId0); props00.SetRefs(IdVec00); // Invalid value test. if (invalidTest == true) { AcDMMStringVec vec100; props00.SetRefs(vec100); } if(strcmp(OLE2A(props00.GetId()), "Partha ID") == 0) myPrintf("\nPassed: AcDMMEPlotProperties::SetId(), GetId() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMEPlotProperties::SetId(), GetId() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMEPlotProperties::SetId(), GetId()"); if(strcmp(OLE2A(props00.GetNamespaceUrl()), "http:\\www.autodesk.com") == 0) myPrintf("\nPassed: AcDMMEPlotProperties::SetNameSpace(), GetNameSpaceUrl() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMEPlotProperties::SetNameSpace(), GetNameSpaceUrl() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMEPlotProperties::SetNameSpace(), GetNameSpaceUrl()"); if(strcmp(OLE2A(props00.GetNamespaceLocation()), "Partha Location") == 0) myPrintf("\nPassed: AcDMMEPlotProperties::SetNameSpace(), GetNameSpaceLocation() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMEPlotProperties::SetNameSpace(), GetNameSpaceLocation() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMEPlotProperties::SetNameSpace(), GetNameSpaceLocation()"); if(props00.GetRefs()->size() == IdVec00.size()) myPrintf("\nPassed: AcDMMEPlotProperties::SetRef(), GetRef() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMEPlotProperties::SetRef(), GetRef() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMEPlotProperties::SetRef(), GetRef()"); // AcDMMWideString. // for testing only will not be written AcDMMWideString wsTemp(wsPropId0); size_t len0 = wsTemp.GetLength(); if (wsTemp.GetLength() == 57) myPrintf("\nAcDMMWideString::GetLength() returns correcft length.", OUTFILE); else myPrintf("\nAcDMMWideString::GetLength() does not return correct length.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMWideString::GetLength()"); if (!wsTemp.IsEmpty()) wsTemp.Empty(); if (wsTemp.IsEmpty()) myPrintf("\nAcDMMWideString::IsEmpty(), Empty() works fine", OUTFILE); else myPrintf("\nAcDMMWideString::IsEmpty(), Empty() do not work fine", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMWideString::IsEmpty(), Empty()"); // string Vector AcDMMStringVec IdVec0; IdVec0.push_back(wsPropId0); int nodeId0 = 0; const AcDMMNode* node0; // check to see if this node already assigned if(!pInfo->GetEntityNode(objId, front, nodeId0)) { nodeId0 = pInfo->GetNextAvailableNodeId(); node0 = new AcDMMNode(nodeId0, L"CUSTOM_ENTITY"); bool bret; bret = pInfo->AddNodeToMap(objId, front, nodeId0); // Invalid value test. if (invalidTest == true) { int NodeId100; unsigned long front100 = g_entIdVec.front(); AcDbObjectId objId100 = pEntity->objectId(); pInfo->AddNodeToMap(0, front100, NodeId100); pInfo->AddNodeToMap(objId100, 0, NodeId100); pInfo->AddNodeToMap(objId100, -3, NodeId100); pInfo->AddNodeToMap(objId100, front100, 0); pInfo->AddNodeToMap(objId100, front100, 123456); pInfo->AddNodeToMap(objId100, front100, -4); } ASSERT(bret); } else { // use the existing node. node0 = pInfo->GetNode(nodeId0); // Invalid value test. if (invalidTest == true) { pInfo->GetNode(0); pInfo->GetNode(100000); pInfo->GetNode(-10); } //bool bret; //bret = pInfo->AddNodeToMap(objId, front, nodeId0); //ASSERT(bret); } // Invalid value test. if (invalidTest == true) { int iNodeId100; unsigned long front100 = g_entIdVec.front(); AcDbObjectId objId100 = pEntity->objectId(); pInfo->GetEntityNode(0, front100, iNodeId100); pInfo->GetEntityNode(objId100, 0, iNodeId100); pInfo->GetEntityNode(objId100, -3, iNodeId100); } ASSERT(0 != nodeId0); if(0 != nodeId0) { g_NodeStack.push(nodeId0); //associate the properties with the node. pInfo->AddPropertiesIds(&IdVec0, (AcDMMNode&)*node0); // Invalid value test. if (invalidTest == true) { AcDMMStringVec IdVec100; const AcDMMNode* node100; pInfo->AddPropertiesIds(&IdVec100, (AcDMMNode&)*node0); // DID 607346 //pInfo->AddPropertiesIds(NULL, (AcDMMNode&)*node0); const AcDMMNode* node101 = NULL; pInfo->AddPropertiesIds(&IdVec100, (AcDMMNode&)*node101); // DID 607346 //pInfo->AddPropertiesIds(NULL, (AcDMMNode&)*node101); } } } if (pEntity->isKindOf(AcDbBlockReference::desc()) && (g_pDxServices != NULL)) // block { myPrintf("\nBlock FOUND, assigning metadata properties to it.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nBlock FOUND, assigning metadata properties to it"); // get the block name. AcDbBlockReference* pBlkRef = 0; char* blkName = 0; if(acdbOpenObject(pBlkRef, objId, AcDb::kForRead) == Acad::eOk) { AcDbBlockTableRecord* pTblRec = 0; if(acdbOpenObject(pTblRec, pBlkRef->blockTableRecord(), AcDb::kForRead) == Acad::eOk) { pTblRec->getName(blkName); pTblRec->close(); } pBlkRef->close(); } // get blocks properties from DX api. g_entIdVec.push_back(oldId); front = g_entIdVec.front(); AcDMMEPlotPropertyVec propVec; // FIRST SET OF PROPERTIES. AcDMMEPlotProperties props; g_pDxServices->get_block_properties(objId, &propVec); //add properties to prop objects. AcDMMEPlotPropertyVec::const_iterator iter = propVec.begin(); // get all the standard meta properties and write them in the new // property collection. while (iter != propVec.end()) { AcDMMEPlotProperty prop = (*iter++); props.AddProperty(&prop); } // write a custom property. AcDMMEPlotProperty prop1(L"ParthaProperty", L"ParthaValue"); USES_CONVERSION; if (blkName != "") prop1.SetCategory(A2W(blkName)); else prop1.SetCategory(L"Custom Catagory1"); props.AddProperty(&prop1); const wchar_t* wsUnique = pInfo->UniqueEntityId(); AcDMMWideString wsPropId; // need an unique ID for properties. wsPropId = L"PARTHA-"; wsPropId += wsUnique; delete wsUnique; props.SetId(PCWIDESTR(wsPropId)); pInfo->AddProperties(&props); // add props obj to cache // Invalid value test. if (invalidTest == true) { AcDMMEPlotProperties props100; AcDMMEPlotProperty prop100; props100.AddProperty(&prop100); props100.AddProperty(NULL); pInfo->AddProperties(&props100); //DID 607332 //pInfo->AddProperties(NULL); } // string Vector AcDMMStringVec IdVec; IdVec.push_back(wsPropId); int nodeId = 0; const AcDMMNode* node; // check to see if this node already assigned if(!pInfo->GetEntityNode(objId, front, nodeId)) { // create a node for this entity. nodeId = pInfo->GetNextAvailableNodeId(); node = new AcDMMNode(nodeId, L"PARTHA"); bool bret; bret = pInfo->AddNodeToMap(objId, front, nodeId); ASSERT(bret); // Invalid value test. if (invalidTest == true) { int NodeId100; unsigned long front100 = g_entIdVec.front(); AcDbObjectId objId100 = pEntity->objectId(); pInfo->AddNodeToMap(0, front100, NodeId100); pInfo->AddNodeToMap(objId100, 0, NodeId100); pInfo->AddNodeToMap(objId100, -3, NodeId100); pInfo->AddNodeToMap(objId100, front100, 0); pInfo->AddNodeToMap(objId100, front100, 123456); pInfo->AddNodeToMap(objId100, front100, -4); } } else { // use the existing node. node = pInfo->GetNode(nodeId); // Invalid value test. if (invalidTest == true) { pInfo->GetNode(0); pInfo->GetNode(100000); pInfo->GetNode(-10); } } // Invalid value test. if (invalidTest == true) { int iNodeId100; unsigned long front100 = g_entIdVec.front(); AcDbObjectId objId100 = pEntity->objectId(); pInfo->GetEntityNode(0, front100, iNodeId100); pInfo->GetEntityNode(objId100, 0, iNodeId100); pInfo->GetEntityNode(objId100, -3, iNodeId100); } ASSERT(0 != nodeId); if (0 != nodeId) { g_NodeStack.push(nodeId); // associate the properties with the node. pInfo->AddPropertiesIds(&IdVec, (AcDMMNode &)*node); // Invalid value test. if (invalidTest == true) { AcDMMStringVec IdVec100; const AcDMMNode* node100; pInfo->AddPropertiesIds(&IdVec100, (AcDMMNode&)*node100); // DID 607346 //pInfo->AddPropertiesIds(NULL, (AcDMMNode&)*node100); const AcDMMNode* node101 = NULL; pInfo->AddPropertiesIds(&IdVec100, (AcDMMNode&)*node101); // DID 607346 //pInfo->AddPropertiesIds(NULL, (AcDMMNode&)*node101);; } } // AcDMMNode::SetNodeNumber(), nodeNumber() // this node will not be added to the map. // this is for testing purpose only. int xNodeId = nodeId+1; AcDMMNode* node1 = new AcDMMNode(nodeId, L"PARTHA01"); node1->SetNodeNumber(xNodeId); if(node1->nodeNumber() == xNodeId) myPrintf("\nPassed: AcDMMNode::SetNodeNumber(), nodeMumber() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMNode::SetNodeNumber(), nodeNumber() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMNode::SetNodeNumber(), nodeMumber()"); // Invalid value test. if (invalidTest == true) { AcDMMNode* node100 = new AcDMMNode(nodeId, L"!@#$%^&*"); node100->SetNodeNumber(0); node100->SetNodeNumber(12345); node100->SetNodeNumber(-34); } //AcDMMNode::SetNodeName(), NodeName() wchar_t* name = L"PARTHA02"; node1->SetNodeName(name); if(strcmp(OLE2A(node1->nodeName()), "PARTHA02") == 0) myPrintf("\nPassed: AcDMMNode::SetNodeName(), nodeName() work fine.", OUTFILE); else myPrintf("\nFailed: AcDMMNode::SetNodeName(), nodeNAme() do not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMNode::SetNodeName(), nodeName()"); // Invalid value test. if (invalidTest == true) { node1->SetNodeName(L""); } // SECOND SET OF PROPERTIES. AcDMMEPlotProperties props2; AcDMMEPlotProperty prop2(L"BappaProperty", L"BappaValue"); if (blkName != "") prop2.SetCategory(A2W(blkName)); else prop2.SetCategory(L"Custom Catagory2"); props2.AddProperty(&prop2); const wchar_t* wsUnique2 = pInfo->UniqueEntityId(); AcDMMWideString wsPropId2; // need an unique ID for properties. wsPropId2 = L"BAPPA-"; wsPropId2 += wsUnique2; delete wsUnique2; props2.SetId(PCWIDESTR(wsPropId2)); pInfo->AddProperties(&props2); // add props obj to cache // Invalid value test. if (invalidTest == true) { AcDMMEPlotProperties props100; AcDMMEPlotProperty prop100; props100.AddProperty(&prop100); props100.AddProperty(NULL); pInfo->AddProperties(&props100); //DID 607332 //pInfo->AddProperties(NULL); } // string Vector AcDMMStringVec IdVec2; IdVec2.push_back(wsPropId2); int nodeId2 = 0; const AcDMMNode* node2; AcDMMNode* node02 = NULL; bool whichOne = true; // check to see if this node already assigned if(!pInfo->GetEntityNode(objId, front, nodeId2)) { // create a node for this entity. nodeId2 = pInfo->GetNextAvailableNodeId(); // try to add the node in a different way. //node2 = new AcDMMNode(nodeId2, L"BAPPA"); //bool bret2; //bret2 = pInfo->AddNodeToMap(objId, front, nodeId2); node02->SetNodeNumber(nodeId2); // Invalid value test. if (invalidTest == true) { AcDMMNode* node100 = new AcDMMNode(nodeId, L"!@#$%^&*"); node100->SetNodeNumber(0); node100->SetNodeNumber(12345); node100->SetNodeNumber(-34); } node02->SetNodeName(L"BAPPA"); // Invalid value test. if (invalidTest == true) { node02->SetNodeName(L""); } pInfo->SetCurrentNode(nodeId2, 0); // Invalid value test. if (invalidTest == true) { pInfo->SetCurrentNode(0, 0); pInfo->SetCurrentNode(-3, 0); pInfo->SetCurrentNode(0, -5); } whichOne = true; AcDMMNode node03; pInfo->GetCurrentEntityNode(node03, 0); /*if (node03.nodeNumber != node02->nodeNumber()) myPrintf("\nFailed: AcDMMEntityReactorInfo::GetCurrentEntityNode() does not get the correct entity node.", OUTFILE);*/ //ASSERT(bret2); // Invalid value test. if (invalidTest == true) { AcDMMNode node100; pInfo->GetCurrentEntityNode(node100, 3345); pInfo->GetCurrentEntityNode(node100, -2); } } else { // use the existing node. node2 = pInfo->GetNode(nodeId2); // Invalid value test. if (invalidTest == true) { pInfo->GetNode(0); pInfo->GetNode(100000); pInfo->GetNode(-10); } pInfo->SetNodeName(nodeId2, L"BAPPA01"); // Invalid value test. if (invalidTest == true) { int node100; pInfo->SetNodeName(node100, L"xx"); node100=12; pInfo->SetNodeName(node100, L""); } pInfo->SetCurrentNode(nodeId2, 0); // Invalid value test. if (invalidTest == true) { pInfo->SetCurrentNode(0, 0); pInfo->SetCurrentNode(-3, 0); pInfo->SetCurrentNode(0, -5); } whichOne = false; AcDMMNode node03; pInfo->GetCurrentEntityNode(node03, 0); /*if (node03.nodeNumber != node2->nodeNumber()) myPrintf("\nFailed: AcDMMEntityReactorInfo::GetCurrentEntityNode() does not get the correct entity node.", OUTFILE);*/ // Invalid value test. if (invalidTest == true) { AcDMMNode node100; pInfo->GetCurrentEntityNode(node100, 3098); pInfo->GetCurrentEntityNode(node100, -2); } } // Invalid value test. if (invalidTest == true) { int iNodeId100; unsigned long front100 = g_entIdVec.front(); AcDbObjectId objId100 = pEntity->objectId(); pInfo->GetEntityNode(0, front100, iNodeId100); pInfo->GetEntityNode(objId100, 0, iNodeId100); pInfo->GetEntityNode(objId100, -3, iNodeId100); } ASSERT(0 != nodeId2); if (0 != nodeId2) { g_NodeStack.push(nodeId2); // associate the properties with the node. if (whichOne == false) pInfo->AddPropertiesIds(&IdVec2, (AcDMMNode &)*node2); else pInfo->AddPropertiesIds(&IdVec2, (AcDMMNode &)*node02); // Invalid value test. if (invalidTest == true) { AcDMMStringVec IdVec100; const AcDMMNode* node100; pInfo->AddPropertiesIds(&IdVec100, (AcDMMNode&)*node100); // DID 607346 //pInfo->AddPropertiesIds(NULL, (AcDMMNode&)*node100); const AcDMMNode* node101 = NULL; pInfo->AddPropertiesIds(&IdVec100, (AcDMMNode&)*node101); // DID 607346 //pInfo->AddPropertiesIds(NULL, (AcDMMNode&)*node101); } } } else { if (!g_NodeStack.empty()) { //ASSERT(!g_entIdVec.empty()); int iNodeId = g_NodeStack.top(); front = g_entIdVec.front(); //if no one else has assigned a Node Id for this entity if(!pInfo->GetEntityNode(objId, front, iNodeId)) { // associate this entity with the top node on the stack bool bret; bret = pInfo->AddNodeToMap(objId, front, iNodeId); ASSERT(bret); // Invalid value test. if (invalidTest == true) { int NodeId100; unsigned long front100 = g_entIdVec.front(); AcDbObjectId objId100 = pEntity->objectId(); pInfo->AddNodeToMap(0, front100, NodeId100); pInfo->AddNodeToMap(objId100, 0, NodeId100); pInfo->AddNodeToMap(objId100, -3, NodeId100); pInfo->AddNodeToMap(objId100, front100, 0); pInfo->AddNodeToMap(objId100, front100, 123456); pInfo->AddNodeToMap(objId100, front100, -4); } } // Invalid value test. if (invalidTest == true) { int iNodeId100; unsigned long front100 = g_entIdVec.front(); AcDbObjectId objId100 = pEntity->objectId(); pInfo->GetEntityNode(0, front100, iNodeId100); pInfo->GetEntityNode(objId100, 0, iNodeId100); pInfo->GetEntityNode(objId100, -3, iNodeId100); } if(pEntity->isKindOf(AcDbBlockEnd::desc())) { g_NodeStack.pop(); g_entIdVec.pop_back(); } } } pInfo->flush(); // this is a test to Job Cancled methods. Make sure when you un-comment these, // you hit the TdPublishReactor::OnCancelledOrFailedPublishing reactor. //pInfo->cancelTheJob(); //if (!pInfo->isCancelled()) // myPrintf("\nThe job is correctly cancled.", OUTFILE); } } void TdDMMReactor::OnBeginSheet(AcDMMSheetReactorInfo * pInfo) //#3 { if (A2 == false) { myPrintf("\nTdDMMReactor::OnBeginSheet", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nTdDMMReactor::OnBeginSheet"); A2 = true; } // be sure to start with empty stack while (!g_NodeStack.empty()) g_NodeStack.pop(); if (!pInfo->isModelLayout()) // Layout { // add a resource AcDMMResourceInfo res(L"ParthaSheetResource", L"text", L"C:\\Current Project\\DWFAPI\\DWFs\\Reflection Paper.doc"); AcDMMResourceVec resVec; resVec.push_back(res); pInfo->AddPageResources(resVec); // Invalid value test. if (invalidTest == true) { AcDMMResourceVec pVec100; pInfo->AddPageResources(pVec100); } // add a property AcDMMEPlotPropertyVec propVec; //AcDMMEPlotProperty prop(L"ParthaSheetProperty", L"ParthaSheetValue"); //prop.SetCategory(L"ParthaSheetProp"); //propVec.push_back(prop); // plotLayoutId() long plotLayId = pInfo->plotLayoutId().asOldId(); AcDMMEPlotProperty propLayId(L"Layout ID", (wchar_t*)plotLayId); propLayId.SetCategory(L"ParthaSheetProp"); propVec.push_back(propLayId); // plotArea() AcDMMSheetReactorInfo::PlotArea plotarea = pInfo->plotArea(); AcDMMEPlotProperty propPlotArea; propPlotArea.SetName(L"Plot Area"); switch (plotarea) { case AcDMMSheetReactorInfo::PlotArea::kDisplay: propPlotArea.SetValue(L"Plot display, the visible portion of the picture."); break; case AcDMMSheetReactorInfo::PlotArea::kExtents: propPlotArea.SetValue(L"Plot extents, i.e. all geometry."); break; case AcDMMSheetReactorInfo::PlotArea::kLimits: propPlotArea.SetValue(L"Plot the limits set by the user."); break; case AcDMMSheetReactorInfo::PlotArea::kView: propPlotArea.SetValue(L"Plot a named view."); break; case AcDMMSheetReactorInfo::PlotArea::kWindow: propPlotArea.SetValue(L"Plot a user specified window - a rectangular area."); break; case AcDMMSheetReactorInfo::PlotArea::kLayout: propPlotArea.SetValue(L"Plot the extents of the layout."); break; } propPlotArea.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotArea); //plotRotation(). AcDMMSheetReactorInfo::PlotRotation plotrotation = pInfo->plotRotation(); AcDMMEPlotProperty propPlotRotation; propPlotRotation.SetName(L"Plot Rotation"); switch (plotrotation) { case AcDMMSheetReactorInfo::PlotRotation::k0degrees: propPlotRotation.SetValue(L"0 degrees camera rotation."); break; case AcDMMSheetReactorInfo::PlotRotation::k180degrees: propPlotRotation.SetValue(L"90 degrees camera rotation."); break; case AcDMMSheetReactorInfo::PlotRotation::k270degrees: propPlotRotation.SetValue(L"180 degrees camera rotation, i.e., plot upside down."); break; case AcDMMSheetReactorInfo::PlotRotation::k90degrees: propPlotRotation.SetValue(L"270 degrees camera rotation."); break; } propPlotRotation.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotRotation); // plotMediaUnit(). AcDMMSheetReactorInfo::PlotMediaUnits plotmediaunits = pInfo->plotMediaUnits(); AcDMMEPlotProperty propPlotMediaUnits; propPlotMediaUnits.SetName(L"Plot Rotation"); switch (plotmediaunits) { case AcDMMSheetReactorInfo::PlotMediaUnits::kInches: propPlotMediaUnits.SetValue(L"Using imperial units."); break; case AcDMMSheetReactorInfo::PlotMediaUnits::kMillimeters: propPlotMediaUnits.SetValue(L"Using metric units."); break; case AcDMMSheetReactorInfo::PlotMediaUnits::kPixels: propPlotMediaUnits.SetValue(L"Using dimensionaless raster units, not expected for DWF."); break; } propPlotMediaUnits.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotMediaUnits); USES_CONVERSION; // paperScale(). double paperScale = pInfo->paperScale(); bool isScale = pInfo->isScaleSpecified(); AcDMMEPlotProperty propPaperScale; propPaperScale.SetName(L"Paper Scale"); if (isScale) { m_cstr.Format("%g",paperScale); m_wchar = A2W(m_cstr); propPaperScale.SetValue(m_wchar); } else { propPaperScale.SetValue(L"Scale to Fit."); } propPaperScale.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPaperScale); // drawingScale(). double drawingScale = pInfo->drawingScale(); AcDMMEPlotProperty propDrawingScale; propDrawingScale.SetName(L"Drawing Scale"); m_cstr.Format("%g",drawingScale); m_wchar = A2W(m_cstr); propDrawingScale.SetValue(m_wchar); propDrawingScale.SetCategory(L"ParthaSheetProp"); propVec.push_back(propDrawingScale); // originX(). double OriginX = pInfo->originX(); AcDMMEPlotProperty propOriginX; propOriginX.SetName(L"Drawing Origin X"); m_cstr.Format("%g",OriginX); m_wchar = A2W(m_cstr); propOriginX.SetValue(m_wchar); propOriginX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propOriginX); // originY(). double OriginY = pInfo->originY(); AcDMMEPlotProperty propOriginY; propOriginY.SetName(L"Drawing Origin Y"); m_cstr.Format("%g",OriginY); m_wchar = A2W(m_cstr); propOriginY.SetValue(m_wchar); propOriginY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propOriginY); // plotWindowMinX(). double PlotWinMinX = pInfo->plotWindowMinX(); AcDMMEPlotProperty propPlotWinMinX; propPlotWinMinX.SetName(L"Plot Window MinX"); m_cstr.Format("%g",PlotWinMinX); m_wchar = A2W(m_cstr); propPlotWinMinX.SetValue(m_wchar); propPlotWinMinX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotWinMinX); // plotWindowMinY(). double PlotWinMinY = pInfo->plotWindowMinY(); AcDMMEPlotProperty propPlotWinMinY; propPlotWinMinY.SetName(L"Plot Window MinY"); m_cstr.Format("%g",PlotWinMinY); m_wchar = A2W(m_cstr); propPlotWinMinY.SetValue(m_wchar); propPlotWinMinY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotWinMinY); // plotWindowMaxX(). double PlotWinMaxX = pInfo->plotWindowMaxX(); AcDMMEPlotProperty propPlotWinMaxX; propPlotWinMaxX.SetName(L"Plot Window MaxX"); m_cstr.Format("%g",PlotWinMaxX); m_wchar = A2W(m_cstr); propPlotWinMaxX.SetValue(m_wchar); propPlotWinMaxX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotWinMaxX); // plotWindowMinY(). double PlotWinMaxY = pInfo->plotWindowMaxY(); AcDMMEPlotProperty propPlotWinMaxY; propPlotWinMaxY.SetName(L"Plot Window MaxY"); m_cstr.Format("%g",PlotWinMaxY); m_wchar = A2W(m_cstr); propPlotWinMaxY.SetValue(m_wchar); propPlotWinMaxY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotWinMaxY); //viewPlotted() const TCHAR* ViewPlotted = pInfo->viewPlotted(); AcDMMEPlotProperty propViewPlotted; propViewPlotted.SetName(L"View Plotted"); if (strcmp(ViewPlotted, "") == 0) propViewPlotted.SetValue(L"View name not defined."); else { m_cstr.Format("%s",ViewPlotted); m_wchar = A2W(m_cstr); propViewPlotted.SetValue(m_wchar); } propViewPlotted.SetCategory(L"ParthaSheetProp"); propVec.push_back(propViewPlotted); // areLinesHidden(). bool areLinesHidden = pInfo->areLinesHidden(); AcDMMEPlotProperty propIsLinesHidden; propIsLinesHidden.SetName(L"Are lines hidden"); if (areLinesHidden) propIsLinesHidden.SetValue(L"Yes"); else propIsLinesHidden.SetValue(L"No"); propIsLinesHidden.SetCategory(L"ParthaSheetProp"); propVec.push_back(propIsLinesHidden); // arePlottingLineWeights(). bool arePlottingLineWeights = pInfo->arePlottingLineWeights(); AcDMMEPlotProperty propPlottingLineWeights; propPlottingLineWeights.SetName(L"Are Plotting Line Weights"); if (arePlottingLineWeights) propPlottingLineWeights.SetValue(L"Yes"); else propPlottingLineWeights.SetValue(L"No"); propPlottingLineWeights.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlottingLineWeights); // areScallingLineWeights(). bool areScallingLineWeights = pInfo->areScalingLineWeights(); AcDMMEPlotProperty propScallingLineWeights; propScallingLineWeights.SetName(L"Are Scalling Line Weights"); if (areScallingLineWeights) propScallingLineWeights.SetValue(L"Yes"); else propScallingLineWeights.SetValue(L"No"); propScallingLineWeights.SetCategory(L"ParthaSheetProp"); propVec.push_back(propScallingLineWeights); // displayMinX(). double displayMinX = pInfo->displayMinX(); AcDMMEPlotProperty propDisplayMinX; propDisplayMinX.SetName(L"Display Min X"); m_cstr.Format("%g",displayMinX); m_wchar = A2W(m_cstr); propDisplayMinX.SetValue(m_wchar); propDisplayMinX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propDisplayMinX); // displayMinY(). double displayMinY = pInfo->displayMinY(); AcDMMEPlotProperty propDisplayMinY; propDisplayMinY.SetName(L"Display Min Y"); m_cstr.Format("%g",displayMinY); m_wchar = A2W(m_cstr); propDisplayMinY.SetValue(m_wchar); propDisplayMinY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propDisplayMinY); // displayMaxX(). double displayMaxX = pInfo->displayMaxX(); AcDMMEPlotProperty propDisplayMaxX; propDisplayMaxX.SetName(L"Display Max X"); m_cstr.Format("%g",displayMaxX); m_wchar = A2W(m_cstr); propDisplayMaxX.SetValue(m_wchar); propDisplayMaxX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propDisplayMaxX); // displayMaxY(). double displayMaxY = pInfo->displayMaxY(); AcDMMEPlotProperty propDisplayMaxY; propDisplayMaxY.SetName(L"Display Max Y"); m_cstr.Format("%g",displayMaxY); m_wchar = A2W(m_cstr); propDisplayMaxY.SetValue(m_wchar); propDisplayMaxY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propDisplayMaxY); // layoutMarginMinX(). double layoutMarginMinX = pInfo->layoutMarginMinX(); AcDMMEPlotProperty propLayoutMarginMinX; propLayoutMarginMinX.SetName(L"Layout Margin Min X"); m_cstr.Format("%g",layoutMarginMinX); m_wchar = A2W(m_cstr); propLayoutMarginMinX.SetValue(m_wchar); propLayoutMarginMinX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propLayoutMarginMinX); // layoutMarginMinY(). double layoutMarginMinY = pInfo->layoutMarginMinY(); AcDMMEPlotProperty propLayoutMarginMinY; propLayoutMarginMinY.SetName(L"Layout Margin Min Y"); m_cstr.Format("%g",layoutMarginMinY); m_wchar = A2W(m_cstr); propLayoutMarginMinY.SetValue(m_wchar); propLayoutMarginMinY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propLayoutMarginMinY); // layoutMarginMaxX(). double layoutMarginMaxX = pInfo->layoutMarginMaxX(); AcDMMEPlotProperty propLayoutMarginMaxX; propLayoutMarginMaxX.SetName(L"Layout Margin Max X"); m_cstr.Format("%g",layoutMarginMaxX); m_wchar = A2W(m_cstr); propLayoutMarginMaxX.SetValue(m_wchar); propLayoutMarginMaxX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propLayoutMarginMaxX); // layoutMarginMaxY(). double layoutMarginMaxY = pInfo->layoutMarginMaxY(); AcDMMEPlotProperty propLayoutMarginMaxY; propLayoutMarginMaxY.SetName(L"Layout Margin Max Y"); m_cstr.Format("%g",layoutMarginMaxY); m_wchar = A2W(m_cstr); propLayoutMarginMaxY.SetValue(m_wchar); propLayoutMarginMaxY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propLayoutMarginMaxY); // printableBoundsX(). double printableBoundsX = pInfo->printableBoundsX(); AcDMMEPlotProperty propPrintableBoundsX; propPrintableBoundsX.SetName(L"Printable Bounds X"); m_cstr.Format("%g",printableBoundsX); m_wchar = A2W(m_cstr); propPrintableBoundsX.SetValue(m_wchar); propPrintableBoundsX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPrintableBoundsX); // printableBoundsY(). double printableBoundsY = pInfo->printableBoundsY(); AcDMMEPlotProperty propPrintableBoundsY; propPrintableBoundsY.SetName(L"Printable Bounds Y"); m_cstr.Format("%g",printableBoundsY); m_wchar = A2W(m_cstr); propPrintableBoundsY.SetValue(m_wchar); propPrintableBoundsY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPrintableBoundsY); // maxBoundsX(). double maxBoundsX = pInfo->maxBoundsX(); AcDMMEPlotProperty propMaxBoundsX; propMaxBoundsX.SetName(L"Max Bounds X"); m_cstr.Format("%g",maxBoundsX); m_wchar = A2W(m_cstr); propMaxBoundsX.SetValue(m_wchar); propMaxBoundsX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propMaxBoundsX); // maxBoundsY(). double maxBoundsY = pInfo->maxBoundsY(); AcDMMEPlotProperty propMaxBoundsY; propMaxBoundsY.SetName(L"Max Bounds Y"); m_cstr.Format("%g",maxBoundsY); m_wchar = A2W(m_cstr); propMaxBoundsY.SetValue(m_wchar); propMaxBoundsY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propMaxBoundsY); // stepsPerInch(). double stepsPerInch = pInfo->stepsPerInch(); AcDMMEPlotProperty propStepsPerInch; propMaxBoundsY.SetName(L"Steps per Inch"); m_cstr.Format("%g",stepsPerInch); m_wchar = A2W(m_cstr); propMaxBoundsY.SetValue(m_wchar); propMaxBoundsY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propMaxBoundsY); //configuration() const TCHAR* configuration = pInfo->configuration(); AcDMMEPlotProperty propConfiguration; propConfiguration.SetName(L"Configuration"); if (strcmp(configuration, "") == 0) propConfiguration.SetValue(L"Configuration name not defined."); else { m_cstr.Format("%s",configuration); m_wchar = A2W(m_cstr); propConfiguration.SetValue(m_wchar); } propConfiguration.SetCategory(L"ParthaSheetProp"); propVec.push_back(propConfiguration); //plotToFilePath() const TCHAR* plotToFilePath = pInfo->plotToFilePath(); AcDMMEPlotProperty propPlotToFilePath; propPlotToFilePath.SetName(L"Plot To File Path"); if (strcmp(plotToFilePath, "") == 0) propPlotToFilePath.SetValue(L"Plot To File Path not defined."); else { m_cstr.Format("%s",plotToFilePath); m_wchar = A2W(m_cstr); propPlotToFilePath.SetValue(m_wchar); } propPlotToFilePath.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotToFilePath); //plotToFileName() const TCHAR* plotToFileName = pInfo->plotToFileName(); AcDMMEPlotProperty propPlotToFileName; propPlotToFileName.SetName(L"Plot To File Name"); if (strcmp(plotToFileName, "") == 0) propPlotToFileName.SetValue(L"Plot To File Name not defined."); else { m_cstr.Format("%s",plotToFileName); m_wchar = A2W(m_cstr); propPlotToFileName.SetValue(m_wchar); } propPlotToFileName.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotToFileName); //caninicalMediaName() const TCHAR* caninicalMediaName = pInfo->canonicalMediaName(); AcDMMEPlotProperty propCaninicalMediaName; propCaninicalMediaName.SetName(L"Caninical Media Name"); if (strcmp(caninicalMediaName, "") == 0) propCaninicalMediaName.SetValue(L"Caninical Media Name not defined."); else { m_cstr.Format("%s",caninicalMediaName); m_wchar = A2W(m_cstr); propCaninicalMediaName.SetValue(m_wchar); } propCaninicalMediaName.SetCategory(L"ParthaSheetProp"); propVec.push_back(propCaninicalMediaName); ///////////////// // plotBoundsMinX(). double plotBoundsMinX = pInfo->plotBoundsMinX(); AcDMMEPlotProperty propPlotBoundsMinX; propPlotBoundsMinX.SetName(L"Plot Bounds Min X"); m_cstr.Format("%g",plotBoundsMinX); m_wchar = A2W(m_cstr); propPlotBoundsMinX.SetValue(m_wchar); propPlotBoundsMinX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotBoundsMinX); // plotBoundsMinY(). double plotBoundsMinY = pInfo->plotBoundsMinY(); AcDMMEPlotProperty propPlotBoundsMinY; propPlotBoundsMinY.SetName(L"Plot Bounds Min Y"); m_cstr.Format("%g",plotBoundsMinY); m_wchar = A2W(m_cstr); propPlotBoundsMinY.SetValue(m_wchar); propPlotBoundsMinY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotBoundsMinY); // plotBoundsMaxX(). double plotBoundsMaxX = pInfo->plotBoundsMaxX(); AcDMMEPlotProperty propPlotBoundsMaxX; propPlotBoundsMaxX.SetName(L"Plot Bounds Max X"); m_cstr.Format("%g",plotBoundsMaxX); m_wchar = A2W(m_cstr); propPlotBoundsMaxX.SetValue(m_wchar); propPlotBoundsMaxX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotBoundsMaxX); // plotBoundsMaxY(). double plotBoundsMaxY = pInfo->plotBoundsMaxY(); AcDMMEPlotProperty propPlotBoundsMaxY; propPlotBoundsMaxY.SetName(L"Plot Bounds Max Y"); m_cstr.Format("%g",plotBoundsMaxY); m_wchar = A2W(m_cstr); propPlotBoundsMaxY.SetValue(m_wchar); propPlotBoundsMaxY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propPlotBoundsMaxY); // layoutBoundsMinX(). double layoutBoundsMinX = pInfo->layoutBoundsMinX(); AcDMMEPlotProperty propLayoutBoundsMinX; propLayoutBoundsMinX.SetName(L"Layout Bounds Min X"); m_cstr.Format("%g",layoutBoundsMinX); m_wchar = A2W(m_cstr); propLayoutBoundsMinX.SetValue(m_wchar); propLayoutBoundsMinX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propLayoutBoundsMinX); // layoutBoundsMinY(). double layoutBoundsMinY = pInfo->layoutBoundsMinY(); AcDMMEPlotProperty propLayoutBoundsMinY; propLayoutBoundsMinY.SetName(L"Layout Bounds Min Y"); m_cstr.Format("%g",layoutBoundsMinY); m_wchar = A2W(m_cstr); propLayoutBoundsMinY.SetValue(m_wchar); propLayoutBoundsMinY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propLayoutBoundsMinY); // layoutBoundsMaxX(). double layoutBoundsMaxX = pInfo->layoutBoundsMaxX(); AcDMMEPlotProperty propLayoutBoundsMaxX; propLayoutBoundsMaxX.SetName(L"Layout Bounds Max X"); m_cstr.Format("%g",layoutBoundsMaxX); m_wchar = A2W(m_cstr); propLayoutBoundsMaxX.SetValue(m_wchar); propLayoutBoundsMaxX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propLayoutBoundsMaxX); // plotBoundsMaxY(). double layoutBoundsMaxY = pInfo->layoutBoundsMaxY(); AcDMMEPlotProperty propLayoutBoundsMaxY; propLayoutBoundsMaxY.SetName(L"Layout Bounds Max Y"); m_cstr.Format("%g",layoutBoundsMaxY); m_wchar = A2W(m_cstr); propLayoutBoundsMaxY.SetValue(m_wchar); propLayoutBoundsMaxY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propLayoutBoundsMaxY); // effectivePlotOffsetX(). double effectivePlotOffsetX = pInfo->effectivePlotOffsetX(); AcDMMEPlotProperty propEffectivePlotOffsetX; propEffectivePlotOffsetX.SetName(L"Effective Plot Offset X"); m_cstr.Format("%g",effectivePlotOffsetX); m_wchar = A2W(m_cstr); propEffectivePlotOffsetX.SetValue(m_wchar); propEffectivePlotOffsetX.SetCategory(L"ParthaSheetProp"); propVec.push_back(propEffectivePlotOffsetX); // effectivePlotOffsetY(). double effectivePlotOffsetY = pInfo->effectivePlotOffsetY(); AcDMMEPlotProperty propEffectivePlotOffsetY; propEffectivePlotOffsetY.SetName(L"Effective Plot Offset Y"); m_cstr.Format("%g",effectivePlotOffsetY); m_wchar = A2W(m_cstr); propEffectivePlotOffsetY.SetValue(m_wchar); propEffectivePlotOffsetY.SetCategory(L"ParthaSheetProp"); propVec.push_back(propEffectivePlotOffsetY); // effectivePlotOffsetXdevice(). int effectivePlotOffsetXdevice = pInfo->effectivePlotOffsetXdevice(); AcDMMEPlotProperty propEffectivePlotOffsetXdevice; propEffectivePlotOffsetXdevice.SetName(L"Effective Plot Offset X Device"); m_cstr.Format("%d",effectivePlotOffsetXdevice); m_wchar = A2W(m_cstr); propEffectivePlotOffsetXdevice.SetValue(m_wchar); propEffectivePlotOffsetXdevice.SetCategory(L"ParthaSheetProp"); propVec.push_back(propEffectivePlotOffsetXdevice); // effectivePlotOffsetYdevice(). int effectivePlotOffsetYdevice = pInfo->effectivePlotOffsetYdevice(); AcDMMEPlotProperty propEffectivePlotOffsetYdevice; propEffectivePlotOffsetYdevice.SetName(L"Effective Plot Offset Y Device"); m_cstr.Format("%d",effectivePlotOffsetYdevice); m_wchar = A2W(m_cstr); propEffectivePlotOffsetYdevice.SetValue(m_wchar); propEffectivePlotOffsetYdevice.SetCategory(L"ParthaSheetProp"); propVec.push_back(propEffectivePlotOffsetYdevice); // Add all properties to the Sheet Info object. pInfo->AddPageProperties(propVec); // add props obj to cache // Invalid value test. if (invalidTest == true) { AcDMMEPlotPropertyVec pVec100; pInfo->AddPageProperties(pVec100); } } else // model Layout { // add a property AcDMMEPlotProperty prop(L"ParthaModelProperty", L"ParthaModelValue"); prop.SetCategory(L"ParthaModelProp"); AcDMMEPlotPropertyVec propVec; propVec.push_back(prop); pInfo->AddPageProperties(propVec); // add props obj to cache // Invalid value test. if (invalidTest == true) { AcDMMEPlotPropertyVec pVec100; pInfo->AddPageProperties(pVec100); } // add a resource AcDMMResourceInfo res(L"ParthaModelResource", L"text", L"C:\\Current Project\\DWFAPI\\DWFs\\Resource-zip.zip"); USES_CONVERSION; // SetRole() char* role = "Partha's role"; res.SetRole(A2W(role)); const char* outRole = OLE2A(res.GetRole()); if (strcmp(outRole, role) == 0) myPrintf("\nAcDMMResourceInfo::role(), getRole() worked fine.", OUTFILE); else myPrintf("\nAcDMMResourceInfo::role(), getRole() did not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMResourceInfo::role(), getRole()"); // SetMime() char* mime = "Partha's mime"; res.SetMime(A2W(mime)); const char* outMime = OLE2A(res.GetMime()); if (strcmp(outMime, mime) == 0) myPrintf("\nAcDMMResourceInfo::mime(), getMime() worked fine.", OUTFILE); else myPrintf("\nAcDMMResourceInfo::mime(), getMime() did not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMResourceInfo::mime(), getMime()"); // SetPath() char* path = "C:\\Partha's Path"; res.SetPath(A2W(path)); const char* outPath = OLE2A(res.GetPath()); if (strcmp(outPath, path) == 0) myPrintf("\nAcDMMResourceInfo::path(), getPath() worked fine.", OUTFILE); else myPrintf("\nAcDMMResourceInfo::path(), getPath() did not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMResourceInfo::path(), getPath()"); // = operator. AcDMMResourceInfo res1 = res; res1.SetRole(L"Bappa's role"); const char* outPath1 = OLE2A(res1.GetPath()); if (strcmp(outPath1, path) == 0) myPrintf("\nAcDMMResourceInfo::'=' operator worked fine.", OUTFILE); else myPrintf("\nAcDMMResourceInfo::'=' operator did not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMResourceInfo::'=' operator"); // other constructor; AcDMMResourceInfo res2(res1); res2.SetRole(L"Anit's role"); const char* outPath2 = OLE2A(res2.GetPath()); if (strcmp(outPath2, path) == 0) myPrintf("\nAcDMMResourceInfo::other constructor worked fine.", OUTFILE); else myPrintf("\nAcDMMResourceInfo::other constructor did not work fine.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcDMMResourceInfo::other constructor"); AcDMMResourceVec resVec; resVec.push_back(res); resVec.push_back(res1); resVec.push_back(res2); pInfo->AddPageResources(resVec); } } void TdDMMReactor::OnEndEntity(AcDMMEntityReactorInfo * pInfo) //#5 { if (A3 == false) { myPrintf("\nTdDMMReactor::OnEndEntity", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nTdDMMReactor::OnEndEntity"); A3 = true; } } void TdDMMReactor::OnEndSheet(AcDMMSheetReactorInfo * pInfo) //#6 { if (A4 == false) { myPrintf("\nTdDMMReactor::OnEndSheet", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nTdDMMReactor::OnEndSheet"); A4 = true; } } // TdPublishReactor class implementation. TdPublishReactor::TdPublishReactor() { B1=false; B2=false; B3=false; B4=false; B5=false; B6=false; B7=false; B8=false; } TdPublishReactor::~TdPublishReactor() { B1=false; B2=false; B3=false; B4=false; B5=false; B6=false; B7=false; B8=false; } void TdPublishReactor::OnAboutToBeginBackgroundPublishing(AcPublishBeforeJobInfo* pInfo) { if (B1 == false) { myPrintf("\nTdPublishReactor::OnAboutToBeginBackgroundPublishing", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); B1 = true; } // check to see if this job is publishing to DWF // GetDSDData(). if (pInfo->GetDSDData()->sheetType() == AcPlDSDEntry::SheetType::kOriginalDevice) // not a DWF job, nothing to do here return; else myPrintf("\n Passed: AcPublishBeforeJobInfo::GetDSDData", OUTFILE); // WritePrivateSection() AcNameValuePairVec valuePairVec; AcNameValuePair nameValuePair(_T("Partha_JobBefore_Private_Name"), _T("Partha_JobBefore_Private_Value")); // Invalid value test. if (invalidTest == true) { AcNameValuePair nameValuePair100(_T("!@#$^%^*&*&%&*%"), _T("^$$&*%%_*^&*%&$%^")); } // Invalid value test. if (invalidTest == true) { AcNameValuePair nameValuePair100(_T("!@#$^%^*&*&%&*%"), _T("^$$&*%%_*^&*%&$%^")); } valuePairVec.push_back(nameValuePair); pInfo->WritePrivateSection(_T("Partha JobBefore Private Data"), valuePairVec); // Invalid value test. if (invalidTest == true) { AcNameValuePairVec valuePairVec100; pInfo->WritePrivateSection(_T("^$$^^"), valuePairVec100); } //JobWillPublishInBackground bool ret = pInfo->JobWillPublishInBackground(); if (ret == true) myPrintf("\nPassed: AcPublishBeforeJobInfo::JobWillPublishInBackground(), publishing background.", OUTFILE); else myPrintf("\nPassed: AcPublishBeforeJobInfo::JobWillPublishInBackground(), publishing foreground.", OUTFILE); } void TdPublishReactor::OnAboutToBeginPublishing(AcPublishBeginJobInfo* pInfo) //#1 { if (B2 == false) { myPrintf("\nTdPublishReactor::OnAboutToBeginPublishing", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nTdPublishReactor::OnAboutToBeginPublishing"); B2 = true; } // check to see if this job is publishing to DWF // GetDSDData(). if (pInfo->GetDSDData()->sheetType() == AcPlDSDEntry::SheetType::kOriginalDevice) // not a DWF job, nothing to do here return; else myPrintf("\n Passed: AcPublishBeginJobInfo::GetDSDData", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcPublishBeginJobInfo::GetDSDData"); // make sure AcEplotX.arx is loaded if (!acrxServiceIsRegistered("AcEPlotX")) { acrxLoadModule("AcEPlotx.arx", false, false); } HINSTANCE hInst = NULL; hInst = ::GetModuleHandle("AcEPlotX.arx"); ASSERT(NULL != hInst); if ((hInst)) { ACGLOBADDDMMREACTOR pAcGlobalAddDMMReactor = NULL; pAcGlobalAddDMMReactor = (ACGLOBADDDMMREACTOR)GetProcAddress(hInst, _T("AcGlobAddDMMReactor")); ASSERT(NULL != pAcGlobalAddDMMReactor); if (NULL != pAcGlobalAddDMMReactor) { ASSERT(NULL == g_pDMMReactor); g_pDMMReactor = new TdDMMReactor(); pAcGlobalAddDMMReactor(g_pDMMReactor); } } // here is where we will load the BLK file (if one is configured) AcNameValuePairVec valuePairVec; // Invalid value test. if (invalidTest == true) { AcNameValuePair nameValuePair100(_T("!@#$^%^*&*&%&*%"), _T("^$$&*%%_*^&*%&$%^")); } bool bIncludeBlockInfo = false; CString csIncludeBlockInfo; CString csBlockTmplFilePath; valuePairVec = pInfo->GetPrivateData("AutoCAD Block Data"); AcNameValuePairVec::const_iterator iter = valuePairVec.begin(); while (iter != valuePairVec.end()) { AcNameValuePair pair = (*iter++); CString csName = pair.name(); CString csValue = pair.value(); if (csName == _T("IncludeBlockInfo")) if (csValue == "1") bIncludeBlockInfo = true; else bIncludeBlockInfo = false; if (csName == _T("BlockTmplFilePath")) csBlockTmplFilePath = csValue; } if (bIncludeBlockInfo && !csBlockTmplFilePath.IsEmpty()) { // verify that the file exists? g_pDxServices = new CCW_AcPublishMgdServices(csBlockTmplFilePath); g_bIncludeBlockInfo = true; } else g_bIncludeBlockInfo = false; // WritePrivateSection() AcNameValuePairVec valuePairVec1; //AcNameValuePair nameValuePair(_T("Partha_JobBegin_Private_Name"), _T("Partha_JobBegin_Private_Value")); AcNameValuePair nameValuePair; //AcNameValuePair::SetName() nameValuePair.setName(_T("Partha_JobBegin_Private_Name")); //AcNameValuePair::SetValue() nameValuePair.setValue(_T("Partha_JobBegin_Private_Value")); //AcNameValuePair::name() if (strcmp(nameValuePair.name(), _T("Partha_JobBegin_Private_Name")) == 0) myPrintf("\nPassed: AcNameValuePair::name() returned correct name", OUTFILE); else myPrintf("\nFailed: AcNameValuePair::name() did not return correct name", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcNameValuePair::name()"); //AcNameValuePair::value() if (strcmp(nameValuePair.name(), _T("Partha_JobBegin_Private_Name")) == 0) myPrintf("\nPassed: AcNameValuePair::name() returned correct name", OUTFILE); else myPrintf("\nFailed: AcNameValuePair::name() did not return correct name", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcNameValuePair::name()"); //AcNameValuePair::= operator AcNameValuePair nameValuePair1 = nameValuePair; //AcNameValuePair::AcNameValuePair(const AcNameValuePair &src) AcNameValuePair nameValuePair2(nameValuePair1); valuePairVec1.push_back(nameValuePair2); pInfo->WritePrivateSection(_T("Partha JobBegin Private Data"), valuePairVec1); // Invalid value test. if (invalidTest == true) { AcNameValuePairVec valuePairVec100; pInfo->WritePrivateSection(_T("^$$^^"), valuePairVec100); } //JobWillPublishInBackground bool ret = pInfo->JobWillPublishInBackground(); if (ret == true) myPrintf("\nPassed: AcPublishBeginJobInfo::JobWillPublishInBackground(), publishing background.", OUTFILE); else myPrintf("\nPassed: AcPublishBeginJobInfo::JobWillPublishInBackground(), publishing foreground.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcPublishBeginJobInfo::JobWillPublishInBackground()"); } void TdPublishReactor::OnAboutToEndPublishing(AcPublishReactorInfo *pInfo) //#9 { if (B3 == false) { myPrintf("\nTdPublishReactor::OnAboutToEndPublishing", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); B3 = true; } //cleaning up DMMReactor if (NULL != g_pDMMReactor) { HINSTANCE hInst0 = ::GetModuleHandle("AcEPlotX.arx"); if ((hInst0)) { ACGLOBREMOVEDMMREACTOR pAcGlobalRemoveDMMReactor = (ACGLOBREMOVEDMMREACTOR)GetProcAddress(hInst0, "AcGlobRemoveDMMReactor"); ASSERT(NULL != pAcGlobalRemoveDMMReactor); if (NULL != pAcGlobalRemoveDMMReactor) pAcGlobalRemoveDMMReactor(g_pDMMReactor); else AfxMessageBox("\nFailed to remove DMMReactor to the Manager."); g_pDMMReactor = NULL; } } // dwfFileName() const char* fileName = pInfo->dwfFileName(); if (strcmp(fileName, "") == 0) myPrintf("\nFailed: AcPublishReactorInfo::dwfFileName(), failed to get the DWF file name.", OUTFILE); else myPrintf("\nPassed: AcPublishReactorInfo::dwfFileName(), got the DWF file name.", OUTFILE); // tempDwfFileName() const char* tempFileName = pInfo->tempDwfFileName(); if (strcmp(tempFileName, "") == 0) myPrintf("\nFailed: AcPublishReactorInfo::tempDwfFileName(), failed to get the temporary DWF file name.", OUTFILE); else myPrintf("\nPassed: AcPublishReactorInfo::tempDwfFileName(), got the temporary DWF file name.", OUTFILE); // dwfPassword() const char* dwfPassword = pInfo->dwfPassword(); if (strcmp(dwfPassword, "") == 0) myPrintf("\nPassed: AcPublishReactorInfo::dwfPassword(), there is no password for this DWF file.", OUTFILE); else myPrintf("\nPassed: AcPublishReactorInfo::dwfPassword(), got the DWF file password.", OUTFILE); // getUnrecognizedDSDData() AcArray<char*>* urSectionArray; AcArray<char*>* urDataArray; pInfo->getUnrecognizedDSDData(urSectionArray, urDataArray); int len = urSectionArray->length(); char* section; char* data; CString str; myPrintf("\nPassed:UnRecognized DSD data:", OUTFILE); for (int i=0; i<len; i++) { section = urSectionArray->at(i); data = urDataArray->at(i); str.Format("\n\tSection = %s: Data = %s", section, data); myPrintf(str, OUTFILE); } if (pInfo->isMultiSheetDwf()) myPrintf("\nPassed: It's a Multisheet DWF file.", OUTFILE); else myPrintf("\nPassed: It's a Single DWF file.", OUTFILE); } void TdPublishReactor::OnAboutToMoveFile(AcPublishReactorInfo *pInfo) //#8 { if (B4 == false) { myPrintf("\nTdPublishReactor::OnAboutToMoveFile", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); B4 = true; } } void TdPublishReactor::OnBeginAggregation(AcPublishAggregationInfo *pInfo) //#7 { if (B5 == false) { myPrintf("\nTdPublishReactor::OnBeginAggregation", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nTdPublishReactor::OnBeginAggregation"); B5 = true; } // addGlobalProperties() AcDMMEPlotProperty prop(L"Partha_Global_Property", L"Partha_Global_Value"); AcDMMEPlotPropertyVec propVec; propVec.push_back(prop); pInfo->AddGlobalProperties(propVec); myPrintf("\nAcPublishAggregationInfo::AddGlobalProperties(), added global properties.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcPublishAggregationInfo::AddGlobalProperties()"); // Invalid value test. if (invalidTest == true) { AcDMMEPlotPropertyVec vec100; pInfo->AddGlobalProperties(vec100); } // addGlobalResources() AcDMMResourceInfo res(L"Partha_Global_Resource", L"Partha", L"C:\\Current Project\\DWFAPI\\DWFs\\Volcano_lava.JPG"); AcDMMResourceVec resVec; resVec.push_back(res); pInfo->AddGlobalResources(resVec); myPrintf("\nAcPublishAggregationInfo::AddGlobalResources(), added global resources.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcPublishAggregationInfo::AddGlobalResources()"); // Invalid value test. if (invalidTest == true) { AcDMMResourceVec res100; pInfo->AddGlobalResources(res100); } // dwfFileName() const char* fileName = pInfo->dwfFileName(); if (strcmp(fileName, "") == 0) myPrintf("\nFailed: AcPublishAggregationInfo::dwfFileName(), failed to get the DWF file name.", OUTFILE); else myPrintf("\nPassed: AcPublishAggregationInfo::dwfFileName(), got the DWF file name.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcPublishAggregationInfo::dwfFileName()"); // tempDwfFileName() const char* tempFileName = pInfo->tempDwfFileName(); // DID #605461: the call returns NULL and crash gere. // uncomment when the bug is fixed. //if (strcmp(tempFileName, "") == 0) // myPrintf("\nFailed: AcPublishAggregationInfo::tempDwfFileName(), failed to get the temporary DWF file name.", OUTFILE); //else // myPrintf("\nPassed: AcPublishAggregationInfo::tempDwfFileName(), got the temporary DWF file name.", OUTFILE); // dwfPassword() const char* dwfPassword = pInfo->dwfPassword(); if (strcmp(dwfPassword, "") == 0) myPrintf("\nPassed: AcPublishAggregationInfo::dwfPassword(), there is no password for this DWF file.", OUTFILE); else myPrintf("\nPassed: AcPublishAggregationInfo::dwfPassword(), got the DWF file password.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcPublishAggregationInfo::dwfPassword()"); } void TdPublishReactor::OnBeginPublishingSheet(AcPublishSheetInfo *pInfo) //#2 { if (B6 == false) { myPrintf("\nTdPublishReactor::OnBeginPublishingSheet", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nTdPublishReactor::OnBeginPublishingSheet"); B6 = true; } // check to see if this job is publishing to DWF // GetDSDEntity(). const AcPlDSDEntry* pEntity = pInfo->GetDSDEntry(); if (pEntity != NULL) if ((strcmp(pEntity->dwgName(), "") != 0) && (strcmp(pEntity->layout(), "") != 0)) myPrintf("\nPassed: AcPublishSheetInfo::GetDSDEntry(): return DSD entity /w valid DWG name and layout name.", OUTFILE); else myPrintf("\nFailed: AcPublishSheetInfo::GetDSDEntry(): return DSD entity but failed to return valid DWG name and layout name.", OUTFILE); else myPrintf("\nFailed: AcPublishSheetInfo::GetDSDEntry(): failed to return DSD entity for the sheet.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcPublishSheetInfo::GetDSDEntry()"); // GetUniqueId() const char* uniqueId = pInfo->GetUniqueId(); if (strcmp(uniqueId, "") == 0) myPrintf("\nFailed: AcPublishSheetInfo::GetUniqueId(), failed to get the unique ID.", OUTFILE); else myPrintf("\nPassed: AcPublishSheetInfo::GetUniqueId(), got the unique ID.", OUTFILE); pInfo->GetPlotLogger()->logMessage("\nAcPublishSheetInfo::GetUniqueId()"); } void TdPublishReactor::OnCancelledOrFailedPublishing(AcPublishReactorInfo *pInfo) { if (B7 == false) { myPrintf("\nTdPublishReactor::OnCancelledOrFailedPublishing", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); B7 = true; } // Cleaning up all reactors. //DMMReactor if (NULL != g_pDMMReactor) { HINSTANCE hInst0 = ::GetModuleHandle("AcEPlotX.arx"); if ((hInst0)) { ACGLOBREMOVEDMMREACTOR pAcGlobalRemoveDMMReactor = (ACGLOBREMOVEDMMREACTOR)GetProcAddress(hInst0, "AcGlobRemoveDMMReactor"); ASSERT(NULL != pAcGlobalRemoveDMMReactor); if (NULL != pAcGlobalRemoveDMMReactor) pAcGlobalRemoveDMMReactor(g_pDMMReactor); else AfxMessageBox("\nFailed to remove DMMReactor to the Manager."); g_pDMMReactor = NULL; } } } void TdPublishReactor::OnEndPublish(AcPublishReactorInfo *pInfo) //#10 { if (B8 == false) { myPrintf("\nTdPublishReactor::OnEndPublish", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); B8 = true; } } // TdPublishUIReactor class implementation TdPublishUIReactor::TdPublishUIReactor() { C1=false; } TdPublishUIReactor::~TdPublishUIReactor() { C1=false; } void TdPublishUIReactor::OnInitPublishOptionsDialog(IUnknown **pUnk, AcPublishUIReactorInfo *pInfo) { if (C1 == false) { myPrintf("\nTdPublishUIReactor::OnInitPublishOptionsDialog", OUTFILE); myPrintf("\n------------------------------------\n", OUTFILE); C1 = true; } // check to see if this job is publishing to DWF // GetDSDData(). if (pInfo->GetDSDData()->sheetType() == AcPlDSDEntry::SheetType::kOriginalDevice) // not a DWF job, nothing to do here return; // WritePrivateSection() AcNameValuePairVec valuePairVec1; AcNameValuePair nameValuePair1(_T("Partha_PublishOption_Private_Name1"), _T("Partha_PublishOption_Private_Value1")); // Invalid value test. if (invalidTest == true) { AcNameValuePair nameValuePair100(_T("!@#$^%^*&*&%&*%"), _T("^$$&*%%_*^&*%&$%^")); } valuePairVec1.push_back(nameValuePair1); pInfo->WritePrivateSection(_T("Partha PublishOption Private Data1"), valuePairVec1); AcNameValuePairVec valuePairVec2; AcNameValuePair nameValuePair2(_T("Partha_PublishOption_Private_Name2"), _T("Partha_PublishOption_Private_Value2")); valuePairVec2.push_back(nameValuePair2); pInfo->WritePrivateSection(_T("Partha PublishOption Private Data2"), valuePairVec2); AcNameValuePairVec valuePairVec3; AcNameValuePair nameValuePair3(_T("Partha_PublishOption_Private_Name3"), _T("Partha_PublishOption_Private_Value3")); valuePairVec3.push_back(nameValuePair3); pInfo->WritePrivateSection(_T("Partha PublishOption Private Data3"), valuePairVec3); // get the a specific data and change it. const AcNameValuePairVec pPairVec = pInfo->GetPrivateData(_T("Partha PublishOption Private Data2")); // Invalid value test. if (invalidTest == true) { AcNameValuePair nameValuePair100(_T("!@#$^%^*&*&%&*%"), _T("^$$&*%%_*^&*%&$%^")); } int size = pPairVec.size(); for (int i = 0; i < size; i++) { CString name, value, str; AcNameValuePair pPair = pPairVec.at(i); name = pPair.name(); value = pPair.value(); str = "\nPassed: Name-Value of the private 2nd private data written is " + name + "," + value; myPrintf(str, OUTFILE); } // add a new property in the publish-options dialog. //CComPtr<IPropertyManager2> pPropMan; //(*pUnk)->QueryInterface(IID_IPropertyManager2, (void **)&pPropMan); //JobWillPublishInBackground bool ret = pInfo->JobWillPublishInBackground(); if (ret == true) myPrintf("\nPassed: AcPublishUIReactorInfo::JobWillPublishInBackground(), publishing background.", OUTFILE); else myPrintf("\nPassed: AcPublishUIReactorInfo::JobWillPublishInBackground(), publishing foreground.", OUTFILE); } /* //prepared for DevDays PPT. At run time enable above code and disable following code void AcTestDMMEntReactor:: OnBeginEntity(AcDMMEntityReactorInfo * pInfo) { int nNodeId = 0; bool bRet = pInfo->GetEntityNode(pInfo->entity()->objectId(),0, nNodeId); if (!bRet) { //step1: Detect your entity AcDbEntity* pEntity = pInfo->entity(); //step2: container for object's metadata AcDMMEPlotProperties props; //step3: Assume we want to get the handle of object and publish same as metadata AcDMMEPlotProperty * entityProp1 = new AcDMMEPlotProperty(L"Handle", locale_to_wchar(m_EntGenralPorps.m_chHandle)); entityProp1->SetCategory(L"DMMAPI"); //step4:Add each of AcDMMEPlotProperty objects to the AcDMMEPlotProperties props.AddProperty(entityProp1); //step5:Generate a unique ID, Assign same ID to props const wchar_t * wsUnique = pInfo->UniqueEntityId(); AcDMMWideString wsPropId; // need a unique string id for properties wsPropId = L"ACAD"; //application name (optional) wsPropId += wsUnique; delete wsUnique; props.SetId(PCWIDESTR(wsPropId)); pInfo->AddProperties(&props); //step6:To associate the metadata to a graphic object we need NodeId: int nodeId = pInfo->GetNextAvailableNodeId(); // create a Node for this entity AcDMMNode node(nodeId, L"dummy"); AcDMMStringVec IdVec; IdVec.push_back(wsPropId); //step7: assign node to entity bRet = pInfo->AddNodeToMap(pEntity->objectId(), 0, nodeId); // step8: Now associate your properties with this node by calling AddPropertiesIds() pInfo->AddPropertiesIds(&IdVec, node); } } */ void AcTestDMMEntReactor::ProcessBlocks(AcDMMEntityReactorInfo * pInfo) { AcDbEntity* pEntity = pInfo->entity(); AcDbObjectId objId = pEntity->objectId(); long oldId = objId.asOldId(); bool bret; //unsigned long front = 0; AcDbObjectIdArray objectIds; if (pEntity->isKindOf(AcDbBlockReference::desc())) // block { pInfo->GetPlotLogger()->logMessage("\nBlock FOUND, assigning metadata properties to it"); // Add the object Id to the objectIds array. objectIds.append(objId); // get the block name. AcDbBlockReference* pBlkRef = 0; const char* blkName = 0; if(acdbOpenObject(pBlkRef, objId, AcDb::kForRead) == Acad::eOk) { AcDbBlockTableRecord* pTblRec = 0; if(acdbOpenObject(pTblRec, pBlkRef->blockTableRecord(), AcDb::kForRead) == Acad::eOk) { pTblRec->getName(blkName); pTblRec->close(); } pBlkRef->close(); } g_entIdVec.push_back(oldId); //front = g_entIdVec.front(); AcDMMEPlotPropertyVec propVec; // FIRST SET OF PROPERTIES. AcDMMEPlotProperties props; //add properties to prop objects. AcDMMEPlotPropertyVec::const_iterator iter = propVec.begin(); // get all the standard meta properties and write them in the new // property collection. while (iter != propVec.end()) { AcDMMEPlotProperty prop = (*iter++); props.AddProperty(&prop); } // write a custom property. AcDMMEPlotProperty prop1(L"TestProperty", L"TestValue"); prop1.SetType(L"string"); USES_CONVERSION; if (blkName != "") prop1.SetCategory(A2W(blkName)); else prop1.SetCategory(L"Custom Catagory1"); props.AddProperty(&prop1); const wchar_t* wsUnique = pInfo->UniqueEntityId(); //step5:Generate a unique ID, Assign same ID to props AcDMMWideString wsPropId; // need a unique string id for properties wsPropId = L"ACAD"; wsPropId += wsUnique; delete wsUnique; props.SetId(PCWIDESTR(wsPropId)); pInfo->AddProperties(&props); // add props obj to cache // string Vector AcDMMStringVec IdVec; IdVec.push_back(wsPropId); int nodeId = 0; const AcDMMNode* node; // check to see if this node already assigned if(!pInfo->GetEntityNode(objId, objectIds, nodeId)) { // create a node for this entity. nodeId = pInfo->GetNextAvailableNodeId(); node = new AcDMMNode(nodeId, L"PARTHA"); bret = pInfo->AddNodeToMap(objId, 0, nodeId); ASSERT(bret); g_NodeStack.push(nodeId); // associate the properties with the node. bret = pInfo->AddPropertiesIds(&IdVec, (AcDMMNode &)*node); } } }
34.436771
141
0.691821
kevinzhwl
03aeca585a9a5164b117f7f9af56071cb43c1513
22,291
cpp
C++
agent/config.cpp
markovchainz/cppagent
97314ec43786a90697ca7fda15db13f2973aee3e
[ "Apache-2.0" ]
null
null
null
agent/config.cpp
markovchainz/cppagent
97314ec43786a90697ca7fda15db13f2973aee3e
[ "Apache-2.0" ]
null
null
null
agent/config.cpp
markovchainz/cppagent
97314ec43786a90697ca7fda15db13f2973aee3e
[ "Apache-2.0" ]
null
null
null
/* * Copyright Copyright 2012, System Insights, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.hpp" #include "agent.hpp" #include "options.hpp" #include "device.hpp" #include "xml_printer.hpp" #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <dlib/config_reader.h> #include <dlib/logger.h> #include <stdexcept> #include <algorithm> #include <sys/stat.h> #include "rolling_file_logger.hpp" using namespace std; using namespace dlib; static logger sLogger("init.config"); static inline const char *get_with_default(const config_reader::kernel_1a &reader, const char *aKey, const char *aDefault) { if (reader.is_key_defined(aKey)) return reader[aKey].c_str(); else return aDefault; } static inline int get_with_default(const config_reader::kernel_1a &reader, const char *aKey, int aDefault) { if (reader.is_key_defined(aKey)) return atoi(reader[aKey].c_str()); else return aDefault; } static inline const string &get_with_default(const config_reader::kernel_1a &reader, const char *aKey, const string &aDefault) { if (reader.is_key_defined(aKey)) return reader[aKey]; else return aDefault; } static inline bool get_bool_with_default(const config_reader::kernel_1a &reader, const char *aKey, bool aDefault) { if (reader.is_key_defined(aKey)) return reader[aKey] == "true" || reader[aKey] == "yes"; else return aDefault; } AgentConfiguration::AgentConfiguration() : mAgent(NULL), mLoggerFile(NULL), mMonitorFiles(false), mRestart(false), mMinimumConfigReloadAge(15) { } void AgentConfiguration::initialize(int aArgc, const char *aArgv[]) { MTConnectService::initialize(aArgc, aArgv); const char *configFile = "agent.cfg"; OptionsList optionList; optionList.append(new Option(0, configFile, "The configuration file", "file", false)); optionList.parse(aArgc, (const char**) aArgv); mConfigFile = configFile; try { ifstream file(mConfigFile.c_str()); loadConfig(file); } catch (std::exception & e) { sLogger << LFATAL << "Agent failed to load: " << e.what(); cerr << "Agent failed to load: " << e.what() << std::endl; optionList.usage(); } } AgentConfiguration::~AgentConfiguration() { if (mAgent != NULL) delete mAgent; if (mLoggerFile != NULL) delete mLoggerFile; set_all_logging_output_streams(cout); } void AgentConfiguration::monitorThread() { struct stat devices_at_start, cfg_at_start; if (stat(mConfigFile.c_str(), &cfg_at_start) != 0) sLogger << LWARN << "Cannot stat config file: " << mConfigFile << ", exiting monitor"; if (stat(mDevicesFile.c_str(), &devices_at_start) != 0) sLogger << LWARN << "Cannot stat devices file: " << mDevicesFile << ", exiting monitor"; sLogger << LDEBUG << "Monitoring files: " << mConfigFile << " and " << mDevicesFile << ", will warm start if they change."; bool changed = false; // Check every 10 seconds do { dlib::sleep(10000); struct stat devices, cfg; bool check = true; if (stat(mConfigFile.c_str(), &cfg) != 0) { sLogger << LWARN << "Cannot stat config file: " << mConfigFile << ", retrying in 10 seconds"; check = false; } if (stat(mDevicesFile.c_str(), &devices) != 0) { sLogger << LWARN << "Cannot stat devices file: " << mDevicesFile << ", retrying in 10 seconds"; check = false; } // Check if the files have changed. if (check && (cfg_at_start.st_mtime != cfg.st_mtime || devices_at_start.st_mtime != devices.st_mtime)) { time_t now = time(NULL); sLogger << LWARN << "Dected change in configuarion files. Will reload when youngest file is at least " << mMinimumConfigReloadAge <<" seconds old"; sLogger << LWARN << " Devices.xml file modified " << (now - devices.st_mtime) << " seconds ago"; sLogger << LWARN << " ...cfg file modified " << (now - cfg.st_mtime) << " seconds ago"; changed = (now - cfg.st_mtime) > mMinimumConfigReloadAge && (now - devices.st_mtime) > mMinimumConfigReloadAge; } } while (!changed && mAgent->is_running()); // Restart agent if changed... // stop agent and signal to warm start if (mAgent->is_running() && changed) { sLogger << LWARN << "Monitor thread has detected change in configuration files, restarting agent."; mRestart = true; mAgent->clear(); delete mAgent; mAgent = NULL; sLogger << LWARN << "Monitor agent has completed shutdown, reinitializing agent."; // Re initialize const char *argv[] = { mConfigFile.c_str() }; initialize(1, argv); } sLogger << LDEBUG << "Monitor thread is exiting"; } void AgentConfiguration::start() { auto_ptr<dlib::thread_function> mon; do { mRestart = false; if (mMonitorFiles) { // Start the file monitor to check for changes to cfg or devices. sLogger << LDEBUG << "Waiting for monitor thread to exit to restart agent"; mon.reset(new dlib::thread_function(make_mfp(*this, &AgentConfiguration::monitorThread))); } mAgent->start(); if (mRestart && mMonitorFiles) { // Will destruct and wait to re-initialize. sLogger << LDEBUG << "Waiting for monitor thread to exit to restart agent"; mon.reset(0); sLogger << LDEBUG << "Monitor has exited"; } } while (mRestart); } void AgentConfiguration::stop() { mAgent->clear(); } Device *AgentConfiguration::defaultDevice() { const std::vector<Device*> &devices = mAgent->getDevices(); if (devices.size() == 1) return devices[0]; else return NULL; } static const char *timestamp(char *aBuffer) { #ifdef _WINDOWS SYSTEMTIME st; GetSystemTime(&st); sprintf(aBuffer, "%4d-%02d-%02dT%02d:%02d:%02d.%04dZ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); #else struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); strftime(aBuffer, 64, "%Y-%m-%dT%H:%M:%S", gmtime(&tv.tv_sec)); sprintf(aBuffer + strlen(aBuffer), ".%06dZ", (int) tv.tv_usec); #endif return aBuffer; } void AgentConfiguration::LoggerHook(const std::string& aLoggerName, const dlib::log_level& l, const dlib::uint64 aThreadId, const char* aMessage) { stringstream out; char buffer[64]; timestamp(buffer); out << buffer << ": " << l.name << " [" << aThreadId << "] " << aLoggerName << ": " << aMessage; #ifdef WIN32 out << "\r\n"; #else out << "\n"; #endif if (mLoggerFile != NULL) mLoggerFile->write(out.str().c_str()); else cout << out.str(); } static dlib::log_level string_to_log_level ( const std::string& level ) { using namespace std; if (level == "LALL" || level == "ALL" || level == "all") return LALL; else if (level == "LNONE" || level == "NONE" || level == "none") return LNONE; else if (level == "LTRACE" || level == "TRACE" || level == "trace") return LTRACE; else if (level == "LDEBUG" || level == "DEBUG" || level == "debug") return LDEBUG; else if (level == "LINFO" || level == "INFO" || level == "info") return LINFO; else if (level == "LWARN" || level == "WARN" || level == "warn") return LWARN; else if (level == "LERROR" || level == "ERROR" || level == "error") return LERROR; else if (level == "LFATAL" || level == "FATAL" || level == "fatal") return LFATAL; else { return LINFO; } } void AgentConfiguration::configureLogger(dlib::config_reader::kernel_1a &aReader) { if (mLoggerFile != NULL) delete mLoggerFile; if (mIsDebug) { set_all_logging_output_streams(cout); set_all_logging_levels(LDEBUG); } else { string name("agent.log"); RollingFileLogger::RollingSchedule sched = RollingFileLogger::NEVER; int maxSize = 10 * 1024 * 1024; int maxIndex = 9; if (aReader.is_block_defined("logger_config")) { const config_reader::kernel_1a& cr = aReader.block("logger_config"); if (cr.is_key_defined("logging_level")) set_all_logging_levels(string_to_log_level(cr["logging_level"])); else set_all_logging_levels(LINFO); if (cr.is_key_defined("output")) { string output = cr["output"]; if (output == "cout") set_all_logging_output_streams(cout); else if (output == "cerr") set_all_logging_output_streams(cerr); else { istringstream sin(output); string one, two, three; sin >> one; sin >> two; sin >> three; if (one == "file" && three.size() == 0) name = two; else name = one; } } string maxSizeStr = get_with_default(cr, "max_size", "10M"); stringstream ss(maxSizeStr); char mag = '\0'; ss >> maxSize >> mag; switch(mag) { case 'G': case 'g': maxSize *= 1024; case 'M': case 'm': maxSize *= 1024; case 'K': case 'k': maxSize *= 1024; case 'B': case 'b': case '\0': break; } maxIndex = get_with_default(cr, "max_index", maxIndex); string schedCfg = get_with_default(cr, "schedule", "NEVER"); if (schedCfg == "DAILY") sched = RollingFileLogger::DAILY; else if (schedCfg == "WEEKLY") sched = RollingFileLogger::WEEKLY; } mLoggerFile = new RollingFileLogger(name, maxIndex, maxSize, sched); set_all_logging_output_hooks<AgentConfiguration>(*this, &AgentConfiguration::LoggerHook); } } inline static void trim(std::string &str) { size_t index = str.find_first_not_of(" \r\t"); if (index != string::npos && index > 0) str.erase(0, index); index = str.find_last_not_of(" \r\t"); if (index != string::npos) str.erase(index + 1); } void AgentConfiguration::loadConfig(std::istream &aFile) { // Now get our configuration config_reader::kernel_1a reader(aFile); if (mLoggerFile == NULL) configureLogger(reader); bool defaultPreserve = get_bool_with_default(reader, "PreserveUUID", true); int port = get_with_default(reader, "Port", 5000); string serverIp = get_with_default(reader, "ServerIp", ""); int bufferSize = get_with_default(reader, "BufferSize", DEFAULT_SLIDING_BUFFER_EXP); int maxAssets = get_with_default(reader, "MaxAssets", DEFAULT_MAX_ASSETS); int checkpointFrequency = get_with_default(reader, "CheckpointFrequency", 1000); int legacyTimeout = get_with_default(reader, "LegacyTimeout", 600); int reconnectInterval = get_with_default(reader, "ReconnectInterval", 10 * 1000); bool ignoreTimestamps = get_bool_with_default(reader, "IgnoreTimestamps", false); bool conversionRequired = get_bool_with_default(reader, "ConversionRequired", true); bool upcaseValue = get_bool_with_default(reader, "UpcaseDataItemValue", true); mMonitorFiles = get_bool_with_default(reader, "MonitorConfigFiles", false); mMinimumConfigReloadAge = get_with_default(reader, "MinimumConfigReloadAge", 15); mPidFile = get_with_default(reader, "PidFile", "agent.pid"); const char *probe; struct stat buf; if (reader.is_key_defined("Devices")) { probe = reader["Devices"].c_str(); if (stat(probe, &buf) != 0) { throw runtime_error(((string) "Please make sure the Devices XML configuration " "file " + probe + " is in the current path ").c_str()); } } else { probe = "probe.xml"; if (stat(probe, &buf) != 0) probe = "Devices.xml"; if (stat(probe, &buf) != 0) { throw runtime_error(((string) "Please make sure the configuration " "file probe.xml or Devices.xml is in the current " "directory or specify the correct file " "in the configuration file " + mConfigFile + " using Devices = <file>").c_str()); } } mDevicesFile = probe; mName = get_with_default(reader, "ServiceName", "MTConnect Agent"); // Check for schema version string schemaVersion = get_with_default(reader, "SchemaVersion", ""); if (!schemaVersion.empty()) XmlPrinter::setSchemaVersion(schemaVersion); sLogger << LINFO << "Starting agent on port " << port; if (mAgent == NULL) mAgent = new Agent(probe, bufferSize, maxAssets, checkpointFrequency); mAgent->set_listening_port(port); mAgent->set_listening_ip(serverIp); mAgent->setLogStreamData(get_bool_with_default(reader, "LogStreams", false)); for (size_t i = 0; i < mAgent->getDevices().size(); i++) mAgent->getDevices()[i]->mPreserveUuid = defaultPreserve; if (XmlPrinter::getSchemaVersion().empty()) XmlPrinter::setSchemaVersion("1.3"); loadAllowPut(reader); loadAdapters(reader, defaultPreserve, legacyTimeout, reconnectInterval, ignoreTimestamps, conversionRequired, upcaseValue); // Files served by the Agent... allows schema files to be served by // agent. loadFiles(reader); // Load namespaces, allow for local file system serving as well. loadNamespace(reader, "DevicesNamespaces", &XmlPrinter::addDevicesNamespace); loadNamespace(reader, "StreamsNamespaces", &XmlPrinter::addStreamsNamespace); loadNamespace(reader, "AssetsNamespaces", &XmlPrinter::addAssetsNamespace); loadNamespace(reader, "ErrorNamespaces", &XmlPrinter::addErrorNamespace); loadStyle(reader, "DevicesStyle", &XmlPrinter::setDevicesStyle); loadStyle(reader, "StreamsStyle", &XmlPrinter::setStreamStyle); loadStyle(reader, "AssetsStyle", &XmlPrinter::setAssetsStyle); loadStyle(reader, "ErrorStyle", &XmlPrinter::setErrorStyle); loadTypes(reader); } void AgentConfiguration::loadAdapters(dlib::config_reader::kernel_1a &aReader, bool aDefaultPreserve, int aLegacyTimeout, int aReconnectInterval, bool aIgnoreTimestamps, bool aConversionRequired, bool aUpcaseValue) { Device *device; if (aReader.is_block_defined("Adapters")) { const config_reader::kernel_1a &adapters = aReader.block("Adapters"); std::vector<string> blocks; adapters.get_blocks(blocks); std::vector<string>::iterator block; for (block = blocks.begin(); block != blocks.end(); ++block) { const config_reader::kernel_1a &adapter = adapters.block(*block); string deviceName; if (adapter.is_key_defined("Device")) { deviceName = adapter["Device"].c_str(); } else { deviceName = *block; } device = mAgent->getDeviceByName(deviceName); if (device == NULL) { sLogger << LWARN << "Cannot locate device name '" << deviceName << "', trying default"; device = defaultDevice(); if (device != NULL) { deviceName = device->getName(); sLogger << LINFO << "Assigning default device " << deviceName << " to adapter"; } } if (device == NULL) { sLogger << LWARN << "Cannot locate device name '" << deviceName << "', assuming dynamic"; } const string host = get_with_default(adapter, "Host", (string)"localhost"); int port = get_with_default(adapter, "Port", 7878); int legacyTimeout = get_with_default(adapter, "LegacyTimeout", aLegacyTimeout); int reconnectInterval = get_with_default(adapter, "ReconnectInterval", aReconnectInterval); sLogger << LINFO << "Adding adapter for " << deviceName << " on " << host << ":" << port; Adapter *adp = mAgent->addAdapter(deviceName, host, port, false, legacyTimeout); device->mPreserveUuid = get_bool_with_default(adapter, "PreserveUUID", aDefaultPreserve); // Add additional device information if (adapter.is_key_defined("UUID")) device->setUuid(adapter["UUID"]); if (adapter.is_key_defined("Manufacturer")) device->setManufacturer(adapter["Manufacturer"]); if (adapter.is_key_defined("Station")) device->setStation(adapter["Station"]); if (adapter.is_key_defined("SerialNumber")) device->setSerialNumber(adapter["SerialNumber"]); adp->setDupCheck(get_bool_with_default(adapter, "FilterDuplicates", adp->isDupChecking())); adp->setAutoAvailable(get_bool_with_default(adapter, "AutoAvailable", adp->isAutoAvailable())); adp->setIgnoreTimestamps(get_bool_with_default(adapter, "IgnoreTimestamps", aIgnoreTimestamps || adp->isIgnoringTimestamps())); adp->setConversionRequired(get_bool_with_default(adapter, "ConversionRequired", aConversionRequired)); adp->setRealTime(get_bool_with_default(adapter, "RealTime", false)); adp->setRelativeTime(get_bool_with_default(adapter, "RelativeTime", false)); adp->setReconnectInterval(reconnectInterval); adp->setUpcaseValue(get_bool_with_default(adapter, "UpcaseDataItemValue", aUpcaseValue)); if (adapter.is_key_defined("AdditionalDevices")) { istringstream devices(adapter["AdditionalDevices"]); string name; while (getline(devices, name, ',')) { size_t index = name.find_first_not_of(" \r\t"); if (index != string::npos && index > 0) name.erase(0, index); index = name.find_last_not_of(" \r\t"); if (index != string::npos) name.erase(index + 1); adp->addDevice(name); } } } } else if ((device = defaultDevice()) != NULL) { sLogger << LINFO << "Adding default adapter for " << device->getName() << " on localhost:7878"; Adapter *adp = mAgent->addAdapter(device->getName(), "localhost", 7878, false, aLegacyTimeout); adp->setIgnoreTimestamps(aIgnoreTimestamps || adp->isIgnoringTimestamps()); adp->setReconnectInterval(aReconnectInterval); device->mPreserveUuid = aDefaultPreserve; } else { throw runtime_error("Adapters must be defined if more than one device is present"); } } void AgentConfiguration::loadAllowPut(dlib::config_reader::kernel_1a &aReader) { bool putEnabled = get_bool_with_default(aReader, "AllowPut", false); mAgent->enablePut(putEnabled); string putHosts = get_with_default(aReader, "AllowPutFrom", ""); if (!putHosts.empty()) { istringstream toParse(putHosts); string putHost; do { getline(toParse, putHost, ','); trim(putHost); if (!putHost.empty()) { string ip; int n; for (n = 0; dlib::hostname_to_ip(putHost, ip, n) == 0 && ip == "0.0.0.0"; n++) ip = ""; if (!ip.empty()) { mAgent->enablePut(); mAgent->allowPutFrom(ip); } } } while (!toParse.eof()); } } void AgentConfiguration::loadNamespace(dlib::config_reader::kernel_1a &aReader, const char *aNamespaceType, NamespaceFunction *aCallback) { // Load namespaces, allow for local file system serving as well. if (aReader.is_block_defined(aNamespaceType)) { const config_reader::kernel_1a &namespaces = aReader.block(aNamespaceType); std::vector<string> blocks; namespaces.get_blocks(blocks); std::vector<string>::iterator block; for (block = blocks.begin(); block != blocks.end(); ++block) { const config_reader::kernel_1a &ns = namespaces.block(*block); if (*block != "m" && !ns.is_key_defined("Urn")) { sLogger << LERROR << "Name space must have a Urn: " << *block; } else { string location, urn; if (ns.is_key_defined("Location")) location = ns["Location"]; if (ns.is_key_defined("Urn")) urn = ns["Urn"]; (*aCallback)(urn, location, *block); if (ns.is_key_defined("Path") && !location.empty()) mAgent->registerFile(location, ns["Path"]); } } } } void AgentConfiguration::loadFiles(dlib::config_reader::kernel_1a &aReader) { if (aReader.is_block_defined("Files")) { const config_reader::kernel_1a &files = aReader.block("Files"); std::vector<string> blocks; files.get_blocks(blocks); std::vector<string>::iterator block; for (block = blocks.begin(); block != blocks.end(); ++block) { const config_reader::kernel_1a &file = files.block(*block); if (!file.is_key_defined("Location") || !file.is_key_defined("Path")) { sLogger << LERROR << "Name space must have a Location (uri) or Directory and Path: " << *block; } else { mAgent->registerFile(file["Location"], file["Path"]); } } } } void AgentConfiguration::loadStyle(dlib::config_reader::kernel_1a &aReader, const char *aDoc, StyleFunction *aFunction) { if (aReader.is_block_defined(aDoc)) { const config_reader::kernel_1a &doc = aReader.block(aDoc); if (!doc.is_key_defined("Location")) { sLogger << LERROR << "A style must have a Location: " << aDoc; } else { string location = doc["Location"]; aFunction(location); if (doc.is_key_defined("Path")) mAgent->registerFile(location, doc["Path"]); } } } void AgentConfiguration::loadTypes(dlib::config_reader::kernel_1a &aReader) { if (aReader.is_block_defined("MimeTypes")) { const config_reader::kernel_1a &types = aReader.block("MimeTypes"); std::vector<string> keys; types.get_keys(keys); std::vector<string>::iterator key; for (key = keys.begin(); key != keys.end(); ++key) { mAgent->addMimeType(*key, types[*key]); } } }
33.928463
135
0.636759
markovchainz
03af014a9d8ef72ced695c343c136bd7c4e82d97
13,959
cpp
C++
src/systemfonts.cpp
kevinushey/systemfonts
597f94f1cb55ba7693c5534638978924fa6a6394
[ "MIT" ]
null
null
null
src/systemfonts.cpp
kevinushey/systemfonts
597f94f1cb55ba7693c5534638978924fa6a6394
[ "MIT" ]
null
null
null
src/systemfonts.cpp
kevinushey/systemfonts
597f94f1cb55ba7693c5534638978924fa6a6394
[ "MIT" ]
null
null
null
#include <string> #include <R.h> #include <Rinternals.h> #include <R_ext/GraphicsEngine.h> #include "systemfonts.h" #include "utils.h" #include "FontDescriptor.h" // these functions are implemented by the platform ResultSet *getAvailableFonts(); ResultSet *findFonts(FontDescriptor *); FontDescriptor *findFont(FontDescriptor *); FontDescriptor *substituteFont(char *, char *); void resetFontCache(); // Default fonts based on browser behaviour #if defined _WIN32 #define SANS "Arial" #define SERIF "Times New Roman" #define MONO "Courier New" #elif defined __APPLE__ #define SANS "Helvetica" #define SERIF "Times" #define MONO "Courier" #else #define SANS "sans" #define SERIF "serif" #define MONO "mono" #endif bool locate_in_registry(const char *family, int italic, int bold, FontLoc& res) { FontReg& registry = get_font_registry(); if (registry.empty()) return false; auto search = registry.find(std::string(family)); if (search == registry.end()) { return false; } int index = bold ? (italic ? 3 : 1) : (italic ? 2 : 0); res.first = search->second[index].first; res.second = search->second[index].second; return true; } int locate_font(const char *family, int italic, int bold, char *path, int max_path_length) { FontLoc registry_match; if (locate_in_registry(family, italic, bold, registry_match)) { strncpy(path, registry_match.first.c_str(), max_path_length); return registry_match.second; } const char* resolved_family = family; if (strcmp_no_case(family, "") || strcmp_no_case(family, "sans")) { resolved_family = SANS; } else if (strcmp_no_case(family, "serif")) { resolved_family = SERIF; } else if (strcmp_no_case(family, "mono")) { resolved_family = MONO; } FontDescriptor font_desc(resolved_family, italic, bold); FontDescriptor* font_loc = findFont(&font_desc); int index; if (font_loc == NULL) { SEXP fallback_call = PROTECT(Rf_lang1(Rf_install("get_fallback"))); SEXP fallback = PROTECT(Rf_eval(fallback_call, sf_ns_env)); SEXP fallback_path = VECTOR_ELT(fallback, 0); strncpy(path, CHAR(STRING_ELT(fallback_path, 0)), max_path_length); index = INTEGER(VECTOR_ELT(fallback, 1))[0]; UNPROTECT(2); } else { strncpy(path, font_loc->path, max_path_length); index = font_loc->index; } delete font_loc; return index; } SEXP match_font(SEXP family, SEXP italic, SEXP bold) { char *path = new char[PATH_MAX+1]; path[PATH_MAX] = '\0'; int index = locate_font(Rf_translateCharUTF8(STRING_ELT(family, 0)), LOGICAL(italic)[0], LOGICAL(bold)[0], path, PATH_MAX); SEXP font = PROTECT(Rf_allocVector(VECSXP, 2)); SET_VECTOR_ELT(font, 0, Rf_mkString(path)); SET_VECTOR_ELT(font, 1, Rf_ScalarInteger(index)); SEXP names = PROTECT(Rf_allocVector(STRSXP, 2)); SET_STRING_ELT(names, 0, Rf_mkChar("path")); SET_STRING_ELT(names, 1, Rf_mkChar("index")); Rf_setAttrib(font, Rf_install("names"), names); delete[] path; UNPROTECT(2); return font; } SEXP system_fonts() { SEXP res = PROTECT(Rf_allocVector(VECSXP, 9)); SEXP cl = PROTECT(Rf_allocVector(STRSXP, 3)); SET_STRING_ELT(cl, 0, Rf_mkChar("tbl_df")); SET_STRING_ELT(cl, 1, Rf_mkChar("tbl")); SET_STRING_ELT(cl, 2, Rf_mkChar("data.frame")); Rf_classgets(res, cl); SEXP names = PROTECT(Rf_allocVector(STRSXP, 9)); SET_STRING_ELT(names, 0, Rf_mkChar("path")); SET_STRING_ELT(names, 1, Rf_mkChar("index")); SET_STRING_ELT(names, 2, Rf_mkChar("name")); SET_STRING_ELT(names, 3, Rf_mkChar("family")); SET_STRING_ELT(names, 4, Rf_mkChar("style")); SET_STRING_ELT(names, 5, Rf_mkChar("weight")); SET_STRING_ELT(names, 6, Rf_mkChar("width")); SET_STRING_ELT(names, 7, Rf_mkChar("italic")); SET_STRING_ELT(names, 8, Rf_mkChar("monospace")); setAttrib(res, Rf_install("names"), names); ResultSet* all_fonts = getAvailableFonts(); int n = all_fonts->n_fonts(); SEXP path = PROTECT(Rf_allocVector(STRSXP, n)); SEXP index = PROTECT(Rf_allocVector(INTSXP, n)); SEXP name = PROTECT(Rf_allocVector(STRSXP, n)); SEXP family = PROTECT(Rf_allocVector(STRSXP, n)); SEXP style = PROTECT(Rf_allocVector(STRSXP, n)); SEXP fct_cl = PROTECT(Rf_allocVector(STRSXP, 2)); SET_STRING_ELT(fct_cl, 0, Rf_mkChar("ordered")); SET_STRING_ELT(fct_cl, 1, Rf_mkChar("factor")); SEXP weight = PROTECT(Rf_allocVector(INTSXP, n)); SEXP weight_lvl = PROTECT(Rf_allocVector(STRSXP, 9)); SET_STRING_ELT(weight_lvl, 0, Rf_mkChar("thin")); SET_STRING_ELT(weight_lvl, 1, Rf_mkChar("ultralight")); SET_STRING_ELT(weight_lvl, 2, Rf_mkChar("light")); SET_STRING_ELT(weight_lvl, 3, Rf_mkChar("normal")); SET_STRING_ELT(weight_lvl, 4, Rf_mkChar("medium")); SET_STRING_ELT(weight_lvl, 5, Rf_mkChar("semibold")); SET_STRING_ELT(weight_lvl, 6, Rf_mkChar("bold")); SET_STRING_ELT(weight_lvl, 7, Rf_mkChar("ultrabold")); SET_STRING_ELT(weight_lvl, 8, Rf_mkChar("heavy")); Rf_classgets(weight, fct_cl); Rf_setAttrib(weight, Rf_install("levels"), weight_lvl); SEXP width = PROTECT(Rf_allocVector(INTSXP, n)); SEXP width_lvl = PROTECT(Rf_allocVector(STRSXP, 9)); SET_STRING_ELT(width_lvl, 0, Rf_mkChar("ultracondensed")); SET_STRING_ELT(width_lvl, 1, Rf_mkChar("extracondensed")); SET_STRING_ELT(width_lvl, 2, Rf_mkChar("condensed")); SET_STRING_ELT(width_lvl, 3, Rf_mkChar("semicondensed")); SET_STRING_ELT(width_lvl, 4, Rf_mkChar("normal")); SET_STRING_ELT(width_lvl, 5, Rf_mkChar("semiexpanded")); SET_STRING_ELT(width_lvl, 6, Rf_mkChar("expanded")); SET_STRING_ELT(width_lvl, 7, Rf_mkChar("extraexpanded")); SET_STRING_ELT(width_lvl, 8, Rf_mkChar("ultraexpanded")); Rf_classgets(width, fct_cl); Rf_setAttrib(width, Rf_install("levels"), width_lvl); SEXP italic = PROTECT(Rf_allocVector(LGLSXP, n)); SEXP monospace = PROTECT(Rf_allocVector(LGLSXP, n)); SET_VECTOR_ELT(res, 0, path); SET_VECTOR_ELT(res, 1, index); SET_VECTOR_ELT(res, 2, name); SET_VECTOR_ELT(res, 3, family); SET_VECTOR_ELT(res, 4, style); SET_VECTOR_ELT(res, 5, weight); SET_VECTOR_ELT(res, 6, width); SET_VECTOR_ELT(res, 7, italic); SET_VECTOR_ELT(res, 8, monospace); int i = 0; for (ResultSet::iterator it = all_fonts->begin(); it != all_fonts->end(); it++) { SET_STRING_ELT(path, i, Rf_mkChar((*it)->path)); INTEGER(index)[i] = (*it)->index; SET_STRING_ELT(name, i, Rf_mkChar((*it)->postscriptName)); SET_STRING_ELT(family, i, Rf_mkChar((*it)->family)); SET_STRING_ELT(style, i, Rf_mkChar((*it)->style)); if ((*it)->weight == 0) { INTEGER(weight)[i] = NA_INTEGER; } else { INTEGER(weight)[i] = (*it)->weight / 100; } if ((*it)->width == 0) { INTEGER(width)[i] = NA_INTEGER; } else { INTEGER(width)[i] = (int) (*it)->width; } LOGICAL(italic)[i] = (int) (*it)->italic; LOGICAL(monospace)[i] = (int) (*it)->monospace; ++i; } delete all_fonts; SEXP row_names = PROTECT(Rf_allocVector(REALSXP, 2)); REAL(row_names)[0] = NA_REAL; REAL(row_names)[1] = -n; setAttrib(res, Rf_install("row.names"), row_names); UNPROTECT(16); return res; } SEXP reset_font_cache() { resetFontCache(); return R_NilValue; } SEXP dev_string_widths(SEXP strings, SEXP family, SEXP face, SEXP size, SEXP cex, SEXP unit) { GEUnit u = GE_INCHES; switch (INTEGER(unit)[0]) { case 0: u = GE_CM; break; case 1: u = GE_INCHES; break; case 2: u = GE_DEVICE; break; case 3: u = GE_NDC; break; } pGEDevDesc dev = GEcurrentDevice(); R_GE_gcontext gc; double width; int n_total = LENGTH(strings); int scalar_family = LENGTH(family) == 1; int scalar_rest = LENGTH(face) == 1; strcpy(gc.fontfamily, Rf_translateCharUTF8(STRING_ELT(family, 0))); gc.fontface = INTEGER(face)[0]; gc.ps = REAL(size)[0]; gc.cex = REAL(cex)[0]; SEXP res = PROTECT(allocVector(REALSXP, n_total)); for (int i = 0; i < n_total; ++i) { if (i > 0 && !scalar_family) { strcpy(gc.fontfamily, Rf_translateCharUTF8(STRING_ELT(family, i))); } if (i > 0 && !scalar_rest) { gc.fontface = INTEGER(face)[i]; gc.ps = REAL(size)[i]; gc.cex = REAL(cex)[i]; } width = GEStrWidth( CHAR(STRING_ELT(strings, i)), getCharCE(STRING_ELT(strings, i)), &gc, dev ); REAL(res)[i] = GEfromDeviceWidth(width, u, dev); } UNPROTECT(1); return res; } SEXP dev_string_metrics(SEXP strings, SEXP family, SEXP face, SEXP size, SEXP cex, SEXP unit) { GEUnit u = GE_INCHES; switch (INTEGER(unit)[0]) { case 0: u = GE_CM; break; case 1: u = GE_INCHES; break; case 2: u = GE_DEVICE; break; case 3: u = GE_NDC; break; } pGEDevDesc dev = GEcurrentDevice(); R_GE_gcontext gc; double width, ascent, descent; int n_total = LENGTH(strings); int scalar_family = LENGTH(family) == 1; int scalar_rest = LENGTH(face) == 1; strcpy(gc.fontfamily, Rf_translateCharUTF8(STRING_ELT(family, 0))); gc.fontface = INTEGER(face)[0]; gc.ps = REAL(size)[0]; gc.cex = REAL(cex)[0]; SEXP w = PROTECT(allocVector(REALSXP, n_total)); SEXP a = PROTECT(allocVector(REALSXP, n_total)); SEXP d = PROTECT(allocVector(REALSXP, n_total)); for (int i = 0; i < n_total; ++i) { if (i > 0 && !scalar_family) { strcpy(gc.fontfamily, Rf_translateCharUTF8(STRING_ELT(family, i))); } if (i > 0 && !scalar_rest) { gc.fontface = INTEGER(face)[i]; gc.ps = REAL(size)[i]; gc.cex = REAL(cex)[i]; } GEStrMetric( CHAR(STRING_ELT(strings, i)), getCharCE(STRING_ELT(strings, i)), &gc, &ascent, &descent, &width, dev ); REAL(w)[i] = GEfromDeviceWidth(width, u, dev); REAL(a)[i] = GEfromDeviceWidth(ascent, u, dev); REAL(d)[i] = GEfromDeviceWidth(descent, u, dev); } SEXP res = PROTECT(allocVector(VECSXP, 3)); SET_VECTOR_ELT(res, 0, w); SET_VECTOR_ELT(res, 1, a); SET_VECTOR_ELT(res, 2, d); SEXP row_names = PROTECT(Rf_allocVector(REALSXP, 2)); REAL(row_names)[0] = NA_REAL; REAL(row_names)[1] = -n_total; setAttrib(res, Rf_install("row.names"), row_names); SEXP names = PROTECT(Rf_allocVector(STRSXP, 3)); SET_STRING_ELT(names, 0, Rf_mkChar("width")); SET_STRING_ELT(names, 1, Rf_mkChar("ascent")); SET_STRING_ELT(names, 2, Rf_mkChar("descent")); setAttrib(res, Rf_install("names"), names); SEXP cl = PROTECT(Rf_allocVector(STRSXP, 3)); SET_STRING_ELT(cl, 0, Rf_mkChar("tbl_df")); SET_STRING_ELT(cl, 1, Rf_mkChar("tbl")); SET_STRING_ELT(cl, 2, Rf_mkChar("data.frame")); Rf_classgets(res, cl); UNPROTECT(7); return res; } SEXP register_font(SEXP family, SEXP paths, SEXP indices) { FontReg& registry = get_font_registry(); std::string name = Rf_translateCharUTF8(STRING_ELT(family, 0)); FontCollection col; for (int i = 0; i < LENGTH(paths); ++i) { std::string font_path = Rf_translateCharUTF8(STRING_ELT(paths, i)); FontLoc font(font_path, INTEGER(indices)[i]); col.push_back(font); } registry[name] = col; return R_NilValue; } SEXP clear_registry() { FontReg& registry = get_font_registry(); registry.clear(); return R_NilValue; } SEXP registry_fonts() { FontReg& registry = get_font_registry(); int n_reg = registry.size(); int n = n_reg * 4; SEXP res = PROTECT(Rf_allocVector(VECSXP, 6)); SEXP cl = PROTECT(Rf_allocVector(STRSXP, 3)); SET_STRING_ELT(cl, 0, Rf_mkChar("tbl_df")); SET_STRING_ELT(cl, 1, Rf_mkChar("tbl")); SET_STRING_ELT(cl, 2, Rf_mkChar("data.frame")); Rf_classgets(res, cl); SEXP names = PROTECT(Rf_allocVector(STRSXP, 6)); SET_STRING_ELT(names, 0, Rf_mkChar("path")); SET_STRING_ELT(names, 1, Rf_mkChar("index")); SET_STRING_ELT(names, 2, Rf_mkChar("family")); SET_STRING_ELT(names, 3, Rf_mkChar("style")); SET_STRING_ELT(names, 4, Rf_mkChar("weight")); SET_STRING_ELT(names, 5, Rf_mkChar("italic")); setAttrib(res, Rf_install("names"), names); SEXP path = PROTECT(Rf_allocVector(STRSXP, n)); SEXP index = PROTECT(Rf_allocVector(INTSXP, n)); SEXP family = PROTECT(Rf_allocVector(STRSXP, n)); SEXP style = PROTECT(Rf_allocVector(STRSXP, n)); SEXP fct_cl = PROTECT(Rf_allocVector(STRSXP, 2)); SET_STRING_ELT(fct_cl, 0, Rf_mkChar("ordered")); SET_STRING_ELT(fct_cl, 1, Rf_mkChar("factor")); SEXP weight = PROTECT(Rf_allocVector(INTSXP, n)); SEXP weight_lvl = PROTECT(Rf_allocVector(STRSXP, 2)); SET_STRING_ELT(weight_lvl, 0, Rf_mkChar("normal")); SET_STRING_ELT(weight_lvl, 1, Rf_mkChar("bold")); Rf_classgets(weight, fct_cl); Rf_setAttrib(weight, Rf_install("levels"), weight_lvl); SEXP italic = PROTECT(Rf_allocVector(LGLSXP, n)); SET_VECTOR_ELT(res, 0, path); SET_VECTOR_ELT(res, 1, index); SET_VECTOR_ELT(res, 2, family); SET_VECTOR_ELT(res, 3, style); SET_VECTOR_ELT(res, 4, weight); SET_VECTOR_ELT(res, 5, italic); int i = 0; for (auto it = registry.begin(); it != registry.end(); ++it) { for (int j = 0; j < 4; j++) { SET_STRING_ELT(path, i, Rf_mkChar(it->second[j].first.c_str())); INTEGER(index)[i] = it->second[j].second; SET_STRING_ELT(family, i, Rf_mkChar(it->first.c_str())); switch (j) { case 0: SET_STRING_ELT(style, i, Rf_mkChar("Regular")); break; case 1: SET_STRING_ELT(style, i, Rf_mkChar("Bold")); break; case 2: SET_STRING_ELT(style, i, Rf_mkChar("Italic")); break; case 3: SET_STRING_ELT(style, i, Rf_mkChar("Bold Italic")); break; } INTEGER(weight)[i] = 1 + (int) (j == 1 || j == 3); INTEGER(italic)[i] = (int) (j > 1); ++i; } } SEXP row_names = PROTECT(Rf_allocVector(REALSXP, 2)); REAL(row_names)[0] = NA_REAL; REAL(row_names)[1] = -n; setAttrib(res, Rf_install("row.names"), row_names); UNPROTECT(12); return res; } SEXP sf_ns_env = NULL; void sf_init(SEXP ns) { sf_ns_env = ns; }
31.368539
95
0.668243
kevinushey
03b2d68381cf703fe34e113035b6220adb396936
4,754
cpp
C++
src/parseInput/parseTiledModel.cpp
daklinus/model-synthesis
1c2c0c18df72bba82e36c092fc639776dabd878c
[ "MIT" ]
47
2021-07-30T12:32:14.000Z
2022-03-20T22:02:46.000Z
src/parseInput/parseTiledModel.cpp
daklinus/model-synthesis
1c2c0c18df72bba82e36c092fc639776dabd878c
[ "MIT" ]
1
2021-11-29T18:26:53.000Z
2021-11-29T18:26:53.000Z
src/parseInput/parseTiledModel.cpp
daklinus/model-synthesis
1c2c0c18df72bba82e36c092fc639776dabd878c
[ "MIT" ]
3
2021-09-08T11:31:59.000Z
2022-01-05T14:33:07.000Z
// Copyright (c) 2021 Paul Merrell #include <iostream> #include <fstream> #include <sstream> #include "parseTiledModel.h" using namespace std; // Parse a <tiledmodel /> input. void parseTiledModel(InputSettings& settings) { string path = "samples/" + settings.name; ifstream modelFile(path, ios::in); if (!modelFile) { cout << "ERROR: The model file :" << path << " does not exist.\n" << endl; return; } char temp[1000]; modelFile.getline(temp, 1000); modelFile.getline(temp, 1000); modelFile.getline(temp, 1000); // Read in the size and create the example model. int xSize, ySize, zSize; modelFile >> xSize; modelFile >> ySize; modelFile >> zSize; int*** example = new int** [xSize]; for (int x = 0; x < xSize; x++) { example[x] = new int* [ySize]; for (int y = 0; y < ySize; y++) { example[x][y] = new int[zSize]; } } // Read in the labels in the example model. int buffer; modelFile >> buffer; for (int z = 0; z < zSize; z++) { for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { example[x][y][z] = buffer; modelFile >> buffer; } } } // Find the number of labels in the model. int numLabels = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { for (int z = 0; z < zSize; z++) { numLabels = max(numLabels, example[x][y][z]); } } } numLabels++; settings.numLabels = numLabels; // The transition describes which labels can be next to each other. // When transition[direction][labelA][labelB] is true that means labelA // can be just below labelB in the specified direction where x = 0, y = 1, z = 2. bool*** transition = createTransition(numLabels); settings.transition = transition; // Compute the transition. for (int x = 0; x < xSize - 1; x++) { for (int y = 0; y < ySize; y++) { for (int z = 0; z < zSize; z++) { int labelA = example[x][y][z]; int labelB = example[x + 1][y][z]; transition[0][labelA][labelB] = true; } } } for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize - 1; y++) { for (int z = 0; z < zSize; z++) { int labelA = example[x][y][z]; int labelB = example[x][y + 1][z]; transition[1][labelA][labelB] = true; } } } for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { for (int z = 0; z < zSize - 1; z++) { int labelA = example[x][y][z]; int labelB = example[x][y][z + 1]; transition[2][labelA][labelB] = true; } } } // The number of labels of each type in the model. int* labelCount = new int[numLabels]; for (int i = 0; i < numLabels; i++) { labelCount[i] = 0; } for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { for (int z = 0; z < zSize; z++) { labelCount[example[x][y][z]]++; } } } // We could use the label count, but equal weight also works. for (int i = 0; i < numLabels; i++) { settings.weights.push_back(1.0); } // Find the label that should initially appear at the very bottom. // And find the ground plane label. int bottomLabel = -1; int groundLabel = -1; int* onBottom = new int[numLabels]; for (int i = 0; i < numLabels; i++) { onBottom[i] = 0; } for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { onBottom[example[x][y][0]]++; } } // The bottom and ground labels should be tileable and appear frequently. int bottomCount = 0; for (int i = 0; i < numLabels; i++) { if (transition[0][i][i] && transition[1][i][i] && (onBottom[i] > bottomCount)) { bottomLabel = i; bottomCount = onBottom[i]; } } if (bottomLabel != -1) { int groundCount = 0; for (int i = 0; i < numLabels; i++) { if (transition[0][i][i] && transition[1][i][i] && transition[2][bottomLabel][i] && transition[2][i][0] && (labelCount[i] > groundCount)) { groundLabel = i; groundCount = labelCount[i]; } } } if (groundLabel == -1 || bottomLabel == -1) { bool modifyInBlocks = (settings.blockSize[0] < settings.size[0] || settings.blockSize[1] < settings.size[1]); if (modifyInBlocks) { cout << "The example model has no tileable ground plane. The new model can not be modified in blocks.\n" << endl; } } // Set the initial labels. settings.initialLabels = new int[settings.size[2]]; settings.initialLabels[0] = bottomLabel; settings.initialLabels[1] = groundLabel; for (int z = 0; z < settings.size[2]; z++) { if (z < zSize) { settings.initialLabels[z] = example[0][0][z]; } else { settings.initialLabels[z] = 0; } } // Delete the example model. for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { delete example[x][y]; } delete example[x]; } delete example; stringstream stream; stream << modelFile.rdbuf(); settings.tiledModelSuffix += stream.str(); }
26.858757
116
0.592133
daklinus
03b5370273740e53b66b1aecc114f74eb5db2b8a
512
hpp
C++
include/jln/mp/functional/flip.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
include/jln/mp/functional/flip.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
include/jln/mp/functional/flip.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#pragma once #include <jln/mp/list/listify.hpp> #include <jln/mp/utility/unpack.hpp> #include <jln/mp/functional/call.hpp> namespace jln::mp { /// \ingroup functional /// Invokes a \function with its two first arguments reversed. /// \treturn \sequence template<class C = listify> struct flip { template<class x0, class x1, class... xs> using f = call<C, x1, x0, xs...>; }; namespace emp { template<class L, class C = mp::listify> using flip = unpack<L, mp::flip<C>>; } }
19.692308
64
0.640625
jonathanpoelen
03b7acf4293f327946ef2e921c4ebbaf9182fea7
3,384
hpp
C++
libs/Delphi/src/Syntax/DelphiParameterSyntax.hpp
henrikfroehling/interlinck
d9d947b890d9286c6596c687fcfcf016ef820d6b
[ "MIT" ]
null
null
null
libs/Delphi/src/Syntax/DelphiParameterSyntax.hpp
henrikfroehling/interlinck
d9d947b890d9286c6596c687fcfcf016ef820d6b
[ "MIT" ]
19
2021-12-01T20:37:23.000Z
2022-02-14T21:05:43.000Z
libs/Delphi/src/Syntax/DelphiParameterSyntax.hpp
henrikfroehling/interlinck
d9d947b890d9286c6596c687fcfcf016ef820d6b
[ "MIT" ]
null
null
null
#ifndef ARGOS_DELPHI_SYNTAX_DELPHIPARAMETERSYNTAX_H #define ARGOS_DELPHI_SYNTAX_DELPHIPARAMETERSYNTAX_H #include <string> #include <argos-Core/Syntax/SyntaxVariant.hpp> #include <argos-Core/Types.hpp> #include "Syntax/DelphiSyntaxNode.hpp" namespace argos::Core::Syntax { class ISyntaxToken; } namespace argos::Delphi::Syntax { class DelphiEqualsValueClauseSyntax; class DelphiTypeDeclarationSyntax; // ---------------------------------------------------------------------------- // DelphiParameterType // ---------------------------------------------------------------------------- class DelphiParameterType : public DelphiSyntaxNode { public: DelphiParameterType() = delete; explicit DelphiParameterType(const Core::Syntax::ISyntaxToken* colonToken, const DelphiTypeDeclarationSyntax* type) noexcept; ~DelphiParameterType() noexcept override = default; const Core::Syntax::ISyntaxToken* colonToken() const noexcept; const DelphiTypeDeclarationSyntax* type() const noexcept; argos_size childCount() const noexcept override; Core::Syntax::SyntaxVariant child(argos_size index) const noexcept override; Core::Syntax::SyntaxVariant first() const noexcept override; Core::Syntax::SyntaxVariant last() const noexcept override; std::string typeName() const noexcept override; private: const Core::Syntax::ISyntaxToken* _colonToken; const DelphiTypeDeclarationSyntax* _type; }; // ---------------------------------------------------------------------------- // DelphiParameterSyntax // ---------------------------------------------------------------------------- class DelphiParameterSyntax : public DelphiSyntaxNode { public: DelphiParameterSyntax() = delete; explicit DelphiParameterSyntax(Core::Syntax::SyntaxVariantList&& attributes, Core::Syntax::SyntaxVariantList&& parameterNames, const DelphiParameterType* parameterType = nullptr, const Core::Syntax::ISyntaxToken* parameterTypeKeyword = nullptr, const DelphiEqualsValueClauseSyntax* defaultExpression = nullptr) noexcept; ~DelphiParameterSyntax() noexcept override = default; const Core::Syntax::ISyntaxToken* parameterTypeKeyword() const noexcept; const Core::Syntax::SyntaxVariantList& attributes() const noexcept; const Core::Syntax::SyntaxVariantList& parameterNames() const noexcept; const DelphiParameterType* parameterType() const noexcept; const DelphiEqualsValueClauseSyntax* defaultExpression() const noexcept; argos_size childCount() const noexcept override; Core::Syntax::SyntaxVariant child(argos_size index) const noexcept override; Core::Syntax::SyntaxVariant first() const noexcept override; Core::Syntax::SyntaxVariant last() const noexcept override; std::string typeName() const noexcept override; protected: const Core::Syntax::ISyntaxToken* _parameterTypeKeyword; // optional Core::Syntax::SyntaxVariantList _attributes; Core::Syntax::SyntaxVariantList _parameterNames; const DelphiParameterType* _parameterType; // optional const DelphiEqualsValueClauseSyntax* _defaultExpression; // optional }; } // end namespace argos::Delphi::Syntax #endif // ARGOS_DELPHI_SYNTAX_DELPHIPARAMETERSYNTAX_H
38.022472
110
0.673168
henrikfroehling
03b8677a9dee93d9a96f67472fefc39dbe332750
4,681
cpp
C++
tests/symbols_tests.cpp
ruthenium96/july
62f93b33253cd7324b36c851afc58b6f80c00248
[ "Apache-2.0" ]
null
null
null
tests/symbols_tests.cpp
ruthenium96/july
62f93b33253cd7324b36c851afc58b6f80c00248
[ "Apache-2.0" ]
5
2021-11-28T14:29:35.000Z
2022-03-21T08:16:20.000Z
tests/symbols_tests.cpp
ruthenium96/july
62f93b33253cd7324b36c851afc58b6f80c00248
[ "Apache-2.0" ]
null
null
null
#include "gtest/gtest.h" #include "src/common/runner/Runner.h" TEST(symbols, throw_add_the_same_symbol_name) { model::symbols::Symbols symbols(2); symbols.addSymbol("same", 10); EXPECT_THROW(symbols.addSymbol("same", 10), std::invalid_argument); } TEST(symbols, throw_assign_the_same_exchange) { model::symbols::Symbols symbols(2); auto J = symbols.addSymbol("same", 10, model::symbols::J); symbols.assignSymbolToIsotropicExchange(J, 0, 1); EXPECT_THROW(symbols.assignSymbolToIsotropicExchange(J, 0, 1), std::invalid_argument); } // TODO: make these tests pass //TEST(symbols, throw_2222_gfactor_all_were_not_initialized) { // std::vector<int> mults = {2, 2, 2, 2}; // // runner::Runner runner(mults); // // runner.TzSort(); // // double J = 10; // double g = 2.0; // runner.modifySymbol().addSymbol("J", J); // runner.modifySymbol().addSymbol("g1", g); // runner.AddIsotropicExchange("J", 0, 1); // runner.AddIsotropicExchange("J", 1, 2); // runner.AddIsotropicExchange("J", 2, 3); // runner.AddIsotropicExchange("J", 3, 0); // // runner.FinalizeIsotropicInteraction(); // // EXPECT_THROW(runner.BuildMatrices(), std::length_error); //} // //TEST(symbols, throw_2222_gfactor_any_was_not_initialized) { // std::vector<int> mults = {2, 2, 2, 2}; // // runner::Runner runner(mults); // // runner.TzSort(); // // double J = 10; // double g = 2.0; // runner.modifySymbol().addSymbol("J", J); // runner.modifySymbol().addSymbol("g1", g); // runner.AddIsotropicExchange("J", 0, 1); // runner.AddIsotropicExchange("J", 1, 2); // runner.AddIsotropicExchange("J", 2, 3); // runner.AddIsotropicExchange("J", 3, 0); // runner.AddGFactor("g1", 0); // runner.AddGFactor("g1", 1); // runner.AddGFactor("g1", 2); // // runner.FinalizeIsotropicInteraction(); // // EXPECT_THROW(runner.BuildMatrices(), std::invalid_argument); //} TEST(symbols, throw_set_new_value_to_unchangeable_symbol) { model::symbols::Symbols symbols_(10); auto unchangeable = symbols_.addSymbol("Unchangeable", NAN, false, model::symbols::not_specified); EXPECT_THROW( symbols_.setNewValueToChangeableSymbol(unchangeable, INFINITY), std::invalid_argument); } TEST(symbols, throw_specified_not_as_J_symbol) { size_t number_of_spins = 10; model::symbols::Symbols symbols_(number_of_spins); double gChangeable = 2; auto not_specified = symbols_.addSymbol("not_specified", NAN, true, model::symbols::not_specified); symbols_.assignSymbolToIsotropicExchange(not_specified, 1, 3); auto g_changeable = symbols_.addSymbol("gChangeable", gChangeable, true, model::symbols::g_factor); EXPECT_THROW( symbols_.assignSymbolToIsotropicExchange(g_changeable, 2, 7), std::invalid_argument); } TEST(symbols, throw_specified_not_as_g_symbol) { size_t number_of_spins = 10; model::symbols::Symbols symbols_(number_of_spins); double JChangeable = 10; auto not_specified = symbols_.addSymbol("not_specified", NAN, true, model::symbols::not_specified); symbols_.assignSymbolToGFactor(not_specified, 1); auto J_changeable = symbols_.addSymbol("JChangeable", JChangeable, true, model::symbols::J); EXPECT_THROW(symbols_.assignSymbolToGFactor(J_changeable, 2), std::invalid_argument); } TEST(symbols, set_new_value_to_changeable_J_g) { size_t number_of_spins = 10; model::symbols::Symbols symbols_(number_of_spins); double JChangeable_value = 10; double gChangeable_value = 2; auto J_changeable = symbols_.addSymbol("JChangeable", JChangeable_value, true, model::symbols::J); auto g_changeable = symbols_.addSymbol("gChangeable", gChangeable_value, true, model::symbols::g_factor); symbols_.assignSymbolToIsotropicExchange(J_changeable, 2, 7); for (size_t i = 0; i < number_of_spins; ++i) { symbols_.assignSymbolToGFactor(g_changeable, i); } auto shared_ptr_J = symbols_.getIsotropicExchangeParameters(); auto shared_ptr_g = symbols_.getGFactorParameters(); EXPECT_EQ(JChangeable_value, shared_ptr_J->operator()(2, 7)); EXPECT_EQ(gChangeable_value, shared_ptr_g->operator()(7)); symbols_.setNewValueToChangeableSymbol(J_changeable, 2 * JChangeable_value); EXPECT_EQ(2 * JChangeable_value, shared_ptr_J->operator()(2, 7)); EXPECT_EQ(gChangeable_value, shared_ptr_g->operator()(7)); symbols_.setNewValueToChangeableSymbol(g_changeable, 2 * gChangeable_value); EXPECT_EQ(2 * JChangeable_value, shared_ptr_J->operator()(2, 7)); EXPECT_EQ(2 * gChangeable_value, shared_ptr_g->operator()(7)); }
36.570313
96
0.701346
ruthenium96
03ba5b61d4f0bc71fa878e44810db854ec2ecfce
5,639
cpp
C++
tc 160+/PizzaDelivery.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/PizzaDelivery.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/PizzaDelivery.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> #include <queue> using namespace std; int T[20]; int dest[50][50]; int N; int best[50][50]; const int inf = (1<<29); struct state { int t, i, j; state(int t_, int i_, int j_): t(t_), i(i_), j(j_) {} }; bool operator<(const state &a, const state &b) { if (a.t != b.t) { return a.t > b.t; } else if (a.i != b.i) { return a.i < b.i; } else { return a.j < b.j; } } const int di[] = { -1, 0, 1, 0 }; const int dj[] = { 0, 1, 0, -1 }; class PizzaDelivery { public: int deliverAll(vector <string> terrain) { for (int i=0; i<20; ++i) { T[i] = inf; } int si, sj; const int m = terrain.size(); const int n = terrain[0].size(); memset(dest, 0xff, sizeof dest); N = 0; for (int i=0; i<m; ++i) { for (int j=0; j<n; ++j) { if (terrain[i][j] == 'X') { si = i; sj = j; } else if (terrain[i][j] == '$') { dest[i][j] = N++; } } } for (int i=0; i<m; ++i) { for (int j=0; j<n; ++j) { best[i][j] = inf; } } best[si][sj] = 0; priority_queue<state> PQ; PQ.push(state(0, si, sj)); while (!PQ.empty()) { const state temp = PQ.top(); PQ.pop(); const int i = temp.i; const int j = temp.j; const int t = temp.t; if (t > best[i][j]) { continue; } best[i][j] = t; if (dest[i][j] != -1) { T[dest[i][j]] = t; } for (int d=0; d<4; ++d) { const int ii = i + di[d]; const int jj = j + dj[d]; if (ii<0 || jj<0 || ii>=m || jj>=n) { continue; } int nt = t; if (terrain[ii][jj]=='X' || terrain[ii][jj]=='$' || terrain[i][j]=='X' || terrain[i][j]=='$') { nt += 2; } else { int diff = abs(terrain[i][j] - terrain[ii][jj]); if (diff > 1) { continue; } nt += 1 + (diff==1)*2; } if (nt < best[ii][jj]) { best[ii][jj] = nt; PQ.push(state(nt, ii, jj)); } } } for (int i=0; i<N; ++i) { if (T[i] == inf) { return -1; } } int sol = inf; for (int mask=0; mask<(1<<N); ++mask) { int farthest1 = 0; int farthest2 = 0; int one = 0; int two = 0; for (int i=0; i<N; ++i) { if ((mask>>i) & 1) { farthest1 = max(farthest1, T[i]); one += 2*T[i]; } else { farthest2 = max(farthest2, T[i]); two += 2*T[i]; } } sol = min(sol, max(one-farthest1, two-farthest2)); } return sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"3442211", "34$221X", "3442211"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 8; verify_case(0, Arg1, deliverAll(Arg0)); } void test_case_1() { string Arr0[] = {"001000$", "$010X0$", "0010000"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 13; verify_case(1, Arg1, deliverAll(Arg0)); } void test_case_2() { string Arr0[] = {"001000$", "$010X0$", "0010000", "2232222", "2222222", "111$111"} ; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = -1; verify_case(2, Arg1, deliverAll(Arg0)); } void test_case_3() { string Arr0[] = {"001000$", "$010X0$", "0010000", "1232222", "2222222", "111$111"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 28; verify_case(3, Arg1, deliverAll(Arg0)); } void test_case_4() { string Arr0[] = {"X$$", "$$$"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 14; verify_case(4, Arg1, deliverAll(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { PizzaDelivery ___test; ___test.run_test(-1); } // END CUT HERE
32.408046
309
0.422238
ibudiselic
03bfdc806b7a67ddcc7cb79eda6d799c4d39601b
1,754
hpp
C++
modules/models/behavior/behavior_model.hpp
grzPat/bark
807092815c81eeb23defff473449a535a9c42f8b
[ "MIT" ]
null
null
null
modules/models/behavior/behavior_model.hpp
grzPat/bark
807092815c81eeb23defff473449a535a9c42f8b
[ "MIT" ]
null
null
null
modules/models/behavior/behavior_model.hpp
grzPat/bark
807092815c81eeb23defff473449a535a9c42f8b
[ "MIT" ]
null
null
null
// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, Tobias Kessler // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #ifndef MODULES_MODELS_BEHAVIOR_BEHAVIOR_MODEL_HPP_ #define MODULES_MODELS_BEHAVIOR_BEHAVIOR_MODEL_HPP_ #include <memory> #include "modules/commons/base_type.hpp" #include "modules/models/dynamic/dynamic_model.hpp" namespace modules { namespace world { namespace objects { class Agent; typedef std::shared_ptr<Agent> AgentPtr; typedef unsigned int AgentId; } // namespace objects class ObservedWorld; } // namespace world namespace models { namespace behavior { using dynamic::Trajectory; class BehaviorModel : public modules::commons::BaseType { public: explicit BehaviorModel(commons::Params *params) : commons::BaseType(params), last_trajectory_() {} BehaviorModel(const BehaviorModel &behavior_model) : commons::BaseType(behavior_model.get_params()), last_trajectory_(behavior_model.get_last_trajectory()) {} virtual ~BehaviorModel() {} dynamic::Trajectory get_last_trajectory() const { return last_trajectory_; } void set_last_trajectory(const dynamic::Trajectory &trajectory) { last_trajectory_ = trajectory; } virtual Trajectory Plan(float delta_time, const world::ObservedWorld& observed_world) = 0; virtual BehaviorModel *Clone() const = 0; private: dynamic::Trajectory last_trajectory_; }; typedef std::shared_ptr<BehaviorModel> BehaviorModelPtr; } // namespace behavior } // namespace models } // namespace modules #endif // MODULES_MODELS_BEHAVIOR_BEHAVIOR_MODEL_HPP_
28.754098
98
0.730901
grzPat
03ca32200d1d172d5830a06267ec957700848233
3,513
cc
C++
benchmark/benchnum.cc
MengRao/str
80389e30ff07bfd5d71f2bdcfad23db6c1353c2c
[ "MIT" ]
90
2019-01-27T09:02:14.000Z
2022-03-19T16:53:08.000Z
benchmark/benchnum.cc
MengRao/str
80389e30ff07bfd5d71f2bdcfad23db6c1353c2c
[ "MIT" ]
4
2019-01-28T03:42:53.000Z
2021-07-04T13:46:15.000Z
benchmark/benchnum.cc
MengRao/str
80389e30ff07bfd5d71f2bdcfad23db6c1353c2c
[ "MIT" ]
25
2019-02-15T08:18:42.000Z
2022-03-19T16:53:10.000Z
#include <bits/stdc++.h> #include "../Str.h" using namespace std; inline uint64_t getns() { return std::chrono::high_resolution_clock::now().time_since_epoch().count(); } uint32_t getRand() { uint32_t num = rand() & 0xffff; num <<= 16; num |= rand() & 0xffff; return num; } string dest; char buf[1024]; template<uint32_t Size> void bench() { using NumStr = Str<Size>; uint64_t mod = 1; for (int i = 0; i < Size; i++) mod *= 10; const int datasize = 1000; const int loop = 1000; vector<uint64_t> nums(datasize); vector<NumStr> strs(datasize); vector<string> strings(datasize); for (int i = 0; i < datasize; i++) { uint64_t num = getRand(); num <<= 32; num += getRand(); num %= mod; string str = to_string(num); while (str.size() < Size) str = string("0") + str; NumStr numstr = str.data(); assert(numstr.toi64() == num); assert(stoll(str) == num); assert(strtoll(str.data(), NULL, 10) == num); NumStr teststr; teststr.fromi(num); assert(teststr == numstr); sprintf(buf, "%0*lld", Size, num); assert(str == buf); nums[i] = num; strs[i] = numstr; strings[i] = str; } { uint64_t sum = 0; auto before = getns(); for (int l = 0; l < loop; l++) { for (auto& str : strs) { sum += str.toi64(); } } auto after = getns(); cout << "bench " << Size << " toi64: " << (double)(after - before) / (loop * datasize) << " res: " << sum << endl; } { uint64_t sum = 0; auto before = getns(); for (int l = 0; l < loop; l++) { for (auto& str : strings) { sum += stoll(str); } } auto after = getns(); cout << "bench " << Size << " stoll: " << (double)(after - before) / (loop * datasize) << " res: " << sum << endl; } { uint64_t sum = 0; auto before = getns(); for (int l = 0; l < loop; l++) { for (auto& str : strings) { sum += strtoll(str.data(), NULL, 10); } } auto after = getns(); cout << "bench " << Size << " strtoll: " << (double)(after - before) / (loop * datasize) << " res: " << sum << endl; } { union { uint64_t num; char str[Size]; } res; res.num = 0; uint64_t sum = 0; auto before = getns(); for (int l = 0; l < loop; l++) { for (auto num : nums) { (*(NumStr*)res.str).fromi(num); sum += res.num; } } auto after = getns(); cout << "bench " << Size << " fromi: " << (double)(after - before) / (loop * datasize) << " res: " << sum << endl; } { auto before = getns(); for (int l = 0; l < loop; l++) { for (auto num : nums) { dest = to_string(num); } } auto after = getns(); cout << "bench " << Size << " to_string: " << (double)(after - before) / (loop * datasize) << " res: " << dest << endl; } { auto before = getns(); for (int l = 0; l < loop; l++) { for (auto num : nums) { sprintf(buf, "%0*lld", Size, num); } } auto after = getns(); cout << "bench " << Size << " sprintf: " << (double)(after - before) / (loop * datasize) << " res: " << dest << endl; } cout << endl; } int main() { srand(time(NULL)); bench<1>(); bench<2>(); bench<3>(); bench<4>(); bench<5>(); bench<6>(); bench<7>(); bench<8>(); bench<9>(); bench<10>(); bench<11>(); bench<12>(); bench<13>(); bench<14>(); bench<15>(); bench<16>(); bench<17>(); bench<18>(); }
22.375796
120
0.495588
MengRao
03ce66746d11ffe092777d7123bc94bd6832c953
4,520
cpp
C++
2SST/7LW/functions.cpp
AVAtarMod/University
3c784a1e109b7a6f6ea495278ec3dc126258625a
[ "BSD-3-Clause" ]
1
2021-07-31T06:55:08.000Z
2021-07-31T06:55:08.000Z
2SST/7LW/functions.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
1
2020-11-25T12:00:11.000Z
2021-01-13T08:51:52.000Z
2SST/7LW/functions.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
null
null
null
#include "functions.hpp" #include <vector> #include <iostream> #include <string> #include <algorithm> bool isMagickSquareSolved(unsigned **square, unsigned size) { const unsigned numberRows = size, numberCols = size, numberDiagonals = 2; const unsigned numberObjects = numberRows + numberCols + numberDiagonals; unsigned *sum = new unsigned[numberObjects]{0}; for (unsigned i = 0; i < numberCols; ++i) for (unsigned ii = 0; ii < numberRows; ++ii) sum[i] += square[ii][i]; for (unsigned i = 0; i < numberRows; ++i) for (unsigned ii = 0; ii < numberCols; ++ii) sum[i + numberCols] += square[i][ii]; for (unsigned i = 0; i < numberCols; ++i) sum[numberCols + numberRows] += square[i][i]; for (unsigned i = size - 1, ii; i < 0 - 1; --i, ++ii) sum[numberCols + numberCols + 1] += square[i][ii]; bool solved = true; for (unsigned i = 0; i < numberObjects && solved; ++i) if (sum[i] != sum[0]) solved = false; delete[] sum; return solved; } bool checkNumber(unsigned number) { int tnum = number, c = 0; while (tnum != 0) { int temp = tnum % 10; if (temp == 0) return false; tnum /= 10; c++; } int p = 0; tnum = number; for (int i = 0; i < c; ++i) { int temp1 = tnum % 10; int tnum2 = number; int p2 = 0; while (tnum2 != 0) { int temp = tnum2 % 10; if (temp == temp1 && p != p2) return false; tnum2 /= 10; p2++; } p++; tnum /= 10; } return true; } unsigned **magickSquare(unsigned size) { try { if (size < 2) throw "magickSquare: too little size (" + std::to_string(size) + ")"; } catch (const std::exception &e) { std::cerr << e.what() << '\n'; } unsigned **square = array2d::init<unsigned>(size, size, 0); unsigned counter = 1; for (unsigned row = 0; row < size; ++row) for (unsigned col = 0; col < size; ++col, ++counter) square[row][col] = counter; unsigned start = 123456789; while (start < 987654321) { unsigned ts = start; for (unsigned row = size - 1; row < 0 - 1; --row) for (unsigned col = size - 1; col < 0 - 1; --col) { square[row][col] = ts % 10; ts /= 10; } if (isMagickSquareSolved(square, size)) { for (int i = 0; i < 3; ++i) { for (int ii = 0; ii < 3; ++ii) { std::cout << square[i][ii] << " "; } std::cout << "\n"; } std::cout << "\n"; } start++; while (!checkNumber(start)) { start++; } } return square; } struct setNumbers { int a, b; bool used = false; setNumbers(int a = 0, int b = 0, bool used = false) { this->a = a; this->b = b; this->used = used; } bool operator==(setNumbers &b) { return (this->a == b.a && this->b == b.b); } }; bool compareNumbers(int a, int b, int operatorChar) { if (operatorChar == '<') return a < b; else return a > b; } void solveBoxesProblem(int *array, unsigned length) { const unsigned amountNumbers = length / 2 + 1; const unsigned amountOperators = amountNumbers - 1; int *numbers = new int[amountNumbers]; int *operators = new int[amountOperators]; for (unsigned i = 0; i < amountNumbers; ++i) numbers[i] = array[i]; for (unsigned i = 0; i < amountOperators; ++i) operators[i] = array[i + amountNumbers]; std::vector<std::vector<setNumbers>> sets; sets.resize(amountOperators); for (unsigned i = 0; i < amountOperators; ++i) { for (unsigned a = 0; a < amountNumbers; ++a) for (unsigned b = 0; b < amountNumbers; ++b) { setNumbers current = {numbers[a], numbers[b]}; bool uniqueSet = (std::find_if(sets[i].begin(), sets[i].end(), [&current](setNumbers &a) { return (current.a == a.a && current.b == a.b); }) == sets[i].end()); if (compareNumbers(numbers[a], numbers[b], operators[i]) && uniqueSet) { sets.at(i).push_back(current); } } } }
25.828571
175
0.488496
AVAtarMod
03d02a1af870d8d0b6c13a55dac2d2be5cf4e884
3,680
hh
C++
src/drivers/Execute.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/drivers/Execute.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/drivers/Execute.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*----------------------------------// /** * @file Execute.hh * @brief Execute class definition. * @note Copyright (C) 2013 Jeremy Roberts. */ //---------------------------------------------------------------------------// //---------------------------------------------------------------------------// /** @mainpage detran: A DEterministic TRANsport package * * @section sec_introduction Introduction * * This is the introduction. * * @section install_sec Installation * * @subsection step1 Step 1: Opening the box * * etc... */ //---------------------------------------------------------------------------// #ifndef detran_EXECUTE_HH_ #define detran_EXECUTE_HH_ #include "detran_config.hh" #include "StupidParser.hh" #include "external_source/ExternalSource.hh" #include "external_source/ConstantSource.hh" #include "external_source/DiscreteSource.hh" #include "external_source/IsotropicSource.hh" #include "geometry/Mesh.hh" #include "material/Material.hh" #include "solvers/FixedSourceManager.hh" #include "solvers/EigenvalueManager.hh" #include "transport/DimensionTraits.hh" #include "transport/State.hh" #include "utilities/DBC.hh" #include "utilities/InputDB.hh" #include <iostream> #include <string> namespace detran { //---------------------------------------------------------------------------// /** * @class Execute * @brief Setup and execute the problem. */ //---------------------------------------------------------------------------// class Execute { public: //-------------------------------------------------------------------------// // TYPEDEFS //-------------------------------------------------------------------------// typedef detran_utilities::InputDB::SP_input SP_input; typedef detran_geometry::Mesh::SP_mesh SP_mesh; typedef detran_material::Material::SP_material SP_material; typedef detran_external_source:: ExternalSource::SP_externalsource SP_externalsource; typedef detran_external_source:: ExternalSource::vec_externalsource vec_externalsource; typedef detran::State::SP_state SP_state; //-------------------------------------------------------------------------// // CONSTRUCTOR & DESTRUCTOR //-------------------------------------------------------------------------// /* * \brief Constructor * \param parser Input parser */ Execute(StupidParser &parser); //-------------------------------------------------------------------------// // PUBLIC FUNCTIONS //-------------------------------------------------------------------------// /// Solve the problem. template <class D> void solve(); /// Write output to file. void output(); // Return dimension of problem. int dimension() { return d_dimension; } private: //-------------------------------------------------------------------------// // DATA //-------------------------------------------------------------------------// // Input SP_input d_input; // Material SP_material d_material; // Mesh SP_mesh d_mesh; // State vector SP_state d_state; // Number of groups int d_number_groups; // External source SP_externalsource d_externalsource; // Problem dimensions int d_dimension; // Problem type std::string d_problem_type; }; } // end namespace detran #endif /* detran_EXECUTE_HH_ */ //---------------------------------------------------------------------------// // end of Execute.hh //---------------------------------------------------------------------------//
28.091603
79
0.449728
RLReed
03d756a651baef8b69f602d1bacd3c614a2083a0
1,004
hpp
C++
include/_app_state_recognition.hpp
zborffs/Delta
b2efa9fe1cc2138656f4d7964ccdbbbfcebba639
[ "MIT" ]
1
2022-03-03T09:34:54.000Z
2022-03-03T09:34:54.000Z
include/_app_state_recognition.hpp
zborffs/Delta
b2efa9fe1cc2138656f4d7964ccdbbbfcebba639
[ "MIT" ]
null
null
null
include/_app_state_recognition.hpp
zborffs/Delta
b2efa9fe1cc2138656f4d7964ccdbbbfcebba639
[ "MIT" ]
null
null
null
#ifndef DELTA__APP_STATE_RECOGNITION_HPP #define DELTA__APP_STATE_RECOGNITION_HPP /// Third-Party Includes #include <spdlog/spdlog.h> /// Project Includes #include "app.hpp" #include "_app_state_eng.hpp" #include "_app_state_shutdown.hpp" /** * The AppStateRecognition class is responsible for coloring the Application's functionality when in the "Recognition" * state. * - it transforms a null input into a (legal) chess position * - it is reached from either the Initialization state, or the Waiting state * - it makes use of the Recognition component and the Engine component * - if successful, it transitions to the Engine state */ class AppStateRecognition : public AppState { public: explicit AppStateRecognition() { spdlog::get("delta_logger")->info("Created AppStateRecognition"); } ~AppStateRecognition() { spdlog::get("delta_logger")->info("Destroyed AppStateRecognition"); } bool handle() override; }; #endif // DELTA__APP_STATE_RECOGNITION_HPP
30.424242
118
0.747012
zborffs
03d84fff4764df02d25c380969ade60037598442
14,202
hpp
C++
plugins/EstimationPlugin/src/base/estimator/BatchEstimator.hpp
Randl/GMAT
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
2
2020-01-01T13:14:57.000Z
2020-12-09T07:05:07.000Z
plugins/EstimationPlugin/src/base/estimator/BatchEstimator.hpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
1
2018-03-15T08:58:37.000Z
2018-03-20T20:11:26.000Z
plugins/EstimationPlugin/src/base/estimator/BatchEstimator.hpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
3
2019-10-13T10:26:49.000Z
2020-12-09T07:06:55.000Z
//$Id: BatchEstimator.hpp 1398 2011-04-21 20:39:37Z $ //------------------------------------------------------------------------------ // BatchEstimator //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG06CA54C // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: 2009/08/04 // /** * Definition of the BatchEstimator class */ //------------------------------------------------------------------------------ #ifndef BatchEstimator_hpp #define BatchEstimator_hpp #include "Estimator.hpp" #include "PropSetup.hpp" #include "MeasurementManager.hpp" #include "OwnedPlot.hpp" #include "DataWriter.hpp" #include "WriterData.hpp" #include "DataBucket.hpp" /** * Implementation of a standard batch estimation state machine * * This class provides a batch estimation state machine that follows a typical * batch estimation process. Derived classes override specific methods to * implement the math required for their algorithm. Every derived estimator * must implement the Accumulate and Estimate methods. The other methods called * in the finite state machine provide default implementation that can be * overridden as needed. * * BatchEstimator is an abstract class; a derived class is needed to instantiate * a BatchEstimator */ class ESTIMATION_API BatchEstimator : public Estimator { public: BatchEstimator(const std::string &type, const std::string &name); virtual ~BatchEstimator(); BatchEstimator(const BatchEstimator& est); BatchEstimator& operator=(const BatchEstimator& est); virtual bool Initialize(); virtual SolverState AdvanceState(); virtual bool Finalize(); // methods overridden from GmatBase virtual std::string GetParameterText(const Integer id) const; virtual std::string GetParameterUnit(const Integer id) const; virtual Integer GetParameterID(const std::string &str) const; virtual Gmat::ParameterType GetParameterType(const Integer id) const; virtual std::string GetParameterTypeString(const Integer id) const; virtual Integer GetIntegerParameter(const Integer id) const; virtual Integer SetIntegerParameter(const Integer id, const Integer value); virtual Integer GetIntegerParameter(const std::string &label) const; virtual Integer SetIntegerParameter(const std::string &label, const Integer value); virtual std::string GetStringParameter(const Integer id) const; virtual bool SetStringParameter(const Integer id, const std::string &value); virtual std::string GetStringParameter(const Integer id, const Integer index) const; virtual bool SetStringParameter(const Integer id, const std::string &value, const Integer index); virtual std::string GetStringParameter(const std::string &label) const; virtual bool SetStringParameter(const std::string &label, const std::string &value); virtual std::string GetStringParameter(const std::string &label, const Integer index) const; virtual bool SetStringParameter(const std::string &label, const std::string &value, const Integer index); virtual bool GetBooleanParameter(const Integer id) const; virtual bool SetBooleanParameter(const Integer id, const bool value); virtual bool GetBooleanParameter(const std::string &label) const; virtual bool SetBooleanParameter(const std::string &label, const bool value); virtual const StringArray& GetPropertyEnumStrings(const Integer id) const; virtual bool TakeAction(const std::string &action, const std::string &actionData = ""); protected: /// Time system used to specify the estimation epoch std::string estEpochFormat; /// The estimation epoch. "FromParticipants" means use the spacecraft epoch. std::string estEpoch; /// RMS residual value from the previous pass through the data Real oldResidualRMS; /// RMS residual value from the current pass through the data Real newResidualRMS; /// The best RMS residual Real bestResidualRMS; Real resetBestResidualRMS; /// Predicted RMS residual Real predictedRMS; /// Number consecutive iterations diverging Integer numDivIterations; /// Flag to indicate weightedRMS or predictedRMS bool chooseRMSP; /// Flag set when an a priori estimate is available bool useApriori; /// The most recently computed state vector changes RealArray dx; /// The weighting matrix used when accumulating data Rmatrix weights; /// Flag used to indicate propagation to estimation epoch is executing bool advanceToEstimationEpoch; /// The .mat DataWriter object used to write data for MATLAB DataWriter *matWriter; /// Flag indicating is the .mat file should be written bool writeMatFile; /// .mat data file name std::string matFileName; /// Data container used during accumulation DataBucket matData; // Indexing for the .mat data elements /// Iteration number index Integer matIterationIndex; /// Index of the participants list in the .mat data Integer matPartIndex; /// Index of the participants list in the .mat data Integer matTypeIndex; /// Index of the TAI Mod Julian epoch data in the .mat data Integer matEpochIndex; /// Index of the observation data list in the .mat data Integer matObsIndex; /// Index of the calculated data in the .mat data Integer matCalcIndex; /// Index of the O-C data in the .mat data Integer matOmcIndex; /// Index of the elevation for the obs Integer matElevationIndex; /// TAI Gregorian epoch index Integer matGregorianIndex; /// Observation edit flag index Integer matObsEditFlagIndex; // Extra entries Integer matFrequencyIndex; Integer matFreqBandIndex; Integer matDoppCountIndex; // /// Estimation status // Integer estimationStatus; // This variable is moved to Estimator class // String to show reason of convergence std::string convergenceReason; /// Buffer of the participants for the outer batch loop ObjectArray outerLoopBuffer; /// Inversion algorithm used std::string inversionType; /// Maximum consecutive divergences Integer maxConsDivergences; /// particicpants column lenght. It is used for writing report file Integer pcolumnLen; /// Variables used for statistics calculation std::map<std::string, std::map<std::string, Real> > statisticsTable; // this table is for groundstation and measurement type std::map<std::string, std::map<std::string, Real> > statisticsTable1; // this table is for measurement type only // Statistics information for all combination of station and measurement type StringArray stationAndType; // combination of station and type StringArray stationsList; // station StringArray measTypesList; // measurement type IntegerArray sumAllRecords; // total number of records IntegerArray sumAcceptRecords; // total all accepted records RealArray sumResidual; // sum of all O-C of accepted records RealArray sumResidualSquare; // sum of all (O-C)^2 of accepted records RealArray sumWeightResidualSquare; // sum of all [W*(O-C)]^2 of accepted records // Statistics information for sigma edited records IntegerArray sumSERecords; // total all sigma edited records RealArray sumSEResidual; // sum of all O-C of all sigma edited records RealArray sumSEResidualSquare; // sum of all (O-C)^2 of all sigma edited records RealArray sumSEWeightResidualSquare; // sum of all [W*(O-C)]^2 of all sigma edited records std::stringstream textFile0; std::stringstream textFile1; std::stringstream textFile1_1; std::stringstream textFile2; std::stringstream textFile3; std::stringstream textFile4; /// Parameter IDs for the BatchEstimators enum { ESTIMATION_EPOCH_FORMAT = EstimatorParamCount, ESTIMATION_EPOCH, // USE_PRIORI_ESTIMATE, USE_INITIAL_COVARIANCE, INVERSION_ALGORITHM, MAX_CONSECUTIVE_DIVERGENCES, MATLAB_OUTPUT_FILENAME, BatchEstimatorParamCount, }; /// Strings describing the BatchEstimator parameters static const std::string PARAMETER_TEXT[BatchEstimatorParamCount - EstimatorParamCount]; /// Types of the BatchEstimator parameters static const Gmat::ParameterType PARAMETER_TYPE[BatchEstimatorParamCount - EstimatorParamCount]; virtual void CompleteInitialization(); virtual void FindTimeStep(); virtual void CalculateData(); virtual void ProcessEvent(); virtual void CheckCompletion(); virtual void RunComplete(); // Abstract methods defined in derived classes /// Abstract method that implements accumulation in derived classes virtual void Accumulate() = 0; /// Abstract method that performs the estimation in derived classes virtual void Estimate() = 0; virtual Integer TestForConvergence(std::string &reason); virtual void WriteToTextFile(Solver::SolverState state = Solver::UNDEFINED_STATE); // progress string for reporting virtual std::string GetProgressString(); Integer SchurInvert(Real *SUM1, Integer array_size); Integer CholeskyInvert(Real *SUM1, Integer array_size); virtual bool DataFilter(); bool WriteMatData(); private: void WriteReportFileHeaderPart1(); void WriteReportFileHeaderPart2(); void WriteReportFileHeaderPart2b(); void WriteReportFileHeaderPart3(); void WriteReportFileHeaderPart4_1(); void WriteReportFileHeaderPart4_2(); void WriteReportFileHeaderPart4_3(); void WriteReportFileHeaderPart4(); void WriteReportFileHeaderPart5(); void WriteReportFileHeaderPart6(); void WriteReportFileHeader(); void WriteIterationHeader(); void WritePageHeader(); void WriteIterationSummaryPart1(Solver::SolverState sState); void WriteIterationSummaryPart2(Solver::SolverState sState); void WriteIterationSummaryPart3(Solver::SolverState sState); void WriteIterationSummaryPart4(Solver::SolverState sState); void WriteReportFileSummary(Solver::SolverState sState); std::string GetElementFullName(ListItem* infor, bool isInternalCS) const; std::string GetElementUnit(ListItem* infor) const; std::string GetUnit(std::string type); Integer GetElementPrecision(std::string unit) const; Rmatrix CovarianceConvertionMatrix(std::map<GmatBase*, Rvector6> stateMap); std::map<GmatBase*, Rvector6> CalculateCartesianStateMap(const std::vector<ListItem*> *map, GmatState state); std::map<GmatBase*, Rvector6> CalculateKeplerianStateMap(const std::vector<ListItem*> *map, GmatState state); Rmatrix66 CartesianToKeplerianCoverianceConvertionMatrix(GmatBase* obj, const Rvector6 state); std::map<GmatBase*, RealArray> CalculateAncillaryElements(const std::vector<ListItem*> *map, GmatState state); std::string GetFileCreateTime(std::string fileName); std::string CTime(const time_t* time); std::string GetGMATBuildDate(); std::string GetDayOfWeek(Integer day, Integer month, Integer year); std::string GetOperatingSystemName(); std::string GetOperatingSystemVersion(); std::string GetHostName(); std::string GetUserID(); }; #endif /* BatchEstimator_hpp */
44.38125
133
0.62118
Randl
03dd78b44c732d23cd134fdf790cbca208806a4e
8,195
cpp
C++
Source/gday/CoordinateSystemDlg.cpp
mattdocherty314/GDAy3.0
81b13012765e6f4efe3f98c0a4e2c117841f909a
[ "BSD-3-Clause" ]
5
2018-10-30T08:39:02.000Z
2022-02-18T06:34:18.000Z
Source/gday/CoordinateSystemDlg.cpp
mattdocherty314/GDAy3.0
81b13012765e6f4efe3f98c0a4e2c117841f909a
[ "BSD-3-Clause" ]
1
2022-02-18T05:02:24.000Z
2022-02-18T05:02:24.000Z
Source/gday/CoordinateSystemDlg.cpp
mattdocherty314/GDAy3.0
81b13012765e6f4efe3f98c0a4e2c117841f909a
[ "BSD-3-Clause" ]
4
2019-07-30T09:31:05.000Z
2022-01-31T05:51:18.000Z
// CoordinateSystemDlg.cpp : implementation file // #include "stdafx.h" #include "GDAy.h" #include "CoordinateSystemDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CCoordinateSystemDlg dialog CCoordinateSystemDlg::CCoordinateSystemDlg(CWnd* pParent /*=NULL*/) : CDialog(CCoordinateSystemDlg::IDD, pParent) { //{{AFX_DATA_INIT(CCoordinateSystemDlg) //}}AFX_DATA_INIT } void CCoordinateSystemDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CCoordinateSystemDlg) DDX_CBIndex(pDX, IDC_INPUT_DATUM, (m_coordinate_t.InputisGDA20)); DDX_LBIndex(pDX, IDC_INPUT_PROJ, (m_coordinate_t.InputisProjected)); DDX_Radio(pDX, IDC_IN_DMS, (m_coordinate_t.InputDMS)); DDX_CBIndex(pDX, IDC_OUTPUT_DATUM, (m_coordinate_t.OutputisGDA)); DDX_LBIndex(pDX, IDC_OUTPUT_PROJ, (m_coordinate_t.OutputisProjected)); DDX_Check(pDX, IDC_OUTZONE_PROMPT, (m_coordinate_t.PromptforOutputZone)); DDX_Radio(pDX, IDC_OUT_DMS, (m_coordinate_t.OutputDMS)); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CCoordinateSystemDlg, CDialog) //{{AFX_MSG_MAP(CCoordinateSystemDlg) ON_CBN_SELCHANGE(IDC_INPUT_DATUM, OnSelchangeInputDatum) ON_LBN_SELCHANGE(IDC_INPUT_PROJ, OnSelchangeInputProj) ON_CBN_SELCHANGE(IDC_OUTPUT_DATUM, OnSelchangeOutputDatum) ON_LBN_SELCHANGE(IDC_OUTPUT_PROJ, OnSelchangeOutputProj) ON_BN_CLICKED(ID_HELP, OnHelp) ON_WM_HELPINFO() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCoordinateSystemDlg message handlers void CCoordinateSystemDlg::OnSelchangeInputDatum() { int selection; UpdateData(TRUE); selection = ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->GetCurSel(); // delete all contents of the input projection list box ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->ResetContent(); ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(GEO); switch ( ((CComboBox*)GetDlgItem(IDC_INPUT_DATUM))->GetCurSel() ) { case 0: ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(MGA94_STR); break; case 1: ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(MGA20_STR); break; default: MessageBox(SEL_ERR, "Error", MB_OK | MB_ICONEXCLAMATION); break; } ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->SetCurSel(selection); OnSelchangeInputProj(); } void CCoordinateSystemDlg::OnSelchangeInputProj() { switch ( ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->GetCurSel() ) { case 0: // The user selected "None" GetDlgItem(IDC_IN_DDEG)->EnableWindow(TRUE); GetDlgItem(IDC_IN_DMIN)->EnableWindow(TRUE); GetDlgItem(IDC_IN_DMS)->EnableWindow(TRUE); GetDlgItem(IDC_IN_FORMAT)->EnableWindow(TRUE); break; case 1: // The user selected a projection type...no choice for D.ms/D.Deg GetDlgItem(IDC_IN_DDEG)->EnableWindow(FALSE); GetDlgItem(IDC_IN_DMIN)->EnableWindow(FALSE); GetDlgItem(IDC_IN_DMS)->EnableWindow(FALSE); GetDlgItem(IDC_IN_FORMAT)->EnableWindow(FALSE); break; default: MessageBox(SEL_ERR, "Error", MB_OK | MB_ICONEXCLAMATION); break; } } void CCoordinateSystemDlg::OnSelchangeOutputDatum() { int selection; selection = ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->GetCurSel(); // delete all contents of the output projection list box ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->ResetContent(); ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(GEO); switch ( ((CComboBox*)GetDlgItem(IDC_OUTPUT_DATUM))->GetCurSel() ) { case 0: ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(MGA94_STR); break; case 1: ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(MGA20_STR); break; default: MessageBox(SEL_ERR, "Error", MB_OK | MB_ICONEXCLAMATION); break; } ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->SetCurSel(selection); OnSelchangeOutputProj(); } void CCoordinateSystemDlg::OnSelchangeOutputProj() { switch ( ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->GetCurSel() ) { case 0: // The user selected "None" GetDlgItem(IDC_OUT_DDEG)->EnableWindow(TRUE); GetDlgItem(IDC_OUT_DMIN)->EnableWindow(TRUE); GetDlgItem(IDC_OUT_DMS)->EnableWindow(TRUE); GetDlgItem(IDC_OUT_FORMAT)->EnableWindow(TRUE); GetDlgItem(IDC_OUTZONE_PROMPT)->EnableWindow(FALSE); break; case 1: // The user selected a projection type...no choice for D.ms/D.Deg GetDlgItem(IDC_OUT_DDEG)->EnableWindow(FALSE); GetDlgItem(IDC_OUT_DMIN)->EnableWindow(FALSE); GetDlgItem(IDC_OUT_DMS)->EnableWindow(FALSE); GetDlgItem(IDC_OUT_FORMAT)->EnableWindow(FALSE); GetDlgItem(IDC_OUTZONE_PROMPT)->EnableWindow(TRUE); break; default: MessageBox(SEL_ERR, "Error", MB_OK | MB_ICONEXCLAMATION); break; } } BOOL CCoordinateSystemDlg::OnInitDialog() { CDialog::OnInitDialog(); // Create tooltip control if (m_ToolTip.Create(this)) { // add the dialog's controls to the Tooltip m_ToolTip.AddTool(GetDlgItem(IDC_IN_DMS), IDC_DMS); m_ToolTip.AddTool(GetDlgItem(IDC_IN_DMIN), IDC_DMIN); m_ToolTip.AddTool(GetDlgItem(IDC_IN_DDEG), IDC_DDEG); m_ToolTip.AddTool(GetDlgItem(IDC_OUT_DMS), IDC_DMS); m_ToolTip.AddTool(GetDlgItem(IDC_OUT_DMIN), IDC_DMIN); m_ToolTip.AddTool(GetDlgItem(IDC_OUT_DDEG), IDC_DDEG); m_ToolTip.AddTool(GetDlgItem(IDC_OUTPUT_DATUM), IDC_OUTPUT_DATUM); m_ToolTip.AddTool(GetDlgItem(IDC_INPUT_DATUM), IDC_INPUT_DATUM); m_ToolTip.AddTool(GetDlgItem(IDC_OUTPUT_PROJ), IDC_OUTPUT_PROJ); m_ToolTip.AddTool(GetDlgItem(IDC_INPUT_PROJ), IDC_INPUT_PROJ); // activate ToolTip control m_ToolTip.Activate(TRUE); } // clear projection list boxes ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->ResetContent(); ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(GEO); ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->ResetContent(); ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(GEO); // Input Datum switch (m_coordinate_t.InputisGDA20) { case 0: ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(MGA94_STR); break; case 1: ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(MGA20_STR); break; default: return FALSE; } ((CComboBox*)GetDlgItem(IDC_INPUT_DATUM))->SetCurSel(m_coordinate_t.InputisGDA20); // Input Coordinates projected? GetDlgItem(IDC_IN_DDEG)->EnableWindow(!m_coordinate_t.InputisProjected); GetDlgItem(IDC_IN_DMIN)->EnableWindow(!m_coordinate_t.InputisProjected); GetDlgItem(IDC_IN_DMS)->EnableWindow(!m_coordinate_t.InputisProjected); GetDlgItem(IDC_IN_FORMAT)->EnableWindow(!m_coordinate_t.InputisProjected); ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->SetCurSel(m_coordinate_t.InputisProjected); // Output Datum switch (m_coordinate_t.OutputisGDA) { case 0: ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(MGA94_STR); break; case 1: ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(MGA20_STR); break; default: return FALSE; } ((CComboBox*)GetDlgItem(IDC_OUTPUT_DATUM))->SetCurSel(m_coordinate_t.OutputisGDA); // Output Coordinates projected? GetDlgItem(IDC_OUT_DDEG)->EnableWindow(!m_coordinate_t.OutputisProjected); GetDlgItem(IDC_OUT_DMIN)->EnableWindow(!m_coordinate_t.OutputisProjected); GetDlgItem(IDC_OUT_DMS)->EnableWindow(!m_coordinate_t.OutputisProjected); GetDlgItem(IDC_OUT_FORMAT)->EnableWindow(!m_coordinate_t.OutputisProjected); GetDlgItem(IDC_OUTZONE_PROMPT)->EnableWindow(m_coordinate_t.OutputisProjected); ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->SetCurSel(m_coordinate_t.OutputisProjected); UpdateData(FALSE); return TRUE; } void CCoordinateSystemDlg::OnOK() { UpdateData(TRUE); CDialog::OnOK(); } void CCoordinateSystemDlg::OnCancel() { UpdateData(FALSE); CDialog::OnCancel(); } void CCoordinateSystemDlg::OnHelp() { ::HtmlHelp(NULL, "gday.chm::/html/TC_choose_coord_sys.htm", HH_DISPLAY_TOC, 0); } BOOL CCoordinateSystemDlg::PreTranslateMessage(MSG* pMsg) { // Relay events to the tooltip control m_ToolTip.RelayEvent(pMsg); return CDialog::PreTranslateMessage(pMsg); } BOOL CCoordinateSystemDlg::OnHelpInfo(HELPINFO* pHelpInfo) { if (pHelpInfo->iContextType == HELPINFO_WINDOW) return ::HtmlHelp((HWND)pHelpInfo->hItemHandle, "gday.chm::/html/TC_choose_coord_sys.htm", HH_DISPLAY_TOC, 0)!=NULL; return true; }
29.584838
118
0.755461
mattdocherty314
03deff61049e0ab79ea5e1e5fd849c974f217e2a
1,241
cpp
C++
sort/cpu/quickSort.cpp
jitMatrix/xiuxian
ba52d11f39957dd14ca34b51ccb5fadb422e6833
[ "Apache-2.0" ]
3
2021-03-08T06:17:55.000Z
2021-04-09T12:50:21.000Z
sort/cpu/quickSort.cpp
jitMatrix/xiuxian
ba52d11f39957dd14ca34b51ccb5fadb422e6833
[ "Apache-2.0" ]
null
null
null
sort/cpu/quickSort.cpp
jitMatrix/xiuxian
ba52d11f39957dd14ca34b51ccb5fadb422e6833
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <iterator> #include <vector> #include "utils.hpp" template <typename T> std::int64_t partition( std::vector<T> &arr, std::int64_t low, std::int64_t high) { T pivot = arr[low]; while (low < high) { while (low < high && arr[high] >= pivot) { --high; } arr[low] = arr[high]; while (low < high && arr[low] <= pivot) { ++low; } arr[high] = arr[low]; } arr[low] = pivot; return low; } template <typename T> void quickSort(std::vector<T> &arr, std::int64_t low, std::int64_t high) { if (low < high) { std::int64_t pivot = partition(arr, low, high); quickSort(arr, low, pivot - 1); quickSort(arr, pivot + 1, high); } } int main() { std::int64_t count = 10; std::vector<std::int64_t> arr; generator::init(arr, std::make_pair(std::pow(10, generator::minval_radix), std::pow(10, generator::maxval_radix)), count); std::cout << "before sort" << arr << std::endl; quickSort<std::int64_t>(arr, 0, arr.size() - 1); std::cout << "after sort" << arr << std::endl; utils::check_ascend<std::int64_t>(arr); return 0; }
25.854167
74
0.541499
jitMatrix
03df26affc1a5eeb7c79ba5b2b54f5f493990d25
1,582
cpp
C++
src/cpp/rtps/resources/ResourceSend.cpp
zhangzhimin/Fast-RTPS
3032f11d0c62d226eea39ea4f8428afef4558693
[ "Apache-2.0" ]
null
null
null
src/cpp/rtps/resources/ResourceSend.cpp
zhangzhimin/Fast-RTPS
3032f11d0c62d226eea39ea4f8428afef4558693
[ "Apache-2.0" ]
null
null
null
src/cpp/rtps/resources/ResourceSend.cpp
zhangzhimin/Fast-RTPS
3032f11d0c62d226eea39ea4f8428afef4558693
[ "Apache-2.0" ]
1
2021-08-23T01:09:51.000Z
2021-08-23T01:09:51.000Z
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file ResourceSend.cpp * */ #include <fastrtps/rtps/resources/ResourceSend.h> #include "ResourceSendImpl.h" #include "../participant/RTPSParticipantImpl.h" namespace eprosima { namespace fastrtps{ namespace rtps { ResourceSend::ResourceSend() { // TODO Auto-generated constructor stub mp_impl = new ResourceSendImpl(); } ResourceSend::~ResourceSend() { // TODO Auto-generated destructor stub delete(mp_impl); } bool ResourceSend::initSend(RTPSParticipantImpl* pimpl, const Locator_t& loc, uint32_t sendsockBuffer,bool useIP4, bool useIP6) { return mp_impl->initSend(pimpl,loc,sendsockBuffer,useIP4,useIP6); } void ResourceSend::sendSync(CDRMessage_t* msg, const Locator_t& loc) { return mp_impl->sendSync(msg,loc); } boost::recursive_mutex* ResourceSend::getMutex() { return mp_impl->getMutex(); } void ResourceSend::loose_next_change() { return mp_impl->loose_next(); } } } /* namespace rtps */ } /* namespace eprosima */
24.71875
77
0.747788
zhangzhimin
03e12365b2cc583b2428393857ecc55ab3bd134b
421
cpp
C++
src/edible.cpp
Md7tz/Running-Lizard
9a3109cfb7e253dadd75655631bbdefa46a7ee28
[ "MIT" ]
7
2022-02-03T15:57:50.000Z
2022-02-22T12:42:06.000Z
src/edible.cpp
Md7tz/Running-Lizard
9a3109cfb7e253dadd75655631bbdefa46a7ee28
[ "MIT" ]
null
null
null
src/edible.cpp
Md7tz/Running-Lizard
9a3109cfb7e253dadd75655631bbdefa46a7ee28
[ "MIT" ]
null
null
null
#include "GameObjects/edible.h" const uint8_t Edible::count = 2; Edible::Edible() {} Edible::Edible(uint8_t _randInt) { randInt = _randInt; foodColor = RED; } Edible::~Edible() {} bool Edible::update(int16_t lizardHeadx, int16_t lizardHeady) { if (foodPos.x == lizardHeadx && foodPos.y == lizardHeady) return true; else return false; } uint8_t Edible::getCount() { return count; }
16.84
61
0.655582
Md7tz
03e136b4a44a2c80b6aa24e40c73c346a590b9c6
19,606
hpp
C++
gearoenix/math/gx-math-matrix-4d.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/math/gx-math-matrix-4d.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/math/gx-math-matrix-4d.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#ifndef GEAROENIX_MATH_MATRIX_4D_HPP #define GEAROENIX_MATH_MATRIX_4D_HPP #include "gx-math-vector-4d.hpp" namespace gearoenix::math { /// It is a column major matrix template <typename Element> struct Mat4x4 { Element data[4][4]; constexpr Mat4x4() noexcept : data { { static_cast<Element>(1), static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(1), static_cast<Element>(0), static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(1), static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(1) } } { } constexpr explicit Mat4x4(const Element diameter) noexcept : data { { diameter, static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(0) }, { static_cast<Element>(0), diameter, static_cast<Element>(0), static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(0), diameter, static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(1) } } { } constexpr Mat4x4( const Element e0, const Element e1, const Element e2, const Element e3, const Element e4, const Element e5, const Element e6, const Element e7, const Element e8, const Element e9, const Element e10, const Element e11, const Element e12, const Element e13, const Element e14, const Element e15) noexcept : data { { e0, e1, e2, e3 }, { e4, e5, e6, e7 }, { e8, e9, e10, e11 }, { e12, e13, e14, e15 }, } { } explicit Mat4x4(system::stream::Stream* const f) noexcept { read(f); } constexpr Mat4x4(const Mat4x4<Element>& m) noexcept : data { { m.data[0][0], m.data[0][1], m.data[0][2], m.data[0][3] }, { m.data[1][0], m.data[1][1], m.data[1][2], m.data[1][3] }, { m.data[2][0], m.data[2][1], m.data[2][2], m.data[2][3] }, { m.data[3][0], m.data[3][1], m.data[3][2], m.data[3][3] }, } { } template <typename T> constexpr explicit Mat4x4(const Mat4x4<T>& m) noexcept : data { { static_cast<Element>(m.data[0][0]), static_cast<Element>(m.data[0][1]), static_cast<Element>(m.data[0][2]), static_cast<Element>(m.data[0][3]) }, { static_cast<Element>(m.data[1][0]), static_cast<Element>(m.data[1][1]), static_cast<Element>(m.data[1][2]), static_cast<Element>(m.data[1][3]) }, { static_cast<Element>(m.data[2][0]), static_cast<Element>(m.data[2][1]), static_cast<Element>(m.data[2][2]), static_cast<Element>(m.data[2][3]) }, { static_cast<Element>(m.data[3][0]), static_cast<Element>(m.data[3][1]), static_cast<Element>(m.data[3][2]), static_cast<Element>(m.data[3][3]) }, } { } [[nodiscard]] constexpr Vec4<Element> operator*(const Vec4<Element>& v) const noexcept { return Vec4<Element>( data[0][0] * v.x + data[1][0] * v.y + data[2][0] * v.z + data[3][0] * v.w, data[0][1] * v.x + data[1][1] * v.y + data[2][1] * v.z + data[3][1] * v.w, data[0][2] * v.x + data[1][2] * v.y + data[2][2] * v.z + data[3][2] * v.w, data[0][3] * v.x + data[1][3] * v.y + data[2][3] * v.z + data[3][3] * v.w); } [[nodiscard]] constexpr Mat4x4<Element> operator*(const Mat4x4<Element>& m) const noexcept { Mat4x4<Element> r; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { r.data[i][j] = m.data[i][0] * data[0][j] + m.data[i][1] * data[1][j] + m.data[i][2] * data[2][j] + m.data[i][3] * data[3][j]; } } return r; } constexpr Mat4x4<Element>& operator=(const Mat4x4<Element>& m) noexcept { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { data[i][j] = m.data[i][j]; } } return *this; } constexpr void operator*=(const Mat4x4<Element>& m) noexcept { const auto o = *this * m; *this = o; } template <typename T> constexpr Element operator[](const T i) const noexcept { return data[i >> 2][i & 3]; } template <typename T> constexpr Element& operator[](const T i) noexcept { return data[i >> 2][i & 3]; } /// It does not change location constexpr void local_scale(const Element s) noexcept { local_scale(s, s, s); } /// It does not change location constexpr void local_x_scale(const Element s) noexcept { data[0][0] *= s; data[0][1] *= s; data[0][2] *= s; data[0][3] *= s; } /// It does not change location constexpr void local_y_scale(const Element s) noexcept { data[1][0] *= s; data[1][1] *= s; data[1][2] *= s; data[1][3] *= s; } /// It does not change location constexpr void local_z_scale(const Element s) noexcept { data[2][0] *= s; data[2][1] *= s; data[2][2] *= s; data[2][3] *= s; } /// It does not change location constexpr void local_w_scale(const Element s) noexcept { data[3][0] *= s; data[3][1] *= s; data[3][2] *= s; data[3][3] *= s; } /// It does not change location constexpr void local_scale(const Element a, const Element b, const Element c) noexcept { local_x_scale(a); local_y_scale(b); local_z_scale(c); } /// It changes location constexpr void local_scale(const Element a, const Element b, const Element c, const Element d) noexcept { local_scale(a, b, c); local_w_scale(d); } /// It does not change location constexpr void local_scale(const Vec3<Element>& s) noexcept { local_scale(s.x, s.y, s.z); } /// It changes location constexpr void local_scale(const Vec4<Element>& s) noexcept { local_scale(s.x, s.y, s.z, s.w); } /// It changes location constexpr void global_scale(const Element s) noexcept { global_scale(s, s, s); } /// It changes location constexpr void global_scale(const Element a, const Element b, const Element c) noexcept { data[0][0] *= a; data[1][0] *= a; data[2][0] *= a; data[3][0] *= a; data[0][1] *= b; data[1][1] *= b; data[2][1] *= b; data[3][1] *= b; data[0][2] *= c; data[1][2] *= c; data[2][2] *= c; data[3][2] *= c; } /// It changes location constexpr void global_scale(const Element a, const Element b, const Element c, const Element d) noexcept { global_scale(a, b, c); data[0][3] *= d; data[1][3] *= d; data[2][3] *= d; data[3][3] *= d; } /// It changes location constexpr void global_scale(const Vec3<Element>& s) noexcept { global_scale(s.x, s.y, s.z); } /// It changes location constexpr void global_scale(const Vec4<Element>& s) noexcept { global_scale(s.x, s.y, s.z, s.w); } constexpr void translate(const Vec3<Element>& v) noexcept { data[3][0] += v.x; data[3][1] += v.y; data[3][2] += v.z; } constexpr void set_location(const Vec3<Element>& location = Vec3<Element>(0)) noexcept { data[3][0] = location.x; data[3][1] = location.y; data[3][2] = location.z; } constexpr void get_location(Vec3<Element>& location) const noexcept { location.x = data[3][0]; location.y = data[3][1]; location.z = data[3][2]; } [[nodiscard]] constexpr Vec3<Element> get_location() const noexcept { Vec3<Element> v; get_location(v); return v; } constexpr void inverse() noexcept { *this = inverted(); } constexpr void transpose() noexcept { for (auto i = 0; i < 4; ++i) { for (auto j = i + 1; j < 4; ++j) { std::swap(data[i][j], data[j][i]); } } } void read(system::stream::Stream* const f) noexcept { for (auto& r : data) for (auto& c : r) c = static_cast<Element>(f->read<float>()); } [[nodiscard]] constexpr Element determinant() const noexcept { return (+data[0][0] * (+data[1][1] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][1] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) + data[3][1] * (data[1][2] * data[2][3] - data[1][3] * data[2][2])) - data[1][0] * (+data[0][1] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][1] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][1] * (data[0][2] * data[2][3] - data[0][3] * data[2][2])) + data[2][0] * (+data[0][1] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) - data[1][1] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][1] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])) - data[3][0] * (+data[0][1] * (data[1][2] * data[2][3] - data[1][3] * data[2][2]) - data[1][1] * (data[0][2] * data[2][3] - data[0][3] * data[2][2]) + data[2][1] * (data[0][2] * data[1][3] - data[0][3] * data[1][2]))); } [[nodiscard]] constexpr Mat4x4<Element> inverted() const noexcept { const auto id = static_cast<Element>(1) / determinant(); Mat4x4<Element> result; result.data[0][0] = id * (+data[1][1] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][1] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) + data[3][1] * (data[1][2] * data[2][3] - data[1][3] * data[2][2])); result.data[0][1] = id * -(+data[0][1] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][1] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][1] * (data[0][2] * data[2][3] - data[0][3] * data[2][2])); result.data[0][2] = id * (+data[0][1] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) - data[1][1] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][1] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])); result.data[0][3] = id * -(+data[0][1] * (data[1][2] * data[2][3] - data[1][3] * data[2][2]) - data[1][1] * (data[0][2] * data[2][3] - data[0][3] * data[2][2]) + data[2][1] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])); result.data[1][0] = id * -(+data[1][0] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][0] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) + data[3][0] * (data[1][2] * data[2][3] - data[1][3] * data[2][2])); result.data[1][1] = id * (+data[0][0] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][0] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][0] * (data[0][2] * data[2][3] - data[0][3] * data[2][2])); result.data[1][2] = id * -(+data[0][0] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) - data[1][0] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][0] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])); result.data[1][3] = id * (+data[0][0] * (data[1][2] * data[2][3] - data[1][3] * data[2][2]) - data[1][0] * (data[0][2] * data[2][3] - data[0][3] * data[2][2]) + data[2][0] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])); result.data[2][0] = id * (+data[1][0] * (data[2][1] * data[3][3] - data[2][3] * data[3][1]) - data[2][0] * (data[1][1] * data[3][3] - data[1][3] * data[3][1]) + data[3][0] * (data[1][1] * data[2][3] - data[1][3] * data[2][1])); result.data[2][1] = id * -(+data[0][0] * (data[2][1] * data[3][3] - data[2][3] * data[3][1]) - data[2][0] * (data[0][1] * data[3][3] - data[0][3] * data[3][1]) + data[3][0] * (data[0][1] * data[2][3] - data[0][3] * data[2][1])); result.data[2][2] = id * (+data[0][0] * (data[1][1] * data[3][3] - data[1][3] * data[3][1]) - data[1][0] * (data[0][1] * data[3][3] - data[0][3] * data[3][1]) + data[3][0] * (data[0][1] * data[1][3] - data[0][3] * data[1][1])); result.data[2][3] = id * -(+data[0][0] * (data[1][1] * data[2][3] - data[1][3] * data[2][1]) - data[1][0] * (data[0][1] * data[2][3] - data[0][3] * data[2][1]) + data[2][0] * (data[0][1] * data[1][3] - data[0][3] * data[1][1])); result.data[3][0] = id * -(+data[1][0] * (data[2][1] * data[3][2] - data[2][2] * data[3][1]) - data[2][0] * (data[1][1] * data[3][2] - data[1][2] * data[3][1]) + data[3][0] * (data[1][1] * data[2][2] - data[1][2] * data[2][1])); result.data[3][1] = id * (+data[0][0] * (data[2][1] * data[3][2] - data[2][2] * data[3][1]) - data[2][0] * (data[0][1] * data[3][2] - data[0][2] * data[3][1]) + data[3][0] * (data[0][1] * data[2][2] - data[0][2] * data[2][1])); result.data[3][2] = id * -(+data[0][0] * (data[1][1] * data[3][2] - data[1][2] * data[3][1]) - data[1][0] * (data[0][1] * data[3][2] - data[0][2] * data[3][1]) + data[3][0] * (data[0][1] * data[1][2] - data[0][2] * data[1][1])); result.data[3][3] = id * (+data[0][0] * (data[1][1] * data[2][2] - data[1][2] * data[2][1]) - data[1][0] * (data[0][1] * data[2][2] - data[0][2] * data[2][1]) + data[2][0] * (data[0][1] * data[1][2] - data[0][2] * data[1][1])); return result; } [[nodiscard]] constexpr Mat4x4<Element> transposed() const noexcept { Mat4x4<Element> r; for (auto i = 0; i < 4; ++i) { for (auto j = 0; j < 4; ++j) { r.data[i][j] = data[j][i]; } } return r; } [[nodiscard]] constexpr Vec3<Element> project(const Vec3<Element>& v) const noexcept { Vec4<Element> v4(v, static_cast<Element>(1)); v4 = *this * v4; return v4.xyz() / v4.w; } [[nodiscard]] constexpr static Mat4x4<Element> look_at(const Vec3<Element>& position, const Vec3<Element>& target, const Vec3<Element>& up) noexcept { const auto z = (target - position).normalized(); const auto x = up.cross(z).normalized(); const auto y = z.cross(x); Mat4x4<Element> m; m.data[0][0] = -x.x; m.data[0][1] = y.x; m.data[0][2] = -z.x; m.data[0][3] = static_cast<Element>(0); m.data[1][0] = -x.y; m.data[1][1] = y.y; m.data[1][2] = -z.y; m.data[1][3] = static_cast<Element>(0); m.data[2][0] = -x.z; m.data[2][1] = y.z; m.data[2][2] = -z.z; m.data[2][3] = static_cast<Element>(0); m.data[3][0] = x.dot(position); m.data[3][1] = -y.dot(position); m.data[3][2] = z.dot(position); m.data[3][3] = static_cast<Element>(1); return m; } [[nodiscard]] constexpr static Mat4x4<Element> rotation(const Vec3<Element>& v, const Element degree) noexcept { const auto sinus = static_cast<Element>(sin(static_cast<double>(degree))); const auto cosinus = static_cast<Element>(cos(static_cast<double>(degree))); const Element oneminuscos = 1.0f - cosinus; const Vec3 w = v.normalized(); const Element wx2 = w[0] * w[0]; const Element wxy = w[0] * w[1]; const Element wxz = w[0] * w[2]; const Element wy2 = w[1] * w[1]; const Element wyz = w[1] * w[2]; const Element wz2 = w[2] * w[2]; const Element wxyonemincos = wxy * oneminuscos; const Element wxzonemincos = wxz * oneminuscos; const Element wyzonemincos = wyz * oneminuscos; const Element wxsin = w[0] * sinus; const Element wysin = w[1] * sinus; const Element wzsin = w[2] * sinus; Mat4x4 m; m.data[0][0] = cosinus + (wx2 * oneminuscos); m.data[0][1] = wzsin + wxyonemincos; m.data[0][2] = wxzonemincos - wysin; m.data[0][3] = static_cast<Element>(0); m.data[1][0] = wxyonemincos - wzsin; m.data[1][1] = cosinus + (wy2 * oneminuscos); m.data[1][2] = wxsin + wyzonemincos; m.data[1][3] = static_cast<Element>(0); m.data[2][0] = wysin + wxzonemincos; m.data[2][1] = wyzonemincos - wxsin; m.data[2][2] = cosinus + (wz2 * oneminuscos); m.data[2][3] = static_cast<Element>(0); m.data[3][0] = static_cast<Element>(0); m.data[3][1] = static_cast<Element>(0); m.data[3][2] = static_cast<Element>(0); m.data[3][3] = static_cast<Element>(1); return m; } [[nodiscard]] constexpr static Mat4x4<Element> translator(const Vec3<Element>& v) noexcept { Mat4x4<Element> r; r.data[0][0] = static_cast<Element>(1); r.data[0][1] = static_cast<Element>(0); r.data[0][2] = static_cast<Element>(0); r.data[0][3] = static_cast<Element>(0); r.data[1][0] = static_cast<Element>(0); r.data[1][1] = static_cast<Element>(1); r.data[1][2] = static_cast<Element>(0); r.data[1][3] = static_cast<Element>(0); r.data[2][0] = static_cast<Element>(0); r.data[2][1] = static_cast<Element>(0); r.data[2][2] = static_cast<Element>(1); r.data[2][3] = static_cast<Element>(0); r.data[3][0] = v.x; r.data[3][1] = v.y; r.data[3][2] = v.z; r.data[3][3] = static_cast<Element>(1); return r; } [[nodiscard]] constexpr static Mat4x4<Element> orthographic(const Element width, const Element height, const Element near, const Element far) noexcept { Mat4x4 r; r.data[0][0] = Element(2.0f / width); r.data[0][1] = static_cast<Element>(0); r.data[0][2] = static_cast<Element>(0); r.data[0][3] = static_cast<Element>(0); r.data[1][0] = static_cast<Element>(0); r.data[1][1] = Element(2.0f / height); r.data[1][2] = static_cast<Element>(0); r.data[1][3] = static_cast<Element>(0); r.data[2][0] = static_cast<Element>(0); r.data[2][1] = static_cast<Element>(0); r.data[2][2] = Element(2.0f / (near - far)); r.data[2][3] = static_cast<Element>(0); r.data[3][0] = static_cast<Element>(0); r.data[3][1] = static_cast<Element>(0); r.data[3][2] = Element((far + near) / (near - far)); r.data[3][3] = static_cast<Element>(1); return r; } [[nodiscard]] constexpr static Mat4x4<Element> perspective(const Element width, const Element height, const Element near, const Element far) noexcept { Mat4x4 r; r.data[0][0] = Element((2.0f * near) / width); r.data[0][1] = static_cast<Element>(0); r.data[0][2] = static_cast<Element>(0); r.data[0][3] = static_cast<Element>(0); r.data[1][0] = static_cast<Element>(0); r.data[1][1] = Element((2.0f * near) / height); r.data[1][2] = static_cast<Element>(0); r.data[1][3] = static_cast<Element>(0); r.data[2][0] = static_cast<Element>(0); r.data[2][1] = static_cast<Element>(0); r.data[2][2] = Element((far + near) / (near - far)); r.data[2][3] = Element(-1.0); r.data[3][0] = static_cast<Element>(0); r.data[3][1] = static_cast<Element>(0); r.data[3][2] = Element((2.0f * far * near) / (near - far)); r.data[3][3] = static_cast<Element>(0); return r; } }; } #endif
42.163441
236
0.511527
Hossein-Noroozpour
03e1ff81de734ba25e35f11c2c9a5d2de140ded4
10,929
cpp
C++
src/core/TChem_IgnitionZeroD.cpp
mschmidt271/TChem
01adfcbef0ac107cbc7b9df9d03d783ef5eac83b
[ "BSD-2-Clause" ]
null
null
null
src/core/TChem_IgnitionZeroD.cpp
mschmidt271/TChem
01adfcbef0ac107cbc7b9df9d03d783ef5eac83b
[ "BSD-2-Clause" ]
null
null
null
src/core/TChem_IgnitionZeroD.cpp
mschmidt271/TChem
01adfcbef0ac107cbc7b9df9d03d783ef5eac83b
[ "BSD-2-Clause" ]
null
null
null
#include "TChem_Util.hpp" #include "TChem_IgnitionZeroD.hpp" /// tadv - an input structure for time marching /// state (nSpec+3) - initial condition of the state vector /// qidx (lt nSpec+1) - QoI indices to store in qoi output /// work - work space sized by getWorkSpaceSize /// tcnt - time counter /// qoi (time + qidx.extent(0)) - QoI output /// kmcd - const data for kinetic model namespace TChem { template<typename PolicyType, typename TimeAdvance1DViewType, typename RealType0DViewType, typename RealType1DViewType, typename RealType2DViewType, typename KineticModelConstViewType> void IgnitionZeroD_TemplateRunModelVariation( /// required template arguments const std::string& profile_name, const RealType0DViewType& dummy_0d, /// team size setting const PolicyType& policy, /// input const RealType1DViewType& tol_newton, const RealType2DViewType& tol_time, const RealType2DViewType& fac, const TimeAdvance1DViewType& tadv, const RealType2DViewType& state, /// output const RealType1DViewType& t_out, const RealType1DViewType& dt_out, const RealType2DViewType& state_out, /// const data from kinetic model const KineticModelConstViewType& kmcds) { Kokkos::Profiling::pushRegion(profile_name); using policy_type = PolicyType; auto kmcd_host = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), Kokkos::subview(kmcds, 0)); const ordinal_type level = 1; const ordinal_type per_team_extent = IgnitionZeroD::getWorkSpaceSize(kmcd_host()); Kokkos::parallel_for( profile_name, policy, KOKKOS_LAMBDA(const typename policy_type::member_type& member) { const ordinal_type i = member.league_rank(); const auto kmcd_at_i = (kmcds.extent(0) == 1 ? kmcds(0) : kmcds(i)); const RealType1DViewType fac_at_i = Kokkos::subview(fac, i, Kokkos::ALL()); const auto tadv_at_i = tadv(i); const real_type t_end = tadv_at_i._tend; const RealType0DViewType t_out_at_i = Kokkos::subview(t_out, i); if (t_out_at_i() < t_end) { const RealType1DViewType state_at_i = Kokkos::subview(state, i, Kokkos::ALL()); const RealType1DViewType state_out_at_i = Kokkos::subview(state_out, i, Kokkos::ALL()); const RealType0DViewType dt_out_at_i = Kokkos::subview(dt_out, i); Scratch<RealType1DViewType> work(member.team_scratch(level), per_team_extent); Impl::StateVector<RealType1DViewType> sv_at_i(kmcd_at_i.nSpec, state_at_i); Impl::StateVector<RealType1DViewType> sv_out_at_i(kmcd_at_i.nSpec, state_out_at_i); TCHEM_CHECK_ERROR(!sv_at_i.isValid(), "Error: input state vector is not valid"); TCHEM_CHECK_ERROR(!sv_out_at_i.isValid(), "Error: input state vector is not valid"); { const ordinal_type max_num_newton_iterations = tadv_at_i._max_num_newton_iterations; const ordinal_type max_num_time_iterations = tadv_at_i._num_time_iterations_per_interval; const real_type dt_in = tadv_at_i._dt, dt_min = tadv_at_i._dtmin, dt_max = tadv_at_i._dtmax; const real_type t_beg = tadv_at_i._tbeg; const auto temperature = sv_at_i.Temperature(); const auto pressure = sv_at_i.Pressure(); const auto Ys = sv_at_i.MassFractions(); const RealType0DViewType temperature_out(sv_out_at_i.TemperaturePtr()); const RealType0DViewType pressure_out(sv_out_at_i.PressurePtr()); const RealType1DViewType Ys_out = sv_out_at_i.MassFractions(); const ordinal_type m = Impl::IgnitionZeroD_Problem< typename KineticModelConstViewType::non_const_value_type >::getNumberOfEquations(kmcd_at_i); auto wptr = work.data(); const RealType1DViewType vals(wptr, m); wptr += m; const RealType1DViewType ww(wptr, work.extent(0) - (wptr - work.data())); /// we can only guarantee vals is contiguous array. we basically assume /// that a state vector can be arbitrary ordered. /// m is nSpec + 1 Kokkos::parallel_for(Kokkos::TeamVectorRange(member, m), [&](const ordinal_type& i) { vals(i) = i == 0 ? temperature : Ys(i - 1); }); member.team_barrier(); Impl::IgnitionZeroD ::team_invoke(member, max_num_newton_iterations, max_num_time_iterations, tol_newton, tol_time, fac_at_i, dt_in, dt_min, dt_max, t_beg, t_end, pressure, vals, t_out_at_i, dt_out_at_i, pressure_out, vals, ww, kmcd_at_i); member.team_barrier(); Kokkos::parallel_for(Kokkos::TeamVectorRange(member, m), [&](const ordinal_type& i) { if (i == 0) { temperature_out() = vals(0); } else { Ys_out(i - 1) = vals(i); } }); member.team_barrier(); } } }); Kokkos::Profiling::popRegion(); } template<typename PolicyType, typename TimeAdvance1DViewType, typename RealType0DViewType, typename RealType1DViewType, typename RealType2DViewType, typename KineticModelConstType> void IgnitionZeroD_TemplateRun( /// required template arguments const std::string& profile_name, const RealType0DViewType& dummy_0d, /// team size setting const PolicyType& policy, /// input const RealType1DViewType& tol_newton, const RealType2DViewType& tol_time, const RealType2DViewType& fac, const TimeAdvance1DViewType& tadv, const RealType2DViewType& state, /// output const RealType1DViewType& t_out, const RealType1DViewType& dt_out, const RealType2DViewType& state_out, /// const data from kinetic model const KineticModelConstType& kmcd) { Kokkos::Profiling::pushRegion(profile_name); using policy_type = PolicyType; using space_type = typename policy_type::execution_space; Kokkos::View<KineticModelConstType*,space_type> kmcds(do_not_init_tag("IgnitionaZeroD::kmcds"), 1); Kokkos::deep_copy(kmcds, kmcd); IgnitionZeroD_TemplateRunModelVariation (profile_name, dummy_0d, policy, tol_newton, tol_time, fac, tadv, state, t_out, dt_out, state_out, kmcds); Kokkos::Profiling::popRegion(); } void IgnitionZeroD::runHostBatch( /// input typename UseThisTeamPolicy<host_exec_space>::type& policy, const real_type_1d_view_host& tol_newton, const real_type_2d_view_host& tol_time, const real_type_2d_view_host& fac, const time_advance_type_1d_view_host& tadv, const real_type_2d_view_host& state, /// output const real_type_1d_view_host& t_out, const real_type_1d_view_host& dt_out, const real_type_2d_view_host& state_out, /// const data from kinetic model const KineticModelConstDataHost& kmcd) { IgnitionZeroD_TemplateRun( /// template arguments deduction "TChem::IgnitionZeroD::runHostBatch::kmcd", real_type_0d_view_host(), /// team policy policy, /// input tol_newton, tol_time, fac, tadv, state, /// output t_out, dt_out, state_out, /// const data of kinetic model kmcd); } void IgnitionZeroD::runDeviceBatch( /// thread block size typename UseThisTeamPolicy<exec_space>::type& policy, /// input const real_type_1d_view& tol_newton, const real_type_2d_view& tol_time, const real_type_2d_view& fac, const time_advance_type_1d_view& tadv, const real_type_2d_view& state, /// output const real_type_1d_view& t_out, const real_type_1d_view& dt_out, const real_type_2d_view& state_out, /// const data from kinetic model const KineticModelConstDataDevice& kmcd) { IgnitionZeroD_TemplateRun( /// template arguments deduction "TChem::IgnitionZeroD::runHostBatch::kmcd", real_type_0d_view(), /// team policy policy, /// input tol_newton, tol_time, fac, tadv, state, /// output t_out, dt_out, state_out, /// const data of kinetic model kmcd); } void IgnitionZeroD::runHostBatch( /// input typename UseThisTeamPolicy<host_exec_space>::type& policy, const real_type_1d_view_host& tol_newton, const real_type_2d_view_host& tol_time, const real_type_2d_view_host& fac, const time_advance_type_1d_view_host& tadv, const real_type_2d_view_host& state, /// output const real_type_1d_view_host& t_out, const real_type_1d_view_host& dt_out, const real_type_2d_view_host& state_out, /// const data from kinetic model const Kokkos::View<KineticModelConstDataHost*,host_exec_space>& kmcds) { IgnitionZeroD_TemplateRunModelVariation( /// template arguments deduction "TChem::IgnitionZeroD::runHostBatch::kmcd array", real_type_0d_view_host(), /// team policy policy, /// input tol_newton, tol_time, fac, tadv, state, /// output t_out, dt_out, state_out, /// const data of kinetic model kmcds); } void IgnitionZeroD::runDeviceBatch( /// thread block size typename UseThisTeamPolicy<exec_space>::type& policy, /// input const real_type_1d_view& tol_newton, const real_type_2d_view& tol_time, const real_type_2d_view& fac, const time_advance_type_1d_view& tadv, const real_type_2d_view& state, /// output const real_type_1d_view& t_out, const real_type_1d_view& dt_out, const real_type_2d_view& state_out, /// const data from kinetic model const Kokkos::View<KineticModelConstDataDevice*,exec_space>& kmcds) { IgnitionZeroD_TemplateRunModelVariation( /// template arguments deduction "TChem::IgnitionZeroD::runHostBatch::kmcd array", real_type_0d_view(), /// team policy policy, /// input tol_newton, tol_time, fac, tadv, state, /// output t_out, dt_out, state_out, /// const data of kinetic model kmcds); } } // namespace TChem
32.526786
84
0.631897
mschmidt271
03e5b62ad865ba44024dd644fc012af939d2db94
14,267
cpp
C++
Tools/AssetBuilder/src/AssetPacking.cpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
Tools/AssetBuilder/src/AssetPacking.cpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
Tools/AssetBuilder/src/AssetPacking.cpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
#include "AssetBuilder.hpp" static size_t CalculateBaseOffset(AssetBundlerContext& context) { size_t offset{0}; offset += sizeof(AssetColletionHeader); offset += sizeof(TextureLoadEntry) * context.TexturesToCreate.size(); offset += sizeof(IBLoadEntry) * context.IBsToCreate.size(); offset += sizeof(VBLoadEntry) * context.VBsToCreate.size(); offset += sizeof(ImageEntry) * context.Images.size(); offset += sizeof(ImageAtlas) * context.Atlases.size(); offset += sizeof(MaterialLoadEntry) * context.Materials.size(); offset += sizeof(SkyboxLoadEntry) * context.Skyboxes.size(); offset += sizeof(ImageLoadEntry) * context.LoadImages.size(); offset += sizeof(WavLoadEntry) * context.LoadWavs.size(); offset += sizeof(FontLoadEntry) * context.LoadFonts.size(); offset += sizeof(MeshLoadEntry) * context.LoadMeshes.size(); return offset; } static void ApplyBaseOffset(AssetBundlerContext& context, size_t offset) { for (auto& entry : context.TexturesToCreate) { entry.DataOffset += offset; } for (auto& entry : context.VBsToCreate) { entry.DataOffset += offset; } for (auto& entry : context.IBsToCreate) { entry.DataOffset += offset; } for (auto& entry : context.LoadImages) { entry.DataOffset += offset; } for (auto& entry : context.LoadWavs) { entry.DataOffset += offset; } for (auto& entry : context.LoadFonts) { entry.DataOffset += offset; } for (auto& entry : context.Skyboxes) { entry.DataOffset[0] += offset; entry.DataOffset[1] += offset; entry.DataOffset[2] += offset; entry.DataOffset[3] += offset; entry.DataOffset[4] += offset; entry.DataOffset[5] += offset; } } static void GenerateHeaderArrays(std::ofstream& headerFile, AssetBundlerContext& context, AssetType type, std::string_view arrayName) { // Some defines can be emptry which will generate array with 0 elements which is not a thing in C++ if (std::count_if(context.Defines.begin(), context.Defines.end(), [type](auto& def) { return def.Type == type; }) == 0) return; headerFile << fmt::format("static inline const char* {}Names[] = {{\n", arrayName); for(auto& define : context.Defines) if(define.Type == type) headerFile << fmt::format("\t\"{}\",\n", define.Name); headerFile << "};\n\n"; headerFile << fmt::format("static inline uint32 {}Ids[] = {{\n", arrayName); for(auto& define : context.Defines) if(define.Type == type) headerFile << fmt::format("\t{},\n", define.Id); headerFile << "};\n\n"; headerFile << "/* ------------------------------ */\n\n"; } static void GenerateHeaderDefines(std::ofstream& headerFile, AssetBundlerContext& context) { auto maxLength = std::max_element(context.Defines.begin(), context.Defines.end(), [](auto& d1, auto d2) { return d1.Name.size() < d2.Name.size(); })->Name.size(); for(auto& define : context.Defines) { headerFile << fmt::format("#define {} {:>{}}", define.Name, define.Id, maxLength + 4 - define.Name.size()) << "\n"; } headerFile << "\n\n"; } void PackAssets(AssetBuilder::CommandLineArguments arguments, AssetToLoad* assets, size_t assetsCount, ImageToPack* imagesToPack, size_t imagesToPackCount) { AssetBundlerContext context; context.Header.VersionSpec = 1; AssetDataBlob dataBlob; dataBlob.Data.reserve(1024u*1024u*256u); std::chrono::steady_clock::time_point beginBuilding = std::chrono::steady_clock::now(); fmt::print("----------Running the texture packer----------\n"); { TexturePacker::CommandLineArguments texturePackingArguments; texturePackingArguments.Root = arguments.Root; TexturePackerOutput packedImages = PackTextures(texturePackingArguments, imagesToPack, imagesToPackCount); assert(packedImages.Success); fmt::print("----------Done with image packing----------\n"); // @Note: Create atlas entry and texture load entry for each atlas for (size_t i = 0; i < packedImages.Atlases.size(); ++i) { auto& atlas = packedImages.Atlases[i]; TextureLoadEntry texEntry; texEntry.Id = NextTextureAssetId(); texEntry.Desc.Width = atlas.Width; texEntry.Desc.Height = atlas.Height; texEntry.Desc.Format = atlas.Format; texEntry.DataOffset = dataBlob.PutData(packedImages.AtlasesBytes[i]); context.TexturesToCreate.push_back(texEntry); auto texName = fmt::format("T_ATLAS_{}", context.Atlases.size()); NewAssetName(context, Type_Texture, texName.c_str(), texEntry.Id); std::cout << fmt::format("{} \t->\t Bundling Texture [{:.3} MB]\n", texName, dataBlob.lastSize / (1024.0f*1024.0f)); ImageAtlas atlEntry; atlEntry.TexHandle = texEntry.Id; context.Atlases.push_back(atlEntry); } // @Note: Create image entry for each atlas image by using the tex handles generated // in the previous loop for (size_t i = 0; i < packedImages.Images.size(); ++i) { auto atlasImage = packedImages.Images[i]; ImageEntry imgEntry; imgEntry.Image.AtlasSize = { atlasImage.AtlasWidth, atlasImage.AtlasHeight}; imgEntry.Image.ScreenPos = { atlasImage.X, atlasImage.Y}; imgEntry.Image.ScreenSize = { atlasImage.Width, atlasImage.Height}; imgEntry.Image.TexHandle = context.TexturesToCreate[atlasImage.Atlas].Id; imgEntry.Id = NewAssetName(context, Type_Image, atlasImage.Name); context.Images.push_back(imgEntry); } } for (size_t i = 0; i < assetsCount; ++i) { auto& asset = assets[i]; asset.Path = fmt::format("{}/{}", arguments.Root, asset.Path); switch (asset.Type) { case Type_Font: { LoadFont(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Font [{:.3} KB] [{}]\n", asset.Id, dataBlob.lastSize/1024.0f, asset.Path); break; } case Type_Wav: { LoadWav(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling WAV [{:.3} KB] [{}]\n", asset.Id, dataBlob.lastSize/1024.0f, asset.Path); break; } case Type_Image: { LoadImage(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Image [{:.3} MB] [{}]\n", asset.Id, dataBlob.lastSize/(1024.0f*1024.0f), asset.Path); break; } case Type_Texture: { LoadTexture(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Texture [{:.3} MB] [{}]\n", asset.Id, dataBlob.lastSize/(1024.0f*1024.0f), asset.Path); break; } case Type_Skybox: { LoadSkybox(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Skybox [{:.3} MB] [{}]\n", asset.Id, (6*dataBlob.lastSize)/(1024.0f*1024.0f), asset.Path); break; } case Type_Material: { LoadMaterial(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Material [{:.3} B] [{}]\n", asset.Id, (float)sizeof(MaterialDesc), asset.Path); break; } case Type_Mesh: { LoadMesh(asset, context, dataBlob); const float mem = dataBlob.lastSize > 1024*1024 ? dataBlob.lastSize / (1024.0f*1024.0f) : dataBlob.lastSize / 1024.0f; const char* unit = dataBlob.lastSize > 1024*1024 ? "MBs" : "KBs"; std::cout << fmt::format("{} \t->\t Bundling Mesh [{:.3} {}] [{}]\n", asset.Id, mem, unit, asset.Path); break; } } } context.Header.TexturesCount = (uint32)context.TexturesToCreate.size(); context.Header.VBsCount = (uint32)context.VBsToCreate.size(); context.Header.IBsCount = (uint32)context.IBsToCreate.size(); context.Header.ImagesCount = (uint32)context.Images.size(); context.Header.AtlasesCount = (uint32)context.Atlases.size(); context.Header.LoadImagesCount = (uint32)context.LoadImages.size(); context.Header.LoadWavsCount = (uint32)context.LoadWavs.size(); context.Header.LoadFontsCount = (uint32)context.LoadFonts.size(); context.Header.SkyboxesCount = (uint32)context.Skyboxes.size(); context.Header.LoadMeshesCount = (uint32)context.LoadMeshes.size(); context.Header.MaterialsCount = (uint32)context.Materials.size(); // @Note: The offsets in the context are relative to the beginning of the DataBlob; // when we put them on disk, some of the data in the context will be in front of the // pure data; hence we have to add this base offset to the offsets in the context size_t baseOffset = CalculateBaseOffset(context); ApplyBaseOffset(context, baseOffset); fmt::print("----------Done building assets----------\n"); fmt::print("Textures: \t[{}]\n", context.Header.TexturesCount); fmt::print("Images: \t[{}]\n", context.Header.ImagesCount); fmt::print("Atlases: \t[{}]\n", context.Header.AtlasesCount); fmt::print("LoadImages: \t[{}]\n", context.Header.LoadImagesCount); fmt::print("LoadWavs: \t[{}]\n", context.Header.LoadWavsCount); fmt::print("LoadFonts: \t[{}]\n", context.Header.LoadFontsCount); fmt::print("Skyboxes: \t[{}]\n", context.Header.SkyboxesCount); fmt::print("Meshes: \t[{}]\n", context.Header.LoadMeshesCount); fmt::print("Materials: \t[{}]\n", context.Header.MaterialsCount); std::chrono::steady_clock::time_point endBuilding = std::chrono::steady_clock::now(); fmt::print("Total time for building: [{:.2} s]\n", std::chrono::duration_cast<std::chrono::milliseconds>(endBuilding - beginBuilding).count() / 1000.0f); // @Note: From here forward, we are only writing the results of the packing to the files; // one header file and one asset bundle file /* @Note: The output file will have the following format |---------------Header-------------------| -- struct AssetColletionHeader |----------------------------------------| |---------------Texture_i----------------| -- struct TextureLoadEntry |----------------------------------------| |------------------VB_i------------------| -- struct VBLoadEntry |----------------------------------------| |------------------IB_i------------------| -- struct IBLoadEntry |----------------------------------------| |---------------Image_1------------------| -- struct ImageEntry |---------------Image_2------------------| |---------------.......------------------| |---------------Image_i------------------| |----------------------------------------| |---------------Atlas_1------------------| -- struct AtlasEntry |---------------Atlas_2------------------| |---------------.......------------------| |---------------Atlas_i------------------| |----------------------------------------| |---------------Images-------------------| -- struct ImageLoadEntry |----------------------------------------| |----------------Wavs--------------------| -- struct WavLoadEntry |----------------------------------------| |---------------Fonts--------------------| -- struct FontsLoadEntry |----------------------------------------| |---------------Skyboxes-----------------| -- struct SkyboxLoadEntry |----------------------------------------| -----------------Meshes------------------| -- struct MeshLoadEntry |----------------------------------------| |---------------Material-----------------| -- struct MaterialLoadEntrym |----------------------------------------| |----------------DATA--------------------| -- unsigned char[] */ std::string assetFileName = fmt::format("{}.dbundle", arguments.Output); fmt::print("Saving [{} Bytes] of meta data in [{}]\n", baseOffset, assetFileName); fmt::print("Saving [{:.3} MBs] of pure data in [{}]\n", dataBlob.Data.size() / (1024.0f* 1024.0f), assetFileName); std::ofstream outfile(assetFileName, std::ios::out | std::ios::binary); outfile.write((char*)&context.Header, sizeof(AssetColletionHeader)); outfile.write((char*)context.TexturesToCreate.data(), sizeof(TextureLoadEntry)*context.TexturesToCreate.size()); outfile.write((char*)context.VBsToCreate.data(), sizeof(VBLoadEntry)*context.VBsToCreate.size()); outfile.write((char*)context.IBsToCreate.data(), sizeof(IBLoadEntry)*context.IBsToCreate.size()); outfile.write((char*)context.Images.data(), sizeof(ImageEntry)*context.Images.size()); outfile.write((char*)context.Atlases.data(), sizeof(ImageAtlas)*context.Atlases.size()); outfile.write((char*)context.LoadImages.data(), sizeof(ImageLoadEntry)*context.LoadImages.size()); outfile.write((char*)context.LoadWavs.data(), sizeof(WavLoadEntry)*context.LoadWavs.size()); outfile.write((char*)context.LoadFonts.data(), sizeof(FontLoadEntry)*context.LoadFonts.size()); outfile.write((char*)context.Skyboxes.data(), sizeof(SkyboxLoadEntry)*context.Skyboxes.size()); outfile.write((char*)context.LoadMeshes.data(), sizeof(MeshLoadEntry)*context.LoadMeshes.size()); outfile.write((char*)context.Materials.data(), sizeof(MaterialLoadEntry)*context.Materials.size()); outfile.write((char*)dataBlob.Data.data(), sizeof(char) * dataBlob.Data.size()); outfile.close(); std::ofstream headerFile(fmt::format("{}", arguments.Header), std::ios::out); headerFile << "#pragma once\n"; headerFile << "\n\n"; // @Note: Generate #define with the id of every asset GenerateHeaderDefines(headerFile, context); // @Note: Generaet arrays with the names and ids of each asset GenerateHeaderArrays(headerFile, context, Type_Image, "Images"); GenerateHeaderArrays(headerFile, context, Type_Wav, "Wavs"); GenerateHeaderArrays(headerFile, context, Type_Font, "Fonts"); GenerateHeaderArrays(headerFile, context, Type_Mesh, "Meshes"); // Generate an array which can tell us how big (what font size) given font is headerFile << fmt::format("static inline size_t FontsSizes[] = {{\n"); for (auto& font : context.LoadFonts) { headerFile << fmt::format("\t{},\n", font.Desc.FontSize); } headerFile << "};\n\n"; headerFile << "/* ------------------------------ */\n\n"; headerFile << "inline GPUResource GPUResources[] = {\n"; for(auto& define : context.Defines) { if (define.Type >= GP_Count) continue; headerFile << fmt::format("\t{{ GPUResourceType({}), {}, \"{}\" }},\n", define.Type, define.Id, define.Name); } headerFile << "};\n\n"; headerFile << fmt::format("static inline AssetFile AssetFiles[] = {{\n"); headerFile << fmt::format("\t{{ \"{}\", {} }},\n", assetFileName, baseOffset + dataBlob.Data.size()); headerFile << fmt::format("}};\n\n"); // @Note: This teslls the loading code which file from the AssetFiles collection to load headerFile << fmt::format("static inline size_t {} = {};\n", arguments.Id , 0); }
40.997126
163
0.624658
palikar
03e68c0fdd51c9a3e227755939abfa568dd29f5f
648
cpp
C++
dmoj/uncategorized/16_bit_sw_only.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
dmoj/uncategorized/16_bit_sw_only.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
dmoj/uncategorized/16_bit_sw_only.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int multiplications; cin >> multiplications; for (unsigned int i {0}; i < multiplications; ++i) { long long left; long long right; long long product; cin >> left >> right >> product; if (left * right == product) { cout << "POSSIBLE DOUBLE SIGMA"; } else { cout << "16 BIT S/W ONLY"; } cout << '\n'; } return 0; }
15.804878
54
0.521605
Rkhoiwal
03e71a3be1508cfe9132a6a65b3a9f9b2ede5228
1,031
cpp
C++
proZPRd/ScriptParser.cpp
peku33/proZPRd
632097bc8221116c57b9ae5e76dafd0a63d57fe6
[ "MIT" ]
null
null
null
proZPRd/ScriptParser.cpp
peku33/proZPRd
632097bc8221116c57b9ae5e76dafd0a63d57fe6
[ "MIT" ]
null
null
null
proZPRd/ScriptParser.cpp
peku33/proZPRd
632097bc8221116c57b9ae5e76dafd0a63d57fe6
[ "MIT" ]
null
null
null
#include "ScriptParser.hpp" #include "File.hpp" #include "Tools/Exception.hpp" #ifdef _WIN32 #define popen _popen #define pclose _pclose #endif proZPRd::ScriptParser::ScriptParser(const std::string & ParserExecutable): ParserExecutable(ParserExecutable) { } std::string proZPRd::ScriptParser::Parse(const std::string & ScriptName) const { if(!proZPRd::File::Exists(ScriptName)) throw Tools::Exception(EXCEPTION_PARAMS, "file: " + ScriptName + " not found!"); std::string Command = ParserExecutable + " " + ScriptName.c_str(); FILE* ParserProcess = popen(Command.c_str(), "r"); if (!ParserProcess) throw Tools::Exception(EXCEPTION_PARAMS, "popen() failed!"); char Buffer[128]; std::string Result; while(!feof(ParserProcess)) { auto Length = fread(Buffer, 1, sizeof(Buffer), ParserProcess); if(Length > 0) Result.append(Buffer, Length); } if(pclose(ParserProcess) != 0) throw Tools::Exception(EXCEPTION_PARAMS, Command + " process returned an error!"); return Result; }
27.131579
109
0.702231
peku33
03e7e0fb3bd5648ac5f66e0f418e07bb932947ff
7,226
cc
C++
src/sgmmbin/sgmm-acc-tree-stats.cc
hihihippp/Kaldi
861f838a2aea264a9e4ffa4df253df00a8b1247f
[ "Apache-2.0" ]
19
2015-03-19T10:53:38.000Z
2020-12-17T06:12:32.000Z
src/sgmmbin/sgmm-acc-tree-stats.cc
UdyanSachdev/kaldi
861f838a2aea264a9e4ffa4df253df00a8b1247f
[ "Apache-2.0" ]
1
2018-12-18T17:43:44.000Z
2018-12-18T17:43:44.000Z
src/sgmmbin/sgmm-acc-tree-stats.cc
UdyanSachdev/kaldi
861f838a2aea264a9e4ffa4df253df00a8b1247f
[ "Apache-2.0" ]
47
2015-01-27T06:22:57.000Z
2021-11-11T20:59:04.000Z
// sgmmbin/sgmm-acc-tree-stats.cc // Copyright 2012 Johns Hopkins University (Author: Daniel Povey) // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "tree/context-dep.h" #include "tree/build-tree-utils.h" #include "sgmm/sgmm-clusterable.h" #include "hmm/transition-model.h" int main(int argc, char *argv[]) { using namespace kaldi; typedef kaldi::int32 int32; try { const char *usage = "Accumulate statistics for decision tree training.\n" "This version accumulates statistics in the form of state-specific " "SGMM stats; you need to use the program sgmm-build-tree to build " "the tree (and sgmm-sum-tree-accs to sum the stats).\n" "Usage: sgmm-acc-tree-stats [options] sgmm-model-in features-rspecifier " "alignments-rspecifier [tree-accs-out]\n" "e.g.: sgmm-acc-tree-stats --ci-phones=48:49 1.mdl scp:train.scp ark:1.ali 1.tacc\n"; ParseOptions po(usage); bool binary = true; std::string gselect_rspecifier, spkvecs_rspecifier, utt2spk_rspecifier; string ci_phones_str; int N = 3, P = 1; SgmmGselectConfig sgmm_opts; po.Register("binary", &binary, "Write output in binary mode"); po.Register("gselect", &gselect_rspecifier, "Precomputed Gaussian indices (rspecifier)"); po.Register("spk-vecs", &spkvecs_rspecifier, "Speaker vectors (rspecifier)"); po.Register("utt2spk", &utt2spk_rspecifier, "rspecifier for utterance to speaker map"); po.Register("ci-phones", &ci_phones_str, "Colon-separated list of integer " "indices of context-independent phones."); po.Register("context-width", &N, "Context window size."); po.Register("central-position", &P, "Central context-window position (zero-based)"); sgmm_opts.Register(&po); po.Read(argc, argv); if (po.NumArgs() < 3 || po.NumArgs() > 4) { po.PrintUsage(); exit(1); } std::string sgmm_filename = po.GetArg(1), feature_rspecifier = po.GetArg(2), alignment_rspecifier = po.GetArg(3), accs_wxfilename = po.GetOptArg(4); std::vector<int32> ci_phones; if (ci_phones_str != "") { SplitStringToIntegers(ci_phones_str, ":", false, &ci_phones); std::sort(ci_phones.begin(), ci_phones.end()); if (!IsSortedAndUniq(ci_phones) || ci_phones[0] == 0) { KALDI_ERR << "Invalid set of ci_phones: " << ci_phones_str; } } TransitionModel trans_model; AmSgmm am_sgmm; std::vector<SpMatrix<double> > H; // Not initialized in this program-- not needed // as we don't call Objf() from stats. { bool binary; Input ki(sgmm_filename, &binary); trans_model.Read(ki.Stream(), binary); am_sgmm.Read(ki.Stream(), binary); } if (gselect_rspecifier.empty()) KALDI_ERR << "--gselect option is required."; SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier); RandomAccessInt32VectorReader alignment_reader(alignment_rspecifier); RandomAccessInt32VectorVectorReader gselect_reader(gselect_rspecifier); RandomAccessBaseFloatVectorReader spkvecs_reader(spkvecs_rspecifier); RandomAccessTokenReader utt2spk_reader(utt2spk_rspecifier); std::map<EventType, SgmmClusterable*> tree_stats; int num_done = 0, num_err = 0; for (; !feature_reader.Done(); feature_reader.Next()) { std::string utt = feature_reader.Key(); if (!alignment_reader.HasKey(utt)) { num_err++; } else { const Matrix<BaseFloat> &mat = feature_reader.Value(); const std::vector<int32> &alignment = alignment_reader.Value(utt); if (!gselect_reader.HasKey(utt) || gselect_reader.Value(utt).size() != mat.NumRows()) { KALDI_WARN << "No gselect information for utterance " << utt << " (or wrong size)"; num_err++; continue; } const std::vector<std::vector<int32> > &gselect = gselect_reader.Value(utt); if (alignment.size() != mat.NumRows()) { KALDI_WARN << "Alignments has wrong size "<< (alignment.size())<<" vs. "<< (mat.NumRows()); num_err++; continue; } string utt_or_spk; if (utt2spk_rspecifier.empty()) utt_or_spk = utt; else { if (!utt2spk_reader.HasKey(utt)) { KALDI_WARN << "Utterance " << utt << " not present in utt2spk map; " << "skipping this utterance."; num_err++; continue; } else { utt_or_spk = utt2spk_reader.Value(utt); } } SgmmPerSpkDerivedVars spk_vars; if (spkvecs_reader.IsOpen()) { if (spkvecs_reader.HasKey(utt_or_spk)) { spk_vars.v_s = spkvecs_reader.Value(utt_or_spk); am_sgmm.ComputePerSpkDerivedVars(&spk_vars); } else { KALDI_WARN << "Cannot find speaker vector for " << utt_or_spk; } } // else spk_vars is "empty" // The work gets done here. if (!AccumulateSgmmTreeStats(trans_model, am_sgmm, H, N, P, ci_phones, alignment, gselect, spk_vars, mat, &tree_stats)) { num_err++; } else { num_done++; if (num_done % 1000 == 0) KALDI_LOG << "Processed " << num_done << " utterances."; } } } BuildTreeStatsType stats; // Converting from a map to a vector of pairs. for (std::map<EventType, SgmmClusterable*>::const_iterator iter = tree_stats.begin(); iter != tree_stats.end(); iter++ ) { stats.push_back(std::make_pair<EventType, Clusterable*>(iter->first, iter->second)); } tree_stats.clear(); { Output ko(accs_wxfilename, binary); WriteBuildTreeStats(ko.Stream(), binary, stats); } KALDI_LOG << "Accumulated stats for " << num_done << " files, " << num_err << " failed."; KALDI_LOG << "Number of separate stats (context-dependent states) is " << stats.size(); DeleteBuildTreeStats(&stats); return (num_done != 0 ? 0 : 1); } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
36.680203
101
0.596872
hihihippp
03e7eedbb9a40e47d88ba5db11d7f0db5d1e653c
1,634
cpp
C++
src/Common_Controls/Button/Button.cpp
gammasoft71/Examples_FLTK
7d8f11d5da25f7279834d3730732d07e91591f7c
[ "MIT" ]
21
2020-03-04T17:38:14.000Z
2022-03-07T02:46:39.000Z
src/Common_Controls/Button/Button.cpp
gammasoft71/Examples_FLTK
7d8f11d5da25f7279834d3730732d07e91591f7c
[ "MIT" ]
null
null
null
src/Common_Controls/Button/Button.cpp
gammasoft71/Examples_FLTK
7d8f11d5da25f7279834d3730732d07e91591f7c
[ "MIT" ]
6
2021-03-12T20:57:00.000Z
2022-03-31T23:19:03.000Z
#include <string> #include <FL/Fl.H> #include <FL/Fl_Box.H> #include <FL/Fl_Button.H> #include <FL/Fl_Repeat_Button.H> #include <FL/Fl_Window.H> using namespace std; namespace Examples { class Main_Window : public Fl_Window { public: Main_Window() : Fl_Window(200, 100, 300, 300, "Button example") { button1.align(FL_ALIGN_INSIDE | FL_ALIGN_CLIP | FL_ALIGN_WRAP); button1.callback([](Fl_Widget* sender, void* window) { auto result = "button1 clicked " + to_string(++reinterpret_cast<Main_Window*>(window)->button1_clicked) + " times"; reinterpret_cast<Main_Window*>(window)->box1.copy_label(result.c_str()); }, this); button2.align(FL_ALIGN_INSIDE | FL_ALIGN_CLIP | FL_ALIGN_WRAP); button2.callback([](Fl_Widget* sender, void* window) { auto result = "button2 clicked " + to_string(++reinterpret_cast<Main_Window*>(window)->button2_clicked) + " times"; reinterpret_cast<Main_Window*>(window)->box2.copy_label(result.c_str()); }, this); box1.align(FL_ALIGN_LEFT | FL_ALIGN_TOP | FL_ALIGN_INSIDE | FL_ALIGN_CLIP); box2.align(FL_ALIGN_LEFT | FL_ALIGN_TOP | FL_ALIGN_INSIDE | FL_ALIGN_CLIP); } private: Fl_Button button1 {50, 50, 75, 25, "button1"}; Fl_Repeat_Button button2 {50, 100, 200, 75, "button 2"}; Fl_Box box1 {50, 200, 200, 20, "button1 clicked 0 times"}; Fl_Box box2 {50, 230, 200, 25, "button2 clicked 0 times"}; int button1_clicked = 0; int button2_clicked = 0; }; } int main(int argc, char *argv[]) { Examples::Main_Window window; window.show(argc, argv); return Fl::run(); }
36.311111
123
0.672583
gammasoft71
03ec5b5f51d937311a211b54c17fb4910be5ee95
2,286
hh
C++
notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2011-2014 Centreon ** ** 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. ** ** For more information : [email protected] */ #ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_TIMEPERIOD_BUILDER_HH # define CCB_NOTIFICATION_BUILDERS_COMPOSED_TIMEPERIOD_BUILDER_HH # include <vector> # include "com/centreon/broker/namespace.hh" # include "com/centreon/broker/time/timeperiod.hh" # include "com/centreon/broker/notification/builders/timeperiod_builder.hh" # include "com/centreon/broker/notification/builders/composed_builder.hh" CCB_BEGIN() namespace notification { /** * @class composed_timeperiod_builder composed_timeperiod_builder.hh "com/centreon/broker/notification/builders/composed_timeperiod_builder.hh" * @brief Composed timeperiod builder. * * This class forward its method call to several other builders. */ class composed_timeperiod_builder : public composed_builder<timeperiod_builder> { public: composed_timeperiod_builder(); virtual ~composed_timeperiod_builder() {} virtual void add_timeperiod( unsigned int id, time::timeperiod::ptr tperiod); virtual void add_timeperiod_exception( unsigned int timeperiod_id, std::string const& days, std::string const& timerange); virtual void add_timeperiod_exclude_relation( unsigned int timeperiod_id, unsigned int exclude_id); virtual void add_timeperiod_include_relation( unsigned int timeperiod_id, unsigned int include_id); }; } CCB_END() #endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_TIMEPERIOD_BUILDER_HH
36.285714
146
0.698163
sdelafond
03edcec7dd078dd995694fd563f26e980748dcfa
2,271
hpp
C++
include/codegen/include/OVR/OpenVR/IVROverlay__FindOverlay.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/OVR/OpenVR/IVROverlay__FindOverlay.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/OVR/OpenVR/IVROverlay__FindOverlay.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:02 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: OVR.OpenVR.IVROverlay #include "OVR/OpenVR/IVROverlay.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: OVR::OpenVR namespace OVR::OpenVR { // Forward declaring type: EVROverlayError struct EVROverlayError; } // Completed forward declares // Type namespace: OVR.OpenVR namespace OVR::OpenVR { // Autogenerated type: OVR.OpenVR.IVROverlay/_FindOverlay class IVROverlay::_FindOverlay : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x1508B08 static IVROverlay::_FindOverlay* New_ctor(::Il2CppObject* object, System::IntPtr method); // public OVR.OpenVR.EVROverlayError Invoke(System.String pchOverlayKey, System.UInt64 pOverlayHandle) // Offset: 0x1508B1C OVR::OpenVR::EVROverlayError Invoke(::Il2CppString* pchOverlayKey, uint64_t& pOverlayHandle); // public System.IAsyncResult BeginInvoke(System.String pchOverlayKey, System.UInt64 pOverlayHandle, System.AsyncCallback callback, System.Object object) // Offset: 0x1508F28 System::IAsyncResult* BeginInvoke(::Il2CppString* pchOverlayKey, uint64_t& pOverlayHandle, System::AsyncCallback* callback, ::Il2CppObject* object); // public OVR.OpenVR.EVROverlayError EndInvoke(System.UInt64 pOverlayHandle, System.IAsyncResult result) // Offset: 0x1508FC4 OVR::OpenVR::EVROverlayError EndInvoke(uint64_t& pOverlayHandle, System::IAsyncResult* result); }; // OVR.OpenVR.IVROverlay/_FindOverlay } DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::IVROverlay::_FindOverlay*, "OVR.OpenVR", "IVROverlay/_FindOverlay"); #pragma pack(pop)
45.42
157
0.745927
Futuremappermydud
03f2d5de87a128dbbf8ea8b365b65dd3c6282c1b
2,590
cpp
C++
Source/engine/render/automap_render.cpp
pionere/devilutionX
63f8deb298a00b040010fc299c0568eae19522e1
[ "Unlicense" ]
2
2021-02-02T19:27:20.000Z
2022-03-07T16:50:55.000Z
Source/engine/render/automap_render.cpp
pionere/devilutionX
63f8deb298a00b040010fc299c0568eae19522e1
[ "Unlicense" ]
null
null
null
Source/engine/render/automap_render.cpp
pionere/devilutionX
63f8deb298a00b040010fc299c0568eae19522e1
[ "Unlicense" ]
1
2022-03-07T16:51:16.000Z
2022-03-07T16:51:16.000Z
/** * @file automap_render.cpp * * Line drawing routines for the automap. */ #include "automap_render.hpp" #include "all.h" DEVILUTION_BEGIN_NAMESPACE #ifdef _DEBUG /** automap pixel color 8-bit (palette entry) */ char gbPixelCol; /** flip - if y < x */ bool _gbRotateMap; /** valid - if x/y are in bounds */ bool _gbNotInView; /** Number of times the current seed has been fetched */ #endif /** * @brief Set the value of a single pixel in the back buffer, DOES NOT checks bounds * @param sx Back buffer coordinate * @param sy Back buffer coordinate * @param col Color index from current palette */ void AutomapDrawPixel(int sx, int sy, BYTE col) { BYTE *dst; //assert(gpBuffer != NULL); //if (sy < SCREEN_Y || sy >= SCREEN_HEIGHT + SCREEN_Y || sx < SCREEN_X || sx >= SCREEN_WIDTH + SCREEN_X) // return; dst = &gpBuffer[sx + BUFFER_WIDTH * sy]; //if (dst < gpBufEnd && dst > gpBufStart) *dst = col; } #ifdef _DEBUG /** * @brief Set the value of a single pixel in the back buffer to that of gbPixelCol, checks bounds * @param sx Back buffer coordinate * @param sy Back buffer coordinate */ void engine_draw_pixel(int sx, int sy) { BYTE *dst; assert(gpBuffer != NULL); if (_gbRotateMap) { if (_gbNotInView && (sx < 0 || sx >= SCREEN_HEIGHT + SCREEN_Y || sy < SCREEN_X || sy >= SCREEN_WIDTH + SCREEN_X)) return; dst = &gpBuffer[sy + BUFFER_WIDTH * sx]; } else { if (_gbNotInView && (sy < 0 || sy >= SCREEN_HEIGHT + SCREEN_Y || sx < SCREEN_X || sx >= SCREEN_WIDTH + SCREEN_X)) return; dst = &gpBuffer[sx + BUFFER_WIDTH * sy]; } if (dst < gpBufEnd && dst > gpBufStart) *dst = gbPixelCol; } #endif /** * @brief Draw a line on the back buffer * @param x0 Back buffer coordinate * @param y0 Back buffer coordinate * @param x1 Back buffer coordinate * @param y1 Back buffer coordinate * @param col Color index from current palette */ void AutomapDrawLine(int x0, int y0, int x1, int y1, BYTE col) { int di, ip, dx, dy, ax, ay, steps; float df, fp; dx = x1 - x0; dy = y1 - y0; ax = abs(dx); ay = abs(dy); if (ax > ay) { steps = ax; di = dx / ax; df = dy / (float)steps; ip = x0; fp = (float)y0; for ( ; steps >= 0; steps--, ip += di, fp += df) { AutomapDrawPixel(ip, (int)fp, col); } } else { steps = ay; di = dy / ay; df = dx / float(steps); fp = (float)x0; ip = y0; for ( ; steps >= 0; steps--, fp += df, ip += di) { AutomapDrawPixel((int)fp, ip, col); } } } DEVILUTION_END_NAMESPACE
23.981481
116
0.609266
pionere
03f6af84193b21e7db5661a2f272d288bb969f3c
964
cpp
C++
codeforces/A - Parity/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Parity/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Parity/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Feb/15/2019 00:51 * solution_verdict: Accepted language: GNU C++14 * run_time: 46 ms memory_used: 3900 KB * problem: https://codeforces.com/contest/1110/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; int aa[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int b,k;cin>>b>>k; for(int i=1;i<=k;i++) cin>>aa[i],aa[i]%=2; int bs=1;int sum=0; for(int i=k;i>=1;i--) { sum=(sum+aa[i]*bs)%2; bs=(bs*b)%2; } if(sum)cout<<"odd"<<endl; else cout<<"even"<<endl; return 0; }
35.703704
111
0.378631
kzvd4729
03fed44f9750c22e983dccbafcbdc592396eee76
784
hpp
C++
cppsrc/js-wrappers/wrapColour.hpp
sjoerd108/jimp-native
d489a68923e377d5a7f4fd0f9583382fc3773906
[ "MIT" ]
11
2021-06-05T19:32:08.000Z
2022-03-24T02:01:10.000Z
cppsrc/js-wrappers/wrapColour.hpp
sjoerd108/jimp-native
d489a68923e377d5a7f4fd0f9583382fc3773906
[ "MIT" ]
1
2021-11-13T13:12:48.000Z
2022-02-07T23:46:17.000Z
cppsrc/js-wrappers/wrapColour.hpp
sjoerd108/jimp-native
d489a68923e377d5a7f4fd0f9583382fc3773906
[ "MIT" ]
null
null
null
#pragma once #include <napi.h> #include "../util/referenceFactory.hpp" void wrapBrightness (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapOpacity (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapOpaque (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapContrast (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapPosterize (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapSepia (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapConvolution (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapGreyscale (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory);
39.2
90
0.8125
sjoerd108