blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cc2e165412db3409fe428c3a5a7422a61450eb66 | ea2b696bbe5e7e7cb99b4884a1703bb9dddce8b3 | /day04/ex01/Dog.hpp | 8fc7c9cf8b30391748c0c86baea030c2c7dcb8bd | [] | no_license | mehdaoui-fatima/cpp | 8e2aadb215abb049ccaea9a6ecfb19b3a1478b6e | 947494c9635d60075d5592478917c24bd22cd174 | refs/heads/master | 2023-08-02T14:15:08.058700 | 2021-10-08T07:09:15 | 2021-10-08T07:09:15 | 385,615,239 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,215 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Dog.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fmehdaou <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/14 11:59:30 by fmehdaou #+# #+# */
/* Updated: 2021/09/21 10:45:30 by fmehdaou ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef __DOG_H__
#define __DOG_H__
#include "Animal.hpp"
#include "Brain.hpp"
class Dog : public Animal {
private:
Brain *brain;
public:
Dog(void);
Dog(Dog const &old_obj);
Dog& operator=(Dog const &dog);
virtual void makeSound(void) const;
~Dog(void);
};
#endif | [
"[email protected]"
] | |
10267fe28047eae6742fe822606ec3ac26744f59 | f7b4f20538b2201e2af5af6a2a0b3eb8788e0946 | /Part.cpp | 522259b534efd31000e33e734cf8bd33b20f833a | [] | no_license | jmhensey/Inventory-Database | 456bcc3cec8fea3c6aef5ded084e43694bbd6759 | 50d55d8f40430d4d21f87db27bf97e3e394fadfd | refs/heads/master | 2021-01-25T04:09:12.895871 | 2012-02-25T21:54:33 | 2012-02-25T21:54:33 | 3,539,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,931 | cpp | //Part.cpp: implementation of the header file part.h
//Creator: Julianna Hensey
//Date: 2010/4/17 version 1.0
//Description: This source file includes the function definitions for all functions within the
//part.h header file.
//Assumptions: Data has been checked for stream failure
#include "Part.h"
CPart::CPart()
{
ePartState = CONSTRUCTED;
}
CPart::RTN CPart::Initialize(/*in*/ int iInitPartNum,
/*in*/ string sInitPartDescrip,
/*in*/ int iInitUnitsOnHand,
/*in*/ float fInitUnitValue)
{
//error returns
if (ePartState == INITIALIZED)
return ALREADY_INITIALIZED;
if (sInitPartDescrip.length() == 0)
return DESCRIP_EMPTY;
if (iInitUnitsOnHand < 0 || iInitPartNum > INT_MAX)
return UNITS_INVALID_RANGE;
if (fInitUnitValue < 0)
return UNIT_COST_NEG;
iPartNum = iInitPartNum;
sPartDescrip = sInitPartDescrip;
//set up and loop to check for non-alphanumeric characters
string::size_type LENGTH = sInitPartDescrip.length();
for (int unsigned iCount = 0; LENGTH > iCount; iCount++)
{
if (! isalnum(sPartDescrip.at(iCount)))
sPartDescrip[iCount]= '_';
}
iUnitsOnHand = iInitUnitsOnHand;
fUnitCost = float (int(fInitUnitValue * 100.f + .5f))/100.f;
ePartState = INITIALIZED;
return OK;
}//Initialize
CPart::RTN CPart::Uninitialize()
{
ePartState = CONSTRUCTED;
return OK;
}//Unitialize
CPart::RTN CPart::GetPartState (/*out*/ CPart::STATE& eOutPartState) const
{
eOutPartState = ePartState;
return OK;
}//GetPartState
CPart::RTN CPart::AddUnits (/*in*/ int iUnitsToAdd,
/*out*/ int& iUpdatedOnHand)
{
if (ePartState != INITIALIZED)
return NOT_INITIALIZED;
else
{
iUnitsOnHand += iUnitsToAdd;
iUpdatedOnHand = iUnitsOnHand;
return OK;
}
}//AddUnits
CPart::RTN CPart::SubtractUnits(/*in*/ int iUnitsToSubtract,
/*out*/ int& iUpdatedOnHand)
{
if (ePartState != INITIALIZED)
return NOT_INITIALIZED;
if (iUnitsToSubtract > iUnitsOnHand)
return UNITS_INVALID_RANGE;
else
{
iUnitsOnHand -= iUnitsToSubtract;
iUpdatedOnHand = iUnitsOnHand;
return OK;
}
}//SubtractUnits
CPart::RTN CPart::ReplaceUnitsOnHand(/*in*/ int iNewUnitsOnHand)
{
if (ePartState != INITIALIZED)
return NOT_INITIALIZED;
else if (iNewUnitsOnHand < 0 || iNewUnitsOnHand > INT_MAX)
return UNITS_INVALID_RANGE;
else
{
iUnitsOnHand = iNewUnitsOnHand;
return OK;
}
}//ReplaceUnitsOnHand
CPart::RTN CPart::ReplaceUnitCost(/*in*/ float fNewUnitCost)
{
if (ePartState != INITIALIZED)
return NOT_INITIALIZED;
else if (fNewUnitCost < 0)
return UNIT_COST_NEG;
else
{
fUnitCost = float (int(fNewUnitCost * 100.f + .5f))/100.f;;
return OK;
}
}//ReplaceUnitCost
CPart::RTN CPart::ReplacePartDescrip(/*in*/ string sNewDescrip)
{
if (CPart::ePartState != INITIALIZED)
return NOT_INITIALIZED;
else if (sNewDescrip.length() == 0)
return DESCRIP_EMPTY;
else
{
sPartDescrip = sNewDescrip;
return OK;
}
}//ReplacePartDescrip
CPart::RTN CPart::ReplacePartNum(/*in*/ int iNewPartNum)
{
if (ePartState != INITIALIZED)
return NOT_INITIALIZED;
else
{
iPartNum = iNewPartNum;
return OK;
}
}//ReplacePartNum
CPart::RTN CPart::GetPartInfo(/*out*/ int& iOutPartNum,
/*out*/ string& sOutPartDescrip,
/*out*/ int& iOutUnitsOnHand,
/*out*/ float& fOutUnitCost) const
{
if (ePartState == CONSTRUCTED)
return NOT_INITIALIZED;
iOutPartNum = iPartNum;
sOutPartDescrip = sPartDescrip;
iOutUnitsOnHand = iUnitsOnHand;
fOutUnitCost = fUnitCost;
return OK;
}//GetPartInfo
int CPart::PartNumIsGreaterThan(/*in*/ CPart partOther)
{
if (iPartNum > partOther.iPartNum)
return 1;
else if (iPartNum == partOther.iPartNum)
return 0;
else
return -1;
}//PartNumIsGreaterThan
int CPart::PartDescripIsGreaterThan(/*in*/ CPart partOther)
{
if (sPartDescrip > partOther.sPartDescrip)
return 1;
else if (sPartDescrip == partOther.sPartDescrip)
return 0;
else
return -1;
}//PartDescripIsGreaterThan | [
"[email protected]"
] | |
c60a9d88da0a80e9831ba94fb16692389d865bd4 | 6a5a61b3225b9c2317258c56802ffb575fa57306 | /src/classes/ConflictMarker.hpp | 9ad13d83bff99659af11b5341834644a606bb136 | [
"MIT"
] | permissive | hazuki3417/conflict-marker-check | 49c10dcbef9e06f29fde1c38c27664a0d18061b7 | f8caa281b72a6f616b25656acfc8c4b9fc459a4e | refs/heads/master | 2023-04-26T00:23:02.468271 | 2021-05-14T08:12:46 | 2021-05-14T08:13:08 | 348,280,862 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | hpp | #pragma once
#include <string>
class ConflictMarker
{
private:
int type;
int line;
public:
static const int HEAD_ID;
static const int BOUNDARY_ID;
static const int TAIL_ID;
static const std::string HEAD_NAME;
static const std::string BOUNDARY_NAME;
static const std::string TAIL_NAME;
ConflictMarker(int type, int line);
int get_type();
int get_line();
};
| [
"[email protected]"
] | |
31b3c54a62e912cec7df56c4427b9a5cf6551485 | ed91c77afaeb0e075da38153aa89c6ee8382d3fc | /mediasoup-client/deps/webrtc/src/modules/audio_processing/aec3/subtractor.cc | 2eae686752ddb2c75222042c173bb45ef04547d2 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"MIT"
] | permissive | whatisor/mediasoup-client-android | 37bf1aeaadc8db642cff449a26545bf15da27539 | dc3d812974991d9b94efbc303aa2deb358928546 | refs/heads/master | 2023-04-26T12:24:18.355241 | 2023-01-02T16:55:19 | 2023-01-02T16:55:19 | 243,833,549 | 0 | 0 | MIT | 2020-02-28T18:56:36 | 2020-02-28T18:56:36 | null | UTF-8 | C++ | false | false | 14,243 | cc | /*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_processing/aec3/subtractor.h"
#include <algorithm>
#include <utility>
#include "api/array_view.h"
#include "modules/audio_processing/aec3/adaptive_fir_filter_erl.h"
#include "modules/audio_processing/aec3/fft_data.h"
#include "modules/audio_processing/logging/apm_data_dumper.h"
#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_minmax.h"
#include "system_wrappers/include/field_trial.h"
namespace webrtc {
namespace {
bool UseCoarseFilterResetHangover() {
return !field_trial::IsEnabled(
"WebRTC-Aec3CoarseFilterResetHangoverKillSwitch");
}
void PredictionError(const Aec3Fft& fft,
const FftData& S,
rtc::ArrayView<const float> y,
std::array<float, kBlockSize>* e,
std::array<float, kBlockSize>* s) {
std::array<float, kFftLength> tmp;
fft.Ifft(S, &tmp);
constexpr float kScale = 1.0f / kFftLengthBy2;
std::transform(y.begin(), y.end(), tmp.begin() + kFftLengthBy2, e->begin(),
[&](float a, float b) { return a - b * kScale; });
if (s) {
for (size_t k = 0; k < s->size(); ++k) {
(*s)[k] = kScale * tmp[k + kFftLengthBy2];
}
}
}
void ScaleFilterOutput(rtc::ArrayView<const float> y,
float factor,
rtc::ArrayView<float> e,
rtc::ArrayView<float> s) {
RTC_DCHECK_EQ(y.size(), e.size());
RTC_DCHECK_EQ(y.size(), s.size());
for (size_t k = 0; k < y.size(); ++k) {
s[k] *= factor;
e[k] = y[k] - s[k];
}
}
} // namespace
Subtractor::Subtractor(const EchoCanceller3Config& config,
size_t num_render_channels,
size_t num_capture_channels,
ApmDataDumper* data_dumper,
Aec3Optimization optimization)
: fft_(),
data_dumper_(data_dumper),
optimization_(optimization),
config_(config),
num_capture_channels_(num_capture_channels),
use_coarse_filter_reset_hangover_(UseCoarseFilterResetHangover()),
refined_filters_(num_capture_channels_),
coarse_filter_(num_capture_channels_),
refined_gains_(num_capture_channels_),
coarse_gains_(num_capture_channels_),
filter_misadjustment_estimators_(num_capture_channels_),
poor_coarse_filter_counters_(num_capture_channels_, 0),
coarse_filter_reset_hangover_(num_capture_channels_, 0),
refined_frequency_responses_(
num_capture_channels_,
std::vector<std::array<float, kFftLengthBy2Plus1>>(
std::max(config_.filter.refined_initial.length_blocks,
config_.filter.refined.length_blocks),
std::array<float, kFftLengthBy2Plus1>())),
refined_impulse_responses_(
num_capture_channels_,
std::vector<float>(GetTimeDomainLength(std::max(
config_.filter.refined_initial.length_blocks,
config_.filter.refined.length_blocks)),
0.f)),
coarse_impulse_responses_(0) {
// Set up the storing of coarse impulse responses if data dumping is
// available.
if (ApmDataDumper::IsAvailable()) {
coarse_impulse_responses_.resize(num_capture_channels_);
const size_t filter_size = GetTimeDomainLength(
std::max(config_.filter.coarse_initial.length_blocks,
config_.filter.coarse.length_blocks));
for (std::vector<float>& impulse_response : coarse_impulse_responses_) {
impulse_response.resize(filter_size, 0.f);
}
}
for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
refined_filters_[ch] = std::make_unique<AdaptiveFirFilter>(
config_.filter.refined.length_blocks,
config_.filter.refined_initial.length_blocks,
config.filter.config_change_duration_blocks, num_render_channels,
optimization, data_dumper_);
coarse_filter_[ch] = std::make_unique<AdaptiveFirFilter>(
config_.filter.coarse.length_blocks,
config_.filter.coarse_initial.length_blocks,
config.filter.config_change_duration_blocks, num_render_channels,
optimization, data_dumper_);
refined_gains_[ch] = std::make_unique<RefinedFilterUpdateGain>(
config_.filter.refined_initial,
config_.filter.config_change_duration_blocks);
coarse_gains_[ch] = std::make_unique<CoarseFilterUpdateGain>(
config_.filter.coarse_initial,
config.filter.config_change_duration_blocks);
}
RTC_DCHECK(data_dumper_);
for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
for (auto& H2_k : refined_frequency_responses_[ch]) {
H2_k.fill(0.f);
}
}
}
Subtractor::~Subtractor() = default;
void Subtractor::HandleEchoPathChange(
const EchoPathVariability& echo_path_variability) {
const auto full_reset = [&]() {
for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
refined_filters_[ch]->HandleEchoPathChange();
coarse_filter_[ch]->HandleEchoPathChange();
refined_gains_[ch]->HandleEchoPathChange(echo_path_variability);
coarse_gains_[ch]->HandleEchoPathChange();
refined_gains_[ch]->SetConfig(config_.filter.refined_initial, true);
coarse_gains_[ch]->SetConfig(config_.filter.coarse_initial, true);
refined_filters_[ch]->SetSizePartitions(
config_.filter.refined_initial.length_blocks, true);
coarse_filter_[ch]->SetSizePartitions(
config_.filter.coarse_initial.length_blocks, true);
}
};
if (echo_path_variability.delay_change !=
EchoPathVariability::DelayAdjustment::kNone) {
full_reset();
}
if (echo_path_variability.gain_change) {
for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
refined_gains_[ch]->HandleEchoPathChange(echo_path_variability);
}
}
}
void Subtractor::ExitInitialState() {
for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
refined_gains_[ch]->SetConfig(config_.filter.refined, false);
coarse_gains_[ch]->SetConfig(config_.filter.coarse, false);
refined_filters_[ch]->SetSizePartitions(
config_.filter.refined.length_blocks, false);
coarse_filter_[ch]->SetSizePartitions(config_.filter.coarse.length_blocks,
false);
}
}
void Subtractor::Process(const RenderBuffer& render_buffer,
const std::vector<std::vector<float>>& capture,
const RenderSignalAnalyzer& render_signal_analyzer,
const AecState& aec_state,
rtc::ArrayView<SubtractorOutput> outputs) {
RTC_DCHECK_EQ(num_capture_channels_, capture.size());
// Compute the render powers.
const bool same_filter_sizes = refined_filters_[0]->SizePartitions() ==
coarse_filter_[0]->SizePartitions();
std::array<float, kFftLengthBy2Plus1> X2_refined;
std::array<float, kFftLengthBy2Plus1> X2_coarse_data;
auto& X2_coarse = same_filter_sizes ? X2_refined : X2_coarse_data;
if (same_filter_sizes) {
render_buffer.SpectralSum(refined_filters_[0]->SizePartitions(),
&X2_refined);
} else if (refined_filters_[0]->SizePartitions() >
coarse_filter_[0]->SizePartitions()) {
render_buffer.SpectralSums(coarse_filter_[0]->SizePartitions(),
refined_filters_[0]->SizePartitions(),
&X2_coarse, &X2_refined);
} else {
render_buffer.SpectralSums(refined_filters_[0]->SizePartitions(),
coarse_filter_[0]->SizePartitions(), &X2_refined,
&X2_coarse);
}
// Process all capture channels
for (size_t ch = 0; ch < num_capture_channels_; ++ch) {
RTC_DCHECK_EQ(kBlockSize, capture[ch].size());
SubtractorOutput& output = outputs[ch];
rtc::ArrayView<const float> y = capture[ch];
FftData& E_refined = output.E_refined;
FftData E_coarse;
std::array<float, kBlockSize>& e_refined = output.e_refined;
std::array<float, kBlockSize>& e_coarse = output.e_coarse;
FftData S;
FftData& G = S;
// Form the outputs of the refined and coarse filters.
refined_filters_[ch]->Filter(render_buffer, &S);
PredictionError(fft_, S, y, &e_refined, &output.s_refined);
coarse_filter_[ch]->Filter(render_buffer, &S);
PredictionError(fft_, S, y, &e_coarse, &output.s_coarse);
// Compute the signal powers in the subtractor output.
output.ComputeMetrics(y);
// Adjust the filter if needed.
bool refined_filters_adjusted = false;
filter_misadjustment_estimators_[ch].Update(output);
if (filter_misadjustment_estimators_[ch].IsAdjustmentNeeded()) {
float scale = filter_misadjustment_estimators_[ch].GetMisadjustment();
refined_filters_[ch]->ScaleFilter(scale);
for (auto& h_k : refined_impulse_responses_[ch]) {
h_k *= scale;
}
ScaleFilterOutput(y, scale, e_refined, output.s_refined);
filter_misadjustment_estimators_[ch].Reset();
refined_filters_adjusted = true;
}
// Compute the FFts of the refined and coarse filter outputs.
fft_.ZeroPaddedFft(e_refined, Aec3Fft::Window::kHanning, &E_refined);
fft_.ZeroPaddedFft(e_coarse, Aec3Fft::Window::kHanning, &E_coarse);
// Compute spectra for future use.
E_coarse.Spectrum(optimization_, output.E2_coarse);
E_refined.Spectrum(optimization_, output.E2_refined);
// Update the refined filter.
if (!refined_filters_adjusted) {
// Do not allow the performance of the coarse filter to affect the
// adaptation speed of the refined filter just after the coarse filter has
// been reset.
const bool disallow_leakage_diverged =
coarse_filter_reset_hangover_[ch] > 0 &&
use_coarse_filter_reset_hangover_;
std::array<float, kFftLengthBy2Plus1> erl;
ComputeErl(optimization_, refined_frequency_responses_[ch], erl);
refined_gains_[ch]->Compute(X2_refined, render_signal_analyzer, output,
erl, refined_filters_[ch]->SizePartitions(),
aec_state.SaturatedCapture(),
disallow_leakage_diverged, &G);
} else {
G.re.fill(0.f);
G.im.fill(0.f);
}
refined_filters_[ch]->Adapt(render_buffer, G,
&refined_impulse_responses_[ch]);
refined_filters_[ch]->ComputeFrequencyResponse(
&refined_frequency_responses_[ch]);
if (ch == 0) {
data_dumper_->DumpRaw("aec3_subtractor_G_refined", G.re);
data_dumper_->DumpRaw("aec3_subtractor_G_refined", G.im);
}
// Update the coarse filter.
poor_coarse_filter_counters_[ch] =
output.e2_refined < output.e2_coarse
? poor_coarse_filter_counters_[ch] + 1
: 0;
if (poor_coarse_filter_counters_[ch] < 5) {
coarse_gains_[ch]->Compute(X2_coarse, render_signal_analyzer, E_coarse,
coarse_filter_[ch]->SizePartitions(),
aec_state.SaturatedCapture(), &G);
coarse_filter_reset_hangover_[ch] =
std::max(coarse_filter_reset_hangover_[ch] - 1, 0);
} else {
poor_coarse_filter_counters_[ch] = 0;
coarse_filter_[ch]->SetFilter(refined_filters_[ch]->SizePartitions(),
refined_filters_[ch]->GetFilter());
coarse_gains_[ch]->Compute(X2_coarse, render_signal_analyzer, E_refined,
coarse_filter_[ch]->SizePartitions(),
aec_state.SaturatedCapture(), &G);
coarse_filter_reset_hangover_[ch] =
config_.filter.coarse_reset_hangover_blocks;
}
if (ApmDataDumper::IsAvailable()) {
RTC_DCHECK_LT(ch, coarse_impulse_responses_.size());
coarse_filter_[ch]->Adapt(render_buffer, G,
&coarse_impulse_responses_[ch]);
} else {
coarse_filter_[ch]->Adapt(render_buffer, G);
}
if (ch == 0) {
data_dumper_->DumpRaw("aec3_subtractor_G_coarse", G.re);
data_dumper_->DumpRaw("aec3_subtractor_G_coarse", G.im);
filter_misadjustment_estimators_[ch].Dump(data_dumper_);
DumpFilters();
}
std::for_each(e_refined.begin(), e_refined.end(),
[](float& a) { a = rtc::SafeClamp(a, -32768.f, 32767.f); });
if (ch == 0) {
data_dumper_->DumpWav("aec3_refined_filters_output", kBlockSize,
&e_refined[0], 16000, 1);
data_dumper_->DumpWav("aec3_coarse_filter_output", kBlockSize,
&e_coarse[0], 16000, 1);
}
}
}
void Subtractor::FilterMisadjustmentEstimator::Update(
const SubtractorOutput& output) {
e2_acum_ += output.e2_refined;
y2_acum_ += output.y2;
if (++n_blocks_acum_ == n_blocks_) {
if (y2_acum_ > n_blocks_ * 200.f * 200.f * kBlockSize) {
float update = (e2_acum_ / y2_acum_);
if (e2_acum_ > n_blocks_ * 7500.f * 7500.f * kBlockSize) {
// Duration equal to blockSizeMs * n_blocks_ * 4.
overhang_ = 4;
} else {
overhang_ = std::max(overhang_ - 1, 0);
}
if ((update < inv_misadjustment_) || (overhang_ > 0)) {
inv_misadjustment_ += 0.1f * (update - inv_misadjustment_);
}
}
e2_acum_ = 0.f;
y2_acum_ = 0.f;
n_blocks_acum_ = 0;
}
}
void Subtractor::FilterMisadjustmentEstimator::Reset() {
e2_acum_ = 0.f;
y2_acum_ = 0.f;
n_blocks_acum_ = 0;
inv_misadjustment_ = 0.f;
overhang_ = 0.f;
}
void Subtractor::FilterMisadjustmentEstimator::Dump(
ApmDataDumper* data_dumper) const {
data_dumper->DumpRaw("aec3_inv_misadjustment_factor", inv_misadjustment_);
}
} // namespace webrtc
| [
"[email protected]"
] | |
4dd4e86953fd15a222e9f4b293a5ac5a33ac2888 | ef9a782df42136ec09485cbdbfa8a56512c32530 | /branches/Chickens/src/livestock/uk_cattle.cpp | 2dbc0556a98fcc7dfdbedf70da0746bb6d67e4ff | [] | no_license | penghuz/main | c24ca5f2bf13b8cc1f483778e72ff6432577c83b | 26d9398309eeacbf24e3c5affbfb597be1cc8cd4 | refs/heads/master | 2020-04-22T15:59:50.432329 | 2017-11-23T10:30:22 | 2017-11-23T10:30:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,022 | cpp |
// Class: uk_cattle
//////////////////////////.cpp file/////////////////////////////////////////////////////
#include <common.h>
#include <base.h>
#include "uk_cattle.h"
#include <feed_resource.h>
#include <NixCbits.h>
#include <output.h> // only needed for logging to debug file
// Functions for class uk_cattle
/****************************************************************************\
Constructor with arguments
\****************************************************************************/
uk_cattle::uk_cattle(const char *aName,const int aIndex,const base * aOwner):
cattle(aName,aIndex,aOwner)
{
breed = 0;
birthWeightFactor = 0.07; // SCA p45
partitionSystem=1;
bodyEnergy = 0.0;
uterusProtein=0.0;
uterusEnergy=0.0;
}
/****************************************************************************\
Copy Constructor - is shallow
\****************************************************************************/
uk_cattle::uk_cattle(const uk_cattle& anAnimal)
: cattle(anAnimal)
{
breed = anAnimal.breed;
bodyEnergy = anAnimal.bodyEnergy;
weightChange = anAnimal.weightChange;
birthWeightFactor = anAnimal.birthWeightFactor; // SCA p45
partitionSystem=anAnimal.partitionSystem;
uterusWeight =anAnimal.uterusWeight;
uterusEnergy = anAnimal.uterusEnergy; //track uterus weight (has to be lost at birth) (kg)
uterusProtein =anAnimal.uterusProtein; //track uterus weight (has to be lost at birth) (kg)
a = anAnimal.a;
b = anAnimal.b;
c = anAnimal.c;
Gzero = anAnimal.Gzero;
lactating = anAnimal.lactating;
pregnant = anAnimal.pregnant;
calf = anAnimal.calf;
potPeakMilkYield = anAnimal.potPeakMilkYield;
lactose = anAnimal.lactose;
milkProteinConc = anAnimal.milkProteinConc;
milkfat = anAnimal.milkfat;
milk = NULL;
foetus= NULL;
}
/****************************************************************************\
Destructor
\****************************************************************************/
uk_cattle::~uk_cattle()
{
};
// Function: ManureProduction
void uk_cattle::ManureProduction( fstream* fileStream)
{
theMessage->FatalError("Function in uk_cattle not implemented");
*fileStream << ".LIQM 0.0\n"; //dummy line which is never reached - stops a warning
}
/****************************************************************************\
Reads parameters when initialising an animal at start of simulation
\****************************************************************************/
void uk_cattle::ReadParameters(fstream * afile)
{
Setfile(afile);
cattle::ReadParameters(afile);
SetCritical();
Setcur_pos(0);
string namestr;
namestr=(string) "Animal";
FindSection(namestr.c_str(),code); // find the correct place in the input file
GetParameter("amountFluid",&amountFluid );
GetParameter("amountSolid",&amountSolid );
GetParameter("heatProduction",&heatProduction );
GetParameter("Alias",&Alias);
GetParameter("potPeakMilkYield",&potPeakMilkYield);
GetParameter("lactose",&lactose);
GetParameter("milkprotein",&milkProteinConc);
GetParameter("milkfat",&milkfat);
GetParameter("a",&a);
GetParameter("b",&b);
GetParameter("c",&c);
GetParameter("Gzero",&Gzero);
UnsetCritical();
Setfile(NULL);
}
void uk_cattle::EndBudget(bool show)
{
if (show)
{
cout << "Balance for " << GetName() << endl;
cout << Nbudget;
}
double NRemaining=0;
NRemaining=bodyProtein/N_to_protein();
if (foetus){ NRemaining+=((uk_cattle *)foetus)->GetbodyProtein()/N_to_protein();}
double balance =Nbudget.GetInput()-(Nbudget.GetOutput()+ NRemaining);
if (abs(balance)>0.01) theMessage->FatalError("uk_cattle: N budget error");
Nbudget.Balance(NRemaining);
if (calf)
calf->checkBalances(show);
}
/****************************************************************************\
Calculate intake
\****************************************************************************/
void uk_cattle::intake()
{
DM_intake=0.0;
ME_intake = 0.0;
double DMFromGrazing = 0.0;
double rel_capacity=1;
if (isSuckling) //only if is a calf and is with mother
{
rel_capacity-=SucklingCalfMilkIntake();
feedPlanList=Getmother()->GetfeedPlanList(); //suckling calves have access to same diet as mother
}
int counter=0,Hi=0;
linkList <feed_resource> * ptrlist = new linkList <feed_resource>;
DoSelection(ptrlist,&Hi);
if (fieldList==NULL)
{theMessage->FatalError("uk_cattle: no fieldList initialised");}
for (int i=0;i<fieldList->NumOfNodes(); i++) {fieldOfftakeList[i]= 0.0;};
// {work out potential intake}
double pot_intake=GetPotentialIntake();
double tonnes_per_ha=0;
double tonnes_per_ha_this_resource,rel_avail,rel_intake,DM_intake_this_resource;
double deficit=0.0; //used to record difference between feed intake capacity and feed availability
// fieldOfftakeList->ForgetAll();
feed_resource *aFeed_resource;
for (counter=Hi;counter>=0;counter--)
{
// aFeed_resource=(feed_resource*) ptrlist[counter];
aFeed_resource= ptrlist->ElementAtNumber(counter);
if (rel_capacity>0.001) //avoids rounding errors
{
//handle a supplement
if (aFeed_resource->GetIsSupplement())
{
// calc relative intake from this resource
rel_intake=rel_capacity * Get_quality_factor(aFeed_resource->GetOMD());
// calc potential intake from this resource
DM_intake_this_resource=rel_intake * pot_intake; //max possible intake of this supplement
if ((aFeed_resource->GetAmount() * aFeed_resource->GetdryMatter() * 1000.0) < DM_intake_this_resource) //if ration < potential intake
DM_intake_this_resource = aFeed_resource->GetAmount() * aFeed_resource->GetdryMatter() * 1000.0;
rel_capacity -= DM_intake_this_resource/(Get_quality_factor(aFeed_resource->GetOMD())*pot_intake);
aFeed_resource->Setamount(DM_intake_this_resource/(aFeed_resource->GetdryMatter() * 1000.0)); //convert from DM to FW basis
*aFeed_resource * GetNumber(); //adjust for animal number prior to output of demand
theProducts->SubtractProduct(aFeed_resource); // subtract feed from storage
*aFeed_resource * (1/GetNumber()); //adjust back
}
else //handle a grazed feed resource
{
if (hoursHoused==24.0)
{theMessage->WarningWithDisplay("uk_cattle: intake - grazed feed in diet but animal housed all day");}
tonnes_per_ha_this_resource=aFeed_resource->GetAmount() * aFeed_resource->GetdryMatter()/
aFeed_resource->Getarea_occupied();
if (tonnes_per_ha_this_resource>0.0)
{
// calc relative availability of this resource
rel_avail=(1-hoursHoused/24.0) * Get_availability_factor(tonnes_per_ha_this_resource);
// calc relative intake from this resource
rel_intake=rel_capacity * Get_quality_factor(aFeed_resource->GetOMD()) * rel_avail;
// calc intake from this resource
DM_intake_this_resource=rel_intake * pot_intake;
DMFromGrazing+=DM_intake_this_resource;
aFeed_resource->Setamount(DM_intake_this_resource/(aFeed_resource->GetdryMatter() * 1000.0)); //convert from kg DM to tonnes FW
if (aFeed_resource->GetAmount()>1000.0)
theMessage->FatalError("uk_cattle: error in feed resource diet");
*aFeed_resource * GetNumber(); //adjust for animal number prior to output of demand
double NGrazed = aFeed_resource->GetAmount() * aFeed_resource->GetAllN().n * 1000.0;
((patch *)aFeed_resource ->GetOwner())->SetGrazed(0.5,DM_intake_this_resource);
theOutput->AddIndicator(environmentalIndicator,"33.04 N grazed by cattle","kg N",NGrazed);
*aFeed_resource * (1/GetNumber()); //adjust back
// go through field list and find to which field this patch belongs then add the offtake
for (int i=0;i<fieldList->NumOfNodes(); i++)
{
field* aField = (field*) fieldList->ElementAtNumber(i);
patch* aPatch = (patch *)aFeed_resource ->GetOwner();
if (aPatch->GetOwner() == aField)
{
{fieldOfftakeList[i]+= DM_intake_this_resource * GetNumber();}
}
}
rel_capacity-=rel_intake;
}
else
{
DM_intake_this_resource=0.0;
aFeed_resource->Setamount(0.0);
}
}
DM_intake+=DM_intake_this_resource;
// add this resource to the current diet
if (aFeed_resource->GetAmount()>0.0)
*currentDiet = *currentDiet + *aFeed_resource;
ME_intake+= DM_intake_this_resource * (aFeed_resource->GetME()/aFeed_resource->GetdryMatter());
}
if ((counter==0)&&(rel_capacity>0.001)) // is the last feed available and still have capacity for more
{
deficit = rel_capacity * pot_intake; //check!
}
delete aFeed_resource;
if (rel_capacity<0.0) rel_capacity=0.0;
}// end count through grazing resources
if ((ME_intake<0.00001)||(ME_intake>1000.0))
theMessage->FatalError("uk_cattle: error in current diet");
double totalNinput= currentDiet->GetAmount() * 1000.0 * currentDiet->GetorgN_content().n;
if (isYoung) //output BEFORE adding milk (is internal to livestock)
{theOutput->AddIndicator(environmentalIndicator,"33.01 N in feed for young cattle","kg N",Number * totalNinput);}
else
{theOutput->AddIndicator(environmentalIndicator,"33.02 N in feed for adult cattle","kg N",Number * totalNinput);}
Nbudget.AddInput(currentDiet->GetAmount() * 1000.0 * currentDiet->GetAllN().n);
if (isSuckling)
{
totalNinput+=milk->GetAmount() * 1000.0 * milk->GetorgN_content().n;
Nbudget.AddInput(milk->GetAmount() * 1000.0 * milk->GetorgN_content().n);
feedPlanList=NULL; //otherwise, if calf is culled, feedPlanList will be deleted and mother will have no diet
}
double feedNPerc= 100.0 *totalNinput/DM_intake;
if (feedNPerc<1.0)
theMessage->WarningWithDisplay("uk_cattle: N in diet <1.0%");
// if no grazing then house animals (otherwise will try an partition manure to fields)
if (DMFromGrazing == 0)
hoursHoused = 24.0;
// used for debugging tempfeedList->ForgetAll(); delete tempfeedList;
}
/****************************************************************************\
Calculate quality parameter for SCA 1990 intake equation
\****************************************************************************/
double uk_cattle::Get_quality_factor( double digestibility)
{
// double factor=1 - 1.7*(0.8 - digestibility) ;
double coeff = 1.7;
double factor=1 - coeff * (0.8 - digestibility);
return factor;
}
/****************************************************************************\
Calculate Normal weight (ie LW adjusted to standard condition)
\****************************************************************************/
double uk_cattle::Get_norm_weight()
{
double ret_val;
double k, months, birth_w;
birth_w = MBW * birthWeightFactor;
k = 0.47 / pow(MBW, 0.27);
ret_val = MBW - (MBW - birth_w) * exp(-k * age * 12/theTime.daysInYear(0));
return ret_val;
} /* Get_norm_weight */
/****************************************************************************\
Calculate current size of animal (adjusted for CS), relative to MBW
\****************************************************************************/
double uk_cattle::relsiz()
{
double ret_val;
ret_val = Get_norm_weight() / MBW;
if (ret_val > 1.0) ret_val = 1.0;
return ret_val;
} /* relsiz */
/****************************************************************************\
Calculate potential intake from SCA 1990 intake equation
\****************************************************************************/
double uk_cattle::GetPotentialIntake()
{
// double ret_val = 0.024 * MBW * relsiz() * (1.7-relsiz());
double ret_val;
double s = 1.0;
if (age < 60)
s = 1.0/(1.0 + exp(0.2*(60-age)));
ret_val = s * (0.020 * MBW * relsiz() * (1.7-relsiz()));
return ret_val;
};
/****************************************************************************\
Calculate maintenance energy (MJ ME per day)
\****************************************************************************/
double uk_cattle::calc_energy_maint()
{
double dum, ret_val, age_in_yrs, maturity_factor;
age_in_yrs = age / theTime.daysInYear(0);
// following line ensures age factor has maximum value of 0.84
if (age_in_yrs > 6.0) age_in_yrs = 6.0;
dum = eff_energy_main();
if (isFemale)
{
//for B.taurus, females
ret_val = (1.4 * 1.0 * 0.26 * pow(weight, 0.75) *
exp(age_in_yrs * -0.03)/ dum)
+ ME_intake * 0.09;
// + (Egraze(All_r, Sel_r, num_r) / dum);
}
else
{
ret_val = (1.4 * 1.15 * 0.26 * pow(weight, 0.75) *
exp(age_in_yrs * -0.03)/ dum)
+ ME_intake * 0.09;
}
return ret_val;
}
/*
Calculate EFFICIENCY OF USE OF ENERGY FOR MAINTENANCE
NJH 20.06.00
*/
double uk_cattle::eff_energy_main()
{
double ret_val;
double prop_solid=0;
double conc_ME_solid_diet = 0.0;
double ME_milk = 0.0;
double ME_solid = 0.0;
double DM_solid = 0.0;
if (isSuckling)
{
ME_milk = milk->GetAmount() * milk->GetME();
ME_solid = ME_intake - ME_milk;
DM_solid = DM_intake - milk->GetAmount() * milk->GetdryMatter();
}
else
{
ME_solid = ME_intake;
DM_solid = DM_intake;
}
if (DM_solid>0.0)
conc_ME_solid_diet = ME_solid/DM_solid;
ret_val = (ME_milk/ME_intake) * 0.85 + (ME_solid/ME_intake) * (conc_ME_solid_diet * 0.02 + 0.5);
return ret_val;
}
/****************************************************************************\
Calculate efficiency of use of ME for growth
\****************************************************************************/
double uk_cattle::eff_energy_growth()
{
double ret_val;
double prop_solid=0;
double conc_ME_solid_diet = 0.0;
double ME_milk = 0.0;
double ME_solid = 0.0;
double DM_solid = 0.0;
if (isSuckling)
{
ME_milk = milk->GetAmount() * milk->GetME();
ME_solid = ME_intake - ME_milk;
DM_solid = DM_intake - milk->GetAmount() * milk->GetdryMatter();
}
else
{
ME_solid = ME_intake;
DM_solid = DM_intake;
}
if (DM_solid>0.0)
conc_ME_solid_diet = ME_solid/DM_solid;
ret_val = (ME_milk/ME_intake) * 0.70 + (ME_solid/ME_intake) * (conc_ME_solid_diet * 0.043);
return ret_val;
}
/*
Return energy in EBW change (in MJ of ME)
*/
double uk_cattle::MEinEBWchange()
{ //from SCA p 43, assuming zero rate of change of body weight
double ret_val;
double P = weight/MBW;
ret_val = 4.7 + 22.3/(1+exp(-6.0*(P-0.4)));
return ret_val;
}
/****************************************************************************\
Calculate change in weight for a given amount of ME available for growth
\****************************************************************************/
double uk_cattle::GetWeightChange(double avail_ME)
{
double ret_val;
if (avail_ME<0)
{
double effFactor = 0.8; // from SCA p26
ret_val =avail_ME/(effFactor * MEinEBWchange());
}
else ret_val=avail_ME * eff_energy_growth()/MEinEBWchange();
return ret_val;
}
/****************************************************************************\
Returns the amount of N required/released (in g) by a 1 kg change in empty body weight
\****************************************************************************/
double uk_cattle::NinEBWchange()
{ //from SCA p 103, assuming zero rate of change of body weight
double ret_val;
double P = weight/MBW;
double proteinReq = 220 - 148/(1+exp(-6.0*(P-0.4)));
ret_val = proteinReq/N_to_protein();
return ret_val;
}
/****************************************************************************\
Partitions energy and protein
\****************************************************************************/
void uk_cattle::Partition(double *dungN, double *urineN)
{
//note that daily amounts of N are in g but body protein is in kg
double rumenNsurplus, availableN, heat;
*urineN=0.0;
heat=0.0;
double totalNinput= currentDiet->GetAmount() * 1000000.0 * currentDiet->GetorgN_content().n; //in g
if (isSuckling)
{
totalNinput+=milk->GetAmount() * 1000000.0 * milk->GetorgN_content().n; //in g
}
ProteinDigestion(&availableN);
//sort out protein and energy maintenance
double maintenanceN = CalcMaintenanceN();
if (availableN<maintenanceN) //no protein remobilisation allowed
theMessage->FatalError(GetAlias().c_str()," uk_cattle: insufficient protein available for maintenance");
else availableN-=maintenanceN;
double emain = calc_energy_maint();
double avail_ME = ME_intake - emain;
double pregnancyN=DoPregnancy(&avail_ME, &availableN);
if (avail_ME<0.0) //remobilise body reserves
{
weightChange=GetWeightChange(avail_ME);
weight+=weightChange; //weight change is negative here
if (weight<0.0)
theMessage->FatalError("uk_cattle: lost too much weight - is now <zero!");
bodyEnergy+=weightChange * MEinEBWchange(); //weight change is negative
double remobilisedN= -weightChange * NinEBWchange();
bodyProtein-=remobilisedN/1000.0;
heat+=ME_intake - weightChange * MEinEBWchange(); //weight change is negative
*urineN=availableN + remobilisedN; //assumes that no protein is made available - all is used for energy
}
double milkN = DoLactation(&avail_ME, &availableN); //milkN is in grams
double growthN=0.0;
if (avail_ME>0.0)
{
weightChange=GetWeightChange(avail_ME); //start by assuming growth limited by energy
growthN = weightChange * NinEBWchange();
double growthNDemand = growthN/0.59; //0.59 comes from TCOORN report p 799
if (availableN<growthNDemand) //then growth is restricted by protein
{
growthNDemand = availableN;
growthN = availableN * 0.59;
weightChange=growthN/NinEBWchange();
}
// this is a fudge to stop the animal growing enormous
double maxWeight = 1.0 * Get_norm_weight();
if ((weight + weightChange) > maxWeight)
{
weightChange = maxWeight - weight;
growthN = weightChange * NinEBWchange();
}
bodyEnergy+=weightChange*MEinEBWchange();
bodyProtein+=growthN * N_to_protein()/1000.0;
weight+= weightChange;
heat+=ME_intake - weightChange*MEinEBWchange();
*urineN = totalNinput - (*dungN + growthN + pregnancyN + milkN);
}
if (isSuckling) // finished with milk so delete it
delete milk;
//if rumenNsurplus is negative then it has been used for growth, milk etc
//check here to see if enough N was actually available to be recycled
if (*urineN<0.0)
{
theMessage->FatalError("uk_cattle: urine N has gone negative!");
}
/* if (rumenNsurplus<0.0) //if rumenNsurplus is negative, check to see if enough N is available to be recycled
//this currently creates an error in the farm N balance
{
if (abs(rumenNsurplus)>*urineN) //not enough N for recycling - force feed urea but issue warning
{
double deficit= abs(rumenNsurplus)-*urineN;
feed_resource * aFeed_resource = new feed_resource();
aFeed_resource->Setname("UREA");
theProducts->GiveProductInformation(aFeed_resource);
double amountRequired = deficit/(aFeed_resource->GetAllN().n*1000000.0);
aFeed_resource->Setamount(amountRequired);
theProducts->SubtractProduct(aFeed_resource); // subtract feed from storage
*currentDiet = *currentDiet + *aFeed_resource;
delete aFeed_resource;
if (isYoung)
{theOutput->AddIndicator(environmentalIndicator,"21.30 N in feed for young cattle","kg N",Number * deficit/1000.0);}
else
{theOutput->AddIndicator(environmentalIndicator,"21.31 N in feed for adult cattle","kg N",Number * deficit/1000.0);}
// theMessage->WarningWithDisplay("cattle: insufficient N available for recycling - urea force-fed!");
theMessage->Warning("cattle: insufficient N available for recycling - urea force-fed!");
// theMessage->FatalError(GetAlias().c_str()," cattle: insufficient N available for recycling");
}
} */
if (weight<0.0)
theMessage->FatalError(GetAlias().c_str()," uk_cattle: weight has fallen below zero");
}
/****************************************************************************\
Calculate potential intake from SCA 1990 intake equation
\****************************************************************************/
double uk_cattle::GetPotentialMilkIntake()
{
double ret_val;
ret_val = pow((MBW * relsiz()),0.75) * (0.42 + 0.58*exp(-0.036 * age));
return ret_val;
};
/****************************************************************************\
Remobilise body protein (only in an emergency!) NJH March 2001
\****************************************************************************/
/*double uk_cattle::GetCattleN()
{
return bodyProtein/N_to_protein();
};
*/
/*feed_resource * cattle::GetOutputResource(feed_resource * aFeedResource)
{
feed_resource * anOutputResource = new feed_resource(*aFeedResource);
return anOutputResource;
} */
/****************************************************************************\
Used to calculate potential intake of a given feedstuff (e.g. used to determine silage requirement over winter
\****************************************************************************/
double uk_cattle::GetPotentialIntake(double digestibility)
{
double potentialIntake;
potentialIntake = GetPotentialIntake() * Get_quality_factor(digestibility);
// equation from SCA p 213
if (lactating)
{
double lactationFactor=0.0;
lactationFactor = 1.0 + 0.0024 * pow((daysFromParturition+15),1.7)
*exp(-0.021*(daysFromParturition+15));
//note hack on dayfrompart NJH ??
potentialIntake *= lactationFactor;
}
return potentialIntake;
};
/*
efficiency of use of ME for milk production
*/
double uk_cattle::eff_energy_lactation()
{
double effFactor = 0.02 * ME_intake/DM_intake + 0.4;
return effFactor;
}
double uk_cattle::GetPotentialMilkYield()
{
a = potPeakMilkYield * 1.156;
double potentialMilkYield= a*(exp(-exp(Gzero-b*daysFromParturition)))*exp(-c*daysFromParturition);
return potentialMilkYield;
}
/****************************************************************************\
Checks to see if foetus is at term and if so, produces a calf
\****************************************************************************/
//cattle* cattle::CheckBirth()
uk_cattle* uk_cattle::CheckBirth()
{
if ((pregnant)&&(daysFromConception>=GetgestationPeriod()))
{
weight-=(uterusWeight + foetus->Getweight());
foetus->Setage(0);
foetus->SetisFoetus(false);
calf = foetus;
foetus = NULL;
calf->SetisYoung(true);
calf->SetisSuckling(true);
bodyEnergy-=uterusEnergy;
uterusEnergy=0.0;
bodyProtein-=uterusProtein;
theOutput->AddIndicator(environmentalIndicator,"33.40 N in dairy cattle waste","kg N",Number * uterusProtein/N_to_protein());
Nbudget.AddOutput(uterusProtein/N_to_protein());
uterusProtein=0.0;
Nbudget.AddOutput(((uk_cattle *)calf)->GetbodyProtein()/N_to_protein());
lactating = true;
lactationNumber++;
pregnant = false;
// calf->SetfeedPlanList(NULL); // calf gets same diet choice as mother
calf->SetfieldList(fieldList); //calf has access to same fields as mother
calf->SetAlias("CALF");
calf->SetStableSection(GetStableSection());
((uk_cattle *)calf)->SetFoetus(NULL);
calf->SetNumber(Number);
return (uk_cattle *) calf;
}
else return NULL;
}
double uk_cattle::DoPregnancy(double *avail_ME, double *availableN)
{
double pregnancyNDemand = 0.0;
if (pregnant)
{
double pregnancyEnergyDemand=0.0;
double newFoetusEnergy = exp(11.946 - 16.595 * exp(-0.00334*(daysFromConception+1)))-exp(11.946 - 16.595 * exp(-0.00334*daysFromConception));
double newGravidUterusEnergy= exp(349.222 - 349.164 * exp(-0.0000576*(daysFromConception+1)))-exp(349.222 - 349.164 * exp(-0.0000576*daysFromConception));
double newUterusEnergy = newGravidUterusEnergy - newFoetusEnergy;
// scale for assumed 40kg calf, as suggested in SCA p 39
double adjustment = MBW*birthWeightFactor/40.0;
newFoetusEnergy *= adjustment;
((uk_cattle *)foetus)->SetbodyEnergy(((uk_cattle *)foetus)->GetbodyEnergy() + newFoetusEnergy);
newUterusEnergy *=adjustment;
bodyEnergy+=newUterusEnergy;
uterusEnergy+=newUterusEnergy;
double newUterus = GetWeightChange(newUterusEnergy); //note that GetWeightChange will update weight
uterusWeight+=newUterus;
double newFoetus = newFoetusEnergy/5.8; //estimate of MJ/kg EBW of foetus from energy at term/weight at term
foetus->Setweight(foetus->Getweight()+newFoetus);
pregnancyEnergyDemand = (newFoetusEnergy + newUterusEnergy)/eff_energy_growth();
weightChange=newUterus + newFoetus;
//now protein
double newFoetusProtein = CalcFoetusProtein(1)-CalcFoetusProtein(0);
double newGravidUterusProtein= CalcGravidUterusProtein(1)
- CalcGravidUterusProtein(0);
double newUterusProtein = newGravidUterusProtein - newFoetusProtein;
newFoetusProtein *=adjustment; //scale for assumed calf size of 40 kg
newUterusProtein *=adjustment;
((uk_cattle *)foetus)->AddBodyProtein(newFoetusProtein/1000.0);
bodyProtein+= newUterusProtein/1000.0;
uterusProtein+=newUterusProtein/1000.0;
pregnancyNDemand=(newFoetusProtein + newUterusProtein)/(N_to_protein()* 0.85);
*avail_ME-=pregnancyEnergyDemand;
if (*availableN<pregnancyNDemand) //no protein remobilisation allowed for pregnancy
theMessage->FatalError("uk_cattle: insufficient protein available for pregnancy");
else *availableN-=pregnancyNDemand;
}
return pregnancyNDemand * 0.85;
}
void uk_cattle::MakePregnant(bool isAFemale)
{
//assumes calf is same genetic makeup as mother
foetus = new uk_cattle(*this);
foetus->Setage(GetgestationPeriod());
foetus->SetisFoetus(true); //prob should collect these calls together in one routine
foetus->Setweight(0.0);
// foetus->Initialise(animalModel, Getcode(), 0.0, LivestockUnits, GetNumber(), true, (fstream *) CattleSuitcase->GetOutputFile());
foetus->Initialise(Getcode(), 0.0, LivestockUnits, GetNumber(), true);
foetus->Setmother(this);
((uk_cattle *)foetus)->SetFoetus(NULL);
foetus->SetCalf(NULL);
foetus->SetlactationNumber(0);
foetus->SetisFemale(isAFemale);
daysFromConception=0;
pregnant = true;
// lactationNumber++;
};
/****************************************************************************\
Calculate lactation
\****************************************************************************/
double uk_cattle::DoLactation(double *avail_ME, double *availableN)
{
double milkN = 0.0; //milkN is in grams
if (lactating)
{
milk = new feedItem(); //deleted later in this routine (if no calf), otherwise deleted by calf
milk->Setname("MILK");
theProducts->GiveProductInformation(milk);
bool proteinLimited = false;
bool energyLimited = false;
double lactationN = 0.0;
double potentialMilkYield = GetPotentialMilkYield();
if (calf) // see if has a calf (only has calf if calf is suckling)
{
// see if calf intake limits milk production
double calfPotentialIntake = ((uk_cattle *)calf)->GetPotentialMilkIntake();
if (calfPotentialIntake<potentialMilkYield) potentialMilkYield=calfPotentialIntake;
}
double NEMilk = 0.0381 * milkfat + 0.0245 * milkProteinConc + 0.0165 * lactose; //SCA p54
double lactationEnergy = potentialMilkYield * NEMilk/eff_energy_lactation();
milkN = potentialMilkYield * milkProteinConc/N_to_protein();
lactationN = milkN/0.68; //from TCOORN p809
double proteinLimitedMilk = 9999.0, energyLimitedMilk = 9999.0, actMilkYield;
if (*availableN < lactationN) // see if protein is limiting
{
proteinLimitedMilk = *availableN * 0.68 * N_to_protein()/milkProteinConc;
}
if (*avail_ME<lactationEnergy) // see if energy is limiting
{
energyLimitedMilk = *avail_ME * eff_energy_lactation()/NEMilk;
}
// if energy or protein limiting, find out which one
if ((proteinLimitedMilk<potentialMilkYield)||(energyLimitedMilk<potentialMilkYield))
{
if (proteinLimitedMilk<energyLimitedMilk) proteinLimited = true;
else energyLimited=true;
}
else
{
actMilkYield=potentialMilkYield;
*avail_ME-=lactationEnergy;
*availableN-=lactationN;
}
// if protein limiting then there is no remobilisation
if (proteinLimited)
{
actMilkYield=proteinLimitedMilk;
milkN = *availableN * 0.68;
lactationEnergy = actMilkYield * NEMilk/eff_energy_lactation();
*availableN=0.0;
}
// if energy is limiting, there SHOULD be remobilisatin but this is not implemented
if (energyLimited)
{
actMilkYield=energyLimitedMilk;
lactationEnergy = *avail_ME;
milkN = actMilkYield * milkProteinConc/N_to_protein();
lactationN = milkN/0.68;
*avail_ME = 0.0;
}
//these following values need to be checked!!!!
milk->SetME(NEMilk*1000.0); //convert to ME per tonne (standard for products)
milk->SetorgN_content(milkProteinConc/(1000.0 * N_to_protein()));
milk->Setamount(actMilkYield/1000.0);
if (!calf)
{
// theProducts->AddProduct(milk);
// CattleSuitcase->AddIndicator(environmentalIndicator,"Milk yield",actMilkYield);
double value = milk->GetaPrice()->GetactualSellPrice();
theOutput->AddIndicator(environmentalIndicator,"33.20 N in milk","kg N",Number * milkN/1000.0);
theOutput->AddIndicator(economicIndicator,"05.55 Milk sold","Dkr",Number * milk->GetAmount() * 1000.0 * value); //proce is in litrs
theOutput->AddIndicator(economicIndicator,"19.40 Milk sold","litres",Number * milk->GetAmount() * 1000.0);
delete milk; //should really be exported to a tank
}
Nbudget.AddOutput(milkN/1000.0);
}
return milkN;
}
double uk_cattle::CalcFoetusEnergy(double timeFromConception)
{
double FoetusEnergy = exp(11.946 - 16.595 * exp(-0.00334*(timeFromConception)));
return FoetusEnergy;
}
double uk_cattle::CalcFoetusWeight(double timeFromConception)
{
double foetusWeight = CalcFoetusEnergy(timeFromConception)/5.8; //estimate of MJ/kg EBW of foetus from energy at term/weight at term
return foetusWeight;
}
double uk_cattle::SucklingCalfMilkIntake()
{
milk = ((uk_cattle*)mother)->Getmilk();
double potMilkIntake = GetPotentialMilkIntake();
double intakeReduction = milk->GetAmount()*1000.0/potMilkIntake;
ME_intake= milk->GetAmount() * milk->GetME();
DM_intake =milk->GetAmount() * milk->GetdryMatter() * 1000.0;
return intakeReduction;
}
void uk_cattle::Createfoetus()
{
foetus = new uk_cattle(*this);
}
double uk_cattle::CalcFoetusProtein(double daysFromConception)
{
double foetusProtein = cattle::CalcFoetusProtein(daysFromConception);
return foetusProtein;
}
double uk_cattle::CalcGravidUterusProtein(double daysFromConception)
{
double gravidUterusProtein= cattle::CalcGravidUterusProtein(daysFromConception);
return gravidUterusProtein;
}
| [
"[email protected]"
] | |
d1fa101a4e6cc75fe3d509d03690df3e77dcd7c8 | a1c878e9ce6f92aeb00b15065d8c63dd4104a299 | /llarp/link_message.cpp | 226e66c330b5c03900e77717a03b483348b72dc4 | [
"Zlib"
] | permissive | KeeJef/llarp | 18838023b6b69f515b78c50a9b6f059b4506f79f | 9723a11195545afdbb801517747dcb37bf252b1f | refs/heads/master | 2020-03-20T18:10:05.774691 | 2018-06-15T14:33:38 | 2018-06-15T14:33:38 | 137,574,536 | 0 | 0 | null | 2018-06-16T11:07:03 | 2018-06-16T11:07:02 | null | UTF-8 | C++ | false | false | 2,863 | cpp | #include <llarp/router_contact.h>
#include <llarp/messages.hpp>
#include "buffer.hpp"
#include "logger.hpp"
#include "router.hpp"
namespace llarp
{
ILinkMessage::ILinkMessage(const RouterID& id) : remote(id)
{
}
InboundMessageParser::InboundMessageParser(llarp_router* _router)
: router(_router)
{
reader.user = this;
reader.on_key = &OnKey;
}
bool
InboundMessageParser::OnKey(dict_reader* r, llarp_buffer_t* key)
{
InboundMessageParser* handler =
static_cast< InboundMessageParser* >(r->user);
llarp_buffer_t strbuf;
// we are reading the first key
if(handler->firstkey)
{
// check for empty dict
if(!key)
return false;
// we are expecting the first key to be 'a'
if(!llarp_buffer_eq(*key, "a"))
{
llarp::Warn("message has no message type");
return false;
}
if(!bencode_read_string(r->buffer, &strbuf))
{
llarp::Warn("could not read value of message type");
return false;
}
// bad key size
if(strbuf.sz != 1)
{
llarp::Warn("bad mesage type size: ", strbuf.sz);
return false;
}
// create the message to parse based off message type
switch(*strbuf.cur)
{
case 'i':
handler->msg = new LinkIntroMessage(
handler->from->get_remote_router(handler->from));
break;
case 'd':
handler->msg = new RelayDownstreamMessage(handler->GetCurrentFrom());
break;
case 'u':
handler->msg = new RelayUpstreamMessage(handler->GetCurrentFrom());
break;
case 'm':
handler->msg = new DHTImmeidateMessage(handler->GetCurrentFrom());
break;
case 'a':
handler->msg = new LR_AckMessage(handler->GetCurrentFrom());
break;
case 'c':
handler->msg = new LR_CommitMessage(handler->GetCurrentFrom());
break;
case 'z':
handler->msg = new DiscardMessage(handler->GetCurrentFrom());
break;
default:
return false;
}
handler->firstkey = false;
return handler->msg != nullptr;
}
// check for last element
if(!key)
return handler->MessageDone();
return handler->msg->DecodeKey(*key, r->buffer);
}
RouterID
InboundMessageParser::GetCurrentFrom()
{
auto rc = from->get_remote_router(from);
return rc->pubkey;
}
bool
InboundMessageParser::MessageDone()
{
bool result = false;
if(msg)
{
result = msg->HandleMessage(router);
delete msg;
msg = nullptr;
}
return result;
}
bool
InboundMessageParser::ProcessFrom(llarp_link_session* src, llarp_buffer_t buf)
{
from = src;
firstkey = true;
return bencode_read_dict(&buf, &reader);
}
}
| [
"[email protected]"
] | |
8e48bc42dece972eb710f85d99b5864134d14b2e | d96b7a4388c08e93af0f23a56cec49698265ffd9 | /src/fragglescript/t_parse.h | f33483ff52fed88de4423b58f93f35e131d2a4c1 | [] | no_license | ddraigcymraeg/gzscoredoom | eb59f0e2e56774ffb8db92447b1c92ed119be004 | 51f0c7a88ee29e1aa29c82dec513ecff0dd38894 | refs/heads/master | 2021-01-10T11:55:02.906157 | 2016-03-04T01:16:36 | 2016-03-04T01:16:36 | 53,095,610 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,329 | h | // Emacs style mode select -*- C++ -*-
//----------------------------------------------------------------------------
//
// Copyright(C) 2000 Simon Howard
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//--------------------------------------------------------------------------
#ifndef __PARSE_H__
#define __PARSE_H__
#include "m_fixed.h"
#include "actor.h"
typedef struct sfarray_s sfarray_t;
typedef struct script_s script_t;
typedef struct svalue_s svalue_t;
typedef struct operator_s operator_t;
#define T_MAXTOKENS 256
#define TOKENLENGTH 128
struct svalue_s
{
int type;
union
{
long i;
char *s;
char *labelptr; // goto() label
fixed_t f; // haleyjd: 8-17
AActor *mobj;
sfarray_t *a; // haleyjd 05/27: arrays
} value;
};
struct sfarray_s
{
struct sfarray_s *next; // next array in save list
int saveindex; // index for saving
unsigned int length; // number of values currently initialized
svalue_t *values; // array of contained values
};
// haleyjd: following macros updated to 8-17 standard
// furthered to include support for svt_mobj
// un-inline these two functions to save some memory
int intvalue(const svalue_s & v);
fixed_t fixedvalue(const svalue_s & v);
float floatvalue(const svalue_s & v);
const char *stringvalue(const svalue_t & v);
#include "t_vari.h"
#include "t_prepro.h"
// haleyjd: moved from t_script.h - 8-17
// 01/06/01: doubled number of allowed scripts
#define MAXSCRIPTS 257
struct script_s
{
// script data
char *data;
int scriptnum; // this script's number
int len;
// {} sections
section_t *sections[SECTIONSLOTS];
// variables:
svariable_t *variables[VARIABLESLOTS];
// ptr to the parent script
// the parent script is the script above this level
// eg. individual linetrigger scripts are children
// of the levelscript, which is a child of the
// global_script
script_t *parent;
// haleyjd: 8-17
// child scripts.
// levelscript holds ptrs to all of the level's scripts
// here.
script_t *children[MAXSCRIPTS];
AActor *trigger; // object which triggered this script
bool lastiftrue; // haleyjd: whether last "if" statement was
// true or false
};
struct operator_s
{
char *string;
svalue_t (*handler)(int, int, int); // left, mid, right
int direction;
};
enum
{
forward,
backward
};
void run_script(script_t *script);
void continue_script(script_t *script, char *continue_point);
void parse_include(char *lumpname);
void run_statement();
void script_error(char *s, ...);
svalue_t evaluate_expression(int start, int stop);
int find_operator(int start, int stop, char *value);
int find_operator_backwards(int start, int stop, char *value);
/******* tokens **********/
typedef enum
{
name_, // a name, eg 'count1' or 'frag'
number,
operator_,
string_,
unset,
function // function name
} tokentype_t;
enum // brace types: where current_section is a { or }
{
bracket_open,
bracket_close
};
extern svalue_t nullvar;
extern script_t *current_script;
extern AActor *trigger_obj;
extern int killscript;
extern char *tokens[T_MAXTOKENS];
extern tokentype_t tokentype[T_MAXTOKENS];
extern int num_tokens;
extern char *rover; // current point reached in parsing
extern char *linestart; // start of the current expression
extern section_t *current_section;
extern section_t *prev_section;
extern int bracetype;
// the global_script is the root
// script and contains only built-in
// FraggleScript variables/functions
extern script_t global_script;
extern script_t hub_script;
#endif
| [
"[email protected]"
] | |
e1cb5225b7e6cca3cea4ac20305b574291a2e791 | e17f641d6d6ccb4eed67a7e0b1fcf127e4cd669b | /MIRZA/1/src/MIRZA.cpp | 3131fa6e4ea598084d359cc8fab1590279d30221 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-or-later"
] | permissive | zavolanlab/Dockerfiles | 1aa31a71a24da81f55719ec4b6b065ca4c19b60d | 5212974b57f363447ca54b2daec36c397f2e1385 | refs/heads/master | 2022-07-19T15:30:48.472357 | 2022-07-07T19:31:07 | 2022-07-08T10:09:11 | 133,523,143 | 9 | 3 | Apache-2.0 | 2022-07-08T10:09:12 | 2018-05-15T13:50:09 | Perl | UTF-8 | C++ | false | false | 4,431 | cpp | // ===========================================================================
// Name : MIRZA.cpp
// Author : Mohsen Khorshid
// Copyright : University of Basel, 2010
// Description : Alignment model miRNA to mRNA target
// ===========================================================================
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "Hybridize.h"
#include <stdlib.h>
#include <string>
#include <math.h>
#include <time.h>
#define miRNA_FIXED_LENGTH 21
#define NUMBER_OF_ENERGY_PARAMETER_LENGTH 6
#define NOISE 0.05
#define ENERGY_SCALE 20
using namespace std;
//The Hybridizer
Hybridize Hybridizer = Hybridize();
int main(int argc, char* argv[]) {
int mRNAlength = atoi(argv[4]);
int updatePriors = 0;
string PriorUpdate_ARGUMENT = argv[5];
if(!(PriorUpdate_ARGUMENT.compare("update"))){updatePriors = 1;}
//Initialize the Hybridizer and allocate the necessary memory
Hybridizer.mRNA_Length = mRNAlength;
Hybridizer.updatePriors = updatePriors;
Hybridizer.Initialize();
//microRNA expression levels
string miRNA_expression_file = argv[1];
//set the file Names for Hybridizer
string my_mRNA_file = argv[2];
string my_miRNA_file = argv[3];
Hybridizer.Read_mRNA_fasta_file(my_mRNA_file);
//Estimate the base content fractions in the mRNA sequences
Hybridizer.Params.Initialize();
cerr << "__________________________________________________" << endl;
Hybridizer.Read_miRNA_fasta_file(my_miRNA_file);
cerr << "__________________________________________________" << endl;
//Setting the initial miRNA expression levels in the sample
Hybridizer.Read_miRNA_expressions(miRNA_expression_file);
cerr << "__________________________________________________" << endl;
Hybridizer.Gaussian_Penalty = 0;
// These are the parameters of the hybridization model
double parameters[miRNA_FIXED_LENGTH + NUMBER_OF_ENERGY_PARAMETER_LENGTH] = {0};
cout << "Setting the Energy Parameters of the Hybridizer with the following values: " << endl;
parameters[0]= 2.38714;
parameters[1]= 2.39491;
parameters[2]= -3.61813;
parameters[3]= -0.285659;
parameters[4]= 1.01614;
parameters[5]= 1.03229;
//These are the 21 positional parameters
parameters[6]= -3.24074;
parameters[7]= -0.249397;
parameters[8]= 3.45158;
parameters[9]= 3.59005;
parameters[10]= 0.609733;
parameters[11]= 2.46235;
parameters[12]= -0.0431051;
parameters[13]= -0.815238;
parameters[14]= -4.25303;
parameters[15]= -3.08829;
parameters[16]= -1.84676;
parameters[17]= -4.55569;
parameters[18]= -1.75914;
parameters[19]= -1.53761;
parameters[20]= -1.78762;
parameters[21]= -1.46246;
parameters[22]= -4.20649;
parameters[23]= -1.79764;
parameters[24]= -2.24505;
parameters[25]= -4.15307;
parameters[26]= -3.82612;
for (unsigned int i = 0; i < miRNA_FIXED_LENGTH + NUMBER_OF_ENERGY_PARAMETER_LENGTH; i++) {
cout << "init[" << i << "] = " << parameters[i] << ";" << endl;
Hybridizer.Gaussian_Penalty += (parameters[i] / ENERGY_SCALE) * (parameters[i] / ENERGY_SCALE);
}
//Initialize the looping energies
Hybridizer.eE_OPEN=0;
Hybridizer.eE_SYM=0;
Hybridizer.eE_mRNA_Assymetric_loops=0;
Hybridizer.eE_miRNA_Assymetric_loops=0;
//Initializing the miRNA priors relative to their expression in the cell
Hybridizer.Initialize_miRNA_priors();
//Initialize mRNA versus miRNA likelihood ratios
Hybridizer.Initialize_miRNA_mRNA_likelihood_ratios();
//Initialaize the values mRNA likelihood ratios
Hybridizer.Initialize_mRNA_log_likelihood_ratios();
//Set the energy parameters [with length of ENERGY_PARAMETER_LENGTH] that are being optimized and Calculate the Exponentials and Coefficients
Hybridizer.Initialize_Global_Parameters_and_Prepare(parameters);
//Start the calculation
Hybridizer.Calculate_data_log_likelihood_ratio();
return 0;
}
| [
"[email protected]"
] | |
5111b38c005b27293ba0ace01c82f886488b64aa | 60a93f1c34617bd08f1862ef076dc77f766d37b2 | /source/World/Detail/GameObjectManager_Implementation.hpp | 5f6d5529893495322dfc7acdbbb44d7a14bc4005 | [
"MIT"
] | permissive | dantros/MonaEngine | 4f4fdbd2344f553f9bfd0189a4872a0581022f40 | e3d0048c2fe2dd282b84686f0e31e5741714222b | refs/heads/master | 2023-07-27T10:51:18.565020 | 2021-09-17T00:11:39 | 2021-09-17T00:11:39 | 395,851,979 | 0 | 1 | MIT | 2021-08-15T03:23:15 | 2021-08-14T01:32:20 | null | UTF-8 | C++ | false | false | 2,309 | hpp | #pragma once
#ifndef GAMEOBJECTMANAGER_IMPLEMENTATION_HPP
#define GAMEOBJECTMANAGER_IMPLEMENTATION_HPP
#include <utility>
#include "../../Core/Log.hpp"
namespace Mona {
template <typename ObjectType, typename ...Args>
ObjectType* GameObjectManager::CreateGameObject(World& world, Args&& ... args)
{
static_assert(std::is_base_of<GameObject, ObjectType>::value, "ObjectType must be a derived class from GameObject");
MONA_ASSERT(m_gameObjects.size() < s_maxEntries, "GameObjectManager Error: Cannot Add more objects, max number reached.");
ObjectType* rawPointer = new ObjectType(std::forward<Args>(args)...);
std::unique_ptr<ObjectType>gameObjectPointer(rawPointer);
if (m_firstFreeIndex != s_maxEntries && m_freeIndicesCount > s_minFreeIndices)
{
auto& handleEntry = m_handleEntries[m_firstFreeIndex];
MONA_ASSERT(handleEntry.active == false, "GameObjectManager Error: Incorrect active state for handleEntry");
MONA_ASSERT(handleEntry.generation < std::numeric_limits<decltype(handleEntry.generation)>::max(),
"GameObjectManager Error: Generational Index reached its maximunn value, GameObject cannot be added.");
auto handleIndex = m_firstFreeIndex;
if (m_firstFreeIndex == m_lastFreeIndex)
m_firstFreeIndex = m_lastFreeIndex = s_maxEntries;
else
m_firstFreeIndex = handleEntry.index;
handleEntry.generation += 1;
handleEntry.active = true;
handleEntry.index = static_cast<size_type>(m_gameObjects.size());
handleEntry.prevIndex = s_maxEntries;
--m_freeIndicesCount;
InnerGameObjectHandle resultHandle(handleIndex, handleEntry.generation);
m_gameObjects.emplace_back(std::move(gameObjectPointer));
rawPointer->SetObjectHandle(resultHandle);
rawPointer->StartUp(world);
//m_gameObjectHandleIndices.emplace_back(handleIndex);
return rawPointer;
}
else {
m_handleEntries.emplace_back(static_cast<size_type>(m_gameObjects.size()), s_maxEntries, 0);
InnerGameObjectHandle resultHandle(static_cast<size_type>(m_handleEntries.size() - 1), 0);
m_gameObjects.emplace_back(std::move(gameObjectPointer));
rawPointer->SetObjectHandle(resultHandle);
rawPointer->StartUp(world);
//m_gameObjectHandleIndices.emplace_back(static_cast<size_type>(m_handleEntries.size() - 1));
return rawPointer;
}
}
}
#endif | [
"[email protected]"
] | |
1f04bfcaa7f206554dc75d37c760c088d87f97f4 | 8cc2264268a38cc8ec192a7c61e4b0c64c2492aa | /extern/SX1509.h | a9a8f4e8195460e658359b093955424b2a883ace | [] | no_license | Mechatronikwelt/MixHit-Libraries | ddbfed90bb3abc277b6470ea4bcaa1ed42e2ace8 | 7495e603c34c708a78beaa1ed7eab03051c53783 | refs/heads/master | 2020-04-04T06:44:37.025542 | 2019-01-08T13:43:09 | 2019-01-08T13:43:09 | 155,755,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,498 | h | /******************************************************************************
SparkFunSX1509.h
SparkFun SX1509 I/O Expander Library Header File
Jim Lindblom @ SparkFun Electronics
Original Creation Date: September 21, 2015
https://github.com/sparkfun/SparkFun_SX1509_Arduino_Library
Here you'll find the Arduino code used to interface with the SX1509 I2C
16 I/O expander. There are functions to take advantage of everything the
SX1509 provides - input/output setting, writing pins high/low, reading
the input value of pins, LED driver utilities (blink, breath, pwm), and
keypad engine utilites.
Development environment specifics:
IDE: Arduino 1.6.5
Hardware Platform: Arduino Uno
SX1509 Breakout Version: v2.0
This code is beerware; if you see me (or any other SparkFun employee) at the
local, and you've found our code helpful, please buy us a round!
Distributed as-is; no warranty is given.
******************************************************************************/
#include <stdint.h>
#include "I2C.h"
#ifndef SparkFunSX1509_H
#define SparkFunSX1509_H
#define RECEIVE_TIMEOUT_VALUE 1000 // Timeout for I2C receive
// These are used for setting LED driver to linear or log mode:
#define LINEAR 0
#define LOGARITHMIC 1
// These are used for clock config:
#define INTERNAL_CLOCK_2MHZ 2
#define EXTERNAL_CLOCK 1
#define SOFTWARE_RESET 0
#define HARDWARE_RESET 1
#define SX1509_INPUT 0x01
#define SX1509_OUTPUT 0x02
#define SX1509_ANALOG_OUTPUT 0x3 // To set a pin mode for PWM output
#define SX1509_PULLUP 0x04
#define SX1509_INPUT_PULLUP 0x05
#define SX1509_PULLDOWN 0x08
#define SX1509_INPUT_PULLDOWN 0x09
#define SX1509_OPEN_DRAIN 0x10
#define SX1509_OUTPUT_OPEN_DRAIN 0x12
class SX1509
{
private: // These private functions are not available to Arduino sketches.
// If you need to read or write directly to registers, consider
// putting the writeByte, readByte functions in the public section
I2C * mI2c;
uint8_t mAddress;
// Pin definitions:
uint8_t pinInterrupt;
uint8_t pinOscillator;
uint8_t pinReset;
// Misc variables:
unsigned long _clkX;
// Read Functions:
uint8_t readByte(uint8_t registerAddress);
unsigned int readWord(uint8_t registerAddress);
void readBytes(uint8_t firstRegisterAddress, uint8_t * destination, uint8_t length);
// Write functions:
void writeByte(uint8_t registerAddress, uint8_t writeValue);
void writeWord(uint8_t registerAddress, unsigned int writeValue);
void writeBytes(uint8_t firstRegisterAddress, uint8_t * writeArray, uint8_t length);
// Helper functions:
// calculateLEDTRegister - Try to estimate an LED on/off duration register,
// given the number of milliseconds and LED clock frequency.
uint8_t calculateLEDTRegister(int ms);
// calculateSlopeRegister - Try to estimate an LED rise/fall duration
// register, given the number of milliseconds and LED clock frequency.
uint8_t calculateSlopeRegister(int ms, uint8_t onIntensity, uint8_t offIntensity);
public:
// -----------------------------------------------------------------------------
// Constructor - SX1509: This function sets up the pins connected to the
// SX1509, and sets up the private deviceAddress variable.
// -----------------------------------------------------------------------------
SX1509();
// Legacy below. Use 0-parameter constructor, and set these parameters in the
// begin function:
SX1509(uint8_t address, uint8_t resetPin = 255, uint8_t interruptPin = 255, uint8_t oscillatorPin = 255);
// -----------------------------------------------------------------------------
// begin(uint8_t address, uint8_t resetPin): This function initializes the SX1509.
// It begins the Wire library, resets the IC, and tries to read some
// registers to prove it's connected.
// Inputs:
// - address: should be the 7-bit address of the SX1509. This should be
// one of four values - 0x3E, 0x3F, 0x70, 0x71 - all depending on what the
// ADDR0 and ADDR1 pins ar se to. This variable is required.
// - resetPin: This is the Arduino pin tied to the SX1509 RST pin. This
// pin is optional. If not declared, the library will attempt to
// software reset the SX1509.
// Output: Returns a 1 if communication is successful, 0 on error.
// -----------------------------------------------------------------------------
uint8_t begin(uint8_t address = 0x3E, uint8_t resetPin = 0xFF);
uint8_t init(void); // Legacy -- use begin now
// -----------------------------------------------------------------------------
// reset(bool hardware): This function resets the SX1509 - either a hardware
// reset or software. A hardware reset (hardware parameter = 1) pulls the
// reset line low, pausing, then pulling the reset line high. A software
// reset writes a 0x12 then 0x34 to the REG_RESET as outlined in the
// datasheet.
//
// Input:
// - hardware: 0 executes a software reset, 1 executes a hardware reset
// -----------------------------------------------------------------------------
void reset(bool hardware);
// -----------------------------------------------------------------------------
// pinMode(uint8_t pin, uint8_t inOut): This function sets one of the SX1509's 16
// outputs to either an INPUT or OUTPUT.
//
// Inputs:
// - pin: should be a value between 0 and 15
// - inOut: The Arduino INPUT and OUTPUT constants should be used for the
// inOut parameter. They do what they say!
// -----------------------------------------------------------------------------
void pinMode(uint8_t pin, uint8_t inOut);
void pinDir(uint8_t pin, uint8_t inOut); // Legacy - use pinMode
// -----------------------------------------------------------------------------
// digitalWrite(uint8_t pin, uint8_t highLow): This function writes a pin to either high
// or low if it's configured as an OUTPUT. If the pin is configured as an
// INPUT, this method will activate either the PULL-UP or PULL-DOWN
// resistor (HIGH or LOW respectively).
//
// Inputs:
// - pin: The SX1509 pin number. Should be a value between 0 and 15.
// - highLow: should be Arduino's defined HIGH or LOW constants.
// -----------------------------------------------------------------------------
void digitalWrite(uint8_t pin, uint8_t highLow);
void writePin(uint8_t pin, uint8_t highLow); // Legacy - use digitalWrite
// -----------------------------------------------------------------------------
// digitalRead(uint8_t pin): This function reads the HIGH/LOW status of a pin.
// The pin should be configured as an INPUT, using the pinDir function.
//
// Inputs:
// - pin: The SX1509 pin to be read. should be a value between 0 and 15.
// Outputs:
// This function returns a 1 if HIGH, 0 if LOW
// -----------------------------------------------------------------------------
uint8_t digitalRead(uint8_t pin);
uint8_t readPin(uint8_t pin); // Legacy - use digitalRead
// -----------------------------------------------------------------------------
// ledDriverInit(uint8_t pin, uint8_t freq, bool log): This function initializes LED
// driving on a pin. It must be called if you want to use the pwm or blink
// functions on that pin.
//
// Inputs:
// - pin: The SX1509 pin connected to an LED. Should be 0-15.
// - freq: Sets LED clock frequency divider.
// - log: selects either linear or logarithmic mode on the LED drivers
// - log defaults to 0, linear mode
// - currently log sets both bank A and B to the same mode
// Note: this function automatically decides to use the internal 2MHz osc.
// -----------------------------------------------------------------------------
void ledDriverInit(uint8_t pin, uint8_t freq = 1, bool log = false);
// -----------------------------------------------------------------------------
// analogWrite(uint8_t pin, uint8_t iOn): This function can be used to control the intensity
// of an output pin connected to an LED.
//
// Inputs:
// - pin: The SX1509 pin connecte to an LED.Should be 0-15.
// - iOn: should be a 0-255 value setting the intensity of the LED
// - 0 is completely off, 255 is 100% on.
//
// Note: ledDriverInit should be called on the pin before calling this.
// -----------------------------------------------------------------------------
void analogWrite(uint8_t pin, uint8_t iOn);
void pwm(uint8_t pin, uint8_t iOn); // Legacy - use analogWrite
// -----------------------------------------------------------------------------
// setupBlink(uint8_t pin, uint8_t tOn, uint8_t tOff, uint8_t offIntensity, uint8_t tRise, byte
// tFall): blink performs both the blink and breath LED driver functions.
//
// Inputs:
// - pin: the SX1509 pin (0-15) you want to set blinking/breathing.
// - tOn: the amount of time the pin is HIGH
// - This value should be between 1 and 31. 0 is off.
// - tOff: the amount of time the pin is at offIntensity
// - This value should be between 1 and 31. 0 is off.
// - offIntensity: How dim the LED is during the off period.
// - This value should be between 0 and 7. 0 is completely off.
// - onIntensity: How bright the LED will be when completely on.
// - This value can be between 0 (0%) and 255 (100%).
// - tRise: This sets the time the LED takes to fade in.
// - This value should be between 1 and 31. 0 is off.
// - This value is used with tFall to make the LED breath.
// - tFall: This sets the time the LED takes to fade out.
// - This value should be between 1 and 31. 0 is off.
// Notes:
// - The breathable pins are 4, 5, 6, 7, 12, 13, 14, 15 only. If tRise and
// tFall are set on 0-3 or 8-11 those pins will still only blink.
// - ledDriverInit should be called on the pin to be blinked before this.
// -----------------------------------------------------------------------------
void setupBlink(uint8_t pin, uint8_t tOn, uint8_t toff, uint8_t onIntensity = 255, uint8_t offIntensity = 0, uint8_t tRise = 0, uint8_t tFall = 0, bool log = false);
// -----------------------------------------------------------------------------
// blink(uint8_t pin, unsigned long tOn, unsigned long tOff, uint8_t onIntensity, uint8_t offIntensity);
// Set a pin to blink output for estimated on/off millisecond durations.
//
// Inputs:
// - pin: the SX1509 pin (0-15) you want to set blinking
// - tOn: estimated number of milliseconds the pin is LOW (LED sinking current will be on)
// - tOff: estimated number of milliseconds the pin is HIGH (LED sinking current will be off)
// - onIntensity: 0-255 value determining LED on brightness
// - offIntensity: 0-255 value determining LED off brightness
// Notes:
// - The breathable pins are 4, 5, 6, 7, 12, 13, 14, 15 only. If tRise and
// tFall are set on 0-3 or 8-11 those pins will still only blink.
// - ledDriverInit should be called on the pin to be blinked before this.
// -----------------------------------------------------------------------------
void blink(uint8_t pin, unsigned long tOn, unsigned long tOff, uint8_t onIntensity = 255, uint8_t offIntensity = 0);
// -----------------------------------------------------------------------------
// breathe(uint8_t pin, unsigned long tOn, unsigned long tOff, unsigned long rise, unsigned long fall, uint8_t onInt, uint8_t offInt, bool log);
// Set a pin to breathe output for estimated on/off millisecond durations, with
// estimated rise and fall durations.
//
// Inputs:
// - pin: the SX1509 pin (0-15) you want to set blinking
// - tOn: estimated number of milliseconds the pin is LOW (LED sinking current will be on)
// - tOff: estimated number of milliseconds the pin is HIGH (LED sinking current will be off)
// - rise: estimated number of milliseconds the pin rises from LOW to HIGH
// - falll: estimated number of milliseconds the pin falls from HIGH to LOW
// - onIntensity: 0-255 value determining LED on brightness
// - offIntensity: 0-255 value determining LED off brightness
// Notes:
// - The breathable pins are 4, 5, 6, 7, 12, 13, 14, 15 only. If tRise and
// tFall are set on 0-3 or 8-11 those pins will still only blink.
// - ledDriverInit should be called on the pin to be blinked before this,
// Or call pinMode(<pin>, ANALOG_OUTPUT);
// -----------------------------------------------------------------------------
void breathe(uint8_t pin, unsigned long tOn, unsigned long tOff, unsigned long rise, unsigned long fall, uint8_t onInt = 255, uint8_t offInt = 0, bool log = LINEAR);
// -----------------------------------------------------------------------------
// keypad(uint8_t rows, uint8_t columns, uint8_t sleepTime, uint8_t scanTime, uint8_t debounceTime)
// Initializes the keypad function on the SX1509. Millisecond durations for sleep,
// scan, and debounce can be set.
//
// Inputs:
// - rows: The number of rows in the button matrix.
// - This value must be between 1 and 7. 0 will turn it off.
// - eg: 1 = 2 rows, 2 = 3 rows, 7 = 8 rows, etc.
// - columns: The number of columns in the button matrix
// - This value should be between 0 and 7.
// - 0 = 1 column, 7 = 8 columns, etc.
// - sleepTime: Sets the auto-sleep time of the keypad engine.
// Should be a millisecond duration between 0 (OFF) and 8000 (8 seconds).
// Possible values are 0, 128, 256, 512, 1000, 2000, 4000, 8000
// - scanTime: Sets the scan time per row. Must be set above debounce.
// Should be a millisecond duration between 1 and 128.
// Possible values are 1, 2, 4, 8, 16, 32, 64, 128.
// - debounceTime: Sets the debounc time per button. Must be set below scan.
// Should be a millisecond duration between 0 and 64.
// Possible values are 0 (0.5), 1, 2, 4, 8, 16, 32, 64.
// -----------------------------------------------------------------------------
void keypad(uint8_t rows, uint8_t columns, unsigned int sleepTime = 0, uint8_t scanTime = 1, uint8_t debounceTime = 0);
// -----------------------------------------------------------------------------
// readKeypad(): This function returns a 16-bit value containing the status of
// keypad engine.
//
// Output:
// A 16-bit value is returned. The lower 8 bits represent the up-to 8 rows,
// while the MSB represents the up-to 8 columns. Bit-values of 1 indicate a
// button in that row or column is being pressed. As such, at least two
// bits should be set.
// -----------------------------------------------------------------------------
unsigned int readKeypad();
unsigned int readKeyData(); // Legacy: use readKeypad();
// -----------------------------------------------------------------------------
// getRow(): This function returns the first active row from the return value of
// readKeypad().
//
// Input:
// - keyData: Should be the unsigned int value returned from readKeypad().
// Output:
// A 16-bit value is returned. The lower 8 bits represent the up-to 8 rows,
// while the MSB represents the up-to 8 columns. Bit-values of 1 indicate a
// button in that row or column is being pressed. As such, at least two
// bits should be set.
// -----------------------------------------------------------------------------
uint8_t getRow(unsigned int keyData);
// -----------------------------------------------------------------------------
// getCol(): This function returns the first active column from the return value of
// readKeypad().
//
// Input:
// - keyData: Should be the unsigned int value returned from readKeypad().
// Output:
// A 16-bit value is returned. The lower 8 bits represent the up-to 8 rows,
// while the MSB represents the up-to 8 columns. Bit-values of 1 indicate a
// button in that row or column is being pressed. As such, at least two
// bits should be set.
// -----------------------------------------------------------------------------
uint8_t getCol(unsigned int keyData);
// -----------------------------------------------------------------------------
// sync(void): this function resets the PWM/Blink/Fade counters, syncing any
// blinking LEDs. Bit 2 of REG_MISC is set, which alters the functionality
// of the nReset pin. The nReset pin is toggled low->high, which should
// reset all LED counters. Bit 2 of REG_MISC is again cleared, returning
// nReset pin to POR functionality
// -----------------------------------------------------------------------------
void sync(void);
// -----------------------------------------------------------------------------
// debounceConfig(uint8_t configValue): This method configures the debounce time of
// every input.
//
// Input:
// - configValue: A 3-bit value configuring the debounce time.
// 000: 0.5ms * 2MHz/fOSC
// 001: 1ms * 2MHz/fOSC
// 010: 2ms * 2MHz/fOSC
// 011: 4ms * 2MHz/fOSC
// 100: 8ms * 2MHz/fOSC
// 101: 16ms * 2MHz/fOSC
// 110: 32ms * 2MHz/fOSC
// 111: 64ms * 2MHz/fOSC
//
// Note: fOSC is set with the configClock function. It defaults to 2MHz.
// -----------------------------------------------------------------------------
void debounceConfig(uint8_t configVaule);
// -----------------------------------------------------------------------------
// debounceTime(uint8_t configValue): This method configures the debounce time of
// every input to an estimated millisecond time duration.
//
// Input:
// - time: A millisecond duration estimating the debounce time. Actual
// debounce time will depend on fOSC. Assuming it's 2MHz, debounce will
// be set to the 0.5, 1, 2, 4, 8, 16, 32, or 64 ms (whatever's closest)
//
// Note: fOSC is set with the configClock function. It defaults to 2MHz.
// -----------------------------------------------------------------------------
void debounceTime(uint8_t time);
// -----------------------------------------------------------------------------
// debouncePin(uint8_t pin): This method enables debounce on SX1509 input pin.
//
// Input:
// - pin: The SX1509 pin to be debounced. Should be between 0 and 15.
// -----------------------------------------------------------------------------
void debouncePin(uint8_t pin);
void debounceEnable(uint8_t pin); // Legacy, use debouncePin
// -----------------------------------------------------------------------------
// debounceKeypad(uint8_t pin): This method enables debounce on all pins connected
// to a row/column keypad matrix.
//
// Input:
// - time: Millisecond time estimate for debounce (see debounceTime()).
// - numRows: The number of rows in the keypad matrix.
// - numCols: The number of columns in the keypad matrix.
// -----------------------------------------------------------------------------
void debounceKeypad(uint8_t time, uint8_t numRows, uint8_t numCols);
// -----------------------------------------------------------------------------
// enableInterrupt(uint8_t pin, uint8_t riseFall): This function sets up an interrupt
// on a pin. Interrupts can occur on all SX1509 pins, and can be generated
// on rising, falling, or both.
//
// Inputs:
// -pin: SX1509 input pin that will generate an input. Should be 0-15.
// -riseFall: Configures if you want an interrupt generated on rise fall or
// both. For this param, send the pin-change values previously defined
// by Arduino:
// #define CHANGE 1 <-Both
// #define FALLING 2 <- Falling
// #define RISING 3 <- Rising
//
// Note: This function does not set up a pin as an input, or configure its
// pull-up/down resistors! Do that before (or after).
// -----------------------------------------------------------------------------
void enableInterrupt(uint8_t pin, uint8_t riseFall);
// -----------------------------------------------------------------------------
// interruptSource(void): Returns an unsigned int representing which pin caused
// an interrupt.
//
// Output: 16-bit value, with a single bit set representing the pin(s) that
// generated an interrupt. E.g. a return value of 0x0104 would mean pins 8
// and 3 (bits 8 and 3) have generated an interrupt.
// Input:
// - clear: boolean commanding whether the interrupt should be cleared
// after reading or not.
// -----------------------------------------------------------------------------
unsigned int interruptSource(bool clear = true);
// -----------------------------------------------------------------------------
// checkInterrupt(void): Checks if a single pin generated an interrupt.
//
// Output: Boolean value. True if the requested pin has triggered an interrupt/
// Input:
// - pin: Pin to be checked for generating an input.
// -----------------------------------------------------------------------------
bool checkInterrupt(int pin);
// -----------------------------------------------------------------------------
// configClock(uint8_t oscSource, uint8_t oscPinFunction, uint8_t oscFreqOut, uint8_t oscDivider)
// This function configures the oscillator source/speed
// and the clock, which is used to drive LEDs and time debounces.
//
// Inputs:
// - oscSource: Choose either internal 2MHz oscillator or an external signal
// applied to the OSCIO pin.
// - INTERNAL_CLOCK and EXTERNAL_CLOCK are defined in the header file.
// Use those.
// - This value defaults to internal.
// - oscDivider: Sets the clock divider in REG_MISC.
// - ClkX = fOSC / (2^(RegMisc[6:4] -1))
// - This value defaults to 1.
// - oscPinFunction: Allows you to set OSCIO as an input or output.
// - You can use Arduino's INPUT, OUTPUT defines for this value
// - This value defaults to input
// - oscFreqOut: If oscio is configured as an output, this will set the output
// frequency
// - This should be a 4-bit value. 0=0%, 0xF=100%, else
// fOSCOut = FOSC / (2^(RegClock[3:0]-1))
// - This value defaults to 0.
// -----------------------------------------------------------------------------
void configClock(uint8_t oscSource = 2, uint8_t oscPinFunction = 0, uint8_t oscFreqOut = 0, uint8_t oscDivider = 1); // Legacy, use clock();
// -----------------------------------------------------------------------------
// clock(uint8_t oscSource, uint8_t oscDivider, uint8_t oscPinFunction, uint8_t oscFreqOut)
// This function configures the oscillator source/speed
// and the clock, which is used to drive LEDs and time debounces.
// This is just configClock in a bit more sane order.
//
// -----------------------------------------------------------------------------
void clock(uint8_t oscSource = 2, uint8_t oscDivider = 1, uint8_t oscPinFunction = 0, uint8_t oscFreqOut = 0);
};
// Add backwards compatibility for the old class name: sx1509Class
typedef SX1509 sx1509Class;
#endif // SX1509_library_H
| [
"[email protected]"
] | |
74dd5fe2b6d2fa15ff14bc2e19567bd0540dea5b | a568d13304fad8f44b1a869837b99ca29687b7d8 | /Code_16/Camp_2/Brute_Force_Algo/Spaceship.cpp | aa45db94916c6e6d5a2f0aa479ddb27133cbf51a | [] | no_license | MasterIceZ/Code_CPP | ded570ace902c57e2f5fc84e4b1055d191fc4e3d | bc2561484e58b3a326a5f79282f1e6e359ba63ba | refs/heads/master | 2023-02-20T14:13:47.722180 | 2021-01-21T06:15:03 | 2021-01-21T06:15:03 | 331,527,248 | 0 | 0 | null | 2021-01-21T05:51:49 | 2021-01-21T05:43:59 | null | UTF-8 | C++ | false | false | 1,047 | cpp | /*
TASK:Spaceship
LANG: CPP
AUTHOR: Wichada
SCHOOL: RYW
*/
#include<bits/stdc++.h>
using namespace std;
struct A{
int x,y,z,a,b,c;
};
A s[15];
int mark[15];
int want,sn,mi=2e9,aa,bb,cc,nd;
void play(int x,int y,int z,int a,int b,int c,int dis){
if(a>=want && b>=want && c>=want){
mi=min(dis,mi);
return ;
}
for(int i=1;i<=sn;i++){
if(mark[i])continue;
mark[i]=1;
aa=a+s[i].a;
bb=b+s[i].b;
cc=c+s[i].c;
nd=dis+(s[i].x-x)*(s[i].x-x)+(s[i].y-y)*(s[i].y-y)+(s[i].z-z)*(s[i].z-z);
if(a>=want && b>=want && c>=want){
mi=min(nd,mi);
continue;
}
play(s[i].x,s[i].y,s[i].z,aa,bb,cc,nd);
mark[i]=0;
}
return ;
}
int main()
{
int x,y,z;
scanf("%d",&want);
scanf("%d %d %d",&x,&y,&z);
scanf("%d",&sn);
for(int i=1;i<=sn;i++){
scanf("%d %d %d %d %d %d",&s[i].x,&s[i].y,&s[i].z,&s[i].a,&s[i].b,&s[i].c);
}
play(x,y,z,0,0,0,0);
printf("%d\n",mi);
return 0;
} | [
"[email protected]"
] | |
3ef40fc09dc21850b48ee0ad560e944deea9d70a | cb92ee9be36a6f44d33a6ec8798f5183c6adbb1f | /Builder/Include/WorldController.h | 5e52e37eac07c3b079a60b7c454dd9eda783ccce | [
"MIT"
] | permissive | Nanoteck137/Seek | e95026afcea3e685527495ad84f016be3020e398 | eaa8af3f1ba4830734415fd310a6649feb9f1664 | refs/heads/master | 2022-10-29T18:49:12.186034 | 2020-06-09T20:49:45 | 2020-06-09T20:49:45 | 231,681,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | h | #pragma once
#include <Seek.h>
#include "Model/World.h"
class WorldController
{
public:
WorldController();
~WorldController();
void Update(Seek::Timestep ts);
inline World& GetWorld() const { return *m_World; }
private:
World* m_World;
}; | [
"[email protected]"
] | |
3417912d0486303957dda8a1542302276b5a64bc | d620d7c4f3632f796c15d476cc04cba75301cc98 | /Engine2/Math/Random.h | 9debec6fe822475ee74eb3f96945323b2dd8c127 | [] | no_license | Bagg-png/CSC196 | aeeb0dd06fb21b6728b715fcaf9d2bce30eac2aa | 6fb8d9ba6d64acacc7e6dace814ab47865efbf62 | refs/heads/master | 2023-07-02T22:51:34.125300 | 2021-07-30T01:36:54 | 2021-07-30T01:36:54 | 381,502,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | h | #pragma once
namespace nc {
void SeedRandom(unsigned int seed);
float Random(); // 0 - 1
float RandomRange(float min, float max);
int RandomInt();
int RandomRangeInt(int min, int max);
}
| [
"[email protected]"
] | |
3b4f61c82fa9d4e3af1583f2474eebb6d7b33d25 | 0bd54aa4272c97fccc6f63f412b55e4ea242d53a | /S3/HMIN323 - Informatique graphique/TDs-TPs/test2/lib/magic_get-develop/test/common/read_write.cpp | f00f49f9793cab66b279ba20a99675eec534afdb | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | su6i/master-imagina | 099c12e12b912e3f8c1d9295e062e1f65b8ddfbd | 2257329464a8e3bc6c94aac983aa23f77c4a63e4 | refs/heads/master | 2022-12-27T07:03:12.856509 | 2020-08-26T12:39:57 | 2020-08-26T12:39:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,600 | cpp | // Copyright (c) 2016-2019 Antony Polukhin
//
// 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 <boost/core/lightweight_test.hpp>
#include <sstream>
#include <string>
#ifdef BOOST_PFR_TEST_FLAT
#include <boost/pfr/flat/io.hpp>
namespace boost { namespace test {
template <class Char, class Traits, class T>
void read(std::basic_istream<Char, Traits>& in, T& value) {
::boost::pfr::flat_read(in, value);
}
template <class Char, class Traits, class T>
void write(std::basic_ostream<Char, Traits>& out, const T& value) {
::boost::pfr::flat_write(out, value);
}
}}
#endif
#ifdef BOOST_PFR_TEST_PRECISE
#include <boost/pfr/precise/io.hpp>
namespace boost { namespace test {
using boost::pfr::read;
using boost::pfr::write;
}}
#endif
template <class T>
void test_write_read(const T& value) {
T result;
std::stringstream ss;
boost::test::write(ss, value);
boost::test::read(ss, result);
BOOST_TEST_EQ(value.f0, result.f0);
BOOST_TEST_EQ(value.f1, result.f1);
BOOST_TEST_EQ(value.f2, result.f2);
BOOST_TEST_EQ(value.f3, result.f3);
BOOST_TEST_EQ(value.f4, result.f4);
}
template <class T>
void to_string_test(const T& value, const char* ethalon) {
std::stringstream ss;
boost::test::write(ss, value);
BOOST_TEST_EQ(ss.str(), ethalon);
}
template <class T>
void test_type(const T& value, const char* ethalon) {
test_write_read(value);
to_string_test(value, ethalon);
}
struct with_operator{};
inline bool operator==(with_operator, with_operator) {
return true;
}
std::ostream& operator<<(std::ostream& os, with_operator) {
return os << "{with_operator}";
}
std::istream& operator>>(std::istream& is, with_operator&) {
std::string s;
is >> s;
return is;
}
int main() {
struct test1 {
int f0;
int f1;
char f2;
int f3;
short f4;
};
test_type(test1{1, 2, '3', 4, 5}, "{1, 2, 3, 4, 5}");
test_type(test1{199, 299, '9', 499, 599}, "{199, 299, 9, 499, 599}");
#ifdef BOOST_PFR_TEST_PRECISE
struct test2 {
with_operator f0;
with_operator f1;
with_operator f2;
with_operator f3;
with_operator f4;
};
test_type(test2{}, "{{with_operator}, {with_operator}, {with_operator}, {with_operator}, {with_operator}}");
struct test3 {
int f0;
int f1;
char f2;
int f3;
with_operator f4;
};
test_type(
test3{1, 2, '3', 4, {}},
"{1, 2, 3, 4, {with_operator}}"
);
#if (BOOST_PFR_USE_CPP17 || BOOST_PFR_USE_LOOPHOLE) \
&& !defined(_MSC_VER) /* TODO: remove after fixing strange errors https://ci.appveyor.com/project/apolukhin/magic-get/build/1.65.108-develop */
struct test4 {
int f0;
std::string f1;
char f2;
int f3;
std::string f4;
};
test_type(
test4{1, {"my o my"}, '3', 4, {"hello there!"} },
"{1, \"my o my\", 3, 4, \"hello there!\"}"
);
#if 0
// TODO:
std::string f1_referenced{"my O my"};
std::string f4_referenced{"Hello There!"};
struct test5 {
int f0;
const std::string& f1;
char f2;
int f3;
const std::string& f4;
};
to_string_test(
test5{1, f1_referenced, '3', 4, f4_referenced },
"{1, \"my o my\", 3, 4, \"hello there!\"}"
);
#endif
#endif
#endif // BOOST_PFR_TEST_PRECISE
return boost::report_errors();
}
| [
"[email protected]"
] | |
b8ab8783b255509f5e75df2e9f85b14734b70757 | 6e665dcd74541d40647ebb64e30aa60bc71e610c | /800/VPBX/plugins/isdn/msg/IEs/notOffered/IeComplete.hxx | 91af071e9d23614a6b08876352f3c578300f7edf | [] | no_license | jacklee032016/pbx | b27871251a6d49285eaade2d0a9ec02032c3ec62 | 554149c134e50db8ea27de6a092934a51e156eb6 | refs/heads/master | 2020-03-24T21:52:18.653518 | 2018-08-04T20:01:15 | 2018-08-04T20:01:15 | 143,054,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,017 | hxx | #ifndef __IE_COMPLATE_HXX__
#define __IE_COMPLATE_HXX__
/*
* $Id: IeComplete.hxx,v 1.1.1.1 2006/11/30 16:26:29 lizhijie Exp $
*/
#include "global.h"
#include "Data.hxx"
#include "IsdnIE.hxx"
#include "VException.hxx"
namespace Assist
{
/* just a type for this IE, so no data is keep in this Class
* defined but not offered in INS
*/
class IeComplete : public IsdnIE
{
public:
IeComplete(const char *p) throw(IsdnIeParserException &) ;
IeComplete( int _complete =0 );
IeComplete( const IeComplete& src);
~IeComplete();
IeComplete& operator=(const IeComplete& rhs);
bool operator ==( IeComplete& src) const;
IsdnIE* duplicate() const;
virtual bool compareIsdnIE(IsdnIE* msg) const;
char *encode( msg_t *msg);
int decode(const char *p);
virtual int getIeType() const
{
return ISDN_IE_COMPLETE;
};
int getComplete();
void setComplete(int _complete);
#if WITH_DEBUG
virtual const char *debugInfo();
#endif
protected:
private:
int complete;
};
}
#endif
| [
"[email protected]"
] | |
c3a75698cdc78ce7643ae598f51c253673edbd62 | ebc0847a666d690e0271a2a190fa40b6888cf275 | /ResExplorer/ResExplorer/MsgDecode.cpp | f83c02178dd54c14b034f9dc7567994614651cc9 | [] | no_license | hackerlank/cosps | 59ba7eefde9bf11e29515529839a17be3a9ff7f4 | 23c008c08a7efb846d098a3db738e22a7c3eb365 | refs/heads/master | 2020-06-12T18:27:21.633457 | 2015-01-01T12:42:26 | 2015-01-01T12:42:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,182 | cpp |
#include "stdafx.h"
#include <AFXPRIV.H>
#include "MsgDecode.h"
#ifdef _DEBUG // entire file for debugging
// Module de test et de debug
// Decode les messages et les resources pour la TRACE par exemple
#ifndef WM_SYSTIMER
#define WM_SYSTIMER 0x0118 // (caret blink)
#endif
// report very frequently sent messages
static UINT veryFreq[] = {
// Add in this table a message to skip
WM_MOUSEMOVE,
WM_NCMOUSEMOVE,
WM_NCHITTEST,
WM_SETCURSOR,
WM_CTLCOLORBTN,
WM_CTLCOLORDLG,
WM_CTLCOLOREDIT,
WM_CTLCOLORLISTBOX,
WM_CTLCOLORMSGBOX,
WM_CTLCOLORSCROLLBAR,
WM_CTLCOLORSTATIC,
WM_ENTERIDLE,
WM_CANCELMODE,
// WM_TIMER,
WM_SYSTIMER, // 0x0118 (caret blink)
0 };
BOOL IsVeryFrequentlySent(UINT msg)
{
UINT *pMsg = veryFreq, m;
while (m = *pMsg++) if (m == msg) return TRUE;
return FALSE;
}
// Messages decode table
typedef struct { UINT id; LPCTSTR text; } t_MESS;
#define TEXID(id) { id, #id }
static t_MESS messages[] = {
TEXID(WM_CREATE), // 0x0001
TEXID(WM_DESTROY), // 0x0002
TEXID(WM_MOVE), // 0x0003
TEXID(0x0004),
TEXID(WM_SIZE), // 0x0005
TEXID(WM_ACTIVATE), // 0x0006
TEXID(WM_SETFOCUS), // 0x0007
TEXID(WM_KILLFOCUS), // 0x0008
TEXID(0x0009),
TEXID(WM_ENABLE), // 0x000A
TEXID(WM_SETREDRAW), // 0x000B
TEXID(WM_SETTEXT), // 0x000C
TEXID(WM_GETTEXT), // 0x000D
TEXID(WM_GETTEXTLENGTH), // 0x000E
TEXID(WM_PAINT), // 0x000F
TEXID(WM_CLOSE), // 0x0010
TEXID(WM_QUERYENDSESSION), // 0x0011
TEXID(WM_QUIT), // 0x0012
TEXID(WM_QUERYOPEN), // 0x0013
TEXID(WM_ERASEBKGND), // 0x0014
TEXID(WM_SYSCOLORCHANGE), // 0x0015
TEXID(WM_ENDSESSION), // 0x0016
TEXID(0x0017),
TEXID(WM_SHOWWINDOW), // 0x0018
TEXID(0x0019),
TEXID(WM_WININICHANGE), // 0x001A
TEXID(WM_DEVMODECHANGE), // 0x001B
TEXID(WM_ACTIVATEAPP), // 0x001C
TEXID(WM_FONTCHANGE), // 0x001D
TEXID(WM_TIMECHANGE), // 0x001E
TEXID(WM_CANCELMODE), // 0x001F
TEXID(WM_SETCURSOR), // 0x0020
TEXID(WM_MOUSEACTIVATE), // 0x0021
TEXID(WM_CHILDACTIVATE), // 0x0022
TEXID(WM_QUEUESYNC), // 0x0023
TEXID(WM_GETMINMAXINFO), // 0x0024
TEXID(0x0025),
TEXID(WM_PAINTICON), // 0x0026
TEXID(WM_ICONERASEBKGND), // 0x0027
TEXID(WM_NEXTDLGCTL), // 0x0028
TEXID(0x0029),
TEXID(WM_SPOOLERSTATUS), // 0x002A
TEXID(WM_DRAWITEM), // 0x002B
TEXID(WM_MEASUREITEM), // 0x002C
TEXID(WM_DELETEITEM), // 0x002D
TEXID(WM_VKEYTOITEM), // 0x002E
TEXID(WM_CHARTOITEM), // 0x002F
TEXID(WM_SETFONT), // 0x0030
TEXID(WM_GETFONT), // 0x0031
TEXID(WM_SETHOTKEY), // 0x0032
TEXID(WM_GETHOTKEY), // 0x0033
TEXID(0x0034),
TEXID(0x0035),
TEXID(0x0036),
TEXID(WM_QUERYDRAGICON), // 0x0037
TEXID(0x0038),
TEXID(WM_COMPAREITEM), // 0x0039
TEXID(0x003A),
TEXID(0x003B),
TEXID(0x003C),
#ifndef WM_GETOBJECT // WINVER >= 0x0500
#define WM_GETOBJECT 0x003D
#endif
TEXID(WM_GETOBJECT), // 0x003D
TEXID(0x003E),
TEXID(0x003F),
TEXID(0x0040),
TEXID(WM_COMPACTING), // 0x0041
TEXID(0x0042),
TEXID(0x0043),
TEXID(WM_COMMNOTIFY), // 0x0044 /* no longer suported */
TEXID(0x0045),
TEXID(WM_WINDOWPOSCHANGING), // 0x0046
TEXID(WM_WINDOWPOSCHANGED), // 0x0047
TEXID(WM_POWER), // 0x0048
TEXID(WM_COPYDATA),
TEXID(WM_CANCELJOURNAL),
#if(WINVER >= 0x0400)
TEXID(WM_NOTIFY),
TEXID(WM_INPUTLANGCHANGEREQUEST),
TEXID(WM_INPUTLANGCHANGE),
TEXID(WM_TCARD),
TEXID(WM_HELP),
TEXID(WM_USERCHANGED),
TEXID(WM_NOTIFYFORMAT),
TEXID(WM_CONTEXTMENU),
TEXID(WM_STYLECHANGING),
TEXID(WM_STYLECHANGED),
TEXID(WM_DISPLAYCHANGE),
TEXID(WM_GETICON),
TEXID(WM_SETICON),
#endif /* WINVER >= 0x0400 */
TEXID(WM_NCCREATE),
TEXID(WM_NCDESTROY),
TEXID(WM_NCCALCSIZE),
TEXID(WM_NCHITTEST),
TEXID(WM_NCPAINT),
TEXID(WM_NCACTIVATE),
TEXID(WM_GETDLGCODE),
TEXID(WM_SYNCPAINT),
TEXID(WM_NCMOUSEMOVE),
TEXID(WM_NCLBUTTONDOWN),
TEXID(WM_NCLBUTTONUP),
TEXID(WM_NCLBUTTONDBLCLK),
TEXID(WM_NCRBUTTONDOWN),
TEXID(WM_NCRBUTTONUP),
TEXID(WM_NCRBUTTONDBLCLK),
TEXID(WM_NCMBUTTONDOWN),
TEXID(WM_NCMBUTTONUP),
TEXID(WM_NCMBUTTONDBLCLK), // 0x00A9
TEXID(SBM_SETPOS), // 0x00E0 /*not in win3.1 */
TEXID(SBM_GETPOS), // 0x00E1 /*not in win3.1 */
TEXID(SBM_SETRANGE), // 0x00E2 /*not in win3.1 */
TEXID(SBM_SETRANGEREDRAW), // 0x00E6 /*not in win3.1 */
TEXID(SBM_GETRANGE), // 0x00E3 /*not in win3.1 */
TEXID(SBM_ENABLE_ARROWS), // 0x00E4 /*not in win3.1 */
#if(WINVER >= 0x0400)
TEXID(SBM_SETSCROLLINFO), // 0x00E9
TEXID(SBM_GETSCROLLINFO), // 0x00EA
#endif
/*
* Button Control Messages
*/
TEXID(BM_GETCHECK), // 0x00F0
TEXID(BM_SETCHECK), // 0x00F1
TEXID(BM_GETSTATE), // 0x00F2
TEXID(BM_SETSTATE), // 0x00F3
TEXID(BM_SETSTYLE), // 0x00F4
TEXID(BM_CLICK), // 0x00F5
TEXID(BM_GETIMAGE), // 0x00F6
TEXID(BM_SETIMAGE), // 0x00F7
TEXID(WM_KEYFIRST), // 0x0100
TEXID(WM_KEYDOWN),
TEXID(WM_KEYUP),
TEXID(WM_CHAR),
TEXID(WM_DEADCHAR),
TEXID(WM_SYSKEYDOWN),
TEXID(WM_SYSKEYUP),
TEXID(WM_SYSCHAR),
TEXID(WM_SYSDEADCHAR),
TEXID(WM_KEYLAST), // 0x0108
#if(WINVER >= 0x0400)
TEXID(WM_IME_STARTCOMPOSITION),
TEXID(WM_IME_ENDCOMPOSITION),
TEXID(WM_IME_COMPOSITION),
TEXID(WM_IME_KEYLAST),
#endif /* WINVER >= 0x0400 */
TEXID(WM_INITDIALOG), // 0x0110
TEXID(WM_COMMAND), // 0x0111
TEXID(WM_SYSCOMMAND), // 0x0112
TEXID(WM_TIMER), // 0x0113
TEXID(WM_HSCROLL), // 0x0114
TEXID(WM_VSCROLL), // 0x0115
TEXID(WM_INITMENU), // 0x0116
TEXID(WM_INITMENUPOPUP), // 0x0117
TEXID(WM_SYSTIMER), // 0x0118 (caret blink)
TEXID(WM_MENUSELECT), // 0x011F
TEXID(WM_MENUCHAR), // 0x0120
TEXID(WM_ENTERIDLE), // 0x0121
#if(WINVER >= 0x0500)
TEXID(WM_MENURBUTTONUP),
TEXID(WM_MENUDRAG),
TEXID(WM_MENUGETOBJECT),
TEXID(WM_UNINITMENUPOPUP),
TEXID(WM_MENUCOMMAND),
#endif /* WINVER >= 0x0500 */
TEXID(WM_CTLCOLORMSGBOX), // 0x0132
TEXID(WM_CTLCOLOREDIT),
TEXID(WM_CTLCOLORLISTBOX),
TEXID(WM_CTLCOLORBTN),
TEXID(WM_CTLCOLORDLG),
TEXID(WM_CTLCOLORSCROLLBAR),
TEXID(WM_CTLCOLORSTATIC), // 0x0138
/*
* Combo Box messages
*/
TEXID(CB_GETEDITSEL), // 0x0140
TEXID(CB_LIMITTEXT), // 0x0141
TEXID(CB_SETEDITSEL), // 0x0142
TEXID(CB_ADDSTRING), // 0x0143
TEXID(CB_DELETESTRING), // 0x0144
TEXID(CB_DIR), // 0x0145
TEXID(CB_GETCOUNT), // 0x0146
TEXID(CB_GETCURSEL), // 0x0147
TEXID(CB_GETLBTEXT), // 0x0148
TEXID(CB_GETLBTEXTLEN), // 0x0149
TEXID(CB_INSERTSTRING), // 0x014A
TEXID(CB_RESETCONTENT), // 0x014B
TEXID(CB_FINDSTRING), // 0x014C
TEXID(CB_SELECTSTRING), // 0x014D
TEXID(CB_SETCURSEL), // 0x014E
TEXID(CB_SHOWDROPDOWN), // 0x014F
TEXID(CB_GETITEMDATA), // 0x0150
TEXID(CB_SETITEMDATA), // 0x0151
TEXID(CB_GETDROPPEDCONTROLRECT), // 0x0152
TEXID(CB_SETITEMHEIGHT), // 0x0153
TEXID(CB_GETITEMHEIGHT), // 0x0154
TEXID(CB_SETEXTENDEDUI), // 0x0155
TEXID(CB_GETEXTENDEDUI), // 0x0156
TEXID(CB_GETDROPPEDSTATE), // 0x0157
TEXID(CB_FINDSTRINGEXACT), // 0x0158
TEXID(CB_SETLOCALE), // 0x0159
TEXID(CB_GETLOCALE), // 0x015A
#if(WINVER >= 0x0400)
TEXID(CB_GETTOPINDEX), // 0x015b
TEXID(CB_SETTOPINDEX), // 0x015c
TEXID(CB_GETHORIZONTALEXTENT), // 0x015d
TEXID(CB_SETHORIZONTALEXTENT), // 0x015e
TEXID(CB_GETDROPPEDWIDTH), // 0x015f
TEXID(CB_SETDROPPEDWIDTH), // 0x0160
TEXID(CB_INITSTORAGE), // 0x0161
#endif /* WINVER >= 0x0400 */
#if(WINVER >= 0x0400)
TEXID(CB_MSGMAX), // 0x0162
#else
TEXID(CB_MSGMAX), // 0x015B
#endif
/*
* Listbox messages
*/
TEXID(LB_ADDSTRING), // 0x0180
TEXID(LB_INSERTSTRING), // 0x0181
TEXID(LB_DELETESTRING), // 0x0182
TEXID(LB_SELITEMRANGEEX), // 0x0183
TEXID(LB_RESETCONTENT), // 0x0184
TEXID(LB_SETSEL), // 0x0185
TEXID(LB_SETCURSEL), // 0x0186
TEXID(LB_GETSEL), // 0x0187
TEXID(LB_GETCURSEL), // 0x0188
TEXID(LB_GETTEXT), // 0x0189
TEXID(LB_GETTEXTLEN), // 0x018A
TEXID(LB_GETCOUNT), // 0x018B
TEXID(LB_SELECTSTRING), // 0x018C
TEXID(LB_DIR), // 0x018D
TEXID(LB_GETTOPINDEX), // 0x018E
TEXID(LB_FINDSTRING), // 0x018F
TEXID(LB_GETSELCOUNT), // 0x0190
TEXID(LB_GETSELITEMS), // 0x0191
TEXID(LB_SETTABSTOPS), // 0x0192
TEXID(LB_GETHORIZONTALEXTENT), // 0x0193
TEXID(LB_SETHORIZONTALEXTENT), // 0x0194
TEXID(LB_SETCOLUMNWIDTH), // 0x0195
TEXID(LB_ADDFILE), // 0x0196
TEXID(LB_SETTOPINDEX), // 0x0197
TEXID(LB_GETITEMRECT), // 0x0198
TEXID(LB_GETITEMDATA), // 0x0199
TEXID(LB_SETITEMDATA), // 0x019A
TEXID(LB_SELITEMRANGE), // 0x019B
TEXID(LB_SETANCHORINDEX), // 0x019C
TEXID(LB_GETANCHORINDEX), // 0x019D
TEXID(LB_SETCARETINDEX), // 0x019E
TEXID(LB_GETCARETINDEX), // 0x019F
TEXID(LB_SETITEMHEIGHT), // 0x01A0
TEXID(LB_GETITEMHEIGHT), // 0x01A1
TEXID(LB_FINDSTRINGEXACT), // 0x01A2
TEXID(LB_SETLOCALE), // 0x01A5
TEXID(LB_GETLOCALE), // 0x01A6
TEXID(LB_SETCOUNT), // 0x01A7
#if(WINVER >= 0x0400)
TEXID(LB_INITSTORAGE), // 0x01A8
TEXID(LB_ITEMFROMPOINT), // 0x01A9
#endif /* WINVER >= 0x0400 */
#if(WINVER >= 0x0400)
TEXID(LB_MSGMAX), // 0x01B0
#else
TEXID(LB_MSGMAX), // 0x01A8
#endif
TEXID(WM_MOUSEFIRST), // 0x0200
TEXID(WM_MOUSEMOVE),
TEXID(WM_LBUTTONDOWN),
TEXID(WM_LBUTTONUP),
TEXID(WM_LBUTTONDBLCLK),
TEXID(WM_RBUTTONDOWN),
TEXID(WM_RBUTTONUP),
TEXID(WM_RBUTTONDBLCLK),
TEXID(WM_MBUTTONDOWN),
TEXID(WM_MBUTTONUP),
TEXID(WM_MBUTTONDBLCLK),
#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)
TEXID(WM_MOUSEWHEEL), // 0x020A
TEXID(WM_MOUSELAST),
#else
TEXID(WM_MOUSELAST),
#endif /* if (_WIN32_WINNT < 0x0400) */
TEXID(WM_PARENTNOTIFY),
TEXID(WM_ENTERMENULOOP),
TEXID(WM_EXITMENULOOP),
#if(WINVER >= 0x0400)
TEXID(WM_NEXTMENU),
TEXID(WM_SIZING),
TEXID(WM_CAPTURECHANGED),
TEXID(WM_MOVING),
// end_r_winuser
TEXID(WM_POWERBROADCAST), // r_winuser pbt
// begin_r_winuser
TEXID(WM_DEVICECHANGE),
#endif /* WINVER >= 0x0400 */
TEXID(WM_MDICREATE),
TEXID(WM_MDIDESTROY),
TEXID(WM_MDIACTIVATE),
TEXID(WM_MDIRESTORE),
TEXID(WM_MDINEXT),
TEXID(WM_MDIMAXIMIZE),
TEXID(WM_MDITILE),
TEXID(WM_MDICASCADE),
TEXID(WM_MDIICONARRANGE),
TEXID(WM_MDIGETACTIVE),
TEXID(WM_MDISETMENU),
TEXID(WM_ENTERSIZEMOVE),
TEXID(WM_EXITSIZEMOVE),
TEXID(WM_DROPFILES),
TEXID(WM_MDIREFRESHMENU),
#if(WINVER >= 0x0400)
TEXID(WM_IME_SETCONTEXT),
TEXID(WM_IME_NOTIFY),
TEXID(WM_IME_CONTROL),
TEXID(WM_IME_COMPOSITIONFULL),
TEXID(WM_IME_SELECT),
TEXID(WM_IME_CHAR),
#endif /* WINVER >= 0x0400 */
#if(WINVER >= 0x0500)
TEXID(WM_IME_REQUEST),
#endif /* WINVER >= 0x0500 */
#if(WINVER >= 0x0400)
TEXID(WM_IME_KEYDOWN),
TEXID(WM_IME_KEYUP),
#endif /* WINVER >= 0x0400 */
#if(_WIN32_WINNT >= 0x0400)
TEXID(WM_MOUSEHOVER),
TEXID(WM_MOUSELEAVE),
#endif /* _WIN32_WINNT >= 0x0400 */
TEXID(WM_CUT),// 0x0300
TEXID(WM_COPY),// 0x0301
TEXID(WM_PASTE),// 0x0302
TEXID(WM_CLEAR),// 0x0303
TEXID(WM_UNDO),// 0x0304
TEXID(WM_RENDERFORMAT),// 0x0305
TEXID(WM_RENDERALLFORMATS),// 0x0306
TEXID(WM_DESTROYCLIPBOARD),// 0x0307
TEXID(WM_DRAWCLIPBOARD),// 0x0308
TEXID(WM_PAINTCLIPBOARD),// 0x0309
TEXID(WM_VSCROLLCLIPBOARD),// 0x030A
TEXID(WM_SIZECLIPBOARD),// 0x030B
TEXID(WM_ASKCBFORMATNAME),// 0x030C
TEXID(WM_CHANGECBCHAIN),// 0x030D
TEXID(WM_HSCROLLCLIPBOARD),// 0x030E
TEXID(WM_QUERYNEWPALETTE),// 0x030F
TEXID(WM_PALETTEISCHANGING),// 0x0310
TEXID(WM_PALETTECHANGED),// 0x0311
TEXID(WM_HOTKEY),// 0x0312
#if(WINVER >= 0x0400)
TEXID(WM_PRINT),// 0x0317
TEXID(WM_PRINTCLIENT),// 0x0318
TEXID(WM_HANDHELDFIRST),// 0x0358
TEXID(WM_HANDHELDLAST),// 0x035F
TEXID(WM_AFXFIRST),// 0x0360
TEXID(WM_QUERYAFXWNDPROC),// 0x0360 // lResult = 1 if processed by AfxWndProc
TEXID(WM_SIZEPARENT),// 0x0361 // lParam = &AFX_SIZEPARENTPARAMS
TEXID(WM_SETMESSAGESTRING),// 0x0362 // wParam = nIDS (or 0),
// lParam = lpszOther (or NULL)
TEXID(WM_IDLEUPDATECMDUI),// 0x0363 // wParam == bDisableIfNoHandler
TEXID(WM_INITIALUPDATE),// 0x0364 // (params unused) - sent to children
TEXID(WM_COMMANDHELP),// 0x0365 // lResult = TRUE/FALSE,
// lParam = dwContext
TEXID(WM_HELPHITTEST),// 0x0366 // lResult = dwContext,
// lParam = MAKELONG(x,y)
TEXID(WM_EXITHELPMODE),// 0x0367 // (params unused)
TEXID(WM_RECALCPARENT),// 0x0368 // force RecalcLayout on frame window
// (only for inplace frame windows)
TEXID(WM_SIZECHILD),// 0x0369 // special notify from COleResizeBar
// wParam = ID of child window
// lParam = lpRectNew (new position/size)
TEXID(WM_KICKIDLE),// 0x036A // (params unused) causes idles to kick in
TEXID(WM_QUERYCENTERWND),// 0x036B // lParam = HWND to use as centering parent
TEXID(WM_DISABLEMODAL),// 0x036C // lResult = 0, disable during modal state
// lResult = 1, don't disable
TEXID(WM_FLOATSTATUS),// 0x036D // wParam combination of FS_* flags below
// WM_ACTIVATETOPLEVEL is like WM_ACTIVATEAPP but works with hierarchies
// of mixed processes (as is the case with OLE in-place activation)
TEXID(WM_ACTIVATETOPLEVEL),// 0x036E // wParam = nState (like WM_ACTIVATE)
// lParam = pointer to HWND[2]
// lParam[0] = hWnd getting WM_ACTIVATE
// lParam[1] = hWndOther
// TEXID(WM_QUERY3DCONTROLS),// 0x036F // lResult != 0 if 3D controls wanted
// Note: Messages 0x0370, 0x0371, and 0x372 were incorrectly used by
// some versions of Windows. To remain compatible, MFC does not
// use messages in that range.
TEXID(WM_RESERVED_0370),// 0x0370
TEXID(WM_RESERVED_0371),// 0x0371
TEXID(WM_RESERVED_0372),// 0x0372
// WM_SOCKET_NOTIFY and WM_SOCKET_DEAD are used internally by MFC's
// Windows sockets implementation. For more information, see sockcore.cpp
TEXID(WM_SOCKET_NOTIFY),// 0x0373
TEXID(WM_SOCKET_DEAD),// 0x0374
// same as WM_SETMESSAGESTRING except not popped if IsTracking()
TEXID(WM_POPMESSAGESTRING),// 0x0375
// WM_HELPPROMPTADDR is used internally to get the address of
// m_dwPromptContext from the associated frame window. This is used
// during message boxes to setup for F1 help while that msg box is
// displayed. lResult is the address of m_dwPromptContext.
TEXID(WM_HELPPROMPTADDR),// 0x0376
// Constants used in DLGINIT resources for OLE control containers
// NOTE: These are NOT real Windows messages they are simply tags
// used in the control resource and are never used as 'messages'
TEXID(WM_OCC_LOADFROMSTREAM),// 0x0376
TEXID(WM_OCC_LOADFROMSTORAGE),// 0x0377
TEXID(WM_OCC_INITNEW),// 0x0378
TEXID(WM_OCC_LOADFROMSTREAM_EX),// 0x037A
TEXID(WM_OCC_LOADFROMSTORAGE_EX),// 0x037B
// Marker used while rearranging the message queue
TEXID(WM_QUEUE_SENTINEL),// 0x0379
// Note: Messages 0x037C - 0x37E reserved for future MFC use.
TEXID(WM_RESERVED_037C),// 0x037C
TEXID(WM_RESERVED_037D),// 0x037D
TEXID(WM_RESERVED_037E),// 0x037E
// WM_FORWARDMSG - used by ATL to forward a message to another window for processing
// WPARAM - DWORD dwUserData - defined by user
// LPARAM - LPMSG pMsg - a pointer to the MSG structure
// return value - 0 if the message was not processed, nonzero if it was
TEXID(WM_FORWARDMSG),// 0x037F
TEXID(WM_AFXLAST),// 0x037F
#endif /* WINVER >= 0x0400 */
TEXID(WM_PENWINFIRST),// 0x0380
TEXID(WM_PENWINLAST),// 0x038F
#if(WINVER >= 0x0400)
TEXID(WM_APP),// 0x8000
#endif /* WINVER >= 0x0400 */
/*
* NOTE: All Message Numbers below 0x0400 are RESERVED.
*
* Private Window Messages Start Here:
*/
TEXID(WM_USER),// 0x0400
TEXID(TTM_ACTIVATE),// (WM_USER + 1)
TEXID(TTM_SETDELAYTIME),// (WM_USER + 3)
TEXID(TTM_ADDTOOLA),// (WM_USER + 4)
TEXID(TTM_ADDTOOLW),// (WM_USER + 50)
TEXID(TTM_DELTOOLA),// (WM_USER + 5)
TEXID(TTM_DELTOOLW),// (WM_USER + 51)
TEXID(TTM_NEWTOOLRECTA),// (WM_USER + 6)
TEXID(TTM_NEWTOOLRECTW),// (WM_USER + 52)
TEXID(TTM_RELAYEVENT),// (WM_USER + 7)
TEXID(TTM_GETTOOLINFOA),// (WM_USER + 8)
TEXID(TTM_GETTOOLINFOW),// (WM_USER + 53)
TEXID(TTM_SETTOOLINFOA),// (WM_USER + 9)
TEXID(TTM_SETTOOLINFOW),// (WM_USER + 54)
TEXID(TTM_HITTESTA),// (WM_USER + 10)
TEXID(TTM_HITTESTW),// (WM_USER + 55)
TEXID(TTM_GETTEXTA),// (WM_USER + 11)
TEXID(TTM_GETTEXTW),// (WM_USER + 56)
TEXID(TTM_UPDATETIPTEXTA),// (WM_USER + 12)
TEXID(TTM_UPDATETIPTEXTW),// (WM_USER + 57)
TEXID(TTM_GETTOOLCOUNT),// (WM_USER + 13)
TEXID(TTM_ENUMTOOLSA),// (WM_USER + 14)
TEXID(TTM_ENUMTOOLSW),// (WM_USER + 58)
TEXID(TTM_GETCURRENTTOOLA),// (WM_USER + 15)
TEXID(TTM_GETCURRENTTOOLW),// (WM_USER + 59)
TEXID(TTM_WINDOWFROMPOINT),// (WM_USER + 16)
#if (_WIN32_IE >= 0x0300)
TEXID(TTM_TRACKACTIVATE),// (WM_USER + 17) // wParam = TRUE/FALSE start end lparam = LPTOOLINFO
TEXID(TTM_TRACKPOSITION),// (WM_USER + 18) // lParam = dwPos
TEXID(TTM_SETTIPBKCOLOR),// (WM_USER + 19)
TEXID(TTM_SETTIPTEXTCOLOR),// (WM_USER + 20)
TEXID(TTM_GETDELAYTIME),// (WM_USER + 21)
TEXID(TTM_GETTIPBKCOLOR),// (WM_USER + 22)
TEXID(TTM_GETTIPTEXTCOLOR),// (WM_USER + 23)
TEXID(TTM_SETMAXTIPWIDTH),// (WM_USER + 24)
TEXID(TTM_GETMAXTIPWIDTH),// (WM_USER + 25)
TEXID(TTM_SETMARGIN),// (WM_USER + 26) // lParam = lprc
TEXID(TTM_GETMARGIN),// (WM_USER + 27) // lParam = lprc
TEXID(TTM_POP),// (WM_USER + 28)
#endif
#if (_WIN32_IE >= 0x0400)
TEXID(TTM_UPDATE),// (WM_USER + 29)
#endif
// LVM_FIRST 0x1000 // ListView messages
TEXID(LVM_GETBKCOLOR),// (LVM_FIRST + 0)
TEXID(LVM_SETBKCOLOR),// (LVM_FIRST + 1)
TEXID(LVM_GETIMAGELIST),// (LVM_FIRST + 2)
TEXID(LVM_SETIMAGELIST),// (LVM_FIRST + 3)
TEXID(LVM_GETITEMCOUNT),// (LVM_FIRST + 4)
TEXID(LVM_GETITEMA),// (LVM_FIRST + 5)
TEXID(LVM_GETITEMW),// (LVM_FIRST + 75)
TEXID(LVM_SETITEMA),// (LVM_FIRST + 6)
TEXID(LVM_SETITEMW),// (LVM_FIRST + 76)
TEXID(LVM_INSERTITEMA),// (LVM_FIRST + 7)
TEXID(LVM_INSERTITEMW),// (LVM_FIRST + 77)
TEXID(LVM_DELETEITEM),// (LVM_FIRST + 8)
TEXID(LVM_DELETEALLITEMS),// (LVM_FIRST + 9)
TEXID(LVM_GETCALLBACKMASK),// (LVM_FIRST + 10)
TEXID(LVM_SETCALLBACKMASK),// (LVM_FIRST + 11)
TEXID(LVM_GETNEXTITEM),// (LVM_FIRST + 12)
TEXID(LVM_FINDITEMA),// (LVM_FIRST + 13)
TEXID(LVM_FINDITEMW),// (LVM_FIRST + 83)
TEXID(LVM_GETITEMRECT),// (LVM_FIRST + 14)
TEXID(LVM_SETITEMPOSITION),// (LVM_FIRST + 15)
TEXID(LVM_GETITEMPOSITION),// (LVM_FIRST + 16)
TEXID(LVM_GETSTRINGWIDTHA),// (LVM_FIRST + 17)
TEXID(LVM_GETSTRINGWIDTHW),// (LVM_FIRST + 87)
TEXID(LVM_HITTEST),// (LVM_FIRST + 18)
TEXID(LVM_ENSUREVISIBLE),// (LVM_FIRST + 19)
TEXID(LVM_SCROLL),// (LVM_FIRST + 20)
TEXID(LVM_REDRAWITEMS),// (LVM_FIRST + 21)
TEXID(LVM_ARRANGE),// (LVM_FIRST + 22)
TEXID(LVM_EDITLABELA),// (LVM_FIRST + 23)
TEXID(LVM_EDITLABELW),// (LVM_FIRST + 118)
TEXID(LVM_GETEDITCONTROL),// (LVM_FIRST + 24)
TEXID(LVM_GETCOLUMNA),// (LVM_FIRST + 25)
TEXID(LVM_GETCOLUMNW),// (LVM_FIRST + 95)
TEXID(LVM_SETCOLUMNA),// (LVM_FIRST + 26)
TEXID(LVM_SETCOLUMNW),// (LVM_FIRST + 96)
TEXID(LVM_INSERTCOLUMNA),// (LVM_FIRST + 27)
TEXID(LVM_INSERTCOLUMNW),// (LVM_FIRST + 97)
TEXID(LVM_DELETECOLUMN),// (LVM_FIRST + 28)
TEXID(LVM_GETCOLUMNWIDTH),// (LVM_FIRST + 29)
TEXID(LVM_SETCOLUMNWIDTH),// (LVM_FIRST + 30)
TEXID(LVM_GETHEADER),// (LVM_FIRST + 31)
TEXID(LVM_CREATEDRAGIMAGE),// (LVM_FIRST + 33)
TEXID(LVM_GETVIEWRECT),// (LVM_FIRST + 34)
TEXID(LVM_GETTEXTCOLOR),// (LVM_FIRST + 35)
TEXID(LVM_SETTEXTCOLOR),// (LVM_FIRST + 36)
TEXID(LVM_GETTEXTBKCOLOR),// (LVM_FIRST + 37)
TEXID(LVM_SETTEXTBKCOLOR),// (LVM_FIRST + 38)
TEXID(LVM_GETTOPINDEX),// (LVM_FIRST + 39)
TEXID(LVM_GETCOUNTPERPAGE),// (LVM_FIRST + 40)
TEXID(LVM_GETORIGIN),// (LVM_FIRST + 41)
TEXID(LVM_UPDATE),// (LVM_FIRST + 42)
TEXID(LVM_SETITEMSTATE),// (LVM_FIRST + 43)
TEXID(LVM_GETITEMSTATE),// (LVM_FIRST + 44)
TEXID(LVM_GETITEMTEXTA),// (LVM_FIRST + 45)
TEXID(LVM_GETITEMTEXTW),// (LVM_FIRST + 115)
TEXID(LVM_SETITEMTEXTA),// (LVM_FIRST + 46)
TEXID(LVM_SETITEMTEXTW),// (LVM_FIRST + 116)
TEXID(LVM_SETITEMCOUNT),// (LVM_FIRST + 47)
TEXID(LVM_SORTITEMS),// (LVM_FIRST + 48)
TEXID(LVM_SETITEMPOSITION32),// (LVM_FIRST + 49)
TEXID(LVM_GETSELECTEDCOUNT),// (LVM_FIRST + 50)
TEXID(LVM_GETITEMSPACING),// (LVM_FIRST + 51)
TEXID(LVM_GETISEARCHSTRINGA),// (LVM_FIRST + 52)
TEXID(LVM_GETISEARCHSTRINGW),// (LVM_FIRST + 117)
TEXID(LVM_SETICONSPACING),// (LVM_FIRST + 53)
TEXID(LVM_SETEXTENDEDLISTVIEWSTYLE),//(LVM_FIRST + 54) // optional wParam == mask
TEXID(LVM_GETEXTENDEDLISTVIEWSTYLE),//(LVM_FIRST + 55)
TEXID(LVM_GETSUBITEMRECT),// (LVM_FIRST + 56)
TEXID(LVM_SUBITEMHITTEST),// (LVM_FIRST + 57)
TEXID(LVM_SETCOLUMNORDERARRAY),// (LVM_FIRST + 58)
TEXID(LVM_GETCOLUMNORDERARRAY),// (LVM_FIRST + 59)
TEXID(LVM_SETHOTITEM),// (LVM_FIRST + 60)
TEXID(LVM_GETHOTITEM),// (LVM_FIRST + 61)
TEXID(LVM_SETHOTCURSOR),// (LVM_FIRST + 62)
TEXID(LVM_GETHOTCURSOR),// (LVM_FIRST + 63)
TEXID(LVM_APPROXIMATEVIEWRECT),// (LVM_FIRST + 64)
TEXID(LVM_SETWORKAREAS),// (LVM_FIRST + 65)
TEXID(LVM_GETSELECTIONMARK),// (LVM_FIRST + 66)
TEXID(LVM_SETSELECTIONMARK),// (LVM_FIRST + 67)
TEXID(LVM_SETBKIMAGEA),// (LVM_FIRST + 68)
TEXID(LVM_GETBKIMAGEA),// (LVM_FIRST + 69)
TEXID(LVM_GETWORKAREAS),// (LVM_FIRST + 70)
TEXID(LVM_SETHOVERTIME),// (LVM_FIRST + 71)
TEXID(LVM_GETHOVERTIME),// (LVM_FIRST + 72)
TEXID(LVM_GETNUMBEROFWORKAREAS),//(LVM_FIRST + 73)
TEXID(LVM_SETTOOLTIPS),// (LVM_FIRST + 74)
TEXID(LVM_GETTOOLTIPS),// (LVM_FIRST + 78)
TEXID(LVM_SETBKIMAGEW),// (LVM_FIRST + 138)
TEXID(LVM_GETBKIMAGEW),// (LVM_FIRST + 139)
TEXID(LVN_ITEMCHANGING),// (LVN_FIRST-0)
TEXID(LVN_ITEMCHANGED),// (LVN_FIRST-1)
TEXID(LVN_INSERTITEM),// (LVN_FIRST-2)
TEXID(LVN_DELETEITEM),// (LVN_FIRST-3)
TEXID(LVN_DELETEALLITEMS),// (LVN_FIRST-4)
TEXID(LVN_BEGINLABELEDITA),// (LVN_FIRST-5)
TEXID(LVN_BEGINLABELEDITW),// (LVN_FIRST-75)
TEXID(LVN_ENDLABELEDITA),// (LVN_FIRST-6)
TEXID(LVN_ENDLABELEDITW),// (LVN_FIRST-76)
TEXID(LVN_COLUMNCLICK),// (LVN_FIRST-8)
TEXID(LVN_BEGINDRAG),// (LVN_FIRST-9)
TEXID(LVN_BEGINRDRAG),// (LVN_FIRST-11)
TEXID(LVN_ODCACHEHINT),// (LVN_FIRST-13)
TEXID(LVN_ODFINDITEMA),// (LVN_FIRST-52)
TEXID(LVN_ODFINDITEMW),// (LVN_FIRST-79)
TEXID(LVN_ITEMACTIVATE),// (LVN_FIRST-14)
TEXID(LVN_ODSTATECHANGED),// (LVN_FIRST-15)
TEXID(LVN_HOTTRACK),// (LVN_FIRST-21)
TEXID(LVN_GETDISPINFOA),// (LVN_FIRST-50)
TEXID(LVN_GETDISPINFOW),// (LVN_FIRST-77)
TEXID(LVN_SETDISPINFOA),// (LVN_FIRST-51)
TEXID(LVN_SETDISPINFOW),// (LVN_FIRST-78)
TEXID(LVN_MARQUEEBEGIN),// (LVN_FIRST-56)
TEXID(LVN_GETINFOTIPA),// (LVN_FIRST-57)
TEXID(LVN_GETINFOTIPW),// (LVN_FIRST-58)
{0, NULL} };
CString decode(UINT msg)
{
for (t_MESS *pt = messages; pt->text; pt++)
if (pt->id == msg) return pt->text;
CString text;
text.Format("WS_%08X", msg);
return text;
}
typedef struct { LPCTSTR res; LPCTSTR text; } t_RES;
static t_RES resource[] = {
TEXID(RT_ACCELERATOR),
TEXID(RT_ANICURSOR),
TEXID(RT_ANIICON),
TEXID(RT_BITMAP),
TEXID(RT_CURSOR),
TEXID(RT_DIALOG),
TEXID(RT_DLGINIT),
TEXID(RT_FONT),
TEXID(RT_FONTDIR),
TEXID(RT_GROUP_CURSOR),
TEXID(RT_GROUP_ICON),
TEXID(RT_HTML),
TEXID(RT_ICON),
TEXID(RT_MENU),
TEXID(RT_MESSAGETABLE),
TEXID(RT_PLUGPLAY),
TEXID(RT_RCDATA),
TEXID(RT_STRING),
TEXID(RT_TOOLBAR),
TEXID(RT_VERSION),
TEXID(RT_VXD),
{NULL, NULL} };
CString decodeRes(LPCTSTR resType)
{
for (t_RES *pt = resource; pt->text; pt++)
if (pt->res == resType) return pt->text;
CString text;
text.Format("RT_%08X", resType);
return text;
}
#endif
| [
"cconger77@2afb5f34-2eaf-11df-9ac8-ff20597b2c9b"
] | cconger77@2afb5f34-2eaf-11df-9ac8-ff20597b2c9b |
f0f9d83d610facb87645fa075e0dc9dc905cceb6 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE78_OS_Command_Injection/s05/CWE78_OS_Command_Injection__wchar_t_connect_socket_w32_execv_72a.cpp | a47864ab75cab013a01bec7548a68209af05d6b5 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 5,813 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_connect_socket_w32_execv_72a.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-72a.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Fixed string
* Sinks: w32_execv
* BadSink : execute command with wexecv
* Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <vector>
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"ls"
#define COMMAND_ARG2 L"-la"
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
using namespace std;
namespace CWE78_OS_Command_Injection__wchar_t_connect_socket_w32_execv_72
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(vector<wchar_t *> dataVector);
void bad()
{
wchar_t * data;
vector<wchar_t *> dataVector;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
badSink(dataVector);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<wchar_t *> dataVector);
static void goodG2B()
{
wchar_t * data;
vector<wchar_t *> dataVector;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
goodG2BSink(dataVector);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE78_OS_Command_Injection__wchar_t_connect_socket_w32_execv_72; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"[email protected]"
] | |
b21c67651adbfe61ab0876a32c0ebc3c816522d3 | f9a26583bdd20989184ee1eb223cc53bb60681b2 | /character.h | dbb500d9be4dcefdb45ce1a72900e98863bf41f6 | [] | no_license | MayaLavi22/ex2-part_b | c30922b45231c804cd7b1ab8ff54604de12bdd13 | 073f0af61ba466de4e0c178894fd98ac6f3ac199 | refs/heads/main | 2023-06-02T03:25:15.873914 | 2021-06-14T14:47:31 | 2021-06-14T14:47:31 | 376,856,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,270 | h | #ifndef CHARACTER_H_
#define CHARACTER_H_
#include "Auxiliaries.h"
#include <iostream>
#include <memory>
#include <vector>
namespace mtm
{
class Character
{
int health;
int ammo;
int range;
int power;
Team team;
public:
Character(units_t health,units_t ammo,units_t range,units_t power, Team team):
health(health), ammo(ammo),range(range),power(power), team(team){}
Character(const Character& character) = default;
Character& operator=(const Character& character) = default;
virtual ~Character() = default;
virtual bool isLegalMovement(int distance) const;
virtual void attack(int src_row, int src_col, int dst_row, int dst_col, int height, int width, std::vector<std::vector<std::shared_ptr<Character>>> game_grid);
void reduceHealth(int points_reduced){
health = health - points_reduced;
}
virtual CharacterType getCharacterType();
virtual void reload();
void SetAmmo(int x) {ammo+=x;}
virtual std::shared_ptr<Character> clone() const = 0;
};
}
#endif /* CHARACTER_H_ */ | [
"[email protected]"
] | |
53ffac9b986d053fef00303923f7b0f016bf0cf6 | 1809c6922be6dfcfd222824ea342542f11ff2cae | /cocos2d/cocos/2d/CCSpriteFrame.cpp | 1b5554f77d694f5f7079006f3e5769d699095823 | [
"MIT"
] | permissive | ngladkoff/tutorial-puzzle | cf6152174a5e3061b620c02c4ee72d1d663401f0 | 9a4c2d30e56a572eb18f8048e9985600aea2e00d | refs/heads/master | 2020-04-07T19:59:17.595425 | 2014-05-23T14:46:59 | 2014-05-23T14:46:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,897 | cpp | /****************************************************************************
Copyright (c) 2008-2011 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCTextureCache.h"
#include "2d/CCSpriteFrame.h"
#include "2d/CCDirector.h"
NS_CC_BEGIN
// implementation of SpriteFrame
SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect)
{
SpriteFrame *spriteFrame = new SpriteFrame();
spriteFrame->initWithTextureFilename(filename, rect);
spriteFrame->autorelease();
return spriteFrame;
}
SpriteFrame* SpriteFrame::createWithTexture(Texture2D *texture, const Rect& rect)
{
SpriteFrame *spriteFrame = new SpriteFrame();
spriteFrame->initWithTexture(texture, rect);
spriteFrame->autorelease();
return spriteFrame;
}
SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture, const Rect& rect, bool rotated, const Vector2& offset, const Size& originalSize)
{
SpriteFrame *spriteFrame = new SpriteFrame();
spriteFrame->initWithTexture(texture, rect, rotated, offset, originalSize);
spriteFrame->autorelease();
return spriteFrame;
}
SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect, bool rotated, const Vector2& offset, const Size& originalSize)
{
SpriteFrame *spriteFrame = new SpriteFrame();
spriteFrame->initWithTextureFilename(filename, rect, rotated, offset, originalSize);
spriteFrame->autorelease();
return spriteFrame;
}
bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect)
{
Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect);
return initWithTexture(texture, rectInPixels, false, Vector2::ZERO, rectInPixels.size);
}
bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect)
{
Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect );
return initWithTextureFilename(filename, rectInPixels, false, Vector2::ZERO, rectInPixels.size);
}
bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect, bool rotated, const Vector2& offset, const Size& originalSize)
{
_texture = texture;
if (texture)
{
texture->retain();
}
_rectInPixels = rect;
_rect = CC_RECT_PIXELS_TO_POINTS(rect);
_offsetInPixels = offset;
_offset = CC_POINT_PIXELS_TO_POINTS( _offsetInPixels );
_originalSizeInPixels = originalSize;
_originalSize = CC_SIZE_PIXELS_TO_POINTS( _originalSizeInPixels );
_rotated = rotated;
return true;
}
bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect, bool rotated, const Vector2& offset, const Size& originalSize)
{
_texture = nullptr;
_textureFilename = filename;
_rectInPixels = rect;
_rect = CC_RECT_PIXELS_TO_POINTS( rect );
_offsetInPixels = offset;
_offset = CC_POINT_PIXELS_TO_POINTS( _offsetInPixels );
_originalSizeInPixels = originalSize;
_originalSize = CC_SIZE_PIXELS_TO_POINTS( _originalSizeInPixels );
_rotated = rotated;
return true;
}
SpriteFrame::~SpriteFrame(void)
{
CCLOGINFO("deallocing SpriteFrame: %p", this);
CC_SAFE_RELEASE(_texture);
}
SpriteFrame* SpriteFrame::clone() const
{
// no copy constructor
SpriteFrame *copy = new SpriteFrame();
copy->initWithTextureFilename(_textureFilename.c_str(), _rectInPixels, _rotated, _offsetInPixels, _originalSizeInPixels);
copy->setTexture(_texture);
copy->autorelease();
return copy;
}
void SpriteFrame::setRect(const Rect& rect)
{
_rect = rect;
_rectInPixels = CC_RECT_POINTS_TO_PIXELS(_rect);
}
void SpriteFrame::setRectInPixels(const Rect& rectInPixels)
{
_rectInPixels = rectInPixels;
_rect = CC_RECT_PIXELS_TO_POINTS(rectInPixels);
}
const Vector2& SpriteFrame::getOffset() const
{
return _offset;
}
void SpriteFrame::setOffset(const Vector2& offsets)
{
_offset = offsets;
_offsetInPixels = CC_POINT_POINTS_TO_PIXELS( _offset );
}
const Vector2& SpriteFrame::getOffsetInPixels() const
{
return _offsetInPixels;
}
void SpriteFrame::setOffsetInPixels(const Vector2& offsetInPixels)
{
_offsetInPixels = offsetInPixels;
_offset = CC_POINT_PIXELS_TO_POINTS( _offsetInPixels );
}
void SpriteFrame::setTexture(Texture2D * texture)
{
if( _texture != texture ) {
CC_SAFE_RELEASE(_texture);
CC_SAFE_RETAIN(texture);
_texture = texture;
}
}
Texture2D* SpriteFrame::getTexture(void)
{
if( _texture ) {
return _texture;
}
if( _textureFilename.length() > 0 ) {
return Director::getInstance()->getTextureCache()->addImage(_textureFilename.c_str());
}
// no texture or texture filename
return nullptr;
}
NS_CC_END
| [
"[email protected]"
] | |
72ef6c2bbcdd9220adcbe102b628b29a7085257b | 67c3e1b71db50271a6aede941837a08081d28464 | /BitRotation/BitRotation.cpp | a961a222394ed8095952cb01a3a470ef10ea5008 | [] | no_license | Innikolov/BitRotation | d4dd4e88fb2b7a2c333dc6cb821526cc9288637b | ba0de4d1bd7f44c92c40bd98409c8f6afcf69e94 | refs/heads/main | 2023-06-15T04:58:52.181950 | 2021-07-12T09:01:00 | 2021-07-12T09:01:00 | 385,186,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
int rotateLeft(unsigned int num, unsigned int rotation)
{
while (rotation--)
num = (num << 1) | (1 & (num >> 31));
return num;
}
int main()
{
unsigned int num;
unsigned int rotation;
printf("Enter a hex number: ");
scanf("%x", &num);
printf("Enter number of rotation: ");
scanf("%d", &rotation);
printf("%x left rotated %d times = %x\n\n", num, rotation, rotateLeft(num, rotation));
}
| [
"[email protected]"
] | |
d45f8ebd0c7c266a2f32df0bbd218248604d1582 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/shortlinksrv/Bluetooth/T_BTSdpAPI/src/T_DataRSdp.cpp | da214e524bc2d612f4fce9e75cc70508426391a5 | [] | no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,799 | cpp | /*
* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include "T_DataRSdp.h"
/*@{*/
//Parameters
_LIT(KExpected, "expected");
_LIT(KVersionName, "name");
_LIT(KVersionBuild, "build");
_LIT(KVersionMajor, "major");
_LIT(KVersionMinor, "minor");
//Commands
_LIT(KCmdConstructor, "Constructor");
_LIT(KCmdConnect, "Connect");
_LIT(KCmdClose, "Close");
_LIT(KCmdVersion, "Version");
_LIT(KCmdResourceCountMarkStart, "ResourceCountMarkStart");
_LIT(KCmdResourceCountMarkEnd, "ResourceCountMarkEnd");
_LIT(KCmdResourceCount, "ResourceCount");
/*@}*/
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CT_DataRSdp* CT_DataRSdp::NewL()
{
CT_DataRSdp* ret=new (ELeave) CT_DataRSdp();
CleanupStack::PushL(ret);
ret->ConstructL();
CleanupStack::Pop(ret);
return ret;
}
CT_DataRSdp::CT_DataRSdp()
: iRsdp(NULL)
{
}
void CT_DataRSdp::ConstructL()
{
}
CT_DataRSdp::~CT_DataRSdp()
{
DestroyData();
}
void CT_DataRSdp::SetObjectL(TAny* aAny)
{
DestroyData();
iRsdp = static_cast<RSdp*> (aAny);
}
void CT_DataRSdp::DisownObjectL()
{
iRsdp = NULL;
}
void CT_DataRSdp::DestroyData()
{
delete iRsdp;
iRsdp=NULL;
}
inline TCleanupOperation CT_DataRSdp::CleanupOperation()
{
return CleanupOperation;
}
void CT_DataRSdp::CleanupOperation(TAny* aAny)
{
RSdp* sdp=static_cast<RSdp*>(aAny);
delete sdp;
}
/**
test script command entry point
@internalAll
@return ETrue if syncronous command otherwise EFalse
@param aParam1 descriptor containing the command value
@param aParam2 descriptor containing the command parameter
@pre N/A
@post N/A
*/
TBool CT_DataRSdp::DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt /*aAsyncErrorIndex*/)
{
TBool ret=ETrue;
if ( aCommand==KCmdConstructor )
{
DoCmdConstructor();
}
else if( aCommand==KCmdConnect )
{
DoCmdConnect();
}
else if( aCommand==KCmdClose )
{
DoCmdClose();
}
else if( aCommand==KCmdVersion )
{
DoCmdVersion(aSection);
}
else if( aCommand==KCmdResourceCountMarkStart )
{
DoCmdResourceCountMarkStart();
}
else if( aCommand==KCmdResourceCountMarkEnd )
{
DoCmdResourceCountMarkEnd();
}
else if( aCommand==KCmdResourceCount )
{
DoCmdResourceCount(aSection);
}
else
{
ret=EFalse;
}
return ret;
}
void CT_DataRSdp::DoCmdConstructor()
{
DestroyData();
TRAPD(err, iRsdp = new (ELeave) RSdp());
if(err != KErrNone)
{
ERR_PRINTF2(_L("**** RSdp Constructor failed with error %d"), err);
SetError(err);
}
}
void CT_DataRSdp::DoCmdConnect()
{
TInt err = iRsdp->Connect();
if(err != KErrNone)
{
ERR_PRINTF2(_L("**** RSdp Connect failed with error %d"), err);
SetError(err);
}
}
void CT_DataRSdp::DoCmdClose()
{
iRsdp->Close();
}
void CT_DataRSdp::DoCmdVersion(const TDesC& aSection)
{
TVersion version=iRsdp->Version();
TVersionName versionName = version.Name();
INFO_PRINTF1(_L("Version name :"));
INFO_PRINTF1(versionName);
INFO_PRINTF2(_L("Version build : %d"), (TInt)version.iBuild);
INFO_PRINTF2(_L("Version major : %d"), (TInt)version.iMajor);
INFO_PRINTF2(_L("Version minor : %d"), (TInt)version.iMinor);
TPtrC name;
if ( GetStringFromConfig(aSection, KVersionName(), name) )
{
if ( name != versionName )
{
ERR_PRINTF1(_L("Name does not match expected name"));
SetBlockResult(EFail);
}
}
else
{
ERR_PRINTF2(_L("Missing expected value %S"), &KVersionName());
SetBlockResult(EFail);
}
/*
The following expected values are optional since the version name already includes these info.
*/
TInt intTemp;
if ( GetIntFromConfig(aSection, KVersionBuild(), intTemp) )
{
if ( intTemp != version.iBuild )
{
ERR_PRINTF1(_L("Build does not match expected build"));
SetBlockResult(EFail);
}
}
if ( GetIntFromConfig(aSection, KVersionMajor(), intTemp) )
{
if ( intTemp != version.iMajor )
{
ERR_PRINTF1(_L("Major does not match expected major"));
SetBlockResult(EFail);
}
}
if ( GetIntFromConfig(aSection, KVersionMinor(), intTemp) )
{
if ( intTemp != version.iMinor )
{
ERR_PRINTF1(_L("Minor does not match expected minor"));
SetBlockResult(EFail);
}
}
if (versionName == _L("") && version.iBuild == 0)
{
ERR_PRINTF1(_L("Some version fields are not set!"));
SetBlockResult(EFail);
}
if (version.iMajor == 0 && version.iMinor == 0)
{
ERR_PRINTF1(_L("Some version fields are not set!"));
SetBlockResult(EFail);
}
}
void CT_DataRSdp::DoCmdResourceCountMarkStart()
{
iRsdp->ResourceCountMarkStart();
}
void CT_DataRSdp::DoCmdResourceCountMarkEnd()
{
iRsdp->ResourceCountMarkEnd();
}
void CT_DataRSdp::DoCmdResourceCount(const TDesC& aSection)
{
TInt actual=iRsdp->ResourceCount();
INFO_PRINTF2(_L("RSdp::ResourceCount = %d"), actual);
TInt expected;
if ( GetIntFromConfig(aSection, KExpected(), expected) )
{
if ( actual!=expected )
{
ERR_PRINTF1(_L("ResourceCount is not as expected!"));
SetBlockResult(EFail);
}
}
}
| [
"none@none"
] | none@none |
589cb1f0b0e50f5007d51acc4a40868d7e911d82 | 1635fd43607db0aebf047e77cd8577226e5ca11a | /ifs/tests/programmingTests/cpp/main.cpp | cdccc95102240d5e12efa901a333562f75ffead9 | [
"MIT"
] | permissive | ian-james/IFS | f0275dabc21379200200845babd6ff03e163ffab | 4004dbd0d9a4dfb868ff76b6881ba2b51ce5f33d | refs/heads/master | 2021-01-11T23:21:28.405904 | 2019-09-20T19:39:50 | 2019-09-20T19:39:50 | 78,569,768 | 7 | 14 | MIT | 2020-08-05T15:51:59 | 2017-01-10T20:10:57 | JavaScript | UTF-8 | C++ | false | false | 419 | cpp | /**
Testing programs only, not validated in any way.
Jamey
*/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<functional>
#include<iterator>
#include<ostream>
using namespace std;
int main( int argc, char ** argv )
{
string str = "";
istream_iterator< string > in(cin);
copy(in, istream_iterator<string> (), ostream_iterator< string > ( cout ) );
}
| [
"[email protected]"
] | |
25772177f6b92ef93cd1b86da5aae3b1468cc753 | c547b89ca549234cf2d3536bd4f7530eb83e627f | /src/ART_Version/runtime/class_linker.h | 107a4b20ca2446036826a8708f77c647c69e19b8 | [
"NCSA",
"Apache-2.0"
] | permissive | UchihaL/AppSpear | 9c4dbf5bc8d4084a8d678cbb82311a41945a33bc | fd73d19429651fca040bb33822bc222b068791b8 | refs/heads/master | 2021-09-02T06:47:45.766224 | 2017-12-31T06:05:11 | 2017-12-31T06:05:11 | 115,843,307 | 37 | 25 | null | null | null | null | UTF-8 | C++ | false | false | 37,231 | h | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ART_RUNTIME_CLASS_LINKER_H_
#define ART_RUNTIME_CLASS_LINKER_H_
#include <string>
#include <utility>
#include <vector>
#include "base/allocator.h"
#include "base/macros.h"
#include "base/mutex.h"
#include "dex_file.h"
#include "gc_root.h"
#include "gtest/gtest.h"
#include "jni.h"
#include "oat_file.h"
#include "object_callbacks.h"
namespace art {
namespace gc {
namespace space {
class ImageSpace;
} // namespace space
} // namespace gc
namespace mirror {
class ClassLoader;
class DexCache;
class DexCacheTest_Open_Test;
class IfTable;
template<class T> class ObjectArray;
class StackTraceElement;
} // namespace mirror
class InternTable;
template<class T> class ObjectLock;
class ScopedObjectAccessAlreadyRunnable;
template<class T> class Handle;
typedef bool (ClassVisitor)(mirror::Class* c, void* arg);
enum VisitRootFlags : uint8_t;
class ClassLinker {
public:
explicit ClassLinker(InternTable* intern_table);
~ClassLinker();
// Initialize class linker by bootstraping from dex files.
void InitWithoutImage(const std::vector<const DexFile*>& boot_class_path)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Initialize class linker from one or more images.
void InitFromImage() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Finds a class by its descriptor, loading it if necessary.
// If class_loader is null, searches boot_class_path_.
mirror::Class* FindClass(Thread* self, const char* descriptor,
Handle<mirror::ClassLoader> class_loader)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Find a class in the path class loader, loading it if necessary.
mirror::Class* FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Thread* self, const char* descriptor,
Handle<mirror::ClassLoader> class_loader)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Finds a class by its descriptor using the "system" class loader, ie by searching the
// boot_class_path_.
mirror::Class* FindSystemClass(Thread* self, const char* descriptor)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Finds the array class given for the element class.
mirror::Class* FindArrayClass(Thread* self, mirror::Class** element_class)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Returns true if the class linker is initialized.
bool IsInitialized() const;
// Define a new a class based on a ClassDef from a DexFile
mirror::Class* DefineClass(const char* descriptor,
Handle<mirror::ClassLoader> class_loader,
const DexFile& dex_file, const DexFile::ClassDef& dex_class_def)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Finds a class by its descriptor, returning NULL if it isn't wasn't loaded
// by the given 'class_loader'.
mirror::Class* LookupClass(const char* descriptor, const mirror::ClassLoader* class_loader)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Finds all the classes with the given descriptor, regardless of ClassLoader.
void LookupClasses(const char* descriptor, std::vector<mirror::Class*>& classes)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::Class* FindPrimitiveClass(char type) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// General class unloading is not supported, this is used to prune
// unwanted classes during image writing.
bool RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void DumpAllClasses(int flags)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void DumpForSigQuit(std::ostream& os)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
size_t NumLoadedClasses()
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Resolve a String with the given index from the DexFile, storing the
// result in the DexCache. The referrer is used to identify the
// target DexCache and ClassLoader to use for resolution.
mirror::String* ResolveString(uint32_t string_idx, mirror::ArtMethod* referrer)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Resolve a String with the given index from the DexFile, storing the
// result in the DexCache.
mirror::String* ResolveString(const DexFile& dex_file, uint32_t string_idx,
Handle<mirror::DexCache> dex_cache)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Resolve a Type with the given index from the DexFile, storing the
// result in the DexCache. The referrer is used to identity the
// target DexCache and ClassLoader to use for resolution.
mirror::Class* ResolveType(const DexFile& dex_file, uint16_t type_idx, mirror::Class* referrer)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Resolve a Type with the given index from the DexFile, storing the
// result in the DexCache. The referrer is used to identify the
// target DexCache and ClassLoader to use for resolution.
mirror::Class* ResolveType(uint16_t type_idx, mirror::ArtMethod* referrer)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::Class* ResolveType(uint16_t type_idx, mirror::ArtField* referrer)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Resolve a type with the given ID from the DexFile, storing the
// result in DexCache. The ClassLoader is used to search for the
// type, since it may be referenced from but not contained within
// the given DexFile.
mirror::Class* ResolveType(const DexFile& dex_file, uint16_t type_idx,
Handle<mirror::DexCache> dex_cache,
Handle<mirror::ClassLoader> class_loader)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Resolve a method with a given ID from the DexFile, storing the
// result in DexCache. The ClassLinker and ClassLoader are used as
// in ResolveType. What is unique is the method type argument which
// is used to determine if this method is a direct, static, or
// virtual method.
mirror::ArtMethod* ResolveMethod(const DexFile& dex_file,
uint32_t method_idx,
Handle<mirror::DexCache> dex_cache,
Handle<mirror::ClassLoader> class_loader,
Handle<mirror::ArtMethod> referrer,
InvokeType type)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ArtMethod* GetResolvedMethod(uint32_t method_idx, mirror::ArtMethod* referrer,
InvokeType type)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ArtMethod* ResolveMethod(Thread* self, uint32_t method_idx, mirror::ArtMethod** referrer,
InvokeType type)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ArtField* GetResolvedField(uint32_t field_idx, mirror::Class* field_declaring_class)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ArtField* ResolveField(uint32_t field_idx, mirror::ArtMethod* referrer,
bool is_static)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Resolve a field with a given ID from the DexFile, storing the
// result in DexCache. The ClassLinker and ClassLoader are used as
// in ResolveType. What is unique is the is_static argument which is
// used to determine if we are resolving a static or non-static
// field.
mirror::ArtField* ResolveField(const DexFile& dex_file,
uint32_t field_idx,
Handle<mirror::DexCache> dex_cache,
Handle<mirror::ClassLoader> class_loader,
bool is_static)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Resolve a field with a given ID from the DexFile, storing the
// result in DexCache. The ClassLinker and ClassLoader are used as
// in ResolveType. No is_static argument is provided so that Java
// field resolution semantics are followed.
mirror::ArtField* ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx,
Handle<mirror::DexCache> dex_cache,
Handle<mirror::ClassLoader> class_loader)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Get shorty from method index without resolution. Used to do handlerization.
const char* MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer, uint32_t* length)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Returns true on success, false if there's an exception pending.
// can_run_clinit=false allows the compiler to attempt to init a class,
// given the restriction that no <clinit> execution is possible.
bool EnsureInitialized(Handle<mirror::Class> c, bool can_init_fields, bool can_init_parents)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Initializes classes that have instances in the image but that have
// <clinit> methods so they could not be initialized by the compiler.
void RunRootClinits() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void RegisterDexFile(const DexFile& dex_file)
LOCKS_EXCLUDED(dex_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void RegisterDexFile(const DexFile& dex_file, Handle<mirror::DexCache> dex_cache)
LOCKS_EXCLUDED(dex_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
const OatFile* RegisterOatFile(const OatFile* oat_file)
LOCKS_EXCLUDED(dex_lock_);
const std::vector<const DexFile*>& GetBootClassPath() {
return boot_class_path_;
}
void VisitClasses(ClassVisitor* visitor, void* arg)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Less efficient variant of VisitClasses that copies the class_table_ into secondary storage
// so that it can visit individual classes without holding the doesn't hold the
// Locks::classlinker_classes_lock_. As the Locks::classlinker_classes_lock_ isn't held this code
// can race with insertion and deletion of classes while the visitor is being called.
void VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags)
LOCKS_EXCLUDED(dex_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::DexCache* FindDexCache(const DexFile& dex_file)
LOCKS_EXCLUDED(dex_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool IsDexFileRegistered(const DexFile& dex_file)
LOCKS_EXCLUDED(dex_lock_) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void FixupDexCaches(mirror::ArtMethod* resolution_method)
LOCKS_EXCLUDED(dex_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Generate an oat file from a dex file
bool GenerateOatFile(const char* dex_filename,
int oat_fd,
const char* oat_cache_filename,
std::string* error_msg)
LOCKS_EXCLUDED(Locks::mutator_lock_);
// Find or create the oat file holding dex_location. Then load all corresponding dex files
// (if multidex) into the given vector.
bool OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
std::vector<std::string>* error_msgs,
std::vector<const DexFile*>* dex_files)
LOCKS_EXCLUDED(dex_lock_, Locks::mutator_lock_);
// Returns true if the given oat file has the same image checksum as the image it is paired with.
static bool VerifyOatImageChecksum(const OatFile* oat_file, const InstructionSet instruction_set);
// Returns true if the oat file checksums match with the image and the offsets are such that it
// could be loaded with it.
static bool VerifyOatChecksums(const OatFile* oat_file, const InstructionSet instruction_set,
std::string* error_msg);
// Returns true if oat file contains the dex file with the given location and checksum.
static bool VerifyOatAndDexFileChecksums(const OatFile* oat_file,
const char* dex_location,
uint32_t dex_location_checksum,
InstructionSet instruction_set,
std::string* error_msg);
// TODO: replace this with multiple methods that allocate the correct managed type.
template <class T>
mirror::ObjectArray<T>* AllocObjectArray(Thread* self, size_t length)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ObjectArray<mirror::Class>* AllocClassArray(Thread* self, size_t length)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ObjectArray<mirror::String>* AllocStringArray(Thread* self, size_t length)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ObjectArray<mirror::ArtMethod>* AllocArtMethodArray(Thread* self, size_t length)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::IfTable* AllocIfTable(Thread* self, size_t ifcount)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ObjectArray<mirror::ArtField>* AllocArtFieldArray(Thread* self, size_t length)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ObjectArray<mirror::StackTraceElement>* AllocStackTraceElementArray(Thread* self,
size_t length)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void VerifyClass(Handle<mirror::Class> klass) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
mirror::Class::Status& oat_file_class_status)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Handle<mirror::Class> klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, mirror::ArtMethod* klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::Class* CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
jobjectArray interfaces, jobject loader, jobjectArray methods,
jobjectArray throws)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
std::string GetDescriptorForProxy(mirror::Class* proxy_class)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ArtMethod* FindMethodForProxy(mirror::Class* proxy_class,
mirror::ArtMethod* proxy_method)
LOCKS_EXCLUDED(dex_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Get the oat code for a method when its class isn't yet initialized
const void* GetQuickOatCodeFor(mirror::ArtMethod* method)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
#if defined(ART_USE_PORTABLE_COMPILER)
const void* GetPortableOatCodeFor(mirror::ArtMethod* method, bool* have_portable_code)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
#endif
// Get the oat code for a method from a method index.
const void* GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx, uint32_t method_idx)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
#if defined(ART_USE_PORTABLE_COMPILER)
const void* GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx, uint32_t method_idx)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
#endif
pid_t GetClassesLockOwner(); // For SignalCatcher.
pid_t GetDexLockOwner(); // For SignalCatcher.
const void* GetPortableResolutionTrampoline() const {
return portable_resolution_trampoline_;
}
const void* GetQuickGenericJniTrampoline() const {
return quick_generic_jni_trampoline_;
}
const void* GetQuickResolutionTrampoline() const {
return quick_resolution_trampoline_;
}
const void* GetPortableImtConflictTrampoline() const {
return portable_imt_conflict_trampoline_;
}
const void* GetQuickImtConflictTrampoline() const {
return quick_imt_conflict_trampoline_;
}
const void* GetQuickToInterpreterBridgeTrampoline() const {
return quick_to_interpreter_bridge_trampoline_;
}
InternTable* GetInternTable() const {
return intern_table_;
}
// Attempts to insert a class into a class table. Returns NULL if
// the class was inserted, otherwise returns an existing class with
// the same descriptor and ClassLoader.
mirror::Class* InsertClass(const char* descriptor, mirror::Class* klass, size_t hash)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Special code to allocate an art method, use this instead of class->AllocObject.
mirror::ArtMethod* AllocArtMethod(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ObjectArray<mirror::Class>* GetClassRoots() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
DCHECK(class_roots != NULL);
return class_roots;
}
private:
bool FindOatMethodFor(mirror::ArtMethod* method, OatFile::OatMethod* oat_method)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
OatFile& GetImageOatFile(gc::space::ImageSpace* space)
LOCKS_EXCLUDED(dex_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void FinishInit(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// For early bootstrapping by Init
mirror::Class* AllocClass(Thread* self, mirror::Class* java_lang_Class, uint32_t class_size)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Alloc* convenience functions to avoid needing to pass in mirror::Class*
// values that are known to the ClassLinker such as
// kObjectArrayClass and kJavaLangString etc.
mirror::Class* AllocClass(Thread* self, uint32_t class_size)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::DexCache* AllocDexCache(Thread* self, const DexFile& dex_file)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ArtField* AllocArtField(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::Class* CreatePrimitiveClass(Thread* self, Primitive::Type type)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::Class* InitializePrimitiveClass(mirror::Class* primitive_class, Primitive::Type type)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::Class* CreateArrayClass(Thread* self, const char* descriptor,
Handle<mirror::ClassLoader> class_loader)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void AppendToBootClassPath(const DexFile& dex_file)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void AppendToBootClassPath(const DexFile& dex_file, Handle<mirror::DexCache> dex_cache)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
mirror::Class* c, SafeMap<uint32_t, mirror::ArtField*>& field_map)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Precomputes size needed for Class, in the case of a non-temporary class this size must be
// sufficient to hold all static fields.
uint32_t SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
const DexFile::ClassDef& dex_class_def);
void LoadClass(const DexFile& dex_file,
const DexFile::ClassDef& dex_class_def,
Handle<mirror::Class> klass,
mirror::ClassLoader* class_loader)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void LoadClassMembers(const DexFile& dex_file,
const byte* class_data,
Handle<mirror::Class> klass,
mirror::ClassLoader* class_loader,
const OatFile::OatClass* oat_class)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
Handle<mirror::Class> klass, Handle<mirror::ArtField> dst)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ArtMethod* LoadMethod(Thread* self, const DexFile& dex_file,
const ClassDataItemIterator& dex_method,
Handle<mirror::Class> klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void FixupStaticTrampolines(mirror::Class* klass) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Finds the associated oat class for a dex_file and descriptor. Returns whether the class
// was found, and sets the data in oat_class.
bool FindOatClass(const DexFile& dex_file, uint16_t class_def_idx, OatFile::OatClass* oat_class)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void RegisterDexFileLocked(const DexFile& dex_file, Handle<mirror::DexCache> dex_cache)
EXCLUSIVE_LOCKS_REQUIRED(dex_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool IsDexFileRegisteredLocked(const DexFile& dex_file)
SHARED_LOCKS_REQUIRED(dex_lock_, Locks::mutator_lock_);
bool InitializeClass(Handle<mirror::Class> klass, bool can_run_clinit,
bool can_init_parents)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
ObjectLock<mirror::Class>& lock);
bool ValidateSuperClassDescriptors(Handle<mirror::Class> klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool IsSameDescriptorInDifferentClassContexts(Thread* self, const char* descriptor,
Handle<mirror::ClassLoader> class_loader1,
Handle<mirror::ClassLoader> class_loader2)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool IsSameMethodSignatureInDifferentClassContexts(Thread* self, mirror::ArtMethod* method,
mirror::Class* klass1,
mirror::Class* klass2)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
Handle<mirror::ObjectArray<mirror::Class>> interfaces,
mirror::Class** new_class)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool LinkSuperClass(Handle<mirror::Class> klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool LinkMethods(Thread* self, Handle<mirror::Class> klass,
Handle<mirror::ObjectArray<mirror::Class>> interfaces)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool LinkInterfaceMethods(Handle<mirror::Class> klass,
Handle<mirror::ObjectArray<mirror::Class>> interfaces)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool LinkStaticFields(Handle<mirror::Class> klass, size_t* class_size)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool LinkInstanceFields(Handle<mirror::Class> klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
bool LinkFields(Handle<mirror::Class> klass, bool is_static, size_t* class_size)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void LinkCode(Handle<mirror::ArtMethod> method, const OatFile::OatClass* oat_class,
const DexFile& dex_file, uint32_t dex_method_index, uint32_t method_index)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void CreateReferenceInstanceOffsets(Handle<mirror::Class> klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void CreateReferenceStaticOffsets(Handle<mirror::Class> klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void CreateReferenceOffsets(Handle<mirror::Class> klass, bool is_static,
uint32_t reference_offsets)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// For use by ImageWriter to find DexCaches for its roots
ReaderWriterMutex* DexLock()
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) LOCK_RETURNED(dex_lock_) {
return &dex_lock_;
}
size_t GetDexCacheCount() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, dex_lock_) {
return dex_caches_.size();
}
mirror::DexCache* GetDexCache(size_t idx) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, dex_lock_);
const OatFile::OatDexFile* FindOpenedOatDexFileForDexFile(const DexFile& dex_file)
LOCKS_EXCLUDED(dex_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Find an opened oat dex file that contains dex_location. If oat_location is not nullptr,
// the file must have that location, else any oat location is accepted.
const OatFile::OatDexFile* FindOpenedOatDexFile(const char* oat_location,
const char* dex_location,
const uint32_t* dex_location_checksum)
LOCKS_EXCLUDED(dex_lock_);
// Will open the oat file directly without relocating, even if we could/should do relocation.
const OatFile* FindOatFileFromOatLocation(const std::string& oat_location,
std::string* error_msg)
LOCKS_EXCLUDED(dex_lock_);
const OatFile* FindOpenedOatFileFromOatLocation(const std::string& oat_location)
LOCKS_EXCLUDED(dex_lock_);
const OatFile* OpenOatFileFromDexLocation(const std::string& dex_location,
InstructionSet isa,
bool* already_opened,
bool* obsolete_file_cleanup_failed,
std::vector<std::string>* error_msg)
LOCKS_EXCLUDED(dex_lock_, Locks::mutator_lock_);
const OatFile* GetInterpretedOnlyOat(const std::string& oat_path,
InstructionSet isa,
std::string* error_msg);
const OatFile* PatchAndRetrieveOat(const std::string& input, const std::string& output,
const std::string& image_location, InstructionSet isa,
std::string* error_msg)
LOCKS_EXCLUDED(Locks::mutator_lock_);
bool CheckOatFile(const OatFile* oat_file, InstructionSet isa,
bool* checksum_verified, std::string* error_msg);
int32_t GetRequiredDelta(const OatFile* oat_file, InstructionSet isa);
// Note: will not register the oat file.
const OatFile* FindOatFileInOatLocationForDexFile(const char* dex_location,
uint32_t dex_location_checksum,
const char* oat_location,
std::string* error_msg)
LOCKS_EXCLUDED(dex_lock_);
// Creates the oat file from the dex_location to the oat_location. Needs a file descriptor for
// the file to be written, which is assumed to be under a lock.
const OatFile* CreateOatFileForDexLocation(const char* dex_location,
int fd, const char* oat_location,
std::vector<std::string>* error_msgs)
LOCKS_EXCLUDED(dex_lock_, Locks::mutator_lock_);
// Finds an OatFile that contains a DexFile for the given a DexFile location.
//
// Note 1: this will not check open oat files, which are assumed to be stale when this is run.
// Note 2: Does not register the oat file. It is the caller's job to register if the file is to
// be kept.
const OatFile* FindOatFileContainingDexFileFromDexLocation(const char* dex_location,
const uint32_t* dex_location_checksum,
InstructionSet isa,
std::vector<std::string>* error_msgs,
bool* obsolete_file_cleanup_failed)
LOCKS_EXCLUDED(dex_lock_, Locks::mutator_lock_);
// Verifies:
// - that the oat file contains the dex file (with a matching checksum, which may be null if the
// file was pre-opted)
// - the checksums of the oat file (against the image space)
// - the checksum of the dex file against dex_location_checksum
// - that the dex file can be opened
// Returns true iff all verification succeed.
//
// The dex_location is the dex location as stored in the oat file header.
// (see DexFile::GetDexCanonicalLocation for a description of location conventions)
bool VerifyOatWithDexFile(const OatFile* oat_file, const char* dex_location,
const uint32_t* dex_location_checksum,
std::string* error_msg);
mirror::ArtMethod* CreateProxyConstructor(Thread* self, Handle<mirror::Class> klass,
mirror::Class* proxy_class)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::ArtMethod* CreateProxyMethod(Thread* self, Handle<mirror::Class> klass,
Handle<mirror::ArtMethod> prototype)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Ensures that methods have the kAccPreverified bit set. We use the kAccPreverfied bit on the
// class access flags to determine whether this has been done before.
void EnsurePreverifiedMethods(Handle<mirror::Class> c)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::Class* LookupClassFromTableLocked(const char* descriptor,
const mirror::ClassLoader* class_loader,
size_t hash)
SHARED_LOCKS_REQUIRED(Locks::classlinker_classes_lock_, Locks::mutator_lock_);
mirror::Class* UpdateClass(const char* descriptor, mirror::Class* klass, size_t hash)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void MoveImageClassesToClassTable() LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
mirror::Class* LookupClassFromImage(const char* descriptor)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// EnsureResolved is called to make sure that a class in the class_table_ has been resolved
// before returning it to the caller. Its the responsibility of the thread that placed the class
// in the table to make it resolved. The thread doing resolution must notify on the class' lock
// when resolution has occurred. This happens in mirror::Class::SetStatus. As resolution may
// retire a class, the version of the class in the table is returned and this may differ from
// the class passed in.
mirror::Class* EnsureResolved(Thread* self, const char* descriptor, mirror::Class* klass)
WARN_UNUSED SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
std::vector<const DexFile*> boot_class_path_;
mutable ReaderWriterMutex dex_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
std::vector<size_t> new_dex_cache_roots_ GUARDED_BY(dex_lock_);;
std::vector<GcRoot<mirror::DexCache>> dex_caches_ GUARDED_BY(dex_lock_);
std::vector<const OatFile*> oat_files_ GUARDED_BY(dex_lock_);
// multimap from a string hash code of a class descriptor to
// mirror::Class* instances. Results should be compared for a matching
// Class::descriptor_ and Class::class_loader_.
typedef AllocationTrackingMultiMap<size_t, GcRoot<mirror::Class>, kAllocatorTagClassTable> Table;
// This contains strong roots. To enable concurrent root scanning of
// the class table, be careful to use a read barrier when accessing this.
Table class_table_ GUARDED_BY(Locks::classlinker_classes_lock_);
std::vector<std::pair<size_t, GcRoot<mirror::Class>>> new_class_roots_;
// Do we need to search dex caches to find image classes?
bool dex_cache_image_class_lookup_required_;
// Number of times we've searched dex caches for a class. After a certain number of misses we move
// the classes into the class_table_ to avoid dex cache based searches.
Atomic<uint32_t> failed_dex_cache_class_lookups_;
// indexes into class_roots_.
// needs to be kept in sync with class_roots_descriptors_.
enum ClassRoot {
kJavaLangClass,
kJavaLangObject,
kClassArrayClass,
kObjectArrayClass,
kJavaLangString,
kJavaLangDexCache,
kJavaLangRefReference,
kJavaLangReflectArtField,
kJavaLangReflectArtMethod,
kJavaLangReflectProxy,
kJavaLangStringArrayClass,
kJavaLangReflectArtFieldArrayClass,
kJavaLangReflectArtMethodArrayClass,
kJavaLangClassLoader,
kJavaLangThrowable,
kJavaLangClassNotFoundException,
kJavaLangStackTraceElement,
kPrimitiveBoolean,
kPrimitiveByte,
kPrimitiveChar,
kPrimitiveDouble,
kPrimitiveFloat,
kPrimitiveInt,
kPrimitiveLong,
kPrimitiveShort,
kPrimitiveVoid,
kBooleanArrayClass,
kByteArrayClass,
kCharArrayClass,
kDoubleArrayClass,
kFloatArrayClass,
kIntArrayClass,
kLongArrayClass,
kShortArrayClass,
kJavaLangStackTraceElementArrayClass,
kClassRootsMax,
};
GcRoot<mirror::ObjectArray<mirror::Class>> class_roots_;
mirror::Class* GetClassRoot(ClassRoot class_root) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
void SetClassRoot(ClassRoot class_root, mirror::Class* klass)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
static const char* class_roots_descriptors_[];
const char* GetClassRootDescriptor(ClassRoot class_root) {
const char* descriptor = class_roots_descriptors_[class_root];
CHECK(descriptor != NULL);
return descriptor;
}
// The interface table used by all arrays.
GcRoot<mirror::IfTable> array_iftable_;
// A cache of the last FindArrayClass results. The cache serves to avoid creating array class
// descriptors for the sake of performing FindClass.
static constexpr size_t kFindArrayCacheSize = 16;
GcRoot<mirror::Class> find_array_class_cache_[kFindArrayCacheSize];
size_t find_array_class_cache_next_victim_;
bool init_done_;
bool log_new_dex_caches_roots_ GUARDED_BY(dex_lock_);
bool log_new_class_table_roots_ GUARDED_BY(Locks::classlinker_classes_lock_);
InternTable* intern_table_;
// Trampolines within the image the bounce to runtime entrypoints. Done so that there is a single
// patch point within the image. TODO: make these proper relocations.
const void* portable_resolution_trampoline_;
const void* quick_resolution_trampoline_;
const void* portable_imt_conflict_trampoline_;
const void* quick_imt_conflict_trampoline_;
const void* quick_generic_jni_trampoline_;
const void* quick_to_interpreter_bridge_trampoline_;
friend class ImageWriter; // for GetClassRoots
friend class ImageDumper; // for FindOpenedOatFileFromOatLocation
friend class ElfPatcher; // for FindOpenedOatFileForDexFile & FindOpenedOatFileFromOatLocation
friend class NoDex2OatTest; // for FindOpenedOatFileForDexFile
friend class NoPatchoatTest; // for FindOpenedOatFileForDexFile
FRIEND_TEST(ClassLinkerTest, ClassRootDescriptors);
FRIEND_TEST(mirror::DexCacheTest, Open);
FRIEND_TEST(ExceptionTest, FindExceptionHandler);
FRIEND_TEST(ObjectTest, AllocObjectArray);
DISALLOW_COPY_AND_ASSIGN(ClassLinker);
};
} // namespace art
#endif // ART_RUNTIME_CLASS_LINKER_H_
| [
"[email protected]"
] | |
76415f474342085cb0c9ed5ce95c71bc52c1ac5b | 2f100173e4ab17b892e869316959db9b29526c1e | /source/lib/PccLibBitstreamCommon/include/PCCProfileTierLevel.h | be4746719bf6e0358f433a3bfd0deab20558ddc6 | [
"BSD-3-Clause"
] | permissive | Neutrinoant/mpeg-pcc-tmc2 | c8aa211aa5d035f660e4c10cce4aa562a88f9a36 | f3a1c659020c6ec6a88638a459371e2e093a4b44 | refs/heads/master | 2023-01-20T15:26:36.339101 | 2020-08-05T13:21:26 | 2020-08-05T13:21:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,052 | h | /* 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-2017, 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 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.
*/
#ifndef PCC_BITSTREAM_PROFILETIERLEVEL_H
#define PCC_BITSTREAM_PROFILETIERLEVEL_H
#include "PCCBitstreamCommon.h"
#include "PCCProfileToolsetConstraintsInformation.h"
namespace pcc {
// 7.3.4.2 Profile, Tier and Level Syntax
class ProfileTierLevel {
public:
ProfileTierLevel() :
tierFlag_( false ),
profileCodecGroupIdc_( 0 ),
profileToolsetIdc_( 0 ),
profileReconctructionIdc_( 0 ),
levelIdc_( 0 ),
numSubProfiles_( 0 ),
extendedSubProfileFlag_( false ),
toolConstraintsPresentFlag_( false ) {}
~ProfileTierLevel() { subProfileIdc_.clear(); }
ProfileTierLevel& operator=( const ProfileTierLevel& ) = default;
void allocate() { subProfileIdc_.resize( numSubProfiles_, 0 ); }
bool getTierFlag() { return tierFlag_; }
uint8_t getProfileCodecGroupIdc() { return profileCodecGroupIdc_; }
uint8_t getProfileToolsetIdc() { return profileToolsetIdc_; }
uint8_t getProfileReconctructionIdc() { return profileReconctructionIdc_; }
uint8_t getLevelIdc() { return levelIdc_; }
uint8_t getNumSubProfiles() { return numSubProfiles_; }
bool getExtendedSubProfileFlag() { return extendedSubProfileFlag_; }
bool getToolConstraintsPresentFlag() { return toolConstraintsPresentFlag_; }
uint8_t getSubProfileIdc( size_t index ) { return subProfileIdc_[index]; }
ProfileToolsetConstraintsInformation& getProfileToolsetConstraintsInformation() {
return profileToolsetConstraintsInformation_;
}
void setTierFlag( bool value ) { tierFlag_ = value; }
void setProfileCodecGroupIdc( uint8_t value ) { profileCodecGroupIdc_ = value; }
void setProfileToolsetIdc( uint8_t value ) { profileToolsetIdc_ = value; }
void setProfileReconctructionIdc( uint8_t value ) { profileReconctructionIdc_ = value; }
void setLevelIdc( uint8_t value ) { levelIdc_ = value; }
void setNumSubProfiles( uint8_t value ) { numSubProfiles_ = value; }
void setExtendedSubProfileFlag( bool value ) { extendedSubProfileFlag_ = value; }
void setToolConstraintsPresentFlag( bool value ) { toolConstraintsPresentFlag_ = value; }
void setSubProfileIdc( size_t index, uint8_t value ) { subProfileIdc_[index] = value; }
private:
bool tierFlag_;
uint8_t profileCodecGroupIdc_;
uint8_t profileToolsetIdc_;
uint8_t profileReconctructionIdc_;
uint8_t levelIdc_;
uint8_t numSubProfiles_;
bool extendedSubProfileFlag_;
bool toolConstraintsPresentFlag_;
std::vector<uint8_t> subProfileIdc_;
ProfileToolsetConstraintsInformation profileToolsetConstraintsInformation_;
};
}; // namespace pcc
#endif //~PCC_BITSTREAM_PROFILETIERLEVEL_H | [
"[email protected]"
] | |
7760491cd7595b90d1abd7eb6189a6013c36fdd4 | 8681c91756b2941035db515b621e32480d35ec11 | /xr_3da/xrRender_R2/DetailManager.cpp | 308324229bda35446134d8036cc3b04cbd3a7762 | [] | no_license | MaoZeDongXiJinping/xray-2212 | 1f3206c803c5fbc506114606424e2e834ffc51c0 | e143f01368c67b997f4be0dcdafb22f792bf485c | refs/heads/main | 2023-07-17T09:53:01.301852 | 2021-09-06T17:00:23 | 2021-09-06T17:00:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,016 | cpp | // DetailManager.cpp: implementation of the CDetailManager class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#pragma hdrstop
#include "DetailManager.h"
#include "cl_intersect.h"
#ifdef _EDITOR
# include "SceneClassList.h"
# include "Scene.h"
# include "SceneObject.h"
# include "igame_persistent.h"
# include "environment.h"
#else
# include "..\igame_persistent.h"
# include "..\environment.h"
#endif
const float dbgOffset = 0.f;
const int dbgItems = 128;
//--------------------------------------------------- Decompression
static int magic4x4[4][4] =
{
0, 14, 3, 13,
11, 5, 8, 6,
12, 2, 15, 1,
7, 9, 4, 10
};
void bwdithermap (int levels, int magic[16][16])
{
/* Get size of each step */
float N = 255.0f / (levels - 1);
/*
* Expand 4x4 dither pattern to 16x16. 4x4 leaves obvious patterning,
* and doesn't give us full intensity range (only 17 sublevels).
*
* magicfact is (N - 1)/16 so that we get numbers in the matrix from 0 to
* N - 1: mod N gives numbers in 0 to N - 1, don't ever want all
* pixels incremented to the next level (this is reserved for the
* pixel value with mod N == 0 at the next level).
*/
float magicfact = (N - 1) / 16;
for ( int i = 0; i < 4; i++ )
for ( int j = 0; j < 4; j++ )
for ( int k = 0; k < 4; k++ )
for ( int l = 0; l < 4; l++ )
magic[4*k+i][4*l+j] =
(int)(0.5 + magic4x4[i][j] * magicfact +
(magic4x4[k][l] / 16.) * magicfact);
}
//--------------------------------------------------- Decompression
void CDetailManager::SSwingValue::lerp(const SSwingValue& A, const SSwingValue& B, float f)
{
float fi = 1.f-f;
amp1 = fi*A.amp1 + f*B.amp1;
amp2 = fi*A.amp2 + f*B.amp2;
rot1 = fi*A.rot1 + f*B.rot1;
rot2 = fi*A.rot2 + f*B.rot2;
speed = fi*A.speed + f*B.speed;
}
//---------------------------------------------------
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CDetailManager::CDetailManager ()
{
dtFS = 0;
dtSlots = 0;
soft_Geom = 0;
hw_Geom = 0;
hw_BatchSize= 0;
hw_VB = 0;
hw_IB = 0;
}
CDetailManager::~CDetailManager ()
{
}
/*
*/
#ifndef _EDITOR
/*
void dump (CDetailManager::vis_list& lst)
{
for (int i=0; i<lst.size(); i++)
{
Msg("%8x / %8x / %8x", lst[i]._M_start, lst[i]._M_finish, lst[i]._M_end_of_storage._M_data);
}
}
*/
void CDetailManager::Load ()
{
// Open file stream
if (!FS.exist("$level$","level.details"))
{
dtFS = NULL;
return;
}
string256 fn;
FS.update_path (fn,"$level$","level.details");
dtFS = FS.r_open(fn);
// Header
dtFS->r_chunk_safe (0,&dtH,sizeof(dtH));
R_ASSERT (dtH.version == DETAIL_VERSION);
u32 m_count = dtH.object_count;
// Models
IReader* m_fs = dtFS->open_chunk(1);
for (u32 m_id = 0; m_id < m_count; m_id++)
{
CDetail* dt = xr_new<CDetail> ();
IReader* S = m_fs->open_chunk(m_id);
dt->Load (S);
objects.push_back (dt);
S->close ();
}
m_fs->close ();
// Get pointer to database (slots)
IReader* m_slots = dtFS->open_chunk(2);
dtSlots = (DetailSlot*)m_slots->pointer();
m_slots->close ();
// Initialize 'vis' and 'cache'
visible[0].resize (objects.size()); // dump(visible[0]);
visible[1].resize (objects.size()); // dump(visible[1]);
visible[2].resize (objects.size()); // dump(visible[2]);
cache_Initialize ();
// Make dither matrix
bwdithermap (2,dither);
// Hardware specific optimizations
if (UseVS()) hw_Load ();
else soft_Load ();
// swing desc
// normal
swing_desc[0].amp1 = .1f;
swing_desc[0].amp2 = .05f;
swing_desc[0].rot1 = 30.f;
swing_desc[0].rot2 = 1.f;
swing_desc[0].speed = 2.f;
// fast
swing_desc[1].amp1 = 1.f;
swing_desc[1].amp2 = .5f;
swing_desc[1].rot1 = .01f;
swing_desc[1].rot2 = .9f;
swing_desc[1].speed = 1.f;
}
#endif
void CDetailManager::Unload ()
{
if (UseVS()) hw_Unload ();
else soft_Unload ();
for (DetailIt it=objects.begin(); it!=objects.end(); it++){
(*it)->Unload();
xr_delete (*it);
}
objects.clear ();
visible[0].clear();
visible[1].clear();
visible[2].clear();
xr_delete (dtFS);
}
extern ECORE_API float r_ssaDISCARD;
void CDetailManager::Render ()
{
#ifndef _EDITOR
if (0==dtFS) return;
if (!psDeviceFlags.is(rsDetails)) return;
#endif
float factor = g_pGamePersistent->Environment.wind_strength;
swing_current.lerp (swing_desc[0],swing_desc[1],factor);
float r_ssaCHEAP = 16*r_ssaDISCARD;
Fvector EYE = Device.vCameraPosition;
CFrustum View = RImplementation.ViewBase;
int s_x = iFloor (EYE.x/dm_slot_size+.5f);
int s_z = iFloor (EYE.z/dm_slot_size+.5f);
Device.Statistic.RenderDUMP_DT_Cache.Begin ();
cache_Update (s_x,s_z,EYE,dm_max_decompress);
Device.Statistic.RenderDUMP_DT_Cache.End ();
float fade_limit = dm_fade; fade_limit=fade_limit*fade_limit;
float fade_start = 1.f; fade_start=fade_start*fade_start;
float fade_range = fade_limit-fade_start;
// Collect objects for rendering
Device.Statistic.RenderDUMP_DT_VIS.Begin ();
for (int _z=-dm_size; _z<=dm_size; _z++)
{
for (int _x=-dm_size; _x<=dm_size; _x++)
{
// Query for slot
Slot* CS = cache_Query(_x,_z);
Slot& S = *CS;
// Transfer visibile and partially visible slot contents
u32 mask = 0xff;
u32 res = View.testSAABB (S.vis.sphere.P,S.vis.sphere.R,S.vis.box.data(),mask);
if (fcvNone==res) continue; // invisible-view frustum
#ifdef _EDITOR
if (!RImplementation.occ_visible(S.vis)) continue; // invisible-occlusion
#else
if (!RImplementation.HOM.visible(S.vis)) continue; // invisible-occlusion
#endif
// Calc fade factor (per slot)
float dist_sq = EYE.distance_to_sqr (S.vis.sphere.P);
if (dist_sq>fade_limit) continue;
float alpha = (dist_sq<fade_start)?0.f:(dist_sq-fade_start)/fade_range;
float alpha_i = 1.f - alpha;
float dist_sq_rcp = 1.f / dist_sq;
// Add to visibility structures
for (int sp_id=0; sp_id<dm_obj_in_slot; sp_id++)
{
SlotPart& sp = S.G [sp_id];
if (sp.id==DetailSlot::ID_Empty) continue;
float R = objects [sp.id]->bv_sphere.R;
float Rq_drcp = R*R*dist_sq_rcp; // reordered expression for 'ssa' calc
SlotItem **siIT=&(*sp.items.begin()), **siEND=&(*sp.items.end());
for (; siIT!=siEND; siIT++)
{
SlotItem& Item = *(*siIT);
float scale = Item.scale_calculated = Item.scale*alpha_i;
float ssa = scale*scale*Rq_drcp;
if (ssa < r_ssaDISCARD) continue;
u32 vis_id = 0;
if (ssa > r_ssaCHEAP) vis_id = Item.vis_ID;
visible[vis_id][sp.id].push_back (*siIT);
}
}
}
}
Device.Statistic.RenderDUMP_DT_VIS.End ();
Device.Statistic.RenderDUMP_DT_Render.Begin ();
RCache.set_CullMode (CULL_NONE);
RCache.set_xform_world (Fidentity);
if (UseVS()) hw_Render ();
else soft_Render ();
RCache.set_CullMode (CULL_CCW);
Device.Statistic.RenderDUMP_DT_Render.End ();
}
| [
"[email protected]"
] | |
6b9b0a73c76f7a7460a1e06a6408864c9d98673e | 98410335456794507c518e361c1c52b6a13b0b39 | /sprayMASCOTTELAM2/0.06/H2O | 34aed21ccae7b6d5ca11a19b78724048d53b5bf6 | [] | no_license | Sebvi26/MASCOTTE | d3d817563f09310dfc8c891d11b351ec761904f3 | 80241928adec6bcaad85dca1f2159f6591483986 | refs/heads/master | 2022-10-21T03:19:24.725958 | 2020-06-14T21:19:38 | 2020-06-14T21:19:38 | 270,176,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format binary;
class volScalarField;
location "0.06";
object H2O;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 0;
boundaryField
{
inlet
{
type fixedValue;
value uniform 0;
}
outlet
{
type zeroGradient;
}
bottom1
{
type zeroGradient;
}
bottom2
{
type zeroGradient;
}
top1
{
type zeroGradient;
}
top2
{
type zeroGradient;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
681753a05a8234e93ef12dd1b99ad9d05bebc899 | 229f25ccda6d721f31c6d4de27a7bb85dcc0f929 | /solutions/spoj/KOPC12A - K12 - Building Construction/solution.cpp | 3893efe7f8aa44af48cb6b543bb68804e40391a9 | [] | no_license | camil0palacios/Competitive-programming | e743378a8791a66c90ffaae29b4fd4cfb58fff59 | 4211fa61e516cb986b3404d87409ad1a49f78132 | refs/heads/master | 2022-11-01T20:35:21.541132 | 2022-10-27T03:13:42 | 2022-10-27T03:13:42 | 155,419,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | #include <bits/stdc++.h>
#define endl '\n'
#define ll long long
#define fori(i,a,b) for(int i = a; i < b; i++)
#define forr(i,a,b) for(int i = a; i >= b; i--)
#define fore(i,a,b) for(int i = a; i <= b; i++)
#define ft first
#define sd second
#define all(v) v.begin(), v.end()
#define sz(v) (int) v.size()
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define ar array
using namespace std;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef vector<ii> vii;
typedef vector<ll> vl;
const int Mxn = 1e5 + 5;
int n;
int h[Mxn];
int c[Mxn];
ll f(int x) {
ll ans = 0;
fori(i,0,n)
ans += 1ll*abs(x - h[i])*c[i];
return ans;
}
void solve() {
cin >> n;
fori(i,0,n) cin >> h[i];
fori(i,0,n) cin >> c[i];
int l = 0, r = 10005;
fori(i,0,100) {
int m1 = l + (r - l) / 3;
int m2 = r - (r - l) / 3;
if(f(m1) <= f(m2)) r = m2;
else l = m1;
}
ll ans = f((l+r)/2);
cout << ans << endl;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int t;
cin >> t;
while(t--) solve();
return 0;
} | [
"[email protected]"
] | |
8ff8a4844966fca80170df9a389c1017425a3141 | bb5ef04be3fd69e5fd0c51eb04d658509fbfcceb | /src/test/ItemAttTest.cpp | cbe641140c5a66df26f463640a080adc8900bb97 | [
"Artistic-2.0",
"MIT"
] | permissive | Kreyren/pwsafe | 29d17ea5e328a27d97c51f1b2712c518d01fa560 | fce797e839e3cbe767eff431012a5b838f527565 | refs/heads/master | 2022-08-04T05:40:39.974326 | 2020-05-28T16:47:26 | 2020-05-28T16:47:26 | 267,818,847 | 0 | 0 | NOASSERTION | 2020-05-30T14:50:07 | 2020-05-29T09:30:10 | null | UTF-8 | C++ | false | false | 5,098 | cpp | /*
* Copyright (c) 2003-2020 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
// ItemAttTest.cpp: Unit test for CItemAtt class
#ifdef WIN32
#include "../ui/Windows/stdafx.h"
#endif
#include "core/ItemAtt.h"
#include "core/PWScore.h"
#include "os/file.h"
#include "os/dir.h"
#include "os/debug.h"
#include "gtest/gtest.h"
#include <vector>
using namespace std;
// A fixture for factoring common code across tests
class ItemAttTest : public ::testing::Test
{
protected:
ItemAttTest(); // to init members
void SetUp();
// members used to populate and test fullItem:
const StringX title, mediaType;
stringT fullfileName, fileName, filePath;
};
ItemAttTest::ItemAttTest()
: title(_T("a-title")), mediaType(_T("application/octet-stream"))
{
fullfileName = pws_os::fullpath(L"data/image1.jpg");
stringT sDrive, sDir, sFName, sExtn;
pws_os::splitpath(fullfileName, sDrive, sDir, sFName, sExtn);
fileName = sFName + sExtn;
filePath = sDrive + sDir;
}
void ItemAttTest::SetUp()
{
}
// And now the tests...
TEST_F(ItemAttTest, EmptyItems)
{
CItemAtt ai1, ai2;
EXPECT_TRUE(ai1 == ai2);
ai1.SetTitle(title);
EXPECT_FALSE(ai1 == ai2);
ai2.SetTitle(title);
EXPECT_TRUE(ai1 == ai2);
}
TEST_F(ItemAttTest, UUIDs)
{
CItemAtt ai1, ai2;
EXPECT_FALSE(ai1.HasUUID());
ai1.CreateUUID();
ai2.CreateUUID();
EXPECT_FALSE(ai1 == ai2);
ai2.SetUUID(ai1.GetUUID());
EXPECT_TRUE(ai1 == ai2);
}
TEST_F(ItemAttTest, ImpExp)
{
const stringT testImpFile(fullfileName);
const stringT testExpFile(L"output.tmp");
CItemAtt ai;
int status;
status = ai.Import(L"nosuchfile");
EXPECT_EQ(PWScore::CANT_OPEN_FILE, status);
EXPECT_EQ(L"", ai.GetFileName());
EXPECT_FALSE(ai.HasContent());
status = ai.Import(testImpFile);
EXPECT_EQ(PWScore::SUCCESS, status);
EXPECT_STREQ(fileName.c_str(), ai.GetFileName().c_str());
EXPECT_STREQ(filePath.c_str(), ai.GetFilePath().c_str());
EXPECT_TRUE(ai.HasContent());
status = ai.Export(testExpFile);
EXPECT_EQ(PWScore::SUCCESS, status);
EXPECT_TRUE(pws_os::FileExists(testExpFile));
FILE *f1 = pws_os::FOpen(testImpFile, L"rb");
FILE *f2 = pws_os::FOpen(testExpFile, L"rb");
EXPECT_EQ(pws_os::fileLength(f1), pws_os::fileLength(f2));
size_t flen = static_cast<size_t>(pws_os::fileLength(f1));
unsigned char *m1 = new unsigned char[flen];
unsigned char *m2 = new unsigned char[flen];
ASSERT_EQ(1U, fread(m1, flen, 1, f1));
ASSERT_EQ(1U, fread(m2, flen, 1, f2));
fclose(f1); fclose(f2);
EXPECT_EQ(0, memcmp(m1, m2, flen));
delete[] m1; delete[] m2;
pws_os::DeleteAFile(testExpFile);
}
TEST_F(ItemAttTest, CopyCtor)
{
const stringT testImpFile(fullfileName);
CItemAtt ea1;
CItemAtt ea2(ea1);
EXPECT_TRUE(ea1 == ea2);
CItemAtt a1;
a1.SetTitle(title);
int status = a1.Import(testImpFile);
ASSERT_EQ(PWScore::SUCCESS, status);
CItemAtt a2(a1);
EXPECT_TRUE(a1 == a2);
}
TEST_F(ItemAttTest, Getters_n_Setters)
{
CItemAtt ai;
pws_os::CUUID uuid;
time_t cTime = 1425836169;
unsigned char content[122] = {0xff, 0x00, 0xb4, 0x65, 0xfc, 0x91, 0xfb, 0xbf,
0xe0, 0x8f, 0xea, 0x6b, 0xf9, 0x9f, 0xde, 0x1f,
0x62, 0xd6, 0xbf, 0xe8, 0x2f, 0xfb, 0x2c, 0xff,
0x00, 0xe0, 0xf3, 0xe1, 0xff, 0x00, 0xff, 0x00,
0x1d, 0xa5, 0x5b, 0x2d, 0x67, 0xbe, 0xaf, 0xfb,
0x2c, 0xff, 0x00, 0xe0, 0xf3, 0xc0, 0x1f, 0xfc,
0x76, 0x8a, 0x29, 0x7f, 0x68, 0x4b, 0xf9, 0x23,
0xf7, 0x7f, 0xc1, 0x1f, 0xd4, 0xd7, 0xf3, 0x3f,
0xbc, 0x5f, 0xb1, 0x6b, 0x1f, 0xf4, 0x17, 0xfd,
0x96, 0x7f, 0xf0, 0x79, 0xe0, 0x0f, 0xfe, 0x3b,
0x47, 0xd8, 0xb5, 0x8f, 0xfa, 0x0b, 0xfe, 0xcb,
0x3f, 0xf8, 0x3c, 0xf0, 0x07, 0xff, 0x00, 0x1d,
0xa2, 0x8a, 0x3f, 0xb4, 0x25, 0xfc, 0x91, 0xfb,
0xbf, 0xe0, 0x8b, 0xea, 0x6b, 0xf9, 0x9f, 0xde,
0xb0, 0xf1, 0xa7, 0xef, 0xa6, 0xdb, 0xf3, 0x3f,
0xff, 0xd9};
ai.SetUUID(uuid);
ai.SetTitle(title);
ai.SetCTime(cTime);
ai.SetContent(content, sizeof(content));
time_t tVal = 0;
unsigned char *contentVal;
EXPECT_EQ(uuid, ai.GetUUID());
EXPECT_EQ(title, ai.GetTitle());
EXPECT_EQ(cTime, ai.GetCTime(tVal));
ASSERT_EQ(sizeof(content), ai.GetContentLength());
size_t contentSize = ai.GetContentSize();
contentVal = new unsigned char[contentSize];
EXPECT_FALSE(ai.GetContent(contentVal, contentSize - 1));
EXPECT_TRUE(ai.GetContent(contentVal, contentSize));
EXPECT_EQ(0, memcmp(content, contentVal, sizeof(content)));
delete[] contentVal;
}
| [
"[email protected]"
] | |
5c636a304d932bff41179d494a8a8e41e9b46d60 | ffb447710501c202ad63bbe05005193c769db9ef | /PluginTestAPI.h | 200190b920e751d2c907574f7c25b102666b01eb | [] | no_license | qiwenz/EEGPluginMAC | 2b4c3209b0daf84dc073b007c664864f931b9aa7 | e41ad2fc4daae4a753b84c76e7885b9594f7310c | refs/heads/master | 2020-04-27T23:09:22.042688 | 2014-03-22T23:45:50 | 2014-03-22T23:45:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,891 | h | /**********************************************************\
Auto-generated PluginTestAPI.h
\**********************************************************/
#include <string>
#include <sstream>
#include <boost/weak_ptr.hpp>
#include "JSAPIAuto.h"
#include "BrowserHost.h"
#include "PluginTest.h"
#ifndef H_PluginTestAPI
#define H_PluginTestAPI
class PluginTestAPI : public FB::JSAPIAuto
{
public:
////////////////////////////////////////////////////////////////////////////
/// @fn PluginTestAPI::PluginTestAPI(const PluginTestPtr& plugin, const FB::BrowserHostPtr host)
///
/// @brief Constructor for your JSAPI object.
/// You should register your methods, properties, and events
/// that should be accessible to Javascript from here.
///
/// @see FB::JSAPIAuto::registerMethod
/// @see FB::JSAPIAuto::registerProperty
/// @see FB::JSAPIAuto::registerEvent
////////////////////////////////////////////////////////////////////////////
PluginTestAPI(const PluginTestPtr& plugin, const FB::BrowserHostPtr& host) :
m_plugin(plugin), m_host(host)
{
registerMethod("echo", make_method(this, &PluginTestAPI::echo));
registerMethod("testEvent", make_method(this, &PluginTestAPI::testEvent));
// Read-write property
registerProperty("testString",
make_property(this,
&PluginTestAPI::get_testString,
&PluginTestAPI::set_testString));
// Read-only property
registerProperty("version",
make_property(this,
&PluginTestAPI::get_version));
}
///////////////////////////////////////////////////////////////////////////////
/// @fn PluginTestAPI::~PluginTestAPI()
///
/// @brief Destructor. Remember that this object will not be released until
/// the browser is done with it; this will almost definitely be after
/// the plugin is released.
///////////////////////////////////////////////////////////////////////////////
virtual ~PluginTestAPI() {};
PluginTestPtr getPlugin();
// Read/Write property ${PROPERTY.ident}
std::string get_testString();
void set_testString(const std::string& val);
// Read-only property ${PROPERTY.ident}
std::string get_version();
void siginthandler(int sig);
FB::variant connect();
// Method echo
FB::variant echo(const FB::variant& msg);
// Event helpers
FB_JSAPI_EVENT(test, 0, ());
FB_JSAPI_EVENT(echo, 2, (const FB::variant&, const int));
// Method test-event
void testEvent();
private:
PluginTestWeakPtr m_plugin;
FB::BrowserHostPtr m_host;
std::string m_testString;
};
#endif // H_PluginTestAPI
| [
"[email protected]"
] | |
2653e6391d73e26c11c4398f866334246bf7f46a | d305e9667f18127e4a1d4d65e5370cf60df30102 | /mindspore/ccsrc/backend/optimizer/ascend/ir_fusion/clip_by_value_fusion.h | c78542bf542b90d642d799e39bb4634e360c749d | [
"Apache-2.0",
"MIT",
"Libpng",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"AGPL-3.0-only",
"MPL-2.0-no-copyleft-exception",
"IJG",
"Zlib",
"MPL-1.1",
"BSD-3-Clause",
"BSD-3-Clause-Open-MPI",
"MPL-1.0",
"GPL-2.0-only",
"MPL-2.0",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | imyzx2017/mindspore_pcl | d8e5bd1f80458538d07ef0a8fc447b552bd87420 | f548c9dae106879d1a83377dd06b10d96427fd2d | refs/heads/master | 2023-01-13T22:28:42.064535 | 2020-11-18T11:15:41 | 2020-11-18T11:15:41 | 313,906,414 | 6 | 1 | Apache-2.0 | 2020-11-18T11:25:08 | 2020-11-18T10:57:26 | null | UTF-8 | C++ | false | false | 1,546 | h | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MINDSPORE_CCSRC_BACKEND_OPTIMIZER_ASCEND_IR_FUSION_CLIP_BY_VALUE_FUSION_H_
#define MINDSPORE_CCSRC_BACKEND_OPTIMIZER_ASCEND_IR_FUSION_CLIP_BY_VALUE_FUSION_H_
#include <memory>
#include "backend/optimizer/common/optimizer.h"
namespace mindspore {
namespace opt {
class ClipByValueFusion : public PatternProcessPass {
public:
explicit ClipByValueFusion(bool multigraph = true) : PatternProcessPass("clip_by_value_fusion", multigraph) {
maximum_input0_ = std::make_shared<Var>();
maximum_input1_ = std::make_shared<Var>();
}
~ClipByValueFusion() override = default;
const BaseRef DefinePattern() const override;
const AnfNodePtr Process(const FuncGraphPtr &, const AnfNodePtr &, const EquivPtr &) const override;
private:
VarPtr maximum_input0_;
VarPtr maximum_input1_;
};
} // namespace opt
} // namespace mindspore
#endif // MINDSPORE_CCSRC_BACKEND_OPTIMIZER_ASCEND_IR_FUSION_CLIP_BY_VALUE_FUSION_H_
| [
"[email protected]"
] | |
7d61fc14759ecace5c4aa9ec7c244d9445a29aa9 | 485faf9d4ec7def9a505149c6a491d6133e68750 | /include/dsm/CDAVServerInfo.H | 7d811b2c7301e0f0bebffa2da12dcfb779de0018 | [
"LicenseRef-scancode-warranty-disclaimer",
"ECL-2.0"
] | permissive | ohlincha/ECCE | af02101d161bae7e9b05dc7fe6b10ca07f479c6b | 7461559888d829338f29ce5fcdaf9e1816042bfe | refs/heads/master | 2020-06-25T20:59:27.882036 | 2017-06-16T10:45:21 | 2017-06-16T10:45:21 | 94,240,259 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,156 | h | // CDAVServerInfo.H
// Created: 05/10/2000
// Version: 05/10/2000
//
// Description:
//
// Modifications:
#if !defined( __CDAVSERVERINFO_H )
#define __CDAVSERVERINFO_H // prevent multiple includes
// include files ***********************************************************
#include "dsm/CHTTPServerInfo.H"
#include "dsm/CDAVHeader.H"
// class: CDAVServerInfo ***************************************************
class CDAVServerInfo : public CHTTPServerInfo
{
public :
typedef CHTTPServerInfo parent;
// Constructors
CDAVServerInfo(void)
: parent(), isDAVServer_(false), supportLocks_(false) {}
CDAVServerInfo(const CDAVHeader& h)
: parent(), isDAVServer_(false), supportLocks_(false) { getInfo(h); }
CDAVServerInfo(const CDAVServerInfo& other)
: parent(), isDAVServer_(other.isDAVServer_),
supportLocks_(other.supportLocks_) {}
// Destructor
virtual ~CDAVServerInfo(void) {}
// Assignment operator
CDAVServerInfo& operator = (const CDAVServerInfo& other)
{
parent::operator = (other);
isDAVServer_ = other.isDAVServer_;
supportLocks_ = other.supportLocks_;
return *this;
}
// Clear current values
virtual void clear(void)
{ parent::clear(); isDAVServer_ = supportLocks_ = false; }
// Get server information from headers
virtual void getInfo(const CDAVHeader&);
virtual void getInfo(const CHTTPHeader& h) { parent::getInfo(h); }
// Return true is the server is known to be a DAV server.
// Return false otherwise.
virtual bool isDAVServer(void) const { return isDAVServer_; }
// Return true is the server supports DAV locks
// Return false otherwise.
virtual bool supportLocks(void) const { return supportLocks_; }
protected :
bool isDAVServer_, // is this really a DAV server?
supportLocks_; // does it support DAV locks?
// If <m> is a valid method string, return it's numeric value.
// Return -1 if invalid.
// NOTE: This version uses CDAVRequest::stringToMethod()
virtual int methodToInt(const string_type& m) const;
};
#endif // __CDAVSERVERINFO_H
// end of CDAVServerInfo.H *************************************************
| [
"[email protected]"
] | |
495651f01c5668feb0060987cab29748ae3cd3f3 | 31ac07ecd9225639bee0d08d00f037bd511e9552 | /externals/OCCTLib/inc/TColStd_ListIteratorOfSetListOfSetOfTransient.hxx | 58915d0d13ef4d3c47ef3442cc355d4106924b17 | [] | no_license | litao1009/SimpleRoom | 4520e0034e4f90b81b922657b27f201842e68e8e | 287de738c10b86ff8f61b15e3b8afdfedbcb2211 | refs/heads/master | 2021-01-20T19:56:39.507899 | 2016-07-29T08:01:57 | 2016-07-29T08:01:57 | 64,462,604 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,925 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _TColStd_ListIteratorOfSetListOfSetOfTransient_HeaderFile
#define _TColStd_ListIteratorOfSetListOfSetOfTransient_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineAlloc_HeaderFile
#include <Standard_DefineAlloc.hxx>
#endif
#ifndef _Standard_Macro_HeaderFile
#include <Standard_Macro.hxx>
#endif
#ifndef _Standard_Address_HeaderFile
#include <Standard_Address.hxx>
#endif
#ifndef _Handle_Standard_Transient_HeaderFile
#include <Handle_Standard_Transient.hxx>
#endif
#ifndef _Handle_TColStd_ListNodeOfSetListOfSetOfTransient_HeaderFile
#include <Handle_TColStd_ListNodeOfSetListOfSetOfTransient.hxx>
#endif
#ifndef _Standard_Boolean_HeaderFile
#include <Standard_Boolean.hxx>
#endif
class Standard_NoMoreObject;
class Standard_NoSuchObject;
class TColStd_SetListOfSetOfTransient;
class Standard_Transient;
class TColStd_ListNodeOfSetListOfSetOfTransient;
class TColStd_ListIteratorOfSetListOfSetOfTransient {
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT TColStd_ListIteratorOfSetListOfSetOfTransient();
Standard_EXPORT TColStd_ListIteratorOfSetListOfSetOfTransient(const TColStd_SetListOfSetOfTransient& L);
Standard_EXPORT void Initialize(const TColStd_SetListOfSetOfTransient& L) ;
Standard_Boolean More() const;
Standard_EXPORT void Next() ;
Standard_EXPORT Handle_Standard_Transient& Value() const;
friend class TColStd_SetListOfSetOfTransient;
protected:
private:
Standard_Address current;
Standard_Address previous;
};
#define Item Handle_Standard_Transient
#define Item_hxx <Standard_Transient.hxx>
#define TCollection_ListNode TColStd_ListNodeOfSetListOfSetOfTransient
#define TCollection_ListNode_hxx <TColStd_ListNodeOfSetListOfSetOfTransient.hxx>
#define TCollection_ListIterator TColStd_ListIteratorOfSetListOfSetOfTransient
#define TCollection_ListIterator_hxx <TColStd_ListIteratorOfSetListOfSetOfTransient.hxx>
#define Handle_TCollection_ListNode Handle_TColStd_ListNodeOfSetListOfSetOfTransient
#define TCollection_ListNode_Type_() TColStd_ListNodeOfSetListOfSetOfTransient_Type_()
#define TCollection_List TColStd_SetListOfSetOfTransient
#define TCollection_List_hxx <TColStd_SetListOfSetOfTransient.hxx>
#include <TCollection_ListIterator.lxx>
#undef Item
#undef Item_hxx
#undef TCollection_ListNode
#undef TCollection_ListNode_hxx
#undef TCollection_ListIterator
#undef TCollection_ListIterator_hxx
#undef Handle_TCollection_ListNode
#undef TCollection_ListNode_Type_
#undef TCollection_List
#undef TCollection_List_hxx
// other Inline functions and methods (like "C++: function call" methods)
#endif
| [
"[email protected]"
] | |
dd9d871c873a5a96330f2559e0c2fcd2762325a6 | d49553002c4e981a818adc060464f3aa01cf43e8 | /branch/0.2.x/pykd/stkframe.cpp | 3cbc608261d8114b438939100fa2e250bf5818d6 | [] | no_license | QuincyWork/Python-extension-for-WinDbg | 1e483c1d03d3cb52bdd87ef40d66edfa9d63a937 | 81d8d991f839a6d9639cda17c349335e81d4ad45 | refs/heads/master | 2021-05-15T09:45:36.627637 | 2017-10-24T09:54:51 | 2017-10-24T09:54:51 | 108,106,581 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 19,068 | cpp | //
// Stack frame: DEBUG_STACK_FRAME wrapper
//
#include "stdafx.h"
#include "stkframe.h"
#include "dbgengine.h"
#include "module.h"
////////////////////////////////////////////////////////////////////////////////
namespace pykd {
////////////////////////////////////////////////////////////////////////////////
StackFrame::StackFrame( const STACK_FRAME_DESC& desc )
{
m_frameNumber = desc.number;
m_instructionOffset = desc.instructionOffset;
m_returnOffset = desc.returnOffset;
m_frameOffset = desc.frameOffset;
m_stackOffset = desc.stackOffset;
}
////////////////////////////////////////////////////////////////////////////////
std::string StackFrame::print() const
{
std::stringstream sstream;
sstream << std::dec << "(" << m_frameNumber << ")";
sstream << " ip= 0x" << std::hex << m_instructionOffset;
sstream << ", ret= 0x" << std::hex << m_returnOffset;
sstream << ", frame= 0x" << std::hex << m_frameOffset;
sstream << ", stack= 0x" << std::hex << m_stackOffset;
return sstream.str();
}
////////////////////////////////////////////////////////////////////////////////
ScopeVarsPtr StackFrame::getLocals()
{
return ScopeVarsPtr( new LocalVars( shared_from_this() ) );
}
///////////////////////////////////////////////////////////////////////////////
ScopeVarsPtr StackFrame::getParams()
{
return ScopeVarsPtr( new FunctionParams( shared_from_this() ) );
}
///////////////////////////////////////////////////////////////////////////////
ULONG64 StackFrame::getValue(RegRealativeId rri, LONG64 offset /*= 0*/) const
{
switch (rri)
{
case rriInstructionPointer: return m_instructionOffset + offset;
case rriStackFrame: return m_frameOffset + offset;
case rriStackPointer: return m_stackOffset + offset;
}
BOOST_ASSERT(!"Unexcepted error");
throw DbgException(__FUNCTION__ " Unexcepted error" );
}
////////////////////////////////////////////////////////////////////////////////
static bool IsInDebugRange(
SymbolPtr func,
ULONG ipRva
)
{
SymbolPtrList lstFuncDebugStart;
SymbolPtrList lstFuncDebugEnd;
try
{
lstFuncDebugStart = func->findChildren(SymTagFuncDebugStart);
if (1 != lstFuncDebugStart.size())
{
BOOST_ASSERT(lstFuncDebugStart.empty());
return true;
}
lstFuncDebugEnd = func->findChildren(SymTagFuncDebugEnd);
if (1 != lstFuncDebugEnd.size())
{
BOOST_ASSERT(lstFuncDebugEnd.empty());
return true;
}
}
catch (const SymbolException &except)
{
DBG_UNREFERENCED_PARAMETER(except);
return true;
}
return
((*lstFuncDebugStart.begin())->getRva() <= ipRva) &&
((*lstFuncDebugEnd.begin())->getRva() >= ipRva);
}
python::object StackFrame::getLocalByName( const std::string& name )
{
ModulePtr mod = Module::loadModuleByOffset( m_instructionOffset);
LONG displacemnt;
SymbolPtr func = mod->getSymbolByVa( m_instructionOffset, SymTagFunction, &displacemnt );
#ifdef _DEBUG
std::string funcName;
funcName = func->getName();
#endif // _DEBUG
if (!IsInDebugRange(func, static_cast<ULONG>( m_instructionOffset - mod->getBase())))
{
throw DbgException("is not debug range");
}
// find var in current scope
SymbolPtrList symList = func->findChildren(SymTagData);
SymbolPtrList::iterator itVar = symList.begin();
SymbolPtr symVar;
for (; itVar != symList.end(); ++itVar)
{
if ( (*itVar)->getName() == name )
{
symVar = *itVar;
break;
}
}
if ( itVar == symList.end() )
{
// find inners scopes
SymbolPtrList scopeList = func->findChildren(SymTagBlock);
SymbolPtrList::iterator itScope = scopeList.begin();
ULONG ipRva = static_cast<ULONG>( m_instructionOffset - mod->getBase());
for (; itScope != scopeList.end() && !symVar; ++itScope)
{
SymbolPtr scope = *itScope;
ULONG scopeRva = scope->getRva();
if (scopeRva <= ipRva && (scopeRva + scope->getSize()) > ipRva)
{
SymbolPtrList symList = scope->findChildren(SymTagData);
SymbolPtrList::iterator itVar = symList.begin();
for (; itVar != symList.end(); ++itVar)
{
if ( (*itVar)->getName() == name )
{
symVar = *itVar;
break;
}
}
}
}
}
if ( !symVar )
throw DbgException("local var not found");
ULONG64 varAddr;
const LocationType locType = static_cast<LocationType>(symVar->getLocType());
switch (locType)
{
case LocIsStatic:
varAddr = mod->getBase() + symVar->getRva();
break;
case LocIsRegRel:
{
RegRealativeId rri;
rri = static_cast<RegRealativeId>(symVar->getRegRealativeId());
varAddr = getValue(rri, symVar->getOffset());
}
break;
default:
BOOST_ASSERT(LocIsEnregistered == locType);
throw DbgException("");
}
TypeInfoPtr typeInfo = TypeInfo::getTypeInfo(symVar);
TypedVarPtr typedVar = TypedVar::getTypedVarByTypeInfo(typeInfo, varAddr);
typedVar->setDataKind( symVar->getDataKind() );
return python::object( typedVar );
}
////////////////////////////////////////////////////////////////////////////////
python::object StackFrame::getParamByName( const std::string& name )
{
ModulePtr mod = Module::loadModuleByOffset( m_instructionOffset);
LONG displacemnt;
SymbolPtr func = mod->getSymbolByVa( m_instructionOffset, SymTagFunction, &displacemnt );
#ifdef _DEBUG
std::string funcName;
funcName = func->getName();
#endif // _DEBUG
if (!IsInDebugRange(func, static_cast<ULONG>( m_instructionOffset - mod->getBase())))
{
throw DbgException("is not debug range");
}
// find var in current scope
SymbolPtrList symList = func->findChildren(SymTagData);
SymbolPtrList::iterator itVar = symList.begin();
SymbolPtr symVar;
for (; itVar != symList.end(); ++itVar)
{
if ( (*itVar)->getDataKind() == DataIsParam && (*itVar)->getName() == name )
{
symVar = *itVar;
break;
}
}
if ( !symVar )
throw DbgException("local var not found");
ULONG64 varAddr;
const LocationType locType = static_cast<LocationType>(symVar->getLocType());
switch (locType)
{
case LocIsStatic:
varAddr = mod->getBase() + symVar->getRva();
break;
case LocIsRegRel:
{
RegRealativeId rri;
rri = static_cast<RegRealativeId>(symVar->getRegRealativeId());
varAddr = getValue(rri, symVar->getOffset());
}
break;
default:
BOOST_ASSERT(LocIsEnregistered == locType);
throw DbgException("");
}
TypeInfoPtr typeInfo = TypeInfo::getTypeInfo(symVar);
TypedVarPtr typedVar = TypedVar::getTypedVarByTypeInfo(typeInfo, varAddr);
typedVar->setDataKind( symVar->getDataKind() );
return python::object( typedVar );
}
////////////////////////////////////////////////////////////////////////////////
bool StackFrame::isContainsLocal( const std::string& name )
{
ModulePtr mod = Module::loadModuleByOffset( m_instructionOffset);
LONG displacemnt;
SymbolPtr func;
try {
func = mod->getSymbolByVa( m_instructionOffset, SymTagFunction, &displacemnt );
}
catch(SymbolException&)
{
return false;
}
#ifdef _DEBUG
std::string funcName;
funcName = func->getName();
#endif // _DEBUG
if (!IsInDebugRange(func, static_cast<ULONG>( m_instructionOffset - mod->getBase())))
{
return false;
}
// find var in current scope
SymbolPtrList symList = func->findChildren(SymTagData);
SymbolPtrList::iterator itVar = symList.begin();
for (; itVar != symList.end(); ++itVar)
{
if ( (*itVar)->getName() == name )
{
return true;
}
}
if ( itVar == symList.end() )
{
// find inners scopes
SymbolPtrList scopeList = func->findChildren(SymTagBlock);
SymbolPtrList::iterator itScope = scopeList.begin();
ULONG ipRva = static_cast<ULONG>( m_instructionOffset - mod->getBase());
for (; itScope != scopeList.end(); ++itScope)
{
SymbolPtr scope = *itScope;
ULONG scopeRva = scope->getRva();
if (scopeRva <= ipRva && (scopeRva + scope->getSize()) > ipRva)
{
SymbolPtrList symList = scope->findChildren(SymTagData);
SymbolPtrList::iterator itVar = symList.begin();
for (; itVar != symList.end(); ++itVar)
{
if ( (*itVar)->getName() == name )
{
return true;
}
}
}
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool StackFrame::isContainsParam( const std::string& name )
{
ModulePtr mod = Module::loadModuleByOffset( m_instructionOffset);
LONG displacemnt;
SymbolPtr func;
try {
func = mod->getSymbolByVa( m_instructionOffset, SymTagFunction, &displacemnt );
}
catch(SymbolException&)
{
return false;
}
#ifdef _DEBUG
std::string funcName;
funcName = func->getName();
#endif // _DEBUG
if (!IsInDebugRange(func, static_cast<ULONG>( m_instructionOffset - mod->getBase())))
{
return false;
}
// find var in current scope
SymbolPtrList symList = func->findChildren(SymTagData);
SymbolPtrList::iterator itVar = symList.begin();
for (; itVar != symList.end(); ++itVar)
{
if ( (*itVar)->getDataKind() == DataIsParam && (*itVar)->getName() == name )
{
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
ULONG StackFrame::getLocalCount()
{
ULONG count = 0;
ModulePtr mod;
mod = Module::loadModuleByOffset( m_instructionOffset);
LONG displacemnt;
SymbolPtr func;
try {
func = mod->getSymbolByVa( m_instructionOffset, SymTagFunction, &displacemnt );
}
catch(SymbolException&)
{
return 0;
}
#ifdef _DEBUG
std::string funcName;
funcName = func->getName();
#endif // _DEBUG
if (!IsInDebugRange(func, static_cast<ULONG>( m_instructionOffset - mod->getBase())))
{
return 0;
}
// find var in current scope
SymbolPtrList symList = func->findChildren(SymTagData);
SymbolPtrList::iterator it;
for ( it = symList.begin(); it != symList.end(); it++ )
{
if ( (*it)->getName() != "" )
count++;
}
// find inners scopes
SymbolPtrList scopeList = func->findChildren(SymTagBlock);
SymbolPtrList::iterator itScope = scopeList.begin();
ULONG ipRva = static_cast<ULONG>( m_instructionOffset - mod->getBase());
for (; itScope != scopeList.end(); ++itScope)
{
SymbolPtr scope = *itScope;
ULONG scopeRva = scope->getRva();
if (scopeRva <= ipRva && (scopeRva + scope->getSize()) > ipRva)
{
SymbolPtrList symList = scope->findChildren(SymTagData);
count += (ULONG)symList.size();
}
}
return count;
}
////////////////////////////////////////////////////////////////////////////////
ULONG StackFrame::getParamCount()
{
ULONG count = 0;
ModulePtr mod;
mod = Module::loadModuleByOffset( m_instructionOffset);
LONG displacemnt;
SymbolPtr func;
try {
func = mod->getSymbolByVa( m_instructionOffset, SymTagFunction, &displacemnt );
}
catch(SymbolException&)
{
return 0;
}
#ifdef _DEBUG
std::string funcName;
funcName = func->getName();
#endif // _DEBUG
if (!IsInDebugRange(func, static_cast<ULONG>( m_instructionOffset - mod->getBase())))
{
return 0;
}
// find var in current scope
SymbolPtrList symList = func->findChildren(SymTagData);
SymbolPtrList::iterator it;
for ( it = symList.begin(); it != symList.end(); it++ )
{
if ( (*it)->getDataKind() == DataIsParam )
count++;
}
return count;
}
////////////////////////////////////////////////////////////////////////////////
python::object StackFrame::getLocalByIndex( ULONG index )
{
ModulePtr mod = Module::loadModuleByOffset( m_instructionOffset);
LONG displacemnt;
SymbolPtr func;
try {
func = mod->getSymbolByVa( m_instructionOffset, SymTagFunction, &displacemnt );
}
catch(SymbolException&)
{
throw PyException( PyExc_IndexError, "index out of range" );
}
#ifdef _DEBUG
std::string funcName;
funcName = func->getName();
#endif // _DEBUG
if (!IsInDebugRange(func, static_cast<ULONG>( m_instructionOffset - mod->getBase())))
{
throw PyException( PyExc_IndexError, "index out of range" );
}
// find var in current scope
SymbolPtrList symList = func->findChildren(SymTagData);
SymbolPtrList::iterator itVar = symList.begin();
SymbolPtr symVar;
ULONG i = 0;
for (; itVar != symList.end(); ++itVar, ++i)
{
if ( i == index )
{
symVar = *itVar;
break;
}
}
if ( itVar == symList.end() )
{
// find inners scopes
SymbolPtrList scopeList = func->findChildren(SymTagBlock);
SymbolPtrList::iterator itScope = scopeList.begin();
ULONG ipRva = static_cast<ULONG>( m_instructionOffset - mod->getBase());
for (; itScope != scopeList.end() && !symVar; ++itScope)
{
SymbolPtr scope = *itScope;
ULONG scopeRva = scope->getRva();
if (scopeRva <= ipRva && (scopeRva + scope->getSize()) > ipRva)
{
SymbolPtrList symList = scope->findChildren(SymTagData);
SymbolPtrList::iterator itVar = symList.begin();
for (; itVar != symList.end(); ++itVar, ++i)
{
if ( i == index )
{
symVar = *itVar;
break;
}
}
}
}
}
if ( !symVar )
throw PyException( PyExc_IndexError, "index out of range" );
ULONG64 varAddr;
const LocationType locType = static_cast<LocationType>(symVar->getLocType());
switch (locType)
{
case LocIsStatic:
varAddr = mod->getBase() + symVar->getRva();
break;
case LocIsRegRel:
{
RegRealativeId rri;
rri = static_cast<RegRealativeId>(symVar->getRegRealativeId());
varAddr = getValue(rri, symVar->getOffset());
}
break;
default:
BOOST_ASSERT(LocIsEnregistered == locType);
throw DbgException("");
}
TypeInfoPtr typeInfo = TypeInfo::getTypeInfo(symVar);
TypedVarPtr typedVar = TypedVar::getTypedVarByTypeInfo(typeInfo, varAddr);
typedVar->setDataKind( symVar->getDataKind() );
return python::object( typedVar );
}
////////////////////////////////////////////////////////////////////////////////
python::object StackFrame::getParamByIndex( ULONG index )
{
ModulePtr mod = Module::loadModuleByOffset( m_instructionOffset);
LONG displacemnt;
SymbolPtr func;
try {
func = mod->getSymbolByVa( m_instructionOffset, SymTagFunction, &displacemnt );
}
catch(SymbolException&)
{
throw PyException( PyExc_IndexError, "index out of range" );
}
#ifdef _DEBUG
std::string funcName;
funcName = func->getName();
#endif // _DEBUG
if (!IsInDebugRange(func, static_cast<ULONG>( m_instructionOffset - mod->getBase())))
{
throw PyException( PyExc_IndexError, "index out of range" );
}
// find var in current scope
SymbolPtrList symList = func->findChildren(SymTagData);
SymbolPtrList::iterator itVar = symList.begin();
SymbolPtr symVar;
for ( ULONG i = 0; itVar != symList.end(); ++itVar )
{
if ( (*itVar)->getDataKind() == DataIsParam )
{
if ( i == index )
{
symVar = *itVar;
break;
}
i++;
}
}
if ( !symVar )
throw PyException( PyExc_IndexError, "index out of range" );
ULONG64 varAddr;
const LocationType locType = static_cast<LocationType>(symVar->getLocType());
switch (locType)
{
case LocIsStatic:
varAddr = mod->getBase() + symVar->getRva();
break;
case LocIsRegRel:
{
RegRealativeId rri;
rri = static_cast<RegRealativeId>(symVar->getRegRealativeId());
varAddr = getValue(rri, symVar->getOffset());
}
break;
default:
BOOST_ASSERT(LocIsEnregistered == locType);
throw DbgException("");
}
TypeInfoPtr typeInfo = TypeInfo::getTypeInfo(symVar);
TypedVarPtr typedVar = TypedVar::getTypedVarByTypeInfo(typeInfo, varAddr);
typedVar->setDataKind( symVar->getDataKind() );
return python::object( typedVar );
}
////////////////////////////////////////////////////////////////////////////////
python::list getCurrentStack()
{
std::vector<STACK_FRAME_DESC> frames;
getStackTrace( frames );
python::list frameList;
for ( ULONG i = 0; i < frames.size(); ++i )
{
python::object frameObj( StackFramePtr( new StackFrame( frames.at(i) ) ) );
frameList.append( frameObj );
}
return frameList;
}
////////////////////////////////////////////////////////////////////////////////
python::list getCurrentStackWow64()
{
std::vector<STACK_FRAME_DESC> frames;
getStackTraceWow64( frames );
python::list frameList;
for ( ULONG i = 0; i < frames.size(); ++i )
{
python::object frameObj( StackFramePtr( new StackFrame( frames.at(i) ) ) );
frameList.append( frameObj );
}
return frameList;
}
////////////////////////////////////////////////////////////////////////////////
StackFramePtr getCurrentStackFrame()
{
STACK_FRAME_DESC frame;
getCurrentFrame( frame );
return StackFramePtr( new StackFrame( frame ) );
}
///////////////////////////////////////////////////////////////////////////////
ScopeVarsPtr getLocals()
{
return getCurrentStackFrame()->getLocals();
}
///////////////////////////////////////////////////////////////////////////////
ScopeVarsPtr getParams()
{
return getCurrentStackFrame()->getParams();
}
///////////////////////////////////////////////////////////////////////////////
} // namespace pykd
| [
"[email protected]"
] | |
2ee18f0f5a9dfcc10bbcf9a2f317f77d234f5e5d | a8e71222864b672f900a08791e2d6579426209af | /swdFile.hpp | 2c9b513dbf0a99ec1fd151c028b1ecff31a21687 | [] | no_license | enler/pmDJ | d5e2a947303daa1927d1899fa0dab4ba1f88dce5 | 482cde666f638859ff188e67f8a92c6df53bfc91 | refs/heads/master | 2021-01-09T20:37:16.680203 | 2014-11-18T22:18:13 | 2014-11-18T22:18:13 | 81,286,850 | 0 | 0 | null | 2017-02-08T04:18:13 | 2017-02-08T04:18:13 | null | UTF-8 | C++ | false | false | 2,629 | hpp | #ifndef __SWDFILE_HPP
#define __SWDFILE_HPP
class swdFile;
class swdFileChunk;
class swdChunkEOD;
class swdChunkKGRP;
class swdChunkPCMD;
class swdChunkPRGI;
class swdChunkWAVI;
#include <fstream>
#include <ostream>
#include <stdint.h>
#include <string>
#include <vector>
unsigned readByte(const char*);
unsigned readWord(const char*);
unsigned readDWord(const char*);
class swdFile {
private:
std::string intFilename;
size_t pcmdLength;
size_t waviLength;
std::vector< swdFileChunk* > chunks;
public:
swdFile (std::ifstream&);
swdFile (const swdFile&);
~swdFile ();
swdFile& operator= (swdFile);
friend std::ostream& operator<< (std::ostream&,const swdFile&);
std::string GetFilename () const;
size_t GetPcmdLength () const;
size_t GetWaviLength () const;
int ChunkCount () const;
const swdFileChunk& operator[] (int) const;
const std::vector< swdFileChunk* >& Chunks() const;
};
class swdFileChunk {
public:
typedef enum { UNKNOWN_CHUNK,
CHUNK_EOD,
CHUNK_KGRP,
CHUNK_PCMD,
CHUNK_PRGI,
CHUNK_WAVI
} ChunkType;
protected:
char label[5];
off_t chunkOffset;
size_t dataSize;
char* dataPtr;
virtual std::ostream& AdvancedInfo(std::ostream&) const;
public:
swdFileChunk (std::ifstream&);
swdFileChunk (const swdFileChunk&);
~swdFileChunk ();
friend std::ostream& operator<< (std::ostream&,const swdFileChunk&);
swdFileChunk& operator= (swdFileChunk);
std::string GetLabel () const;
size_t GetSize () const;
const char* GetDataPtr () const;
virtual ChunkType GetType () const;
static ChunkType GetType (std::ifstream&);
};
class swdChunkEOD : public swdFileChunk {
public:
swdChunkEOD (std::ifstream&);
swdFileChunk::ChunkType GetType () const;
};
class swdChunkKGRP : public swdFileChunk {
public:
swdChunkKGRP (std::ifstream&);
swdFileChunk::ChunkType GetType () const;
};
class swdChunkPCMD : public swdFileChunk {
public:
swdChunkPCMD (std::ifstream&);
swdFileChunk::ChunkType GetType () const;
};
class swdChunkPRGI : public swdFileChunk {
public:
swdChunkPRGI (std::ifstream&);
swdFileChunk::ChunkType GetType () const;
};
class swdChunkWAVI : public swdFileChunk {
public:
typedef struct {
int indexNumber;
uint16_t unk_04;
char unk_12[0x20-0x12];
uint16_t sampleRate;
char unk_22[0x40-0x22];
} Entry;
private:
std::vector< Entry > dataEntry;
void AddEntry(off_t);
std::ostream& AdvancedInfo(std::ostream&) const;
public:
swdChunkWAVI (std::ifstream&);
swdFileChunk::ChunkType GetType () const;
};
#endif
| [
"[email protected]"
] | |
f9a74369fd239eaf8f5c6cd86ca90732986551de | 88a0d7c6c9f128e6316db8eaa81cf4b973420a94 | /spt/ipc/ipc.cpp | 7c2d0e20e60d801254cc818dc7527c9601784f5f | [] | no_license | Milky-Max/SourcePauseTool | 6cfcc0851cbcb6ba7fd25af54cefc13b132493f2 | 4f33293b85e78f610b2f9129b5cc79377f452e6b | refs/heads/master | 2023-04-11T14:54:39.702121 | 2021-04-23T09:38:25 | 2021-04-23T14:32:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,683 | cpp | #include "stdafx.h"
#include "ipc.hpp"
#include <chrono>
#include <iphlpapi.h>
#include <thread>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace ipc;
static PrintFunc PRINT_FUNC = nullptr;
static bool WINSOCK_INITIALIZED = false;
static u_long BLOCKING = 1;
const int BUFLEN = 32767;
const int MAX_MSG_BUFFER = 256;
void CloseSocket(int& socket)
{
closesocket(socket);
socket = INVALID_SOCKET;
}
static bool DataAvailable(int& socket)
{
fd_set read;
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
FD_ZERO(&read);
FD_SET(socket, &read);
int result = select(socket + 1, &read, &read, &read, &timeout);
return result > 0;
}
ipc::IPCServer::IPCServer()
{
listenSocket = INVALID_SOCKET;
clientSocket = INVALID_SOCKET;
RECV_BUFFER = new char[BUFLEN];
}
void ipc::InitWinsock()
{
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
WINSOCK_INITIALIZED = false;
Print("WSAStartup failed: %d\n", iResult);
return;
}
WINSOCK_INITIALIZED = true;
}
void ipc::AddPrintFunc(PrintFunc func)
{
PRINT_FUNC = func;
}
void IPCServer::StartListening(const char* port)
{
if (listenSocket != INVALID_SOCKET)
{
Print("Already listening to a socket!\n");
return;
}
struct addrinfo *result = NULL, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
int iResult = getaddrinfo("127.0.0.1", port, &hints, &result);
if (iResult != 0)
{
Print("getaddrinfo failed: %d\n", iResult);
return;
}
listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (listenSocket == INVALID_SOCKET)
{
Print("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
return;
}
// Setup the TCP listening socket
iResult = bind(listenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
Print("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
CloseSocket(listenSocket);
return;
}
freeaddrinfo(result);
iResult = ioctlsocket(listenSocket, FIONBIO, &BLOCKING);
if (iResult == -1)
{
Print("bind failed with error: %d\n", WSAGetLastError());
CloseSocket(listenSocket);
return;
}
Print("Started listening to socket.\n");
}
void ipc::IPCServer::CloseConnections()
{
Print("Closing sockets.\n");
if (listenSocket != SOCKET_ERROR)
CloseSocket(listenSocket);
if (clientSocket != SOCKET_ERROR)
CloseSocket(clientSocket);
}
void ipc::IPCServer::Loop()
{
CheckForConnections();
ReadMessages();
DispatchMessages();
}
bool ipc::IPCServer::BlockForMessages(const std::string& type, int timeoutMsec)
{
long long msecElapsed = 0;
auto begin = std::chrono::steady_clock::now();
if (msgQueue.find(type) != msgQueue.end())
{
auto& vec = msgQueue.find(type)->second;
auto end = std::chrono::steady_clock::now();
ReadMessages();
while (vec.empty() && msecElapsed < timeoutMsec)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
end = std::chrono::steady_clock::now();
msecElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();
ReadMessages();
}
bool result = !vec.empty();
DispatchMessages(type);
return result;
}
else
{
Print("Message type has no callback!\n");
return false;
}
}
void ipc::IPCServer::AddCallback(std::string type, MsgCallback callback, bool blocking)
{
callbacks[type] = callback;
blockingMap[type] = blocking;
msgQueue[type] = std::vector<nlohmann::json>();
}
void ipc::IPCServer::SendMsg(const nlohmann::json& msg)
{
if (clientSocket == SOCKET_ERROR)
{
Print("No client connected.\n");
return;
}
std::string out = msg.dump();
const char* string = out.c_str();
for (std::size_t i = 0; i <= out.size();)
{
int result = send(clientSocket, string, out.size() - i + 1, 0);
if (result == SOCKET_ERROR)
{
Print("Send failed: %d\n", WSAGetLastError());
CloseSocket(clientSocket);
return;
}
i += result;
string += result;
}
}
bool ipc::IPCServer::ClientConnected()
{
return clientSocket != SOCKET_ERROR;
}
ipc::IPCServer::~IPCServer()
{
delete[] RECV_BUFFER;
}
void ipc::IPCServer::ReadMessages()
{
if (clientSocket == SOCKET_ERROR || !DataAvailable(clientSocket))
{
return;
}
int offset = 0;
int result;
do
{
result = recv(clientSocket, RECV_BUFFER + offset, BUFLEN - offset, 0);
if (result > 0)
{
offset += result;
}
else if (result == 0)
{
CloseSocket(clientSocket);
Print("Client disconnected, closing socket.\n");
return;
}
else
{
int error = WSAGetLastError();
if (error != WSAEWOULDBLOCK && error != WSAECONNREFUSED)
{
CloseSocket(clientSocket);
Print("Client disconnected, closing socket.\n");
return;
}
}
} while (result > 0 && offset < BUFLEN);
int bytesRead = offset;
int startIndex = 0;
for (int i = 0; i < bytesRead; ++i)
{
if (RECV_BUFFER[i] == '\0')
{
char* str = RECV_BUFFER + startIndex;
try
{
nlohmann::json msg = nlohmann::json::parse(str, RECV_BUFFER + i);
if (msg.find("type") != msg.end())
{
std::string type = msg["type"];
if (callbacks.find(type) == callbacks.end())
{
Print("No callback for message type %s\n", type.c_str());
}
else
{
if (msgQueue.find(type) == msgQueue.end())
{
msgQueue[type] = std::vector<nlohmann::json>();
}
if (msgQueue[type].size() < MAX_MSG_BUFFER)
{
msgQueue[type].push_back(msg);
}
else
{
Print(
"Too many messages of type %s in queue, discarding message.\n",
type.c_str());
}
}
}
else
{
Print("Bad message received.\n");
}
}
catch (const std::exception& ex)
{
Print("Error parsing message: %s\n", ex.what());
}
startIndex = i + 1;
}
}
}
void ipc::IPCServer::CheckForConnections()
{
if (listenSocket == SOCKET_ERROR || clientSocket != SOCKET_ERROR)
{
return;
}
int result = listen(listenSocket, SOMAXCONN);
if (result == SOCKET_ERROR)
{
int error = WSAGetLastError();
if (error == WSAEWOULDBLOCK || error == WSAECONNREFUSED)
{
return;
}
Print("Listen failed with error: %ld\n", WSAGetLastError());
CloseSocket(listenSocket);
return;
}
// Accept a client socket
clientSocket = accept(listenSocket, NULL, NULL);
if (clientSocket == INVALID_SOCKET)
{
int error = WSAGetLastError();
if (error == WSAEWOULDBLOCK || error == WSAECONNREFUSED)
{
return;
}
Print("Accept failed: %d\n", WSAGetLastError());
CloseSocket(listenSocket);
return;
}
Print("Got client\n");
ioctlsocket(clientSocket, FIONBIO, &BLOCKING);
}
void ipc::IPCServer::DispatchMessages()
{
for (auto& pair : msgQueue)
{
if (!blockingMap[pair.first] && !pair.second.empty())
{
DispatchMessages(pair.first);
}
}
}
void ipc::IPCServer::DispatchMessages(const std::string& type)
{
auto& vec = msgQueue.find(type)->second;
auto callbackIt = callbacks.find(type);
if (callbackIt != callbacks.end())
{
MsgCallback callback = callbackIt->second;
for (auto item : vec)
{
callback(item);
}
}
vec.clear();
}
void ipc::Print(const char* msg, ...)
{
if (PRINT_FUNC != nullptr)
{
const int buflen = 256;
char buffer[buflen];
va_list args;
va_start(args, msg);
vsnprintf(buffer, buflen - 1, msg, args);
PRINT_FUNC(buffer);
}
}
void ipc::Shutdown_IPC()
{
WSACleanup();
WINSOCK_INITIALIZED = false;
}
bool ipc::Winsock_Initialized()
{
return WINSOCK_INITIALIZED;
}
| [
"[email protected]"
] | |
a98473b70dcaa8cc10f99e9f309fece4506f98e4 | c370635bb72fd714d7e9c46854f3773e765912e0 | /B_Array_Reodering.cpp | ac32e9b412de1c731819adbc38584c21f8b3bf3d | [] | no_license | ashutosh61973/codeforces_practice | 8b198ecb254989ce928b353455ec5cc5d8c29001 | 4949b199eb1a4347535d3f49ac8d28bb19d0c7d7 | refs/heads/master | 2023-06-02T05:59:47.944872 | 2021-06-20T12:42:49 | 2021-06-20T12:42:49 | 378,029,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,939 | cpp | #include "bits/stdc++.h"
using namespace std;
#define inti long long
#define ll long long
const long long INF = 1e18;
const int32_t M = 1e9 + 7;
const int32_t mod = 1e9 + 7;
const int32_t MM = 998244353;
bool prime[100000 + 10]; //primes under 10^5
//////////////////////////////////seive for prime/////////////////////////////
void primes()
{
int n = 1e5 + 10;
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
// for (int p=2; p<=n; p++)
// if (prime[p])
// cout << p << " ";
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////NCR////////////////////////////////////////
/*const int N=5000;
#define NCR
#define PRIME M
inti pw(inti a,inti p=M-2,inti MOD=M){
inti result = 1;
while (p > 0) {
if (p & 1)
result = a * result % MOD;
a = a * a % MOD;
p >>= 1;
}
return result;
}
inti fact[N],invfact[N];
void init(){
inti p=PRIME;
fact[0]=1;
inti i;
for(i=1;i<N;i++){
fact[i]=i*fact[i-1]%p;
}
i--;
invfact[i]=pw(fact[i],p-2,p);
for(i--;i>=0;i--){
invfact[i]=invfact[i+1]*(i+1)%p;
}
}
inti ncr(inti n,inti r){
if(r > n || n < 0 || r < 0)return 0;
return fact[n]*invfact[r]%PRIME*invfact[n-r]%PRIME;
}*/
///////////////////////////////////////////////////////////////////////////////
////\\//////\\/////////\\///////////\\\////////\\/////////////\\\/////
/*
ll power(ll a, ll b) //time complexity is o(log(b));
{
if (a == 0)
return 0;
ll ans = 1;
a = a % mod;
while (b > 0)
{
if ((b & 1) == 1)
ans = (ans * a) % mod;
b = b >> 1;
a = (a * a) % mod;
}
return ans;
}*/
//\\////\\//////\\//////\//////\\///////\\//////////\\/////\\///
/*bool isPrime(int n) {
if (n == 1) {
return false;
}
for (int i = 2; i*i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}*/
//////////////\\\\\\\\////////\\\\\\\\\\//////////\\\\////
///////////////////////////////////////////////////////////////////////
/*
//sort string by there length ==>
sort(v.begin(), v.end(), [&] (const string &s, const string &t) {
return s.size() < t.size();
});
*/
void checker()
{
ll n = 1e18;
string nn = to_string(n);
ll cnt = 0;
while (n > 0)
{
//function to check time complexity
cnt++;
n = n - (double(n) / (10));
}
cout << "loops runs (" << cnt << ") times for n=" << nn << endl;
}
///////////////////////////////////////////////////////////////////////
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
memset(prime, true, sizeof(prime));
primes(); // primes under 1lakh
/*
#ifdef NCR
init();
#endif
*/
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<pair<int, int>> v(n);
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
v[i] = {x % 2, x};
}
sort(v.begin(), v.end());
// reverse(v.begin(), v.end());
// vector<int> ans;
// for (int i = 0; i < n; i++)
// {
// if (!prime[v[i]])
// {
// ans.push_back(v[i]);
// }
// }
// for (int i = n - 1; i >= 0; i--)
// {
// if (prime[v[i]])
// {
// ans.push_back(v[i]);
// }
// }
int cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (__gcd(v[i].second, 2 * (v[j].second)) > 1)
{
cnt++;
}
}
}
cout << cnt << endl;
}
}
| [
"[email protected]"
] | |
d8477585d7ee36704a372f710dca28ff976b88da | 04ff070e5c1bc79d7f5b8eb0b67d0bfbd102cc3a | /docxbox/docx/docx_xml_to_plaintext.cc | 382bc9d0396ddfecd1b49fcdde3b02a374f8132a | [
"MIT",
"Zlib",
"Apache-2.0",
"GPL-1.0-or-later",
"GPL-3.0-only",
"BSD-3-Clause"
] | permissive | LucasBornhauser/docxbox | 63b10dc16b21589b8f2d347570233e27503775e4 | 1a198374c92b71b713e45ea71f5567854699d37d | refs/heads/master | 2021-05-26T08:54:48.013592 | 2020-04-14T06:31:30 | 2020-04-14T06:31:30 | 254,066,271 | 0 | 0 | MIT | 2020-07-14T06:26:46 | 2020-04-08T11:17:17 | C++ | UTF-8 | C++ | false | false | 1,678 | cc | // Copyright (c) 2020 gyselroth GmbH
#include "docx_xml_to_plaintext.h"
docx_xml_to_plaintext::docx_xml_to_plaintext(int argc, char **argv) : docx_xml(
argc,
argv) {
}
std::string docx_xml_to_plaintext::GetTextFromXmlFile(
const std::string &path_xml,
bool newline_at_segments) {
tinyxml2::XMLDocument doc;
doc.LoadFile(path_xml.c_str());
if (doc.ErrorID() != 0) return "";
tinyxml2::XMLElement *body = doc.FirstChildElement("w:document")
->FirstChildElement("w:body");
GetChildNodesText(body, newline_at_segments);
return document_text_;
}
void docx_xml_to_plaintext::GetChildNodesText(
tinyxml2::XMLElement *node,
bool newline_at_segments) {
if (!node || node->NoChildren()) return;
if (0 == strcmp(node->Value(), "w:p")) document_text_ += "\n";
tinyxml2::XMLElement *sub_node = node->FirstChildElement();
if (sub_node == nullptr) return;
do {
if (!sub_node) continue;
const char *value = sub_node->Value();
if (value) {
if (0 == strcmp(value, "w:instrText")) {
continue;
} else if (0 == strcmp(value, "w:fldChar")) {
if (0 == strcmp(
sub_node->Attribute("w:fldCharType"),
"begin")) document_text_ += " ";
} else if (0 == strcmp(value, "w:t")) {
const char *text = sub_node->GetText();
if (text) {
document_text_ += text;
if (newline_at_segments) document_text_ += "\n";
}
continue;
}
}
GetChildNodesText(sub_node, newline_at_segments);
} while ((sub_node = sub_node->NextSiblingElement()));
}
void docx_xml_to_plaintext::Output() {
std::cout << document_text_;
}
| [
"[email protected]"
] | |
b276f6234f1db5239d17d1a20d20b0a0cfcb4e97 | cb517177a1a2fc008285c84c6ab105c29967cfcc | /Competition/UVa299.cpp | e2f7c9927c135fb6953464466cf75c4df7bcb595 | [] | no_license | cshung/Competition | 8b4219593bfe28372ba82fbf923437988d862e2c | f534f37b34a0ef2351f4af3926ac864fed6dafc5 | refs/heads/main | 2023-08-29T03:25:35.042880 | 2023-08-16T15:32:45 | 2023-08-16T15:32:45 | 23,745,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,103 | cpp | #include "stdafx.h"
// http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=235
#include "UVa299.h"
#include <iostream>
using namespace std;
int UVa299()
{
int number_of_cases;
cin >> number_of_cases;
for (int c = 0; c < number_of_cases; c++)
{
int number_of_carriages;
cin >> number_of_carriages;
int* carriages = new int[number_of_carriages];
for (int ca = 0; ca < number_of_carriages; ca++)
{
cin >> carriages[ca];
}
int num_swap = 0;
for (int i = 1; i < number_of_carriages; i++)
{
for (int j = i; j > 0; j--)
{
if (carriages[j] < carriages[j-1])
{
int temp = carriages[j];
carriages[j] = carriages[j-1];
carriages[j-1] = temp;
num_swap++;
}
}
}
cout << "Optimal train swapping takes " << num_swap << " swaps." << endl;
delete[] carriages;
}
return 0;
} | [
"[email protected]"
] | |
9decef5766608652131c100c1156dd785fbed1d9 | e94ca3b308dddd06fe4255f35b123fd38e811ed0 | /src/obj/NodeB.cpp | 3996721fd34223e331d436a786fc32839c5989f2 | [] | no_license | LoghinVladDev/IS-T1-CPP | 848836e952a3622fbb8c110fac58ba4a7538f2a9 | 46855995ecc85a350babdeb8422c1a40c2eec813 | refs/heads/master | 2023-01-05T07:31:17.844548 | 2020-11-08T01:55:48 | 2020-11-08T01:55:48 | 310,169,069 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,758 | cpp | //
// Created by loghin on 04.11.2020.
//
#include <iostream>
#include <Socket.h>
#include <defs.h>
class Client {
private:
ClientSocket _socket;
std::ostream & _logChannel {std::clog};
bool _enableDebug {false};
public:
Client () noexcept = delete;
explicit Client ( const char * pIP, uint16 port, bool enableDebug = false, std::ostream & debugChannel = std::clog ) noexcept :
_socket( pIP, port ),
_logChannel ( debugChannel ),
_enableDebug ( enableDebug ){
}
int run () noexcept (false);
};
#include <fstream>
int main () {
try {
std::ofstream logFile ( "../logs/nodeBLog.txt" );
return Client( LOCALHOST, PORT, true, logFile ).run();
logFile.close();
} catch ( std::exception const & exception ) {
std::cerr << "Exception caught in application base runtime : " << exception.what() << '\n';
}
return 1;
}
auto toLower = [](std::string & s) -> std::string & { for( char & c : s ) c = static_cast < char > (std::tolower(c)); return s; };
auto removeSpaces = [](std::string & s) -> std::string & { while ( s.ends_with(' ') ) s.pop_back(); return s; };
bool isValidEncryptMode ( std::string & string ) noexcept {
if ( toLower ( string ) == "ecb" ) return true;
if ( toLower ( string ) == "cbc" ) return true;
if ( toLower ( string ) == "cfb" ) return true;
if ( toLower ( string ) == "ofb" ) return true;
return false;
}
crypto128::CryptoManager::EncryptMode getEncryptionMode ( std::string & string ) noexcept {
if ( removeSpaces ( toLower ( string ) ) == "ecb" ) return crypto128::CryptoManager::ECB;
if ( removeSpaces ( toLower ( string ) ) == "cbc" ) return crypto128::CryptoManager::CBC;
if ( removeSpaces ( toLower ( string ) ) == "cfb" ) return crypto128::CryptoManager::CFB;
if ( removeSpaces ( toLower ( string ) ) == "ofb" ) return crypto128::CryptoManager::OFB;
return crypto::CryptoManager<crypto::BITS_128>::ECB;
}
#include <fstream>
int Client::run () noexcept (false) {
try {
std::ifstream keysFile;
keysFile.open ( "../resources/keys.dat" );
std::string keyString;
keysFile >> keyString >> keyString >> keyString;
auto key = crypto128::Key::getFromHex(keyString.c_str());
auto iv = crypto128::IV();
this->_socket.enableEncryption( crypto128::CryptoManager::ECB, key, iv );
if ( this->_enableDebug )
ClientSocket::enableDebug( this->_logChannel );
std::string encryptionMode;
while ( true ) {
std::cout << "Input desired encryption mode (ECB/CFB) : ";
std::cin >> encryptionMode;
if ( isValidEncryptMode( encryptionMode ) ) {
this->_socket << encryptionMode;
break;
}
std::cout << "Invalid mode. Try again\n";
}
std::string ivString;
this->_socket >> encryptionMode >> keyString;
if ( removeSpaces(encryptionMode) != "ecb" )
this->_socket >> ivString;
crypto128::Key receivedKey( keyString.c_str() );
crypto128::IV receivedIV( ivString.c_str() );
// std::cout << encryptionMode << '\n' << receivedKey.toHexString() << '\n' << receivedIV.toHexString() << '\n';
// std::cout << "SWITCH ENCRIPTION : \n" << getEncryptionMode ( encryptionMode ) << '\n'
// << receivedKey.toHexString() << '\n' << receivedIV.toHexString();
this->_socket.enableEncryption( getEncryptionMode( encryptionMode ), receivedKey, receivedIV );
this->_socket << "NODE_READY";
std::string startConfirm;
this->_socket >> startConfirm;
if ( removeSpaces(startConfirm) != "ready" )
exit(0);
Socket nodeSocket;
ClientSocket toNode ( "127.0.0.1", 6999 );
if ( ! toNode.isConnected() ) {
ServerSocket channel ( 6999 );
Socket fromNode = channel.accept();
nodeSocket = Socket(fromNode);
} else {
nodeSocket = Socket(toNode);
}
nodeSocket.enableEncryption( getEncryptionMode( encryptionMode ), receivedKey, receivedIV );
std::string aInfo;
nodeSocket >> aInfo;
std::string confirm;
while ( removeSpaces ( aInfo ) != "<EOF>" ) {
std::cout << aInfo;
this->_socket << "8_blocks";
this->_socket >> confirm;
nodeSocket >> aInfo;
}
this->_socket << "done";
this->_socket.close();
} catch ( Socket::Exception const & exception ) {
std::cerr << "Exception caught in client runtime : " << exception.what() << '\n';
}
return 0;
}
| [
"[email protected]"
] | |
66e2cfe4cfa477d52956783e9b15fb72ccc8a347 | 1dbf007249acad6038d2aaa1751cbde7e7842c53 | /ocr/src/v1/model/BusinessLicenseRequestBody.cpp | d6769550cde4a8b0788d95d4c49bc2f4b7ab1b0c | [] | permissive | huaweicloud/huaweicloud-sdk-cpp-v3 | 24fc8d93c922598376bdb7d009e12378dff5dd20 | 71674f4afbb0cd5950f880ec516cfabcde71afe4 | refs/heads/master | 2023-08-04T19:37:47.187698 | 2023-08-03T08:25:43 | 2023-08-03T08:25:43 | 324,328,641 | 11 | 10 | Apache-2.0 | 2021-06-24T07:25:26 | 2020-12-25T09:11:43 | C++ | UTF-8 | C++ | false | false | 2,286 | cpp |
#include "huaweicloud/ocr/v1/model/BusinessLicenseRequestBody.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Ocr {
namespace V1 {
namespace Model {
BusinessLicenseRequestBody::BusinessLicenseRequestBody()
{
image_ = "";
imageIsSet_ = false;
url_ = "";
urlIsSet_ = false;
}
BusinessLicenseRequestBody::~BusinessLicenseRequestBody() = default;
void BusinessLicenseRequestBody::validate()
{
}
web::json::value BusinessLicenseRequestBody::toJson() const
{
web::json::value val = web::json::value::object();
if(imageIsSet_) {
val[utility::conversions::to_string_t("image")] = ModelBase::toJson(image_);
}
if(urlIsSet_) {
val[utility::conversions::to_string_t("url")] = ModelBase::toJson(url_);
}
return val;
}
bool BusinessLicenseRequestBody::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("image"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("image"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setImage(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("url"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("url"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setUrl(refVal);
}
}
return ok;
}
std::string BusinessLicenseRequestBody::getImage() const
{
return image_;
}
void BusinessLicenseRequestBody::setImage(const std::string& value)
{
image_ = value;
imageIsSet_ = true;
}
bool BusinessLicenseRequestBody::imageIsSet() const
{
return imageIsSet_;
}
void BusinessLicenseRequestBody::unsetimage()
{
imageIsSet_ = false;
}
std::string BusinessLicenseRequestBody::getUrl() const
{
return url_;
}
void BusinessLicenseRequestBody::setUrl(const std::string& value)
{
url_ = value;
urlIsSet_ = true;
}
bool BusinessLicenseRequestBody::urlIsSet() const
{
return urlIsSet_;
}
void BusinessLicenseRequestBody::unseturl()
{
urlIsSet_ = false;
}
}
}
}
}
}
| [
"[email protected]"
] | |
fffcff4b556db033470a0ae909ce77c0e82d2bec | e50b5f066628ef65fd7f79078b4b1088f9d11e87 | /llvm/tools/clang/test/CodeGenCXX/address-space-ref.cpp | c5d56d1d6a19960e5f6ad01a5d79ba369e290cc5 | [
"NCSA"
] | permissive | uzleo/coast | 1471e03b2a1ffc9883392bf80711e6159917dca1 | 04bd688ac9a18d2327c59ea0c90f72e9b49df0f4 | refs/heads/master | 2020-05-16T11:46:24.870750 | 2019-04-23T13:57:53 | 2019-04-23T13:57:53 | 183,025,687 | 0 | 0 | null | 2019-04-23T13:52:28 | 2019-04-23T13:52:27 | null | UTF-8 | C++ | false | false | 1,028 | cpp | // RUN: %clang_cc1 %s -std=c++11 -triple=x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s
// For a reference to a complete type, output the dereferenceable attribute (in
// any address space).
typedef int a __attribute__((address_space(1)));
a & foo(a &x, a & y) {
return x;
}
// CHECK: define dereferenceable(4) i32 addrspace(1)* @_Z3fooRU3AS1iS0_(i32 addrspace(1)* dereferenceable(4) %x, i32 addrspace(1)* dereferenceable(4) %y)
// For a reference to an incomplete type in an alternate address space, output
// neither dereferenceable nor nonnull.
class bc;
typedef bc b __attribute__((address_space(1)));
b & bar(b &x, b & y) {
return x;
}
// CHECK: define %class.bc addrspace(1)* @_Z3barRU3AS12bcS1_(%class.bc addrspace(1)* %x, %class.bc addrspace(1)* %y)
// For a reference to an incomplete type in addrspace(0), output nonnull.
bc & bar2(bc &x, bc & y) {
return x;
}
// CHECK: define nonnull %class.bc* @_Z4bar2R2bcS0_(%class.bc* nonnull %x, %class.bc* nonnull %y)
| [
"[email protected]"
] | |
b7dc7082d003ff0ea15d7e480337d0d5ef4547d3 | c0914249b835d5a56fdbf854fb6d1a47826334c4 | /M8M/AlgoMiner.h | 6c09fc7d2e8f4a12e4827d9b37db02fedcbe6812 | [
"BSD-3-Clause",
"JSON",
"BSD-2-Clause",
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | MaxDZ8/M8M | aa7414f3254196f0fe7c5014f482f1cd4a021209 | a208b2fdb48b51814508d2c1fbbddd26cc5485ba | refs/heads/main | 2021-07-09T14:35:18.722359 | 2020-08-28T08:17:47 | 2020-08-28T08:17:47 | 22,286,403 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 538 | h | /*
* This code is released under the MIT license.
* For conditions of distribution and use, see the LICENSE or hit the web.
*/
#pragma once
#include "ThreadedNonceFinders.h"
#include "../BlockVerifiers/BlockVerifierInterface.h"
class AlgoMiner : public ThreadedNonceFinders {
public:
AlgoMiner(BlockVerifierInterface &bv) : checker(bv) { }
private:
BlockVerifierInterface &checker;
std::array<aubyte, 32> HashHeader(std::array<aubyte, 80> &header, auint nonce) const {
return checker.Hash(header, nonce);
}
};
| [
"[email protected]"
] | |
d10b5133119f3042e9837dd4f081ff6e758dd45f | 43b4006c4ee90376918b8b88b6b6b67186bd70e0 | /src/ofxAddons/ofxFX/src/filters/ofxBokeh.h | a65927c62ff5352f86d2b77f10179eaa7851940e | [
"MIT"
] | permissive | laboluz/GAmuza | efcd55479833176a0761335a29dbe68a7ca6f28d | eaa363c4f67041b785e63ea56d7f148aff37c0e9 | refs/heads/master | 2021-01-13T03:03:05.753164 | 2016-12-09T13:43:49 | 2016-12-09T13:43:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,246 | h | //
// ofxBokeh.h
//
//
// Created by Tim Scaffidi ( http://timothyscaffidi.com/ )
//
// He share it on the openFrameworks forum here:
// http://forum.openframeworks.cc/index.php/topic,8583.msg40032.html#msg40032
//
#ifndef OFXBOKEH
#define OFXBOKEH
#define STRINGIFY(A) #A
#include "ofxFXObject.h"
#include "ofxBlur.h"
class ofxBokeh : public ofxBlur {
public:
ofxBokeh(){
passes = 3;
internalFormat = GL_RGBA;
// Fade constant
value0 = 1.0f;
// In this example the tex0 it´s more like a backbuffer
// The doble loop demands lot´s of resources to the GPU
fragmentShader = STRINGIFY(uniform sampler2DRect tex0;
uniform float value0;
void main(void) {
vec4 finalColor = vec4(0.0,0.0,0.0,1.0);
float weight = 0.;
int radius = int(value0);
for(int x = radius * -1 ; x < radius; x++) {
for(int y = radius * -1; y < radius; y++){
vec2 coord = gl_TexCoord[0].xy + vec2(x,y);
if(distance(coord, gl_TexCoord[0].xy) < float(radius)){
vec4 texel = texture2DRect(tex0, coord);
float w = length(texel.rgb)+ 0.1;
weight += w;
finalColor += texel * w;
}
}
}
gl_FragColor = finalColor/weight;
});
};
void setRadius(float _radius) { if (_radius >= 1) value0 = _radius;};
};
#endif
| [
"[email protected]"
] | |
8e1da1c9cef9bb3e46c2e1a859736aaef6550cf1 | fbbc81924cc7df8c66a50d73596b6aa3cce01fbf | /src/qt/qrcodedialog.cpp | a84c156a149fa39941a3206f0c2c48236715b744 | [
"MIT"
] | permissive | Icebergcoin/icebergcoin | f333be2f3dc08256e753e971f602f35db4845787 | 37530dbc1af2c28d27512198ac1e8fe0391685d2 | refs/heads/master | 2016-08-06T14:07:28.211344 | 2014-07-13T21:07:52 | 2014-07-13T21:07:52 | 21,796,323 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,326 | cpp | #include "qrcodedialog.h"
#include "ui_qrcodedialog.h"
#include "icebergcoinunits.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include <QPixmap>
#include <QUrl>
#include <qrencode.h>
QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) :
QDialog(parent),
ui(new Ui::QRCodeDialog),
model(0),
address(addr)
{
ui->setupUi(this);
setWindowTitle(QString("%1").arg(address));
ui->chkReqPayment->setVisible(enableReq);
ui->lblAmount->setVisible(enableReq);
ui->lnReqAmount->setVisible(enableReq);
ui->lnLabel->setText(label);
ui->btnSaveAs->setEnabled(false);
genCode();
}
QRCodeDialog::~QRCodeDialog()
{
delete ui;
}
void QRCodeDialog::setModel(OptionsModel *model)
{
this->model = model;
if (model)
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
// update the display unit, to not use the default ("ICB")
updateDisplayUnit();
}
void QRCodeDialog::genCode()
{
QString uri = getURI();
if (uri != "")
{
ui->lblQRCode->setText("");
QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300));
ui->outUri->setPlainText(uri);
}
}
QString QRCodeDialog::getURI()
{
QString ret = QString("Icebergcoin:%1").arg(address);
int paramCount = 0;
ui->outUri->clear();
if (ui->chkReqPayment->isChecked())
{
if (ui->lnReqAmount->validate())
{
// even if we allow a non ICB unit input in lnReqAmount, we generate the URI with ICB as unit (as defined in BIP21)
ret += QString("?amount=%1").arg(IcebergcoinUnits::format(IcebergcoinUnits::ICB, ui->lnReqAmount->value()));
paramCount++;
}
else
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("The entered amount is invalid, please check."));
return QString("");
}
}
if (!ui->lnLabel->text().isEmpty())
{
QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text()));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!ui->lnMessage->text().isEmpty())
{
QString msg(QUrl::toPercentEncoding(ui->lnMessage->text()));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
// limit URI length to prevent a DoS against the QR-Code dialog
if (ret.length() > MAX_URI_LENGTH)
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
return QString("");
}
ui->btnSaveAs->setEnabled(true);
return ret;
}
void QRCodeDialog::on_lnReqAmount_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnLabel_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnMessage_textChanged()
{
genCode();
}
void QRCodeDialog::on_btnSaveAs_clicked()
{
QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)"));
if (!fn.isEmpty())
myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn);
}
void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked)
{
if (!fChecked)
// if chkReqPayment is not active, don't display lnReqAmount as invalid
ui->lnReqAmount->setValid(true);
genCode();
}
void QRCodeDialog::updateDisplayUnit()
{
if (model)
{
// Update lnReqAmount with the current unit
ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit());
}
}
| [
"[email protected]"
] | |
ebd48da948d6fee6e02867b4f3756d26f1b3068e | a815edcd3c7dcbb79d7fc20801c0170f3408b1d6 | /chrome/browser/sync/user_event_service_factory.cc | c82c3a51edefeb13d517fa99c19c879cc6cce599 | [
"BSD-3-Clause"
] | permissive | oguzzkilic/chromium | 06be90df9f2e7f218bff6eee94235b6e684e2b40 | 1de71b638f99c15a3f97ec7b25b0c6dc920fbee0 | refs/heads/master | 2023-03-04T00:01:27.864257 | 2018-07-17T10:33:19 | 2018-07-17T10:33:19 | 141,275,697 | 1 | 0 | null | 2018-07-17T10:48:53 | 2018-07-17T10:48:52 | null | UTF-8 | C++ | false | false | 3,177 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/user_event_service_factory.h"
#include <memory>
#include <utility>
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/common/channel_info.h"
#include "components/browser_sync/profile_sync_service.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/sync/base/model_type.h"
#include "components/sync/base/report_unrecoverable_error.h"
#include "components/sync/model_impl/client_tag_based_model_type_processor.h"
#include "components/sync/user_events/no_op_user_event_service.h"
#include "components/sync/user_events/user_event_service_impl.h"
#include "components/sync/user_events/user_event_sync_bridge.h"
namespace browser_sync {
// static
UserEventServiceFactory* UserEventServiceFactory::GetInstance() {
return base::Singleton<UserEventServiceFactory>::get();
}
// static
syncer::UserEventService* UserEventServiceFactory::GetForProfile(
Profile* profile) {
return static_cast<syncer::UserEventService*>(
GetInstance()->GetServiceForBrowserContext(profile, true));
}
UserEventServiceFactory::UserEventServiceFactory()
: BrowserContextKeyedServiceFactory(
"UserEventService",
BrowserContextDependencyManager::GetInstance()) {
// TODO(vitaliii): This is missing
// DependsOn(ProfileSyncServiceFactory::GetInstance()), which we can't
// simply add because ProfileSyncServiceFactory itself depends on this
// factory. This won't be relevant anymore once the separate consents datatype
// is fully launched.
}
UserEventServiceFactory::~UserEventServiceFactory() {}
KeyedService* UserEventServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = Profile::FromBrowserContext(context);
syncer::SyncService* sync_service =
ProfileSyncServiceFactory::GetForProfile(profile);
if (!syncer::UserEventServiceImpl::MightRecordEvents(
context->IsOffTheRecord(), sync_service)) {
return new syncer::NoOpUserEventService();
}
syncer::OnceModelTypeStoreFactory store_factory =
browser_sync::ProfileSyncService::GetModelTypeStoreFactory(
profile->GetPath());
auto change_processor =
std::make_unique<syncer::ClientTagBasedModelTypeProcessor>(
syncer::USER_EVENTS,
base::BindRepeating(&syncer::ReportUnrecoverableError,
chrome::GetChannel()));
auto bridge = std::make_unique<syncer::UserEventSyncBridge>(
std::move(store_factory), std::move(change_processor),
sync_service->GetGlobalIdMapper());
return new syncer::UserEventServiceImpl(sync_service, std::move(bridge));
}
content::BrowserContext* UserEventServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return chrome::GetBrowserContextOwnInstanceInIncognito(context);
}
} // namespace browser_sync
| [
"[email protected]"
] | |
6a37a6340c3642b9a405e48d1a41099382f38c0e | dc24b5becff8ea5a72002d86e6676707792e747e | /dict.cpp | 3601dca5098624f138a952fedab16d830a447318 | [] | no_license | soumikpaul/Cpp-Practice | 83a0bb1b5522d6c61822f7cc993556464efe0633 | 4520269f60e0e39a15894faef9c2f7d6af8c0bc0 | refs/heads/master | 2022-12-13T17:29:20.266399 | 2020-09-05T15:10:21 | 2020-09-05T15:10:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,400 | cpp | #include <bits/stdc++.h>
using namespace std;
int dictionaryContains(string word)
{
string dictionary[] = {"mobile","samsung","sam","sung",
"man","mango","icecream","and",
"go","i","like","ice","cream"};
int size = sizeof(dictionary)/sizeof(dictionary[0]);
for (int i = 0; i < size; i++)
if (dictionary[i].compare(word) == 0)
return true;
return false;
}
// returns true if string can be segmented into space
// separated words, otherwise returns false
bool wordBreak(string str)
{
int size = str.size();
// Base case
if (size == 0) return true;
// Try all prefixes of lengths from 1 to size
for (int i=1; i<=size; i++)
{
// The parameter for dictionaryContains is
// str.substr(0, i) which is prefix (of input
// string) of length 'i'. We first check whether
// current prefix is in dictionary. Then we
// recursively check for remaining string
// str.substr(i, size-i) which is suffix of
// length size-i
if (dictionaryContains( str.substr(0, i) ) &&
wordBreak( str.substr(i, size-i) ))
return true;
}
// If we have tried all prefixes and
// none of them worked
return false;
}
int main()
{
wordBreak("ilikesam")?cout<<"true"<<endl:cout<<"false"<<endl;
}
| [
"[email protected]"
] | |
2d7606151e1a6499c89a040993dc6afe00fd6bf8 | 0f05b00aa31787c8da146a7fee3355a2c3e7fde6 | /test/resqml2_0_1test/StratigraphicColumnRankInterpretationTest.cpp | abc5dbc64d0424932dc3cdf6a40425540d594a34 | [] | no_license | mbrucher/Fesapi | 2bd3ddbe0f4c277a76b9ee81a828e34b628e5da5 | 8d1b4c78bc1d0c82b2f768352a64372520624a0f | refs/heads/master | 2021-01-10T07:29:40.090725 | 2016-09-19T15:45:18 | 2017-01-05T15:18:59 | 52,535,277 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,183 | cpp | #include "resqml2_0_1test/StratigraphicColumnRankInterpretationTest.h"
#include <stdexcept>
#include "catch.hpp"
#include "resqml2_0_1test/StratigraphicOrganizationTest.h"
#include "resqml2_0_1test/StratigraphicUnitInterpretationTest.h"
#include "EpcDocument.h"
#include "resqml2_0_1/OrganizationFeature.h"
#include "resqml2_0_1/StratigraphicColumnRankInterpretation.h"
#include "resqml2_0_1/StratigraphicUnitInterpretation.h"
#include <stdexcept>
using namespace std;
using namespace resqml2_0_1test;
using namespace common;
using namespace resqml2_0_1;
const char* StratigraphicColumnRankInterpretationTest::defaultUuid = "51f39ab2-3b1f-4da3-8541-324632357dd7";
const char* StratigraphicColumnRankInterpretationTest::defaultTitle = "Strati Column Rank";
const char* StratigraphicColumnRankInterpretationTest::defaultOverburdenUuid = "91622a20-e2a0-4123-a8b5-6540a1ff4f8f";
const char* StratigraphicColumnRankInterpretationTest::defaultOverburdenTitle = "Overburden";
const char* StratigraphicColumnRankInterpretationTest::defaultOverburdenInterpUuid = "80ba46c8-86e7-42ef-ab30-4718958f3707";
const char* StratigraphicColumnRankInterpretationTest::defaultOverburdenInterpTitle = "Overburden Interp";
const char* StratigraphicColumnRankInterpretationTest::defaultUnderburdenUuid = "88575500-4f85-4bea-9245-530e71867945";
const char* StratigraphicColumnRankInterpretationTest::defaultUnderburdenTitle = "Underburden";
const char* StratigraphicColumnRankInterpretationTest::defaultUnderburdenInterpUuid = "1914478a-e50b-4808-ad62-11201992024d";
const char* StratigraphicColumnRankInterpretationTest::defaultUnderburdenInterpTitle = "Underburden Interp";
StratigraphicColumnRankInterpretationTest::StratigraphicColumnRankInterpretationTest(const string & epcDocPath)
: AbstractFeatureInterpretationTest(epcDocPath, defaultUuid, defaultTitle, StratigraphicOrganizationTest::defaultUuid, StratigraphicOrganizationTest::defaultTitle) {
}
StratigraphicColumnRankInterpretationTest::StratigraphicColumnRankInterpretationTest(const string & epcDocPath, const std::string & uuid, const std::string & title, const string & uuidFeature, const string & titleFeature)
: AbstractFeatureInterpretationTest(epcDocPath, uuid, title, uuidFeature, titleFeature) {
}
StratigraphicColumnRankInterpretationTest::StratigraphicColumnRankInterpretationTest(EpcDocument* epcDoc, bool init)
: AbstractFeatureInterpretationTest(epcDoc, defaultUuid, defaultTitle, StratigraphicOrganizationTest::defaultUuid, StratigraphicOrganizationTest::defaultTitle) {
if (init)
initEpcDoc();
else
readEpcDoc();
}
StratigraphicColumnRankInterpretationTest::StratigraphicColumnRankInterpretationTest(common::EpcDocument* epcDoc, const std::string & uuid, const std::string & title, const string & uuidFeature, const string & titleFeature, bool init)
: AbstractFeatureInterpretationTest(epcDocPath, uuid, title, uuidFeature, titleFeature) {
}
void StratigraphicColumnRankInterpretationTest::initEpcDocHandler() {
// creating dependencies
StratigraphicOrganizationTest* stratiOrgtTest = new StratigraphicOrganizationTest(epcDoc, true);
StratigraphicUnitInterpretationTest* overburdenInterpTest = new StratigraphicUnitInterpretationTest(epcDoc, defaultOverburdenInterpUuid, defaultOverburdenInterpTitle, defaultOverburdenUuid, defaultOverburdenTitle, true);
StratigraphicUnitInterpretationTest* stratiLayerInterpTest = new StratigraphicUnitInterpretationTest(epcDoc, true);
StratigraphicUnitInterpretationTest* underburdenInterpTest = new StratigraphicUnitInterpretationTest(epcDoc, defaultUnderburdenInterpUuid, defaultUnderburdenInterpTitle, defaultUnderburdenUuid, defaultUnderburdenTitle, true);
OrganizationFeature* stratiOrg = epcDoc->getResqmlAbstractObjectByUuid<OrganizationFeature>(StratigraphicOrganizationTest::defaultUuid);
StratigraphicUnitInterpretation* overburdenInterp = epcDoc->getResqmlAbstractObjectByUuid<StratigraphicUnitInterpretation>(defaultOverburdenInterpUuid);
StratigraphicUnitInterpretation* stratiLayerInterp = epcDoc->getResqmlAbstractObjectByUuid<StratigraphicUnitInterpretation>(StratigraphicUnitInterpretationTest::defaultUuid);
StratigraphicUnitInterpretation* underburdenInterp = epcDoc->getResqmlAbstractObjectByUuid<StratigraphicUnitInterpretation>(defaultUnderburdenInterpUuid);
// cleaning
delete stratiOrgtTest;
delete overburdenInterpTest;
delete stratiLayerInterpTest;
delete underburdenInterpTest;
StratigraphicColumnRankInterpretation* stratiColumnRank = epcDoc->createStratigraphicColumnRankInterpretationInApparentDepth(stratiOrg, uuid, title, 0);
REQUIRE(stratiColumnRank != nullptr);
stratiColumnRank->pushBackStratiUnitInterpretation(overburdenInterp);
stratiColumnRank->pushBackStratiUnitInterpretation(stratiLayerInterp);
stratiColumnRank->pushBackStratiUnitInterpretation(underburdenInterp);
}
void StratigraphicColumnRankInterpretationTest::readEpcDocHandler()
{
StratigraphicColumnRankInterpretation* stratiColumnRank = epcDoc->getResqmlAbstractObjectByUuid<StratigraphicColumnRankInterpretation>(uuid);
REQUIRE(stratiColumnRank != nullptr);
REQUIRE(stratiColumnRank->getStratigraphicUnitInterpretationSet().size() == 3);
} | [
"philippe.verney@553bd026-d4ad-425d-a02a-e125c7656c9a"
] | philippe.verney@553bd026-d4ad-425d-a02a-e125c7656c9a |
fb57adc4985b788bf4737c182f7e258c512e79f9 | 473fc28d466ddbe9758ca49c7d4fb42e7d82586e | /app/src/main/java/com/syd/source/aosp/external/libcxx/test/std/utilities/variant/variant.variant/variant.ctor/in_place_type_args.pass.cpp | a023f02bad6e3991a5c0fb9bbbee5df3e61da858 | [
"NCSA",
"MIT"
] | permissive | lz-purple/Source | a7788070623f2965a8caa3264778f48d17372bab | e2745b756317aac3c7a27a4c10bdfe0921a82a1c | refs/heads/master | 2020-12-23T17:03:12.412572 | 2020-01-31T01:54:37 | 2020-01-31T01:54:37 | 237,205,127 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,397 | cpp | // -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// <variant>
// template <class ...Types> class variant;
// template <class Tp, class ...Args>
// constexpr explicit variant(in_place_type_t<Tp>, Args&&...);
#include <cassert>
#include <type_traits>
#include <variant>
#include "test_convertible.hpp"
#include "test_macros.h"
void test_ctor_sfinae() {
{
using V = std::variant<int>;
static_assert(
std::is_constructible<V, std::in_place_type_t<int>, int>::value, "");
static_assert(!test_convertible<V, std::in_place_type_t<int>, int>(), "");
}
{
using V = std::variant<int, long, long long>;
static_assert(
std::is_constructible<V, std::in_place_type_t<long>, int>::value, "");
static_assert(!test_convertible<V, std::in_place_type_t<long>, int>(), "");
}
{
using V = std::variant<int, long, int *>;
static_assert(
std::is_constructible<V, std::in_place_type_t<int *>, int *>::value,
"");
static_assert(!test_convertible<V, std::in_place_type_t<int *>, int *>(),
"");
}
{ // duplicate type
using V = std::variant<int, long, int>;
static_assert(
!std::is_constructible<V, std::in_place_type_t<int>, int>::value, "");
static_assert(!test_convertible<V, std::in_place_type_t<int>, int>(), "");
}
{ // args not convertible to type
using V = std::variant<int, long, int *>;
static_assert(
!std::is_constructible<V, std::in_place_type_t<int>, int *>::value, "");
static_assert(!test_convertible<V, std::in_place_type_t<int>, int *>(), "");
}
{ // type not in variant
using V = std::variant<int, long, int *>;
static_assert(
!std::is_constructible<V, std::in_place_type_t<long long>, int>::value,
"");
static_assert(!test_convertible<V, std::in_place_type_t<long long>, int>(),
"");
}
}
void test_ctor_basic() {
{
constexpr std::variant<int> v(std::in_place_type<int>, 42);
static_assert(v.index() == 0, "");
static_assert(std::get<0>(v) == 42, "");
}
{
constexpr std::variant<int, long> v(std::in_place_type<long>, 42);
static_assert(v.index() == 1, "");
static_assert(std::get<1>(v) == 42, "");
}
{
constexpr std::variant<int, const int, long> v(
std::in_place_type<const int>, 42);
static_assert(v.index() == 1, "");
static_assert(std::get<1>(v) == 42, "");
}
{
using V = std::variant<const int, volatile int, int>;
int x = 42;
V v(std::in_place_type<const int>, x);
assert(v.index() == 0);
assert(std::get<0>(v) == x);
}
{
using V = std::variant<const int, volatile int, int>;
int x = 42;
V v(std::in_place_type<volatile int>, x);
assert(v.index() == 1);
assert(std::get<1>(v) == x);
}
{
using V = std::variant<const int, volatile int, int>;
int x = 42;
V v(std::in_place_type<int>, x);
assert(v.index() == 2);
assert(std::get<2>(v) == x);
}
}
int main() {
test_ctor_basic();
test_ctor_sfinae();
}
| [
"[email protected]"
] | |
ce7ab901282a9800ccee48e985c2a81076dae928 | c6935dd90b51f225a347940eb16ca147b90a9c73 | /AVL-Tree/BST/AVLTree.hpp | ac38b11bc44a0755d60df42dfb2415f42ddba9fc | [] | no_license | vlongle/Binary-Search-Tree | 4203374fe10455ea0d279f6bba671ab9b927e1df | dfc83e86c9c90485de51040fd3bea950c7872cc7 | refs/heads/master | 2021-04-15T10:30:06.967305 | 2018-04-01T01:54:29 | 2018-04-01T01:54:29 | 126,705,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,539 | hpp | //
// AVLTree.hpp
// BST
//
// Created by Le Nguyen VIet Long on 3/25/18.
// Copyright © 2018 Le Nguyen Viet Long. All rights reserved.
//
#ifndef AVLTree_hpp
#define AVLTree_hpp
#include <stdio.h>
#include <stack>
// right is bigger, left is smaller
struct BSTNode{
// default
BSTNode(int val, int size, int length, BSTNode* parent,BSTNode* leftC,BSTNode* rightC ):
val(val),
size(size),
length(length),
parent(parent),
leftC(leftC),
rightC(rightC){};
BSTNode(int value):val(value),
parent(nullptr),
leftC(new BSTNode{-69,0,-1,this, nullptr,nullptr}),
rightC(new BSTNode{-69,0,-1,this, nullptr,nullptr}),
size(1){};
int val;
int size; // size of subtree with this as its topNode
int length; // the # of paths/vertices from this node to the furthest leaf.
BSTNode* parent;
BSTNode* leftC;
BSTNode* rightC;
};
class BST{
public:
BSTNode* topNode;
// create the fictious node
BST(): topNode(new BSTNode(-69,0,-1,nullptr, nullptr,nullptr)){};
BST(BSTNode* top): topNode(top){};
void insert(BSTNode* newN);
void counterclock(BSTNode* grandpa);
void clockwise(BSTNode* grandpa);
int checkAVL(BSTNode* check);
BSTNode* search(int searchVal);
int inOrderTranversal(BSTNode* top);
BSTNode* min(BSTNode* nodeSub);
BSTNode* successor(int val);
BSTNode* predecessor(int val);
void fixAVL(BSTNode* myNode);
void printTreeStack();
void deleteN(int searchVal);
};
#endif /* AVLTree_hpp */
| [
"[email protected]"
] | |
90ee4fb9df6d209ec35603228a23c7e1c2c35292 | b126a8248240fd71653159beeccc732ca49f49c2 | /OpenCascade/gp_Pnt.hxx | 10b45848c1271eae3d0e8708177bd6909a03be9b | [] | no_license | jicc/3rdpartyincludes | 90fd194a37082027482043c56e66cfdafa386d2b | f790f816dc2c4ef5868189b87cb6edb65a755538 | refs/heads/master | 2021-01-14T13:39:24.774980 | 2013-07-26T08:15:01 | 2013-07-26T08:15:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,569 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _gp_Pnt_HeaderFile
#define _gp_Pnt_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_Macro_HeaderFile
#include <Standard_Macro.hxx>
#endif
#ifndef _gp_XYZ_HeaderFile
#include <gp_XYZ.hxx>
#endif
#ifndef _Standard_Storable_HeaderFile
#include <Standard_Storable.hxx>
#endif
#ifndef _Standard_Real_HeaderFile
#include <Standard_Real.hxx>
#endif
#ifndef _Standard_Integer_HeaderFile
#include <Standard_Integer.hxx>
#endif
#ifndef _Standard_Boolean_HeaderFile
#include <Standard_Boolean.hxx>
#endif
#ifndef _Standard_PrimitiveTypes_HeaderFile
#include <Standard_PrimitiveTypes.hxx>
#endif
class Standard_OutOfRange;
class gp_XYZ;
class gp_Ax1;
class gp_Ax2;
class gp_Trsf;
class gp_Vec;
Standard_EXPORT const Handle(Standard_Type)& STANDARD_TYPE(gp_Pnt);
//! Defines a 3D cartesian point. <br>
class gp_Pnt {
public:
void* operator new(size_t,void* anAddress)
{
return anAddress;
}
void* operator new(size_t size)
{
return Standard::Allocate(size);
}
void operator delete(void *anAddress)
{
if (anAddress) Standard::Free((Standard_Address&)anAddress);
}
//! Creates a point with zero coordinates. <br>
gp_Pnt();
//! Creates a point from a XYZ object. <br>
gp_Pnt(const gp_XYZ& Coord);
//! Creates a point with its 3 cartesian's coordinates : Xp, Yp, Zp. <br>
gp_Pnt(const Standard_Real Xp,const Standard_Real Yp,const Standard_Real Zp);
//! Changes the coordinate of range Index : <br>
//! Index = 1 => X is modified <br>
//! Index = 2 => Y is modified <br>
//! Index = 3 => Z is modified <br>//! Raised if Index != {1, 2, 3}. <br>
void SetCoord(const Standard_Integer Index,const Standard_Real Xi) ;
//! For this point, assigns the values Xp, Yp and Zp to its three coordinates. <br>
void SetCoord(const Standard_Real Xp,const Standard_Real Yp,const Standard_Real Zp) ;
//! Assigns the given value to the X coordinate of this point. <br>
void SetX(const Standard_Real X) ;
//! Assigns the given value to the Y coordinate of this point. <br>
void SetY(const Standard_Real Y) ;
//! Assigns the given value to the Z coordinate of this point. <br>
void SetZ(const Standard_Real Z) ;
//! Assigns the three coordinates of Coord to this point. <br>
void SetXYZ(const gp_XYZ& Coord) ;
//! Returns the coordinate of corresponding to the value of Index : <br>
//! Index = 1 => X is returned <br>
//! Index = 2 => Y is returned <br>
//! Index = 3 => Z is returned <br>
//! Raises OutOfRange if Index != {1, 2, 3}. <br>//! Raised if Index != {1, 2, 3}. <br>
Standard_Real Coord(const Standard_Integer Index) const;
//! For this point gives its three coordinates Xp, Yp and Zp. <br>
void Coord(Standard_Real& Xp,Standard_Real& Yp,Standard_Real& Zp) const;
//! For this point, returns its X coordinate. <br>
Standard_Real X() const;
//! For this point, returns its Y coordinate. <br>
Standard_Real Y() const;
//! For this point, returns its Z coordinate. <br>
Standard_Real Z() const;
//! For this point, returns its three coordinates as a XYZ object. <br>
const gp_XYZ& XYZ() const;
//! For this point, returns its three coordinates as a XYZ object. <br>
const gp_XYZ& Coord() const;
//! Returns the coordinates of this point. <br>
//! Note: This syntax allows direct modification of the returned value. <br>
gp_XYZ& ChangeCoord() ;
//! Assigns the result of the following expression to this point <br>
//! (Alpha*this + Beta*P) / (Alpha + Beta) <br>
void BaryCenter(const Standard_Real Alpha,const gp_Pnt& P,const Standard_Real Beta) ;
//! Comparison <br>
//! Returns True if the distance between the two points is <br>
//! lower or equal to LinearTolerance. <br>
Standard_Boolean IsEqual(const gp_Pnt& Other,const Standard_Real LinearTolerance) const;
//! Computes the distance between two points. <br>
Standard_Real Distance(const gp_Pnt& Other) const;
//! Computes the square distance between two points. <br>
Standard_Real SquareDistance(const gp_Pnt& Other) const;
//! Performs the symmetrical transformation of a point <br>
//! with respect to the point P which is the center of <br>
//! the symmetry. <br>
Standard_EXPORT void Mirror(const gp_Pnt& P) ;
//! Performs the symmetrical transformation of a point <br>
//! with respect to an axis placement which is the axis <br>
//! of the symmetry. <br>
Standard_EXPORT gp_Pnt Mirrored(const gp_Pnt& P) const;
Standard_EXPORT void Mirror(const gp_Ax1& A1) ;
//! Performs the symmetrical transformation of a point <br>
//! with respect to a plane. The axis placement A2 locates <br>
//! the plane of the symmetry : (Location, XDirection, YDirection). <br>
Standard_EXPORT gp_Pnt Mirrored(const gp_Ax1& A1) const;
Standard_EXPORT void Mirror(const gp_Ax2& A2) ;
//! Rotates a point. A1 is the axis of the rotation. <br>
//! Ang is the angular value of the rotation in radians. <br>
Standard_EXPORT gp_Pnt Mirrored(const gp_Ax2& A2) const;
void Rotate(const gp_Ax1& A1,const Standard_Real Ang) ;
//! Scales a point. S is the scaling value. <br>
gp_Pnt Rotated(const gp_Ax1& A1,const Standard_Real Ang) const;
void Scale(const gp_Pnt& P,const Standard_Real S) ;
//! Transforms a point with the transformation T. <br>
gp_Pnt Scaled(const gp_Pnt& P,const Standard_Real S) const;
Standard_EXPORT void Transform(const gp_Trsf& T) ;
//! Translates a point in the direction of the vector V. <br>
//! The magnitude of the translation is the vector's magnitude. <br>
gp_Pnt Transformed(const gp_Trsf& T) const;
void Translate(const gp_Vec& V) ;
//! Translates a point from the point P1 to the point P2. <br>
gp_Pnt Translated(const gp_Vec& V) const;
void Translate(const gp_Pnt& P1,const gp_Pnt& P2) ;
gp_Pnt Translated(const gp_Pnt& P1,const gp_Pnt& P2) const;
const gp_XYZ& _CSFDB_Getgp_Pntcoord() const { return coord; }
protected:
private:
gp_XYZ coord;
};
#include <gp_Pnt.lxx>
// other Inline functions and methods (like "C++: function call" methods)
#endif
| [
"[email protected]"
] | |
86d63d797f7cf77d51726b02664fb0627432c431 | 866823c87ad8736e763e0e696335861fb60b43e5 | /ANDEquation.cpp | be19117da70caa620e52889403c2e5bc3b5ce3e1 | [] | no_license | jainakshay/codechef | deb23eb65c1f74741da2f9732f7d0ccd16f8311c | 6e32c62d8e5a40a7fcfc6efa57c165dd0eb92fb9 | refs/heads/master | 2021-01-11T11:18:55.370233 | 2017-02-12T11:44:22 | 2017-02-12T11:44:22 | 71,572,793 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,105 | cpp | /***********************************************************
AIM:https://arena.topcoder.com/#/u/practiceCode/15191/26460/12029/2/313351
AUTHOR: AKSHAY JAIN
DATE: 19/01/2016
STATUS: AC
SCORE: 132.5/250
***********************************************************/
//Code goes here..!!
#include<bits/stdc++.h>
#include<vector>
using namespace std;
class ANDEquation
{
public:
int i,j,y;
int restoreY(vector <int> A)
{
bool val=false;
for(i=1;i<A.size();i++)
{
y=A[0];
for(j=0;j<A.size();j++)
{
if(j!=i)
y=y&A[j];
}
if(y==A[i])
{
val=true;
return A[i];
}
}
if(val==false)
{
y=A[1];
for(i=1;i<A.size();i++)
y=y&A[i];
if(y==A[0])
{
return A[0];
}
else
return -1;
}
return 0;
}
}; | [
"[email protected]"
] | |
402d9247936c0138ef0efef0bb31ce5d2f11a15e | d7e3cb7f34a67bbec6e2f267889be52dd20efaca | /042_Water_semiPort_0524/UnitTest/Models/Car.h | 612de8f2623b2050961acadef3c534bb2bfaaadc | [] | no_license | ParkMalza/MapTool | d8ba102d07158c23f3c1e9d86b5b4d029bfcf9a7 | 1ad9367df8c6e2a1130bd7e6c64f36cba279dc7e | refs/heads/master | 2020-05-26T22:48:40.308478 | 2019-05-24T10:38:24 | 2019-05-24T10:38:24 | 188,400,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | h | #pragma once
class Car
{
public:
Car(Shader*, Model* modelinsShader, ModelRender* modelRendere, class Terrain* terrain);
~Car();
void Update(class Terrain* terrain);
void CubeRender();
void PreRender();
void Render();
//void Move();
void Position(D3DXVECTOR3* position) { *position = this->position; }
void Scale(D3DXVECTOR3* scale) { *scale = this->scale; }
void Rotation(D3DXVECTOR3* rot) { *rot = this->rotation; }
void Position(D3DXVECTOR3& position) { this->position = position; }
void Scale(D3DXVECTOR3& scale) { this->scale = scale; }
void Rotation(D3DXVECTOR3& rot) { this->rotation = rot; }
UINT GetDrawCount() { return carRender->GetDrawCount(); }
void GetTextureCube(TextureCube** val) { *val = textureCube; }
void InstanceCar(D3DXVECTOR3& picked);
void CheckHeight();
void Save(wstring fileName);
void Load(wstring fileName);
private:
void EditCar();
void Selected();
//void SetImgui();
private:
class Terrain* terrain;
Model* model;
ModelRender* carRender;
Shader* modelShader;
InstanceMesh* box;
Transform* editTrans;
Transform* boxEditTrans;
private:
//float speed;
D3DXVECTOR3 position;
D3DXVECTOR3 scale;
D3DXVECTOR3 rotation;
D3DXMATRIX world;
bool isClick;
vector<D3DXVECTOR3> saveCar;
vector<D3DXVECTOR3> saveBox;
int selectIndex;
int loadCarCount;
int loadBoxCount;
private:
TextureCube* textureCube;
//ID3DX11EffectShaderResourceVariable* sCubeSrv;
}; | [
"[email protected]"
] | |
b1719644d9de24d3b26199eeca2405ade5a06117 | 2d5db0df3c23f9251d7a71d4f42341078b31d6a8 | /cp30.cpp | 3261a4a1b13db1f39a4f154a0d221e74a894d484 | [] | no_license | justfornamesake/coding | 381e7e0e6b1f25d325d8a8bd83321c5e5c43338d | 6fe2ecb61e0a28bc50573d0dfba106ab8bbe7ce0 | refs/heads/master | 2020-06-04T20:23:45.881340 | 2019-06-16T10:40:51 | 2019-06-16T10:40:51 | 192,178,973 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | cpp | #include <bits/stdc++.h>
using namespace std;
int a[100000];
int*alternatesort(int* arr,int len){
sort(arr,arr+len);
int a[len/2];
int j=0;
for(int i=0;i<len;i+=2){
a[j]=arr[i];
j++;
}
return a;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
int ans*;
ans=alternatesort(a,n);;
for(int i=0;i<len/2;i++){
cout<<ans[i]<<"";
}
cout<<endl;
}
| [
"[email protected]"
] | |
93a831dc6e729d87fc8c89ad62f3b63ae52b77d1 | 19194c2f2c07ab3537f994acfbf6b34ea9b55ae7 | /android-29/android/text/style/TtsSpan_FractionBuilder.hpp | fd925ac409574eae9e1e77196fb47aeee9181956 | [
"GPL-3.0-only"
] | permissive | YJBeetle/QtAndroidAPI | e372609e9db0f96602da31b8417c9f5972315cae | ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c | refs/heads/Qt6 | 2023-08-05T03:14:11.842336 | 2023-07-24T08:35:31 | 2023-07-24T08:35:31 | 249,539,770 | 19 | 4 | Apache-2.0 | 2022-03-14T12:15:32 | 2020-03-23T20:42:54 | C++ | UTF-8 | C++ | false | false | 2,308 | hpp | #pragma once
#include "../../../JString.hpp"
#include "./TtsSpan_FractionBuilder.def.hpp"
namespace android::text::style
{
// Fields
// Constructors
inline TtsSpan_FractionBuilder::TtsSpan_FractionBuilder()
: android::text::style::TtsSpan_SemioticClassBuilder(
"android.text.style.TtsSpan$FractionBuilder",
"()V"
) {}
inline TtsSpan_FractionBuilder::TtsSpan_FractionBuilder(jlong arg0, jlong arg1, jlong arg2)
: android::text::style::TtsSpan_SemioticClassBuilder(
"android.text.style.TtsSpan$FractionBuilder",
"(JJJ)V",
arg0,
arg1,
arg2
) {}
// Methods
inline android::text::style::TtsSpan_FractionBuilder TtsSpan_FractionBuilder::setDenominator(JString arg0) const
{
return callObjectMethod(
"setDenominator",
"(Ljava/lang/String;)Landroid/text/style/TtsSpan$FractionBuilder;",
arg0.object<jstring>()
);
}
inline android::text::style::TtsSpan_FractionBuilder TtsSpan_FractionBuilder::setDenominator(jlong arg0) const
{
return callObjectMethod(
"setDenominator",
"(J)Landroid/text/style/TtsSpan$FractionBuilder;",
arg0
);
}
inline android::text::style::TtsSpan_FractionBuilder TtsSpan_FractionBuilder::setIntegerPart(JString arg0) const
{
return callObjectMethod(
"setIntegerPart",
"(Ljava/lang/String;)Landroid/text/style/TtsSpan$FractionBuilder;",
arg0.object<jstring>()
);
}
inline android::text::style::TtsSpan_FractionBuilder TtsSpan_FractionBuilder::setIntegerPart(jlong arg0) const
{
return callObjectMethod(
"setIntegerPart",
"(J)Landroid/text/style/TtsSpan$FractionBuilder;",
arg0
);
}
inline android::text::style::TtsSpan_FractionBuilder TtsSpan_FractionBuilder::setNumerator(JString arg0) const
{
return callObjectMethod(
"setNumerator",
"(Ljava/lang/String;)Landroid/text/style/TtsSpan$FractionBuilder;",
arg0.object<jstring>()
);
}
inline android::text::style::TtsSpan_FractionBuilder TtsSpan_FractionBuilder::setNumerator(jlong arg0) const
{
return callObjectMethod(
"setNumerator",
"(J)Landroid/text/style/TtsSpan$FractionBuilder;",
arg0
);
}
} // namespace android::text::style
// Base class headers
#include "./TtsSpan_Builder.hpp"
#include "./TtsSpan_SemioticClassBuilder.hpp"
#ifdef QT_ANDROID_API_AUTOUSE
using namespace android::text::style;
#endif
| [
"[email protected]"
] | |
b27e8e6e2c9bc2cf82866854c06ab0e31e7bebb6 | b6607ecc11e389cc56ee4966293de9e2e0aca491 | /codeforces.com/Contests/248 div 1/A/A.cpp | 69fb566634367d42cb8cde8e937e681dd81b808d | [] | no_license | BekzhanKassenov/olymp | ec31cefee36d2afe40eeead5c2c516f9bf92e66d | e3013095a4f88fb614abb8ac9ba532c5e955a32e | refs/heads/master | 2022-09-21T10:07:10.232514 | 2021-11-01T16:40:24 | 2021-11-01T16:40:24 | 39,900,971 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,627 | cpp | /****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const int MOD = 1000 * 1000 * 1000 + 7;
const int INF = 2000 * 1000 * 1000;
const double EPS = 1e-9;
const double pi = acos(-1.0);
const int maxn = 100010;
template <typename T>
inline T sqr(T n) {
return (n * n);
}
vector <int> adj[maxn];
int a[maxn], last, x, n, m;
ll ans, temp, sum;
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d", &x);
if (last == 0 || a[last - 1] != x)
a[last++] = x;
}
m = last;
for (int i = 1; i < m - 1; i++) {
adj[a[i]].push_back(a[i + 1]);
adj[a[i]].push_back(a[i - 1]);
}
if (m > 1) {
adj[a[0]].push_back(a[1]);
adj[a[m - 1]].push_back(a[m - 2]);
}
for (int i = 0; i < m - 1; i++) {
sum += abs(a[i] - a[i + 1]);
}
ans = sum;
for (int i = 1; i <= n; i++) {
if (adj[i].empty())
continue;
sort(all(adj[i]));
temp = sum;
int mid = adj[i][adj[i].size() / 2];
for (size_t j = 0; j < adj[i].size(); j++) {
temp -= abs(adj[i][j] - i);
temp += abs(adj[i][j] - mid);
}
ans = min(ans, temp);
}
printf("%I64d", ans);
return 0;
}
| [
"[email protected]"
] | |
561f6b8285bee2928b0235a71f49d7c85318870e | 769cff1fce30a3edbd41e4d1b407a2d7a8924314 | /femm/hd_probdlg.cpp | e58d9b0324bdb45a4deba115e75e680dae4fab3b | [] | no_license | mtp22peng/femm42src_cuda | 206b541ebbc68e800c388fd35954f3435f0a708f | ee29e597ccc576703a907d6ff77bd7f029c8b226 | refs/heads/master | 2021-05-27T10:27:13.168545 | 2020-04-29T08:24:38 | 2020-04-29T08:24:38 | 254,252,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,343 | cpp | // probdlg.cpp : implementation file
//
#include "stdafx.h"
#include "femm.h"
#include "hd_probdlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// probdlg dialog
hdCProbDlg::hdCProbDlg(CWnd* pParent /*=NULL*/)
: CDialog(hdCProbDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(hdCProbDlg)
m_problem_note = _T("");
m_precision = 1.e-8;
m_minangle=DEFAULT_MINIMUM_ANGLE;
m_depth = 1.0;
m_dt = 0.0;
m_prevsoln = _T("");
//}}AFX_DATA_INIT
}
void hdCProbDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(hdCProbDlg)
DDX_Control(pDX, IDC_HD_LENGTH_UNITS, m_length_units);
DDX_Control(pDX, IDC_BSMART, m_bsmart);
DDX_Control(pDX, IDC_HD_PROBTYPE, m_probtype);
DDX_Text(pDX, IDC_HD_PROBNOTE, m_problem_note);
DDX_Text(pDX, IDC_HD_PRC, m_precision);
DDV_MinMaxDouble(pDX, m_precision, 1.e-016, 1.e-008);
DDX_Text(pDX, IDC_HD_MINANG, m_minangle);
DDV_MinMaxDouble(pDX, m_minangle, 1., MINANGLE_MAX);
DDX_Text(pDX, IDC_HD_EDIT_DEPTH, m_depth);
DDX_Text(pDX, IDC_HD_DT, m_dt);
DDX_Text(pDX, IDC_HD_PREVSOLN, m_prevsoln);
//}}AFX_DATA_MAP
DDX_Control(pDX, IDC_HD_EDIT_DEPTH, m_IDC_depth);
DDX_Control(pDX, IDC_HD_PROBNOTE, m_IDC_problem_note);
DDX_Control(pDX, IDC_HD_PREVSOLN, m_IDC_prevsoln);
DDX_Control(pDX, IDC_HD_DT, m_IDC_dt);
DDX_Control(pDX, IDC_HD_PRC, m_IDC_precision);
DDX_Control(pDX, IDC_HD_MINANG, m_IDC_minangle);
}
BEGIN_MESSAGE_MAP(hdCProbDlg, CDialog)
//{{AFX_MSG_MAP(hdCProbDlg)
ON_CBN_SELCHANGE(IDC_HD_LENGTH_UNITS, OnSelchangeLengthUnits)
ON_CBN_SELCHANGE(IDC_HD_PROBTYPE, OnSelchangeProbtype)
ON_EN_CHANGE(IDC_HD_PREVSOLN, OnChangeHdPrevsoln)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// probdlg message handlers
BOOL hdCProbDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
m_probtype.SetCurSel(probtype);
if(probtype) m_IDC_depth.EnableWindow(FALSE);
else m_IDC_depth.EnableWindow(TRUE);
m_length_units.SetCurSel(lengthunits);
m_bsmart.SetCurSel(bsmart);
if(m_prevsoln.GetLength()==0){
m_IDC_dt.EnableWindow(FALSE);
m_dt=0;
}
else m_IDC_dt.EnableWindow(TRUE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void hdCProbDlg::OnOK()
{
if (UpdateData()==FALSE) return;
probtype=m_probtype.GetCurSel();
if(probtype) m_depth=1;
if (m_prevsoln.GetLength()==0) m_dt=0;
UpdateData(FALSE);
lengthunits=m_length_units.GetCurSel();
bsmart=m_bsmart.GetCurSel();
CDialog::OnOK();
}
void hdCProbDlg::OnSelchangeLengthUnits()
{
}
void hdCProbDlg::OnSelchangeProbtype()
{
if(m_probtype.GetCurSel()) m_IDC_depth.EnableWindow(FALSE);
else m_IDC_depth.EnableWindow(TRUE);
}
void hdCProbDlg::OnChangeHdPrevsoln()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialog::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
UpdateData();
if(m_prevsoln.GetLength()==0){
m_IDC_dt.EnableWindow(FALSE);
m_dt=0;
UpdateData(FALSE);
}
else m_IDC_dt.EnableWindow(TRUE);
}
| [
"[email protected]"
] | |
c8de02b379e6aafae9267a8322222ba996280907 | 7cffb2303be4abe065384e102b03900160bce0da | / oop-hampus-lind --username [email protected]/DOA14/Fakultet/main.cpp | 6841eb3c0199bac7baab0a133e4d80fc85ce1761 | [] | no_license | HampusLind/oop-hampus-lind | f6304a49bce7e2c9a540ec3a095331a10afafb1a | f418388dee30df3cbefa0400bb71fe81ffd3521a | refs/heads/master | 2016-09-05T09:56:25.210192 | 2015-03-19T09:23:59 | 2015-03-19T09:23:59 | 33,168,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 667 | cpp | #include "hr_time.h"
#include <iostream>
using namespace std;
int factorial(int n)
{
int sum;
if (n == 1){
return 1;
}
else{
sum = n*factorial(n - 1);
}
return sum;
}
int FactorialIterative(int n){
int r = n;
for (int i = n - 1; i > 0; i--)
{
r *= i;
}
return r;
}
int main(){
CStopWatch clock;
clock.startTimer();
for (int t = 0; t < 1000000; t++)
{
FactorialIterative(4);
}
clock.stopTimer();
cout << "Time1 = " << clock.getElapsedTime() * 1000000000 / 1000000 << " nanosekunder" << endl << endl;
cout << factorial(3) << endl;
cout << FactorialIterative(3) << endl;
system("PAUSE");
return 0;
} | [
"[email protected]@e98ff420-f582-c4b9-0fa7-a23d757adad3"
] | [email protected]@e98ff420-f582-c4b9-0fa7-a23d757adad3 |
645f719c2b566987238a4c2bb72633eee6d97bcc | 7644744add670e13ddf3ae07447ed5072aa8485e | /TrafficSimulation/TrafficSimulation/graphicsview.cpp | 5f6f677f70b97dc5d1409a657fc050ecd8a05441 | [] | no_license | duxiaodong/graduate-pro | 1eef969e49d328f4e2ab6fabfb3579bb0da4adf8 | 9bc1cc4607bba206e1b8e6f3c0ceecdf233819c0 | refs/heads/master | 2021-01-16T21:54:32.096354 | 2014-05-26T14:05:58 | 2014-05-26T14:05:58 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,869 | cpp | #include "graphicsview.h"
#include <QResizeEvent>
#include <QWheelEvent>
#include <QMouseEvent>
#include <QGLWidget>
#include <QPrinter>
#include <QPrintDialog>
#include <QFileDialog>
GraphicsView::GraphicsView(QWidget* parent/*=0*/ )
: QGraphicsView(parent)
{
}
GraphicsView::~GraphicsView()
{
}
void GraphicsView::resizeEvent( QResizeEvent *event )
{
QSize size = event->size();
emit sizeChange(size.width(), size.height());
}
void GraphicsView::wheelEvent( QWheelEvent *event )
{
QPoint numDegrees = event->angleDelta()/8;
QPoint numSteps = numDegrees/15;
QPoint hoverPos = event->pos();
QPointF scenePos = mapToScene(hoverPos);
emit zoom(numSteps.y(), scenePos);
}
void GraphicsView::init(GraphicsScene* scene)
{
mIsPressed = false;
setRenderHint(QPainter::Antialiasing, false);
connect(this, SIGNAL(sizeChange(int, int)), scene, SLOT(changeSceneRect(int, int)));
connect(this, SIGNAL(zoom(int, QPointF)), scene, SLOT(zoom(int, QPointF)));
connect(this, SIGNAL(move(QPointF)), scene, SLOT(move(QPointF)));
//setOptimizationFlag(QGraphicsView::DontSavePainterState);
setViewportUpdateMode(FullViewportUpdate);
setCursor(Qt::OpenHandCursor);
setDragMode(QGraphicsView::ScrollHandDrag);
setCacheMode(CacheBackground);
setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
}
void GraphicsView::print()
{
QPrinter printer;
if (QPrintDialog(&printer).exec() == QDialog::Accepted) {
// printer自带的filedialog不能用, 原因未知, 所以手动加了一个
QString filename = QFileDialog::getSaveFileName(this,"filename",QString(),QString("pdf Files (*.pdf)"));
printer.setOutputFileName(filename);
QPainter painter(&printer);
painter.setRenderHint(QPainter::Antialiasing);
//开始打印
render(&painter);
}
}
void GraphicsView::setScene( GraphicsScene *scene )
{
init(scene);
QGraphicsView::setScene(scene);
}
| [
"[email protected]"
] | |
d19a27e6f6624f1086d30bd1ca4718572fa6fef7 | 1917e86190e49a0d017a90aeeefc96665611cfb2 | /tests/ami_test/mix_annotation_pragma/client.cpp | 3205e1ab7f419a98e1f0d9c736de6495af846261 | [
"MIT"
] | permissive | mcorino/taox11 | 72c5cd11dc29ca760a5726ede3e86e3c171bb8da | 2fead9148ae1e206a9e82178b5482800ca79773f | refs/heads/master | 2022-11-04T03:26:44.136162 | 2022-10-18T15:07:55 | 2022-10-18T15:07:55 | 222,112,628 | 0 | 0 | MIT | 2023-09-11T09:25:24 | 2019-11-16T14:40:16 | C++ | UTF-8 | C++ | false | false | 17,582 | cpp | /**
* @file client.cpp
* @author Marijke Hengstmengel
*
* @brief CORBA C++11 client ami test
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#include "ace/Get_Opt.h"
#include "ace/Task.h"
#include "ami_testAmiC.h"
#include <thread>
#include "testlib/taox11_testlog.h"
const ACE_TCHAR *ior = ACE_TEXT("file://server.ior");
int16_t result = 0;
int16_t nr_of_replies = 0;
int16_t myfoo_foo = 0;
int16_t mybar_foo = 0;
int16_t myfoo_attrib = 0;
int16_t mybar_attrib = 0;
int16_t myfoo_foo_excep = 0;
int16_t mybar_foo_excep = 0;
bool
parse_args (int argc, ACE_TCHAR *argv[])
{
ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("k:"));
int c;
while ((c = get_opts ()) != -1)
switch (c)
{
case 'k':
ior = get_opts.opt_arg ();
break;
case '?':
default:
TAOX11_TEST_ERROR << "usage: -k <ior>"
<< std::endl;
return false;
}
// Indicates successful parsing of the command line
return true;
}
class MyFooHandler
: public virtual CORBA::amic_traits<A::MyFoo>::replyhandler_base_type
{
public:
/// Constructor.
MyFooHandler () = default;
/// Destructor.
~MyFooHandler () = default;
void foo (int32_t ami_return_val) override
{
TAOX11_TEST_INFO << "Callback method <MyFooHandler::foo> called: ret "
<< ami_return_val << std::endl;
nr_of_replies--;
myfoo_foo++;
}
void foo_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override
{
try
{
excep_holder->raise_exception ();
}
catch (const A::InternalError& ex)
{
myfoo_foo_excep++;
TAOX11_TEST_INFO << "Callback method <MyFoo::foo_excep> exception received successfully <"
<< ex.id() << "> and <" << ex.error_string() << ">." << std::endl;
if (ex.id() != 2)
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyFoo::foo_excep> exception ex.id not 2 but "
<< ex.id() << std::endl;
result = 1;
}
if (ex.error_string() != "Hello from foo")
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyFoo::foo_excep> exception ex.error_string() not ok: "
<< ex.error_string() << std::endl;
result = 1;
}
}
catch (const CORBA::Exception& )
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyFoo::foo_excep> caught the wrong exception"
<< std::endl;
result = 1;
}
nr_of_replies--;
}
void get_my_foo_attrib (int32_t ret) override
{
TAOX11_TEST_INFO << "Callback method <MyFooHandler::get_my_foo_attrib> called: ret "
<< ret << std::endl;
nr_of_replies--;
myfoo_attrib++;
}
void get_my_foo_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <get_my_foo_attrib_excep> called."
<< std::endl;
}
void set_my_foo_attrib () override
{
TAOX11_TEST_INFO << "Callback method <MyFooHandler::set_my_foo_attrib> called:"
<< std::endl;
nr_of_replies--;
myfoo_attrib++;
}
void set_my_foo_attrib_excep (IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <set_my_foo_attrib_excep> called:"
<< std::endl;
}
};
class MyBarHandler final
: public virtual CORBA::amic_traits<A::MyBar>::replyhandler_base_type
{
public:
/// Constructor.
MyBarHandler () = default;
/// Destructor.
~MyBarHandler () = default;
void bye (int32_t ami_return_val, int32_t /*answer*/) override
{
nr_of_replies--;
TAOX11_TEST_INFO << "Callback method <MyBarHandler::bye> called: ret "
<< ami_return_val << std::endl;
}
void bye_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <bye_excep> called."<< std::endl;
}
void foo (int32_t ami_return_val) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::foo> called: ret "
<< ami_return_val << std::endl;
nr_of_replies--;
mybar_foo++;
}
void foo_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override
{
try
{
excep_holder->raise_exception ();
}
catch (const A::InternalError& ex)
{
mybar_foo_excep++;
TAOX11_TEST_INFO
<< "Callback method <MyBarHandler::foo_excep> exception received successfully <"
<< ex.id() << "> and <" << ex.error_string() << ">." << std::endl;
if (ex.id() != 3)
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyBarHandler::foo_excep> exception ex.id not 3 but "
<< ex.id() << std::endl;
result = 1;
}
if (ex.error_string() != "Hello from bar")
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyBarHandler::foo_excep> exception ex.error_string() not ok: "
<< ex.error_string() << std::endl;
result = 1;
}
}
catch (const CORBA::Exception& )
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyBarHandler::foo_excep> caught the wrong exception"
<< std::endl;
result = 1;
}
nr_of_replies--;
}
void get_my_foo_attrib (int32_t ret) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::get_my_foo_attrib> called: ret "
<< ret << std::endl;
nr_of_replies--;
mybar_attrib++;
}
void get_my_foo_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::get_my_foo_attrib_excep> called."
<< std::endl;
}
void set_my_foo_attrib () override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::set_my_foo_attrib> called:"
<< std::endl;
nr_of_replies--;
mybar_attrib++;
}
void set_my_foo_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::set_my_foo_attrib_excep> called:"
<< std::endl;
}
void do_something (int32_t /*ami_return_val*/) override
{
}
void do_something_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::do_someting_excep> called."
<< std::endl;
}
void get_my_derived_attrib (int32_t ret) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::get_my_derived_attrib> called: ret "
<< ret << std::endl;
}
void get_my_derived_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::get_my_derived_attrib_excep> called."
<< std::endl;
}
void set_my_derived_attrib () override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::set_my_derived_attrib> called."
<< std::endl;
}
void set_my_derived_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::set_my_derived_attrib_excep> called:"
<< std::endl;
}
void get_my_bar_attrib (int32_t ret) override
{
nr_of_replies--;
TAOX11_TEST_INFO << "Callback method <MyBarHandler::get_my_bar_attrib> called: ret "
<< ret << std::endl;
}
void get_my_bar_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::get_my_bar_attrib_excep> called."
<< std::endl;
}
void set_my_bar_attrib () override
{
nr_of_replies--;
TAOX11_TEST_INFO << "Callback method <MyBarHandler::set_my_bar_attrib> called:"
<< std::endl;
}
void set_my_bar_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::set_my_bar_attrib_excep> called:"
<< std::endl;
}
};
int main(int argc, char* argv[])
{
try
{
IDL::traits<CORBA::ORB>::ref_type _orb = CORBA::ORB_init (argc, argv);
if (_orb == nullptr)
{
TAOX11_TEST_ERROR << "ERROR: CORBA::ORB_init (argc, argv) returned null ORB."
<< std::endl;
return 1;
}
if (parse_args (argc, argv) == false)
return 1;
IDL::traits<CORBA::Object>::ref_type obj = _orb->string_to_object (ior);
if (!obj)
{
TAOX11_TEST_ERROR << "ERROR: string_to_object(<ior>) returned null reference."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "client:retrieved object reference" << std::endl;
IDL::traits<A::Hello>::ref_type ami_test_var = IDL::traits<A::Hello>::narrow (obj);
if (!ami_test_var)
{
TAOX11_TEST_ERROR << "ERROR: IDL::traits<A::Hello>::narrow (obj) returned null object."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "narrowed A::Hello interface" << std::endl;
// Instantiate the ReplyHandlers and register that with the POA.
IDL::traits<CORBA::Object>::ref_type poa_obj =
_orb->resolve_initial_references ("RootPOA");
if (!poa_obj)
{
TAOX11_TEST_ERROR
<< "ERROR: resolve_initial_references (\"RootPOA\") returned null reference."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "retrieved RootPOA object reference" << std::endl;
IDL::traits<PortableServer::POA>::ref_type root_poa =
IDL::traits<PortableServer::POA>::narrow (poa_obj);
if (!root_poa)
{
TAOX11_TEST_ERROR
<< "ERROR: IDL::traits<PortableServer::POA>::narrow (obj) returned null object."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "narrowed POA interface" << std::endl;
IDL::traits<PortableServer::POAManager>::ref_type poaman =
root_poa->the_POAManager ();
if (!poaman)
{
TAOX11_TEST_ERROR
<< "ERROR: root_poa->the_POAManager () returned null object."
<< std::endl;
return 1;
}
//Handler for interface MyBar
CORBA::amic_traits<A::MyBar>::replyhandler_servant_ref_type test_handler_impl_bar =
CORBA::make_reference<MyBarHandler> ();
TAOX11_TEST_INFO << "created MyBarHandler servant" << std::endl;
PortableServer::ObjectId id_bar = root_poa->activate_object (test_handler_impl_bar);
TAOX11_TEST_INFO << "activated MyBarHandler servant" << std::endl;
IDL::traits<CORBA::Object>::ref_type test_handler_bar_obj =
root_poa->id_to_reference (id_bar);
if (test_handler_bar_obj == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: root_poa->id_to_reference (id) returned null reference."
<< std::endl;
return 1;
}
CORBA::amic_traits<A::MyBar>::replyhandler_ref_type test_handler_bar =
CORBA::amic_traits<A::MyBar>::replyhandler_traits::narrow (test_handler_bar_obj);
if (test_handler_bar == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: CORBA::amic_traits<A::MyBar>::replyhandler_traits::narrow (test_handler_bar_obj) returned null reference."
<< std::endl;
return 1;
}
//Handler for interface MyFoo
CORBA::amic_traits<A::MyFoo>::replyhandler_servant_ref_type test_handler_impl_foo =
CORBA::make_reference<MyFooHandler> ();
TAOX11_TEST_INFO << "created MyFooHandler servant" << std::endl;
PortableServer::ObjectId id_foo = root_poa->activate_object (test_handler_impl_foo);
TAOX11_TEST_INFO << "activated MyFooHandler servant" << std::endl;
IDL::traits<CORBA::Object>::ref_type test_handler_foo_obj =
root_poa->id_to_reference (id_foo);
if (test_handler_foo_obj == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: root_poa->id_to_reference (id) returned null reference."
<< std::endl;
return 1;
}
CORBA::amic_traits<A::MyFoo>::replyhandler_ref_type test_handler_foo =
CORBA::amic_traits<A::MyFoo>::replyhandler_traits::narrow (test_handler_foo_obj);
if (test_handler_foo == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: CORBA::amic_traits<A::MyFoo>::replyhandler_traits::narrow (test_handler_foo_obj) returned null reference."
<< std::endl;
return 1;
}
poaman->activate ();
A::MyBar::_ref_type i_bar_ref = ami_test_var->get_iMyBar();
if (!i_bar_ref)
{
TAOX11_TEST_ERROR << "ERROR: Retrieve of iMyBar returned null object." << std::endl;
return 1;
}
CORBA::amic_traits<A::MyBar>::ref_type i_bar = CORBA::amic_traits<A::MyBar>::narrow (i_bar_ref);
if (!i_bar)
{
TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traits<A::MyBar>::narrow (i_bar) returned null object."
<< std::endl;
return 1;
}
A::MyFoo::_ref_type i_foo_ref = ami_test_var->get_iMyFoo();
if (!i_foo_ref)
{
TAOX11_TEST_ERROR << "ERROR: Retrieve of iMyFoo returned null object." << std::endl;
return 1;
}
CORBA::amic_traits<A::MyFoo>::ref_type i_foo = CORBA::amic_traits<A::MyFoo>::narrow (i_foo_ref);
if (!i_foo)
{
TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traits<A::MyFoo>::narrow (i_foo) returned null object."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "Client: Sending 3 asynch messages MyBar::bye, MyBar::foo and MyFoo::foo." << std::endl;
i_bar->sendc_bye (test_handler_bar);
i_bar->sendc_foo (test_handler_bar, 12);
i_foo->sendc_foo (test_handler_foo, 11);
TAOX11_TEST_INFO << "Client: Sending 2 asynch messages for MyBar::my_bar_attrib attributes." << std::endl;
i_bar->sendc_set_my_bar_attrib (test_handler_bar, 101);
i_bar->sendc_get_my_bar_attrib (test_handler_bar);
TAOX11_TEST_INFO << "Client: Sending 2 asynch messages for MyBar::my_foo_attrib attributes." << std::endl;
i_bar->sendc_set_my_foo_attrib (test_handler_bar, 101);
i_bar->sendc_get_my_foo_attrib (test_handler_bar);
TAOX11_TEST_INFO << "Client: Sending 2 asynch messages for MyFoo::my_foo_attrib attributes." << std::endl;
i_foo->sendc_set_my_foo_attrib (test_handler_foo, 101);
i_foo->sendc_get_my_foo_attrib (test_handler_foo);
TAOX11_TEST_INFO << "Client: Sending asynch messages MyBar::foo (2) and MyFoo::foo (1)to trigger exceptions." << std::endl;
i_bar->sendc_foo (test_handler_bar, 0);
i_foo->sendc_foo (test_handler_foo, 0);
i_bar->sendc_foo (test_handler_bar, 0);
nr_of_replies = 12;
TAOX11_TEST_INFO << "Client: Do something else before coming back for the replies." << std::endl;
for (int i = 0; i < 10; i ++)
{
TAOX11_TEST_INFO << " ...";
std::this_thread::sleep_for (std::chrono::milliseconds (10));
}
TAOX11_TEST_INFO << std::endl << "Client: Now let's look for the replies." << std::endl;
std::this_thread::sleep_for (std::chrono::seconds (2));
while ((nr_of_replies > 0))
{
bool pending = _orb->work_pending();
if (pending)
{
_orb->perform_work ();
}
}
if ((nr_of_replies != 0) || (myfoo_foo != 1) || (mybar_foo != 1))
{
TAOX11_TEST_ERROR << "ERROR: Client didn't receive expected replies. Expected -12- , received -"
<< (5 - nr_of_replies) << "-. " << " Expected MyFoo- foo <1> , received <"
<< myfoo_foo << ">. Expected MyBar- foo <1>, received <" << mybar_foo << ">." << std::endl;
result = 1;
}
if ((myfoo_attrib != 2) || (mybar_attrib != 2))
{
TAOX11_TEST_ERROR << "ERROR: Client didn't receive expected replies on my_foo_attrib. "
<< "Expected MyFoo- my_foo_attrib <2> , received <"
<< myfoo_attrib << ">. Expected MyBar- my_foo_attrib <2>, received <"
<< mybar_attrib << ">." << std::endl;
result = 1;
}
if ((myfoo_foo_excep != 1) || (mybar_foo_excep != 2))
{
TAOX11_TEST_ERROR << "ERROR: Client didn't receive expected exceptions on my_foo. "
<< "Expected MyFoo- my_foo_excep <1> , received <"
<< myfoo_foo_excep << ">. Expected MyBar- my_foo_excep <2>, received <"
<< mybar_foo_excep << ">." << std::endl;
result = 1;
}
ami_test_var->shutdown ();
root_poa->destroy (true, false);
_orb->destroy ();
}
catch (const std::exception& e)
{
TAOX11_TEST_ERROR << "exception caught: " << e << std::endl;
return 1;
}
return result;
}
| [
"[email protected]"
] | |
1f4be1d1878d964d6c8cb32501805ea657d2c0e5 | 9a84b600b005c04f7ef9beb7f4aedd86a54d3e33 | /src/libAlgorithm/sar_detect.cpp | 4f6e2a4ce6262acdd47dd4b2535f4a4630db2608 | [] | no_license | hbkooo/shipProject | 05b7bfaf450e240f0850e5a170a8880fa2a208f7 | 517fc5a6a52f95f14001ddf42690f680451f1c01 | refs/heads/master | 2023-06-05T03:46:11.526639 | 2021-06-18T14:44:58 | 2021-06-18T14:44:58 | 221,817,032 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,011 | cpp | //
// Created by hbk on 19-4-19.
//
//#include <caffe/caffe.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <algorithm>
#include <iomanip>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "sar_detect.h"
using namespace caffe; // NOLINT(build/namespaces)
SarDetector::SarDetector(const string& model_file,
const string& weights_file) {
#ifdef CPU_ONLY // work model CPU or GPU
Caffe::set_mode(Caffe::CPU);
std::cout << "use CPU to caculate SAR .... \n";
#else
Caffe::set_mode(Caffe::GPU);
std::cout << "use GPU to caculate SAR .... \n";
#endif
/* Load the network. */
net_.reset(new Net<float>(model_file, TEST)); //��model_file�ж�ȡ����ṹ����ʼ������
net_->CopyTrainedLayersFrom(weights_file); //��Ȩ�ļ��ж�ȡ�����������ʼ��net_
std::cout << "sar model is loading over ... \n";
CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";
CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";
input_layer = net_->input_blobs()[0];
num_channels_ = input_layer->channels(); //��ȡ����ͼƬ��channel
CHECK(num_channels_ == 3 || num_channels_ == 1)
<< "Input layer should have 1 or 3 channels.";
input_geometry_ = cv::Size(input_layer->width(), input_layer->height()); //��ȡ����ͼƬ��size
// Load the binaryproto mean file.
SetMean("104,117,123"); //��ʼ����ͼƬ���������г�����������ʼ����
}
// detector : get information formation : [label, score, xmin, ymin, xmax, ymax]
vector<vector<float> > SarDetector::Detect(const cv::Mat& img) {
input_layer->Reshape(1, num_channels_, input_geometry_.height, input_geometry_.width);
net_->Reshape(); // net reshape
std::vector<cv::Mat> input_channels;
WrapInputLayer(&input_channels); // bind net and input_channels
Preprocess(img, &input_channels); // pre process
net_->ForwardFrom(0); // net forward
/* Copy the output layer to a std::vector */
Blob<float>* result_blob = net_->output_blobs()[0];
const float* result = result_blob->cpu_data(); //the detect out information
const int num_det = result_blob->height(); // height : the number of detection
vector<vector<float> > detections;
for (int k = 0; k < num_det; ++k) {
if (result[0] == -1) { //-1 is background
// Skip invalid detection.
result += 7; // 7 infos represent one location
continue;
}
// Detection format: [label, score, xmin, ymin, xmax, ymax]
vector<float> detection(result + 1, result + 7); //vector to save location
detection[2] = detection[2] * img.cols;
detection[3] = detection[3] * img.rows;
detection[4] = detection[4] * img.cols;
detection[5] = detection[5] * img.rows;
detections.push_back(detection);
// Detection format: [image_id, label, score, xmin, ymin, xmax, ymax]
result += 7;
}
result_blob = nullptr;
result = nullptr;
return detections;
}
/* Load the mean file in binaryproto format. */
void SarDetector::SetMean(const string& mean_value) {
//mean_file or mean_value
cv::Scalar channel_mean;
stringstream ss(mean_value);
vector<float> values;
string item;
while (getline(ss, item, ',')) {
float value = std::atof(item.c_str());
values.push_back(value);
}
CHECK(values.size() == 1 || values.size() == num_channels_) <<
"Specify either 1 mean_value or as many as channels: " << num_channels_;
std::vector<cv::Mat> channels;
for (int i = 0; i < num_channels_; ++i) {
/* Extract an individual channel. */
cv::Mat channel(input_geometry_.height, input_geometry_.width, CV_32FC1,
cv::Scalar(values[i]));
channels.push_back(channel);
}
cv::merge(channels, mean_);
}
/* Wrap the input layer of the network in separate cv::Mat objects
* (one per channel). This way we save one memcpy operation and we
* don't need to rely on cudaMemcpy2D. The last preprocessing
* operation will write the separate channels directly to the input //bang ding
* layer. */
void SarDetector::WrapInputLayer(std::vector<cv::Mat>* input_channels) { //���ォ����input_channels������������wrap��
int width = input_layer->width();
int height = input_layer->height();
float* input_data = input_layer->mutable_cpu_data();
for (int i = 0; i < input_layer->channels(); ++i) {
cv::Mat channel(height, width, CV_32FC1, input_data);
input_channels->push_back(channel);
input_data += width * height;
}
input_data = nullptr;
}
void SarDetector::Preprocess(const cv::Mat& img,
std::vector<cv::Mat>* input_channels) {
/* Convert the input image to the input image format of the network. */
cv::Mat sample;
if (img.channels() == 3 && num_channels_ == 1)
cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
else if (img.channels() == 4 && num_channels_ == 1)
cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
else if (img.channels() == 4 && num_channels_ == 3)
cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
else if (img.channels() == 1 && num_channels_ == 3)
cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
else
sample = img;
cv::Mat sample_resized;
if (sample.size() != input_geometry_)
cv::resize(sample, sample_resized, input_geometry_);
else
sample_resized = sample;
cv::Mat sample_float;
if (num_channels_ == 3)
sample_resized.convertTo(sample_float, CV_32FC3);
else
sample_resized.convertTo(sample_float, CV_32FC1);
cv::Mat sample_normalized;
cv::subtract(sample_float, mean_, sample_normalized);
/* This operation will write the separate BGR planes directly to the
* input layer of the network because it is wrapped by the cv::Mat
* objects in input_channels. */
cv::split(sample_normalized, *input_channels);
CHECK(reinterpret_cast<float*>(input_channels->at(0).data)
== net_->input_blobs()[0]->cpu_data())
<< "Input channels are not wrapping the input layer of the network.";
}
SarDetector::~SarDetector() {
input_layer = nullptr;
}
| [
"[email protected]"
] | |
e55ebf74225bc98210c064c285bb57a9e80b17ac | 149a7e1c014da6cb0f3c87f6748a8b3fd440e6c0 | /core.liberation/ui/liberation_notifications.hpp | dd8d64168a0472a7d19e686b01c8e4a3851f4509 | [] | no_license | TheFr3eMan/Liberation-RX | 1d91defb6ccd40f328afb7185d46b3d621c3f335 | 81ed419e785e68ae0cffaa9ba7274519893cd467 | refs/heads/master | 2023-01-08T10:43:14.350113 | 2020-11-05T12:14:00 | 2020-11-05T12:14:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,916 | hpp | class CfgNotifications
{
class lib_default_notification {
duration = 10;
soundClose = "defaultNotificationClose";
colorIconPicture[] = {1,1,1,1};
colorIconText[] = {1,1,1,1};
priority = 5;
};
class lib_sector_captured : lib_default_notification
{
title = $STR_NOTIFICATION_SECTORCAPTURED_TITLE;
description = $STR_NOTIFICATION_SECTORCAPTURED_TEXT;
iconPicture = "res\notif\ui_notif_sec_cap.paa";
color[] = {0,1,0,1};
sound = "taskSucceeded";
};
class lib_sector_captured_info : lib_default_notification
{
title = "Info Capture:";
description = "%1";
iconPicture = "res\notif\ui_notif_sec_cap.paa";
color[] = {0,1,0,1};
};
class lib_sector_attacked : lib_default_notification
{
title = $STR_NOTIFICATION_SECTORATTACKED_TITLE;
description = $STR_NOTIFICATION_SECTORATTACKED_TEXT;
iconPicture = "res\notif\ui_notif_sec_una.paa";
color[] = {1,1,0,1};
sound = "taskCanceled";
};
class lib_sector_lost : lib_default_notification
{
title = $STR_NOTIFICATION_SECTORLOST_TITLE;
description = $STR_NOTIFICATION_SECTORLOST_TEXT;
iconPicture = "res\notif\ui_notif_sec_los.paa";
color[] = {1,0,0,1};
sound = "taskFailed";
};
class lib_sector_safe : lib_default_notification
{
title = $STR_NOTIFICATION_SECTORSAFE_TITLE;
description = $STR_NOTIFICATION_SECTORSAFE_TEXT;
iconPicture = "res\notif\ui_notif_sec_saf.paa";
color[] = {0,0.35,1,1};
sound = "taskUpdated";
priority = 3;
};
class lib_fob_built : lib_default_notification
{
title = $STR_NOTIFICATION_FOBBUILT_TITLE;
description = $STR_NOTIFICATION_FOBBUILT_TEXT;
iconPicture = "res\notif\ui_notif_fob_new.paa";
color[] = {0,0.35,1,1};
sound = "taskUpdated";
};
class lib_fob_safe : lib_default_notification
{
title = $STR_NOTIFICATION_FOBSAFE_TITLE;
description = $STR_NOTIFICATION_FOBSAFE_TEXT;
iconPicture = "res\notif\ui_notif_fob_sec.paa";
color[] = {0,0.35,1,1};
sound = "taskUpdated";
priority = 3;
};
class lib_fob_attacked : lib_default_notification
{
title = $STR_NOTIFICATION_FOBATTACKED_TITLE;
description = $STR_NOTIFICATION_FOBATTACKED_TEXT;
iconPicture = "res\notif\ui_notif_fob_und.paa";
color[] = {1,1,0,1};
sound = "taskCanceled";
};
class lib_fob_lost : lib_default_notification
{
title = $STR_NOTIFICATION_FOBLOST_TITLE;
description = $STR_NOTIFICATION_FOBLOST_TEXT;
iconPicture = "res\notif\ui_notif_fob_los.paa";
color[] = {1,0,0,1};
sound = "taskFailed";
};
class lib_battlegroup : lib_default_notification
{
title = $STR_NOTIFICATION_BATTLEGROUP_TITLE;
description = $STR_NOTIFICATION_BATTLEGROUP_TEXT;
iconPicture = "res\notif\ui_notif_bgp.paa";
color[] = {1,0,0,1};
sound = "taskFailed";
};
class lib_incoming : lib_battlegroup
{
description = $STR_NOTIFICATION_INCOMING_TEXT;
};
class lib_intel : lib_default_notification
{
title = $STR_NOTIFICATION_INTEL_TITLE;
iconPicture = "res\notif\ui_notif_int.paa";
color[] = {0,0.35,1,1};
sound = "taskUpdated";
};
class lib_intel_prisoner : lib_intel
{
description = $STR_NOTIFICATION_PRISONER_TEXT;
};
class lib_intel_document : lib_intel
{
description = $STR_NOTIFICATION_DOCUMENT_TEXT;
};
class lib_intel_fob : lib_intel
{
description = $STR_NOTIFICATION_FOB_TEXT;
};
class lib_intel_convoy : lib_intel
{
description = $STR_NOTIFICATION_CONVOY_SPOTTED_TEXT;
};
class lib_secondary_fob_destroyed : lib_default_notification
{
title = $STR_NOTIFICATION_SECONDARY_TITLE;
description = $STR_NOTIFICATION_SECONDARY_TEXT;
iconPicture = "res\notif\ui_notif_sob.paa";
color[] = {0,1,0,1};
sound = "taskSucceeded";
};
class lib_secondary_convoy_destroyed : lib_secondary_fob_destroyed
{
description = $STR_NOTIFICATION_CONVOY_DESTROYED_TEXT;
};
class lib_reinforcements : lib_default_notification
{
title = $STR_NOTIFICATION_REINFORCEMENTS_TITLE;
description = $STR_NOTIFICATION_REINFORCEMENTS_TEXT;
iconPicture = "res\notif\ui_notif_ref.paa";
color[] = {1,1,0,1};
sound = "taskCanceled";
};
class lib_reinforcementsblu : lib_default_notification
{
title = $STR_NOTIFICATION_REINFORCEMENTS_TITLE;
description = "Air Supremacy is Incoming...";
iconPicture = "res\notif\ui_notif_ref.paa";
color[] = {0,0.35,1,1};
sound = "taskUpdated";
};
class lib_intel_sar : lib_intel
{
description = $STR_NOTIFICATION_SAR_STARTED;
};
class lib_intel_sar_failed : lib_secondary_fob_destroyed
{
description = $STR_NOTIFICATION_SAR_FAILED;
color[] = {1,0,0,1};
sound = "taskFailed";
};
class lib_intel_sar_succeeded : lib_secondary_fob_destroyed
{
description = $STR_NOTIFICATION_SAR_SUCCESS;
};
}; | [
"[email protected]"
] | |
f73b38a2734e09f221251c5da13919daebc17ec4 | ee32b610900ff75dd096ea07461aea0596d9edd2 | /logdevice/admin/safety/CheckMetaDataLogRequest.cpp | 4576c2ed36a30973848fa7acaf02ca160de684ff | [
"BSD-3-Clause"
] | permissive | kasshu/LogDevice | 61e0c6b2f3b4c123d08c5a3e9c189920176b775e | 4f8f248f25ffb09f984b91415297b62e5017e96d | refs/heads/master | 2020-03-31T22:04:22.061797 | 2018-10-11T08:07:29 | 2018-10-11T08:12:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,996 | cpp | /**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "CheckMetaDataLogRequest.h"
#include <boost/format.hpp>
#include "logdevice/common/ClusterState.h"
#include "logdevice/common/Processor.h"
#include "logdevice/common/Worker.h"
#include "logdevice/common/Timestamp.h"
#include "logdevice/server/FailureDetector.h"
namespace facebook { namespace logdevice {
CheckMetaDataLogRequest::CheckMetaDataLogRequest(
logid_t log_id,
std::chrono::milliseconds timeout,
std::shared_ptr<Configuration> config,
const ShardAuthoritativeStatusMap& shard_status,
std::shared_ptr<ShardSet> op_shards,
int operations,
const SafetyMargin* safety_margin,
bool check_metadata_nodeset,
Callback callback)
: Request(RequestType::CHECK_METADATA_LOG),
log_id_(log_id),
timeout_(timeout),
config_(std::move(config)),
shard_status_(shard_status),
op_shards_(std::move(op_shards)),
operations_(operations),
safety_margin_(safety_margin),
check_metadata_nodeset_(check_metadata_nodeset),
callback_(std::move(callback)) {
ld_check(op_shards_ != nullptr);
if (!check_metadata_nodeset_) {
ld_check(log_id != LOGID_INVALID);
ld_check(!MetaDataLog::isMetaDataLog(log_id_));
}
ld_check(callback_ != nullptr);
}
CheckMetaDataLogRequest::~CheckMetaDataLogRequest() {
ld_check(current_worker_.val_ == -1 ||
current_worker_ == Worker::onThisThread()->idx_);
}
Request::Execution CheckMetaDataLogRequest::execute() {
if (check_metadata_nodeset_) {
checkMetadataNodeset();
} else {
ld_debug("CheckMetaDataLogRequest::execute for log %lu", log_id_.val_);
// Worker thread on which the request is running
current_worker_ = Worker::onThisThread()->idx_;
fetchHistoricalMetadata();
}
return Execution::CONTINUE;
}
std::tuple<bool, bool, NodeLocationScope>
CheckMetaDataLogRequest::checkReadWriteAvailablity(
const StorageSet& storage_set,
const ReplicationProperty& replication_property) {
bool safe_writes = true;
bool safe_reads = true;
NodeLocationScope fail_scope;
if (operations_ & Operation::DISABLE_WRITES) {
ReplicationProperty replication_prop =
extendReplicationWithSafetyMargin(replication_property, true);
if (replication_prop.isEmpty()) {
safe_writes = false;
} else {
safe_writes =
checkWriteAvailability(storage_set, replication_prop, &fail_scope);
}
}
if (operations_ & Operation::DISABLE_READS) {
ReplicationProperty replication_prop =
extendReplicationWithSafetyMargin(replication_property, false);
if (replication_prop.isEmpty()) {
safe_reads = false;
} else {
safe_reads = checkReadAvailability(storage_set, replication_prop);
}
}
return std::make_tuple(safe_reads, safe_writes, fail_scope);
}
void CheckMetaDataLogRequest::checkMetadataNodeset() {
auto metadatalogs_config = config_->serverConfig()->getMetaDataLogsConfig();
auto metadatalog_group = config_->serverConfig()->getMetaDataLogGroup();
if (!metadatalog_group) {
complete(E::OK, Impact::ImpactResult::NONE, EPOCH_INVALID, {}, "");
return;
}
ReplicationProperty replication_property =
ReplicationProperty::fromLogAttributes(metadatalog_group->attrs());
// TODO(T15517759): metadata log storage set should use ShardID.
auto storage_set =
EpochMetaData::nodesetToStorageSet(metadatalogs_config.metadata_nodes);
NodeLocationScope fail_scope;
bool safe_reads;
bool safe_writes;
std::tie(safe_reads, safe_writes, fail_scope) =
checkReadWriteAvailablity(storage_set, replication_property);
if (safe_writes && safe_reads) {
ld_debug("It is safe to perform operations on metadata nodes");
complete(E::OK, Impact::ImpactResult::NONE, EPOCH_INVALID, {}, "");
} else {
std::string message = "Operation would cause loss of read "
"or wite availability for metadata logs";
ld_warning("ERROR: %s", message.c_str());
complete(E::FAILED,
Impact::ImpactResult::METADATA_LOSS,
EPOCH_INVALID,
std::move(storage_set),
std::move(message));
}
}
void CheckMetaDataLogRequest::complete(Status st,
int impact_result,
epoch_t error_epoch,
StorageSet storage_set,
std::string message) {
// call user provided callback
callback_(st,
impact_result,
log_id_,
error_epoch,
std::move(storage_set),
std::move(message));
// destroy the request
delete this;
}
void CheckMetaDataLogRequest::fetchHistoricalMetadata() {
nodeset_finder_ = std::make_unique<NodeSetFinder>(
log_id_,
timeout_,
[this](Status st) {
if (st != E::OK) {
if (st == E::NOTINCONFIG || st == E::NOTFOUND) {
complete(st, 0, EPOCH_INVALID, {}, "");
return;
}
std::string message = boost::str(
boost::format(
"Fetching historical metadata for log %lu FAILED: %s. ") %
log_id_.val() % error_description(st));
complete(st, Impact::ImpactResult::ERROR, EPOCH_INVALID, {}, message);
return; // `this` has been destroyed.
}
auto result = nodeset_finder_->getResult();
for (const auto& interval : *result) {
if (!onEpochMetaData(interval.second)) {
// `this` was destroyed.
return;
}
}
complete(E::OK, Impact::ImpactResult::NONE, EPOCH_INVALID, {}, "");
},
(read_epoch_metadata_from_sequencer_
? NodeSetFinder::Source::BOTH
: NodeSetFinder::Source::METADATA_LOG));
nodeset_finder_->start();
}
// returns empty ReplicationProperty if is impossible to satisfy
// resulting replicaiton property
ReplicationProperty CheckMetaDataLogRequest::extendReplicationWithSafetyMargin(
const ReplicationProperty& replication_base,
bool add) const {
ReplicationProperty replication_new(replication_base);
auto scope = NodeLocation::nextSmallerScope(NodeLocationScope::ROOT);
int prev = 0;
while (scope != NodeLocationScope::INVALID) {
int replication = replication_base.getReplication(scope);
// Do not consider the scope if the user did not specify a replication
// factor for it
if (replication != 0) {
auto safety = safety_margin_->find(scope);
if (safety != safety_margin_->end()) {
if (add) {
replication += safety->second;
} else {
replication -= safety->second;
}
if (replication <= 0) {
// can't be satisfied. fail on this
return ReplicationProperty();
}
// required to bypass ReplicationProperty validation
// as lower scope can't be smaller
int max_for_higher_domians = std::max(replication, prev);
replication_new.setReplication(scope, max_for_higher_domians);
prev = max_for_higher_domians;
}
}
scope = NodeLocation::nextSmallerScope(scope);
}
return replication_new;
}
bool CheckMetaDataLogRequest::onEpochMetaData(EpochMetaData metadata) {
ld_check(Worker::onThisThread()->idx_ == current_worker_);
ld_check(metadata.isValid());
NodeLocationScope fail_scope;
bool safe_writes;
bool safe_reads;
const auto since = metadata.h.effective_since.val_;
const auto epoch = metadata.h.epoch.val_;
std::tie(safe_reads, safe_writes, fail_scope) =
checkReadWriteAvailablity(metadata.shards, metadata.replication);
if (safe_writes && safe_reads) {
ld_debug("for log %lu, epochs [%u, %u] is OK", log_id_.val_, since, epoch);
return true;
}
// in case we can't replicate we return epoch & nodeset for it
std::unordered_set<node_index_t> nodes_to_drain;
for (const auto& shard_id : *op_shards_) {
nodes_to_drain.insert(shard_id.node());
}
std::string message;
if (!safe_writes) {
message = boost::str(
boost::format(
"Drain on (%u shards, %u nodes) would cause "
"loss of write availability for log %lu, epochs [%u, %u], as in "
"that storage set not enough %s domains would be "
"available for writes. ") %
op_shards_->size() % nodes_to_drain.size() % log_id_.val() % since %
epoch % NodeLocation::scopeNames()[fail_scope].c_str());
}
if (!safe_reads) {
message += boost::str(
boost::format(
"Disabling reads on (%u shards, %u nodes) would cause "
"loss of read availability for log %lu, epochs [%u, %u], as "
"that storage would not constitute f-majority ") %
op_shards_->size() % nodes_to_drain.size() % log_id_.val() % since %
epoch);
}
int impact_result = 0;
if (!safe_reads) {
impact_result |= Impact::ImpactResult::READ_AVAILABILITY_LOSS;
}
if (!safe_writes) {
impact_result |= Impact::ImpactResult::REBUILDING_STALL;
// TODO #22911589 check do we loose write availablility
}
complete(E::FAILED,
impact_result,
metadata.h.effective_since,
std::move(metadata.shards),
std::move(message));
return false;
}
bool CheckMetaDataLogRequest::checkWriteAvailability(
const StorageSet& storage_set,
const ReplicationProperty& replication,
NodeLocationScope* fail_scope) const {
// We use FailureDomainNodeSet to determine if draining shards in
// `op_shards_` would result in this StorageSet being unwritable. The boolean
// attribute indicates for each node whether it will be able to take writes
// after the drain. As such, a node can take writes if:
// * It's weight is > 0;
// * it's not part of `op_shards_`;
// * it's FULLY_AUTHORITATIVE (ie it's not been drained or being drained,
// or it's not being rebuilt / in repair).
// TODO #21954681 Add safety threshold x:
// if N nodes are required to maintain write availability, make sure to
// always have N+x nodes to have room for organic failures of x nodes
FailureDomainNodeSet<bool> available_node_set(
storage_set, config_->serverConfig(), replication);
for (const ShardID& shard : storage_set) {
const auto& node = config_->serverConfig()->getNode(shard.node());
if (node && node->isWritableStorageNode()) {
if (!op_shards_->count(shard)) {
AuthoritativeStatus status = shard_status_.getShardStatus(shard);
if (status == AuthoritativeStatus::FULLY_AUTHORITATIVE) {
available_node_set.setShardAttribute(shard, true);
}
}
}
}
return available_node_set.canReplicate(true, fail_scope);
}
bool CheckMetaDataLogRequest::checkReadAvailability(
const StorageSet& storage_set,
const ReplicationProperty& replication) const {
// We use FailureDomainNodeSet to determine if disabling reads for shards in
// `op_shards_` would result in this StorageSet being unreadable.
// The boolean attribute indicates for each node whether it will be able to
// serve reads after the operation. As such, a node can serve reads if:
// * It's weight is >= 0 (storage node);
// * it's not part of `op_shards_`;
// Authoritative status is set for all shards and it is taken into
// account by isFmajority.
// We should have f-majority of FULLY_AUTHORITATIVE (ie it's not been drained
// or being drained, or it's not being rebuilt / in repair) shards, excluding
// shards on which we are going to be stopped.
FailureDomainNodeSet<bool> available_node_set(
storage_set, config_->serverConfig(), replication);
for (const ShardID& shard : storage_set) {
const auto& node = config_->serverConfig()->getNode(shard.node());
if (node && node->isReadableStorageNode()) {
AuthoritativeStatus status = shard_status_.getShardStatus(shard);
available_node_set.setShardAuthoritativeStatus(shard, status);
if ((!op_shards_ || !op_shards_->count(shard)) && isAlive(shard.node())) {
available_node_set.setShardAttribute(shard, true);
}
}
}
FmajorityResult health_state = available_node_set.isFmajority(true);
// we treat NON_AUTHORITATIVE as unsafe, as we may increase damage,
// i.e. more records will become unaccesible if stop more nodes
auto res = health_state == FmajorityResult::AUTHORITATIVE_COMPLETE ||
health_state == FmajorityResult::AUTHORITATIVE_INCOMPLETE;
return res;
}
bool CheckMetaDataLogRequest::isAlive(node_index_t index) const {
auto* cluster_state = Worker::getClusterState();
if (cluster_state) {
return cluster_state->isNodeAlive(index);
} else {
return true;
}
}
}} // namespace facebook::logdevice
| [
"[email protected]"
] | |
e64b6d067b94cede11b8ba751cec42430d0adbf8 | 3cf8038cb4809c43065e031e41e300b79be17b93 | /ppm/ppm_loader.h | 255cc67ed0b2f341df2221896960494ea13122d2 | [] | no_license | pdrabik223/ppm_editor | 30e7dadc718c597220c71256b471207607a21eb5 | 5a5d1004a909067d075bb43d36ad1740ebf71c78 | refs/heads/main | 2023-06-20T20:45:41.694808 | 2021-07-18T00:10:31 | 2021-07-18T00:10:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | //
// Created by studio25 on 07.07.2021.
//
#include "../canvas.h"
#include "file_exception.h"
#include <fstream>
#include <string>
#ifndef PPM_LOADER_H_
#define PPM_LOADER_H_
void LoadFromPpm(std::string path, Canvas &image);
void SaveToPpm(const Canvas & target,const std::string& path);
bool IsComment(const char &letter);
void IgnoreComment(std::fstream &plik);
void HandleChar(std::fstream &plik);
int ReadNumber(std::fstream &plik);
unsigned char CheckColor(int color);
void ReadHeader(std::fstream &plik);
#endif // PPM_LOADER_H_
| [
"[email protected]"
] | |
419d039ff0c05f7cf6de24130383548975590206 | 58ed5cda1443024c0595730ff93ccc5b6efa52f2 | /Item/item.cpp | 18ed467a246ef8db5c6f16b4c935f35c042ad9d9 | [] | no_license | fenixnix/InfinityArena | a10b80ebccc5a4f5e67ba2b16109cd721a0686af | b5e95c030ea39d43d56d8f5da72e45f6b515deba | refs/heads/master | 2020-03-27T20:31:18.217700 | 2018-09-02T10:17:16 | 2018-09-02T10:17:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | cpp | #include "item.h"
#include "itemfactory.h"
#include "Render/nglrender.h"
Item::Item()
{
}
void Item::drawOnMap(float x, float y)
{
NGLRender* render = NGLRender::the();
// render->useTex(getDrawID());
// render->drawPoint(x,y,0.2);
render->setMode(MODE_SPRITE);
render->drawTextSprite(getDrawID(),x,y,0.2,64);
}
| [
"[email protected]"
] | |
c12088f7e5114776bbed51055d6f9fd1b78183e1 | 1fc4f5203d231f0abe1d1168298dd41e0ad2dc2e | /Bcode_WintgTerm_V2.6.6_Build_20180929(界面统一版本)/GpcTerms/BasicTerm/DyncCerty.cpp | 40c9ac792d39ab1223c15ddff1b04582f14208e5 | [] | no_license | Huixaing/Project | 79d5ceb89620c0de6278cb211ef837c728f1af71 | fc3ab640265eaaed0c0a2c217370196525e1efc3 | refs/heads/master | 2020-03-30T00:44:07.773723 | 2018-10-08T05:44:22 | 2018-10-08T05:44:22 | 150,541,134 | 1 | 5 | null | null | null | null | GB18030 | C++ | false | false | 2,896 | cpp | // DyncCerty.cpp : implementation file
//
#include "stdafx.h"
#include "DyncCerty.h"
#include "DynCertificate.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDyncCerty dialog
CDyncCerty::CDyncCerty(CWnd* pParent /*=NULL*/)
: CDialog(CDyncCerty::IDD, pParent)
{
//{{AFX_DATA_INIT(CDyncCerty)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
CDyncCerty::~CDyncCerty()
{
}
void CDyncCerty::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDyncCerty)
DDX_Control(pDX, IDC_DC_PWD, m_pwd);
DDX_Control(pDX, IDC_DC_USER, m_userid);
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDyncCerty, CDialog)
//{{AFX_MSG_MAP(CDyncCerty)
ON_BN_CLICKED(IDOK, OnOk)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDyncCerty message handlers
void CDyncCerty::OnCancel()
{
isOk=false;
CDialog::OnCancel();
}
void CDyncCerty::OnOk()
{
m_userid.GetWindowText(m_strUser);
m_pwd.GetWindowText(m_strPwd);
CDynCertificate dynCert;
if(!dynCert.DynInit())
{
AfxMessageBox("动态口令认证服务初始化失败");
exit(0);
}
int rc = dynCert.DynVerify((char*)(LPCTSTR)m_strUser,(char*)(LPCTSTR)m_strPwd);
dynCert.DynUninit();
isOk=false;
if(rc==AUTH_SUCCESS||rc == AUTH_ERR_NET){
if(rc == AUTH_ERR_NET){
AfxMessageBox("连接口令认证服务器出错,现在采用本地认证,请速联系管理员!!");
}
isOk=true;
}else if(rc == AUTH_USER_NOTEXIST){
AfxMessageBox("认证服务器上不存在本用户,请重试。");
}
else
{
AfxMessageBox("口令认证失败,请联系管理员");
}
if(!isOk){
m_userid.SetWindowText("");
m_pwd.SetWindowText("");
m_userid.SetFocus();
return;
}else{
/* KillTimer(13);*/
CDialog::OnOK();
}
}
BOOL CDyncCerty::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
// TODO: Add your specialized code here and/or call the base class
CWnd* pWndFocus = GetFocus();
if ((pMsg->message == WM_KEYDOWN) &&
((pMsg->wParam == VK_RETURN) || (pMsg->wParam == VK_ESCAPE)))
{
// Special case: if control with focus is an edit control with
// ES_WANTRETURN style, let it handle the Return key.
TCHAR szClass[10];
if ((pMsg->wParam == VK_RETURN) &&((pWndFocus = GetFocus()) != NULL) &&IsChild(pWndFocus))
{
CWnd *pWnd;
if(pWndFocus == GetDlgItem(IDC_DC_USER))
{
pWnd = GetDlgItem(IDC_DC_PWD);
GotoDlgCtrl(pWnd);
} else if(pWndFocus == GetDlgItem(IDC_DC_PWD)){
pWnd = GetDlgItem(IDOK);
GotoDlgCtrl(pWnd);
OnOk();
}
}
return TRUE;
}
return CDialog::PreTranslateMessage(pMsg);
}
| [
"[email protected]"
] | |
05ae4f3663e68d2e8471e8bc546b5ff8f322529a | 98daaaf2a4521fea24f1ebe52e95d45e038142af | /l5root/l5_14/Tests.h | 1a11f4f8b31877f29cf95ffeaa839221764c0172 | [] | no_license | ionut-mntn/Laboratoare-OOP-Cpp | 47d7eaeaf91fc70cb5d777af7b76e1542e1a33af | 282fc0bc123e146a7a6461139185af8a98cf44e9 | refs/heads/main | 2023-03-17T06:29:00.434348 | 2021-03-04T07:34:38 | 2021-03-04T07:34:38 | 343,857,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 369 | h | #pragma once
#include "Movie.h"
#include "Repository.h"
#include "Validator.h"
#include "Controller.h"
namespace Tests{
void testRepositoryConstructor();
void testExists();
void testExists2();
void testAdd();
void testAdd2();
void testAdd3();
void testDel();
void testDel2();
void testDel3();
void testEdit();
void testEdit2();
void testEdit3();
void testAll();
} | [
"[email protected]"
] | |
6535edfb17dd63af5e29bbaf805a403b1c2be5a8 | 2da291d5877ed3edbde5d15ca91b4d327504dee4 | /Project 2/Book.h | 3b76ab452aa5584dbd5358c0a1e2414af7a7191a | [] | no_license | samboehle/CSCI1300 | ae2a9007a1747cd44db745bed6f464aa7b036e14 | 50dd5f629b21c2034df248bb94520a66e2d86e2e | refs/heads/main | 2023-09-03T02:43:46.357950 | 2021-10-28T22:39:55 | 2021-10-28T22:39:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 417 | h | // CSCI1300 Spring 2020
// Author: Samuel Boehle
//Recitation: 101 - James Watson
//Project 2 - Task #1
#include <string>
using namespace std;
//Defining book class
class Book{
public:
Book();
Book(string, string);
string getTitle();
string getAuthor();
void setTitle(string);
void setAuthor(string);
private:
string title;
string author;
}; | [
"[email protected]"
] | |
9ea1cc033ddcb0359dea0e4429bf5f90d116228b | 8f07a718d93a324bdc196071082d8f8db27a6b1d | /KHLUG_PROJECT/Configure.h | 4f83d1e90ed40d992c6fd02d08732c97efc5c669 | [] | no_license | siosio34/NetworkProgramming | 2b6cc8d0cb4528d485e4f8e29f6ba5d860b3d0d8 | e88458861135273cdfcc01c7604cf5281748e685 | refs/heads/master | 2020-12-13T21:44:09.892721 | 2016-05-17T04:27:24 | 2016-05-17T04:27:24 | 47,766,669 | 2 | 1 | null | null | null | null | UHC | C++ | false | false | 4,452 | h | #pragma once
#define HAVE_REMOTE
#define ETHER_ADDR_LEN 6
#define ETHERTYPE_IP 0x0800
#define ETHERTYPE_ARP 0x0806
#define ETHERTYPE_REVARP 0X8035
#define ETHERTYPE_IPv6 0X86dd
#define ARP_IP_LEN 4
#define ARP_REQUEST 1
#define ARP_REPLY 2
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
#define TCP_PRO 6
#define UDP_PRO 17
#define WORKING_BUFFER_SIZE 15000
#define MAX_TRIES 3
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
#define GET_GATEMAC_MODE 0
#define GET_VICTIMEMAC_MODE 1
#define MAXBUF 0xFFFF
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "IPHLPAPI.lib")
#pragma comment(lib, "windivert.lib")
#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#include <iphlpapi.h>
#include <Windows.h>
#include <conio.h>
#include <iostream>
#include <string>
#include <vector>
#include <thread> // c+ 11 쓰레드를 쓰기 위해 추가한 헤더.
#include <mutex> // Mutex 객체 구현
#include <chrono> // c+ 11 에서 지원해주는 시간 코드
// 오픈 소스인 pcap 라이브러리와 windivert 라이브러리 인클루드
// winpcap과 windivert의 차이는 오는 패킷이나 가는 패킷을 가로 챌수 있는지 아님 보기만 하는지 차이
// windiver 함수를 사용할려면 관리자 모드로 켜야되고 이상하게 디버깅을 시도하면 패킷 자체가 안열림 ( 아마 드라이버 서명 문제인듯 )
#include <windivert.h>
#include <pcap.h>
using namespace std;
typedef struct etc_header {
u_int8_t ether_dhost[ETHER_ADDR_LEN]; //destination Mac
u_int8_t ether_shost[ETHER_ADDR_LEN]; //source Mac
u_int16_t ether_type;
}ETC_HEADER;
typedef struct arp_header
{
u_short hard_type; //
u_short Pro_type; //
u_char hard_length;
u_char pro_length;
u_short op_code;
u_char source_Macaddr[ETHER_ADDR_LEN]; //sender hard address
u_char source_ipaddr[ARP_IP_LEN]; // sender sourse ip
u_char Des_Macaddr[ETHER_ADDR_LEN]; // target Hard address
u_char Des_ipaddr[ARP_IP_LEN]; // target source IP
}ARP_HEADER;
typedef struct infection {
ETC_HEADER etc;
ARP_HEADER arp;
} infection;
/* IPv4 header */
typedef struct ip_header {
u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)
u_char tos; // Type of service
u_short tlen; // Total length
u_short identification; // Identification
u_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)
u_char ttl; // Time to live
u_char proto; // Protocol
u_short crc; // Header checksum
u_char saddr[4]; // Source address
u_char daddr[4]; // Destination address
u_int op_pad; // Option + Padding
}IPHEADER;
// TCP Header
typedef struct tcp_header {
unsigned short sourceport; // source port
unsigned short destport; // destination port
unsigned long seqno; // sequenz number
unsigned long ackno; // acknowledge number
unsigned char th_x2 : 4;
unsigned char hlen:4; // Header length
unsigned char flag; // flags
unsigned short window; // window
unsigned short chksum; // checksum
unsigned short urgptr; // urgend pointer
unsigned int op_pad;
}TCPHEADER, *PTCPHEADER;
/* UDP header*/
typedef struct udp_header {
u_short sport; // Source port
u_short dport; // Destination port
u_short len; // Datagram length
u_short crc; // Checksum
}UDPHEADER;
typedef struct Basic_ip_mac_addr
{
vector<u_char> attacker_ip; // 어택커 ip
vector<u_char> attacker_mac; // 어택커맥
vector<u_char> gate_ip; // 게이트웨어 ip
vector<u_char> gate_mac; // 게이트웨어 mac
vector<u_char> victim_ip; // 희생자 ip
vector<u_char> victim_mac; // victim mac
} Basic_ip_mac_addr;
//TCP PAYLOAD 길이 ip header의 총길이 - ip헤더크기 - tcp 헤더크기
//UDP DATAGRAM 길이 호스트 바이 오더로 바뀬 udp_header.len에서 udp 헤더크기를 빼주어야한다.
typedef struct
{
WINDIVERT_ADDRESS send_addr; // 보낼 방향 및 플래그 설정
chrono::system_clock::time_point receive_packet_time; // 그 패킷을 저장한 시간
int len;
u_char buff[MAXBUF];
} SENDSAVEPACKET;
typedef struct
{
WINDIVERT_ADDRESS send_addr; // 보낼 방향 및 플래그 설정
u_char pay_load_data[65535];
} SENDTCPPACKET, *PSENDTCPPACKET;
| [
"[email protected]"
] | |
d7b0d94482389798b64323a662200f96e52ff8bb | d4d494be69e013b4069db6b1e68afdef5f124484 | /AudioEditor/TXT_Body_Italian.cpp | 7609cc061a676390c90dbe1355735bae44bd7a1d | [] | no_license | LigasN/AudioEditor | d268f8fcce9dbd5b9ba316435f4462df957c27a3 | d507f2646b2fd6de387036c48497526ec5c94b1b | refs/heads/master | 2020-05-17T14:39:16.711767 | 2019-06-10T16:22:38 | 2019-06-10T16:22:38 | 183,768,286 | 0 | 1 | null | 2019-06-09T12:49:19 | 2019-04-27T12:10:42 | C++ | UTF-8 | C++ | false | false | 739 | cpp | #include "TXT_Body_Italian.h"
#include <assert.h>
void TXT_Body_Italian::Load_Texts_Matrix(std::vector <std::wstring> &newText)
{
newText.clear();
assert(newText.empty());
std::wifstream file;
file.open("Texts_Italian.txt", std::ios::in);
std::wstring partLine{};
std::wstring wholeLine{};
std::wstring noEnter = L";";
int i{};
while (std::getline(file, partLine))
{
if (partLine.empty())
{
wholeLine += L"\n";
newText.push_back(wholeLine);
wholeLine.clear();
assert(wholeLine.empty());
}
else if (partLine == noEnter)
{
newText.push_back(wholeLine);
wholeLine.clear();
assert(wholeLine.empty());
}
else
{
wholeLine += partLine;
}
}
newText.push_back(wholeLine);
file.close();
}
| [
"[email protected]"
] | |
801ee9e266410a7cde26c276f518a84a286e706d | 4cd7f9447801592739d8b05c4f41f9f210fdb784 | /src/chrome/browser/android/signin/signin_manager_android.cc | d11e1adb0b409483ae392245111f4f2d5091b0ea | [
"BSD-3-Clause"
] | permissive | crash0verrid3/Firework-Browser | 15fbcdcdf521f1b1a1f609310fba9a5ab520b92a | 9f2e99135fa4230581bde1806ca51e484372be50 | refs/heads/master | 2021-01-10T13:18:41.267236 | 2015-10-18T23:04:10 | 2015-10-18T23:04:10 | 44,147,842 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,128 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "chrome/browser/android/signin/signin_manager_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/prefs/pref_service.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "base/thread_task_runner_handle.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/browsing_data_helper.h"
#include "chrome/browser/browsing_data/browsing_data_remover.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/account_tracker_service_factory.h"
#include "chrome/browser/signin/oauth2_token_service_delegate_android.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/signin/core/browser/account_tracker_service.h"
#include "components/signin/core/browser/profile_oauth2_token_service.h"
#include "components/signin/core/browser/signin_manager.h"
#include "components/signin/core/browser/signin_metrics.h"
#include "components/signin/core/common/profile_management_switches.h"
#include "google_apis/gaia/gaia_constants.h"
#include "jni/SigninManager_jni.h"
#if defined(ENABLE_CONFIGURATION_POLICY)
#include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_mobile.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/cloud/cloud_policy_core.h"
#include "components/policy/core/common/cloud/cloud_policy_store.h"
#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "net/url_request/url_request_context_getter.h"
#endif
using bookmarks::BookmarkModel;
namespace {
// A BrowsingDataRemover::Observer that clears all Profile data and then
// invokes a callback and deletes itself.
class ProfileDataRemover : public BrowsingDataRemover::Observer {
public:
ProfileDataRemover(Profile* profile, const base::Closure& callback)
: callback_(callback),
origin_runner_(base::ThreadTaskRunnerHandle::Get()),
remover_(BrowsingDataRemover::CreateForUnboundedRange(profile)) {
remover_->AddObserver(this);
remover_->Remove(BrowsingDataRemover::REMOVE_ALL, BrowsingDataHelper::ALL);
}
~ProfileDataRemover() override {}
void OnBrowsingDataRemoverDone() override {
remover_->RemoveObserver(this);
origin_runner_->PostTask(FROM_HERE, callback_);
origin_runner_->DeleteSoon(FROM_HERE, this);
}
private:
base::Closure callback_;
scoped_refptr<base::SingleThreadTaskRunner> origin_runner_;
BrowsingDataRemover* remover_;
DISALLOW_COPY_AND_ASSIGN(ProfileDataRemover);
};
} // namespace
SigninManagerAndroid::SigninManagerAndroid(JNIEnv* env, jobject obj)
: profile_(NULL),
weak_factory_(this) {
java_signin_manager_.Reset(env, obj);
profile_ = ProfileManager::GetActiveUserProfile();
DCHECK(profile_);
pref_change_registrar_.Init(profile_->GetPrefs());
pref_change_registrar_.Add(
prefs::kSigninAllowed,
base::Bind(&SigninManagerAndroid::OnSigninAllowedPrefChanged,
base::Unretained(this)));
}
SigninManagerAndroid::~SigninManagerAndroid() {}
void SigninManagerAndroid::CheckPolicyBeforeSignIn(JNIEnv* env,
jobject obj,
jstring username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
username_ = base::android::ConvertJavaStringToUTF8(env, username);
policy::UserPolicySigninService* service =
policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
service->RegisterForPolicy(
base::android::ConvertJavaStringToUTF8(env, username),
base::Bind(&SigninManagerAndroid::OnPolicyRegisterDone,
weak_factory_.GetWeakPtr()));
#else
// This shouldn't be called when ShouldLoadPolicyForUser() is false.
NOTREACHED();
base::android::ScopedJavaLocalRef<jstring> domain;
Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
java_signin_manager_.obj(),
domain.obj());
#endif
}
void SigninManagerAndroid::FetchPolicyBeforeSignIn(JNIEnv* env, jobject obj) {
#if defined(ENABLE_CONFIGURATION_POLICY)
if (!dm_token_.empty()) {
policy::UserPolicySigninService* service =
policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
service->FetchPolicyForSignedInUser(
username_,
dm_token_,
client_id_,
profile_->GetRequestContext(),
base::Bind(&SigninManagerAndroid::OnPolicyFetchDone,
weak_factory_.GetWeakPtr()));
dm_token_.clear();
client_id_.clear();
return;
}
#endif
// This shouldn't be called when ShouldLoadPolicyForUser() is false, or when
// CheckPolicyBeforeSignIn() failed.
NOTREACHED();
Java_SigninManager_onPolicyFetchedBeforeSignIn(env,
java_signin_manager_.obj());
}
void SigninManagerAndroid::OnSignInCompleted(JNIEnv* env,
jobject obj,
jstring username,
jobjectArray accountIds,
jobjectArray accountNames) {
DVLOG(1) << "SigninManagerAndroid::OnSignInCompleted";
// Seed the account tracker with id/email information if provided.
if (accountIds && accountNames) {
std::vector<std::string> gaia_ids;
std::vector<std::string> emails;
base::android::AppendJavaStringArrayToStringVector(env, accountIds,
&gaia_ids);
base::android::AppendJavaStringArrayToStringVector(env, accountNames,
&emails);
DCHECK_EQ(emails.size(), gaia_ids.size());
DVLOG(1) << "SigninManagerAndroid::OnSignInCompleted: seeding "
<< emails.size() << " accounts";
AccountTrackerService* tracker =
AccountTrackerServiceFactory::GetForProfile(profile_);
for (size_t i = 0; i < emails.size(); ++i) {
DVLOG(1) << "SigninManagerAndroid::OnSignInCompleted: seeding"
<< " gaia_id=" << gaia_ids[i]
<< " email=" << emails[i];
if (!gaia_ids[i].empty() && !emails[i].empty())
tracker->SeedAccountInfo(gaia_ids[i], emails[i]);
}
} else {
DVLOG(1) << "SigninManagerAndroid::OnSignInCompleted: missing ids/email"
<< " ids=" << (void*) accountIds
<< " emails=" << (void*) accountNames;
}
SigninManagerFactory::GetForProfile(profile_)->OnExternalSigninCompleted(
base::android::ConvertJavaStringToUTF8(env, username));
}
void SigninManagerAndroid::SignOut(JNIEnv* env, jobject obj) {
SigninManagerFactory::GetForProfile(profile_)->SignOut(
signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS);
}
base::android::ScopedJavaLocalRef<jstring>
SigninManagerAndroid::GetManagementDomain(JNIEnv* env, jobject obj) {
base::android::ScopedJavaLocalRef<jstring> domain;
#if defined(ENABLE_CONFIGURATION_POLICY)
policy::UserCloudPolicyManager* manager =
policy::UserCloudPolicyManagerFactory::GetForBrowserContext(profile_);
policy::CloudPolicyStore* store = manager->core()->store();
if (store && store->is_managed() && store->policy()->has_username()) {
domain.Reset(
base::android::ConvertUTF8ToJavaString(
env, gaia::ExtractDomainName(store->policy()->username())));
}
#endif
return domain;
}
void SigninManagerAndroid::WipeProfileData(JNIEnv* env, jobject obj) {
// The ProfileDataRemover deletes itself once done.
new ProfileDataRemover(
profile_,
base::Bind(&SigninManagerAndroid::OnBrowsingDataRemoverDone,
weak_factory_.GetWeakPtr()));
}
#if defined(ENABLE_CONFIGURATION_POLICY)
void SigninManagerAndroid::OnPolicyRegisterDone(
const std::string& dm_token,
const std::string& client_id) {
dm_token_ = dm_token;
client_id_ = client_id;
JNIEnv* env = base::android::AttachCurrentThread();
base::android::ScopedJavaLocalRef<jstring> domain;
if (!dm_token_.empty()) {
DCHECK(!username_.empty());
domain.Reset(
base::android::ConvertUTF8ToJavaString(
env, gaia::ExtractDomainName(username_)));
} else {
username_.clear();
}
Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
java_signin_manager_.obj(),
domain.obj());
}
void SigninManagerAndroid::OnPolicyFetchDone(bool success) {
Java_SigninManager_onPolicyFetchedBeforeSignIn(
base::android::AttachCurrentThread(),
java_signin_manager_.obj());
}
#endif
void SigninManagerAndroid::OnBrowsingDataRemoverDone() {
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
model->RemoveAllUserBookmarks();
// All the Profile data has been wiped. Clear the last signed in username as
// well, so that the next signin doesn't trigger the acount change dialog.
ClearLastSignedInUser();
Java_SigninManager_onProfileDataWiped(base::android::AttachCurrentThread(),
java_signin_manager_.obj());
}
void SigninManagerAndroid::ClearLastSignedInUser(JNIEnv* env, jobject obj) {
ClearLastSignedInUser();
}
void SigninManagerAndroid::ClearLastSignedInUser() {
profile_->GetPrefs()->ClearPref(prefs::kGoogleServicesLastUsername);
}
void SigninManagerAndroid::LogInSignedInUser(JNIEnv* env, jobject obj) {
SigninManagerBase* signin_manager =
SigninManagerFactory::GetForProfile(profile_);
// With the account consistency enabled let the account Reconcilor handles
// everything.
ProfileOAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
const std::string& primary_acct = signin_manager->GetAuthenticatedAccountId();
static_cast<OAuth2TokenServiceDelegateAndroid*>(token_service->GetDelegate())
->ValidateAccounts(primary_acct, true);
}
jboolean SigninManagerAndroid::IsSigninAllowedByPolicy(JNIEnv* env,
jobject obj) {
return SigninManagerFactory::GetForProfile(profile_)->IsSigninAllowed();
}
jboolean SigninManagerAndroid::IsSignedInOnNative(JNIEnv* env, jobject obj) {
return SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated();
}
void SigninManagerAndroid::OnSigninAllowedPrefChanged() {
Java_SigninManager_onSigninAllowedByPolicyChanged(
base::android::AttachCurrentThread(), java_signin_manager_.obj(),
SigninManagerFactory::GetForProfile(profile_)->IsSigninAllowed());
}
static jlong Init(JNIEnv* env, jobject obj) {
SigninManagerAndroid* signin_manager_android =
new SigninManagerAndroid(env, obj);
return reinterpret_cast<intptr_t>(signin_manager_android);
}
static jboolean ShouldLoadPolicyForUser(JNIEnv* env,
jobject obj,
jstring j_username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
std::string username =
base::android::ConvertJavaStringToUTF8(env, j_username);
return !policy::BrowserPolicyConnector::IsNonEnterpriseUser(username);
#else
return false;
#endif
}
// static
bool SigninManagerAndroid::Register(JNIEnv* env) {
return RegisterNativesImpl(env);
}
| [
"sasha@sasha-kaidalov"
] | sasha@sasha-kaidalov |
71def7aecdd0a4cb7dba003826296be2c2d5b107 | 57a3f56c0e16f7cbbdcb6502b1acad07bfe9be4c | /CIS-17A - C++ Programming Objects/Final/P6Loader.cpp | 4778374a2f817af6db0ceb50a4b27990c3a2afa4 | [] | no_license | tpedretti/Community-College | 7ac7c87aa535449f09d953b1910ff86d98c5f016 | 71a120f9664efdd40dd667a01d2e58b5fdb5016b | refs/heads/master | 2020-04-14T19:19:42.481355 | 2019-04-03T06:46:58 | 2019-04-03T06:46:58 | 164,053,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,091 | cpp | #include"P6Loader.h"
/*
int** ary = new int*[sizeX];
for(int i = 0; i < sizeX; ++i)
ary[i] = new int[sizeY];
*/
color** P6Loader::loadimage(string filename)
{
//convert p6 of a ppm file to ascii or numbers
//open filename, read in height and width, read and dump uneeded lines,
//read in red green blue values. close file, return temporary color array.
ifstream inFile;
string s;
//char *temp;
int numLevels;
// ios::binary because it is a data file
inFile.open(filename, ios::binary);
if (inFile.fail())
{
cout << "Error Opening File!\n\n";
}
cout << "file opened\n";
// read in the ppm header
inFile >> s;
if (s != "P6")
cout << "Not a valid PPM image" << endl;
inFile.ignore();
getline(inFile, s);
cout << s << endl;
inFile >> width >> height >> numLevels;
inFile.ignore();
cout << "file variables saved\n" << width << height << numLevels << endl;
system("pause");
//temp = new char[width*height*3];
//color** img = new color[width][height];
color** img = new color*[height];
for(int i = 0; i< height; i++)
{
img[i] = new color[width];
}
cout << "created pixel array\n";
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
//char* temp = new char[1];
//inFile.read(temp, 1);
//cout << temp[1] << endl;
//img[i][j].r = temp[1];
//inFile.read(temp, 1);
//img[i][j].g = temp[1];
//inFile.read(temp, 1);
//img[i][j].b = temp[1];
//cout << img[i][j].r << " " <<img[i][j].g << " " << img[i][j].b << endl;
char temp;
inFile.get(temp);
img[i][j].r = (int)temp;
inFile.get(temp);
img[i][j].g = (int)temp;
inFile.get(temp);
img[i][j].b = (int)temp;
cout << "pixel " << "["<<i<<"]"<<"["<<j<<"]" << " loaded\n" ;
cout << img[i][j].r << " " <<img[i][j].g << " " << img[i][j].b << endl;
inFile.ignore();
}
}
system("pause");
// read in the image data to temp
//inFile.read(width*height*3);
inFile.close();
return img;
}
void P6Loader::saveimage(string filename, color** img, int w, int h)
{
cout << "begining file saving\n";
ofstream outFile;
outFile.open(filename, ios::out | ios::binary);
if (outFile.fail())
{
cout << "Error Opening File!\n\n";
}
cout << "file opend\n";
//
//
//
//
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
char buffer[3];
buffer[0] = img[i][j].r;
buffer[1] = img[i][j].g;
buffer[2] = img[i][j].b;
outFile.write(buffer, sizeof(char)*3);
}
outFile << endl;
}
outFile.close();
}
/*
Open the file
read until the first white space and check you got P6. Then skip other white-spaces.
read until the next white space, convert your buffer to an integer width. Then skip other white-spaces
read until the next white space, convert your buffer to an integer height. Then skip other white-spaces
Allocate a 2D array of integers in the size of height*width
read the max-val
read line by line and fill the array
*/ | [
"[email protected]"
] | |
ad04208786d798c59148fcee7123a4686345c723 | e71d40ad4e76272fca4494c6bcc818050d221090 | /Blink/Source/bindings/v8/ScriptDebugServer.h | f4b8d4ea0fc7eadb60675f25521937596eb64459 | [] | no_license | yuanyan/know-your-chrome | e038e49c160bdf46b28241427e99bf2816fac022 | 18cace725261122f6903c98bfdcbfa0b370138c3 | refs/heads/master | 2022-12-29T18:31:42.046729 | 2013-12-18T11:45:13 | 2013-12-18T11:45:13 | 9,907,874 | 7 | 7 | null | 2022-12-18T00:00:55 | 2013-05-07T08:55:26 | C++ | UTF-8 | C++ | false | false | 5,579 | h | /*
* Copyright (c) 2010, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ScriptDebugServer_h
#define ScriptDebugServer_h
#include "bindings/v8/ScopedPersistent.h"
#include "core/inspector/ScriptBreakpoint.h"
#include <v8-debug.h>
#include "wtf/HashMap.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/StringHash.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
class ScriptDebugListener;
class ScriptObject;
class ScriptState;
class ScriptValue;
class ScriptDebugServer {
WTF_MAKE_NONCOPYABLE(ScriptDebugServer);
public:
String setBreakpoint(const String& sourceID, const ScriptBreakpoint&, int* actualLineNumber, int* actualColumnNumber);
void removeBreakpoint(const String& breakpointId);
void clearBreakpoints();
void setBreakpointsActivated(bool activated);
enum PauseOnExceptionsState {
DontPauseOnExceptions,
PauseOnAllExceptions,
PauseOnUncaughtExceptions
};
PauseOnExceptionsState pauseOnExceptionsState();
void setPauseOnExceptionsState(PauseOnExceptionsState pauseOnExceptionsState);
void setPauseOnNextStatement(bool pause);
void breakProgram();
void continueProgram();
void stepIntoStatement();
void stepOverStatement();
void stepOutOfFunction();
bool setScriptSource(const String& sourceID, const String& newContent, bool preview, String* error, ScriptValue* newCallFrames, ScriptObject* result);
void updateCallStack(ScriptValue* callFrame);
void setScriptPreprocessor(const String& preprocessorBody);
class Task {
public:
virtual ~Task() { }
virtual void run() = 0;
};
static void interruptAndRun(PassOwnPtr<Task>, v8::Isolate*);
void runPendingTasks();
bool isPaused();
bool runningNestedMessageLoop() { return m_runningNestedMessageLoop; }
v8::Local<v8::Value> functionScopes(v8::Handle<v8::Function>);
v8::Local<v8::Value> getInternalProperties(v8::Handle<v8::Object>&);
v8::Local<v8::Value> setFunctionVariableValue(v8::Handle<v8::Value> functionValue, int scopeNumber, const String& variableName, v8::Handle<v8::Value> newValue);
virtual void compileScript(ScriptState*, const String& expression, const String& sourceURL, String* scriptId, String* exceptionMessage);
virtual void clearCompiledScripts();
virtual void runScript(ScriptState*, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionMessage);
protected:
ScriptDebugServer(v8::Isolate*);
virtual ~ScriptDebugServer();
ScriptValue currentCallFrame();
virtual ScriptDebugListener* getDebugListenerForContext(v8::Handle<v8::Context>) = 0;
virtual void runMessageLoopOnPause(v8::Handle<v8::Context>) = 0;
virtual void quitMessageLoopOnPause() = 0;
static v8::Handle<v8::Value> breakProgramCallback(const v8::Arguments& args);
void breakProgram(v8::Handle<v8::Object> executionState, v8::Handle<v8::Value> exception);
static void v8DebugEventCallback(const v8::Debug::EventDetails& eventDetails);
void handleV8DebugEvent(const v8::Debug::EventDetails& eventDetails);
void dispatchDidParseSource(ScriptDebugListener* listener, v8::Handle<v8::Object> sourceObject);
void ensureDebuggerScriptCompiled();
v8::Local<v8::Value> callDebuggerMethod(const char* functionName, int argc, v8::Handle<v8::Value> argv[]);
String preprocessSourceCode(const String& sourceCode);
PauseOnExceptionsState m_pauseOnExceptionsState;
ScopedPersistent<v8::Object> m_debuggerScript;
ScopedPersistent<v8::Object> m_executionState;
v8::Local<v8::Context> m_pausedContext;
bool m_breakpointsActivated;
ScopedPersistent<v8::FunctionTemplate> m_breakProgramCallbackTemplate;
HashMap<String, OwnPtr<ScopedPersistent<v8::Script> > > m_compiledScripts;
v8::Isolate* m_isolate;
private:
class ScriptPreprocessor;
OwnPtr<ScriptPreprocessor> m_scriptPreprocessor;
bool m_runningNestedMessageLoop;
};
} // namespace WebCore
#endif // ScriptDebugServer_h
| [
"[email protected]"
] | |
a436612e262fd0f7ca7d19bcf857ab632ef76061 | 688007a503afb29465fbac016fc2478250bfaf5d | /src/game_shared/sdk/paintballmgr.cpp | d79fbdd9295f37e76df6472d12fe61df333ceb1e | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | Digital-Paintball/dpb_source | 47546a42e888c55c83884fd447b19a9a26503555 | a15cc1e1e0f01e0bdbc95c44f99b5e892498c334 | refs/heads/master | 2021-01-07T17:18:34.720929 | 2020-02-20T00:16:28 | 2020-02-20T00:16:28 | 241,753,517 | 3 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 7,200 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "usermessages.h"
#include "paintballmgr.h"
#include "paintball_shared.h"
#include "movevars_shared.h"
#ifdef CLIENT_DLL
#include "hud_macros.h"
#include "c_sdk_player.h"
#else
#include "sdk_player.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
CPaintballMgr CPaintballMgr::s_PaintballMgr;
#ifdef CLIENT_DLL
void __MsgFunc_Paintball(bf_read &msg)
{
C_BaseEntity *pEnt = cl_entitylist->GetEnt(msg.ReadByte());
Assert(pEnt->IsPlayer());
CPaintballMgr::GetManager()->AddBall((C_BasePlayer*)pEnt);
}
#endif
void CPaintballMgr::LevelInitPreEntity()
{
for (int i = 0; i < MAX_PAINTBALLS; i++)
{
m_aBalls[i].Init(i);
}
m_iBalls = 0;
m_iLastBall = -1;
m_iFirstAvailable = 0;
#ifdef CLIENT_DLL
HOOK_MESSAGE(Paintball);
C_Paintball::Init();
#endif
m_bInitialized = true;
}
int CPaintballMgr::FindEmptySpace( )
{
int i;
for (i = m_iFirstAvailable; i < MAX_PAINTBALLS; i++)
{
if (m_aBalls[i].IsAvailable())
return i;
}
//Not enough space? Sucks to be you.
return -1;
/* //Not enough space? Grow the memory.
int h = m_hBalls.Count();
m_hBalls.Grow(1); //This grows by the grow size, not 1.
//Initialize new balls.
for (i = h; i < m_hBalls.Count(); i++)
{
m_hBalls[i].Init();
}
return h;*/
}
//Kujar lieks milk.
void CPaintballMgr::AddBall( CBasePlayer *pOwner )
{
int i = FindEmptySpace();
if (i < 0 || i >= MAX_PAINTBALLS)
{
#ifdef CLIENT_DLL
AssertMsg(0, VarArgs("Client paintball index %d invalid.\n", i));
#else
AssertMsg(0, UTIL_VarArgs("Server paintball index %d invalid.\n", i));
#endif
return;
}
#ifdef GAME_DLL
CArenaRecipientFilter filter( pOwner->GetArena(), true );
filter.RemoveRecipientsByInvPVS( pOwner->GetAbsOrigin() );
filter.UsePredictionRules();
UserMessageBegin( filter, "Paintball" );
WRITE_BYTE( engine->IndexOfEdict(pOwner->edict()) );
MessageEnd();
#endif
float flSpread = pOwner->GetPredictedSpread();
const float flSpinFactor = 120; // A popular show on Fox News.
RandomSeed( pOwner->GetPredictionRandomSeed() );
float flRadius = RandomFloat( 0.0, 1.0 );
float flTheta = RandomFloat( 0.0, 2*M_PI );
float flX = flRadius*cos(flTheta);
float flY = flRadius*sin(flTheta);
float flSpinTheta = RandomFloat( 0.0, 2*M_PI );
float flVelocity = PAINTBALL_AIR_VELOCITY + RandomFloat(-120, 120);
Vector vecForward, vecUp, vecRight;
QAngle angEyeAngles;
#ifdef CLIENT_DLL
if (pOwner->IsLocalPlayer())
angEyeAngles = pOwner->EyeAngles() + pOwner->m_Local.m_vecPunchAngle;
else
{
C_SDKPlayer *pSDKPlayer = dynamic_cast<C_SDKPlayer*>( pOwner );
angEyeAngles = pSDKPlayer->m_angEyeAngles + pOwner->m_Local.m_vecPunchAngle;
}
#else
angEyeAngles = pOwner->EyeAngles() + pOwner->m_Local.m_vecPunchAngle;
#endif
AngleVectors( angEyeAngles, &vecForward, &vecRight, &vecUp );
IPaintball *pPB = &m_aBalls[i];
Assert(pPB->m_bAvailable);
pPB->m_bAvailable = false;
pPB->m_pOwner = pOwner;
pPB->m_pArena = pOwner->GetArena();
pPB->m_vecPosition = pOwner->Weapon_ShootPosition();
pPB->m_vecVelocity = vecForward * flVelocity + flSpread * flX * vecRight + flSpread * flY * vecUp;
pPB->m_flXSpin = cos(flSpinTheta) * flSpinFactor;
pPB->m_flYSpin = sin(flSpinTheta) * flSpinFactor;
m_iBalls++;
if (i > m_iLastBall)
m_iLastBall = i;
if (i == m_iFirstAvailable)
m_iFirstAvailable = FindEmptySpace();
SanityCheck();
pPB->Spawn();
}
void CPaintballMgr::RemoveBall( int i )
{
if (i < 0 || i >= MAX_PAINTBALLS)
return;
IPaintball *pPB = &m_aBalls[i];
Assert(!pPB->m_bAvailable);
pPB->m_bAvailable = true;
m_iBalls--;
if (i == m_iLastBall)
{
bool bLastBallFound = false;
for (int j = m_iLastBall-1; j >= 0; j--)
{
if (m_aBalls[j].IsUsed())
{
m_iLastBall = j;
bLastBallFound = true;
break;
}
}
if (!bLastBallFound)
m_iLastBall = -1;
}
if (i < m_iFirstAvailable)
m_iFirstAvailable = i;
SanityCheck();
pPB->Destroy();
}
void CPaintballMgr::RemoveBalls( CArena *pArena )
{
if (!pArena)
return;
for (int i = 0; i < MAX_PAINTBALLS; i++)
if (m_aBalls[i].IsUsed() && m_aBalls[i].m_pArena == pArena)
RemoveBall( i );
}
void CPaintballMgr::SanityCheck()
{
#ifdef _DEBUG
int iBalls = 0;
int iFirstAvailable = 0;
int iLastBall = -1;
//Do some sanity checking.
for (int i = 0; i < MAX_PAINTBALLS; i++)
{
// If we're before the first available ball, this ball had better be used.
Assert(i >= m_iFirstAvailable || m_aBalls[i].IsUsed());
// If we're beyond the last ball, this ball had better be unused.
Assert((m_iLastBall != -1 && i <= m_iLastBall) || m_aBalls[i].IsAvailable());
if (m_aBalls[i].IsUsed() && iFirstAvailable == i)
iFirstAvailable++;
if (m_aBalls[i].IsUsed() && i > iLastBall)
iLastBall = i;
if (m_aBalls[i].IsUsed())
iBalls++;
}
Assert(iBalls == m_iBalls);
Assert(iLastBall == iLastBall);
Assert(iFirstAvailable == m_iFirstAvailable);
#endif
}
void CPaintballMgr::THINK_PROTOTYPE
{
//Don't think before we're initialized.
if (!m_bInitialized)
return;
#ifdef GAME_DLL
float flFrametime = gpGlobals->frametime;
#endif
for (int i = 0; i <= m_iLastBall; i++)
{
if (m_aBalls[i].IsUsed())
m_aBalls[i].Update( flFrametime );
}
}
void IPaintball::Update( float flFrametime )
{
Vector vecVelNormal = m_vecVelocity;
VectorNormalize(vecVelNormal);
float flVelocity = m_vecVelocity.Length();
Vector vecForward, vecUp, vecRight;
QAngle angForward;
VectorAngles( vecVelNormal, angForward );
AngleVectors( angForward, &vecForward, &vecRight, &vecUp );
Vector vecGravity = Vector(0, 0, -1) * sv_gravity.GetFloat();
Vector vecSpin = vecRight * m_flXSpin + vecUp * m_flYSpin;
Vector vecDrag = flVelocity * flVelocity * PAINTBALL_DRAG_COEFF * -vecVelNormal;
// Apply all velocity changes at once.
m_vecVelocity += (vecGravity + vecSpin + vecDrag) * flFrametime;
// New velocity
flVelocity = m_vecVelocity.Length();
// Degrade spin
m_flXSpin *= 1 - (0.1 * flFrametime);
m_flYSpin *= 1 - (0.1 * flFrametime);
//TODO: Use vphysics instead.
CGameTrace tr;
UTIL_TraceLine(
m_vecPosition,
m_vecPosition + m_vecVelocity * flFrametime,
MASK_SHOT,
m_pOwner, COLLISION_GROUP_NONE, &tr );
if (tr.DidHit())
{
bool bBroke = false;
if (m_pOwner && flVelocity < 2640 && flVelocity > 1680) //Between 220 and 140 fps
{
RandomSeed( m_pOwner->GetPredictionRandomSeed() );
bBroke = RandomFloat( 0.0, 1.0 ) > (2640 - flVelocity)/(2640 - 1680);
}
else if (flVelocity >= 2640)
bBroke = true;
if (bBroke)
PaintballTouch(tr.m_pEnt, &tr);
//Todo: bounce the ball if it did not break.
CPaintballMgr::GetManager()->RemoveBall(m_iIndex);
return;
}
m_vecPosition = tr.endpos;
}
| [
"[email protected]"
] | |
a9dcff3906170f514edb7d6f71e5a25bbc2396a4 | a1834fec227490dfda4d6e83ec4b411f3e3627f2 | /src/utility/bag_of_tricks/lockable.cpp | 9a3db06d9702297c0871353dfa09154d03ada76b | [
"BSD-3-Clause"
] | permissive | lou-magazino/ros_clams | ac52ce7363673e97af8997ec2875f11702b32d91 | 3f5084efd3c4cbf378e5f5158542eb296851077d | refs/heads/master | 2021-01-20T03:34:37.509416 | 2016-11-26T07:59:33 | 2016-11-26T07:59:33 | 74,369,048 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | cpp | //#include <bag_of_tricks/lockable.h>
#include <utility/bag_of_tricks/lockable.h>
Lockable::Lockable() :
mutex_(pthread_mutex_t())
{
}
void Lockable::lock()
{
pthread_mutex_lock(&mutex_);
}
void Lockable::unlock()
{
pthread_mutex_unlock(&mutex_);
}
bool Lockable::trylock()
{
if(pthread_mutex_trylock(&mutex_) == EBUSY)
return false;
else
return true;
}
void SharedLockable::lockWrite()
{
shared_mutex_.lock();
}
void SharedLockable::unlockWrite()
{
shared_mutex_.unlock();
}
bool SharedLockable::trylockWrite()
{
return shared_mutex_.try_lock();
}
void SharedLockable::lockRead()
{
shared_mutex_.lock_shared();
}
void SharedLockable::unlockRead()
{
shared_mutex_.unlock_shared();
}
bool SharedLockable::trylockRead()
{
return shared_mutex_.try_lock_shared();
}
| [
"[email protected]"
] | |
b8ed18924dd7d6fddb539b29a6f97b3da41857a5 | 013133699e7f1910d0ebe75ca5b0657316437df3 | /eps.cpp | 86561743d61e8ab7ee555280d1ebf565f082d91a | [] | no_license | smmasruk/ComputationalPhysics | 6109332de051c036588902e114ea0ae207c8d7c9 | 3adc47f49602411cf203491382f0611422b10d70 | refs/heads/main | 2023-08-28T07:56:37.561938 | 2021-11-04T13:55:10 | 2021-11-04T13:55:10 | 381,454,106 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 297 | cpp | #include <iostream>
using namespace std;
int main()
//this code will find the epsilon of machine
{
double x = 2.0;
int f;
for (int i = 1; 1+x>1; i ++)
{
x=x/2;
f=i;
}
cout << "Machine eps is: " << x << endl;
cout<<f<<endl;
return 0;
}
| [
"[email protected]"
] | |
ed651d81fce15d8f5f82f589204a6787e4da38f4 | e63c08a5009eea613361b9040da6573382581742 | /union_find_sets.h | 834a3c6fbef7a37fc6d3094e401d5bf89398ba4c | [] | no_license | Wcent/coding | c5f2497f7dd6af18e6581e48ea29e36008cd9b2c | 32a486ff25879b5cfa317359e94c9c980da321bc | refs/heads/master | 2021-01-13T01:39:59.618718 | 2015-09-11T01:35:17 | 2015-09-11T01:35:17 | 42,280,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,929 | h | // UnionFindSets.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
// 并查集 ~ union-find sets
// ~
// 带路径压缩的查找
int find(int *p, int len, int x)
{
if(x < 0 || x >= len)
return -1;
if(x != p[x])
p[x] = find(p, len, p[x]);
return p[x];
}
int _tmain(int argc, _TCHAR* argv[])
{
int g[8][8];
memset(g, 0, sizeof(int)*8*8);
/*
g[1][2] = 1;
g[1][6] = 1;
g[2][3] = 1;
g[3][5] = 1;
g[3][6] = 1;
// g[3][7] = 1;
// g[4][5] = 1;
g[4][7] = 1;
*/
g[1][6] = 1;
g[2][4] = 1;
g[3][4] = 1;
g[5][6] = 1;
g[4][5] = 1;
// g[5][7] = 2;
int root[8];
for(int i=0; i<8; i++)
root[i] = i;
for(int i=0; i<8; i++)
{
for(int j=0; j<8; j++)
{
if(g[i][j] == 1)
{
int x = find(root, 8, i);
int y = find(root, 8, j);
if(x > y)
root[x] = y;
else if(x < y)
root[y] = x;
}
}
}
for(int i=0; i<8; i++)
cout<<"root["<<i<<"] = "<<root[i]<<endl;
cout<<endl;
int a = 2;
int b = 5;
cout<<a<<" & "<<b<<" are in the same sets?"<<endl;
if(find(root, 8, a) == find(root, 8, b))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
a = 3;
b = 4;
cout<<a<<" & "<<b<<" are in the same sets?"<<endl;
if(find(root, 8, a) == find(root, 8, b))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
a = 4;
b = 6;
cout<<a<<" & "<<b<<" are in the same sets?"<<endl;
if(find(root, 8, a) == find(root, 8, b))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
a = 5;
b = 7;
cout<<a<<" & "<<b<<" are in the same sets?"<<endl;
if(find(root, 8, a) == find(root, 8, b))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
a = 4;
b = 7;
cout<<a<<" & "<<b<<" are in the same sets?"<<endl;
if(find(root, 8, a) == find(root, 8, b))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
cout<<endl;
for(int i=0; i<8; i++)
cout<<"find("<<i<<") = "<<find(root, 8, i)<<endl;
cout<<endl;
return 0;
} | [
"[email protected]"
] | |
d85b761459fdf09341f430357f48fc598582c6e0 | 89fa188323ca65cb75e5902122257a00ff610ccd | /MEKD/src/MadGraphSrc/Parameters_MEKD.h | d04b484746fb7a66a2cef2d32deed4668d8a8ca9 | [] | no_license | VBF-HZZ/HiggsAnalysis-ZZMatrixElement | 80b86ac25dae2f708dc89706f5a4ab2e2b81624e | df0a70c704a30684d1c05a42288708f4053e20c0 | refs/heads/master | 2021-01-12T22:33:24.738368 | 2014-03-06T16:22:22 | 2014-03-06T16:22:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,314 | h | //==========================================================================
// This file has been automatically generated for C++
// MadGraph 5 v. 1.5.2, 2012-10-15
// By the MadGraph Development Team
// Please visit us at https://launchpad.net/madgraph5
//==========================================================================
#ifndef Parameters_MEKD_H
#define Parameters_MEKD_H
#include <complex>
#include "read_slha.h"
using namespace std;
class Parameters_MEKD
{
public:
static Parameters_MEKD * getInstance();
// Define "zero"
double zero, ZERO;
// Model parameters independent of aS
double WXG, WH, WZp, WW, WZ, WT, ymtau, ymm, yme, ymt, ymb, ymc, yms, ymup,
ymdo, aS, Gf, aEWM1, MXG, MH, MZp, MZ, MTA, MM, Me, MT, MB, MC, MS, MU, MD,
cabi, gw, g1, cos__cabi, sin__cabi, MZ__exp__2,
MZ__exp__4, sqrt__2, MH__exp__2, aEW, MW, sqrt__aEW, ee, MW__exp__2,
sw2, cw, sqrt__sw2, sw, vev, vev__exp__2, lam, yb, yc, ydo, ye, ym,
ys, yt, ytau, yup, muH, ee__exp__2, sw__exp__2, cw__exp__2;
// Spin 0
std::complex<double> rhob02, rhob01, rhos02, rhos01, rhod02, rhod01, rhoc02, rhoc01, rhou02, rhou01, g4z, g3z, g2z, g1z, g4g, g3g, g2g, g1g;
std::complex<double> rhomu02, rhomu01, rhoe02, rhoe01; // 2l
// Spin 1
std::complex<double> rhob14, rhob13, rhob12, rhob11, rhos14, rhos13, rhos12, rhos11, rhod14, rhod13, rhod12, rhod11, rhoc14, rhoc13, rhoc12, rhoc11, rhou14, rhou13, rhou12, rhou11, b2z, b1z;
std::complex<double> rhomu14, rhomu13, rhomu12, rhomu11, rhoe14, rhoe13, rhoe12, rhoe11; // 2l
// Spin 2
std::complex<double> rhob24, rhob23, rhob22, rhob21, rhos24, rhos23, rhos22, rhos21, rhod24, rhod23, rhod22, rhod21, rhoc24, rhoc23, rhoc22, rhoc21, rhou24, rhou23, rhou22, rhou21, k10g, k9g, k8g, k7g, k6g, k5g, k4g, k3g, k2g, k1g, k10z, k9z, k8z, k7z, k6z, k5z, k4z, k3z, k2z, k1z;
std::complex<double> rhomu24, rhomu23, rhomu22, rhomu21, rhoe24, rhoe23, rhoe22, rhoe21; // 2l
std::complex<double> CKM11, CKM12, CKM13, CKM21, CKM22, CKM23, CKM31,
CKM32, CKM33, conjg__CKM11, conjg__CKM21, conjg__CKM31, conjg__CKM12,
conjg__CKM22, conjg__CKM32, conjg__CKM13, conjg__CKM23, conjg__CKM33,
complexi, I1x11, I1x12, I1x13, I1x21, I1x22, I1x23, I1x31, I1x32,
I1x33, I2x11, I2x12, I2x13, I2x21, I2x22, I2x23, I2x31, I2x32, I2x33,
I3x11, I3x12, I3x13, I3x21, I3x22, I3x23, I3x31, I3x32, I3x33, I4x11,
I4x12, I4x13, I4x21, I4x22, I4x23, I4x31, I4x32, I4x33;
// Model parameters dependent on aS
double sqrt__aS, G, G__exp__2;
// Model couplings independent of aS, ZZ part
std::complex<double> GC_1, GC_2, GC_3, GC_109, GC_110, GC_115, GC_116,
Unitary_GC_5, Unitary_GC_6, Unitary_GC_7, Unitary_GC_70, Unitary_GC_71, Unitary_GC_74, Unitary_GC_75;
// Coming extra from spin 0
std::complex<double> HEF_MEKD_GC_3, HEF_MEKD_GC_4, HEF_MEKD_GC_5, HEF_MEKD_GC_13, HEF_MEKD_GC_14, HEF_MEKD_GC_15, HEF_MEKD_GC_18, HEF_MEKD_GC_19, HEF_MEKD_GC_22, HEF_MEKD_GC_23, HEF_MEKD_GC_25, HEF_MEKD_GC_106, HEF_MEKD_GC_107, HEF_MEKD_GC_116, HEF_MEKD_GC_117, HEF_MEKD_GC_126, HEF_MEKD_GC_127, HEF_MEKD_GC_136, HEF_MEKD_GC_137, HEF_MEKD_GC_161, HEF_MEKD_GC_168;
// Coming extra from spin 1
std::complex<double> HEF_MEKD_GC_1, HEF_MEKD_GC_2, HEF_MEKD_GC_108, HEF_MEKD_GC_109, HEF_MEKD_GC_110, HEF_MEKD_GC_111, HEF_MEKD_GC_118, HEF_MEKD_GC_119, HEF_MEKD_GC_120, HEF_MEKD_GC_121, HEF_MEKD_GC_128, HEF_MEKD_GC_129, HEF_MEKD_GC_130, HEF_MEKD_GC_131, HEF_MEKD_GC_138, HEF_MEKD_GC_139, HEF_MEKD_GC_140, HEF_MEKD_GC_141;
// Coming extra from spin 2
std::complex<double> HEF_MEKD_GC_62, HEF_MEKD_GC_63, HEF_MEKD_GC_64, HEF_MEKD_GC_67, HEF_MEKD_GC_68, HEF_MEKD_GC_71, HEF_MEKD_GC_72, HEF_MEKD_GC_75 , HEF_MEKD_GC_76, HEF_MEKD_GC_79, HEF_MEKD_GC_80, HEF_MEKD_GC_81, HEF_MEKD_GC_82, HEF_MEKD_GC_83, HEF_MEKD_GC_84, HEF_MEKD_GC_85, HEF_MEKD_GC_86, HEF_MEKD_GC_90, HEF_MEKD_GC_91, HEF_MEKD_GC_92, HEF_MEKD_GC_112, HEF_MEKD_GC_113, HEF_MEKD_GC_114, HEF_MEKD_GC_115, HEF_MEKD_GC_122, HEF_MEKD_GC_123, HEF_MEKD_GC_124, HEF_MEKD_GC_125, HEF_MEKD_GC_132, HEF_MEKD_GC_133, HEF_MEKD_GC_134, HEF_MEKD_GC_135, HEF_MEKD_GC_142, HEF_MEKD_GC_143, HEF_MEKD_GC_144, HEF_MEKD_GC_145;
/// HEF_MEKD2_1 model
// Coming from DY
std::complex<double> HEF_MEKD2_1_GC_3, HEF_MEKD2_1_GC_4, HEF_MEKD2_1_GC_5, HEF_MEKD2_1_GC_181, HEF_MEKD2_1_GC_182, HEF_MEKD2_1_GC_187, HEF_MEKD2_1_GC_188;
// Coming extra from spin 0
std::complex<double> HEF_MEKD2_1_GC_13, HEF_MEKD2_1_GC_14, HEF_MEKD2_1_GC_15, HEF_MEKD2_1_GC_18, HEF_MEKD2_1_GC_19, HEF_MEKD2_1_GC_22, HEF_MEKD2_1_GC_23, HEF_MEKD2_1_GC_25, HEF_MEKD2_1_GC_126, HEF_MEKD2_1_GC_127, HEF_MEKD2_1_GC_136, HEF_MEKD2_1_GC_137;
// Coming extra from spin 1
std::complex<double> HEF_MEKD2_1_GC_1, HEF_MEKD2_1_GC_2, HEF_MEKD2_1_GC_108, HEF_MEKD2_1_GC_109, HEF_MEKD2_1_GC_110, HEF_MEKD2_1_GC_111, HEF_MEKD2_1_GC_128, HEF_MEKD2_1_GC_129, HEF_MEKD2_1_GC_130, HEF_MEKD2_1_GC_131, HEF_MEKD2_1_GC_138, HEF_MEKD2_1_GC_139, HEF_MEKD2_1_GC_140, HEF_MEKD2_1_GC_141, HEF_MEKD2_1_GC_148, HEF_MEKD2_1_GC_149, HEF_MEKD2_1_GC_150, HEF_MEKD2_1_GC_151;
// Coming extra from spin 2
std::complex<double> HEF_MEKD2_1_GC_62, HEF_MEKD2_1_GC_63, HEF_MEKD2_1_GC_64, HEF_MEKD2_1_GC_67, HEF_MEKD2_1_GC_68, HEF_MEKD2_1_GC_71, HEF_MEKD2_1_GC_72, HEF_MEKD2_1_GC_75, HEF_MEKD2_1_GC_76, HEF_MEKD2_1_GC_79, HEF_MEKD2_1_GC_80, HEF_MEKD2_1_GC_81, HEF_MEKD2_1_GC_82, HEF_MEKD2_1_GC_83, HEF_MEKD2_1_GC_84, HEF_MEKD2_1_GC_85, HEF_MEKD2_1_GC_86, HEF_MEKD2_1_GC_90, HEF_MEKD2_1_GC_91, HEF_MEKD2_1_GC_92, HEF_MEKD2_1_GC_112, HEF_MEKD2_1_GC_113, HEF_MEKD2_1_GC_114, HEF_MEKD2_1_GC_115, HEF_MEKD2_1_GC_132, HEF_MEKD2_1_GC_133, HEF_MEKD2_1_GC_134, HEF_MEKD2_1_GC_135, HEF_MEKD2_1_GC_142, HEF_MEKD2_1_GC_143, HEF_MEKD2_1_GC_144, HEF_MEKD2_1_GC_145, HEF_MEKD2_1_GC_152, HEF_MEKD2_1_GC_153, HEF_MEKD2_1_GC_154, HEF_MEKD2_1_GC_155;
// Model couplings dependent on aS
// Set parameters that are unchanged during the run
void setIndependentParameters(SLHAReader& slha);
// Set couplings that are unchanged during the run
void setIndependentCouplings();
// Set parameters that are changed event by event
void setDependentParameters();
// Set couplings that are changed event by event
void setDependentCouplings();
private:
static Parameters_MEKD * instance;
};
#endif // Parameters_MEKD_H
| [
"[email protected]"
] | |
f2f5887d81965a263543bb85780b476463a5842a | 9347ff539187c0d3e03e9ed840bb4bfe7078ddce | /external/intel/src/common/SoftFrustum.h | 6ae1b555125edb3849e4388c245cd14f5c88d288 | [] | no_license | gamedevforks/SoftOcclude | ef526342ae545a4535236aaac14c224fef925697 | a930a5b8f620262cd6f00ad025d3e21bb20ea661 | refs/heads/master | 2020-12-25T20:08:56.535797 | 2015-09-18T23:03:06 | 2015-09-18T23:03:06 | 44,450,708 | 1 | 0 | null | 2015-10-17T19:14:58 | 2015-10-17T19:14:55 | null | UTF-8 | C++ | false | false | 1,662 | h | //--------------------------------------------------------------------------------------
// Copyright 2012 Intel Corporation
// All Rights Reserved
//
// Permission is granted to use, copy, distribute and prepare derivative works of this
// software for any purpose and without fee, provided, that the above copyright notice
// and this statement appear in all copies. Intel makes no representations about the
// suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS."
// INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY,
// INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE,
// INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not
// assume any responsibility for any errors which may appear in this software nor any
// responsibility to update it.
//--------------------------------------------------------------------------------------
#ifndef _SOFTFRUSTUM_H
#define _SOFTFRUSTUM_H
#include "../common/SoftMath.h"
class SoftFrustum
{
public:
float3 mpPosition[8];
float3 mpNormal[6];
float mFov;
float *mPlanes;
UINT mNumFrustumVisibleModels;
UINT mNumFrustumCulledModels;
SoftFrustum();
~SoftFrustum();
void InitializeFrustum
(
float nearClipDistance,
float farClipDistance,
float aspectRatio,
float fov,
const float3 &position,
const float3 &look,
const float3 &up
);
bool IsVisible(
const float3 ¢er,
const float3 &half
);
};
#endif // _SOFTFRUSTUM_H
| [
"[email protected]"
] | |
5ea6a90c318f819a07be44e17098339f31c83b99 | d70bc150251f13ba0da021778016dfc437a74d95 | /pluriNotes/AbstractNote.h | 6f225dae89de4ce09fe25adf5e704cd6d9f36dff | [] | no_license | ThomasCaud/pluriNotes | 4d564246d39d6bc1719792a85b8c948a68e3506c | ec0383a2801c11f2238b4e750fd5b45033d7631d | refs/heads/master | 2020-04-27T21:15:02.857396 | 2019-03-09T12:09:09 | 2019-03-09T12:09:09 | 174,689,482 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 729 | h | #ifndef ABSTRACTNOTE_H
#define ABSTRACTNOTE_H
#include <string>
#include <Enumeration.h>
/**
* @brief The AbstractNote class est une classe abstraite permettant de gérer les attributs et méthodes communs aux différents types de notes
*/
class AbstractNote
{
public:
AbstractNote():title(""){}
AbstractNote(const std::string& t):title(t){}
const std::string getTitle()const{return title;}
void setTitle(const std::string& t){title=t;}
virtual void display()const=0;
virtual Enumeration::typeNote getTypeNote()const=0;
virtual QString getNameTypeNote()const=0;
virtual QString getAllQString()const=0;
virtual ~AbstractNote(){}
private:
std::string title;
};
#endif // ABSTRACTNOTE_H
| [
"[email protected]"
] | |
f0fbbfffcb25664b65b06764aa3ea98702110790 | b5482a55813f3e6f3f288967a1443c734c52e6ed | /d912pxy/d912pxy_device_unimpl.cpp | 001ad5d464245fbb67accbdf3f828e56f373b6df | [
"MIT"
] | permissive | BearsMan/d912pxy | db484c0f3cc0497fdfda4a613b97c5bd5c6afee7 | bcb2363669d4af595c647c167899d2a6acc188e8 | refs/heads/master | 2020-06-20T21:15:20.864868 | 2019-07-16T05:54:51 | 2019-07-16T05:54:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,847 | cpp | /*
MIT License
Copyright(c) 2018-2019 megai2
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 "stdafx.h"
//UNIMPLEMENTED !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
HRESULT d912pxy_device::SetDialogBoxMode(BOOL bEnableDialogs)
{
//ignore
LOG_DBG_DTDM(__FUNCTION__);
return D3D_OK;
}
HRESULT d912pxy_device::SetCursorProperties(UINT XHotSpot, UINT YHotSpot, IDirect3DSurface9* pCursorBitmap)
{
//megai2: not for full d3d9 porting here
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
BOOL d912pxy_device::ShowCursor(BOOL bShow)
{
LOG_DBG_DTDM(__FUNCTION__);
//ShowCursor(bShow); <= insanity
return true;
}
//megai2: texture stage states are fixed pipeline and won't work if we use shaders, is that correct?
HRESULT d912pxy_device::GetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD* pValue)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
HRESULT d912pxy_device::SetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3D_OK;
}
HRESULT d912pxy_device::GetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD* pValue)
{
return D3DERR_INVALIDCALL;
}
HRESULT d912pxy_device::SetVertexShaderConstantI(UINT StartRegister, CONST int* pConstantData, UINT Vector4iCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::SetVertexShaderConstantB(UINT StartRegister, CONST BOOL* pConstantData, UINT BoolCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::SetPixelShaderConstantI(UINT StartRegister, CONST int* pConstantData, UINT Vector4iCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::SetPixelShaderConstantB(UINT StartRegister, CONST BOOL* pConstantData, UINT BoolCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetVertexShaderConstantF(UINT StartRegister, float* pConstantData, UINT Vector4fCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetVertexShaderConstantI(UINT StartRegister, int* pConstantData, UINT Vector4iCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetVertexShaderConstantB(UINT StartRegister, BOOL* pConstantData, UINT BoolCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetPixelShaderConstantF(UINT StartRegister, float* pConstantData, UINT Vector4fCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetPixelShaderConstantI(UINT StartRegister, int* pConstantData, UINT Vector4iCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetPixelShaderConstantB(UINT StartRegister, BOOL* pConstantData, UINT BoolCount) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetStreamSource(UINT StreamNumber, IDirect3DVertexBuffer9** ppStreamData, UINT* OffsetInBytes, UINT* pStride) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetStreamSourceFreq(UINT StreamNumber, UINT* Divider) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetIndices(IDirect3DIndexBuffer9** ppIndexData) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::UpdateSurface(IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestinationSurface, CONST POINT* pDestPoint) { LOG_DBG_DTDM(__FUNCTION__); return D3DERR_INVALIDCALL; }
HRESULT d912pxy_device::UpdateTexture(IDirect3DBaseTexture9* pSourceTexture, IDirect3DBaseTexture9* pDestinationTexture) { LOG_DBG_DTDM(__FUNCTION__); return D3DERR_INVALIDCALL; }
HRESULT d912pxy_device::ColorFill(IDirect3DSurface9* pSurface, CONST RECT* pRect, D3DCOLOR color) { LOG_DBG_DTDM(__FUNCTION__); return D3DERR_INVALIDCALL; }
//clipping
//^ done in shaders
HRESULT d912pxy_device::GetClipPlane(DWORD Index, float* pPlane) { LOG_DBG_DTDM(__FUNCTION__); return D3DERR_INVALIDCALL; }
HRESULT d912pxy_device::SetClipStatus(CONST D3DCLIPSTATUS9* pClipStatus) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetClipStatus(D3DCLIPSTATUS9* pClipStatus) { LOG_DBG_DTDM(__FUNCTION__); return D3DERR_INVALIDCALL; }
//fixed pipe states
HRESULT d912pxy_device::SetTransform(D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetTransform(D3DTRANSFORMSTATETYPE State, D3DMATRIX* pMatrix) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::MultiplyTransform(D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::SetMaterial(CONST D3DMATERIAL9* pMaterial) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetMaterial(D3DMATERIAL9* pMaterial) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::SetLight(DWORD Index, CONST D3DLIGHT9* pLight) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetLight(DWORD Index, D3DLIGHT9* pLight) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::LightEnable(DWORD Index, BOOL Enable) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetLightEnable(DWORD Index, BOOL* pEnable) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
//palette
HRESULT d912pxy_device::SetPaletteEntries(UINT PaletteNumber, CONST PALETTEENTRY* pEntries) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetPaletteEntries(UINT PaletteNumber, PALETTEENTRY* pEntries) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::SetCurrentTexturePalette(UINT PaletteNumber) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::GetCurrentTexturePalette(UINT *PaletteNumber) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
//npatch
HRESULT d912pxy_device::SetNPatchMode(float nSegments) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
float d912pxy_device::GetNPatchMode(void) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::DrawRectPatch(UINT Handle, CONST float* pNumSegs, CONST D3DRECTPATCH_INFO* pRectPatchInfo) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::DrawTriPatch(UINT Handle, CONST float* pNumSegs, CONST D3DTRIPATCH_INFO* pTriPatchInfo) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::DeletePatch(UINT Handle) { LOG_DBG_DTDM(__FUNCTION__); return 0; }
HRESULT d912pxy_device::SetFVF(DWORD FVF)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3D_OK;
}
HRESULT d912pxy_device::GetFVF(DWORD* pFVF)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3D_OK;
}
HRESULT d912pxy_device::GetTexture(DWORD Stage, IDirect3DBaseTexture9** ppTexture)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
HRESULT d912pxy_device::GetVertexDeclaration(IDirect3DVertexDeclaration9** ppDecl)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
HRESULT d912pxy_device::GetVertexShader(IDirect3DVertexShader9** ppShader)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
HRESULT d912pxy_device::GetPixelShader(IDirect3DPixelShader9** ppShader)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
HRESULT d912pxy_device::SetSoftwareVertexProcessing(BOOL bSoftware)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
BOOL d912pxy_device::GetSoftwareVertexProcessing(void)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
HRESULT d912pxy_device::ProcessVertices(UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9* pDestBuffer, IDirect3DVertexDeclaration9* pVertexDecl, DWORD Flags)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3D_OK;
}
HRESULT d912pxy_device::GetViewport(D3DVIEWPORT9* pViewport)
{
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
HRESULT d912pxy_device::GetScissorRect(RECT* pRect) {
LOG_DBG_DTDM(__FUNCTION__);
return D3DERR_INVALIDCALL;
}
HRESULT d912pxy_device::EvictManagedResources(void)
{
//megai2: ignore this for now
LOG_DBG_DTDM(__FUNCTION__);
return D3D_OK;
} | [
"[email protected]"
] | |
944d3858152d85f0d1d06245bb5c3c187e9b34c5 | 5ec06dab1409d790496ce082dacb321392b32fe9 | /clients/cpp-restsdk/generated/model/ComAdobeGraniteBundlesHcImplSlingJavaScriptHandlerHealthCheckProperties.h | 5da18a3a8ad627ff3738f5401c89b938318baec0 | [
"Apache-2.0"
] | permissive | shinesolutions/swagger-aem-osgi | e9d2385f44bee70e5bbdc0d577e99a9f2525266f | c2f6e076971d2592c1cbd3f70695c679e807396b | refs/heads/master | 2022-10-29T13:07:40.422092 | 2021-04-09T07:46:03 | 2021-04-09T07:46:03 | 190,217,155 | 3 | 3 | Apache-2.0 | 2022-10-05T03:26:20 | 2019-06-04T14:23:28 | null | UTF-8 | C++ | false | false | 2,215 | h | /**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
* ComAdobeGraniteBundlesHcImplSlingJavaScriptHandlerHealthCheckProperties.h
*
*
*/
#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteBundlesHcImplSlingJavaScriptHandlerHealthCheckProperties_H_
#define ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteBundlesHcImplSlingJavaScriptHandlerHealthCheckProperties_H_
#include "../ModelBase.h"
#include "ConfigNodePropertyArray.h"
namespace org {
namespace openapitools {
namespace client {
namespace model {
/// <summary>
///
/// </summary>
class ComAdobeGraniteBundlesHcImplSlingJavaScriptHandlerHealthCheckProperties
: public ModelBase
{
public:
ComAdobeGraniteBundlesHcImplSlingJavaScriptHandlerHealthCheckProperties();
virtual ~ComAdobeGraniteBundlesHcImplSlingJavaScriptHandlerHealthCheckProperties();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
void fromJson(web::json::value& json) override;
void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override;
void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override;
/////////////////////////////////////////////
/// ComAdobeGraniteBundlesHcImplSlingJavaScriptHandlerHealthCheckProperties members
/// <summary>
///
/// </summary>
std::shared_ptr<ConfigNodePropertyArray> getHcTags() const;
bool hcTagsIsSet() const;
void unsetHc_tags();
void setHcTags(std::shared_ptr<ConfigNodePropertyArray> value);
protected:
std::shared_ptr<ConfigNodePropertyArray> m_Hc_tags;
bool m_Hc_tagsIsSet;
};
}
}
}
}
#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteBundlesHcImplSlingJavaScriptHandlerHealthCheckProperties_H_ */
| [
"[email protected]"
] | |
f26f3ec2df52abbb3e147b9e61c187e9d1d403e9 | 44fefcc260b39c18ed45c3bf08bce31b4c3d034d | /Person.h | cccf2e1137f98aaebc957fdb3618e079c8cdd0c9 | [] | no_license | patmauro/CollegeDatabase | 3c3503f01e0746dea2e3e9df81afbb6921529650 | 6e2a25e66283db3974ad5fc3fa421d0f095c6208 | refs/heads/master | 2021-01-10T19:16:03.462430 | 2014-02-18T11:22:36 | 2014-02-18T11:22:36 | 16,945,792 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | h | //Patrick Mauro, CS203 Final Project
//Person.h
//Header for Person class
#ifndef PERSON_H
#define PERSON_H
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
Person(string, string, int);
void setFirstName(string);
void setLastName(string);
string getFirstName();
string getLastName();
void setSsNum(int);
int getSsNum();
virtual void printPerson();
int getCount();
protected:
string firstName;
string lastName;
int ssNum;
//static int count = 0;
};
#endif | [
"[email protected]"
] | |
c683f768d91627d1a8d7f3925f5dbd740432d02f | 73dc9e988e7d543d1e6239c942346883443d05e6 | /NowCoder/2017校招真题在线编程 句子反转.cpp | 488d9bcd57832f618a9ecbefccfde116e0b2cbfe | [] | no_license | JanDeng25/Online-Judge | 09df5da88b82d9814cde4d52c098ac8feeb1e555 | bffea7837cb61f6d6d94b8ed8cf20550141e3fc4 | refs/heads/master | 2021-01-16T23:54:42.512245 | 2018-03-18T02:40:14 | 2018-03-18T02:40:14 | 59,482,739 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 603 | cpp | //×Ö·û´®·Ö¸î
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <string.h>
using namespace std;
string splitstring(string s) {
const char *split = " ";
char * tmp;
tmp = strtok((char*)s.c_str(), split);
string res = "";
vector<string> v;
while (tmp != NULL) {
v.push_back(string(tmp));
tmp = strtok(NULL, split);
}
int size = v.size();
res += v[size - 1];
for (int i = size - 2; i >= 0; i--)
res += (" " + v[i]);
//cout << res << endl;
return res;
}
int main() {
string s;
while (getline(cin, s)) {
cout << splitstring(s);
}
return 0;
} | [
"[email protected]"
] | |
11acf4081db0f20aa4f4d4ebf5dbfb8364fe8037 | dd6147bf9433298a64bbceb7fdccaa4cc477fba6 | /8383/kolmykov/GAMEE/OOP/AttackBehavior/AttackWithBat.h | 86bc172dfb8c3d5bc3a27f42552c36938f8d6555 | [] | no_license | moevm/oop | 64a89677879341a3e8e91ba6d719ab598dcabb49 | faffa7e14003b13c658ccf8853d6189b51ee30e6 | refs/heads/master | 2023-03-16T15:48:35.226647 | 2020-06-08T16:16:31 | 2020-06-08T16:16:31 | 85,785,460 | 42 | 304 | null | 2023-03-06T23:46:08 | 2017-03-22T04:37:01 | C++ | UTF-8 | C++ | false | false | 179 | h | #pragma once
#include "attackBehavior.h"
class AttackWithBat :
public AttackBehavior
{
public:
AttackWithBat();
~AttackWithBat();
void attack(std::shared_ptr<Unit> unit);
};
| [
"[email protected]"
] | |
f4aa30c3e91997fd1391f83065a461213ae06d7f | cc7661edca4d5fb2fc226bd6605a533f50a2fb63 | /System.Core/HashSet.h | bb8a72e49ae46131d9271a3ad24fe16f0cfa1697 | [
"MIT"
] | permissive | g91/Rust-C-SDK | 698e5b573285d5793250099b59f5453c3c4599eb | d1cce1133191263cba5583c43a8d42d8d65c21b0 | refs/heads/master | 2020-03-27T05:49:01.747456 | 2017-08-23T09:07:35 | 2017-08-23T09:07:35 | 146,053,940 | 1 | 0 | null | 2018-08-25T01:13:44 | 2018-08-25T01:13:44 | null | UTF-8 | C++ | false | false | 1,100 | h | #pragma once
#include "..\System\Collections\Generic\HashSet\Link<T>.h"
#include "T.h"
#include "..\System\Collections\Generic\IEqualityComparer<T>.h"
#include "..\System\Runtime\Serialization\SerializationInfo.h"
namespace System
{
namespace Collections
{
{
namespace Generic
{
template <typename T0>
class HashSet : public Object // 0x0
{
public:
int* table; // 0x10 (size: 0x8, flags: 0x1, type: 0x1d)
System::Collections::Generic::HashSet::Link<T>* links; // 0x18 (size: 0x8, flags: 0x1, type: 0x1d)
T* slots; // 0x20 (size: 0x8, flags: 0x1, type: 0x1d)
System::Collections::Generic::IEqualityComparer<T> comparer; // 0x28 (size: 0x8, flags: 0x1, type: 0x15)
System::Runtime::Serialization::SerializationInfo* si; // 0x30 (size: 0x8, flags: 0x1, type: 0x12)
int touched; // 0x38 (size: 0x4, flags: 0x1, type: 0x8)
int empty_slot; // 0x3c (size: 0x4, flags: 0x1, type: 0x8)
int count; // 0x40 (size: 0x4, flags: 0x1, type: 0x8)
int threshold; // 0x44 (size: 0x4, flags: 0x1, type: 0x8)
int generation; // 0x48 (size: 0x4, flags: 0x1, type: 0x8)
}; // size = 0x50
}
| [
"[email protected]"
] | |
c53b6a549440f033ba35fe9a299982942baf78b4 | b6746e04974255e054065ba88658c5e1e0c689a2 | /newCSGO_dll_03/newCSGO/CHackEsp.h | 23082499f8139cce2b72bf1180650508234d9e3a | [] | no_license | Pokerkoffer/CS-GO-HackClient | 3b49d42d4ec3ea34b997feb16fbd8a48ac78ea04 | dab9e021f7c416ad787cb258572985bd027cfeea | refs/heads/master | 2021-06-19T23:08:23.504343 | 2017-07-09T03:22:23 | 2017-07-09T03:22:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 203 | h | #pragma once
class CHackEsp
{
public:
void DrawPlayers(int i, IClientEntity* pLocalBaseEntity, IClientEntity* pBaseEntity );
};
extern Vector vHead, vEyePos;
extern bool bIsEnemy;
extern CHackEsp cEsp; | [
"[email protected]"
] | |
ad63da887e7923949bbac1f6590a2f822a9f83da | 54670b434c6706f79f44de5da73ec7ccf80c0391 | /BrushRunner/IdleState.h | 293f5cb889d2729a500eee0af48044bb2604e146 | [
"MIT"
] | permissive | SomeTake/BrushRunner | fe154d5cf3827256876f663270e2304ea722c908 | 28208e570a1ba0f969c22bfc0b43a2d1b39bd532 | refs/heads/master | 2020-05-22T04:04:09.738930 | 2019-09-12T03:29:19 | 2019-09-12T03:29:19 | 186,221,243 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 749 | h | //=============================================================================
//
// プレイヤーの状態管理(待機中)[IdleState.h]
// Author : HAL東京 GP12B332-19 80277 染谷武志
//
//=============================================================================
#ifndef _IDLESTATE_H_
#define _IDLESTATE_H_
#include "PlayerState.h"
#include "Player.h"
//*****************************************************************************
// クラス定義
//*****************************************************************************
class IdleState :
public PlayerState
{
private:
Player * owner_; // 状態の所有者
public:
IdleState(Player* owner);
~IdleState();
virtual void Update(int AnimCurtID)override;
};
#endif
| [
"[email protected]"
] | |
0b80a8a90666fcd225a676bf58d48e53548776c4 | a368cc268aa9d19515d29c57c5a9355e5a3613b6 | /mobile/ncnnapp/alexnet2/app/src/main/cpp/classification/sort.cpp | ef47213f0a77d8e764bb6f85f4db2269ed05f510 | [] | no_license | aliushn/world | 4cae1131da0bc335aebc48c76f9e11e176bc5b2d | 18b8fd97ef4e0cc0f8e854021624d04bfd7d439e | refs/heads/master | 2022-03-25T18:58:19.405454 | 2019-11-24T11:12:30 | 2019-11-24T11:12:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | cpp | //
// Created by clausewang(王立昌) on 2019-06-02.
//
#include <vector>
bool cmp(std::pair<std::size_t,float>& i1, std::pair<std::size_t,float>& i2){
return i1.second>i2.second;
} | [
"[email protected]"
] | |
13e09b9c28d95ca798332dbb27509580982ea381 | 6e002c286cf993e8c015dc90ba714998ad7c0894 | /src/RevertTextWithoutDot/RevertTextWithoutDot.cpp | d228f83aef4581af7faf12707fc0ea3ee04e83ca | [] | no_license | dnasdw/FireEmblemKakuseiTempTools | fc2742cf7fbf65c744f058ec540564281d05cf88 | 865c521c681cb551d5e7fa451bb3ccd0ee928bb3 | refs/heads/master | 2022-11-08T16:51:30.613454 | 2022-10-27T09:24:29 | 2022-10-27T09:34:32 | 88,421,241 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,815 | cpp | #include <sdw.h>
int UMain(int argc, UChar* argv[])
{
if (argc != 2)
{
return 1;
}
FILE* fp = UFopen(argv[1], USTR("rb"), false);
if (fp == nullptr)
{
return 1;
}
fseek(fp, 0, SEEK_END);
u32 uTxtSize = ftell(fp);
if (uTxtSize % 2 != 0)
{
fclose(fp);
return 1;
}
uTxtSize /= 2;
fseek(fp, 0, SEEK_SET);
Char16_t* pTemp = new Char16_t[uTxtSize + 1];
fread(pTemp, 2, uTxtSize, fp);
fclose(fp);
if (pTemp[0] != 0xFEFF)
{
delete[] pTemp;
return 1;
}
pTemp[uTxtSize] = 0;
wstring sTxt = U16ToW(pTemp + 1);
delete[] pTemp;
// £¤£¤£¤£¤£¤£¤£¤£¤Öظ´Îı¾£¤£¤£¤£¤£¤£¤£¤
wstring sReplacement = L"\uFFE5\uFFE5\uFFE5\uFFE5\uFFE5\uFFE5\uFFE5\uFFE5\u91CD\u590D\u6587\u672C\uFFE5\uFFE5\uFFE5\uFFE5\uFFE5\uFFE5\uFFE5";
wstring::size_type uPos0 = 0;
while ((uPos0 = sTxt.find(L"No.", uPos0)) != wstring::npos)
{
uPos0 += wcslen(L"No.");
wstring::size_type uPos1 = sTxt.find(L"\r\n--------------------------------------\r\n", uPos0);
if (uPos1 == wstring::npos)
{
return 1;
}
UString sNum = WToU(sTxt.substr(uPos0, uPos1 - uPos0));
uPos0 = uPos1 + wcslen(L"\r\n--------------------------------------\r\n");
uPos1 = sTxt.find(L"\r\n======================================\r\n", uPos0);
if (uPos1 == wstring::npos)
{
return 1;
}
wstring sStmtOld = sTxt.substr(uPos0, uPos1 - uPos0);
uPos0 = uPos1 + wcslen(L"\r\n======================================\r\n");
uPos1 = sTxt.find(L"\r\n--------------------------------------", uPos0);
if (uPos1 == wstring::npos)
{
return 1;
}
wstring sStmtNew = sTxt.substr(uPos0, uPos1 - uPos0);
uPos0 = uPos1 += wcslen(L"\r\n--------------------------------------");
wstring sTempTxt = sStmtOld;
sTempTxt = Replace(sTempTxt, L"[--------------------------------------]", L"");
sTempTxt = Replace(sTempTxt, L"[======================================]", L"");
if (sTempTxt.find(L"--------------------------------------") != wstring::npos)
{
return 1;
}
if (sTempTxt.find(L"======================================") != wstring::npos)
{
return 1;
}
if (sTempTxt.find(L"No.") != wstring::npos)
{
return 1;
}
sTempTxt = sStmtNew;
sTempTxt = Replace(sTempTxt, L"[--------------------------------------]", L"");
sTempTxt = Replace(sTempTxt, L"[======================================]", L"");
if (sTempTxt.find(L"--------------------------------------") != wstring::npos)
{
return 1;
}
if (sTempTxt.find(L"======================================") != wstring::npos)
{
return 1;
}
if (sTempTxt.find(L"No.") != wstring::npos)
{
return 1;
}
if (sStmtNew != sReplacement && sStmtNew != sStmtOld)
{
wstring::size_type uPosOld0 = 0;
wstring::size_type uPosNew0 = 0;
do
{
uPosOld0 = sStmtOld.find(L'{', uPosOld0);
uPosNew0 = sStmtNew.find(L'{', uPosNew0);
if (uPosOld0 == wstring::npos && uPosNew0 == wstring::npos)
{
break;
}
if (uPosOld0 == wstring::npos || uPosNew0 == wstring::npos)
{
UPrintf(USTR("No.%") PRIUS USTR(" fatal error, miss {}\n"), sNum.c_str());
break;
}
wstring::size_type uPosOld1 = uPosOld0;
uPosOld1 = sStmtOld.find(L'}', uPosOld0);
if (uPosOld1 == wstring::npos)
{
UPrintf(USTR("No.%") PRIUS USTR(" error, old not find }\n"), sNum.c_str());
return 1;
}
wstring::size_type uPosNew1 = uPosNew0;
uPosNew1 = sStmtNew.find(L'}', uPosNew0);
if (uPosNew1 == wstring::npos)
{
UPrintf(USTR("No.%") PRIUS USTR(" error, new not find }\n"), sNum.c_str());
return 1;
}
uPosOld0 = uPosOld1 + 1;
uPosNew0 = uPosNew1 + 1;
} while (true);
}
}
wstring sTxtNew;
uPos0 = 0;
while ((uPos0 = sTxt.find(L"No.", uPos0)) != wstring::npos)
{
uPos0 += wcslen(L"No.");
wstring::size_type uPos1 = sTxt.find(L"\r\n--------------------------------------\r\n", uPos0);
if (uPos1 == wstring::npos)
{
return 1;
}
UString sNum = WToU(sTxt.substr(uPos0, uPos1 - uPos0));
uPos0 = uPos1 + wcslen(L"\r\n--------------------------------------\r\n");
uPos1 = sTxt.find(L"\r\n======================================\r\n", uPos0);
if (uPos1 == wstring::npos)
{
return 1;
}
wstring sStmtOld = sTxt.substr(uPos0, uPos1 - uPos0);
uPos0 = uPos1 + wcslen(L"\r\n======================================\r\n");
uPos1 = sTxt.find(L"\r\n--------------------------------------", uPos0);
if (uPos1 == wstring::npos)
{
return 1;
}
wstring sStmtNew = sTxt.substr(uPos0, uPos1 - uPos0);
uPos0 = uPos1 += wcslen(L"\r\n--------------------------------------");
if (sStmtNew != sReplacement && sStmtNew != sStmtOld)
{
wstring::size_type uPosOld0 = 0;
wstring::size_type uPosNew0 = 0;
do
{
uPosOld0 = sStmtOld.find_first_of(L"<{", uPosOld0);
uPosNew0 = sStmtNew.find_first_of(L"<{", uPosNew0);
if (uPosOld0 == wstring::npos && uPosNew0 == wstring::npos)
{
break;
}
if (uPosOld0 == wstring::npos || uPosNew0 == wstring::npos)
{
UPrintf(USTR("No.%") PRIUS USTR(" error\n"), sNum.c_str());
break;
}
wstring::size_type uPosOld1 = uPosOld0;
if (sStmtOld[uPosOld0] == L'<')
{
uPosOld1 = sStmtOld.find(L'>', uPosOld0);
if (uPosOld1 == wstring::npos)
{
UPrintf(USTR("No.%") PRIUS USTR(" error, old not find >\n"), sNum.c_str());
return 1;
}
}
else if (sStmtOld[uPosOld0] == L'{')
{
uPosOld1 = sStmtOld.find(L'}', uPosOld0);
if (uPosOld1 == wstring::npos)
{
UPrintf(USTR("No.%") PRIUS USTR(" error, old not find }\n"), sNum.c_str());
return 1;
}
}
wstring::size_type uPosNew1 = uPosNew0;
if (sStmtNew[uPosNew0] == L'<')
{
uPosNew1 = sStmtNew.find(L'>', uPosNew0);
if (uPosNew1 == wstring::npos)
{
UPrintf(USTR("No.%") PRIUS USTR(" error, new not find >\n"), sNum.c_str());
return 1;
}
}
else if (sStmtNew[uPosNew0] == L'{')
{
uPosNew1 = sStmtNew.find(L'}', uPosNew0);
if (uPosNew1 == wstring::npos)
{
UPrintf(USTR("No.%") PRIUS USTR(" error, new not find }\n"), sNum.c_str());
return 1;
}
}
uPosOld0 = uPosOld1 + 1;
uPosNew0 = uPosNew1 + 1;
} while (true);
}
if (!sTxtNew.empty())
{
sTxtNew += L"\r\n\r\n";
}
sTxtNew += L"No.";
sTxtNew += UToW(sNum);
sTxtNew += L"\r\n--------------------------------------\r\n";
sTxtNew += sStmtOld;
sTxtNew += L"\r\n======================================\r\n";
sTxtNew += sStmtNew;
sTxtNew += L"\r\n--------------------------------------\r\n";
}
U16String sTxtNewU16 = WToU16(sTxtNew);
fp = UFopen(argv[1], USTR("wb"), false);
if (fp == nullptr)
{
return 1;
}
fwrite("\xFF\xFE", 2, 1, fp);
fwrite(sTxtNewU16.c_str(), 2, sTxtNewU16.size(), fp);
fclose(fp);
return 0;
}
| [
"[email protected]"
] | |
3c2ca1911708268ee9bdd958e45ff70ff314e108 | fe42957471db3088d6c11acc179ebf2836140299 | /benchmarks/ComponentPerformance.cpp | 10ca62c32d6a36224fc3ba7fc6bd3169ec715b4e | [
"BSL-1.0"
] | permissive | LongJohnCoder/fast_ber | 4b51099b95d223323e897574b3cbdf131fdfe0f0 | 885b29bd5b5a90df1a5122051937d07244f755bc | refs/heads/master | 2020-08-29T00:19:38.448563 | 2019-10-26T14:58:08 | 2019-10-26T14:58:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,782 | cpp | #include "fast_ber/ber_types/All.hpp"
#include "catch2/catch.hpp"
#include <vector>
const int iterations = 1000000;
template <typename T>
void component_benchmark_encode(const T& type, const std::string& type_name)
{
std::array<uint8_t, 1000> buffer{};
fast_ber::EncodeResult res = {};
BENCHMARK("fast_ber - encode " + type_name)
{
for (int i = 0; i < iterations; i++)
{
res = fast_ber::encode(absl::Span<uint8_t>(buffer), type);
}
}
REQUIRE(res.success);
}
template <typename T>
void component_benchmark_decode(const T& type, const std::string& type_name)
{
std::array<uint8_t, 1000> buffer{};
fast_ber::encode(absl::Span<uint8_t>(buffer), type);
T decoded_copy;
fast_ber::DecodeResult res = {false};
BENCHMARK("fast_ber - decode " + type_name)
{
for (int i = 0; i < iterations; i++)
{
res = fast_ber::decode(absl::Span<uint8_t>(buffer), decoded_copy);
}
}
REQUIRE(res.success);
}
template <typename T1, typename T2>
void component_benchmark_construct(const T2& initial_value, const std::string& type_name)
{
BENCHMARK("fast_ber - construct " + type_name)
{
for (int i = 0; i < iterations; i++)
{
T1 t1(initial_value);
}
}
}
template <typename T1>
void component_benchmark_default_construct(const std::string& type_name)
{
BENCHMARK("fast_ber - dflt construct " + type_name)
{
for (int i = 0; i < iterations; i++)
{
T1 t1{};
}
}
}
TEST_CASE("Component Performance: Encode")
{
component_benchmark_encode(fast_ber::Integer(-99999999), "Integer");
component_benchmark_encode(fast_ber::Boolean(true), "Boolean");
component_benchmark_encode(fast_ber::OctetString("Test string!"), "OctetString");
component_benchmark_encode(fast_ber::Null(), "Null");
component_benchmark_encode(fast_ber::ObjectIdentifier(fast_ber::ObjectIdentifierComponents{1, 2, 840, 113549}),
"ObjectIdentifier");
component_benchmark_encode(fast_ber::Optional<fast_ber::OctetString>("hello!"), "Optional (String)");
component_benchmark_encode(fast_ber::Optional<fast_ber::Integer>(500), "Optional (Integer)");
component_benchmark_encode(fast_ber::Optional<fast_ber::Integer>(absl::nullopt), "Optional (Empty)");
component_benchmark_encode(
fast_ber::Choice<fast_ber::Integer, fast_ber::OctetString>(fast_ber::OctetString("hello!")), "Choice (String)");
component_benchmark_encode(fast_ber::Choice<fast_ber::Integer, fast_ber::OctetString>(fast_ber::Integer(5)),
"Choice (Integer)");
}
TEST_CASE("Component Performance: Decode")
{
component_benchmark_decode(fast_ber::Integer(-99999999), "Integer");
component_benchmark_decode(fast_ber::Boolean(true), "Boolean");
component_benchmark_decode(fast_ber::OctetString("Test string!"), "OctetString");
component_benchmark_decode(fast_ber::Null(), "Null");
component_benchmark_decode(fast_ber::ObjectIdentifier(fast_ber::ObjectIdentifierComponents{1, 2, 840, 113549}),
"ObjectIdentifier");
component_benchmark_decode(fast_ber::Optional<fast_ber::OctetString>("hello!"), "Optional (String)");
component_benchmark_decode(fast_ber::Optional<fast_ber::Integer>(500), "Optional (Integer)");
component_benchmark_decode(fast_ber::Optional<fast_ber::Integer>(absl::nullopt), "Optional (Empty)");
component_benchmark_decode(
fast_ber::Choice<fast_ber::Integer, fast_ber::OctetString>(fast_ber::OctetString("hello!")), "Choice (String)");
component_benchmark_decode(fast_ber::Choice<fast_ber::Integer, fast_ber::OctetString>(fast_ber::Integer(5)),
"Choice (Integer)");
}
TEST_CASE("Component Performance: Object Construction")
{
component_benchmark_construct<fast_ber::Integer>(-99999999, "Integer");
component_benchmark_construct<fast_ber::Boolean>(true, "Boolean");
component_benchmark_construct<fast_ber::OctetString>("Test string!", "OctetString");
component_benchmark_construct<fast_ber::Null>(fast_ber::Null{}, "Null");
component_benchmark_construct<fast_ber::ObjectIdentifier>(fast_ber::ObjectIdentifierComponents{1, 2, 840, 113549},
"ObjectIdentifier");
component_benchmark_construct<fast_ber::Optional<fast_ber::OctetString>>("hello!", "Optional (String)");
component_benchmark_construct<fast_ber::Optional<fast_ber::Integer>>(500, "Optional (Integer)");
component_benchmark_construct<fast_ber::Optional<fast_ber::Integer>>(absl::nullopt, "Optional (Empty)");
component_benchmark_construct<fast_ber::Choice<fast_ber::Integer, fast_ber::OctetString>>(
fast_ber::OctetString("hello!"), "Choice (String)");
component_benchmark_construct<fast_ber::Choice<fast_ber::Integer, fast_ber::OctetString>>(fast_ber::Integer(5),
"Choice (Integer)");
}
TEST_CASE("Component Performance: Default Construction")
{
component_benchmark_default_construct<fast_ber::Integer>("Integer");
component_benchmark_default_construct<fast_ber::Boolean>("Boolean");
component_benchmark_default_construct<fast_ber::OctetString>("OctetString");
component_benchmark_default_construct<fast_ber::Null>("Null");
component_benchmark_default_construct<fast_ber::ObjectIdentifier>("ObjectId");
component_benchmark_default_construct<fast_ber::Optional<fast_ber::Integer>>("Optional");
component_benchmark_default_construct<fast_ber::Choice<fast_ber::Integer, fast_ber::OctetString>>("Choice");
}
| [
"[email protected]"
] | |
99fdade89c29d76e23f441c01a140c756dfbad15 | 1d085c881bb592adcfaf14ad26370bf2befc92cc | /src/node_control/src/imu/Navigation.cpp | cec8d873a1afee3668806cc0521d7ff8d53a4154 | [] | no_license | Young-Geo/Ros_Car | 2b87c3d67186a26d36c0e0a837aaeaecd1c82f05 | fe03f291c78c7dc6a437cbead908051045dd4330 | refs/heads/master | 2020-03-06T22:29:40.267059 | 2018-06-20T04:04:34 | 2018-06-20T04:04:34 | 127,104,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,110 | cpp | #include "Navigation.h"
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
void NavHistoryPush (NAV_T * nav)
{
HISTORY_T * h ;
h = &nav ->history[nav ->history_idx] ;
h ->imuk = nav ->imuk ;
h ->qnb = nav ->qnb ;
h ->att = nav ->att ;
h ->pos = nav ->pos ;
h ->velocity = nav ->velocity ;
NavHistoryInc(nav ->history_idx) ;
}
void NavHistoryPop (NAV_T * nav , int idx )
{
HISTORY_T * h ;
h = &nav ->history[idx] ;
nav ->imuk = h ->imuk ;
nav ->qnb = h ->qnb ;
nav ->att = h ->att ;
nav ->pos = h ->pos ;
nav ->velocity = h ->velocity ;
}
int NavHistoryPass (NAV_T * nav, int pass_count)
{
int i ;
i = nav ->history_idx - pass_count ;
if ( i < 0 )
{
i += HISTORY_MAX ;
}
return i ;
}
void NavSVD (NAV_T * nav, VECT * svd)
{
int i , j , t ;
static double **a = NULL ;
static double *w = NULL ;
static double **v = NULL ;
if ( !a )
{
//申请空间
a = dmatrix(1,SVD_NM,1,SVD_NM);
w = dvector(1,SVD_NM);
v = dmatrix(1,SVD_NM,1,SVD_NM);
}
//将矩阵各向量都置零
for ( i = 1 ; i <= SVD_NM ; i ++ )
{
for ( j = 1 ; j <= SVD_NM ; j ++ )
{
a[i][j] = 0 ;
v[i][j] = 0 ;
}
w[i] = 0 ;
}
//得到过去10帧的位姿,赋值给a
j = NavHistoryPass(nav, 10) ;
for ( i = 1 ; i <= 10 ; i ++ )
{
a[i][1] = nav ->history[j].att.i ;
a[i][2] = nav ->history[j].att.j ;
a[i][3] = nav ->history[j].att.k ;
//printf("svd: a[%2d][1]:%lf a[%2d][2]:%f a[%2d][3]:%f\n",i,a[i][1],i,a[i][2],i,a[i][3]);
NavHistoryInc(j);
}
//进行奇异值计算
svdcmp(a, SVD_NM, SVD_NM, w, v) ;
//将计算结果使用一个冒泡排序,按大小进行排序
for( i = 1 ; i <= SVD_N ; i ++ )
{
for( j = i + 1 ; j <= SVD_N ; j ++ )
{
if(w[i] < w[j])
{
t = w[i];
w[i] = w[j];
w[j] = t;
}
}
}
//将结果输出到返回值
svd ->i = w[1];
svd ->j = w[2];
svd ->k = w[3];
//printf("svd result: %lf %lf %lf\n",w[1],w[2],w[3]);
}
int NavSVDIsCrushed(VECT * svd)
{
if((svd ->j * 500.0 > 600.0) && (svd ->k * 500.0 > 390.0))
{
return 1 ;
}
return 0 ;
}
PVECT VelocityUpdate(PVECT vnm, VECT vnm_1, QUAT qnb, VECT vsfm)
{
VECT vtemp,vtemp1;
VECT gn;
gn.i = 0;
gn.j = 0;
gn.k = -G0;
QMulVector(&vtemp, qnb, vsfm);
VMulFactor(&vtemp1, gn, Tm);
VAdd2(vnm, vnm_1, vtemp, vtemp1);
return vnm;
}
PVECT NavSn(PVECT sn, VECT vnm, VECT vnm_1)
{
VECT vtemp;
VAdd(&vtemp,vnm,vnm_1);
VMulFactor(sn,vtemp,0.5*Tm);
return sn;
}
void MSINS(QUAT * qnb , VECT * att , VECT * velocity , VECT * pos , IMUK_T * imuk)
{
VECT sn;
VEqual(&sn, *velocity);
VelocityUpdate(velocity, *velocity,*qnb, imuk ->dv);//纯加计更新速度
velocity ->k = 0.0; //因为是平面运动,所以把z轴速度置0.
NavSn(&sn,sn,*velocity);//用速度计算位移的delta量
VAdd(pos, *pos, sn) ; //更新位置
QMulRVector(qnb, *qnb, imuk ->dw);//纯陀螺姿态更新
QNormalize(qnb, *qnb); //四元数归一化
Q2Attitude(att, *qnb) ;//将4元数转为欧拉角
VMulFactor(att, *att, 180.0/PI) ;//转成角度制
}
void NavInitMSINS(NAV_T * nav, int pass, int whole, int rump)
{
int s , e , i ;
VECT velocity ;
//计算回溯位置,并将当时的状态pop出来
nav ->history_backtracking_idx = NavHistoryPass(nav, pass) ;
NavHistoryPop(nav, nav ->history_backtracking_idx) ;
//计算出当时的速度:需要差值计算,把往前5帧,往后4帧,及当前帧共10帧,进行均值计算.
assert(pass >= 4) ;
s = NavHistoryPass(nav, pass + 5) ;
e = NavHistoryPass(nav, pass - 4) ;
VZero(&velocity) ;
for ( i = s ; i <= e ; )
{
VAdd(&velocity, velocity, nav ->history[i].velocity) ;
NavHistoryInc(i) ;
}
VMulFactor(&nav ->velocity, velocity, 0.1) ;
printf("MSINS init velocity %lf %lf %lf\n" , \
nav ->velocity.i , \
nav ->velocity.j , \
nav ->velocity.k ) ;
//总共需要进行MSINS解算多少次
nav ->msins = whole ;
//残余多少次
nav ->msins_rump = rump ;
}
int NavUpdateMSINS(NAV_T * nav)
{
HISTORY_T * h ;
assert(nav ->msins > 0) ;
h = &nav ->history[nav ->history_backtracking_idx] ;
nav ->imuk = h ->imuk ;
MSINS(&nav ->qnb, &nav ->att, &nav ->velocity, &nav ->pos, &nav ->imuk) ;
NavHistoryInc(nav ->history_backtracking_idx) ;
nav ->msins -- ;
return ((nav ->msins > 0) ? 0 : 1) ;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
static void InitDiag(double *mout, double *m_in, Uint8 size)
{
int i, j;
for(i=0; i<size; i++)
{
for(j=0; j<size; j++)
{
if(i == j)
{
mout[i * size + j] = m_in[i];
}
else
{
mout[i * size + j] = 0.0;
}
}
}
}
void InitVG(VG_T * vg)
{
Uint8 i ;
KPFRAME kpFrm ;
for(i=0; i<VGL; i++)
{
vg ->Xk[i] = 0;
}
KMatZero(vg ->F, VGL, VGL);
KMatZero(vg ->H, KM, VGL);
//P
kpFrm.kp.att[0] = pow(5.0*PI/180.0, 2);
kpFrm.kp.att[1] = pow(5.0*PI/180.0, 2);
kpFrm.kp.att[2] = pow(5.0*PI/180.0, 2);
kpFrm.kp.eb[0] = pow(60.0*PI/180.0/3600.0, 2);
kpFrm.kp.eb[1] = pow(60.0*PI/180.0/3600.0, 2);
kpFrm.kp.eb[2] = pow(60.0*PI/180.0/3600.0, 2);
InitDiag(vg ->Pk, kpFrm.db, VGL);
//Q
kpFrm.kp.att[0] = pow(0.2*PI/180.0/60.0, 2);
kpFrm.kp.att[1] = pow(0.2*PI/180.0/60.0, 2);
kpFrm.kp.att[2] = pow(0.2*PI/180.0/60.0, 2);
kpFrm.kp.eb[0] = pow(0.2*PI/180.0/3600.0, 2);
kpFrm.kp.eb[1] = pow(0.2*PI/180.0/3600.0, 2);
kpFrm.kp.eb[2] = pow(0.2*PI/180.0/3600.0, 2);
InitDiag(vg ->Q0, kpFrm.db, VGL);
vg ->H[1] = -G0;
vg ->H[KL] = G0;
//R
kpFrm.kp.att[0] = pow(0.4*MG, 2);
kpFrm.kp.att[1] = pow(0.4*MG, 2);
kpFrm.kp.att[2] = pow(0.4*MG, 2);
InitDiag(vg ->R, kpFrm.db, KM);
}
////////////////////////////////////////////////////////////////////////
void UpdateVG(VG_T * vg, IMUK_T * imuk , QUAT * qnb, VECT * att)
{
MAT Cnb;
VECT phim, vsfm;
VECT gn;
VECT vTemp;
double Zk[KM], phi[VGL*VGL];
gn.i = 0;
gn.j = 0;
gn.k = -G0;
phim.i = imuk ->dw.i;
phim.j = imuk ->dw.j;
phim.k = imuk ->dw.k;
vsfm.i = imuk ->dv.i;
vsfm.j = imuk ->dv.j;
vsfm.k = imuk ->dv.k;
////////////KF
memset(vg ->Xk, 0, sizeof(vg ->Xk)) ;
QMulRVector(qnb, *qnb, phim);//纯陀螺姿态更新
QMulVector(&vsfm, *qnb, vsfm);
VMulFactor(&vsfm, vsfm, 1/Tm);//fnsf
VAdd(&vTemp,vsfm,gn);
Zk[0] = vTemp.i;
Zk[1] = vTemp.j;
Zk[2] = vTemp.k;
Q2AttMatrix(&Cnb, *qnb);
GetKalmanF(vg ->F, VGL, Cnb);
GetKalmanQ(vg ->Q, vg ->Q0, vg ->F, VGL, Tm);
GetKalmanPhi(phi, vg ->F, VGL, Tm);
KFTimeUpdate(vg ->Xk, vg ->Pk, phi, vg ->Q, VGL);
KFMeasureUpdate(vg ->Xk, vg ->Pk, Zk, vg ->H, vg ->R, VGL);
phim.i = vg ->Xk[0];
phim.j = vg ->Xk[1];
phim.k = vg ->Xk[2];
if(VNorm(imuk ->dv)<1.2)//1.3
{
imuk ->dv.k = 0;
if(VNorm(imuk ->dv)<0.6)//0.7
{
QDelPhi(qnb, phim, *qnb);//加计修正姿态
}
}
Q2Attitude(att, *qnb) ;//将4元数转成欧拉角
VMulFactor(att, *att, 180.0/PI) ;//转成角度制
}
////////////////////////////////////////////////////////////////////////
PVECT DRSn(PVECT sn, double milemeter, QUAT qnb, IMUK_T * imuk)
{
double scm = milemeter * PPDIS ;
VECT dSb, vtmp, vtmp1;
double meliPhi , meliTheta;
//计算里程计中心相对于陀螺仪的安装角度
meliTheta = ODO_GY_THETA ;
meliPhi = ODO_GY_PHI ;
dSb.i = scm * cos(meliTheta) * sin(meliPhi);
dSb.j = scm * cos(meliTheta) * cos(meliPhi);
dSb.k = scm * sin(meliTheta);
//计算里程计中心相对于陀螺仪的安装位置
vtmp1.i = ODO_GY_DELTA_X ;
vtmp1.j = ODO_GY_DELTA_Y ;
vtmp1.k = ODO_GY_DELTA_Z ;
VMulCross(&vtmp, imuk ->dw, vtmp1);
VMulFactor(&vtmp1, vtmp, -1.0);
VAdd(&vtmp, vtmp, vtmp1);
//这里是不是还要加入对vtmp的使用代码?
//计算SN
QMulVector(sn, qnb, dSb);
return sn;
}
void UpdatePos(VECT * velocity, VECT * pos, QUAT * qnb, IMUK_T * imuk)
{
VECT sn ;
double milemeter ;
milemeter = (imuk ->vl + imuk ->vr) / 2.0;
DRSn(&sn, milemeter, *qnb, imuk);//得到位置增量
VMulFactor(velocity, sn, 1 / Tm);//计算速度
//位置更新
VAdd(pos, *pos, sn) ;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
void NavInit(NAV_T * nav)
{
memset(nav, 0, sizeof(NAV_T)) ;
InitVG(&nav ->vg) ;
QInitialize(&nav ->qnb, 1, 0, 0, 0) ;
nav ->eb_len = 1200 ;
nav ->svd_work_len = nav ->eb_len + 256 ;
}
void NavUpdate ( NAV_T * nav , IMUK_T * imuk )
{
nav ->imuk = *imuk ;
#if 0
printf("input data : %lf %lf %lf %lf %lf %lf %d %d %d\n",\
nav ->imuk.dw.i,\
nav ->imuk.dw.j,\
nav ->imuk.dw.k,\
nav ->imuk.dv.i,\
nav ->imuk.dv.j,\
nav ->imuk.dv.k,\
nav ->imuk.vl,\
nav ->imuk.vr,\
nav ->imuk.timestamp);
#endif
if( abs(nav ->imuk.vl) > 1024 )
{
nav ->imuk.vl = 0 ;
nav ->imuk.vr = 0 ;
}
if( abs(nav ->imuk.vr) > 1024 )
{
nav ->imuk.vr = 0 ;
nav ->imuk.vl = 0 ;
}
nav ->cnt ++ ;
if ( nav ->cnt < nav ->eb_len )
{
VAdd(&nav ->eb,nav ->eb,nav ->imuk.dw);
if(nav ->cnt % 100 == 0)
{
printf("System Init Plase Waiting...%d\n", 12 - nav ->cnt / 100);
}
return ;
}
if ( nav ->cnt == nav ->eb_len )
{
//计算零偏
VAdd(&nav ->eb,nav ->eb,nav ->imuk.dw);
VMulFactor(&nav ->eb,nav ->eb,-1.0 / nav ->cnt);
printf("System Init Result %e %e %e\n", nav ->eb.i , nav ->eb.j , nav ->eb.k) ;
}
//扣除零偏
VAdd(&(nav ->imuk.dw),nav ->imuk.dw,nav ->eb);
//判断当前是否是纯惯导模式
if ( nav ->msins > 0 )
{
//纯惯导模式
int i ;
//在纯惯导模式下,也需要记录imuk的实时数据.
NavHistoryPush(nav) ;
//每次进行3次纯惯导运算,可用100ms追上实时更新的数据.
//即,从开始纯惯导,到纯惯导结束,共用时100ms,10个周期。这10个周期内又产生了10组新数据,由于每周期解算3次,那这10个周期内解算了
//30组数据,刚好解算完成。
for ( i = 0 ; i < 3 ; i ++ )
{
printf("MSINS ing...%d\n" , nav ->msins) ;
if ( NavUpdateMSINS(nav) )
{
printf("MSINS finished!\n") ;
break ;
}
}
}
//正常模式
else
{
//更新位姿
UpdateVG(&nav ->vg, &nav ->imuk, &nav ->qnb, &nav ->att) ;
//通过里程计进行位置推算
UpdatePos(&nav ->velocity, &nav ->pos, &nav ->qnb, &nav ->imuk) ;
//将数据存储于到历史数据区中,用作纯惯导检测、回溯、曲率计算、打滑锁定
NavHistoryPush(nav) ;
//在残余阶段,不能进入纯惯导模式
if ( nav ->msins_rump > 0 )
{
nav ->msins_rump -- ;
}
if ( (nav ->cnt > nav ->svd_work_len) && (nav ->msins_rump <= 0) )
{
//进行奇异值计算
NavSVD(nav, &nav ->svd) ;
if ( NavSVDIsCrushed(&nav ->svd) )
{
//位姿有比较大的变化,说明刚体在进行比较剧烈的运动,这个时候要进入纯惯导。
//纯惯导有效性时间是300MS,所以回溯20帧,之后每秒算3帧数据,恰好10个周期算守30组数据(20个历史数据+新产生的10帧数据)实时数据。
printf("MSINS enable!\n") ;
NavInitMSINS(nav, HISTORY_MSINS - 10, HISTORY_MSINS, HISTORY_MSINS_RUMP) ;
}
}
}
if ( nav ->cnt % 300 == 0 )
{
printf("odo: [%d %d] att: [%lf %lf %lf] pos: [%lf %lf %lf] \n\t - svd: <%lf %lf %lf> velocity: <%lf %lf %lf>\n",\
nav ->imuk.vl,\
nav ->imuk.vr,\
nav ->att.i,\
nav ->att.j,\
nav ->att.k,\
nav ->pos.i,\
nav ->pos.j,\
nav ->pos.k,\
nav ->svd.i,\
nav ->svd.j,\
nav ->svd.k,\
nav ->velocity.i,\
nav ->velocity.j,\
nav ->velocity.k);
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
a4350f06e60d570feccd84b1ecab98dd4299f9ab | 068a46b3281cb80277d3f1068da8223894dcccb6 | /server/sv_netinterface.h | 5e9fc1a5c014ee896920ced8257a90d5192b6ca3 | [] | no_license | lachbr/libpandabsp-game | f8b9155db9a57ebb6f620125c0e87b52451d26ef | ecf668230bfd2606adde43ac00d3d7b9348f5a9d | refs/heads/master | 2022-04-23T19:11:06.716343 | 2020-04-19T02:06:52 | 2020-04-19T02:06:52 | 256,395,933 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,554 | h | #pragma once
#include <pmap.h>
#include <uniqueIdAllocator.h>
#include <referenceCount.h>
#include "baseentity.h"
#include "bsploader.h"
#include "client.h"
#include "iserverdatagramhandler.h"
#include "igamesystem.h"
#include <steam\steamnetworkingsockets.h>
NotifyCategoryDeclNoExport( server )
class EXPORT_SERVER_DLL ServerNetInterface : private ISteamNetworkingSocketsCallbacks, public IGameSystem
{
DECLARE_CLASS( ServerNetInterface, IGameSystem )
public:
ServerNetInterface();
// Methods of IGameSystem
virtual const char *get_name() const;
virtual bool initialize();
virtual void shutdown();
virtual void update( double frametime );
void add_datagram_handler( IServerDatagramHandler *handler );
virtual PT( CBaseEntity ) make_player();
void send_tick();
void broadcast_datagram( Datagram &dg, bool only_playing = false );
void snapshot();
void send_full_snapshot_to_client( Client *cl );
Datagram build_tick();
void send_tick( Client *cl );
virtual void OnSteamNetConnectionStatusChanged( SteamNetConnectionStatusChangedCallback_t *clbk ) override;
typedef pmap<HSteamNetConnection, PT( Client )> clientmap_t;
void send_datagram( Datagram &dg, HSteamNetConnection conn );
void send_datagram_to_clients( Datagram &dg, const vector_uint32 &client_ids );
void send_datagram_to_client( Datagram &dg, uint32_t client_id );
void process_cmd( Client *cl, const std::string &cmd );
void update_client_state( Client *cl, int state );
void read_incoming_messages();
void run_networking_events();
clientmap_t *get_clients();
int get_max_clients() const;
private:
int remove_client( Client *cl );
void handle_datagram( Datagram &dg, Client *cl );
void handle_client_hello( SteamNetConnectionStatusChangedCallback_t *info );
private:
pvector<IServerDatagramHandler *> _datagram_handlers;
UniqueIdAllocator _client_id_alloc;
clientmap_t _clients_by_address;
SimpleHashMap<uint32_t, Client *, int_hash> _clients_by_id;
HSteamListenSocket _listen_socket;
HSteamNetPollGroup _poll_group;
int _max_clients;
bool _is_started;
};
INLINE int ServerNetInterface::get_max_clients() const
{
return _max_clients;
}
INLINE void ServerNetInterface::add_datagram_handler( IServerDatagramHandler *handler )
{
_datagram_handlers.push_back( handler );
}
INLINE ServerNetInterface::clientmap_t *ServerNetInterface::get_clients()
{
return &_clients_by_address;
}
INLINE const char *ServerNetInterface::get_name() const
{
return "ServerNetInterface";
}
extern EXPORT_SERVER_DLL ServerNetInterface *svnet; | [
"[email protected]"
] | |
d2c9290c930e8d72caf6256e3827ba0dc63f5bad | 393342b158891746e7b64dc25c6ccbce90abd0e3 | /Labs/Lab4/mainLab4.cpp | 3a0467eb20d0823259862f4203374a36cc070b3b | [] | no_license | zwetekamm/CS162 | 6a307f3536858a2494be763d4c1ca4606ca0bc8d | fcd6a6cf09751b68c713a0cf86b41fbcc38b5ec7 | refs/heads/master | 2020-04-05T01:47:55.516462 | 2018-12-19T19:45:17 | 2018-12-19T19:45:17 | 156,450,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 490 | cpp | /*******************************************************************************
* Author: Zachary Wetekamm
* Date: 07/22/18
* Description: Main file for Lab4, which uses the classes University, Building,
* Person, Student, and Instructor to demonstrate polymorphism.
*******************************************************************************/
#include "university.hpp"
#include <iostream>
int main()
{
University osu("Oregon State University");
osu.start();
return 0;
}
| [
"[email protected]"
] | |
fba217d3e6ce167002bc7be1e8e95eac3977a25b | c03a202e1215e2b192babca2b084b66543aadf68 | /ANARC05B.cpp | c8ecb8c162cd9a5e59ea9c47ee43029c23291500 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | Akki5/spoj-solutions | 9af62efbca6211762b1bcded3c8950ee963d8e69 | 9169830415eb4f888ba0300eb47a423166b8d938 | refs/heads/master | 2021-01-01T05:30:21.107707 | 2015-01-06T08:41:57 | 2015-01-06T08:41:57 | 28,825,231 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 675 | cpp | #include <iostream>
#include <cstdio>
using namespace std;
int main() {
int n1,n2,i,j;
long long ans,res1,res2;
scanf("%d",&n1);
while(n1!=0)
{
int *A=new int[n1];
for(i=0;i<n1;i++) scanf("%d",&A[i]);
scanf("%d",&n2);
int *B=new int[n2];
for(i=0;i<n2;i++) scanf("%d",&B[i]);
i=0;
j=0;
res1=0;
res2=0;
ans=0;
while(i<n1&&j<n2)
{
if(A[i]==B[j])
{
ans+=max(res1,res2)+A[i];
res1=0;
res2=0;
i++;
j++;
}
else if(A[i]<B[j])
{
res1+=A[i++];
}
else
res2+=B[j++];
}
for(int k=i;k<n1;k++) res1+=A[k];
for(int k=j;k<n2;k++) res2+=B[k];
ans+=max(res1,res2);
cout<<ans<<"\n";
scanf("%d",&n1);
}
}
| [
"[email protected]"
] | |
e4e3c9ef8471dc84bcbd091ba7596e1f9ca0ebd1 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /ui/ozone/platform/drm/gpu/drm_display_unittest.cc | 30e8c7ef8bcf877adfd82632881302e59a78c0cf | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 6,676 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/ozone/platform/drm/gpu/drm_display.h"
#include <utility>
#include "base/test/task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/color_space.h"
#include "ui/gfx/linux/test/mock_gbm_device.h"
#include "ui/ozone/platform/drm/gpu/hardware_display_plane.h"
#include "ui/ozone/platform/drm/gpu/hardware_display_plane_manager.h"
#include "ui/ozone/platform/drm/gpu/mock_drm_device.h"
#include "ui/ozone/platform/drm/gpu/screen_manager.h"
using ::testing::_;
using ::testing::SizeIs;
// Verifies that the argument goes from 0 to the maximum uint16_t times |scale|.
MATCHER_P(MatchesLinearRamp, scale, "") {
EXPECT_FALSE(arg.empty());
EXPECT_EQ(arg.front().r, 0);
EXPECT_EQ(arg.front().g, 0);
EXPECT_EQ(arg.front().b, 0);
const uint16_t max_value = std::numeric_limits<uint16_t>::max() * scale;
const auto middle_element = arg[arg.size() / 2];
const uint16_t middle_value = max_value * (arg.size() / 2) / (arg.size() - 1);
EXPECT_NEAR(middle_element.r, middle_value, 1);
EXPECT_NEAR(middle_element.g, middle_value, 1);
EXPECT_NEAR(middle_element.b, middle_value, 1);
const uint16_t last_value = max_value;
EXPECT_EQ(arg.back().r, last_value);
EXPECT_EQ(arg.back().g, last_value);
EXPECT_EQ(arg.back().b, last_value);
return true;
}
namespace ui {
namespace {
class MockHardwareDisplayPlaneManager : public HardwareDisplayPlaneManager {
public:
explicit MockHardwareDisplayPlaneManager(DrmDevice* drm)
: HardwareDisplayPlaneManager(drm) {}
~MockHardwareDisplayPlaneManager() override = default;
MOCK_METHOD3(SetGammaCorrection,
bool(uint32_t crtc_id,
const std::vector<display::GammaRampRGBEntry>& degamma_lut,
const std::vector<display::GammaRampRGBEntry>& gamma_lut));
bool Modeset(uint32_t crtc_id,
uint32_t framebuffer_id,
uint32_t connector_id,
const drmModeModeInfo& mode,
const HardwareDisplayPlaneList& plane_list) override {
return false;
}
bool DisableModeset(uint32_t crtc_id, uint32_t connector) override {
return false;
}
bool Commit(HardwareDisplayPlaneList* plane_list,
scoped_refptr<PageFlipRequest> page_flip_request,
std::unique_ptr<gfx::GpuFence>* out_fence) override {
return false;
}
bool DisableOverlayPlanes(HardwareDisplayPlaneList* plane_list) override {
return false;
}
bool SetColorCorrectionOnAllCrtcPlanes(
uint32_t crtc_id,
ScopedDrmColorCtmPtr ctm_blob_data) override {
return false;
}
bool ValidatePrimarySize(const DrmOverlayPlane& primary,
const drmModeModeInfo& mode) override {
return false;
}
void RequestPlanesReadyCallback(
DrmOverlayPlaneList planes,
base::OnceCallback<void(DrmOverlayPlaneList planes)> callback) override {
return;
}
bool InitializePlanes() override { return false; }
bool SetPlaneData(HardwareDisplayPlaneList* plane_list,
HardwareDisplayPlane* hw_plane,
const DrmOverlayPlane& overlay,
uint32_t crtc_id,
const gfx::Rect& src_rect) override {
return false;
}
std::unique_ptr<HardwareDisplayPlane> CreatePlane(
uint32_t plane_id) override {
return nullptr;
}
bool IsCompatible(HardwareDisplayPlane* plane,
const DrmOverlayPlane& overlay,
uint32_t crtc_index) const override {
return false;
}
bool CommitColorMatrix(const CrtcProperties& crtc_props) override {
return false;
}
bool CommitGammaCorrection(const CrtcProperties& crtc_props) override {
return false;
}
};
} // namespace
class DrmDisplayTest : public testing::Test {
protected:
DrmDisplayTest()
: mock_drm_device_(base::MakeRefCounted<MockDrmDevice>(
std::make_unique<MockGbmDevice>())),
drm_display_(&screen_manager_, mock_drm_device_) {}
MockHardwareDisplayPlaneManager* AddMockHardwareDisplayPlaneManager() {
auto mock_hardware_display_plane_manager =
std::make_unique<MockHardwareDisplayPlaneManager>(
mock_drm_device_.get());
MockHardwareDisplayPlaneManager* pointer =
mock_hardware_display_plane_manager.get();
mock_drm_device_->plane_manager_ =
std::move(mock_hardware_display_plane_manager);
return pointer;
}
base::test::TaskEnvironment env_;
scoped_refptr<DrmDevice> mock_drm_device_;
ScreenManager screen_manager_;
DrmDisplay drm_display_;
};
TEST_F(DrmDisplayTest, SetColorSpace) {
drm_display_.set_is_hdr_capable_for_testing(true);
MockHardwareDisplayPlaneManager* plane_manager =
AddMockHardwareDisplayPlaneManager();
ON_CALL(*plane_manager, SetGammaCorrection(_, SizeIs(0), _))
.WillByDefault(::testing::Return(true));
const auto kHDRColorSpace = gfx::ColorSpace::CreateHDR10();
EXPECT_CALL(*plane_manager, SetGammaCorrection(_, SizeIs(0), SizeIs(0)));
drm_display_.SetColorSpace(kHDRColorSpace);
const auto kSDRColorSpace = gfx::ColorSpace::CreateREC709();
constexpr float kHDRLevel = 2.0;
EXPECT_CALL(
*plane_manager,
SetGammaCorrection(_, SizeIs(0), MatchesLinearRamp(1.0 / kHDRLevel)));
drm_display_.SetColorSpace(kSDRColorSpace);
}
TEST_F(DrmDisplayTest, SetEmptyGammaCorrectionNonHDRDisplay) {
MockHardwareDisplayPlaneManager* plane_manager =
AddMockHardwareDisplayPlaneManager();
ON_CALL(*plane_manager, SetGammaCorrection(_, _, _))
.WillByDefault(::testing::Return(true));
EXPECT_CALL(*plane_manager, SetGammaCorrection(_, SizeIs(0), SizeIs(0)));
drm_display_.SetGammaCorrection(std::vector<display::GammaRampRGBEntry>(),
std::vector<display::GammaRampRGBEntry>());
}
TEST_F(DrmDisplayTest, SetEmptyGammaCorrectionHDRDisplay) {
drm_display_.set_is_hdr_capable_for_testing(true);
MockHardwareDisplayPlaneManager* plane_manager =
AddMockHardwareDisplayPlaneManager();
ON_CALL(*plane_manager, SetGammaCorrection(_, _, _))
.WillByDefault(::testing::Return(true));
constexpr float kHDRLevel = 2.0;
EXPECT_CALL(
*plane_manager,
SetGammaCorrection(_, SizeIs(0), MatchesLinearRamp(1.0 / kHDRLevel)));
drm_display_.SetGammaCorrection(std::vector<display::GammaRampRGBEntry>(),
std::vector<display::GammaRampRGBEntry>());
}
} // namespace ui
| [
"[email protected]"
] | |
56316f8b4fb7727ba84b3acf7ff4cdc2c242e230 | 76fb9740c43caa87f53c46462a282c517953c96f | /VecTest.cpp | 5a893cede75705b886303554212dd8413e7192cb | [] | no_license | 1suming/STLSimulate | 74ece8beadeb3e96b606a37892e17d977c746974 | d3b6833836c12451bd3917bdf32b9f889086af76 | refs/heads/master | 2020-12-24T13:29:27.210566 | 2015-03-21T03:23:32 | 2015-03-21T03:23:32 | 12,348,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 629 | cpp | #include<iostream>
#include"vec.cpp"
int main()
{
Vec<int> v; //no argument construtor
v.push_back(1);
cout<<v[0]<<endl;
Vec<int> v2(5,2); //Vec(size_t n,const T& val=T())
for(int i=0;i<v2.size();i++)
cout<<v2[i]<<ends;
cout<<endl;
Vec<int> v3(v2); //copy constructor
for(int i=0;i<v3.size();i++)
cout<<v3[i]<<ends;
cout<<endl;
Vec<int> v4;
v4=v3;
for(Vec<int>::const_iterator it=v4.begin();it!=v4.end();it++)
{
cout<<*it<<ends;
}
cout<<endl;
//erase
v4.erase(v4.begin(),v4.begin()+2);
v4[0]=3;
for(Vec<int>::const_iterator it=v4.begin();it!=v4.end();it++)
{
cout<<*it<<ends;
}
cout<<endl;
}
| [
"[email protected]"
] | |
b7628cdb794567bc3c14a61548231f69d26de468 | 2f1a092537d8650cacbd274a3bd600e87a627e90 | /thrift/compiler/test/fixtures/py3/gen-py3/empty/clients_wrapper.cpp | f7b51182414c3d22c7d6a0e443cf7aa5af7ba00b | [
"Apache-2.0"
] | permissive | ConnectionMaster/fbthrift | 3aa7d095c00b04030fddbabffbf09a5adca29d42 | d5d0fa3f72ee0eb4c7b955e9e04a25052678d740 | refs/heads/master | 2023-04-10T17:49:05.409858 | 2021-08-03T02:32:49 | 2021-08-03T02:33:57 | 187,603,239 | 1 | 1 | Apache-2.0 | 2023-04-03T23:15:28 | 2019-05-20T08:49:29 | C++ | UTF-8 | C++ | false | false | 209 | cpp | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#include <src/gen-py3/empty/clients_wrapper.h>
namespace cpp2 {
} // namespace cpp2
| [
"[email protected]"
] | |
95a5e5d357af78f16a17003279d9c4e7b8268b0c | c101ad1f394a590c48afb1998c8bc9fdb20b9bc6 | /sketch_senseair_s8_neopixel/sketch_senseair_s8_neopixel.ino | 400c6bb3a0316c6b144a478f8295efbc29cb9129 | [
"MIT"
] | permissive | fvanderbiest/arduino-sketches | 6e0824dc0fa966ec63c5539f2c07fb40d667bc4e | 602338fec86b1968e1fcfa1fe10a0a6ca24db505 | refs/heads/main | 2023-02-22T02:03:13.427297 | 2021-02-02T21:28:31 | 2021-02-02T21:28:31 | 323,269,267 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,489 | ino | #include "SoftwareSerial.h"
#include "Adafruit_NeoPixel.h"
#include "TaskScheduler.h"
#define RX_PIN 3
#define TX_PIN 4
#define NUMPIXELS 1
#define PIN_WS2812 7
#define BRIGHTNESS 50
#define MEASURE_PERIOD 5000
void measure();
void blinkLed();
Task mainTask(MEASURE_PERIOD, TASK_FOREVER, &measure);
Task blinkTask(500, TASK_FOREVER, &blinkLed);
Scheduler runner;
SoftwareSerial SoftSerial(RX_PIN, TX_PIN);
Adafruit_NeoPixel neopixel = Adafruit_NeoPixel(NUMPIXELS, PIN_WS2812);
int getCO2() {
// Inspired from https://github.com/airgradienthq/arduino
int retry = 0;
const byte CO2Command[] = {0xFE, 0X44, 0X00, 0X08, 0X02, 0X9F, 0X25};
byte CO2Response[] = {0,0,0,0,0,0,0};
while(!(SoftSerial.available())) {
retry++;
SoftSerial.write(CO2Command, 7);
delay(50);
if (retry > 10) {
return -1;
}
}
int timeout = 0;
while (SoftSerial.available() < 7) {
timeout++;
if (timeout > 10) {
while(SoftSerial.available())
SoftSerial.read();
break;
}
delay(50);
}
for (int i=0; i < 7; i++) {
int byte = SoftSerial.read();
if (byte == -1) {
return -1;
}
CO2Response[i] = byte;
}
int high = CO2Response[3];
int low = CO2Response[4];
unsigned long val = high*256 + low;
return val;
}
void fillLed(boolean red) {
if (red) {
neopixel.fill(neopixel.Color(255, 0, 0), 0, NUMPIXELS);
} else {
neopixel.fill(neopixel.Color(0, 255, 0), 0, NUMPIXELS);
}
}
boolean ledOn = false;
void blinkLed() {
if (ledOn) {
neopixel.clear();
ledOn = false;
} else {
fillLed(true);
ledOn = true;
}
neopixel.show();
}
void measure() {
int taux_co2 = getCO2();
if (taux_co2 < 430) {
blinkTask.disable();
neopixel.fill(neopixel.Color(255, 255, 255), 0, NUMPIXELS);
neopixel.show();
} else if (taux_co2 < 1000) {
blinkTask.disable();
if (taux_co2 < 800) {
fillLed(false);
} else {
fillLed(true);
}
neopixel.show();
} else {
if (taux_co2 > 2000) {
blinkTask.setInterval(50);
} else {
int period = 500 - 450 * (taux_co2 - 1000) / 1000;
if (period != blinkTask.getInterval()) {
blinkTask.setInterval(period);
}
}
blinkTask.enable();
}
}
void setup(){
neopixel.begin();
neopixel.setBrightness(BRIGHTNESS);
SoftSerial.begin(9600);
runner.init();
runner.addTask(mainTask);
mainTask.enable();
runner.addTask(blinkTask);
}
void loop(){
runner.execute();
}
| [
"[email protected]"
] | |
99f762a508375f1af46f83bf23a45f50ddb2eb2a | f6e58c4c2e2e932f580e8092c6a86197503d6e9a | /galaxy/src/galaxy/graphics/AnimationFrame.cpp | 6a38d9c3908a5a461dbd9604eec70d8f50b199cf | [
"Apache-2.0"
] | permissive | blockspacer/galaxy | 7df4dc839b23dad764589492e672d1c22478f2bb | 59766490fd5a30f128dabf5f02a712d06df54f2b | refs/heads/master | 2021-03-17T15:41:55.150851 | 2020-02-21T08:26:48 | 2020-02-21T08:26:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,032 | cpp | ///
/// AnimationFrame.cpp
/// galaxy
///
/// Created by reworks on 07/03/2018.
/// MIT License.
/// Refer to LICENSE.txt for more details.
///
#include "galaxy/core/ServiceLocator.hpp"
#include "galaxy/graphics/TextureAtlas.hpp"
#include "AnimationFrame.hpp"
namespace galaxy
{
AnimationFrame::AnimationFrame()
:m_timePerFrame(0), m_frameTextureID(Locator::textureAtlas->m_nullTexture)
{
}
AnimationFrame::AnimationFrame(const std::uint32_t timePerFrame, const std::string& frameTextureID)
:m_timePerFrame(timePerFrame), m_frameTextureID(frameTextureID)
{
// Argument constructor.
}
AnimationFrame::AnimationFrame(AnimationFrame&& af)
:m_timePerFrame(af.m_timePerFrame), m_frameTextureID(af.m_frameTextureID)
{
// Explicit copy constructor.
}
AnimationFrame::AnimationFrame(const AnimationFrame& af)
:m_timePerFrame(af.m_timePerFrame), m_frameTextureID(af.m_frameTextureID)
{
// Explicit move constructor.
}
AnimationFrame& AnimationFrame::operator=(const AnimationFrame &)
{
return *this;
}
} | [
"[email protected]"
] | |
318eae611960a3a18cea73770623b178d8d4f06a | 920dc0c7a32229b6c6aea2a3f860178b2bb2fe81 | /plugins/mqtt2mongo_plugin/mqtt2mongo_plugin.cpp | cf0dd8556691a7dcec3b191bad6a6be8bd985018 | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | myappbase/myappbase | d2afd8a04a62ba27e1d29806c1a8fd288a015487 | 5a405ca0c1411da48ee755874b11dfb4ee625155 | refs/heads/master | 2023-01-22T06:36:41.584611 | 2020-12-02T02:22:03 | 2020-12-02T02:22:03 | 316,116,177 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,571 | cpp | #include <mqtt2mongo_plugin/mqtt2mongo_plugin.hpp>
#include <fc/io/json.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/variant.hpp>
#include <help_mqtt/help_mqtt.hpp>
#include <help_mongo/help_mongo.hpp>
namespace my
{
using namespace std;
using namespace help_mongo;
using namespace help_mqtt;
using namespace bsoncxx::types;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
static appbase::abstract_plugin &_mqtt2mongo_plugin = app().register_plugin<mqtt2mongo_plugin>();
class mongo_instance
{
public:
std::string mongod_uri = "mongodb://127.0.0.1:27017/datastore";
std::string db_name = "datastore";
mongocxx::instance mongo_inst;
fc::optional<mongocxx::pool> mongo_pool;
mongocxx::collection _datastore_col;
std::atomic_bool startup{true};
const std::string datastore_collection_name = "datastore";
void store_datastore(const std::string& data)
{
auto doc = bsoncxx::builder::basic::document{};
ilog("data=${d}",("d", data));
try
{
doc.append(kvp("_id", help_mongo::make_custom_oid()));
fc::variant v = fc::json::from_string(data);
doc.append(bsoncxx::builder::concatenate_doc{to_bson(v)});
}
catch (...)
{
help_mongo::handle_mongo_exception("create bson doc", __LINE__);
elog( "${d}", ("d", data));
return ;
}
try
{
auto result = _datastore_col.insert_one(doc.view());
if( !result)
elog( "Failed to insert datastore ${d}", ("d", data));
}
catch (...)
{
help_mongo::handle_mongo_exception("datastore insert", __LINE__);
elog( "${d}", ("d", data));
}
}
void start()
{
ilog("init mongo");
try
{
auto mongo_client = mongo_pool->acquire();
auto &mongo_conn = *mongo_client;
try
{
_datastore_col = mongo_conn[db_name][datastore_collection_name];
_datastore_col.create_index(bsoncxx::from_json(R"xxx({ "id" : 1, "_id" : 1 })xxx"));
}
catch (...)
{
help_mongo::handle_mongo_exception("create indexes", __LINE__);
ilog("quit now ...");
raise(SIGINT);
return;
}
}
catch (...)
{
help_mongo::handle_mongo_exception("mongo init", __LINE__);
ilog("quit now ...");
raise(SIGINT);
return;
}
startup = false;
}
mongo_instance()
{
}
~mongo_instance()
{
if (!startup)
{
try
{
mongo_pool.reset();
}
catch (std::exception &e)
{
elog("Exception on mqtt2mongo_plugin shutdown of consume thread: ${e}", ("e", e.what()));
}
}
}
}; // class mongo_instance
class mycallback : public virtual mqtt::callback,
public virtual mqtt::iaction_listener
{
mqtt::async_client& cli_;
mqtt::connect_options& connOpts_;
action_listener subListener_ = action_listener("Subscription");
std::string server;
std::string topic;
std::string client_id;
int qos = 1;
int nretry_ = 0;
std::shared_ptr<class mongo_instance> mongo;
public:
void reconnect() {
std::this_thread::sleep_for(std::chrono::milliseconds(2500));
try {
cli_.connect(connOpts_, nullptr, *this);
}
catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
exit(1);
}
}
// Re-connection failure
void on_failure(const mqtt::token& tok) override {
std::cout << "Connection attempt failed" << std::endl;
if (++nretry_ > 5 )
exit(1);
reconnect();
}
void on_success(const mqtt::token& tok) override {}
void connected(const std::string& cause) override {
std::cout << "\nConnection success, Subscribing to topic '" << topic << "'\n"
<< "\tfor client " << client_id
<< " using QoS" << qos << std::endl;
cli_.subscribe(topic, qos, nullptr, subListener_);
}
void connection_lost(const std::string& cause) override {
std::cout << "\nConnection lost" << std::endl;
if (!cause.empty())
std::cout << "\tcause: " << cause << std::endl;
std::cout << "Reconnecting..." << std::endl;
nretry_ = 0;
reconnect();
}
void message_arrived(mqtt::const_message_ptr msg) override {
std::cout << "Message arrived" << std::endl;
std::cout << "\ttopic: '" << msg->get_topic() << "'" << std::endl;
std::cout << "\tpayload: '" << msg->to_string() << "'\n" << std::endl;
mongo->store_datastore(msg->to_string());
}
void delivery_complete(mqtt::delivery_token_ptr token) override {}
mycallback(mqtt::async_client& cli,
mqtt::connect_options& connOpts,
std::string& server_,
std::string& topic_,
std::string& client_id_,
std::shared_ptr<class mongo_instance> mongo_ ):
cli_(cli),
connOpts_(connOpts),
server(server_),
topic(topic_),
client_id(client_id_),
mongo(mongo_)
{}
};
////////////////////////////////////////////////////////////////////////////////////////
class mqtt_instance : std::enable_shared_from_this<mqtt_instance> {
public:
std::string mqtt_server = "tcp://post-cn-n6w1qkoir06.mqtt.aliyuncs.com:1883";
std::string mqtt_topic = "eosio_topic" ;
std::string mqtt_client = "GID_eosio@@@mongo";
std::string mqtt_user = "Signature|LTAI4GJKsfb8VexSkcQodggS|post-cn-n6w1qkoir06";
std::string mqtt_password = "9cut+eYpoc4CCd9IpOuXToqdocA=" ;
fc::optional<mqtt::async_client> client;
bool subscribe(std::shared_ptr<class mongo_instance>& mongo) {
mqtt::connect_options connOpts = mqtt::connect_options(mqtt_user, mqtt_password);
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
mycallback cb(*client, connOpts, mqtt_server, mqtt_topic, mqtt_client, mongo );
client->set_callback(cb);
try {
std::cout << "Connecting to the MQTT server..." << std::flush;
client->connect(connOpts, nullptr, cb);
}
catch (const mqtt::exception&) {
std::cerr << "\nERROR: Unable to connect to MQTT server: '"
<< mqtt_server << "'" << std::endl;
return false;
}
return true;
}
void close() {
try {
std::cout << "\nDisconnecting from the MQTT server..." << std::flush;
client->disconnect()->wait();
std::cout << "OK" << std::endl;
}
catch (const mqtt::exception& exc) {
std::cerr << exc.what() << std::endl;
}
}
}; // class mqtt_instance
mqtt2mongo_plugin::mqtt2mongo_plugin() :
mongo(std::make_shared<mongo_instance>()),
mqtt(std::make_shared<mqtt_instance>())
{
}
mqtt2mongo_plugin::~mqtt2mongo_plugin()
{
ilog("quit...");
}
void mqtt2mongo_plugin::set_program_options(options_description &cli, options_description &cfg)
{
auto options = cfg.add_options();
options("mongodb-uri", bpo::value<std::string>(), " Example: mongodb://127.0.0.1:27017/datastore");
options("mqtt-server", bpo::value<std::string>(), " Example: tcp://post-cn-n6w1qkoir06.mqtt.aliyuncs.com:1883");
options("mqtt-topic", bpo::value<std::string>(), " Example: eosio_topic");
options("mqtt-client", bpo::value<std::string>(), " Example: GID_eosio@@@mongo");
options("mqtt-user", bpo::value<std::string>(), " Example: Signature|LTAI4GJKsfb8VexSkcQodggS|post-cn-n6w1qkoir06");
options("mqtt-password", bpo::value<std::string>(), " Example: 9cut+eYpoc4CCd9IpOuXToqdocA=");
}
void mqtt2mongo_plugin::plugin_initialize(const variables_map &options)
{
ilog("initializing...");
try
{
if (options.count("mongodb-uri"))
{
mongo->mongod_uri = options.at("mongodb-uri").as<std::string>();
mongocxx::uri uri = mongocxx::uri{mongo->mongod_uri};
mongo->db_name = uri.database();
mongo->mongo_pool.emplace(uri);
}
ilog("connecting to ${u}", ("u", mongo->mongod_uri));
if (options.count("mqtt-server"))
mqtt->mqtt_server = options.at("mqtt-server").as<std::string>();
if( options.count("mqtt-topic"))
mqtt->mqtt_topic = options.at("mqtt-topic").as<std::string>();
if( options.count("mqtt-client"))
mqtt->mqtt_client = options.at("mqtt-client").as<std::string>();
if( options.count("mqtt-user"))
mqtt->mqtt_user = options.at("mqtt-user").as<std::string>();
if( options.count("mqtt-password"))
mqtt->mqtt_password = options.at("mqtt-password").as<std::string>();
mqtt->client.emplace(mqtt->mqtt_server,mqtt->mqtt_client);
}
FC_LOG_AND_RETHROW()
}
void mqtt2mongo_plugin::plugin_startup()
{
ilog("starting...");
mongo->start();
mqtt->subscribe(mongo);
}
void mqtt2mongo_plugin::plugin_shutdown()
{
ilog("shutdown...");
mongo.reset();
mqtt->close();
}
} // namespace my
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.