hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
054f9861e4c257cf7140e1fb788c558c03aa6921
5,929
cc
C++
tonic-suite/asr/src/ivectorbin/ivector-mean.cc
csb1024/djinn_csb
de50d6b6bc9c137e9f4b881de9048eba9e83142d
[ "BSD-3-Clause" ]
59
2015-07-01T21:41:47.000Z
2021-07-28T07:07:42.000Z
tonic-suite/asr/src/ivectorbin/ivector-mean.cc
csb1024/djinn_csb
de50d6b6bc9c137e9f4b881de9048eba9e83142d
[ "BSD-3-Clause" ]
4
2016-01-24T13:25:03.000Z
2021-07-06T09:10:23.000Z
tonic-suite/asr/src/ivectorbin/ivector-mean.cc
csb1024/djinn_csb
de50d6b6bc9c137e9f4b881de9048eba9e83142d
[ "BSD-3-Clause" ]
54
2015-06-13T15:31:20.000Z
2021-07-28T07:07:43.000Z
// ivectorbin/ivector-mean.cc // Copyright 2013-2014 Daniel Povey // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" int main(int argc, char *argv[]) { using namespace kaldi; typedef kaldi::int32 int32; try { const char *usage = "With 3 or 4 arguments, averages iVectors over all the\n" "utterances of each speaker using the spk2utt file.\n" "Input the spk2utt file and a set of iVectors indexed by\n" "utterance; output is iVectors indexed by speaker. If 4\n" "arguments are given, extra argument is a table for the number\n" "of utterances per speaker (can be useful for PLDA). If 2\n" "arguments are given, computes the mean of all input files and\n" "writes out the mean vector.\n" "\n" "Usage: ivector-mean <spk2utt-rspecifier> <ivector-rspecifier> " "<ivector-wspecifier> [<num-utt-wspecifier>]\n" "or: ivector-mean <ivector-rspecifier> <mean-wxfilename>\n" "e.g.: ivector-mean data/spk2utt exp/ivectors.ark exp/spk_ivectors.ark " "exp/spk_num_utts.ark\n" "or: ivector-mean exp/ivectors.ark exp/mean.vec\n" "See also: ivector-subtract-global-mean\n"; ParseOptions po(usage); bool binary_write = false; po.Register("binary", &binary_write, "If true, write output in binary " "(only applicable when writing files, not archives/tables."); po.Read(argc, argv); if (po.NumArgs() < 2 || po.NumArgs() > 4) { po.PrintUsage(); exit(1); } if (po.NumArgs() == 2) { // Compute the mean of the input vectors and write it out. std::string ivector_rspecifier = po.GetArg(1), mean_wxfilename = po.GetArg(2); int32 num_done = 0; SequentialBaseFloatVectorReader ivector_reader(ivector_rspecifier); Vector<double> sum; for (; !ivector_reader.Done(); ivector_reader.Next()) { if (sum.Dim() == 0) sum.Resize(ivector_reader.Value().Dim()); sum.AddVec(1.0, ivector_reader.Value()); num_done++; } if (num_done == 0) { KALDI_ERR << "No iVectors read"; } else { sum.Scale(1.0 / num_done); WriteKaldiObject(sum, mean_wxfilename, binary_write); return 0; } } else { std::string spk2utt_rspecifier = po.GetArg(1), ivector_rspecifier = po.GetArg(2), ivector_wspecifier = po.GetArg(3), num_utts_wspecifier = po.GetOptArg(4); double spk_sumsq = 0.0; Vector<double> spk_sum; int64 num_spk_done = 0, num_spk_err = 0, num_utt_done = 0, num_utt_err = 0; RandomAccessBaseFloatVectorReader ivector_reader(ivector_rspecifier); SequentialTokenVectorReader spk2utt_reader(spk2utt_rspecifier); BaseFloatVectorWriter ivector_writer(ivector_wspecifier); Int32Writer num_utts_writer(num_utts_wspecifier); for (; !spk2utt_reader.Done(); spk2utt_reader.Next()) { std::string spk = spk2utt_reader.Key(); const std::vector<std::string> &uttlist = spk2utt_reader.Value(); if (uttlist.empty()) { KALDI_ERR << "Speaker with no utterances."; } Vector<BaseFloat> spk_mean; int32 utt_count = 0; for (size_t i = 0; i < uttlist.size(); i++) { std::string utt = uttlist[i]; if (!ivector_reader.HasKey(utt)) { KALDI_WARN << "No iVector present in input for utterance " << utt; num_utt_err++; } else { if (utt_count == 0) { spk_mean = ivector_reader.Value(utt); } else { spk_mean.AddVec(1.0, ivector_reader.Value(utt)); } num_utt_done++; utt_count++; } } if (utt_count == 0) { KALDI_WARN << "Not producing output for speaker " << spk << " since no utterances had iVectors"; num_spk_err++; } else { spk_mean.Scale(1.0 / utt_count); ivector_writer.Write(spk, spk_mean); if (num_utts_wspecifier != "") num_utts_writer.Write(spk, utt_count); num_spk_done++; spk_sumsq += VecVec(spk_mean, spk_mean); if (spk_sum.Dim() == 0) spk_sum.Resize(spk_mean.Dim()); spk_sum.AddVec(1.0, spk_mean); } } KALDI_LOG << "Computed mean of " << num_spk_done << " speakers (" << num_spk_err << " with no utterances), consisting of " << num_utt_done << " utterances (" << num_utt_err << " absent from input)."; if (num_spk_done != 0) { spk_sumsq /= num_spk_done; spk_sum.Scale(1.0 / num_spk_done); double mean_length = spk_sum.Norm(2.0), spk_length = sqrt(spk_sumsq), norm_spk_length = spk_length / sqrt(spk_sum.Dim()); KALDI_LOG << "Norm of mean of speakers is " << mean_length << ", root-mean-square speaker-iVector length divided by " << "sqrt(dim) is " << norm_spk_length; } return (num_spk_done != 0 ? 0 : 1); } } catch (const std::exception &e) { std::cerr << e.what(); return -1; } }
38.5
80
0.60398
csb1024
054fc497d48fcb564f03919a9190610f91a6fc28
2,122
hpp
C++
modules/asset/include/glpp/asset/render/scene_renderer.hpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
16
2019-12-10T19:44:17.000Z
2022-01-04T03:16:19.000Z
modules/asset/include/glpp/asset/render/scene_renderer.hpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
null
null
null
modules/asset/include/glpp/asset/render/scene_renderer.hpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
3
2021-06-04T21:56:55.000Z
2022-03-03T06:47:56.000Z
#pragma once #include "scene_view.hpp" #include "mesh_renderer.hpp" namespace glpp::asset::render { template<class ShadingModel> class scene_renderer_t { public: using material_key_t = size_t; using renderer_t = mesh_renderer_t<ShadingModel>; scene_renderer_t(const ShadingModel& model, const scene_t& scene); void render(const scene_view_t& view); void render(const scene_view_t& view, const glpp::core::render::camera_t& camera); renderer_t& renderer(material_key_t index); const renderer_t& renderer(material_key_t index) const; private: std::vector<renderer_t> m_renderers; }; template<class ShadingModel> scene_renderer_t<ShadingModel>::scene_renderer_t(const ShadingModel& model, const scene_t& scene) { m_renderers.reserve(scene.materials.size()); std::transform( scene.materials.begin(), scene.materials.end(), std::back_inserter(m_renderers), [&](const material_t& material) { return mesh_renderer_t<ShadingModel>{ model, material }; } ); } template<class ShadingModel> void scene_renderer_t<ShadingModel>::render(const scene_view_t& view) { for(auto i = 0u; i < m_renderers.size(); ++i) { const auto& meshes = view.meshes_by_material(i); auto& renderer = m_renderers[i]; for(const auto& mesh : meshes) { renderer.update_model_matrix(mesh.model_matrix); renderer.render(mesh); } } } template<class ShadingModel> void scene_renderer_t<ShadingModel>::render(const scene_view_t& view, const glpp::core::render::camera_t& camera) { for(auto i = 0u; i < m_renderers.size(); ++i) { const auto& meshes = view.meshes_by_material(i); auto& renderer = m_renderers[i]; for(const auto& mesh : meshes) { renderer.update_model_matrix(mesh.model_matrix); renderer.render(mesh, camera); } } } template<class ShadingModel> typename scene_renderer_t<ShadingModel>::renderer_t& scene_renderer_t<ShadingModel>::renderer(material_key_t index) { return m_renderers[index]; } template<class ShadingModel> const typename scene_renderer_t<ShadingModel>::renderer_t& scene_renderer_t<ShadingModel>::renderer(material_key_t index) const { return m_renderers[index]; } }
28.675676
129
0.759661
lenamueller
05521ab08edad824e4200edaf15b4947e28577be
16,867
cpp
C++
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGLength.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGLength.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGLength.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
// Copyright 2014 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. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8SVGLength.h" #include "bindings/core/v8/V8SVGElement.h" #include "bindings/v8/ExceptionState.h" #include "bindings/v8/V8DOMConfiguration.h" #include "bindings/v8/V8HiddenValue.h" #include "bindings/v8/V8ObjectConstructor.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace WebCore { static void initializeScriptWrappableForInterface(SVGLengthTearOff* object) { if (ScriptWrappable::wrapperCanBeStoredInObject(object)) ScriptWrappable::fromObject(object)->setTypeInfo(&V8SVGLength::wrapperTypeInfo); else ASSERT_NOT_REACHED(); } } // namespace WebCore void webCoreInitializeScriptWrappableForInterface(WebCore::SVGLengthTearOff* object) { WebCore::initializeScriptWrappableForInterface(object); } namespace WebCore { const WrapperTypeInfo V8SVGLength::wrapperTypeInfo = { gin::kEmbedderBlink, V8SVGLength::domTemplate, V8SVGLength::derefObject, 0, 0, V8SVGLength::visitDOMWrapper, V8SVGLength::installPerContextEnabledMethods, 0, WrapperTypeObjectPrototype, RefCountedObject }; namespace SVGLengthTearOffV8Internal { template <typename T> void V8_USE(T) { } static void unitTypeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGLengthTearOff* impl = V8SVGLength::toNative(holder); v8SetReturnValueUnsigned(info, impl->unitType()); } static void unitTypeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGLengthTearOffV8Internal::unitTypeAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void valueAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGLengthTearOff* impl = V8SVGLength::toNative(holder); ExceptionState exceptionState(ExceptionState::GetterContext, "value", "SVGLength", holder, info.GetIsolate()); float v8Value = impl->value(exceptionState); if (UNLIKELY(exceptionState.throwIfNeeded())) return; v8SetReturnValue(info, v8Value); } static void valueAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGLengthTearOffV8Internal::valueAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void valueAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); ExceptionState exceptionState(ExceptionState::SetterContext, "value", "SVGLength", holder, info.GetIsolate()); SVGLengthTearOff* impl = V8SVGLength::toNative(holder); TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue())); impl->setValue(cppValue, exceptionState); exceptionState.throwIfNeeded(); } static void valueAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); SVGLengthTearOffV8Internal::valueAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void valueInSpecifiedUnitsAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGLengthTearOff* impl = V8SVGLength::toNative(holder); v8SetReturnValue(info, impl->valueInSpecifiedUnits()); } static void valueInSpecifiedUnitsAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGLengthTearOffV8Internal::valueInSpecifiedUnitsAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void valueInSpecifiedUnitsAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); ExceptionState exceptionState(ExceptionState::SetterContext, "valueInSpecifiedUnits", "SVGLength", holder, info.GetIsolate()); SVGLengthTearOff* impl = V8SVGLength::toNative(holder); TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue())); impl->setValueInSpecifiedUnits(cppValue, exceptionState); exceptionState.throwIfNeeded(); } static void valueInSpecifiedUnitsAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); SVGLengthTearOffV8Internal::valueInSpecifiedUnitsAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void valueAsStringAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGLengthTearOff* impl = V8SVGLength::toNative(holder); v8SetReturnValueString(info, impl->valueAsString(), info.GetIsolate()); } static void valueAsStringAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGLengthTearOffV8Internal::valueAsStringAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void valueAsStringAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); ExceptionState exceptionState(ExceptionState::SetterContext, "valueAsString", "SVGLength", holder, info.GetIsolate()); SVGLengthTearOff* impl = V8SVGLength::toNative(holder); TOSTRING_VOID(V8StringResource<WithNullCheck>, cppValue, v8Value); impl->setValueAsString(cppValue, exceptionState); exceptionState.throwIfNeeded(); } static void valueAsStringAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); SVGLengthTearOffV8Internal::valueAsStringAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void newValueSpecifiedUnitsMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "newValueSpecifiedUnits", "SVGLength", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 2)) { throwMinimumArityTypeError(exceptionState, 2, info.Length()); return; } SVGLengthTearOff* impl = V8SVGLength::toNative(info.Holder()); unsigned unitType; float valueInSpecifiedUnits; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(unitType, toUInt16(info[0], exceptionState), exceptionState); TONATIVE_VOID_INTERNAL(valueInSpecifiedUnits, static_cast<float>(info[1]->NumberValue())); } impl->newValueSpecifiedUnits(unitType, valueInSpecifiedUnits, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } } static void newValueSpecifiedUnitsMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); SVGLengthTearOffV8Internal::newValueSpecifiedUnitsMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void convertToSpecifiedUnitsMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "convertToSpecifiedUnits", "SVGLength", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 1)) { throwMinimumArityTypeError(exceptionState, 1, info.Length()); return; } SVGLengthTearOff* impl = V8SVGLength::toNative(info.Holder()); unsigned unitType; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(unitType, toUInt16(info[0], exceptionState), exceptionState); } impl->convertToSpecifiedUnits(unitType, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } } static void convertToSpecifiedUnitsMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); SVGLengthTearOffV8Internal::convertToSpecifiedUnitsMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } } // namespace SVGLengthTearOffV8Internal void V8SVGLength::visitDOMWrapper(void* object, const v8::Persistent<v8::Object>& wrapper, v8::Isolate* isolate) { SVGLengthTearOff* impl = fromInternalPointer(object); v8::Local<v8::Object> creationContext = v8::Local<v8::Object>::New(isolate, wrapper); V8WrapperInstantiationScope scope(creationContext, isolate); SVGElement* contextElement = impl->contextElement(); if (contextElement) { if (!DOMDataStore::containsWrapper<V8SVGElement>(contextElement, isolate)) wrap(contextElement, creationContext, isolate); DOMDataStore::setWrapperReference<V8SVGElement>(wrapper, contextElement, isolate); } setObjectGroup(object, wrapper, isolate); } static const V8DOMConfiguration::AttributeConfiguration V8SVGLengthAttributes[] = { {"unitType", SVGLengthTearOffV8Internal::unitTypeAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"value", SVGLengthTearOffV8Internal::valueAttributeGetterCallback, SVGLengthTearOffV8Internal::valueAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"valueInSpecifiedUnits", SVGLengthTearOffV8Internal::valueInSpecifiedUnitsAttributeGetterCallback, SVGLengthTearOffV8Internal::valueInSpecifiedUnitsAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"valueAsString", SVGLengthTearOffV8Internal::valueAsStringAttributeGetterCallback, SVGLengthTearOffV8Internal::valueAsStringAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, }; static const V8DOMConfiguration::MethodConfiguration V8SVGLengthMethods[] = { {"newValueSpecifiedUnits", SVGLengthTearOffV8Internal::newValueSpecifiedUnitsMethodCallback, 0, 2}, {"convertToSpecifiedUnits", SVGLengthTearOffV8Internal::convertToSpecifiedUnitsMethodCallback, 0, 1}, }; static void configureV8SVGLengthTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "SVGLength", v8::Local<v8::FunctionTemplate>(), V8SVGLength::internalFieldCount, V8SVGLengthAttributes, WTF_ARRAY_LENGTH(V8SVGLengthAttributes), 0, 0, V8SVGLengthMethods, WTF_ARRAY_LENGTH(V8SVGLengthMethods), isolate); v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate(); v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate(); static const V8DOMConfiguration::ConstantConfiguration V8SVGLengthConstants[] = { {"SVG_LENGTHTYPE_UNKNOWN", 0}, {"SVG_LENGTHTYPE_NUMBER", 1}, {"SVG_LENGTHTYPE_PERCENTAGE", 2}, {"SVG_LENGTHTYPE_EMS", 3}, {"SVG_LENGTHTYPE_EXS", 4}, {"SVG_LENGTHTYPE_PX", 5}, {"SVG_LENGTHTYPE_CM", 6}, {"SVG_LENGTHTYPE_MM", 7}, {"SVG_LENGTHTYPE_IN", 8}, {"SVG_LENGTHTYPE_PT", 9}, {"SVG_LENGTHTYPE_PC", 10}, }; V8DOMConfiguration::installConstants(functionTemplate, prototypeTemplate, V8SVGLengthConstants, WTF_ARRAY_LENGTH(V8SVGLengthConstants), isolate); COMPILE_ASSERT(0 == SVGLengthTearOff::SVG_LENGTHTYPE_UNKNOWN, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_UNKNOWNDoesntMatchWithImplementation); COMPILE_ASSERT(1 == SVGLengthTearOff::SVG_LENGTHTYPE_NUMBER, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_NUMBERDoesntMatchWithImplementation); COMPILE_ASSERT(2 == SVGLengthTearOff::SVG_LENGTHTYPE_PERCENTAGE, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_PERCENTAGEDoesntMatchWithImplementation); COMPILE_ASSERT(3 == SVGLengthTearOff::SVG_LENGTHTYPE_EMS, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_EMSDoesntMatchWithImplementation); COMPILE_ASSERT(4 == SVGLengthTearOff::SVG_LENGTHTYPE_EXS, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_EXSDoesntMatchWithImplementation); COMPILE_ASSERT(5 == SVGLengthTearOff::SVG_LENGTHTYPE_PX, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_PXDoesntMatchWithImplementation); COMPILE_ASSERT(6 == SVGLengthTearOff::SVG_LENGTHTYPE_CM, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_CMDoesntMatchWithImplementation); COMPILE_ASSERT(7 == SVGLengthTearOff::SVG_LENGTHTYPE_MM, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_MMDoesntMatchWithImplementation); COMPILE_ASSERT(8 == SVGLengthTearOff::SVG_LENGTHTYPE_IN, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_INDoesntMatchWithImplementation); COMPILE_ASSERT(9 == SVGLengthTearOff::SVG_LENGTHTYPE_PT, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_PTDoesntMatchWithImplementation); COMPILE_ASSERT(10 == SVGLengthTearOff::SVG_LENGTHTYPE_PC, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_PCDoesntMatchWithImplementation); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Handle<v8::FunctionTemplate> V8SVGLength::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8SVGLengthTemplate); } bool V8SVGLength::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Handle<v8::Object> V8SVGLength::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } SVGLengthTearOff* V8SVGLength::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value) { return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0; } v8::Handle<v8::Object> wrap(SVGLengthTearOff* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8SVGLength>(impl, isolate)); return V8SVGLength::createWrapper(impl, creationContext, isolate); } v8::Handle<v8::Object> V8SVGLength::createWrapper(PassRefPtr<SVGLengthTearOff> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8SVGLength>(impl.get(), isolate)); if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) { const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo(); // Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have // the same object de-ref functions, though, so use that as the basis of the check. RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction); } v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; installPerContextEnabledProperties(wrapper, impl.get(), isolate); V8DOMWrapper::associateObjectWithWrapper<V8SVGLength>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Dependent); return wrapper; } void V8SVGLength::derefObject(void* object) { fromInternalPointer(object)->deref(); } template<> v8::Handle<v8::Value> toV8NoInline(SVGLengthTearOff* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { return toV8(impl, creationContext, isolate); } } // namespace WebCore
49.031977
299
0.771744
jingcao80
05522110b84434638f878cd187d1463d33d0e6ff
4,137
cpp
C++
PopcornTorrent/Source/torrent/stack_allocator.cpp
tommy071/PopcornTorrent
88a1a4371d58e9d81839754d2eae079197dee5c5
[ "MIT" ]
4
2015-03-13T18:55:48.000Z
2015-06-27T09:33:44.000Z
src/stack_allocator.cpp
joriscarrier/libtorrent
1d801ec1b28c4e3643186905a5d28c7c1edbf534
[ "BSL-1.0", "BSD-3-Clause" ]
1
2017-09-19T08:52:30.000Z
2017-09-19T08:52:30.000Z
src/stack_allocator.cpp
joriscarrier/libtorrent
1d801ec1b28c4e3643186905a5d28c7c1edbf534
[ "BSL-1.0", "BSD-3-Clause" ]
1
2022-03-01T07:57:14.000Z
2022-03-01T07:57:14.000Z
/* Copyright (c) 2015-2016, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/stack_allocator.hpp" #include <cstdarg> // for va_list, va_copy, va_end namespace libtorrent { namespace aux { allocation_slot stack_allocator::copy_string(string_view str) { int const ret = int(m_storage.size()); m_storage.resize(ret + numeric_cast<int>(str.size()) + 1); std::memcpy(&m_storage[ret], str.data(), str.size()); m_storage[ret + int(str.length())] = '\0'; return allocation_slot(ret); } allocation_slot stack_allocator::copy_string(char const* str) { int const ret = int(m_storage.size()); int const len = int(std::strlen(str)); m_storage.resize(ret + len + 1); std::memcpy(&m_storage[ret], str, numeric_cast<std::size_t>(len)); m_storage[ret + len] = '\0'; return allocation_slot(ret); } allocation_slot stack_allocator::format_string(char const* fmt, va_list v) { int const pos = int(m_storage.size()); int len = 512; for(;;) { m_storage.resize(pos + len + 1); va_list args; va_copy(args, v); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif int const ret = std::vsnprintf(m_storage.data() + pos, static_cast<std::size_t>(len + 1), fmt, args); #ifdef __clang__ #pragma clang diagnostic pop #endif va_end(args); if (ret < 0) { m_storage.resize(pos); return copy_string("(format error)"); } if (ret > len) { // try again len = ret; continue; } break; } // +1 is to include the 0-terminator m_storage.resize(pos + len + 1); return allocation_slot(pos); } allocation_slot stack_allocator::copy_buffer(span<char const> buf) { int const ret = int(m_storage.size()); int const size = int(buf.size()); if (size < 1) return {}; m_storage.resize(ret + size); std::memcpy(&m_storage[ret], buf.data(), numeric_cast<std::size_t>(size)); return allocation_slot(ret); } allocation_slot stack_allocator::allocate(int const bytes) { if (bytes < 1) return {}; int const ret = m_storage.end_index(); m_storage.resize(ret + bytes); return allocation_slot(ret); } char* stack_allocator::ptr(allocation_slot const idx) { if(idx.val() < 0) return nullptr; TORRENT_ASSERT(idx.val() < int(m_storage.size())); return &m_storage[idx.val()]; } char const* stack_allocator::ptr(allocation_slot const idx) const { if(idx.val() < 0) return nullptr; TORRENT_ASSERT(idx.val() < int(m_storage.size())); return &m_storage[idx.val()]; } void stack_allocator::swap(stack_allocator& rhs) { m_storage.swap(rhs.m_storage); } void stack_allocator::reset() { m_storage.clear(); } } }
28.729167
104
0.71767
tommy071
0552835adf7de414f2166c3571a77d85d166ebf7
43,016
hpp
C++
src/lapack_like/spectral/Pseudospectra/IRA.hpp
sg0/Elemental
614f02509690449b553451e36bc78e7e132ea517
[ "BSD-3-Clause" ]
1
2015-12-08T22:54:37.000Z
2015-12-08T22:54:37.000Z
src/lapack_like/spectral/Pseudospectra/IRA.hpp
sg0/Elemental
614f02509690449b553451e36bc78e7e132ea517
[ "BSD-3-Clause" ]
null
null
null
src/lapack_like/spectral/Pseudospectra/IRA.hpp
sg0/Elemental
614f02509690449b553451e36bc78e7e132ea517
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef EL_PSEUDOSPECTRA_IRA_HPP #define EL_PSEUDOSPECTRA_IRA_HPP #include "./Lanczos.hpp" namespace El { namespace pspec { template<typename Real> inline void ComputeNewEstimates ( const vector<Matrix<Complex<Real>>>& HList, const Matrix<Int>& activeConverged, Matrix<Real>& activeEsts, Int n ) { DEBUG_ONLY(CallStackEntry cse("pspec::ComputeNewEstimates")) const Real normCap = NormCap<Real>(); const Int numShifts = activeEsts.Height(); if( numShifts == 0 ) return; Matrix<Complex<Real>> H, HTL; Matrix<Complex<Real>> w(n,1); for( Int j=0; j<numShifts; ++j ) { H = HList[j]; HTL = H( IR(0,n), IR(0,n) ); if( !activeConverged.Get(j,0) ) { if( !HasNan(HTL) ) { lapack::HessenbergEig ( n, HTL.Buffer(), HTL.LDim(), w.Buffer() ); Real estSquared=0; for( Int k=0; k<n; ++k ) if( w.GetRealPart(k,0) > estSquared ) estSquared = w.GetRealPart(k,0); activeEsts.Set( j, 0, Min(Sqrt(estSquared),normCap) ); } else activeEsts.Set( j, 0, normCap ); } } } template<typename Real> inline void ComputeNewEstimates ( const vector<Matrix<Complex<Real>>>& HList, const DistMatrix<Int,MR,STAR>& activeConverged, DistMatrix<Real,MR,STAR>& activeEsts, Int n ) { DEBUG_ONLY(CallStackEntry cse("pspec::ComputeNewEstimates")) ComputeNewEstimates ( HList, activeConverged.LockedMatrix(), activeEsts.Matrix(), n ); } template<typename Real> inline void Restart ( const vector<Matrix<Complex<Real>>>& HList, const Matrix<Int>& activeConverged, vector<Matrix<Complex<Real>>>& VList ) { DEBUG_ONLY(CallStackEntry cse("pspec::Restart")) const Int n = VList[0].Height(); const Int numShifts = VList[0].Width(); if( numShifts == 0 ) return; const Int basisSize = HList[0].Width(); Matrix<Complex<Real>> H, HTL, Q(basisSize,basisSize); Matrix<Complex<Real>> w(basisSize,1), u(n,1); for( Int j=0; j<numShifts; ++j ) { H = HList[j]; HTL = H( IR(0,basisSize), IR(0,basisSize) ); if( !activeConverged.Get(j,0) ) { if( !HasNan(HTL) ) { // TODO: Switch to lapack::HessenbergEig lapack::Eig ( basisSize, HTL.Buffer(), HTL.LDim(), w.Buffer(), Q.Buffer(), Q.LDim() ); Real maxReal=0; Int maxIdx=0; for( Int k=0; k<basisSize; ++k ) { if( w.GetRealPart(k,0) > maxReal ) { maxReal = w.GetRealPart(k,0); maxIdx = k; } } Zeros( u, n, 1 ); for( Int k=0; k<basisSize; ++k ) { const Matrix<Complex<Real>>& V = VList[k]; auto v = V( IR(0,n), IR(j,j+1) ); Axpy( Q.Get(k,maxIdx), v, u ); } Matrix<Complex<Real>>& V = VList[0]; auto v = V( IR(0,n), IR(j,j+1) ); v = u; } } } } template<typename Real> inline void Restart ( const vector<Matrix<Complex<Real>>>& HList, const Matrix<Int>& activeConverged, vector<Matrix<Real>>& VRealList, vector<Matrix<Real>>& VImagList ) { DEBUG_ONLY(CallStackEntry cse("pspec::Restart")) const Int n = VRealList[0].Height(); const Int numShifts = VRealList[0].Width(); if( numShifts == 0 ) return; const Int basisSize = HList[0].Width(); Matrix<Complex<Real>> H, HTL, Q(basisSize,basisSize); Matrix<Complex<Real>> w(basisSize,1), u(n,1), v(n,1); for( Int j=0; j<numShifts; ++j ) { H = HList[j]; HTL = H( IR(0,basisSize), IR(0,basisSize) ); if( !activeConverged.Get(j,0) ) { if( !HasNan(HTL) ) { // TODO: Switch to lapack::HessenbergEig lapack::Eig ( basisSize, HTL.Buffer(), HTL.LDim(), w.Buffer(), Q.Buffer(), Q.LDim() ); Real maxReal=0; Int maxIdx=0; for( Int k=0; k<basisSize; ++k ) { if( w.GetRealPart(k,0) > maxReal ) { maxReal = w.GetRealPart(k,0); maxIdx = k; } } Zeros( u, n, 1 ); for( Int k=0; k<basisSize; ++k ) { const Matrix<Real>& VReal = VRealList[k]; const Matrix<Real>& VImag = VImagList[k]; auto vReal = VReal( IR(0,n), IR(j,j+1) ); auto vImag = VImag( IR(0,n), IR(j,j+1) ); for( Int i=0; i<n; ++i ) v.Set( i, 0, Complex<Real>(vReal.Get(i,0), vImag.Get(i,0)) ); Axpy( Q.Get(k,maxIdx), v, u ); } Matrix<Real>& VReal = VRealList[0]; Matrix<Real>& VImag = VImagList[0]; auto vReal = VReal( IR(0,n), IR(j,j+1) ); auto vImag = VImag( IR(0,n), IR(j,j+1) ); for( Int i=0; i<n; ++i ) { vReal.Set( i, 0, u.GetRealPart(i,0) ); vImag.Set( i, 0, u.GetImagPart(i,0) ); } } } } } template<typename Real> inline void Restart ( const vector<Matrix<Complex<Real>>>& HList, const DistMatrix<Int,MR,STAR>& activeConverged, vector<DistMatrix<Complex<Real>>>& VList ) { DEBUG_ONLY(CallStackEntry cse("pspec::Restart")) const Int basisSize = HList[0].Width(); vector<Matrix<Complex<Real>>> VLocList(basisSize+1); for( Int j=0; j<basisSize+1; ++j ) VLocList[j] = View( VList[j].Matrix() ); Restart( HList, activeConverged.LockedMatrix(), VLocList ); } template<typename Real> inline void Restart ( const vector<Matrix<Complex<Real>>>& HList, const DistMatrix<Int,MR,STAR>& activeConverged, vector<DistMatrix<Real>>& VRealList, vector<DistMatrix<Real>>& VImagList ) { DEBUG_ONLY(CallStackEntry cse("pspec::Restart")) const Int basisSize = HList[0].Width(); vector<Matrix<Real>> VRealLocList(basisSize+1), VImagLocList(basisSize+1); for( Int j=0; j<basisSize+1; ++j ) { VRealLocList[j] = View( VRealList[j].Matrix() ); VImagLocList[j] = View( VImagList[j].Matrix() ); } Restart ( HList, activeConverged.LockedMatrix(), VRealLocList, VImagLocList ); } template<typename Real> inline Matrix<Int> IRA ( const Matrix<Complex<Real>>& U, const Matrix<Complex<Real>>& shifts, Matrix<Real>& invNorms, PseudospecCtrl<Real> psCtrl=PseudospecCtrl<Real>() ) { DEBUG_ONLY(CallStackEntry cse("pspec::IRA")) using namespace pspec; typedef Complex<Real> C; const Int n = U.Height(); const Int numShifts = shifts.Height(); const Int maxIts = psCtrl.maxIts; const Int basisSize = psCtrl.basisSize; const bool deflate = psCtrl.deflate; const bool progress = psCtrl.progress; // Keep track of the number of iterations per shift Matrix<Int> itCounts; Ones( itCounts, numShifts, 1 ); // Keep track of the pivoting history if deflation is requested Matrix<Int> preimage; Matrix<C> pivShifts( shifts ); if( deflate ) { preimage.Resize( numShifts, 1 ); for( Int j=0; j<numShifts; ++j ) preimage.Set( j, 0, j ); } // MultiShiftTrm requires write access for now... Matrix<C> UCopy( U ); // The Hessenberg variant currently requires explicit access to the adjoint Matrix<C> UAdj; if( !psCtrl.schur ) Adjoint( U, UAdj ); // Simultaneously run IRA for different shifts vector<Matrix<C>> VList(basisSize+1), activeVList(basisSize+1); for( Int j=0; j<basisSize+1; ++j ) Zeros( VList[j], n, numShifts ); Gaussian( VList[0], n, numShifts ); vector<Matrix<Complex<Real>>> HList(numShifts); Matrix<Real> realComponents; Matrix<Complex<Real>> components; Matrix<Int> activeConverged; Zeros( activeConverged, numShifts, 1 ); psCtrl.snapCtrl.ResetCounts(); Timer timer, subtimer; Int numIts=0, numDone=0; Matrix<Real> estimates(numShifts,1); Zeros( estimates, numShifts, 1 ); Matrix<Real> lastActiveEsts; Matrix<Int> activePreimage; while( true ) { const Int numActive = ( deflate ? numShifts-numDone : numShifts ); auto activeShifts = pivShifts( IR(0,numActive), IR(0,1) ); auto activeEsts = estimates( IR(0,numActive), IR(0,1) ); auto activeItCounts = itCounts( IR(0,numActive), IR(0,1) ); for( Int j=0; j<basisSize+1; ++j ) View( activeVList[j], VList[j], IR(0,n), IR(0,numActive) ); if( deflate ) { View( activePreimage, preimage, IR(0,numActive), IR(0,1) ); Zeros( activeConverged, numActive, 1 ); } HList.resize( numActive ); for( Int j=0; j<numActive; ++j ) Zeros( HList[j], basisSize+1, basisSize ); if( progress ) timer.Start(); ColumnNorms( activeVList[0], realComponents ); InvBetaScale( realComponents, activeVList[0] ); for( Int j=0; j<basisSize; ++j ) { lastActiveEsts = activeEsts; activeVList[j+1] = activeVList[j]; if( psCtrl.schur ) { if( progress ) subtimer.Start(); MultiShiftTrsm ( LEFT, UPPER, NORMAL, C(1), UCopy, activeShifts, activeVList[j+1] ); MultiShiftTrsm ( LEFT, UPPER, ADJOINT, C(1), UCopy, activeShifts, activeVList[j+1] ); if( progress ) { const double msTime = subtimer.Stop(); const Int numActiveShifts = activeShifts.Height(); const double gflops = (8.*n*n*numActiveShifts)/(msTime*1e9); cout << " MultiShiftTrsm's: " << msTime << " seconds, " << gflops << " GFlops" << endl; } } else { if( progress ) subtimer.Start(); MultiShiftHessSolve ( UPPER, NORMAL, C(1), U, activeShifts, activeVList[j+1] ); Matrix<C> activeShiftsConj; Conjugate( activeShifts, activeShiftsConj ); MultiShiftHessSolve ( LOWER, NORMAL, C(1), UAdj, activeShiftsConj, activeVList[j+1] ); if( progress ) { const double msTime = subtimer.Stop(); const Int numActiveShifts = activeShifts.Height(); const double gflops = (32.*n*n*numActiveShifts)/(msTime*1.e9); cout << " MultiShiftHessSolve's: " << msTime << " seconds, " << gflops << " GFlops" << endl; } } // Orthogonalize with respect to the old iterate if( j > 0 ) { ExtractList( HList, components, j, j-1 ); // TODO: Conjugate components? PlaceList( HList, components, j-1, j ); ColumnSubtractions ( components, activeVList[j-1], activeVList[j+1] ); } // Orthogonalize with respect to the last iterate InnerProducts( activeVList[j], activeVList[j+1], components ); PlaceList( HList, components, j, j ); ColumnSubtractions ( components, activeVList[j], activeVList[j+1] ); // Explicitly (re)orthogonalize against all previous vectors for( Int i=0; i<j-1; ++i ) { InnerProducts ( activeVList[i], activeVList[j+1], components ); PlaceList( HList, components, i, j ); ColumnSubtractions ( components, activeVList[i], activeVList[j+1] ); } if( j > 0 ) { InnerProducts ( activeVList[j-1], activeVList[j+1], components ); UpdateList( HList, components, j-1, j ); ColumnSubtractions ( components, activeVList[j-1], activeVList[j+1] ); } // Compute the norm of what is left ColumnNorms( activeVList[j+1], realComponents ); PlaceList( HList, realComponents, j+1, j ); // TODO: Handle lucky breakdowns InvBetaScale( realComponents, activeVList[j+1] ); ComputeNewEstimates( HList, activeConverged, activeEsts, j+1 ); // We will have the same estimate two iterations in a row when // restarting if( j != 0 ) activeConverged = FindConverged ( lastActiveEsts, activeEsts, activeItCounts, psCtrl.tol ); psCtrl.snapCtrl.Iterate(); } if( progress ) subtimer.Start(); Restart( HList, activeConverged, activeVList ); if( progress ) cout << "IRA restart: " << subtimer.Stop() << " seconds" << endl; const Int numActiveDone = ZeroNorm( activeConverged ); if( deflate ) numDone += numActiveDone; else numDone = numActiveDone; numIts += basisSize; if( progress ) { const double iterTime = timer.Stop(); cout << "iteration " << numIts << ": " << iterTime << " seconds, " << numDone << " of " << numShifts << " converged" << endl; } if( numIts >= maxIts ) break; if( numDone == numShifts ) break; else if( deflate && numActiveDone != 0 ) { Deflate ( activeShifts, activePreimage, activeVList[0], activeEsts, activeConverged, activeItCounts, progress ); lastActiveEsts = activeEsts; } // Save snapshots of the estimates at the requested rate Snapshot ( preimage, estimates, itCounts, numIts, deflate, psCtrl.snapCtrl ); } invNorms = estimates; if( deflate ) RestoreOrdering( preimage, invNorms, itCounts ); FinalSnapshot( invNorms, itCounts, psCtrl.snapCtrl ); return itCounts; } template<typename Real> inline Matrix<Int> IRA ( const Matrix<Real>& U, const Matrix<Complex<Real>>& shifts, Matrix<Real>& invNorms, PseudospecCtrl<Real> psCtrl=PseudospecCtrl<Real>() ) { DEBUG_ONLY(CallStackEntry cse("pspec::IRA")) using namespace pspec; typedef Complex<Real> C; const Int n = U.Height(); const Int numShifts = shifts.Height(); const Int maxIts = psCtrl.maxIts; const Int basisSize = psCtrl.basisSize; const bool deflate = psCtrl.deflate; const bool progress = psCtrl.progress; // Keep track of the number of iterations per shift Matrix<Int> itCounts; Ones( itCounts, numShifts, 1 ); // Keep track of the pivoting history if deflation is requested Matrix<Int> preimage; Matrix<C> pivShifts( shifts ); if( deflate ) { preimage.Resize( numShifts, 1 ); for( Int j=0; j<numShifts; ++j ) preimage.Set( j, 0, j ); } // Simultaneously run IRA for different shifts vector<Matrix<Real>> VRealList(basisSize+1), VImagList(basisSize+1), activeVRealList(basisSize+1), activeVImagList(basisSize+1); for( Int j=0; j<basisSize+1; ++j ) { Zeros( VRealList[j], n, numShifts ); Zeros( VImagList[j], n, numShifts ); } // The variance will be off from that of the usual complex case Gaussian( VRealList[0], n, numShifts ); Gaussian( VImagList[0], n, numShifts ); vector<Matrix<Complex<Real>>> HList(numShifts); Matrix<Real> realComponents; Matrix<Complex<Real>> components; Matrix<Int> activeConverged; Zeros( activeConverged, numShifts, 1 ); psCtrl.snapCtrl.ResetCounts(); Timer timer, subtimer; Int numIts=0, numDone=0; Matrix<Real> estimates(numShifts,1); Zeros( estimates, numShifts, 1 ); Matrix<Real> lastActiveEsts; Matrix<Int> activePreimage; while( true ) { const Int numActive = ( deflate ? numShifts-numDone : numShifts ); auto activeShifts = pivShifts( IR(0,numActive), IR(0,1) ); auto activeEsts = estimates( IR(0,numActive), IR(0,1) ); auto activeItCounts = itCounts( IR(0,numActive), IR(0,1) ); for( Int j=0; j<basisSize+1; ++j ) { activeVRealList[j] = VRealList[j]( IR(0,n), IR(0,numActive) ); activeVImagList[j] = VImagList[j]( IR(0,n), IR(0,numActive) ); } if( deflate ) { activePreimage = preimage( IR(0,numActive), IR(0,1) ); Zeros( activeConverged, numActive, 1 ); } HList.resize( numActive ); for( Int j=0; j<numActive; ++j ) Zeros( HList[j], basisSize+1, basisSize ); if( progress ) timer.Start(); ColumnNorms( activeVRealList[0], activeVImagList[0], realComponents ); InvBetaScale( realComponents, activeVRealList[0] ); InvBetaScale( realComponents, activeVImagList[0] ); for( Int j=0; j<basisSize; ++j ) { lastActiveEsts = activeEsts; activeVRealList[j+1] = activeVRealList[j]; activeVImagList[j+1] = activeVImagList[j]; if( progress ) subtimer.Start(); MultiShiftQuasiTrsm ( LEFT, UPPER, NORMAL, C(1), U, activeShifts, activeVRealList[j+1], activeVImagList[j+1] ); MultiShiftQuasiTrsm ( LEFT, UPPER, ADJOINT, C(1), U, activeShifts, activeVRealList[j+1], activeVImagList[j+1] ); if( progress ) { const double msTime = subtimer.Stop(); const Int numActiveShifts = activeShifts.Height(); const double gflops = (4.*n*n*numActiveShifts)/(msTime*1.e9); cout << " MultiShiftQuasiTrsm's: " << msTime << " seconds, " << gflops << " GFlops" << endl; } // Orthogonalize with respect to the old iterate if( j > 0 ) { ExtractList( HList, components, j, j-1 ); // TODO: Conjugate components? PlaceList( HList, components, j-1, j ); ColumnSubtractions ( components, activeVRealList[j-1], activeVImagList[j-1], activeVRealList[j+1], activeVImagList[j+1] ); } // Orthogonalize with respect to the last iterate InnerProducts ( activeVRealList[j ], activeVImagList[j ], activeVRealList[j+1], activeVImagList[j+1], components ); PlaceList( HList, components, j, j ); ColumnSubtractions ( components, activeVRealList[j ], activeVImagList[j ], activeVRealList[j+1], activeVImagList[j+1] ); // Explicitly (re)orthogonalize against all previous vectors for( Int i=0; i<j-1; ++i ) { InnerProducts ( activeVRealList[i ], activeVImagList[i ], activeVRealList[j+1], activeVImagList[j+1], components ); PlaceList( HList, components, i, j ); ColumnSubtractions ( components, activeVRealList[i ], activeVImagList[i ], activeVRealList[j+1], activeVImagList[j+1] ); } if( j > 0 ) { InnerProducts ( activeVRealList[j-1], activeVImagList[j-1], activeVRealList[j+1], activeVImagList[j+1], components ); UpdateList( HList, components, j-1, j ); ColumnSubtractions ( components, activeVRealList[j-1], activeVImagList[j-1], activeVRealList[j+1], activeVImagList[j+1] ); } // Compute the norm of what is left ColumnNorms ( activeVRealList[j+1], activeVImagList[j+1], realComponents ); PlaceList( HList, realComponents, j+1, j ); // TODO: Handle lucky breakdowns InvBetaScale( realComponents, activeVRealList[j+1] ); InvBetaScale( realComponents, activeVImagList[j+1] ); ComputeNewEstimates( HList, activeConverged, activeEsts, j+1 ); // We will have the same estimate two iterations in a row when // restarting if( j != 0 ) activeConverged = FindConverged ( lastActiveEsts, activeEsts, activeItCounts, psCtrl.tol ); psCtrl.snapCtrl.Iterate(); } if( progress ) subtimer.Start(); Restart( HList, activeConverged, activeVRealList, activeVImagList ); if( progress ) cout << "IRA restart: " << subtimer.Stop() << " seconds" << endl; const Int numActiveDone = ZeroNorm( activeConverged ); if( deflate ) numDone += numActiveDone; else numDone = numActiveDone; numIts += basisSize; if( progress ) { const double iterTime = timer.Stop(); cout << "iteration " << numIts << ": " << iterTime << " seconds, " << numDone << " of " << numShifts << " converged" << endl; } if( numIts >= maxIts ) break; if( numDone == numShifts ) break; else if( deflate && numActiveDone != 0 ) { Deflate ( activeShifts, activePreimage, activeVRealList[0], activeVImagList[0], activeEsts, activeConverged, activeItCounts, progress ); lastActiveEsts = activeEsts; } // Save snapshots of the estimates at the requested rate Snapshot ( preimage, estimates, itCounts, numIts, deflate, psCtrl.snapCtrl ); } invNorms = estimates; if( deflate ) RestoreOrdering( preimage, invNorms, itCounts ); FinalSnapshot( invNorms, itCounts, psCtrl.snapCtrl ); return itCounts; } template<typename Real> inline DistMatrix<Int,VR,STAR> IRA ( const AbstractDistMatrix<Complex<Real>>& UPre, const AbstractDistMatrix<Complex<Real>>& shiftsPre, AbstractDistMatrix<Real>& invNormsPre, PseudospecCtrl<Real> psCtrl=PseudospecCtrl<Real>() ) { DEBUG_ONLY(CallStackEntry cse("pspec::IRA")) using namespace pspec; typedef Complex<Real> C; auto UPtr = ReadProxy<C,MC,MR>( &UPre ); auto& U = *UPtr; auto shiftsPtr = ReadProxy<C,VR,STAR>( &shiftsPre ); auto& shifts = *shiftsPtr; auto invNormsPtr = WriteProxy<Real,VR,STAR>( &invNormsPre ); auto& invNorms = *invNormsPtr; const Int n = U.Height(); const Int numShifts = shifts.Height(); const Grid& g = U.Grid(); const Int maxIts = psCtrl.maxIts; const Int basisSize = psCtrl.basisSize; const bool deflate = psCtrl.deflate; const bool progress = psCtrl.progress; // Keep track of the number of iterations per shift DistMatrix<Int,VR,STAR> itCounts(g); Ones( itCounts, numShifts, 1 ); // Keep track of the pivoting history if deflation is requested DistMatrix<Int,VR,STAR> preimage(g); DistMatrix<C, VR,STAR> pivShifts( shifts ); if( deflate ) { preimage.AlignWith( shifts ); preimage.Resize( numShifts, 1 ); const Int numLocShifts = preimage.LocalHeight(); for( Int iLoc=0; iLoc<numLocShifts; ++iLoc ) { const Int i = preimage.GlobalRow(iLoc); preimage.SetLocal( iLoc, 0, i ); } } // The Hessenberg case currently requires explicit access to the adjoint DistMatrix<C,VC,STAR> U_VC_STAR(g), UAdj_VC_STAR(g); if( !psCtrl.schur ) { U_VC_STAR = U; Adjoint( U, UAdj_VC_STAR ); } // Simultaneously run IRA for different shifts vector<DistMatrix<C>> VList(basisSize+1), activeVList(basisSize+1); for( Int j=0; j<basisSize+1; ++j ) { VList[j].SetGrid( g ); Zeros( VList[j], n, numShifts ); } Gaussian( VList[0], n, numShifts ); const Int numMRShifts = VList[0].LocalWidth(); vector<Matrix<Complex<Real>>> HList(numMRShifts); Matrix<Real> realComponents; Matrix<Complex<Real>> components; DistMatrix<Int,MR,STAR> activeConverged(g); Zeros( activeConverged, numShifts, 1 ); psCtrl.snapCtrl.ResetCounts(); Timer timer, subtimer; Int numIts=0, numDone=0; DistMatrix<Real,MR,STAR> estimates(g), lastActiveEsts(g); estimates.AlignWith( shifts ); Zeros( estimates, numShifts, 1 ); DistMatrix<Int,VR,STAR> activePreimage(g); while( true ) { const Int numActive = ( deflate ? numShifts-numDone : numShifts ); auto activeShifts = pivShifts( IR(0,numActive), IR(0,1) ); auto activeEsts = estimates( IR(0,numActive), IR(0,1) ); auto activeItCounts = itCounts( IR(0,numActive), IR(0,1) ); for( Int j=0; j<basisSize+1; ++j ) View( activeVList[j], VList[j], IR(0,n), IR(0,numActive) ); if( deflate ) { View( activePreimage, preimage, IR(0,numActive), IR(0,1) ); Zeros( activeConverged, numActive, 1 ); } HList.resize( activeEsts.LocalHeight() ); for( Int jLoc=0; jLoc<HList.size(); ++jLoc ) Zeros( HList[jLoc], basisSize+1, basisSize ); if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) timer.Start(); } ColumnNorms( activeVList[0], realComponents ); InvBetaScale( realComponents, activeVList[0] ); for( Int j=0; j<basisSize; ++j ) { lastActiveEsts = activeEsts; activeVList[j+1] = activeVList[j]; if( psCtrl.schur ) { if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) subtimer.Start(); } MultiShiftTrsm ( LEFT, UPPER, NORMAL, C(1), U, activeShifts, activeVList[j+1] ); MultiShiftTrsm ( LEFT, UPPER, ADJOINT, C(1), U, activeShifts, activeVList[j+1] ); if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) { const double msTime = subtimer.Stop(); const Int numActiveShifts = activeShifts.Height(); const double gflops = (8.*n*n*numActiveShifts)/(msTime*1.e9); cout << " MultiShiftTrsm's: " << msTime << " seconds, " << gflops << " GFlops" << endl; } } } else { if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) subtimer.Start(); } // NOTE: This redistribution sequence might not be necessary DistMatrix<C,STAR,VR> activeV_STAR_VR( activeVList[j+1] ); MultiShiftHessSolve ( UPPER, NORMAL, C(1), U_VC_STAR, activeShifts, activeV_STAR_VR ); DistMatrix<C,VR,STAR> activeShiftsConj(g); Conjugate( activeShifts, activeShiftsConj ); MultiShiftHessSolve ( LOWER, NORMAL, C(1), UAdj_VC_STAR, activeShiftsConj, activeV_STAR_VR ); activeVList[j+1] = activeV_STAR_VR; if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) { const double msTime = subtimer.Stop(); const Int numActiveShifts = activeShifts.Height(); const double gflops = (32.*n*n*numActiveShifts)/(msTime*1.e9); cout << " MultiShiftHessSolve's: " << msTime << " seconds, " << gflops << " GFlops" << endl; } } } // Orthogonalize with respect to the old iterate if( j > 0 ) { ExtractList( HList, components, j, j-1 ); // TODO: Conjugate components? PlaceList( HList, components, j-1, j ); ColumnSubtractions ( components, activeVList[j-1], activeVList[j+1] ); } // Orthogonalize with respect to the last iterate InnerProducts( activeVList[j], activeVList[j+1], components ); PlaceList( HList, components, j, j ); ColumnSubtractions ( components, activeVList[j], activeVList[j+1] ); // Explicitly (re)orthogonalize against all previous vectors for( Int i=0; i<j-1; ++i ) { InnerProducts ( activeVList[i], activeVList[j+1], components ); PlaceList( HList, components, i, j ); ColumnSubtractions ( components, activeVList[i], activeVList[j+1] ); } if( j > 0 ) { InnerProducts ( activeVList[j-1], activeVList[j+1], components ); UpdateList( HList, components, j-1, j ); ColumnSubtractions ( components, activeVList[j-1], activeVList[j+1] ); } // Compute the norm of what is left ColumnNorms( activeVList[j+1], realComponents ); PlaceList( HList, realComponents, j+1, j ); // TODO: Handle lucky breakdowns InvBetaScale( realComponents, activeVList[j+1] ); ComputeNewEstimates( HList, activeConverged, activeEsts, j+1 ); // We will have the same estimate two iterations in a row when // restarting if( j != 0 ) activeConverged = FindConverged ( lastActiveEsts, activeEsts, activeItCounts, psCtrl.tol ); psCtrl.snapCtrl.Iterate(); } if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) subtimer.Start(); } Restart( HList, activeConverged, activeVList ); if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) cout << "IRA computations: " << subtimer.Stop() << " seconds" << endl; } const Int numActiveDone = ZeroNorm( activeConverged ); if( deflate ) numDone += numActiveDone; else numDone = numActiveDone; numIts += basisSize; if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) { const double iterTime = timer.Stop(); cout << "iteration " << numIts << ": " << iterTime << " seconds, " << numDone << " of " << numShifts << " converged" << endl; } } if( numIts >= maxIts ) break; if( numDone == numShifts ) break; else if( deflate && numActiveDone != 0 ) { Deflate ( activeShifts, activePreimage, activeVList[0], activeEsts, activeConverged, activeItCounts, progress ); lastActiveEsts = activeEsts; } // Save snapshots of the estimates at the requested rate Snapshot ( preimage, estimates, itCounts, numIts, deflate, psCtrl.snapCtrl ); } invNorms = estimates; if( deflate ) RestoreOrdering( preimage, invNorms, itCounts ); FinalSnapshot( invNorms, itCounts, psCtrl.snapCtrl ); return itCounts; } template<typename Real> inline DistMatrix<Int,VR,STAR> IRA ( const AbstractDistMatrix<Real>& UPre, const AbstractDistMatrix<Complex<Real>>& shiftsPre, AbstractDistMatrix<Real>& invNormsPre, PseudospecCtrl<Real> psCtrl=PseudospecCtrl<Real>() ) { DEBUG_ONLY(CallStackEntry cse("pspec::IRA")) using namespace pspec; typedef Complex<Real> C; auto UPtr = ReadProxy<Real,MC,MR>( &UPre ); auto& U = *UPtr; auto shiftsPtr = ReadProxy<C,VR,STAR>( &shiftsPre ); auto& shifts = *shiftsPtr; auto invNormsPtr = WriteProxy<Real,VR,STAR>( &invNormsPre ); auto& invNorms = *invNormsPtr; const Int n = U.Height(); const Int numShifts = shifts.Height(); const Grid& g = U.Grid(); const Int maxIts = psCtrl.maxIts; const Int basisSize = psCtrl.basisSize; const bool deflate = psCtrl.deflate; const bool progress = psCtrl.progress; // Keep track of the number of iterations per shift DistMatrix<Int,VR,STAR> itCounts(g); Ones( itCounts, numShifts, 1 ); // Keep track of the pivoting history if deflation is requested DistMatrix<Int,VR,STAR> preimage(g); DistMatrix<C, VR,STAR> pivShifts( shifts ); if( deflate ) { preimage.AlignWith( shifts ); preimage.Resize( numShifts, 1 ); const Int numLocShifts = preimage.LocalHeight(); for( Int iLoc=0; iLoc<numLocShifts; ++iLoc ) { const Int i = preimage.GlobalRow(iLoc); preimage.SetLocal( iLoc, 0, i ); } } // Simultaneously run IRA for different shifts vector<DistMatrix<Real>> VRealList(basisSize+1), VImagList(basisSize+1), activeVRealList(basisSize+1), activeVImagList(basisSize+1); for( Int j=0; j<basisSize+1; ++j ) { VRealList[j].SetGrid( g ); VImagList[j].SetGrid( g ); Zeros( VRealList[j], n, numShifts ); Zeros( VImagList[j], n, numShifts ); } // The variance will be off from that of the usual complex case Gaussian( VRealList[0], n, numShifts ); Gaussian( VImagList[0], n, numShifts ); const Int numMRShifts = VRealList[0].LocalWidth(); vector<Matrix<Complex<Real>>> HList(numMRShifts); Matrix<Real> realComponents; Matrix<Complex<Real>> components; DistMatrix<Int,MR,STAR> activeConverged(g); Zeros( activeConverged, numShifts, 1 ); psCtrl.snapCtrl.ResetCounts(); Timer timer, subtimer; Int numIts=0, numDone=0; DistMatrix<Real,MR,STAR> estimates(g), lastActiveEsts(g); estimates.AlignWith( shifts ); Zeros( estimates, numShifts, 1 ); DistMatrix<Int,VR,STAR> activePreimage(g); while( true ) { const Int numActive = ( deflate ? numShifts-numDone : numShifts ); auto activeShifts = pivShifts( IR(0,numActive), IR(0,1) ); auto activeEsts = estimates( IR(0,numActive), IR(0,1) ); auto activeItCounts = itCounts( IR(0,numActive), IR(0,1) ); for( Int j=0; j<basisSize+1; ++j ) { View( activeVRealList[j], VRealList[j], IR(0,n), IR(0,numActive) ); View( activeVImagList[j], VImagList[j], IR(0,n), IR(0,numActive) ); } if( deflate ) { View( activePreimage, preimage, IR(0,numActive), IR(0,1) ); Zeros( activeConverged, numActive, 1 ); } HList.resize( activeEsts.LocalHeight() ); for( Int jLoc=0; jLoc<HList.size(); ++jLoc ) Zeros( HList[jLoc], basisSize+1, basisSize ); if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) timer.Start(); } ColumnNorms( activeVRealList[0], activeVImagList[0], realComponents ); InvBetaScale( realComponents, activeVRealList[0] ); InvBetaScale( realComponents, activeVImagList[0] ); for( Int j=0; j<basisSize; ++j ) { lastActiveEsts = activeEsts; activeVRealList[j+1] = activeVRealList[j]; activeVImagList[j+1] = activeVImagList[j]; if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) subtimer.Start(); } MultiShiftQuasiTrsm ( LEFT, UPPER, NORMAL, C(1), U, activeShifts, activeVRealList[j+1], activeVImagList[j+1] ); MultiShiftQuasiTrsm ( LEFT, UPPER, ADJOINT, C(1), U, activeShifts, activeVRealList[j+1], activeVImagList[j+1] ); if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) { const double msTime = subtimer.Stop(); const Int numActiveShifts = activeShifts.Height(); const double gflops = (4.*n*n*numActiveShifts)/(msTime*1.e9); cout << " MultiShiftQuasiTrsm's: " << msTime << " seconds, " << gflops << " GFlops" << endl; } } // Orthogonalize with respect to the old iterate if( j > 0 ) { ExtractList( HList, components, j, j-1 ); // TODO: Conjugate components? PlaceList( HList, components, j-1, j ); ColumnSubtractions ( components, activeVRealList[j-1], activeVImagList[j-1], activeVRealList[j+1], activeVImagList[j+1] ); } // Orthogonalize with respect to the last iterate InnerProducts ( activeVRealList[j+0], activeVImagList[j+0], activeVRealList[j+1], activeVImagList[j+1], components ); PlaceList( HList, components, j, j ); ColumnSubtractions ( components, activeVRealList[j+0], activeVImagList[j+0], activeVRealList[j+1], activeVImagList[j+1] ); // Explicitly (re)orthogonalize against all previous vectors for( Int i=0; i<j-1; ++i ) { InnerProducts ( activeVRealList[i ], activeVImagList[i ], activeVRealList[j+1], activeVImagList[j+1], components ); PlaceList( HList, components, i, j ); ColumnSubtractions ( components, activeVRealList[i ], activeVImagList[i ], activeVRealList[j+1], activeVImagList[j+1] ); } if( j > 0 ) { InnerProducts ( activeVRealList[j-1], activeVImagList[j-1], activeVRealList[j+1], activeVImagList[j+1], components ); UpdateList( HList, components, j-1, j ); ColumnSubtractions ( components, activeVRealList[j-1], activeVImagList[j-1], activeVRealList[j+1], activeVImagList[j+1] ); } // Compute the norm of what is left ColumnNorms ( activeVRealList[j+1], activeVImagList[j+1], realComponents ); PlaceList( HList, realComponents, j+1, j ); // TODO: Handle lucky breakdowns InvBetaScale( realComponents, activeVRealList[j+1] ); InvBetaScale( realComponents, activeVImagList[j+1] ); ComputeNewEstimates( HList, activeConverged, activeEsts, j+1 ); // We will have the same estimate two iterations in a row when // restarting if( j != 0 ) activeConverged = FindConverged ( lastActiveEsts, activeEsts, activeItCounts, psCtrl.tol ); psCtrl.snapCtrl.Iterate(); } if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) subtimer.Start(); } Restart( HList, activeConverged, activeVRealList, activeVImagList ); if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) cout << "IRA computations: " << subtimer.Stop() << " seconds" << endl; } const Int numActiveDone = ZeroNorm( activeConverged ); if( deflate ) numDone += numActiveDone; else numDone = numActiveDone; numIts += basisSize; if( progress ) { mpi::Barrier( g.Comm() ); if( g.Rank() == 0 ) { const double iterTime = timer.Stop(); cout << "iteration " << numIts << ": " << iterTime << " seconds, " << numDone << " of " << numShifts << " converged" << endl; } } if( numIts >= maxIts ) break; if( numDone == numShifts ) break; else if( deflate && numActiveDone != 0 ) { Deflate ( activeShifts, activePreimage, activeVRealList[0], activeVImagList[0], activeEsts, activeConverged, activeItCounts, progress ); lastActiveEsts = activeEsts; } // Save snapshots of the estimates at the requested rate Snapshot ( preimage, estimates, itCounts, numIts, deflate, psCtrl.snapCtrl ); } invNorms = estimates; if( deflate ) RestoreOrdering( preimage, invNorms, itCounts ); FinalSnapshot( invNorms, itCounts, psCtrl.snapCtrl ); return itCounts; } } // namespace pspec } // namespace El #endif // ifndef EL_PSEUDOSPECTRA_IRA_HPP
35.579818
80
0.526479
sg0
0552cb692d7c38ce92bed21ac12f87f3dc644950
545
cpp
C++
src/core/objects/storage.cpp
PeculiarVentures/pvpkcs11
474cf3b2a958c83ccfebf3165e45e7f46d649c81
[ "MIT" ]
30
2017-05-25T08:54:25.000Z
2021-12-21T13:42:35.000Z
src/core/objects/storage.cpp
PeculiarVentures/pvpkcs11
474cf3b2a958c83ccfebf3165e45e7f46d649c81
[ "MIT" ]
37
2017-05-24T21:47:36.000Z
2021-06-02T09:23:54.000Z
src/core/objects/storage.cpp
PeculiarVentures/pvpkcs11
474cf3b2a958c83ccfebf3165e45e7f46d649c81
[ "MIT" ]
7
2017-07-22T09:50:13.000Z
2019-08-18T23:42:52.000Z
#include "storage.h" using namespace core; Storage::Storage() : Object() { LOGGER_FUNCTION_BEGIN; LOGGER_DEBUG("New %s", __FUNCTION__); try { // set props defaults Add(AttributeBool::New(CKA_TOKEN, false, PVF_13)); Add(AttributeBool::New(CKA_PRIVATE, false, PVF_13)); Add(AttributeBool::New(CKA_MODIFIABLE, true, PVF_13)); Add(AttributeBytes::New(CKA_LABEL, NULL, 0, PVF_8)); // PVF_8 - no in spec Add(AttributeBool::New(CKA_COPYABLE, true, PVF_12)); } CATCH_EXCEPTION }
27.25
82
0.645872
PeculiarVentures
0553e9e2e4fd4df78f4ff7634230b41afaad54b9
5,495
cpp
C++
Source/GASExtensions/Private/Tasks/GASExtAT_WaitAttributeChangeWithValues.cpp
TheEmidee/UEGASExtensions
8851dbaf9251ecdc914f381df161484a7c5d4275
[ "MIT" ]
null
null
null
Source/GASExtensions/Private/Tasks/GASExtAT_WaitAttributeChangeWithValues.cpp
TheEmidee/UEGASExtensions
8851dbaf9251ecdc914f381df161484a7c5d4275
[ "MIT" ]
null
null
null
Source/GASExtensions/Private/Tasks/GASExtAT_WaitAttributeChangeWithValues.cpp
TheEmidee/UEGASExtensions
8851dbaf9251ecdc914f381df161484a7c5d4275
[ "MIT" ]
null
null
null
// Copy of AbilityTask_WaitAttributeChange that passes the old and new values on change #include "Tasks/GASExtAT_WaitAttributeChangeWithValues.h" #include <AbilitySystemComponent.h> #include <AbilitySystemGlobals.h> #include <GameplayEffectExtension.h> UGASExtAT_WaitAttributeChangeWithValues::UGASExtAT_WaitAttributeChangeWithValues( const FObjectInitializer & object_initializer ) : Super( object_initializer ) { bTriggerOnce = false; ComparisonType = EGASExtWaitAttributeChangeComparisonType::None; ComparisonValue = 0.0f; ExternalOwner = nullptr; } UGASExtAT_WaitAttributeChangeWithValues * UGASExtAT_WaitAttributeChangeWithValues::WaitForAttributeChangeWithValues( UGameplayAbility * owning_ability, FGameplayAttribute attribute, FGameplayTag with_src_tag, FGameplayTag without_src_tag, bool trigger_once, AActor * optional_external_owner ) { UGASExtAT_WaitAttributeChangeWithValues * my_obj = NewAbilityTask< UGASExtAT_WaitAttributeChangeWithValues >( owning_ability ); my_obj->WithTag = with_src_tag; my_obj->WithoutTag = without_src_tag; my_obj->Attribute = attribute; my_obj->ComparisonType = EGASExtWaitAttributeChangeComparisonType::None; my_obj->bTriggerOnce = trigger_once; my_obj->ExternalOwner = optional_external_owner ? UAbilitySystemGlobals::GetAbilitySystemComponentFromActor( optional_external_owner ) : nullptr; return my_obj; } UGASExtAT_WaitAttributeChangeWithValues * UGASExtAT_WaitAttributeChangeWithValues::WaitForAttributeChangeWithComparisonAndValues( UGameplayAbility * owning_ability, FGameplayAttribute in_attribute, FGameplayTag in_with_tag, FGameplayTag in_without_tag, EGASExtWaitAttributeChangeComparisonType in_comparison_type, float in_comparison_value, bool trigger_once, AActor * optional_external_owner ) { UGASExtAT_WaitAttributeChangeWithValues * my_obj = NewAbilityTask< UGASExtAT_WaitAttributeChangeWithValues >( owning_ability ); my_obj->WithTag = in_with_tag; my_obj->WithoutTag = in_without_tag; my_obj->Attribute = in_attribute; my_obj->ComparisonType = in_comparison_type; my_obj->ComparisonValue = in_comparison_value; my_obj->bTriggerOnce = trigger_once; my_obj->ExternalOwner = optional_external_owner ? UAbilitySystemGlobals::GetAbilitySystemComponentFromActor( optional_external_owner ) : nullptr; return my_obj; } void UGASExtAT_WaitAttributeChangeWithValues::Activate() { if ( UAbilitySystemComponent * asc = GetFocusedASC() ) { OnAttributeChangeDelegateHandle = asc->GetGameplayAttributeValueChangeDelegate( Attribute ).AddUObject( this, &UGASExtAT_WaitAttributeChangeWithValues::OnAttributeChange ); } } void UGASExtAT_WaitAttributeChangeWithValues::OnAttributeChange( const FOnAttributeChangeData & callback_data ) { const float new_value = callback_data.NewValue; const float old_value = callback_data.OldValue; const FGameplayEffectModCallbackData * data = callback_data.GEModData; if ( data == nullptr ) { // There may be no execution data associated with this change, for example a GE being removed. // In this case, we auto fail any WithTag requirement and auto pass any WithoutTag requirement if ( WithTag.IsValid() ) { return; } } else { if ( ( WithTag.IsValid() && !data->EffectSpec.CapturedSourceTags.GetAggregatedTags()->HasTag( WithTag ) ) || ( WithoutTag.IsValid() && data->EffectSpec.CapturedSourceTags.GetAggregatedTags()->HasTag( WithoutTag ) ) ) { // Failed tag check return; } } bool passed_comparison = true; switch ( ComparisonType ) { case EGASExtWaitAttributeChangeComparisonType::ExactlyEqualTo: passed_comparison = ( new_value == ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::GreaterThan: passed_comparison = ( new_value > ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::GreaterThanOrEqualTo: passed_comparison = ( new_value >= ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::LessThan: passed_comparison = ( new_value < ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::LessThanOrEqualTo: passed_comparison = ( new_value <= ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::NotEqualTo: passed_comparison = ( new_value != ComparisonValue ); break; default: break; } if ( passed_comparison ) { if ( ShouldBroadcastAbilityTaskDelegates() ) { OnChange.Broadcast( old_value, new_value ); } if ( bTriggerOnce ) { EndTask(); } } } UAbilitySystemComponent * UGASExtAT_WaitAttributeChangeWithValues::GetFocusedASC() { return ExternalOwner ? ExternalOwner : AbilitySystemComponent; } void UGASExtAT_WaitAttributeChangeWithValues::OnDestroy( bool ability_ended ) { if ( UAbilitySystemComponent * asc = GetFocusedASC() ) { asc->GetGameplayAttributeValueChangeDelegate( Attribute ).Remove( OnAttributeChangeDelegateHandle ); } Super::OnDestroy( ability_ended ); }
42.596899
395
0.719199
TheEmidee
0557b766a096ebf2de547bda82e105cba2d89fad
14,159
cpp
C++
Common/src/EGL/eglInstance.cpp
kbiElude/DolceSDK-Experiments
1b5cca8b437f5384e074b5b666bb2bdd3031d08d
[ "Unlicense" ]
null
null
null
Common/src/EGL/eglInstance.cpp
kbiElude/DolceSDK-Experiments
1b5cca8b437f5384e074b5b666bb2bdd3031d08d
[ "Unlicense" ]
null
null
null
Common/src/EGL/eglInstance.cpp
kbiElude/DolceSDK-Experiments
1b5cca8b437f5384e074b5b666bb2bdd3031d08d
[ "Unlicense" ]
null
null
null
extern "C" { #include <psp2/libdbg.h> } #include <sstream> #include <vector> #include "EGL/eglInstance.h" #include "ES/buffer.h" #include "ES/program.h" #include "ES/texture.h" #include "gfx/text_renderer.h" #include "io.h" #include "logger.h" EGLInstance::EGLInstance(Logger* in_logger_ptr) :m_display (nullptr), m_egl_config_ptr (nullptr), m_egl_context (nullptr), m_egl_surface (nullptr), m_gl_extensions_ptr(nullptr), m_logger_ptr (in_logger_ptr), m_never_bound (true) { /* Stub */ } EGLInstance::~EGLInstance() { m_text_renderer_ptr.reset(); if (m_egl_context != nullptr) { ::eglDestroyContext(m_display, m_egl_context); } if (m_egl_surface != nullptr) { ::eglDestroySurface(m_display, m_egl_surface); } } bool EGLInstance::bind_to_current_thread() { bool result = false; result = ::eglMakeCurrent(m_display, m_egl_surface, m_egl_surface, m_egl_context) == EGL_TRUE; if (m_never_bound) { /* Log base GL info & available GL extensions. */ auto es_extensions_ptr = ::eglQueryString(m_display, EGL_EXTENSIONS); auto renderer_ptr = ::glGetString (GL_RENDERER); auto vendor_ptr = ::glGetString (GL_VENDOR); auto version_ptr = ::glGetString (GL_VERSION); m_gl_extensions_ptr = reinterpret_cast<const char*>(::glGetString(GL_EXTENSIONS) ); #if 0 m_logger_ptr->log(false, /* in_flush_and_wait */ "Renderer version: %s\n" "Renderer: %s\n" "Vendor: %s\n", version_ptr, renderer_ptr, vendor_ptr); m_logger_ptr->log(false, /* in_flush_and_wait */ "ES Extensions: %s\n", es_extensions_ptr); m_logger_ptr->log(false, /* in_flush_and_wait */ "GL Extensions: %s\n", m_gl_extensions_ptr); #endif /* Init extension entrypoints */ if (strstr(m_gl_extensions_ptr, "GL_EXT_draw_instanced") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glDrawArraysInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_draw_instanced.glDrawArraysInstancedEXT)}, {"glDrawElementsInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_draw_instanced.glDrawElementsInstancedEXT)}, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } if (strstr(m_gl_extensions_ptr, "GL_EXT_instanced_arrays") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glDrawArraysInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_instanced_arrays.glDrawArraysInstancedEXT)}, {"glDrawElementsInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_instanced_arrays.glDrawElementsInstancedEXT)}, {"glVertexAttribDivisorEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_instanced_arrays.glVertexAttribDivisorEXT)}, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } if (strstr(m_gl_extensions_ptr, "GL_EXT_texture_storage") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glTexStorage2DEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_texture_storage.glTexStorage2DEXT)}, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } if (strstr(m_gl_extensions_ptr, "GL_SCE_piglet_shader_binary") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glPigletGetShaderBinarySCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_piglet_shader_binary.glPigletGetShaderBinarySCE) }, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } if (strstr(m_gl_extensions_ptr, "GL_SCE_texture_resource") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glMapTextureResourceSCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_texture_resource_entrypoints.glMapTextureResourceSCE)}, {"glTexImageResourceSCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_texture_resource_entrypoints.glTexImageResourceSCE)}, {"glUnmapTextureResourceSCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_texture_resource_entrypoints.glUnmapTextureResourceSCE)}, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } /* Init text renderer */ m_text_renderer_ptr = TextRenderer::create(this, m_logger_ptr); SCE_DBG_ASSERT(m_text_renderer_ptr != nullptr); /* Done */ m_never_bound = false; } SCE_DBG_ASSERT(result); end: return result; } std::unique_ptr<EGLInstance> EGLInstance::create(Logger* in_logger_ptr, const bool& in_require_depth_buffer, const bool& in_require_stencil_buffer) { std::unique_ptr<EGLInstance> result_ptr; result_ptr.reset( new EGLInstance(in_logger_ptr) ); SCE_DBG_ASSERT(result_ptr != nullptr); if (result_ptr != nullptr) { if (!result_ptr->init(in_require_depth_buffer, in_require_stencil_buffer) ) { SCE_DBG_ASSERT(false); result_ptr.reset(); } } return result_ptr; } const EXTDrawInstancedEntrypoints* EGLInstance::get_ext_draw_instanced_entrypoints_ptr() const { return &m_entrypoints_gl_ext_draw_instanced; } const EXTInstancedArraysEntrypoints* EGLInstance::get_ext_instanced_arrays_entrypoints_ptr() const { return &m_entrypoints_gl_ext_instanced_arrays; } const EXTTextureStorageEntrypoints* EGLInstance::get_ext_texture_storage_entrypoints_ptr() const { return &m_entrypoints_gl_ext_texture_storage; } const uint32_t* EGLInstance::get_rt_extents_wh() const { static const uint32_t rt[] = {960, 544}; return rt; } const SCEPigletShaderBinaryEntrypoints* EGLInstance::get_sce_piglet_shader_binary_entrypoints_ptr() const { return &m_entrypoints_gl_sce_piglet_shader_binary; } const SCETextureResourceEntrypoints* EGLInstance::get_sce_texture_resource_entrypoints_ptr() const { return &m_entrypoints_gl_sce_texture_resource_entrypoints; } TextRenderer* EGLInstance::get_text_renderer_ptr() const { SCE_DBG_ASSERT(m_text_renderer_ptr != nullptr); return m_text_renderer_ptr.get(); } bool EGLInstance::init(const bool& in_require_depth_buffer, const bool& in_require_stencil_buffer) { EGLBoolean result; m_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); SCE_DBG_ASSERT(m_display != EGL_NO_DISPLAY); result = eglInitialize(m_display, nullptr, /* major */ nullptr); /* minor */ SCE_DBG_ASSERT(result == EGL_TRUE); /* Enumerate available EGL configs */ { std::vector<EGLConfig> egl_config_vec; EGLint n_egl_configs = 0; result = eglGetConfigs(m_display, nullptr, /* configs */ 0, /* config_size */ &n_egl_configs); SCE_DBG_ASSERT(result == EGL_TRUE); egl_config_vec.resize (n_egl_configs); m_egl_config_vec.resize(n_egl_configs); result = eglGetConfigs(m_display, egl_config_vec.data(), n_egl_configs, &n_egl_configs); SCE_DBG_ASSERT(result == EGL_TRUE); for (uint32_t n_egl_config = 0; n_egl_config < n_egl_configs; ++n_egl_config) { const auto current_egl_config = egl_config_vec.at (n_egl_config); auto& current_egl_config_props = m_egl_config_vec.at(n_egl_config); current_egl_config_props.egl_config = current_egl_config; const struct { EGLint attribute; EGLint* result_ptr; } config_attribs[] = { {EGL_ALPHA_SIZE, &current_egl_config_props.n_alpha_bits}, {EGL_BLUE_SIZE, &current_egl_config_props.n_blue_bits}, {EGL_CONFIG_ID, &current_egl_config_props.egl_config_id}, {EGL_DEPTH_SIZE, &current_egl_config_props.n_depth_bits}, {EGL_GREEN_SIZE, &current_egl_config_props.n_green_bits}, {EGL_RED_SIZE, &current_egl_config_props.n_red_bits}, {EGL_STENCIL_SIZE, &current_egl_config_props.n_stencil_bits} }; for (const auto& current_config_attrib : config_attribs) { result = eglGetConfigAttrib(m_display, current_egl_config, current_config_attrib.attribute, current_config_attrib.result_ptr); SCE_DBG_ASSERT(result == EGL_TRUE); } } } /* On 3.60, we are reported 3 different configs, the only difference between the three being presence (or lack) * of depth and/or stencil buffer. * * Pick the right EGLConfig instance, depending on the input arguments. **/ { uint32_t best_score = 0xFFFFFFFFu; for (const auto& current_egl_config : m_egl_config_vec) { uint32_t score = 0; if (( in_require_depth_buffer && current_egl_config.n_depth_bits != 0) || (!in_require_depth_buffer && current_egl_config.n_depth_bits == 0) ) { ++score; } if (( in_require_stencil_buffer && current_egl_config.n_stencil_bits != 0) || (!in_require_stencil_buffer && current_egl_config.n_stencil_bits == 0) ) { ++score; } if ((best_score == 0xFFFFFFFFu) || (best_score < score) ) { best_score = score; m_egl_config_ptr = &current_egl_config; } } } SCE_DBG_ASSERT(m_egl_config_ptr != nullptr); /* Create an ES context. */ { static const EGLint attrib_list[] = { EGL_CONTEXT_MAJOR_VERSION, 2, EGL_CONTEXT_MINOR_VERSION, 0, EGL_NONE }; m_egl_context = eglCreateContext(m_display, m_egl_config_ptr->egl_config, EGL_NO_CONTEXT, /* share_context */ attrib_list); SCE_DBG_ASSERT(m_egl_context != EGL_NO_CONTEXT); } /* Create a rendering surface. * * NOTE: If the resolution is ever changed, make sure to update get_rt_extents_wh() too. **/ m_egl_surface = eglCreateWindowSurface(m_display, m_egl_config_ptr->egl_config, VITA_WINDOW_960X544, nullptr); /* attrib_list */ SCE_DBG_ASSERT(m_egl_surface != EGL_NO_SURFACE); /* NOTE: Do not bind the context to the calling thread. It is caller's responsibility to invoke bind() * from the right thread later on. */ return (m_egl_context != nullptr && m_egl_surface != nullptr); } bool EGLInstance::init_extension_entrypoints(const ExtensionEntrypoint* in_ext_entrypoint_ptr, const uint32_t& in_n_ext_entrypoints) { bool result = false; for (uint32_t n_entrypoint = 0; n_entrypoint < in_n_ext_entrypoints; ++n_entrypoint) { const auto& current_entrypoint = in_ext_entrypoint_ptr[n_entrypoint]; *current_entrypoint.func_ptr_ptr = reinterpret_cast<void*>(::eglGetProcAddress(current_entrypoint.func_name_ptr) ); if (*current_entrypoint.func_ptr_ptr == nullptr) { SCE_DBG_ASSERT(false); goto end; } } result = true; end: return result; } void EGLInstance::swap_buffers() { ::eglSwapBuffers(m_display, m_egl_surface); }
33.315294
150
0.558443
kbiElude
0558276d222da6ed998865223f317b3aa1b5a994
298
cpp
C++
introduction/model_answer/cpp/17_one_quadrillion_and_one_dalmatians.cpp
AAAR-Salmon/procon
d65865e7c7d98f7194f93610b4f06df8fff3332c
[ "MIT" ]
null
null
null
introduction/model_answer/cpp/17_one_quadrillion_and_one_dalmatians.cpp
AAAR-Salmon/procon
d65865e7c7d98f7194f93610b4f06df8fff3332c
[ "MIT" ]
null
null
null
introduction/model_answer/cpp/17_one_quadrillion_and_one_dalmatians.cpp
AAAR-Salmon/procon
d65865e7c7d98f7194f93610b4f06df8fff3332c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ll N; cin >> N; ll L = 0, X = 1; while (N - X >= 0) { N -= X; L++; X *= 26; } string ans(L, 'a'); for (int i = L - 1; i >= 0; i--) { ans[i] += N % 26; N /= 26; } cout << ans << endl; return 0; }
12.956522
35
0.446309
AAAR-Salmon
0558840bdaa1ae8725ae0bde815c93c79b69a3c5
2,614
cpp
C++
src/plugins/device.cpp
localarchive/incubator-cordova-qt
41f94032208723e35f4b6b907ffa145fa8820c7a
[ "Apache-2.0" ]
null
null
null
src/plugins/device.cpp
localarchive/incubator-cordova-qt
41f94032208723e35f4b6b907ffa145fa8820c7a
[ "Apache-2.0" ]
null
null
null
src/plugins/device.cpp
localarchive/incubator-cordova-qt
41f94032208723e35f4b6b907ffa145fa8820c7a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2011 Wolfgang Koller - http://www.gofg.at/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include"device.h" #include "../pluginregistry.h" #if QT_VERSION < 0x050000 #include <QSystemDeviceInfo> #include <QSystemInfo> #else #include <QDeviceInfo> #include <QtSystemInfo> #endif #include <QDebug> #define CORDOVA "2.2.0" #ifdef QTM_NAMESPACE QTM_USE_NAMESPACE #endif // Create static instance of ourself Device* Device::m_device = new Device(); /** * Constructor - NOTE: Never do anything except registering the plugin */ Device::Device() : CPlugin() { PluginRegistry::getRegistry()->registerPlugin( "com.cordova.Device", this ); } /** * Called by the javascript constructor in order to receive all required device info(s) */ void Device::getInfo( int scId, int ecId ) { Q_UNUSED(ecId) #if QT_VERSION < 0x050000 QSystemDeviceInfo *systemDeviceInfo = new QSystemDeviceInfo(this); QSystemInfo *systemInfo = new QSystemInfo(this); #else QDeviceInfo *systemDeviceInfo = new QDeviceInfo(this); QDeviceInfo *systemInfo = new QDeviceInfo(this); #endif #ifdef Q_OS_SYMBIAN QString platform = "Symbian"; #endif #ifdef Q_OS_WIN QString platform = "Windows"; #endif #ifdef Q_OS_WINCE QString platform = "Windows CE"; #endif #ifdef Q_OS_LINUX QString platform = "Linux"; #endif #if QT_VERSION < 0x050000 this->callback( scId, "'" + systemDeviceInfo->model() + "', '" + CORDOVA + "', '" + platform + "', '" + systemDeviceInfo->uniqueDeviceID() + "', '" + systemInfo->version( QSystemInfo::Os ) + "'" ); #else qDebug() << Q_FUNC_INFO << ":" << systemInfo->imei(0) << "; " << systemInfo->manufacturer() << "; " << systemInfo->model() << "; " << systemInfo->productName() << "; " << systemInfo->uniqueDeviceID() << "; " << systemInfo->version(QDeviceInfo::Os) << "; " << systemInfo->version(QDeviceInfo::Firmware); this->callback( scId, "'" + systemDeviceInfo->model() + "', '" + CORDOVA + "', '" + platform + "', '" + systemDeviceInfo->uniqueDeviceID() + "', '" + systemInfo->version( QDeviceInfo::Os ) + "'" ); #endif }
32.271605
306
0.682479
localarchive
055901eb2636856689cab8c248cefff777fee2dd
6,213
cpp
C++
Core/GDCore/IDE/Events/EventsBehaviorRenamer.cpp
psydox/GDevelop
cf462f6c6eede34faa5282158c2bd6a1b784d1bc
[ "MIT" ]
2,990
2018-09-10T19:49:49.000Z
2022-03-31T05:01:42.000Z
Core/GDCore/IDE/Events/EventsBehaviorRenamer.cpp
TheGemDev/GDevelop
6350b035e3f6ce6ecb985f02b1a591927dffe7e2
[ "MIT" ]
2,614
2018-09-09T21:37:47.000Z
2022-03-31T22:09:25.000Z
Core/GDCore/IDE/Events/EventsBehaviorRenamer.cpp
TheGemDev/GDevelop
6350b035e3f6ce6ecb985f02b1a591927dffe7e2
[ "MIT" ]
566
2018-09-11T17:48:13.000Z
2022-03-27T07:59:48.000Z
/* * GDevelop Core * Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights * reserved. This project is released under the MIT License. */ #include "GDCore/IDE/Events/EventsBehaviorRenamer.h" #include <map> #include <memory> #include <vector> #include "GDCore/Events/Event.h" #include "GDCore/Events/EventsList.h" #include "GDCore/Events/Parsers/ExpressionParser2.h" #include "GDCore/Events/Parsers/ExpressionParser2NodePrinter.h" #include "GDCore/Events/Parsers/ExpressionParser2NodeWorker.h" #include "GDCore/Extensions/Metadata/MetadataProvider.h" #include "GDCore/Extensions/Metadata/ParameterMetadataTools.h" #include "GDCore/IDE/Events/ExpressionValidator.h" #include "GDCore/Project/Layout.h" #include "GDCore/Project/Project.h" #include "GDCore/String.h" #include "GDCore/Tools/Log.h" namespace gd { /** * \brief Go through the nodes and rename any reference to an object behavior. * * \see gd::ExpressionParser2 */ class GD_CORE_API ExpressionBehaviorRenamer : public ExpressionParser2NodeWorker { public: ExpressionBehaviorRenamer(const gd::ObjectsContainer& globalObjectsContainer_, const gd::ObjectsContainer& objectsContainer_, const gd::String& objectName_, const gd::String& oldBehaviorName_, const gd::String& newBehaviorName_) : hasDoneRenaming(false), globalObjectsContainer(globalObjectsContainer_), objectsContainer(objectsContainer_), objectName(objectName_), oldBehaviorName(oldBehaviorName_), newBehaviorName(newBehaviorName_){}; virtual ~ExpressionBehaviorRenamer(){}; bool HasDoneRenaming() const { return hasDoneRenaming; } protected: void OnVisitSubExpressionNode(SubExpressionNode& node) override { node.expression->Visit(*this); } void OnVisitOperatorNode(OperatorNode& node) override { node.leftHandSide->Visit(*this); node.rightHandSide->Visit(*this); } void OnVisitUnaryOperatorNode(UnaryOperatorNode& node) override { node.factor->Visit(*this); } void OnVisitNumberNode(NumberNode& node) override {} void OnVisitTextNode(TextNode& node) override {} void OnVisitVariableNode(VariableNode& node) override { if (node.child) node.child->Visit(*this); } void OnVisitVariableAccessorNode(VariableAccessorNode& node) override { if (node.child) node.child->Visit(*this); } void OnVisitVariableBracketAccessorNode( VariableBracketAccessorNode& node) override { node.expression->Visit(*this); if (node.child) node.child->Visit(*this); } void OnVisitIdentifierNode(IdentifierNode& node) override {} void OnVisitObjectFunctionNameNode(ObjectFunctionNameNode& node) override { if (!node.behaviorFunctionName.empty()) { // Behavior function name if (node.objectName == objectName && node.objectFunctionOrBehaviorName == oldBehaviorName) { node.objectFunctionOrBehaviorName = newBehaviorName; hasDoneRenaming = true; } } } void OnVisitFunctionCallNode(FunctionCallNode& node) override { if (!node.behaviorName.empty()) { // Behavior function call if (node.objectName == objectName && node.behaviorName == oldBehaviorName) { node.behaviorName = newBehaviorName; hasDoneRenaming = true; } } for (auto& parameter : node.parameters) { parameter->Visit(*this); } } void OnVisitEmptyNode(EmptyNode& node) override {} private: bool hasDoneRenaming; const gd::ObjectsContainer& globalObjectsContainer; const gd::ObjectsContainer& objectsContainer; const gd::String& objectName; // The object name for which the behavior // must be replaced. const gd::String& oldBehaviorName; const gd::String& newBehaviorName; }; bool EventsBehaviorRenamer::DoVisitInstruction(gd::Instruction& instruction, bool isCondition) { const auto& metadata = isCondition ? gd::MetadataProvider::GetConditionMetadata( platform, instruction.GetType()) : gd::MetadataProvider::GetActionMetadata( platform, instruction.GetType()); gd::ParameterMetadataTools::IterateOverParametersWithIndex( instruction.GetParameters(), metadata.GetParameters(), [&](const gd::ParameterMetadata& parameterMetadata, const gd::String& parameterValue, size_t parameterIndex, const gd::String& lastObjectName) { const gd::String& type = parameterMetadata.type; if (gd::ParameterMetadata::IsBehavior(type)) { if (lastObjectName == objectName) { if (parameterValue == oldBehaviorName) { instruction.SetParameter(parameterIndex, gd::Expression(newBehaviorName)); } } } else { gd::ExpressionParser2 parser( platform, GetGlobalObjectsContainer(), GetObjectsContainer()); auto node = gd::ParameterMetadata::IsExpression("number", type) ? parser.ParseExpression("number", parameterValue) : (gd::ParameterMetadata::IsExpression("string", type) ? parser.ParseExpression("string", parameterValue) : std::unique_ptr<gd::ExpressionNode>()); if (node) { ExpressionBehaviorRenamer renamer(GetGlobalObjectsContainer(), GetObjectsContainer(), objectName, oldBehaviorName, newBehaviorName); node->Visit(renamer); if (renamer.HasDoneRenaming()) { instruction.SetParameter( parameterIndex, ExpressionParser2NodePrinter::PrintNode(*node)); } } } }); return false; } EventsBehaviorRenamer::~EventsBehaviorRenamer() {} } // namespace gd
37.654545
98
0.640431
psydox
055ab2002a9c1a604026d64f4ef956c193e8b527
2,586
cpp
C++
src/net/Server.cpp
landness/RPC-K8S-githubAction_cicd_test
8178274f1b952650d52125deeda2cfc3e6d3632c
[ "MIT" ]
null
null
null
src/net/Server.cpp
landness/RPC-K8S-githubAction_cicd_test
8178274f1b952650d52125deeda2cfc3e6d3632c
[ "MIT" ]
null
null
null
src/net/Server.cpp
landness/RPC-K8S-githubAction_cicd_test
8178274f1b952650d52125deeda2cfc3e6d3632c
[ "MIT" ]
null
null
null
#include"net/Server.h" #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include"base/Util.h" Server::Server(Eventloop* loop,int threadnum,uint16_t port) :loop_(loop), threadnum_(threadnum), eventloopthreadpool_(new Eventloopthreadpool(loop_,threadnum_)), started_(false), port_(port), listenfd_(socket_bind_and_listen(port_)), acceptchannel_(new Channel(loop_,listenfd_)), nextconnid_(0) { //SIGPIPE if(setSocketNonBlocking(listenfd_) < 0) { perror("set nonblock error"); abort(); } } void Server::start() { if(!started_) { eventloopthreadpool_->start(); acceptchannel_->set_events(EPOLLIN|EPOLLET); acceptchannel_->setreadcallback(bind(&Server::newconnection,this)); loop_->addchannel(acceptchannel_); started_ = true; } } void Server::newconnection() { struct sockaddr_in client_addr; memset(&client_addr,0,sizeof(struct sockaddr_in)); socklen_t client_addr_len = sizeof(client_addr); int accept_fd = 0; while((accept_fd = accept(listenfd_,(struct sockaddr*)&client_addr,&client_addr_len)) > 0 ) { if(accept_fd >= MAXFDS) //限制并发链接数 { close(accept_fd); continue; } if(setSocketNonBlocking(accept_fd) < 0) { return; } setSocketNodelay(accept_fd); char buf[32]; snprintf(buf,sizeof(buf),"#%d",nextconnid_); ++nextconnid_; std::string connname = buf; setSocketNodelay(accept_fd); Eventloop* ioloop = eventloopthreadpool_->getnextloop(); TcpconnectionPtr conn = make_shared<Tcpconnection>(ioloop,connname,accept_fd); //不使用new by 陈硕?????? connections_[connname] = conn; conn->setConnectioncallback(connectioncallback_); conn->setMessagecallback(messagecallback_); //Rpc messagecallback 由connectioncallback 绑定 conn->setClosecallback(std::bind(&Server::removeconnection, this, std::placeholders::_1));//Fixme::unsafe ioloop->runinloop(std::bind(&Tcpconnection::connectEstablished,conn)); } } void Server::removeconnection(const TcpconnectionPtr& conn) { loop_->runinloop(std::bind(&Server::removeconnectioninloop,this,conn)); } void Server::removeconnectioninloop(const TcpconnectionPtr& conn) { loop_->assertinloopthread(); size_t n = connections_.erase(conn->name()); assert( n == 1); Eventloop* ioloop = conn->getloop(); ioloop->queueinloop(std::bind(&Tcpconnection::connectDestroyed,conn)); }
29.386364
113
0.663186
landness
055b67249412faf462f91267025e145b1d5b5c21
7,118
cpp
C++
Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/PlatformIncl.h> #include <AzCore/Asset/AssetManagerComponent.h> #include <AzCore/Component/ComponentApplication.h> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/IO/Path/Path.h> #include <AzCore/Settings/SettingsRegistryMergeUtils.h> #include <AzCore/IO/Streamer/StreamerComponent.h> #include <AzCore/Jobs/JobManagerComponent.h> #include <AzCore/Memory/PoolAllocator.h> #include <AzCore/UserSettings/UserSettingsComponent.h> #include <AzFramework/Asset/CustomAssetTypeComponent.h> #include <AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.h> #include <AzQtComponents/Components/GlobalEventFilter.h> #include <AzQtComponents/Components/StyledDockWidget.h> #include <AzQtComponents/Components/O3DEStylesheet.h> #include <AzQtComponents/Utilities/HandleDpiAwareness.h> #include <AzQtComponents/Components/WindowDecorationWrapper.h> #include "ComponentDemoWidget.h" #include <AzCore/Memory/SystemAllocator.h> #include <QApplication> #include <QMainWindow> #include <QSettings> #include <iostream> const QString g_ui_1_0_SettingKey = QStringLiteral("useUI_1_0"); static void LogToDebug([[maybe_unused]] QtMsgType Type, [[maybe_unused]] const QMessageLogContext& Context, const QString& message) { #ifdef Q_OS_WIN OutputDebugStringW(L"Qt: "); OutputDebugStringW(reinterpret_cast<const wchar_t*>(message.utf16())); OutputDebugStringW(L"\n"); #else std::wcerr << L"Qt: " << message.toStdWString() << std::endl; #endif } /* * Sets up and tears down everything we need for an AZ::ComponentApplication. * This is required for the ReflectedPropertyEditorPage. */ class ComponentApplicationWrapper { public: explicit ComponentApplicationWrapper() { AZ::ComponentApplication::Descriptor appDesc; m_systemEntity = m_componentApp.Create(appDesc); AZ::AllocatorInstance<AZ::PoolAllocator>::Create(); AZ::AllocatorInstance<AZ::ThreadPoolAllocator>::Create(); m_componentApp.RegisterComponentDescriptor(AZ::AssetManagerComponent::CreateDescriptor()); m_componentApp.RegisterComponentDescriptor(AZ::JobManagerComponent::CreateDescriptor()); m_componentApp.RegisterComponentDescriptor(AZ::StreamerComponent::CreateDescriptor()); m_componentApp.RegisterComponentDescriptor(AZ::UserSettingsComponent::CreateDescriptor()); m_componentApp.RegisterComponentDescriptor(AzFramework::CustomAssetTypeComponent::CreateDescriptor()); m_componentApp.RegisterComponentDescriptor(AzToolsFramework::Components::PropertyManagerComponent::CreateDescriptor()); m_systemEntity->CreateComponent<AZ::AssetManagerComponent>(); m_systemEntity->CreateComponent<AZ::JobManagerComponent>(); m_systemEntity->CreateComponent<AZ::StreamerComponent>(); m_systemEntity->CreateComponent<AZ::UserSettingsComponent>(); m_systemEntity->CreateComponent<AzFramework::CustomAssetTypeComponent>(); m_systemEntity->CreateComponent<AzToolsFramework::Components::PropertyManagerComponent>(); m_systemEntity->Init(); m_systemEntity->Activate(); m_serializeContext = m_componentApp.GetSerializeContext(); m_serializeContext->CreateEditContext(); } ~ComponentApplicationWrapper() { m_serializeContext->DestroyEditContext(); m_systemEntity->Deactivate(); std::vector<AZ::Component*> components = { m_systemEntity->FindComponent<AZ::AssetManagerComponent>(), m_systemEntity->FindComponent<AZ::JobManagerComponent>(), m_systemEntity->FindComponent<AZ::StreamerComponent>(), m_systemEntity->FindComponent<AZ::UserSettingsComponent>(), m_systemEntity->FindComponent<AzFramework::CustomAssetTypeComponent>(), m_systemEntity->FindComponent<AzToolsFramework::Components::PropertyManagerComponent>() }; for (auto component : components) { m_systemEntity->RemoveComponent(component); delete component; } m_componentApp.UnregisterComponentDescriptor(AZ::AssetManagerComponent::CreateDescriptor()); m_componentApp.UnregisterComponentDescriptor(AZ::JobManagerComponent::CreateDescriptor()); m_componentApp.UnregisterComponentDescriptor(AZ::StreamerComponent::CreateDescriptor()); m_componentApp.UnregisterComponentDescriptor(AZ::UserSettingsComponent::CreateDescriptor()); m_componentApp.UnregisterComponentDescriptor(AzFramework::CustomAssetTypeComponent::CreateDescriptor()); m_componentApp.UnregisterComponentDescriptor(AzToolsFramework::Components::PropertyManagerComponent::CreateDescriptor()); AZ::AllocatorInstance<AZ::ThreadPoolAllocator>::Destroy(); AZ::AllocatorInstance<AZ::PoolAllocator>::Destroy(); m_componentApp.Destroy(); } private: // ComponentApplication must not be a pointer - it cannot be dynamically allocated AZ::ComponentApplication m_componentApp; AZ::Entity* m_systemEntity = nullptr; AZ::SerializeContext* m_serializeContext = nullptr; }; int main(int argc, char **argv) { ComponentApplicationWrapper componentApplicationWrapper; QApplication::setOrganizationName("O3DE"); QApplication::setOrganizationDomain("o3de.org"); QApplication::setApplicationName("O3DEWidgetGallery"); QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates)); QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); qInstallMessageHandler(LogToDebug); AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::PerScreenDpiAware); QApplication app(argc, argv); auto globalEventFilter = new AzQtComponents::GlobalEventFilter(&app); app.installEventFilter(globalEventFilter); AzQtComponents::StyleManager styleManager(&app); AZ::IO::FixedMaxPath engineRootPath; if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); } styleManager.initialize(&app, engineRootPath); auto wrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionNone); auto widget = new ComponentDemoWidget(wrapper); wrapper->setGuest(widget); widget->resize(550, 900); widget->show(); wrapper->enableSaveRestoreGeometry("windowGeometry"); wrapper->restoreGeometryFromSettings(); QObject::connect(widget, &ComponentDemoWidget::refreshStyle, &styleManager, [&styleManager]() { styleManager.Refresh(); }); app.setQuitOnLastWindowClosed(true); app.exec(); }
40.674286
158
0.756392
aaarsene
055c54e469f20bed508c25b918ccb9bf9b4143a5
7,557
cpp
C++
matlab_code/jjcao_code-head/toolbox/jjcao_plot/mex_draw_thick_lines_on_img.cpp
joycewangsy/normals_pointnet
fc74a8ed1a009b18785990b1b4c20eda0549721c
[ "MIT" ]
null
null
null
matlab_code/jjcao_code-head/toolbox/jjcao_plot/mex_draw_thick_lines_on_img.cpp
joycewangsy/normals_pointnet
fc74a8ed1a009b18785990b1b4c20eda0549721c
[ "MIT" ]
null
null
null
matlab_code/jjcao_code-head/toolbox/jjcao_plot/mex_draw_thick_lines_on_img.cpp
joycewangsy/normals_pointnet
fc74a8ed1a009b18785990b1b4c20eda0549721c
[ "MIT" ]
null
null
null
/* // // Draw multiple thick lines on the image // // Inputs: // InputImg: Input image (Grayscale or Color) // CoordPnt: Coordinates of end points of lines [r1 r2 c1 c2] // (n x 4 double array, n: # of lines) // Thickness: Thickness of lines (The value is integer, but the type is double.) // (n x 1 double array, n: # of lines) // LineColor: Line colors (The values should be integers from 0 to 255) // (n x 4 double array, n: # of lines) // (Data type: double, ex. [255 255 255]: white ) // (The channels of 'InputImg' and 'LineColor' should be consistent) // // // Outputs: // OutputImg: Output image (The same format with InputImg) // // // Copyright, Gunhee Kim (gunhee@cs.cmu.edu) // Computer Science Department, Carnegie Mellon University, // October 19 2009 */ #include <mex.h> #include <math.h> //#include <string.h> #define UINT8 unsigned char #define UINT32 unsigned int #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) #define abs(x) ((x) >= 0 ? (x) : -(x)) #define pow2(x) ((x)*(x)) void Bresenham(int x1, int x2, int y1, int yt) ; void plot(int x1, int y1) ; void draw_thick_line(int x1, int x2, int y1, int y2) ; double *LineColor, *LineThickness ; UINT8 *OutputImg ; int nPnt, nChannel, indLine ; int dimR, dimC, nDim ; void mexFunction( int nlhs, // Number of left hand side (output) arguments mxArray *plhs[], // Array of left hand side arguments int nrhs, // Number of right hand side (input) arguments const mxArray *prhs[] // Array of right hand side arguments ) { UINT8 *InputImg ; double *CoordPnt, *InCoord ; int i, dimPnt, add_r1, add_r2, add_c1, add_c2 ; /* Check for proper number of arguments. */ if (nrhs <4) { mexErrMsgTxt("Four inputs are required."); } else if (nlhs > 1) { mexErrMsgTxt("Too many output assigned."); } InputImg = (UINT8 *)mxGetPr(prhs[0]); // Input image (Data type: uint8*) InCoord = (double *) mxGetPr(prhs[1]); // [r1 r2 c1 c2] (Data type: double*) nPnt = (int) mxGetM(prhs[1]); dimPnt = (int) mxGetN(prhs[1]); LineThickness = (double *)mxGetPr(prhs[2]); // Line Thickness (Data type: double*) LineColor = (double *)mxGetPr(prhs[3]); // Line color (Data type: double*) nChannel = (int)mxGetN(prhs[3]); // Dimensions of input image dimR = (int)mxGetM(prhs[0]); dimC = (int)mxGetN(prhs[0]); nDim = (int)mxGetNumberOfDimensions(prhs[0]); /* // If the channels of Input image and line color are different, terminate it. if (((nDim==2) && (nChannel==3)) || ((nDim==3) && (nChannel==1)) ) { mexErrMsgTxt("The channels of Input image and line color are different !"); } */ // If the input image is color image if(nChannel==3) dimC = dimC/nChannel; //mexPrintf("%d %d %d %d %d %d\n", nChannel, dimR, dimC, nDim, dimPnt, nPnt) ; // Set output plhs[0] = mxCreateNumericArray(mxGetNumberOfDimensions(prhs[0]), mxGetDimensions(prhs[0]),mxUINT8_CLASS,mxREAL); OutputImg = (UINT8*)mxGetPr(plhs[0]); // copy InputImg to OutputImg for (i=0; i<dimR*dimC*nChannel; i++) OutputImg[i] = InputImg[i] -1 ; // decrease coordinates by 1 CoordPnt = (double *) mxCalloc(nPnt*dimPnt, sizeof(double)); // If the coordinate< 0 or > image dimension, reduce it. for (i=0; i<nPnt*dimPnt/2; i++) { CoordPnt[i] = InCoord[i] -1 ; if (CoordPnt[i]<0) CoordPnt[i] = 0 ; if (CoordPnt[i]>dimR) CoordPnt[i] = dimR ; } for (i=nPnt*dimPnt/2; i<nPnt*dimPnt; i++) { CoordPnt[i] = InCoord[i] -1 ; if (CoordPnt[i]<0) CoordPnt[i] = 0 ; if (CoordPnt[i]>dimC) CoordPnt[i] = dimC ; } // adding indices for each dim. add_r1 = 0 ; add_r2 = nPnt ; add_c1 = 2*nPnt ; add_c2 = 3*nPnt ; // Main loop for (i=0; i<nPnt; i++) { // lineIdx indLine = i ; draw_thick_line((int)CoordPnt[i+add_c1], // c1 = x1 (int)CoordPnt[i+add_c2], // c2 = x2 (int)CoordPnt[i+add_r1], // r1 = y1 (int)CoordPnt[i+add_r2] // r2 = y2 ) ; } mxFree(CoordPnt) ; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // End of the function "Main" function ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Set the values void plot(int x1, int y1) { int idx = y1 + dimR*x1 ; for (int i=0; i<nChannel; i++) OutputImg[dimR*dimC*i+idx] = (UINT8)LineColor[indLine+i*nPnt] ; } // draw thick lines // (reference) Computer Graphics by A.P. Godse void draw_thick_line(int x1, int x2, int y1, int y2) { int i; float wy, wx ; int thickness = (int)LineThickness[indLine] ; Bresenham(x1, x2, y1, y2) ; if (abs((float)(y2-y1)/(float)(x2-x1)) < 1) { wy = (float)(thickness-1)*sqrt((float)(pow2(x2-x1)+pow2(y2-y1))) / (2.*(float)abs(x2-x1)) ; //mexPrintf("wy: %f %d %f \n", 2.*(float)abs(x2-x1), thickness, wy) ; for (i=0; i<wy; i++) { if ( ((y1-i)>-1) && ((y2-i)>-1) ) Bresenham(x1, x2, y1-i, y2-i) ; if ( ((y1+i)<dimR) && ((y2+i)<dimR) ) Bresenham(x1, x2, y1+i, y2+i) ; } } else { wx = (float)(thickness-1)*sqrt((float)(pow2(x2-x1)+pow2(y2-y1))) / (2.*(float)abs(y2-y1)) ; //mexPrintf("wx: %f %d %f \n", 2.*(float)abs(y2-y1), thickness, wx) ; for (i=0; i<wx; i++) { if ( ((x1-i)>-1) && ((x2-i)>-1) ) Bresenham(x1-i, x2-i, y1, y2) ; if ( ((x1+i)<dimC) && ((x2+i)<dimC) ) Bresenham(x1+i, x2+i, y1, y2) ; } } } // The following code is Bresenham's Line Algorithm. // (Reference) http://roguebasin.roguelikedevelopment.org/index.php?title=Bresenham's_Line_Algorithm //////////////////////////////////////////////////////////////////////////////// void Bresenham(int x1, int x2, int y1, int y2) { int delta_x = abs(x2 - x1) << 1; int delta_y = abs(y2 - y1) << 1; // if x1 == x2 or y1 == y2, then it does not matter what we set here signed char ix = x2 > x1?1:-1; signed char iy = y2 > y1?1:-1; plot(x1, y1); if (delta_x >= delta_y) { // error may go below zero int error = delta_y - (delta_x >> 1); while (x1 != x2) { if (error >= 0) { if (error || (ix > 0)) { y1 += iy; error -= delta_x; } // else do nothing } // else do nothing x1 += ix; error += delta_y; plot(x1, y1); } } else { // error may go below zero int error = delta_x - (delta_y >> 1); while (y1 != y2) { if (error >= 0) { if (error || (iy > 0)) { x1 += ix; error -= delta_y; } // else do nothing } // else do nothing y1 += iy; error += delta_x; plot(x1, y1); } } }
29.519531
110
0.492259
joycewangsy
055d55e7eecdc28c2152938f6a7f51df7a6cea94
1,892
cc
C++
src/reader/wgsl/parser_impl_struct_decoration_test.cc
sunnyps/tint
22daca166bbc412345fc60d4f60646d6d2f3ada0
[ "Apache-2.0" ]
null
null
null
src/reader/wgsl/parser_impl_struct_decoration_test.cc
sunnyps/tint
22daca166bbc412345fc60d4f60646d6d2f3ada0
[ "Apache-2.0" ]
null
null
null
src/reader/wgsl/parser_impl_struct_decoration_test.cc
sunnyps/tint
22daca166bbc412345fc60d4f60646d6d2f3ada0
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/ast/struct_block_decoration.h" #include "src/reader/wgsl/parser_impl_test_helper.h" namespace tint { namespace reader { namespace wgsl { namespace { struct DecorationData { const char* input; bool is_block; }; inline std::ostream& operator<<(std::ostream& out, DecorationData data) { out << std::string(data.input); return out; } class DecorationTest : public ParserImplTestWithParam<DecorationData> {}; TEST_P(DecorationTest, Parses) { auto params = GetParam(); auto p = parser(params.input); auto deco = p->decoration(); ASSERT_FALSE(p->has_error()); EXPECT_TRUE(deco.matched); EXPECT_FALSE(deco.errored); ASSERT_NE(deco.value, nullptr); auto* struct_deco = deco.value->As<ast::Decoration>(); ASSERT_NE(struct_deco, nullptr); EXPECT_EQ(struct_deco->Is<ast::StructBlockDecoration>(), params.is_block); } INSTANTIATE_TEST_SUITE_P(ParserImplTest, DecorationTest, testing::Values(DecorationData{"block", true})); TEST_F(ParserImplTest, Decoration_NoMatch) { auto p = parser("not-a-stage"); auto deco = p->decoration(); EXPECT_FALSE(deco.matched); EXPECT_FALSE(deco.errored); ASSERT_EQ(deco.value, nullptr); } } // namespace } // namespace wgsl } // namespace reader } // namespace tint
30.031746
76
0.716702
sunnyps
055e506ba9b67cc8d6287f8e41f7a2a3b1aaf783
2,196
hpp
C++
src/test/utils/thread.hpp
koplyarov/wigwag
d5646c610b324c9252ec7ac807f883f88e7442eb
[ "0BSD" ]
103
2016-02-26T14:39:03.000Z
2021-02-13T10:15:52.000Z
src/test/utils/thread.hpp
koplyarov/wigwag
d5646c610b324c9252ec7ac807f883f88e7442eb
[ "0BSD" ]
1
2018-05-07T06:00:19.000Z
2018-05-07T19:57:20.000Z
src/test/utils/thread.hpp
koplyarov/wigwag
d5646c610b324c9252ec7ac807f883f88e7442eb
[ "0BSD" ]
9
2016-03-17T11:56:33.000Z
2020-08-06T10:11:50.000Z
#ifndef UTILS_UTILS_HPP #define UTILS_UTILS_HPP // Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com> // // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <chrono> #include <thread> namespace wigwag { class thread { public: using thread_func = std::function<void(const std::atomic<bool>&)>; private: std::atomic<bool> _alive; thread_func _thread_func; std::string _error_message; std::thread _impl; public: thread(const thread_func& f) : _alive(true), _thread_func(f) { _impl = std::thread(std::bind(&thread::func, this)); } ~thread() { _alive = false; if (_impl.joinable()) _impl.join(); else std::cerr << "WARNING: thread is not joinable!" << std::endl; if (!_error_message.empty()) TS_FAIL(("Uncaught exception in thread: " + _error_message).c_str()); } static void sleep(int64_t ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); } private: void func() { try { _thread_func(_alive); } catch (const std::exception& ex) { _error_message = ex.what(); } } }; template < typename Lockable_ > std::unique_lock<Lockable_> lock(Lockable_& lockable) { return std::unique_lock<Lockable_>(lockable); } } #endif
30.5
172
0.617486
koplyarov
055eafa4d630e6a34738b1391aa08f6ba137c091
9,107
cpp
C++
openstudiocore/src/runmanager/lib/Test/ErrorEstimation_GTest.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/runmanager/lib/Test/ErrorEstimation_GTest.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/runmanager/lib/Test/ErrorEstimation_GTest.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * Likey = cense along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include "RunManagerTestFixture.hpp" #include <runmanager/Test/ToolBin.hxx> #include <resources.hxx> #include "../JobFactory.hpp" #include "../RunManager.hpp" #include "../Workflow.hpp" #include "../ErrorEstimation.hpp" #include "../../../model/Model.hpp" #include "../../../model/Building.hpp" #include "../../../utilities/idf/IdfFile.hpp" #include "../../../utilities/idf/IdfObject.hpp" #include "../../../utilities/data/EndUses.hpp" #include "../../../utilities/data/Attribute.hpp" #include "../../../utilities/sql/SqlFile.hpp" #include "../../../isomodel/UserModel.hpp" #include "../../../isomodel/ForwardTranslator.hpp" #include <boost/filesystem/path.hpp> #include <QDir> #include <QElapsedTimer> #include <boost/filesystem.hpp> using openstudio::Attribute; using openstudio::IdfFile; using openstudio::IdfObject; using openstudio::IddObjectType; using openstudio::SqlFile; openstudio::SqlFile runSimulation(openstudio::model::Model t_model, bool t_estimate) { if (t_estimate) { openstudio::runmanager::RunManager::simplifyModelForPerformance(t_model); } openstudio::path outdir = openstudio::toPath(QDir::tempPath()) / openstudio::toPath("ErrorEstimationRunTest"); boost::filesystem::create_directories(outdir); openstudio::path db = outdir / openstudio::toPath("ErrorEstimationRunDB"); openstudio::runmanager::RunManager kit(db, true); openstudio::path infile = outdir / openstudio::toPath("in.osm"); openstudio::path weatherdir = resourcesPath() / openstudio::toPath("runmanager") / openstudio::toPath("USA_CO_Golden-NREL.724666_TMY3.epw"); t_model.save(infile, true); openstudio::runmanager::Workflow workflow("modeltoidf->expandobjects->energyplus"); workflow.setInputFiles(infile, weatherdir); // Build list of tools openstudio::runmanager::Tools tools = openstudio::runmanager::ConfigOptions::makeTools( energyPlusExePath().parent_path(), openstudio::path(), openstudio::path(), openstudio::path(), openstudio::path()); workflow.add(tools); int offset = 7; if (t_estimate) offset = 1; workflow.parallelizeEnergyPlus(kit.getConfigOptions().getMaxLocalJobs(), offset); openstudio::runmanager::Job job = workflow.create(outdir); kit.enqueue(job, true); kit.waitForFinished(); openstudio::path sqlpath = job.treeOutputFiles().getLastByExtension("sql").fullPath; openstudio::SqlFile sqlfile(sqlpath); return sqlfile; } double compareSqlFile(const openstudio::SqlFile &sf1, const openstudio::SqlFile &sf2) { return *sf1.netSiteEnergy() - *sf2.netSiteEnergy(); } double compare(double v1, double v2) { return v1-v2; } double compareUses(const openstudio::runmanager::FuelUses &t_fuse1, const openstudio::runmanager::FuelUses &t_fuse2) { double gas1 = t_fuse1.fuelUse(openstudio::FuelType::Gas); double elec1 = t_fuse1.fuelUse(openstudio::FuelType::Electricity); double gas2 = t_fuse2.fuelUse(openstudio::FuelType::Gas); double elec2 = t_fuse2.fuelUse(openstudio::FuelType::Electricity); LOG_FREE(Info, "compareUses", "Gas1 " << gas1 << " gas2 " << gas2 << " Gas Difference " << gas1 - gas2); LOG_FREE(Info, "compareUses", "Elec1 " << elec1 << " elec2 " << elec2 << " Elec Difference " << elec1 - elec2); double totalerror = (gas1+elec1) - (gas2+elec2); LOG_FREE(Info, "compareUses", "Total Error" << totalerror); return totalerror; } std::pair<double, double> runSimulation(openstudio::runmanager::ErrorEstimation &t_ee, double t_rotation) { openstudio::model::Model m = openstudio::model::exampleModel(); openstudio::model::Building b = *m.building(); b.setNorthAxis(b.northAxis() + t_rotation); QElapsedTimer et; et.start(); openstudio::SqlFile sqlfile1(runSimulation(m, false)); qint64 originaltime = et.restart(); openstudio::SqlFile sqlfile2(runSimulation(m, true)); qint64 reducedtime = et.elapsed(); openstudio::path weatherpath = resourcesPath() / openstudio::toPath("runmanager") / openstudio::toPath("USA_CO_Golden-NREL.724666_TMY3.epw"); openstudio::isomodel::ForwardTranslator translator; openstudio::isomodel::UserModel userModel = translator.translateModel(m); userModel.setWeatherFilePath(weatherpath); openstudio::isomodel::SimModel simModel = userModel.toSimModel(); openstudio::isomodel::ISOResults isoResults = simModel.simulate(); LOG_FREE(Info, "runSimulation", "OriginalTime " << originaltime << " reduced " << reducedtime); std::vector<double> variables; variables.push_back(t_rotation); openstudio::runmanager::FuelUses fuses0(0); try { fuses0 = t_ee.approximate(variables); } catch (const std::exception &e) { LOG_FREE(Info, "runSimulation", "Unable to generate estimate: " << e.what()); } openstudio::runmanager::FuelUses fuses3 = t_ee.add(userModel, isoResults, "ISO", variables); openstudio::runmanager::FuelUses fuses2 = t_ee.add(sqlfile2, "Estimation", variables); openstudio::runmanager::FuelUses fuses1 = t_ee.add(sqlfile1, "FullRun", variables); LOG_FREE(Info, "runSimulation", "Comparing Full Run to linear approximation"); compareUses(fuses1, fuses0); LOG_FREE(Info, "runSimulation", "Comparing Full Run to error adjusted ISO run"); return std::make_pair(compare(*sqlfile1.netSiteEnergy(), isoResults.totalEnergyUse()), compareUses(fuses1, fuses3)); } TEST_F(RunManagerTestFixture, ErrorEstimationTest) { openstudio::runmanager::ErrorEstimation ee(1); ee.setConfidence("FullRun", 1.0); ee.setConfidence("Estimation", 0.75); ee.setConfidence("ISO", 0.50); std::pair<double, double> run1 = runSimulation(ee, 0); LOG(Info, "Run1 initialerror: " << run1.first*1000000000 << " adjustederror: " << run1.second); std::pair<double, double> run2 = runSimulation(ee, 90); LOG(Info, "Run2 initialerror: " << run2.first*1000000000 << " adjustederror: " << run2.second); std::pair<double, double> run3 = runSimulation(ee, 180); LOG(Info, "Run3 initialerror: " << run3.first*1000000000 << " adjustederror: " << run3.second); std::pair<double, double> run4 = runSimulation(ee, 270); LOG(Info, "Run4 initialerror: " << run4.first*1000000000 << " adjustederror: " << run4.second); // std::pair<double, double> run5 = runSimulation(ee, 225); // LOG(Info, "Run5 initialerror: " << run5.first*1000000000 << " adjustederror: " << run5.second); } TEST_F(RunManagerTestFixture, LinearApproximationTestSimple) { LinearApproximation la(1); std::vector<double> vals; vals.push_back(0); la.addVals(vals, 0); vals[0] = 2; la.addVals(vals, 2); EXPECT_DOUBLE_EQ(2.0, la.approximate(vals)); vals[0] = 0; EXPECT_DOUBLE_EQ(0.0, la.approximate(vals)); vals[0] = 1; EXPECT_DOUBLE_EQ(1.0, la.approximate(vals)); } TEST_F(RunManagerTestFixture, LinearApproximationTestHuge) { const size_t size = 200; LinearApproximation la(size); std::vector<double> vals(size); // just establish a baseline for (size_t i = 0; i < size; ++i) { vals[i] = i; } // let's say that this equals 100 la.addVals(vals, 100); // and we should be able to get back the value we just put in EXPECT_EQ(100.0, la.approximate(vals)); // now we'll modify one variable at a time for (size_t i = 0; i < size; ++i) { std::vector<double> newvals(vals); double origVariable = newvals[i]; double newVariable = origVariable * 2.0; newvals[i] = newVariable; double valueAtThisPoint = 100.0 + newvals[i]; la.addVals(newvals, valueAtThisPoint); EXPECT_DOUBLE_EQ(valueAtThisPoint, la.approximate(newvals)); newvals[i] = (origVariable + newVariable) / 2; EXPECT_DOUBLE_EQ((valueAtThisPoint + 100.0) / 2, la.approximate(newvals)); } vals[size/10] = 62.4; vals[size/8] = 99; vals[size/6] = 99; vals[size/4] = 102; vals[size/2] = 102; la.approximate(vals); }
33.981343
144
0.676183
zhouchong90
0560051d6a4c63e3b6a83d6c821a61f5f2d96669
2,570
cxx
C++
Testing/Code/BasicFilters/itkNormalizeImageFilterTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
1
2018-04-15T13:32:43.000Z
2018-04-15T13:32:43.000Z
Testing/Code/BasicFilters/itkNormalizeImageFilterTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
Testing/Code/BasicFilters/itkNormalizeImageFilterTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkNormalizeImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImage.h" #include <iostream> #include "itkImageRegionIterator.h" #include "itkNormalizeImageFilter.h" #include "itkRandomImageSource.h" #include "itkStatisticsImageFilter.h" #include "itkStreamingImageFilter.h" #include "itkFilterWatcher.h" int itkNormalizeImageFilterTest(int, char* [] ) { std::cout << "itkNormalizeImageFilterTest Start" << std::endl; typedef itk::Image<short,3> ShortImage; typedef itk::Image<float,3> FloatImage; ShortImage::Pointer image = ShortImage::New(); // Generate a real image typedef itk::RandomImageSource<ShortImage> SourceType; SourceType::Pointer source = SourceType::New(); ShortImage::SizeValueType randomSize[3] = {18, 17, 67}; source->SetSize( randomSize ); float minValue = -1000.0; float maxValue = 1000.0; source->SetMin( static_cast<ShortImage::PixelType>( minValue ) ); source->SetMax( static_cast<ShortImage::PixelType>( maxValue ) ); typedef itk::NormalizeImageFilter<ShortImage,FloatImage> NormalizeType; NormalizeType::Pointer normalize = NormalizeType::New(); FilterWatcher watch(normalize, "Streaming"); normalize->SetInput(source->GetOutput()); typedef itk::StreamingImageFilter<FloatImage,FloatImage> StreamingType; StreamingType::Pointer streaming = StreamingType::New(); streaming->SetNumberOfStreamDivisions(5); streaming->SetInput (normalize->GetOutput()); streaming->Update(); // Force the filter to re-execute source->Modified(); typedef itk::StatisticsImageFilter<FloatImage> StatisticsType; StatisticsType::Pointer statistics = StatisticsType::New(); statistics->SetInput(streaming->GetOutput()); statistics->UpdateLargestPossibleRegion(); std::cout << "Mean is: " << statistics->GetMean() << " Sigma is: " << statistics->GetSigma() << std::endl; return EXIT_SUCCESS; }
31.728395
108
0.694942
kiranhs
056385addecf1c5c6e493ce4be2b08b27e21f22c
2,688
cpp
C++
src/effect.cpp
limal/nit
a1db3068d8f7426a1700e4729c247db97f9af9de
[ "Zlib" ]
2
2015-09-19T00:43:34.000Z
2016-05-31T19:33:22.000Z
src/effect.cpp
limal/nit
a1db3068d8f7426a1700e4729c247db97f9af9de
[ "Zlib" ]
null
null
null
src/effect.cpp
limal/nit
a1db3068d8f7426a1700e4729c247db97f9af9de
[ "Zlib" ]
null
null
null
/* Copyright (C) 2010 Lukasz Wolnik This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Lukasz Wolnik lukasz.wolnik@o2.pl */ #include "StdAfx.h" #include "effect.h" #include "graphics.h" using namespace nit; IEffect::IEffect(Graphics* gfx, wchar_t* filename) : effect(0) { ID3DXBuffer* errors = 0; IDirect3DDevice9* device = gfx->GetDevice(); D3DXCreateEffectFromFile(device, filename, 0, 0, D3DXSHADER_DEBUG, 0, &effect, &errors); // TODO // // Remove dependency to dxerr.lib from March 2009 DirectX SDK if (errors) { MessageBoxA(NULL, (char*)errors->GetBufferPointer(), 0, 0); } gfx->AddOnLostDevice(&MakeDelegate(this, &IEffect::OnLostDevice)); gfx->AddOnResetDevice(&MakeDelegate(this, &IEffect::OnResetDevice)); } IEffect::~IEffect() { effect->Release(); } void IEffect::Begin(unsigned int* num_passes) { effect->Begin(num_passes, 0); } void IEffect::BeginPass(unsigned int pass) { effect->BeginPass(pass); } void IEffect::CommitChanges() { effect->CommitChanges(); } void IEffect::End() { effect->End(); } void IEffect::EndPass() { effect->EndPass(); } void IEffect::GetParameterByName(char* name) { params[name] = effect->GetParameterByName(0, name); } void IEffect::GetTechniqueByName(char* name) { params[name] = effect->GetTechniqueByName(name); } void IEffect::OnLostDevice() { effect->OnLostDevice(); } void IEffect::OnResetDevice() { effect->OnResetDevice(); } void IEffect::SetFloat(char* name, const float f) { effect->SetFloat(params[name], f); } void IEffect::SetMatrix(char* name, const D3DXMATRIX *matrix) { effect->SetMatrix(params[name], matrix); } void IEffect::SetTechnique(char* name) { effect->SetTechnique(params[name]); } void IEffect::SetTexture(char* name, IDirect3DTexture9* texture) { effect->SetTexture(params[name], texture); } void IEffect::SetVector(char* name, const D3DXVECTOR4* vector) { effect->SetVector(params[name], vector); }
21.853659
89
0.739583
limal
05656729ed189d79f5ec7f09e2b886db97894a52
14,655
cc
C++
packager/media/formats/mp2t/pes_packet_generator_unittest.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5
2021-07-08T10:19:13.000Z
2021-09-10T09:17:57.000Z
packager/media/formats/mp2t/pes_packet_generator_unittest.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-21T21:17:55.000Z
2020-10-21T23:20:23.000Z
packager/media/formats/mp2t/pes_packet_generator_unittest.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2021-09-08T13:21:58.000Z
2022-03-01T05:57:44.000Z
// Copyright 2016 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include <gmock/gmock.h> #include <gtest/gtest.h> #include "packager/media/base/audio_stream_info.h" #include "packager/media/base/media_sample.h" #include "packager/media/base/text_stream_info.h" #include "packager/media/base/video_stream_info.h" #include "packager/media/codecs/aac_audio_specific_config.h" #include "packager/media/codecs/nal_unit_to_byte_stream_converter.h" #include "packager/media/formats/mp2t/pes_packet.h" #include "packager/media/formats/mp2t/pes_packet_generator.h" namespace shaka { namespace media { inline bool operator==(const SubsampleEntry& lhs, const SubsampleEntry& rhs) { return lhs.clear_bytes == rhs.clear_bytes && lhs.cipher_bytes == rhs.cipher_bytes; } namespace mp2t { using ::testing::_; using ::testing::DoAll; using ::testing::Eq; using ::testing::IsEmpty; using ::testing::Pointee; using ::testing::Return; using ::testing::SetArgPointee; namespace { const uint32_t kZeroTransportStreamTimestampOffset = 0; // Bogus data for testing. const uint8_t kAnyData[] = { 0x56, 0x87, 0x88, 0x33, 0x98, 0xAF, 0xE5, }; const bool kIsKeyFrame = true; const bool kEscapeEncryptedNalu = true; // Only Codec and extra data matter for this test. Other values are // bogus. const Codec kH264Codec = Codec::kCodecH264; const Codec kAacCodec = Codec::kCodecAAC; // TODO(rkuroiwa): It might make sense to inject factory functions to create // NalUnitToByteStreamConverter and AACAudioSpecificConfig so that these // extra data don't need to be copy pasted from other tests. const uint8_t kVideoExtraData[] = { 0x01, // configuration version (must be 1) 0x00, // AVCProfileIndication (bogus) 0x00, // profile_compatibility (bogus) 0x00, // AVCLevelIndication (bogus) 0xFF, // Length size minus 1 == 3 0xE1, // 1 sps. 0x00, 0x1D, // SPS length == 29 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x01, // 1 pps. 0x00, 0x0A, // PPS length == 10 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, }; // Basic profile. const uint8_t kAudioExtraData[] = {0x12, 0x10}; const int kTrackId = 0; const uint32_t kTimeScale = 90000; const uint64_t kDuration = 180000; const char kCodecString[] = "avc1"; const char kLanguage[] = "eng"; const uint32_t kWidth = 1280; const uint32_t kHeight = 720; const uint32_t kPixelWidth = 1; const uint32_t kPixelHeight = 1; const uint8_t kTransferCharacteristics = 0; const uint16_t kTrickPlayFactor = 1; const uint8_t kNaluLengthSize = 1; const bool kIsEncrypted = false; const uint8_t kSampleBits = 16; const uint8_t kNumChannels = 2; const uint32_t kSamplingFrequency = 44100; const uint64_t kSeekPreroll = 0; const uint64_t kCodecDelay = 0; const uint32_t kMaxBitrate = 320000; const uint32_t kAverageBitrate = 256000; class MockNalUnitToByteStreamConverter : public NalUnitToByteStreamConverter { public: MOCK_METHOD2(Initialize, bool(const uint8_t* decoder_configuration_data, size_t decoder_configuration_data_size)); MOCK_METHOD6(ConvertUnitToByteStreamWithSubsamples, bool(const uint8_t* sample, size_t sample_size, bool is_key_frame, bool escape_encrypted_nalu, std::vector<uint8_t>* output, std::vector<SubsampleEntry>* subsamples)); }; class MockAACAudioSpecificConfig : public AACAudioSpecificConfig { public: MOCK_METHOD1(Parse, bool(const std::vector<uint8_t>& data)); MOCK_CONST_METHOD3(ConvertToADTS, bool(const uint8_t* data, size_t data_size, std::vector<uint8_t>* audio_frame)); }; std::shared_ptr<VideoStreamInfo> CreateVideoStreamInfo(Codec codec) { std::shared_ptr<VideoStreamInfo> stream_info(new VideoStreamInfo( kTrackId, kTimeScale, kDuration, codec, H26xStreamFormat::kAnnexbByteStream, kCodecString, kVideoExtraData, arraysize(kVideoExtraData), kWidth, kHeight, kPixelWidth, kPixelHeight, kTransferCharacteristics, kTrickPlayFactor, kNaluLengthSize, kLanguage, kIsEncrypted)); return stream_info; } std::shared_ptr<AudioStreamInfo> CreateAudioStreamInfo(Codec codec) { std::shared_ptr<AudioStreamInfo> stream_info(new AudioStreamInfo( kTrackId, kTimeScale, kDuration, codec, kCodecString, kAudioExtraData, arraysize(kAudioExtraData), kSampleBits, kNumChannels, kSamplingFrequency, kSeekPreroll, kCodecDelay, kMaxBitrate, kAverageBitrate, kLanguage, kIsEncrypted)); return stream_info; } } // namespace class PesPacketGeneratorTest : public ::testing::Test { protected: PesPacketGeneratorTest() : generator_(kZeroTransportStreamTimestampOffset) {} void UseMockNalUnitToByteStreamConverter( std::unique_ptr<MockNalUnitToByteStreamConverter> mock_nal_unit_to_byte_stream_converter) { generator_.converter_ = std::move(mock_nal_unit_to_byte_stream_converter); } void UseMockAACAudioSpecificConfig( std::unique_ptr<MockAACAudioSpecificConfig> mock) { generator_.adts_converter_ = std::move(mock); } PesPacketGenerator generator_; }; TEST_F(PesPacketGeneratorTest, InitializeVideo) { std::shared_ptr<VideoStreamInfo> stream_info( CreateVideoStreamInfo(kH264Codec)); EXPECT_TRUE(generator_.Initialize(*stream_info)); } TEST_F(PesPacketGeneratorTest, InitializeVideoNonH264) { std::shared_ptr<VideoStreamInfo> stream_info( CreateVideoStreamInfo(Codec::kCodecVP9)); EXPECT_FALSE(generator_.Initialize(*stream_info)); } TEST_F(PesPacketGeneratorTest, InitializeAudio) { std::shared_ptr<AudioStreamInfo> stream_info( CreateAudioStreamInfo(kAacCodec)); EXPECT_TRUE(generator_.Initialize(*stream_info)); } TEST_F(PesPacketGeneratorTest, InitializeAudioNonAac) { std::shared_ptr<AudioStreamInfo> stream_info( CreateAudioStreamInfo(Codec::kCodecOpus)); EXPECT_FALSE(generator_.Initialize(*stream_info)); } // Text is not supported yet. TEST_F(PesPacketGeneratorTest, InitializeTextInfo) { std::shared_ptr<TextStreamInfo> stream_info(new TextStreamInfo( kTrackId, kTimeScale, kDuration, kCodecText, kCodecString, std::string(), kWidth, kHeight, kLanguage)); EXPECT_FALSE(generator_.Initialize(*stream_info)); } TEST_F(PesPacketGeneratorTest, AddVideoSample) { std::shared_ptr<VideoStreamInfo> stream_info( CreateVideoStreamInfo(kH264Codec)); EXPECT_TRUE(generator_.Initialize(*stream_info)); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); std::shared_ptr<MediaSample> sample = MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame); const uint32_t kPts = 12345; const uint32_t kDts = 12300; sample->set_pts(kPts); sample->set_dts(kDts); std::vector<uint8_t> expected_data(kAnyData, kAnyData + arraysize(kAnyData)); std::unique_ptr<MockNalUnitToByteStreamConverter> mock( new MockNalUnitToByteStreamConverter()); EXPECT_CALL(*mock, ConvertUnitToByteStreamWithSubsamples( _, arraysize(kAnyData), kIsKeyFrame, kEscapeEncryptedNalu, _, Pointee(IsEmpty()))) .WillOnce(DoAll(SetArgPointee<4>(expected_data), Return(true))); UseMockNalUnitToByteStreamConverter(std::move(mock)); EXPECT_TRUE(generator_.PushSample(*sample)); EXPECT_EQ(1u, generator_.NumberOfReadyPesPackets()); std::unique_ptr<PesPacket> pes_packet = generator_.GetNextPesPacket(); ASSERT_TRUE(pes_packet); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); EXPECT_EQ(0xe0, pes_packet->stream_id()); EXPECT_EQ(kPts, pes_packet->pts()); EXPECT_EQ(kDts, pes_packet->dts()); EXPECT_EQ(expected_data, pes_packet->data()); EXPECT_TRUE(generator_.Flush()); } TEST_F(PesPacketGeneratorTest, AddEncryptedVideoSample) { std::shared_ptr<VideoStreamInfo> stream_info( CreateVideoStreamInfo(kH264Codec)); EXPECT_TRUE(generator_.Initialize(*stream_info)); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); std::shared_ptr<MediaSample> sample = MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame); const uint32_t kPts = 12345; const uint32_t kDts = 12300; sample->set_pts(kPts); sample->set_dts(kDts); const std::vector<uint8_t> key_id(16, 0); const std::vector<uint8_t> iv(8, 0); const std::vector<SubsampleEntry> subsamples = { SubsampleEntry(0x12, 0x110), SubsampleEntry(0x122, 0x11000)}; std::unique_ptr<DecryptConfig> decrypt_config( new DecryptConfig(key_id, iv, subsamples)); sample->set_is_encrypted(true); sample->set_decrypt_config(std::move(decrypt_config)); std::vector<uint8_t> expected_data(kAnyData, kAnyData + arraysize(kAnyData)); std::unique_ptr<MockNalUnitToByteStreamConverter> mock( new MockNalUnitToByteStreamConverter()); EXPECT_CALL(*mock, ConvertUnitToByteStreamWithSubsamples( _, arraysize(kAnyData), kIsKeyFrame, kEscapeEncryptedNalu, _, Pointee(Eq(subsamples)))) .WillOnce(DoAll(SetArgPointee<4>(expected_data), Return(true))); UseMockNalUnitToByteStreamConverter(std::move(mock)); EXPECT_TRUE(generator_.PushSample(*sample)); EXPECT_EQ(1u, generator_.NumberOfReadyPesPackets()); std::unique_ptr<PesPacket> pes_packet = generator_.GetNextPesPacket(); ASSERT_TRUE(pes_packet); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); EXPECT_EQ(0xe0, pes_packet->stream_id()); EXPECT_EQ(kPts, pes_packet->pts()); EXPECT_EQ(kDts, pes_packet->dts()); EXPECT_EQ(expected_data, pes_packet->data()); EXPECT_TRUE(generator_.Flush()); } TEST_F(PesPacketGeneratorTest, AddVideoSampleFailedToConvert) { std::shared_ptr<VideoStreamInfo> stream_info( CreateVideoStreamInfo(kH264Codec)); EXPECT_TRUE(generator_.Initialize(*stream_info)); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); std::shared_ptr<MediaSample> sample = MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame); std::vector<uint8_t> expected_data(kAnyData, kAnyData + arraysize(kAnyData)); std::unique_ptr<MockNalUnitToByteStreamConverter> mock( new MockNalUnitToByteStreamConverter()); EXPECT_CALL(*mock, ConvertUnitToByteStreamWithSubsamples( _, arraysize(kAnyData), kIsKeyFrame, kEscapeEncryptedNalu, _, Pointee(IsEmpty()))) .WillOnce(Return(false)); UseMockNalUnitToByteStreamConverter(std::move(mock)); EXPECT_FALSE(generator_.PushSample(*sample)); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); EXPECT_TRUE(generator_.Flush()); } TEST_F(PesPacketGeneratorTest, AddAudioSample) { std::shared_ptr<AudioStreamInfo> stream_info( CreateAudioStreamInfo(kAacCodec)); EXPECT_TRUE(generator_.Initialize(*stream_info)); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); std::shared_ptr<MediaSample> sample = MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame); std::vector<uint8_t> expected_data(kAnyData, kAnyData + arraysize(kAnyData)); std::unique_ptr<MockAACAudioSpecificConfig> mock( new MockAACAudioSpecificConfig()); EXPECT_CALL(*mock, ConvertToADTS(sample->data(), sample->data_size(), _)) .WillOnce(DoAll(SetArgPointee<2>(expected_data), Return(true))); UseMockAACAudioSpecificConfig(std::move(mock)); EXPECT_TRUE(generator_.PushSample(*sample)); EXPECT_EQ(1u, generator_.NumberOfReadyPesPackets()); std::unique_ptr<PesPacket> pes_packet = generator_.GetNextPesPacket(); ASSERT_TRUE(pes_packet); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); EXPECT_EQ(0xc0, pes_packet->stream_id()); EXPECT_EQ(expected_data, pes_packet->data()); EXPECT_TRUE(generator_.Flush()); } TEST_F(PesPacketGeneratorTest, AddAudioSampleFailedToConvert) { std::shared_ptr<AudioStreamInfo> stream_info( CreateAudioStreamInfo(kAacCodec)); EXPECT_TRUE(generator_.Initialize(*stream_info)); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); std::shared_ptr<MediaSample> sample = MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame); std::unique_ptr<MockAACAudioSpecificConfig> mock( new MockAACAudioSpecificConfig()); EXPECT_CALL(*mock, ConvertToADTS(_, _, _)).WillOnce(Return(false)); UseMockAACAudioSpecificConfig(std::move(mock)); EXPECT_FALSE(generator_.PushSample(*sample)); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); EXPECT_TRUE(generator_.Flush()); } // Because TS has to use 90000 as its timescale, make sure that the timestamps // are scaled. TEST_F(PesPacketGeneratorTest, TimeStampScaling) { const uint32_t kTestTimescale = 1000; std::shared_ptr<VideoStreamInfo> stream_info(new VideoStreamInfo( kTrackId, kTestTimescale, kDuration, kH264Codec, H26xStreamFormat::kAnnexbByteStream, kCodecString, kVideoExtraData, arraysize(kVideoExtraData), kWidth, kHeight, kPixelWidth, kPixelHeight, kTransferCharacteristics, kTrickPlayFactor, kNaluLengthSize, kLanguage, kIsEncrypted)); EXPECT_TRUE(generator_.Initialize(*stream_info)); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); std::shared_ptr<MediaSample> sample = MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame); const uint32_t kPts = 5000; const uint32_t kDts = 4000; sample->set_pts(kPts); sample->set_dts(kDts); std::unique_ptr<MockNalUnitToByteStreamConverter> mock( new MockNalUnitToByteStreamConverter()); EXPECT_CALL(*mock, ConvertUnitToByteStreamWithSubsamples( _, arraysize(kAnyData), kIsKeyFrame, kEscapeEncryptedNalu, _, Pointee(IsEmpty()))) .WillOnce(Return(true)); UseMockNalUnitToByteStreamConverter(std::move(mock)); EXPECT_TRUE(generator_.PushSample(*sample)); EXPECT_EQ(1u, generator_.NumberOfReadyPesPackets()); std::unique_ptr<PesPacket> pes_packet = generator_.GetNextPesPacket(); ASSERT_TRUE(pes_packet); EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets()); // Since 90000 (MPEG2 timescale) / 1000 (input timescale) is 90, the // timestamps should be multipled by 90. EXPECT_EQ(kPts * 90, pes_packet->pts()); EXPECT_EQ(kDts * 90, pes_packet->dts()); EXPECT_TRUE(generator_.Flush()); } } // namespace mp2t } // namespace media } // namespace shaka
36.729323
80
0.740293
koln67
0565a1b5e9a933f750b3496639ca912fae31b108
709
cpp
C++
libsnes/bsnes/snes/alt/dsp/serialization.cpp
ircluzar/BizhawkLegacy-Vanguard
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
[ "MIT" ]
null
null
null
libsnes/bsnes/snes/alt/dsp/serialization.cpp
ircluzar/BizhawkLegacy-Vanguard
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
[ "MIT" ]
null
null
null
libsnes/bsnes/snes/alt/dsp/serialization.cpp
ircluzar/BizhawkLegacy-Vanguard
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
[ "MIT" ]
null
null
null
#ifdef DSP_CPP static void dsp_state_save(unsigned char **out, void *in, size_t size) { memcpy(*out, in, size); *out += size; } static void dsp_state_load(unsigned char **in, void *out, size_t size) { memcpy(out, *in, size); *in += size; } void DSP::serialize(serializer &s) { Processor::serialize(s); s.array(samplebuffer); unsigned char state[SPC_DSP::state_size]; unsigned char *p = state; memset(&state, 0, SPC_DSP::state_size); if(s.mode() == serializer::Save) { spc_dsp.copy_state(&p, dsp_state_save); s.array(state); } else if(s.mode() == serializer::Load) { s.array(state); spc_dsp.copy_state(&p, dsp_state_load); } else { s.array(state); } } #endif
22.15625
72
0.651622
ircluzar
0566d988bade4998cde6afb234a1d84565515983
215
hxx
C++
src/public_include/decaf/eddsa.tmpl.hxx
nondejus/ed448goldilocks
dc09d56accd631bd6786e87fefe422eb2d6898a7
[ "MIT" ]
null
null
null
src/public_include/decaf/eddsa.tmpl.hxx
nondejus/ed448goldilocks
dc09d56accd631bd6786e87fefe422eb2d6898a7
[ "MIT" ]
null
null
null
src/public_include/decaf/eddsa.tmpl.hxx
nondejus/ed448goldilocks
dc09d56accd631bd6786e87fefe422eb2d6898a7
[ "MIT" ]
null
null
null
/** * EdDSA crypto routines, metaheader. */ namespace decaf { enum Prehashed { PURE, PREHASHED }; } $("\n".join([ "#include <decaf/ed%s.hxx>" % g for g in sorted([c["bits"] for _,c in curve.iteritems()]) ]))
23.888889
93
0.609302
nondejus
05676a0da268dacdd6de29a9f16ab2151852e4af
4,664
cpp
C++
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/corelib/global/qmalloc.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/corelib/global/qmalloc.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/corelib/global/qmalloc.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qplatformdefs.h" #include <stdlib.h> #include <string.h> /* Define the container allocation functions in a separate file, so that our users can easily override them. */ QT_BEGIN_NAMESPACE #if !QT_DEPRECATED_SINCE(5, 0) // Make sure they're defined to be exported Q_CORE_EXPORT void *qMalloc(size_t size) Q_ALLOC_SIZE(1); Q_CORE_EXPORT void qFree(void *ptr); Q_CORE_EXPORT void *qRealloc(void *ptr, size_t size) Q_ALLOC_SIZE(2); #endif void *qMalloc(size_t size) { return ::malloc(size); } void qFree(void *ptr) { ::free(ptr); } void *qRealloc(void *ptr, size_t size) { return ::realloc(ptr, size); } void *qMallocAligned(size_t size, size_t alignment) { return qReallocAligned(0, size, 0, alignment); } void *qReallocAligned(void *oldptr, size_t newsize, size_t oldsize, size_t alignment) { // fake an aligned allocation void *actualptr = oldptr ? static_cast<void **>(oldptr)[-1] : 0; if (alignment <= sizeof(void*)) { // special, fast case void **newptr = static_cast<void **>(realloc(actualptr, newsize + sizeof(void*))); if (!newptr) return 0; if (newptr == actualptr) { // realloc succeeded without reallocating return oldptr; } *newptr = newptr; return newptr + 1; } // malloc returns pointers aligned at least at sizeof(size_t) boundaries // but usually more (8- or 16-byte boundaries). // So we overallocate by alignment-sizeof(size_t) bytes, so we're guaranteed to find a // somewhere within the first alignment-sizeof(size_t) that is properly aligned. // However, we need to store the actual pointer, so we need to allocate actually size + // alignment anyway. void *real = realloc(actualptr, newsize + alignment); if (!real) return 0; quintptr faked = reinterpret_cast<quintptr>(real) + alignment; faked &= ~(alignment - 1); void **faked_ptr = reinterpret_cast<void **>(faked); if (oldptr) { qptrdiff oldoffset = static_cast<char *>(oldptr) - static_cast<char *>(actualptr); qptrdiff newoffset = reinterpret_cast<char *>(faked_ptr) - static_cast<char *>(real); if (oldoffset != newoffset) memmove(faked_ptr, static_cast<char *>(real) + oldoffset, qMin(oldsize, newsize)); } // now save the value of the real pointer at faked-sizeof(void*) // by construction, alignment > sizeof(void*) and is a power of 2, so // faked-sizeof(void*) is properly aligned for a pointer faked_ptr[-1] = real; return faked_ptr; } void qFreeAligned(void *ptr) { if (!ptr) return; void **ptr2 = static_cast<void **>(ptr); free(ptr2[-1]); } QT_END_NAMESPACE
33.553957
94
0.673456
GrinCash
0568e69a2d055267a721157689224fc5b3a29411
7,452
cpp
C++
src/cpu/resampling/ref_resampling.cpp
bhipple/mkl-dnn
ed1cf723ee94cf95b77af55fe1309374363b8edd
[ "Apache-2.0" ]
1
2020-09-18T04:34:16.000Z
2020-09-18T04:34:16.000Z
src/cpu/resampling/ref_resampling.cpp
awesomemachinelearning/mkl-dnn
ed1cf723ee94cf95b77af55fe1309374363b8edd
[ "Apache-2.0" ]
null
null
null
src/cpu/resampling/ref_resampling.cpp
awesomemachinelearning/mkl-dnn
ed1cf723ee94cf95b77af55fe1309374363b8edd
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <assert.h> #include <float.h> #include <math.h> #include "c_types_map.hpp" #include "dnnl_thread.hpp" #include "math_utils.hpp" #include "type_helpers.hpp" #include "ref_resampling.hpp" #include "resampling_utils.hpp" namespace dnnl { namespace impl { namespace cpu { static inline dim_t get_offset( const memory_desc_wrapper &data_d, int n, int c, int d, int h, int w) { if (data_d.ndims() == 5) return data_d.off(n, c, d, h, w); else if (data_d.ndims() == 4) return data_d.off(n, c, h, w); else return data_d.off(n, c, w); } using namespace resampling_utils; template <impl::data_type_t data_type> void ref_resampling_fwd_t<data_type>::execute_forward( const exec_ctx_t &ctx) const { if (this->pd()->has_zero_dim_memory()) return; const auto src = CTX_IN_MEM(const data_t *, DNNL_ARG_SRC); auto dst = CTX_OUT_MEM(data_t *, DNNL_ARG_DST); const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper dst_d(pd()->dst_md()); const auto alg = pd()->desc()->alg_kind; const int MB = pd()->MB(); const int C = pd()->C(); const int ID = pd()->ID(); const int IH = pd()->IH(); const int IW = pd()->IW(); const int OD = pd()->OD(); const int OH = pd()->OH(); const int OW = pd()->OW(); const float FD = pd()->FD(); const float FH = pd()->FH(); const float FW = pd()->FW(); auto lin_interp = [&](float c0, float c1, float w) { return c0 * w + c1 * (1 - w); }; auto bilin_interp = [&](float c00, float c01, float c10, float c11, float w0, float w1) { return lin_interp( lin_interp(c00, c10, w0), lin_interp(c01, c11, w0), w1); }; auto trilin_interp = [&](float c000, float c010, float c100, float c110, float c001, float c011, float c101, float c111, float w0, float w1, float w2) { return lin_interp(bilin_interp(c000, c010, c100, c110, w0, w1), bilin_interp(c001, c011, c101, c111, w0, w1), w2); }; parallel_nd(MB, C, OD, OH, OW, [&](dim_t mb, dim_t ch, dim_t od, dim_t oh, dim_t ow) { if (alg == alg_kind::resampling_nearest) { dim_t id = nearest_idx(od, FD), ih = nearest_idx(oh, FH), iw = nearest_idx(ow, FW); dst[get_offset(dst_d, mb, ch, od, oh, ow)] = src[get_offset(src_d, mb, ch, id, ih, iw)]; } else if (alg == alg_kind::resampling_linear) { // Trilinear interpolation (linear interpolation on a 3D spatial // tensor) can be expressed as linear interpolation along // dimension x followed by interpolation along dimension y and z // C011--C11--C111 // - - | // - - | //C001--C01--C111 | // - .C - C110 // - - - // - - - //C000--C00--C100 auto id = linear_coeffs_t(od, FD, ID); auto iw = linear_coeffs_t(ow, FW, IW); auto ih = linear_coeffs_t(oh, FH, IH); dim_t src_l[8] = {0}; for_(int i = 0; i < 2; i++) for_(int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) { src_l[4 * i + 2 * j + k] = src[get_offset(src_d, mb, ch, id.idx[i], ih.idx[j], iw.idx[k])]; } dst[get_offset(dst_d, mb, ch, od, oh, ow)] = trilin_interp(src_l[0], src_l[1], src_l[2], src_l[3], src_l[4], src_l[5], src_l[6], src_l[7], id.wei[0], ih.wei[0], iw.wei[0]); } }); } template struct ref_resampling_fwd_t<data_type::f32>; template struct ref_resampling_fwd_t<data_type::bf16>; template <impl::data_type_t data_type> void ref_resampling_bwd_t<data_type>::execute_backward( const exec_ctx_t &ctx) const { if (this->pd()->has_zero_dim_memory()) return; const auto diff_dst = CTX_IN_MEM(const data_t *, DNNL_ARG_DIFF_DST); auto diff_src = CTX_OUT_MEM(data_t *, DNNL_ARG_DIFF_SRC); const memory_desc_wrapper diff_src_d(pd()->diff_src_md()); const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md()); const auto alg = pd()->desc()->alg_kind; const int MB = pd()->MB(); const int C = pd()->C(); const int ID = pd()->ID(); const int IH = pd()->IH(); const int IW = pd()->IW(); const int OD = pd()->OD(); const int OH = pd()->OH(); const int OW = pd()->OW(); const float FD = pd()->FD(); const float FH = pd()->FH(); const float FW = pd()->FW(); parallel_nd(MB, C, ID, IH, IW, [&](dim_t mb, dim_t ch, dim_t id, dim_t ih, dim_t iw) { diff_src[get_offset(diff_src_d, mb, ch, id, ih, iw)] = 0.f; }); parallel_nd(MB, C, [&](dim_t mb, dim_t ch) { for_(int od = 0; od < OD; ++od) for_(int oh = 0; oh < OH; ++oh) for (int ow = 0; ow < OW; ++ow) { if (alg == alg_kind::resampling_nearest) { dim_t id = nearest_idx(od, FD), ih = nearest_idx(oh, FH), iw = nearest_idx(ow, FW); diff_src[get_offset(diff_src_d, mb, ch, id, ih, iw)] += diff_dst[get_offset(diff_dst_d, mb, ch, od, oh, ow)]; } else if (alg == alg_kind::resampling_linear) { auto id = linear_coeffs_t(od, FD, ID); auto iw = linear_coeffs_t(ow, FW, IW); auto ih = linear_coeffs_t(oh, FH, IH); // accessor for source values on a cubic lattice data_t dd = diff_dst[get_offset(diff_dst_d, mb, ch, od, oh, ow)]; for_(int i = 0; i < 2; i++) for_(int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) { auto off = get_offset(diff_src_d, mb, ch, id.idx[i], ih.idx[j], iw.idx[k]); diff_src[off] += dd * id.wei[i] * ih.wei[j] * iw.wei[k]; } } } }); } template struct ref_resampling_bwd_t<data_type::f32>; template struct ref_resampling_bwd_t<data_type::bf16>; } // namespace cpu } // namespace impl } // namespace dnnl // vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
39.428571
84
0.510735
bhipple
056e10daebea881f4612325d74584eca8bd8ec2b
5,767
cpp
C++
tests/test_os_char_driver.cpp
KKoovalsky/JunglesOsStructs
33b3341aa7d99b152a6cb95bc3016bf78d6f5535
[ "MIT" ]
null
null
null
tests/test_os_char_driver.cpp
KKoovalsky/JunglesOsStructs
33b3341aa7d99b152a6cb95bc3016bf78d6f5535
[ "MIT" ]
null
null
null
tests/test_os_char_driver.cpp
KKoovalsky/JunglesOsStructs
33b3341aa7d99b152a6cb95bc3016bf78d6f5535
[ "MIT" ]
null
null
null
/** * @file test_os_char_driver.cpp * @brief Tests os_char_driver template * @author Kacper Kowalski - kacper.s.kowalski@gmail.com */ #include "os_char_driver.hpp" #include "os_task.hpp" #include "unity.h" #include <array> #include <csignal> #include <functional> #include <iostream> #include <string> #include <string_view> #include <vector> using namespace jungles; #define SIGNAL_TX SIGRTMIN #define SIGNAL_RX (SIGRTMIN + 1) // -------------------------------------------------------------------------------------------------------------------- // DECLARATION OF THE TEST CASES // -------------------------------------------------------------------------------------------------------------------- static void UNIT_TEST_1_block_on_read_and_unblock_on_message_received(); static void UNIT_TEST_2_blocking_write_multiple_string_types(); // -------------------------------------------------------------------------------------------------------------------- // DECLARATION OF PRIVATE FUNCTIONS AND VARIABLES // -------------------------------------------------------------------------------------------------------------------- static std::function<void(void)> tx_isr_handler, rx_isr_handler; static std::function<void(char)> byte_sender; static void helper_set_tx_isr_handler(std::function<void(void)> f); static void helper_set_rx_isr_handler(std::function<void(void)> f); static void helper_set_byte_sender(std::function<void(char)> f); static bool tx_isr_enabled; static void tx_isr_handler_callback(int signal); static void rx_isr_handler_callback(int signal); static void tx_it_enable(); static void tx_it_disable(); static void rx_it_enable(); static void rx_it_disable(); static void byte_send(char c); // -------------------------------------------------------------------------------------------------------------------- // EXECUTION OF THE TESTS // -------------------------------------------------------------------------------------------------------------------- void test_os_char_driver() { std::signal(SIGNAL_TX, tx_isr_handler_callback); std::signal(SIGNAL_RX, rx_isr_handler_callback); RUN_TEST(UNIT_TEST_1_block_on_read_and_unblock_on_message_received); RUN_TEST(UNIT_TEST_2_blocking_write_multiple_string_types); std::signal(SIGNAL_TX, SIG_DFL); std::signal(SIGNAL_RX, SIG_DFL); } // -------------------------------------------------------------------------------------------------------------------- // DEFINITION OF THE TEST CASES // -------------------------------------------------------------------------------------------------------------------- static void UNIT_TEST_1_block_on_read_and_unblock_on_message_received() { os_char_driver<64, 16> chardrv{tx_it_enable, tx_it_disable, rx_it_enable, rx_it_disable, byte_send}; auto reader_task_handle = os_task_get_current_task_handle(); os_task sync_reader_task( [reader_task_handle, &chardrv]() { // Ensure readline() will be called os_task_yield(); os_task_yield(); os_task_yield(); for (unsigned state = os_task_state_running; state != os_task_state_blocked && state != os_task_state_blocked; state = os_task_get_state(reader_task_handle)) os_delay_ms(1); helper_set_rx_isr_handler([&chardrv]() { static constexpr char test_string_rcvd[] = "makapaka"; static const char *it = test_string_rcvd; static constexpr const char *end = test_string_rcvd + std::distance(std::begin(test_string_rcvd), std::end(test_string_rcvd)); if (it != end) { chardrv.rx_isr_handler(*it++); std::raise(SIGNAL_RX); } }); std::raise(SIGNAL_RX); }, "sync_reader", 256, 1); auto line = chardrv.readline(os_no_timeout); TEST_ASSERT_EQUAL_STRING("makapaka", line.c_str()); os_task_yield(); } static void UNIT_TEST_2_blocking_write_multiple_string_types() { os_char_driver<64, 16> chardrv{tx_it_enable, tx_it_disable, rx_it_enable, rx_it_disable, byte_send}; std::string s{"std::string"}; std::vector v{'s', 't', 'd', ':', ':', 'v', 'e', 'c', 't', 'o', 'r'}; std::array<char, 10> a{'s', 't', 'd', ':', ':', 'a', 'r', 'r', 'a', 'y'}; std::string sv{"std::string_view"}; std::string result; helper_set_byte_sender([&result](char c) { result += c; }); helper_set_tx_isr_handler([&chardrv]() { chardrv.tx_isr_handler(); }); chardrv.write(s, v, a, sv); TEST_ASSERT_EQUAL_STRING("std::stringstd::vectorstd::arraystd::string_view", result.c_str()); } // -------------------------------------------------------------------------------------------------------------------- // DEFINITION OF PRIVATE FUNCTIONS // -------------------------------------------------------------------------------------------------------------------- static void helper_set_tx_isr_handler(std::function<void(void)> f) { tx_isr_handler = f; } static void helper_set_rx_isr_handler(std::function<void(void)> f) { rx_isr_handler = f; } static void tx_isr_handler_callback(int signal) { tx_isr_handler(); if (tx_isr_enabled) std::raise(SIGNAL_TX); } static void rx_isr_handler_callback(int signal) { rx_isr_handler(); } static void helper_set_byte_sender(std::function<void(char)> f) { byte_sender = f; } static void tx_it_enable() { tx_isr_enabled = true; std::raise(SIGNAL_TX); } static void tx_it_disable() { tx_isr_enabled = false; } static void rx_it_enable() { } static void rx_it_disable() { } static void byte_send(char c) { byte_sender(c); }
33.923529
119
0.542396
KKoovalsky
056e7d6bc7b38f40689aba0e0d4206d0501718ae
3,742
cpp
C++
DearPyGui/src/core/AppItems/textures/mvTextureContainer.cpp
iFreilicht/DearPyGui
f9d45f6c0ace71de32fcd8bbfa7fb6d347cb6912
[ "MIT" ]
null
null
null
DearPyGui/src/core/AppItems/textures/mvTextureContainer.cpp
iFreilicht/DearPyGui
f9d45f6c0ace71de32fcd8bbfa7fb6d347cb6912
[ "MIT" ]
null
null
null
DearPyGui/src/core/AppItems/textures/mvTextureContainer.cpp
iFreilicht/DearPyGui
f9d45f6c0ace71de32fcd8bbfa7fb6d347cb6912
[ "MIT" ]
null
null
null
#include "mvTextureContainer.h" #include "mvPythonExceptions.h" #include "mvLog.h" #include "mvStaticTexture.h" #include "mvDynamicTexture.h" namespace Marvel { void mvTextureContainer::InsertParser(std::map<std::string, mvPythonParser>* parsers) { mvPythonParser parser(mvPyDataType::String, "Undocumented function", { "Textures", "Widgets" }); mvAppItem::AddCommonArgs(parser, (CommonParserArgs)( MV_PARSER_ARG_ID | MV_PARSER_ARG_SHOW) ); parser.finalize(); parsers->insert({ s_command, parser }); } mvTextureContainer::mvTextureContainer(const std::string& name) : mvAppItem(name) { m_show = false; } void mvTextureContainer::draw(ImDrawList* drawlist, float x, float y) { for (auto& item : m_children[1]) item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); if (m_show) show_debugger(); } bool mvTextureContainer::canChildBeAdded(mvAppItemType type) { if (type == mvAppItemType::mvStaticTexture) return true; if (type == mvAppItemType::mvDynamicTexture) return true; mvThrowPythonError(1000, "Drawing children must be draw commands only."); MV_ITEM_REGISTRY_ERROR("Drawing children must be draw commands only."); assert(false); return false; } void mvTextureContainer::onChildRemoved(mvRef<mvAppItem> item) { m_selection = -1; } void mvTextureContainer::onChildrenRemoved() { m_selection = -1; } void mvTextureContainer::show_debugger() { ImGui::PushID(this); ImGui::SetNextWindowSize(ImVec2(500, 500), ImGuiCond_FirstUseEver); if (ImGui::Begin(m_label.c_str(), &m_show)) { ImGui::Text("Textures"); ImGui::BeginChild("##TextureStorageChild", ImVec2(400, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar); int index = 0; for (auto& texture : m_children[1]) { bool status = false; void* textureRaw = nullptr; if(texture->getType() == mvAppItemType::mvStaticTexture) textureRaw = static_cast<mvStaticTexture*>(texture.get())->getRawTexture(); else textureRaw = static_cast<mvDynamicTexture*>(texture.get())->getRawTexture(); ImGui::Image(textureRaw, ImVec2(25, 25)); ImGui::SameLine(); if (ImGui::Selectable(texture->m_name.c_str(), &status)) m_selection = index; ++index; } ImGui::EndChild(); if (m_selection != -1) { ImGui::SameLine(); ImGui::BeginGroup(); ImGui::BeginGroup(); ImGui::Text("Width: %d", m_children[1][m_selection]->getWidth()); ImGui::Text("Height: %d", m_children[1][m_selection]->getHeight()); ImGui::Text("Type: %s", m_children[1][m_selection]->getType() == mvAppItemType::mvStaticTexture ? "static" : "dynamic"); ImGui::EndGroup(); ImGui::SameLine(); void* textureRaw = nullptr; if (m_children[1][m_selection]->getType() == mvAppItemType::mvStaticTexture) textureRaw = static_cast<mvStaticTexture*>(m_children[1][m_selection].get())->getRawTexture(); else textureRaw = static_cast<mvDynamicTexture*>(m_children[1][m_selection].get())->getRawTexture(); ImGui::Image(textureRaw, ImVec2((float)m_children[1][m_selection]->getWidth(), (float)m_children[1][m_selection]->getHeight())); ImPlot::PushStyleColor(ImPlotCol_FrameBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); if (ImPlot::BeginPlot("##texture plot", 0, 0, ImVec2(-1, -1), ImPlotFlags_NoTitle | ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_Equal)) { ImPlot::PlotImage(m_children[1][m_selection]->m_name.c_str(), textureRaw, ImPlotPoint(0.0, 0.0), ImPlotPoint(m_children[1][m_selection]->getWidth(), m_children[1][m_selection]->getHeight())); ImPlot::EndPlot(); } ImPlot::PopStyleColor(); ImGui::EndGroup(); } } ImGui::End(); ImGui::PopID(); } }
27.115942
132
0.689471
iFreilicht
057034491dd499f87a2e96c9394bc97ddf53ba3f
1,215
cc
C++
src/ast/ArrayLiteral.cc
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
1
2020-01-06T09:43:56.000Z
2020-01-06T09:43:56.000Z
src/ast/ArrayLiteral.cc
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
src/ast/ArrayLiteral.cc
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
#include "ArrayLiteral.hh" void ArrayLiteral::add_expression(ptr_t<Expression> &expression) { m_expressions.push_back(std::move(expression)); } void ArrayLiteral::analyze(Scope *scope) { m_type.change_kind(Kind::ARRAY); if (m_expressions.empty()) { m_type.change_primitive(Primitive::DONT_CARE); return; } m_expressions.front()->analyze(scope); Type first = m_expressions.front()->type(); for (unsigned i = 1; i < m_expressions.size(); ++i) { auto &current = m_expressions.at(i); current->analyze(scope); if (!current->is_literal()) { error::add_semantic_error("Array literals require literal values", source_ref); } if (current->type() != first) { error::add_semantic_error("Mismatched types in array literal", source_ref); } } m_type.change_primitive(first.primitive()); } std::string ArrayLiteral::dump(unsigned indent) const { std::ostringstream oss {}; oss << util::indent(indent) << name() << " [" << std::endl; for (auto &x : m_expressions) { oss << x->dump(indent + 1) << std::endl; } oss << util::indent(indent) << "]"; return oss.str(); }
27.613636
91
0.614815
walecome
0574c46d401ff119ce5fb2146c678e1a77fbb4d4
4,208
cc
C++
squid/squid3-3.3.8.spaceify/src/globals.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/globals.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/globals.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
#include "squid.h" /* * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * 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, USA. * */ #include "acl/AclDenyInfoList.h" #include "CacheDigest.h" #include "defines.h" #include "hash.h" #include "IoStats.h" #include "rfc2181.h" #if HAVE_STDIO_H #include <stdio.h> #endif char *ConfigFile = NULL; char tmp_error_buf[ERROR_BUF_SZ]; char ThisCache[RFC2181_MAXHOSTNAMELEN << 1]; char ThisCache2[RFC2181_MAXHOSTNAMELEN << 1]; char config_input_line[BUFSIZ]; const char *DefaultConfigFile = DEFAULT_CONFIG_FILE; const char *cfg_filename = NULL; const char *dash_str = "-"; const char *null_string = ""; const char *version_string = VERSION; const char *appname_string = PACKAGE; char const *visible_appname_string = NULL; int Biggest_FD = -1; int Number_FD = 0; int Opening_FD = 0; int NDnsServersAlloc = 0; int RESERVED_FD; int Squid_MaxFD = SQUID_MAXFD; int config_lineno = 0; int do_mallinfo = 0; int opt_reuseaddr = 1; int neighbors_do_private_keys = 1; int opt_catch_signals = 1; int opt_foreground_rebuild = 0; char *opt_forwarded_for = NULL; int opt_reload_hit_only = 0; int opt_udp_hit_obj = 0; int opt_create_swap_dirs = 0; int opt_store_doublecheck = 0; int syslog_enable = 0; int DnsSocketA = -1; int DnsSocketB = -1; int n_disk_objects = 0; IoStats IOStats; AclDenyInfoList *DenyInfoList = NULL; struct timeval squid_start; int starting_up = 1; int shutting_down = 0; int reconfiguring = 0; time_t hit_only_mode_until = 0; double request_failure_ratio = 0.0; int store_hash_buckets = 0; hash_table *store_table = NULL; int hot_obj_count = 0; int CacheDigestHashFuncCount = 4; CacheDigest *store_digest = NULL; const char *StoreDigestFileName = "store_digest"; const char *StoreDigestMimeStr = "application/cache-digest"; const char *MultipartMsgBoundaryStr = "Unique-Squid-Separator"; #if USE_HTTP_VIOLATIONS int refresh_nocache_hack = 0; #endif int store_open_disk_fd = 0; int store_swap_low = 0; int store_swap_high = 0; size_t store_pages_max = 0; int64_t store_maxobjsize = -1; hash_table *proxy_auth_username_cache = NULL; int incoming_sockets_accepted; #if _SQUID_MSWIN_ unsigned int WIN32_Socks_initialized = 0; #endif #if _SQUID_WINDOWS_ unsigned int WIN32_OS_version = 0; char *WIN32_OS_string = NULL; char *WIN32_Service_name = NULL; char *WIN32_Command_Line = NULL; char *WIN32_Service_Command_Line = NULL; unsigned int WIN32_run_mode = _WIN_SQUID_RUN_MODE_INTERACTIVE; #endif #if HAVE_SBRK void *sbrk_start = 0; #endif int ssl_ex_index_server = -1; int ssl_ctx_ex_index_dont_verify_domain = -1; int ssl_ex_index_cert_error_check = -1; int ssl_ex_index_ssl_error_detail = -1; int ssl_ex_index_ssl_peeked_cert = -1; int ssl_ex_index_ssl_errors = -1; const char *external_acl_message = NULL; int opt_send_signal = -1; int opt_no_daemon = 0; int opt_parse_cfg_only = 0; /// current Squid process number (e.g., 4). /// Zero for SMP-unaware code and in no-SMP mode. int KidIdentifier = 0;
30.492754
72
0.753327
spaceify
05757127a7838beddc1bf07edd5253cb2ef89b80
4,301
cpp
C++
CarbonRender/Src/CRCinematicController.cpp
lanyu8/CarbonRender
dcd0a5d53ee2c458ad53c4e690359c250219ee22
[ "MIT" ]
44
2017-07-23T08:38:19.000Z
2022-03-27T02:53:10.000Z
CarbonRender/Src/CRCinematicController.cpp
lanyu8/CarbonRender
dcd0a5d53ee2c458ad53c4e690359c250219ee22
[ "MIT" ]
2
2018-10-10T15:56:58.000Z
2021-07-16T07:31:10.000Z
CarbonRender/Src/CRCinematicController.cpp
lanyu8/CarbonRender
dcd0a5d53ee2c458ad53c4e690359c250219ee22
[ "MIT" ]
14
2018-06-08T09:19:55.000Z
2022-03-17T08:04:57.000Z
#include "..\Inc\CRCinematicController.h" float CinematicController::GetCurrentTime() { clock_t currentTime; currentTime = clock(); return (float)currentTime/CLOCKS_PER_SEC; } void CinematicController::Init() { end = true; filmStartTime = -1; } void CinematicController::Update() { float stage0Cost = 6.0f; float stage1Cost = 3.0f; float stage2Cost = 6.0f; if (!end) { float currentTime = GetCurrentTime(); if (currentTime - filmStartTime >= stage0Cost + stage1Cost + stage2Cost) { end = true; } else { float process = (currentTime - filmStartTime) / (stage0Cost + stage1Cost + stage2Cost); process = Math::Min(process, 1.0f); float sunStartTime = 14.8f; float sunEndTime = 16.6f; float fogStartPrec = 55.0f; float fogEndPrec = 60.0f; float currentSunTime = (1.0f - process) * sunStartTime + process * sunEndTime; WeatherSystem::Instance()->SetHour(currentSunTime); float currentFogPrec = (1.0f - process) * fogStartPrec + process * fogEndPrec; WeatherSystem::Instance()->SetFogPrecipitation(currentFogPrec); if (currentTime - filmStartTime <= stage0Cost) { float3 camStartPos = float3(11.868318f, 5.0f, -8.464635f); float3 camEndPos = float3(11.868318f, 3.151639f, -8.464635f); process = (currentTime - filmStartTime) / stage0Cost; process = Math::Min(process, 1.0f); process = (-Math::Cos(process * PI) + 1.0f) * 0.5f; float3 camCurrentPos = (1.0f - process) * camStartPos + process * camEndPos; CameraManager::Instance()->GetCurrentCamera()->SetPosition(camCurrentPos); } else if (currentTime - filmStartTime <= stage0Cost + stage1Cost) { float3 camStartPos = float3(11.868318f, 3.151639f, -8.464635f); float3 camEndPos = float3(9.648738f, 3.151639f, -4.547123f); float3 camStartRota = float3(3.600040f, -54.599995f, 0.0f); float3 camEndRota = float3(1.500041f, -43.599918f, 0.0f); float camStartFov = 55.0f; float camEndFov = 60.0f; process = (currentTime - filmStartTime - stage0Cost) / stage1Cost; process = Math::Min(process, 1.0f); process = (-Math::Cos(process * PI) + 1.0f) * 0.5f; float3 camCurrentPos = (1.0f - process) * camStartPos + process * camEndPos; CameraManager::Instance()->GetCurrentCamera()->SetPosition(camCurrentPos); float3 camCurrentRota = (1.0f - process) * camStartRota + process * camEndRota; CameraManager::Instance()->GetCurrentCamera()->SetRotation(camCurrentRota); float camCurrentFov = (1.0f - process) * camStartFov + process * camEndFov; CameraManager::Instance()->GetCurrentCamera()->SetFov(camCurrentFov); } else { float3 camStartPos = float3(9.648738f, 3.151639f, -4.547123f); float3 camEndPos = float3(11.303256f, 3.151639f, -2.809704f); process = (currentTime - filmStartTime - stage0Cost - stage1Cost) / stage2Cost; process = Math::Min(process, 1.0f); process = (-Math::Cos(process * PI) + 1.0f) * 0.5f; float3 camCurrentPos = (1.0f - process) * camStartPos + process * camEndPos; CameraManager::Instance()->GetCurrentCamera()->SetPosition(camCurrentPos); } } } } void CinematicController::KeyInputCallback(GLFWwindow * window, int key, int scanCode, int action, int mods) { switch (key) { default: break; case GLFW_KEY_F1: { if (action == GLFW_PRESS) MenuManager::Instance()->ToogleMenu(); } break; case GLFW_KEY_P: { if (action == GLFW_PRESS) { ControllerManager::Instance()->Pop(); } } break; case GLFW_KEY_SPACE: { if (action == GLFW_PRESS && end) { WeatherSystem::Instance()->SetHour(14.8f); WeatherSystem::Instance()->SetFogPrecipitation(55.0f); CameraManager::Instance()->GetCurrentCamera()->SetFov(55.0f); CameraManager::Instance()->GetCurrentCamera()->SetPosition(float3(11.868318f, 5.0f, -8.464635f)); CameraManager::Instance()->GetCurrentCamera()->SetRotation(float3(3.600040f, -54.599995f, 0.0f)); filmStartTime = GetCurrentTime(); end = false; } } break; case GLFW_KEY_BACKSPACE: { if (action == GLFW_PRESS) { filmStartTime = GetCurrentTime(); } } break; } } void CinematicController::MouseMotionCallback(GLFWwindow * window, double x, double y) { } void CinematicController::ScrollCallback(GLFWwindow * window, double xOffset, double yOffset) { }
29.060811
108
0.686585
lanyu8
05764b74bd3baf37391e5337874a74ef262936fb
25,394
cpp
C++
TAO/tao/RTScheduling/Current.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/RTScheduling/Current.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/RTScheduling/Current.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- // $Id: Current.cpp 96992 2013-04-11 18:07:48Z huangh $ #include "tao/RTScheduling/Current.h" #include "tao/RTScheduling/Distributable_Thread.h" #include "tao/RTCORBA/Priority_Mapping_Manager.h" #include "tao/RTCORBA/RT_Current.h" #include "tao/ORB_Core.h" #include "tao/TSS_Resources.h" #include "ace/ACE.h" #include "ace/OS_NS_errno.h" #include "ace/OS_NS_string.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL ACE_Atomic_Op<TAO_SYNCH_MUTEX, long> TAO_RTScheduler_Current::guid_counter; u_long TAO_DTId_Hash::operator () (const IdType &id) const { return ACE::hash_pjw ((const char *) id.get_buffer (), id.length ()); } TAO_RTScheduler_Current::TAO_RTScheduler_Current (void) : orb_ (0) { } TAO_RTScheduler_Current::~TAO_RTScheduler_Current (void) { } void TAO_RTScheduler_Current::init (TAO_ORB_Core* orb) { this->orb_ = orb; // Create the RT_Current. RTCORBA::Current_ptr current; ACE_NEW_THROW_EX (current, TAO_RT_Current (orb), CORBA::NO_MEMORY (CORBA::SystemException::_tao_minor_code ( TAO::VMCID, ENOMEM), CORBA::COMPLETED_NO)); this->rt_current_ = current; } void TAO_RTScheduler_Current::rt_current (RTCORBA::Current_ptr rt_current) { this->rt_current_ = RTCORBA::Current::_duplicate (rt_current); } TAO_ORB_Core* TAO_RTScheduler_Current::orb (void) { return this->orb_; } DT_Hash_Map* TAO_RTScheduler_Current::dt_hash (void) { return &this->dt_hash_; } void TAO_RTScheduler_Current::begin_scheduling_segment ( const char * name, CORBA::Policy_ptr sched_param, CORBA::Policy_ptr implicit_sched_param) { TAO_RTScheduler_Current_i *impl = this->implementation (); if (impl == 0) { ACE_NEW_THROW_EX (impl, TAO_RTScheduler_Current_i (this->orb_, &this->dt_hash_), CORBA::NO_MEMORY ( CORBA::SystemException::_tao_minor_code ( TAO::VMCID, ENOMEM), CORBA::COMPLETED_NO)); this->implementation (impl); } impl->begin_scheduling_segment (name, sched_param, implicit_sched_param ); } void TAO_RTScheduler_Current::update_scheduling_segment (const char * name, CORBA::Policy_ptr sched_param, CORBA::Policy_ptr implicit_sched_param ) { TAO_RTScheduler_Current_i *impl = this->implementation (); if (impl == 0) throw ::CORBA::BAD_INV_ORDER (); impl->update_scheduling_segment (name, sched_param, implicit_sched_param ); } void TAO_RTScheduler_Current::end_scheduling_segment (const char * name) { TAO_RTScheduler_Current_i *impl = this->implementation (); if (impl == 0) { TAOLIB_ERROR ((LM_ERROR, "Missing scheduling context OR DT cancelled\n")); throw ::CORBA::BAD_INV_ORDER (); return; } impl->end_scheduling_segment (name ); } RTScheduling::DistributableThread_ptr TAO_RTScheduler_Current::lookup(const RTScheduling::Current::IdType & id) { RTScheduling::DistributableThread_var DT; int result = this->dt_hash_.find (id, DT); if (result == 0) return DT._retn (); else return RTScheduling::DistributableThread::_nil (); } // returns a null reference if // the distributable thread is // not known to the local scheduler RTScheduling::DistributableThread_ptr TAO_RTScheduler_Current::spawn (RTScheduling::ThreadAction_ptr start, CORBA::VoidData data, const char* name, CORBA::Policy_ptr sched_param, CORBA::Policy_ptr implicit_sched_param, CORBA::ULong stack_size, RTCORBA::Priority base_priority) { TAO_RTScheduler_Current_i *impl = this->implementation (); if (impl == 0) throw ::CORBA::BAD_INV_ORDER (); return impl->spawn (start, data, name, sched_param, implicit_sched_param, stack_size, base_priority ); } RTScheduling::Current::IdType * TAO_RTScheduler_Current::id (void) { TAO_RTScheduler_Current_i *impl = this->implementation (); if (impl == 0) throw ::CORBA::BAD_INV_ORDER (); return impl->id (); } CORBA::Policy_ptr TAO_RTScheduler_Current::scheduling_parameter (void) { TAO_RTScheduler_Current_i *impl = this->implementation (); if (impl == 0) throw ::CORBA::BAD_INV_ORDER (); return impl->scheduling_parameter (); } CORBA::Policy_ptr TAO_RTScheduler_Current::implicit_scheduling_parameter (void) { TAO_RTScheduler_Current_i *impl = this->implementation (); if (impl == 0) throw ::CORBA::BAD_INV_ORDER (); return impl->implicit_scheduling_parameter (); } RTScheduling::Current::NameList * TAO_RTScheduler_Current::current_scheduling_segment_names (void) { TAO_RTScheduler_Current_i *impl = this->implementation (); if (impl == 0) throw ::CORBA::BAD_INV_ORDER (); return impl->current_scheduling_segment_names (); } RTCORBA::Priority TAO_RTScheduler_Current::the_priority (void) { return this->rt_current_->the_priority (); } void TAO_RTScheduler_Current::the_priority (RTCORBA::Priority the_priority) { this->rt_current_->the_priority(the_priority); } TAO_RTScheduler_Current_i* TAO_RTScheduler_Current::implementation (TAO_RTScheduler_Current_i* new_current) { TAO_TSS_Resources *tss = TAO_TSS_Resources::instance (); TAO_RTScheduler_Current_i *old = static_cast<TAO_RTScheduler_Current_i *> (tss->rtscheduler_current_impl_); tss->rtscheduler_current_impl_ = new_current; return old; } TAO_RTScheduler_Current_i* TAO_RTScheduler_Current::implementation (void) { TAO_TSS_Resources *tss = TAO_TSS_Resources::instance (); TAO_RTScheduler_Current_i* impl = static_cast<TAO_RTScheduler_Current_i *> (tss->rtscheduler_current_impl_); return impl; } TAO_ORB_Core* TAO_RTScheduler_Current_i::orb (void) { return this->orb_; } DT_Hash_Map* TAO_RTScheduler_Current_i::dt_hash (void) { return this->dt_hash_; } RTScheduling::Scheduler_ptr TAO_RTScheduler_Current_i::scheduler (void) { return RTScheduling::Scheduler::_duplicate (this->scheduler_.in ()); } TAO_RTScheduler_Current_i::TAO_RTScheduler_Current_i (TAO_ORB_Core* orb, DT_Hash_Map* dt_hash) :orb_ (orb), dt_ (RTScheduling::DistributableThread::_nil ()), previous_current_ (0), dt_hash_ (dt_hash) { CORBA::Object_var scheduler_obj = this->orb_->object_ref_table ().resolve_initial_reference ( "RTScheduler"); this->scheduler_ = RTScheduling::Scheduler::_narrow (scheduler_obj.in ()); } TAO_RTScheduler_Current_i::TAO_RTScheduler_Current_i ( TAO_ORB_Core* orb, DT_Hash_Map* dt_hash, RTScheduling::Current::IdType guid, const char * name, CORBA::Policy_ptr sched_param, CORBA::Policy_ptr implicit_sched_param, RTScheduling::DistributableThread_ptr dt, TAO_RTScheduler_Current_i* prev_current) : orb_ (orb), guid_ (guid), name_ (CORBA::string_dup (name)), sched_param_ (CORBA::Policy::_duplicate (sched_param)), implicit_sched_param_ (CORBA::Policy::_duplicate (implicit_sched_param)), dt_ (RTScheduling::DistributableThread::_duplicate (dt)), previous_current_ (prev_current), dt_hash_ (dt_hash) { CORBA::Object_var scheduler_obj = orb->object_ref_table ().resolve_initial_reference ( "RTScheduler"); this->scheduler_ = RTScheduling::Scheduler::_narrow (scheduler_obj.in () ); } TAO_RTScheduler_Current_i::~TAO_RTScheduler_Current_i (void) { } void TAO_RTScheduler_Current_i::begin_scheduling_segment( const char * name, CORBA::Policy_ptr sched_param, CORBA::Policy_ptr implicit_sched_param) { // Check if it is a new Scheduling Segmnet if (this->guid_.length () == 0) { //Generate GUID size_t temp = ++TAO_RTScheduler_Current::guid_counter; this->guid_.length (sizeof(size_t)); ACE_OS::memcpy (this->guid_.get_buffer (), &temp, sizeof(size_t)); size_t guid; ACE_OS::memcpy (&guid, this->guid_.get_buffer (), this->guid_.length ()); // Inform the scheduler of the new scheduling segment. this->scheduler_->begin_new_scheduling_segment (this->guid_, name, sched_param, implicit_sched_param ); if (CORBA::is_nil (this->dt_.in ())) //Create new DT. this->dt_ = TAO_DistributableThread_Factory::create_DT (); //Add new DT to map int result = this->dt_hash_->bind (this->guid_, this->dt_); // Error in binding to the map - cancel thread. if (result != 0) { this->cancel_thread (); } // Remember parameters for the scheduling segment. this->name_ = CORBA::string_dup (name); this->sched_param_ = CORBA::Policy::_duplicate (sched_param); this->implicit_sched_param_ = CORBA::Policy::_duplicate (implicit_sched_param); } else //Nested segment { // Check current DT state. if (this->dt_->state () == RTScheduling::DistributableThread::CANCELLED) { this->cancel_thread (); } // Inform scheduler of start of nested scheduling segment. this->scheduler_->begin_nested_scheduling_segment (this->guid_, name, sched_param, implicit_sched_param ); TAO_TSS_Resources *tss = TAO_TSS_Resources::instance (); TAO_RTScheduler_Current_i* new_current = 0; ACE_NEW_THROW_EX (new_current, TAO_RTScheduler_Current_i (this->orb_, this->dt_hash_, this->guid_, name, sched_param, implicit_sched_param, this->dt_.in (), this), CORBA::NO_MEMORY ( CORBA::SystemException::_tao_minor_code ( TAO::VMCID, ENOMEM), CORBA::COMPLETED_NO)); tss->rtscheduler_current_impl_ = new_current; } } void TAO_RTScheduler_Current_i::update_scheduling_segment (const char * name, CORBA::Policy_ptr sched_param, CORBA::Policy_ptr implicit_sched_param ) { // Check if DT has been cancelled if (this->dt_->state () == RTScheduling::DistributableThread::CANCELLED) { this->cancel_thread (); } // Let scheduler know of the updates. this->scheduler_->update_scheduling_segment (this->guid_, name, sched_param, implicit_sched_param ); // Remember the new values. this->name_ = CORBA::string_dup (name); this->sched_param_ = CORBA::Policy::_duplicate (sched_param); this->implicit_sched_param_ = CORBA::Policy::_duplicate (implicit_sched_param); } void TAO_RTScheduler_Current_i::end_scheduling_segment (const char * name) { // Check if DT has been cancelled if (this->dt_->state () == RTScheduling::DistributableThread::CANCELLED) { this->cancel_thread (); } if (this->previous_current_ == 0) { // Let the scheduler know that the DT is // terminating. this->scheduler_->end_scheduling_segment(this->guid_, name ); // Cleanup DT. this->cleanup_DT (); // Cleanup current. this->cleanup_current (); // A Nested segment. } else { // Inform scheduler of end of nested // scheduling segment. this->scheduler_->end_nested_scheduling_segment (this->guid_, name, this->previous_current_->sched_param_.in () ); // Cleanup current. this->cleanup_current (); } } // returns a null reference if // the distributable thread is // not known to the local scheduler RTScheduling::DistributableThread_ptr TAO_RTScheduler_Current_i::spawn (RTScheduling::ThreadAction_ptr start, CORBA::VoidData data, const char* name, CORBA::Policy_ptr sched_param, CORBA::Policy_ptr implicit_sched_param, CORBA::ULong stack_size, RTCORBA::Priority base_priority ) { // Check if DT has been cancelled. if (this->dt_->state () == RTScheduling::DistributableThread::CANCELLED) { this->cancel_thread (); } // Create new task for new DT. DTTask *dttask = 0; // If no scheduling parameter is specified then use the current // implicit scheduling parameter as the scheduling parameter if (sched_param == 0) sched_param = this->implicit_sched_param_.in (); RTScheduling::DistributableThread_var dt = TAO_DistributableThread_Factory::create_DT (); TAO_RTScheduler_Current_i *new_current = 0; ACE_NEW_RETURN (new_current, TAO_RTScheduler_Current_i (this->orb_, this->dt_hash_), 0); new_current->DT (dt.in ()); ACE_NEW_RETURN (dttask, DTTask (//thread_manager_, this->orb_, this->dt_hash_, new_current, start, data, name, sched_param, implicit_sched_param), 0); if (dttask->activate_task (base_priority, stack_size) == -1) { TAOLIB_ERROR((LM_ERROR, "Unable to activate DistributableThread\n")); delete dttask; return RTScheduling::DistributableThread::_nil (); } return dt._retn (); } int DTTask::activate_task (RTCORBA::Priority base_priority, CORBA::ULong stack_size ) { // Activate thread. long default_flags = THR_NEW_LWP | THR_JOINABLE; long flags = default_flags | this->orb_->orb_params ()->scope_policy () | this->orb_->orb_params ()->sched_policy (); CORBA::Object_var object = this->orb_->object_ref_table ().resolve_initial_reference ( TAO_OBJID_PRIORITYMAPPINGMANAGER); RTCORBA::PriorityMappingManager_var mapping_manager = RTCORBA::PriorityMappingManager::_narrow (object.in () ); RTCORBA::PriorityMapping *pm = mapping_manager->mapping (); RTCORBA::NativePriority native_priority; pm->to_native (base_priority, native_priority); size_t stack [1]; stack [0] = stack_size; if (this->activate (flags, 1, 0,//force_active native_priority,//priority -1,//grp_id 0,//ACE_Task_Base 0,//thread_handles 0,//stack stack//stack_size ) == -1) { if (ACE_OS::last_error () == EPERM) TAOLIB_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Insufficient privilege to run this test.\n")), -1); } return 0; } DTTask::DTTask (TAO_ORB_Core *orb, DT_Hash_Map *dt_hash, TAO_RTScheduler_Current_i* new_current, RTScheduling::ThreadAction_ptr start, CORBA::VoidData data, const char *name, CORBA::Policy_ptr sched_param, CORBA::Policy_ptr implicit_sched_param) :orb_ (orb), dt_hash_ (dt_hash), current_ (new_current), start_ (RTScheduling::ThreadAction::_duplicate (start)), data_ (data), name_ (CORBA::string_dup (name)), sched_param_ (CORBA::Policy::_duplicate (sched_param)), implicit_sched_param_ (CORBA::Policy::_duplicate (implicit_sched_param)) { } DTTask::~DTTask (void) { delete this->current_; } int DTTask::svc (void) { try { TAO_TSS_Resources *tss = TAO_TSS_Resources::instance (); tss->rtscheduler_current_impl_ = this->current_; this->current_->begin_scheduling_segment (this->name_.in (), this->sched_param_.in (), this->implicit_sched_param_.in () ); // Invoke entry point into new DT. this->start_->_cxx_do (this->data_ ); this->current_->end_scheduling_segment (this->name_.in () ); } catch (const ::CORBA::Exception& ex) { ex._tao_print_exception ("Caught exception:"); return -1; } return 0; } RTScheduling::Current::IdType * TAO_RTScheduler_Current_i::id (void) { RTScheduling::Current::IdType_var guid = this->guid_; return guid._retn (); } CORBA::Policy_ptr TAO_RTScheduler_Current_i::scheduling_parameter (void) { return CORBA::Policy::_duplicate (this->sched_param_.in ()); } CORBA::Policy_ptr TAO_RTScheduler_Current_i::implicit_scheduling_parameter (void) { return CORBA::Policy::_duplicate (this->implicit_sched_param_.in ()); } RTScheduling::Current::NameList * TAO_RTScheduler_Current_i::current_scheduling_segment_names (void) { RTScheduling::Current::NameList* name_list; ACE_NEW_RETURN (name_list, RTScheduling::Current::NameList, 0); TAO_RTScheduler_Current_i* current = this; for (int index = 0; current != 0; index++) { name_list->length (index+1); (*name_list) [index] = current->name (); current = current->previous_current_; } return name_list; } const char* TAO_RTScheduler_Current_i::name (void) { return this->name_.in (); } #if defined (THREAD_CANCELLED) #undef THREAD_CANCELLED #endif /* THREAD_CANCELLED */ void TAO_RTScheduler_Current_i::cancel_thread (void) { size_t guid; ACE_OS::memcpy (&guid, this->guid_.get_buffer (), this->guid_.length ()); TAOLIB_DEBUG ((LM_DEBUG, "Distributable Thread - %d is cancelled\n", guid)); // Let the scheduler know that the thread has // been cancelled. this->scheduler_->cancel (this->guid_ ); this->cleanup_DT (); // Remove all related nested currents. this->delete_all_currents (); // Throw exception. throw ::CORBA::THREAD_CANCELLED (); } void TAO_RTScheduler_Current_i::cleanup_DT (void) { // Remove DT from map. this->dt_hash_->unbind (this->guid_); } void TAO_RTScheduler_Current_i::cleanup_current (void) { TAO_TSS_Resources *tss = TAO_TSS_Resources::instance (); tss->rtscheduler_current_impl_ = this->previous_current_; // Delete this current. delete this; } void TAO_RTScheduler_Current_i::delete_all_currents (void) { TAO_RTScheduler_Current_i* current = this; while (current != 0) { TAO_RTScheduler_Current_i* prev_current = current->previous_current_; current->cleanup_current (); current = prev_current; } TAO_TSS_Resources *tss = TAO_TSS_Resources::instance (); tss->rtscheduler_current_impl_ = tss->rtscheduler_previous_current_impl_; } void TAO_RTScheduler_Current_i::id (RTScheduling::Current::IdType guid) { this->guid_ = guid; } void TAO_RTScheduler_Current_i::name (const char * name) { this->name_ = CORBA::string_dup (name); } RTScheduling::DistributableThread_ptr TAO_RTScheduler_Current_i::DT (void) { return this->dt_._retn (); } void TAO_RTScheduler_Current_i::DT (RTScheduling::DistributableThread_ptr dt) { this->dt_ = RTScheduling::DistributableThread::_duplicate (dt); } void TAO_RTScheduler_Current_i::scheduling_parameter (CORBA::Policy_ptr sched_param) { this->sched_param_ = CORBA::Policy::_duplicate (sched_param); } void TAO_RTScheduler_Current_i::implicit_scheduling_parameter (CORBA::Policy_ptr implicit_sched_param) { this->implicit_sched_param_ = CORBA::Policy::_duplicate (implicit_sched_param); } // ************************************************************* // ************************************************************* // Operations for class TAO_RTScheduler_Current_var // ************************************************************* TAO_RTScheduler_Current_var::TAO_RTScheduler_Current_var (void) // default constructor : ptr_ (TAO_RTScheduler_Current::_nil ()) {} ::TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current_var::ptr (void) const { return this->ptr_; } TAO_RTScheduler_Current_var::TAO_RTScheduler_Current_var (const ::TAO_RTScheduler_Current_var &p) : TAO_Base_var (), ptr_ (TAO_RTScheduler_Current::_duplicate (p.ptr ())) {} TAO_RTScheduler_Current_var::~TAO_RTScheduler_Current_var (void) // destructor { ::CORBA::release (this->ptr_); } TAO_RTScheduler_Current_var & TAO_RTScheduler_Current_var::operator= (TAO_RTScheduler_Current_ptr p) { ::CORBA::release (this->ptr_); this->ptr_ = p; return *this; } TAO_RTScheduler_Current_var & TAO_RTScheduler_Current_var::operator= (const ::TAO_RTScheduler_Current_var &p) { if (this != &p) { ::CORBA::release (this->ptr_); this->ptr_ = ::TAO_RTScheduler_Current::_duplicate (p.ptr ()); } return *this; } TAO_RTScheduler_Current_var::operator const ::TAO_RTScheduler_Current_ptr &() const { return this->ptr_; } TAO_RTScheduler_Current_var::operator ::TAO_RTScheduler_Current_ptr &() { return this->ptr_; } TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current_var::operator-> (void) const { return this->ptr_; } TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current_var::in (void) const { return this->ptr_; } TAO_RTScheduler_Current_ptr & TAO_RTScheduler_Current_var::inout (void) { return this->ptr_; } TAO_RTScheduler_Current_ptr & TAO_RTScheduler_Current_var::out (void) { ::CORBA::release (this->ptr_); this->ptr_ = ::TAO_RTScheduler_Current::_nil (); return this->ptr_; } TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current_var::_retn (void) { // yield ownership of managed obj reference ::TAO_RTScheduler_Current_ptr val = this->ptr_; this->ptr_ = ::TAO_RTScheduler_Current::_nil (); return val; } TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current_var::duplicate (TAO_RTScheduler_Current_ptr p) { return ::TAO_RTScheduler_Current::_duplicate (p); } void TAO_RTScheduler_Current_var::release (TAO_RTScheduler_Current_ptr p) { ::CORBA::release (p); } TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current_var::nil (void) { return ::TAO_RTScheduler_Current::_nil (); } TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current_var::narrow ( CORBA::Object *p ) { return ::TAO_RTScheduler_Current::_narrow (p); } CORBA::Object * TAO_RTScheduler_Current_var::upcast (void *src) { TAO_RTScheduler_Current **tmp = static_cast<TAO_RTScheduler_Current **> (src); return *tmp; } TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current::_narrow ( CORBA::Object_ptr obj ) { return TAO_RTScheduler_Current::_duplicate ( dynamic_cast<TAO_RTScheduler_Current *> (obj) ); } TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current::_duplicate (TAO_RTScheduler_Current_ptr obj) { if (!CORBA::is_nil (obj)) obj->_add_ref (); return obj; } const char* TAO_RTScheduler_Current::_interface_repository_id (void) const { return "IDL:TAO_RTScheduler_Current:1.0"; } TAO_END_VERSIONED_NAMESPACE_DECL
27.217578
98
0.598606
cflowe
05785b84b5e654e85f09eb3050356cabd3289965
184
hpp
C++
plugins/arclite/example/headers.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
null
null
null
plugins/arclite/example/headers.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
null
null
null
plugins/arclite/example/headers.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <string> #include <list> #include <vector> #include <map> #include <iterator> using namespace std; #include <initguid.h> #include "CPP/7zip/Archive/IArchive.h"
15.333333
38
0.733696
TheChatty
05795ecf3bfc2271a2f8b4bb27e8dc0d9759b6b3
20,875
cc
C++
tools/InterfaceGenerator/test/generator/generators/test_expected_jsonrpc.cc
russjohnson09/sdl_core
9de7f1456f1807ae97348f774f7eead0ee92fd6d
[ "BSD-3-Clause" ]
249
2015-01-15T16:50:53.000Z
2022-03-24T13:23:34.000Z
tools/InterfaceGenerator/test/generator/generators/test_expected_jsonrpc.cc
russjohnson09/sdl_core
9de7f1456f1807ae97348f774f7eead0ee92fd6d
[ "BSD-3-Clause" ]
2,917
2015-01-12T16:17:49.000Z
2022-03-31T11:57:47.000Z
tools/InterfaceGenerator/test/generator/generators/test_expected_jsonrpc.cc
russjohnson09/sdl_core
9de7f1456f1807ae97348f774f7eead0ee92fd6d
[ "BSD-3-Clause" ]
306
2015-01-12T09:23:20.000Z
2022-01-28T18:06:30.000Z
/** * @file Test.cc * @brief Generated class Test source file. * * This class is a part of SmartObjects solution. It provides * factory functionallity which allows client to use SmartSchemas * in accordance with definitions from Test.xml file */ // Copyright (c) 2013, Ford Motor Company // 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 Ford Motor Company 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. #include <map> #include <set> #include "Test.h" #include "SmartObjects/CAlwaysTrueSchemaItem.hpp" #include "SmartObjects/CAlwaysFalseSchemaItem.hpp" #include "SmartObjects/CArraySchemaItem.hpp" #include "SmartObjects/CBoolSchemaItem.hpp" #include "SmartObjects/CObjectSchemaItem.hpp" #include "SmartObjects/CStringSchemaItem.hpp" #include "SmartObjects/TEnumSchemaItem.hpp" #include "SmartObjects/TNumberSchemaItem.hpp" #include "SmartObjects/TSchemaItemParameter.hpp" using namespace ns_smart_device_link::ns_smart_objects; XXX::YYY::ZZZ::Test::Test() : CSmartFactory<FunctionID::eType, messageType::eType, StructIdentifiers::eType>() { TStructsSchemaItems struct_schema_items; InitStructSchemes(struct_schema_items); std::set<FunctionID::eType> function_id_items; std::set<messageType::eType> message_type_items; message_type_items.insert(messageType::request); message_type_items.insert(messageType::response); message_type_items.insert(messageType::notification); message_type_items.insert(messageType::error_response); InitFunctionSchemes(struct_schema_items, function_id_items, message_type_items); } TSharedPtr<ISchemaItem> XXX::YYY::ZZZ::Test::ProvideObjectSchemaItemForStruct( const TStructsSchemaItems &struct_schema_items, const StructIdentifiers::eType struct_id) { const TStructsSchemaItems::const_iterator it = struct_schema_items.find(struct_id); if (it != struct_schema_items.end()) { return it->second; } return ns_smart_device_link::ns_smart_objects::CAlwaysFalseSchemaItem::create(); } void XXX::YYY::ZZZ::Test::InitStructSchemes( TStructsSchemaItems &struct_schema_items) { TSharedPtr<ISchemaItem> struct_schema_item_Struct2 = InitStructSchemaItem_Struct2(struct_schema_items); struct_schema_items.insert(std::make_pair(StructIdentifiers::Struct2, struct_schema_item_Struct2)); structs_schemes_.insert(std::make_pair(StructIdentifiers::Struct2, CSmartSchema(struct_schema_item_Struct2))); TSharedPtr<ISchemaItem> struct_schema_item_Struct1 = InitStructSchemaItem_Struct1(struct_schema_items); struct_schema_items.insert(std::make_pair(StructIdentifiers::Struct1, struct_schema_item_Struct1)); structs_schemes_.insert(std::make_pair(StructIdentifiers::Struct1, CSmartSchema(struct_schema_item_Struct1))); } void XXX::YYY::ZZZ::Test::InitFunctionSchemes( const TStructsSchemaItems &struct_schema_items, const std::set<FunctionID::eType> &function_id_items, const std::set<messageType::eType> &message_type_items) { std::map<std::string, SMember> params_members; params_members[ns_smart_device_link::ns_json_handler::strings::S_FUNCTION_ID] = SMember(TEnumSchemaItem<FunctionID::eType>::create(function_id_items), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_MESSAGE_TYPE] = SMember(TEnumSchemaItem<messageType::eType>::create(message_type_items), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_VERSION] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_TYPE] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_CORRELATION_ID] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::kCode] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::kMessage] = SMember(CStringSchemaItem::create(), true); std::map<std::string, SMember> root_members_map; root_members_map[ns_smart_device_link::ns_json_handler::strings::S_PARAMS] = SMember(CObjectSchemaItem::create(params_members), true); CSmartSchema error_response_schema(CObjectSchemaItem::create(root_members_map)); functions_schemes_.insert(std::make_pair(ns_smart_device_link::ns_json_handler::SmartSchemaKey<FunctionID::eType, messageType::eType>(FunctionID::val_1, messageType::error_response), error_response_schema)); functions_schemes_.insert(std::make_pair(ns_smart_device_link::ns_json_handler::SmartSchemaKey<FunctionID::eType, messageType::eType>(FunctionID::name1, messageType::request), InitFunction_name1_request(struct_schema_items, function_id_items, message_type_items))); functions_schemes_.insert(std::make_pair(ns_smart_device_link::ns_json_handler::SmartSchemaKey<FunctionID::eType, messageType::eType>(FunctionID::val_1, messageType::response), InitFunction_val_1_response(struct_schema_items, function_id_items, message_type_items))); functions_schemes_.insert(std::make_pair(ns_smart_device_link::ns_json_handler::SmartSchemaKey<FunctionID::eType, messageType::eType>(FunctionID::val_2, messageType::notification), InitFunction_val_2_notification(struct_schema_items, function_id_items, message_type_items))); } //------------- Functions schemes initialization ------------- CSmartSchema XXX::YYY::ZZZ::Test::InitFunction_name1_request( const TStructsSchemaItems &struct_schema_items, const std::set<FunctionID::eType> &function_id_items, const std::set<messageType::eType> &message_type_items) { std::set<Enum_new4::eType> Enum_new4_all_enum_values; Enum_new4_all_enum_values.insert(Enum_new4::_11); Enum_new4_all_enum_values.insert(Enum_new4::_22); std::set<Enum1::eType> param2_allowed_enum_subset_values; param2_allowed_enum_subset_values.insert(Enum1::name1); // Function parameter param1. // // Description Line1 // Description Line2 // // Design Line1 // // Note: Issue1 // Note: Issue2 // Note: Issue3 // // ToDo: Do1 // ToDo: Do2 TSharedPtr<ISchemaItem> param1_SchemaItem = TEnumSchemaItem<Enum_new4::eType>::create(Enum_new4_all_enum_values, TSchemaItemParameter<Enum_new4::eType>(Enum_new4::_11)); // Function parameter param2. TSharedPtr<ISchemaItem> param2_SchemaItem = TEnumSchemaItem<Enum1::eType>::create(param2_allowed_enum_subset_values, TSchemaItemParameter<Enum1::eType>(name1)); std::map<std::string, SMember> schema_members; schema_members["param1"] = SMember(param1_SchemaItem, true); schema_members["param2"] = SMember(param2_SchemaItem, true); std::map<std::string, SMember> params_members; params_members[ns_smart_device_link::ns_json_handler::strings::S_FUNCTION_ID] = SMember(TEnumSchemaItem<FunctionID::eType>::create(function_id_items), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_MESSAGE_TYPE] = SMember(TEnumSchemaItem<messageType::eType>::create(message_type_items), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_VERSION] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_TYPE] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_CORRELATION_ID] = SMember(TNumberSchemaItem<int>::create(), true); std::map<std::string, SMember> root_members_map; root_members_map[ns_smart_device_link::ns_json_handler::strings::S_MSG_PARAMS] = SMember(CObjectSchemaItem::create(schema_members), true); root_members_map[ns_smart_device_link::ns_json_handler::strings::S_PARAMS] = SMember(CObjectSchemaItem::create(params_members), true); return CSmartSchema(CObjectSchemaItem::create(root_members_map)); } CSmartSchema XXX::YYY::ZZZ::Test::InitFunction_val_1_response( const TStructsSchemaItems &struct_schema_items, const std::set<FunctionID::eType> &function_id_items, const std::set<messageType::eType> &message_type_items) { std::map<std::string, SMember> schema_members; std::map<std::string, SMember> params_members; params_members[ns_smart_device_link::ns_json_handler::strings::S_FUNCTION_ID] = SMember(TEnumSchemaItem<FunctionID::eType>::create(function_id_items), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_MESSAGE_TYPE] = SMember(TEnumSchemaItem<messageType::eType>::create(message_type_items), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_VERSION] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_TYPE] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_CORRELATION_ID] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::kCode] = SMember(TNumberSchemaItem<int>::create(), true); std::map<std::string, SMember> root_members_map; root_members_map[ns_smart_device_link::ns_json_handler::strings::S_MSG_PARAMS] = SMember(CObjectSchemaItem::create(schema_members), true); root_members_map[ns_smart_device_link::ns_json_handler::strings::S_PARAMS] = SMember(CObjectSchemaItem::create(params_members), true); return CSmartSchema(CObjectSchemaItem::create(root_members_map)); } CSmartSchema XXX::YYY::ZZZ::Test::InitFunction_val_2_notification( const TStructsSchemaItems &struct_schema_items, const std::set<FunctionID::eType> &function_id_items, const std::set<messageType::eType> &message_type_items) { std::map<std::string, SMember> schema_members; std::map<std::string, SMember> params_members; params_members[ns_smart_device_link::ns_json_handler::strings::S_FUNCTION_ID] = SMember(TEnumSchemaItem<FunctionID::eType>::create(function_id_items), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_MESSAGE_TYPE] = SMember(TEnumSchemaItem<messageType::eType>::create(message_type_items), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_VERSION] = SMember(TNumberSchemaItem<int>::create(), true); params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_TYPE] = SMember(TNumberSchemaItem<int>::create(), true); std::map<std::string, SMember> root_members_map; root_members_map[ns_smart_device_link::ns_json_handler::strings::S_MSG_PARAMS] = SMember(CObjectSchemaItem::create(schema_members), true); root_members_map[ns_smart_device_link::ns_json_handler::strings::S_PARAMS] = SMember(CObjectSchemaItem::create(params_members), true); return CSmartSchema(CObjectSchemaItem::create(root_members_map)); } //----------- Structs schema items initialization ------------ TSharedPtr<ISchemaItem> XXX::YYY::ZZZ::Test::InitStructSchemaItem_Struct1( const TStructsSchemaItems &struct_schema_items) { std::set<Enum1::eType> Enum1_all_enum_values; Enum1_all_enum_values.insert(Enum1::name1); Enum1_all_enum_values.insert(Enum1::internal_name2); std::set<Enum1::eType> enumSubset1_allowed_enum_subset_values; enumSubset1_allowed_enum_subset_values.insert(Enum1::name1); std::set<Enum_new2::eType> Enum_new2_all_enum_values; Enum_new2_all_enum_values.insert(Enum_new2::_1); Enum_new2_all_enum_values.insert(Enum_new2::_2); Enum_new2_all_enum_values.insert(Enum_new2::_3); std::set<Enum1::eType> sub1_allowed_enum_subset_values; sub1_allowed_enum_subset_values.insert(Enum1::name1); std::set<Enum1::eType> sub2_allowed_enum_subset_values; sub2_allowed_enum_subset_values.insert(Enum1::internal_name2); std::set<Enum_new4::eType> sub3_allowed_enum_subset_values; sub3_allowed_enum_subset_values.insert(Enum_new4::_22); // Struct member intParam. TSharedPtr<ISchemaItem> intParam_SchemaItem = TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(), TSchemaItemParameter<int>(2), TSchemaItemParameter<int>()); // Struct member doubleParam. TSharedPtr<ISchemaItem> doubleParam_SchemaItem = TNumberSchemaItem<double>::create(TSchemaItemParameter<double>(0.333), TSchemaItemParameter<double>(), TSchemaItemParameter<double>()); // Struct member boolParam. TSharedPtr<ISchemaItem> boolParam_SchemaItem = CBoolSchemaItem::create(TSchemaItemParameter<bool>()); // Struct member structParam. TSharedPtr<ISchemaItem> structParam_SchemaItem = ProvideObjectSchemaItemForStruct(struct_schema_items, StructIdentifiers::Struct2); // Struct member enumParam. TSharedPtr<ISchemaItem> enumParam_SchemaItem = TEnumSchemaItem<Enum1::eType>::create(Enum1_all_enum_values, TSchemaItemParameter<Enum1::eType>()); // Struct member enumParam1. TSharedPtr<ISchemaItem> enumParam1_SchemaItem = TEnumSchemaItem<Enum1::eType>::create(Enum1_all_enum_values, TSchemaItemParameter<Enum1::eType>()); // Struct member enumSubset1. TSharedPtr<ISchemaItem> enumSubset1_SchemaItem = TEnumSchemaItem<Enum1::eType>::create(enumSubset1_allowed_enum_subset_values, TSchemaItemParameter<Enum1::eType>()); // Struct member arrayOfInt. TSharedPtr<ISchemaItem> arrayOfInt_SchemaItem = CArraySchemaItem::create(CBoolSchemaItem::create(TSchemaItemParameter<bool>()), TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(20)); // Struct member arrayOfEnum1. TSharedPtr<ISchemaItem> arrayOfEnum1_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum1::eType>::create(Enum1_all_enum_values, TSchemaItemParameter<Enum1::eType>()), TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(20)); // Struct member arrayOfEnum3. TSharedPtr<ISchemaItem> arrayOfEnum3_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum_new2::eType>::create(Enum_new2_all_enum_values, TSchemaItemParameter<Enum_new2::eType>()), TSchemaItemParameter<size_t>(10), TSchemaItemParameter<size_t>(40)); // Struct member arrayOfEnum4. TSharedPtr<ISchemaItem> arrayOfEnum4_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum1::eType>::create(sub1_allowed_enum_subset_values, TSchemaItemParameter<Enum1::eType>()), TSchemaItemParameter<size_t>(10), TSchemaItemParameter<size_t>(41)); // Struct member arrayOfEnum5. TSharedPtr<ISchemaItem> arrayOfEnum5_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum1::eType>::create(sub2_allowed_enum_subset_values, TSchemaItemParameter<Enum1::eType>()), TSchemaItemParameter<size_t>(10), TSchemaItemParameter<size_t>(42)); // Struct member arrayOfEnum6. TSharedPtr<ISchemaItem> arrayOfEnum6_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum_new4::eType>::create(sub3_allowed_enum_subset_values, TSchemaItemParameter<Enum_new4::eType>()), TSchemaItemParameter<size_t>(10), TSchemaItemParameter<size_t>(43)); std::map<std::string, SMember> schema_members; schema_members["intParam"] = SMember(intParam_SchemaItem, true); schema_members["doubleParam"] = SMember(doubleParam_SchemaItem, false); schema_members["boolParam"] = SMember(boolParam_SchemaItem, true); schema_members["structParam"] = SMember(structParam_SchemaItem, true); schema_members["enumParam"] = SMember(enumParam_SchemaItem, true); schema_members["enumParam1"] = SMember(enumParam1_SchemaItem, true); schema_members["enumSubset1"] = SMember(enumSubset1_SchemaItem, false); schema_members["arrayOfInt"] = SMember(arrayOfInt_SchemaItem, false); schema_members["arrayOfEnum1"] = SMember(arrayOfEnum1_SchemaItem, false); schema_members["arrayOfEnum3"] = SMember(arrayOfEnum3_SchemaItem, true); schema_members["arrayOfEnum4"] = SMember(arrayOfEnum4_SchemaItem, true); schema_members["arrayOfEnum5"] = SMember(arrayOfEnum5_SchemaItem, true); schema_members["arrayOfEnum6"] = SMember(arrayOfEnum6_SchemaItem, true); return CObjectSchemaItem::create(schema_members); } TSharedPtr<ISchemaItem> XXX::YYY::ZZZ::Test::InitStructSchemaItem_Struct2( const TStructsSchemaItems &struct_schema_items) { std::map<std::string, SMember> schema_members; return CObjectSchemaItem::create(schema_members); } //-------------- String to value enum mapping ---------------- namespace ns_smart_device_link { namespace ns_smart_objects { template <> const std::map<XXX::YYY::ZZZ::Enum1::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::Enum1::eType>::getEnumElementsStringRepresentation() { static bool is_initialized = false; static std::map<XXX::YYY::ZZZ::Enum1::eType, std::string> enum_string_representation; if (false == is_initialized) { enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum1::name1, "name1")); enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum1::internal_name2, "name2")); is_initialized = true; } return enum_string_representation; } template <> const std::map<XXX::YYY::ZZZ::E2::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::E2::eType>::getEnumElementsStringRepresentation() { static bool is_initialized = false; static std::map<XXX::YYY::ZZZ::E2::eType, std::string> enum_string_representation; if (false == is_initialized) { enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::E2::val_1, "xxx")); enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::E2::val_2, "yyy")); enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::E2::val_3, "val_3")); is_initialized = true; } return enum_string_representation; } template <> const std::map<XXX::YYY::ZZZ::Enum_new2::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::Enum_new2::eType>::getEnumElementsStringRepresentation() { static bool is_initialized = false; static std::map<XXX::YYY::ZZZ::Enum_new2::eType, std::string> enum_string_representation; if (false == is_initialized) { enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new2::_1, "xxx")); enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new2::_2, "xxx")); enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new2::_3, "xxx")); is_initialized = true; } return enum_string_representation; } template <> const std::map<XXX::YYY::ZZZ::Enum_new4::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::Enum_new4::eType>::getEnumElementsStringRepresentation() { static bool is_initialized = false; static std::map<XXX::YYY::ZZZ::Enum_new4::eType, std::string> enum_string_representation; if (false == is_initialized) { enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new4::_11, "xxx")); enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new4::_22, "xxx")); is_initialized = true; } return enum_string_representation; } template <> const std::map<XXX::YYY::ZZZ::messageType::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::messageType::eType>::getEnumElementsStringRepresentation() { static bool is_initialized = false; static std::map<XXX::YYY::ZZZ::messageType::eType, std::string> enum_string_representation; if (false == is_initialized) { enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::messageType::request, "request")); enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::messageType::response, "response")); enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::messageType::notification, "notification")); enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::messageType::error_response, "error_response")); is_initialized = true; } return enum_string_representation; } } // ns_smart_objects } // ns_smart_device_link
54.080311
277
0.790611
russjohnson09
057bf478027317dbf2e6e791e08ab202259413e4
1,539
hpp
C++
source/redx/core/gname.hpp
clayne/CyberpunkSaveEditor
2069ea833ced56f549776179c2147b27d32d650c
[ "MIT" ]
276
2020-12-21T11:54:44.000Z
2022-03-28T16:49:44.000Z
source/redx/core/gname.hpp
13397729377/CyberpunkSaveEditor
2069ea833ced56f549776179c2147b27d32d650c
[ "MIT" ]
37
2020-12-21T18:25:12.000Z
2022-03-31T23:51:33.000Z
source/redx/core/gname.hpp
13397729377/CyberpunkSaveEditor
2069ea833ced56f549776179c2147b27d32d650c
[ "MIT" ]
36
2020-12-21T12:02:08.000Z
2022-03-21T10:47:43.000Z
#pragma once #include <redx/core/platform.hpp> #include <nlohmann/json.hpp> #include <redx/core/stringpool.hpp> #include <redx/core/gstring.hpp> namespace redx { inline constexpr uint32_t gstring_name_category_tag = 'GNAM'; using gname = gstring<gstring_name_category_tag>; namespace literals { using literal_gname_helper = literal_gstring_helper<gstring_name_category_tag>; #if __cpp_nontype_template_args >= 201911 && !defined(__INTELLISENSE__) // todo: finish that when c++20 finally works in msvc.. template <literal_gname_helper::builder Builder> constexpr literal_gname_helper::singleton<Builder>::gstring_builder operator""_gndef() { return literal_gname_helper::singleton<Builder>::gstring_builder(); } template <literal_gname_helper::builder Builder> constexpr literal_gname_helper::singleton<Builder>::gstrid_builder operator""_gndef_id() { return literal_gname_helper::singleton<Builder>::gstrid_builder(); } #else // does register the name constexpr literal_gname_helper::gstring_builder operator""_gndef(const char* s, std::size_t) { return literal_gname_helper::gstring_builder(s); } //constexpr literal_gname_helper::gstrid_builder operator""_gnid(const char* s, std::size_t) //{ // return literal_gname_helper::gstrid_builder(s); //} #endif inline constexpr auto gn_test1 = literal_gname_helper::builder("test1"); inline constexpr auto gn_test2 = "test2"_gndef; } // namespace literals using literals::operator""_gndef; } // namespace redx
26.534483
93
0.758934
clayne
057e50845e3042a8b51b0286ab7ce9674434fba2
2,591
hpp
C++
drape/metal/metal_states.hpp
kudlav/organicmaps
390236365749e0525b9229684132c2888d11369d
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
drape/metal/metal_states.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
drape/metal/metal_states.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#pragma once #import <MetalKit/MetalKit.h> #include "drape/graphics_context.hpp" #include "drape/metal/metal_gpu_program.hpp" #include "drape/pointers.hpp" #include "drape/texture_types.hpp" #include <cstdint> #include <map> namespace dp { namespace metal { class MetalStates { public: struct DepthStencilKey { void SetDepthTestEnabled(bool enabled); void SetDepthTestFunction(TestFunction depthFunction); void SetStencilTestEnabled(bool enabled); void SetStencilFunction(StencilFace face, TestFunction stencilFunction); void SetStencilActions(StencilFace face, StencilAction stencilFailAction, StencilAction depthFailAction, StencilAction passAction); bool operator<(DepthStencilKey const & rhs) const; MTLDepthStencilDescriptor * BuildDescriptor() const; bool m_depthEnabled = false; bool m_stencilEnabled = false; TestFunction m_depthFunction = TestFunction::Always; uint64_t m_stencil = 0; }; struct PipelineKey { PipelineKey() = default; PipelineKey(ref_ptr<GpuProgram> program, MTLPixelFormat colorFormat, MTLPixelFormat depthStencilFormat, bool blendingEnabled); bool operator<(PipelineKey const & rhs) const; MTLRenderPipelineDescriptor * BuildDescriptor() const; ref_ptr<GpuProgram> m_program; MTLPixelFormat m_colorFormat = MTLPixelFormatInvalid; MTLPixelFormat m_depthStencilFormat = MTLPixelFormatInvalid; bool m_blendingEnabled = false; }; struct SamplerKey { SamplerKey() = default; SamplerKey(TextureFilter filter, TextureWrapping wrapSMode, TextureWrapping wrapTMode); void Set(TextureFilter filter, TextureWrapping wrapSMode, TextureWrapping wrapTMode); bool operator<(SamplerKey const & rhs) const; MTLSamplerDescriptor * BuildDescriptor() const; uint32_t m_sampler = 0; }; id<MTLDepthStencilState> GetDepthStencilState(id<MTLDevice> device, DepthStencilKey const & key); id<MTLRenderPipelineState> GetPipelineState(id<MTLDevice> device, PipelineKey const & key); id<MTLSamplerState> GetSamplerState(id<MTLDevice> device, SamplerKey const & key); void ResetPipelineStatesCache(); private: using DepthStencilCache = std::map<DepthStencilKey, id<MTLDepthStencilState>>; DepthStencilCache m_depthStencilCache; using PipelineCache = std::map<PipelineKey, id<MTLRenderPipelineState>>; PipelineCache m_pipelineCache; using SamplerCache = std::map<SamplerKey, id<MTLSamplerState>>; SamplerCache m_samplerCache; }; } // namespace metal } // namespace dp
32.3875
99
0.752605
kudlav
058175ced462290509186918414dff716bf41037
2,998
cxx
C++
inetsrv/iis/iisrearc/iisplus/ulw3/options_handler.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/iisrearc/iisplus/ulw3/options_handler.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/iisrearc/iisplus/ulw3/options_handler.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 2001 Microsoft Corporation Module Name : options_handler.cxx Abstract: Handle OPTIONS requests Author: Anil Ruia (AnilR) 4-Apr-2001 Environment: Win32 - User Mode Project: ULW3.DLL --*/ #include "precomp.hxx" #include "options_handler.hxx" CONTEXT_STATUS W3_OPTIONS_HANDLER::DoWork() /*++ Routine Description: Do the OPTIONS thing if DAV is disabled Return Value: CONTEXT_STATUS_PENDING if async pending, else CONTEXT_STATUS_CONTINUE --*/ { HRESULT hr; W3_CONTEXT *pW3Context = QueryW3Context(); DBG_ASSERT(pW3Context != NULL); W3_RESPONSE *pW3Response = pW3Context->QueryResponse(); W3_REQUEST *pW3Request = pW3Context->QueryRequest(); STACK_STRU (strUrl, MAX_PATH); if (FAILED(hr = pW3Response->SetHeader(HEADER("Public"), HEADER("OPTIONS, TRACE, GET, HEAD, POST")))) { goto Failed; } if (FAILED(hr = pW3Request->GetUrl(&strUrl))) { goto Failed; } if (wcscmp(strUrl.QueryStr(), L"*") != 0 && wcscmp(strUrl.QueryStr(), L"/*") != 0) { // // Add Allow header // if (FAILED(hr = pW3Context->SetupAllowHeader())) { goto Failed; } // // Also figure out whether Frontpage is enabled and send // MS-Author-Via header if so // Cannot store it with the metadata since we do not want to pick // up the inherited value, can store with url-info but deferred // for later (BUGBUG) // MB mb( g_pW3Server->QueryMDObject() ); BOOL fIsFrontPageWeb; if (!mb.Open(pW3Context->QuerySite()->QueryMBRoot()->QueryStr())) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Failed; } if (mb.GetDword(strUrl.QueryStr(), MD_FRONTPAGE_WEB, IIS_MD_UT_SERVER, (DWORD *)&fIsFrontPageWeb, METADATA_NO_ATTRIBUTES) && fIsFrontPageWeb) { if (FAILED(hr = pW3Response->SetHeader(HEADER("MS-Author-Via"), HEADER("MS-FP/4.0")))) { goto Failed; } } DBG_REQUIRE( mb.Close() ); } else { pW3Response->SetHeaderByReference(HttpHeaderAllow, HEADER("OPTIONS, TRACE, GET, HEAD, POST")); } if (FAILED(hr = pW3Context->SendResponse(W3_FLAG_ASYNC))) { goto Failed; } return CONTEXT_STATUS_PENDING; Failed: pW3Context->SetErrorStatus(hr); pW3Response->SetStatus(HttpStatusServerError); pW3Context->SendResponse(W3_FLAG_SYNC); return CONTEXT_STATUS_CONTINUE; }
24.77686
88
0.527352
npocmaka
0581e6944bec46067d0c8b50521a9f7e6ae526e9
467
cpp
C++
programmer/TestDataBus.cpp
cheinan/eeprom
690f9adeb7c3a06aec3c3600fd298b22ec76fb13
[ "MIT" ]
null
null
null
programmer/TestDataBus.cpp
cheinan/eeprom
690f9adeb7c3a06aec3c3600fd298b22ec76fb13
[ "MIT" ]
null
null
null
programmer/TestDataBus.cpp
cheinan/eeprom
690f9adeb7c3a06aec3c3600fd298b22ec76fb13
[ "MIT" ]
null
null
null
#include <iostream> #include "DataBus.h" #include "ControlLines.h" void TestDataBusWrite() { std::cout << "Testing the address bus\n"; ControlLines the_control_lines(HIGH, HIGH, HIGH); DataBus the_data_bus(true); unsigned short data = 1; for (unsigned char i = 0; i < 8;i++) { the_data_bus.Set(data); std::cout << "Data bus set to 0x" << std::hex << data << "\n"; std::cin.get(); data <<= 1; } } int main() { TestDataBusWrite(); return 0; }
15.566667
64
0.631692
cheinan
05824ee8344f61cfabe03ebd45d7232391c2a3e6
5,822
cpp
C++
llbc/src/core/objbase/DictionaryElem.cpp
lailongwei/llbc
ec7e69bfa1f0afece8bb19dfa9a0a4578508a077
[ "MIT" ]
83
2015-11-10T09:52:56.000Z
2022-01-12T11:53:01.000Z
llbc/src/core/objbase/DictionaryElem.cpp
lailongwei/llbc
ec7e69bfa1f0afece8bb19dfa9a0a4578508a077
[ "MIT" ]
30
2017-09-30T07:43:20.000Z
2022-01-23T13:18:48.000Z
llbc/src/core/objbase/DictionaryElem.cpp
lailongwei/llbc
ec7e69bfa1f0afece8bb19dfa9a0a4578508a077
[ "MIT" ]
34
2015-11-14T12:37:44.000Z
2021-12-16T02:38:36.000Z
// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // 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 "llbc/common/Export.h" #include "llbc/common/BeforeIncl.h" #include "llbc/common/Config.h" #include "llbc/core/os/OS_Console.h" #include "llbc/core/utils/Util_Debug.h" #include "llbc/core/objbase/Object.h" #include "llbc/core/objbase/KeyHashAlgorithm.h" #include "llbc/core/objbase/DictionaryElem.h" __LLBC_INTERNAL_NS_BEGIN static LLBC_NS LLBC_String __emptyStrKey; __LLBC_INTERNAL_NS_END __LLBC_NS_BEGIN LLBC_DictionaryElem::LLBC_DictionaryElem(int key, LLBC_Object *o) : _intKey(key) , _strKey(NULL) , _hash(0) , _obj(o) , _bucket(NULL) , _bucketSize(0) , _prev(NULL) , _next(NULL) , _bucketPrev(NULL) , _bucketNext(NULL) , _hashFun(*LLBC_KeyHashAlgorithmSingleton->GetAlgorithm(LLBC_CFG_OBJBASE_DICT_KEY_HASH_ALGO)) { o->Retain(); } LLBC_DictionaryElem::LLBC_DictionaryElem(const LLBC_String &key, LLBC_Object *o) : _intKey(0) , _strKey(LLBC_New(LLBC_String, key)) , _hash(0) , _obj(o) , _bucket(NULL) , _bucketSize(0) , _prev(NULL) , _next(NULL) , _bucketPrev(NULL) , _bucketNext(NULL) , _hashFun(*LLBC_KeyHashAlgorithmSingleton->GetAlgorithm(LLBC_CFG_OBJBASE_DICT_KEY_HASH_ALGO)) { o->Retain(); } LLBC_DictionaryElem::~LLBC_DictionaryElem() { LLBC_XDelete(_strKey); _obj->Release(); } bool LLBC_DictionaryElem::IsIntKey() const { return !_strKey; } bool LLBC_DictionaryElem::IsStrKey() const { return !!_strKey; } const int &LLBC_DictionaryElem::GetIntKey() const { return _intKey; } const LLBC_String &LLBC_DictionaryElem::GetStrKey() const { return _strKey ? *_strKey : LLBC_INL_NS __emptyStrKey; } uint32 LLBC_DictionaryElem::GetHashValue() const { return _hash; } LLBC_Object *&LLBC_DictionaryElem::GetObject() { return _obj; } LLBC_Object * const &LLBC_DictionaryElem::GetObject() const { return _obj; } void LLBC_DictionaryElem::Hash(LLBC_DictionaryElem **bucket, size_t bucketSize) { _bucket = bucket; _bucketSize = bucketSize; // Generate hash key. if(IsIntKey()) { _hash = _intKey % _bucketSize; } else { _hash = _hashFun(_strKey->c_str(), _strKey->size()) % static_cast<uint32>(_bucketSize); } // Link to hash bucket. SetBucketElemPrev(NULL); LLBC_DictionaryElem *&hashed = _bucket[_hash]; if(!hashed) { SetBucketElemNext(NULL); hashed = this; } else { hashed->SetBucketElemPrev(this); SetBucketElemNext(hashed); hashed = this; #ifdef LLBC_DEBUG int confictCount = 0; LLBC_DictionaryElem *countElem = hashed; for(; countElem != NULL; countElem = countElem->GetBucketElemNext()) { confictCount += 1; } trace("Dictionary(addr: %x), key confict!, bucket: %d, count: %d\n", this, _hash, confictCount); #endif } } void LLBC_DictionaryElem::CancelHash() { if(_bucket[_hash] == this) { _bucket[_hash] = GetBucketElemNext(); } if(GetBucketElemPrev()) { GetBucketElemPrev()-> SetBucketElemNext(GetBucketElemNext()); } if(GetBucketElemNext()) { GetBucketElemNext()-> SetBucketElemPrev(GetBucketElemPrev()); } } LLBC_DictionaryElem **LLBC_DictionaryElem::GetBucket() { return _bucket; } size_t LLBC_DictionaryElem::GetBucketSize() const { return _bucketSize; } LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemPrev() { return _prev; } const LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemPrev() const { return _prev; } void LLBC_DictionaryElem::SetElemPrev(LLBC_DictionaryElem *prev) { _prev = prev; } LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemNext() { return _next; } const LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemNext() const { return _next; } void LLBC_DictionaryElem::SetElemNext(LLBC_DictionaryElem *next) { _next = next; } LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemPrev() { return _bucketPrev; } const LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemPrev() const { return _bucketPrev; } void LLBC_DictionaryElem::SetBucketElemPrev(LLBC_DictionaryElem *prev) { _bucketPrev = prev; } LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemNext() { return _bucketNext; } const LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemNext() const { return _bucketNext; } void LLBC_DictionaryElem::SetBucketElemNext(LLBC_DictionaryElem *next) { _bucketNext = next; } LLBC_Object *&LLBC_DictionaryElem::operator *() { return _obj; } LLBC_Object * const &LLBC_DictionaryElem::operator *() const { return _obj; } __LLBC_NS_END #include "llbc/common/AfterIncl.h"
21.562963
104
0.714703
lailongwei
0589d911fb2a560a6c1cddd47658091dd08c6672
1,669
cpp
C++
src/core/configuration/JSONConfiguration.cpp
FrankPfirmann/opovlint
5e0925650cd469fdcd74240dd0d6ac603097e6f3
[ "MIT" ]
5
2015-05-15T23:27:08.000Z
2019-09-28T07:21:42.000Z
src/core/configuration/JSONConfiguration.cpp
FrankPfirmann/opovlint
5e0925650cd469fdcd74240dd0d6ac603097e6f3
[ "MIT" ]
null
null
null
src/core/configuration/JSONConfiguration.cpp
FrankPfirmann/opovlint
5e0925650cd469fdcd74240dd0d6ac603097e6f3
[ "MIT" ]
3
2015-07-16T09:09:42.000Z
2019-10-02T18:32:41.000Z
/* * JSONConfiguration.cpp * * Created on: Jul 10, 2014 * Author: ahueck */ #include <core/configuration/JSONConfiguration.h> #include <core/logging/Logger.h> #include <fstream> namespace opov { JSONConfiguration::JSONConfiguration() { // TODO Auto-generated constructor stub } bool JSONConfiguration::load(const std::string& file) { std::ifstream in(file); if (!in.is_open()) { LOG_INFO("Configuration file not found: " << file << ". Exiting..."); return false; } json::parse(in, data); return true; } void JSONConfiguration::getValue(const std::string& id, std::string& val, std::string def) const { val = get<std::string>(id, std::move(def)); } void JSONConfiguration::getValue(const std::string& id, double& val, double def) const { val = get<double>(id, std::move(def)); } void JSONConfiguration::getValue(const std::string& id, int& val, int def) const { val = get<int>(id, std::move(def)); } void JSONConfiguration::getValue(const std::string& id, bool& val, bool def) const { val = get<bool>(id, std::move(def)); } void JSONConfiguration::getVector(const std::string& id, std::vector<std::string>& vec) const { vec = getVec<std::string>(id); } void JSONConfiguration::getVector(const std::string& id, std::vector<double>& vec) const { vec = getVec<double>(id); } void JSONConfiguration::getVector(const std::string& id, std::vector<int>& vec) const { vec = getVec<int>(id); } void JSONConfiguration::getVector(const std::string& id, std::vector<bool>& vec) const { vec = getVec<bool>(id); } JSONConfiguration::~JSONConfiguration() { // TODO Auto-generated destructor stub } } /* namespace opov */
25.287879
98
0.683643
FrankPfirmann
058b8021a09c1ed7b9b95f8b5c2a0d66fc88c4d5
4,281
hh
C++
src/phantasm-renderer/ComputePass.hh
project-arcana/phantasm-renderer
dd6f9af8d95f227f88c81194dea4a893761cac62
[ "MIT" ]
2
2020-10-22T18:09:11.000Z
2020-12-09T13:53:46.000Z
src/phantasm-renderer/ComputePass.hh
project-arcana/phantasm-renderer
dd6f9af8d95f227f88c81194dea4a893761cac62
[ "MIT" ]
1
2021-04-29T08:16:49.000Z
2021-04-30T07:54:25.000Z
src/phantasm-renderer/ComputePass.hh
project-arcana/phantasm-renderer
dd6f9af8d95f227f88c81194dea4a893761cac62
[ "MIT" ]
null
null
null
#pragma once #include <phantasm-hardware-interface/commands.hh> #include <phantasm-renderer/argument.hh> #include <phantasm-renderer/common/api.hh> #include <phantasm-renderer/fwd.hh> #include <phantasm-renderer/resource_types.hh> namespace pr::raii { class Frame; class PR_API ComputePass { public: [[nodiscard]] ComputePass bind(prebuilt_argument const& sv) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_argument(sv._sv, phi::handle::null_resource, 0); return p; } [[nodiscard]] ComputePass bind(prebuilt_argument const& sv, buffer const& constant_buffer, uint32_t constant_buffer_offset = 0) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_argument(sv._sv, constant_buffer.res.handle, constant_buffer_offset); return p; } // CBV only [[nodiscard]] ComputePass bind(buffer const& constant_buffer, uint32_t constant_buffer_offset = 0) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_argument(phi::handle::null_shader_view, constant_buffer.res.handle, constant_buffer_offset); return p; } // raw phi [[nodiscard]] ComputePass bind(phi::handle::shader_view sv, phi::handle::resource cbv = phi::handle::null_resource, uint32_t cbv_offset = 0) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_argument(sv, cbv, cbv_offset); return p; } // cache-access variants // hits a OS mutex [[nodiscard]] ComputePass bind(argument const& arg) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_cached_argument(arg, phi::handle::null_resource, 0); return p; } [[nodiscard]] ComputePass bind(argument const& arg, buffer const& constant_buffer, uint32_t constant_buffer_offset = 0) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_cached_argument(arg, constant_buffer.res.handle, constant_buffer_offset); return p; } void dispatch(uint32_t x, uint32_t y = 1, uint32_t z = 1); void dispatch_indirect(buffer const& argument_buffer, uint32_t num_arguments = 1, uint32_t offset_bytes = 0); void set_constant_buffer(buffer const& constant_buffer, unsigned offset = 0); void set_constant_buffer(phi::handle::resource raw_cbv, unsigned offset = 0); void set_constant_buffer_offset(unsigned offset); template <class T> void write_constants(T const& val) { mCmd.write_root_constants<T>(val); } ComputePass(ComputePass&& rhs) = default; private: friend class Frame; // Frame-side ctor ComputePass(Frame* parent, phi::handle::pipeline_state pso) : mParent(parent) { mCmd.pipeline_state = pso; } private: // internal re-bind ctor ComputePass(Frame* parent, phi::cmd::dispatch const& cmd, unsigned arg_i) : mParent(parent), mCmd(cmd), mArgNum(arg_i) {} private: // persisted, raw phi void add_argument(phi::handle::shader_view sv, phi::handle::resource cbv, uint32_t cbv_offset); // cache-access variant // hits a OS mutex void add_cached_argument(argument const& arg, phi::handle::resource cbv, uint32_t cbv_offset); Frame* mParent = nullptr; phi::cmd::dispatch mCmd; // index of owning argument - 1, 0 means no arguments existing unsigned mArgNum = 0; }; // inline implementation inline void ComputePass::set_constant_buffer(const buffer& constant_buffer, unsigned offset) { set_constant_buffer(constant_buffer.res.handle, offset); } inline void ComputePass::set_constant_buffer(phi::handle::resource raw_cbv, unsigned offset) { CC_ASSERT(mArgNum != 0 && "Attempted to set_constant_buffer on a ComputePass without prior bind"); mCmd.shader_arguments[uint8_t(mArgNum - 1)].constant_buffer = raw_cbv; mCmd.shader_arguments[uint8_t(mArgNum - 1)].constant_buffer_offset = offset; } inline void ComputePass::set_constant_buffer_offset(unsigned offset) { CC_ASSERT(mArgNum != 0 && "Attempted to set_constant_buffer_offset on a ComputePass without prior bind"); mCmd.shader_arguments[uint8_t(mArgNum - 1)].constant_buffer_offset = offset; } inline void ComputePass::add_argument(phi::handle::shader_view sv, phi::handle::resource cbv, uint32_t cbv_offset) { ++mArgNum; mCmd.add_shader_arg(cbv, cbv_offset, sv); } }
33.445313
144
0.705443
project-arcana
058dbe3b9450e1fda9666c2ec33f238bee8610a0
3,337
cpp
C++
src/Engine/ResourceManager.cpp
ennis/autograph-pipelines
afc66ef60bf99fca26d200bd7739528e1bf3ed8c
[ "MIT" ]
1
2021-04-24T12:29:42.000Z
2021-04-24T12:29:42.000Z
src/Engine/ResourceManager.cpp
ennis/autograph-pipelines
afc66ef60bf99fca26d200bd7739528e1bf3ed8c
[ "MIT" ]
null
null
null
src/Engine/ResourceManager.cpp
ennis/autograph-pipelines
afc66ef60bf99fca26d200bd7739528e1bf3ed8c
[ "MIT" ]
null
null
null
#include <autograph/Core/Support/Debug.h> #include <autograph/Core/Support/string_view.h> #include <autograph/Core/Types.h> #include <autograph/Engine/ResourceManager.h> #include <experimental/filesystem> namespace ag { namespace fs = std::experimental::filesystem; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// namespace ResourceManager { static std::vector<std::string> resourceDirectories_; // returns the main path part of the ID, or the empty string if it has none std::string getPathPart(const char *id) { ag::string_view idstr{id}; return idstr.substr(0, idstr.find_last_of('$')).to_string(); } std::string getPathPart(const std::string &id) { return getPathPart(id.c_str()); } // returns the subpath part of the ID, or the empty string if it has none std::string getSubpathPart(const char *id) { ag::string_view idstr{id}; auto p = idstr.find_last_of('$'); if (p == std::string::npos) { return {}; } else { return idstr.substr(p + 1).to_string(); } } std::string getSubpathPart(const std::string &id) { return getSubpathPart(id.c_str()); } std::string getParentPath(const char *id) { fs::path path = getPathPart(id); return path.parent_path().generic_string(); } std::string getParentPath(const std::string &id) { return getParentPath(id.c_str()); } void addResourceDirectory(const std::string &fullPath) { addResourceDirectory(fullPath.c_str()); } void addResourceDirectory(const char *fullPath) { resourceDirectories_.emplace_back(fullPath); } int getResourceDirectoriesCount() { return (int)resourceDirectories_.size(); } std::string getResourceDirectory(int index) { return resourceDirectories_[index]; } std::string getFilesystemPath(const char *id) { return getFilesystemPath(id, {}); } std::string getFilesystemPath(const std::string &id) { return getFilesystemPath(id.c_str()); } std::string getFilesystemPath(const char *id, ag::span<const char *const> prefixes) { namespace fs = std::experimental::filesystem; std::string pathPart = getPathPart(id); std::string ret; // first, check if ID is a well-specified filesystem path fs::path path{pathPart}; if (fs::is_regular_file(path)) { return pathPart; } for (auto &dir : resourceDirectories_) { fs::path baseDir{dir}; if (prefixes.empty()) { auto fullPath = baseDir / pathPart; if (fs::is_regular_file(fullPath)) { // got our file AG_DEBUG("{} -> {}", pathPart, fullPath.string()); ret = fullPath.string(); return ret; } } else { for (auto prefix : prefixes) { auto fullPath = baseDir / prefix / pathPart; if (fs::is_regular_file(fullPath)) { // got our file AG_DEBUG("{} -> {}", pathPart, fullPath.string()); ret = fullPath.string(); return ret; } } } } AG_DEBUG("findResourceFile: {} not found", pathPart); AG_DEBUG(" Tried directories:"); for (auto &dir : resourceDirectories_) { AG_DEBUG(" - {}", dir); } if (!prefixes.empty()) { AG_DEBUG(" Tried prefixes:"); for (auto prefix : prefixes) { AG_DEBUG(" - {}", prefix); } } return {}; } } // namespace ResourceManager } // namespace ag
26.91129
78
0.633203
ennis
058e03ba87822896688a16ae33e7c0490f2658e7
5,344
cpp
C++
particles-simulator/src/OpenGL/Shader.cpp
bartos97/particles-simulator
dc2fc18fbc047803b3c17d7cc7bf9dbc99b00a2b
[ "WTFPL" ]
null
null
null
particles-simulator/src/OpenGL/Shader.cpp
bartos97/particles-simulator
dc2fc18fbc047803b3c17d7cc7bf9dbc99b00a2b
[ "WTFPL" ]
null
null
null
particles-simulator/src/OpenGL/Shader.cpp
bartos97/particles-simulator
dc2fc18fbc047803b3c17d7cc7bf9dbc99b00a2b
[ "WTFPL" ]
null
null
null
#include "pch.h" #include "Shader.h" #include <fstream> #include <sstream> const Shader* Shader::m_currentlyBound = nullptr; Shader::Shader(const char* vertexShaderPath, const char* fragmentShaderPath) : m_id(0) { PS_LOG("Shader object constructed"); assignData(vertexShaderPath, fragmentShaderPath); m_isDataAssigned = true; } Shader::Shader() : m_isDataAssigned(false), m_id(0) { PS_LOG("Shader object constructed without data assignment!"); } Shader::~Shader() { GL_CALL(glDeleteProgram(m_id)); PS_LOG("Shader #%d deleted", m_id); } void Shader::assignData(const char* vertexShaderPath, const char* fragmentShaderPath) { std::string vertexStr; std::string fragmentStr; readFiles(vertexShaderPath, fragmentShaderPath, vertexStr, fragmentStr); createShaderProgram(vertexStr, fragmentStr); m_isDataAssigned = true; PS_LOG("Shader #%d data assigned", m_id); } void Shader::bind() const { PS_ASSERT(m_isDataAssigned, "Tring to bind Shader without data assigned!"); if (Shader::m_currentlyBound != this) { GL_CALL(glUseProgram(m_id)); Shader::m_currentlyBound = this; PS_LOG("Shader #%d is now bound", m_id); } } void Shader::unbind() const { GL_CALL(glUseProgram(0)); Shader::m_currentlyBound = nullptr; PS_LOG("No Shader bound."); } void Shader::setUniform(const std::string& name, float x) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform1f(location, x); } void Shader::setUniform(const std::string& name, bool x) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform1i(location, x); } void Shader::setUniform(const std::string& name, int x) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform1i(location, x); } void Shader::setUniform(const std::string& name, float x, float y, float z, float w) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform4f(location, x, y, z, w); } void Shader::setUniform(const std::string& name, const glm::vec4& vec) { setUniform(name, vec.x, vec.y, vec.z, vec.w); } void Shader::setUniform(const std::string& name, float x, float y, float z) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform3f(location, x, y, z); } void Shader::setUniform(const std::string& name, const glm::vec3& vec) { setUniform(name, vec.x, vec.y, vec.z); } void Shader::setUniform(const std::string& name, float x, float y) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform2f(location, x, y); } void Shader::setUniform(const std::string& name, const glm::vec2& vec) { setUniform(name, vec.x, vec.y); } void Shader::setUniform(const std::string& name, const glm::mat4& mat) { int location = glGetUniformLocation(m_id, name.c_str()); glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(mat)); } void Shader::setUniform(const std::string& name, const glm::mat3& mat) { int location = glGetUniformLocation(m_id, name.c_str()); glUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(mat)); } void Shader::readFiles(const char* vertexShaderPath, const char* fragmentShaderPath, std::string& vertexStr, std::string& fragmentStr) { std::ifstream vertexFile; std::ifstream fragmentFile; vertexFile.exceptions(std::ifstream::badbit | std::ifstream::failbit); fragmentFile.exceptions(std::ifstream::badbit | std::ifstream::failbit); try { std::stringstream vertexStream; vertexFile.open(vertexShaderPath); vertexStream << vertexFile.rdbuf(); vertexFile.close(); vertexStr = vertexStream.str(); std::stringstream fragmentStream; fragmentFile.open(fragmentShaderPath); fragmentStream << fragmentFile.rdbuf(); fragmentFile.close(); fragmentStr = fragmentStream.str(); } catch (const std::exception & e) { PS_ASSERT(false, "Failed with some shader file!\n%s", e.what()); } } void Shader::createShaderProgram(std::string& vertexStr, std::string& fragmentStr) { unsigned int vertexShader = compileSingleShader(vertexStr.c_str(), GL_VERTEX_SHADER); unsigned int fragmentShader = compileSingleShader(fragmentStr.c_str(), GL_FRAGMENT_SHADER); int success; GL_CALL(m_id = glCreateProgram()); GL_CALL(glAttachShader(m_id, vertexShader)); GL_CALL(glAttachShader(m_id, fragmentShader)); GL_CALL(glLinkProgram(m_id)); glGetProgramiv(m_id, GL_LINK_STATUS, &success); if (!success) { char errorInfo[512]; glGetProgramInfoLog(m_id, 512, NULL, errorInfo); PS_ASSERT(success, "%s", errorInfo); } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); } unsigned int Shader::compileSingleShader(const char* shaderStr, GLenum shaderEnum) { int success; GL_CALL(unsigned int shader = glCreateShader(shaderEnum)); GL_CALL(glShaderSource(shader, 1, &shaderStr, NULL)); GL_CALL(glCompileShader(shader)); glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { char errorInfo[512]; glGetShaderInfoLog(shader, 512, NULL, errorInfo); PS_ASSERT(success, "%s", errorInfo); } return shader; }
26.72
95
0.680015
bartos97
05901ad8b5edb9a693c390620e47089fdada2186
384
hpp
C++
Loader.hpp
mcgillowen/cpsc453-hw2
2276beec4102da044a4d2c4888089a5eb47eb79c
[ "MIT" ]
null
null
null
Loader.hpp
mcgillowen/cpsc453-hw2
2276beec4102da044a4d2c4888089a5eb47eb79c
[ "MIT" ]
null
null
null
Loader.hpp
mcgillowen/cpsc453-hw2
2276beec4102da044a4d2c4888089a5eb47eb79c
[ "MIT" ]
null
null
null
// Loader.hpp // Class that loads a .obj file into vectors of floats for OpenGL #ifndef LOADER_HPP #define LOADER_HPP #include <vector> #include "IndexedVertexArray.hpp" #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> using std::vector; class Loader { private: public: static IndexedVertexArray* loadObjFile(const char * path); }; #endif // LOADER_HPP
16
66
0.713542
mcgillowen
05908226497d855649fa2daee06a5d7100e553ec
870
cpp
C++
src/problem38/Solution1.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
1
2016-09-29T14:23:59.000Z
2016-09-29T14:23:59.000Z
src/problem38/Solution1.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
src/problem38/Solution1.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
class Solution { public: string countAndSay(int n) { int curr = 1; string curr_str = "1"; while (curr < n) { curr++; string newString; char curr_char = ' '; int count = 0; for (int i = 0; i < curr_str.size(); i++) { if (curr_str[i] == curr_char) { count++; } else { if (curr_char != ' ') { newString.push_back('1' + count - 1); newString.push_back(curr_char); } curr_char = curr_str[i]; count = 1; } } newString.push_back('1' + count - 1); newString.push_back(curr_char); curr_str = newString; } return curr_str; } };
29
61
0.385057
MyYaYa
0592b8544d8f02b6d232bbf9bdfc1fc0afe312a1
2,041
cc
C++
cc/xlsx-read-test.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/xlsx-read-test.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/xlsx-read-test.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
#include "acmacs-base/argv.hh" #include "acmacs-base/read-file.hh" #include "acmacs-base/range-v3.hh" #include "acmacs-whocc/xlsx.hh" #include "acmacs-whocc/log.hh" // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } option<str_array> verbose{*this, 'v', "verbose", desc{"comma separated list (or multiple switches) of enablers"}}; argument<str_array> xlsx{*this, arg_name{".xlsx"}, mandatory}; }; int main(int argc, char* const argv[]) { using namespace std::string_view_literals; using namespace acmacs; int exit_code = 0; try { Options opt(argc, argv); acmacs::log::enable(opt.verbose); for (const auto& filename : *opt.xlsx) { AD_INFO("{}", filename); auto doc = acmacs::xlsx::open(filename); // AD_INFO("{} sheets: {}", filename, doc.number_of_sheets()); for (const auto sheet_no : range_from_0_to(doc.number_of_sheets())) { auto sheet = doc.sheet(sheet_no); AD_INFO(" {}: \"{}\" {}-{}", sheet_no + 1, sheet->name(), sheet->number_of_rows(), sheet->number_of_columns()); for (acmacs::sheet::nrow_t row{0}; row < sheet->number_of_rows(); ++row) { for (acmacs::sheet::ncol_t col{0}; col < sheet->number_of_columns(); ++col) { const auto cell = fmt::format("{}", sheet->cell(row, col)); AD_LOG(acmacs::log::xlsx, "cell {}{}: \"{}\"", row, col, cell); } } } } } catch (std::exception& err) { AD_ERROR("{}", err); exit_code = 2; } return exit_code; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
36.446429
130
0.525723
acorg
059328b8c4f845f40f3560aa5835da3fa0c383a4
19,719
cpp
C++
inetcore/outlookexpress/mailnews/news/pickgrp.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/outlookexpress/mailnews/news/pickgrp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/outlookexpress/mailnews/news/pickgrp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
///////////////////////////////////////////////////////////////////////////// // Copyright (C) 1993-1996 Microsoft Corporation. All Rights Reserved. // // MODULE: PickGrp.cpp // // PURPOSE: Dialog to allow the user to select groups to post to in the // send note window. // #include "pch.hxx" #include <iert.h> #include "pickgrp.h" #include "grplist2.h" #include "shlwapip.h" #include "resource.h" #include "strconst.h" #include "demand.h" CPickGroupDlg::CPickGroupDlg() { m_cRef = 1; m_ppszGroups = 0; m_hwndPostTo = 0; m_fPoster = FALSE; m_hIcon = NULL; m_pGrpList = NULL; m_pszAcct = NULL; m_idAcct = FOLDERID_INVALID; } CPickGroupDlg::~CPickGroupDlg() { if (m_hIcon) SideAssert(DestroyIcon(m_hIcon)); if (m_pGrpList != NULL) m_pGrpList->Release(); } HRESULT STDMETHODCALLTYPE CPickGroupDlg::QueryInterface(REFIID riid, void **ppvObj) { if (IsEqualIID(riid, IID_IUnknown)) *ppvObj = (void*) (IUnknown *)(IGroupListAdvise *)this; else if (IsEqualIID(riid, IID_IGroupListAdvise)) *ppvObj = (void*) (IGroupListAdvise *) this; else { *ppvObj = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; } ULONG STDMETHODCALLTYPE CPickGroupDlg::AddRef() { return ++m_cRef; } ULONG STDMETHODCALLTYPE CPickGroupDlg::Release() { if (--m_cRef == 0) { delete this; return 0; } return m_cRef; } // // FUNCTION: CPickGroupsDlg::FCreate() // // PURPOSE: Handles initialization of the data and creation of the pick // groups dialog. // // PARAMETERS: // hwndOwner - Window that will own this dialog. // pszAccount - account to use initially. // ppszGroups - This is where we return the last selected group // // RETURN VALUE: // Returns TRUE if successful, or FALSE otherwise. // BOOL CPickGroupDlg::FCreate(HWND hwndOwner, FOLDERID idServer, LPSTR *ppszGroups, BOOL fPoster) { int iret; HRESULT hr; FOLDERID idAcct; FOLDERINFO info; char szAcct[CCHMAX_ACCOUNT_NAME]; Assert(ppszGroups != NULL); m_pGrpList = new CGroupList; if (m_pGrpList == NULL) return(FALSE); m_ppszGroups = ppszGroups; m_fPoster = fPoster; hr = g_pStore->GetFolderInfo(idServer, &info); if (FAILED(hr)) return(FALSE); StrCpyN(szAcct, info.pszName, ARRAYSIZE(szAcct)); g_pStore->FreeRecord(&info); m_pszAcct = szAcct; m_idAcct = idServer; // Now create the dialog. iret = (int) DialogBoxParam(g_hLocRes, MAKEINTRESOURCE(iddPickGroup), hwndOwner, PickGrpDlgProc, (LPARAM)this); return(iret == IDOK); } INT_PTR CALLBACK CPickGroupDlg::PickGrpDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { BOOL fRet; CPickGroupDlg *pThis; fRet = TRUE; pThis = (CPickGroupDlg *)GetWindowLongPtr(hwnd, DWLP_USER); switch (msg) { case WM_INITDIALOG: Assert(pThis == NULL); Assert(lParam != NULL); pThis = (CPickGroupDlg *)lParam; SetWindowLongPtr(hwnd, DWLP_USER, (LPARAM)pThis); fRet = pThis->_OnInitDialog(hwnd); break; case WM_CLOSE: pThis->_OnClose(hwnd); break; case WM_COMMAND: pThis->_OnCommand(hwnd, LOWORD(wParam), (HWND)lParam, HIWORD(wParam)); break; case WM_NOTIFY: pThis->_OnNotify(hwnd, (int)wParam, (LPNMHDR)lParam); break; case WM_TIMER: pThis->_OnTimer(hwnd, (UINT)wParam); break; case WM_PAINT: pThis->_OnPaint(hwnd); break; case NVM_CHANGESERVERS: pThis->_OnChangeServers(hwnd); break; default: fRet = FALSE; break; } return(fRet); } // // FUNCTION: CPickGroupDlg::OnInitDialog() // // PURPOSE: Handles initializing the PickGroup dialog. Initializes the // dependant classes, list view, buttons, etc. // // PARAMETERS: // hwnd - Handle of the dialog box. // hwndFocus - Handle of the control that will get focus if TRUE is returned. // lParam - Contains a pointer to a string of newsgroups the user has // already selected. // // RETURN VALUE: // Returns TRUE to set the focus to hwndFocus, or FALSE otherwise. // BOOL CPickGroupDlg::_OnInitDialog(HWND hwnd) { char szTitle[256]; LV_COLUMN lvc; RECT rc; LONG cx; HDC hdc; TEXTMETRIC tm; HIMAGELIST himl; HRESULT hr; HWND hwndList; CColumns *pColumns; m_hwnd = hwnd; m_hwndPostTo = GetDlgItem(hwnd, idcPostTo); hwndList = GetDlgItem(hwnd, idcGroupList); pColumns = new CColumns; if (pColumns == NULL) { EndDialog(hwnd, IDCANCEL); return(FALSE); } pColumns->Initialize(hwndList, COLUMN_SET_PICKGRP); pColumns->ApplyColumns(COLUMN_LOAD_DEFAULT, 0, 0); Assert(m_pGrpList != NULL); hr = m_pGrpList->Initialize((IGroupListAdvise *)this, pColumns, hwndList, FOLDER_NEWS); Assert(SUCCEEDED(hr)); pColumns->Release(); // Bug #21471 - Add the server name to the dialog box title GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle)); Assert(m_pszAcct); StrCatBuff(szTitle, m_pszAcct, ARRAYSIZE(szTitle)); SetWindowText(hwnd, szTitle); GetClientRect(m_hwndPostTo, &rc); // Set the image lists for the listview himl = ImageList_LoadBitmap(g_hLocRes, MAKEINTRESOURCE(idbFolders), 16, 0, RGB(255, 0, 255)); Assert(himl); // Group name column lvc.mask = LVCF_SUBITEM | LVCF_WIDTH; lvc.cx = rc.right; lvc.iSubItem = 0; ListView_InsertColumn(m_hwndPostTo, 0, &lvc); // Make the second listview have images too ListView_SetImageList(m_hwndPostTo, himl, LVSIL_SMALL); hdc = GetDC(hwndList); if (GetTextMetrics(hdc, &tm)) { cx = tm.tmAveCharWidth * 150; ListView_SetColumnWidth(hwndList, 0, cx); ListView_SetColumnWidth(m_hwndPostTo, 0, cx); } ReleaseDC(hwndList, hdc); SendDlgItemMessage(hwnd, idcShowFavorites, BM_SETCHECK, TRUE, 0L); if (!m_fPoster) ShowWindow(GetDlgItem(hwnd, idcEmailAuthor), SW_HIDE); m_hIcon = (HICON)LoadImage(g_hLocRes, MAKEINTRESOURCE(idiNewsGroup), IMAGE_ICON, 16, 16, 0); SendDlgItemMessage(hwnd, idcShowFavorites, BM_SETIMAGE, IMAGE_ICON, (LPARAM)m_hIcon); PostMessage(hwnd, NVM_CHANGESERVERS, 0, 0L); return(FALSE); } BOOL CPickGroupDlg::_OnFilter(HWND hwnd) { UINT cch; LPSTR pszText; HRESULT hr; BOOL fSub; HWND hwndEdit; pszText = NULL; hwndEdit = GetDlgItem(hwnd, idcFindText); cch = GetWindowTextLength(hwndEdit); if (cch > 0) { cch++; if (!MemAlloc((void **)&pszText, cch + 1)) return(FALSE); GetWindowText(hwndEdit, pszText, cch); } fSub = (IsDlgButtonChecked(hwnd, idcShowFavorites)); hr = m_pGrpList->Filter(pszText, fSub ? SUB_TAB_SUBSCRIBED : SUB_TAB_ALL, FALSE); Assert(SUCCEEDED(hr)); if (pszText != NULL) MemFree(pszText); return(TRUE); } void CPickGroupDlg::_OnChangeServers(HWND hwnd) { LPSTR pszTok, pszToken; UINT index; HRESULT hr; FOLDERINFO Folder; // TODO: we need to fix the initialization so the filtering is only performed // once (we should call IGroupList::Filter once and then IGroupList::SetServer once // during creation of the dialog) UpdateWindow(hwnd); _OnFilter(hwnd); hr = m_pGrpList->SetServer(m_idAcct); Assert(SUCCEEDED(hr)); if (m_ppszGroups) { pszTok = *m_ppszGroups; pszToken = StrTokEx(&pszTok, c_szDelimiters); while (pszToken != NULL) { if (m_fPoster && 0 == lstrcmpi(pszToken, c_szPosterKeyword)) CheckDlgButton(hwnd, idcEmailAuthor, TRUE); ZeroMemory(&Folder, sizeof(FOLDERINFO)); Folder.idParent = m_idAcct; Folder.pszName = pszToken; if (DB_S_FOUND == g_pStore->FindRecord(IINDEX_ALL, COLUMNS_ALL, &Folder, NULL)) { _InsertList(Folder.idFolder); g_pStore->FreeRecord(&Folder); } pszToken = StrTokEx(&pszTok, c_szDelimiters); } MemFree(*m_ppszGroups); *m_ppszGroups = 0; } // Bug #17674 - Make sure the post-to listview has an initial selection. ListView_SetItemState(m_hwndPostTo, 0, LVIS_SELECTED, LVIS_SELECTED); _UpdateStateUI(hwnd); } // // FUNCTION: CPickGroupDlg::OnCommand() // // PURPOSE: Processes the WM_COMMAND messages for the pick group dialog. // // PARAMETERS: // hwnd - Handle of the dialog window. // id - ID of the control which sent the message. // hwndCtl - Handle of the control sending the message. // codeNotify - Notification code being sent. // void CPickGroupDlg::_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { switch (id) { case idcAddGroup: _AddGroup(); break; case idcRemoveGroup: _RemoveGroup(); break; case IDOK: if (_OnOK(hwnd)) EndDialog(hwnd, IDOK); break; case IDCANCEL: EndDialog(hwnd, IDCANCEL); break; case idcShowFavorites: _OnFilter(hwnd); _UpdateStateUI(hwnd); break; case idcFindText: // This is generated when someone types in the find text edit box. // We set a timer and when that timer expires we assume the user is // done typing and go ahead and perform the query. if (EN_CHANGE == codeNotify) { KillTimer(hwnd, idtFindDelay); SetTimer(hwnd, idtFindDelay, dtFindDelay, NULL); } break; } } HRESULT CPickGroupDlg::ItemUpdate(void) { _UpdateStateUI(m_hwnd); return(S_OK); } HRESULT CPickGroupDlg::ItemActivate(FOLDERID id) { _AddGroup(); return(S_OK); } // // FUNCTION: CPickGroupDlg::OnNotify() // // PURPOSE: Handles notification messages from the group list listview. // // PARAMETERS: // hwnd - Handle of the pick group dialog. // idFrom - ID of the control sending the notification. // pnmhdr - Pointer to the NMHDR struct with the notification info. // // RETURN VALUE: // Dependent on the notification. // LRESULT CPickGroupDlg::_OnNotify(HWND hwnd, int idFrom, LPNMHDR pnmhdr) { HRESULT hr; LRESULT lRes; hr = m_pGrpList->HandleNotify(hwnd, idFrom, pnmhdr, &lRes); if (hr == S_OK) return(lRes); switch (pnmhdr->code) { case NM_DBLCLK: if (pnmhdr->hwndFrom == m_hwndPostTo) _RemoveGroup(); break; case LVN_ITEMCHANGED: _UpdateStateUI(hwnd); break; } return(0); } void CPickGroupDlg::_OnTimer(HWND hwnd, UINT id) { KillTimer(hwnd, id); _OnFilter(hwnd); _UpdateStateUI(hwnd); } void CPickGroupDlg::_OnClose(HWND hwnd) { int iReturn; iReturn = AthMessageBoxW(hwnd, MAKEINTRESOURCEW(idsAthenaNews), MAKEINTRESOURCEW(idsDoYouWantToSave), 0, MB_YESNOCANCEL | MB_ICONEXCLAMATION ); if (iReturn == IDYES) _OnCommand(hwnd, IDOK, 0, 0); else if (iReturn == IDNO) _OnCommand(hwnd, IDCANCEL, 0, 0); } // // FUNCTION: CPickGroupDlg::OnOK() // // PURPOSE: This function copies the group names from the dialog that // the user has selected and returns them in the pointer the // caller provided. // // RETURN VALUE: // Returns TRUE if the copy was successful, or FALSE otherwise. // // COMMENTS: // Note - 1000 characters is a good maximum line length (specified by the // Son-of-RFC 1036 doc) so we limit the number of groups based on // this line limit. // // BOOL CPickGroupDlg::_OnOK(HWND hwnd) { // OK, we've got the entire sorted list. Create a string with all the groups // and put it in the edit control. char szGroups[c_cchLineMax], szGroup[256]; int cGroups; LPSTR psz; LV_ITEM lvi; int cchGroups = 0, cch; szGroups[0] = 0; if (m_fPoster && IsDlgButtonChecked(hwnd, idcEmailAuthor)) { StrCatBuff(szGroups, c_szPosterKeyword, ARRAYSIZE(szGroups)); cchGroups += lstrlen(c_szPosterKeyword); } if (cGroups = ListView_GetItemCount(m_hwndPostTo)) { lvi.mask = LVIF_TEXT; lvi.iSubItem = 0; lvi.pszText = szGroup; lvi.cchTextMax = ARRAYSIZE(szGroup); for (lvi.iItem = 0; lvi.iItem < cGroups; lvi.iItem++) { // Get the item ListView_GetItem(m_hwndPostTo, &lvi); // Make sure the length of this next group doesn't push us over // the max line length. cch = lstrlen(lvi.pszText); if ((cch + cchGroups + 2) > c_cchLineMax) { // Bug #24156 - If we have to truncate, then let the user know. AthMessageBoxW(hwnd, MAKEINTRESOURCEW(idsAthenaNews), MAKEINTRESOURCEW(idsErrNewsgroupLineTooLong), 0, MB_OK | MB_ICONINFORMATION); return (FALSE); } if (cchGroups) { StrCatBuff(szGroups, ", ", ARRAYSIZE(szGroups)); } StrCatBuff(szGroups, lvi.pszText, ARRAYSIZE(szGroups)); cchGroups += (cch + 2); } } // Now that we're done building this marvelous string, copy it to // the buffer for returning. if (!MemAlloc((LPVOID *)&psz, cchGroups + 1)) return(FALSE); StrCpyN(psz, szGroups, cchGroups + 1); *m_ppszGroups = psz; return(TRUE); } // // FUNCTION: CPickGroupDlg::AddGroup() // // PURPOSE: Takes the group names selected in the ListView and adds them // to the selected groups Post To list. // void CPickGroupDlg::_AddGroup(void) { FOLDERID *pid; DWORD cid, i; HCURSOR hcur; HRESULT hr; hcur = SetCursor(LoadCursor(NULL, IDC_WAIT)); SetWindowRedraw(m_hwndPostTo, FALSE); hr = m_pGrpList->GetSelectedCount(&cid); if (SUCCEEDED(hr) && cid > 0) { if (MemAlloc((void **)&pid, cid * sizeof(FOLDERID))) { hr = m_pGrpList->GetSelected(pid, &cid); if (SUCCEEDED(hr)) { for (i = 0; i < cid; i++) { _InsertList(pid[i]); } } MemFree(pid); } } if (-1 == ListView_GetNextItem(m_hwndPostTo, -1, LVNI_ALL | LVNI_SELECTED)) ListView_SetItemState(m_hwndPostTo, 0, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED); SetWindowRedraw(m_hwndPostTo, TRUE); InvalidateRect(m_hwndPostTo, NULL, TRUE); SetCursor(hcur); } // // FUNCTION: CPickGroupDlg::InsertList() // // PURPOSE: Given a index into the CGroupList's newsgroup list, that group // is inserted into the Post To list. // // PARAMETERS: // index - Index of a newsgroup in the CGroupList newsgroup list. // void CPickGroupDlg::_InsertList(FOLDERID id) { LV_ITEM lvi; int count; FOLDERINFO info; HRESULT hr; count = ListView_GetItemCount(m_hwndPostTo); // First make sure this isn't a duplicate. lvi.mask = LVIF_PARAM; lvi.iSubItem = 0; for (lvi.iItem = 0; lvi.iItem < count; lvi.iItem++) { ListView_GetItem(m_hwndPostTo, &lvi); if (id == (FOLDERID)lvi.lParam) return; } hr = g_pStore->GetFolderInfo(id, &info); if (SUCCEEDED(hr)) { lvi.mask = LVIF_TEXT | LVIF_PARAM; lvi.iItem = 0; lvi.iSubItem = 0; lvi.pszText = info.pszName; if (!!(info.dwFlags & FOLDER_SUBSCRIBED)) { lvi.iImage = iNewsGroup; lvi.mask |= LVIF_IMAGE; } lvi.lParam = (LPARAM)id; ListView_InsertItem(m_hwndPostTo, &lvi); g_pStore->FreeRecord(&info); } } void CPickGroupDlg::_RemoveGroup(void) { int index, count, iItemFocus; HCURSOR hcur; hcur = SetCursor(LoadCursor(NULL, IDC_WAIT)); SetWindowRedraw(m_hwndPostTo, FALSE); count = ListView_GetItemCount(m_hwndPostTo); iItemFocus = ListView_GetNextItem(m_hwndPostTo, -1, LVNI_FOCUSED); // Loop through all the selected items and remove them from the ListView for (index = count; index >= 0; index--) { if (ListView_GetItemState(m_hwndPostTo, index, LVIS_SELECTED)) ListView_DeleteItem(m_hwndPostTo, index); } // Bug #22189 - Make sure the focus/selection goes somewhere after we delete. iItemFocus--; if (iItemFocus < 0 || ListView_GetItemCount(m_hwndPostTo) < iItemFocus) iItemFocus = 0; ListView_SetItemState(m_hwndPostTo, iItemFocus, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); SetWindowRedraw(m_hwndPostTo, TRUE); InvalidateRect(m_hwndPostTo, NULL, TRUE); SetCursor(hcur); } void CPickGroupDlg::_UpdateStateUI(HWND hwnd) { DWORD cid; HRESULT hr; hr = m_pGrpList->GetSelectedCount(&cid); if (FAILED(hr)) return; EnableWindow(GetDlgItem(hwnd, idcAddGroup), cid > 0); EnableWindow(GetDlgItem(hwnd, idcRemoveGroup), ListView_GetSelectedCount(m_hwndPostTo)); } void CPickGroupDlg::_OnPaint(HWND hwnd) { RECT rc; HDC hdc; PAINTSTRUCT ps; HFONT hf; char szBuffer[CCHMAX_STRINGRES]; hdc = BeginPaint(hwnd, &ps); // Only do this if the button is available if (IsWindow(GetDlgItem(hwnd, idcShowFavorites))) { // Get the position of the toggle button GetClientRect(GetDlgItem(hwnd, idcShowFavorites), &rc); MapWindowPoints(GetDlgItem(hwnd, idcShowFavorites), hwnd, (LPPOINT) &rc, 1); rc.left += (rc.right + 4); rc.right = rc.left + 300; rc.top += 1; rc.bottom += rc.top; AthLoadString(idsShowFavorites, szBuffer, ARRAYSIZE(szBuffer)); hf = (HFONT) SelectObject(hdc, (HFONT) SendMessage(hwnd, WM_GETFONT, 0, 0)); SetBkMode(hdc, TRANSPARENT); SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT)); DrawText(hdc, szBuffer, lstrlen(szBuffer), &rc, DT_SINGLELINE | DT_VCENTER | DT_NOCLIP); SelectObject(hdc, hf); } EndPaint(hwnd, &ps); }
27.851695
116
0.576855
npocmaka
05938f355df10d92cc67e3edb25a3c558c90129e
938
cpp
C++
Mathematics/Handshake.cpp
chicio/Hackerrank
5d2a828492d2096fbc5d4f54c6c0bbb9612ed752
[ "MIT" ]
6
2017-04-11T15:31:40.000Z
2018-07-12T09:29:30.000Z
Mathematics/Handshake.cpp
chicio/Hackerrank
5d2a828492d2096fbc5d4f54c6c0bbb9612ed752
[ "MIT" ]
null
null
null
Mathematics/Handshake.cpp
chicio/Hackerrank
5d2a828492d2096fbc5d4f54c6c0bbb9612ed752
[ "MIT" ]
1
2018-07-10T11:45:08.000Z
2018-07-10T11:45:08.000Z
// // Handshake.cpp // HackerRank // // Created by Fabrizio Duroni on 02/09/16. // // https://www.hackerrank.com/challenges/handshake #include <cmath> #include <iostream> using namespace std; /* In the previous version I used the standard Binomial coefficient formula. But there's a more efficient multiplicative formula that could be used: https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula Expanding the multiplicative formula for k = 2 gives the following formula: binomial_coefficient = (n^2 - n) / 2 This is the formula used below to compute the number of handshakes between board members. */ int main() { int t; cin >> t; unsigned long long n; for(int i = 0; i < t; i++) { cin >> n; unsigned long long handshakes = (pow(n, 2) - n) / 2; cout << handshakes << endl; } return 0; }
19.142857
74
0.626866
chicio
0596f5a5ae5747e7f4e34985b2f2ce685bbb3b5b
5,901
cpp
C++
kernel/net/E1000ENetworkAdapter.cpp
elango/pranaOS
1017aff798c04c5811befdaca2afdbd7fefed09a
[ "BSD-2-Clause" ]
null
null
null
kernel/net/E1000ENetworkAdapter.cpp
elango/pranaOS
1017aff798c04c5811befdaca2afdbd7fefed09a
[ "BSD-2-Clause" ]
null
null
null
kernel/net/E1000ENetworkAdapter.cpp
elango/pranaOS
1017aff798c04c5811befdaca2afdbd7fefed09a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, Krisna Pranav * * SPDX-License-Identifier: BSD-2-Clause */ // includes #include <base/MACAddress.h> #include <kernel/bus/PCI/IDs.h> #include <kernel/net/E1000ENetworkAdapter.h> #include <kernel/Sections.h> namespace Kernel { #define REG_EEPROM 0x0014 static bool is_valid_device_id(u16 device_id) { switch (device_id) { case 0x10D3: return true; case 0x1000: case 0x0438: case 0x043A: case 0x043C: case 0x0440: case 0x1001: case 0x1004: case 0x1008: case 0x1009: case 0x100C: case 0x100D: case 0x100E: case 0x100F: case 0x1010: case 0x1011: case 0x1012: case 0x1013: case 0x1014: case 0x1015: case 0x1016: case 0x1017: case 0x1018: case 0x1019: case 0x101A: case 0x101D: case 0x101E: case 0x1026: case 0x1027: case 0x1028: case 0x1049: case 0x104A: case 0x104B: case 0x104C: case 0x104D: case 0x105E: case 0x105F: case 0x1060: case 0x1075: case 0x1076: case 0x1077: case 0x1078: case 0x1079: case 0x107A: case 0x107B: case 0x107C: case 0x107D: case 0x107E: case 0x107F: case 0x108A: case 0x108B: case 0x108C: case 0x1096: case 0x1098: case 0x1099: case 0x109A: case 0x10A4: case 0x10A5: case 0x10A7: case 0x10A9: case 0x10B5: case 0x10B9: case 0x10BA: case 0x10BB: case 0x10BC: case 0x10BD: case 0x10BF: case 0x10C0: case 0x10C2: case 0x10C3: case 0x10C4: case 0x10C5: case 0x10C9: case 0x10CA: case 0x10CB: case 0x10CC: case 0x10CD: case 0x10CE: case 0x10D5: case 0x10D6: case 0x10D9: case 0x10DA: case 0x10DE: case 0x10DF: case 0x10E5: case 0x10E6: case 0x10E7: case 0x10E8: case 0x10EA: case 0x10EB: case 0x10EF: case 0x10F0: case 0x10F5: case 0x10F6: case 0x1501: case 0x1502: case 0x1503: case 0x150A: case 0x150C: case 0x150D: case 0x150E: case 0x150F: case 0x1510: case 0x1511: case 0x1516: case 0x1518: case 0x1520: case 0x1521: case 0x1522: case 0x1523: case 0x1524: case 0x1525: case 0x1526: case 0x1527: case 0x152D: case 0x152F: case 0x1533: case 0x1534: case 0x1535: case 0x1536: case 0x1537: case 0x1538: case 0x1539: case 0x153A: case 0x153B: case 0x1546: case 0x1559: case 0x155A: case 0x156F: case 0x1570: case 0x157B: case 0x157C: case 0x15A0: case 0x15A1: case 0x15A2: case 0x15A3: case 0x15B7: case 0x15B8: case 0x15B9: case 0x15BB: case 0x15BC: case 0x15BD: case 0x15BE: case 0x15D6: case 0x15D7: case 0x15D8: case 0x15DF: case 0x15E0: case 0x15E1: case 0x15E2: case 0x15E3: case 0x1F40: case 0x1F41: case 0x1F45: case 0x294C: return false; default: return false; } } UNMAP_AFTER_INIT RefPtr<E1000ENetworkAdapter> E1000ENetworkAdapter::try_to_initialize(PCI::Address address) { auto id = PCI::get_id(address); if (id.vendor_id != PCI::VendorID::Intel) return {}; if (!is_valid_device_id(id.device_id)) return {}; u8 irq = PCI::get_interrupt_line(address); auto adapter = adopt_ref_if_nonnull(new (nothrow) E1000ENetworkAdapter(address, irq)); if (!adapter) return {}; if (adapter->initialize()) return adapter; return {}; } UNMAP_AFTER_INIT bool E1000ENetworkAdapter::initialize() { dmesgln("E1000e: Found @ {}", pci_address()); m_io_base = IOAddress(PCI::get_BAR2(pci_address()) & ~1); enable_bus_mastering(pci_address()); size_t mmio_base_size = PCI::get_BAR_space_size(pci_address(), 0); m_mmio_region = MM.allocate_kernel_region(PhysicalAddress(page_base_of(PCI::get_BAR0(pci_address()))), page_round_up(mmio_base_size), "E1000e MMIO", Region::Access::Read | Region::Access::Write, Region::Cacheable::No); if (!m_mmio_region) return false; m_mmio_base = m_mmio_region->vaddr(); m_use_mmio = true; m_interrupt_line = PCI::get_interrupt_line(pci_address()); dmesgln("E1000e: port base: {}", m_io_base); dmesgln("E1000e: MMIO base: {}", PhysicalAddress(PCI::get_BAR0(pci_address()) & 0xfffffffc)); dmesgln("E1000e: MMIO base size: {} bytes", mmio_base_size); dmesgln("E1000e: Interrupt line: {}", m_interrupt_line); detect_eeprom(); dmesgln("E1000e: Has EEPROM? {}", m_has_eeprom); read_mac_address(); const auto& mac = mac_address(); dmesgln("E1000e: MAC address: {}", mac.to_string()); initialize_rx_descriptors(); initialize_tx_descriptors(); setup_link(); setup_interrupts(); return true; } UNMAP_AFTER_INIT E1000ENetworkAdapter::E1000ENetworkAdapter(PCI::Address address, u8 irq) : E1000NetworkAdapter(address, irq) { } UNMAP_AFTER_INIT E1000ENetworkAdapter::~E1000ENetworkAdapter() { } UNMAP_AFTER_INIT void E1000ENetworkAdapter::detect_eeprom() { m_has_eeprom = true; } UNMAP_AFTER_INIT u32 E1000ENetworkAdapter::read_eeprom(u8 address) { VERIFY(m_has_eeprom); u16 data = 0; u32 tmp = 0; if (m_has_eeprom) { out32(REG_EEPROM, ((u32)address << 2) | 1); while (!((tmp = in32(REG_EEPROM)) & (1 << 1))) ; } else { out32(REG_EEPROM, ((u32)address << 2) | 1); while (!((tmp = in32(REG_EEPROM)) & (1 << 1))) ; } data = (tmp >> 16) & 0xffff; return data; } }
22.437262
222
0.601762
elango
0597689167ff69903da3616ab978d7596688e018
1,812
hpp
C++
boost/boost/graph/distributed/detail/dijkstra_shortest_paths.hpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
boost/boost/graph/distributed/detail/dijkstra_shortest_paths.hpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
boost/boost/graph/distributed/detail/dijkstra_shortest_paths.hpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Copyright (C) 2004-2006 The Trustees of Indiana University. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Douglas Gregor // Andrew Lumsdaine #ifndef BOOST_GRAPH_PARALLEL_DIJKSTRA_DETAIL_HPP #define BOOST_GRAPH_PARALLEL_DIJKSTRA_DETAIL_HPP #ifndef BOOST_GRAPH_USE_MPI #error "Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included" #endif #include <boost/property_map/property_map.hpp> namespace boost { namespace graph { namespace distributed { namespace detail { /********************************************************************** * Dijkstra queue message data * **********************************************************************/ template<typename DistanceMap, typename PredecessorMap> class dijkstra_msg_value { typedef typename property_traits<DistanceMap>::value_type distance_type; typedef typename property_traits<PredecessorMap>::value_type predecessor_type; public: typedef std::pair<distance_type, predecessor_type> type; static type create(distance_type dist, predecessor_type pred) { return std::make_pair(dist, pred); } }; template<typename DistanceMap> class dijkstra_msg_value<DistanceMap, dummy_property_map> { typedef typename property_traits<DistanceMap>::key_type vertex_descriptor; public: typedef typename property_traits<DistanceMap>::value_type type; static type create(type dist, vertex_descriptor) { return dist; } }; /**********************************************************************/ } } } } // end namespace boost::graph::distributed::detail #endif // BOOST_GRAPH_PARALLEL_DIJKSTRA_DETAIL_HPP
35.529412
101
0.681015
randolphwong
059f420b9459540b73fe39df0c7c74a82b5141d6
9,325
hpp
C++
include/rovio/RovioInterfaceImpl.hpp
krzacz0r/maplab_rovio
1c881862bdfd5096d7c8ad268218020187bd6bc4
[ "BSD-3-Clause" ]
40
2017-11-29T08:46:10.000Z
2021-11-12T05:46:04.000Z
include/rovio/RovioInterfaceImpl.hpp
krzacz0r/maplab_rovio
1c881862bdfd5096d7c8ad268218020187bd6bc4
[ "BSD-3-Clause" ]
5
2018-01-08T17:02:15.000Z
2019-04-01T18:29:01.000Z
include/rovio/RovioInterfaceImpl.hpp
krzacz0r/maplab_rovio
1c881862bdfd5096d7c8ad268218020187bd6bc4
[ "BSD-3-Clause" ]
26
2017-12-03T02:22:47.000Z
2022-01-17T05:39:46.000Z
/* * Copyright (c) 2014, Autonomous Systems Lab * 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 Autonomous Systems Lab, ETH Zurich 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 ROVIO_ROVIO_INTERFACE_IMPL_H_ #define ROVIO_ROVIO_INTERFACE_IMPL_H_ #include <functional> #include <memory> #include <mutex> #include <queue> #include <glog/logging.h> #include "rovio/CameraCalibration.hpp" #include "rovio/CoordinateTransform/FeatureOutput.hpp" #include "rovio/CoordinateTransform/FeatureOutputReadable.hpp" #include "rovio/CoordinateTransform/LandmarkOutput.hpp" #include "rovio/CoordinateTransform/RovioOutput.hpp" #include "rovio/CoordinateTransform/YprOutput.hpp" #include "rovio/FilterConfiguration.hpp" #include "rovio/Memory.hpp" #include "rovio/RovioFilter.hpp" #include "RovioInterfaceStatesImpl.hpp" #include "rovio/RovioInterface.hpp" namespace rovio { struct FilterInitializationState; template <typename FILTER> class RovioInterfaceImpl : public RovioInterface { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW RovioInterfaceImpl(typename std::shared_ptr<FILTER> mpFilter); explicit RovioInterfaceImpl(const std::string &filter_config_file); RovioInterfaceImpl( const std::string &filter_config_file, const std::vector<std::string>& camera_calibration_files); explicit RovioInterfaceImpl(const FilterConfiguration &filter_config); RovioInterfaceImpl( const FilterConfiguration &filter_config, const CameraCalibrationVector& camera_calibrations); virtual ~RovioInterfaceImpl() {} typedef FILTER mtFilter; typedef typename mtFilter::mtFilterState mtFilterState; typedef typename mtFilterState::mtState mtState; /** \brief Outputting the feature and patch update state involves allocating * some large arrays and could result in some overhead. Therefore the * state will not be retrieved by default. */ bool getState(const bool get_feature_update, const bool get_patch_update, RovioState* filter_update); bool getState(RovioState* filter_update); /** \brief Returns the time step of the last/latest safe filter state.. */ double getLastSafeTime(); /** \brief Reset the filter when the next IMU measurement is received. * The orientaetion is initialized using an accel. measurement. */ void requestReset(); /** \brief Reset the filter when the next IMU measurement is received. * The pose is initialized to the passed pose. * @param WrWM - Position Vector, pointing from the World-Frame to the * IMU-Frame, expressed in World-Coordinates. * @param qMW - Quaternion, expressing World-Frame in IMU-Coordinates (World * Coordinates->IMU Coordinates) */ void requestResetToPose(const V3D &WrWM, const QPD &qMW); void resetToLastSafePose(); bool processVelocityUpdate(const Eigen::Vector3d &AvM, const double time_s); bool processImuUpdate(const Eigen::Vector3d &acc, const Eigen::Vector3d &gyr, const double time_s, bool update_filter); bool processImageUpdate(const int camID, const cv::Mat &cv_img, const double time_s); bool processGroundTruthUpdate(const Eigen::Vector3d &JrJV, const QPD &qJV, const double time_s); bool processGroundTruthOdometryUpdate( const Eigen::Vector3d &JrJV, const QPD &qJV, const Eigen::Matrix<double, 6, 6> &measuredCov, const double time_s); bool processLocalizationLandmarkUpdates( const int camID, const Eigen::Matrix2Xd& keypoint_observations, const Eigen::Matrix3Xd& G_landmarks, const double time_s); void resetLocalizationMapBaseframeAndCovariance( const V3D& WrWG, const QPD& qWG, double position_cov, double rotation_cov); /** \brief Register multiple callbacks that are invoked once the filter * concludes a successful update. */ typedef std::function<void(const RovioState&)> RovioStateCallback; void registerStateUpdateCallback(RovioStateCallback callback); /** \brief Enable and disable feature and patch update output. If disabled, * the RovioStateImpl<FILTER> returned by the callback does not contain * any state information of the features/patches. */ void setEnableFeatureUpdateOutput(const bool enable_feature_update); void setEnablePatchUpdateOutput(const bool get_patch_update); bool isInitialized() const; /** \brief Tests the functionality of the rovio node. * * @todo debug with doVECalibration = false and depthType = 0 */ void makeTest(); private: /** \brief Trigger a filter update. Will return true if an update happened. */ bool updateFilter(); void notifyAllStateUpdateCallbacks(const RovioState& state) const; /** \brief Print update to std::cout and visualize images using opencv. The * visualization is configured and enabled/disabled based on mpImgUpdate. */ void visualizeUpdate(); std::vector<RovioStateCallback> filter_update_state_callbacks_; typedef StandardOutput mtOutput; // TODO(mfehr): Ownership of the filter does not need to be shared, consider // changing to unique ptr or raw ptr if someone outside the interface can own // the filter. std::shared_ptr<mtFilter> mpFilter_; typedef typename mtFilter::mtPrediction::mtMeas mtPredictionMeas; mtPredictionMeas predictionMeas_; typedef typename std::tuple_element<0, typename mtFilter::mtUpdates>::type mtImgUpdate; mtImgUpdate *mpImgUpdate_; typedef typename std::tuple_element<1, typename mtFilter::mtUpdates>::type mtPoseUpdate; mtPoseUpdate *mpPoseUpdate_; typedef typename std::tuple_element<3, typename mtFilter::mtUpdates>::type mtLocLandmarkUpdate; mtLocLandmarkUpdate *mpLocLandmarkUpdate_; typedef typename mtImgUpdate::mtMeas mtImgMeas; mtImgMeas imgUpdateMeas_; typedef typename mtPoseUpdate::mtMeas mtPoseMeas; mtPoseMeas poseUpdateMeas_; typedef typename mtLocLandmarkUpdate::mtMeas mtLocLandmarkMeas; mtLocLandmarkMeas locLandmarkUpdateMeas_; typedef typename std::tuple_element<2, typename mtFilter::mtUpdates>::type mtVelocityUpdate; typedef typename mtVelocityUpdate::mtMeas mtVelocityMeas; mtVelocityMeas velocityUpdateMeas_; struct FilterInitializationState { FilterInitializationState() : WrWM_(V3D::Zero()), state_(State::WaitForInitUsingAccel) {} enum class State { // Initialize the filter using accelerometer measurement on the next // opportunity. WaitForInitUsingAccel, // Initialize the filter using an external pose on the next opportunity. WaitForInitExternalPose, // The filter is initialized. Initialized } state_; // Buffer to hold the initial pose that should be set during initialization // with the state WaitForInitExternalPose. V3D WrWM_; QPD qMW_; explicit operator bool() const { return isInitialized(); } bool isInitialized() const { return (state_ == State::Initialized); } }; FilterInitializationState init_state_; // Rovio outputs and coordinate transformations Eigen::MatrixXd cameraOutputCov_; CameraOutputCT<mtState> cameraOutputCT_; ImuOutputCT<mtState> imuOutputCT_; rovio::TransformFeatureOutputCT<mtState> transformFeatureOutputCT_; rovio::LandmarkOutputImuCT<mtState> landmarkOutputImuCT_; // Features. rovio::FeatureOutput featureOutput_; rovio::FeatureOutputReadable featureOutputReadable_; rovio::FeatureOutputReadableCT featureOutputReadableCT_; Eigen::MatrixXd featureOutputCov_; Eigen::MatrixXd featureOutputReadableCov_; // Landmarks. rovio::LandmarkOutput landmarkOutput_; Eigen::MatrixXd landmarkOutputCov_; // State output config. bool enable_feature_update_output_; bool enable_patch_update_output_; mutable std::recursive_mutex m_filter_; }; } // namespace rovio #endif // ROVIO_ROVIO_INTERFACE_IMPL_H_ #include "RovioInterfaceImplInl.hpp"
36.425781
81
0.760536
krzacz0r
05a180599890366b7d731e58dd437a17ed2f82eb
22,776
cpp
C++
tests/HttpHandlerTest.cpp
acossette/pillow
89259eb4540d27551470de0d80363a37ba3eda7d
[ "Zed", "Ruby" ]
39
2015-01-28T12:51:41.000Z
2021-09-25T16:27:09.000Z
tests/HttpHandlerTest.cpp
acossette/pillow
89259eb4540d27551470de0d80363a37ba3eda7d
[ "Zed", "Ruby" ]
1
2016-01-21T00:10:25.000Z
2016-01-21T00:29:40.000Z
tests/HttpHandlerTest.cpp
acossette/pillow
89259eb4540d27551470de0d80363a37ba3eda7d
[ "Zed", "Ruby" ]
22
2015-08-07T23:28:27.000Z
2020-07-13T08:12:22.000Z
#include <QtTest/QTest> #include <QtTest/QSignalSpy> #include "HttpHandlerTest.h" #include "HttpHandler.h" #include "HttpHandlerSimpleRouter.h" #include "HttpConnection.h" #include <QtCore/QDir> #include <QtCore/QBuffer> #include <QtCore/QCoreApplication> using namespace Pillow; Pillow::HttpConnection * HttpHandlerTestBase::createGetRequest(const QByteArray &path, const QByteArray& httpVersion) { return createRequest("GET", path, QByteArray(), httpVersion); } Pillow::HttpConnection * HttpHandlerTestBase::createPostRequest(const QByteArray &path, const QByteArray &content, const QByteArray &httpVersion) { return createRequest("POST", path, content, httpVersion); } Pillow::HttpConnection * HttpHandlerTestBase::createRequest(const QByteArray &method, const QByteArray &path, const QByteArray &content, const QByteArray &httpVersion) { QByteArray data = QByteArray().append(method).append(" ").append(path).append(" HTTP/").append(httpVersion).append("\r\n"); if (content.size() > 0) { data.append("Content-Length: ").append(QByteArray::number(content.size())).append("\r\n"); data.append("Content-Type: text/plain\r\n"); } data.append("\r\n").append(content); QBuffer* inputBuffer = new QBuffer(); inputBuffer->open(QIODevice::ReadWrite); QBuffer* outputBuffer = new QBuffer(); outputBuffer->open(QIODevice::ReadWrite); connect(outputBuffer, SIGNAL(bytesWritten(qint64)), this, SLOT(outputBuffer_bytesWritten())); Pillow::HttpConnection* connection = new Pillow::HttpConnection(this); connect(connection, SIGNAL(requestCompleted(Pillow::HttpConnection*)), this, SLOT(requestCompleted(Pillow::HttpConnection*))); connection->initialize(inputBuffer, outputBuffer); inputBuffer->setParent(connection); outputBuffer->setParent(connection); inputBuffer->write(data); inputBuffer->seek(0); while (connection->state() != Pillow::HttpConnection::SendingHeaders) QCoreApplication::processEvents(); return connection; } void HttpHandlerTestBase::requestCompleted(Pillow::HttpConnection* connection) { QCoreApplication::processEvents(); response = responseBuffer; responseBuffer = QByteArray(); requestParams = connection->requestParams(); } void HttpHandlerTestBase::outputBuffer_bytesWritten() { QBuffer* buffer = static_cast<QBuffer*>(sender()); responseBuffer.append(buffer->data()); if (buffer->isOpen()) buffer->seek(0); } class MockHandler : public Pillow::HttpHandler { public: MockHandler(const QByteArray& acceptPath, int statusCode, QObject* parent) : Pillow::HttpHandler(parent), acceptPath(acceptPath), statusCode(statusCode), handleRequestCount(0) {} QByteArray acceptPath; int statusCode; int handleRequestCount; bool handleRequest(Pillow::HttpConnection *connection) { ++handleRequestCount; if (acceptPath == connection->requestPath()) { connection->writeResponse(statusCode); return true; } return false; } }; void HttpHandlerTest::testHandlerStack() { HttpHandlerStack handler; MockHandler* mock1 = new MockHandler("/1", 200, &handler); MockHandler* mock1_1 = new MockHandler("/", 403, mock1); new QObject(&handler); // Some dummy object, also child of handler. MockHandler* mock2 = new MockHandler("/2", 302, &handler); MockHandler* mock3 = new MockHandler("/", 500, &handler); MockHandler* mock4 = new MockHandler("/", 200, &handler); bool handled = handler.handleRequest(createGetRequest("/")); QVERIFY(handled); QVERIFY(response.startsWith("HTTP/1.0 500")); QCOMPARE(mock1->handleRequestCount, 1); QCOMPARE(mock1_1->handleRequestCount, 0); QCOMPARE(mock2->handleRequestCount, 1); QCOMPARE(mock3->handleRequestCount, 1); QCOMPARE(mock4->handleRequestCount, 0); handled = handler.handleRequest(createGetRequest("/2")); QVERIFY(handled); QVERIFY(response.startsWith("HTTP/1.0 302")); QCOMPARE(mock1->handleRequestCount, 2); QCOMPARE(mock1_1->handleRequestCount, 0); QCOMPARE(mock2->handleRequestCount, 2); QCOMPARE(mock3->handleRequestCount, 1); QCOMPARE(mock4->handleRequestCount, 0); } void HttpHandlerTest::testHandlerFixed() { bool handled = HttpHandlerFixed(403, "Fixed test").handleRequest(createGetRequest()); QVERIFY(handled); QVERIFY(response.startsWith("HTTP/1.0 403")); QVERIFY(response.endsWith("\r\n\r\nFixed test")); } void HttpHandlerTest::testHandler404() { bool handled = HttpHandler404().handleRequest(createGetRequest("/some_path")); QVERIFY(handled); QVERIFY(response.startsWith("HTTP/1.0 404")); QVERIFY(response.contains("/some_path")); } void HttpHandlerTest::testHandlerFunction() { #ifdef Q_COMPILER_LAMBDA HttpHandlerFunction handler([](Pillow::HttpConnection* request) { request->writeResponse(200, Pillow::HttpHeaderCollection(), "hello from lambda"); }); QVERIFY(handler.handleRequest(createGetRequest("/some/random/path"))); QVERIFY(response.startsWith("HTTP/1.0 200 OK")); QVERIFY(response.endsWith("hello from lambda")); #else QSKIP("Compiler does not support lambdas or C++0x support is not enabled.", SkipSingle); #endif } void HttpHandlerTest::testHandlerLog() { QBuffer buffer; buffer.open(QIODevice::ReadWrite); Pillow::HttpConnection* request1 = createGetRequest("/first"); Pillow::HttpConnection* request2 = createGetRequest("/second"); Pillow::HttpConnection* request3 = createGetRequest("/third"); HttpHandlerLog handler(&buffer, &buffer); QVERIFY(!handler.handleRequest(request1)); QVERIFY(!handler.handleRequest(request2)); QVERIFY(!handler.handleRequest(request3)); QVERIFY(buffer.data().isEmpty()); request3->writeResponse(302); request1->writeResponse(200); request2->writeResponse(500); // The log handler should write the log entries as they are completed. buffer.seek(0); QVERIFY(buffer.readLine().contains("GET /third")); QVERIFY(buffer.readLine().contains("GET /first")); QVERIFY(buffer.readLine().contains("GET /second")); QVERIFY(buffer.readLine().isEmpty()); } void HttpHandlerTest::testHandlerLogTrace() { QBuffer buffer; buffer.open(QIODevice::ReadWrite); Pillow::HttpConnection* request1 = createGetRequest("/first", "1.1"); Pillow::HttpConnection* request2 = createGetRequest("/second", "1.1"); Pillow::HttpConnection* request3 = createGetRequest("/third", "1.1"); HttpHandlerLog handler(&buffer, &buffer); handler.setMode(HttpHandlerLog::TraceRequests); QVERIFY(!handler.handleRequest(request1)); QVERIFY(!buffer.data().isEmpty()); QVERIFY(buffer.data().contains("[BEGIN]")); QVERIFY(!buffer.data().contains("[ END ]")); QVERIFY(!handler.handleRequest(request2)); QVERIFY(!handler.handleRequest(request3)); request3->writeResponse(302); QVERIFY(buffer.data().contains("[ END ]")); request1->writeResponse(200); request2->writeResponse(500); QVERIFY(!buffer.data().contains("[CLOSE]")); request1->close(); QVERIFY(buffer.data().contains("[CLOSE]")); buffer.seek(0); QVERIFY(buffer.readLine().contains("GET /first")); QVERIFY(buffer.readLine().contains("GET /second")); QVERIFY(buffer.readLine().contains("GET /third")); QVERIFY(buffer.readLine().contains("GET /third")); // END QVERIFY(buffer.readLine().contains("GET /first")); // END QVERIFY(buffer.readLine().contains("GET /second")); // END QVERIFY(buffer.readLine().contains("GET /first")); // CLOSE QVERIFY(buffer.readLine().isEmpty()); } void HttpHandlerFileTest::initTestCase() { testPath = QDir::tempPath() + "/HttpHandlerFileTest"; QDir(testPath).mkpath("."); QVERIFY(QFile::exists(testPath)); QByteArray bigData(16 * 1024 * 1024, '-'); { QFile f(testPath + "/first"); f.open(QIODevice::WriteOnly); f.write("first content"); f.flush(); f.close(); } { QFile f(testPath + "/second"); f.open(QIODevice::WriteOnly); f.write("second content"); f.flush(); f.close(); } { QFile f(testPath + "/large"); f.open(QIODevice::WriteOnly); f.write(bigData); f.flush(); f.close(); } { QFile f(testPath + "/first"); f.open(QIODevice::ReadOnly); QCOMPARE(f.readAll(), QByteArray("first content")); } { QFile f(testPath + "/second"); f.open(QIODevice::ReadOnly); QCOMPARE(f.readAll(), QByteArray("second content")); } { QFile f(testPath + "/large"); f.open(QIODevice::ReadOnly); QCOMPARE(f.readAll(), bigData); } } void HttpHandlerFileTest::testServesFiles() { HttpHandlerFile handler(testPath); QVERIFY(!handler.handleRequest(createGetRequest("/"))); QVERIFY(!handler.handleRequest(createGetRequest("/bad_path"))); QVERIFY(!handler.handleRequest(createGetRequest("/another_bad"))); Pillow::HttpConnection* request = createGetRequest("/first"); QVERIFY(handler.handleRequest(request)); QVERIFY(response.startsWith("HTTP/1.0 200 OK")); QVERIFY(response.endsWith("first content")); response.clear(); // Note: the large files test currently fails when the output device is a QBuffer. request = createGetRequest("/large"); QVERIFY(handler.handleRequest(request)); while (response.isEmpty()) QCoreApplication::processEvents(); QVERIFY(response.size() > 16 * 1024 * 1024); QVERIFY(response.startsWith("HTTP/1.0 200 OK")); QVERIFY(response.endsWith(QByteArray(16 * 1024 * 1024, '-'))); } void HttpHandlerSimpleRouterTest::testHandlerRoute() { HttpHandlerSimpleRouter handler; handler.addRoute("/some_path", new HttpHandlerFixed(303, "Hello")); handler.addRoute("/other/path", new HttpHandlerFixed(404, "World")); handler.addRoute("/some_path/even/deeper", new HttpHandlerFixed(200, "!")); QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either"))); QVERIFY(!handler.handleRequest(createGetRequest("/some_path/should_not_match"))); QVERIFY(handler.handleRequest(createGetRequest("/other/path"))); QVERIFY(response.startsWith("HTTP/1.0 404")); QVERIFY(response.endsWith("World")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/some_path/even/deeper?with=query_string"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("!")); response.clear(); } void HttpHandlerSimpleRouterTest::testQObjectMetaCallRoute() { HttpHandlerSimpleRouter handler; handler.addRoute("/first", this, "handleRequest1"); handler.addRoute("/first/second", this, "handleRequest2"); QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either"))); QVERIFY(!handler.handleRequest(createGetRequest("/first/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/first/second/should_not_match"))); QVERIFY(handler.handleRequest(createGetRequest("/first"))); QVERIFY(response.startsWith("HTTP/1.0 403")); QVERIFY(response.endsWith("Hello")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/first/second?with=query_string"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("World")); response.clear(); } void HttpHandlerSimpleRouterTest::testQObjectSlotCallRoute() { HttpHandlerSimpleRouter handler; handler.addRoute("/route", this, SLOT(handleRequest2(Pillow::HttpConnection*))); QVERIFY(handler.handleRequest(createGetRequest("/route"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("World")); response.clear(); } void HttpHandlerSimpleRouterTest::testStaticRoute() { HttpHandlerSimpleRouter handler; handler.addRoute("/first", 200, Pillow::HttpHeaderCollection(), "First Route"); handler.addRoute("/first/second", 404, Pillow::HttpHeaderCollection(), "Second Route"); handler.addRoute("/third", 500, Pillow::HttpHeaderCollection(), "Third Route"); QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either"))); QVERIFY(!handler.handleRequest(createGetRequest("/first/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/first/second/should_not_match"))); QVERIFY(handler.handleRequest(createGetRequest("/first"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("First Route")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/third?with=query_string#and_fragment"))); QVERIFY(response.startsWith("HTTP/1.0 500")); QVERIFY(response.endsWith("Third Route")); response.clear(); } void HttpHandlerSimpleRouterTest::testFuncRoute() { #ifdef Q_COMPILER_LAMBDA HttpHandlerSimpleRouter handler; handler.addRoute("/a_route", [](Pillow::HttpConnection* request) { request->writeResponse(200, Pillow::HttpHeaderCollection(), "Amazing First Route"); }); handler.addRoute("/a_route/and_another", [](Pillow::HttpConnection* request) { request->writeResponse(400, Pillow::HttpHeaderCollection(), "Delicious Second Route"); }); QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either"))); QVERIFY(!handler.handleRequest(createGetRequest("/a_route/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/a_route/and_another/should_not_match"))); QVERIFY(handler.handleRequest(createGetRequest("/a_route"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Amazing First Route")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/a_route/and_another?with=query_string#and_fragment"))); QVERIFY(response.startsWith("HTTP/1.0 400")); QVERIFY(response.endsWith("Delicious Second Route")); response.clear(); #else QSKIP("Compiler does not support lambdas or C++0x support is not enabled.", SkipSingle); #endif } void HttpHandlerSimpleRouterTest::handleRequest1(Pillow::HttpConnection *request) { request->writeResponse(403, Pillow::HttpHeaderCollection(), "Hello"); } void HttpHandlerSimpleRouterTest::handleRequest2(Pillow::HttpConnection *request) { request->writeResponse(200, Pillow::HttpHeaderCollection(), "World"); } void HttpHandlerSimpleRouterTest::testPathParams() { HttpHandlerSimpleRouter handler; handler.addRoute("/first/:with_param", 200, Pillow::HttpHeaderCollection(), "First Route"); handler.addRoute("/second/:with_param/and/:another", 200, Pillow::HttpHeaderCollection(), "Second Route"); handler.addRoute("/third/:with/:many/:params", 200, Pillow::HttpHeaderCollection(), "Third Route"); QVERIFY(handler.handleRequest(createGetRequest("/first/some_param-value"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("First Route")); QCOMPARE(requestParams.size(), 1); QCOMPARE(requestParams.at(0).first, QString("with_param")); QCOMPARE(requestParams.at(0).second, QString("some_param-value")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/second/some_param-value/and/another_value"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Second Route")); QCOMPARE(requestParams.size(), 2); QCOMPARE(requestParams.at(0).first, QString("with_param")); QCOMPARE(requestParams.at(0).second, QString("some_param-value")); QCOMPARE(requestParams.at(1).first, QString("another")); QCOMPARE(requestParams.at(1).second, QString("another_value")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/third/some_param-value/another_value/and_a_last_one?with=overriden&extra=bonus_query_param#and_fragment"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Third Route")); QCOMPARE(requestParams.size(), 4); QCOMPARE(requestParams.at(0).first, QString("with")); QCOMPARE(requestParams.at(0).second, QString("some_param-value")); // The route param should have overriden the query string param. QCOMPARE(requestParams.at(1).first, QString("extra")); QCOMPARE(requestParams.at(1).second, QString("bonus_query_param")); QCOMPARE(requestParams.at(2).first, QString("many")); QCOMPARE(requestParams.at(2).second, QString("another_value")); QCOMPARE(requestParams.at(3).first, QString("params")); QCOMPARE(requestParams.at(3).second, QString("and_a_last_one")); response.clear(); QVERIFY(!handler.handleRequest(createGetRequest("/first/some_param-value/and_extra_stuff"))); QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/bad_part/another_value"))); QVERIFY(!handler.handleRequest(createGetRequest("/third/some_param-value/another_value/and_a_last_one/and_extra_stuff"))); } void HttpHandlerSimpleRouterTest::testPathSplats() { HttpHandlerSimpleRouter handler; handler.addRoute("/first/*with_splat", 200, Pillow::HttpHeaderCollection(), "First Route"); handler.addRoute("/second/:with_param/and/*splat", 200, Pillow::HttpHeaderCollection(), "Second Route"); handler.addRoute("/third/*with/two/*splats", 200, Pillow::HttpHeaderCollection(), "Third Route"); QVERIFY(handler.handleRequest(createGetRequest("/first/"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("First Route")); QCOMPARE(requestParams.size(), 1); QCOMPARE(requestParams.at(0).first, QString("with_splat")); QCOMPARE(requestParams.at(0).second, QString("")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/first/with/anything-after.that/really_I_tell_you.html"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("First Route")); QCOMPARE(requestParams.size(), 1); QCOMPARE(requestParams.at(0).first, QString("with_splat")); QCOMPARE(requestParams.at(0).second, QString("with/anything-after.that/really_I_tell_you.html")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/second/some-param-value/and/"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Second Route")); QCOMPARE(requestParams.size(), 2); QCOMPARE(requestParams.at(0).first, QString("with_param")); QCOMPARE(requestParams.at(0).second, QString("some-param-value")); QCOMPARE(requestParams.at(1).first, QString("splat")); QCOMPARE(requestParams.at(1).second, QString("")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/second/some-param-value/and/extra/stuff/splatted.at/the.end?with=bonus_query_param#and_fragment"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Second Route")); QCOMPARE(requestParams.size(), 3); QCOMPARE(requestParams.at(0).first, QString("with")); QCOMPARE(requestParams.at(0).second, QString("bonus_query_param")); QCOMPARE(requestParams.at(1).first, QString("with_param")); QCOMPARE(requestParams.at(1).second, QString("some-param-value")); QCOMPARE(requestParams.at(2).first, QString("splat")); QCOMPARE(requestParams.at(2).second, QString("extra/stuff/splatted.at/the.end")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/third/some/path/two/and/another/path%20with%20spaces.txt"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Third Route")); QCOMPARE(requestParams.size(), 2); QCOMPARE(requestParams.at(0).first, QString("with")); QCOMPARE(requestParams.at(0).second, QString("some/path")); QCOMPARE(requestParams.at(1).first, QString("splats")); QCOMPARE(requestParams.at(1).second, QString("and/another/path with spaces.txt")); response.clear(); QVERIFY(!handler.handleRequest(createGetRequest("/first"))); QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/"))); QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/and"))); QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/bad_part/splat/splat/splat"))); } void HttpHandlerSimpleRouterTest::testMatchesMethod() { HttpHandlerSimpleRouter handler; handler.addRoute("GET", "/get", 200, Pillow::HttpHeaderCollection(), "First Route"); handler.addRoute("POST", "/post", 200, Pillow::HttpHeaderCollection(), "Second Route"); handler.addRoute("GET", "/both", 200, Pillow::HttpHeaderCollection(), "Third Route (GET)"); handler.addRoute("POST", "/both", 200, Pillow::HttpHeaderCollection(), "Third Route (POST)"); QVERIFY(handler.handleRequest(createGetRequest("/get"))); QVERIFY(!handler.handleRequest(createPostRequest("/get"))); QVERIFY(!handler.handleRequest(createGetRequest("/post"))); QVERIFY(handler.handleRequest(createPostRequest("/post"))); QVERIFY(handler.handleRequest(createGetRequest("/both"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Third Route (GET)")); response.clear(); QVERIFY(handler.handleRequest(createPostRequest("/both"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Third Route (POST)")); response.clear(); } void HttpHandlerSimpleRouterTest::testUnmatchedRequestAction() { HttpHandlerSimpleRouter handler; QVERIFY(handler.unmatchedRequestAction() == HttpHandlerSimpleRouter::Passthrough); handler.setUnmatchedRequestAction(HttpHandlerSimpleRouter::Return4xxResponse); handler.addRoute("GET", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (GET)"); handler.addRoute("DELETE", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (DELETE)"); QVERIFY(handler.handleRequest(createGetRequest("/unmatched/route"))); QVERIFY(response.startsWith("HTTP/1.0 404")); response.clear(); } void HttpHandlerSimpleRouterTest::testMethodMismatchAction() { HttpHandlerSimpleRouter handler; QVERIFY(handler.methodMismatchAction() == HttpHandlerSimpleRouter::Passthrough); handler.setMethodMismatchAction(HttpHandlerSimpleRouter::Return4xxResponse); handler.addRoute("GET", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (GET)"); handler.addRoute("DELETE", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (DELETE)"); QVERIFY(handler.handleRequest(createPostRequest("/a"))); QVERIFY(response.startsWith("HTTP/1.0 405")); QVERIFY(response.contains("Allow: GET, DELETE")); response.clear(); } void HttpHandlerSimpleRouterTest::testSupportsMethodParam() { HttpHandlerSimpleRouter handler; handler.addRoute("POST", "/a", 200, Pillow::HttpHeaderCollection(), "Route"); handler.addRoute("DELETE", "/b", 200, Pillow::HttpHeaderCollection(), "Route"); QVERIFY(handler.acceptsMethodParam() == false); QVERIFY(!handler.handleRequest(createGetRequest("/a"))); QVERIFY(handler.handleRequest(createPostRequest("/a"))); QVERIFY(!handler.handleRequest(createGetRequest("/a?_method=post"))); QVERIFY(!handler.handleRequest(createGetRequest("/b?_method=delete"))); QVERIFY(!handler.handleRequest(createPostRequest("/b?_method=delete"))); handler.setAcceptsMethodParam(true); QVERIFY(!handler.handleRequest(createGetRequest("/a"))); QVERIFY(handler.handleRequest(createPostRequest("/a"))); QVERIFY(handler.handleRequest(createGetRequest("/a?_method=POST"))); QVERIFY(handler.handleRequest(createGetRequest("/b?_method=DELETE"))); QVERIFY(handler.handleRequest(createPostRequest("/b?_method=DELETE"))); QVERIFY(handler.handleRequest(createGetRequest("/b?_method=delete"))); QVERIFY(handler.handleRequest(createPostRequest("/b?_method=delete"))); }
41.944751
170
0.757684
acossette
05a26347bf35dd497dab7ff0fedfbfb069773116
3,911
cpp
C++
GUI/build-StudentManagementSystem-Desktop_x86_darwin_generic_mach_o_64bit-Release/moc_delete.cpp
AppDevIn/StudentManagement
38f88cd00473437fbffacd5d797f0a927c439544
[ "MIT" ]
null
null
null
GUI/build-StudentManagementSystem-Desktop_x86_darwin_generic_mach_o_64bit-Release/moc_delete.cpp
AppDevIn/StudentManagement
38f88cd00473437fbffacd5d797f0a927c439544
[ "MIT" ]
null
null
null
GUI/build-StudentManagementSystem-Desktop_x86_darwin_generic_mach_o_64bit-Release/moc_delete.cpp
AppDevIn/StudentManagement
38f88cd00473437fbffacd5d797f0a927c439544
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'delete.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.15.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../StudentManagementSystem/delete.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'delete.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.15.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_Delete_t { QByteArrayData data[7]; char stringdata0[85]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Delete_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Delete_t qt_meta_stringdata_Delete = { { QT_MOC_LITERAL(0, 0, 6), // "Delete" QT_MOC_LITERAL(1, 7, 25), // "on_listWidget_itemClicked" QT_MOC_LITERAL(2, 33, 0), // "" QT_MOC_LITERAL(3, 34, 16), // "QListWidgetItem*" QT_MOC_LITERAL(4, 51, 4), // "item" QT_MOC_LITERAL(5, 56, 23), // "on_lineEdit_textChanged" QT_MOC_LITERAL(6, 80, 4) // "arg1" }, "Delete\0on_listWidget_itemClicked\0\0" "QListWidgetItem*\0item\0on_lineEdit_textChanged\0" "arg1" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Delete[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x08 /* Private */, 5, 1, 27, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, 0x80000000 | 3, 4, QMetaType::Void, QMetaType::QString, 6, 0 // eod }; void Delete::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<Delete *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_listWidget_itemClicked((*reinterpret_cast< QListWidgetItem*(*)>(_a[1]))); break; case 1: _t->on_lineEdit_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject Delete::staticMetaObject = { { QMetaObject::SuperData::link<QMainWindow::staticMetaObject>(), qt_meta_stringdata_Delete.data, qt_meta_data_Delete, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *Delete::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Delete::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_Delete.stringdata0)) return static_cast<void*>(this); return QMainWindow::qt_metacast(_clname); } int Delete::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
30.554688
103
0.62516
AppDevIn
05a4793814cdf4b3c2dfa2d1c2559e5d161339e7
13,758
cpp
C++
libs/type_index/test/type_index_test.cpp
Abce/boost
2d7491a27211aa5defab113f8e2d657c3d85ca93
[ "BSL-1.0" ]
85
2015-02-08T20:36:17.000Z
2021-11-14T20:38:31.000Z
libs/boost/libs/type_index/test/type_index_test.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/boost/libs/type_index/test/type_index_test.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
27
2015-01-28T16:33:30.000Z
2021-08-12T05:04:39.000Z
// // Copyright Antony Polukhin, 2012-2014. // // 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/test/minimal.hpp> #include <boost/type_index.hpp> #include <boost/functional/hash.hpp> #include <boost/lexical_cast.hpp> #define BOOST_CHECK_EQUAL(x, y) BOOST_CHECK(x == y) #define BOOST_CHECK_NE(x, y) BOOST_CHECK(x != y) #define BOOST_CHECK_LE(x, y) BOOST_CHECK(x <= y) #define BOOST_CHECK_GE(x, y) BOOST_CHECK(x >= y) namespace my_namespace1 { class my_class{}; } namespace my_namespace2 { class my_class{}; } void names_matches_type_id() { using namespace boost::typeindex; BOOST_CHECK_EQUAL(type_id<int>().pretty_name(), "int"); BOOST_CHECK_EQUAL(type_id<double>().pretty_name(), "double"); BOOST_CHECK_EQUAL(type_id<int>().name(), type_id<int>().name()); BOOST_CHECK_NE(type_id<int>().name(), type_id<double>().name()); BOOST_CHECK_NE(type_id<double>().name(), type_id<int>().name()); BOOST_CHECK_EQUAL(type_id<double>().name(), type_id<double>().name()); } void default_construction() { using namespace boost::typeindex; type_index ti1, ti2; BOOST_CHECK_EQUAL(ti1, ti2); BOOST_CHECK_EQUAL(type_id<void>(), ti1); BOOST_CHECK_EQUAL(type_id<void>().name(), ti1.name()); BOOST_CHECK_NE(type_id<int>(), ti1); } void copy_construction() { using namespace boost::typeindex; type_index ti1, ti2 = type_id<int>(); BOOST_CHECK_NE(ti1, ti2); ti1 = ti2; BOOST_CHECK_EQUAL(ti2, ti1); const type_index ti3(ti1); BOOST_CHECK_EQUAL(ti3, ti1); } void comparators_type_id() { using namespace boost::typeindex; type_index t_int = type_id<int>(); type_index t_double = type_id<double>(); BOOST_CHECK_EQUAL(t_int, t_int); BOOST_CHECK_LE(t_int, t_int); BOOST_CHECK_GE(t_int, t_int); BOOST_CHECK_NE(t_int, t_double); BOOST_CHECK_LE(t_double, t_double); BOOST_CHECK_GE(t_double, t_double); BOOST_CHECK_NE(t_double, t_int); BOOST_CHECK(t_double < t_int || t_int < t_double); BOOST_CHECK(t_double > t_int || t_int > t_double); } void hash_code_type_id() { using namespace boost::typeindex; std::size_t t_int1 = type_id<int>().hash_code(); std::size_t t_double1 = type_id<double>().hash_code(); std::size_t t_int2 = type_id<int>().hash_code(); std::size_t t_double2 = type_id<double>().hash_code(); BOOST_CHECK_EQUAL(t_int1, t_int2); BOOST_CHECK_NE(t_int1, t_double2); BOOST_CHECK_LE(t_double1, t_double2); } template <class T1, class T2> static void test_with_modofiers() { using namespace boost::typeindex; type_index t1 = type_id_with_cvr<T1>(); type_index t2 = type_id_with_cvr<T2>(); BOOST_CHECK_NE(t2, t1); BOOST_CHECK(t2 != t1.type_info()); BOOST_CHECK(t2.type_info() != t1); BOOST_CHECK(t1 < t2 || t2 < t1); BOOST_CHECK(t1 > t2 || t2 > t1); BOOST_CHECK(t1.type_info() < t2 || t2.type_info() < t1); BOOST_CHECK(t1.type_info() > t2 || t2.type_info() > t1); BOOST_CHECK(t1 < t2.type_info() || t2 < t1.type_info()); BOOST_CHECK(t1 > t2.type_info() || t2 > t1.type_info()); // Chaecking that comparison operators overloads compile BOOST_CHECK(t1 <= t2 || t2 <= t1); BOOST_CHECK(t1 >= t2 || t2 >= t1); BOOST_CHECK(t1.type_info() <= t2 || t2.type_info() <= t1); BOOST_CHECK(t1.type_info() >= t2 || t2.type_info() >= t1); BOOST_CHECK(t1 <= t2.type_info() || t2 <= t1.type_info()); BOOST_CHECK(t1 >= t2.type_info() || t2 >= t1.type_info()); BOOST_CHECK_EQUAL(t1, type_id_with_cvr<T1>()); BOOST_CHECK_EQUAL(t2, type_id_with_cvr<T2>()); BOOST_CHECK(t1 == type_id_with_cvr<T1>().type_info()); BOOST_CHECK(t2 == type_id_with_cvr<T2>().type_info()); BOOST_CHECK(t1.type_info() == type_id_with_cvr<T1>()); BOOST_CHECK(t2.type_info() == type_id_with_cvr<T2>()); BOOST_CHECK_EQUAL(t1.hash_code(), type_id_with_cvr<T1>().hash_code()); BOOST_CHECK_EQUAL(t2.hash_code(), type_id_with_cvr<T2>().hash_code()); BOOST_CHECK_NE(t1.hash_code(), type_id_with_cvr<T2>().hash_code()); BOOST_CHECK_NE(t2.hash_code(), type_id_with_cvr<T1>().hash_code()); } void type_id_storing_modifiers() { test_with_modofiers<int, const int>(); test_with_modofiers<int, const int&>(); test_with_modofiers<int, int&>(); test_with_modofiers<int, volatile int>(); test_with_modofiers<int, volatile int&>(); test_with_modofiers<int, const volatile int>(); test_with_modofiers<int, const volatile int&>(); test_with_modofiers<const int, int>(); test_with_modofiers<const int, const int&>(); test_with_modofiers<const int, int&>(); test_with_modofiers<const int, volatile int>(); test_with_modofiers<const int, volatile int&>(); test_with_modofiers<const int, const volatile int>(); test_with_modofiers<const int, const volatile int&>(); test_with_modofiers<const int&, int>(); test_with_modofiers<const int&, const int>(); test_with_modofiers<const int&, int&>(); test_with_modofiers<const int&, volatile int>(); test_with_modofiers<const int&, volatile int&>(); test_with_modofiers<const int&, const volatile int>(); test_with_modofiers<const int&, const volatile int&>(); test_with_modofiers<int&, const int>(); test_with_modofiers<int&, const int&>(); test_with_modofiers<int&, int>(); test_with_modofiers<int&, volatile int>(); test_with_modofiers<int&, volatile int&>(); test_with_modofiers<int&, const volatile int>(); test_with_modofiers<int&, const volatile int&>(); #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES test_with_modofiers<int&&, const int>(); test_with_modofiers<int&&, const int&>(); test_with_modofiers<int&&, const int&&>(); test_with_modofiers<int&&, int>(); test_with_modofiers<int&&, volatile int>(); test_with_modofiers<int&&, volatile int&>(); test_with_modofiers<int&&, volatile int&&>(); test_with_modofiers<int&&, const volatile int>(); test_with_modofiers<int&&, const volatile int&>(); test_with_modofiers<int&&, const volatile int&&>(); #endif } template <class T> static void test_storing_nonstoring_modifiers_templ() { using namespace boost::typeindex; type_index t1 = type_id_with_cvr<T>(); type_index t2 = type_id<T>(); BOOST_CHECK_EQUAL(t2, t1); BOOST_CHECK_EQUAL(t1, t2); BOOST_CHECK(t1 <= t2); BOOST_CHECK(t1 >= t2); BOOST_CHECK(t2 <= t1); BOOST_CHECK(t2 >= t1); BOOST_CHECK_EQUAL(t2.pretty_name(), t1.pretty_name()); } void type_id_storing_modifiers_vs_nonstoring() { test_storing_nonstoring_modifiers_templ<int>(); test_storing_nonstoring_modifiers_templ<my_namespace1::my_class>(); test_storing_nonstoring_modifiers_templ<my_namespace2::my_class>(); boost::typeindex::type_index t1 = boost::typeindex::type_id_with_cvr<const int>(); boost::typeindex::type_index t2 = boost::typeindex::type_id<int>(); BOOST_CHECK_NE(t2, t1); BOOST_CHECK(t1.pretty_name() == "const int" || t1.pretty_name() == "int const"); } void type_index_stream_operator_via_lexical_cast_testing() { using namespace boost::typeindex; std::string s_int2 = boost::lexical_cast<std::string>(type_id<int>()); BOOST_CHECK_EQUAL(s_int2, "int"); std::string s_double2 = boost::lexical_cast<std::string>(type_id<double>()); BOOST_CHECK_EQUAL(s_double2, "double"); } void type_index_stripping_cvr_test() { using namespace boost::typeindex; BOOST_CHECK_EQUAL(type_id<int>(), type_id<const int>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<const volatile int>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<const volatile int&>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<int&>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<volatile int>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<volatile int&>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<const double>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<const volatile double>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<const volatile double&>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<double&>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<volatile double>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<volatile double&>()); } void type_index_user_defined_class_test() { using namespace boost::typeindex; BOOST_CHECK_EQUAL(type_id<my_namespace1::my_class>(), type_id<my_namespace1::my_class>()); BOOST_CHECK_EQUAL(type_id<my_namespace2::my_class>(), type_id<my_namespace2::my_class>()); #ifndef BOOST_NO_RTTI BOOST_CHECK(type_id<my_namespace1::my_class>() == typeid(my_namespace1::my_class)); BOOST_CHECK(type_id<my_namespace2::my_class>() == typeid(my_namespace2::my_class)); BOOST_CHECK(typeid(my_namespace1::my_class) == type_id<my_namespace1::my_class>()); BOOST_CHECK(typeid(my_namespace2::my_class) == type_id<my_namespace2::my_class>()); #endif BOOST_CHECK_NE(type_id<my_namespace1::my_class>(), type_id<my_namespace2::my_class>()); BOOST_CHECK_NE( type_id<my_namespace1::my_class>().pretty_name().find("my_namespace1::my_class"), std::string::npos); } struct A { public: BOOST_TYPE_INDEX_REGISTER_CLASS virtual ~A(){} }; struct B: public A { BOOST_TYPE_INDEX_REGISTER_CLASS }; struct C: public B { BOOST_TYPE_INDEX_REGISTER_CLASS }; void comparators_type_id_runtime() { C c1; B b1; A* pc1 = &c1; A& rc1 = c1; A* pb1 = &b1; A& rb1 = b1; #ifndef BOOST_NO_RTTI BOOST_CHECK(typeid(rc1) == typeid(*pc1)); BOOST_CHECK(typeid(rb1) == typeid(*pb1)); BOOST_CHECK(typeid(rc1) != typeid(*pb1)); BOOST_CHECK(typeid(rb1) != typeid(*pc1)); BOOST_CHECK(typeid(&rc1) == typeid(pb1)); BOOST_CHECK(typeid(&rb1) == typeid(pc1)); #else BOOST_CHECK(boost::typeindex::type_index(pc1->boost_type_index_type_id_runtime_()).raw_name()); #endif BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(rc1), boost::typeindex::type_id_runtime(*pc1)); BOOST_CHECK_EQUAL(boost::typeindex::type_id<C>(), boost::typeindex::type_id_runtime(*pc1)); BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(rb1), boost::typeindex::type_id_runtime(*pb1)); BOOST_CHECK_EQUAL(boost::typeindex::type_id<B>(), boost::typeindex::type_id_runtime(*pb1)); BOOST_CHECK_NE(boost::typeindex::type_id_runtime(rc1), boost::typeindex::type_id_runtime(*pb1)); BOOST_CHECK_NE(boost::typeindex::type_id_runtime(rb1), boost::typeindex::type_id_runtime(*pc1)); #ifndef BOOST_NO_RTTI BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(&rc1), boost::typeindex::type_id_runtime(pb1)); BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(&rb1), boost::typeindex::type_id_runtime(pc1)); BOOST_CHECK(boost::typeindex::type_id_runtime(rc1) == typeid(*pc1)); BOOST_CHECK(boost::typeindex::type_id_runtime(rb1) == typeid(*pb1)); BOOST_CHECK(boost::typeindex::type_id_runtime(rc1) != typeid(*pb1)); BOOST_CHECK(boost::typeindex::type_id_runtime(rb1) != typeid(*pc1)); BOOST_CHECK(boost::typeindex::type_id_runtime(&rc1) == typeid(pb1)); BOOST_CHECK(boost::typeindex::type_id_runtime(&rb1) == typeid(pc1)); #endif } #ifndef BOOST_NO_RTTI void comparators_type_id_vs_type_info() { using namespace boost::typeindex; type_index t_int = type_id<int>(); BOOST_CHECK(t_int == typeid(int)); BOOST_CHECK(typeid(int) == t_int); BOOST_CHECK(t_int <= typeid(int)); BOOST_CHECK(typeid(int) <= t_int); BOOST_CHECK(t_int >= typeid(int)); BOOST_CHECK(typeid(int) >= t_int); type_index t_double = type_id<double>(); BOOST_CHECK(t_double == typeid(double)); BOOST_CHECK(typeid(double) == t_double); BOOST_CHECK(t_double <= typeid(double)); BOOST_CHECK(typeid(double) <= t_double); BOOST_CHECK(t_double >= typeid(double)); BOOST_CHECK(typeid(double) >= t_double); if (t_double < t_int) { BOOST_CHECK(t_double < typeid(int)); BOOST_CHECK(typeid(double) < t_int); BOOST_CHECK(typeid(int) > t_double); BOOST_CHECK(t_int > typeid(double)); BOOST_CHECK(t_double <= typeid(int)); BOOST_CHECK(typeid(double) <= t_int); BOOST_CHECK(typeid(int) >= t_double); BOOST_CHECK(t_int >= typeid(double)); } else { BOOST_CHECK(t_double > typeid(int)); BOOST_CHECK(typeid(double) > t_int); BOOST_CHECK(typeid(int) < t_double); BOOST_CHECK(t_int < typeid(double)); BOOST_CHECK(t_double >= typeid(int)); BOOST_CHECK(typeid(double) >= t_int); BOOST_CHECK(typeid(int) <= t_double); BOOST_CHECK(t_int <= typeid(double)); } } #endif // BOOST_NO_RTTI int test_main(int , char* []) { names_matches_type_id(); default_construction(); copy_construction(); comparators_type_id(); hash_code_type_id(); type_id_storing_modifiers(); type_id_storing_modifiers_vs_nonstoring(); type_index_stream_operator_via_lexical_cast_testing(); type_index_stripping_cvr_test(); type_index_user_defined_class_test(); comparators_type_id_runtime(); #ifndef BOOST_NO_RTTI comparators_type_id_vs_type_info(); #endif return 0; }
33.720588
104
0.672554
Abce
05a6cf3b2dd11e36ff53ce0c1def9bbf6099d848
2,190
cpp
C++
src/boydelatour.cpp
matheuscscp/TG
a460ed3f756cd9a759f7a0accc69bfe0754c4f2e
[ "MIT" ]
1
2016-06-10T02:37:25.000Z
2016-06-10T02:37:25.000Z
src/boydelatour.cpp
matheuscscp/TG
a460ed3f756cd9a759f7a0accc69bfe0754c4f2e
[ "MIT" ]
null
null
null
src/boydelatour.cpp
matheuscscp/TG
a460ed3f756cd9a759f7a0accc69bfe0754c4f2e
[ "MIT" ]
null
null
null
#include "libtg.hpp" #define clip(X) min(X,10000) using namespace std; static vector<Vertex>* formula; // position of u in a reverse toposort static vector<int> posdp; static int pos(int u) { static int next = 1; int& ans = posdp[u]; if (ans) return ans; for (int v : (*formula)[u].down) pos(v); return ans = next++; } // p(phi(u)) static vector<int> p; static int p_(int u) { int& ans = p[u]; if (ans) return ans; switch ((*formula)[u].type) { case CONJ: ans = 0; for (int v : (*formula)[u].down) ans = clip(ans+p_(v)); break; case DISJ: ans = 1; for (int v : (*formula)[u].down) ans = clip(ans*p_(v)); break; default: ans = 1; break; } return ans; } // Boy de la Tour's top-down renaming static void R_rec(int u, int a) { auto& phi = (*formula)[u]; if (p[u] == 1) return; // check renaming condition bool renamed = false; if (a >= 2 && (a != 2 || p[u] != 2)) { // ap > a+p a = 1; renamed = true; } // search children if (phi.type == CONJ) { for (int v : phi.down) R_rec(v,a); p[u] = 0; for (int v : phi.down) p[u] = clip(p[u]+p[v]); } else { // phi.type == DISJ int n = phi.down.size(); vector<int> dp(n,1); // dp[i] = prod(phi_j.p), i < j < n for (int i = n-2; 0 <= i; i--) dp[i] = clip(p[phi.down[i+1]]*dp[i+1]); int ai = a; // ai = a*prod(phi_j.p), 0 <= j < i for (int i = 0; i < n; i++) { R_rec(phi.down[i],clip(ai*dp[i])); ai = clip(ai*p[phi.down[i]]); } p[u] = 1; for (int v : phi.down) p[u] = clip(p[u]*p[v]); } if (renamed) { R.push_back(u); p[u] = 1; } } void boydelatour() { formula = (is_tree ? &T : &G); // dp tables posdp = vector<int>(formula->size(),0); p = vector<int>(formula->size(),0); // necessary preprocessing for Boy de la Tour's algorithm // compute p field and reverse toposort edges auto toposortless = [](int u, int v) { return pos(u) < pos(v); }; for (int u = 0; u < formula->size(); u++) { auto& phi = (*formula)[u]; sort(phi.down.begin(),phi.down.end(),toposortless); p[u] = p_(u); } R_rec(0,1); // recursive algorithm }
23.052632
74
0.528311
matheuscscp
05a8a2c97bbfb68028699f4ffdd7a63d12c7c337
2,831
cc
C++
mindspore/ccsrc/backend/optimizer/graph_kernel/eliminate_redundant_complex.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
1
2021-07-03T06:52:20.000Z
2021-07-03T06:52:20.000Z
mindspore/ccsrc/backend/optimizer/graph_kernel/eliminate_redundant_complex.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/backend/optimizer/graph_kernel/eliminate_redundant_complex.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "backend/optimizer/graph_kernel/eliminate_redundant_complex.h" #include <algorithm> #include <vector> #include <string> #include <utility> #include "frontend/optimizer/irpass.h" #include "backend/session/anf_runtime_algorithm.h" #include "backend/kernel_compiler/common_utils.h" #include "debug/anf_ir_dump.h" namespace mindspore { namespace opt { namespace { bool EliminateRedudantComplexInGraphkernel(const FuncGraphPtr &func_graph) { auto mng = func_graph->manager(); MS_EXCEPTION_IF_NULL(mng); auto todos = TopoSort(func_graph->get_return()); bool changed = false; for (const auto &node : todos) { auto cnode = node->cast<CNodePtr>(); // Find all Complex node in graphkernel sub_graph if (cnode != nullptr && IsPrimitiveCNode(cnode, std::make_shared<Primitive>("Complex"))) { auto original_users = mng->node_users()[cnode]; for (const auto &getitem_iter : original_users) { auto getitem = getitem_iter.first; auto getitem_cnode = getitem->cast<CNodePtr>(); // Find all complex users which are CReal or CImag, then use Complex inputs replace them. if (IsPrimitiveCNode(getitem_cnode, std::make_shared<Primitive>("CReal"))) { mng->Replace(getitem, cnode->inputs()[1]); changed = true; } else if (IsPrimitiveCNode(getitem_cnode, std::make_shared<Primitive>("CImag"))) { mng->Replace(getitem, cnode->inputs()[2]); changed = true; } } } } return changed; } } // namespace bool EliminateRedundantComplex::Run(const FuncGraphPtr &func_graph) { auto mng = func_graph->manager(); MS_EXCEPTION_IF_NULL(mng); bool changed = false; auto todos = TopoSort(func_graph->get_return()); std::reverse(todos.begin(), todos.end()); for (const auto &node : todos) { auto cnode = node->cast<CNodePtr>(); // Check whether graph_kernel node if (cnode != nullptr && AnfAlgo::IsGraphKernel(cnode)) { auto graph_kernel_fg = AnfAlgo::GetCNodeFuncGraphPtr(cnode); MS_EXCEPTION_IF_NULL(graph_kernel_fg); changed = EliminateRedudantComplexInGraphkernel(graph_kernel_fg) || changed; } } return changed; } } // namespace opt } // namespace mindspore
36.294872
97
0.705051
Vincent34
05af88578e695fae5aef5141d6dcd710aad563a4
863
cpp
C++
prj_4/dictionary_merge.cpp
MatrixWood/some-modern-cpp-training
d4d6901acf394bd6d620d63aab5f514839e31c57
[ "MIT" ]
null
null
null
prj_4/dictionary_merge.cpp
MatrixWood/some-modern-cpp-training
d4d6901acf394bd6d620d63aab5f514839e31c57
[ "MIT" ]
null
null
null
prj_4/dictionary_merge.cpp
MatrixWood/some-modern-cpp-training
d4d6901acf394bd6d620d63aab5f514839e31c57
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <iterator> #include <deque> #include <tuple> #include <string> #include <fstream> using namespace std; using dict_entry = pair<string, string>; namespace std { ostream& operator<<(ostream &os, const dict_entry p) { return os << p.first << " " << p.second; } istream& operator>>(istream &is, dict_entry &p) { return is >> p.first >> p.second; } } template <typename IS> deque<dict_entry> from_instream(IS &&is) { deque<dict_entry> d {istream_iterator<dict_entry>{is}, {}}; sort(begin(d), end(d)); return d; } int main() { ifstream file_in {"dict.txt"}; const auto dict1 (from_instream(ifstream{"dict.txt"})); const auto dict2 (from_instream(cin)); merge(begin(dict1), end(dict1), begin(dict2), end(dict2), ostream_iterator<dict_entry>{cout, "\n"}); }
20.069767
63
0.651217
MatrixWood
05b372e1c629199932cd5a8f322804fb6545217d
596
cpp
C++
C++/Cpp-Concurrency-in-Action/listing_4.16.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
1
2021-02-20T00:14:35.000Z
2021-02-20T00:14:35.000Z
C++/Cpp-Concurrency-in-Action/listing_4.16.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
null
null
null
C++/Cpp-Concurrency-in-Action/listing_4.16.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
null
null
null
void atm::getting_pin() { incoming.wait() .handle<digit_pressed>([&](digit_pressed const& msg) { unsigned const pin_length = 4; pin += msg.digit; if (pin.length() == pin_length) { bank.send(verify_pin(account, pin, incoming)); state = &atm::verifying_pin; } }) .handle<clear_last_pressed>([&](clear_last_pressed const& msg) { if (!pin.empty()) { pin.resize(pin.length() - 1); } }) .handle<cancel_pressed>( [&](cancel_pressed const& msg) { state = &atm::done_processing; }); }
31.368421
77
0.548658
haohaibo
05b38635a526b938ded96e2cddcd4052b36969bf
3,032
hpp
C++
samples/RayTracing/CameraManipulator.hpp
W4RH4WK/Vulkan-Hpp
33b244859b97650c9ca5d32ed6439f944f0eb83c
[ "Apache-2.0" ]
null
null
null
samples/RayTracing/CameraManipulator.hpp
W4RH4WK/Vulkan-Hpp
33b244859b97650c9ca5d32ed6439f944f0eb83c
[ "Apache-2.0" ]
null
null
null
samples/RayTracing/CameraManipulator.hpp
W4RH4WK/Vulkan-Hpp
33b244859b97650c9ca5d32ed6439f944f0eb83c
[ "Apache-2.0" ]
null
null
null
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <glm/glm.hpp> #include <vulkan/vulkan.hpp> namespace vk { namespace su { class CameraManipulator { public: enum class Action { None, Orbit, Dolly, Pan, LookAround }; enum class Mode { Examine, Fly, Walk, Trackball }; enum class MouseButton { None, Left, Middle, Right }; enum class ModifierFlagBits { Shift = 1, Ctrl = 2, Alt = 4 }; using ModifierFlags = vk::Flags<ModifierFlagBits, uint32_t, ModifierFlagBits::Shift>; public: CameraManipulator(); glm::vec3 const& getCameraPosition() const; glm::vec3 const& getCenterPosition() const; glm::mat4 const& getMatrix() const; Mode getMode() const; glm::ivec2 const& getMousePosition() const; float getRoll() const; float getSpeed() const; glm::vec3 const& getUpVector() const; glm::u32vec2 const& getWindowSize() const; Action mouseMove(glm::ivec2 const& position, MouseButton mouseButton, ModifierFlags & modifiers); void setLookat(const glm::vec3& cameraPosition, const glm::vec3& centerPosition, const glm::vec3& upVector); void setMode(Mode mode); void setMousePosition(glm::ivec2 const& position); void setRoll(float roll); // roll in radians void setSpeed(float speed); void setWindowSize(glm::ivec2 const& size); void wheel(int value); private: void dolly(glm::vec2 const& delta); void motion(glm::ivec2 const& position, Action action = Action::None); void orbit(glm::vec2 const& delta, bool invert = false); void pan(glm::vec2 const& delta); double projectOntoTBSphere(const glm::vec2& p); void trackball(glm::ivec2 const& position); void update(); private: glm::vec3 m_cameraPosition = glm::vec3(10, 10, 10); glm::vec3 m_centerPosition = glm::vec3(0, 0, 0); glm::vec3 m_upVector = glm::vec3(0, 1, 0); float m_roll = 0; // Rotation around the Z axis in RAD glm::mat4 m_matrix = glm::mat4(1); glm::u32vec2 m_windowSize = glm::u32vec2(1, 1); float m_speed = 30.0f; glm::ivec2 m_mousePosition = glm::ivec2(0, 0); Mode m_mode = Mode::Examine; }; } // namespace su } // namespace vk
37.9
116
0.628958
W4RH4WK
05b4c5234ba53c898edaec6ba6aee734875dc6ca
7,126
cpp
C++
src/third_party/mozjs-45/extract/js/src/jit/InstructionReordering.cpp
danx0r/mongo
70d4944c235bcdf7fbbc63971099563d2af72956
[ "Apache-2.0" ]
72
2020-06-12T06:33:41.000Z
2021-03-22T03:15:56.000Z
src/third_party/mozjs-45/extract/js/src/jit/InstructionReordering.cpp
danx0r/mongo
70d4944c235bcdf7fbbc63971099563d2af72956
[ "Apache-2.0" ]
9
2020-07-02T09:36:49.000Z
2021-03-25T23:54:00.000Z
src/third_party/mozjs-45/extract/js/src/jit/InstructionReordering.cpp
danx0r/mongo
70d4944c235bcdf7fbbc63971099563d2af72956
[ "Apache-2.0" ]
14
2020-06-12T03:08:03.000Z
2021-02-03T11:43:09.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "jit/InstructionReordering.h" #include "jit/MIRGraph.h" using namespace js; using namespace js::jit; static void MoveBefore(MBasicBlock* block, MInstruction* at, MInstruction* ins) { if (at == ins) return; // Update instruction numbers. for (MInstructionIterator iter(block->begin(at)); *iter != ins; iter++) { MOZ_ASSERT(iter->id() < ins->id()); iter->setId(iter->id() + 1); } ins->setId(at->id() - 1); block->moveBefore(at, ins); } static bool IsLastUse(MDefinition* ins, MDefinition* input, MBasicBlock* loopHeader) { // If we are in a loop, this cannot be the last use of any definitions from // outside the loop, as those definitions can be used in future iterations. if (loopHeader && input->block()->id() < loopHeader->id()) return false; for (MUseDefIterator iter(input); iter; iter++) { // Watch for uses defined in blocks which ReorderInstructions hasn't // processed yet. These nodes have not had their ids set yet. if (iter.def()->block()->id() > ins->block()->id()) return false; if (iter.def()->id() > ins->id()) return false; } return true; } bool jit::ReorderInstructions(MIRGenerator* mir, MIRGraph& graph) { // Renumber all instructions in the graph as we go. size_t nextId = 0; // List of the headers of any loops we are in. Vector<MBasicBlock*, 4, SystemAllocPolicy> loopHeaders; for (ReversePostorderIterator block(graph.rpoBegin()); block != graph.rpoEnd(); block++) { // Don't reorder instructions within entry blocks, which have special requirements. if (*block == graph.entryBlock() || *block == graph.osrBlock()) continue; if (block->isLoopHeader()) { if (!loopHeaders.append(*block)) return false; } MBasicBlock* innerLoop = loopHeaders.empty() ? nullptr : loopHeaders.back(); for (MPhiIterator iter(block->phisBegin()); iter != block->phisEnd(); iter++) iter->setId(nextId++); for (MInstructionIterator iter(block->begin()); iter != block->end(); iter++) iter->setId(nextId++); for (MInstructionIterator iter(block->begin()); iter != block->end(); ) { MInstruction* ins = *iter; // Filter out some instructions which are never reordered. if (ins->isEffectful() || !ins->isMovable() || ins->resumePoint() || ins == block->lastIns()) { iter++; continue; } // Move constants with a single use in the current block to the // start of the block. Constants won't be reordered by the logic // below, as they have no inputs. Moving them up as high as // possible can allow their use to be moved up further, though, // and has no cost if the constant is emitted at its use. if (ins->isConstant() && ins->hasOneUse() && ins->usesBegin()->consumer()->block() == *block && !IsFloatingPointType(ins->type())) { iter++; MInstructionIterator targetIter = block->begin(); while (targetIter->isConstant() || targetIter->isInterruptCheck()) { if (*targetIter == ins) break; targetIter++; } MoveBefore(*block, *targetIter, ins); continue; } // Look for inputs where this instruction is the last use of that // input. If we move this instruction up, the input's lifetime will // be shortened, modulo resume point uses (which don't need to be // stored in a register, and can be handled by the register // allocator by just spilling at some point with no reload). Vector<MDefinition*, 4, SystemAllocPolicy> lastUsedInputs; for (size_t i = 0; i < ins->numOperands(); i++) { MDefinition* input = ins->getOperand(i); if (!input->isConstant() && IsLastUse(ins, input, innerLoop)) { if (!lastUsedInputs.append(input)) return false; } } // Don't try to move instructions which aren't the last use of any // of their inputs (we really ought to move these down instead). if (lastUsedInputs.length() < 2) { iter++; continue; } MInstruction* target = ins; for (MInstructionReverseIterator riter = ++block->rbegin(ins); riter != block->rend(); riter++) { MInstruction* prev = *riter; if (prev->isInterruptCheck()) break; // The instruction can't be moved before any of its uses. bool isUse = false; for (size_t i = 0; i < ins->numOperands(); i++) { if (ins->getOperand(i) == prev) { isUse = true; break; } } if (isUse) break; // The instruction can't be moved before an instruction that // stores to a location read by the instruction. if (prev->isEffectful() && (ins->getAliasSet().flags() & prev->getAliasSet().flags()) && ins->mightAlias(prev)) { break; } // Make sure the instruction will still be the last use of one // of its inputs when moved up this far. for (size_t i = 0; i < lastUsedInputs.length(); ) { bool found = false; for (size_t j = 0; j < prev->numOperands(); j++) { if (prev->getOperand(j) == lastUsedInputs[i]) { found = true; break; } } if (found) { lastUsedInputs[i] = lastUsedInputs.back(); lastUsedInputs.popBack(); } else { i++; } } if (lastUsedInputs.length() < 2) break; // We can move the instruction before this one. target = prev; } iter++; MoveBefore(*block, target, ins); } if (block->isLoopBackedge()) loopHeaders.popBack(); } return true; }
37.904255
109
0.511086
danx0r
05b897c9c3e127bb51aae3329e962a46e18b36c4
9,288
cxx
C++
python/src/b2Math.cxx
pyb2d/pyb2d
5d0f9f581d93c3681ee4f518a5d7fd6be900e695
[ "MIT" ]
26
2021-12-10T12:08:39.000Z
2022-03-29T17:45:31.000Z
python/src/b2Math.cxx
pyb2d/pyb2d
5d0f9f581d93c3681ee4f518a5d7fd6be900e695
[ "MIT" ]
14
2021-11-18T23:58:55.000Z
2022-01-06T09:44:58.000Z
python/src/b2Math.cxx
DerThorsten/pybox2d
5d0f9f581d93c3681ee4f518a5d7fd6be900e695
[ "MIT" ]
3
2021-12-16T05:52:12.000Z
2021-12-21T08:58:54.000Z
#include <pybind11/pybind11.h> #include <pybind11/operators.h> #include "box2d_wrapper.hpp" namespace py = pybind11; b2Vec2 operator+ (const b2Vec2 & lhs, const py::tuple & rhs) { return b2Vec2( lhs.x + rhs[0].cast<float>() , lhs.y + rhs[1].cast<float>() ); } b2Vec2 operator+ (const py::tuple & lhs, const b2Vec2 & rhs) { return b2Vec2( lhs[0].cast<float>() + rhs.x , lhs[1].cast<float>() + rhs.y ); } // b2Vec2 operator+ (const b2Vec2 & lhs, const b2Vec2 & rhs) // { // return b2Vec2( // lhs.x + rhs.x , // lhs.y + rhs.y // ); // } #ifndef PYB2D_LIQUID_FUN b2Vec2 operator/ (const b2Vec2 & lhs, float rhs) { return b2Vec2( lhs.x / rhs , lhs.y / rhs ); } b2Vec2 operator* (const b2Vec2 & lhs, float rhs) { return b2Vec2( lhs.x * rhs , lhs.y * rhs ); } #endif void exportB2Math(py::module & pyb2dModule){ pyb2dModule.def("b2IsValid",&b2IsValid, py::arg("x")); //pyb2dModule.def("b2InvSqrt",&b2InvSqrt, py::arg("x")); pyb2dModule.def("b2Sqrt",&sqrtf, py::arg("x")); pyb2dModule.def("b2Atan2",&atan2f, py::arg("x"),py::arg("y")); py::class_<b2Vec2>(pyb2dModule,"Vec2") .def(py::init([](py::tuple t) { if(py::len(t) != 2) { throw std::runtime_error("tuple has wrong length"); } return new b2Vec2(t[0].cast<float>(), t[1].cast<float>()); } )) .def(py::init([](py::list t) { if(py::len(t) != 2) { throw std::runtime_error("list has wrong length"); } return new b2Vec2(t[0].cast<float>(), t[1].cast<float>()); } )) .def(py::init<>()) .def(py::init<b2Vec2>()) .def(py::init<float,float>(),py::arg("x"),py::arg("y")) .def_readwrite("x", &b2Vec2::x) .def_readwrite("y", &b2Vec2::y) // member functions .def("set_zero",&b2Vec2::SetZero) .def("Set",&b2Vec2::Set,py::arg("x"),py::arg("y")) //.def("Length",&b2Vec2::Length) .def("normalize",&b2Vec2::Normalize) .def("is_valid",&b2Vec2::IsValid) .def("skew",&b2Vec2::Skew) .def("__len__",[](const b2Vec2 & vec){return 2;}) // operators // .def(py::self += py::self) // .def(py::self -= py::self) // .def(py::self *= float()) // .def(py::self + float()) // .def(py::self - float()) .def(float() * py::self) .def(py::self * float()) .def(py::self / float()) .def(py::self + py::self) .def(py::self - py::self) // .def(py::self + py::tuple()) // .def(py::tuple() + py::self) .def_property_readonly("length",[](const b2Vec2 & self){ return std::sqrt(self.x * self.x + self.y * self.y); }) .def_property_readonly("length_squared",&b2Vec2::LengthSquared) ; py::implicitly_convertible<py::tuple, b2Vec2>(); py::implicitly_convertible<py::list, b2Vec2>(); py::class_<b2Vec3>(pyb2dModule,"Vec3") .def(py::init<>()) .def(py::init<float,float,float>(),py::arg("x"),py::arg("y"),py::arg("z")) .def_readwrite("x", &b2Vec3::x) .def_readwrite("y", &b2Vec3::y) .def_readwrite("z", &b2Vec3::z) // member functions .def("set_zero",&b2Vec3::SetZero) .def("set",&b2Vec3::Set,py::arg("x"),py::arg("y"),py::arg("z")) //.def("normalize",&b2Vec3::Normalize) // operators .def(py::self += py::self) .def(py::self -= py::self) .def(py::self *= float()) //.def_property_readonly("length",&b2Vec3::Length) // .def_property_readonly("length_squared",&b2Vec3::LengthSquared) ; // py::class_<b2Vec4>(pyb2dModule,"b2Vec4") // .def(py::init<>()) // .def(py::init<float,float,float,float>(),py::arg("x"),py::arg("y"),py::arg("z"),py::arg("w")) // .def_readwrite("x", &b2Vec4::x) // .def_readwrite("y", &b2Vec4::y) // .def_readwrite("z", &b2Vec4::z) // .def_readwrite("z", &b2Vec4::w) // //.def_property_readonly("length",&b2Vec4::Length) // //.def_property_readonly("length_squared",&b2Vec4::LengthSquared) // ; py::class_<b2Mat22>(pyb2dModule,"Mat22") .def(py::init<>()) .def(py::init<const b2Vec2 &,const b2Vec2 &>(),py::arg("c1"),py::arg("c2")) .def(py::init<float,float,float,float>(),py::arg("a11"),py::arg("a12"),py::arg("a21"),py::arg("a22")) .def_readwrite("ex", &b2Mat22::ex) .def_readwrite("ey", &b2Mat22::ey) // member functions .def("set",&b2Mat22::Set,py::arg("c1"),py::arg("c2")) .def("set_identity",&b2Mat22::SetIdentity) .def("set_zero",&b2Mat22::SetZero) .def("get_inverse",&b2Mat22::GetInverse) .def("solve",&b2Mat22::Solve,py::arg("b")) // operators ; py::class_<b2Mat33>(pyb2dModule,"Mat33") .def(py::init<>()) .def(py::init<const b2Vec3 &,const b2Vec3 &,const b2Vec3 &>(),py::arg("c1"),py::arg("c2"),py::arg("c3")) .def_readwrite("ex", &b2Mat33::ex) .def_readwrite("ey", &b2Mat33::ey) .def_readwrite("ez", &b2Mat33::ez) // member functions .def("set_zero",&b2Mat33::SetZero) .def("solve_33",&b2Mat33::Solve33,py::arg("b")) .def("solve_22",&b2Mat33::Solve22,py::arg("b")) .def("get_inverse_22",&b2Mat33::GetInverse22,py::arg("M")) .def("get_sym_inverse_33",&b2Mat33::GetSymInverse33,py::arg("M")) // operators // ; py::class_<b2Rot>(pyb2dModule,"Rot") .def(py::init<>()) .def(py::init<float>(),py::arg("angle")) .def_readwrite("s", &b2Rot::s) .def_readwrite("c", &b2Rot::c) // member functions .def("set",&b2Rot::Set,py::arg("angle")) .def("set_identity",&b2Rot::SetIdentity) .def("get_angle",&b2Rot::GetAngle) .def("get_x_axis",&b2Rot::GetXAxis) .def("get_y_axis",&b2Rot::GetYAxis) // operators // ; py::class_<b2Transform>(pyb2dModule,"Transform") .def(py::init<>()) .def(py::init<const b2Vec2 &, const b2Rot & >(),py::arg("position"),py::arg("rotation")) .def_readwrite("p", &b2Transform::p) .def_readwrite("position", &b2Transform::p) .def_readwrite("q", &b2Transform::q) // member functions .def("set",&b2Transform::Set,py::arg("position"),py::arg("angle")) .def("set_identity",&b2Transform::SetIdentity) // .def("GetPositionX",&b2Transform::GetPositionX) // .def("GetPositionY",&b2Transform::GetPositionY) //.def("GetRotationCos",&b2Transform::GetRotationCos) // operators // ; py::class_<b2Sweep>(pyb2dModule,"Sweep") .def(py::init<>()) .def_readwrite("local_center", &b2Sweep::localCenter) .def_readwrite("c0", &b2Sweep::c0) .def_readwrite("c", &b2Sweep::c) .def_readwrite("a0", &b2Sweep::a0) .def_readwrite("a", &b2Sweep::a) .def_readwrite("alpha0", &b2Sweep::alpha0) // member functions .def("Advance",&b2Sweep::Advance,py::arg("alpha")) .def("Normalize",&b2Sweep::Normalize) // operators // ; pyb2dModule.def("dot", [](const b2Vec2& a, const b2Vec2& b){ return b2Dot(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("dot", [](const b2Vec3& a, const b2Vec3& b){ return b2Dot(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("cross", [](const b2Vec2& a, const b2Vec2& b){ return b2Cross(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("cross", [](const b2Vec3& a, const b2Vec3& b){ return b2Cross(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("cross", [](const b2Vec2& a, float b){ return b2Cross(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("cross", [](float a, const b2Vec2& b){ return b2Cross(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("mulT", [](const b2Mat22 & A, const b2Vec2& v){ return b2MulT(A,v); },py::arg("A"),py::arg("v")); pyb2dModule.def("mulT", [](const b2Rot & q, const b2Vec2& v){ return b2MulT(q,v); },py::arg("q"),py::arg("v")); pyb2dModule.def("distance", [](const b2Vec2& a, const b2Vec2& b){ return b2Distance(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("distance_squared", [](const b2Vec2& a, const b2Vec2& b){ return b2DistanceSquared(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("mul", [](const b2Mat22 & A, const b2Mat22& B){ return b2Mul(A,B); },py::arg("A"),py::arg("B")); pyb2dModule.def("mul", [](const b2Mat33 & A, const b2Vec3& v){ return b2Mul(A,v); },py::arg("A"),py::arg("v")); pyb2dModule.def("mul", [](const b2Rot & q, const b2Rot& r){ return b2Mul(q,r); },py::arg("q"),py::arg("r")); pyb2dModule.def("mul", [](const b2Rot & q, const b2Vec2& v){ return b2Mul(q,v); },py::arg("q"),py::arg("v")); pyb2dModule.def("mul", [](const b2Transform & T, const b2Vec2& v){ return b2Mul(T,v); },py::arg("T"),py::arg("v")); }
33.652174
112
0.535099
pyb2d
05ba47e8895cf955a05ef6a01d3c87fb17df13f6
354
hpp
C++
srook/type_traits/clock.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
1
2018-07-01T07:54:37.000Z
2018-07-01T07:54:37.000Z
srook/type_traits/clock.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
srook/type_traits/clock.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License #ifndef INCLUDED_SROOK_MPL_TYPETRAITS_CLOCK_HPP #define INCLUDED_SROOK_MPL_TYPETRAITS_CLOCK_HPP #ifdef _MSC_VER # if _MSC_VER > 1000 # pragma once # endif #endif #include <srook/type_traits/clock/is_clock.hpp> #include <srook/type_traits/clock/is_trivial_clock.hpp> #endif
22.125
66
0.788136
falgon
05bd135eb8b2b8e46aed8631402574a3e700a232
3,135
cpp
C++
src/RJChorus.cpp
netboy3/RJModules-rack-plugins
0ec265da4d7cff14c2b7fc6749e3f4e81241f093
[ "MIT" ]
null
null
null
src/RJChorus.cpp
netboy3/RJModules-rack-plugins
0ec265da4d7cff14c2b7fc6749e3f4e81241f093
[ "MIT" ]
null
null
null
src/RJChorus.cpp
netboy3/RJModules-rack-plugins
0ec265da4d7cff14c2b7fc6749e3f4e81241f093
[ "MIT" ]
null
null
null
/* Slackback! */ #include "RJModules.hpp" #include "common.hpp" #include "Chorus.h" #include <iostream> #include <cmath> #include <sstream> #include <iomanip> #include <unistd.h> #include <mutex> using namespace std; #define HISTORY_SIZE (1<<21) struct RJChorusRoundSmallBlackKnob : RoundSmallBlackKnob { RJChorusRoundSmallBlackKnob() { setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/KTFRoundSmallBlackKnob.svg"))); } }; struct RJChorus : Module { enum ParamIds { DELAY_PARAM, FREQ_PARAM, DEPTH_PARAM, NUM_PARAMS }; enum InputIds { IN_INPUT, DELAY_CV, FREQ_CV, DEPTH_CV, NUM_INPUTS }; enum OutputIds { OUT_OUTPUT, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; int lastDelay = 50; stk::Chorus chorus; RJChorus() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); configParam(RJChorus::DELAY_PARAM, 1, 6000, 50, "Delay Time ms"); configParam(RJChorus::FREQ_PARAM, 0.0, 25.0, 2.0, "Frequency"); configParam(RJChorus::DEPTH_PARAM, 0.00001, 0.99999, 0.99999, "Depth"); chorus = stk::Chorus(50); } void process(const ProcessArgs &args) override { float input = inputs[IN_INPUT].value; int delay = params[DELAY_PARAM].value * clamp(inputs[DELAY_CV].getNormalVoltage(1.0f) / 1.0f, 0.0f, 1.0f); if(delay != lastDelay){ chorus = stk::Chorus(delay); lastDelay = delay; } chorus.setModFrequency( params[FREQ_PARAM].value * clamp(inputs[FREQ_CV].getNormalVoltage(1.0f) / 1.0f, 0.0f, 1.0f) ); chorus.setModDepth( params[DEPTH_PARAM].value * clamp(inputs[DEPTH_CV].getNormalVoltage(1.0f) / 1.0f, 0.0f, 1.0f) ); float processed = chorus.tick( input ); outputs[OUT_OUTPUT].value = processed; } }; struct RJChorusWidget : ModuleWidget { RJChorusWidget(RJChorus *module) { setModule(module); setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Chorus.svg"))); int ONE = -4; addParam(createParam<RJChorusRoundSmallBlackKnob>(mm2px(Vec(3.5, 38.9593 + ONE)), module, RJChorus::DELAY_PARAM)); addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 48.74977 + ONE)), module, RJChorus::DELAY_CV)); addParam(createParam<RJChorusRoundSmallBlackKnob>(mm2px(Vec(3.51398, 62.3 + ONE)), module, RJChorus::FREQ_PARAM)); addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 73.3 + ONE)), module, RJChorus::FREQ_CV)); int TWO = 45; addParam(createParam<RJChorusRoundSmallBlackKnob>(mm2px(Vec(3.5, 38.9593 + TWO)), module, RJChorus::DEPTH_PARAM)); addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 48.74977 + TWO)), module, RJChorus::DEPTH_CV)); addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 62.3 + TWO)), module, RJChorus::IN_INPUT)); addOutput(createOutput<PJ301MPort>(mm2px(Vec(3.51398, 73.3 + TWO)), module, RJChorus::OUT_OUTPUT)); } }; Model *modelRJChorus = createModel<RJChorus, RJChorusWidget>("RJChorus");
30.436893
126
0.649442
netboy3
05bd6ffb0a52b6134088fbd432cc826e23f25524
28,193
cpp
C++
src/helics/shared_api_library/FederateExport.cpp
manoj1511/HELICS
5b085bb4331f943d3fa98eb40056c3e10a1b882d
[ "BSD-3-Clause" ]
null
null
null
src/helics/shared_api_library/FederateExport.cpp
manoj1511/HELICS
5b085bb4331f943d3fa98eb40056c3e10a1b882d
[ "BSD-3-Clause" ]
null
null
null
src/helics/shared_api_library/FederateExport.cpp
manoj1511/HELICS
5b085bb4331f943d3fa98eb40056c3e10a1b882d
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017-2019, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #include "../core/core-exceptions.hpp" #include "../helics.hpp" #include "gmlc/concurrency/TripWire.hpp" #include "helics.h" #include "internal/api_objects.h" #include <iostream> #include <map> #include <mutex> #include <vector> /** this is a random identifier put in place when the federate or core or broker gets created*/ static const int fedValidationIdentifier = 0x2352188; static const char *invalidFedString = "federate object is not valid"; static const std::string nullstr; static constexpr char nullcstr[] = ""; namespace helics { FedObject *getFedObject (helics_federate fed, helics_error *err) noexcept { HELICS_ERROR_CHECK (err, nullptr); if (fed == nullptr) { if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = invalidFedString; } return nullptr; } auto fedObj = reinterpret_cast<helics::FedObject *> (fed); if (fedObj->valid == fedValidationIdentifier) { return fedObj; } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = invalidFedString; } return nullptr; } } // namespace helics helics::Federate *getFed (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); return (fedObj == nullptr) ? nullptr : fedObj->fedptr.get (); } static const char *notValueFedString = "Federate must be a value federate"; helics::ValueFederate *getValueFed (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } if ((fedObj->type == helics::vtype::value_fed) || (fedObj->type == helics::vtype::combination_fed)) { auto rval = dynamic_cast<helics::ValueFederate *> (fedObj->fedptr.get ()); if (rval != nullptr) { return rval; } } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = notValueFedString; } return nullptr; } static const char *notMessageFedString = "Federate must be a message federate"; helics::MessageFederate *getMessageFed (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } if ((fedObj->type == helics::vtype::message_fed) || (fedObj->type == helics::vtype::combination_fed)) { auto rval = dynamic_cast<helics::MessageFederate *> (fedObj->fedptr.get ()); if (rval != nullptr) { return rval; } } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = notMessageFedString; } return nullptr; } std::shared_ptr<helics::Federate> getFedSharedPtr (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } return fedObj->fedptr; } std::shared_ptr<helics::ValueFederate> getValueFedSharedPtr (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } if ((fedObj->type == helics::vtype::value_fed) || (fedObj->type == helics::vtype::combination_fed)) { auto rval = std::dynamic_pointer_cast<helics::ValueFederate> (fedObj->fedptr); if (rval) { return rval; } } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = notValueFedString; } return nullptr; } std::shared_ptr<helics::MessageFederate> getMessageFedSharedPtr (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } if ((fedObj->type == helics::vtype::message_fed) || (fedObj->type == helics::vtype::combination_fed)) { auto rval = std::dynamic_pointer_cast<helics::MessageFederate> (fedObj->fedptr); if (rval) { return rval; } } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = notMessageFedString; } return nullptr; } /* Creation and destruction of Federates */ helics_federate helicsCreateValueFederate (const char *fedName, helics_federate_info fi, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { if (fi == nullptr) { FedI->fedptr = std::make_shared<helics::ValueFederate> (AS_STRING (fedName), helics::FederateInfo ()); } else { FedI->fedptr = std::make_shared<helics::ValueFederate> (AS_STRING (fedName), *reinterpret_cast<helics::FederateInfo *> (fi)); } } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::value_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } helics_federate helicsCreateValueFederateFromConfig (const char *configFile, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { FedI->fedptr = std::make_shared<helics::ValueFederate> (AS_STRING (configFile)); } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::value_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } /* Creation and destruction of Federates */ helics_federate helicsCreateMessageFederate (const char *fedName, helics_federate_info fi, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { if (fi == nullptr) { FedI->fedptr = std::make_shared<helics::MessageFederate> (AS_STRING (fedName), helics::FederateInfo ()); } else { FedI->fedptr = std::make_shared<helics::MessageFederate> (AS_STRING (fedName), *reinterpret_cast<helics::FederateInfo *> (fi)); } } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::message_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } helics_federate helicsCreateMessageFederateFromConfig (const char *configFile, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { FedI->fedptr = std::make_shared<helics::MessageFederate> (AS_STRING (configFile)); } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::message_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } /* Creation and destruction of Federates */ helics_federate helicsCreateCombinationFederate (const char *fedName, helics_federate_info fi, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { if (fi == nullptr) { FedI->fedptr = std::make_shared<helics::CombinationFederate> (AS_STRING (fedName), helics::FederateInfo ()); } else { FedI->fedptr = std::make_shared<helics::CombinationFederate> (AS_STRING (fedName), *reinterpret_cast<helics::FederateInfo *> (fi)); } } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::combination_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } helics_federate helicsCreateCombinationFederateFromConfig (const char *configFile, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { FedI->fedptr = std::make_shared<helics::CombinationFederate> (AS_STRING (configFile)); } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::combination_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } helics_federate helicsFederateClone (helics_federate fed, helics_error *err) { auto *fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } auto fedClone = std::make_unique<helics::FedObject> (); fedClone->fedptr = fedObj->fedptr; fedClone->type = fedObj->type; fedClone->valid = fedObj->valid; auto fedB = reinterpret_cast<helics_federate> (fedClone.get ()); getMasterHolder ()->addFed (std::move (fedClone)); return (fedB); } helics_bool helicsFederateIsValid (helics_federate fed) { auto fedObj = getFed (fed, nullptr); return (fedObj == nullptr) ? helics_false : helics_true; } helics_core helicsFederateGetCoreObject (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return nullptr; } auto core = std::make_unique<helics::CoreObject> (); core->valid = coreValidationIdentifier; core->coreptr = fedObj->getCorePointer (); auto retcore = reinterpret_cast<helics_core> (core.get ()); getMasterHolder ()->addCore (std::move (core)); return retcore; } static constexpr char invalidFile[] = "Invalid File specification"; void helicsFederateRegisterInterfaces (helics_federate fed, const char *file, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } if (file == nullptr) { if (err != nullptr) { err->error_code = helics_error_invalid_argument; err->message = invalidFile; } return; } try { fedObj->registerInterfaces (file); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateFinalize (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->finalize (); } catch (...) { helicsErrorHandler (err); } } void helicsFederateFinalizeAsync (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->finalizeAsync (); } catch (...) { helicsErrorHandler (err); } } void helicsFederateFinalizeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->finalizeComplete (); } catch (...) { helicsErrorHandler (err); } } /* initialization, execution, and time requests */ void helicsFederateEnterInitializingMode (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterInitializingMode (); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateEnterInitializingModeAsync (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterInitializingModeAsync (); } catch (...) { return helicsErrorHandler (err); } } helics_bool helicsFederateIsAsyncOperationCompleted (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_false; } return (fedObj->isAsyncOperationCompleted ()) ? helics_true : helics_false; } void helicsFederateEnterInitializingModeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterInitializingModeComplete (); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateEnterExecutingMode (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { // printf("current state=%d\n", static_cast<int>(fedObj->getCurrentState())); fedObj->enterExecutingMode (); } catch (...) { return helicsErrorHandler (err); } } static helics::iteration_request getIterationRequest (helics_iteration_request iterate) { switch (iterate) { case helics_iteration_request_no_iteration: default: return helics::iteration_request::no_iterations; case helics_iteration_request_force_iteration: return helics::iteration_request::force_iteration; case helics_iteration_request_iterate_if_needed: return helics::iteration_request::iterate_if_needed; } } static helics_iteration_result getIterationStatus (helics::iteration_result iterationState) { switch (iterationState) { case helics::iteration_result::next_step: return helics_iteration_result_next_step; case helics::iteration_result::iterating: return helics_iteration_result_iterating; case helics::iteration_result::error: default: return helics_iteration_result_error; case helics::iteration_result::halted: return helics_iteration_result_halted; } } helics_iteration_result helicsFederateEnterExecutingModeIterative (helics_federate fed, helics_iteration_request iterate, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_iteration_result_error; } try { auto val = fedObj->enterExecutingMode (getIterationRequest (iterate)); return getIterationStatus (val); } catch (...) { helicsErrorHandler (err); return helics_iteration_result_error; } } void helicsFederateEnterExecutingModeAsync (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterExecutingModeAsync (); } catch (...) { helicsErrorHandler (err); } } void helicsFederateEnterExecutingModeIterativeAsync (helics_federate fed, helics_iteration_request iterate, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterExecutingModeAsync (getIterationRequest (iterate)); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateEnterExecutingModeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterExecutingModeComplete (); } catch (...) { return helicsErrorHandler (err); } } helics_iteration_result helicsFederateEnterExecutingModeIterativeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_iteration_result_error; } try { auto val = fedObj->enterExecutingModeComplete (); return getIterationStatus (val); } catch (...) { helicsErrorHandler (err); return helics_iteration_result_error; } } helics_time helicsFederateRequestTime (helics_federate fed, helics_time requestTime, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto timeret = fedObj->requestTime (requestTime); return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } helics_time helicsFederateRequestTimeAdvance (helics_federate fed, helics_time timeDelta, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto timeret = fedObj->requestTimeAdvance (timeDelta); return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } helics_time helicsFederateRequestNextStep (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto timeret = fedObj->requestNextStep (); return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } helics_time helicsFederateRequestTimeIterative (helics_federate fed, helics_time requestTime, helics_iteration_request iterate, helics_iteration_result *outIterate, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { if (outIterate != nullptr) { *outIterate = helics_iteration_result_error; } return helics_time_invalid; } try { auto val = fedObj->requestTimeIterative (requestTime, getIterationRequest (iterate)); if (outIterate != nullptr) { *outIterate = getIterationStatus (val.state); } return (val.grantedTime < helics::Time::maxVal ()) ? static_cast<double> (val.grantedTime) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); if (outIterate != nullptr) { *outIterate = helics_iteration_result_error; } return helics_time_invalid; } } void helicsFederateRequestTimeAsync (helics_federate fed, helics_time requestTime, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->requestTimeAsync (requestTime); } catch (...) { return helicsErrorHandler (err); } } helics_time helicsFederateRequestTimeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto timeret = fedObj->requestTimeComplete (); return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } void helicsFederateRequestTimeIterativeAsync (helics_federate fed, helics_time requestTime, helics_iteration_request iterate, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->requestTimeIterative (requestTime, getIterationRequest (iterate)); } catch (...) { return helicsErrorHandler (err); } } helics_time helicsFederateRequestTimeIterativeComplete (helics_federate fed, helics_iteration_result *outIteration, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto val = fedObj->requestTimeIterativeComplete (); if (outIteration != nullptr) { *outIteration = getIterationStatus (val.state); } return (val.grantedTime < helics::Time::maxVal ()) ? static_cast<double> (val.grantedTime) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } static const std::map<helics::Federate::modes, helics_federate_state> modeEnumConversions{ {helics::Federate::modes::error, helics_federate_state::helics_state_error}, {helics::Federate::modes::startup, helics_federate_state::helics_state_startup}, {helics::Federate::modes::executing, helics_federate_state::helics_state_execution}, {helics::Federate::modes::finalize, helics_federate_state::helics_state_finalize}, {helics::Federate::modes::pending_exec, helics_federate_state::helics_state_pending_exec}, {helics::Federate::modes::pending_init, helics_federate_state::helics_state_pending_init}, {helics::Federate::modes::pending_iterative_time, helics_federate_state::helics_state_pending_iterative_time}, {helics::Federate::modes::pending_time, helics_federate_state::helics_state_pending_time}, {helics::Federate::modes::initializing, helics_federate_state::helics_state_initialization}, {helics::Federate::modes::pending_finalize, helics_federate_state::helics_state_pending_finalize}}; helics_federate_state helicsFederateGetState (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_state_error; } try { auto FedMode = fedObj->getCurrentMode (); return modeEnumConversions.at (FedMode); } catch (...) { helicsErrorHandler (err); return helics_state_error; } } const char *helicsFederateGetName (helics_federate fed) { auto fedObj = getFed (fed, nullptr); if (fedObj == nullptr) { return nullcstr; } auto &ident = fedObj->getName (); return ident.c_str (); } void helicsFederateSetTimeProperty (helics_federate fed, int timeProperty, helics_time time, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->setProperty (timeProperty, time); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateSetFlagOption (helics_federate fed, int flag, helics_bool flagValue, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->setFlagOption (flag, (flagValue != helics_false)); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateSetIntegerProperty (helics_federate fed, int intProperty, int propVal, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->setProperty (intProperty, propVal); } catch (...) { return helicsErrorHandler (err); } } helics_time helicsFederateGetTimeProperty (helics_federate fed, int timeProperty, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto T = fedObj->getTimeProperty (timeProperty); return (T < helics::Time::maxVal ()) ? static_cast<double> (T) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } helics_bool helicsFederateGetFlagOption (helics_federate fed, int flag, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_false; } try { bool res = fedObj->getFlagOption (flag); return (res) ? helics_true : helics_false; } catch (...) { helicsErrorHandler (err); return helics_false; } } int helicsFederateGetIntegerProperty (helics_federate fed, int intProperty, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return -101; } try { return fedObj->getIntegerProperty (intProperty); } catch (...) { helicsErrorHandler (err); return -101; } } void helicsFederateSetSeparator (helics_federate fed, char separator, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->setSeparator (separator); } catch (...) { helicsErrorHandler (err); } } helics_time helicsFederateGetCurrentTime (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto T = fedObj->getCurrentTime (); return (T < helics::Time::maxVal ()) ? static_cast<double> (T) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } static constexpr char invalidGlobalString[] = "Global name cannot be null"; void helicsFederateSetGlobal (helics_federate fed, const char *valueName, const char *value, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } if (valueName == nullptr) { if (err != nullptr) { err->error_code = helics_error_invalid_argument; err->message = invalidGlobalString; } return; } fedObj->setGlobal (valueName, AS_STRING (value)); } static constexpr char invalidFederateCore[] = "Federate core is not connected"; void helicsFederateSetLogFile (helics_federate fed, const char *logFile, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } auto cr = fedObj->getCorePointer (); try { if (cr) { cr->setLogFile (AS_STRING (logFile)); } else { if (err != nullptr) { err->error_code = helics_error_invalid_function_call; err->message = invalidFederateCore; } return; } } catch (...) { helicsErrorHandler (err); } } void helicsFederateLogErrorMessage (helics_federate fed, const char *logmessage, helics_error *err) { helicsFederateLogLevelMessage (fed, helics_log_level_error, logmessage, err); } void helicsFederateLogWarningMessage (helics_federate fed, const char *logmessage, helics_error *err) { helicsFederateLogLevelMessage (fed, helics_log_level_warning, logmessage, err); } void helicsFederateLogInfoMessage (helics_federate fed, const char *logmessage, helics_error *err) { helicsFederateLogLevelMessage (fed, helics_log_level_summary, logmessage, err); } void helicsFederateLogDebugMessage (helics_federate fed, const char *logmessage, helics_error *err) { helicsFederateLogLevelMessage (fed, helics_log_level_data, logmessage, err); } void helicsFederateLogLevelMessage (helics_federate fed, int loglevel, const char *logmessage, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } fedObj->logMessage (loglevel, AS_STRING (logmessage)); }
26.447467
140
0.630582
manoj1511
05bf64bc3cf0fa74f6f3c3996361f4c977618203
8,489
cpp
C++
examples/example_matrix_multiply.cpp
rise-lang/yacx
da81fe8f814151b1c2024617f0bc9891f210cd84
[ "MIT" ]
5
2019-12-16T15:32:05.000Z
2021-05-21T18:36:37.000Z
examples/example_matrix_multiply.cpp
rise-lang/yacx
da81fe8f814151b1c2024617f0bc9891f210cd84
[ "MIT" ]
98
2019-12-07T15:28:18.000Z
2021-03-02T14:20:48.000Z
examples/example_matrix_multiply.cpp
rise-lang/yacx
da81fe8f814151b1c2024617f0bc9891f210cd84
[ "MIT" ]
6
2019-12-08T13:20:57.000Z
2021-05-16T11:21:14.000Z
#include "yacx/main.hpp" #include <algorithm> #include <array> #include <cstdio> #include <ctime> #include <functional> #include <iostream> #include <iterator> #include <random> #include <string> using yacx::Source, yacx::KernelArg, yacx::Kernel, yacx::Options, yacx::Device, yacx::load, yacx::KernelTime, yacx::Devices; void compare(float *lhs, float *rhs, int width) { int errors = 0; for (int i{0}; i < width; i += 1) { //printf("[%d] expected %f : actually %f\n", i, lhs[i], rhs[i]); if ((lhs[i] - rhs[i]) != 0) { errors += 1; } } if (errors > 0) printf("\u001b[31m%d errors occured, out of %d values.\u001b[0m\n", errors, width); else printf("\u001b[32mno errors occured.\u001b[0m\n"); } std::function<bool(const float &, const float &)> comparator = [](const float &left, const float &right) { // double epsilon{1.0E-8}; double epsilon{1}; return (abs(left - right) < epsilon); }; template <class Iter> void fill(Iter start, Iter end, int min = 0, int max = 100) { static std::random_device rd; static std::mt19937 mte(rd()); std::uniform_int_distribution<int> dist(min, max); std::generate(start, end, [&]() { return dist(mte); }); } void MatrixMulSeq(const float *M, const float *N, float *P, size_t width) { size_t Col, Row, k; for (Col = 0; Col < width; ++Col) for (Row = 0; Row < width; ++Row) { float sum = 0; for (k = 0; k < width; k += 1) { sum += M[Row * width + k] * N[k * width + Col]; } P[Row * width + Col] = sum; } } int main() { std::clock_t start; bool equalMultiply1, equalMultiply1unfolded, equalMultiply2, equalMultiplyNaive; const size_t WIDTH{1024}; const size_t BLOCK_SIZE{16}; const size_t GRANULARITY{4}; const size_t matrix_size{WIDTH * WIDTH * sizeof(float)}; static_assert(WIDTH % BLOCK_SIZE == 0); static_assert(BLOCK_SIZE % GRANULARITY == 0); // problem with WIDTH > 500 // std::array<float, WIDTH * WIDTH> M, N, P_cuda, P_seq; float *M = new float[WIDTH * WIDTH]; float *N = new float[WIDTH * WIDTH]; float *P_seq = new float[WIDTH * WIDTH]; float *P_cuda = new float[WIDTH * WIDTH]; KernelTime time; // Fill arrays with random values // fill(N.begin(), N.end()); // fill(M.begin(), M.end()); fill(M, M + (WIDTH * WIDTH)); fill(N, N + (WIDTH * WIDTH)); try { // Select Device Device dev = Devices::findDevice(); std::cout << "===================================\n"; std::cout << "Selected " << dev.name() << " with " << (dev.total_memory() / 1024) / 1024 << "mb VRAM\n"; std::cout << "Kernel Arguments total size: " << ((matrix_size * 3 + sizeof(size_t)) / 1024) << "kb\n\n"; std::cout << "Theoretical Bandwith: " << yacx::theoretical_bandwidth(dev) << " GB/s\n"; // Set kernel string and compile options Source source{load("examples/kernels/matrixMult.cu")}; Options options; options.insert("--std", "c++14"); options.insert("--device-debug"); options.insertOptions(yacx::options::GpuArchitecture{dev}); // Set arguments std::vector<KernelArg> args; // args.emplace_back(KernelArg{M.data(), matrix_size}); // args.emplace_back(KernelArg{N.data(), matrix_size}); // args.emplace_back(KernelArg{P_cuda.data(), matrix_size, true, false}); args.emplace_back(KernelArg{M, matrix_size}); args.emplace_back(KernelArg{N, matrix_size}); args.emplace_back(KernelArg{P_cuda, matrix_size, true, false}); args.emplace_back(KernelArg{const_cast<size_t *>(&WIDTH)}); // Compile Kernels dim3 grid(WIDTH, WIDTH); dim3 block(1, 1); Kernel kernelNaive = source.program("MatrixMultyNaive") .compile(options) .configure(grid, block); block.x = BLOCK_SIZE; block.y = BLOCK_SIZE / GRANULARITY; grid.x = WIDTH / block.x; grid.y = WIDTH / GRANULARITY / block.y; // std::cout << "get_global_size(0): " << block.x * grid.x << std::endl; // std::cout << "get_global_size(1): " << block.y * grid.y << std::endl; // std::cout << "get_local_size(0): " << block.x << std::endl; // std::cout << "get_local_size(1): " << block.y << std::endl; Kernel kernel1 = source.program("MatrixMulty1") .instantiate(BLOCK_SIZE, GRANULARITY) .compile(options) .configure(grid, block); block.x = BLOCK_SIZE; block.y = BLOCK_SIZE / 4; grid.x = WIDTH / block.x; grid.y = WIDTH / 4 / block.y; Kernel kernel1_1 = source.program("MatrixMulty1unfolded") .instantiate(BLOCK_SIZE) .compile(options) .configure(grid, block); block.x = BLOCK_SIZE; block.y = BLOCK_SIZE; grid.x = WIDTH / BLOCK_SIZE; grid.y = WIDTH / BLOCK_SIZE; Kernel kernel2 = source.program("MatrixMulty2") .instantiate(BLOCK_SIZE) .compile(options) .configure(grid, block); // Launch kernels // CPU single threaded matrix multiplication start = std::clock(); // MatrixMulSeq(M.data(), N.data(), P_seq.data(), WIDTH); MatrixMulSeq(M, N, P_seq, WIDTH); std::cout << "Time" << yacx::gColorBrightYellow << "[CPU single threaded]" << yacx::gColorReset << ": " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl; time = kernelNaive.launch(args, dev); std::cout << "Time" << yacx::gColorBrightYellow << "[MatrixMultyNaive]" << yacx::gColorReset << ": " << time.total << " ms\n"; std::cout << "Effective Bandwith: " << time.effective_bandwidth_launch() << " GB/s\n"; equalMultiplyNaive = std::equal(P_cuda, P_cuda + (WIDTH * WIDTH), P_seq, comparator); if (!equalMultiplyNaive) compare(P_seq, P_cuda, WIDTH * WIDTH); if (BLOCK_SIZE % 4 == 0) { time = kernel1_1.launch(args, dev); std::cout << "Time" << yacx::gColorBrightYellow << "[MatrixMulty1unfolded]" << yacx::gColorReset << ": " << time.total << " ms\n"; std::cout << "Effective Bandwith: " << time.effective_bandwidth_launch() << " GB/s\n"; equalMultiply1unfolded = std::equal(P_cuda, P_cuda + (WIDTH * WIDTH), P_seq, comparator); if (!equalMultiply1unfolded) compare(P_seq, P_cuda, WIDTH * WIDTH); } else { equalMultiply1unfolded = true; } time = kernel1.launch(args, dev); std::cout << "Time" << yacx::gColorBrightYellow << "[MatrixMulty1]" << yacx::gColorReset << ": " << time.total << " ms\n"; std::cout << "Effective Bandwith: " << time.effective_bandwidth_launch() << " GB/s\n"; equalMultiply1 = std::equal(P_cuda, P_cuda + (WIDTH * WIDTH), P_seq, comparator); if (!equalMultiply1) compare(P_seq, P_cuda, WIDTH * WIDTH); time = kernel2.launch(args, dev); std::cout << "Time" << yacx::gColorBrightYellow << "[MatrixMulty2]" << yacx::gColorReset << ": " << time.total << " ms\n"; std::cout << "Effective Bandwith: " << time.effective_bandwidth_launch() << " GB/s\n\n"; equalMultiply2 = std::equal(P_cuda, P_cuda + (WIDTH * WIDTH), P_seq, comparator); if (!equalMultiply2) compare(P_seq, P_cuda, WIDTH * WIDTH); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; exit(1); } if (equalMultiplyNaive && equalMultiply1 && equalMultiply1unfolded && equalMultiply2) { std::cout << yacx::gColorBrightGreen << "Everything was correctly calculated!" << yacx::gColorReset; } else { std::cout << yacx::gColorBrightRed; } if (!equalMultiplyNaive) { std::cout << "Naive went wrong ;_;\n"; } if (!equalMultiply1) { std::cout << "Multy1 went wrong ;_;\n"; } if (!equalMultiply1unfolded) { std::cout << "Multy1unfolded went wrong ;_;\n"; } if (!equalMultiply2) { std::cout << "Multy2 went wrong ;_;\n"; } std::cout << yacx::gColorReset << "===================================" << std::endl; // Free resources delete[] M; delete[] N; delete[] P_seq; delete[] P_cuda; return 0; }
33.55336
79
0.568972
rise-lang
05c047501cbc80390d8e93d1cd7bd27cd77666f8
11,268
cpp
C++
ofApp.cpp
2552Software/music2
fcefe78029104214e8174cd5cf16bc690ce5bda4
[ "MIT" ]
null
null
null
ofApp.cpp
2552Software/music2
fcefe78029104214e8174cd5cf16bc690ce5bda4
[ "MIT" ]
null
null
null
ofApp.cpp
2552Software/music2
fcefe78029104214e8174cd5cf16bc690ce5bda4
[ "MIT" ]
null
null
null
#include "ofApp.h" //https://commons.wikimedia.org/wiki/File:Beer_in_glass_close_up.jpg // This is the most basic pdsp example // we set up everything and check that everything is working // before running this also check that the basic oF audio output example is working // ofxx_folder/examples/sound/audioOutputExample/ // for documentation of the modules and functions: // http://npisanti.com/ofxPDSP/md__modules.html /* roate ofPushMatrix(); ofTranslate(leafImg.width/2, leafImg.height/2, 0);//move pivot to centre ofRotate(ofGetFrameNum() * .01, 0, 0, 1);//rotate from centre ofPushMatrix(); ofTranslate(-leafImg.width/2,-leafImg.height/2,0);//move back by the centre offset leafImg.draw(0,0); ofPopMatrix(); ofPopMatrix(); https://www.vidsplay.com/ */ int AudioPlayer::number = 0; void AudioPlayer::patch() { addModuleOutput("0", fader0); addModuleOutput("1", fader1); pitchControl >> sampler0.in_pitch(); pitchControl >> sampler1.in_pitch(); sampleTrig >> sampler0 >> amp0; envGate >> env >> amp0.in_mod(); sampleTrig >> sampler1 >> amp1; env >> amp1.in_mod(); sampler0 >> amp0 >> fader0; sampler1 >> amp1 >> fader1; faderControl >> dBtoLin >> fader0.in_mod(); dBtoLin >> fader1.in_mod(); sampler0.addSample(&sample, 0); sampler1.addSample(&sample, 1); smoothControl >> env.in_attack(); smoothControl >> env.in_release(); ui.setName("pdsp player " + ofToString(++number)); ui.add(faderControl.set("volume", 0, -48, 24)); ui.add(loadButton.set("load", false)); ui.add(sampleName.set("sample", "no sample")); ui.add(samplePath.set("path", "no path")); ui.add(pitchControl.set("pitch", 0, -24, 24)); ui.add(smoothControl.set("fade ms", 0, 0, 50)); ui.add(bPlay.set("play", false)); ui.add(bPause.set("pause", false)); ui.add(bStop.set("stop", true)); loadButton.addListener(this, &AudioPlayer::loadButtonCall); samplePath.addListener(this, &AudioPlayer::sampleChangedCall); bPlay.addListener(this, &AudioPlayer::onPlay); bPause.addListener(this, &AudioPlayer::onPause); bStop.addListener(this, &AudioPlayer::onStop); bSemaphore = true; sample.setVerbose(true); } void AudioPlayer::onPlay(bool & value) { if (bSemaphore) { bSemaphore = false; if (bStop) { bPlay = true; bStop = false; envGate.trigger(1.0f); sampleTrig.trigger(1.0f); ofLogVerbose() << "[pdsp] player: playing\n"; } else if (bPause) { ofLogVerbose() << "[pdsp] player: unpaused\n"; bPlay = true; bPause = false; envGate.trigger(1.0f); } else { bPlay = true; sampleTrig.trigger(1.0f); } bSemaphore = true; } } void AudioPlayer::onPause(bool & value) { if (bSemaphore) { bSemaphore = false; if (bPlay) { bPause = true; bPlay = false; ofLogVerbose() << "[pdsp] player: paused\n"; envGate.off(); } else if (bStop) { bPause = false; ofLogVerbose() << "[pdsp] player: impossible to pause on stop"; } else { ofLogVerbose() << "[pdsp] player: unpaused\n"; bPlay = true; bPause = false; envGate.trigger(1.0f); } bSemaphore = true; } } void AudioPlayer::onStop(bool & value) { if (bSemaphore) { bSemaphore = false; if (bPlay || bPause) { bStop = true; bPlay = false; bPause = false; ofLogVerbose() << "[pdsp] player: stopped\n"; envGate.off(); } bSemaphore = true; } } void AudioPlayer::loadButtonCall(bool & value) { if (value) { float fvalue = faderControl.get(); faderControl.setv(0.0f); //Open the Open File Dialog ofFileDialogResult openFileResult = ofSystemLoadDialog("select an audio sample"); //Check if the user opened a file if (openFileResult.bSuccess) { string path = openFileResult.getPath(); samplePath = path; ofLogVerbose("file loaded"); } else { ofLogVerbose("User hit cancel"); } // switch to mono if the sample has just one channel if (sample.channels == 1) { sampler1.setSample(&sample, 0, 0); } else { sampler1.setSample(&sample, 0, 1); } loadButton = false; faderControl.setv(fvalue); bool dummy = true; onStop(dummy); } } void AudioPlayer::sampleChangedCall(string & value) { ofLogVerbose("loading" + value); loadSample(samplePath); auto v = ofSplitString(samplePath, "/"); sampleName = v[v.size() - 1]; } void AudioPlayer::loadSample(string path) { sample.load(path); } void AudioPlayer::load(string path) { samplePath = path; } void AudioPlayer::play() { bPlay = bPlay ? false : true; } void AudioPlayer::pause() { bPause = bPause ? false : true; } void AudioPlayer::stop() { bStop = bStop ? false : true; } //-------------------------------------------------------------- void ofApp::setup() { player.load(ofToDataPath("song3.wav")); player.play(); //-------------------GRAPHIC SETUP-------------- ofBackground(0); ofSetFrameRate(30); videos.add("Beer_Pour_Videvo.mp4", ofColor(255, 255, 255), 32.0f, 52.0f); videos.add("lighthouse.mp4", ofColor(255, 255, 255)); videos.setNext(); background1.load("beer1.jpg"); beer.load("beer2.jpg"); popcorn.load("popcorn.jpg"); burger.load("burger.jpg"); ignore = 0; //--------PATCHING------- // a pdsp::ADSR is an ADSR envelope that makes a one-shot modulation when triggered // pdsp::ADSR require an output sending trigger signals // remember, in pdsp out_trig() always have to be connected to in_trig() // in_trig() is the default pdsp::ADSR input signal // a pdsp::Amp multiply in_signal() and in_mod() player.out("0") >> engine.audio_out(0); player.out("1") >> engine.audio_out(1); gate_ctrl.out_trig() >> adsrEnvelop; adsrEnvelop >> amp.in_mod(); pitch_ctrl >> oscillator.in_pitch(); //oscillator >> amp * dB(-12.0f) >> engine.audio_out(0); //amp * dB(-12.0f) >> engine.audio_out(1); // we patch the pdsp::Parameter to control pitch and amp // and then patch the oscillator to the engine outs osc1_pitch_ctrl >> fm1.in_pitch(); osc2_pitch_ctrl >> fm2.in_pitch(); osc3_pitch_ctrl >> fm3.in_pitch(); // pdsp::ParameterGain can be added to gui like an ofParameter // and has an input and output for signals // it is used to control volume as it has control in deciBel // pdsp::ParameterAmp instead just multiply the input for the parameter value // it is usefule for scaling modulation signals fm1 >> osc1_amp >> engine.audio_out(0); osc1_amp >> engine.audio_out(1); //fm2 >> osc2_gain >> engine.audio_out(0); // osc2_gain >> engine.audio_out(1); //fm3 >> osc3_gain >> engine.audio_out(0); // osc3_gain >> engine.audio_out(1); osc1_pitch_ctrl.set("pitch", 60.0f, 24.0f, 96.0f); osc1_amp.set("amp", 0.25f, 0.0f, 1.0f); osc2_pitch_ctrl.set("pitch", 60, 24, 96); osc2_gain.set("active", false, -48.0f, -12.0f); osc3_pitch_ctrl.set("pitch coarse", 60, 24, 96); osc3_pitch_ctrl.set("pitch fine ", 0.0f, -0.5f, 0.5f); osc3_gain.set("gain", -24.f, -48.0f, 0.0f); osc2_pitch_ctrl.setv(ofRandom(48.0f, 96.0f)); 1.0f >> adsrEnvelop.in_attack(); 50.0f >> adsrEnvelop.in_decay(); 0.5f >> adsrEnvelop.in_sustain(); 500.0f >> adsrEnvelop.in_release(); gate_ctrl.trigger(1.0f); pitch_ctrl.setv(36.0f); // we control the value of an pdsp::Parameter directly with the setv function // you can smooth out an pdsp::Parameter changes, decomment this for less "grainy" pitch changes pitch_ctrl.enableSmoothing(50.0f); // 50ms smoothing //----------------------AUDIO SETUP------------- // set up the audio output device engine.listDevices(); engine.setDeviceID(0); // REMEMBER TO SET THIS AT THE RIGHT INDEX!!!! // start your audio engine ! engine.setup(44100, 512, 3); // arguments are : sample rate, buffer size, and how many buffer there are in the audio callback queue // 512 is the minimum buffer size for the raspberry Pi to work // 3 buffers queue is the minimum for the rPi to work // if you are using JACK you have to set this number to the bufferSize you set in JACK // on Windows you have to set the sample rate to the system sample rate, usually 44100hz // on iOS sometimes the systems forces the sample rate to 48khz, so if you have problems set 48000 } //-------------------------------------------------------------- void ofApp::update() { videos.update(); pitch_ctrl.setv(videos.getPitch()); osc1_pitch_ctrl.setv(videos.getPitch()); } //-------------------------------------------------------------- void ofApp::draw() { ofPushMatrix(); if (!ignore) { background1.draw(0, 0, ofGetScreenWidth(), ofGetScreenHeight()); } ofEnableAlphaBlending(); ofSetColor(videos.getColor().r, videos.getColor().g, videos.getColor().b, videos.getAlpha()); videos.draw(0, 0, ofGetScreenWidth(), ofGetScreenHeight()); ofDisableAlphaBlending(); ofPopMatrix(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { } //-------------------------------------------------------------- void ofApp::keyReleased(int key) { } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button) { float pitch = ofMap(x, 0, ofGetWidth(), 36.0f, 72.0f); pitch_ctrl.setv(pitch); } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button) { float pitch = ofMap(x, 0, ofGetWidth(), 36.0f, 72.0f); pitch_ctrl.setv(pitch); // y value controls the trigger intensity float trig = ofMap(y, 0, ofGetHeight(), 1.0f, 0.000001f); gate_ctrl.trigger(trig); // we send a trigger to the envelope } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button) { gate_ctrl.off(); // we send an "off" trigger to the envelope } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y) { } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo) { }
30.619565
124
0.564164
2552Software
05c55538623289359a668a35521b9bfeb8f01a82
4,118
cpp
C++
Sources/Engine/NeoAxis.Core.Native/NativeWrapper/MiniDump.cpp
intensifier/NeoAxisEngine
5c3d6d853c1d420e332aa31c73840f7cf3fd3eef
[ "IJG" ]
null
null
null
Sources/Engine/NeoAxis.Core.Native/NativeWrapper/MiniDump.cpp
intensifier/NeoAxisEngine
5c3d6d853c1d420e332aa31c73840f7cf3fd3eef
[ "IJG" ]
null
null
null
Sources/Engine/NeoAxis.Core.Native/NativeWrapper/MiniDump.cpp
intensifier/NeoAxisEngine
5c3d6d853c1d420e332aa31c73840f7cf3fd3eef
[ "IJG" ]
null
null
null
// Copyright (C) NeoAxis Group Ltd. 8 Copthall, Roseau Valley, 00152 Commonwealth of Dominica. #include "OgreStableHeaders.h" #include "OgreNativeWrapperGeneral.h" #pragma hdrstop #include "MiniDump.h" #ifdef MINIDUMP #include "MiniDump.h" #include <windows.h> #include <dbghelp.h> #include <tchar.h> typedef BOOL (WINAPI *MINIDUMPWRITEDUMP)( HANDLE hProcess, DWORD dwPid, HANDLE hFile, MINIDUMP_TYPE DumpType, CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam); BOOL MiniDump::Create(HMODULE hModule, PEXCEPTION_POINTERS pExceptionInfo) { BOOL bRet = FALSE; DWORD dwLastError = 0; HANDLE hImpersonationToken = NULL; if(!GetImpersonationToken(&hImpersonationToken)) return FALSE; HMODULE hDbgDll = LocalLoadLibrary(hModule, _T("dbghelp.dll")); if(!hDbgDll) return FALSE; MINIDUMPWRITEDUMP pDumpFunction = (MINIDUMPWRITEDUMP)::GetProcAddress(hDbgDll, "MiniDumpWriteDump"); if(!pDumpFunction) { FreeLibrary(hDbgDll); return FALSE; } // ::CreateDirectory("Errors",NULL); //const char* dumpfilename = "UserSettings//NativeError.dmp"; const char* dumpfilename = "C://NativeError.dmp"; HANDLE hDumpFile = ::CreateFile(dumpfilename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0); if(hDumpFile == INVALID_HANDLE_VALUE) { MessageBox(0, "Cannot create dump file.", "Error", MB_OK); return FALSE; } MINIDUMP_EXCEPTION_INFORMATION stInfo = {0}; stInfo.ThreadId = GetCurrentThreadId(); stInfo.ExceptionPointers = pExceptionInfo; stInfo.ClientPointers = TRUE; // We need the SeDebugPrivilege to be able to run MiniDumpWriteDump TOKEN_PRIVILEGES tp; BOOL bPrivilegeEnabled = EnablePriv(SE_DEBUG_NAME, hImpersonationToken, &tp); // DBGHELP.DLL is not thread safe //EnterCriticalSection(pCS); bRet = pDumpFunction(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpWithDataSegs, &stInfo, NULL, NULL); //LeaveCriticalSection(pCS); if(bPrivilegeEnabled) RestorePriv(hImpersonationToken, &tp); CloseHandle(hDumpFile); FreeLibrary(hDbgDll); return bRet; } BOOL MiniDump::GetImpersonationToken(HANDLE* phToken) { *phToken = NULL; if(!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, TRUE, phToken)) { if(GetLastError() == ERROR_NO_TOKEN) { // No impersonation token for the curren thread available - go for the process token if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, phToken)) return FALSE; } else return FALSE; } return TRUE; } BOOL MiniDump::EnablePriv(LPCTSTR pszPriv, HANDLE hToken, TOKEN_PRIVILEGES* ptpOld) { BOOL bOk = FALSE; TOKEN_PRIVILEGES tp; tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; bOk = LookupPrivilegeValue( 0, pszPriv, &tp.Privileges[0].Luid); if(bOk) { DWORD cbOld = sizeof(*ptpOld); bOk = AdjustTokenPrivileges(hToken, FALSE, &tp, cbOld, ptpOld, &cbOld); } return (bOk && (ERROR_NOT_ALL_ASSIGNED != GetLastError())); } BOOL MiniDump::RestorePriv(HANDLE hToken, TOKEN_PRIVILEGES* ptpOld) { BOOL bOk = AdjustTokenPrivileges(hToken, FALSE, ptpOld, 0, 0, 0); return (bOk && (ERROR_NOT_ALL_ASSIGNED != GetLastError())); } HMODULE MiniDump::LocalLoadLibrary(HMODULE hModule, LPCTSTR pszModule) { HMODULE hDll = NULL; // Attempt to load local module first TCHAR pszModulePath[MAX_PATH]; if(GetModuleFileName(hModule, pszModulePath, sizeof(pszModulePath) / sizeof(pszModulePath[0]))) { TCHAR* pSlash = _tcsrchr(pszModulePath, _T('\\')); if(0 != pSlash) { _tcscpy(pSlash + 1, pszModule); hDll = ::LoadLibrary(pszModulePath); } } if(!hDll) { // If not found, load any available copy hDll = ::LoadLibrary(pszModule); } return hDll; } unsigned long ExceptionHandler(LPEXCEPTION_POINTERS pExceptionPointers) { if(MiniDump::Create(NULL, pExceptionPointers)) { } else { } return EXCEPTION_EXECUTE_HANDLER; } #endif
24.957576
101
0.733123
intensifier
05c5a3aeba06470baf5f2934446b9061e2844011
30,479
cpp
C++
isis/src/base/apps/nocam2map/nocam2map.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
1
2022-02-17T01:07:03.000Z
2022-02-17T01:07:03.000Z
isis/src/base/apps/nocam2map/nocam2map.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
null
null
null
isis/src/base/apps/nocam2map/nocam2map.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
null
null
null
#include <algorithm> #include <QList> #include <QString> #include <QStringList> #include <QVector> #include <SpiceUsr.h> #include "Cube.h" #include "Brick.h" #include "Constants.h" #include "Cube.h" #include "IString.h" #include "LeastSquares.h" #include "NaifStatus.h" #include "nocam2map.h" #include "PolynomialBivariate.h" #include "ProcessRubberSheet.h" #include "ProjectionFactory.h" #include "Statistics.h" #include "Target.h" #include "TextFile.h" #include "TProjection.h" using namespace std; using namespace Isis; namespace Isis { static void DeleteTables(Pvl *label, PvlGroup kernels); void nocam2map(UserInterface &ui, Pvl *log) { QString inputFileName = ui.GetCubeName("FROM"); Cube iCube(inputFileName); nocam2map(&iCube, ui, log); } void nocam2map(Cube *inCube, UserInterface &ui, Pvl *log) { //Create a process to create the input cubes Process p; //Create the input cubes, matching sample/lines Cube *latCube = p.SetInputCube(ui.GetCubeName("LATCUB"), ui.GetInputAttribute("LATCUB"), SpatialMatch); Cube *lonCube = p.SetInputCube(ui.GetCubeName("LONCUB"), ui.GetInputAttribute("LONCUB"), SpatialMatch); //A 1x1 brick to read in the latitude and longitude DN values from //the specified cubes Brick latBrick(1, 1, 1, latCube->pixelType()); Brick lonBrick(1, 1, 1, lonCube->pixelType()); //Set the sample and line increments float sinc = (inCube->sampleCount() * 0.10); if (ui.WasEntered("SINC")) { sinc = ui.GetInteger("SINC"); } float linc = (inCube->lineCount() * 0.10); if (ui.WasEntered("LINC")) { linc = ui.GetInteger("LINC"); } //Set the degree of the polynomial to use in our functions int degree = ui.GetInteger("DEGREE"); //We are using a polynomial with two variables PolynomialBivariate sampFunct(degree); PolynomialBivariate lineFunct(degree); //We will be solving the function using the least squares method LeastSquares sampSol(sampFunct); LeastSquares lineSol(lineFunct); //Setup the variables for solving the stereographic projection //x = cos(latitude) * sin(longitude - lon_center) //y = cos(lat_center) * sin(latitude) - sin(lat_center) * cos(latitude) * cos(longitude - lon_center) //Get the center lat and long from the input cubes double lat_center = latCube->statistics()->Average() * PI / 180.0; double lon_center = lonCube->statistics()->Average() * PI / 180.0; /** * Loop through lines and samples projecting the latitude and longitude at those * points to stereographic x and y and adding these points to the LeastSquares * matrix. */ for (float i = 1; i <= inCube->lineCount(); i += linc) { for (float j = 1; j <= inCube->sampleCount(); j += sinc) { latBrick.SetBasePosition(j, i, 1); latCube->read(latBrick); if (IsSpecial(latBrick.at(0))) continue; double lat = latBrick.at(0) * PI / 180.0; lonBrick.SetBasePosition(j, i, 1); lonCube->read(lonBrick); if (IsSpecial(lonBrick.at(0))) continue; double lon = lonBrick.at(0) * PI / 180.0; //Project lat and lon to x and y using a stereographic projection double k = 2 / (1 + sin(lat_center) * sin(lat) + cos(lat_center) * cos(lat) * cos(lon - lon_center)); double x = k * cos(lat) * sin(lon - lon_center); double y = k * (cos(lat_center) * sin(lat)) - (sin(lat_center) * cos(lat) * cos(lon - lon_center)); //Add x and y to the least squares matrix vector<double> data; data.push_back(x); data.push_back(y); sampSol.AddKnown(data, j); lineSol.AddKnown(data, i); //If the sample increment goes past the last sample in the line, we want to //always read the last sample.. if (j != inCube->sampleCount() && j + sinc > inCube->sampleCount()) { j = inCube->sampleCount() - sinc; } } //If the line increment goes past the last line in the cube, we want to //always read the last line.. if (i != inCube->lineCount() && i + linc > inCube->lineCount()) { i = inCube->lineCount() - linc; } } //Solve the least squares functions using QR Decomposition try { sampSol.Solve(LeastSquares::QRD); lineSol.Solve(LeastSquares::QRD); } catch (IException &e) { FileName inFile = inCube->fileName(); QString msg = "Unable to calculate transformation of projection for [" + inFile.expanded() + "]."; throw IException(e, IException::Unknown, msg, _FILEINFO_); } //If the user wants to save the residuals to a file, create a file and write //the column titles to it. TextFile oFile; if (ui.WasEntered("RESIDUALS")) { oFile.Open(ui.GetFileName("RESIDUALS"), "overwrite"); oFile.PutLine("Sample,\tLine,\tX,\tY,\tSample Error,\tLine Error\n"); } //Gather the statistics for the residuals from the least squares solutions Statistics sampErr; Statistics lineErr; vector<double> sampResiduals = sampSol.Residuals(); vector<double> lineResiduals = lineSol.Residuals(); for (int i = 0; i < (int)sampResiduals.size(); i++) { sampErr.AddData(sampResiduals[i]); lineErr.AddData(lineResiduals[i]); } //If a residuals file was specified, write the previous data, and the errors to the file. if (ui.WasEntered("RESIDUALS")) { for (int i = 0; i < sampSol.Rows(); i++) { vector<double> data = sampSol.GetInput(i); QString tmp = ""; tmp += toString(sampSol.GetExpected(i)); tmp += ",\t"; tmp += toString(lineSol.GetExpected(i)); tmp += ",\t"; tmp += toString(data[0]); tmp += ",\t"; tmp += toString(data[1]); tmp += ",\t"; tmp += toString(sampResiduals[i]); tmp += ",\t"; tmp += toString(lineResiduals[i]); oFile.PutLine(tmp + "\n"); } } oFile.Close(); //Records the error to the log PvlGroup error("Error"); error += PvlKeyword("Degree", toString(degree)); error += PvlKeyword("NumberOfPoints", toString((int)sampResiduals.size())); error += PvlKeyword("SampleMinimumError", toString(sampErr.Minimum())); error += PvlKeyword("SampleAverageError", toString(sampErr.Average())); error += PvlKeyword("SampleMaximumError", toString(sampErr.Maximum())); error += PvlKeyword("SampleStdDeviationError", toString(sampErr.StandardDeviation())); error += PvlKeyword("LineMinimumError", toString(lineErr.Minimum())); error += PvlKeyword("LineAverageError", toString(lineErr.Average())); error += PvlKeyword("LineMaximumError", toString(lineErr.Maximum())); error += PvlKeyword("LineStdDeviationError", toString(lineErr.StandardDeviation())); if (log) { log->addGroup(error); } //Close the input cubes for cleanup p.EndProcess(); //If we want to warp the image, then continue, otherwise return if (!ui.GetBoolean("NOWARP")) { //Creates the mapping group Pvl mapFile; mapFile.read(ui.GetFileName("MAP")); PvlGroup &mapGrp = mapFile.findGroup("Mapping", Pvl::Traverse); //Reopen the lat and long cubes latCube = new Cube(); latCube->setVirtualBands(ui.GetInputAttribute("LATCUB").bands()); latCube->open(ui.GetCubeName("LATCUB")); lonCube = new Cube(); lonCube->setVirtualBands(ui.GetInputAttribute("LONCUB").bands()); lonCube->open(ui.GetCubeName("LONCUB")); PvlKeyword targetName; //If the user entered the target name if (ui.WasEntered("TARGET")) { targetName = PvlKeyword("TargetName", ui.GetString("TARGET")); } //Else read the target name from the input cube else { Pvl fromFile; fromFile.read(inCube->fileName()); targetName = fromFile.findKeyword("TargetName", Pvl::Traverse); } mapGrp.addKeyword(targetName, Pvl::Replace); PvlKeyword equRadius; PvlKeyword polRadius; //If the user entered the equatorial and polar radii if (ui.WasEntered("EQURADIUS") && ui.WasEntered("POLRADIUS")) { equRadius = PvlKeyword("EquatorialRadius", toString(ui.GetDouble("EQURADIUS"))); polRadius = PvlKeyword("PolarRadius", toString(ui.GetDouble("POLRADIUS"))); } //Else read them from the pck else { PvlGroup radii = Target::radiiGroup(targetName[0]); equRadius = radii["EquatorialRadius"]; polRadius = radii["PolarRadius"]; } mapGrp.addKeyword(equRadius, Pvl::Replace); mapGrp.addKeyword(polRadius, Pvl::Replace); //If the latitude type is not in the mapping group, copy it from the input if (!mapGrp.hasKeyword("LatitudeType")) { if (ui.GetString("LATTYPE") == "PLANETOCENTRIC") { mapGrp.addKeyword(PvlKeyword("LatitudeType", "Planetocentric"), Pvl::Replace); } else { mapGrp.addKeyword(PvlKeyword("LatitudeType", "Planetographic"), Pvl::Replace); } } //If the longitude direction is not in the mapping group, copy it from the input if (!mapGrp.hasKeyword("LongitudeDirection")) { if (ui.GetString("LONDIR") == "POSITIVEEAST") { mapGrp.addKeyword(PvlKeyword("LongitudeDirection", "PositiveEast"), Pvl::Replace); } else { mapGrp.addKeyword(PvlKeyword("LongitudeDirection", "PositiveWest"), Pvl::Replace); } } //If the longitude domain is not in the mapping group, assume it is 360 if (!mapGrp.hasKeyword("LongitudeDomain")) { mapGrp.addKeyword(PvlKeyword("LongitudeDomain", "360"), Pvl::Replace); } //If the default range is to be computed, use the input lat/long cubes to determine the range if (ui.GetString("DEFAULTRANGE") == "COMPUTE") { //NOTE - When computing the min/max longitude this application does not account for the //longitude seam if it exists. Since the min/max are calculated from the statistics of //the input longitude cube and then converted to the mapping group's domain they may be //invalid for cubes containing the longitude seam. Statistics *latStats = latCube->statistics(); Statistics *lonStats = lonCube->statistics(); double minLat = latStats->Minimum(); double maxLat = latStats->Maximum(); bool isOcentric = ((QString)mapGrp.findKeyword("LatitudeType")) == "Planetocentric"; if (isOcentric) { if (ui.GetString("LATTYPE") != "PLANETOCENTRIC") { minLat = TProjection::ToPlanetocentric(minLat, (double)equRadius, (double)polRadius); maxLat = TProjection::ToPlanetocentric(maxLat, (double)equRadius, (double)polRadius); } } else { if (ui.GetString("LATTYPE") == "PLANETOCENTRIC") { minLat = TProjection::ToPlanetographic(minLat, (double)equRadius, (double)polRadius); maxLat = TProjection::ToPlanetographic(maxLat, (double)equRadius, (double)polRadius); } } int lonDomain = (int)mapGrp.findKeyword("LongitudeDomain"); double minLon = lonDomain == 360 ? TProjection::To360Domain(lonStats->Minimum()) : TProjection::To180Domain(lonStats->Minimum()); double maxLon = lonDomain == 360 ? TProjection::To360Domain(lonStats->Maximum()) : TProjection::To180Domain(lonStats->Maximum()); bool isPosEast = ((QString)mapGrp.findKeyword("LongitudeDirection")) == "PositiveEast"; if (isPosEast) { if (ui.GetString("LONDIR") != "POSITIVEEAST") { minLon = TProjection::ToPositiveEast(minLon, lonDomain); maxLon = TProjection::ToPositiveEast(maxLon, lonDomain); } } else { if (ui.GetString("LONDIR") == "POSITIVEEAST") { minLon = TProjection::ToPositiveWest(minLon, lonDomain); maxLon = TProjection::ToPositiveWest(maxLon, lonDomain); } } if (minLon > maxLon) { double temp = minLon; minLon = maxLon; maxLon = temp; } mapGrp.addKeyword(PvlKeyword("MinimumLatitude", toString(minLat)), Pvl::Replace); mapGrp.addKeyword(PvlKeyword("MaximumLatitude", toString(maxLat)), Pvl::Replace); mapGrp.addKeyword(PvlKeyword("MinimumLongitude", toString(minLon)), Pvl::Replace); mapGrp.addKeyword(PvlKeyword("MaximumLongitude", toString(maxLon)), Pvl::Replace); } //If the user decided to enter a ground range then override if (ui.WasEntered("MINLAT")) { mapGrp.addKeyword(PvlKeyword("MinimumLatitude", toString(ui.GetDouble("MINLAT"))), Pvl::Replace); } if (ui.WasEntered("MAXLAT")) { mapGrp.addKeyword(PvlKeyword("MaximumLatitude", toString(ui.GetDouble("MAXLAT"))), Pvl::Replace); } if (ui.WasEntered("MINLON")) { mapGrp.addKeyword(PvlKeyword("MinimumLongitude", toString(ui.GetDouble("MINLON"))), Pvl::Replace); } if (ui.WasEntered("MAXLON")) { mapGrp.addKeyword(PvlKeyword("MaximumLongitude", toString(ui.GetDouble("MAXLON"))), Pvl::Replace); } //If the pixel resolution is to be computed, compute the pixels/degree from the input if (ui.GetString("PIXRES") == "COMPUTE") { latBrick.SetBasePosition(1, 1, 1); latCube->read(latBrick); lonBrick.SetBasePosition(1, 1, 1); lonCube->read(lonBrick); //Read the lat and long at the upper left corner double a = latBrick.at(0) * PI / 180.0; double c = lonBrick.at(0) * PI / 180.0; latBrick.SetBasePosition(latCube->sampleCount(), latCube->lineCount(), 1); latCube->read(latBrick); lonBrick.SetBasePosition(lonCube->sampleCount(), lonCube->lineCount(), 1); lonCube->read(lonBrick); //Read the lat and long at the lower right corner double b = latBrick.at(0) * PI / 180.0; double d = lonBrick.at(0) * PI / 180.0; //Determine the angle between the two points double angle = acos(cos(a) * cos(b) * cos(c - d) + sin(a) * sin(b)); //double angle = acos((cos(a1) * cos(b1) * cos(b2)) + (cos(a1) * sin(b1) * cos(a2) * sin(b2)) + (sin(a1) * sin(a2))); angle *= 180 / PI; //Determine the number of pixels between the two points double pixels = sqrt(pow(latCube->sampleCount() - 1.0, 2.0) + pow(latCube->lineCount() - 1.0, 2.0)); //Add the scale in pixels/degree to the mapping group mapGrp.addKeyword(PvlKeyword("Scale", toString(pixels / angle), "pixels/degree"), Pvl::Replace); if (mapGrp.hasKeyword("PixelResolution")) { mapGrp.deleteKeyword("PixelResolution"); } } // If the user decided to enter a resolution then override if (ui.GetString("PIXRES") == "MPP") { mapGrp.addKeyword(PvlKeyword("PixelResolution", toString(ui.GetDouble("RESOLUTION")), "meters/pixel"), Pvl::Replace); if (mapGrp.hasKeyword("Scale")) { mapGrp.deleteKeyword("Scale"); } } else if (ui.GetString("PIXRES") == "PPD") { mapGrp.addKeyword(PvlKeyword("Scale", toString(ui.GetDouble("RESOLUTION")), "pixels/degree"), Pvl::Replace); if (mapGrp.hasKeyword("PixelResolution")) { mapGrp.deleteKeyword("PixelResolution"); } } //Create a projection using the map file we created int samples, lines; TProjection *outmap = (TProjection *) ProjectionFactory::CreateForCube(mapFile, samples, lines, false); //Create a process rubber sheet ProcessRubberSheet r; //Set the input cube r.SetInputCube(inCube); double tolerance = ui.GetDouble("TOLERANCE") * outmap->Resolution(); //Create a new transform object Transform *transform = new NoCam2Map(sampSol, lineSol, outmap, latCube, lonCube, ui.GetString("LATTYPE") == "PLANETOCENTRIC", ui.GetString("LONDIR") == "POSITIVEEAST", tolerance, ui.GetInteger("ITERATIONS"), inCube->sampleCount(), inCube->lineCount(), samples, lines); //Allocate the output cube and add the mapping labels Cube *oCube = r.SetOutputCube(ui.GetCubeName("TO"), ui.GetOutputAttribute("TO"), transform->OutputSamples(), transform->OutputLines(), inCube->bandCount()); oCube->putGroup(mapGrp); PvlGroup kernels; Pvl *label=oCube->label(); if ( oCube->hasGroup("Kernels") ) { kernels=oCube->group("Kernels"); DeleteTables(label, kernels); oCube->deleteGroup("Kernels"); } if ( label->hasObject("NaifKeywords") ) { label->deleteObject("NaifKeywords"); } //Determine which interpolation to use Interpolator *interp = NULL; if (ui.GetString("INTERP") == "NEARESTNEIGHBOR") { interp = new Interpolator(Interpolator::NearestNeighborType); } else if (ui.GetString("INTERP") == "BILINEAR") { interp = new Interpolator(Interpolator::BiLinearType); } else if (ui.GetString("INTERP") == "CUBICCONVOLUTION") { interp = new Interpolator(Interpolator::CubicConvolutionType); } //Warp the cube r.StartProcess(*transform, *interp); r.EndProcess(); // add mapping to print.prt PvlGroup mapping = outmap->Mapping(); if (log) { log->addGroup(mapping); } //Clean up delete latCube; delete lonCube; delete outmap; delete transform; delete interp; } } // Transform object constructor NoCam2Map::NoCam2Map(LeastSquares sample, LeastSquares line, TProjection *outmap, Cube *latCube, Cube *lonCube, bool isOcentric, bool isPosEast, double tolerance, int iterations, const int inputSamples, const int inputLines, const int outputSamples, const int outputLines) { p_sampleSol = &sample; p_lineSol = &line; p_outmap = outmap; p_inputSamples = inputSamples; p_inputLines = inputLines; p_outputSamples = outputSamples; p_outputLines = outputLines; p_latCube = latCube; p_lonCube = lonCube; p_isOcentric = isOcentric; p_isPosEast = isPosEast; p_tolerance = tolerance; p_iterations = iterations; p_latCenter = p_latCube->statistics()->Average() * PI / 180.0; p_lonCenter = p_lonCube->statistics()->Average() * PI / 180.0; p_radius = p_outmap->LocalRadius(p_latCenter); } // Transform method mapping output line/samps to lat/lons to input line/samps bool NoCam2Map::Xform(double &inSample, double &inLine, const double outSample, const double outLine) { if (!p_outmap->SetWorld(outSample, outLine)) return false; if (outSample > p_outputSamples) return false; if (outLine > p_outputLines) return false; //Get the known latitude and longitudes from the projection //Convert to the input's latitude/longitude domain if necessary double lat_known, lon_known; if (p_outmap->IsPlanetocentric()) { if (!p_isOcentric) lat_known = p_outmap->ToPlanetographic(p_outmap->Latitude()); else lat_known = p_outmap->Latitude(); } else { if (p_isOcentric) lat_known = p_outmap->ToPlanetocentric(p_outmap->Latitude()); else lat_known = p_outmap->Latitude(); } if (p_outmap->IsPositiveEast()) { if (!p_isPosEast) lon_known = p_outmap->ToPositiveWest(p_outmap->Longitude(), 360); else lon_known = p_outmap->Longitude(); } else { if (p_isPosEast) lon_known = p_outmap->ToPositiveEast(p_outmap->Longitude(), 360); else lon_known = p_outmap->Longitude(); } lat_known *= PI / 180.0; lon_known *= PI / 180.0; //Project the known lat/long to x/y using the stereographic projection double k_known = 2 / (1 + sin(p_latCenter) * sin(lat_known) + cos(p_latCenter) * cos(lat_known) * cos(lon_known - p_lonCenter)); double x_known = k_known * cos(lat_known) * sin(lon_known - p_lonCenter); double y_known = k_known * (cos(p_latCenter) * sin(lat_known)) - (sin(p_latCenter) * cos(lat_known) * cos(lon_known - p_lonCenter)); vector<double> data_known; data_known.push_back(x_known); data_known.push_back(y_known); //Get the sample/line guess from the least squares solutions double sample_guess = p_sampleSol->Evaluate(data_known); double line_guess = p_lineSol->Evaluate(data_known); //If the sample/line guess is out of bounds return false if (sample_guess < -1.5) return false; if (line_guess < -1.5) return false; if (sample_guess > p_inputSamples + 1.5) return false; if (line_guess > p_inputLines + 1.5) return false; if (sample_guess < 0.5) sample_guess = 1; if (line_guess < 0.5) line_guess = 1; if (sample_guess > p_inputSamples + 0.5) sample_guess = p_inputSamples; if (line_guess > p_inputLines + 0.5) line_guess = p_inputLines; //Create a bilinear interpolator Interpolator interp(Interpolator::BiLinearType); //Create a 2x2 buffer to read the lat and long cubes Portal latPortal(interp.Samples(), interp.Lines(), p_latCube->pixelType() , interp.HotSample(), interp.HotLine()); Portal lonPortal(interp.Samples(), interp.Lines(), p_lonCube->pixelType() , interp.HotSample(), interp.HotLine()); //Set the buffers positions to the sample/line guess and read from the lat/long cubes latPortal.SetPosition(sample_guess, line_guess, 1); p_latCube->read(latPortal); lonPortal.SetPosition(sample_guess, line_guess, 1); p_lonCube->read(lonPortal); //Get the lat/long guess from the interpolator double lat_guess = interp.Interpolate(sample_guess, line_guess, latPortal.DoubleBuffer()) * PI / 180.0; double lon_guess = interp.Interpolate(sample_guess, line_guess, lonPortal.DoubleBuffer()) * PI / 180.0; //Project the lat/long guess to x/y using the stereographic projection double k_guess = 2 / (1 + sin(p_latCenter) * sin(lat_guess) + cos(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter)); double x_guess = k_guess * cos(lat_guess) * sin(lon_guess - p_lonCenter); double y_guess = k_guess * (cos(p_latCenter) * sin(lat_guess)) - (sin(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter)); //Calculate the difference between the known x/y to the x/y from our least squares solutions double x_diff = abs(x_guess - x_known) * p_radius; double y_diff = abs(y_guess - y_known) * p_radius; //If the difference is above the tolerance, correct it until it is below the tolerance or we have iterated through a set amount of times int iteration = 0; while (x_diff > p_tolerance || y_diff > p_tolerance) { if (iteration++ >= p_iterations) return false; //Create a 1st order polynomial function PolynomialBivariate sampFunct(1); PolynomialBivariate lineFunct(1); //Create a least squares solution LeastSquares sampConverge(sampFunct); LeastSquares lineConverge(lineFunct); //Add the points around the line/sample guess point to the least squares matrix for (int i = (int)(line_guess + 0.5) - 1; i <= (int)(line_guess + 0.5) + 1; i++) { //If the line is out of bounds, then skip it if (i < 1 || i > p_inputLines) continue; for (int j = (int)(sample_guess + 0.5) - 1; j <= (int)(sample_guess + 0.5) + 1; j++) { //If the sample is out of bounds, then skip it if (j < 1 || j > p_inputSamples) continue; latPortal.SetPosition(j, i, 1); p_latCube->read(latPortal); if (IsSpecial(latPortal.at(0))) continue; double n_lat = latPortal.at(0) * PI / 180.0; lonPortal.SetPosition(j, i, 1); p_lonCube->read(lonPortal); if (IsSpecial(lonPortal.at(0))) continue; double n_lon = lonPortal.at(0) * PI / 180.0; //Conver the lat/lon to x/y using the stereographic projection double n_k = 2 / (1 + sin(p_latCenter) * sin(n_lat) + cos(p_latCenter) * cos(n_lat) * cos(n_lon - p_lonCenter)); double n_x = n_k * cos(n_lat) * sin(n_lon - p_lonCenter); double n_y = n_k * (cos(p_latCenter) * sin(n_lat)) - (sin(p_latCenter) * cos(n_lat) * cos(n_lon - p_lonCenter)); //Add the points to the least squares solution vector<double> data; data.push_back(n_x); data.push_back(n_y); sampConverge.AddKnown(data, j); lineConverge.AddKnown(data, i); } } //TODO: What if solve can't and throws an error? //Solve the least squares functions sampConverge.Solve(LeastSquares::QRD); lineConverge.Solve(LeastSquares::QRD); //Try to solve the known data with our new function sample_guess = sampConverge.Evaluate(data_known); line_guess = lineConverge.Evaluate(data_known); //If the new sample/line is out of bounds return false if (sample_guess < -1.5) return false; if (line_guess < -1.5) return false; if (sample_guess > p_inputSamples + 1.5) return false; if (line_guess > p_inputLines + 1.5) return false; if (sample_guess < 0.5) sample_guess = 1; if (line_guess < 0.5) line_guess = 1; if (sample_guess > p_inputSamples + 0.5) sample_guess = p_inputSamples; if (line_guess > p_inputLines + 0.5) line_guess = p_inputLines; //Set the buffers positions to the sample/line guess and read from the lat/long cubes latPortal.SetPosition(sample_guess, line_guess, 1); p_latCube->read(latPortal); lonPortal.SetPosition(sample_guess, line_guess, 1); p_lonCube->read(lonPortal); //Get the lat/long guess from the interpolator lat_guess = interp.Interpolate(sample_guess, line_guess, latPortal.DoubleBuffer()) * PI / 180.0; lon_guess = interp.Interpolate(sample_guess, line_guess, lonPortal.DoubleBuffer()) * PI / 180.0; //Project the lat/long guess to x/y using the stereographic projection k_guess = 2 / (1 + sin(p_latCenter) * sin(lat_guess) + cos(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter)); x_guess = k_guess * cos(lat_guess) * sin(lon_guess - p_lonCenter); y_guess = k_guess * (cos(p_latCenter) * sin(lat_guess)) - (sin(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter)); //Calculate the difference between the known x/y to the x/y from our least squares solutions x_diff = abs(x_guess - x_known) * p_radius; y_diff = abs(y_guess - y_known) * p_radius; } //Set the input sample/line to the sample/line we've determined to be the closest fit inSample = sample_guess; inLine = line_guess; return true; } // Function to delete unwanted tables in header void DeleteTables(Pvl *label, PvlGroup kernels) { //Delete any tables in header corresponding to the Kernel const QString tableStr("Table"); const QString nameStr("Name"); //Setup a list of tables to delete with predetermined values and any tables in the kernel. //If additional tables need to be removed, they can be added to the list of tables that //detine the 'tmpTablesToDelete' QString array directly below. QString tmpTablesToDelete[] = {"SunPosition","BodyRotation","InstrumentPointing", "InstrumentPosition"}; std::vector<QString> tablesToDelete; int sizeOfTablesToDelete = (int) sizeof(tmpTablesToDelete)/sizeof(*tmpTablesToDelete); for (int i = 0; i < sizeOfTablesToDelete; i++) { tablesToDelete.push_back( tmpTablesToDelete[i] ); } for (int j=0; j < kernels.keywords(); j++) { if (kernels[j].operator[](0) == tableStr) { bool newTableToDelete=true; for (int k = 0; k<sizeOfTablesToDelete; k++) { if ( tablesToDelete[k] == kernels[j].name() ) { newTableToDelete=false; break; } } if (newTableToDelete) { tablesToDelete.push_back( kernels[j].name() ); sizeOfTablesToDelete++; } } } int tablesToDeleteSize = (int) tablesToDelete.size(); //Now go through and find all entries in the label corresponding to our unwanted keywords std::vector<int> indecesToDelete; int indecesToDeleteSize=0; for (int k=0; k < label->objects(); k++) { PvlObject &currentObject=(*label).object(k); if (currentObject.name() == tableStr) { PvlKeyword &nameKeyword = currentObject.findKeyword(nameStr); for (int l=0; l < tablesToDeleteSize; l++) { if ( nameKeyword[0] == tablesToDelete[l] ) { indecesToDelete.push_back(k-indecesToDeleteSize); indecesToDeleteSize++; //(*label).deleteObject(k); //tableDeleted = true; break; } } } } //Now go through and delete the corresponding tables for (int k=0; k < indecesToDeleteSize; k++) { (*label).deleteObject(indecesToDelete[k]); } } int NoCam2Map::OutputSamples() const { return p_outputSamples; } int NoCam2Map::OutputLines() const { return p_outputLines; } }
40.103947
140
0.616556
gknorman
05c5d8126b4dde4f2e90a721193c5f2174a895ba
566
cpp
C++
0901-1000/0973-K Closest Points to Origin/0973-K Closest Points to Origin.cpp
jiadaizhao/LeetCode
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
0901-1000/0973-K Closest Points to Origin/0973-K Closest Points to Origin.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
0901-1000/0973-K Closest Points to Origin/0973-K Closest Points to Origin.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: vector<vector<int>> kClosest(vector<vector<int>>& points, int K) { priority_queue<pair<int, int>> pq; for (int i = 0; i < points.size(); ++i) { pq.emplace(points[i][0]* points[i][0] + points[i][1] * points[i][1], i); if (pq.size() > K) { pq.pop(); } } vector<vector<int>> result; while (!pq.empty()) { int i = pq.top().second; result.push_back(points[i]); pq.pop(); } return result; } };
26.952381
84
0.452297
jiadaizhao
05c68db7063849741136465ac44439d72e8f6af0
7,382
hxx
C++
Eudora71/SpelChek/src/nuspell/string_utils.hxx
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
1
2019-06-15T17:46:11.000Z
2019-06-15T17:46:11.000Z
Eudora71/SpelChek/src/nuspell/string_utils.hxx
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
null
null
null
Eudora71/SpelChek/src/nuspell/string_utils.hxx
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
null
null
null
/* Copyright 2018 Dimitrij Mijoski, Sander van Geloven * Copyright 2016-2017 Dimitrij Mijoski * * This file is part of Nuspell. * * Nuspell is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Nuspell 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Nuspell. If not, see <http://www.gnu.org/licenses/>. */ /** * @file string_utils.hxx * String algorithms. */ #ifndef NUSPELL_STRING_UTILS_HXX #define NUSPELL_STRING_UTILS_HXX #include <algorithm> #include <iterator> #include <locale> #include <string> #include <vector> namespace nuspell { #define LITERAL(T, x) ::nuspell::literal_choose<T>(x, L##x) template <class CharT> auto constexpr literal_choose(const char* narrow, const wchar_t* wide); template <> auto constexpr literal_choose<char>(const char* narrow, const wchar_t*) { return narrow; } template <> auto constexpr literal_choose<wchar_t>(const char*, const wchar_t* wide) { return wide; } /** * Splits string on set of single char seperators. * * Consecutive separators are treated as separate and will emit empty strings. * * @param s string to split. * @param sep seperator to split on. * @param out start of the output range where separated strings are * appended. * @return The end of the output range where separated strings are appended. */ template <class CharT, class SepT, class OutIt> auto split_on_any_of(const std::basic_string<CharT>& s, const SepT& sep, OutIt out) { using size_type = typename std::basic_string<CharT>::size_type; size_type i1 = 0; size_type i2; do { i2 = s.find_first_of(sep, i1); *out++ = s.substr(i1, i2 - i1); i1 = i2 + 1; // we can only add +1 if sep is single char. // i2 gets s.npos after the last separator. // Length of i2-i1 will always go past the end. That is defined. } while (i2 != s.npos); return out; } /** * Splits string on single char seperator. * * Consecutive separators are treated as separate and will emit empty strings. * * @param s string to split. * @param sep char that acts as separator to split on. * @param out start of the output range where separated strings are * appended. * @return The iterator that indicates the end of the output range. */ template <class CharT, class OutIt> auto split(const std::basic_string<CharT>& s, CharT sep, OutIt out) { return split_on_any_of(s, sep, out); } /** * Splits string on string separator. * * @param s string to split. * @param sep seperator to split on. * @param out start of the output range where separated strings are * appended. * @return The end of the output range where separated strings are appended. */ template <class CharT, class OutIt> auto split(const std::basic_string<CharT>& s, const std::basic_string<CharT>& sep, OutIt out) { using size_type = typename std::basic_string<CharT>::size_type; size_type i1 = 0; size_type i2; do { i2 = s.find(sep, i1); *out++ = s.substr(i1, i2 - i1); i1 = i2 + sep.size(); } while (i2 != s.npos); return out; } /** * Splits string on string separator. * * @param s string to split. * @param sep seperator to split on. * @param out start of the output range where separated strings are * appended. * @return The end of the output range where separated strings are appended. */ template <class CharT, class OutIt> auto split(const std::basic_string<CharT>& s, const CharT* sep, OutIt out) { return split(s, std::basic_string<CharT>(sep), out); } /** * Splits string on seperator, output to vector of strings. * * See split(). * * @param s string to split. * @param sep separator to split on. * @param[out] v vector with separated strings. The vector is first cleared. */ template <class CharT, class CharOrStr> auto split_v(const std::basic_string<CharT>& s, const CharOrStr& sep, std::vector<std::basic_string<CharT>>& v) { v.clear(); split(s, sep, std::back_inserter(v)); } /** * Gets the first token of a splitted string. * * @param s string to split. * @param sep char or string that acts as separator to split on. * @return The string that has been split off. */ template <class CharT, class CharOrStr> auto split_first(const std::basic_string<CharT>& s, const CharOrStr& sep) -> std::basic_string<CharT> { auto index = s.find(sep); return s.substr(0, index); } /** * Splits on whitespace. * * Consecutive whitespace is treated as single separator. Behaves same as * Python's split called without separator argument. * * @param s string to split. * @param out start of the output range where separated strings are * appended. * @param loc locale object that takes care of what is whitespace. * @return The iterator that indicates the end of the output range. */ template <class CharT, class OutIt> auto split_on_whitespace(const std::basic_string<CharT>& s, OutIt out, const std::locale& loc = std::locale()) -> OutIt { auto& f = std::use_facet<std::ctype<CharT>>(loc); auto isspace = [&](auto& c) { return f.is(std::ctype_base::space, c); }; auto i1 = begin(s); auto endd = end(s); do { auto i2 = std::find_if_not(i1, endd, isspace); if (i2 == endd) break; auto i3 = std::find_if(i2, endd, isspace); *out++ = std::basic_string<CharT>(i2, i3); i1 = i3; } while (i1 != endd); return out; } /** * Splits on whitespace, outputs to vector of strings. * * See split_on_whitespace(). * * @param s string to split. * @param[out] v vector with separated strings. The vector is first cleared. * @param loc input locale. */ template <class CharT> auto split_on_whitespace_v(const std::basic_string<CharT>& s, std::vector<std::basic_string<CharT>>& v, const std::locale& loc = std::locale()) -> void { v.clear(); split_on_whitespace(s, back_inserter(v), loc); } template <class CharT> auto& erase_chars(std::basic_string<CharT>& s, const std::basic_string<CharT>& erase_chars) { if (erase_chars.empty()) return s; auto is_erasable = [&](CharT c) { return erase_chars.find(c) != erase_chars.npos; }; auto it = remove_if(begin(s), end(s), is_erasable); s.erase(it, end(s)); return s; } /** * Tests if word is a number. * * Allow numbers with dots ".", dashes "-" and commas ",", but forbids double * separators such as "..", "--" and ".,". This results in increase of * performance over an implementation with <regex> use. */ template <class CharT> auto is_number(const std::basic_string<CharT>& s) -> bool { if (s.empty()) return false; size_t i = 0; if (s[0] == '-') ++i; for (; i != s.size();) { auto next = s.find_first_not_of(LITERAL(CharT, "0123456789"), i); if (next == i) return false; if (next == s.npos) return true; i = next; auto c = s[i]; if (c == '.' || c == ',' || c == '-') ++i; else return false; } return false; } } // namespace nuspell #endif // NUSPELL_STRING_UTILS_HXX
27.962121
78
0.67922
ivanagui2
05c7e7d60bf9b8cb9a869ba1275d541a44719580
7,752
cpp
C++
src/data/Node.cpp
yunify/qsfs-fuse
24d7445df491dd9fe3924eda81026272d3db7e53
[ "Apache-2.0" ]
20
2018-02-11T06:16:53.000Z
2019-09-06T06:57:39.000Z
src/data/Node.cpp
yunify/qsfs-fuse
24d7445df491dd9fe3924eda81026272d3db7e53
[ "Apache-2.0" ]
6
2018-03-15T06:53:54.000Z
2018-09-02T17:32:51.000Z
src/data/Node.cpp
qingstor-incubating/qsfs-fuse
24d7445df491dd9fe3924eda81026272d3db7e53
[ "Apache-2.0" ]
5
2018-03-01T09:58:19.000Z
2018-08-20T01:50:07.000Z
// +------------------------------------------------------------------------- // | Copyright (C) 2017 Yunify, Inc. // +------------------------------------------------------------------------- // | Licensed under the Apache License, Version 2.0 (the "License"); // | You may not use this work except in compliance with the License. // | You may obtain a copy of the License in the LICENSE file, or at: // | // | http://www.apache.org/licenses/LICENSE-2.0 // | // | Unless required by applicable law or agreed to in writing, software // | distributed under the License is distributed on an "AS IS" BASIS, // | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // | See the License for the specific language governing permissions and // | limitations under the License. // +------------------------------------------------------------------------- #include "data/Node.h" #include <assert.h> #include <deque> #include <set> #include <string> #include <utility> #include "boost/foreach.hpp" #include "boost/shared_ptr.hpp" #include "base/LogMacros.h" #include "base/StringUtils.h" #include "base/Utils.h" #include "data/FileMetaDataManager.h" namespace QS { namespace Data { using boost::shared_ptr; using QS::StringUtils::FormatPath; using QS::Utils::AppendPathDelim; using std::deque; using std::pair; using std::set; using std::string; // -------------------------------------------------------------------------- Node::Node(const Entry &entry, const shared_ptr<Node> &parent) : m_entry(entry), m_parent(parent) { m_children.clear(); } // -------------------------------------------------------------------------- Node::Node(const Entry &entry, const shared_ptr<Node> &parent, const string &symbolicLink) : m_entry(entry), m_parent(parent) { // must use m_entry instead of entry which is moved to m_entry now if (m_entry && m_entry.GetFileSize() <= symbolicLink.size()) { m_symbolicLink = string(symbolicLink, 0, m_entry.GetFileSize()); } } // -------------------------------------------------------------------------- Node::~Node() { if (!m_entry) return; if (IsDirectory()) { shared_ptr<Node> parent = m_parent.lock(); if (parent) { parent->GetEntry().DecreaseNumLink(); } } GetEntry().DecreaseNumLink(); if (m_entry.GetNumLink() <= 0 || (m_entry.GetNumLink() <= 1 && m_entry.IsDirectory())) { FileMetaDataManager::Instance().Erase(GetFilePath()); } } // -------------------------------------------------------------------------- shared_ptr<Node> Node::Find(const string &childFileName) const { ChildrenMapConstIterator child = m_children.find(childFileName); if (child != m_children.end()) { return child->second; } return shared_ptr<Node>(); } // -------------------------------------------------------------------------- bool Node::HaveChild(const string &childFilePath) const { return m_children.find(childFilePath) != m_children.end(); } // -------------------------------------------------------------------------- const FilePathToNodeUnorderedMap &Node::GetChildren() const { return m_children; } // -------------------------------------------------------------------------- FilePathToNodeUnorderedMap &Node::GetChildren() { return m_children; } // -------------------------------------------------------------------------- set<string> Node::GetChildrenIds() const { set<string> ids; BOOST_FOREACH(const FilePathToNodeUnorderedMap::value_type &p, m_children) { ids.insert(p.first); } return ids; } // -------------------------------------------------------------------------- deque<string> Node::GetDescendantIds() const { deque<string> ids; deque<shared_ptr<Node> > childs; BOOST_FOREACH(const FilePathToNodeUnorderedMap::value_type &p, m_children) { ids.push_back(p.first); childs.push_back(p.second); } while (!childs.empty()) { shared_ptr<Node> &child = childs.front(); childs.pop_front(); if (child->IsDirectory()) { BOOST_FOREACH(const FilePathToNodeUnorderedMap::value_type &p, child->GetChildren()) { ids.push_back(p.first); childs.push_back(p.second); } } } return ids; } // -------------------------------------------------------------------------- shared_ptr<Node> Node::Insert(const shared_ptr<Node> &child) { assert(IsDirectory()); if (child) { pair<ChildrenMapIterator, bool> res = m_children.emplace(child->GetFilePath(), child); if (res.second) { if (child->IsDirectory()) { m_entry.IncreaseNumLink(); } } else { DebugWarning("Node insertion failed " + FormatPath(child->GetFilePath())); } } else { DebugWarning("Try to insert null Node"); } return child; } // -------------------------------------------------------------------------- void Node::Remove(const shared_ptr<Node> &child) { if (child) { Remove(child->GetFilePath()); } else { DebugWarning("Try to remove null Node") } } // -------------------------------------------------------------------------- void Node::Remove(const string &childFilePath) { if (childFilePath.empty()) return; bool reset = m_children.size() == 1 ? true : false; ChildrenMapIterator it = m_children.find(childFilePath); if (it != m_children.end()) { m_children.erase(it); if (reset) m_children.clear(); } else { DebugWarning("Node not exist, no remove " + FormatPath(childFilePath)); } } // -------------------------------------------------------------------------- void Node::Rename(const string &newFilePath) { if (m_entry) { string oldFilePath = m_entry.GetFilePath(); if (oldFilePath == newFilePath) { return; } if (m_children.find(newFilePath) != m_children.end()) { DebugWarning("Cannot rename, target node already exist " + FormatPath(oldFilePath, newFilePath)); return; } m_entry.Rename(newFilePath); if (m_children.empty()) { return; } deque<shared_ptr<Node> > childs; BOOST_FOREACH(FilePathToNodeUnorderedMap::value_type &p, m_children) { childs.push_back(p.second); } m_children.clear(); BOOST_FOREACH(shared_ptr<Node> &child, childs) { string newPath = AppendPathDelim(newFilePath) + child->MyBaseName(); pair<ChildrenMapIterator, bool> res = m_children.emplace(newPath, child); if (res.second) { child->Rename(newPath); } else { DebugWarning("Node rename failed " + FormatPath(child->GetFilePath())); } } } } // -------------------------------------------------------------------------- void Node::RenameChild(const string &oldFilePath, const string &newFilePath) { if (oldFilePath == newFilePath) { DebugInfo("Same file name, no rename " + FormatPath(oldFilePath)); return; } if (m_children.find(newFilePath) != m_children.end()) { DebugWarning("Cannot rename, target node already exist " + FormatPath(oldFilePath, newFilePath)); return; } ChildrenMapIterator it = m_children.find(oldFilePath); if (it != m_children.end()) { shared_ptr<Node> &child = it->second; child->Rename(newFilePath); // Need to emplace before erase, otherwise the shared_ptr // will probably get deleted when erasing cause its' reference // count to be 0. pair<ChildrenMapIterator, bool> res = m_children.emplace(newFilePath, child); if (!res.second) { DebugWarning("Fail to rename " + FormatPath(oldFilePath, newFilePath)); } m_children.erase(it); } else { DebugWarning("Node not exist, no rename " + FormatPath(oldFilePath)); } } } // namespace Data } // namespace QS
31.008
81
0.553277
yunify
05cb9856c8a2c606631323ff2ed060567613eeaa
1,144
cpp
C++
XBeat/Physics/PMXMotionState.cpp
shirayukikitsune/xbeat
df1f0ea3ada18d9790ebf6a16cee9370d82b431b
[ "NCSA" ]
3
2015-03-02T13:27:00.000Z
2021-01-10T15:20:38.000Z
XBeat/Physics/PMXMotionState.cpp
shirayukikitsune/xbeat
df1f0ea3ada18d9790ebf6a16cee9370d82b431b
[ "NCSA" ]
null
null
null
XBeat/Physics/PMXMotionState.cpp
shirayukikitsune/xbeat
df1f0ea3ada18d9790ebf6a16cee9370d82b431b
[ "NCSA" ]
null
null
null
//===-- Physics/PMXMotionState.cpp - Defines a Motion State for PMX ----*- C++ -*-===// // // The XBeat Project // // This file is distributed under the University of Illinois Open Source License. // See LICENSE.TXT for details. // //===-----------------------------------------------------------------------------===// /// /// \file /// \brief This file defines everything related to the Physics::PMXMotionState class, /// which is an interface between bullet dynamics world and a PMX::Model. /// //===-----------------------------------------------------------------------------===// #include "../PMX/PMXBone.h" #include "PMXMotionState.h" Physics::PMXMotionState::PMXMotionState(PMX::Bone *AssociatedBone, const btTransform &InitialTransform) { assert(AssociatedBone != nullptr); this->InitialTransform = InitialTransform; this->AssociatedBone = AssociatedBone; } void Physics::PMXMotionState::getWorldTransform(btTransform &WorldTransform) const { WorldTransform = InitialTransform * AssociatedBone->getLocalTransform(); } void Physics::PMXMotionState::setWorldTransform(const btTransform &WorldTransform) { }
32.685714
103
0.620629
shirayukikitsune
fe4ae5e44e1eeb8c963dd883d513875033e811f2
876
cpp
C++
judge_client/1/uoj_judger/builtin/checker/wcmp.cpp
TRCYX/UOJ-System
a70283a4ee309f5485ec00c4cd1143fbf87d616a
[ "MIT" ]
483
2016-07-18T16:40:58.000Z
2022-03-31T04:29:12.000Z
judger/uoj_judger/builtin/checker/wcmp.cpp
chy-2003/UOJ-System
8ca70fc87c36b81a37d3a437c319348710404181
[ "MIT" ]
102
2019-04-14T05:40:54.000Z
2022-02-07T13:21:36.000Z
judger/uoj_judger/builtin/checker/wcmp.cpp
chy-2003/UOJ-System
8ca70fc87c36b81a37d3a437c319348710404181
[ "MIT" ]
166
2017-04-07T01:04:35.000Z
2022-03-30T04:59:25.000Z
#include "testlib.h" using namespace std; int main(int argc, char * argv[]) { setName("compare sequences of tokens"); registerTestlibCmd(argc, argv); int n = 0; string j, p; while (!ans.seekEof() && !ouf.seekEof()) { n++; ans.readWordTo(j); ouf.readWordTo(p); if (j != p) quitf(_wa, "%d%s words differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str()); } if (ans.seekEof() && ouf.seekEof()) { if (n == 1) quitf(_ok, "\"%s\"", compress(j).c_str()); else quitf(_ok, "%d tokens", n); } else { if (ans.seekEof()) quitf(_wa, "Participant output contains extra tokens"); else quitf(_wa, "Unexpected EOF in the participants output"); } }
22.461538
145
0.505708
TRCYX
fe4aec1898da27ecc3d02c703e90ee52deebd955
5,753
cc
C++
quic/quic_transport/quic_transport_server_session.cc
fcharlie/quiche
56835aa2c2e3645e0eec85bff07f9d58e3bace63
[ "BSD-3-Clause" ]
1
2019-11-05T05:26:53.000Z
2019-11-05T05:26:53.000Z
quic/quic_transport/quic_transport_server_session.cc
fcharlie/quiche
56835aa2c2e3645e0eec85bff07f9d58e3bace63
[ "BSD-3-Clause" ]
null
null
null
quic/quic_transport/quic_transport_server_session.cc
fcharlie/quiche
56835aa2c2e3645e0eec85bff07f9d58e3bace63
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/quic_transport/quic_transport_server_session.h" #include <memory> #include "url/gurl.h" #include "net/third_party/quiche/src/quic/core/quic_error_codes.h" #include "net/third_party/quiche/src/quic/core/quic_stream.h" #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h" #include "net/third_party/quiche/src/quic/platform/api/quic_string_piece.h" #include "net/third_party/quiche/src/quic/quic_transport/quic_transport_protocol.h" #include "net/third_party/quiche/src/quic/quic_transport/quic_transport_stream.h" namespace quic { namespace { class QuicTransportServerCryptoHelper : public QuicCryptoServerStream::Helper { public: bool CanAcceptClientHello(const CryptoHandshakeMessage& /*message*/, const QuicSocketAddress& /*client_address*/, const QuicSocketAddress& /*peer_address*/, const QuicSocketAddress& /*self_address*/, std::string* /*error_details*/) const override { return true; } }; } // namespace QuicTransportServerSession::QuicTransportServerSession( QuicConnection* connection, Visitor* owner, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, ServerVisitor* visitor) : QuicSession(connection, owner, config, supported_versions, /*num_expected_unidirectional_static_streams*/ 0), visitor_(visitor) { for (const ParsedQuicVersion& version : supported_versions) { QUIC_BUG_IF(version.handshake_protocol != PROTOCOL_TLS1_3) << "QuicTransport requires TLS 1.3 handshake"; } static QuicTransportServerCryptoHelper* helper = new QuicTransportServerCryptoHelper(); crypto_stream_ = std::make_unique<QuicCryptoServerStream>( crypto_config, compressed_certs_cache, this, helper); } QuicStream* QuicTransportServerSession::CreateIncomingStream(QuicStreamId id) { if (id == ClientIndicationStream()) { auto indication = std::make_unique<ClientIndication>(this); ClientIndication* indication_ptr = indication.get(); ActivateStream(std::move(indication)); return indication_ptr; } auto stream = std::make_unique<QuicTransportStream>(id, this, this); QuicTransportStream* stream_ptr = stream.get(); ActivateStream(std::move(stream)); return stream_ptr; } QuicTransportServerSession::ClientIndication::ClientIndication( QuicTransportServerSession* session) : QuicStream(ClientIndicationStream(), session, /* is_static= */ false, StreamType::READ_UNIDIRECTIONAL), session_(session) {} void QuicTransportServerSession::ClientIndication::OnDataAvailable() { sequencer()->Read(&buffer_); if (buffer_.size() > ClientIndicationMaxSize()) { session_->connection()->CloseConnection( QUIC_TRANSPORT_INVALID_CLIENT_INDICATION, QuicStrCat("Client indication size exceeds ", ClientIndicationMaxSize(), " bytes"), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (sequencer()->IsClosed()) { session_->ProcessClientIndication(buffer_); OnFinRead(); } } bool QuicTransportServerSession::ClientIndicationParser::Parse() { bool origin_received = false; while (!reader_.IsDoneReading()) { uint16_t key; if (!reader_.ReadUInt16(&key)) { ParseError("Expected 16-bit key"); return false; } QuicStringPiece value; if (!reader_.ReadStringPiece16(&value)) { ParseError(QuicStrCat("Failed to read value for key ", key)); return false; } switch (static_cast<QuicTransportClientIndicationKeys>(key)) { case QuicTransportClientIndicationKeys::kOrigin: { GURL origin_url{std::string(value)}; if (!origin_url.is_valid()) { Error("Unable to parse the specified origin"); return false; } url::Origin origin = url::Origin::Create(origin_url); QUIC_DLOG(INFO) << "QuicTransport server received origin " << origin; if (!session_->visitor_->CheckOrigin(origin)) { Error("Origin check failed"); return false; } origin_received = true; break; } default: QUIC_DLOG(INFO) << "Unknown client indication key: " << key; break; } } if (!origin_received) { Error("No origin received"); return false; } return true; } void QuicTransportServerSession::ClientIndicationParser::Error( const std::string& error_message) { session_->connection()->CloseConnection( QUIC_TRANSPORT_INVALID_CLIENT_INDICATION, error_message, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } void QuicTransportServerSession::ClientIndicationParser::ParseError( QuicStringPiece error_message) { Error(QuicStrCat("Failed to parse the client indication stream: ", error_message, reader_.DebugString())); } void QuicTransportServerSession::ProcessClientIndication( QuicStringPiece indication) { ClientIndicationParser parser(this, indication); if (!parser.Parse()) { return; } // Don't set the ready bit if we closed the connection due to any error // beforehand. if (!connection()->connected()) { return; } ready_ = true; } } // namespace quic
33.643275
89
0.695116
fcharlie
fe4b3b929e3b82ad887618942b909fd2b68529f6
191
cpp
C++
exercises/3/week15/src/Animal.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
19
2020-02-21T16:46:50.000Z
2022-01-26T19:59:49.000Z
exercises/3/week15/src/Animal.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
1
2020-03-14T08:09:45.000Z
2020-03-14T08:09:45.000Z
exercises/3/week15/src/Animal.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
11
2020-02-23T12:29:58.000Z
2021-04-11T08:30:12.000Z
#include"Animal.h" Animal::Animal(int health){ this->health=health; } void Animal::eat(Food& f,int quantity){ health+=f.eat(quantity); }; int Animal::getHealth()const{ return health; };
17.363636
39
0.696335
triffon
fe4ba2bfd810e1a3784419134e7e7b35e6573d09
9,491
hpp
C++
pythran/pythonic/numpy/argminmax.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1
2020-07-21T10:01:20.000Z
2020-07-21T10:01:20.000Z
pythran/pythonic/numpy/argminmax.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/argminmax.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_NUMPY_ARGMINMAX_HPP #define PYTHONIC_NUMPY_ARGMINMAX_HPP #include "pythonic/utils/functor.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/numpy/asarray.hpp" #include "pythonic/builtins/ValueError.hpp" PYTHONIC_NS_BEGIN namespace numpy { namespace details { template <class P, size_t... Is> P iota(utils::index_sequence<Is...>) { return {static_cast<typename P::value_type>(Is)...}; } template <class P> P iota() { return iota<P>(utils::make_index_sequence<P::size>()); } } template <class Op, class E, class T> long _argminmax_seq(E const &elts, T &minmax_elts) { long index = 0; long res = -1; for (auto const &elt : elts) { if (Op::value(elt, minmax_elts)) { minmax_elts = elt; res = index; } ++index; } return res; } template <class Op, class E, class T> #ifdef USE_XSIMD typename std::enable_if< !E::is_vectorizable || !types::is_vector_op<typename Op::op, T, T>::value || std::is_same<typename E::dtype, bool>::value, long>::type #else long #endif _argminmax(E const &elts, T &minmax_elts, utils::int_<1>) { return _argminmax_seq<Op>(elts, minmax_elts); } template <class Op, class E, class T, class... Indices> std::tuple<long, long> _argminmax_fast(E const &elts, T &minmax_elts, long current_pos, utils::int_<1>, Indices... indices) { long res = -1; long n = elts.template shape<std::decay<E>::type::value - 1>(); for (long i = 0; i < n; ++i) { auto elt = elts.load(indices..., i); if (Op::value(elt, minmax_elts)) { minmax_elts = elt; res = current_pos + i; } } return std::make_tuple(res, current_pos + n); } #ifdef USE_XSIMD template <bool IsInt> struct bool_caster; template <> struct bool_caster<true> { template <class T> auto operator()(T const &value) -> decltype(xsimd::bool_cast(value)) { return xsimd::bool_cast(value); } }; template <> struct bool_caster<false> { template <class T> T operator()(T const &value) { return value; } }; template <class Op, class E, class T> typename std::enable_if< E::is_vectorizable && types::is_vector_op<typename Op::op, T, T>::value && !std::is_same<typename E::dtype, bool>::value, long>::type _argminmax(E const &elts, T &minmax_elts, utils::int_<1>) { using vT = xsimd::simd_type<T>; using iT = xsimd::as_integer_t<T>; static const size_t vN = vT::size; const long n = elts.size(); if (n >= std::numeric_limits<iT>::max()) { return _argminmax_seq<Op>(elts, minmax_elts); } auto viter = types::vectorizer_nobroadcast::vbegin(elts), vend = types::vectorizer_nobroadcast::vend(elts); const long bound = std::distance(viter, vend); long minmax_index = -1; if (bound > 0) { auto vacc = *viter; iT iota[vN] = {0}; for (long i = 0; i < vN; ++i) iota[i] = i; auto curr = xsimd::load_unaligned(iota); xsimd::simd_type<iT> indices = curr; xsimd::simd_type<iT> step{vN}; for (++viter; viter != vend; ++viter) { curr += step; auto c = *viter; vacc = typename Op::op{}(vacc, c); auto mask = c == vacc; indices = xsimd::select(bool_caster<std::is_floating_point<T>::value>{}(mask), curr, indices); } alignas(sizeof(vT)) T stored[vN]; vacc.store_aligned(&stored[0]); alignas(sizeof(vT)) long indexed[vN]; indices.store_aligned(&indexed[0]); for (size_t j = 0; j < vN; ++j) { if (Op::value(stored[j], minmax_elts)) { minmax_elts = stored[j]; minmax_index = indexed[j]; } } } auto iter = elts.begin() + bound * vN; for (long i = bound * vN; i < n; ++i, ++iter) { if (Op::value(*iter, minmax_elts)) { minmax_elts = *iter; minmax_index = i; } } return minmax_index; } #endif template <class Op, class E, size_t N, class T> long _argminmax(E const &elts, T &minmax_elts, utils::int_<N>) { long current_pos = 0; long current_minmaxarg = 0; for (auto &&elt : elts) { long v = _argminmax<Op>(elt, minmax_elts, utils::int_<N - 1>()); if (v >= 0) current_minmaxarg = current_pos + v; current_pos += elt.flat_size(); } return current_minmaxarg; } template <class Op, class E, size_t N, class T, class... Indices> typename std::enable_if<N != 1, std::tuple<long, long>>::type _argminmax_fast(E const &elts, T &minmax_elts, long current_pos, utils::int_<N>, Indices... indices) { long current_minmaxarg = 0; for (long i = 0, n = elts.template shape<std::decay<E>::type::value - N>(); i < n; ++i) { long v; std::tie(v, current_pos) = _argminmax_fast<Op>( elts, minmax_elts, current_pos, utils::int_<N - 1>(), indices..., i); if (v >= 0) current_minmaxarg = v; } return std::make_tuple(current_minmaxarg, current_pos); } template <class Op, class E> long argminmax(E const &expr) { if (!expr.flat_size()) throw types::ValueError("empty sequence"); using elt_type = typename E::dtype; elt_type argminmax_value = Op::limit(); #ifndef USE_XSIMD if (utils::no_broadcast_ex(expr)) { return std::get<0>(_argminmax_fast<Op>(expr, argminmax_value, 0, utils::int_<E::value>())); } else #endif return _argminmax<Op>(expr, argminmax_value, utils::int_<E::value>()); } template <class Op, size_t Dim, size_t Axis, class T, class E, class V> void _argminmax_tail(T &out, E const &expr, long curr, V &curr_minmax, std::integral_constant<size_t, 0>) { if (Op::value(expr, curr_minmax)) { out = curr; curr_minmax = expr; } } template <class Op, size_t Dim, size_t Axis, class T, class E, class V, size_t N> typename std::enable_if<Axis != (Dim - N), void>::type _argminmax_tail(T &&out, E const &expr, long curr, V &&curr_minmax, std::integral_constant<size_t, N>) { static_assert(N >= 1, "specialization ok"); for (long i = 0, n = expr.template shape<0>(); i < n; ++i) _argminmax_tail<Op, Dim, Axis>(out.fast(i), expr.fast(i), curr, curr_minmax.fast(i), std::integral_constant<size_t, N - 1>()); } template <class Op, size_t Dim, size_t Axis, class T, class E> typename std::enable_if<Axis == (Dim - 1), void>::type _argminmax_head(T &&out, E const &expr, std::integral_constant<size_t, 1>) { typename E::dtype val = Op::limit(); for (long i = 0, n = expr.template shape<0>(); i < n; ++i) _argminmax_tail<Op, Dim, Axis>(std::forward<T>(out), expr.fast(i), i, val, std::integral_constant<size_t, 0>()); } template <class Op, size_t Dim, size_t Axis, class T, class E, size_t N> typename std::enable_if<Axis == (Dim - N), void>::type _argminmax_head(T &&out, E const &expr, std::integral_constant<size_t, N>) { static_assert(N > 1, "specialization ok"); types::ndarray<typename E::dtype, types::array<long, N - 1>> val{ sutils::getshape(out), Op::limit()}; for (long i = 0, n = expr.template shape<0>(); i < n; ++i) _argminmax_tail<Op, Dim, Axis>(std::forward<T>(out), expr.fast(i), i, val, std::integral_constant<size_t, N - 1>()); } template <class Op, size_t Dim, size_t Axis, class T, class E, size_t N> typename std::enable_if<Axis != (Dim - N), void>::type _argminmax_head(T &&out, E const &expr, std::integral_constant<size_t, N>) { static_assert(N >= 1, "specialization ok"); for (long i = 0, n = expr.template shape<0>(); i < n; ++i) _argminmax_head<Op, Dim, Axis>(out.fast(i), expr.fast(i), std::integral_constant<size_t, N - 1>()); } template <class Op, size_t N, class T, class E, size_t... Axis> void _argminmax_pick_axis(long axis, T &out, E const &expr, utils::index_sequence<Axis...>) { std::initializer_list<bool>{ ((Axis == axis) && (_argminmax_head<Op, N, Axis>( out, expr, std::integral_constant<size_t, N>()), true))...}; } template <class Op, class E> types::ndarray<long, types::array<long, E::value - 1>> argminmax(E const &array, long axis) { if (axis < 0) axis += E::value; if (axis < 0 || size_t(axis) >= E::value) throw types::ValueError("axis out of bounds"); auto shape = sutils::getshape(array); types::array<long, E::value - 1> shp; auto next = std::copy(shape.begin(), shape.begin() + axis, shp.begin()); std::copy(shape.begin() + axis + 1, shape.end(), next); types::ndarray<long, types::array<long, E::value - 1>> out{shp, builtins::None}; typename E::dtype curr_minmax; _argminmax_pick_axis<Op, E::value>(axis, out, array, utils::make_index_sequence<E::value>()); return out; } } PYTHONIC_NS_END #endif
32.503425
80
0.571278
davidbrochart
fe4c00412df73f9c2de37c98a02725bc007e9c77
266
cpp
C++
02. Algorithms/09. Dynamic Programming/003. Best time to Buy and Sell Stock/code.cpp
dr490n1s3d-3d8/Data-Structures-and-Algorithms
f2bba2d836f448cc0cd894c4e9791819910571d5
[ "MIT" ]
1
2022-03-06T13:58:27.000Z
2022-03-06T13:58:27.000Z
02. Algorithms/09. Dynamic Programming/003. Best time to Buy and Sell Stock/code.cpp
dr490n1s3d-3d8/Data-Structures-and-Algorithms
f2bba2d836f448cc0cd894c4e9791819910571d5
[ "MIT" ]
null
null
null
02. Algorithms/09. Dynamic Programming/003. Best time to Buy and Sell Stock/code.cpp
dr490n1s3d-3d8/Data-Structures-and-Algorithms
f2bba2d836f448cc0cd894c4e9791819910571d5
[ "MIT" ]
1
2022-03-24T15:25:34.000Z
2022-03-24T15:25:34.000Z
class Solution { public: int maxProfit(vector<int>& prices) { int cost = INT_MAX, sell=0; for(int i:prices) { cost = min(cost,i); sell = max(sell,i-cost) ; } return sell ; } };
19
40
0.43609
dr490n1s3d-3d8
fe4cc6b9f11183e5b1ded0e42c9c7c3c0716f818
1,059
cpp
C++
src/arch/riscv64/intr/timer.cpp
KehRoche/SimpleKernel
91ebac7e350b39555998c54f93e9d4b879230c26
[ "MIT" ]
820
2018-05-18T15:06:41.000Z
2022-03-04T03:30:01.000Z
src/arch/riscv64/intr/timer.cpp
KehRoche/SimpleKernel
91ebac7e350b39555998c54f93e9d4b879230c26
[ "MIT" ]
10
2018-06-01T09:43:07.000Z
2021-12-29T14:37:00.000Z
src/arch/riscv64/intr/timer.cpp
KehRoche/SimpleKernel
91ebac7e350b39555998c54f93e9d4b879230c26
[ "MIT" ]
92
2018-07-15T13:45:54.000Z
2021-12-29T14:24:12.000Z
/** * @file timer.h * @brief 中断抽象头文件 * @author Zone.N (Zone.Niuzh@hotmail.com) * @version 1.0 * @date 2021-09-18 * @copyright MIT LICENSE * https://github.com/Simple-XX/SimpleKernel * @par change log: * <table> * <tr><th>Date<th>Author<th>Description * <tr><td>2021-09-18<td>digmouse233<td>迁移到 doxygen * </table> */ #include "stdint.h" #include "stdio.h" #include "cpu.hpp" #include "opensbi.h" #include "intr.h" /// timer interrupt interval /// @todo 从 dts 读取 static constexpr const uint64_t INTERVAL = 390000000 / 20; /** * @brief 设置下一次时钟 */ void set_next(void) { // 调用 opensbi 提供的接口设置时钟 OPENSBI::set_timer(CPU::READ_TIME() + INTERVAL); return; } /** * @brief 时钟中断 */ void timer_intr(void) { // 每次执行中断时设置下一次中断的时间 set_next(); return; } void TIMER::init(void) { // 注册中断函数 CLINT::register_interrupt_handler(CLINT::INTR_S_TIMER, timer_intr); // 设置初次中断 OPENSBI::set_timer(CPU::READ_TIME()); // 开启时钟中断 CPU::WRITE_SIE(CPU::READ_SIE() | CPU::SIE_STIE); info("timer init.\n"); return; }
19.254545
71
0.643059
KehRoche
fe4d7c6413cadf3f7de82e6304fc9bb00139fc2e
502
cpp
C++
6.179/ps2/hash.cpp
kalyons11/iap2017
3b8f269d7384e9926f8b6fb3e269d46d34851e26
[ "MIT" ]
null
null
null
6.179/ps2/hash.cpp
kalyons11/iap2017
3b8f269d7384e9926f8b6fb3e269d46d34851e26
[ "MIT" ]
null
null
null
6.179/ps2/hash.cpp
kalyons11/iap2017
3b8f269d7384e9926f8b6fb3e269d46d34851e26
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <math.h> using namespace std; int main() { /*int N, M, D; cin >> N >> M >> D; cout << N << " " << M << " " << D << endl;*/ cout << "Type your message:" << endl; cin.ignore(); string x; getline(cin, x); int length = x.length(); cout << length << endl; vector<char> my_vector; for (int i = 0; i < length; i++) { my_vector.push_back(x[i]); } for (int j = 0; j < length; j++) { cout << my_vector[j] << endl; } }
14.342857
45
0.535857
kalyons11
fe4f316381a1effcabdcfa149ed3927e303e6b53
6,003
cc
C++
components/exo/ui_lock_controller.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/exo/ui_lock_controller.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/exo/ui_lock_controller.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// 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 "components/exo/ui_lock_controller.h" #include "ash/constants/ash_features.h" #include "ash/public/cpp/app_types.h" #include "ash/wm/window_state.h" #include "base/feature_list.h" #include "base/optional.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "chromeos/ui/base/window_properties.h" #include "components/exo/seat.h" #include "components/exo/shell_surface_util.h" #include "components/exo/surface.h" #include "components/exo/ui_lock_bubble.h" #include "components/exo/wm_helper.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/events/event_constants.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/views/widget/widget.h" namespace exo { constexpr auto kLongPressEscapeDuration = base::TimeDelta::FromSeconds(2); constexpr auto kExcludedFlags = ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN | ui::EF_ALTGR_DOWN | ui::EF_IS_REPEAT; UILockController::UILockController(Seat* seat) : seat_(seat) { WMHelper::GetInstance()->AddPreTargetHandler(this); seat_->AddObserver(this); } UILockController::~UILockController() { seat_->RemoveObserver(this); WMHelper::GetInstance()->RemovePreTargetHandler(this); if (bubble_widget_) { bubble_widget_->CloseWithReason(views::Widget::ClosedReason::kUnspecified); bubble_widget_ = nullptr; } } void UILockController::OnKeyEvent(ui::KeyEvent* event) { // TODO(oshima): Rather than handling key event here, add a hook in // keyboard.cc to intercept key event and handle this. // If no surface is focused, let another handler process the event. aura::Window* window = static_cast<aura::Window*>(event->target()); if (!GetTargetSurfaceForKeyboardFocus(window)) return; if (event->code() == ui::DomCode::ESCAPE && (event->flags() & kExcludedFlags) == 0) { OnEscapeKey(event->type() == ui::ET_KEY_PRESSED); } } void UILockController::OnSurfaceFocused(Surface* gained_focus) { if (gained_focus != focused_surface_to_unlock_) StopTimer(); if (!base::FeatureList::IsEnabled(chromeos::features::kExoLockNotification)) return; if (!gained_focus || !gained_focus->window()) return; views::Widget* top_level_widget = views::Widget::GetTopLevelWidgetForNativeView(gained_focus->window()); aura::Window* native_window = top_level_widget ? top_level_widget->GetNativeWindow() : nullptr; ash::WindowState* window_state = ash::WindowState::Get(native_window); // If the window is not fullscreen do not display. if (!window_state || !window_state->IsFullscreen()) return; // If the bubble exists and is already anchored to the current view then exit. if (bubble_widget_ && bubble_widget_->parent()->GetContentsView() == top_level_widget->GetContentsView()) { return; } // If the bubble exists and is anchored to a different surface, destroy that // bubble before creating a new one. if (bubble_widget_ && bubble_widget_->parent()->GetContentsView() != top_level_widget->GetContentsView()) { bubble_widget_->CloseWithReason(views::Widget::ClosedReason::kUnspecified); bubble_widget_ = nullptr; } bubble_widget_ = UILockBubbleView::DisplayBubble(top_level_widget->GetContentsView()); } void UILockController::OnPostWindowStateTypeChange( ash::WindowState* window_state, chromeos::WindowStateType old_type) { // If the window is no longer fullscreen and there is a bubble showing, close // it. if (!window_state->IsFullscreen() && bubble_widget_) { bubble_widget_->CloseWithReason(views::Widget::ClosedReason::kUnspecified); bubble_widget_ = nullptr; } } views::Widget* UILockController::GetBubbleForTesting() { return bubble_widget_; } namespace { bool EscapeHoldShouldExitFullscreen(Seat* seat) { auto* surface = seat->GetFocusedSurface(); if (!surface) return false; auto* widget = views::Widget::GetTopLevelWidgetForNativeView(surface->window()); if (!widget) return false; aura::Window* window = widget->GetNativeWindow(); if (!window || !window->GetProperty(chromeos::kEscHoldToExitFullscreen)) { return false; } auto* window_state = ash::WindowState::Get(window); return window_state && window_state->IsFullscreen(); } } // namespace void UILockController::OnEscapeKey(bool pressed) { if (pressed) { if (EscapeHoldShouldExitFullscreen(seat_) && !exit_fullscreen_timer_.IsRunning()) { focused_surface_to_unlock_ = seat_->GetFocusedSurface(); exit_fullscreen_timer_.Start( FROM_HERE, kLongPressEscapeDuration, base::BindOnce(&UILockController::OnEscapeHeld, base::Unretained(this))); } } else { StopTimer(); } } void UILockController::OnEscapeHeld() { auto* surface = seat_->GetFocusedSurface(); if (!surface || surface != focused_surface_to_unlock_) { focused_surface_to_unlock_ = nullptr; return; } if (bubble_widget_) { bubble_widget_->CloseWithReason(views::Widget::ClosedReason::kUnspecified); bubble_widget_ = nullptr; } focused_surface_to_unlock_ = nullptr; auto* widget = views::Widget::GetTopLevelWidgetForNativeView(surface->window()); auto* window_state = ash::WindowState::Get(widget ? widget->GetNativeWindow() : nullptr); if (window_state) { if (window_state->window()->GetProperty( chromeos::kEscHoldExitFullscreenToMinimized)) { window_state->Minimize(); } else { window_state->Restore(); } } } void UILockController::StopTimer() { if (exit_fullscreen_timer_.IsRunning()) { exit_fullscreen_timer_.Stop(); focused_surface_to_unlock_ = nullptr; } } } // namespace exo
32.101604
80
0.707979
Ron423c
fe50adbac7649eaa5e13242529fa6e9f78b9ac8d
3,235
cpp
C++
sdk/object/entity.cpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
sdk/object/entity.cpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
sdk/object/entity.cpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
#include "sdk/object/entity.hpp" #include "sdk/object/weapon.hpp" #include "csgo/engine.hpp" C_BaseEntity* C_BaseEntity::GetBaseEntity( const int index ) { const auto client_entity = csgo::m_client_entity_list->GetClientEntity( index ); return (client_entity ? client_entity->GetBaseEntity() : nullptr); } C_BaseEntity* C_BaseEntity::GetBaseEntityFromHandle( const CBaseHandle base_handle ) { const auto client_entity = csgo::m_client_entity_list->GetClientEntityFromHandle( base_handle ); return (client_entity ? client_entity->GetBaseEntity() : nullptr); } void C_BaseEntity::SetPredictionSeed(CUserCmd* cmd) { static auto m_pPredictionRandomSeed = memory::scan< int* >(XorStr("client.dll"), XorStr("8B 0D ? ? ? ? BA ? ? ? ? E8 ? ? ? ? 83 C4 04"), 2, 1u); if (cmd) *m_pPredictionRandomSeed = cmd->random_seed; else *m_pPredictionRandomSeed = -1; } bool C_BaseAnimating::GetBoneTransform(matrix3x4_t* output, float time /*= 0.f*/) { return SetupBones(output, 128, 256, time); } bool C_BaseAnimating::GetBonePosition( matrix3x4_t* bone_transform, const int bone, Vector& output ) { if( bone_transform ) { for( auto i = 0; i < 3; i++ ) output[ i ] = bone_transform[ bone ][ i ][ 3 ]; } return ( !output.IsZero() && output.IsValid() ); } bool C_BaseAnimating::GetBoneWorld(int index, matrix3x4_t* transform, Vector& output) { if (transform) { for (auto i = 0; i < 3; i++) output[i] = transform[index][i][3]; } return !output.IsZero(); } bool C_BaseAnimating::GetBoxBoundWorld(int index, matrix3x4_t* transform, Vector& min, Vector& max) { if (transform) { auto model = GetModel(); if (model) { auto studio = csgo::m_model_info_client->GetStudioModel(model); if (studio) { auto box = studio->pHitbox(index, m_nHitboxSet()); if (box) { min = box->bbmin.Transform(transform[box->bone]); max = box->bbmax.Transform(transform[box->bone]); } } } } return (!min.IsZero() && !max.IsZero()); } bool C_BaseAnimating::GetBoxWorld(int index, matrix3x4_t* transform, Vector& output) { Vector min = { }; Vector max = { }; if (GetBoxBoundWorld(index, transform, min, max)) output = (min + max) * 0.5f; return !output.IsZero(); } bool C_BaseAnimating::GetHitboxVector(int hitbox, Vector& out) { matrix3x4_t mat[128]; if (!GetBoneTransform(mat)) return false; auto studio = csgo::m_model_info_client->GetStudioModel(GetModel()); if (!studio) return false; auto set = studio->pHitboxSet(m_nHitboxSet()); if (!set) return false; auto box = set->pHitbox(hitbox); if (!box) return false; Vector mins = { }, maxs = { }; mins = box->bbmin.Transform(mat[box->bone]); maxs = box->bbmax.Transform(mat[box->bone]); if (mins.IsZero() || maxs.IsZero()) return false; out = (mins + maxs) * 0.5f; return !(out.IsZero()); } Vector C_BaseAnimating::GetHitboxPosition(int index) { matrix3x4_t transform[128] = { }; if (!GetBoneTransform(transform)) return Vector::Zero; Vector position = { }; if (!GetBoxWorld(index, transform, position)) return Vector::Zero; return position; } C_BaseViewModel* C_BaseAttributeItem::GetBaseModel() { auto base_model = reinterpret_cast<C_BaseViewModel*>(this); return base_model; }
22.310345
145
0.686553
jrnh
fe52d7540754426ae6925e6573b1141897093ef6
6,296
hpp
C++
android-28/android/media/MediaCodecInfo_CodecProfileLevel.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/media/MediaCodecInfo_CodecProfileLevel.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-28/android/media/MediaCodecInfo_CodecProfileLevel.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" class JObject; namespace android::media { class MediaCodecInfo_CodecProfileLevel : public JObject { public: // Fields static jint AACObjectELD(); static jint AACObjectERLC(); static jint AACObjectERScalable(); static jint AACObjectHE(); static jint AACObjectHE_PS(); static jint AACObjectLC(); static jint AACObjectLD(); static jint AACObjectLTP(); static jint AACObjectMain(); static jint AACObjectSSR(); static jint AACObjectScalable(); static jint AACObjectXHE(); static jint AVCLevel1(); static jint AVCLevel11(); static jint AVCLevel12(); static jint AVCLevel13(); static jint AVCLevel1b(); static jint AVCLevel2(); static jint AVCLevel21(); static jint AVCLevel22(); static jint AVCLevel3(); static jint AVCLevel31(); static jint AVCLevel32(); static jint AVCLevel4(); static jint AVCLevel41(); static jint AVCLevel42(); static jint AVCLevel5(); static jint AVCLevel51(); static jint AVCLevel52(); static jint AVCProfileBaseline(); static jint AVCProfileConstrainedBaseline(); static jint AVCProfileConstrainedHigh(); static jint AVCProfileExtended(); static jint AVCProfileHigh(); static jint AVCProfileHigh10(); static jint AVCProfileHigh422(); static jint AVCProfileHigh444(); static jint AVCProfileMain(); static jint DolbyVisionLevelFhd24(); static jint DolbyVisionLevelFhd30(); static jint DolbyVisionLevelFhd60(); static jint DolbyVisionLevelHd24(); static jint DolbyVisionLevelHd30(); static jint DolbyVisionLevelUhd24(); static jint DolbyVisionLevelUhd30(); static jint DolbyVisionLevelUhd48(); static jint DolbyVisionLevelUhd60(); static jint DolbyVisionProfileDvavPen(); static jint DolbyVisionProfileDvavPer(); static jint DolbyVisionProfileDvavSe(); static jint DolbyVisionProfileDvheDen(); static jint DolbyVisionProfileDvheDer(); static jint DolbyVisionProfileDvheDtb(); static jint DolbyVisionProfileDvheDth(); static jint DolbyVisionProfileDvheDtr(); static jint DolbyVisionProfileDvheSt(); static jint DolbyVisionProfileDvheStn(); static jint H263Level10(); static jint H263Level20(); static jint H263Level30(); static jint H263Level40(); static jint H263Level45(); static jint H263Level50(); static jint H263Level60(); static jint H263Level70(); static jint H263ProfileBackwardCompatible(); static jint H263ProfileBaseline(); static jint H263ProfileH320Coding(); static jint H263ProfileHighCompression(); static jint H263ProfileHighLatency(); static jint H263ProfileISWV2(); static jint H263ProfileISWV3(); static jint H263ProfileInterlace(); static jint H263ProfileInternet(); static jint HEVCHighTierLevel1(); static jint HEVCHighTierLevel2(); static jint HEVCHighTierLevel21(); static jint HEVCHighTierLevel3(); static jint HEVCHighTierLevel31(); static jint HEVCHighTierLevel4(); static jint HEVCHighTierLevel41(); static jint HEVCHighTierLevel5(); static jint HEVCHighTierLevel51(); static jint HEVCHighTierLevel52(); static jint HEVCHighTierLevel6(); static jint HEVCHighTierLevel61(); static jint HEVCHighTierLevel62(); static jint HEVCMainTierLevel1(); static jint HEVCMainTierLevel2(); static jint HEVCMainTierLevel21(); static jint HEVCMainTierLevel3(); static jint HEVCMainTierLevel31(); static jint HEVCMainTierLevel4(); static jint HEVCMainTierLevel41(); static jint HEVCMainTierLevel5(); static jint HEVCMainTierLevel51(); static jint HEVCMainTierLevel52(); static jint HEVCMainTierLevel6(); static jint HEVCMainTierLevel61(); static jint HEVCMainTierLevel62(); static jint HEVCProfileMain(); static jint HEVCProfileMain10(); static jint HEVCProfileMain10HDR10(); static jint HEVCProfileMainStill(); static jint MPEG2LevelH14(); static jint MPEG2LevelHL(); static jint MPEG2LevelHP(); static jint MPEG2LevelLL(); static jint MPEG2LevelML(); static jint MPEG2Profile422(); static jint MPEG2ProfileHigh(); static jint MPEG2ProfileMain(); static jint MPEG2ProfileSNR(); static jint MPEG2ProfileSimple(); static jint MPEG2ProfileSpatial(); static jint MPEG4Level0(); static jint MPEG4Level0b(); static jint MPEG4Level1(); static jint MPEG4Level2(); static jint MPEG4Level3(); static jint MPEG4Level3b(); static jint MPEG4Level4(); static jint MPEG4Level4a(); static jint MPEG4Level5(); static jint MPEG4Level6(); static jint MPEG4ProfileAdvancedCoding(); static jint MPEG4ProfileAdvancedCore(); static jint MPEG4ProfileAdvancedRealTime(); static jint MPEG4ProfileAdvancedScalable(); static jint MPEG4ProfileAdvancedSimple(); static jint MPEG4ProfileBasicAnimated(); static jint MPEG4ProfileCore(); static jint MPEG4ProfileCoreScalable(); static jint MPEG4ProfileHybrid(); static jint MPEG4ProfileMain(); static jint MPEG4ProfileNbit(); static jint MPEG4ProfileScalableTexture(); static jint MPEG4ProfileSimple(); static jint MPEG4ProfileSimpleFBA(); static jint MPEG4ProfileSimpleFace(); static jint MPEG4ProfileSimpleScalable(); static jint VP8Level_Version0(); static jint VP8Level_Version1(); static jint VP8Level_Version2(); static jint VP8Level_Version3(); static jint VP8ProfileMain(); static jint VP9Level1(); static jint VP9Level11(); static jint VP9Level2(); static jint VP9Level21(); static jint VP9Level3(); static jint VP9Level31(); static jint VP9Level4(); static jint VP9Level41(); static jint VP9Level5(); static jint VP9Level51(); static jint VP9Level52(); static jint VP9Level6(); static jint VP9Level61(); static jint VP9Level62(); static jint VP9Profile0(); static jint VP9Profile1(); static jint VP9Profile2(); static jint VP9Profile2HDR(); static jint VP9Profile3(); static jint VP9Profile3HDR(); jint level(); jint profile(); // QJniObject forward template<typename ...Ts> explicit MediaCodecInfo_CodecProfileLevel(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} MediaCodecInfo_CodecProfileLevel(QJniObject obj); // Constructors MediaCodecInfo_CodecProfileLevel(); // Methods jboolean equals(JObject arg0) const; jint hashCode() const; }; } // namespace android::media
32.287179
173
0.760642
YJBeetle
fe53cbdac0756585f7fe8e257890ca1334f1fe07
1,346
cpp
C++
system-test/mxs1947_composite_roles.cpp
Daniel-Xu/MaxScale
35d12c0c9b75c4571dbbeb983c740de098661de6
[ "BSD-3-Clause" ]
null
null
null
system-test/mxs1947_composite_roles.cpp
Daniel-Xu/MaxScale
35d12c0c9b75c4571dbbeb983c740de098661de6
[ "BSD-3-Clause" ]
null
null
null
system-test/mxs1947_composite_roles.cpp
Daniel-Xu/MaxScale
35d12c0c9b75c4571dbbeb983c740de098661de6
[ "BSD-3-Clause" ]
null
null
null
/** * MXS-1947: Composite roles are not supported * * https://jira.mariadb.org/browse/MXS-1947 */ #include <maxtest/testconnections.hh> int main(int argc, char** argv) { TestConnections test(argc, argv); test.repl->connect(); auto prepare = { "DROP USER test@'%'", "CREATE USER test@'%' IDENTIFIED BY 'test';", "CREATE ROLE a;", "CREATE ROLE b;", "CREATE DATABASE db;", "GRANT ALL ON db.* TO a;", "GRANT a TO b;", "GRANT b TO test@'%';", "SET DEFAULT ROLE b FOR test@'%';" }; for (auto a : prepare) { execute_query_silent(test.repl->nodes[0], a); } // Wait for the users to replicate test.repl->sync_slaves(); test.tprintf("Connect with a user that has a composite role as the default role"); MYSQL* conn = open_conn_db(test.maxscales->rwsplit_port[0], test.maxscales->ip4(), "db", "test", "test"); test.expect(mysql_errno(conn) == 0, "Connection failed: %s", mysql_error(conn)); mysql_close(conn); auto cleanup = { "DROP DATABASE IF EXISTS db;", "DROP ROLE IF EXISTS a;", "DROP ROLE IF EXISTS b;", "DROP USER 'test'@'%';" }; for (auto a : cleanup) { execute_query_silent(test.repl->nodes[0], a); } return test.global_result; }
24.035714
109
0.571322
Daniel-Xu
fe565512d54898ccd143d886bcc11de749329e2c
1,221
cpp
C++
Engine/Io/DictionaryReader.cpp
i0r/huisclos
930c641ab64f1deff4c15a6e1617fc596cf8118f
[ "X11" ]
null
null
null
Engine/Io/DictionaryReader.cpp
i0r/huisclos
930c641ab64f1deff4c15a6e1617fc596cf8118f
[ "X11" ]
null
null
null
Engine/Io/DictionaryReader.cpp
i0r/huisclos
930c641ab64f1deff4c15a6e1617fc596cf8118f
[ "X11" ]
null
null
null
#include "Shared.h" #include "DictionaryReader.h" #include <string> #include <fstream> namespace { void Trim( std::string &str ) { size_t charPos = str.find_first_not_of( " \n" ); if ( charPos != std::string::npos ) { str.erase( 0, charPos ); } charPos = str.find_last_not_of( " \n" ); if ( charPos != std::string::npos ) { str.erase( charPos + 1 ); } } } const int Io_ReadDictionaryFile( const char* fileName, dictionary_t& dico ) { std::ifstream fStream( fileName ); if ( fStream.is_open() ) { std::string fLine = "", dicoKey = "", dicoVal = ""; while ( fStream.good() ) { std::getline( fStream, fLine ); const size_t separator = fLine.find_first_of( ':' ); const size_t commentSep = fLine.find_first_of( ';' ); if ( commentSep != -1 ) { fLine.erase( fLine.begin() + commentSep, fLine.end() ); } if ( !fLine.empty() && separator != std::string::npos ) { dicoKey = fLine.substr( 0, separator ); dicoVal = fLine.substr( separator + 1 ); Trim( dicoKey ); Trim( dicoVal ); if ( !dicoVal.empty() ) { dico.insert( std::make_pair( dicoKey, dicoVal ) ); } } } } else { return 1; } fStream.close(); return 0; }
19.380952
75
0.5905
i0r
fe56f15dbd08cf7765305e0e75f598e4fc09eefd
412
cpp
C++
tests/Classes/main.cpp
Derik-T/CPP
adf8ecb11af5bf96d04182b83ae3fa58ca64bc72
[ "MIT" ]
1
2021-08-28T23:51:52.000Z
2021-08-28T23:51:52.000Z
tests/Classes/main.cpp
Derik-T/CPP
adf8ecb11af5bf96d04182b83ae3fa58ca64bc72
[ "MIT" ]
null
null
null
tests/Classes/main.cpp
Derik-T/CPP
adf8ecb11af5bf96d04182b83ae3fa58ca64bc72
[ "MIT" ]
null
null
null
#include "main.h" int main(){ Pessoa Joao, Cleide, Claudo; Joao.setId(1); Joao.setIdade(10); Joao.setSexo(true); Joao.setUsaOculos(false); Joao.copy(Joao); std::cout << Cleide.getId() << std::endl; std::cout << Joao.getIdade() << std::endl; Produto cadeira, ventilador, amplificador; cadeira.fill(); cadeira.setEstoque(10); cadeira.show(); return 0; }
20.6
46
0.601942
Derik-T
fe5774f1eaa8e05d8a30c89117213c3acfbe2f4f
325
cpp
C++
cpp/lab27/inheritance/base_class_content_demonstration.cpp
PeganovAnton/cs-8th-grade
843a1e228473734728949ba286e04612165a163e
[ "AFL-3.0" ]
null
null
null
cpp/lab27/inheritance/base_class_content_demonstration.cpp
PeganovAnton/cs-8th-grade
843a1e228473734728949ba286e04612165a163e
[ "AFL-3.0" ]
null
null
null
cpp/lab27/inheritance/base_class_content_demonstration.cpp
PeganovAnton/cs-8th-grade
843a1e228473734728949ba286e04612165a163e
[ "AFL-3.0" ]
null
null
null
#include <iostream> #include <stdint.h> using namespace std; class A { int32_t a; }; class B: public A { int32_t a; }; int main() { cout << "sizeof(A): " << sizeof(A) << endl; // Печатает 4. // Печатает 8, так как содержит в том числе родительские члены. cout << "sizeof(B): " << sizeof(B) << endl; }
12.037037
65
0.584615
PeganovAnton
fe5b3b007b135d6ada318d38d9b1f06c10a789cf
460
cpp
C++
source/bullet.cpp
aronlebani/math-game
86d30e6a4a89167aefc618b76848566a65ecbcab
[ "MIT" ]
null
null
null
source/bullet.cpp
aronlebani/math-game
86d30e6a4a89167aefc618b76848566a65ecbcab
[ "MIT" ]
null
null
null
source/bullet.cpp
aronlebani/math-game
86d30e6a4a89167aefc618b76848566a65ecbcab
[ "MIT" ]
null
null
null
/* bullet.cpp Aron Lebani 29 March 2016 */ #include "../include/character.h" #include "../include/bullet.h" #include "../include/tools.h" bullet::bullet() { width = 13; height = 2; } void bullet::draw() { tools::printw(getY() , getX(), " x "); tools::printw(getY()+1, getX(), " x "); } void bullet::erase() { int i, j; for (i=0; i<height; i++) { for (j=0; j<width; j++) { tools::printw(getY()+i, getX()+j, " "); } } }
13.529412
50
0.526087
aronlebani
fe5cde8ce7a2c767d2d659c44a42580ee6d1de58
843
hpp
C++
src/Cheats.hpp
soni801/SourceAutoRecord
4bd9fde988eac425f86db050354db490dd3ed69b
[ "MIT" ]
42
2021-04-27T17:03:24.000Z
2022-03-03T18:56:13.000Z
src/Cheats.hpp
soni801/SourceAutoRecord
4bd9fde988eac425f86db050354db490dd3ed69b
[ "MIT" ]
43
2021-04-27T21:20:06.000Z
2022-03-22T12:45:46.000Z
src/Cheats.hpp
soni801/SourceAutoRecord
4bd9fde988eac425f86db050354db490dd3ed69b
[ "MIT" ]
29
2021-06-11T23:52:24.000Z
2022-03-30T14:33:46.000Z
#pragma once #include "Command.hpp" #include "Variable.hpp" class Cheats { public: void Init(); void Shutdown(); }; extern Variable sar_autorecord; extern Variable sar_autojump; extern Variable sar_jumpboost; extern Variable sar_aircontrol; extern Variable sar_duckjump; extern Variable sar_disable_challenge_stats_hud; extern Variable sar_disable_steam_pause; extern Variable sar_disable_no_focus_sleep; extern Variable sar_disable_progress_bar_update; extern Variable sar_prevent_mat_snapshot_recompute; extern Variable sar_challenge_autostop; extern Variable sar_show_entinp; extern Variable sv_laser_cube_autoaim; extern Variable ui_loadingscreen_transition_time; extern Variable ui_loadingscreen_fadein_time; extern Variable ui_loadingscreen_mintransition_time; extern Variable hide_gun_when_holding; extern Command sar_togglewait;
27.193548
52
0.867141
soni801
fe5d29f8c8be4678354d4a49e522903e96401a66
6,393
cpp
C++
src/pocketdb/models/dto/User.cpp
dmaltsiniotis/pocketnet.core
d7f763259330ae3dc6a02ec30ba2525ce2f6a5d9
[ "Apache-2.0" ]
1
2022-01-09T12:22:44.000Z
2022-01-09T12:22:44.000Z
src/pocketdb/models/dto/User.cpp
dmaltsiniotis/pocketnet.core
d7f763259330ae3dc6a02ec30ba2525ce2f6a5d9
[ "Apache-2.0" ]
null
null
null
src/pocketdb/models/dto/User.cpp
dmaltsiniotis/pocketnet.core
d7f763259330ae3dc6a02ec30ba2525ce2f6a5d9
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018-2021 Pocketnet developers // Distributed under the Apache 2.0 software license, see the accompanying // https://www.apache.org/licenses/LICENSE-2.0 #include <primitives/transaction.h> #include "pocketdb/models/dto/User.h" namespace PocketTx { User::User() : Transaction() { SetType(TxType::ACCOUNT_USER); } User::User(const std::shared_ptr<const CTransaction>& tx) : Transaction(tx) { SetType(TxType::ACCOUNT_USER); } shared_ptr <UniValue> User::Serialize() const { auto result = Transaction::Serialize(); result->pushKV("address", GetAddress() ? *GetAddress() : ""); result->pushKV("referrer", GetReferrerAddress() ? *GetReferrerAddress() : ""); result->pushKV("regdate", *GetTime()); result->pushKV("lang", (m_payload && m_payload->GetString1()) ? *m_payload->GetString1() : "en"); result->pushKV("name", (m_payload && m_payload->GetString2()) ? *m_payload->GetString2() : ""); result->pushKV("avatar", (m_payload && m_payload->GetString3()) ? *m_payload->GetString3() : ""); result->pushKV("about", (m_payload && m_payload->GetString4()) ? *m_payload->GetString4() : ""); result->pushKV("url", (m_payload && m_payload->GetString5()) ? *m_payload->GetString5() : ""); result->pushKV("pubkey", (m_payload && m_payload->GetString6()) ? *m_payload->GetString6() : ""); result->pushKV("donations", (m_payload && m_payload->GetString7()) ? *m_payload->GetString7() : ""); result->pushKV("birthday", 0); result->pushKV("gender", 0); result->pushKV("id", 0); return result; } void User::Deserialize(const UniValue& src) { Transaction::Deserialize(src); if (auto[ok, val] = TryGetStr(src, "address"); ok) SetAddress(val); if (auto[ok, val] = TryGetStr(src, "referrer"); ok) SetReferrerAddress(val); } void User::DeserializeRpc(const UniValue& src) { if (auto[ok, val] = TryGetStr(src, "r"); ok) SetReferrerAddress(val); GeneratePayload(); if (auto[ok, val] = TryGetStr(src, "l"); ok) m_payload->SetString1(val); else m_payload->SetString1("en"); if (auto[ok, val] = TryGetStr(src, "n"); ok) m_payload->SetString2(val); else m_payload->SetString2(""); if (auto[ok, val] = TryGetStr(src, "i"); ok) m_payload->SetString3(val); if (auto[ok, val] = TryGetStr(src, "a"); ok) m_payload->SetString4(val); if (auto[ok, val] = TryGetStr(src, "s"); ok) m_payload->SetString5(val); if (auto[ok, val] = TryGetStr(src, "k"); ok) m_payload->SetString6(val); if (auto[ok, val] = TryGetStr(src, "b"); ok) m_payload->SetString7(val); } shared_ptr <string> User::GetAddress() const { return m_string1; } void User::SetAddress(const string& value) { m_string1 = make_shared<string>(value); } shared_ptr <string> User::GetReferrerAddress() const { return m_string2; } void User::SetReferrerAddress(const string& value) { m_string2 = make_shared<string>(value); } // Payload getters shared_ptr <string> User::GetPayloadName() const { return GetPayload() ? GetPayload()->GetString2() : nullptr; } shared_ptr <string> User::GetPayloadAvatar() const { return GetPayload() ? GetPayload()->GetString3() : nullptr; } shared_ptr <string> User::GetPayloadUrl() const { return GetPayload() ? GetPayload()->GetString5() : nullptr; } shared_ptr <string> User::GetPayloadLang() const { return GetPayload() ? GetPayload()->GetString1() : nullptr; } shared_ptr <string> User::GetPayloadAbout() const { return GetPayload() ? GetPayload()->GetString4() : nullptr; } shared_ptr <string> User::GetPayloadDonations() const { return GetPayload() ? GetPayload()->GetString7() : nullptr; } shared_ptr <string> User::GetPayloadPubkey() const { return GetPayload() ? GetPayload()->GetString6() : nullptr; } void User::DeserializePayload(const UniValue& src) { Transaction::DeserializePayload(src); if (auto[ok, val] = TryGetStr(src, "lang"); ok) m_payload->SetString1(val); if (auto[ok, val] = TryGetStr(src, "name"); ok) m_payload->SetString2(val); else m_payload->SetString2(""); if (auto[ok, val] = TryGetStr(src, "avatar"); ok) m_payload->SetString3(val); if (auto[ok, val] = TryGetStr(src, "about"); ok) m_payload->SetString4(val); if (auto[ok, val] = TryGetStr(src, "url"); ok) m_payload->SetString5(val); if (auto[ok, val] = TryGetStr(src, "pubkey"); ok) m_payload->SetString6(val); if (auto[ok, val] = TryGetStr(src, "donations"); ok) m_payload->SetString7(val); } string User::BuildHash() { return BuildHash(true); } string User::BuildHash(bool includeReferrer) { std::string data; data += m_payload && m_payload->GetString2() ? *m_payload->GetString2() : ""; data += m_payload && m_payload->GetString5() ? *m_payload->GetString5() : ""; data += m_payload && m_payload->GetString1() ? *m_payload->GetString1() : ""; data += m_payload && m_payload->GetString4() ? *m_payload->GetString4() : ""; data += m_payload && m_payload->GetString3() ? *m_payload->GetString3() : ""; data += m_payload && m_payload->GetString7() ? *m_payload->GetString7() : ""; data += includeReferrer && GetReferrerAddress() ? *GetReferrerAddress() : ""; data += m_payload && m_payload->GetString6() ? *m_payload->GetString6() : ""; return Transaction::GenerateHash(data); } string User::PreBuildHash() { std::string data; data += m_payload && m_payload->GetString2() ? *m_payload->GetString2() : ""; data += m_payload && m_payload->GetString5() ? *m_payload->GetString5() : ""; data += m_payload && m_payload->GetString1() ? *m_payload->GetString1() : ""; data += m_payload && m_payload->GetString4() ? *m_payload->GetString4() : ""; data += m_payload && m_payload->GetString3() ? *m_payload->GetString3() : ""; data += m_payload && m_payload->GetString7() ? *m_payload->GetString7() : ""; data += GetReferrerAddress() ? *GetReferrerAddress() : ""; data += m_payload && m_payload->GetString6() ? *m_payload->GetString6() : ""; return data; } } // namespace PocketTx
45.992806
121
0.622712
dmaltsiniotis
fe5db8fca8964896b6e08062af6108e4f2d27de6
3,405
cpp
C++
src/picture_node.cpp
slaghuis/camera_lite
2b016006da58ce858895430a0f6b93fce9ee8576
[ "Apache-2.0" ]
null
null
null
src/picture_node.cpp
slaghuis/camera_lite
2b016006da58ce858895430a0f6b93fce9ee8576
[ "Apache-2.0" ]
null
null
null
src/picture_node.cpp
slaghuis/camera_lite
2b016006da58ce858895430a0f6b93fce9ee8576
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Xeni Robotics // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <inttypes.h> #include <memory> #include <chrono> #include <functional> #include <string> #include <vector> #include <sstream> #include "cv_bridge/cv_bridge.h" #include <opencv2/core/core.hpp> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/aruco.hpp> // #include <sensor_msgs/msg/compressed_image.hpp> #include <sensor_msgs/msg/image.hpp> #include <image_transport/image_transport.hpp> #include "std_msgs/msg/string.hpp" #include <geometry_msgs/msg/point_stamped.hpp> #include <message_filters/subscriber.h> #include <rclcpp/rclcpp.hpp> #include "camera_lite_interfaces/srv/save.hpp" #include "rclcpp/rclcpp.hpp" using namespace std::chrono_literals; using SavePicture = camera_lite_interfaces::srv::Save; class PictureNode : public rclcpp::Node { public: PictureNode() : Node("picture_node"), save_next_image_(false) { file_name_ = "undefined.jpg"; image_subscription_ = this->create_subscription<sensor_msgs::msg::Image>( "/camera/image_raw", 10, std::bind(&PictureNode::image_callback, this, std::placeholders::_1)); service_ = create_service<SavePicture>("camera/save_picture", std::bind(&PictureNode::handle_service, this, std::placeholders::_1, std::placeholders::_2)); } private: void image_callback(const sensor_msgs::msg::Image::SharedPtr msg) { RCLCPP_DEBUG(this->get_logger(), "Image received\t Timestamp: %u.%u sec ",msg->header.stamp.sec,msg->header.stamp.nanosec); if( save_next_image_ ) { // Frame acquisition cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, msg->encoding); } catch (cv_bridge::Exception& e) { RCLCPP_ERROR(this->get_logger(), "cv_bridge exception: %s",e.what()); return; } cv::Mat image; cv_ptr->image.copyTo(image); // BGR image coming from Raspberry Pi Camera via ROSinputVideo.retrieve(image); cv::imwrite(file_name_, image); // Save the image to a JPG file. save_next_image_ = false; } } void handle_service( const std::shared_ptr<SavePicture::Request> request, const std::shared_ptr<SavePicture::Response> response) { file_name_ = request->name; save_next_image_ = true; response->result = true; } // Private Variables /////////////////////////////////////////////////////////////////////////// rclcpp::Subscription<sensor_msgs::msg::Image>::SharedPtr image_subscription_; rclcpp::Service<SavePicture>::SharedPtr service_; bool save_next_image_; std::string file_name_; }; int main(int argc, char * argv[]) { rclcpp::init(argc, argv); rclcpp::spin(std::make_shared<PictureNode>()); rclcpp::shutdown(); return 0; }
29.868421
162
0.688106
slaghuis
fe5ec610ca9b45751b3be736b5e3e7e49f4bd5b0
917
cc
C++
coding/Reactor/v2/server_v2.cc
snow-tyan/learn-cpp
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
[ "MulanPSL-1.0" ]
null
null
null
coding/Reactor/v2/server_v2.cc
snow-tyan/learn-cpp
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
[ "MulanPSL-1.0" ]
null
null
null
coding/Reactor/v2/server_v2.cc
snow-tyan/learn-cpp
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
[ "MulanPSL-1.0" ]
null
null
null
#include "Acceptor.hh" #include "TCPConnection.hh" #include "EventLoop.hh" #include <iostream> #include <string> using namespace std; using namespace wd; // 普通函数版的回调函数 void onConnection(const TCPConnectionPtr &conn) { cout << conn->toString() << " has connected" << endl; conn->send("welcome to server"); } void onMessage(const TCPConnectionPtr &conn){ cout << "gets from client: " << conn->recv(); /** * 业务逻辑处理 * decode * compute * encode * **/ conn->send("wo hen shuai"); } void onClose(const TCPConnectionPtr &conn){ cout << ">> " << conn->toString() << " has disconnected" << endl; } int main() { Acceptor acceptor("172.25.40.81", 8888); acceptor.ready(); EventLoop event(acceptor); event.setConnectionCallback(onConnection); event.setMessageCallback(onMessage); event.setCloseCallback(onClose); event.loop(); return 0; }
20.840909
69
0.640131
snow-tyan
fe616724a851973743e3a32240e7c1bf79d58f65
25,891
cpp
C++
core/sql/langman/LmJavaExceptionReporter.cpp
anoopsharma00/incubator-trafodion
b109e2cf5883f8e763af853ab6fad7ce7110d9e8
[ "Apache-2.0" ]
null
null
null
core/sql/langman/LmJavaExceptionReporter.cpp
anoopsharma00/incubator-trafodion
b109e2cf5883f8e763af853ab6fad7ce7110d9e8
[ "Apache-2.0" ]
null
null
null
core/sql/langman/LmJavaExceptionReporter.cpp
anoopsharma00/incubator-trafodion
b109e2cf5883f8e763af853ab6fad7ce7110d9e8
[ "Apache-2.0" ]
null
null
null
/********************************************************************** // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ****************************************************************************** * * File: LmJavaExceptionReporter.cpp * Description: Java Exception Reporting Mechanism * * Created: 08/21/2003 * Language: C++ * * ****************************************************************************** */ #include "Platform.h" #include "lmjni.h" #include "LmJavaExceptionReporter.h" LmJavaExceptionReporter::LmJavaExceptionReporter(LmHandle jniEnv, LmLanguageManagerJava *langMan, LmResult &result, ComDiagsArea *diagsArea) : jniEnv_(jniEnv), langMan_(langMan), throwableClass_(NULL), throwableToStringId_(NULL), throwableGetCauseId_(NULL), exSQLClass_(NULL), exSQLStateId_(NULL), exErrorCodeId_(NULL), exNextExceptionId_(NULL), exMetValFailedClass_(NULL), exGetMethodName_(NULL), exGetSignature_(NULL) { if (loadThrowable(diagsArea) == LM_ERR || loadSQLException(diagsArea) == LM_ERR || loadMethodValidationFailedException(diagsArea) == LM_ERR) { result = LM_ERR; return; } } LmJavaExceptionReporter::~LmJavaExceptionReporter() { JNIEnv *jni = (JNIEnv*) jniEnv_; if (throwableClass_) jni->DeleteGlobalRef((jobject) throwableClass_); if (exSQLClass_) jni->DeleteGlobalRef((jobject) exSQLClass_); if (exMetValFailedClass_) jni->DeleteGlobalRef((jobject) exMetValFailedClass_); } // // loadThrowable: loads java.lang.Throwable and some of its methods. // LmResult LmJavaExceptionReporter::loadThrowable(ComDiagsArea *diagsArea) { JNIEnv *jni = (JNIEnv *) jniEnv_; jclass jc = NULL; jc = (jclass) jni->FindClass("java/lang/Throwable"); if (jc != NULL) { throwableClass_ = (jclass) jni->NewGlobalRef(jc); jni->DeleteLocalRef(jc); if (throwableClass_ != NULL) { throwableToStringId_ = jni->GetMethodID((jclass) throwableClass_, "toString", "()Ljava/lang/String;"); throwableGetCauseId_ = jni->GetMethodID((jclass) throwableClass_, "getCause", "()Ljava/lang/Throwable;"); } } // *** we tolerate throwableGetCauseId_ being NULL because // it is a new feature in JDK 1.4. Need to change this when // we move to JDK1.4 if (throwableClass_ == NULL || throwableToStringId_ == NULL) { *diagsArea << DgSqlCode(-LME_JVM_SYS_CLASS_ERROR) << DgString0("java.lang.Throwable"); return LM_ERR; } // We may get to this point with a pending exception in the JVM if // the getCause() method was not found. We will tolerate that // condition, clear the pending exception, and proceed. jni->ExceptionClear(); return LM_OK; } // // loadSQLException: Loads java.sql.SQLException // LmResult LmJavaExceptionReporter::loadSQLException(ComDiagsArea *diagsArea) { jclass jc = NULL; JNIEnv *jni = (JNIEnv *) jniEnv_; jc = (jclass) jni->FindClass("java/sql/SQLException"); if (jc != NULL) { exSQLClass_ = (jclass) jni->NewGlobalRef(jc); jni->DeleteLocalRef(jc); if (exSQLClass_ != NULL) { exSQLStateId_ = jni->GetMethodID((jclass) exSQLClass_, "getSQLState", "()Ljava/lang/String;"); exErrorCodeId_ = jni->GetMethodID((jclass) exSQLClass_, "getErrorCode", "()I"); exNextExceptionId_ = jni->GetMethodID((jclass) exSQLClass_, "getNextException", "()Ljava/sql/SQLException;"); } } if (exSQLClass_ == NULL || exSQLStateId_ == NULL || exErrorCodeId_ == NULL || exNextExceptionId_ == NULL || jni->ExceptionOccurred()) { insertDiags(diagsArea, -LME_JVM_SYS_CLASS_ERROR, "java.sql.SQLException"); return LM_ERR; } return LM_OK; } // // loadMethodValidationFailedException: Loads org.trafodion.sql.udr // MethodValidationFailedException class // LmResult LmJavaExceptionReporter::loadMethodValidationFailedException( ComDiagsArea *diagsArea) { jclass jc = NULL; JNIEnv *jni = (JNIEnv *) jniEnv_; jc = (jclass) jni->FindClass("org/trafodion/sql/udr/MethodValidationFailedException"); if (jc != NULL) { exMetValFailedClass_ = (jclass) jni->NewGlobalRef(jc); jni->DeleteLocalRef(jc); if (exMetValFailedClass_ != NULL) { exGetMethodName_ = jni->GetMethodID((jclass) exMetValFailedClass_, "getMethodName", "()Ljava/lang/String;"); exGetSignature_ = jni->GetMethodID((jclass) exMetValFailedClass_, "getMethodSignature", "()Ljava/lang/String;"); } } if (exGetMethodName_ == NULL || exGetSignature_ == NULL || jni->ExceptionOccurred()) { insertDiags(diagsArea, -LME_JVM_SYS_CLASS_ERROR, "org.trafodion.sql.udr.MethodValidationFailedException"); return LM_ERR; } return LM_OK; } // // checkJVMException(): Raises an error for JVM's exception // if there is any and adds a condition for each JVM exception. // If 'exception' parameter is not NULL that will be used as exception. // // Returns: LM_OK if there is no exception // LM_ERR if there is an exception // LmResult LmJavaExceptionReporter::checkJVMException(ComDiagsArea *da, LmHandle exception) { JNIEnv *jni = (JNIEnv*)jniEnv_; jthrowable jex = NULL; LmResult result = LM_OK; // This boolean will track whether this method owns a reference to // the current exception object, or whether the caller owns the // reference. This method must release any of its own references // before it returns. NABoolean callerOwnsTheCurrentException; if (exception == NULL) { jex = jni->ExceptionOccurred(); callerOwnsTheCurrentException = FALSE; } else { jex = (jthrowable) exception; callerOwnsTheCurrentException = TRUE; } if (jex != NULL) { result = LM_ERR; } // // ExceptionDescribe() prints the exception information including // the stack trace to standard error. We want to do this so that // user can see the stack. But right now we see two errors if we // enable this // 1. ":" missing in exception message java.lang.NullPointerException // TEST501 // 2. 11229 error with message "Exception in thread "main" " // So we are commenting calls to ExceptionDescribe(). // // jni->ExceptionDescribe(); jni->ExceptionClear(); // Each iteration of this while loop will add a diags condition for // the current exception jex, then move jex to point to the next // exception in the chain. while (jex != NULL) { addJavaExceptionToDiags(jex, *da); jthrowable next = (jthrowable) getNextChainedException(jex); if (!callerOwnsTheCurrentException) { jni->DeleteLocalRef(jex); } jex = next; callerOwnsTheCurrentException = FALSE; } jni->ExceptionClear(); return result; } // // checkNewObjectExceptions(): checks for exceptions after a JNI // call to create a new Java Object, populate diags with exception // messages. // // Returns LM_OK if the jobj is not NULL and there is no // exception occurred // LM_ERR otherwise // LmResult LmJavaExceptionReporter::checkNewObjectExceptions(LmHandle jobj, ComDiagsArea *da) { JNIEnv *jni = (JNIEnv*)jniEnv_; jthrowable jt = jni->ExceptionOccurred(); // jni->ExceptionDescribe(); jni->ExceptionClear(); if(jt == NULL) { if(jobj) { return LM_OK; } else { *da << DgSqlCode(-LME_INTERNAL_ERROR) << DgString0(": a JNI error was encountered but no exception was found in the Java Virtual machine."); return LM_ERR; } } else { // LCOV_EXCL_START jstring jstr = (jstring) jni->CallObjectMethod(jt, (jmethodID) throwableToStringId_); if (jstr) { const char *msg = jni->GetStringUTFChars(jstr, NULL); if ((str_cmp(msg, "java.lang.OutOfMemoryError", 28) == 0)) { *da << DgSqlCode(-LME_JVM_OUT_OF_MEMORY) << DgString0(msg); } else { *da << DgSqlCode(-LME_JAVA_EXCEPTION) << DgString0(msg); } jni->ReleaseStringUTFChars(jstr, msg); jni->DeleteLocalRef(jstr); } else { *da << DgSqlCode(-LME_JAVA_EXCEPTION); } jthrowable next = (jthrowable) getNextChainedException(jt); if (next) { checkJVMException(da, next); jni->DeleteLocalRef(next); } jni->DeleteLocalRef(jt); jni->ExceptionClear(); return LM_ERR; // LCOV_EXCL_STOP } } // // addJavaExceptionToDiags(): Adds a single diags condition // describing an uncaught Java exception. // // Returns Nothing // void LmJavaExceptionReporter::addJavaExceptionToDiags(LmHandle throwable, ComDiagsArea &diags) { JNIEnv *jni = (JNIEnv *) jniEnv_; jthrowable t = (jthrowable) throwable; const char *msg; if (t) { if (!throwableToStringId_) { // We should never get here. For some reason the Throwable class // and its methods have not been loaded yet. msg = ": A Java exception was thrown but the Language Manager was unable to retrieve the message text."; diags << DgSqlCode(-LME_INTERNAL_ERROR) << DgString0(msg); } else { jstring jstr = (jstring) jni->CallObjectMethod(t, (jmethodID) throwableToStringId_); if (jstr != NULL) { msg = jni->GetStringUTFChars(jstr, NULL); diags << DgSqlCode(-LME_JVM_EXCEPTION) << DgString0(msg); jni->ReleaseStringUTFChars(jstr, msg); jni->DeleteLocalRef(jstr); } else { // An exception occurred but it contains no message msg = ": A Java exception with no message text was thrown."; diags << DgSqlCode(-LME_INTERNAL_ERROR) << DgString0(msg); } } } jni->ExceptionClear(); } // // getNextChainedException(): Return a reference to the // next chained Java exception. This method attempts to // avoid method lookups by name if possible, using cached // class references and method IDs if they have non-NULL values. // // Returns LmHandle to next exception // NULL if there is no next exception // LmHandle LmJavaExceptionReporter::getNextChainedException(LmHandle throwable) { if (throwable == NULL) { return NULL; } JNIEnv *jni = (JNIEnv *) jniEnv_; LmHandle result = NULL; jthrowable t = (jthrowable) throwable; jmethodID methodID; jclass classRef = jni->GetObjectClass((jobject) t); jni->ExceptionClear(); if (classRef) { // 1. Is this a SQLException? if (exSQLClass_ != NULL && jni->IsInstanceOf(t, (jclass) exSQLClass_) == JNI_TRUE) { methodID = (jmethodID) exNextExceptionId_; } else { methodID = (jmethodID) jni->GetMethodID(classRef, "getNextException", "()Ljava/sql/SQLException;"); } jni->ExceptionClear(); // 2. If not, does this object have a getCause() method? // The getCause() chaining framework is new in JDK 1.4 if (methodID == NULL) { if (throwableClass_ != NULL) { methodID = (jmethodID) throwableGetCauseId_; } else { methodID = (jmethodID) jni->GetMethodID(classRef, "getCause", "()Ljava/lang/Throwable;"); } jni->ExceptionClear(); } // 3. If not, does the object happen to have a getException() method? // Some Throwable subclasses supported this method for exception // chaining before the getCause() framework arrived in JDK 1.4. if (methodID == NULL) { methodID = (jmethodID) jni->GetMethodID(classRef, "getException", "()Ljava/lang/Throwable;"); jni->ExceptionClear(); } if (methodID) { result = (LmHandle) jni->CallObjectMethod(t, methodID); jni->ExceptionClear(); } jni->DeleteLocalRef(classRef); } // if (classRef) jni->ExceptionClear(); return result; } // // insertDiags() : Inserts conditions into diags area. // This method works only with error messages that take string // parameters. Typically this method is called when the calling // method wants to insert a condition as main SQLCode and one // condition for every exception in the exception chain. Currently // this method can accept at most 2 params to the condition item. // This method calls checkJVMException() to insert conditions // for JVM exceptions. // // Returns: LM_ERR unconditionally // // LCOV_EXCL_START LmResult LmJavaExceptionReporter::insertDiags(ComDiagsArea *diags, Int32 errCode, const char *arg1, const char *arg2, LmHandle jt) { Int32 numArgs; numArgs = (arg2 == NULL)? ((arg1 == NULL)? 0 : 1) : 2; // This is mainSQLCode in the diags area switch (numArgs) { case 0: { *diags << DgSqlCode(errCode); break; } case 1: { *diags << DgSqlCode(errCode) << DgString0(arg1); break; } case 2: { *diags << DgSqlCode(errCode) << DgString0(arg1) << DgString1(arg2); break; } } // Insert a diags condition for every exception in exception chain. checkJVMException(diags, jt); return LM_ERR; } // // checkGetMethodExceptions() : checks for possible exceptions after // a call to jni GetMethodID(). GetMethodID() can throw // NoSuchMethodError, ExceptionInInitializerError, or OutOfMemoryError. // LmResult LmJavaExceptionReporter::checkGetMethodExceptions(const char *routineName, const char *className, ComDiagsArea *da) { JNIEnv *jni = (JNIEnv*)jniEnv_; jthrowable jt; if ((jt = jni->ExceptionOccurred()) == NULL) { *da << DgSqlCode(-LME_INTERNAL_ERROR) << DgString0(": A JNI error was encountered but no exception was found in the Java Virtual Machine."); return LM_ERR; } // jni->ExceptionDescribe(); jni->ExceptionClear(); jstring jstr = (jstring) jni->CallObjectMethod(jt, (jmethodID) throwableToStringId_); if (jstr != NULL) { const char *msg = jni->GetStringUTFChars(jstr, NULL); if ((str_cmp(msg, "java.lang.ExceptionInInitializerError", 37)) == 0) { insertDiags(da, -LME_CLASS_INIT_FAIL, className, NULL, jt); } else if ((str_cmp(msg, "java.lang.OutOfMemoryError", 28) == 0)) { insertDiags(da, -LME_JVM_OUT_OF_MEMORY, NULL, NULL, jt); } else { insertDiags(da, -LME_ROUTINE_NOT_FOUND, routineName, className, jt); } jni->ReleaseStringUTFChars(jstr, msg); jni->DeleteLocalRef(jstr); } else { // Exception occurred, but no message *da << DgSqlCode(-LME_INTERNAL_ERROR) << DgString0(": Unknown error occurred."); } jni->DeleteLocalRef(jt); jni->ExceptionClear(); return LM_ERR; } // LCOV_EXCL_STOP // // processUserException(): Processes possible uncaught Java exceptions. // If no exception occurred, returns OK. In the event of an exception, // diagsArea is filled with proper error message. // // The SQLSTATE value is set according to section 13 'Status Code' of JRT. // // 38000 - For standard java exceptions. // 38??? - For SQL exceptions(java.sql.Exception) when Class = 38 // and Subclass != 000. So valid SQLSTATE values from Java method // are between 38001 to 38999 // 39001 - For all other SQL exceptions(java.sql.Exception) ie. for // SQL exceptions with invalid SQLSTATE value // LmResult LmJavaExceptionReporter::processUserException(LmRoutineJava *routine_handle, ComDiagsArea *da) { jthrowable jex; JNIEnv *jni = (JNIEnv*)jniEnv_; char errText[LMJ_ERR_SIZE_512]; // Get Java exception if one occurred. if ((jex = jni->ExceptionOccurred()) == NULL) return LM_OK; // jni->ExceptionDescribe(); jni->ExceptionClear(); jstring jstr = (jstring) jni->CallObjectMethod(jex, (jmethodID) throwableToStringId_); if (jstr != NULL) { // Record exception error text. const char *msg = jni->GetStringUTFChars(jstr, NULL); Int32 len = min(str_len(msg), (LMJ_ERR_SIZE_512 - 1)); str_cpy_all(errText, msg, len); errText[len] = '\0'; if (str_cmp(errText, "java.sql", 8) == 0 || str_cmp(errText, "com.hp.jdbc.HPT4Exception", 25) == 0) { reportUserSQLException(jex, errText, da); } else if (routine_handle->isInternalSPJ()) { reportInternalSPJException(jex, errText, da); } else { *da << DgSqlCode(-LME_JAVA_EXCEPTION) << DgString0(errText); } jni->ReleaseStringUTFChars(jstr, msg); jni->DeleteLocalRef(jstr); } // Now insert the remaining error messages into diags jthrowable next = (jthrowable) getNextChainedException(jex); if (next) { checkJVMException(da, next); jni->DeleteLocalRef(next); } jni->DeleteLocalRef(jex); jni->ExceptionClear(); return LM_ERR; } // // reportUserSQLException(): populates the diags for SQLException. // Look at the comments of processUserException(). // void LmJavaExceptionReporter::reportUserSQLException(LmHandle jt, char *errText, ComDiagsArea *da) { JNIEnv *jni = (JNIEnv*)jniEnv_; jthrowable jex = (jthrowable) jt; char sqlState[6]; // Get the error code, SQLState Int32 errcode = (Int32) jni->CallIntMethod((jobject)jex, (jmethodID)exErrorCodeId_); jstring jsstate = (jstring) jni->CallObjectMethod(jex, (jmethodID)exSQLStateId_); if (jsstate != NULL) { const char *sstate = jni->GetStringUTFChars(jsstate, NULL); // Check for the validity of the SQLSTATE if (sstate != NULL && str_len(sstate) >= 5 && str_cmp(&sstate[0], "38", 2) == 0 && str_cmp(&sstate[2], "000", 3) != 0) { // Valid sqlstate. Report this as LME_CUSTOM_ERROR // with sqlState as SQLSTATE of LME_CUSTOM_ERROR. str_cpy_all(sqlState, sstate, 5); sqlState[5] = '\0'; *da << DgSqlCode(-LME_CUSTOM_ERROR) << DgString0(errText) << DgString1(sqlState) << DgCustomSQLState(sqlState); } else { // Invalid sqlstate. Report this value wrapped in the message // of LME_JAVA_SQL_EXCEPTION_INVALID. The sqlstate of the reported // message is 39001. Int32 min_len = min(str_len(sstate), 5); // interested only upto 5 chars str_cpy_all(sqlState, sstate, min_len); sqlState[min_len] = '\0'; *da << DgSqlCode(-LME_JAVA_SQL_EXCEPTION_INVALID) << DgInt0(errcode) << DgString0(sqlState) << DgString1(errText); } if (sstate != NULL) jni->ReleaseStringUTFChars(jsstate, sstate); jni->DeleteLocalRef(jsstate); } // if (jsstate != NULL) else { // sqlstate is not specified. // LME_JAVA_SQL_EXCEPTION_INVALID is reported sqlState[0] = '\0'; *da << DgSqlCode(-LME_JAVA_SQL_EXCEPTION_INVALID) << DgInt0(errcode) << DgString0(sqlState) << DgString1(errText); } return; } // // reportInternalSPJException(): populates the diags for // MethodValidationException. This exception is thrown by // the internal SPJ VALIDATEROUTINE. // // LCOV_EXCL_START void LmJavaExceptionReporter::reportInternalSPJException(LmHandle jt, char *errText, ComDiagsArea *da) { JNIEnv *jni = (JNIEnv*)jniEnv_; jthrowable jex = (jthrowable) jt; jstring metNameStr = NULL; jstring metSigStr = NULL; if (exMetValFailedClass_ != NULL && jni->IsInstanceOf(jex, (jclass) exMetValFailedClass_)) { metNameStr = (jstring) jni->CallObjectMethod(jex, (jmethodID) exGetMethodName_); metSigStr = (jstring) jni->CallObjectMethod(jex, (jmethodID) exGetSignature_); } if (metNameStr != NULL && metSigStr != NULL) { const char *metName = jni->GetStringUTFChars(metNameStr, NULL); const char *metSig = jni->GetStringUTFChars(metSigStr, NULL); LmJavaSignature lmSig(metSig, collHeap()); ComSInt32 unpackedSigSize = lmSig.getUnpackedSignatureSize(); ComUInt32 totLen = str_len(metName) + unpackedSigSize; char *signature = new (collHeap()) char[totLen + 1]; sprintf(signature, "%s", metName); lmSig.unpackSignature(signature + str_len(metName)); signature[totLen] = '\0'; *da << DgSqlCode(-LME_VALIDATION_FAILED) << DgString0(signature) << DgString1(errText); jni->ReleaseStringUTFChars(metNameStr, metName); jni->DeleteLocalRef(metNameStr); jni->ReleaseStringUTFChars(metSigStr, metSig); jni->DeleteLocalRef(metSigStr); if (signature) NADELETEBASIC(signature, collHeap()); } else { *da << DgSqlCode(-LME_JAVA_EXCEPTION) << DgString0(errText); if (metNameStr) jni->DeleteLocalRef(metNameStr); if (metSigStr) jni->DeleteLocalRef(metSigStr); } } // LCOV_EXCL_STOP // // reportJavaObjException(): populates the diags for // a return status returned in an LmUDRObjMethodInvoke.ReturnInfo // object used in the Java object interface void LmJavaExceptionReporter::processJavaObjException( LmHandle returnInfoObj, int returnStatus, int callPhase, const char *errText, const char *udrName, ComDiagsArea *da) { if (da) { JNIEnv *jni = (JNIEnv*)jniEnv_; const char *sqlState = NULL; const char *message = NULL; jobject jniResult = (jobject) returnInfoObj; jstring returnedSQLState = static_cast<jstring>(jni->GetObjectField( jniResult, (jfieldID) langMan_->getReturnInfoSQLStateField())); jstring returnedMessage = static_cast<jstring>(jni->GetObjectField( jniResult, (jfieldID) langMan_->getReturnInfoMessageField())); if (returnedSQLState != NULL) sqlState = jni->GetStringUTFChars(returnedSQLState, NULL); if (returnedMessage != NULL) message = jni->GetStringUTFChars(returnedMessage, NULL); if (sqlState || message) { const char *diagsMessage = (message ? message : "no message provided"); const char *diagsSQLState = (sqlState ? sqlState : "no SQLSTATE provided"); // Check the returned SQLSTATE value and raise appropriate // SQL code. Valid SQLSTATE values begin with "38" except "38000" if (sqlState && (strncmp(diagsSQLState, "38", 2) == 0) && (strncmp(diagsSQLState, "38000", 5) != 0)) { *da << DgSqlCode(-LME_CUSTOM_ERROR) << DgString0(diagsMessage) << DgString1(diagsSQLState); *da << DgCustomSQLState(diagsSQLState); } else { *da << DgSqlCode(-LME_UDF_ERROR) << DgString0(udrName) << DgString1(diagsSQLState) << DgString2(diagsMessage); } } else { // Report the return status as an internal error, since // we didn't get a UDRException. This should be rare, since // Java exceptions are caught above. char buf1[4]; snprintf(buf1, sizeof(buf1), "%d", callPhase); char buf2[80]; snprintf(buf2, sizeof(buf2), "Return status %d from JNI call", returnStatus); *da << DgSqlCode(-LME_OBJECT_INTERFACE_ERROR) << DgString0(udrName) << DgString1(buf1) << DgString2(errText) << DgString3(buf2); } if (sqlState) jni->ReleaseStringUTFChars(returnedSQLState, sqlState); if (message) jni->ReleaseStringUTFChars(returnedMessage, message); if (returnedSQLState) jni->DeleteLocalRef(returnedSQLState); if (returnedMessage) jni->DeleteLocalRef(returnedMessage); } }
29.288462
112
0.610791
anoopsharma00
fe61dd8216e41d64b8a9224fb71ca1f5dc1a64d5
4,922
hpp
C++
ThirdParty-mod/java2cpp/javax/crypto/spec/DESKeySpec.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/javax/crypto/spec/DESKeySpec.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/javax/crypto/spec/DESKeySpec.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: javax.crypto.spec.DESKeySpec ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_DECL #define J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace security { namespace spec { class KeySpec; } } } } #include <java/lang/Object.hpp> #include <java/security/spec/KeySpec.hpp> namespace j2cpp { namespace javax { namespace crypto { namespace spec { class DESKeySpec; class DESKeySpec : public object<DESKeySpec> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_FIELD(0) explicit DESKeySpec(jobject jobj) : object<DESKeySpec>(jobj) { } operator local_ref<java::lang::Object>() const; operator local_ref<java::security::spec::KeySpec>() const; DESKeySpec(local_ref< array<jbyte,1> > const&); DESKeySpec(local_ref< array<jbyte,1> > const&, jint); local_ref< array<jbyte,1> > getKey(); static jboolean isParityAdjusted(local_ref< array<jbyte,1> > const&, jint); static jboolean isWeak(local_ref< array<jbyte,1> > const&, jint); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > DES_KEY_LEN; }; //class DESKeySpec } //namespace spec } //namespace crypto } //namespace javax } //namespace j2cpp #endif //J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_IMPL #define J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_IMPL namespace j2cpp { javax::crypto::spec::DESKeySpec::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } javax::crypto::spec::DESKeySpec::operator local_ref<java::security::spec::KeySpec>() const { return local_ref<java::security::spec::KeySpec>(get_jobject()); } javax::crypto::spec::DESKeySpec::DESKeySpec(local_ref< array<jbyte,1> > const &a0) : object<javax::crypto::spec::DESKeySpec>( call_new_object< javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME, javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(0), javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } javax::crypto::spec::DESKeySpec::DESKeySpec(local_ref< array<jbyte,1> > const &a0, jint a1) : object<javax::crypto::spec::DESKeySpec>( call_new_object< javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME, javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(1), javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(1) >(a0, a1) ) { } local_ref< array<jbyte,1> > javax::crypto::spec::DESKeySpec::getKey() { return call_method< javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME, javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(2), javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(2), local_ref< array<jbyte,1> > >(get_jobject()); } jboolean javax::crypto::spec::DESKeySpec::isParityAdjusted(local_ref< array<jbyte,1> > const &a0, jint a1) { return call_static_method< javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME, javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(3), javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(3), jboolean >(a0, a1); } jboolean javax::crypto::spec::DESKeySpec::isWeak(local_ref< array<jbyte,1> > const &a0, jint a1) { return call_static_method< javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME, javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(4), javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(4), jboolean >(a0, a1); } static_field< javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME, javax::crypto::spec::DESKeySpec::J2CPP_FIELD_NAME(0), javax::crypto::spec::DESKeySpec::J2CPP_FIELD_SIGNATURE(0), jint > javax::crypto::spec::DESKeySpec::DES_KEY_LEN; J2CPP_DEFINE_CLASS(javax::crypto::spec::DESKeySpec,"javax/crypto/spec/DESKeySpec") J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,0,"<init>","([B)V") J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,1,"<init>","([BI)V") J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,2,"getKey","()[B") J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,3,"isParityAdjusted","([BI)Z") J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,4,"isWeak","([BI)Z") J2CPP_DEFINE_FIELD(javax::crypto::spec::DESKeySpec,0,"DES_KEY_LEN","I") } //namespace j2cpp #endif //J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
30.012195
108
0.70195
kakashidinho
fe63bbd69243f9a5859bca41001b24b435590254
7,572
cc
C++
Source/MDEC.cc
dkoluris/pseudo
07a8d287f6b22ba70b73a012f560ff4a68dab2c3
[ "Apache-2.0" ]
40
2018-04-04T05:36:58.000Z
2021-11-15T02:03:05.000Z
Source/MDEC.cc
dkoluris/PSeudo
07a8d287f6b22ba70b73a012f560ff4a68dab2c3
[ "Apache-2.0" ]
1
2019-07-24T01:37:12.000Z
2019-09-10T07:58:12.000Z
Source/MDEC.cc
dkoluris/pseudo
07a8d287f6b22ba70b73a012f560ff4a68dab2c3
[ "Apache-2.0" ]
4
2018-09-19T10:29:44.000Z
2020-06-18T22:24:32.000Z
#include "Global.h" #define MAKERGB15(R, G, B) ((((R)>>3)<<10)|(((G)>>3)<<5)|((B)>>3)) #define ROUND(c) rtbl[(c) + 128 + 256] #define RGB15CL(N) IMAGE[N] = MAKERGB15(ROUND(GETY + R), ROUND(GETY + G), ROUND(GETY + B)); #define RGB24CL(N) IMAGE[N+ 2] = ROUND(GETY + R); IMAGE[N+ 1] = ROUND(GETY + G); IMAGE[N+ 0] = ROUND(GETY + B); #define MULR(A) (((sw)0x0000059B * (A)) >> 10) #define MULG(A) (((sw)0xFFFFFEA1 * (A)) >> 10) #define MULB(A) (((sw)0x00000716 * (A)) >> 10) #define MULF(A) (((sw)0xFFFFFD25 * (A)) >> 10) #define RUNOF(a) ((a)>>10) #define VALOF(a) ((sw)(((a)<<22)>>22)) CstrMotionDecoder mdec; void CstrMotionDecoder::reset() { rl = (uh *)&mem.ram.ptr[0x100000]; status = cmd = 0; for (sw k=0; k<256; k++) { rtbl[k+0x000] = 0; rtbl[k+0x100] = k; rtbl[k+0x200] = 255; } } void CstrMotionDecoder::write(uw addr, uw data) { switch(addr & 0xf) { case 0: cmd = data; if ((data&0xf5ff0000) == 0x30000000) { len = data&0xffff; } return; case 4: if (data & 0x80000000) { reset(); } return; } printx("/// PSeudo MDEC write: 0x%08x <- 0x%08x", addr, data); } uw CstrMotionDecoder::read(uw addr) { switch(addr & 0xf) { case 0: return cmd; case 4: return status; } printx("/// PSeudo MDEC read: 0x%08x", addr); return 0; } sw iq_y[64], iq_uv[64]; void CstrMotionDecoder::MacroBlock(sw *block, sw kh, sw sh) { for (sw k=0; k<8; k++, (sh) ? block+=8 : block++) { if((block[kh*1]| block[kh*2]| block[kh*3]| block[kh*4]| block[kh*5]| block[kh*6]| block[kh*7]) == 0) { block[kh*0]= block[kh*1]= block[kh*2]= block[kh*3]= block[kh*4]= block[kh*5]= block[kh*6]= block[kh*7]= block[kh*0]>>sh; continue; } sw z10 = block[kh*0]+block[kh*4]; sw z11 = block[kh*0]-block[kh*4]; sw z13 = block[kh*2]+block[kh*6]; sw z12 = block[kh*2]-block[kh*6]; z12 = ((z12*362)>>8)-z13; sw tmp0 = z10+z13; sw tmp3 = z10-z13; sw tmp1 = z11+z12; sw tmp2 = z11-z12; z13 = block[kh*3]+block[kh*5]; z10 = block[kh*3]-block[kh*5]; z11 = block[kh*1]+block[kh*7]; z12 = block[kh*1]-block[kh*7]; sw z5 = (((z12-z10)*473)>>8); sw tmp7 = z11+z13; sw tmp6 = (((z10)*669)>>8)+z5 -tmp7; sw tmp5 = (((z11-z13)*362)>>8)-tmp6; sw tmp4 = (((z12)*277)>>8)-z5 +tmp5; block[kh*0] = (tmp0+tmp7)>>sh; block[kh*7] = (tmp0-tmp7)>>sh; block[kh*1] = (tmp1+tmp6)>>sh; block[kh*6] = (tmp1-tmp6)>>sh; block[kh*2] = (tmp2+tmp5)>>sh; block[kh*5] = (tmp2-tmp5)>>sh; block[kh*4] = (tmp3+tmp4)>>sh; block[kh*3] = (tmp3-tmp4)>>sh; } } void CstrMotionDecoder::idct(sw *block, sw k) { if (k == 0) { sw val = block[0]>>5; for (sw i=0; i<64; i++) { block[i] = val; } return; } MacroBlock(block, 8, 0); MacroBlock(block, 1, 5); } void CstrMotionDecoder::TabInit(sw *iqtab, ub *iq_y) { for (sw i=0; i<64; i++) { iqtab[i] = iq_y[i]*aanscales[zscan[i]]>>12; } } uh *CstrMotionDecoder::rl2blk(sw *blk, uh *mdec_rl) { sw k,q_scale,rl; sw *iqtab; memset(blk, 0, 6*64*4); iqtab = iq_uv; for (sw i=0; i<6; i++) { if (i>1) iqtab = iq_y; rl = *mdec_rl++; q_scale = rl>>10; blk[0] = iqtab[0]*VALOF(rl); k = 0; for(;;) { rl = *mdec_rl++; if (rl==0xfe00) break; k += (rl>>10)+1;if (k > 63) break; blk[zscan[k]] = (iqtab[k] * q_scale * VALOF(rl)) >> 3; } idct(blk, k+1); blk+=64; } return mdec_rl; } void CstrMotionDecoder::Yuv15(sw *Block, uh *IMAGE) { sw GETY; sw CB,CR,R,G,B; sw *YYBLK = Block + 64 * 2; sw *CBBLK = Block; sw *CRBLK = Block + 64; for (sw Y=0; Y<16; Y+=2, CRBLK+=4, CBBLK+=4, YYBLK+=8, IMAGE+=24) { if (Y == 8) { YYBLK = YYBLK + 64; } for (sw X=0; X<4; X++, IMAGE+=2, CRBLK++, CBBLK++, YYBLK+=2) { CR = *CRBLK; CB = *CBBLK; R = MULR(CR); G = MULG(CB) + MULF(CR); B = MULB(CB); GETY = YYBLK[0]; RGB15CL(0x00); GETY = YYBLK[1]; RGB15CL(0x01); GETY = YYBLK[8]; RGB15CL(0x10); GETY = YYBLK[9]; RGB15CL(0x11); CR = *(CRBLK + 4); CB = *(CBBLK + 4); R = MULR(CR); G = MULG(CB) + MULF(CR); B = MULB(CB); GETY = YYBLK[64 + 0]; RGB15CL(0x08); GETY = YYBLK[64 + 1]; RGB15CL(0x09); GETY = YYBLK[64 + 8]; RGB15CL(0x18); GETY = YYBLK[64 + 9]; RGB15CL(0x19); } } } void CstrMotionDecoder::Yuv24(sw *Block, ub *IMAGE) { sw GETY; sw CB, CR, R, G, B; sw *YYBLK = Block + 64 * 2; sw *CBBLK = Block; sw *CRBLK = Block + 64; for (sw Y=0; Y<16; Y+=2, CRBLK+=4, CBBLK+=4, YYBLK+=8, IMAGE+=24*3) { if (Y == 8) { YYBLK = YYBLK + 64; } for (sw X=0; X<4; X++, IMAGE+=2*3, CRBLK++, CBBLK++, YYBLK+=2) { CR = *CRBLK; CB = *CBBLK; R = MULR(CR); G = MULG(CB) + MULF(CR); B = MULB(CB); GETY = YYBLK[0]; RGB24CL(0x00 * 3); GETY = YYBLK[1]; RGB24CL(0x01 * 3); GETY = YYBLK[8]; RGB24CL(0x10 * 3); GETY = YYBLK[9]; RGB24CL(0x11 * 3); CR = *(CRBLK + 4); CB = *(CBBLK + 4); R = MULR(CR); G = MULG(CB) + MULF(CR); B = MULB(CB); GETY = YYBLK[64 + 0]; RGB24CL(0x08 * 3); GETY = YYBLK[64 + 1]; RGB24CL(0x09 * 3); GETY = YYBLK[64 + 8]; RGB24CL(0x18 * 3); GETY = YYBLK[64 + 9]; RGB24CL(0x19 * 3); } } } void CstrMotionDecoder::executeDMA(CstrBus::castDMA *dma) { ub *p = &mem.ram.ptr[dma->madr&(mem.ram.size-1)]; sw z = (dma->bcr>>16)*(dma->bcr&0xffff); switch (dma->chcr&0xfff) { case 0x200: { sw blocksize, blk[384]; uh *im = (uh *)p; if (cmd&0x08000000) { blocksize = 256; } else { blocksize = 384; } for (; z>0; z-=blocksize/2, im+=blocksize) { rl = rl2blk(blk, rl); if (cmd&0x8000000) { Yuv15(blk, im); } else { Yuv24(blk, (ub *)im); } } break; } case 0x201: if (cmd == 0x40000001) { TabInit(iq_y, p); TabInit(iq_uv, p+64); } if ((cmd&0xf5ff0000) == 0x30000000) { rl = (uh *)p; } break; } }
26.200692
111
0.410195
dkoluris
fe646b8b115e272243b266d33377e414942eb92c
24,117
hpp
C++
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/VbViewInfo/vbViewInfo.hpp
longxingtianxiaShuai/specialView
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
[ "MIT" ]
1
2020-11-21T03:54:34.000Z
2020-11-21T03:54:34.000Z
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/VbViewInfo/vbViewInfo.hpp
longxingtianxiaShuai/specialView
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
[ "MIT" ]
null
null
null
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/VbViewInfo/vbViewInfo.hpp
longxingtianxiaShuai/specialView
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
[ "MIT" ]
3
2017-12-14T00:52:03.000Z
2019-08-08T22:25:04.000Z
#pragma once #include "Quaternion.hpp" #include "vbConfiguration.hpp" #include "vbGeometry.hpp" #include "vbCamera.hpp" #include "vbTrackCameraControl.hpp" #include "vbFPSCameraControl.hpp" #include "vbMoveOrbitZoomCameraControl.hpp" #include "vbMovingForwardCameraControl.hpp" #include "vbHorizontalPanCameraControl.hpp" #include "vbFreeCameraControl.hpp" #include "vbAnimationCameraControl.hpp" #include "vbPerspectiveProjection.hpp" #include "vbOrthogonalProjection.hpp" #include <vector> using std::vector; class vbViewInfo { public: vbViewInfo(); ~vbViewInfo(); enum ProjectionMode { PROJECTION_PERSPECTIVE=0, PROJECTION_ORTHO, PROJECTION_MODE_NONE }; enum NavigationMode { NAVIGATION_3D=0, NAVIGATION_2D, NAVIGATION_WALK, NAVIGATION_ME, NAVIGATION_2D_FIXED, //NAVIGATION_2D는 확대 축소 이동이 되지만 이것은 고정 뷰이다. NAVIGATION_ENVRN //환경맵용 고정 카메라 }; enum NavigationMode3D { NAVIGATION_3D_NONE=0, NAVIGATION_3D_ORBIT_V, NAVIGATION_3D_ORBIT_H, NAVIGATION_3D_PANZOOM, NAVIGATION_3D_ROTATEZOOM, NAVIGATION_3D_PAN, NAVIGATION_3D_ZOOM, NAVIGATION_3D_FIXED_V, //고정 상태에서 Pitch 제어(Vertical) NAVIGATION_3D_FIXED_H, //고정 상태에서 Yaw 제어 NAVIGATION_3D_ELEVATION, NAVIGATION_3D_FORWARD, NAVIGATION_3D_ZOOMHROTATION }; enum CameraAniMode { CAMERA_ANI_NONE = 0, CAMERA_ANI_JUMPPAN = 1, CAMERA_ANI_JUMPZOOM = 2, CAMERA_ANI_JUMPPANROT = 3, CAMERA_ANI_3D2WALK = 4, CAMERA_ANI_3DTO2D = 5, CAMERA_ANI_2DTO3D = 6, CAMERA_ANI_DEVICE_ROT = 7, CAMERA_ANI_FIXEDFREE = 8, CAMERA_ANI_YAW_ROTATE = 9, }; enum vbViewControlSet { vbViewControlSetDefaultLBS =0, //PISA vbViewControlSetYawPitch =1, //IIAC vbViewControlSetStandardI =2, //STD1 vbViewControlSetGongVueTypeA=3, //GongVue Type A vbViewControlSetZoneView =4, //Zone view - Yaw only vbViewControlSetPalladiON =5, //PISA default에서 수직 제어 없애고 수평 연속 회전 되도록 함. vbViewControlSetPlanar3D =6, //2touch planar rotation vbViewControlSetFixedFPS =7 //임의 좌표에서 임의 방향을 바라 볼 수 있도록 함(터치로는 제어 안됨) }; struct vbScreenControlAreaParam { /* 0 - LControl left px offset from Left 1 - LControl right px offset from Left 2 - RControl left px offset from Right 3 - RControl right px offset from 4 - BControl top px offset from bottom 5 - BControl bottom px offset from bottom 6 - TControl top px offset from top 7 - TControl bottom px offset from top */ unsigned short area_param[8]; }; enum vbViewScreenControlArea { vbViewScreenControlAreaMid = 0, vbViewScreenControlAreaTop = 1, vbViewScreenControlAreaLeft = 2, vbViewScreenControlAreaRight = 3, vbViewScreenControlAreaBottom = 4 }; protected: //vbConfiguration vbConfiguration* m_pConf; vbScreenControlAreaParam m_area_param; //GroundPlane vbPlane m_ground_plane; //Pan Valid range float m_pan_valid_ratio; //View Matrix mat4 m_view_matrix; //Projection Matrix mat4 m_prj_matrix; //view matrix X projection matrix - for Window/World conversion mat4 m_view_prj_matrix; bool m_bViewUpdated; //Projection mode ProjectionMode m_projection_mode; //Projection mode float m_min_near_clip; float m_rad_bounding_sphere; vec3 m_bounding_center; vec3 m_bound_min; vec3 m_bound_max; //Camera vbCamera m_Camera; //Move vbFPSCameraControl m_CameraFPSControl; vbMoveOrbitZoomCameraControl m_CameraZoomControl; vbHorizontalPanCameraControl m_CameraHPanControl; vbMovingForwardCameraControl m_CameraForwardControl; //Rotation vbTrackCameraControl m_CameraTrackControl; vbFreeCameraControl m_CameraFreeControl; //Animation vbAnimationCameraControl m_CameraAnimationControl; //Projection vbPerspectiveProjection m_CameraPerspective; vbOrthogonalProjection m_CameraOrthogonal; float m_cam_fMaxDistRatioBBSize; float m_cam_fMaxPanRatioToBSphereRad; bool m_cam_bJumpZoomed; //Environment sphere float m_cam_fEnvSphereRadius; //Camera animation CameraAniMode m_cam_ani_mode; float m_cam_jumpzoom_ratio; bool m_cam_jumpzoom_with_jumppan; // bool m_bBrokePan; bool m_bBrokeZoom; bool m_bBrokeRotate; //Navigation NavigationMode m_cam_navi_mode; //camera navigation mode NavigationMode m_cam_navi_mode_backup; //camera navigation mode NavigationMode3D m_cam_navi_3d_mode; // bool m_bNavigation; ivec2 m_DownPos_prev; vec3 m_cam_reference3D_first; //Reference 3d position 1 vec3 m_cam_reference3D_second; //Reference 3d position 2 //3D View camera backup Quaternion m_cam_3D_backup_rotation; vec3 m_cam_3D_backup_orbit_cntr; float m_cam_3D_backup_distance; //Turn angle float m_fDeviceAngle; vbViewDirection m_eViewDirection; //View mode vbViewControlSet m_eViewControlSet; float m_fRotateAreaRatio; //화면의 아래쪽에서 몇 %까지 수평 회전 영역에 쓸 것인지 (0~1) public: CameraAniMode GetAniMode() { return m_cam_ani_mode; }; vbMoveOrbitZoomCameraControl* GetCameraControl_OrbitZoom() { return &m_CameraZoomControl; } vbTrackCameraControl* GetCameraTrackControl() { return &m_CameraTrackControl; } //Turn vbViewDirection GetViewTurnDirection() { return m_eViewDirection; }; void SetViewTurnDirection(vbViewDirection dir, bool bAnimating=false); float GetDeviceAngle() { return m_fDeviceAngle; }; void UpdateDeviceAngleDeg(); ivec2 ConvertToRotatedDeviceCoord(ivec2 tPos); //Init void InitializeViewInfo(int width, int height, vbConfiguration* pConf); void ReloadConfiguration(); //Viewport void SetScreenSize(ivec2 screen_size); ivec2 GetScreenSize() ; ////////////////////////////////////// Projection - vbViewInfoProjection.cpp //View matrix mat4* GetViewMatrix() { return &m_view_matrix; } float const* GetViewMatrixPointer() { return m_view_matrix.Pointer(); } void SetViewMatrix(mat4 view_mat) { m_view_matrix = view_mat; } void UpdateViewMatrix(); //Projection matrix mat4* GetProjectionMatrix() { return &m_prj_matrix; } float const* GetProjectionMatrixPointer() { return m_prj_matrix.Pointer(); } void SetProjectionMatrix(mat4 view_mat) { m_prj_matrix = view_mat; } void UpdateProjectionMatrix(); ivec2 WorldToWindow(vec3 world_pt); void WindowToWorld(ivec2 win_pos, vec3& near_pt, vec3& far_pt); mat4* GetViewProjectionMatrix() { return &m_view_prj_matrix; } bool IsViewUpdated() { return m_bViewUpdated; } void SetViewUpdated(bool bUpdated) { m_bViewUpdated = bUpdated; } //Projection mode ProjectionMode GetProjectionMode() { return m_projection_mode; } void SetProjectionMode(ProjectionMode mode) { m_projection_mode = mode; } //Perspective void SetPerspectiveParameters(float* perspective_param); void SetPerspectiveParameters(float fovy, float aspect, float near, float far); const float* GetPerspectiveParameters(); void UpdateNearFarClip(); public: //Orthogonal void SetOrthogonalParameters(float left, float right, float bottom, float top, float near, float far); const float* GetOrthogonalParameters(); ////////////////////////////////////// Projection - vbViewInfoProjection.cpp ////////////////////////////////////// Navigation - vbViewInfoNavi.cpp //Fit void FitAABBtoScreen(bool bBoundMinMaxDist=false); void FitAABBtoVertices(std::vector<vec3>& target_vtx, bool bBoundMinMaxDist=false); //Ground void SetGroundPlane(vbPlane ground_plane) { m_ground_plane = ground_plane; } vbPlane GetGroundPlane() { return m_ground_plane; } float GetPanValidRatio() { return m_pan_valid_ratio; } void SetPanValidRatio(float pRatio) { m_pan_valid_ratio = pRatio; } void SetPanValidRange(vec3 min, vec3 max, float pRatio); //Orbit float GetTrackBallRatio(); void SetTrackBallRatio(float trRatio); void SetOrbitCenter(vec3 orbit_center); vec3 GetOrbitCenter(); void StartFreeRotation(ivec2 finger_pos); bool DoFreeRotation(ivec2 touchpoint); void StartRotation(ivec2 finger_pos); void StartHRotation(ivec2 finger_pos); void StartVRotation(ivec2 finger_pos); void StartYawPitchRotation(ivec2 finger_pos); bool DoOrbit(ivec2 touchpoint); //싱글터치, 초기 이동 방향에 따라 수직/수평 회전 bool DoYawRotation(ivec2 touchpoint); //수평 왕복 회전 bool DoContinuousYawRotation(ivec2 touchpoint); //수평 연속 회전 bool DoPitchRotation(ivec2 touchpoint); //수직 회전 bool DoYawPitchRotation(ivec2 touchpoint); //수직/수평 회전 bool DoLandscapeYawPitchRotation(ivec2 touchpoint); //VR용 수직,수평 회전 void EndRotation(); void JumpOrbit(ivec2 finger_pos); void SetHRotationRatio(float fVertialRatioFromBottom) { m_fRotateAreaRatio=fVertialRatioFromBottom;} float GetHRotationRatio() { return m_fRotateAreaRatio; } bool StartHRotationAnimation(float fStepYaw); bool EndHRotationAnimation(); //Panning void StartHPanning(ivec2 finger_pos); bool DoHPanning(ivec2 touchpoint); void EndHPanning(); void JumpPanning(ivec2 finger_pos); void JumpPanning(vec3 new_orbit_cntr); void JumpPanRotation(vec3 new_orbit_cntr, Quaternion new_orientation); void UpdateValidRange(vec3 bbMin, vec3 bbMax); //Zoom void StartZooming(ivec2 finger_pos); bool DoZooming(ivec2 touchpoint); void EndZooming(); void StartZooming2Pt(ivec2 finger_pos1,ivec2 finger_pos2); void StartZooming2PtEnvironment(ivec2 finger_pos1,ivec2 finger_pos2); bool DoZooming2Pt(ivec2 finger_pos1,ivec2 finger_pos2); bool DoZooming2PtEnvironment(ivec2 finger_pos1,ivec2 finger_pos2); void JumpZooming(ivec2 finger_pos); void SphereJumpZooming(ivec2 finger_pos); float GetPreviousZoomDistance(); void SetPreviousZoomDistance(float prevDist); //Pan & Zoom void StartPanZoom(ivec2 pos1, ivec2 pos2); bool DoPanZoom(ivec2 pos1, ivec2 pos2); void EndPanZoom(); //HRotate & Zoom void StartHRotateZoom(ivec2 pos1, ivec2 pos2); bool DoHRotateZoom(ivec2 pos1, ivec2 pos2); void EndHRotateZoom(); //Fixed Yaw & Pitch control void StartFixedYawPitchRotate(ivec2 pos1); void StartForwardZoom(ivec2 pos1, ivec2 pos2); void StartElevation(ivec2 pos1); bool DoFixedYawRotate(ivec2 pos1); bool DoFixedPitchRotate(ivec2 pos1); bool DoFixedYawPitchRotate(ivec2 pos1); bool DoForwardZoom(ivec2 pos1, ivec2 pos2); bool DoElevation(ivec2 pos1); void EndFixedYawPitchRotate(); void EndForwardZoom(); // void BrokeControl(bool bBrokePan, bool bBrokeZoom, bool bBrokeRotate); //Navi void InvalidateManipulation(); //2D-3D Camera void SetTopView(); void ReturnTo3DView(); //Walk float GetEyeHeight(); void SetEyeHeight(float eye_h); void InitWalk();//현재 회전 중심 위치로 내려가 걸어다닌다. void StartWalking(ivec2 finger_pos); bool DoWalking(ivec2 finger_pos); void EndWalking(); void SetWalkingCamera(vec3 pos, Quaternion dir); //FPS-Manipulation void StartFPS(); void EndFPS(); //Navigation mode bool IsNavigation() { return m_bNavigation; } void SetNavigation(bool bNavi) { m_bNavigation = bNavi; } NavigationMode GetNavigationMode() { return m_cam_navi_mode; } bool SetNavigationMode(NavigationMode nMode); void RecoverNavigationMode(); //Calculation vec3 MapToSphere(ivec2 touchpoint); vec3 GetRayFromCamera(ivec2 win_pos, vec3& fromPt); vec3 GetRayIntersectionWithGround(ivec2 ray_win_pos); //Ground = XY Plane ////////////////////////////////////// Navigation - vbViewInfoNavi.cpp ////////////////////////////////////// Camera - vbViewInfoCamera.cpp //camera position void SetCameraPosition(vec3 cam_pos); vec3 GetCameraPosition(); void UpdateCameraPositionFromOrbit();//Orbit center에서 지정된 distance에 지정 된 방향으로 위치 void UpdateCameraTargetPosition(); void UpdateOrbitCenterFromCamPosition(); void InitOrientation(bool bUpdateViewMat=true); void SetCameraPitchRatio(float pitch_ratio); float GetPitchRatio(); float GetPitchDegree(); float GetYawDegree(); void SetYawDegree(float fYaw); void SetYawDegree(vec3 dirYaw); void SetCamera(float cx, float cy, float cz, float yaw_deg_from_nZ, float pitch_deg_from_xz_plane, float fDist); //camera distance float GetCameraDistance(); void SetCameraDistance(float dist, bool bBoundMinMaxDistance=false); void SetCameraMaxDistanceRatioBBSize(float ratio) { m_cam_fMaxDistRatioBBSize = ratio; } void SetCameraMaxPanRatioBSphereRad(float ratio) { m_cam_fMaxPanRatioToBSphereRad = ratio; } void SetCameraMinMaxDistance(float fMinDistance, float fMaxDistance, bool bBoundMinMaxDist=false); //Zoom In/Out (Close to/ Far fromt Rot.Center) void MoveToRotationCenter(bool bToCenter); //Environmental map void SetEnvironmentalCamera(); //camera orientation void SetOrientation(Quaternion qtn); Quaternion GetOrientation(); //회전 쿼터니언을 반환한다. vec3 GetDirection(); //카메라의 방향 벡터 vec3 GetRight(); vec3 GetUp(); //Environment map float GetEnvironmentSphereRadius() { return m_cam_fEnvSphereRadius; } //camera fitting void FullExtendVertexVector(std::vector<vec3>& target_vtx, bool bBoundMinMaxDist=false); bool GetPerspectiveFittingCameraPosition(vec3 inputCameraDirection,/*대상을 바라보고 있을 카메라의 방향. 보통 현재 카메라의 방향*/ vec3 inputCameraUp,/*대상을 바라보고 있을 카메라의 Upvector.*/ float inputCameraFOV_Y_radian,/*카메라의 세로 방향 시야각*/ float inputCameraFOV_X_radian,/*카메라의 가로 방향 시야각*/ std::vector<vec3>& inputVts,/*Fitting 대상이 되는 점들*/ float inputFit_ratio,/* 1 : 화면에 꼭 맞게, 0.5 : 화면의 절반 크기에 맞게, 0.01 : 최소값*/ vec3& outputCameraPosition,/*카메라의 위치*/ vec3& outputOrbitCenter,//New orbit center bool& outVerticalFit,/*세로방향으로 맞췄는지 여부*/ float& outDistance, bool bBoundMinMaxDist=false);// //Orthogonal mode에서 Fitting bool GetOrthogonalFittingCameraPosition(vec3 inputCameraDirection/*대상을 바라보고 있을 카메라의 방향. 보통 현재 카메라의 방향*/, vec3 inputCameraUp/*대상을 바라보고 있을 카메라의 Upvector.*/, std::vector<vec3>& inputVts/*Fitting 대상이 되는 점들*/, float inputFit_ratio/* 1 : 화면에 꼭 맞게, 0.5 : 화면의 절반 크기에 맞게, 0.01 : 최소값*/, float inputDistance_for_ortho/*직교투영은 원근감이 없으므로, 거리에 상관없이 동일한 화면이 나오기 때문에 거리를 지정해야 한다*/, float inputViewAspectRatio/* Width/height*/, vec3& outputCameraPosition/*카메라의 위치*/, float& outputCamWidth/*카메라의 Orthogonal Width*/, float& outputCamHeight/*카메라의 Orthogonal Height*/, bool& outVerticalFit);/*세로방향으로 맞췄는지 여부*/ void UpdateCameraDistWithScreenCenter(bool bBoundMinMaxDist=false); // ////////////////////////////////////// Camera - vbViewInfoCamera.cpp //////////////////// RANGE PARAMETER const vbScreenControlAreaParam* GetScreenAreaParam() { return (const vbScreenControlAreaParam*)&m_area_param; } void SetScreenAreaParam(const vbScreenControlAreaParam* pParam); vbViewScreenControlArea IsScreenControlArea(ivec2 tPos); ////////////////////////////////////// Interaction - vbViewInfoFinger.cpp //Touch interaction bool SingleFingerUp(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown(ivec2 tPos, int tapCount); bool SingleFingerMove(ivec2 tPos, int tapCount); bool DoubleFingerUp(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); vbViewControlSet GetViewControlSet() { return m_eViewControlSet; } void SetViewControlSet(vbViewControlSet viewControlSet) { m_eViewControlSet = viewControlSet; } /////////////// ViewControlSet별 이벤트 처리 함수 //////////// Default bool SingleFingerUp_Default(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_Default(ivec2 tPos, int tapCount); bool SingleFingerMove_Default(ivec2 tPos, int tapCount); bool DoubleFingerUp_Default(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_Default(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_Default(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// Yaw & Pitch bool SingleFingerUp_YawPitch(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_YawPitch(ivec2 tPos, int tapCount); bool SingleFingerMove_YawPitch(ivec2 tPos, int tapCount); bool DoubleFingerUp_YawPitch(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_YawPitch(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_YawPitch(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// STD1 bool SingleFingerUp_STD1(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_STD1(ivec2 tPos, int tapCount); bool SingleFingerMove_STD1(ivec2 tPos, int tapCount); bool DoubleFingerUp_STD1(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_STD1(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_STD1(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// GongVueA bool SingleFingerUp_GongVueA(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_GongVueA(ivec2 tPos, int tapCount); bool SingleFingerMove_GongVueA(ivec2 tPos, int tapCount); bool DoubleFingerUp_GongVueA(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_GongVueA(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_GongVueA(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// ZoneView bool SingleFingerUp_ZoneView(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_ZoneView(ivec2 tPos, int tapCount); bool SingleFingerMove_ZoneView(ivec2 tPos, int tapCount); bool DoubleFingerUp_ZoneView(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_ZoneView(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_ZoneView(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// PalladiON bool SingleFingerUp_PalladiON(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_PalladiON(ivec2 tPos, int tapCount); bool SingleFingerMove_PalladiON(ivec2 tPos, int tapCount); bool DoubleFingerUp_PalladiON(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_PalladiON(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_PalladiON(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// Planar3D bool SingleFingerUp_Planar3D(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_Planar3D(ivec2 tPos, int tapCount); bool SingleFingerMove_Planar3D(ivec2 tPos, int tapCount); bool DoubleFingerUp_Planar3D(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_Planar3D(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_Planar3D(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); ////////////////////////////////////// Interaction - vbViewInfoFinger.cpp /////////////////////////////////////// Animation - vbViewInfoAnimation.cpp void UseCameraAnimation(bool bUseCameraAnimation); bool IsCameraAnimationAvailable(); void UpdateAnimationFrame(); bool UpdateWalkingAnimation(); void InitCameraMoveAni(vec3 pos_start, vec3 pos_end, Quaternion dir_start, Quaternion dir_end, CameraAniMode aniMode); void InitDeviceRotateAni(vbViewDirection eEndDirection); void UpdateAnimatedCamera(); bool IsOnAnimating(); /////////////////////////////////////// Animation - vbViewInfoAnimation.cpp ///////// };
39.471358
149
0.605133
longxingtianxiaShuai
fe648ca1bc737f11012fd6e605fcae87c6db078a
1,916
hpp
C++
include/terms/GeneralTerm.hpp
Krzmbrzl/contractor
7d2d7f08054ba22b12c6e473757f963d5a61a912
[ "BSD-3-Clause" ]
null
null
null
include/terms/GeneralTerm.hpp
Krzmbrzl/contractor
7d2d7f08054ba22b12c6e473757f963d5a61a912
[ "BSD-3-Clause" ]
null
null
null
include/terms/GeneralTerm.hpp
Krzmbrzl/contractor
7d2d7f08054ba22b12c6e473757f963d5a61a912
[ "BSD-3-Clause" ]
null
null
null
#ifndef CONTRACTOR_TERMS_GENERALTERM_HPP_ #define CONTRACTOR_TERMS_GENERALTERM_HPP_ #include "terms/Tensor.hpp" #include "terms/Term.hpp" #include <memory> #include <vector> namespace Contractor::Terms { class BinaryTerm; /** * This special kind of Term simply describes the contained Terms as a list of Tensors. No information about * the optimal order of factorizing the different Tensors is contained (hence the name). */ class GeneralTerm : public Term { public: /** * Type of the container used to store the Tensors */ using tensor_list_t = std::vector< Tensor >; explicit GeneralTerm(const Tensor &result = Tensor(), Term::factor_t prefactor = {}, const tensor_list_t &tensorList = {}); explicit GeneralTerm(const Tensor &result, Term::factor_t prefactor, tensor_list_t &&tensorList); explicit GeneralTerm(const BinaryTerm &binary); GeneralTerm(const GeneralTerm &) = default; GeneralTerm(GeneralTerm &&other) = default; GeneralTerm &operator=(const GeneralTerm &other) = default; GeneralTerm &operator=(GeneralTerm &&other) = default; virtual std::size_t size() const override; /** * Adds a copy of the given Tensor to this Term */ void add(const Tensor &tensor); /** * Adds the given Tensor to this Term */ void add(Tensor &&tensor); /** * Removes a Tensor matching the given one from this Term * * @returns Whether the removal was successful */ bool remove(const Tensor &tensor); /** * @returns A mutable reference of the contained Tensor list */ tensor_list_t &accessTensorList(); /** * @returns A reference of the contained Tensor list */ const tensor_list_t &accessTensorList() const; virtual void sort() override; protected: tensor_list_t m_tensors; Tensor &get(std::size_t index) override; const Tensor &get(std::size_t index) const override; }; }; // namespace Contractor::Terms #endif // CONTRACTOR_TERMS_GENERALTERM_HPP_
25.891892
108
0.733299
Krzmbrzl
fe64c0925f28eda9ebd199765300661a2a2fc3f1
5,051
cc
C++
src/allocator/CrSeparableAllocator.cc
qzcx/supersim
34829411d02fd3bd3f3d7a075edef8749eb8748e
[ "Apache-2.0" ]
17
2017-05-09T07:08:41.000Z
2021-08-03T01:22:09.000Z
src/allocator/CrSeparableAllocator.cc
qzcx/supersim
34829411d02fd3bd3f3d7a075edef8749eb8748e
[ "Apache-2.0" ]
6
2016-12-02T22:07:31.000Z
2020-04-22T07:43:42.000Z
src/allocator/CrSeparableAllocator.cc
qzcx/supersim
34829411d02fd3bd3f3d7a075edef8749eb8748e
[ "Apache-2.0" ]
13
2016-12-02T22:01:04.000Z
2020-03-23T16:44:04.000Z
/* * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "allocator/CrSeparableAllocator.h" #include <factory/ObjectFactory.h> #include <cassert> #include "arbiter/Arbiter.h" CrSeparableAllocator::CrSeparableAllocator( const std::string& _name, const Component* _parent, u32 _numClients, u32 _numResources, Json::Value _settings) : Allocator(_name, _parent, _numClients, _numResources, _settings) { // pointer arrays requests_ = new bool*[numClients_ * numResources_]; metadatas_ = new u64*[numClients_ * numResources_]; intermediates_ = new bool[numClients_ * numResources_]; grants_ = new bool*[numClients_ * numResources_]; // use vector to hold arbiter pointers clientArbiters_.resize(numClients_, nullptr); resourceArbiters_.resize(numResources_, nullptr); // instantiate the client arbiters for (u32 c = 0; c < numClients_; c++) { std::string name = "ArbiterC" + std::to_string(c); clientArbiters_[c] = Arbiter::create( name, this, numResources_, _settings["client_arbiter"]); } // instantiate the resource arbiters for (u32 r = 0; r < numResources_; r++) { std::string name = "ArbiterR" + std::to_string(r); resourceArbiters_[r] = Arbiter::create( name, this, numClients_, _settings["resource_arbiter"]); } // map intermediate request signals to arbiters for (u32 c = 0; c < numClients_; c++) { for (u32 r = 0; r < numResources_; r++) { bool* i = &intermediates_[index(c, r)]; clientArbiters_[c]->setGrant(r, i); resourceArbiters_[r]->setRequest(c, i); } } // parse settings iterations_ = _settings["iterations"].asUInt(); assert(iterations_ > 0); slipLatch_ = _settings["slip_latch"].asBool(); } CrSeparableAllocator::~CrSeparableAllocator() { for (u32 c = 0; c < numClients_; c++) { delete clientArbiters_[c]; } for (u32 r = 0; r < numResources_; r++) { delete resourceArbiters_[r]; } delete[] requests_; delete[] metadatas_; delete[] intermediates_; delete[] grants_; } void CrSeparableAllocator::setRequest(u32 _client, u32 _resource, bool* _request) { requests_[index(_client, _resource)] = _request; clientArbiters_[_client]->setRequest(_resource, _request); } void CrSeparableAllocator::setMetadata(u32 _client, u32 _resource, u64* _metadata) { metadatas_[index(_client, _resource)] = _metadata; clientArbiters_[_client]->setMetadata(_resource, _metadata); resourceArbiters_[_resource]->setMetadata(_client, _metadata); } void CrSeparableAllocator::setGrant(u32 _client, u32 _resource, bool* _grant) { grants_[index(_client, _resource)] = _grant; resourceArbiters_[_resource]->setGrant(_client, _grant); } void CrSeparableAllocator::allocate() { for (u32 remaining = iterations_; remaining > 0; remaining--) { // clear the intermediate stage for (u32 c = 0; c < numClients_; c++) { for (u32 r = 0; r < numResources_; r++) { intermediates_[index(c, r)] = false; } } // run the client arbiters for (u32 c = 0; c < numClients_; c++) { clientArbiters_[c]->arbitrate(); // perform arbiter state latching if (!slipLatch_) { // regular latch always algorithm clientArbiters_[c]->latch(); } } // run the resource arbiters for (u32 r = 0; r < numResources_; r++) { u32 winningClient = resourceArbiters_[r]->arbitrate(); if (winningClient != U32_MAX) { // remove the requests from this client for (u32 r = 0; r < numResources_; r++) { *requests_[index(winningClient, r)] = false; } // remove the requests for this resource for (u32 c = 0; c < numClients_; c++) { *requests_[index(c, r)] = false; } } // perform arbiter state latching if (slipLatch_) { // slip latching (iSLIP algorithm) if (winningClient != U32_MAX) { resourceArbiters_[r]->latch(); clientArbiters_[winningClient]->latch(); } } else { // regular latch always algorithm resourceArbiters_[r]->latch(); } } } } u64 CrSeparableAllocator::index(u64 _client, u64 _resource) const { return (numResources_ * _client) + _resource; } registerWithObjectFactory("cr_separable", Allocator, CrSeparableAllocator, ALLOCATOR_ARGS);
33.230263
79
0.659671
qzcx
fe64f4b5f2ddb33f41fe2594f8fa89f55d94cf9f
1,354
cc
C++
libcassandra/cassandra_host.cc
caoimhechaos/libcassandra
0ae354dd5c41132404c7a5f3c99f6e150e7c823f
[ "BSD-3-Clause" ]
1
2019-04-16T09:06:41.000Z
2019-04-16T09:06:41.000Z
libcassandra/cassandra_host.cc
xiaozhou/libcassandra
5a929edf596621575098959e9c273ab52a27bd34
[ "BSD-3-Clause" ]
null
null
null
libcassandra/cassandra_host.cc
xiaozhou/libcassandra
5a929edf596621575098959e9c273ab52a27bd34
[ "BSD-3-Clause" ]
3
2016-03-14T11:22:24.000Z
2020-04-23T06:58:53.000Z
/* * LibCassandra * Copyright (C) 2010 Padraig O'Sullivan * All rights reserved. * * Use and distribution licensed under the BSD license. See * the COPYING file in the parent directory for full text. */ #include <string> #include <sstream> #include "libcassandra/cassandra.h" #include "libcassandra/cassandra_host.h" #include "libcassandra/util_functions.h" using namespace std; using namespace libcassandra; CassandraHost::CassandraHost() : name(), host(), ip_address(), url(), port(0) { } CassandraHost::CassandraHost(const string &in_url) : name(), host(), ip_address(), url(in_url), port(0) { host= parseHostFromURL(url); port= parsePortFromURL(url); } CassandraHost::CassandraHost(const string &in_host, int in_port) : name(), host(in_host), ip_address(), url(), port(in_port) { url.append(host); url.append(":"); ostringstream port_str; port_str << port; url.append(port_str.str()); } CassandraHost::~CassandraHost() {} const string &CassandraHost::getName() const { return name; } const string &CassandraHost::getHost() const { return host; } const string &CassandraHost::getIPAddress() const { return ip_address; } const string &CassandraHost::getURL() const { return url; } int CassandraHost::getPort() const { return port; }
14.55914
64
0.676514
caoimhechaos
fe6621bb397652b3be2692121a1c61081b7f521c
5,279
hpp
C++
include/xleaflet/xtile_layer.hpp
jtpio/xleaflet
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
[ "BSD-3-Clause" ]
null
null
null
include/xleaflet/xtile_layer.hpp
jtpio/xleaflet
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
[ "BSD-3-Clause" ]
null
null
null
include/xleaflet/xtile_layer.hpp
jtpio/xleaflet
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * Copyright (c) 2018, Sylvain Corlay and Johan Mabille, and Wolf Vollprecht * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * *******************************************************************************/ #ifndef XLEAFLET_TILE_LAYER_HPP #define XLEAFLET_TILE_LAYER_HPP #include <string> #include "xwidgets/xmaterialize.hpp" #include "xwidgets/xwidget.hpp" #include "xleaflet_config.hpp" #include "xraster_layer.hpp" namespace xlf { /************************** * tile_layer declaration * **************************/ template <class D> class xtile_layer : public xraster_layer<D> { public: using load_callback_type = std::function<void(const xeus::xjson&)>; using base_type = xraster_layer<D>; using derived_type = D; void serialize_state(xeus::xjson&, xeus::buffer_sequence&) const; void apply_patch(const xeus::xjson&, const xeus::buffer_sequence&); void on_load(load_callback_type); void handle_custom_message(const xeus::xjson&); XPROPERTY( std::string, derived_type, url, "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"); XPROPERTY(int, derived_type, min_zoom, 0); XPROPERTY(int, derived_type, max_zoom, 18); XPROPERTY(int, derived_type, tile_size, 256); XPROPERTY( std::string, derived_type, attribution, "Map data (c) <a href=\"https://openstreetmap.org\">OpenStreetMap</a> contributors"); XPROPERTY(bool, derived_type, detect_retina, false); protected: xtile_layer(); using base_type::base_type; private: void set_defaults(); std::list<load_callback_type> m_load_callbacks; }; using tile_layer = xw::xmaterialize<xtile_layer>; using tile_layer_generator = xw::xgenerator<xtile_layer>; /****************************** * xtile_layer implementation * ******************************/ template <class D> inline void xtile_layer<D>::serialize_state(xeus::xjson& state, xeus::buffer_sequence& buffers) const { base_type::serialize_state(state, buffers); using xw::set_patch_from_property; set_patch_from_property(url, state, buffers); set_patch_from_property(min_zoom, state, buffers); set_patch_from_property(max_zoom, state, buffers); set_patch_from_property(tile_size, state, buffers); set_patch_from_property(attribution, state, buffers); set_patch_from_property(detect_retina, state, buffers); } template <class D> inline void xtile_layer<D>::apply_patch(const xeus::xjson& patch, const xeus::buffer_sequence& buffers) { base_type::apply_patch(patch, buffers); using xw::set_property_from_patch; set_property_from_patch(url, patch, buffers); set_property_from_patch(min_zoom, patch, buffers); set_property_from_patch(max_zoom, patch, buffers); set_property_from_patch(tile_size, patch, buffers); set_property_from_patch(attribution, patch, buffers); set_property_from_patch(detect_retina, patch, buffers); } template <class D> inline void xtile_layer<D>::on_load(load_callback_type callback) { m_load_callbacks.emplace_back(std::move(callback)); } template <class D> inline xtile_layer<D>::xtile_layer() : base_type() { set_defaults(); } template <class D> inline void xtile_layer<D>::set_defaults() { this->_model_name() = "LeafletTileLayerModel"; this->_view_name() = "LeafletTileLayerView"; this->bottom() = true; this->options().insert( this->options().end(), { "min_zoom", "max_zoom", "tile_size", "attribution", "detect_retina" } ); } template <class D> inline void xtile_layer<D>::handle_custom_message(const xeus::xjson& content) { auto it = content.find("event"); if (it != content.end() && it.value() == "load") { for (auto it = m_load_callbacks.begin(); it != m_load_callbacks.end(); ++it) { it->operator()(content); } } } } /********************* * precompiled types * *********************/ #ifndef _WIN32 extern template class xw::xmaterialize<xlf::xtile_layer>; extern template xw::xmaterialize<xlf::xtile_layer>::xmaterialize(); extern template class xw::xtransport<xw::xmaterialize<xlf::xtile_layer>>; extern template class xw::xgenerator<xlf::xtile_layer>; extern template xw::xgenerator<xlf::xtile_layer>::xgenerator(); extern template class xw::xtransport<xw::xgenerator<xlf::xtile_layer>>; #endif #endif
31.610778
97
0.569805
jtpio
fe6714896167e506eeece31516e164508c4a440e
3,579
cpp
C++
owCore/MPQArchiveManager.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owCore/MPQArchiveManager.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owCore/MPQArchiveManager.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
1
2020-05-11T13:32:49.000Z
2020-05-11T13:32:49.000Z
#include "stdafx.h" // General #include "MPQArchiveManager.h" // Additional #include "BaseManager.h" #if (VERSION == VERSION_Vanila) const char* archives = "D:/_games/World of Warcraft 1.12.1/Data/"; #elif (VERSION == VERSION_WotLK) const char* archives = "D:/_games/World of Warcraft 3.3.5a/Data/"; #endif // CMPQArchiveManager::CMPQArchiveManager() { AddManager<IMPQArchiveManager>(this); // Files 1.12 #if (VERSION == VERSION_Vanila) AddArchive(string("backup.MPQ")); AddArchive(string("base.MPQ")); AddArchive(string("dbc.MPQ")); AddArchive(string("fonts.MPQ")); AddArchive(string("interface.MPQ")); AddArchive(string("misc.MPQ")); AddArchive(string("model.MPQ")); AddArchive(string("patch.MPQ")); AddArchive(string("patch-2.MPQ")); AddArchive(string("patch-3.MPQ")); AddArchive(string("sound.MPQ")); AddArchive(string("speech.MPQ")); AddArchive(string("terrain.MPQ")); AddArchive(string("texture.MPQ")); AddArchive(string("wmo.MPQ")); //AddArchive(string("ruRU/patch-1.MPQ")); //AddArchive(string("ruRU/patch-2.MPQ")); //AddArchive(string("ruRU/patch-3.MPQ")); #elif (VERSION == VERSION_WotLK) AddArchive(string("common.MPQ")); AddArchive(string("common-2.MPQ")); AddArchive(string("expansion.MPQ")); AddArchive(string("lichking.MPQ")); AddArchive(string("patch.MPQ")); AddArchive(string("patch-2.MPQ")); AddArchive(string("patch-3.MPQ")); //AddArchive(string("patch-w.MPQ")); //AddArchive(string("patch-x.MPQ")); AddArchive(string("ruRU/locale-ruRU.MPQ")); AddArchive(string("ruRU/expansion-locale-ruRU.MPQ")); AddArchive(string("ruRU/lichking-locale-ruRU.MPQ")); AddArchive(string("ruRU/patch-ruRU.MPQ")); AddArchive(string("ruRU/patch-ruRU-2.MPQ")); AddArchive(string("ruRU/patch-ruRU-3.MPQ")); //AddArchive(string("ruRU/patch-ruRU-w.MPQ")); //AddArchive(string("ruRU/patch-ruRU-x.MPQ")); #endif } CMPQArchiveManager::~CMPQArchiveManager() { for (auto it : m_OpenArchives) { libmpq__archive_close(it); } } void CMPQArchiveManager::AddArchive(string filename) { mpq_archive_s* mpq_a; int result = libmpq__archive_open(&mpq_a, (archives + filename).c_str(), -1); Log::Info("Opening %s", filename.c_str()); if (result) { switch (result) { case LIBMPQ_ERROR_OPEN: Log::Error("Error opening archive [%s]: Does file really exist?", filename.c_str()); break; case LIBMPQ_ERROR_FORMAT: /* bad file format */ Log::Error("Error opening archive [%s]: Bad file format", filename.c_str()); break; case LIBMPQ_ERROR_SEEK: /* seeking in file failed */ Log::Error("Error opening archive [%s]: Seeking in file failed", filename.c_str()); break; case LIBMPQ_ERROR_READ: /* Read error in archive */ Log::Error("Error opening archive [%s]: Read error in archive", filename.c_str()); break; case LIBMPQ_ERROR_MALLOC: /* maybe not enough memory? :) */ Log::Error("Error opening archive [%s]: Maybe not enough memory", filename.c_str()); break; default: Log::Error("Error opening archive [%s]: Unknown error\n", filename.c_str()); break; } return; } m_OpenArchives.push_back(mpq_a); Log::Green("CMPQFile[%s]: Added!", filename.c_str()); } SMPQFileLocation CMPQArchiveManager::GetFileLocation(cstring filename) { for (auto& i = m_OpenArchives.rbegin(); i != m_OpenArchives.rend(); ++i) { mpq_archive_s* mpq_a = *i; uint32 filenum; if (libmpq__file_number(mpq_a, filename.c_str(), &filenum) == LIBMPQ_ERROR_EXIST) { continue; } return SMPQFileLocation(mpq_a, filenum); } return SMPQFileLocation(); }
26.708955
87
0.689299
adan830
fe68694ab44d19786184d2d8a3724bc0cd9ed6cf
1,666
cpp
C++
SPOJ/MB1.cpp
PiyushArora01/Coding
4f1e61317313fa3a9ea78b221b3ec03d9f256862
[ "Apache-2.0" ]
1
2016-09-01T13:57:27.000Z
2016-09-01T13:57:27.000Z
SPOJ/MB1.cpp
PiyushArora01/Coding
4f1e61317313fa3a9ea78b221b3ec03d9f256862
[ "Apache-2.0" ]
null
null
null
SPOJ/MB1.cpp
PiyushArora01/Coding
4f1e61317313fa3a9ea78b221b3ec03d9f256862
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { int test; cin >> test; int PP[] = {2, 3, 5, 7, 11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 10301, 10501, 10601, 11311, 11411, 12421, 12721, 12821, 13331, 13831, 13931, 14341, 14741, 15451, 15551, 16061, 16361, 16561, 16661, 17471, 17971, 18181, 18481, 19391, 19891, 19991, 30103, 30203, 30403, 30703, 30803, 31013, 31513, 32323, 32423, 33533, 34543, 34843, 35053, 35153, 35353, 35753, 36263, 36563, 37273, 37573, 38083, 38183, 38783, 39293, 70207, 70507, 70607, 71317, 71917, 72227, 72727, 73037, 73237, 73637, 74047, 74747, 75557, 76367, 76667, 77377, 77477, 77977, 78487, 78787, 78887, 79397, 79697, 79997, 90709, 91019, 93139, 93239, 93739, 94049, 94349, 94649, 94849, 94949, 95959, 96269, 96469, 96769, 97379, 97579, 97879, 98389, 98689}; int P[] = {3, 5, 11, 17, 2, 2, 5, 11, 19, 23, 23, 197, 307, 359, 521, 1553, 2693, 3083, 419, 953, 5, 11, 13, 5, 7, 53, 107, 131, 103, 359, 419, 223, 613, 541, 691, 151, 593, 1069, 1321, 1193, 3083, 311, 1619, 1543, 4813, 5519, 23, 61, 151, 307, 359, 23, 197, 593, 827, 2789, 5443, 9311, 1427, 1427, 5039, 13249, 4813, 13697, 6857, 19447, 4211, 4211, 38197, 12197, 521, 1553, 1931, 853, 3083, 2693, 11353, 3083, 6857, 23789, 6007, 53881, 60761, 51713, 111599, 72871, 100169, 244691, 134587, 248851, 288359, 127081, 272141, 424243, 4127, 419, 5519, 12197, 49681, 10627, 36677, 79349, 109037, 124181, 202987, 57559, 124181, 229727, 127081, 222863, 373019, 170627, 364523}; while(test--) { int n; cin >> n; cout << PP[n-1] << " " << P[n-1] << endl; } return 0; }
83.3
759
0.629652
PiyushArora01
fe6a938782cd6ca1f86190c25fa67313aa743eff
100,492
cpp
C++
third_party/WebKit/Source/web/tests/VisualViewportTest.cpp
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
third_party/WebKit/Source/web/tests/VisualViewportTest.cpp
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/web/tests/VisualViewportTest.cpp
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 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 "core/frame/VisualViewport.h" #include "core/dom/Document.h" #include "core/frame/BrowserControls.h" #include "core/frame/FrameHost.h" #include "core/frame/FrameView.h" #include "core/frame/LocalFrame.h" #include "core/html/HTMLBodyElement.h" #include "core/html/HTMLElement.h" #include "core/input/EventHandler.h" #include "core/layout/LayoutObject.h" #include "core/layout/api/LayoutViewItem.h" #include "core/layout/compositing/PaintLayerCompositor.h" #include "core/page/Page.h" #include "core/paint/PaintLayer.h" #include "platform/PlatformGestureEvent.h" #include "platform/geometry/DoublePoint.h" #include "platform/geometry/DoubleRect.h" #include "platform/graphics/CompositorElementId.h" #include "platform/testing/RuntimeEnabledFeaturesTestHelpers.h" #include "platform/testing/URLTestHelpers.h" #include "public/platform/Platform.h" #include "public/platform/WebCachePolicy.h" #include "public/platform/WebInputEvent.h" #include "public/platform/WebLayerTreeView.h" #include "public/platform/WebURLLoaderMockFactory.h" #include "public/web/WebCache.h" #include "public/web/WebContextMenuData.h" #include "public/web/WebDocument.h" #include "public/web/WebFrameClient.h" #include "public/web/WebScriptSource.h" #include "public/web/WebSettings.h" #include "public/web/WebViewClient.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "web/WebLocalFrameImpl.h" #include "web/tests/FrameTestHelpers.h" #include <string> #define ASSERT_POINT_EQ(expected, actual) \ do { \ ASSERT_EQ((expected).x(), (actual).x()); \ ASSERT_EQ((expected).y(), (actual).y()); \ } while (false) #define ASSERT_SIZE_EQ(expected, actual) \ do { \ ASSERT_EQ((expected).width(), (actual).width()); \ ASSERT_EQ((expected).height(), (actual).height()); \ } while (false) #define EXPECT_POINT_EQ(expected, actual) \ do { \ EXPECT_EQ((expected).x(), (actual).x()); \ EXPECT_EQ((expected).y(), (actual).y()); \ } while (false) #define EXPECT_FLOAT_POINT_EQ(expected, actual) \ do { \ EXPECT_FLOAT_EQ((expected).x(), (actual).x()); \ EXPECT_FLOAT_EQ((expected).y(), (actual).y()); \ } while (false) #define EXPECT_POINT_EQ(expected, actual) \ do { \ EXPECT_EQ((expected).x(), (actual).x()); \ EXPECT_EQ((expected).y(), (actual).y()); \ } while (false) #define EXPECT_SIZE_EQ(expected, actual) \ do { \ EXPECT_EQ((expected).width(), (actual).width()); \ EXPECT_EQ((expected).height(), (actual).height()); \ } while (false) #define EXPECT_FLOAT_SIZE_EQ(expected, actual) \ do { \ EXPECT_FLOAT_EQ((expected).width(), (actual).width()); \ EXPECT_FLOAT_EQ((expected).height(), (actual).height()); \ } while (false) #define EXPECT_FLOAT_RECT_EQ(expected, actual) \ do { \ EXPECT_FLOAT_EQ((expected).x(), (actual).x()); \ EXPECT_FLOAT_EQ((expected).y(), (actual).y()); \ EXPECT_FLOAT_EQ((expected).width(), (actual).width()); \ EXPECT_FLOAT_EQ((expected).height(), (actual).height()); \ } while (false) using namespace blink; using ::testing::_; using ::testing::PrintToString; using ::testing::Mock; using blink::URLTestHelpers::toKURL; namespace blink { ::std::ostream& operator<<(::std::ostream& os, const WebContextMenuData& data) { return os << "Context menu location: [" << data.mousePosition.x << ", " << data.mousePosition.y << "]"; } } namespace { typedef bool TestParamRootLayerScrolling; class VisualViewportTest : public testing::Test, public testing::WithParamInterface<TestParamRootLayerScrolling>, private ScopedRootLayerScrollingForTest { public: VisualViewportTest() : ScopedRootLayerScrollingForTest(GetParam()), m_baseURL("http://www.test.com/") {} void initializeWithDesktopSettings( void (*overrideSettingsFunc)(WebSettings*) = 0) { if (!overrideSettingsFunc) overrideSettingsFunc = &configureSettings; m_helper.initialize(true, nullptr, &m_mockWebViewClient, nullptr, overrideSettingsFunc); webViewImpl()->setDefaultPageScaleLimits(1, 4); } void initializeWithAndroidSettings( void (*overrideSettingsFunc)(WebSettings*) = 0) { if (!overrideSettingsFunc) overrideSettingsFunc = &configureAndroidSettings; m_helper.initialize(true, nullptr, &m_mockWebViewClient, nullptr, overrideSettingsFunc); webViewImpl()->setDefaultPageScaleLimits(0.25f, 5); } ~VisualViewportTest() override { Platform::current()->getURLLoaderMockFactory()->unregisterAllURLs(); WebCache::clear(); } void navigateTo(const std::string& url) { FrameTestHelpers::loadFrame(webViewImpl()->mainFrame(), url); } void forceFullCompositingUpdate() { webViewImpl()->updateAllLifecyclePhases(); } void registerMockedHttpURLLoad(const std::string& fileName) { URLTestHelpers::registerMockedURLFromBaseURL( WebString::fromUTF8(m_baseURL.c_str()), WebString::fromUTF8(fileName.c_str())); } WebLayer* getRootScrollLayer() { PaintLayerCompositor* compositor = frame()->contentLayoutItem().compositor(); DCHECK(compositor); DCHECK(compositor->scrollLayer()); WebLayer* webScrollLayer = compositor->scrollLayer()->platformLayer(); return webScrollLayer; } WebViewImpl* webViewImpl() const { return m_helper.webView(); } LocalFrame* frame() const { return m_helper.webView()->mainFrameImpl()->frame(); } static void configureSettings(WebSettings* settings) { settings->setJavaScriptEnabled(true); settings->setPreferCompositingToLCDTextEnabled(true); } static void configureAndroidSettings(WebSettings* settings) { configureSettings(settings); settings->setViewportEnabled(true); settings->setViewportMetaEnabled(true); settings->setShrinksViewportContentToFit(true); settings->setMainFrameResizesAreOrientationChanges(true); } protected: std::string m_baseURL; FrameTestHelpers::TestWebViewClient m_mockWebViewClient; private: FrameTestHelpers::WebViewHelper m_helper; }; INSTANTIATE_TEST_CASE_P(All, VisualViewportTest, ::testing::Bool()); // Test that resizing the VisualViewport works as expected and that resizing the // WebView resizes the VisualViewport. TEST_P(VisualViewportTest, TestResize) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(320, 240)); navigateTo("about:blank"); forceFullCompositingUpdate(); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); IntSize webViewSize = webViewImpl()->size(); // Make sure the visual viewport was initialized. EXPECT_SIZE_EQ(webViewSize, visualViewport.size()); // Resizing the WebView should change the VisualViewport. webViewSize = IntSize(640, 480); webViewImpl()->resize(webViewSize); EXPECT_SIZE_EQ(webViewSize, IntSize(webViewImpl()->size())); EXPECT_SIZE_EQ(webViewSize, visualViewport.size()); // Resizing the visual viewport shouldn't affect the WebView. IntSize newViewportSize = IntSize(320, 200); visualViewport.setSize(newViewportSize); EXPECT_SIZE_EQ(webViewSize, IntSize(webViewImpl()->size())); EXPECT_SIZE_EQ(newViewportSize, visualViewport.size()); } // Make sure that the visibleContentRect method acurately reflects the scale and // scroll location of the viewport with and without scrollbars. TEST_P(VisualViewportTest, TestVisibleContentRect) { RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(false); initializeWithDesktopSettings(); registerMockedHttpURLLoad("200-by-300.html"); navigateTo(m_baseURL + "200-by-300.html"); IntSize size = IntSize(150, 100); // Vertical scrollbar width and horizontal scrollbar height. IntSize scrollbarSize = IntSize(15, 15); webViewImpl()->resize(size); // Scroll layout viewport and verify visibleContentRect. webViewImpl()->mainFrame()->setScrollOffset(WebSize(0, 50)); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_EQ(IntRect(IntPoint(0, 0), size - scrollbarSize), visualViewport.visibleContentRect(ExcludeScrollbars)); EXPECT_EQ(IntRect(IntPoint(0, 0), size), visualViewport.visibleContentRect(IncludeScrollbars)); webViewImpl()->setPageScaleFactor(2.0); // Scroll visual viewport and verify visibleContentRect. size.scale(0.5); scrollbarSize.scale(0.5); visualViewport.setLocation(FloatPoint(10, 10)); EXPECT_EQ(IntRect(IntPoint(10, 10), size - scrollbarSize), visualViewport.visibleContentRect(ExcludeScrollbars)); EXPECT_EQ(IntRect(IntPoint(10, 10), size), visualViewport.visibleContentRect(IncludeScrollbars)); } // This tests that shrinking the WebView while the page is fully scrolled // doesn't move the viewport up/left, it should keep the visible viewport // unchanged from the user's perspective (shrinking the FrameView will clamp // the VisualViewport so we need to counter scroll the FrameView to make it // appear to stay still). This caused bugs like crbug.com/453859. TEST_P(VisualViewportTest, TestResizeAtFullyScrolledPreservesViewportLocation) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(800, 600)); registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); visualViewport.setScale(2); // Fully scroll both viewports. frameView.layoutViewportScrollableArea()->setScrollOffset( ScrollOffset(10000, 10000), ProgrammaticScroll); visualViewport.move(FloatSize(10000, 10000)); // Sanity check. ASSERT_SIZE_EQ(FloatSize(400, 300), visualViewport.scrollOffset()); ASSERT_SIZE_EQ(ScrollOffset(200, 1400), frameView.layoutViewportScrollableArea()->scrollOffset()); IntPoint expectedLocation = frameView.getScrollableArea()->visibleContentRect().location(); // Shrink the WebView, this should cause both viewports to shrink and // WebView should do whatever it needs to do to preserve the visible // location. webViewImpl()->resize(IntSize(700, 550)); EXPECT_POINT_EQ( expectedLocation, frameView.getScrollableArea()->visibleContentRect().location()); webViewImpl()->resize(IntSize(800, 600)); EXPECT_POINT_EQ( expectedLocation, frameView.getScrollableArea()->visibleContentRect().location()); } // Test that the VisualViewport works as expected in case of a scaled // and scrolled viewport - scroll down. TEST_P(VisualViewportTest, TestResizeAfterVerticalScroll) { /* 200 200 | | | | | | | | | | 800 | | 800 |-------------------| | | | | | | | | | | | | | | | | --------> | | | 300 | | | | | | | | 400 | | | | | |-------------------| | | | 75 | | 50 | | 50 100| o----- | o---- | | | | | | 25 | | |100 | |-------------------| | | | | | | | | | | -------------------- -------------------- */ // Disable the test on Mac OSX until futher investigation. // Local build on Mac is OK but thes bot fails. #if OS(MACOSX) return; #endif initializeWithAndroidSettings(); registerMockedHttpURLLoad("200-by-800-viewport.html"); navigateTo(m_baseURL + "200-by-800-viewport.html"); webViewImpl()->resize(IntSize(100, 200)); // Scroll main frame to the bottom of the document webViewImpl()->mainFrame()->setScrollOffset(WebSize(0, 400)); EXPECT_SIZE_EQ( ScrollOffset(0, 400), frame()->view()->layoutViewportScrollableArea()->scrollOffset()); webViewImpl()->setPageScaleFactor(2.0); // Scroll visual viewport to the bottom of the main frame VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); visualViewport.setLocation(FloatPoint(0, 300)); EXPECT_FLOAT_SIZE_EQ(FloatSize(0, 300), visualViewport.scrollOffset()); // Verify the initial size of the visual viewport in the CSS pixels EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 100), visualViewport.visibleRect().size()); // Perform the resizing webViewImpl()->resize(IntSize(200, 100)); // After resizing the scale changes 2.0 -> 4.0 EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 25), visualViewport.visibleRect().size()); EXPECT_SIZE_EQ( ScrollOffset(0, 625), frame()->view()->layoutViewportScrollableArea()->scrollOffset()); EXPECT_FLOAT_SIZE_EQ(FloatSize(0, 75), visualViewport.scrollOffset()); } // Test that the VisualViewport works as expected in case if a scaled // and scrolled viewport - scroll right. TEST_P(VisualViewportTest, TestResizeAfterHorizontalScroll) { /* 200 200 ---------------o----- ---------------o----- | | | | 25| | | | | | -----| | 100| | |100 50 | | | | | | | ---- | |-------------------| | | | | | | | | | | | | | | | | | | | | |400 | ---------> | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |-------------------| | | | | | | */ // Disable the test on Mac OSX until futher investigation. // Local build on Mac is OK but thes bot fails. #if OS(MACOSX) return; #endif initializeWithAndroidSettings(); registerMockedHttpURLLoad("200-by-800-viewport.html"); navigateTo(m_baseURL + "200-by-800-viewport.html"); webViewImpl()->resize(IntSize(100, 200)); // Outer viewport takes the whole width of the document. webViewImpl()->setPageScaleFactor(2.0); // Scroll visual viewport to the right edge of the frame VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); visualViewport.setLocation(FloatPoint(150, 0)); EXPECT_FLOAT_SIZE_EQ(FloatSize(150, 0), visualViewport.scrollOffset()); // Verify the initial size of the visual viewport in the CSS pixels EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 100), visualViewport.visibleRect().size()); webViewImpl()->resize(IntSize(200, 100)); // After resizing the scale changes 2.0 -> 4.0 EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 25), visualViewport.visibleRect().size()); EXPECT_SIZE_EQ(ScrollOffset(0, 0), frame()->view()->scrollOffset()); EXPECT_FLOAT_SIZE_EQ(FloatSize(150, 0), visualViewport.scrollOffset()); } // Test that the container layer gets sized properly if the WebView is resized // prior to the VisualViewport being attached to the layer tree. TEST_P(VisualViewportTest, TestWebViewResizedBeforeAttachment) { initializeWithDesktopSettings(); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); GraphicsLayer* rootGraphicsLayer = frameView.layoutViewItem().compositor()->rootGraphicsLayer(); // Make sure that a resize that comes in while there's no root layer is // honoured when we attach to the layer tree. WebFrameWidgetBase* mainFrameWidget = webViewImpl()->mainFrameImpl()->frameWidget(); mainFrameWidget->setRootGraphicsLayer(nullptr); webViewImpl()->resize(IntSize(320, 240)); mainFrameWidget->setRootGraphicsLayer(rootGraphicsLayer); navigateTo("about:blank"); webViewImpl()->updateAllLifecyclePhases(); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_FLOAT_SIZE_EQ(FloatSize(320, 240), visualViewport.containerLayer()->size()); } // Make sure that the visibleRect method acurately reflects the scale and scroll // location of the viewport. TEST_P(VisualViewportTest, TestVisibleRect) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(320, 240)); navigateTo("about:blank"); forceFullCompositingUpdate(); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); // Initial visible rect should be the whole frame. EXPECT_SIZE_EQ(IntSize(webViewImpl()->size()), visualViewport.size()); // Viewport is whole frame. IntSize size = IntSize(400, 200); webViewImpl()->resize(size); webViewImpl()->updateAllLifecyclePhases(); visualViewport.setSize(size); // Scale the viewport to 2X; size should not change. FloatRect expectedRect(FloatPoint(0, 0), FloatSize(size)); expectedRect.scale(0.5); visualViewport.setScale(2); EXPECT_EQ(2, visualViewport.scale()); EXPECT_SIZE_EQ(size, visualViewport.size()); EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect()); // Move the viewport. expectedRect.setLocation(FloatPoint(5, 7)); visualViewport.setLocation(expectedRect.location()); EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect()); expectedRect.setLocation(FloatPoint(200, 100)); visualViewport.setLocation(expectedRect.location()); EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect()); // Scale the viewport to 3X to introduce some non-int values. FloatPoint oldLocation = expectedRect.location(); expectedRect = FloatRect(FloatPoint(), FloatSize(size)); expectedRect.scale(1 / 3.0f); expectedRect.setLocation(oldLocation); visualViewport.setScale(3); EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect()); expectedRect.setLocation(FloatPoint(0.25f, 0.333f)); visualViewport.setLocation(expectedRect.location()); EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect()); } // Make sure that the visibleRectInDocument method acurately reflects the scale // and scroll location of the viewport relative to the document. TEST_P(VisualViewportTest, TestVisibleRectInDocument) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(100, 400)); registerMockedHttpURLLoad("200-by-800-viewport.html"); navigateTo(m_baseURL + "200-by-800-viewport.html"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); // Scale the viewport to 2X and move it. visualViewport.setScale(2); visualViewport.setLocation(FloatPoint(10, 15)); EXPECT_FLOAT_RECT_EQ(FloatRect(10, 15, 50, 200), visualViewport.visibleRectInDocument()); // Scroll the layout viewport. Ensure its offset is reflected in // visibleRectInDocument(). FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); frameView.layoutViewportScrollableArea()->setScrollOffset( ScrollOffset(40, 100), ProgrammaticScroll); EXPECT_FLOAT_RECT_EQ(FloatRect(50, 115, 50, 200), visualViewport.visibleRectInDocument()); } TEST_P(VisualViewportTest, TestFractionalScrollOffsetIsNotOverwritten) { bool origFractionalOffsetsEnabled = RuntimeEnabledFeatures::fractionalScrollOffsetsEnabled(); RuntimeEnabledFeatures::setFractionalScrollOffsetsEnabled(true); initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(200, 250)); registerMockedHttpURLLoad("200-by-800-viewport.html"); navigateTo(m_baseURL + "200-by-800-viewport.html"); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); frameView.layoutViewportScrollableArea()->setScrollOffset( ScrollOffset(0, 10.5), ProgrammaticScroll); frameView.layoutViewportScrollableArea()->ScrollableArea::setScrollOffset( ScrollOffset(10, 30.5), CompositorScroll); EXPECT_EQ(30.5, frameView.layoutViewportScrollableArea()->scrollOffset().height()); RuntimeEnabledFeatures::setFractionalScrollOffsetsEnabled( origFractionalOffsetsEnabled); } // Test that the viewport's scroll offset is always appropriately bounded such // that the visual viewport always stays within the bounds of the main frame. TEST_P(VisualViewportTest, TestOffsetClamping) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(320, 240)); navigateTo("about:blank"); forceFullCompositingUpdate(); // Visual viewport should be initialized to same size as frame so no scrolling // possible. VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(-1, -2)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(100, 200)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(-5, 10)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); // Scale by 2x. The viewport's visible rect should now have a size of 160x120. visualViewport.setScale(2); FloatPoint location(10, 50); visualViewport.setLocation(location); EXPECT_FLOAT_POINT_EQ(location, visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(1000, 2000)); EXPECT_FLOAT_POINT_EQ(FloatPoint(160, 120), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(-1000, -2000)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); // Make sure offset gets clamped on scale out. Scale to 1.25 so the viewport // is 256x192. visualViewport.setLocation(FloatPoint(160, 120)); visualViewport.setScale(1.25); EXPECT_FLOAT_POINT_EQ(FloatPoint(64, 48), visualViewport.visibleRect().location()); // Scale out smaller than 1. visualViewport.setScale(0.25); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); } // Test that the viewport can be scrolled around only within the main frame in // the presence of viewport resizes, as would be the case if the on screen // keyboard came up. TEST_P(VisualViewportTest, TestOffsetClampingWithResize) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(320, 240)); navigateTo("about:blank"); forceFullCompositingUpdate(); // Visual viewport should be initialized to same size as frame so no scrolling // possible. VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); // Shrink the viewport vertically. The resize shouldn't affect the location, // but it should allow vertical scrolling. visualViewport.setSize(IntSize(320, 200)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(10, 20)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 20), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(0, 100)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 40), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(0, 10)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 10), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(0, -100)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); // Repeat the above but for horizontal dimension. visualViewport.setSize(IntSize(280, 240)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(10, 20)); EXPECT_FLOAT_POINT_EQ(FloatPoint(10, 0), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(100, 0)); EXPECT_FLOAT_POINT_EQ(FloatPoint(40, 0), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(10, 0)); EXPECT_FLOAT_POINT_EQ(FloatPoint(10, 0), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(-100, 0)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); // Now with both dimensions. visualViewport.setSize(IntSize(280, 200)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(10, 20)); EXPECT_FLOAT_POINT_EQ(FloatPoint(10, 20), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(100, 100)); EXPECT_FLOAT_POINT_EQ(FloatPoint(40, 40), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(10, 3)); EXPECT_FLOAT_POINT_EQ(FloatPoint(10, 3), visualViewport.visibleRect().location()); visualViewport.setLocation(FloatPoint(-10, -4)); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); } // Test that the viewport is scrollable but bounded appropriately within the // main frame when we apply both scaling and resizes. TEST_P(VisualViewportTest, TestOffsetClampingWithResizeAndScale) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(320, 240)); navigateTo("about:blank"); forceFullCompositingUpdate(); // Visual viewport should be initialized to same size as WebView so no // scrolling possible. VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0), visualViewport.visibleRect().location()); // Zoom in to 2X so we can scroll the viewport to 160x120. visualViewport.setScale(2); visualViewport.setLocation(FloatPoint(200, 200)); EXPECT_FLOAT_POINT_EQ(FloatPoint(160, 120), visualViewport.visibleRect().location()); // Now resize the viewport to make it 10px smaller. Since we're zoomed in by // 2X it should allow us to scroll by 5px more. visualViewport.setSize(IntSize(310, 230)); visualViewport.setLocation(FloatPoint(200, 200)); EXPECT_FLOAT_POINT_EQ(FloatPoint(165, 125), visualViewport.visibleRect().location()); // The viewport can be larger than the main frame (currently 320, 240) though // typically the scale will be clamped to prevent it from actually being // larger. visualViewport.setSize(IntSize(330, 250)); EXPECT_SIZE_EQ(IntSize(330, 250), visualViewport.size()); // Resize both the viewport and the frame to be larger. webViewImpl()->resize(IntSize(640, 480)); webViewImpl()->updateAllLifecyclePhases(); EXPECT_SIZE_EQ(IntSize(webViewImpl()->size()), visualViewport.size()); EXPECT_SIZE_EQ(IntSize(webViewImpl()->size()), frame()->view()->frameRect().size()); visualViewport.setLocation(FloatPoint(1000, 1000)); EXPECT_FLOAT_POINT_EQ(FloatPoint(320, 240), visualViewport.visibleRect().location()); // Make sure resizing the viewport doesn't change its offset if the resize // doesn't make the viewport go out of bounds. visualViewport.setLocation(FloatPoint(200, 200)); visualViewport.setSize(IntSize(880, 560)); EXPECT_FLOAT_POINT_EQ(FloatPoint(200, 200), visualViewport.visibleRect().location()); } // The main FrameView's size should be set such that its the size of the visual // viewport at minimum scale. If there's no explicit minimum scale set, the // FrameView should be set to the content width and height derived by the aspect // ratio. TEST_P(VisualViewportTest, TestFrameViewSizedToContent) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(320, 240)); registerMockedHttpURLLoad("200-by-300-viewport.html"); navigateTo(m_baseURL + "200-by-300-viewport.html"); webViewImpl()->resize(IntSize(600, 800)); webViewImpl()->updateAllLifecyclePhases(); // Note: the size is ceiled and should match the behavior in CC's // LayerImpl::bounds(). EXPECT_SIZE_EQ( IntSize(200, 267), webViewImpl()->mainFrameImpl()->frameView()->frameRect().size()); } // The main FrameView's size should be set such that its the size of the visual // viewport at minimum scale. On Desktop, the minimum scale is set at 1 so make // sure the FrameView is sized to the viewport. TEST_P(VisualViewportTest, TestFrameViewSizedToMinimumScale) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(320, 240)); registerMockedHttpURLLoad("200-by-300.html"); navigateTo(m_baseURL + "200-by-300.html"); webViewImpl()->resize(IntSize(100, 160)); webViewImpl()->updateAllLifecyclePhases(); EXPECT_SIZE_EQ( IntSize(100, 160), webViewImpl()->mainFrameImpl()->frameView()->frameRect().size()); } // Test that attaching a new frame view resets the size of the inner viewport // scroll layer. crbug.com/423189. TEST_P(VisualViewportTest, TestAttachingNewFrameSetsInnerScrollLayerSize) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(320, 240)); // Load a wider page first, the navigation should resize the scroll layer to // the smaller size on the second navigation. registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); webViewImpl()->updateAllLifecyclePhases(); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); visualViewport.setScale(2); visualViewport.move(ScrollOffset(50, 60)); // Move and scale the viewport to make sure it gets reset in the navigation. EXPECT_SIZE_EQ(FloatSize(50, 60), visualViewport.scrollOffset()); EXPECT_EQ(2, visualViewport.scale()); // Navigate again, this time the FrameView should be smaller. registerMockedHttpURLLoad("viewport-device-width.html"); navigateTo(m_baseURL + "viewport-device-width.html"); // Ensure the scroll layer matches the frame view's size. EXPECT_SIZE_EQ(FloatSize(320, 240), visualViewport.scrollLayer()->size()); EXPECT_EQ(static_cast<int>(CompositorSubElementId::Viewport), visualViewport.scrollLayer()->elementId().secondaryId); // Ensure the location and scale were reset. EXPECT_SIZE_EQ(FloatSize(), visualViewport.scrollOffset()); EXPECT_EQ(1, visualViewport.scale()); } // The main FrameView's size should be set such that its the size of the visual // viewport at minimum scale. Test that the FrameView is appropriately sized in // the presence of a viewport <meta> tag. TEST_P(VisualViewportTest, TestFrameViewSizedToViewportMetaMinimumScale) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(320, 240)); registerMockedHttpURLLoad("200-by-300-min-scale-2.html"); navigateTo(m_baseURL + "200-by-300-min-scale-2.html"); webViewImpl()->resize(IntSize(100, 160)); webViewImpl()->updateAllLifecyclePhases(); EXPECT_SIZE_EQ( IntSize(50, 80), webViewImpl()->mainFrameImpl()->frameView()->frameRect().size()); } // Test that the visual viewport still gets sized in AutoSize/AutoResize mode. TEST_P(VisualViewportTest, TestVisualViewportGetsSizeInAutoSizeMode) { initializeWithDesktopSettings(); EXPECT_SIZE_EQ(IntSize(0, 0), IntSize(webViewImpl()->size())); EXPECT_SIZE_EQ(IntSize(0, 0), frame()->page()->frameHost().visualViewport().size()); webViewImpl()->enableAutoResizeMode(WebSize(10, 10), WebSize(1000, 1000)); registerMockedHttpURLLoad("200-by-300.html"); navigateTo(m_baseURL + "200-by-300.html"); EXPECT_SIZE_EQ(IntSize(200, 300), frame()->page()->frameHost().visualViewport().size()); } // Test that the text selection handle's position accounts for the visual // viewport. TEST_P(VisualViewportTest, TestTextSelectionHandles) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(500, 800)); registerMockedHttpURLLoad("pinch-viewport-input-field.html"); navigateTo(m_baseURL + "pinch-viewport-input-field.html"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); webViewImpl()->setInitialFocus(false); WebRect originalAnchor; WebRect originalFocus; webViewImpl()->selectionBounds(originalAnchor, originalFocus); webViewImpl()->setPageScaleFactor(2); visualViewport.setLocation(FloatPoint(100, 400)); WebRect anchor; WebRect focus; webViewImpl()->selectionBounds(anchor, focus); IntPoint expected(IntRect(originalAnchor).location()); expected.moveBy(-flooredIntPoint(visualViewport.visibleRect().location())); expected.scale(visualViewport.scale(), visualViewport.scale()); EXPECT_POINT_EQ(expected, IntRect(anchor).location()); EXPECT_POINT_EQ(expected, IntRect(focus).location()); // FIXME(bokan) - http://crbug.com/364154 - Figure out how to test text // selection as well rather than just carret. } // Test that the HistoryItem for the page stores the visual viewport's offset // and scale. TEST_P(VisualViewportTest, TestSavedToHistoryItem) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(200, 300)); webViewImpl()->updateAllLifecyclePhases(); registerMockedHttpURLLoad("200-by-300.html"); navigateTo(m_baseURL + "200-by-300.html"); EXPECT_SIZE_EQ(ScrollOffset(0, 0), toLocalFrame(webViewImpl()->page()->mainFrame()) ->loader() .currentItem() ->visualViewportScrollOffset()); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); visualViewport.setScale(2); EXPECT_EQ(2, toLocalFrame(webViewImpl()->page()->mainFrame()) ->loader() .currentItem() ->pageScaleFactor()); visualViewport.setLocation(FloatPoint(10, 20)); EXPECT_SIZE_EQ(ScrollOffset(10, 20), toLocalFrame(webViewImpl()->page()->mainFrame()) ->loader() .currentItem() ->visualViewportScrollOffset()); } // Test restoring a HistoryItem properly restores the visual viewport's state. TEST_P(VisualViewportTest, TestRestoredFromHistoryItem) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(200, 300)); registerMockedHttpURLLoad("200-by-300.html"); WebHistoryItem item; item.initialize(); WebURL destinationURL(URLTestHelpers::toKURL(m_baseURL + "200-by-300.html")); item.setURLString(destinationURL.string()); item.setVisualViewportScrollOffset(WebFloatPoint(100, 120)); item.setPageScaleFactor(2); FrameTestHelpers::loadHistoryItem(webViewImpl()->mainFrame(), item, WebHistoryDifferentDocumentLoad, WebCachePolicy::UseProtocolCachePolicy); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_EQ(2, visualViewport.scale()); EXPECT_FLOAT_POINT_EQ(FloatPoint(100, 120), visualViewport.visibleRect().location()); } // Test restoring a HistoryItem without the visual viewport offset falls back to // distributing the scroll offset between the main frame and the visual // viewport. TEST_P(VisualViewportTest, TestRestoredFromLegacyHistoryItem) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(100, 150)); registerMockedHttpURLLoad("200-by-300-viewport.html"); WebHistoryItem item; item.initialize(); WebURL destinationURL( URLTestHelpers::toKURL(m_baseURL + "200-by-300-viewport.html")); item.setURLString(destinationURL.string()); // (-1, -1) will be used if the HistoryItem is an older version prior to // having visual viewport scroll offset. item.setVisualViewportScrollOffset(WebFloatPoint(-1, -1)); item.setScrollOffset(WebPoint(120, 180)); item.setPageScaleFactor(2); FrameTestHelpers::loadHistoryItem(webViewImpl()->mainFrame(), item, WebHistoryDifferentDocumentLoad, WebCachePolicy::UseProtocolCachePolicy); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_EQ(2, visualViewport.scale()); EXPECT_SIZE_EQ( ScrollOffset(100, 150), frame()->view()->layoutViewportScrollableArea()->scrollOffset()); EXPECT_FLOAT_POINT_EQ(FloatPoint(20, 30), visualViewport.visibleRect().location()); } // Test that navigation to a new page with a different sized main frame doesn't // clobber the history item's main frame scroll offset. crbug.com/371867 TEST_P(VisualViewportTest, TestNavigateToSmallerFrameViewHistoryItemClobberBug) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(400, 400)); webViewImpl()->updateAllLifecyclePhases(); registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); FrameView* frameView = webViewImpl()->mainFrameImpl()->frameView(); frameView->layoutViewportScrollableArea()->setScrollOffset( ScrollOffset(0, 1000), ProgrammaticScroll); EXPECT_SIZE_EQ(IntSize(1000, 1000), frameView->frameRect().size()); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); visualViewport.setScale(2); visualViewport.setLocation(FloatPoint(350, 350)); Persistent<HistoryItem> firstItem = webViewImpl()->mainFrameImpl()->frame()->loader().currentItem(); EXPECT_SIZE_EQ(ScrollOffset(0, 1000), firstItem->scrollOffset()); // Now navigate to a page which causes a smaller frameView. Make sure that // navigating doesn't cause the history item to set a new scroll offset // before the item was replaced. navigateTo("about:blank"); frameView = webViewImpl()->mainFrameImpl()->frameView(); EXPECT_NE(firstItem, webViewImpl()->mainFrameImpl()->frame()->loader().currentItem()); EXPECT_LT(frameView->frameRect().size().width(), 1000); EXPECT_SIZE_EQ(ScrollOffset(0, 1000), firstItem->scrollOffset()); } // Test that the coordinates sent into moveRangeSelection are offset by the // visual viewport's location. TEST_P(VisualViewportTest, DISABLED_TestWebFrameRangeAccountsForVisualViewportScroll) { initializeWithDesktopSettings(); webViewImpl()->settings()->setDefaultFontSize(12); webViewImpl()->resize(WebSize(640, 480)); registerMockedHttpURLLoad("move_range.html"); navigateTo(m_baseURL + "move_range.html"); WebRect baseRect; WebRect extentRect; webViewImpl()->setPageScaleFactor(2); WebFrame* mainFrame = webViewImpl()->mainFrame(); // Select some text and get the base and extent rects (that's the start of // the range and its end). Do a sanity check that the expected text is // selected mainFrame->executeScript(WebScriptSource("selectRange();")); EXPECT_EQ("ir", mainFrame->toWebLocalFrame()->selectionAsText().utf8()); webViewImpl()->selectionBounds(baseRect, extentRect); WebPoint initialPoint(baseRect.x, baseRect.y); WebPoint endPoint(extentRect.x, extentRect.y); // Move the visual viewport over and make the selection in the same // screen-space location. The selection should change to two characters to the // right and down one line. VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); visualViewport.move(ScrollOffset(60, 25)); mainFrame->toWebLocalFrame()->moveRangeSelection(initialPoint, endPoint); EXPECT_EQ("t ", mainFrame->toWebLocalFrame()->selectionAsText().utf8()); } // Test that the scrollFocusedEditableElementIntoRect method works with the // visual viewport. TEST_P(VisualViewportTest, DISABLED_TestScrollFocusedEditableElementIntoRect) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(500, 300)); registerMockedHttpURLLoad("pinch-viewport-input-field.html"); navigateTo(m_baseURL + "pinch-viewport-input-field.html"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); webViewImpl()->resizeVisualViewport(IntSize(200, 100)); webViewImpl()->setInitialFocus(false); visualViewport.setLocation(FloatPoint()); webViewImpl()->scrollFocusedEditableElementIntoRect(IntRect(0, 0, 500, 200)); EXPECT_SIZE_EQ( ScrollOffset(0, frame()->view()->maximumScrollOffset().height()), frame()->view()->scrollOffset()); EXPECT_FLOAT_POINT_EQ(FloatPoint(150, 200), visualViewport.visibleRect().location()); // Try it again but with the page zoomed in frame()->view()->setScrollOffset(ScrollOffset(0, 0), ProgrammaticScroll); webViewImpl()->resizeVisualViewport(IntSize(500, 300)); visualViewport.setLocation(FloatPoint(0, 0)); webViewImpl()->setPageScaleFactor(2); webViewImpl()->scrollFocusedEditableElementIntoRect(IntRect(0, 0, 500, 200)); EXPECT_SIZE_EQ( ScrollOffset(0, frame()->view()->maximumScrollOffset().height()), frame()->view()->scrollOffset()); EXPECT_FLOAT_POINT_EQ(FloatPoint(125, 150), visualViewport.visibleRect().location()); // Once more but make sure that we don't move the visual viewport unless // necessary. registerMockedHttpURLLoad("pinch-viewport-input-field-long-and-wide.html"); navigateTo(m_baseURL + "pinch-viewport-input-field-long-and-wide.html"); webViewImpl()->setInitialFocus(false); visualViewport.setLocation(FloatPoint()); frame()->view()->setScrollOffset(ScrollOffset(0, 0), ProgrammaticScroll); webViewImpl()->resizeVisualViewport(IntSize(500, 300)); visualViewport.setLocation(FloatPoint(30, 50)); webViewImpl()->setPageScaleFactor(2); webViewImpl()->scrollFocusedEditableElementIntoRect(IntRect(0, 0, 500, 200)); EXPECT_SIZE_EQ(ScrollOffset(200 - 30 - 75, 600 - 50 - 65), frame()->view()->scrollOffset()); EXPECT_FLOAT_POINT_EQ(FloatPoint(30, 50), visualViewport.visibleRect().location()); } // Test that resizing the WebView causes ViewportConstrained objects to // relayout. TEST_P(VisualViewportTest, TestWebViewResizeCausesViewportConstrainedLayout) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(500, 300)); registerMockedHttpURLLoad("pinch-viewport-fixed-pos.html"); navigateTo(m_baseURL + "pinch-viewport-fixed-pos.html"); LayoutObject* navbar = frame()->document()->getElementById("navbar")->layoutObject(); EXPECT_FALSE(navbar->needsLayout()); frame()->view()->resize(IntSize(500, 200)); EXPECT_TRUE(navbar->needsLayout()); } class MockWebFrameClient : public FrameTestHelpers::TestWebFrameClient { public: MOCK_METHOD1(showContextMenu, void(const WebContextMenuData&)); MOCK_METHOD1(didChangeScrollOffset, void(WebLocalFrame*)); }; MATCHER_P2(ContextMenuAtLocation, x, y, std::string(negation ? "is" : "isn't") + " at expected location [" + PrintToString(x) + ", " + PrintToString(y) + "]") { return arg.mousePosition.x == x && arg.mousePosition.y == y; } // Test that the context menu's location is correct in the presence of visual // viewport offset. TEST_P(VisualViewportTest, TestContextMenuShownInCorrectLocation) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(200, 300)); registerMockedHttpURLLoad("200-by-300.html"); navigateTo(m_baseURL + "200-by-300.html"); WebMouseEvent mouseDownEvent; mouseDownEvent.type = WebInputEvent::MouseDown; mouseDownEvent.x = 10; mouseDownEvent.y = 10; mouseDownEvent.windowX = 10; mouseDownEvent.windowY = 10; mouseDownEvent.globalX = 110; mouseDownEvent.globalY = 210; mouseDownEvent.clickCount = 1; mouseDownEvent.button = WebMouseEvent::Button::Right; // Corresponding release event (Windows shows context menu on release). WebMouseEvent mouseUpEvent(mouseDownEvent); mouseUpEvent.type = WebInputEvent::MouseUp; WebFrameClient* oldClient = webViewImpl()->mainFrameImpl()->client(); MockWebFrameClient mockWebFrameClient; EXPECT_CALL(mockWebFrameClient, showContextMenu(ContextMenuAtLocation( mouseDownEvent.x, mouseDownEvent.y))); // Do a sanity check with no scale applied. webViewImpl()->mainFrameImpl()->setClient(&mockWebFrameClient); webViewImpl()->handleInputEvent(mouseDownEvent); webViewImpl()->handleInputEvent(mouseUpEvent); Mock::VerifyAndClearExpectations(&mockWebFrameClient); mouseDownEvent.button = WebMouseEvent::Button::Left; webViewImpl()->handleInputEvent(mouseDownEvent); // Now pinch zoom into the page and move the visual viewport. The context menu // should still appear at the location of the event, relative to the WebView. VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); webViewImpl()->setPageScaleFactor(2); EXPECT_CALL(mockWebFrameClient, didChangeScrollOffset(_)); visualViewport.setLocation(FloatPoint(60, 80)); EXPECT_CALL(mockWebFrameClient, showContextMenu(ContextMenuAtLocation( mouseDownEvent.x, mouseDownEvent.y))); mouseDownEvent.button = WebMouseEvent::Button::Right; webViewImpl()->handleInputEvent(mouseDownEvent); webViewImpl()->handleInputEvent(mouseUpEvent); // Reset the old client so destruction can occur naturally. webViewImpl()->mainFrameImpl()->setClient(oldClient); } // Test that the client is notified if page scroll events. TEST_P(VisualViewportTest, TestClientNotifiedOfScrollEvents) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(200, 300)); registerMockedHttpURLLoad("200-by-300.html"); navigateTo(m_baseURL + "200-by-300.html"); WebFrameClient* oldClient = webViewImpl()->mainFrameImpl()->client(); MockWebFrameClient mockWebFrameClient; webViewImpl()->mainFrameImpl()->setClient(&mockWebFrameClient); webViewImpl()->setPageScaleFactor(2); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_CALL(mockWebFrameClient, didChangeScrollOffset(_)); visualViewport.setLocation(FloatPoint(60, 80)); Mock::VerifyAndClearExpectations(&mockWebFrameClient); // Scroll vertically. EXPECT_CALL(mockWebFrameClient, didChangeScrollOffset(_)); visualViewport.setLocation(FloatPoint(60, 90)); Mock::VerifyAndClearExpectations(&mockWebFrameClient); // Scroll horizontally. EXPECT_CALL(mockWebFrameClient, didChangeScrollOffset(_)); visualViewport.setLocation(FloatPoint(70, 90)); // Reset the old client so destruction can occur naturally. webViewImpl()->mainFrameImpl()->setClient(oldClient); } // Tests that calling scroll into view on a visible element doesn't cause // a scroll due to a fractional offset. Bug crbug.com/463356. TEST_P(VisualViewportTest, ScrollIntoViewFractionalOffset) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(1000, 1000)); registerMockedHttpURLLoad("scroll-into-view.html"); navigateTo(m_baseURL + "scroll-into-view.html"); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); ScrollableArea* layoutViewportScrollableArea = frameView.layoutViewportScrollableArea(); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); Element* inputBox = frame()->document()->getElementById("box"); webViewImpl()->setPageScaleFactor(2); // The element is already in the view so the scrollIntoView shouldn't move // the viewport at all. webViewImpl()->setVisualViewportOffset(WebFloatPoint(250.25f, 100.25f)); layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.75), ProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); EXPECT_SIZE_EQ(ScrollOffset(0, 900), layoutViewportScrollableArea->scrollOffset()); EXPECT_SIZE_EQ(FloatSize(250.25f, 100.25f), visualViewport.scrollOffset()); // Change the fractional part of the frameview to one that would round down. layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.125), ProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); EXPECT_SIZE_EQ(ScrollOffset(0, 900), layoutViewportScrollableArea->scrollOffset()); EXPECT_SIZE_EQ(FloatSize(250.25f, 100.25f), visualViewport.scrollOffset()); // Repeat both tests above with the visual viewport at a high fractional. webViewImpl()->setVisualViewportOffset(WebFloatPoint(250.875f, 100.875f)); layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.75), ProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); EXPECT_SIZE_EQ(ScrollOffset(0, 900), layoutViewportScrollableArea->scrollOffset()); EXPECT_SIZE_EQ(FloatSize(250.875f, 100.875f), visualViewport.scrollOffset()); // Change the fractional part of the frameview to one that would round down. layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.125), ProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); EXPECT_SIZE_EQ(ScrollOffset(0, 900), layoutViewportScrollableArea->scrollOffset()); EXPECT_SIZE_EQ(FloatSize(250.875f, 100.875f), visualViewport.scrollOffset()); // Both viewports with a 0.5 fraction. webViewImpl()->setVisualViewportOffset(WebFloatPoint(250.5f, 100.5f)); layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.5), ProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); EXPECT_SIZE_EQ(ScrollOffset(0, 900), layoutViewportScrollableArea->scrollOffset()); EXPECT_SIZE_EQ(FloatSize(250.5f, 100.5f), visualViewport.scrollOffset()); } static ScrollOffset expectedMaxFrameViewScrollOffset( VisualViewport& visualViewport, FrameView& frameView) { float aspectRatio = visualViewport.visibleRect().width() / visualViewport.visibleRect().height(); float newHeight = frameView.frameRect().width() / aspectRatio; return ScrollOffset( frameView.contentsSize().width() - frameView.frameRect().width(), frameView.contentsSize().height() - newHeight); } TEST_P(VisualViewportTest, TestBrowserControlsAdjustment) { initializeWithAndroidSettings(); webViewImpl()->resizeWithBrowserControls(IntSize(500, 450), 20, false); registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); visualViewport.setScale(1); EXPECT_SIZE_EQ(IntSize(500, 450), visualViewport.visibleRect().size()); EXPECT_SIZE_EQ(IntSize(1000, 900), frameView.frameRect().size()); // Simulate bringing down the browser controls by 20px. webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(), WebFloatSize(), 1, 1); EXPECT_SIZE_EQ(IntSize(500, 430), visualViewport.visibleRect().size()); // Test that the scroll bounds are adjusted appropriately: the visual viewport // should be shrunk by 20px to 430px. The outer viewport was shrunk to // maintain the // aspect ratio so it's height is 860px. visualViewport.move(ScrollOffset(10000, 10000)); EXPECT_SIZE_EQ(FloatSize(500, 860 - 430), visualViewport.scrollOffset()); // The outer viewport (FrameView) should be affected as well. frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000), UserScroll); EXPECT_SIZE_EQ(expectedMaxFrameViewScrollOffset(visualViewport, frameView), frameView.layoutViewportScrollableArea()->scrollOffset()); // Simulate bringing up the browser controls by 10.5px. webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(), WebFloatSize(), 1, -10.5f / 20); EXPECT_FLOAT_SIZE_EQ(FloatSize(500, 440.5f), visualViewport.visibleRect().size()); // maximumScrollPosition |ceil|s the browser controls adjustment. visualViewport.move(ScrollOffset(10000, 10000)); EXPECT_FLOAT_SIZE_EQ(FloatSize(500, 881 - 441), visualViewport.scrollOffset()); // The outer viewport (FrameView) should be affected as well. frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000), UserScroll); EXPECT_SIZE_EQ(expectedMaxFrameViewScrollOffset(visualViewport, frameView), frameView.layoutViewportScrollableArea()->scrollOffset()); } TEST_P(VisualViewportTest, TestBrowserControlsAdjustmentWithScale) { initializeWithAndroidSettings(); webViewImpl()->resizeWithBrowserControls(IntSize(500, 450), 20, false); registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); visualViewport.setScale(2); EXPECT_SIZE_EQ(IntSize(250, 225), visualViewport.visibleRect().size()); EXPECT_SIZE_EQ(IntSize(1000, 900), frameView.frameRect().size()); // Simulate bringing down the browser controls by 20px. Since we're zoomed in, // the browser controls take up half as much space (in document-space) than // they do at an unzoomed level. webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(), WebFloatSize(), 1, 1); EXPECT_SIZE_EQ(IntSize(250, 215), visualViewport.visibleRect().size()); // Test that the scroll bounds are adjusted appropriately. visualViewport.move(ScrollOffset(10000, 10000)); EXPECT_SIZE_EQ(FloatSize(750, 860 - 215), visualViewport.scrollOffset()); // The outer viewport (FrameView) should be affected as well. frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000), UserScroll); ScrollOffset expected = expectedMaxFrameViewScrollOffset(visualViewport, frameView); EXPECT_SIZE_EQ(expected, frameView.layoutViewportScrollableArea()->scrollOffset()); // Scale back out, FrameView max scroll shouldn't have changed. Visual // viewport should be moved up to accomodate larger view. webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(), WebFloatSize(), 0.5f, 0); EXPECT_EQ(1, visualViewport.scale()); EXPECT_SIZE_EQ(expected, frameView.layoutViewportScrollableArea()->scrollOffset()); frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000), UserScroll); EXPECT_SIZE_EQ(expected, frameView.layoutViewportScrollableArea()->scrollOffset()); EXPECT_SIZE_EQ(FloatSize(500, 860 - 430), visualViewport.scrollOffset()); visualViewport.move(ScrollOffset(10000, 10000)); EXPECT_SIZE_EQ(FloatSize(500, 860 - 430), visualViewport.scrollOffset()); // Scale out, use a scale that causes fractional rects. webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(), WebFloatSize(), 0.8f, -1); EXPECT_SIZE_EQ(FloatSize(625, 562.5), visualViewport.visibleRect().size()); // Bring out the browser controls by 11 webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(), WebFloatSize(), 1, 11 / 20.f); EXPECT_SIZE_EQ(FloatSize(625, 548.75), visualViewport.visibleRect().size()); // Ensure max scroll offsets are updated properly. visualViewport.move(ScrollOffset(10000, 10000)); EXPECT_FLOAT_SIZE_EQ(FloatSize(375, 877.5 - 548.75), visualViewport.scrollOffset()); frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000), UserScroll); EXPECT_SIZE_EQ(expectedMaxFrameViewScrollOffset(visualViewport, frameView), frameView.layoutViewportScrollableArea()->scrollOffset()); } // Tests that a scroll all the way to the bottom of the page, while hiding the // browser controls doesn't cause a clamp in the viewport scroll offset when the // top controls initiated resize occurs. TEST_P(VisualViewportTest, TestBrowserControlsAdjustmentAndResize) { int browserControlsHeight = 20; int visualViewportHeight = 450; int layoutViewportHeight = 900; float pageScale = 2; float minPageScale = 0.5; initializeWithAndroidSettings(); // Initialize with browser controls showing and shrinking the Blink size. webViewImpl()->resizeWithBrowserControls( WebSize(500, visualViewportHeight - browserControlsHeight), 20, true); webViewImpl()->browserControls().setShownRatio(1); registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); visualViewport.setScale(pageScale); EXPECT_SIZE_EQ( IntSize(250, (visualViewportHeight - browserControlsHeight) / pageScale), visualViewport.visibleRect().size()); EXPECT_SIZE_EQ(IntSize(1000, layoutViewportHeight - browserControlsHeight / minPageScale), frameView.frameRect().size()); EXPECT_SIZE_EQ(IntSize(500, visualViewportHeight - browserControlsHeight), visualViewport.size()); // Scroll all the way to the bottom, hiding the browser controls in the // process. visualViewport.move(ScrollOffset(10000, 10000)); frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000), UserScroll); webViewImpl()->browserControls().setShownRatio(0); EXPECT_SIZE_EQ(IntSize(250, visualViewportHeight / pageScale), visualViewport.visibleRect().size()); ScrollOffset frameViewExpected = expectedMaxFrameViewScrollOffset(visualViewport, frameView); ScrollOffset visualViewportExpected = ScrollOffset( 750, layoutViewportHeight - visualViewportHeight / pageScale); EXPECT_SIZE_EQ(visualViewportExpected, visualViewport.scrollOffset()); EXPECT_SIZE_EQ(frameViewExpected, frameView.layoutViewportScrollableArea()->scrollOffset()); ScrollOffset totalExpected = visualViewportExpected + frameViewExpected; // Resize the widget to match the browser controls adjustment. Ensure that the // total offset (i.e. what the user sees) doesn't change because of clamping // the offsets to valid values. webViewImpl()->resizeWithBrowserControls(WebSize(500, visualViewportHeight), 20, false); EXPECT_SIZE_EQ(IntSize(500, visualViewportHeight), visualViewport.size()); EXPECT_SIZE_EQ(IntSize(250, visualViewportHeight / pageScale), visualViewport.visibleRect().size()); EXPECT_SIZE_EQ(IntSize(1000, layoutViewportHeight), frameView.frameRect().size()); EXPECT_SIZE_EQ(totalExpected, visualViewport.scrollOffset() + frameView.layoutViewportScrollableArea()->scrollOffset()); } // Tests that a scroll all the way to the bottom while showing the browser // controls doesn't cause a clamp to the viewport scroll offset when the browser // controls initiated resize occurs. TEST_P(VisualViewportTest, TestBrowserControlsShrinkAdjustmentAndResize) { int browserControlsHeight = 20; int visualViewportHeight = 500; int layoutViewportHeight = 1000; int contentHeight = 2000; float pageScale = 2; float minPageScale = 0.5; initializeWithAndroidSettings(); // Initialize with browser controls hidden and not shrinking the Blink size. webViewImpl()->resizeWithBrowserControls(IntSize(500, visualViewportHeight), 20, false); webViewImpl()->browserControls().setShownRatio(0); registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); visualViewport.setScale(pageScale); EXPECT_SIZE_EQ(IntSize(250, visualViewportHeight / pageScale), visualViewport.visibleRect().size()); EXPECT_SIZE_EQ(IntSize(1000, layoutViewportHeight), frameView.frameRect().size()); EXPECT_SIZE_EQ(IntSize(500, visualViewportHeight), visualViewport.size()); // Scroll all the way to the bottom, showing the the browser controls in the // process. (This could happen via window.scrollTo during a scroll, for // example). webViewImpl()->browserControls().setShownRatio(1); visualViewport.move(ScrollOffset(10000, 10000)); frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000), UserScroll); EXPECT_SIZE_EQ( IntSize(250, (visualViewportHeight - browserControlsHeight) / pageScale), visualViewport.visibleRect().size()); ScrollOffset frameViewExpected( 0, contentHeight - (layoutViewportHeight - browserControlsHeight / minPageScale)); ScrollOffset visualViewportExpected = ScrollOffset( 750, (layoutViewportHeight - browserControlsHeight / minPageScale - visualViewport.visibleRect().height())); EXPECT_SIZE_EQ(visualViewportExpected, visualViewport.scrollOffset()); EXPECT_SIZE_EQ(frameViewExpected, frameView.layoutViewportScrollableArea()->scrollOffset()); ScrollOffset totalExpected = visualViewportExpected + frameViewExpected; // Resize the widget to match the browser controls adjustment. Ensure that the // total offset (i.e. what the user sees) doesn't change because of clamping // the offsets to valid values. webViewImpl()->resizeWithBrowserControls( WebSize(500, visualViewportHeight - browserControlsHeight), 20, true); EXPECT_SIZE_EQ(IntSize(500, visualViewportHeight - browserControlsHeight), visualViewport.size()); EXPECT_SIZE_EQ( IntSize(250, (visualViewportHeight - browserControlsHeight) / pageScale), visualViewport.visibleRect().size()); EXPECT_SIZE_EQ(IntSize(1000, layoutViewportHeight - browserControlsHeight / minPageScale), frameView.frameRect().size()); EXPECT_SIZE_EQ(totalExpected, visualViewport.scrollOffset() + frameView.layoutViewportScrollableArea()->scrollOffset()); } // Tests that a resize due to browser controls hiding doesn't incorrectly clamp // the main frame's scroll offset. crbug.com/428193. TEST_P(VisualViewportTest, TestTopControlHidingResizeDoesntClampMainFrame) { initializeWithAndroidSettings(); webViewImpl()->resizeWithBrowserControls(webViewImpl()->size(), 500, false); webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(), WebFloatSize(), 1, 1); webViewImpl()->resizeWithBrowserControls(WebSize(1000, 1000), 500, true); registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); // Scroll the FrameView to the bottom of the page but "hide" the browser // controls on the compositor side so the max scroll position should account // for the full viewport height. webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(), WebFloatSize(), 1, -1); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); frameView.layoutViewportScrollableArea()->setScrollOffset( ScrollOffset(0, 10000), ProgrammaticScroll); EXPECT_EQ(500, frameView.layoutViewportScrollableArea()->scrollOffset().height()); // Now send the resize, make sure the scroll offset doesn't change. webViewImpl()->resizeWithBrowserControls(WebSize(1000, 1500), 500, false); EXPECT_EQ(500, frameView.layoutViewportScrollableArea()->scrollOffset().height()); } static void configureHiddenScrollbarsSettings(WebSettings* settings) { VisualViewportTest::configureAndroidSettings(settings); settings->setHideScrollbars(true); } // Tests that scrollbar layers are not attached to the inner viewport container // layer when hideScrollbars WebSetting is true. TEST_P(VisualViewportTest, TestScrollbarsNotAttachedWhenHideScrollbarsSettingIsTrue) { initializeWithAndroidSettings(configureHiddenScrollbarsSettings); webViewImpl()->resize(IntSize(100, 150)); navigateTo("about:blank"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_FALSE(visualViewport.layerForHorizontalScrollbar()->parent()); EXPECT_FALSE(visualViewport.layerForVerticalScrollbar()->parent()); } // Tests that scrollbar layers are attached to the inner viewport container // layer when hideScrollbars WebSetting is false. TEST_P(VisualViewportTest, TestScrollbarsAttachedWhenHideScrollbarsSettingIsFalse) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(100, 150)); navigateTo("about:blank"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); EXPECT_TRUE(visualViewport.layerForHorizontalScrollbar()->parent()); EXPECT_TRUE(visualViewport.layerForVerticalScrollbar()->parent()); } // Tests that the layout viewport's scroll layer bounds are updated in a // compositing change update. crbug.com/423188. TEST_P(VisualViewportTest, TestChangingContentSizeAffectsScrollBounds) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(100, 150)); registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); WebLayer* scrollLayer = frameView.layerForScrolling()->platformLayer(); webViewImpl()->mainFrame()->executeScript( WebScriptSource("var content = document.getElementById(\"content\");" "content.style.width = \"1500px\";" "content.style.height = \"2400px\";")); frameView.updateAllLifecyclePhases(); EXPECT_SIZE_EQ(IntSize(1500, 2400), IntSize(scrollLayer->bounds())); } // Tests that resizing the visual viepwort keeps its bounds within the outer // viewport. TEST_P(VisualViewportTest, ResizeVisualViewportStaysWithinOuterViewport) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(100, 200)); navigateTo("about:blank"); webViewImpl()->updateAllLifecyclePhases(); webViewImpl()->resizeVisualViewport(IntSize(100, 100)); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); visualViewport.move(ScrollOffset(0, 100)); EXPECT_EQ(100, visualViewport.scrollOffset().height()); webViewImpl()->resizeVisualViewport(IntSize(100, 200)); EXPECT_EQ(0, visualViewport.scrollOffset().height()); } TEST_P(VisualViewportTest, ElementBoundsInViewportSpaceAccountsForViewport) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(500, 800)); registerMockedHttpURLLoad("pinch-viewport-input-field.html"); navigateTo(m_baseURL + "pinch-viewport-input-field.html"); webViewImpl()->setInitialFocus(false); Element* inputElement = webViewImpl()->focusedElement(); IntRect bounds = inputElement->layoutObject()->absoluteBoundingBoxRect(); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); IntPoint scrollDelta(250, 400); visualViewport.setScale(2); visualViewport.setLocation(scrollDelta); const IntRect boundsInViewport = inputElement->boundsInViewport(); IntRect expectedBounds = bounds; expectedBounds.scale(2.f); IntPoint expectedScrollDelta = scrollDelta; expectedScrollDelta.scale(2.f, 2.f); EXPECT_POINT_EQ(IntPoint(expectedBounds.location() - expectedScrollDelta), boundsInViewport.location()); EXPECT_SIZE_EQ(expectedBounds.size(), boundsInViewport.size()); } TEST_P(VisualViewportTest, ElementVisibleBoundsInVisualViewport) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(640, 1080)); registerMockedHttpURLLoad("viewport-select.html"); navigateTo(m_baseURL + "viewport-select.html"); ASSERT_EQ(2.0f, webViewImpl()->pageScaleFactor()); webViewImpl()->setInitialFocus(false); Element* element = webViewImpl()->focusedElement(); EXPECT_FALSE(element->visibleBoundsInVisualViewport().isEmpty()); webViewImpl()->setPageScaleFactor(4.0); EXPECT_TRUE(element->visibleBoundsInVisualViewport().isEmpty()); } // Test that the various window.scroll and document.body.scroll properties and // methods work unchanged from the pre-virtual viewport mode. TEST_P(VisualViewportTest, bodyAndWindowScrollPropertiesAccountForViewport) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(200, 300)); // Load page with no main frame scrolling. registerMockedHttpURLLoad("200-by-300-viewport.html"); navigateTo(m_baseURL + "200-by-300-viewport.html"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); visualViewport.setScale(2); // Chrome's quirky behavior regarding viewport scrolling means we treat the // body element as the viewport and don't apply scrolling to the HTML element. RuntimeEnabledFeatures::setScrollTopLeftInteropEnabled(false); LocalDOMWindow* window = webViewImpl()->mainFrameImpl()->frame()->localDOMWindow(); window->scrollTo(100, 150); EXPECT_EQ(100, window->scrollX()); EXPECT_EQ(150, window->scrollY()); EXPECT_FLOAT_SIZE_EQ(FloatSize(100, 150), visualViewport.scrollOffset()); HTMLElement* body = toHTMLBodyElement(window->document()->body()); body->setScrollLeft(50); body->setScrollTop(130); EXPECT_EQ(50, body->scrollLeft()); EXPECT_EQ(130, body->scrollTop()); EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 130), visualViewport.scrollOffset()); HTMLElement* documentElement = toHTMLElement(window->document()->documentElement()); documentElement->setScrollLeft(40); documentElement->setScrollTop(50); EXPECT_EQ(0, documentElement->scrollLeft()); EXPECT_EQ(0, documentElement->scrollTop()); EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 130), visualViewport.scrollOffset()); visualViewport.setLocation(FloatPoint(10, 20)); EXPECT_EQ(10, body->scrollLeft()); EXPECT_EQ(20, body->scrollTop()); EXPECT_EQ(0, documentElement->scrollLeft()); EXPECT_EQ(0, documentElement->scrollTop()); EXPECT_EQ(10, window->scrollX()); EXPECT_EQ(20, window->scrollY()); // Turning on the standards-compliant viewport scrolling impl should make the // document element the viewport and not body. RuntimeEnabledFeatures::setScrollTopLeftInteropEnabled(true); window->scrollTo(100, 150); EXPECT_EQ(100, window->scrollX()); EXPECT_EQ(150, window->scrollY()); EXPECT_FLOAT_SIZE_EQ(FloatSize(100, 150), visualViewport.scrollOffset()); body->setScrollLeft(50); body->setScrollTop(130); EXPECT_EQ(0, body->scrollLeft()); EXPECT_EQ(0, body->scrollTop()); EXPECT_FLOAT_SIZE_EQ(FloatSize(100, 150), visualViewport.scrollOffset()); documentElement->setScrollLeft(40); documentElement->setScrollTop(50); EXPECT_EQ(40, documentElement->scrollLeft()); EXPECT_EQ(50, documentElement->scrollTop()); EXPECT_FLOAT_SIZE_EQ(FloatSize(40, 50), visualViewport.scrollOffset()); visualViewport.setLocation(FloatPoint(10, 20)); EXPECT_EQ(0, body->scrollLeft()); EXPECT_EQ(0, body->scrollTop()); EXPECT_EQ(10, documentElement->scrollLeft()); EXPECT_EQ(20, documentElement->scrollTop()); EXPECT_EQ(10, window->scrollX()); EXPECT_EQ(20, window->scrollY()); } // Tests that when a new frame is created, it is created with the intended size // (i.e. viewport at minimum scale, 100x200 / 0.5). TEST_P(VisualViewportTest, TestMainFrameInitializationSizing) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(100, 200)); registerMockedHttpURLLoad("content-width-1000-min-scale.html"); navigateTo(m_baseURL + "content-width-1000-min-scale.html"); WebLocalFrameImpl* localFrame = webViewImpl()->mainFrameImpl(); // The shutdown() calls are a hack to prevent this test from violating // invariants about frame state during navigation/detach. localFrame->frame()->document()->shutdown(); localFrame->createFrameView(); FrameView& frameView = *localFrame->frameView(); EXPECT_SIZE_EQ(IntSize(200, 400), frameView.frameRect().size()); frameView.dispose(); } // Tests that the maximum scroll offset of the viewport can be fractional. TEST_P(VisualViewportTest, FractionalMaxScrollOffset) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(101, 201)); navigateTo("about:blank"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); ScrollableArea* scrollableArea = &visualViewport; webViewImpl()->setPageScaleFactor(1.0); EXPECT_SIZE_EQ(ScrollOffset(), scrollableArea->maximumScrollOffset()); webViewImpl()->setPageScaleFactor(2); EXPECT_SIZE_EQ(ScrollOffset(101. / 2., 201. / 2.), scrollableArea->maximumScrollOffset()); } // Tests that the slow scrolling after an impl scroll on the visual viewport is // continuous. crbug.com/453460 was caused by the impl-path not updating the // ScrollAnimatorBase class. TEST_P(VisualViewportTest, SlowScrollAfterImplScroll) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(800, 600)); navigateTo("about:blank"); VisualViewport& visualViewport = frame()->page()->frameHost().visualViewport(); // Apply some scroll and scale from the impl-side. webViewImpl()->applyViewportDeltas(WebFloatSize(300, 200), WebFloatSize(0, 0), WebFloatSize(0, 0), 2, 0); EXPECT_SIZE_EQ(FloatSize(300, 200), visualViewport.scrollOffset()); // Send a scroll event on the main thread path. PlatformGestureEvent gsu(PlatformEvent::GestureScrollUpdate, IntPoint(0, 0), IntPoint(0, 0), IntSize(5, 5), 0, PlatformEvent::NoModifiers, PlatformGestureSourceTouchpad); gsu.setScrollGestureData(-50, -60, ScrollByPrecisePixel, 1, 1, ScrollInertialPhaseUnknown, false, -1 /* null plugin id */); frame()->eventHandler().handleGestureEvent(gsu); // The scroll sent from the impl-side must not be overwritten. EXPECT_SIZE_EQ(FloatSize(350, 260), visualViewport.scrollOffset()); } static void accessibilitySettings(WebSettings* settings) { VisualViewportTest::configureSettings(settings); settings->setAccessibilityEnabled(true); } TEST_P(VisualViewportTest, AccessibilityHitTestWhileZoomedIn) { initializeWithDesktopSettings(accessibilitySettings); registerMockedHttpURLLoad("hit-test.html"); navigateTo(m_baseURL + "hit-test.html"); webViewImpl()->resize(IntSize(500, 500)); webViewImpl()->updateAllLifecyclePhases(); WebDocument webDoc = webViewImpl()->mainFrame()->document(); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); webViewImpl()->setPageScaleFactor(2); webViewImpl()->setVisualViewportOffset(WebFloatPoint(200, 230)); frameView.layoutViewportScrollableArea()->setScrollOffset( ScrollOffset(400, 1100), ProgrammaticScroll); // FIXME(504057): PaintLayerScrollableArea dirties the compositing state. forceFullCompositingUpdate(); // Because of where the visual viewport is located, this should hit the bottom // right target (target 4). WebAXObject hitNode = webDoc.accessibilityObject().hitTest(WebPoint(154, 165)); WebAXNameFrom nameFrom; WebVector<WebAXObject> nameObjects; EXPECT_EQ(std::string("Target4"), hitNode.name(nameFrom, nameObjects).utf8()); } // Tests that the maximum scroll offset of the viewport can be fractional. TEST_P(VisualViewportTest, TestCoordinateTransforms) { initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(800, 600)); registerMockedHttpURLLoad("content-width-1000.html"); navigateTo(m_baseURL + "content-width-1000.html"); VisualViewport& visualViewport = webViewImpl()->page()->frameHost().visualViewport(); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); // At scale = 1 the transform should be a no-op. visualViewport.setScale(1); EXPECT_FLOAT_POINT_EQ( FloatPoint(314, 273), visualViewport.viewportToRootFrame(FloatPoint(314, 273))); EXPECT_FLOAT_POINT_EQ( FloatPoint(314, 273), visualViewport.rootFrameToViewport(FloatPoint(314, 273))); // At scale = 2. visualViewport.setScale(2); EXPECT_FLOAT_POINT_EQ(FloatPoint(55, 75), visualViewport.viewportToRootFrame( FloatPoint(110, 150))); EXPECT_FLOAT_POINT_EQ(FloatPoint(110, 150), visualViewport.rootFrameToViewport(FloatPoint(55, 75))); // At scale = 2 and with the visual viewport offset. visualViewport.setLocation(FloatPoint(10, 12)); EXPECT_FLOAT_POINT_EQ(FloatPoint(50, 62), visualViewport.viewportToRootFrame( FloatPoint(80, 100))); EXPECT_FLOAT_POINT_EQ(FloatPoint(80, 100), visualViewport.rootFrameToViewport(FloatPoint(50, 62))); // Test points that will cause non-integer values. EXPECT_FLOAT_POINT_EQ( FloatPoint(50.5, 62.4), visualViewport.viewportToRootFrame(FloatPoint(81, 100.8))); EXPECT_FLOAT_POINT_EQ( FloatPoint(81, 100.8), visualViewport.rootFrameToViewport(FloatPoint(50.5, 62.4))); // Scrolling the main frame should have no effect. frameView.layoutViewportScrollableArea()->setScrollOffset( ScrollOffset(100, 120), ProgrammaticScroll); EXPECT_FLOAT_POINT_EQ(FloatPoint(50, 62), visualViewport.viewportToRootFrame( FloatPoint(80, 100))); EXPECT_FLOAT_POINT_EQ(FloatPoint(80, 100), visualViewport.rootFrameToViewport(FloatPoint(50, 62))); } // Tests that the window dimensions are available before a full layout occurs. // More specifically, it checks that the innerWidth and innerHeight window // properties will trigger a layout which will cause an update to viewport // constraints and a refreshed initial scale. crbug.com/466718 TEST_P(VisualViewportTest, WindowDimensionsOnLoad) { initializeWithAndroidSettings(); registerMockedHttpURLLoad("window_dimensions.html"); webViewImpl()->resize(IntSize(800, 600)); navigateTo(m_baseURL + "window_dimensions.html"); Element* output = frame()->document()->getElementById("output"); DCHECK(output); EXPECT_EQ(std::string("1600x1200"), std::string(output->innerHTML().ascii().data())); } // Similar to above but make sure the initial scale is updated with the content // width for a very wide page. That is, make that innerWidth/Height actually // trigger a layout of the content, and not just an update of the viepwort. // crbug.com/466718 TEST_P(VisualViewportTest, WindowDimensionsOnLoadWideContent) { initializeWithAndroidSettings(); registerMockedHttpURLLoad("window_dimensions_wide_div.html"); webViewImpl()->resize(IntSize(800, 600)); navigateTo(m_baseURL + "window_dimensions_wide_div.html"); Element* output = frame()->document()->getElementById("output"); DCHECK(output); EXPECT_EQ(std::string("2000x1500"), std::string(output->innerHTML().ascii().data())); } TEST_P(VisualViewportTest, PinchZoomGestureScrollsVisualViewportOnly) { initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(100, 100)); registerMockedHttpURLLoad("200-by-800-viewport.html"); navigateTo(m_baseURL + "200-by-800-viewport.html"); WebGestureEvent pinchUpdate; pinchUpdate.type = WebInputEvent::GesturePinchUpdate; pinchUpdate.sourceDevice = WebGestureDeviceTouchpad; pinchUpdate.x = 100; pinchUpdate.y = 100; pinchUpdate.data.pinchUpdate.scale = 2; pinchUpdate.data.pinchUpdate.zoomDisabled = false; webViewImpl()->handleInputEvent(pinchUpdate); VisualViewport& visualViewport = webViewImpl()->page()->frameHost().visualViewport(); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 50), visualViewport.scrollOffset()); EXPECT_SIZE_EQ(ScrollOffset(0, 0), frameView.layoutViewportScrollableArea()->scrollOffset()); } TEST_P(VisualViewportTest, ResizeWithScrollAnchoring) { bool wasScrollAnchoringEnabled = RuntimeEnabledFeatures::scrollAnchoringEnabled(); RuntimeEnabledFeatures::setScrollAnchoringEnabled(true); initializeWithDesktopSettings(); webViewImpl()->resize(IntSize(800, 600)); registerMockedHttpURLLoad("icb-relative-content.html"); navigateTo(m_baseURL + "icb-relative-content.html"); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); frameView.layoutViewportScrollableArea()->setScrollOffset( ScrollOffset(700, 500), ProgrammaticScroll); webViewImpl()->updateAllLifecyclePhases(); webViewImpl()->resize(IntSize(800, 300)); EXPECT_SIZE_EQ(ScrollOffset(700, 200), frameView.layoutViewportScrollableArea()->scrollOffset()); RuntimeEnabledFeatures::setScrollAnchoringEnabled(wasScrollAnchoringEnabled); } // Ensure that resize anchoring as happens when browser controls hide/show // affects the scrollable area that's currently set as the root scroller. TEST_P(VisualViewportTest, ResizeAnchoringWithRootScroller) { bool wasRootScrollerEnabled = RuntimeEnabledFeatures::setRootScrollerEnabled(); RuntimeEnabledFeatures::setSetRootScrollerEnabled(true); initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(800, 600)); registerMockedHttpURLLoad("root-scroller-div.html"); navigateTo(m_baseURL + "root-scroller-div.html"); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); Element* scroller = frame()->document()->getElementById("rootScroller"); NonThrowableExceptionState nonThrow; frame()->document()->setRootScroller(scroller, nonThrow); webViewImpl()->setPageScaleFactor(3.f); frameView.getScrollableArea()->setScrollOffset(ScrollOffset(0, 400), ProgrammaticScroll); VisualViewport& visualViewport = webViewImpl()->page()->frameHost().visualViewport(); visualViewport.setScrollOffset(ScrollOffset(0, 400), ProgrammaticScroll); webViewImpl()->resize(IntSize(800, 500)); EXPECT_SIZE_EQ(ScrollOffset(), frameView.layoutViewportScrollableArea()->scrollOffset()); RuntimeEnabledFeatures::setSetRootScrollerEnabled(wasRootScrollerEnabled); } // Ensure that resize anchoring as happens when the device is rotated affects // the scrollable area that's currently set as the root scroller. TEST_P(VisualViewportTest, RotationAnchoringWithRootScroller) { bool wasRootScrollerEnabled = RuntimeEnabledFeatures::setRootScrollerEnabled(); RuntimeEnabledFeatures::setSetRootScrollerEnabled(true); initializeWithAndroidSettings(); webViewImpl()->resize(IntSize(800, 600)); registerMockedHttpURLLoad("root-scroller-div.html"); navigateTo(m_baseURL + "root-scroller-div.html"); FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView(); Element* scroller = frame()->document()->getElementById("rootScroller"); NonThrowableExceptionState nonThrow; frame()->document()->setRootScroller(scroller, nonThrow); webViewImpl()->updateAllLifecyclePhases(); scroller->setScrollTop(800); webViewImpl()->resize(IntSize(600, 800)); EXPECT_SIZE_EQ(ScrollOffset(), frameView.layoutViewportScrollableArea()->scrollOffset()); EXPECT_EQ(600, scroller->scrollTop()); RuntimeEnabledFeatures::setSetRootScrollerEnabled(wasRootScrollerEnabled); } static void configureAndroidCompositing(WebSettings* settings) { settings->setAcceleratedCompositingEnabled(true); settings->setPreferCompositingToLCDTextEnabled(true); settings->setViewportMetaEnabled(true); settings->setViewportEnabled(true); settings->setMainFrameResizesAreOrientationChanges(true); settings->setShrinksViewportContentToFit(true); } // Make sure a composited background-attachment:fixed background gets resized // when using inert (non-layout affecting) browser controls. TEST_P(VisualViewportTest, ResizeCompositedAndFixedBackground) { bool originalInertTopControls = RuntimeEnabledFeatures::inertTopControlsEnabled(); RuntimeEnabledFeatures::setInertTopControlsEnabled(true); std::unique_ptr<FrameTestHelpers::TestWebViewClient> fakeCompositingWebViewClient = makeUnique<FrameTestHelpers::TestWebViewClient>(); FrameTestHelpers::WebViewHelper webViewHelper; WebViewImpl* webViewImpl = webViewHelper.initialize( true, nullptr, fakeCompositingWebViewClient.get(), nullptr, &configureAndroidCompositing); int pageWidth = 640; int pageHeight = 480; float browserControlsHeight = 50.0f; int smallestHeight = pageHeight - browserControlsHeight; webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight), browserControlsHeight, false); URLTestHelpers::registerMockedURLLoad(toKURL("http://example.com/foo.png"), "white-1x1.png"); WebURL baseURL = URLTestHelpers::toKURL("http://example.com/"); FrameTestHelpers::loadHTMLString(webViewImpl->mainFrame(), "<!DOCTYPE html>" "<style>" " body {" " background: url('foo.png');" " background-attachment: fixed;" " background-size: cover;" " background-repeat: no-repeat;" " }" " div { height:1000px; width: 200px; }" "</style>" "<div></div>", baseURL); webViewImpl->updateAllLifecyclePhases(); Document* document = toLocalFrame(webViewImpl->page()->mainFrame())->document(); PaintLayerCompositor* compositor = document->layoutView()->compositor(); ASSERT_TRUE(compositor->needsFixedRootBackgroundLayer( document->layoutView()->layer())); ASSERT_TRUE(compositor->fixedRootBackgroundLayer()); ASSERT_EQ(pageWidth, compositor->fixedRootBackgroundLayer()->size().width()); ASSERT_EQ(pageHeight, compositor->fixedRootBackgroundLayer()->size().height()); ASSERT_EQ(pageWidth, document->view()->layoutSize().width()); ASSERT_EQ(smallestHeight, document->view()->layoutSize().height()); webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, smallestHeight), browserControlsHeight, true); // The layout size should not have changed. ASSERT_EQ(pageWidth, document->view()->layoutSize().width()); ASSERT_EQ(smallestHeight, document->view()->layoutSize().height()); // The background layer's size should have changed though. EXPECT_EQ(pageWidth, compositor->fixedRootBackgroundLayer()->size().width()); EXPECT_EQ(smallestHeight, compositor->fixedRootBackgroundLayer()->size().height()); webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight), browserControlsHeight, true); // The background layer's size should change again. EXPECT_EQ(pageWidth, compositor->fixedRootBackgroundLayer()->size().width()); EXPECT_EQ(pageHeight, compositor->fixedRootBackgroundLayer()->size().height()); RuntimeEnabledFeatures::setInertTopControlsEnabled(originalInertTopControls); } static void configureAndroidNonCompositing(WebSettings* settings) { settings->setAcceleratedCompositingEnabled(true); settings->setPreferCompositingToLCDTextEnabled(false); settings->setViewportMetaEnabled(true); settings->setViewportEnabled(true); settings->setMainFrameResizesAreOrientationChanges(true); settings->setShrinksViewportContentToFit(true); } // Make sure a non-composited background-attachment:fixed background gets // resized when using inert (non-layout affecting) browser controls. TEST_P(VisualViewportTest, ResizeNonCompositedAndFixedBackground) { bool originalInertTopControls = RuntimeEnabledFeatures::inertTopControlsEnabled(); RuntimeEnabledFeatures::setInertTopControlsEnabled(true); FrameTestHelpers::WebViewHelper webViewHelper; WebViewImpl* webViewImpl = webViewHelper.initialize( true, nullptr, nullptr, nullptr, &configureAndroidNonCompositing); int pageWidth = 640; int pageHeight = 480; float browserControlsHeight = 50.0f; int smallestHeight = pageHeight - browserControlsHeight; webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight), browserControlsHeight, false); URLTestHelpers::registerMockedURLLoad(toKURL("http://example.com/foo.png"), "white-1x1.png"); WebURL baseURL = URLTestHelpers::toKURL("http://example.com/"); FrameTestHelpers::loadHTMLString(webViewImpl->mainFrame(), "<!DOCTYPE html>" "<style>" " body {" " margin: 0px;" " background: url('foo.png');" " background-attachment: fixed;" " background-size: cover;" " background-repeat: no-repeat;" " }" " div { height:1000px; width: 200px; }" "</style>" "<div></div>", baseURL); webViewImpl->updateAllLifecyclePhases(); Document* document = toLocalFrame(webViewImpl->page()->mainFrame())->document(); PaintLayerCompositor* compositor = document->layoutView()->compositor(); ASSERT_FALSE(compositor->needsFixedRootBackgroundLayer( document->layoutView()->layer())); ASSERT_FALSE(compositor->fixedRootBackgroundLayer()); document->view()->setTracksPaintInvalidations(true); webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, smallestHeight), browserControlsHeight, true); // The layout size should not have changed. ASSERT_EQ(pageWidth, document->view()->layoutSize().width()); ASSERT_EQ(smallestHeight, document->view()->layoutSize().height()); const RasterInvalidationTracking* invalidationTracking = document->layoutView() ->layer() ->graphicsLayerBacking() ->getRasterInvalidationTracking(); // If no invalidations occured, this will be a nullptr. ASSERT_TRUE(invalidationTracking); const auto* rasterInvalidations = &invalidationTracking->trackedRasterInvalidations; bool rootLayerScrolling = GetParam(); // Without root-layer-scrolling, the LayoutView is the size of the document // content so invalidating it for background-attachment: fixed // overinvalidates as we should only need to invalidate the viewport size. // With root-layer-scrolling, we should invalidate the entire viewport height. int expectedHeight = rootLayerScrolling ? pageHeight : 1000; // The entire viewport should have been invalidated. EXPECT_EQ(1u, rasterInvalidations->size()); EXPECT_EQ(IntRect(0, 0, 640, expectedHeight), (*rasterInvalidations)[0].rect); document->view()->setTracksPaintInvalidations(false); invalidationTracking = document->layoutView() ->layer() ->graphicsLayerBacking() ->getRasterInvalidationTracking(); ASSERT_FALSE(invalidationTracking); document->view()->setTracksPaintInvalidations(true); webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight), browserControlsHeight, true); invalidationTracking = document->layoutView() ->layer() ->graphicsLayerBacking() ->getRasterInvalidationTracking(); ASSERT_TRUE(invalidationTracking); rasterInvalidations = &invalidationTracking->trackedRasterInvalidations; // Once again, the entire page should have been invalidated. expectedHeight = rootLayerScrolling ? 480 : 1000; EXPECT_EQ(1u, rasterInvalidations->size()); EXPECT_EQ(IntRect(0, 0, 640, expectedHeight), (*rasterInvalidations)[0].rect); document->view()->setTracksPaintInvalidations(false); RuntimeEnabledFeatures::setInertTopControlsEnabled(originalInertTopControls); } // Make sure a browser control resize with background-attachment:not-fixed // background doesn't cause invalidation or layout. TEST_P(VisualViewportTest, ResizeNonFixedBackgroundNoLayoutOrInvalidation) { bool originalInertTopControls = RuntimeEnabledFeatures::inertTopControlsEnabled(); RuntimeEnabledFeatures::setInertTopControlsEnabled(true); std::unique_ptr<FrameTestHelpers::TestWebViewClient> fakeCompositingWebViewClient = makeUnique<FrameTestHelpers::TestWebViewClient>(); FrameTestHelpers::WebViewHelper webViewHelper; WebViewImpl* webViewImpl = webViewHelper.initialize( true, nullptr, fakeCompositingWebViewClient.get(), nullptr, &configureAndroidCompositing); int pageWidth = 640; int pageHeight = 480; float browserControlsHeight = 50.0f; int smallestHeight = pageHeight - browserControlsHeight; webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight), browserControlsHeight, false); URLTestHelpers::registerMockedURLLoad(toKURL("http://example.com/foo.png"), "white-1x1.png"); WebURL baseURL = URLTestHelpers::toKURL("http://example.com/"); // This time the background is the default attachment. FrameTestHelpers::loadHTMLString(webViewImpl->mainFrame(), "<!DOCTYPE html>" "<style>" " body {" " margin: 0px;" " background: url('foo.png');" " background-size: cover;" " background-repeat: no-repeat;" " }" " div { height:1000px; width: 200px; }" "</style>" "<div></div>", baseURL); webViewImpl->updateAllLifecyclePhases(); Document* document = toLocalFrame(webViewImpl->page()->mainFrame())->document(); // A resize will do a layout synchronously so manually check that we don't // setNeedsLayout from viewportSizeChanged. document->view()->viewportSizeChanged(false, true); unsigned needsLayoutObjects = 0; unsigned totalObjects = 0; bool isSubtree = false; EXPECT_FALSE(document->view()->needsLayout()); document->view()->countObjectsNeedingLayout(needsLayoutObjects, totalObjects, isSubtree); EXPECT_EQ(0u, needsLayoutObjects); // Do a real resize to check for invalidations. document->view()->setTracksPaintInvalidations(true); webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, smallestHeight), browserControlsHeight, true); // The layout size should not have changed. ASSERT_EQ(pageWidth, document->view()->layoutSize().width()); ASSERT_EQ(smallestHeight, document->view()->layoutSize().height()); const RasterInvalidationTracking* invalidationTracking = document->layoutView() ->layer() ->graphicsLayerBacking() ->getRasterInvalidationTracking(); // No invalidations should have occured in FrameView scrolling. If // root-layer-scrolls is on, an invalidation is necessary for now, see the // comment and TODO in FrameView::viewportSizeChanged. // http://crbug.com/568847. bool rootLayerScrolling = GetParam(); if (rootLayerScrolling) EXPECT_TRUE(invalidationTracking); else EXPECT_FALSE(invalidationTracking); document->view()->setTracksPaintInvalidations(false); RuntimeEnabledFeatures::setInertTopControlsEnabled(originalInertTopControls); } // Make sure we don't crash when the visual viewport's height is 0. This can // happen transiently in autoresize mode and cause a crash. This test passes if // it doesn't crash. TEST_P(VisualViewportTest, AutoResizeNoHeightUsesMinimumHeight) { initializeWithDesktopSettings(); webViewImpl()->resizeWithBrowserControls(WebSize(0, 0), 0, false); webViewImpl()->enableAutoResizeMode(WebSize(25, 25), WebSize(100, 100)); WebURL baseURL = URLTestHelpers::toKURL("http://example.com/"); FrameTestHelpers::loadHTMLString(webViewImpl()->mainFrame(), "<!DOCTYPE html>" "<style>" " body {" " margin: 0px;" " }" " div { height:110vh; width: 110vw; }" "</style>" "<div></div>", baseURL); } } // namespace
41.388797
80
0.68702
xzhan96