hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
โŒ€
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
โŒ€
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
โŒ€
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
โŒ€
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
โŒ€
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
โŒ€
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
โŒ€
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
โŒ€
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
โŒ€
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
17f4fd2aa42aba2bc2d5e442a303d1bc9d49005b
7,579
cpp
C++
unittests/time/TimeTest.cpp
zavadovsky/stingraykit
33e6587535325f08769bd8392381d70d4d316410
[ "0BSD" ]
24
2015-03-04T16:30:03.000Z
2022-02-04T15:03:42.000Z
unittests/time/TimeTest.cpp
zavadovsky/stingraykit
33e6587535325f08769bd8392381d70d4d316410
[ "0BSD" ]
null
null
null
unittests/time/TimeTest.cpp
zavadovsky/stingraykit
33e6587535325f08769bd8392381d70d4d316410
[ "0BSD" ]
7
2015-04-08T12:22:58.000Z
2018-06-14T09:58:45.000Z
#include <gtest/gtest.h> #include <stingraykit/string/StringUtils.h> #include <stingraykit/time/Time.h> using namespace stingray; TEST(TimeTest, BrokenDownTime) { Time now = Time::Now(); { BrokenDownTime bdt = now.BreakDown(TimeKind::Local); Time reconstructed = Time::FromBrokenDownTime(bdt, TimeKind::Local); ASSERT_EQ(now, reconstructed); } { BrokenDownTime bdt = now.BreakDown(TimeKind::Utc); Time reconstructed = Time::FromBrokenDownTime(bdt, TimeKind::Utc); ASSERT_EQ(now, reconstructed); } } TEST(TimeTest, TimeZone_FromString) { { const auto timeZone = TimeZone::FromString("-05"); ASSERT_EQ(timeZone.GetMinutesFromUtc(), -300); } { const auto timeZone = TimeZone::FromString("+03"); ASSERT_EQ(timeZone.GetMinutesFromUtc(), 180); } { const auto timeZone = TimeZone::FromString("0400"); ASSERT_EQ(timeZone.GetMinutesFromUtc(), 240); } { const auto timeZone = TimeZone::FromString("+0130"); ASSERT_EQ(timeZone.GetMinutesFromUtc(), 90); } { const auto timeZone = TimeZone::FromString("-02:30"); ASSERT_EQ(timeZone.GetMinutesFromUtc(), -150); } } TEST(TimeTest, FromWindowsFileTime) { { const auto time = Time::FromWindowsFileTime(0); ASSERT_EQ(time.GetMilliseconds(), -11644473600000); } { const auto time = Time::FromWindowsFileTime(864003654321); ASSERT_EQ(time.GetMilliseconds(), -11644383545679); const auto bdt = time.BreakDown(TimeKind::Utc); ASSERT_EQ(bdt.Year, 1601); ASSERT_EQ(bdt.Month, 1); ASSERT_EQ(bdt.MonthDay, 2); ASSERT_EQ(bdt.Hours, 1); ASSERT_EQ(bdt.Minutes, 0); ASSERT_EQ(bdt.Seconds, 55); ASSERT_EQ(bdt.Milliseconds, -679); } } TEST(TimeTest, MjdDate) { #if 0 { BrokenDownTime bdt = Time::MJDtoEpoch(0).BreakDown(TimeKind::Utc); ASSERT_EQ(bdt.Year , 1858); ASSERT_EQ(bdt.Month , 11); ASSERT_EQ(bdt.MonthDay , 17); ASSERT_EQ(bdt.Hours , 0); ASSERT_EQ(bdt.Minutes , 0); ASSERT_EQ(bdt.Seconds , 0); ASSERT_EQ(bdt.Milliseconds , 0); } #endif { BrokenDownTime bdt = Time::MJDtoEpoch(57023).BreakDown(TimeKind::Utc); //2015-01-01 ASSERT_EQ(bdt.Year , 2015); ASSERT_EQ(bdt.Month , 1); ASSERT_EQ(bdt.MonthDay , 1); ASSERT_EQ(bdt.Hours , 0); ASSERT_EQ(bdt.Minutes , 0); ASSERT_EQ(bdt.Seconds , 0); ASSERT_EQ(bdt.Milliseconds , 0); } { BrokenDownTime bdt = Time::MJDtoEpoch(60676).BreakDown(TimeKind::Utc); //2025-01-01 ASSERT_EQ(bdt.Year , 2025); ASSERT_EQ(bdt.Month , 1); ASSERT_EQ(bdt.MonthDay , 1); ASSERT_EQ(bdt.Hours , 0); ASSERT_EQ(bdt.Minutes , 0); ASSERT_EQ(bdt.Seconds , 0); ASSERT_EQ(bdt.Milliseconds , 0); } } TEST(TimeTest, EpochDate) { { BrokenDownTime bdt = Time::FromTimeT(1735689600).BreakDown(TimeKind::Utc); //2025-01-01 ASSERT_EQ(bdt.Year , 2025); ASSERT_EQ(bdt.Month , 1); ASSERT_EQ(bdt.MonthDay , 1); ASSERT_EQ(bdt.Hours , 0); ASSERT_EQ(bdt.Minutes , 0); ASSERT_EQ(bdt.Seconds , 0); ASSERT_EQ(bdt.Milliseconds , 0); } { BrokenDownTime bdt = Time::FromTimeT(1420070400).BreakDown(TimeKind::Utc); //2015-01-01 ASSERT_EQ(bdt.Year , 2015); ASSERT_EQ(bdt.Month , 1); ASSERT_EQ(bdt.MonthDay , 1); ASSERT_EQ(bdt.Hours , 0); ASSERT_EQ(bdt.Minutes , 0); ASSERT_EQ(bdt.Seconds , 0); ASSERT_EQ(bdt.Milliseconds , 0); } } TEST(TimeTest, DISABLED_ToIso8601_Zeroes) { const std::string sample = "0000-00-00T00:00:00Z"; const Time testee = TimeUtility::FromIso8601(sample); const BrokenDownTime brokenDown = testee.BreakDown(); ASSERT_EQ(brokenDown.Year, 0); ASSERT_EQ(brokenDown.Month, 0); ASSERT_EQ(brokenDown.MonthDay, 0); ASSERT_EQ(brokenDown.Hours, 0); ASSERT_EQ(brokenDown.Minutes, 0); ASSERT_EQ(brokenDown.Seconds, 0); ASSERT_EQ(brokenDown.Milliseconds, 0); } TEST(TimeTest, ToIso8601_Common) { const std::string sample = "2000-09-21T12:45:05Z"; const Time testee = TimeUtility::FromIso8601(sample); const BrokenDownTime brokenDown = testee.BreakDown(); ASSERT_EQ(brokenDown.Year, 2000); ASSERT_EQ(brokenDown.Month, 9); ASSERT_EQ(brokenDown.MonthDay, 21); ASSERT_EQ(brokenDown.Hours, 12); ASSERT_EQ(brokenDown.Minutes, 45); ASSERT_EQ(brokenDown.Seconds, 5); ASSERT_EQ(brokenDown.Milliseconds, 0); } TEST(TimeTest, ToIso8601_Lowercase) { const std::string sample = "2000-09-21t12:45:05z"; const Time testee = TimeUtility::FromIso8601(sample); const BrokenDownTime brokenDown = testee.BreakDown(); ASSERT_EQ(brokenDown.Year, 2000); ASSERT_EQ(brokenDown.Month, 9); ASSERT_EQ(brokenDown.MonthDay, 21); ASSERT_EQ(brokenDown.Hours, 12); ASSERT_EQ(brokenDown.Minutes, 45); ASSERT_EQ(brokenDown.Seconds, 5); ASSERT_EQ(brokenDown.Milliseconds, 0); } TEST(TimeTest, ToIso8601_SecondFraction) { const std::string sample = "2000-09-21T12:45:05.0Z"; const Time testee = TimeUtility::FromIso8601(sample); const BrokenDownTime brokenDown = testee.BreakDown(); ASSERT_EQ(brokenDown.Year, 2000); ASSERT_EQ(brokenDown.Month, 9); ASSERT_EQ(brokenDown.MonthDay, 21); ASSERT_EQ(brokenDown.Hours, 12); ASSERT_EQ(brokenDown.Minutes, 45); ASSERT_EQ(brokenDown.Seconds, 5); ASSERT_NEAR(brokenDown.Milliseconds, 0, 5); } TEST(TimeTest, Iso8601_SecondFractionDecade) { const std::string sample = "2000-09-21T12:45:05.8Z"; const Time testee = TimeUtility::FromIso8601(sample); BrokenDownTime brokenDown = testee.BreakDown(); ASSERT_EQ(brokenDown.Year, 2000); ASSERT_EQ(brokenDown.Month, 9); ASSERT_EQ(brokenDown.MonthDay, 21); ASSERT_EQ(brokenDown.Hours, 12); ASSERT_EQ(brokenDown.Minutes, 45); ASSERT_EQ(brokenDown.Seconds, 5); ASSERT_NEAR(brokenDown.Milliseconds, 800, 5); } TEST(TimeTest, Iso8601_ZeroOffset) { const std::string sample = "2000-09-21T12:45:05+00:00"; const Time testee = TimeUtility::FromIso8601(sample); const BrokenDownTime brokenDown = testee.BreakDown(); ASSERT_EQ(brokenDown.Year, 2000); ASSERT_EQ(brokenDown.Month, 9); ASSERT_EQ(brokenDown.MonthDay, 21); ASSERT_EQ(brokenDown.Hours, 12); ASSERT_EQ(brokenDown.Minutes, 45); ASSERT_EQ(brokenDown.Seconds, 5); ASSERT_EQ(brokenDown.Milliseconds, 0); } TEST(TimeTest, ToIso8601_PositiveOffset) { const std::string sample = "2000-09-21T12:45:05+13:53"; const Time testee = TimeUtility::FromIso8601(sample); const BrokenDownTime brokenDown = testee.BreakDown(); ASSERT_EQ(brokenDown.Year, 2000); ASSERT_EQ(brokenDown.Month, 9); ASSERT_EQ(brokenDown.MonthDay, 20); ASSERT_EQ(brokenDown.Hours, 22); ASSERT_EQ(brokenDown.Minutes, 52); ASSERT_EQ(brokenDown.Seconds, 5); ASSERT_EQ(brokenDown.Milliseconds, 0); } TEST(TimeTest, ToIso8601_NegativeOffset) { const std::string sample = "2000-09-21T12:45:05-13:53"; const Time testee = TimeUtility::FromIso8601(sample); const BrokenDownTime brokenDown = testee.BreakDown(); ASSERT_EQ(brokenDown.Year, 2000); ASSERT_EQ(brokenDown.Month, 9); ASSERT_EQ(brokenDown.MonthDay, 22); ASSERT_EQ(brokenDown.Hours, 2); ASSERT_EQ(brokenDown.Minutes, 38); ASSERT_EQ(brokenDown.Seconds, 5); ASSERT_EQ(brokenDown.Milliseconds, 0); } TEST(TimeTest, ToIso8601_DateOnly) { const std::string sample = "2000-09-21"; const Time testee = TimeUtility::FromIso8601(sample); const BrokenDownTime brokenDown = testee.BreakDown(); ASSERT_EQ(brokenDown.Year, 2000); ASSERT_EQ(brokenDown.Month, 9); ASSERT_EQ(brokenDown.MonthDay, 21); ASSERT_EQ(brokenDown.Hours, 0); ASSERT_EQ(brokenDown.Minutes, 0); ASSERT_EQ(brokenDown.Seconds, 0); ASSERT_EQ(brokenDown.Milliseconds, 0); } TEST(TimeTest, ToIso8601_NoT_Failure) { const std::string sample = "2000-09-21.12:45:05Z"; ASSERT_ANY_THROW(TimeUtility::FromIso8601(sample)); }
27.067857
89
0.727273
zavadovsky
17f51d46015ebf633df199d9b6436d447422e454
2,760
cpp
C++
firmware/src/ssdp.cpp
chientung/smartplug
3247b15f4c410f0d9d0c4904277ff428485ebbf0
[ "MIT" ]
27
2018-08-28T12:37:22.000Z
2022-03-11T19:39:32.000Z
firmware/src/ssdp.cpp
chientung/smartplug
3247b15f4c410f0d9d0c4904277ff428485ebbf0
[ "MIT" ]
33
2018-09-10T07:26:21.000Z
2022-02-26T17:53:24.000Z
firmware/src/ssdp.cpp
chientung/smartplug
3247b15f4c410f0d9d0c4904277ff428485ebbf0
[ "MIT" ]
4
2019-02-01T22:38:52.000Z
2021-05-09T17:23:57.000Z
///////////////////////////////////////////////////////////////////////////// /** @file SSDP \copyright Copyright (c) 2018 Chris Byrne. All rights reserved. Licensed under the MIT License. Refer to LICENSE file in the project root. */ ///////////////////////////////////////////////////////////////////////////// #ifndef UNIT_TEST //- includes #include "ssdp.h" #include <ESPAsyncWebServer.h> ///////////////////////////////////////////////////////////////////////////// /// send response bool SSDPExt::begin() { SSDP.setSchemaURL("description.xml"); SSDP.setHTTPPort(80); SSDP.setDeviceType("upnp:rootdevice"); SSDP.setName("SmartPlug"); SSDP.setSerialNumber(""); SSDP.setURL("/"); SSDP.setModelName("SmartPlug"); SSDP.setModelNumber("SmartPlug"); SSDP.setModelURL("http://www.github.com/adapt0/smartplug"); SSDP.setManufacturer("Manufacturer"); SSDP.setManufacturerURL("http://www.github.com/adapt0/smartplug"); return SSDP.begin(); } ///////////////////////////////////////////////////////////////////////////// /// send response void SSDPExt::sendResponse(AsyncWebServerRequest* request) { auto* evil = reinterpret_cast<const SSDPExt*>(&SSDP); evil->sendResponse_(request); } /// send response void SSDPExt::sendResponse_(AsyncWebServerRequest* request) const { // reimplement SSDPClass::schema for use with AsyncWebServerRequest static const char SSDP_TEMPLATE[] = "<?xml version=\"1.0\"?>" "<root xmlns=\"urn:schemas-upnp-org:device-1-0\">" "<specVersion>" "<major>1</major>" "<minor>0</minor>" "</specVersion>" "<URLBase>http://%u.%u.%u.%u:%u/</URLBase>" // WiFi.localIP(), _port "<device>" "<deviceType>%s</deviceType>" "<friendlyName>%s</friendlyName>" "<presentationURL>%s</presentationURL>" "<serialNumber>%s</serialNumber>" "<modelName>%s</modelName>" "<modelNumber>%s</modelNumber>" "<modelURL>%s</modelURL>" "<manufacturer>%s</manufacturer>" "<manufacturerURL>%s</manufacturerURL>" "<UDN>uuid:%s</UDN>" "</device>" "</root>" ; IPAddress ip = WiFi.localIP(); char buffer[sizeof(SSDP_TEMPLATE) + sizeof(SSDPClass)]; sprintf(buffer, SSDP_TEMPLATE, ip[0], ip[1], ip[2], ip[3], _port, _deviceType, _friendlyName, _presentationURL, _serialNumber, _modelName, _modelNumber, _modelURL, _manufacturer, _manufacturerURL, _uuid ); request->send(200, "text/xml", buffer); } #endif // UNIT_TEST
32.857143
80
0.526087
chientung
17fc90d62ac97936df4e0b3dfa69815aacb367ff
5,439
cpp
C++
gen/blink/bindings/core/v8/V8HTMLDataListElement.cpp
gergul/MiniBlink
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
[ "Apache-2.0" ]
8
2019-05-05T16:38:05.000Z
2021-11-09T11:45:38.000Z
gen/blink/bindings/core/v8/V8HTMLDataListElement.cpp
gergul/MiniBlink
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
[ "Apache-2.0" ]
null
null
null
gen/blink/bindings/core/v8/V8HTMLDataListElement.cpp
gergul/MiniBlink
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
[ "Apache-2.0" ]
4
2018-12-14T07:52:46.000Z
2021-06-11T18:06:09.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 "V8HTMLDataListElement.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/V8DOMConfiguration.h" #include "bindings/core/v8/V8HTMLCollection.h" #include "bindings/core/v8/V8ObjectConstructor.h" #include "core/dom/ClassCollection.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "core/dom/TagCollection.h" #include "core/html/HTMLCollection.h" #include "core/html/HTMLDataListOptionsCollection.h" #include "core/html/HTMLFormControlsCollection.h" #include "core/html/HTMLTableRowsCollection.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo V8HTMLDataListElement::wrapperTypeInfo = { gin::kEmbedderBlink, V8HTMLDataListElement::domTemplate, V8HTMLDataListElement::refObject, V8HTMLDataListElement::derefObject, V8HTMLDataListElement::trace, 0, 0, V8HTMLDataListElement::preparePrototypeObject, V8HTMLDataListElement::installConditionallyEnabledProperties, "HTMLDataListElement", &V8HTMLElement::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::NodeClassId, WrapperTypeInfo::InheritFromEventTarget, WrapperTypeInfo::Dependent, WrapperTypeInfo::WillBeGarbageCollectedObject }; #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in HTMLDataListElement.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // bindings/core/v8/ScriptWrappable.h. const WrapperTypeInfo& HTMLDataListElement::s_wrapperTypeInfo = V8HTMLDataListElement::wrapperTypeInfo; namespace HTMLDataListElementV8Internal { static void optionsAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); HTMLDataListElement* impl = V8HTMLDataListElement::toImpl(holder); v8SetReturnValueFast(info, WTF::getPtr(impl->options()), impl); } static void optionsAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter"); HTMLDataListElementV8Internal::optionsAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } } // namespace HTMLDataListElementV8Internal static const V8DOMConfiguration::AccessorConfiguration V8HTMLDataListElementAccessors[] = { {"options", HTMLDataListElementV8Internal::optionsAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, }; static void installV8HTMLDataListElementTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "HTMLDataListElement", V8HTMLElement::domTemplate(isolate), V8HTMLDataListElement::internalFieldCount, 0, 0, V8HTMLDataListElementAccessors, WTF_ARRAY_LENGTH(V8HTMLDataListElementAccessors), 0, 0); v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Local<v8::FunctionTemplate> V8HTMLDataListElement::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8HTMLDataListElementTemplate); } bool V8HTMLDataListElement::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Local<v8::Object> V8HTMLDataListElement::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } HTMLDataListElement* V8HTMLDataListElement::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value) { return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0; } void V8HTMLDataListElement::refObject(ScriptWrappable* scriptWrappable) { #if !ENABLE(OILPAN) scriptWrappable->toImpl<HTMLDataListElement>()->ref(); #endif } void V8HTMLDataListElement::derefObject(ScriptWrappable* scriptWrappable) { #if !ENABLE(OILPAN) scriptWrappable->toImpl<HTMLDataListElement>()->deref(); #endif } } // namespace blink
45.325
585
0.797941
gergul
17fd466e46149e08035629ea84e1fc5c92584f7c
4,579
cc
C++
FW/src/lp/common/utilities/simple_circular_buffer.cc
thesofproject/converged-mpp
8e6e13d57b58d1c4ea1793de46f92f9ff819a01d
[ "BSD-3-Clause" ]
null
null
null
FW/src/lp/common/utilities/simple_circular_buffer.cc
thesofproject/converged-mpp
8e6e13d57b58d1c4ea1793de46f92f9ff819a01d
[ "BSD-3-Clause" ]
null
null
null
FW/src/lp/common/utilities/simple_circular_buffer.cc
thesofproject/converged-mpp
8e6e13d57b58d1c4ea1793de46f92f9ff819a01d
[ "BSD-3-Clause" ]
1
2021-12-08T09:43:25.000Z
2021-12-08T09:43:25.000Z
// SPDX-License-Identifier: BSD-3-Clause // // Copyright(c) 2021 Intel Corporation. All rights reserved. #include "simple_circular_buffer.h" #include <xtensa/tie/xt_hifi3.h> namespace dsp_fw { void copy_from_cb(uint8_t* out, size_t s_out, const uint8_t* in, size_t bytes) { size_t n_samples = bytes / 4; const ae_int32x2* sin = reinterpret_cast<const ae_int32x2*> ( in ); ae_int32x2* sout = reinterpret_cast<ae_int32x2*> ( out ); ae_int32x2 vs; if (!IS_ALIGNED(sin, 8)) { AE_L32_XC(vs, reinterpret_cast<const ae_int32*> (sin), 4 ); AE_S32_L_IP(vs, reinterpret_cast<ae_int32*> (sout), 4 ); n_samples--; } ae_valign align_out = AE_ZALIGN64(); for (size_t i = 0; i < n_samples / 2; i++ ) { AE_L32X2_XC( vs, sin, 8 ); AE_SA32X2_IP( vs, align_out, sout ); } AE_SA64POS_FP( align_out, sout ); if ( n_samples % 2 ) { AE_L32_XC(vs, reinterpret_cast<const ae_int32*> (sin), 0 ); AE_S32_L_IP(vs, reinterpret_cast<ae_int32*> (sout), 0 ); } } void copy_from_cb_(uint8_t* out, size_t s_out, const uint8_t* in, size_t n_samples) { const ae_int24x2* sin = reinterpret_cast<const ae_int24x2*> ( in ); ae_int24x2* sout = reinterpret_cast<ae_int24x2*> ( out ); ae_int24x2 vs; ae_valign align_in; ae_valign align_out = AE_ZALIGN64(); AE_LA24X2POS_PC( align_in, sin ); for (size_t i = 0; i < n_samples / 6; i++ ) { AE_LA24X2_IC( vs, align_in, sin ); AE_SA24X2_IP( vs, align_out, sout ); } size_t rest = n_samples % 6; if ( rest ) { AE_LA24X2_IC( vs, align_in, sin ); ae_int32 d32; if ( rest >= 3 ) { AE_SA24_IP( AE_MOVAD32_H( AE_MOVINT32X2_FROMINT24X2( vs ) ), align_out, sout ); d32 = AE_MOVAD32_L( AE_MOVINT32X2_FROMINT24X2( vs ) ); rest -= 3; } else { d32 = AE_MOVAD32_H( AE_MOVINT32X2_FROMINT24X2( vs ) ); } AE_SA64POS_FP( align_out, sout ); if ( 0 == rest-- ) return; out = reinterpret_cast<uint8_t*> ( sout ); *(out++) = static_cast<uint8_t> ( AE_MOVAD32_L( d32 ) ); if ( 0 == rest ) return; *out = static_cast<uint8_t> ( AE_MOVAD32_L( AE_SRLA32( d32, 8 ) ) ); return; } AE_SA64POS_FP( align_out, sout ); } ErrorCode RtCircularBuffer::PushDataFromCb(ByteArray* buffer) { kw_assert(buffer != NULL); const size_t size = buffer->size(); if (ba_.size() < (data_in_buffer_ + size)) { return ADSP_SUCCESS; } RETURN_EC_ON_FAIL(ba_.size() >= size, ADSP_OUT_OF_RESOURCES); if (size <= (uint32_t)(ba_.data_end() - write_ptr_)) { copy_from_cb(write_ptr_, ba_.size(), buffer->data(), size ); write_ptr_ += size; } else { uint32_t non_wrapped_size = (uint32_t)(ba_.data_end() - write_ptr_); uint32_t reminder_size = size - non_wrapped_size; copy_from_cb(write_ptr_, ba_.size(), buffer->data(), non_wrapped_size ); uint32_t c_beg = (uint32_t)AE_GETCBEGIN0(); uint32_t c_end = (uint32_t)AE_GETCEND0(); uint32_t b_beg = (uint32_t)buffer->data(); if ((b_beg + non_wrapped_size) < c_end) { copy_from_cb(ba_.data(), ba_.size(), buffer->data() + non_wrapped_size, reminder_size ); } else { size_t delta = (b_beg + non_wrapped_size) - c_end; uint8_t* new_begin = (uint8_t*)(c_beg + delta); copy_from_cb(ba_.data(), ba_.size(), new_begin, reminder_size ); } write_ptr_ = ba_.data() + reminder_size; } if (write_ptr_ == ba_.data_end()) { write_ptr_ = ba_.data(); } data_in_buffer_ += size; if (data_in_buffer_ > ba_.size()) { HALT_ON_ERROR(ADSP_CIRCULAR_BUFFER_OVERRUN); return ADSP_SUCCESS; } return ADSP_SUCCESS; } ErrorCode RtCircularBuffer::ReadData(ByteArray* buffer, size_t size) { // buffer is not circular // buffer is given // uint8_t* rp = read_ptr_; RETURN_EC_ON_FAIL(ba_.size() >= size, ADSP_OUT_OF_RESOURCES); RETURN_EC_ON_FAIL(size <= data_in_buffer_, ADSP_CIRCULAR_BUFFER_UNDERRUN); void* cached_c_beg = AE_GETCBEGIN0(); void* cached_c_end = AE_GETCEND0(); AE_SETCBEGIN0(ba_.data()); AE_SETCEND0(ba_.data_end()); copy_from_cb(buffer->data(), size, read_ptr(), size); AE_SETCBEGIN0(cached_c_beg); AE_SETCEND0(cached_c_end); data_in_buffer_ -= size; return ADSP_SUCCESS; } } //namespace dsp_fw
30.125
100
0.612798
thesofproject
aa004b7aeb515436363442d3e443913fa0641b60
7,014
cpp
C++
src/config.cpp
lms-org/lms
be5decd8e408bcefb82cbf9e0ee8f5deb04fd5a6
[ "Apache-2.0" ]
8
2016-09-20T20:54:56.000Z
2020-11-08T23:18:45.000Z
src/config.cpp
lms-org/lms
be5decd8e408bcefb82cbf9e0ee8f5deb04fd5a6
[ "Apache-2.0" ]
41
2016-06-07T17:26:11.000Z
2017-05-27T12:22:20.000Z
src/config.cpp
lms-org/lms
be5decd8e408bcefb82cbf9e0ee8f5deb04fd5a6
[ "Apache-2.0" ]
5
2016-10-19T15:04:45.000Z
2020-11-08T23:18:57.000Z
#include <fstream> #include <string> #include <cstdlib> #include <iostream> #include <unordered_map> #include <lms/config.h> #include "internal/string.h" namespace lms { struct Config::Private { std::unordered_map<std::string, std::string> properties; template <typename T> T get(const std::string &key, const T &defaultValue) const { auto it = properties.find(key); if (it == properties.end()) { return defaultValue; } else { return internal::string_cast_to<T>(it->second); } } template <typename T> T get(const std::string &key) const{ T def; return get(key,def); } template <typename T> void set(const std::string &key, const T &value) { properties[key] = internal::string_cast_from<T>(value); } template <typename T> std::vector<T> getArray(const std::string &key, const std::vector<T> &defaultValue) const { auto it = properties.find(key); if (it == properties.end()) { return defaultValue; } else { std::vector<T> result; for (const auto &parts : lms::internal::split(it->second, ',')) { result.push_back( internal::string_cast_to<T>(lms::internal::trim(parts))); } return result; } } template <typename T> std::vector<T> getArray(const std::string &key) const{ std::vector<T> def; return getArray(key,def); } template <typename T> void setArray(const std::string &key, const std::vector<T> &value) { std::ostringstream oss; for (auto it = value.begin(); it != value.end(); it++) { if (it != value.begin()) { oss << " "; } oss << internal::string_cast_from(*it); } properties[key] = oss.str(); } }; Config::Config() : dptr(new Private) {} Config::~Config() { delete dptr; } Config::Config(const Config &other) : dptr(new Private(*other.dptr)) {} void Config::load(std::istream &in) { std::string line; bool isMultiline = false; std::string lineBuffer; while (internal::safeGetline(in, line)) { if (internal::trim(line).empty() || line[0] == '#') { // ignore empty lines and comment lines isMultiline = false; } else { bool isCurrentMultiline = line[line.size() - 1] == '\\'; std::string normalizedLine = isCurrentMultiline ? line.erase(line.size() - 1) : line; if (isMultiline) { lineBuffer += normalizedLine; } else { lineBuffer = normalizedLine; } isMultiline = isCurrentMultiline; } if (!isMultiline) { size_t index = lineBuffer.find_first_of('='); if (index != std::string::npos) { dfunc() ->properties[internal::trim(lineBuffer.substr(0, index))] = internal::trim(lineBuffer.substr(index + 1)); } } } } bool Config::loadFromFile(const std::string &path) { std::ifstream in(path); if (!in.is_open()) { return false; } load(in); in.close(); return true; } bool Config::hasKey(const std::string &key) const { return dfunc()->properties.count(key) == 1; } bool Config::empty() const { return dfunc()->properties.empty(); } void Config::clear() { dfunc()->properties.clear(); } // Template specializations get<T> template <> std::string Config::get<std::string>(const std::string &key, const std::string &defaultValue) const { return dfunc()->get(key, defaultValue); } template <> int Config::get<int>(const std::string &key, const int &defaultValue) const { return dfunc()->get(key, defaultValue); } template <> float Config::get<float>(const std::string &key, const float &defaultValue) const { return dfunc()->get(key, defaultValue); } template<> double Config::get<double>(const std::string &key, const double &defaultValue) const { return dfunc()->get(key, defaultValue); } template <> bool Config::get<bool>(const std::string &key, const bool &defaultValue) const { return dfunc()->get(key, defaultValue); } // Template specializations set<T> template <> void Config::set<std::string>(const std::string &key, const std::string &value) { dfunc()->set(key, value); } template <> void Config::set<int>(const std::string &key, const int &value) { dfunc()->set(key, value); } template <> void Config::set<float>(const std::string &key, const float &value) { dfunc()->set(key, value); } template <> void Config::set<bool>(const std::string &key, const bool &value) { dfunc()->set(key, value); } template <> void Config::set<double>(const std::string &key, const double &value) { dfunc()->set(key, value); } // Template specializations getArray<T> template <> std::vector<std::string> Config::getArray<std::string>( const std::string &key, const std::vector<std::string> &defaultValue) const { return dfunc()->getArray(key, defaultValue); } template <> std::vector<int> Config::getArray<int>(const std::string &key, const std::vector<int> &defaultValue) const { return dfunc()->getArray(key, defaultValue); } template <> std::vector<float> Config::getArray<float>(const std::string &key, const std::vector<float> &defaultValue) const { return dfunc()->getArray(key, defaultValue); } template <> std::vector<bool> Config::getArray<bool>(const std::string &key, const std::vector<bool> &defaultValue) const { return dfunc()->getArray(key, defaultValue); } template <> std::vector<double> Config::getArray<double>(const std::string &key, const std::vector<double> &defaultValue) const { return dfunc()->getArray(key, defaultValue); } // Template specializations setArray<T> template <> void Config::setArray<std::string>(const std::string &key, const std::vector<std::string> &value) { dfunc()->setArray(key, value); } template <> void Config::setArray<int>(const std::string &key, const std::vector<int> &value) { dfunc()->setArray(key, value); } template <> void Config::setArray<float>(const std::string &key, const std::vector<float> &value) { dfunc()->setArray(key, value); } template <> void Config::setArray<bool>(const std::string &key, const std::vector<bool> &value) { dfunc()->setArray(key, value); } template <> void Config::setArray<double>(const std::string &key, const std::vector<double> &value) { dfunc()->setArray(key, value); } } // namespace lms
27.72332
83
0.578129
lms-org
aa0525b1e304a5502a00df3c6058610aaa733929
1,373
cpp
C++
Problems/0322. Coin Change.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0322. Coin Change.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0322. Coin Change.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
class Solution { public: int coinChange(vector<int>& coins, int amount) { int n = coins.size(); // 1D MATRIX APPROACH ========================== vector<int> dp(amount+1, amount+1); dp[0]=0; //0 ways to make 0 amount for(int i=1; i<=amount; i++){ for(int j=0; j<n; j++){ if(coins[j] <= i) //if coins is applicable // min of exclusion and inclusion dp[i] = min(dp[i], 1+ dp[i - coins[j]]); } } return dp[amount] > amount ? -1:dp[amount]; // 2D MATRIX APPROACH ========================== // vector<vector<int>> dp(n+1, vector<int>(amount+1,amount+1)); // // i=0 -> coin = 0 already initialised with amount+1 // for(int i=1; i<=n; i++){ // for(int j=0; j<=amount; j++){ // if(j==0) //amount = 0 // dp[i][j] = 0; // else if(coins[i-1] > j) //coin val > amount // dp[i][j] = dp[i-1][j]; //copy last coin's dp // else // //min of inclusion and exclusion // dp[i][j] = min(1+ dp[i][j-coins[i-1]], dp[i-1][j]); // } // } // return dp[n][amount] > amount ? -1:dp[n][amount]; } };
35.205128
74
0.388201
KrKush23
aa06077527bf6d1a837a7a4879fcedc3e4b7cb1a
505
cpp
C++
codes/TC_2020/FALL/3.cpp
pikaninja/collection-of-chessbot-codes
a56e5e4e38c293ecddd2ce4b0b922723ca833089
[ "MIT" ]
null
null
null
codes/TC_2020/FALL/3.cpp
pikaninja/collection-of-chessbot-codes
a56e5e4e38c293ecddd2ce4b0b922723ca833089
[ "MIT" ]
null
null
null
codes/TC_2020/FALL/3.cpp
pikaninja/collection-of-chessbot-codes
a56e5e4e38c293ecddd2ce4b0b922723ca833089
[ "MIT" ]
null
null
null
//miles #include <iostream> #include <string> using namespace std; int main() { string s; getline(cin,s); string x = ""; for(int i = 0; i < s.length(); i++){ x+=s[i]; if(x == "LLL"){ cout << "A"; x = ""; }else if(x == "SSL"){ cout << "T"; x = ""; }else if(x == "SLL"){ cout << "G"; x = ""; }else if(x == "SLS"){ cout << "C"; x = ""; } } }
18.035714
40
0.320792
pikaninja
aa08cba3638129d6eda29d3a00238ff7717930d2
17,368
hpp
C++
libraries/chain/include/graphene/chain/protocol/types.hpp
cyvasia/cyva
e98b26abfe8e96d0e1470626b0a525d44f9372a9
[ "MIT" ]
null
null
null
libraries/chain/include/graphene/chain/protocol/types.hpp
cyvasia/cyva
e98b26abfe8e96d0e1470626b0a525d44f9372a9
[ "MIT" ]
null
null
null
libraries/chain/include/graphene/chain/protocol/types.hpp
cyvasia/cyva
e98b26abfe8e96d0e1470626b0a525d44f9372a9
[ "MIT" ]
null
null
null
/* (c) 2018 CYVA. For details refer to LICENSE */ /* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <fc/container/flat_fwd.hpp> #include <fc/io/varint.hpp> #include <fc/io/enum_type.hpp> #include <fc/crypto/sha224.hpp> #include <fc/crypto/elliptic.hpp> #include <fc/reflect/reflect.hpp> #include <fc/reflect/variant.hpp> #include <fc/optional.hpp> #include <fc/safe.hpp> #include <fc/container/flat.hpp> #include <fc/string.hpp> #include <fc/io/raw.hpp> #include <fc/uint128.hpp> #include <fc/static_variant.hpp> #include <fc/smart_ref_fwd.hpp> #include <fc/crypto/base58.hpp> #include <fc/crypto/ripemd160.hpp> #include <cyva/encrypt/crypto_types.hpp> #include <memory> #include <vector> #include <deque> #include <cstdint> #include <graphene/db/object_id.hpp> #include <graphene/chain/protocol/config.hpp> namespace graphene { namespace chain { using namespace graphene::db; using std::map; using std::vector; using std::unordered_map; using std::string; using std::deque; using std::shared_ptr; using std::weak_ptr; using std::unique_ptr; using std::set; using std::pair; using std::enable_shared_from_this; using std::tie; using std::make_pair; using fc::smart_ref; using fc::variant_object; using fc::variant; using fc::enum_type; using fc::optional; using fc::unsigned_int; using fc::signed_int; using fc::time_point_sec; using fc::time_point; using fc::safe; using fc::flat_map; using fc::flat_set; using fc::static_variant; using fc::ecc::range_proof_type; using fc::ecc::range_proof_info; using fc::ecc::commitment_type; struct void_t{}; typedef fc::ecc::private_key private_key_type; typedef fc::sha256 chain_id_type; typedef cyva::encrypt::CustodyData custody_data_type; typedef cyva::encrypt::CustodyProof custody_proof_type; typedef cyva::encrypt::DIntegerString bigint_type; typedef cyva::encrypt::CiphertextString ciphertext_type; typedef cyva::encrypt::DeliveryProofString delivery_proof_type; enum reserved_spaces { relative_protocol_ids = 0, protocol_ids = 1, implementation_ids = 2 }; inline bool is_relative( object_id_type o ){ return o.space() == 0; } /** * List all object types from all namespaces here so they can * be easily reflected and displayed in debug output. If a 3rd party * wants to extend the core code then they will have to change the * packed_object::type field from enum_type to uint16 to avoid * warnings when converting packed_objects to/from json. */ enum object_type { null_object_type, base_object_type, account_object_type, asset_object_type, miner_object_type, custom_object_type, proposal_object_type, operation_history_object_type, withdraw_permission_object_type, vesting_balance_object_type, OBJECT_TYPE_COUNT ///< Sentry value which contains the number of different object types }; enum impl_object_type { impl_global_property_object_type, impl_dynamic_global_property_object_type, impl_reserved0_object_type, // formerly index_meta_object_type, TODO: delete me impl_asset_dynamic_data_type, impl_account_balance_object_type, impl_account_statistics_object_type, impl_transaction_object_type, impl_block_summary_object_type, impl_account_transaction_history_object_type, impl_chain_property_object_type, impl_miner_schedule_object_type, impl_budget_record_object_type, impl_transaction_detail_object_type, impl_blinded_balance_object_type, impl_confidential_tx_object_type }; //typedef fc::unsigned_int object_id_type; //typedef uint64_t object_id_type; class account_object; class committee_member_object; class miner_object; class asset_object; class custom_object; class proposal_object; class operation_history_object; class vesting_balance_object; typedef object_id< protocol_ids, account_object_type, account_object> account_id_type; typedef object_id< protocol_ids, asset_object_type, asset_object> asset_id_type; typedef object_id< protocol_ids, miner_object_type, miner_object> miner_id_type; typedef object_id< protocol_ids, custom_object_type, custom_object> custom_id_type; typedef object_id< protocol_ids, proposal_object_type, proposal_object> proposal_id_type; typedef object_id< protocol_ids, operation_history_object_type, operation_history_object> operation_history_id_type; typedef object_id< protocol_ids, vesting_balance_object_type, vesting_balance_object> vesting_balance_id_type; // implementation types class global_property_object; class dynamic_global_property_object; class asset_dynamic_data_object; class account_balance_object; class account_statistics_object; class transaction_object; class block_summary_object; class account_transaction_history_object; class chain_property_object; class miner_schedule_object; class budget_record_object; class transaction_detail_object; class blinded_balance_object; typedef object_id< implementation_ids, impl_global_property_object_type, global_property_object> global_property_id_type; typedef object_id< implementation_ids, impl_dynamic_global_property_object_type, dynamic_global_property_object> dynamic_global_property_id_type; typedef object_id< implementation_ids, impl_asset_dynamic_data_type, asset_dynamic_data_object> asset_dynamic_data_id_type; typedef object_id< implementation_ids, impl_account_balance_object_type, account_balance_object> account_balance_id_type; typedef object_id< implementation_ids, impl_account_statistics_object_type,account_statistics_object> account_statistics_id_type; typedef object_id< implementation_ids, impl_transaction_object_type, transaction_object> transaction_obj_id_type; typedef object_id< implementation_ids, impl_block_summary_object_type, block_summary_object> block_summary_id_type; typedef object_id< implementation_ids, impl_account_transaction_history_object_type, account_transaction_history_object> account_transaction_history_id_type; typedef object_id< implementation_ids, impl_chain_property_object_type, chain_property_object> chain_property_id_type; typedef object_id< implementation_ids, impl_miner_schedule_object_type, miner_schedule_object> miner_schedule_id_type; typedef object_id< implementation_ids, impl_budget_record_object_type, budget_record_object > budget_record_id_type; typedef object_id< implementation_ids, impl_transaction_detail_object_type, transaction_detail_object > transaction_detail_id_type; typedef object_id< implementation_ids, impl_blinded_balance_object_type, blinded_balance_object > blinded_balance_id_type; typedef fc::array<char, GRAPHENE_MAX_ASSET_SYMBOL_LENGTH> symbol_type; typedef fc::ripemd160 block_id_type; typedef fc::ripemd160 checksum_type; typedef fc::ripemd160 transaction_id_type; typedef fc::sha256 digest_type; typedef fc::ecc::compact_signature signature_type; typedef safe<int64_t> share_type; typedef uint16_t weight_type; struct public_key_type { struct binary_key { binary_key() {} uint32_t check = 0; fc::ecc::public_key_data data; }; fc::ecc::public_key_data key_data; public_key_type(); public_key_type( const fc::ecc::public_key_data& data ); public_key_type( const fc::ecc::public_key& pubkey ); explicit public_key_type( const std::string& base58str ); operator fc::ecc::public_key_data() const; operator fc::ecc::public_key() const; explicit operator std::string() const; friend bool operator == ( const public_key_type& p1, const fc::ecc::public_key& p2); friend bool operator == ( const public_key_type& p1, const public_key_type& p2); friend bool operator != ( const public_key_type& p1, const public_key_type& p2); // TODO: This is temporary for testing bool is_valid_v1( const std::string& base58str ); static std::string from_nums(std::string str, bool even = false) { binary_key k; k.data.data[0] = even ? 0x02 : 0x03; str = str.substr(0, 32); auto sz = str.length( ); auto offset = 1 + 32 - sz; memcpy(&k.data.data[offset], str.data( ), sz); k.check = fc::ripemd160::hash(k.data.data, k.data.size( ))._hash[0]; auto data = fc::raw::pack(k); return std::string(GRAPHENE_ADDRESS_PREFIX) + fc::to_base58(data.data( ), data.size( )); } }; inline bool operator < ( const public_key_type& a, const public_key_type& b ) { int i=0; while (i<33 ) { if(a.key_data.at(i) < b.key_data.at(i) ) return true; if(a.key_data.at(i) > b.key_data.at(i) ) return false; i++; } return false; } struct extended_public_key_type { struct binary_key { binary_key() {} uint32_t check = 0; fc::ecc::extended_key_data data; }; fc::ecc::extended_key_data key_data; extended_public_key_type(); extended_public_key_type( const fc::ecc::extended_key_data& data ); extended_public_key_type( const fc::ecc::extended_public_key& extpubkey ); explicit extended_public_key_type( const std::string& base58str ); operator fc::ecc::extended_public_key() const; explicit operator std::string() const; friend bool operator == ( const extended_public_key_type& p1, const fc::ecc::extended_public_key& p2); friend bool operator == ( const extended_public_key_type& p1, const extended_public_key_type& p2); friend bool operator != ( const extended_public_key_type& p1, const extended_public_key_type& p2); }; struct extended_private_key_type { struct binary_key { binary_key() {} uint32_t check = 0; fc::ecc::extended_key_data data; }; fc::ecc::extended_key_data key_data; extended_private_key_type(); extended_private_key_type( const fc::ecc::extended_key_data& data ); extended_private_key_type( const fc::ecc::extended_private_key& extprivkey ); explicit extended_private_key_type( const std::string& base58str ); operator fc::ecc::extended_private_key() const; explicit operator std::string() const; friend bool operator == ( const extended_private_key_type& p1, const fc::ecc::extended_private_key& p2); friend bool operator == ( const extended_private_key_type& p1, const extended_private_key_type& p2); friend bool operator != ( const extended_private_key_type& p1, const extended_private_key_type& p2); }; } } // graphene::chain namespace fc { void to_variant( const graphene::chain::public_key_type& var, fc::variant& vo ); void from_variant( const fc::variant& var, graphene::chain::public_key_type& vo ); void to_variant( const graphene::chain::extended_public_key_type& var, fc::variant& vo ); void from_variant( const fc::variant& var, graphene::chain::extended_public_key_type& vo ); void to_variant( const graphene::chain::extended_private_key_type& var, fc::variant& vo ); void from_variant( const fc::variant& var, graphene::chain::extended_private_key_type& vo ); } FC_REFLECT( graphene::chain::public_key_type, (key_data) ) FC_REFLECT( graphene::chain::public_key_type::binary_key, (data)(check) ) FC_REFLECT( graphene::chain::extended_public_key_type, (key_data) ) FC_REFLECT( graphene::chain::extended_public_key_type::binary_key, (check)(data) ) FC_REFLECT( graphene::chain::extended_private_key_type, (key_data) ) FC_REFLECT( graphene::chain::extended_private_key_type::binary_key, (check)(data) ) FC_REFLECT_ENUM( graphene::chain::object_type, (null_object_type) (base_object_type) (account_object_type) (asset_object_type) (miner_object_type) (custom_object_type) (proposal_object_type) (operation_history_object_type) (withdraw_permission_object_type) (vesting_balance_object_type) (OBJECT_TYPE_COUNT) ) FC_REFLECT_ENUM( graphene::chain::impl_object_type, (impl_global_property_object_type) (impl_dynamic_global_property_object_type) (impl_reserved0_object_type) (impl_asset_dynamic_data_type) (impl_account_balance_object_type) (impl_account_statistics_object_type) (impl_transaction_object_type) (impl_block_summary_object_type) (impl_account_transaction_history_object_type) (impl_chain_property_object_type) (impl_miner_schedule_object_type) (impl_budget_record_object_type) (impl_transaction_detail_object_type) (impl_blinded_balance_object_type) (impl_confidential_tx_object_type) ) FC_REFLECT_TYPENAME( graphene::chain::share_type ) FC_REFLECT_TYPENAME( graphene::chain::account_id_type ) FC_REFLECT_TYPENAME( graphene::chain::asset_id_type ) FC_REFLECT_TYPENAME( graphene::chain::miner_id_type ) FC_REFLECT_TYPENAME( graphene::chain::custom_id_type ) FC_REFLECT_TYPENAME( graphene::chain::proposal_id_type ) FC_REFLECT_TYPENAME( graphene::chain::operation_history_id_type ) FC_REFLECT_TYPENAME( graphene::chain::vesting_balance_id_type ) FC_REFLECT_TYPENAME( graphene::chain::global_property_id_type ) FC_REFLECT_TYPENAME( graphene::chain::dynamic_global_property_id_type ) FC_REFLECT_TYPENAME( graphene::chain::asset_dynamic_data_id_type ) FC_REFLECT_TYPENAME( graphene::chain::account_balance_id_type ) FC_REFLECT_TYPENAME( graphene::chain::account_statistics_id_type ) FC_REFLECT_TYPENAME( graphene::chain::transaction_obj_id_type ) FC_REFLECT_TYPENAME( graphene::chain::block_summary_id_type ) FC_REFLECT_TYPENAME( graphene::chain::account_transaction_history_id_type ) FC_REFLECT_TYPENAME( graphene::chain::budget_record_id_type ) FC_REFLECT_TYPENAME( graphene::chain::transaction_detail_id_type ) FC_REFLECT_TYPENAME( graphene::chain::blinded_balance_id_type ) FC_REFLECT_EMPTY( graphene::chain::void_t )
46.814016
152
0.661389
cyvasia
aa0a7b16813bd572ada4de1cb17fdf969caf0638
227
cpp
C++
slides/assets/physics_engines/snippets/cryengine.cpp
dodocloud/aph-tutorials
85a3d1db0bb4d6add3156f07bde5f597dca34123
[ "MIT" ]
null
null
null
slides/assets/physics_engines/snippets/cryengine.cpp
dodocloud/aph-tutorials
85a3d1db0bb4d6add3156f07bde5f597dca34123
[ "MIT" ]
null
null
null
slides/assets/physics_engines/snippets/cryengine.cpp
dodocloud/aph-tutorials
85a3d1db0bb4d6add3156f07bde5f597dca34123
[ "MIT" ]
1
2022-01-17T20:55:02.000Z
2022-01-17T20:55:02.000Z
if (min(min(min(body.M,ibody_inv.x),ibody_inv.y),ibody_inv.z)<0) { body.M = body.Minv = 0; body.Ibody_inv.zero(); body.Ibody.zero(); } else { body.P = (body.v=v)*body.M; body.L = body.q*(body.Ibody*(!body.q*(body.w=w))); }
32.428571
66
0.621145
dodocloud
aa0ad9ad4dd219b99636017624cb712976491fa0
4,581
hpp
C++
include/huffman/huff_pc_ss.hpp
kurpicz/pwm
7e0837d0e3da6cf7b63e80b04a75a61b73b91779
[ "BSD-2-Clause" ]
14
2017-02-27T10:15:50.000Z
2021-12-06T18:36:53.000Z
include/huffman/huff_pc_ss.hpp
kurpicz/pwm
7e0837d0e3da6cf7b63e80b04a75a61b73b91779
[ "BSD-2-Clause" ]
5
2017-04-21T16:05:10.000Z
2019-03-26T07:08:47.000Z
include/huffman/huff_pc_ss.hpp
kurpicz/pwm
7e0837d0e3da6cf7b63e80b04a75a61b73b91779
[ "BSD-2-Clause" ]
3
2018-10-31T14:12:59.000Z
2021-03-09T15:37:50.000Z
/******************************************************************************* * include/huffman/huff_pc.hpp * * Copyright (C) 2018 Marvin Lรถbel <loebel.marvin@gmail.com> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #include <cstddef> #include <cstdint> #include <iostream> #include "huffman/huff_building_blocks.hpp" #include "huffman/huff_codes.hpp" template <typename AlphabetType, typename ContextType, typename HuffCodes> void huff_pc_ss(AlphabetType const* text, uint64_t const size, uint64_t const levels, HuffCodes const& codes, ContextType& ctx, span<uint64_t const> const) { auto& bv = ctx.bv(); // While calculating the histogram, we also compute the first level huff_scan_text_compute_first_level_bv_and_full_hist(text, size, bv, ctx, codes); for (uint64_t level = levels - 1; level > ContextType::MAX_UPPER_LEVELS; --level) { auto&& borders = ctx.lower_borders_at_level(level); auto&& hist = ctx.hist_at_level(level); if (borders.size() > 0) { borders[0] = 0; } uint64_t containing_prev_block = 0; for (uint64_t pos = 1; pos < ctx.hist_size(level); ++pos) { // This is only required if we compute matrices [[maybe_unused]] auto const prev_block = ctx.rho(level, pos - 1); auto const this_block = ctx.rho(level, pos); if (hist.count(this_block) > 0) { borders[this_block] = borders[containing_prev_block] + hist[containing_prev_block]; containing_prev_block = this_block; } // NB: The above calulcation produces _wrong_ border offsets // for huffman codes that are one-shorter than the current level. // // Since those codes will not be used in the loop below, this does not // produce wrong or out-of-bound accesses. if (ContextType::compute_rho) { ctx.set_rho(level - 1, pos - 1, prev_block >> 1); } } // The number of 0s is the position of the first 1 in the previous level if constexpr (ContextType::compute_zeros) { ctx.zeros()[level - 1] = borders[1]; } } for (uint64_t level = std::min(levels - 1, ContextType::MAX_UPPER_LEVELS); level > 0; --level) { auto&& borders = ctx.upper_borders_at_level(level); auto&& hist = ctx.hist_at_level(level); borders[0] = 0; uint64_t containing_prev_block = 0; for (uint64_t pos = 1; pos < ctx.hist_size(level); ++pos) { // This is only required if we compute matrices [[maybe_unused]] auto const prev_block = ctx.rho(level, pos - 1); auto const this_block = ctx.rho(level, pos); if (hist.count(this_block) > 0) { borders[this_block] = borders[containing_prev_block] + hist[containing_prev_block]; containing_prev_block = this_block; } // NB: The above calulcation produces _wrong_ border offsets // for huffman codes that are one-shorter than the current level. // // Since those codes will not be used in the loop below, this does not // produce wrong or out-of-bound accesses. if (ContextType::compute_rho) { ctx.set_rho(level - 1, pos - 1, prev_block >> 1); } } // The number of 0s is the position of the first 1 in the previous level if constexpr (ContextType::compute_zeros) { ctx.zeros()[level - 1] = borders[1]; } } for (uint64_t i = 0; i < size; ++i) { const code_pair cp = codes.encode_symbol(text[i]); for (uint64_t level = cp.code_length() - 1; level > ContextType::MAX_UPPER_LEVELS; --level) { auto&& borders = ctx.lower_borders_at_level(level); auto const [prefix, bit] = cp.prefix_bit(level); uint64_t const pos = borders[prefix]++; uint64_t const word_pos = 63ULL - (pos & 63ULL); bv[level][pos >> 6] |= (bit << word_pos); } for (uint64_t level = std::min(cp.code_length() - 1, ContextType::MAX_UPPER_LEVELS); level > 0; --level) { auto&& borders = ctx.upper_borders_at_level(level); auto const [prefix, bit] = cp.prefix_bit(level); uint64_t const pos = borders[prefix]++; uint64_t const word_pos = 63ULL - (pos & 63ULL); bv[level][pos >> 6] |= (bit << word_pos); } } } /******************************************************************************/
36.943548
80
0.591356
kurpicz
aa0d16b316f39f58a5dab58ad876890c8a9ff8fb
260
cpp
C++
Game_PC/src/Butterfly.cpp
neuroprod/omniBotProto
5abf1b5a9846ba093325af7a86ee2d7b8cbe12e6
[ "MIT" ]
46
2017-03-03T20:34:23.000Z
2021-11-07T02:37:44.000Z
Game_PC/src/Butterfly.cpp
neuroprod/omniBotProto
5abf1b5a9846ba093325af7a86ee2d7b8cbe12e6
[ "MIT" ]
null
null
null
Game_PC/src/Butterfly.cpp
neuroprod/omniBotProto
5abf1b5a9846ba093325af7a86ee2d7b8cbe12e6
[ "MIT" ]
18
2017-04-27T09:40:47.000Z
2021-12-06T05:38:48.000Z
// // Butterfly.cpp // Game_PC // // Created by Kris Temmerman on 03/10/2017. // // #include "Butterfly.hpp" using namespace ci; using namespace ci::app; using namespace std; ButterflyRef Butterfly::create() { return make_shared<Butterfly>(); }
11.304348
44
0.673077
neuroprod
aa10887002b21c22c61dc722e288c1d02bcc1e0e
8,978
cpp
C++
tephra/src/tephra/descriptor.cpp
cvbn127/captal-engine
93a5f428b4cee810b529b7c9a9b3bf6504c8f32f
[ "MIT" ]
78
2021-11-02T13:55:43.000Z
2022-02-25T09:37:22.000Z
tephra/src/tephra/descriptor.cpp
cvbn127/captal-engine
93a5f428b4cee810b529b7c9a9b3bf6504c8f32f
[ "MIT" ]
null
null
null
tephra/src/tephra/descriptor.cpp
cvbn127/captal-engine
93a5f428b4cee810b529b7c9a9b3bf6504c8f32f
[ "MIT" ]
6
2021-11-03T06:56:22.000Z
2022-01-13T19:11:29.000Z
//MIT License // //Copyright (c) 2021 Alexy Pellegrini // //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 "descriptor.hpp" #include <cassert> #include <captal_foundation/stack_allocator.hpp> #include "vulkan/vulkan_functions.hpp" #include "renderer.hpp" #include "buffer.hpp" #include "texture.hpp" using namespace tph::vulkan::functions; namespace tph { descriptor_set_layout::descriptor_set_layout(renderer& renderer, std::span<const descriptor_set_layout_binding> bindings) { stack_memory_pool<1024 * 2> pool{}; auto native_bindings{make_stack_vector<VkDescriptorSetLayoutBinding>(pool)}; native_bindings.reserve(std::size(bindings)); for(auto&& binding : bindings) { VkDescriptorSetLayoutBinding native_binding{}; native_binding.stageFlags = static_cast<VkShaderStageFlags>(binding.stages); native_binding.binding = binding.binding; native_binding.descriptorType = static_cast<VkDescriptorType>(binding.type); native_binding.descriptorCount = binding.count; native_bindings.emplace_back(native_binding); } m_layout = vulkan::descriptor_set_layout{underlying_cast<VkDevice>(renderer), native_bindings}; } void set_object_name(renderer& renderer, const descriptor_set_layout& object, const std::string& name) { VkDebugUtilsObjectNameInfoEXT info{}; info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT; info.objectType = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; info.objectHandle = reinterpret_cast<std::uint64_t>(underlying_cast<VkDescriptorSetLayout>(object)); info.pObjectName = std::data(name); if(auto result{vkSetDebugUtilsObjectNameEXT(underlying_cast<VkDevice>(renderer), &info)}; result != VK_SUCCESS) throw vulkan::error{result}; } descriptor_pool::descriptor_pool(renderer& renderer, std::span<const descriptor_pool_size> sizes, std::optional<std::uint32_t> max_sets) { stack_memory_pool<1024> pool{}; auto native_sizes{make_stack_vector<VkDescriptorPoolSize>(pool)}; native_sizes.reserve(std::size(sizes)); for(auto&& size : sizes) { auto& native_size{native_sizes.emplace_back()}; native_size.type = static_cast<VkDescriptorType>(size.type); native_size.descriptorCount = size.count; } if(!max_sets.has_value()) { std::uint32_t total_size{}; for(auto&& size : sizes) { total_size += size.count; } max_sets = total_size; } m_descriptor_pool = vulkan::descriptor_pool{underlying_cast<VkDevice>(renderer), native_sizes, *max_sets}; } void set_object_name(renderer& renderer, const descriptor_pool& object, const std::string& name) { VkDebugUtilsObjectNameInfoEXT info{}; info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT; info.objectType = VK_OBJECT_TYPE_DESCRIPTOR_POOL; info.objectHandle = reinterpret_cast<std::uint64_t>(underlying_cast<VkDescriptorPool>(object)); info.pObjectName = std::data(name); if(auto result{vkSetDebugUtilsObjectNameEXT(underlying_cast<VkDevice>(renderer), &info)}; result != VK_SUCCESS) throw vulkan::error{result}; } descriptor_set::descriptor_set(renderer& renderer, descriptor_pool& pool, descriptor_set_layout& layout) :m_descriptor_set{underlying_cast<VkDevice>(renderer), underlying_cast<VkDescriptorPool>(pool), underlying_cast<VkDescriptorSetLayout>(layout)} { } void set_object_name(renderer& renderer, const descriptor_set& object, const std::string& name) { VkDebugUtilsObjectNameInfoEXT info{}; info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT; info.objectType = VK_OBJECT_TYPE_DESCRIPTOR_SET; info.objectHandle = reinterpret_cast<std::uint64_t>(underlying_cast<VkDescriptorSet>(object)); info.pObjectName = std::data(name); if(auto result{vkSetDebugUtilsObjectNameEXT(underlying_cast<VkDevice>(renderer), &info)}; result != VK_SUCCESS) throw vulkan::error{result}; } void write_descriptors(renderer& renderer, std::span<const descriptor_write> writes) { update_descriptors(renderer, writes, std::span<const descriptor_copy>{}); } void copy_descriptors(renderer& renderer, std::span<const descriptor_copy> copies) { update_descriptors(renderer, std::span<const descriptor_write>{}, copies); } void update_descriptors(renderer& renderer, std::span<const descriptor_write> writes, std::span<const descriptor_copy> copies) { std::size_t image_count{}; std::size_t buffer_count{}; for(auto&& write : writes) { assert(!std::holds_alternative<std::monostate>(write.info) && "tph::write_descriptors contains undefined write target."); if(std::holds_alternative<descriptor_texture_info>(write.info)) { ++image_count; } else if(std::holds_alternative<descriptor_buffer_info>(write.info)) { ++buffer_count; } } stack_memory_pool<1024 * 4> pool{}; auto native_images{make_stack_vector<VkDescriptorImageInfo>(pool)}; native_images.reserve(image_count); auto buffers_image{make_stack_vector<VkDescriptorBufferInfo>(pool)}; buffers_image.reserve(buffer_count); auto native_writes{make_stack_vector<VkWriteDescriptorSet>(pool)}; native_writes.reserve(std::size(writes)); for(auto&& write : writes) { VkWriteDescriptorSet native_write{}; native_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; native_write.dstSet = underlying_cast<VkDescriptorSet>(write.descriptor_set.get()); native_write.dstBinding = write.binding; native_write.dstArrayElement = write.array_index; native_write.descriptorType = static_cast<VkDescriptorType>(write.type); native_write.descriptorCount = 1; if(std::holds_alternative<descriptor_texture_info>(write.info)) { auto& write_info{std::get<descriptor_texture_info>(write.info)}; VkDescriptorImageInfo image_info{}; image_info.sampler = write_info.sampler ? underlying_cast<VkSampler>(*write_info.sampler) : VkSampler{}; image_info.imageView = write_info.texture_view ? underlying_cast<VkImageView>(*write_info.texture_view) : VkImageView{}; image_info.imageLayout = static_cast<VkImageLayout>(write_info.layout); native_write.pImageInfo = &native_images.emplace_back(image_info); } else if(std::holds_alternative<descriptor_buffer_info>(write.info)) { auto& write_info{std::get<descriptor_buffer_info>(write.info)}; VkDescriptorBufferInfo buffer_info{}; buffer_info.buffer = underlying_cast<VkBuffer>(write_info.buffer.get()); buffer_info.offset = write_info.offset; buffer_info.range = write_info.size; native_write.pBufferInfo = &buffers_image.emplace_back(buffer_info); } native_writes.emplace_back(native_write); } auto native_copies{make_stack_vector<VkCopyDescriptorSet>(pool)}; native_copies.reserve(std::size(copies)); for(auto&& copy : copies) { VkCopyDescriptorSet& native_copy{native_copies.emplace_back()}; native_copy.sType = VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET; native_copy.srcSet = underlying_cast<VkDescriptorSet>(copy.source_set.get()); native_copy.srcBinding = copy.source_binding; native_copy.srcArrayElement = copy.source_array_index; native_copy.dstSet = underlying_cast<VkDescriptorSet>(copy.destination_set.get()); native_copy.dstBinding = copy.destination_binding; native_copy.dstArrayElement = copy.destination_array_index; native_copy.descriptorCount = copy.count; } vkUpdateDescriptorSets(underlying_cast<VkDevice>(renderer), static_cast<std::uint32_t>(std::size(native_writes)), std::data(native_writes), static_cast<std::uint32_t>(std::size(native_copies)), std::data(native_copies)); } }
39.725664
224
0.736578
cvbn127
aa1a411584f5d23e498cdda72490e27d8fe6dcc2
5,402
cpp
C++
server/nhocr/nhocr-0.21/makedic/makedic.cpp
el-hoshino/HandwrAIter
b9fcc0db975bac615e6331d2a8147b596dd11028
[ "MIT" ]
17
2017-04-11T19:54:05.000Z
2022-01-31T21:04:05.000Z
server/nhocr/nhocr-0.21/makedic/makedic.cpp
el-hoshino/HandwrAIter
b9fcc0db975bac615e6331d2a8147b596dd11028
[ "MIT" ]
null
null
null
server/nhocr/nhocr-0.21/makedic/makedic.cpp
el-hoshino/HandwrAIter
b9fcc0db975bac615e6331d2a8147b596dd11028
[ "MIT" ]
3
2017-05-11T16:57:31.000Z
2019-01-28T13:53:39.000Z
/*-------------------------------------------------------------- Make character dictionary makedic v1.1 (C) 2005-2010 Hideaki Goto (see accompanying LICENSE file) Written by H.Goto, Dec. 2005 Revised by H.Goto, Feb. 2010 --------------------------------------------------------------*/ //#define Use_DEfeature #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include "utypes.h" #include "ufilep.h" #include "siplib.h" #include "ocrbase.h" #include "feature_PLOVE.h" #ifdef Use_DEfeature #include "feature_DEF.h" #endif static int sw_help = 0; static int sw_verbose = 0; static int sw_dim = FVECDIM_PLM; static int n_cat = 0; static int n_set = 1; /*---------------------------------------------- Save dictionary ----------------------------------------------*/ static int save_dic(RecBase *Rec, char *dicfile){ FILE *fp; int cid; if ( NULL == (fp = fopen(dicfile,"wb")) ){ fprintf(stderr,"Failed to open \"%s\" for output.\n",dicfile); return(-1); } for ( cid=0 ; cid<n_cat ; cid++ ){ if ( Rec->dic[cid].write_vector(fp) ){ fprintf(stderr,"Failed to write data to \"%s\".\n",dicfile); fclose(fp); return(3); } } if ( fclose(fp) ){ fprintf(stderr,"Failed to write data to \"%s\".\n",dicfile); return(3); } return(0); } /*---------------------------------------------- Load the first vector file ----------------------------------------------*/ static int load_vec(RecBase *Rec, char *vecfile, int dim){ FILE *fp; int cid; struct stat statinfo; if ( stat(vecfile,&statinfo) ){ fprintf(stderr,"Failed to load vector file \"%s\".\n",vecfile); return(-1); } n_cat = statinfo.st_size / sizeof(double) / dim; if ( n_cat <= 0 ){ fprintf(stderr,"Vector file \"%s\" is too short.\n",vecfile); return(-1); } if ( Rec->alloc(n_cat, dim, 1) ){ fprintf(stderr,"Failed to load vector file \"%s\".\n",vecfile); return(-1); } if ( NULL == (fp = fopen(vecfile,"rb")) ){ fprintf(stderr,"Failed to load vector file \"%s\".\n",vecfile); return(-1); } for ( cid=0 ; cid<n_cat ; cid++ ){ if ( Rec->dic[cid].read_vector(fp) ){ fprintf(stderr,"Failed to load vector file \"%s\".\n",vecfile); fclose(fp); return(-1); } } fclose(fp); if ( sw_verbose ){ fprintf(stderr,"%d categories found.\n",n_cat); } return(0); } /*---------------------------------------------- Add another vector file ----------------------------------------------*/ static int add_vec(RecBase *Rec, char *vecfile){ FILE *fp; int cid; FeatureVector vec(Rec->dic[0].dim); if ( NULL == (fp = fopen(vecfile,"rb")) ){ fprintf(stderr,"Failed to load vector file \"%s\".\n",vecfile); return(-1); } for ( cid=0 ; cid<n_cat ; cid++ ){ // if ( Rec->dic[cid].read_vector(fp) ){ if ( vec.read_vector(fp) ){ fprintf(stderr,"Failed to load vector file \"%s\".\n",vecfile); fclose(fp); return(-1); } Rec->dic[cid] += vec; } fclose(fp); n_set++; return(0); } /*---------------------------------------------- Main routine ----------------------------------------------*/ int main(int ac, char **av){ char *outfile = NULL; char *infile = NULL; int i,k, cid; int rcode; RecBase Rec; int sw_err = 0; for ( k=1 ; k<ac ; k++ ){ if ( 0 == strcmp(av[k],"-h") ){ sw_help = 1; continue; } if ( 0 == strcmp(av[k],"-v") ){ sw_verbose = 1; continue; } if ( 0 == strcmp(av[k],"-dim") ){ if ( ++k >= ac ){ sw_err = 1; break; } sw_dim = atoi(av[k]); if ( sw_dim < 1 ){ sw_err = 1; break; } continue; } if ( 0 == strcmp(av[k],"-F") ){ if ( ++k >= ac ){ sw_err = 1; break; } #ifdef Use_DEfeature if ( 0 == strcmp(av[k],"DEF") ){ sw_dim = FVECDIM_DEF; continue; } if ( 0 == strcmp(av[k],"DEFOL") ){ sw_dim = FVECDIM_DEFOL; continue; } #endif if ( 0 == strcmp(av[k],"P-LOVE") ){ sw_dim = FVECDIM_PLOVE; continue; } if ( 0 == strcmp(av[k],"PLOVE") ){ sw_dim = FVECDIM_PLOVE; continue; } if ( 0 == strcmp(av[k],"P-LM") ){ sw_dim = FVECDIM_PLM; continue; } if ( 0 == strcmp(av[k],"PLM") ){ sw_dim = FVECDIM_PLM; continue; } sw_err = 1; break; } if ( 0 == strcmp(av[k],"-o") ){ if ( ++k >= ac ){ sw_err = 1; break; } outfile = av[k]; continue; } if ( infile == NULL ){ infile = av[k]; break; } } if ( sw_err || sw_help || outfile == NULL || infile == NULL ){ fputs("Make character dictionary\n",stderr); fputs("makedic v1.1 Copyright (C) 2005-2010 Hideaki Goto\n",stderr); fputs("usage: makedic [options] -o out_dic_file vec_file1 vec_file2 ...\n",stderr); #ifdef Use_DEfeature fputs(" -F type : feature type PLOVE/PLM(default)/DEF/DEFOL\n",stderr); #else fputs(" -F type : feature type PLOVE/PLM(default)\n",stderr); #endif fprintf(stderr," -dim N : dimension of feature vector (default:%d)\n",FVECDIM_PLM); fputs(" -v : verbose mode\n",stderr); return(1); } rcode = load_vec(&Rec, infile, sw_dim); if ( rcode ) return(rcode); for ( k++ ; k<ac ; k++ ){ rcode = add_vec(&Rec, av[k]); if ( rcode ) return(rcode); } if ( sw_verbose ){ fprintf(stderr,"%d sets loaded.\n",n_set); } /* normalization */ for ( cid=0 ; cid<Rec.n_cat ; cid++ ){ for ( i=0 ; i<Rec.dic[cid].dim ; i++ ){ Rec.dic[cid].e[i] /= (double)n_set; } } save_dic(&Rec, outfile); return(rcode); }
24.554545
93
0.536283
el-hoshino
aa1ba6daa0399115d30241c8191bf9a23df07db1
358
hpp
C++
src/sdm/core/states.hpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
src/sdm/core/states.hpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
src/sdm/core/states.hpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
#pragma once #include <sdm/types.hpp> #include <sdm/core/state/state.hpp> // #include <sdm/core/state/history.hpp> // #include <sdm/core/state/beliefs.hpp> // #include <sdm/core/state/occupancy_state.hpp> #include <sdm/core/state/serial_state.hpp> // #include <sdm/core/state/serial_belief_state.hpp> // #include <sdm/core/state/serial_occupancy_state.hpp>
32.545455
55
0.751397
SDMStudio
aa1ba7dd1119eda20123b694f8f6eca5b22b2ff8
975
hpp
C++
soccer/planning/primitives/CreatePath.hpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
soccer/planning/primitives/CreatePath.hpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
soccer/planning/primitives/CreatePath.hpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
#pragma once #include "planning/MotionConstraints.hpp" #include "planning/Trajectory.hpp" #include "planning/primitives/PathSmoothing.hpp" namespace Planning::CreatePath { /** * Generate a smooth path from start to goal avoiding obstacles. */ Trajectory rrt(const LinearMotionInstant& start, const LinearMotionInstant& goal, const MotionConstraints& motionConstraints, RJ::Time startTime, const Geometry2d::ShapeSet& static_obstacles, const std::vector<DynamicObstacle>& dynamic_obstacles = {}, const std::vector<Geometry2d::Point>& biasWaypoints = {}); /** * Generate a smooth path from start to goal disregarding obstacles. */ Trajectory simple( const LinearMotionInstant& start, const LinearMotionInstant& goal, const MotionConstraints& motionConstraints, RJ::Time startTime, const std::vector<Geometry2d::Point>& intermediatePoints = {}); } // namespace Planning::CreatePath
36.111111
78
0.716923
kasohrab
aa2189162c3b04b1b1facd84eaca45707d24a94c
2,818
cpp
C++
src/qt/src/corelib/arch/parisc/qatomic_parisc.cpp
martende/phantomjs
5cecd7dde7b8fd04ad2c036d16f09a8d2a139854
[ "BSD-3-Clause" ]
1
2015-03-16T20:49:09.000Z
2015-03-16T20:49:09.000Z
src/qt/src/corelib/arch/parisc/qatomic_parisc.cpp
firedfox/phantomjs
afb0707c9db7b5e693ad1b216a50081565c08ebb
[ "BSD-3-Clause" ]
null
null
null
src/qt/src/corelib/arch/parisc/qatomic_parisc.cpp
firedfox/phantomjs
afb0707c9db7b5e693ad1b216a50081565c08ebb
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qglobal.h> #include <QtCore/qhash.h> QT_BEGIN_NAMESPACE QT_USE_NAMESPACE #define UNLOCKED {-1,-1,-1,-1} #define UNLOCKED2 UNLOCKED,UNLOCKED #define UNLOCKED4 UNLOCKED2,UNLOCKED2 #define UNLOCKED8 UNLOCKED4,UNLOCKED4 #define UNLOCKED16 UNLOCKED8,UNLOCKED8 #define UNLOCKED32 UNLOCKED16,UNLOCKED16 #define UNLOCKED64 UNLOCKED32,UNLOCKED32 #define UNLOCKED128 UNLOCKED64,UNLOCKED64 #define UNLOCKED256 UNLOCKED128,UNLOCKED128 // use a 4k page for locks static int locks[256][4] = { UNLOCKED256 }; int *getLock(volatile void *addr) { return locks[qHash(const_cast<void *>(addr)) % 256]; } static int *align16(int *lock) { ulong off = (((ulong) lock) % 16); return off ? (int *)(ulong(lock) + 16 - off) : lock; } extern "C" { int q_ldcw(volatile int *addr); void q_atomic_lock(int *lock) { // ldcw requires a 16-byte aligned address volatile int *x = align16(lock); while (q_ldcw(x) == 0) ; } void q_atomic_unlock(int *lock) { lock[0] = lock[1] = lock[2] = lock[3] = -1; } } QT_END_NAMESPACE
31.662921
77
0.679205
martende
aa21c0b4124ca9ee858ff56965e21eaf059ff1d7
5,289
cpp
C++
src/compiler/ParserProductionRule.cpp
LucvandenBrand/OperatorGraph
a15f2c9acfc9265e5ed5cbd89a8d3f7f638cb565
[ "MIT" ]
null
null
null
src/compiler/ParserProductionRule.cpp
LucvandenBrand/OperatorGraph
a15f2c9acfc9265e5ed5cbd89a8d3f7f638cb565
[ "MIT" ]
null
null
null
src/compiler/ParserProductionRule.cpp
LucvandenBrand/OperatorGraph
a15f2c9acfc9265e5ed5cbd89a8d3f7f638cb565
[ "MIT" ]
null
null
null
#include <algorithm> #include <cctype> #include <functional> #include <boost/variant/get.hpp> #include <pga/compiler/Symbol.h> #include <pga/compiler/Operator.h> #include "ParserUtils.h" #include "ParserOperator.h" #include "ParserSymbol.h" #include "ParserProductionRule.h" namespace PGA { namespace Compiler { namespace Parser { bool ProductionRule::check(Logger& logger) { double probabilitySum = 0; unsigned int else_idx = 0; for (auto it = successors.begin(); it != successors.end(); ++it) { double tmp_prob = 0; unsigned int idx = static_cast<unsigned int>(std::distance(successors.begin(), it)); switch (it->which()) { case 0: { Symbol& sym = boost::get<Symbol>(*it); tmp_prob = sym.probability; if (tmp_prob == -1) if (else_idx != 0) { logger.addMessage(Logger::LL_ERROR, "(line = %d, column = %d) multiple *else* branches in stochastic rule (%s)", line + 1, column, symbol.c_str()); return false; } else else_idx = idx; else probabilitySum += tmp_prob; break; } case 1: { Operator& op = boost::get<Operator>(*it); tmp_prob = op.probability; if (tmp_prob == -1) if (else_idx != 0) { logger.addMessage(Logger::LL_ERROR, "(line = %d, column = %d) multiple *else* branches in stochastic rule (%s)", line + 1, column, symbol.c_str()); return false; } else else_idx = idx; else { probabilitySum += tmp_prob; if (op.check(logger) == false) return false; } break; } } } if (probabilitySum >= 100) { logger.addMessage(Logger::LL_ERROR, "probability sum of stochastic rule(%s) is %d (more than 100%)", symbol.c_str(), probabilitySum); return false; } else { double else_prob = 100 - probabilitySum; switch (successors.at(else_idx).which()) { case 0: boost::get<Symbol>(successors.at(else_idx)).probability = else_prob; break; case 1: boost::get<Operator>(successors.at(else_idx)).probability = else_prob; break; } } return true; } void ProductionRule::convertToAbstraction(std::vector<PGA::Compiler::Terminal>& terminals, PGA::Compiler::Rule& rule) const { rule.symbol = trim(symbol); double probabilitySum = 0; switch (successors.at(0).which()) { case 0: probabilitySum = boost::get<Symbol>(successors.at(0)).probability; break; case 1: probabilitySum = boost::get<Operator>(successors.at(0)).probability; break; } // TODO: Maybe support more rule successors (e.g. A --> B C D;) // For this, changes to the abstraction in ProductionRule.h need to be made // but this is not supported anyway (see next comment) if ((probabilitySum == 100) && (successors.size() == 1)) { for (auto it = successors.begin(); it != successors.end(); ++it) { switch (it->which()) { case 0: // shouldn't happen: RuleA --> RuleB produces cpp code with only CallRule<RuleB>, which is not supported afaik (but this works in the editor) rule.successor = std::shared_ptr<PGA::Compiler::Successor>(new PGA::Compiler::Symbol(boost::get<Symbol>(*it).symbol)); rule.successor->id = nextSuccessorIdx(); rule.successor->myrule = symbol; break; case 1: Operator op = boost::get<Operator>(*it); PGA::Compiler::Operator* newOperator = new PGA::Compiler::Operator(); newOperator->myrule = symbol; newOperator->id = nextSuccessorIdx(); if (op.operator_ == OperatorType::GENERATE) { for (auto it = terminals.begin(); it != terminals.end(); ++it) { // The 'if' below is true when there's a RuleA --> Generate() if (std::find(it->symbols.begin(), it->symbols.end(), symbol) != it->symbols.end()) { newOperator->type = OperatorType::GENERATE; for (const auto& termAttr : it->parameters) newOperator->terminalAttributes.push_back(termAttr); break; } } } rule.successor = std::shared_ptr<PGA::Compiler::Successor>(newOperator); op.convertToAbstraction(terminals, *newOperator, rule); break; } } } else { Operator stochasticOperator; stochasticOperator.operator_ = STOCHASTIC; for (auto it = successors.begin(); it != successors.end(); ++it) { ParameterizedSuccessor parameterizedSuccessor(*it); switch (it->which()) { case 0: parameterizedSuccessor.parameters.push_back(boost::get<Symbol>(*it).probability); break; case 1: parameterizedSuccessor.parameters.push_back(boost::get<Operator>(*it).probability); break; } stochasticOperator.successors.push_back(parameterizedSuccessor); } PGA::Compiler::Operator* newOperator = new PGA::Compiler::Operator(); newOperator->id = nextSuccessorIdx(); newOperator->myrule = symbol; rule.successor = std::shared_ptr<PGA::Compiler::Successor>(newOperator); stochasticOperator.convertToAbstraction(terminals, *newOperator, rule); } } } } }
29.220994
155
0.607487
LucvandenBrand
aa230dc8b07ea8f54f90d006f116822cb4a903f1
25,341
cpp
C++
src/hardware/gus.cpp
electroduck/boxless
f3a587c73c8003acac3f40392e323600aa6ebb62
[ "BSD-3-Clause" ]
null
null
null
src/hardware/gus.cpp
electroduck/boxless
f3a587c73c8003acac3f40392e323600aa6ebb62
[ "BSD-3-Clause" ]
null
null
null
src/hardware/gus.cpp
electroduck/boxless
f3a587c73c8003acac3f40392e323600aa6ebb62
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2002-2010 The DOSBox Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* $Id: gus.cpp,v 1.37 2009-09-03 16:03:01 c2woody Exp $ */ #include <string.h> #include <iomanip> #include <sstream> #include "dosbox.h" #include "inout.h" #include "mixer.h" #include "dma.h" #include "pic.h" #include "setup.h" #include "shell.h" #include "math.h" #include "regs.h" using namespace std; //Extra bits of precision over normal gus #define WAVE_BITS 2 #define WAVE_FRACT (9+WAVE_BITS) #define WAVE_FRACT_MASK ((1 << WAVE_FRACT)-1) #define WAVE_MSWMASK ((1 << (16+WAVE_BITS))-1) #define WAVE_LSWMASK (0xffffffff ^ WAVE_MSWMASK) //Amount of precision the volume has #define RAMP_FRACT (10) #define RAMP_FRACT_MASK ((1 << RAMP_FRACT)-1) #define GUS_BASE myGUS.portbase #define GUS_RATE myGUS.rate #define LOG_GUS 0 Bit8u adlib_commandreg; static MixerChannel * gus_chan; static Bit8u irqtable[8] = { 0, 2, 5, 3, 7, 11, 12, 15 }; static Bit8u dmatable[8] = { 0, 1, 3, 5, 6, 7, 0, 0 }; static Bit8u GUSRam[1024*1024]; // 1024K of GUS Ram static Bit32s AutoAmp = 512; static Bit16u vol16bit[4096]; static Bit32u pantable[16]; class GUSChannels; static void CheckVoiceIrq(void); struct GFGus { Bit8u gRegSelect; Bit16u gRegData; Bit32u gDramAddr; Bit16u gCurChannel; Bit8u DMAControl; Bit16u dmaAddr; Bit8u TimerControl; Bit8u SampControl; Bit8u mixControl; Bit8u ActiveChannels; Bit32u basefreq; struct GusTimer { Bit8u value; bool reached; bool raiseirq; bool masked; bool running; float delay; } timers[2]; Bit32u rate; Bitu portbase; Bit8u dma1; Bit8u dma2; Bit8u irq1; Bit8u irq2; bool irqenabled; bool ChangeIRQDMA; // IRQ status register values Bit8u IRQStatus; Bit32u ActiveMask; Bit8u IRQChan; Bit32u RampIRQ; Bit32u WaveIRQ; } myGUS; Bitu DEBUG_EnableDebugger(void); static void GUS_DMA_Callback(DmaChannel * chan,DMAEvent event); // Returns a single 16-bit sample from the Gravis's RAM static INLINE Bit32s GetSample(Bit32u Delta, Bit32u CurAddr, bool eightbit) { Bit32u useAddr; Bit32u holdAddr; useAddr = CurAddr >> WAVE_FRACT; if (eightbit) { if (Delta >= (1 << WAVE_FRACT)) { Bit32s tmpsmall = (Bit8s)GUSRam[useAddr]; return tmpsmall << 8; } else { // Interpolate Bit32s w1 = ((Bit8s)GUSRam[useAddr+0]) << 8; Bit32s w2 = ((Bit8s)GUSRam[useAddr+1]) << 8; Bit32s diff = w2 - w1; return (w1+((diff*(Bit32s)(CurAddr&WAVE_FRACT_MASK ))>>WAVE_FRACT)); } } else { // Formula used to convert addresses for use with 16-bit samples holdAddr = useAddr & 0xc0000L; useAddr = useAddr & 0x1ffffL; useAddr = useAddr << 1; useAddr = (holdAddr | useAddr); if(Delta >= (1 << WAVE_FRACT)) { return (GUSRam[useAddr+0] | (((Bit8s)GUSRam[useAddr+1]) << 8)); } else { // Interpolate Bit32s w1 = (GUSRam[useAddr+0] | (((Bit8s)GUSRam[useAddr+1]) << 8)); Bit32s w2 = (GUSRam[useAddr+2] | (((Bit8s)GUSRam[useAddr+3]) << 8)); Bit32s diff = w2 - w1; return (w1+((diff*(Bit32s)(CurAddr&WAVE_FRACT_MASK ))>>WAVE_FRACT)); } } } class GUSChannels { public: Bit32u WaveStart; Bit32u WaveEnd; Bit32u WaveAddr; Bit32u WaveAdd; Bit8u WaveCtrl; Bit16u WaveFreq; Bit32u RampStart; Bit32u RampEnd; Bit32u RampVol; Bit32u RampAdd; Bit32u RampAddReal; Bit8u RampRate; Bit8u RampCtrl; Bit8u PanPot; Bit8u channum; Bit32u irqmask; Bit32u PanLeft; Bit32u PanRight; Bit32s VolLeft; Bit32s VolRight; GUSChannels(Bit8u num) { channum = num; irqmask = 1 << num; WaveStart = 0; WaveEnd = 0; WaveAddr = 0; WaveAdd = 0; WaveFreq = 0; WaveCtrl = 3; RampRate = 0; RampStart = 0; RampEnd = 0; RampCtrl = 3; RampAdd = 0; RampVol = 0; VolLeft = 0; VolRight = 0; PanLeft = 0; PanRight = 0; PanPot = 0x7; }; void WriteWaveFreq(Bit16u val) { WaveFreq = val; double frameadd = double(val >> 1)/512.0; //Samples / original gus frame double realadd = (frameadd*(double)myGUS.basefreq/(double)GUS_RATE) * (double)(1 << WAVE_FRACT); WaveAdd = (Bit32u)realadd; } void WriteWaveCtrl(Bit8u val) { Bit32u oldirq=myGUS.WaveIRQ; WaveCtrl = val & 0x7f; if ((val & 0xa0)==0xa0) myGUS.WaveIRQ|=irqmask; else myGUS.WaveIRQ&=~irqmask; if (oldirq != myGUS.WaveIRQ) CheckVoiceIrq(); } INLINE Bit8u ReadWaveCtrl(void) { Bit8u ret=WaveCtrl; if (myGUS.WaveIRQ & irqmask) ret|=0x80; return ret; } void UpdateWaveRamp(void) { WriteWaveFreq(WaveFreq); WriteRampRate(RampRate); } void WritePanPot(Bit8u val) { PanPot = val; PanLeft = pantable[0x0f-(val & 0xf)]; PanRight = pantable[(val & 0xf)]; UpdateVolumes(); } Bit8u ReadPanPot(void) { return PanPot; } void WriteRampCtrl(Bit8u val) { Bit32u old=myGUS.RampIRQ; RampCtrl = val & 0x7f; if ((val & 0xa0)==0xa0) myGUS.RampIRQ|=irqmask; else myGUS.RampIRQ&=~irqmask; if (old != myGUS.RampIRQ) CheckVoiceIrq(); } INLINE Bit8u ReadRampCtrl(void) { Bit8u ret=RampCtrl; if (myGUS.RampIRQ & irqmask) ret|=0x80; return ret; } void WriteRampRate(Bit8u val) { RampRate = val; double frameadd = (double)(RampRate & 63)/(double)(1 << (3*(val >> 6))); double realadd = (frameadd*(double)myGUS.basefreq/(double)GUS_RATE) * (double)(1 << RAMP_FRACT); RampAdd = (Bit32u)realadd; } INLINE void WaveUpdate(void) { if (WaveCtrl & 0x3) return; Bit32s WaveLeft; if (WaveCtrl & 0x40) { WaveAddr-=WaveAdd; WaveLeft=WaveStart-WaveAddr; } else { WaveAddr+=WaveAdd; WaveLeft=WaveAddr-WaveEnd; } if (WaveLeft<0) return; /* Generate an IRQ if needed */ if (WaveCtrl & 0x20) { myGUS.WaveIRQ|=irqmask; } /* Check for not being in PCM operation */ if (RampCtrl & 0x04) return; /* Check for looping */ if (WaveCtrl & 0x08) { /* Bi-directional looping */ if (WaveCtrl & 0x10) WaveCtrl^=0x40; WaveAddr = (WaveCtrl & 0x40) ? (WaveEnd-WaveLeft) : (WaveStart+WaveLeft); } else { WaveCtrl|=1; //Stop the channel WaveAddr = (WaveCtrl & 0x40) ? WaveStart : WaveEnd; } } INLINE void UpdateVolumes(void) { Bit32s templeft=RampVol - PanLeft; templeft&=~(templeft >> 31); Bit32s tempright=RampVol - PanRight; tempright&=~(tempright >> 31); VolLeft=vol16bit[templeft >> RAMP_FRACT]; VolRight=vol16bit[tempright >> RAMP_FRACT]; } INLINE void RampUpdate(void) { /* Check if ramping enabled */ if (RampCtrl & 0x3) return; Bit32s RampLeft; if (RampCtrl & 0x40) { RampVol-=RampAdd; RampLeft=RampStart-RampVol; } else { RampVol+=RampAdd; RampLeft=RampVol-RampEnd; } if (RampLeft<0) { UpdateVolumes(); return; } /* Generate an IRQ if needed */ if (RampCtrl & 0x20) { myGUS.RampIRQ|=irqmask; } /* Check for looping */ if (RampCtrl & 0x08) { /* Bi-directional looping */ if (RampCtrl & 0x10) RampCtrl^=0x40; RampVol = (RampCtrl & 0x40) ? (RampEnd-RampLeft) : (RampStart+RampLeft); } else { RampCtrl|=1; //Stop the channel RampVol = (RampCtrl & 0x40) ? RampStart : RampEnd; } UpdateVolumes(); } void generateSamples(Bit32s * stream,Bit32u len) { int i; Bit32s tmpsamp; bool eightbit; if (RampCtrl & WaveCtrl & 3) return; eightbit = ((WaveCtrl & 0x4) == 0); for(i=0;i<(int)len;i++) { // Get sample tmpsamp = GetSample(WaveAdd, WaveAddr, eightbit); // Output stereo sample stream[i<<1]+= tmpsamp * VolLeft; stream[(i<<1)+1]+= tmpsamp * VolRight; WaveUpdate(); RampUpdate(); } } }; static GUSChannels *guschan[32]; static GUSChannels *curchan; static void GUSReset(void) { if((myGUS.gRegData & 0x1) == 0x1) { // Reset adlib_commandreg = 85; myGUS.IRQStatus = 0; myGUS.timers[0].raiseirq = false; myGUS.timers[1].raiseirq = false; myGUS.timers[0].reached = false; myGUS.timers[1].reached = false; myGUS.timers[0].running = false; myGUS.timers[1].running = false; myGUS.timers[0].value = 0xff; myGUS.timers[1].value = 0xff; myGUS.timers[0].delay = 0.080f; myGUS.timers[1].delay = 0.320f; myGUS.ChangeIRQDMA = false; myGUS.mixControl = 0x0b; // latches enabled by default LINEs disabled // Stop all channels int i; for(i=0;i<32;i++) { guschan[i]->RampVol=0; guschan[i]->WriteWaveCtrl(0x1); guschan[i]->WriteRampCtrl(0x1); guschan[i]->WritePanPot(0x7); } myGUS.IRQChan = 0; } if ((myGUS.gRegData & 0x4) != 0) { myGUS.irqenabled = true; } else { myGUS.irqenabled = false; } } static INLINE void GUS_CheckIRQ(void) { if (myGUS.IRQStatus && (myGUS.mixControl & 0x08)) PIC_ActivateIRQ(myGUS.irq1); } static void CheckVoiceIrq(void) { myGUS.IRQStatus&=0x9f; Bitu totalmask=(myGUS.RampIRQ|myGUS.WaveIRQ) & myGUS.ActiveMask; if (!totalmask) return; if (myGUS.RampIRQ) myGUS.IRQStatus|=0x40; if (myGUS.WaveIRQ) myGUS.IRQStatus|=0x20; GUS_CheckIRQ(); for (;;) { Bit32u check=(1 << myGUS.IRQChan); if (totalmask & check) return; myGUS.IRQChan++; if (myGUS.IRQChan>=myGUS.ActiveChannels) myGUS.IRQChan=0; } } static Bit16u ExecuteReadRegister(void) { Bit8u tmpreg; // LOG_MSG("Read global reg %x",myGUS.gRegSelect); switch (myGUS.gRegSelect) { case 0x41: // Dma control register - read acknowledges DMA IRQ tmpreg = myGUS.DMAControl & 0xbf; tmpreg |= (myGUS.IRQStatus & 0x80) >> 1; myGUS.IRQStatus&=0x7f; return (Bit16u)(tmpreg << 8); case 0x42: // Dma address register return myGUS.dmaAddr; case 0x45: // Timer control register. Identical in operation to Adlib's timer return (Bit16u)(myGUS.TimerControl << 8); break; case 0x49: // Dma sample register tmpreg = myGUS.DMAControl & 0xbf; tmpreg |= (myGUS.IRQStatus & 0x80) >> 1; return (Bit16u)(tmpreg << 8); case 0x80: // Channel voice control read register if (curchan) return curchan->ReadWaveCtrl() << 8; else return 0x0300; case 0x82: // Channel MSB start address register if (curchan) return (Bit16u)(curchan->WaveStart >> (WAVE_BITS+16)); else return 0x0000; case 0x83: // Channel LSW start address register if (curchan) return (Bit16u)(curchan->WaveStart >> WAVE_BITS); else return 0x0000; case 0x89: // Channel volume register if (curchan) return (Bit16u)((curchan->RampVol >> RAMP_FRACT) << 4); else return 0x0000; case 0x8a: // Channel MSB current address register if (curchan) return (Bit16u)(curchan->WaveAddr >> (WAVE_BITS+16)); else return 0x0000; case 0x8b: // Channel LSW current address register if (curchan) return (Bit16u)(curchan->WaveAddr >> WAVE_BITS); else return 0x0000; case 0x8d: // Channel volume control register if (curchan) return curchan->ReadRampCtrl() << 8; else return 0x0300; case 0x8f: // General channel IRQ status register tmpreg=myGUS.IRQChan|0x20; Bit32u mask; mask=1 << myGUS.IRQChan; if (!(myGUS.RampIRQ & mask)) tmpreg|=0x40; if (!(myGUS.WaveIRQ & mask)) tmpreg|=0x80; myGUS.RampIRQ&=~mask; myGUS.WaveIRQ&=~mask; CheckVoiceIrq(); return (Bit16u)(tmpreg << 8); default: #if LOG_GUS LOG_MSG("Read Register num 0x%x", myGUS.gRegSelect); #endif return myGUS.gRegData; } } static void GUS_TimerEvent(Bitu val) { if (!myGUS.timers[val].masked) myGUS.timers[val].reached=true; if (myGUS.timers[val].raiseirq) { myGUS.IRQStatus|=0x4 << val; GUS_CheckIRQ(); } if (myGUS.timers[val].running) PIC_AddEvent(GUS_TimerEvent,myGUS.timers[val].delay,val); } static void ExecuteGlobRegister(void) { int i; // if (myGUS.gRegSelect|1!=0x44) LOG_MSG("write global register %x with %x", myGUS.gRegSelect, myGUS.gRegData); switch(myGUS.gRegSelect) { case 0x0: // Channel voice control register if(curchan) curchan->WriteWaveCtrl((Bit16u)myGUS.gRegData>>8); break; case 0x1: // Channel frequency control register if(curchan) curchan->WriteWaveFreq(myGUS.gRegData); break; case 0x2: // Channel MSW start address register if (curchan) { Bit32u tmpaddr = (Bit32u)(myGUS.gRegData & 0x1fff) << (16+WAVE_BITS); curchan->WaveStart = (curchan->WaveStart & WAVE_MSWMASK) | tmpaddr; } break; case 0x3: // Channel LSW start address register if(curchan != NULL) { Bit32u tmpaddr = (Bit32u)(myGUS.gRegData) << WAVE_BITS; curchan->WaveStart = (curchan->WaveStart & WAVE_LSWMASK) | tmpaddr; } break; case 0x4: // Channel MSW end address register if(curchan != NULL) { Bit32u tmpaddr = (Bit32u)(myGUS.gRegData & 0x1fff) << (16+WAVE_BITS); curchan->WaveEnd = (curchan->WaveEnd & WAVE_MSWMASK) | tmpaddr; } break; case 0x5: // Channel MSW end address register if(curchan != NULL) { Bit32u tmpaddr = (Bit32u)(myGUS.gRegData) << WAVE_BITS; curchan->WaveEnd = (curchan->WaveEnd & WAVE_LSWMASK) | tmpaddr; } break; case 0x6: // Channel volume ramp rate register if(curchan != NULL) { Bit8u tmpdata = (Bit16u)myGUS.gRegData>>8; curchan->WriteRampRate(tmpdata); } break; case 0x7: // Channel volume ramp start register EEEEMMMM if(curchan != NULL) { Bit8u tmpdata = (Bit16u)myGUS.gRegData >> 8; curchan->RampStart = tmpdata << (4+RAMP_FRACT); } break; case 0x8: // Channel volume ramp end register EEEEMMMM if(curchan != NULL) { Bit8u tmpdata = (Bit16u)myGUS.gRegData >> 8; curchan->RampEnd = tmpdata << (4+RAMP_FRACT); } break; case 0x9: // Channel current volume register if(curchan != NULL) { Bit16u tmpdata = (Bit16u)myGUS.gRegData >> 4; curchan->RampVol = tmpdata << RAMP_FRACT; curchan->UpdateVolumes(); } break; case 0xA: // Channel MSW current address register if(curchan != NULL) { Bit32u tmpaddr = (Bit32u)(myGUS.gRegData & 0x1fff) << (16+WAVE_BITS); curchan->WaveAddr = (curchan->WaveAddr & WAVE_MSWMASK) | tmpaddr; } break; case 0xB: // Channel LSW current address register if(curchan != NULL) { Bit32u tmpaddr = (Bit32u)(myGUS.gRegData) << (WAVE_BITS); curchan->WaveAddr = (curchan->WaveAddr & WAVE_LSWMASK) | tmpaddr; } break; case 0xC: // Channel pan pot register if(curchan) curchan->WritePanPot((Bit16u)myGUS.gRegData>>8); break; case 0xD: // Channel volume control register if(curchan) curchan->WriteRampCtrl((Bit16u)myGUS.gRegData>>8); break; case 0xE: // Set active channel register myGUS.gRegSelect = myGUS.gRegData>>8; //JAZZ Jackrabbit seems to assume this? myGUS.ActiveChannels = 1+((myGUS.gRegData>>8) & 63); if(myGUS.ActiveChannels < 14) myGUS.ActiveChannels = 14; if(myGUS.ActiveChannels > 32) myGUS.ActiveChannels = 32; myGUS.ActiveMask=0xffffffffU >> (32-myGUS.ActiveChannels); gus_chan->Enable(true); myGUS.basefreq = (Bit32u)((float)1000000/(1.619695497*(float)(myGUS.ActiveChannels))); #if LOG_GUS LOG_MSG("GUS set to %d channels", myGUS.ActiveChannels); #endif for (i=0;i<myGUS.ActiveChannels;i++) guschan[i]->UpdateWaveRamp(); break; case 0x10: // Undocumented register used in Fast Tracker 2 break; case 0x41: // Dma control register myGUS.DMAControl = (Bit8u)(myGUS.gRegData>>8); GetDMAChannel(myGUS.dma1)->Register_Callback( (myGUS.DMAControl & 0x1) ? GUS_DMA_Callback : 0); break; case 0x42: // Gravis DRAM DMA address register myGUS.dmaAddr = myGUS.gRegData; break; case 0x43: // MSB Peek/poke DRAM position myGUS.gDramAddr = (0xff0000 & myGUS.gDramAddr) | ((Bit32u)myGUS.gRegData); break; case 0x44: // LSW Peek/poke DRAM position myGUS.gDramAddr = (0xffff & myGUS.gDramAddr) | ((Bit32u)myGUS.gRegData>>8) << 16; break; case 0x45: // Timer control register. Identical in operation to Adlib's timer myGUS.TimerControl = (Bit8u)(myGUS.gRegData>>8); myGUS.timers[0].raiseirq=(myGUS.TimerControl & 0x04)>0; if (!myGUS.timers[0].raiseirq) myGUS.IRQStatus&=~0x04; myGUS.timers[1].raiseirq=(myGUS.TimerControl & 0x08)>0; if (!myGUS.timers[1].raiseirq) myGUS.IRQStatus&=~0x08; break; case 0x46: // Timer 1 control myGUS.timers[0].value = (Bit8u)(myGUS.gRegData>>8); myGUS.timers[0].delay = (0x100 - myGUS.timers[0].value) * 0.080f; break; case 0x47: // Timer 2 control myGUS.timers[1].value = (Bit8u)(myGUS.gRegData>>8); myGUS.timers[1].delay = (0x100 - myGUS.timers[1].value) * 0.320f; break; case 0x49: // DMA sampling control register myGUS.SampControl = (Bit8u)(myGUS.gRegData>>8); GetDMAChannel(myGUS.dma1)->Register_Callback( (myGUS.SampControl & 0x1) ? GUS_DMA_Callback : 0); break; case 0x4c: // GUS reset register GUSReset(); break; default: #if LOG_GUS LOG_MSG("Unimplemented global register %x -- %x", myGUS.gRegSelect, myGUS.gRegData); #endif break; } return; } static Bitu read_gus(Bitu port,Bitu iolen) { // LOG_MSG("read from gus port %x",port); switch(port - GUS_BASE) { case 0x206: return myGUS.IRQStatus; case 0x208: Bit8u tmptime; tmptime = 0; if (myGUS.timers[0].reached) tmptime |= (1 << 6); if (myGUS.timers[1].reached) tmptime |= (1 << 5); if (tmptime & 0x60) tmptime |= (1 << 7); if (myGUS.IRQStatus & 0x04) tmptime|=(1 << 2); if (myGUS.IRQStatus & 0x08) tmptime|=(1 << 1); return tmptime; case 0x20a: return adlib_commandreg; case 0x302: return (Bit8u)myGUS.gCurChannel; case 0x303: return myGUS.gRegSelect; case 0x304: if (iolen==2) return ExecuteReadRegister() & 0xffff; else return ExecuteReadRegister() & 0xff; case 0x305: return ExecuteReadRegister() >> 8; case 0x307: if(myGUS.gDramAddr < sizeof(GUSRam)) { return GUSRam[myGUS.gDramAddr]; } else { return 0; } default: #if LOG_GUS LOG_MSG("Read GUS at port 0x%x", port); #endif break; } return 0xff; } static void write_gus(Bitu port,Bitu val,Bitu iolen) { // LOG_MSG("Write gus port %x val %x",port,val); switch(port - GUS_BASE) { case 0x200: myGUS.mixControl = (Bit8u)val; myGUS.ChangeIRQDMA = true; return; case 0x208: adlib_commandreg = (Bit8u)val; break; case 0x209: //TODO adlib_commandreg should be 4 for this to work else it should just latch the value if (val & 0x80) { myGUS.timers[0].reached=false; myGUS.timers[1].reached=false; return; } myGUS.timers[0].masked=(val & 0x40)>0; myGUS.timers[1].masked=(val & 0x20)>0; if (val & 0x1) { if (!myGUS.timers[0].running) { PIC_AddEvent(GUS_TimerEvent,myGUS.timers[0].delay,0); myGUS.timers[0].running=true; } } else myGUS.timers[0].running=false; if (val & 0x2) { if (!myGUS.timers[1].running) { PIC_AddEvent(GUS_TimerEvent,myGUS.timers[1].delay,1); myGUS.timers[1].running=true; } } else myGUS.timers[1].running=false; break; //TODO Check if 0x20a register is also available on the gus like on the interwave case 0x20b: if (!myGUS.ChangeIRQDMA) break; myGUS.ChangeIRQDMA=false; if (myGUS.mixControl & 0x40) { // IRQ configuration, only use low bits for irq 1 if (irqtable[val & 0x7]) myGUS.irq1=irqtable[val & 0x7]; #if LOG_GUS LOG_MSG("Assigned GUS to IRQ %d", myGUS.irq1); #endif } else { // DMA configuration, only use low bits for dma 1 if (dmatable[val & 0x7]) myGUS.dma1=dmatable[val & 0x7]; #if LOG_GUS LOG_MSG("Assigned GUS to DMA %d", myGUS.dma1); #endif } break; case 0x302: myGUS.gCurChannel = val & 31 ; curchan = guschan[myGUS.gCurChannel]; break; case 0x303: myGUS.gRegSelect = (Bit8u)val; myGUS.gRegData = 0; break; case 0x304: if (iolen==2) { myGUS.gRegData=(Bit16u)val; ExecuteGlobRegister(); } else myGUS.gRegData = (Bit16u)val; break; case 0x305: myGUS.gRegData = (Bit16u)((0x00ff & myGUS.gRegData) | val << 8); ExecuteGlobRegister(); break; case 0x307: if(myGUS.gDramAddr < sizeof(GUSRam)) GUSRam[myGUS.gDramAddr] = (Bit8u)val; break; default: #if LOG_GUS LOG_MSG("Write GUS at port 0x%x with %x", port, val); #endif break; } } static void GUS_DMA_Callback(DmaChannel * chan,DMAEvent event) { if (event!=DMA_UNMASKED) return; Bitu dmaaddr = myGUS.dmaAddr << 4; if((myGUS.DMAControl & 0x2) == 0) { Bitu read=chan->Read(chan->currcnt+1,&GUSRam[dmaaddr]); //Check for 16 or 8bit channel read*=(chan->DMA16+1); if((myGUS.DMAControl & 0x80) != 0) { //Invert the MSB to convert twos compliment form Bitu i; if((myGUS.DMAControl & 0x40) == 0) { // 8-bit data for(i=dmaaddr;i<(dmaaddr+read);i++) GUSRam[i] ^= 0x80; } else { // 16-bit data for(i=dmaaddr+1;i<(dmaaddr+read);i+=2) GUSRam[i] ^= 0x80; } } } else { //Read data out of UltraSound chan->Write(chan->currcnt+1,&GUSRam[dmaaddr]); } /* Raise the TC irq if needed */ if((myGUS.DMAControl & 0x20) != 0) { myGUS.IRQStatus |= 0x80; GUS_CheckIRQ(); } chan->Register_Callback(0); } static void GUS_CallBack(Bitu len) { memset(&MixTemp,0,len*8); Bitu i; Bit16s * buf16 = (Bit16s *)MixTemp; Bit32s * buf32 = (Bit32s *)MixTemp; for(i=0;i<myGUS.ActiveChannels;i++) guschan[i]->generateSamples(buf32,len); for(i=0;i<len*2;i++) { Bit32s sample=((buf32[i] >> 13)*AutoAmp)>>9; if (sample>32767) { sample=32767; AutoAmp--; } else if (sample<-32768) { sample=-32768; AutoAmp--; } buf16[i] = (Bit16s)(sample); } gus_chan->AddSamples_s16(len,buf16); CheckVoiceIrq(); } // Generate logarithmic to linear volume conversion tables static void MakeTables(void) { int i; double out = (double)(1 << 13); for (i=4095;i>=0;i--) { vol16bit[i]=(Bit16s)out; out/=1.002709201; /* 0.0235 dB Steps */ } pantable[0]=0; for (i=1;i<16;i++) { pantable[i]=(Bit32u)(-128.0*(log((double)i/15.0)/log(2.0))*(double)(1 << RAMP_FRACT)); } } class GUS:public Module_base{ private: IO_ReadHandleObject ReadHandler[8]; IO_WriteHandleObject WriteHandler[9]; AutoexecObject autoexecline[2]; MixerObject MixerChan; public: GUS(Section* configuration):Module_base(configuration){ if(!IS_EGAVGA_ARCH) return; Section_prop * section=static_cast<Section_prop *>(configuration); if(!section->Get_bool("gus")) return; memset(&myGUS,0,sizeof(myGUS)); memset(GUSRam,0,1024*1024); myGUS.rate=section->Get_int("gusrate"); myGUS.portbase = section->Get_hex("gusbase") - 0x200; int dma_val = section->Get_int("gusdma"); if ((dma_val<0) || (dma_val>255)) dma_val = 3; // sensible default int irq_val = section->Get_int("gusirq"); if ((irq_val<0) || (irq_val>255)) irq_val = 5; // sensible default myGUS.dma1 = (Bit8u)dma_val; myGUS.dma2 = (Bit8u)dma_val; myGUS.irq1 = (Bit8u)irq_val; myGUS.irq2 = (Bit8u)irq_val; // We'll leave the MIDI interface to the MPU-401 // Ditto for the Joystick // GF1 Synthesizer ReadHandler[0].Install(0x302 + GUS_BASE,read_gus,IO_MB); WriteHandler[0].Install(0x302 + GUS_BASE,write_gus,IO_MB); WriteHandler[1].Install(0x303 + GUS_BASE,write_gus,IO_MB); ReadHandler[1].Install(0x303 + GUS_BASE,read_gus,IO_MB); WriteHandler[2].Install(0x304 + GUS_BASE,write_gus,IO_MB|IO_MW); ReadHandler[2].Install(0x304 + GUS_BASE,read_gus,IO_MB|IO_MW); WriteHandler[3].Install(0x305 + GUS_BASE,write_gus,IO_MB); ReadHandler[3].Install(0x305 + GUS_BASE,read_gus,IO_MB); ReadHandler[4].Install(0x206 + GUS_BASE,read_gus,IO_MB); WriteHandler[4].Install(0x208 + GUS_BASE,write_gus,IO_MB); ReadHandler[5].Install(0x208 + GUS_BASE,read_gus,IO_MB); WriteHandler[5].Install(0x209 + GUS_BASE,write_gus,IO_MB); WriteHandler[6].Install(0x307 + GUS_BASE,write_gus,IO_MB); ReadHandler[6].Install(0x307 + GUS_BASE,read_gus,IO_MB); // Board Only WriteHandler[7].Install(0x200 + GUS_BASE,write_gus,IO_MB); ReadHandler[7].Install(0x20A + GUS_BASE,read_gus,IO_MB); WriteHandler[8].Install(0x20B + GUS_BASE,write_gus,IO_MB); // DmaChannels[myGUS.dma1]->Register_TC_Callback(GUS_DMA_TC_Callback); MakeTables(); for (Bit8u chan_ct=0; chan_ct<32; chan_ct++) { guschan[chan_ct] = new GUSChannels(chan_ct); } // Register the Mixer CallBack gus_chan=MixerChan.Install(GUS_CallBack,GUS_RATE,"GUS"); myGUS.gRegData=0x1; GUSReset(); myGUS.gRegData=0x0; int portat = 0x200+GUS_BASE; // ULTRASND=Port,DMA1,DMA2,IRQ1,IRQ2 // [GUS port], [GUS DMA (recording)], [GUS DMA (playback)], [GUS IRQ (playback)], [GUS IRQ (MIDI)] ostringstream temp; temp << "SET ULTRASND=" << hex << setw(3) << portat << "," << dec << (Bitu)myGUS.dma1 << "," << (Bitu)myGUS.dma2 << "," << (Bitu)myGUS.irq1 << "," << (Bitu)myGUS.irq2 << ends; // Create autoexec.bat lines autoexecline[0].Install(temp.str()); autoexecline[1].Install(std::string("SET ULTRADIR=") + section->Get_string("ultradir")); } ~GUS() { if(!IS_EGAVGA_ARCH) return; Section_prop * section=static_cast<Section_prop *>(m_configuration); if(!section->Get_bool("gus")) return; myGUS.gRegData=0x1; GUSReset(); myGUS.gRegData=0x0; for(Bitu i=0;i<32;i++) { delete guschan[i]; } memset(&myGUS,0,sizeof(myGUS)); memset(GUSRam,0,1024*1024); } }; static GUS* test; void GUS_ShutDown(Section* /*sec*/) { delete test; } void GUS_Init(Section* sec) { test = new GUS(sec); sec->AddDestroyFunction(&GUS_ShutDown,true); }
28.441077
111
0.680084
electroduck
aa295c708985e7c4994156642cb22e6253554fc3
3,368
cpp
C++
src/vcml/net/client_tap.cpp
sturmk/vcml
e6ace78cd039c200df217dd629da16f95c7ca050
[ "Apache-2.0" ]
36
2018-01-29T12:20:37.000Z
2022-03-29T06:14:59.000Z
src/vcml/net/client_tap.cpp
sturmk/vcml
e6ace78cd039c200df217dd629da16f95c7ca050
[ "Apache-2.0" ]
9
2018-12-04T10:37:14.000Z
2021-11-16T16:57:29.000Z
src/vcml/net/client_tap.cpp
sturmk/vcml
e6ace78cd039c200df217dd629da16f95c7ca050
[ "Apache-2.0" ]
18
2018-10-14T11:30:43.000Z
2022-01-08T07:12:56.000Z
/****************************************************************************** * * * Copyright 2021 Jan Henrik Weinstock * * * * 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 <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <linux/if.h> #include <linux/if_tun.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include "vcml/net/client_tap.h" namespace vcml { namespace net { client_tap::client_tap(const string& adapter, int devno): client(adapter) { m_fd = open("/dev/net/tun", O_RDWR); VCML_REPORT_ON(m_fd < 0, "error opening tundev: %s", strerror(errno)); struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; snprintf(ifr.ifr_name, IFNAMSIZ, "tap%d", devno); int err = ioctl(m_fd, TUNSETIFF, (void*)&ifr); VCML_REPORT_ON(err < 0, "error creating tapdev: %s", strerror(errno)); log_info("using tap device %s", ifr.ifr_name); m_type = mkstr("tap:%d", devno); } client_tap::~client_tap() { if (m_fd >= 0) close(m_fd); } bool client_tap::recv_packet(vector<u8>& packet) { if (m_fd < 0) return false; if (!fd_peek(m_fd)) return false; ssize_t len; packet.resize(ETH_MAX_FRAME_SIZE); do { len = ::read(m_fd, packet.data(), packet.size()); } while (len < 0 && errno == EINTR); if (len < 0) { log_error("error reading tap device: %s", strerror(errno)); close(m_fd); m_fd = -1; } if (len <= 0) return false; packet.resize(len); return true; } void client_tap::send_packet(const vector<u8>& packet) { if (m_fd >= 0) fd_write(m_fd, packet.data(), packet.size()); } client* client_tap::create(const string& adapter, const string& type) { int devno = 0; vector<string> args = split(type, ':'); if (args.size() > 1) devno = from_string<int>(args[1]); return new client_tap(adapter, devno); } }}
35.083333
80
0.461401
sturmk
aa29f0bd81aabde4162fd3af125a6adbecf1b7f5
5,109
hpp
C++
src/frontier_lib/StateFrontier.hpp
junkawahara/frontier
4ae3eb360c96511ec5f3592b8bc85a1d8bce3aec
[ "MIT" ]
16
2015-08-02T14:23:23.000Z
2021-10-18T13:45:47.000Z
src/frontier_lib/StateFrontier.hpp
junkawahara/frontier
4ae3eb360c96511ec5f3592b8bc85a1d8bce3aec
[ "MIT" ]
1
2017-07-26T01:52:38.000Z
2017-07-26T01:59:21.000Z
src/frontier_lib/StateFrontier.hpp
junkawahara/frontier
4ae3eb360c96511ec5f3592b8bc85a1d8bce3aec
[ "MIT" ]
7
2015-07-29T22:19:36.000Z
2021-04-20T17:19:40.000Z
// // StateFrontier.hpp // // Copyright (c) 2012 -- 2016 Jun Kawahara // // 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. #ifndef STATEFRONTIER_HPP #define STATEFRONTIER_HPP #include <vector> #include <set> #include <algorithm> #include <string> #include <iostream> #include <cassert> #include <cstdio> #include "Global.hpp" #include "Graph.hpp" #include "ZDDNode.hpp" #include "RBuffer.hpp" #include "FrontierManager.hpp" #include "State.hpp" #include "Mate.hpp" #include "PseudoZDD.hpp" namespace frontier_lib { class Mate; //************************************************************************************************* // StateFrontier: template<typename MT> class StateFrontier : public State { protected: FrontierManager frontier_manager_; //static const short SEPARATOR_ = 32767; enum {SEPARATOR_ = 32767}; public: StateFrontier(Graph* graph) : State(graph), frontier_manager_(graph) { } virtual void StartNextEdge() { State::StartNextEdge(); frontier_manager_.Update(GetCurrentEdge(), GetCurrentEdgeNumber()); } virtual Mate* Initialize(ZDDNode* root_node) { MateS* mate = new MT(this); if (subsetting_dd_ != NULL) { mate->SetUseSubsetting(true, root_node); } return mate; } virtual bool Equals(const ZDDNode& node1, const ZDDNode& node2, Mate* mate) const { return mate->Equals(node1, node2, frontier_manager_); } virtual intx GetHashValue(const ZDDNode& node, Mate* mate) const { return mate->GetHashValue(node, frontier_manager_); } virtual void PackMate(ZDDNode* node, Mate* mate) { mate->PackMate(node, frontier_manager_); } virtual void UnpackMate(ZDDNode* node, Mate* mate, int child_num) { mate->UnpackMate(node, child_num, frontier_manager_); } virtual void Revert(Mate* mate) { mate->Revert(frontier_manager_); } virtual ZDDNode* MakeNewNode(ZDDNode* /*node*/, Mate* mate, int child_num, PseudoZDD* zdd) { MT* m = static_cast<MT*>(mate); if (m->IsUseSubsetting()) { if (DoSubsetting(child_num, m) == 0) { return zdd->ZeroTerminal; } } int c = this->CheckTerminalPre(m, child_num); // ็ต‚็ซฏใซ้ท็งปใ™ใ‚‹ใ‹ไบ‹ๅ‰ใซใƒใ‚งใƒƒใ‚ฏ if (c == 0) { // 0็ต‚็ซฏใซ่กŒใใจใ return zdd->ZeroTerminal; // 0็ต‚็ซฏใ‚’่ฟ”ใ™ } else if (c == 1) { // 1็ต‚็ซฏใซ่กŒใใจใ return zdd->OneTerminal; // 1็ต‚็ซฏใ‚’่ฟ”ใ™ } this->UpdateMate(m, child_num); // mate ใ‚’ๆ›ดๆ–ฐใ™ใ‚‹ c = this->CheckTerminalPost(m); // ็ต‚็ซฏใซ้ท็งปใ™ใ‚‹ใ‹ๅ†ๅบฆใƒใ‚งใƒƒใ‚ฏ if (c == 0) { // 0็ต‚็ซฏใซ่กŒใใจใ return zdd->ZeroTerminal; // 0็ต‚็ซฏใ‚’่ฟ”ใ™ } else if (c == 1) { // 1็ต‚็ซฏใซ่กŒใใจใ return zdd->OneTerminal; // 1็ต‚็ซฏใ‚’่ฟ”ใ™ } else { ZDDNode* child_node = zdd->CreateNode(); return child_node; } } template<typename T> static void VectorVectorToVector(const std::vector<std::vector<T> >& vv, std::vector<T>* v) { for (uint i = 0; i < vv.size(); ++i) { for (uint j = 0; j < vv[i].size(); ++j) { v->push_back(vv[i][j]); } v->push_back(SEPARATOR_); } } template<typename T> static void VectorToVectorVector(const std::vector<T>& v, std::vector<std::vector<T> >* vv) { if (v.size() >= 1) { vv->push_back(std::vector<T>()); } for (uint i = 0; i < v.size(); ++i) { if (v[i] == SEPARATOR_) { if (i < v.size() - 1) { vv->push_back(std::vector<T>()); } } else { vv->back().push_back(v[i]); } } } protected: virtual void UpdateMate(MT* mate, int child_num) = 0; virtual int CheckTerminalPre(MT* mate, int child_num) = 0; virtual int CheckTerminalPost(MT* mate) = 0; }; } // the end of the namespace #endif // STATEFRONTIER_HPP
29.703488
99
0.592875
junkawahara
aa2ecce0c5589845edfba32250a98fdd2d068e7a
1,302
hpp
C++
build/external/include/marnav/nmea/rot.hpp
jft7/signalk-server-cpp
060e79d364e3b82200f0d2962742bf81be9b47da
[ "Apache-2.0" ]
null
null
null
build/external/include/marnav/nmea/rot.hpp
jft7/signalk-server-cpp
060e79d364e3b82200f0d2962742bf81be9b47da
[ "Apache-2.0" ]
1
2021-11-10T14:40:21.000Z
2021-11-10T14:40:21.000Z
build/external/include/marnav/nmea/rot.hpp
jft7/signalk-server-cpp
060e79d364e3b82200f0d2962742bf81be9b47da
[ "Apache-2.0" ]
1
2020-08-14T08:10:05.000Z
2020-08-14T08:10:05.000Z
#ifndef MARNAV__NMEA__ROT__HPP #define MARNAV__NMEA__ROT__HPP #include <marnav/nmea/sentence.hpp> #include <marnav/utils/optional.hpp> namespace marnav { namespace nmea { /// @brief ROT - Rate Of Turn /// /// @code /// 1 2 /// | | /// $--ROT,x.x,A*hh<CR><LF> /// @endcode /// /// Field Number: /// 1. Rate Of Turn, degrees per minute, "-" means bow turns to port /// 2. Status /// - A = data is valid /// - V = invalid /// class rot : public sentence { friend class detail::factory; public: constexpr static sentence_id ID = sentence_id::ROT; constexpr static const char * TAG = "ROT"; rot(); rot(const rot &) = default; rot & operator=(const rot &) = default; rot(rot &&) = default; rot & operator=(rot &&) = default; protected: rot(talker talk, fields::const_iterator first, fields::const_iterator last); virtual void append_data_to(std::string &) const override; private: utils::optional<double> deg_per_minute_; utils::optional<status> data_valid_; public: decltype(deg_per_minute_) get_deg_per_minute() const { return deg_per_minute_; } decltype(data_valid_) get_data_valid() const { return data_valid_; } void set_deg_per_minute(double t) noexcept { deg_per_minute_ = t; } void set_data_valid(status t) noexcept { data_valid_ = t; } }; } } #endif
22.448276
81
0.685868
jft7
aa2faeec1bccc3f361a6742ccef03da1a22bab95
1,345
cpp
C++
example_math_svd/src/ofApp.cpp
icq4ever/ofxDlib
d87602b3f66f2ef3f478f004b65bc414360cd748
[ "MIT" ]
56
2017-04-11T14:09:28.000Z
2020-12-23T15:01:35.000Z
example_math_svd/src/ofApp.cpp
icq4ever/ofxDlib
d87602b3f66f2ef3f478f004b65bc414360cd748
[ "MIT" ]
30
2017-04-13T01:15:43.000Z
2020-12-03T23:28:02.000Z
example_math_svd/src/ofApp.cpp
icq4ever/ofxDlib
d87602b3f66f2ef3f478f004b65bc414360cd748
[ "MIT" ]
16
2017-04-18T07:47:47.000Z
2021-07-09T13:35:51.000Z
// // Copyright (c) 2017 Christopher Baker <https://christopherbaker.net> // // SPDX-License-Identifier: MIT // #include "ofApp.h" void ofApp::setup() { // Example from https://www.mathworks.com/help/matlab/ref/svd.html dlib::matrix<double> A(4, 2); A = 1, 2, 3, 4, 5, 6, 7, 8; std::cout << "Matrix A = \n" << A << std::endl; // SVD usually takes the form of M = U * ฮฃ * trans(V) dlib::matrix<double> U, ฮฃ, // aka S or W V; // Calculate the singular value decomposion. dlib::svd(A, // m x n, where m >= n). U, // m x n, orthogonal columns (i.e. U*trans(U) == I) ฮฃ, // n x n, diagonal matrix, with singular values on diagonal (returned as n-col matrix). V // n x n, orthonormal matrix, (i.e. V*trans(V) == trans(V)*V == I) ); std::cout << "U = \n" << U << std::endl; std::cout << "ฮฃ = \n" << ฮฃ << std::endl; std::cout << "V = \n" << V << std::endl;; dlib::matrix<double> A_reconstructed = U * ฮฃ * dlib::trans(V); std::cout << "A_reconstructed = \n" << A_reconstructed << std::endl;; // The reconstructed A matrix may not be exact due to rounding and numerical // errors, especially if using dlib::svd_fast(...). ofExit(); }
29.23913
104
0.517472
icq4ever
a8f907b57e189def24cb125e52c2bd6e22ab6664
3,039
cpp
C++
captcha/src/v20190722/model/TicketThroughUnit.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
captcha/src/v20190722/model/TicketThroughUnit.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
captcha/src/v20190722/model/TicketThroughUnit.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/captcha/v20190722/model/TicketThroughUnit.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Captcha::V20190722::Model; using namespace std; TicketThroughUnit::TicketThroughUnit() : m_dateKeyHasBeenSet(false), m_throughHasBeenSet(false) { } CoreInternalOutcome TicketThroughUnit::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("DateKey") && !value["DateKey"].IsNull()) { if (!value["DateKey"].IsString()) { return CoreInternalOutcome(Core::Error("response `TicketThroughUnit.DateKey` IsString=false incorrectly").SetRequestId(requestId)); } m_dateKey = string(value["DateKey"].GetString()); m_dateKeyHasBeenSet = true; } if (value.HasMember("Through") && !value["Through"].IsNull()) { if (!value["Through"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `TicketThroughUnit.Through` IsInt64=false incorrectly").SetRequestId(requestId)); } m_through = value["Through"].GetInt64(); m_throughHasBeenSet = true; } return CoreInternalOutcome(true); } void TicketThroughUnit::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_dateKeyHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DateKey"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_dateKey.c_str(), allocator).Move(), allocator); } if (m_throughHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Through"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_through, allocator); } } string TicketThroughUnit::GetDateKey() const { return m_dateKey; } void TicketThroughUnit::SetDateKey(const string& _dateKey) { m_dateKey = _dateKey; m_dateKeyHasBeenSet = true; } bool TicketThroughUnit::DateKeyHasBeenSet() const { return m_dateKeyHasBeenSet; } int64_t TicketThroughUnit::GetThrough() const { return m_through; } void TicketThroughUnit::SetThrough(const int64_t& _through) { m_through = _through; m_throughHasBeenSet = true; } bool TicketThroughUnit::ThroughHasBeenSet() const { return m_throughHasBeenSet; }
27.133929
143
0.699243
suluner
a8fba8542063e488be2af5788f0ce8e53c1393ca
7,958
cpp
C++
Engine/Collider.cpp
LeviMooreDev/Wolfenstein-3D-CPlusPlus
24242623b679a6ec9e5020dfc1266d5b0e53db4a
[ "MIT" ]
null
null
null
Engine/Collider.cpp
LeviMooreDev/Wolfenstein-3D-CPlusPlus
24242623b679a6ec9e5020dfc1266d5b0e53db4a
[ "MIT" ]
null
null
null
Engine/Collider.cpp
LeviMooreDev/Wolfenstein-3D-CPlusPlus
24242623b679a6ec9e5020dfc1266d5b0e53db4a
[ "MIT" ]
null
null
null
#include "Collider.h" #include "Scene.h" #include <GLFW\glfw3.h> #include <iostream> #include "Debug.h" #include "Raycast.h" typedef std::basic_string<char> string; //declare static fields bool Collider::showWireframe = false; void Collider::ListenForHit(std::function<void(GameObject *)> onHit) { (*this).onHit = onHit; } void Collider::ListenForTrigger(std::function<void(GameObject *)> onTrigger) { (*this).onTrigger = onTrigger; } Vector3 Collider::Min() { return Vector3(gameObject->transform.position.x - centerOffset.x - size.x / 2.0f, gameObject->transform.position.y - centerOffset.y - size.y / 2.0f, gameObject->transform.position.z - centerOffset.z - size.z / 2.0f); } Vector3 Collider::Max() { return Vector3(gameObject->transform.position.x + centerOffset.x + size.x / 2.0f, gameObject->transform.position.y + centerOffset.y + size.y / 2.0f, gameObject->transform.position.z + centerOffset.z + size.z / 2.0f); } void Collider::Update(Scene * scene) { //if we have not changed position, center offset or size we dont need to check for collision if (lastCenterOffset == centerOffset && lastSize == size && lastValidPosition == gameObject->transform.position) return; //true if we need to check for collision bool checkForCollision = true; //the amount of times we are allowed to recheck for collision int checkCountLeft = 5; //if we want to check for a collision while (checkForCollision) { checkForCollision = false; //we are going to use min and max x,y,z a lot so we store them here for faster access later Vector3 selfMin = Min(); Vector3 selfMax = Max(); //loop through all game objects in the scene std::vector<GameObject *>::iterator otherGameObject = scene->GetAllGameObjects()->begin(); while (otherGameObject != scene->GetAllGameObjects()->end()) { //if the game object we are at is not ourself and it is enabled if ((*otherGameObject) != gameObject && (*otherGameObject)->enabled) { //if it has a collider on it if ((*otherGameObject)->HasColliders()) { //get the collider component and check if it is enabled Collider * otherCollider = (Collider *)(*otherGameObject)->GetComponent(ColliderComponentName); if (otherCollider->enabled) { //get the min and max x,y,z value of the other collider Vector3 otherMin = otherCollider->Min(); Vector3 otherMax = otherCollider->Max(); //if our box is inside the other box if ((selfMax.x > otherMin.x && selfMin.x < otherMax.x && selfMax.y > otherMin.y && selfMin.y < otherMax.y && selfMax.z > otherMin.z && selfMin.z < otherMax.z)) { //if the other box is solid if (otherCollider->solid) { //if we are solid if (solid) { // ------------------ // ---------|------ | // | minX| | | // | |< w >| other | // | self | |maxX | // | ------|----------- // ---------------- //w = abs(minX - maxX) //self.position -= w // ---------------- // ----------------| | // | || | // | || other | // | self || | // | |---------------- // ---------------- //the amount we want to move our game object to avoid being inside the other game object Vector3 move = Vector3(); //if we are to the right of the other game object subtract the amount we are inside the other game object to our x position //see the beautiful drawing above for visual explanation //#to the right if (gameObject->transform.position.x < (*otherGameObject)->transform.position.x) { Vector3 newMove = Vector3(-abs(selfMax.x - otherMin.x), 0, 0); //only set move to newMove if the amount we want to move is less than what we already want to move //we only use the smallest move amount for every collision check to avoid being pushed into another game collider that then do the same if (move == Vector3() || move.Distance(Vector3()) > newMove.Distance(Vector3())) move = newMove; } //left, right, forward and back checks are almost the same //# behind if (gameObject->transform.position.z > (*otherGameObject)->transform.position.z) { Vector3 newMove = Vector3(0, 0, abs(otherMax.z - selfMin.z)); if (move == Vector3() || move.Distance(Vector3()) > newMove.Distance(Vector3())) move = newMove; } //# to the right if (gameObject->transform.position.x > (*otherGameObject)->transform.position.x) { Vector3 newMove = Vector3(abs(selfMin.x - otherMax.x), 0, 0); if (move == Vector3() || move.Distance(Vector3()) > newMove.Distance(Vector3())) move = newMove; } //# infront if (gameObject->transform.position.z < (*otherGameObject)->transform.position.z) { Vector3 newMove = Vector3(0, 0, -abs(otherMin.z - selfMax.z)); if (move == Vector3() || move.Distance(Vector3()) > newMove.Distance(Vector3())) move = newMove; } //if we want to move the game object if (move != Vector3()) { //move the game object gameObject->transform.position += move; //remove a collision check checkCountLeft--; //if we have no more collision checks left, reset the game object position to the last known valid position //this should not happen except if the game object is placed in a closed area smaller then itself if (checkCountLeft == 0) { gameObject->transform.position = lastValidPosition; } //if we are allowed to use more collision checks, stop the code here and return to the beginning else { checkForCollision = true; break; } } //call the onHit method on our self and the other game object if (onHit != nullptr) onHit(otherCollider->gameObject); if (otherCollider->onHit != nullptr) otherCollider->onHit(gameObject); } } else { //call the onTrigger method on our self and the other game object if (onTrigger != nullptr) onTrigger(otherCollider->gameObject); if (otherCollider->onTrigger != nullptr) otherCollider->onTrigger(gameObject); } } } } } otherGameObject++; } } //set last center offset, size and valid position lastCenterOffset = centerOffset; lastSize = size; lastValidPosition = gameObject->transform.position; } void Collider::Draw2(Scene * scene) { //if we dont want to draw a wireframe for our collision box return. if (!Collider::showWireframe) return; glPushMatrix(); //set position glTranslatef(gameObject->transform.position.x + centerOffset.x, gameObject->transform.position.y + centerOffset.y, -gameObject->transform.position.z - centerOffset.z); //set scale glScalef(size.x, size.y, size.z); //set polygon mode to line to give the wireframe effect glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //disable depth test. we want to see all colliders even if they are behind other things glDisable(GL_DEPTH_TEST); //enable drawing by vertex and color arrays glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, wireframeVertices); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(3, GL_FLOAT, 0, colors); //draw glDrawArrays(GL_QUADS, 0, 24); //cleanup glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glPopMatrix(); }
34.301724
168
0.602413
LeviMooreDev
a8fc68640a6667f1ca9933f6a12576ba0eef8455
3,150
cpp
C++
DDOCP/LevelButton.cpp
shortydude/DDOBuilder-learning
e71162c10b81bb4afd0365e61088437353cc4607
[ "MIT" ]
null
null
null
DDOCP/LevelButton.cpp
shortydude/DDOBuilder-learning
e71162c10b81bb4afd0365e61088437353cc4607
[ "MIT" ]
null
null
null
DDOCP/LevelButton.cpp
shortydude/DDOBuilder-learning
e71162c10b81bb4afd0365e61088437353cc4607
[ "MIT" ]
null
null
null
// LevelButton.cpp // #include "stdafx.h" #include "LevelButton.h" #include "Character.h" #include "GlobalSupportFunctions.h" namespace { const COLORREF c_pinkWarningColour = RGB(0xFF, 0xB6, 0xC1); // Light Pink } #pragma warning(push) #pragma warning(disable: 4407) // warning C4407: cast between different pointer to member representations, compiler may generate incorrect code BEGIN_MESSAGE_MAP(CLevelButton, CStatic) //{{AFX_MSG_MAP(CLevelButton) ON_WM_ERASEBKGND() ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() #pragma warning(pop) CLevelButton::CLevelButton() : m_level(0), m_class(Class_Unknown), m_bSelected(false), m_bHasIssue(false) { //{{AFX_DATA_INIT(CLevelButton) //}}AFX_DATA_INIT HRESULT result = LoadImageFile( IT_enhancement, (LPCTSTR)EnumEntryText(m_class, classTypeMap), &m_image); m_image.SetTransparentColor(c_transparentColour); // create the font used LOGFONT lf; ZeroMemory((PVOID)&lf, sizeof(LOGFONT)); NONCLIENTMETRICS nm; nm.cbSize = sizeof(NONCLIENTMETRICS); VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, nm.cbSize, &nm, 0)); lf = nm.lfMenuFont; lf.lfHeight = -12; m_font.CreateFontIndirect(&lf); } BOOL CLevelButton::OnEraseBkgnd(CDC* pDC) { return 0; } void CLevelButton::OnPaint() { CPaintDC pdc(this); // validates the client area on destruction pdc.SaveDC(); CRect rect; GetWindowRect(&rect); rect -= rect.TopLeft(); // convert to client rectangle // fill the background if (m_bSelected) { pdc.FillSolidRect(rect, GetSysColor(COLOR_HIGHLIGHT)); } else { if (m_bHasIssue) { pdc.FillSolidRect(rect, c_pinkWarningColour); } else { pdc.FillSolidRect(rect, GetSysColor(COLOR_BTNFACE)); } } m_image.TransparentBlt( pdc.GetSafeHdc(), (rect.Width() - 32) / 2, 4, // always 4 pixels from the top 32, 32); // and lastly add the level text pdc.SelectObject(&m_font); CString text; text.Format("Level %d", m_level); CSize ts = pdc.GetTextExtent(text); pdc.SetBkMode(TRANSPARENT); pdc.TextOut((rect.Width() - ts.cx) / 2, 38, text); pdc.RestoreDC(-1); } void CLevelButton::SetLevel(size_t level) { m_level = level; } void CLevelButton::SetClass(ClassType ct) { m_class = ct; m_image.Destroy(); // load the new icon to display HRESULT result = LoadImageFile( IT_ui, (LPCTSTR)EnumEntryText(m_class, classTypeMap), &m_image); m_image.SetTransparentColor(c_transparentColour); Invalidate(); } void CLevelButton::SetSelected(bool selected) { if (selected != m_bSelected) { m_bSelected = selected; Invalidate(); // redraw on state change } } bool CLevelButton::IsSelected() const { return m_bSelected; } void CLevelButton::SetIssueState(bool hasIssue) { if (m_bHasIssue != hasIssue) { m_bHasIssue = hasIssue; Invalidate(); } }
23.333333
143
0.63873
shortydude
a8ffc21781f7dd9c6cc48c1821e0f9f5ae1ebc29
662
cpp
C++
problems/letter-combinations-of-a-phone-number/src/Solution.cpp
bbackspace/leetcode
bc3f235fcd42c37800e6ef7eefab4c826d70f3d3
[ "CC0-1.0" ]
null
null
null
problems/letter-combinations-of-a-phone-number/src/Solution.cpp
bbackspace/leetcode
bc3f235fcd42c37800e6ef7eefab4c826d70f3d3
[ "CC0-1.0" ]
null
null
null
problems/letter-combinations-of-a-phone-number/src/Solution.cpp
bbackspace/leetcode
bc3f235fcd42c37800e6ef7eefab4c826d70f3d3
[ "CC0-1.0" ]
null
null
null
class Solution { const vector<string> keypad = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; string s; vector<string> ans; void comb(string &dig, int d) { if (dig.length() == 0) { return; } if (d == dig.length()) { ans.push_back(s); return; } for (auto &k : keypad[dig[d] - '0']) { s.push_back(k); comb(dig, d + 1); s.pop_back(); } } public: vector<string> letterCombinations(string digits) { ans = vector<string>(); s = ""; comb(digits, 0); return ans; } };
23.642857
101
0.432024
bbackspace
d100cc31b223afbda5fc9b7bcbbe8c3d2d20ec9e
4,808
cpp
C++
NFIQ2/NFIQ2/NFIQ2Algorithm/src/features/OCLHistogramFeature.cpp
mahizhvannan/PYNFIQ2
56eac2d780c9b5becd0ca600ffa6198d3a0115a7
[ "MIT" ]
null
null
null
NFIQ2/NFIQ2/NFIQ2Algorithm/src/features/OCLHistogramFeature.cpp
mahizhvannan/PYNFIQ2
56eac2d780c9b5becd0ca600ffa6198d3a0115a7
[ "MIT" ]
null
null
null
NFIQ2/NFIQ2/NFIQ2Algorithm/src/features/OCLHistogramFeature.cpp
mahizhvannan/PYNFIQ2
56eac2d780c9b5becd0ca600ffa6198d3a0115a7
[ "MIT" ]
1
2022-02-14T03:16:05.000Z
2022-02-14T03:16:05.000Z
#include "OCLHistogramFeature.h" #include "FeatureFunctions.h" #include "include/NFIQException.h" #include "include/Timer.hpp" #include <sstream> #if defined WINDOWS || defined WIN32 #include <windows.h> #include <float.h> #define isnan _isnan // re-define isnan #else #ifndef isnan #define isnan(x) ((x) != (x)) #endif #endif using namespace NFIQ; using namespace cv; #define HISTOGRAM_FEATURES 1 OCLHistogramFeature::~OCLHistogramFeature() { } std::list<NFIQ::QualityFeatureResult> OCLHistogramFeature::computeFeatureData( const NFIQ::FingerprintImageData & fingerprintImage) { std::list<NFIQ::QualityFeatureResult> featureDataList; Mat img; // check if input image has 500 dpi if (fingerprintImage.m_ImageDPI != NFIQ::e_ImageResolution_500dpi) throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, "Only 500 dpi fingerprint images are supported!"); try { // get matrix from fingerprint image img = Mat(fingerprintImage.m_ImageHeight, fingerprintImage.m_ImageWidth, CV_8UC1, (void*)fingerprintImage.data()); } catch (cv::Exception & e) { std::stringstream ssErr; ssErr << "Cannot get matrix from fingerprint image: " << e.what(); throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, ssErr.str()); } // compute OCL NFIQ::Timer timerOCL; double timeOCL = 0.0; std::vector<double>oclres; try { timerOCL.startTimer(); // divide into blocks for (int i = 0; i < img.rows; i += BS_OCL) { for (int j = 0; j < img.cols; j += BS_OCL) { unsigned int actualBS_X = ((img.cols - j) < BS_OCL) ? (img.cols - j) : BS_OCL; unsigned int actualBS_Y = ((img.rows - i) < BS_OCL) ? (img.rows - i) : BS_OCL; if (actualBS_X == BS_OCL && actualBS_Y == BS_OCL) { // only take blocks of full size // ignore other blocks // get current block Mat bl_img = img(Rect(j, i, actualBS_X, actualBS_Y)); // get OCL value of current block double bl_ocl = 0.0; if (!getOCLValueOfBlock(bl_img, bl_ocl)) continue; // block is not used oclres.push_back(bl_ocl); } } } #if HISTOGRAM_FEATURES std::vector<double> histogramBins10; histogramBins10.push_back(OCLPHISTLIMITS[0]); histogramBins10.push_back(OCLPHISTLIMITS[1]); histogramBins10.push_back(OCLPHISTLIMITS[2]); histogramBins10.push_back(OCLPHISTLIMITS[3]); histogramBins10.push_back(OCLPHISTLIMITS[4]); histogramBins10.push_back(OCLPHISTLIMITS[5]); histogramBins10.push_back(OCLPHISTLIMITS[6]); histogramBins10.push_back(OCLPHISTLIMITS[7]); histogramBins10.push_back(OCLPHISTLIMITS[8]); addHistogramFeatures(featureDataList, "OCL_Bin10_", histogramBins10, oclres, 10); #endif timeOCL = timerOCL.endTimerAndGetElapsedTime(); if (m_bOutputSpeed) { NFIQ::QualityFeatureSpeed speed; speed.featureIDGroup = "Orientation certainty"; #if HISTOGRAM_FEATURES addHistogramFeatureNames(speed.featureIDs, "OCL_Bin10_", 10); #endif speed.featureSpeed = timeOCL; m_lSpeedValues.push_back(speed); } } catch (cv::Exception & e) { std::stringstream ssErr; ssErr << "Cannot compute feature OCL histogram: " << e.what(); throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, ssErr.str()); } catch (NFIQ::NFIQException & e) { throw e; } catch (...) { throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, "Unknown exception occurred!"); } return featureDataList; } bool OCLHistogramFeature::getOCLValueOfBlock(const cv::Mat & block, double & ocl) { double eigv_max = 0.0, eigv_min = 0.0; // compute the numerical gradients of the block Mat grad_x, grad_y; computeNumericalGradients(block, grad_x, grad_y); // compute covariance matrix double a = 0.0; double b = 0.0; double c = 0.0; for (unsigned int k = 0; k < BS_OCL; k++) { for (unsigned int l = 0; l < BS_OCL; l++) { a += (grad_x.at<double>(l, k) * grad_x.at<double>(l, k)); b += (grad_y.at<double>(l, k) * grad_y.at<double>(l, k)); c += (grad_x.at<double>(l, k) * grad_y.at<double>(l, k)); } } // take mean value covariance matrix values a /= (BS_OCL*BS_OCL); b /= (BS_OCL*BS_OCL); c /= (BS_OCL*BS_OCL); // compute the eigenvalues eigv_max = ( (a + b) + sqrt( pow(a - b, 2) + 4*pow(c, 2) ) ) / 2.0; eigv_min = ( (a + b) - sqrt( pow(a - b, 2) + 4*pow(c, 2) ) ) / 2.0; if (eigv_max == 0) { // block is excluded from usage ocl = 0.0; return false; } // compute the OCL value of the block ocl = (1.0 - (eigv_min / eigv_max)); // 0 (worst), 1 (best) return true; } std::string OCLHistogramFeature::getModuleID() { return "NFIQ2_OCLHistogram"; } std::list<std::string> OCLHistogramFeature::getAllFeatureIDs() { std::list<std::string> featureIDs; #if HISTOGRAM_FEATURES addHistogramFeatureNames(featureIDs, "OCL_Bin10_", 10); #endif return featureIDs; }
26.130435
117
0.691764
mahizhvannan
d10447f20db2c6868d431b2832d8471f897f020f
850
cpp
C++
tests/Test_ST_Policy_Safe.cpp
wuzhl2018/nano-signal-slot
051588437938a262b0a9738da024afcab2e8b8e6
[ "MIT" ]
null
null
null
tests/Test_ST_Policy_Safe.cpp
wuzhl2018/nano-signal-slot
051588437938a262b0a9738da024afcab2e8b8e6
[ "MIT" ]
null
null
null
tests/Test_ST_Policy_Safe.cpp
wuzhl2018/nano-signal-slot
051588437938a262b0a9738da024afcab2e8b8e6
[ "MIT" ]
null
null
null
#include <list> #include "CppUnitTest.h" #include "Test_Base.hpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace Nano_Tests { TEST_CLASS(Test_ST_Policy_Safe) { const int N = 64; using Moo_T = Moo<Observer_STS>; using Subject = Signal_Rng_STS; TEST_METHOD(Test_Global_Signal) { Subject subject; std::size_t count = 0; Rng rng; for (; count < N; ++count) { std::list<Moo_T> moo(N); for (auto& moo_instance : moo) { subject.connect<&Moo_T::slot_next_random>(moo_instance); } subject.fire(rng); } Assert::IsTrue(subject.is_empty(), L"A signal was found not empty."); } }; }
21.25
81
0.52
wuzhl2018
d1065e8800a4f5fa75e67e4d231f97b5173ee5cf
4,625
hpp
C++
rviz_default_plugins/test/rviz_default_plugins/publishers/odometry_publisher.hpp
EricCousineau-TRI/rviz
3344a8ed63b134549eeb82682f0dee76f53b7565
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/test/rviz_default_plugins/publishers/odometry_publisher.hpp
EricCousineau-TRI/rviz
3344a8ed63b134549eeb82682f0dee76f53b7565
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/test/rviz_default_plugins/publishers/odometry_publisher.hpp
EricCousineau-TRI/rviz
3344a8ed63b134549eeb82682f0dee76f53b7565
[ "BSD-3-Clause-Clear" ]
null
null
null
/* * Copyright (c) 2018, Bosch Software Innovations GmbH. * 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 copyright holder nor the names of its contributors * may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef RVIZ_DEFAULT_PLUGINS__PUBLISHERS__ODOMETRY_PUBLISHER_HPP_ #define RVIZ_DEFAULT_PLUGINS__PUBLISHERS__ODOMETRY_PUBLISHER_HPP_ #define _USE_MATH_DEFINES #include <cmath> #include <memory> #include <string> #include <vector> #include "rclcpp/rclcpp.hpp" #include "rclcpp/clock.hpp" #include "std_msgs/msg/header.hpp" #include "geometry_msgs/msg/pose_stamped.hpp" #include "nav_msgs/msg/odometry.hpp" #include "tf2_ros/transform_broadcaster.h" using namespace std::chrono_literals; // NOLINT namespace nodes { class OdometryPublisher : public rclcpp::Node { public: OdometryPublisher() : Node("odometry_publisher") { publisher = this->create_publisher<nav_msgs::msg::Odometry>("odometry"); timer = this->create_wall_timer(200ms, std::bind(&OdometryPublisher::timer_callback, this)); } // TODO(Martin-Idel-SI): shared_from_this() cannot be used in constructor. Use different // constructor once available. void initialize() { broadcaster = std::make_shared<tf2_ros::TransformBroadcaster>(shared_from_this()); } private: void timer_callback() { std::string base_frame("odometry_frame"); std::string child_frame("map"); auto now = rclcpp::Clock().now(); auto id = tf2::Quaternion::getIdentity(); auto transform = geometry_msgs::msg::TransformStamped(); transform.header.frame_id = base_frame; transform.header.stamp = now; transform.child_frame_id = child_frame; transform.transform.translation.x = 0.0f; transform.transform.translation.y = 0.0f; transform.transform.translation.z = 0.0f; transform.transform.rotation.x = id.getX(); transform.transform.rotation.y = id.getY(); transform.transform.rotation.z = id.getZ(); transform.transform.rotation.w = id.getW(); if (broadcaster) { broadcaster->sendTransform(transform); } auto odometry_msg = nav_msgs::msg::Odometry(); odometry_msg.header.frame_id = base_frame; odometry_msg.header.stamp = now; odometry_msg.child_frame_id = child_frame; odometry_msg.pose.pose.position.x = 0.0f; odometry_msg.pose.pose.position.y = 0.0f; odometry_msg.pose.pose.position.z = 0.0f; odometry_msg.pose.pose.orientation.x = id.getX(); odometry_msg.pose.pose.orientation.y = id.getY(); odometry_msg.pose.pose.orientation.z = id.getZ(); odometry_msg.pose.pose.orientation.w = id.getW(); odometry_msg.pose.covariance = std::array<double, 36>{ {0.75, 0.04, 0.1, 0, 0, 0, 0.04, 0.7, 0.4, 0, 0, 0, 0.1, 0.4, 0.5, 0, 0, 0, 0, 0, 0, 0.8, 0.25, 0.06, 0, 0, 0, 0.25, 0.3, 0.22, 0, 0, 0, 0.06, 0.22, 0.6} }; odometry_msg.twist.twist.linear.x = 0.3f; publisher->publish(odometry_msg); } std::shared_ptr<tf2_ros::TransformBroadcaster> broadcaster; rclcpp::TimerBase::SharedPtr timer; rclcpp::Publisher<nav_msgs::msg::Odometry>::SharedPtr publisher; }; } // namespace nodes #endif // RVIZ_DEFAULT_PLUGINS__PUBLISHERS__ODOMETRY_PUBLISHER_HPP_
36.132813
96
0.721297
EricCousineau-TRI
d106d308a5b4edbed76b7acdca490bd4b5fc0f06
2,320
hpp
C++
src/utils/lambda/lambda_info.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
2
2021-03-18T16:25:04.000Z
2021-11-13T00:29:27.000Z
src/utils/lambda/lambda_info.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
null
null
null
src/utils/lambda/lambda_info.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
1
2021-11-13T00:29:30.000Z
2021-11-13T00:29:30.000Z
/** * @file * @author __AUTHOR_NAME__ <mail@host.com> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ #ifndef ZEN_UTILS_LAMBDA_INFO_HPP #define ZEN_UTILS_LAMBDA_INFO_HPP #include <tuple> namespace Zen { /** * Source: angeart - https://qiita.com/angeart/items/94734d68999eca575881 * * This type trait allows one to get the following information about a given * lambda function: * - Return type * - Arity (Number of paramters) * - Type of each parameter * - Type of context/instance (In case of member function) * * It can be used as follow: * ```cpp * auto lambda = [] () { return 5; }; * * std::cout << "Return type: " << std::is_same<lambda_info<decltype(lambda)>::type, int>::value << std::endl; * * std::cout << "Args size: " << lambda_info<decltype(lambda)>::arity << std::endl; * * std::cout << "Argument 0 Type: " << std::is_same<lambda_info<decltype(lambda)>::arg<0>::type, int>::value << std::endl; * ``` * * @since 0.0.0 */ /** * @tparam T The return type of the lambda * @tparam C - * @tparam Args The paramter types of the lambda function * * @since 0.0.0 */ template <typename T, typename C, typename... Args> struct lambda_details { using type = T; enum { arity = sizeof...(Args) }; template<unsigned int i> struct arg { typedef typename std::tuple_element<i, std::tuple<Args...>>::type type; }; }; /** * Interface. * * @tparam L The lambda type to make a functor out of. * * @since 0.0.0 */ template <typename L> struct lambda_info : lambda_info<decltype(&L::operator())> {}; /** * Mutable Specialization. * * @tparam T The return type of the lambda * @tparam C The type of the context of the lambda * @tparam Args The paramter types of the lambda function * * @since 0.0.0 */ template <typename T, typename C, typename... Args> struct lambda_info<T (C::*)(Args...)> : lambda_details<T, C, Args...> {}; /** * Constant Specialization. * * @tparam T The return type of the lambda * @tparam C The type of the context of the lambda * @tparam Args The paramter types of the lambda function * * @since 0.0.0 */ template <typename T, typename C, typename... Args> struct lambda_info<T (C::*)(Args...) const> : lambda_details<T, C, Args...> {}; } // namespace Zen #endif
22.307692
122
0.656466
hexoctal
d107d752afefac53db3abc46d66eb517ebcd3fc4
12,688
cc
C++
flare/rpc/protocol/protobuf/poppy_protocol.cc
AriCheng/flare
b2c84588fe4ac52f0875791d22284d7e063fd057
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
868
2021-05-28T04:00:22.000Z
2022-03-31T08:57:14.000Z
flare/rpc/protocol/protobuf/poppy_protocol.cc
AriCheng/flare
b2c84588fe4ac52f0875791d22284d7e063fd057
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
33
2021-05-28T08:44:47.000Z
2021-09-26T13:09:21.000Z
flare/rpc/protocol/protobuf/poppy_protocol.cc
AriCheng/flare
b2c84588fe4ac52f0875791d22284d7e063fd057
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
122
2021-05-28T08:22:23.000Z
2022-03-29T09:52:09.000Z
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "flare/rpc/protocol/protobuf/poppy_protocol.h" #include <string> #include "flare/base/buffer/zero_copy_stream.h" #include "flare/base/down_cast.h" #include "flare/base/endian.h" #include "flare/base/string.h" #include "flare/rpc/protocol/protobuf/call_context.h" #include "flare/rpc/protocol/protobuf/call_context_factory.h" #include "flare/rpc/protocol/protobuf/compression.h" #include "flare/rpc/protocol/protobuf/message.h" #include "flare/rpc/protocol/protobuf/poppy_rpc_meta.pb.h" #include "flare/rpc/protocol/protobuf/rpc_meta.pb.h" #include "flare/rpc/protocol/protobuf/service_method_locator.h" using namespace std::literals; namespace flare::protobuf { FLARE_RPC_REGISTER_CLIENT_SIDE_STREAM_PROTOCOL_ARG("poppy", PoppyProtocol, false); FLARE_RPC_REGISTER_SERVER_SIDE_STREAM_PROTOCOL_ARG("poppy", PoppyProtocol, true); namespace { // All members are network byte-order. struct Header { std::uint32_t meta_size; std::uint32_t body_size; }; constexpr auto kHeaderSize = sizeof(Header); static_assert(kHeaderSize == 8); struct OnWireMessage : public Message { OnWireMessage() { SetRuntimeTypeTo<OnWireMessage>(); } std::uint64_t GetCorrelationId() const noexcept override { return meta.sequence_id(); } Type GetType() const noexcept override { return Type::Single; } poppy::RpcMeta meta; NoncontiguousBuffer body; }; StreamProtocol::Characteristics characteristics = {.name = "Poppy"}; poppy::CompressType GetCompressType(rpc::RpcMeta* meta) { if (!meta->has_compression_algorithm()) { return poppy::COMPRESS_TYPE_NONE; } auto compression = meta->compression_algorithm(); switch (compression) { case rpc::COMPRESSION_ALGORITHM_NONE: return poppy::COMPRESS_TYPE_NONE; case rpc::COMPRESSION_ALGORITHM_SNAPPY: return poppy::COMPRESS_TYPE_SNAPPY; default: // The compression algorithm specified is not supported by Poppy. meta->clear_compression_algorithm(); FLARE_LOG_WARNING_ONCE( "Compression algorithm [{}] is not supported by Poppy. Failing back " "to no compression.", rpc::CompressionAlgorithm_Name(compression)); return poppy::COMPRESS_TYPE_NONE; } } bool SetCompressionAlgorithm(rpc::RpcMeta* meta, google::protobuf::uint32 compress_type) { auto poppy_compress = static_cast<poppy::CompressType>(compress_type); switch (poppy_compress) { case poppy::COMPRESS_TYPE_NONE: return true; case poppy::COMPRESS_TYPE_SNAPPY: meta->set_compression_algorithm(rpc::COMPRESSION_ALGORITHM_SNAPPY); return true; default: FLARE_LOG_WARNING_EVERY_SECOND( "Unexpected compression algorithm #{} received.", compress_type); return false; } } } // namespace const StreamProtocol::Characteristics& PoppyProtocol::GetCharacteristics() const { return characteristics; } const MessageFactory* PoppyProtocol::GetMessageFactory() const { return &error_message_factory; } const ControllerFactory* PoppyProtocol::GetControllerFactory() const { return &passive_call_context_factory; } PoppyProtocol::MessageCutStatus PoppyProtocol::TryCutMessage( NoncontiguousBuffer* buffer, std::unique_ptr<Message>* message) { if (FLARE_UNLIKELY(!handshake_in_done_)) { auto status = KeepHandshakingIn(buffer); if (status != MessageCutStatus::Cut) { return status; } // Fall-through otherwise. } if (buffer->ByteSize() < kHeaderSize) { return MessageCutStatus::NeedMore; } // Extract the header (and convert the endianness if necessary) first. Header hdr; FlattenToSlow(*buffer, &hdr, kHeaderSize); FromBigEndian(&hdr.meta_size); FromBigEndian(&hdr.body_size); if (buffer->ByteSize() < kHeaderSize + hdr.meta_size + hdr.body_size) { return MessageCutStatus::NeedMore; } // `msg_bytes` is not filled. We're going to remove that argument soon. buffer->Skip(kHeaderSize); // Parse the meta. poppy::RpcMeta meta; { auto meta_bytes = buffer->Cut(hdr.meta_size); NoncontiguousBufferInputStream nbis(&meta_bytes); if (!meta.ParseFromZeroCopyStream(&nbis)) { FLARE_LOG_WARNING_EVERY_SECOND("Invalid meta received, dropped."); return MessageCutStatus::Error; } } // We've cut the message then. auto msg = std::make_unique<OnWireMessage>(); msg->meta = std::move(meta); msg->body = buffer->Cut(hdr.body_size); // Cut message off. *message = std::move(msg); return MessageCutStatus::Cut; } bool PoppyProtocol::TryParse(std::unique_ptr<Message>* message, Controller* controller) { auto on_wire = cast<OnWireMessage>(message->get()); auto&& poppy_meta = on_wire->meta; auto meta = object_pool::Get<rpc::RpcMeta>(); MaybeOwning<google::protobuf::Message> unpack_to; bool accept_msg_in_bytes; if ((server_side_ && !poppy_meta.has_method()) || (!server_side_ && !poppy_meta.has_failed())) { FLARE_LOG_WARNING_EVERY_SECOND( "Corrupted message: Essential fields not present. Correlation ID {}.", poppy_meta.sequence_id()); return false; } meta->set_correlation_id(poppy_meta.sequence_id()); meta->set_method_type(rpc::METHOD_TYPE_SINGLE); // Set compression algorithm. if (!SetCompressionAlgorithm(meta.Get(), poppy_meta.compress_type())) { return false; } if (server_side_) { auto&& req_meta = *meta->mutable_request_meta(); req_meta.set_method_name(poppy_meta.method()); auto&& method = meta->request_meta().method_name(); auto desc = ServiceMethodLocator::Instance()->TryGetMethodDesc( protocol_ids::standard, method); if (!desc) { FLARE_LOG_WARNING_EVERY_SECOND("Method [{}] is not found.", method); *message = std::make_unique<EarlyErrorMessage>( poppy_meta.sequence_id(), rpc::STATUS_METHOD_NOT_FOUND, fmt::format("Method [{}] is not implemented.", method)); return true; } // Not exactly. TODO(luobogao): Use what we've negotiated in handshaking // phase. static constexpr std::uint64_t kAcceptableCompressionAlgorithms = 1 << rpc::COMPRESSION_ALGORITHM_NONE | 1 << rpc::COMPRESSION_ALGORITHM_SNAPPY; req_meta.set_acceptable_compression_algorithms( kAcceptableCompressionAlgorithms); unpack_to = std::unique_ptr<google::protobuf::Message>( desc->request_prototype->New()); accept_msg_in_bytes = false; // TODO(luobogao): Implementation. } else { auto ctx = cast<ProactiveCallContext>(controller); accept_msg_in_bytes = ctx->accept_response_in_bytes; if (FLARE_LIKELY(!accept_msg_in_bytes)) { unpack_to = ctx->GetOrCreateResponse(); } if (!poppy_meta.failed()) { meta->mutable_response_meta()->set_status(rpc::STATUS_SUCCESS); } else { // FIXME: Error code definition does not match between brpc & flare. meta->mutable_response_meta()->set_status(poppy_meta.error_code()); if (poppy_meta.has_reason()) { meta->mutable_response_meta()->set_description(poppy_meta.reason()); } } } auto parsed = std::make_unique<ProtoMessage>(); parsed->meta = std::move(meta); if (FLARE_UNLIKELY(accept_msg_in_bytes)) { parsed->msg_or_buffer = std::move(on_wire->body); } else { NoncontiguousBuffer* buffer = &on_wire->body; if (!compression::DecompressBodyIfNeeded(*parsed->meta, on_wire->body, buffer)) { FLARE_LOG_WARNING_EVERY_SECOND( "Failed to decompress message (correlation id {}).", parsed->meta->correlation_id()); return false; } NoncontiguousBufferInputStream nbis(buffer); if (!unpack_to->ParseFromZeroCopyStream(&nbis)) { FLARE_LOG_WARNING_EVERY_SECOND( "Failed to parse message (correlation id {}).", poppy_meta.sequence_id()); return false; } parsed->msg_or_buffer = std::move(unpack_to); } *message = std::move(parsed); return true; } // Serialize `message` into `buffer`. void PoppyProtocol::WriteMessage(const Message& message, NoncontiguousBuffer* buffer, Controller* controller) { NoncontiguousBufferBuilder nbb; if (FLARE_UNLIKELY(!handeshake_out_done_)) { KeepHandshakingOut(&nbb); // Fall-through otherwise. } auto msg = cast<ProtoMessage>(&message); auto&& meta = *msg->meta; auto reserved_hdr = nbb.Reserve(sizeof(Header)); FLARE_LOG_ERROR_IF_ONCE(!msg->attachment.Empty(), "Attachment is not supported by Poppy protocol"); FLARE_LOG_ERROR_IF_ONCE( !controller->GetTracingContext().empty() || controller->IsTraceForciblySampled(), "Passing tracing context is not supported by Poppy protocol."); Header hdr; { NoncontiguousBufferOutputStream nbos(&nbb); // Translate & serialize rpc meta. poppy::RpcMeta poppy_meta; poppy_meta.set_sequence_id(meta.correlation_id()); poppy_meta.set_compress_type(GetCompressType(&meta)); if (server_side_) { auto&& resp_meta = meta.response_meta(); poppy_meta.set_failed(resp_meta.status() != rpc::STATUS_SUCCESS); poppy_meta.set_error_code(resp_meta.status()); // FIXME: Translate it. poppy_meta.set_reason(resp_meta.description()); } else { auto&& req_meta = meta.request_meta(); poppy_meta.set_method(req_meta.method_name()); poppy_meta.set_timeout(req_meta.timeout()); } hdr.meta_size = poppy_meta.ByteSizeLong(); FLARE_CHECK(poppy_meta.SerializeToZeroCopyStream(&nbos)); } hdr.body_size = compression::CompressBodyIfNeeded(meta, *msg, &nbb); // Fill the header. ToBigEndian(&hdr.body_size); ToBigEndian(&hdr.meta_size); memcpy(reserved_hdr, &hdr, sizeof(hdr)); buffer->Append(nbb.DestructiveGet()); } // Called in single-threaded environment. Each `PoppyProtocol` is bound to // exactly one connection, thus we can't be called concurrently. PoppyProtocol::MessageCutStatus PoppyProtocol::KeepHandshakingIn( NoncontiguousBuffer* buffer) { if (server_side_) { static constexpr auto kSignature = "POST /__rpc_service__ HTTP/1.1\r\n"sv; if (buffer->ByteSize() < kSignature.size()) { return MessageCutStatus::NotIdentified; } if (FlattenSlow(*buffer, kSignature.size()) != kSignature) { return MessageCutStatus::ProtocolMismatch; } } // I'm not sure if we need these headers but let's keep them anyway.. auto flatten = FlattenSlowUntil(*buffer, "\r\n\r\n"); if (!EndsWith(flatten, "\r\n\r\n")) { return MessageCutStatus::NeedMore; } buffer->Skip(flatten.size()); // Cut the handshake data off. auto splited = Split(flatten, "\r\n"); splited.erase(splited.begin()); // Skip Start-Line for (auto&& e : splited) { auto kvs = Split(e, ":", true /* Keep empty */); if (kvs.size() != 2) { FLARE_LOG_WARNING_EVERY_SECOND( "Failed to handshake with the remote side: Unexpected HTTP header " "[{}].", e); return MessageCutStatus::Error; } conn_headers_[std::string(Trim(kvs[0]))] = std::string(Trim(kvs[1])); } handshake_in_done_ = true; return MessageCutStatus::Cut; } // Always called in single-threaded environment. void PoppyProtocol::KeepHandshakingOut(NoncontiguousBufferBuilder* builder) { // Well, hard-code here should work adequately well. if (server_side_) { builder->Append( "HTTP/1.1 200 OK\r\n" "X-Poppy-Compress-Type: 0,1\r\n\r\n"); // No-compression & snappy. } else { builder->Append( "POST /__rpc_service__ HTTP/1.1\r\n" "Cookie: POPPY_AUTH_TICKET=\r\n" // Allow channel options to override // this? "X-Poppy-Compress-Type: 0,1\r\n" "X-Poppy-Tos: 96\r\n\r\n"); // We don't support TOS. } handeshake_out_done_ = true; } } // namespace flare::protobuf
34.291892
80
0.686239
AriCheng
d109752586cd1d82c191278962f520bf82dba9f4
5,117
cpp
C++
scene_with_camera/src/scene_with_camera.cpp
Phyllostachys/graphics-demos
bf1f1f10c95e0c9f752117ad23295ce06acdb17c
[ "MIT" ]
1
2015-09-05T11:15:07.000Z
2015-09-05T11:15:07.000Z
scene_with_camera/src/scene_with_camera.cpp
Phyllostachys/graphics-demos
bf1f1f10c95e0c9f752117ad23295ce06acdb17c
[ "MIT" ]
null
null
null
scene_with_camera/src/scene_with_camera.cpp
Phyllostachys/graphics-demos
bf1f1f10c95e0c9f752117ad23295ce06acdb17c
[ "MIT" ]
null
null
null
#include "cube.h" #include "shader.h" #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "glad/glad.h" #include "GLFW/glfw3.h" #include <cstdio> #include <iostream> glm::vec3 cameraPos = glm::vec3(0.0, 0.05, 23.0); glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f); glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); GLfloat cameraSpeed = 0.05f; bool showNewPosition = false; switch (key) { case GLFW_KEY_W: { cameraPos += cameraSpeed * cameraFront; showNewPosition = true; break; } case GLFW_KEY_S: { cameraPos -= cameraSpeed * cameraFront; showNewPosition = true; break; } case GLFW_KEY_A: { cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed; showNewPosition = true; break; } case GLFW_KEY_D: { cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed; showNewPosition = true; break; } case GLFW_KEY_Q: { cameraPos += cameraSpeed * cameraUp; showNewPosition = true; break; } case GLFW_KEY_Z: { cameraPos -= cameraSpeed * cameraUp; showNewPosition = true; break; } default: { break; } } if (showNewPosition) { printf("%02F,%02F,%02F\n", cameraPos.x, cameraPos.y, cameraPos.z); } } int main(int argc, char** argv) { int result; int width, height; result = glfwInit(); if (result == GLFW_FALSE) { printf("Problem initializing GLFW3."); return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow* window = glfwCreateWindow(800, 600, "Scene with Camera", nullptr, nullptr); if (window == nullptr) { printf("Problem creating window context."); return -1; } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Load in OGL functions if (!gladLoadGL()) { printf("Failed to initialize OpenGL context"); return -1; } glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); GLuint VAO; GLuint vertBufferIndex[2]; glGenVertexArrays(1, &VAO); glGenBuffers(2, vertBufferIndex); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, vertBufferIndex[0]); glBufferData(GL_ARRAY_BUFFER, NUM_CUBE_VERTS * sizeof(float), cubeVerts, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertBufferIndex[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_CUBE_IND * sizeof(unsigned int), cubeIndices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); // shaders Shader s("assets\\basic.vert", "assets\\basic.geom", "assets\\basic.frag"); if(!s.compile()) { printf("Some error happened while creating shaders\n"); return -1; } GLint mvpLoc = glGetUniformLocation(s.getShaderProgram(), "MVP"); GLint timeLoc = glGetUniformLocation(s.getShaderProgram(), "time"); glEnable(GL_DEPTH_TEST); // main loop while (!glfwWindowShouldClose(window)) { /* Poll for and process events */ glfwPollEvents(); glm::mat4 center, scale, rotate, translate; center = glm::translate(center, glm::vec3(-0.5, -0.5, -0.5)); //scale = glm::scale(scale, glm::vec3(1.6, 1.6, 1.6)); rotate = glm::rotate(rotate, (GLfloat)glfwGetTime() * 1.0f, glm::normalize(glm::vec3(0.0f, 1.0f, 0.0f))); translate = glm::translate(translate, glm::vec3(0.0, 0.0, 20.0)); glm::mat4 model; model = translate * rotate * scale * center * model; glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); glm::mat4 proj = glm::perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 1000.0f); glm::mat4 mvp = proj * view * model; glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(s.getShaderProgram()); glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, glm::value_ptr(mvp)); glUniform1f(timeLoc, (GLfloat)glfwGetTime() * 1.5); glUniform3f(glGetUniformLocation(s.getShaderProgram(), "drawColor"), 0.0f, 1.0f, 0.0f); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDrawElements(GL_TRIANGLES, NUM_CUBE_IND, GL_UNSIGNED_INT, 0); glfwSwapBuffers(window); } glfwTerminate(); return 0; }
30.640719
113
0.62478
Phyllostachys
d10aa175883debfa6a2ed2df0f352342fbe3048d
211
hpp
C++
app/AppRunner.hpp
ChristopherCanfield/canfield_ant_simulator
9ec671fe4936a8ed3a19f2c79a54e420092769fe
[ "MIT" ]
1
2016-01-29T06:25:36.000Z
2016-01-29T06:25:36.000Z
app/AppRunner.hpp
ChristopherCanfield/canfield_ant_simulator
9ec671fe4936a8ed3a19f2c79a54e420092769fe
[ "MIT" ]
null
null
null
app/AppRunner.hpp
ChristopherCanfield/canfield_ant_simulator
9ec671fe4936a8ed3a19f2c79a54e420092769fe
[ "MIT" ]
null
null
null
#pragma once #include "App.hpp" // Christopher D. Canfield // October 2013 // AppRunner.hpp namespace cdc { class AppRunner { public: AppRunner() {} ~AppRunner() {} void execute(App& app); }; }
9.590909
26
0.630332
ChristopherCanfield
d10c1022c5bef0fe89795eefc41779312f3a3d25
4,146
cpp
C++
tcss/src/v20201101/model/ModifyVirusMonitorSettingRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tcss/src/v20201101/model/ModifyVirusMonitorSettingRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tcss/src/v20201101/model/ModifyVirusMonitorSettingRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tcss/v20201101/model/ModifyVirusMonitorSettingRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Tcss::V20201101::Model; using namespace std; ModifyVirusMonitorSettingRequest::ModifyVirusMonitorSettingRequest() : m_enableScanHasBeenSet(false), m_scanPathAllHasBeenSet(false), m_scanPathTypeHasBeenSet(false), m_scanPathHasBeenSet(false) { } string ModifyVirusMonitorSettingRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_enableScanHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EnableScan"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_enableScan, allocator); } if (m_scanPathAllHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ScanPathAll"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_scanPathAll, allocator); } if (m_scanPathTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ScanPathType"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_scanPathType, allocator); } if (m_scanPathHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ScanPath"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_scanPath.begin(); itr != m_scanPath.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } bool ModifyVirusMonitorSettingRequest::GetEnableScan() const { return m_enableScan; } void ModifyVirusMonitorSettingRequest::SetEnableScan(const bool& _enableScan) { m_enableScan = _enableScan; m_enableScanHasBeenSet = true; } bool ModifyVirusMonitorSettingRequest::EnableScanHasBeenSet() const { return m_enableScanHasBeenSet; } bool ModifyVirusMonitorSettingRequest::GetScanPathAll() const { return m_scanPathAll; } void ModifyVirusMonitorSettingRequest::SetScanPathAll(const bool& _scanPathAll) { m_scanPathAll = _scanPathAll; m_scanPathAllHasBeenSet = true; } bool ModifyVirusMonitorSettingRequest::ScanPathAllHasBeenSet() const { return m_scanPathAllHasBeenSet; } uint64_t ModifyVirusMonitorSettingRequest::GetScanPathType() const { return m_scanPathType; } void ModifyVirusMonitorSettingRequest::SetScanPathType(const uint64_t& _scanPathType) { m_scanPathType = _scanPathType; m_scanPathTypeHasBeenSet = true; } bool ModifyVirusMonitorSettingRequest::ScanPathTypeHasBeenSet() const { return m_scanPathTypeHasBeenSet; } vector<string> ModifyVirusMonitorSettingRequest::GetScanPath() const { return m_scanPath; } void ModifyVirusMonitorSettingRequest::SetScanPath(const vector<string>& _scanPath) { m_scanPath = _scanPath; m_scanPathHasBeenSet = true; } bool ModifyVirusMonitorSettingRequest::ScanPathHasBeenSet() const { return m_scanPathHasBeenSet; }
27.64
104
0.733237
suluner
d111089c7c015c4b4d0049c87a575b577a2ccebf
3,841
hpp
C++
libraries/eos-vm/include/eosio/vm/opcodes.hpp
pizzachain/pizchain
ba51553e46521ca7b265d7045d678312a32f8140
[ "MIT" ]
1,313
2018-01-09T01:49:01.000Z
2022-02-26T11:10:40.000Z
src/vm/wasm/eos-vm/include/eosio/vm/opcodes.hpp
linnbenton/WaykiChain
91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a
[ "MIT" ]
32
2018-06-07T10:21:21.000Z
2021-12-07T06:53:42.000Z
src/vm/wasm/eos-vm/include/eosio/vm/opcodes.hpp
linnbenton/WaykiChain
91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a
[ "MIT" ]
322
2018-02-26T03:41:36.000Z
2022-02-08T08:12:16.000Z
#pragma once #include <eosio/vm/opcodes_def.hpp> #include <eosio/vm/variant.hpp> #include <map> namespace eosio { namespace vm { enum opcodes { EOS_VM_CONTROL_FLOW_OPS(EOS_VM_CREATE_ENUM) EOS_VM_BR_TABLE_OP(EOS_VM_CREATE_ENUM) EOS_VM_RETURN_OP(EOS_VM_CREATE_ENUM) EOS_VM_CALL_OPS(EOS_VM_CREATE_ENUM) EOS_VM_CALL_IMM_OPS(EOS_VM_CREATE_ENUM) EOS_VM_PARAMETRIC_OPS(EOS_VM_CREATE_ENUM) EOS_VM_VARIABLE_ACCESS_OPS(EOS_VM_CREATE_ENUM) EOS_VM_MEMORY_OPS(EOS_VM_CREATE_ENUM) EOS_VM_I32_CONSTANT_OPS(EOS_VM_CREATE_ENUM) EOS_VM_I64_CONSTANT_OPS(EOS_VM_CREATE_ENUM) EOS_VM_F32_CONSTANT_OPS(EOS_VM_CREATE_ENUM) EOS_VM_F64_CONSTANT_OPS(EOS_VM_CREATE_ENUM) EOS_VM_COMPARISON_OPS(EOS_VM_CREATE_ENUM) EOS_VM_NUMERIC_OPS(EOS_VM_CREATE_ENUM) EOS_VM_CONVERSION_OPS(EOS_VM_CREATE_ENUM) EOS_VM_EXIT_OP(EOS_VM_CREATE_ENUM) EOS_VM_EMPTY_OPS(EOS_VM_CREATE_ENUM) EOS_VM_ERROR_OPS(EOS_VM_CREATE_ENUM) }; struct opcode_utils { std::map<uint16_t, std::string> opcode_map{ EOS_VM_CONTROL_FLOW_OPS(EOS_VM_CREATE_MAP) EOS_VM_BR_TABLE_OP(EOS_VM_CREATE_MAP) EOS_VM_RETURN_OP(EOS_VM_CREATE_MAP) EOS_VM_CALL_OPS(EOS_VM_CREATE_MAP) EOS_VM_CALL_IMM_OPS(EOS_VM_CREATE_MAP) EOS_VM_PARAMETRIC_OPS(EOS_VM_CREATE_MAP) EOS_VM_VARIABLE_ACCESS_OPS(EOS_VM_CREATE_MAP) EOS_VM_MEMORY_OPS(EOS_VM_CREATE_MAP) EOS_VM_I32_CONSTANT_OPS(EOS_VM_CREATE_MAP) EOS_VM_I64_CONSTANT_OPS(EOS_VM_CREATE_MAP) EOS_VM_F32_CONSTANT_OPS(EOS_VM_CREATE_MAP) EOS_VM_F64_CONSTANT_OPS(EOS_VM_CREATE_MAP) EOS_VM_COMPARISON_OPS(EOS_VM_CREATE_MAP) EOS_VM_NUMERIC_OPS(EOS_VM_CREATE_MAP) EOS_VM_CONVERSION_OPS(EOS_VM_CREATE_MAP) EOS_VM_EXIT_OP(EOS_VM_CREATE_MAP) EOS_VM_EMPTY_OPS(EOS_VM_CREATE_MAP) EOS_VM_ERROR_OPS(EOS_VM_CREATE_MAP) }; }; enum imm_types { none, block_imm, varuint32_imm, br_table_imm, }; EOS_VM_CONTROL_FLOW_OPS(EOS_VM_CREATE_CONTROL_FLOW_TYPES) EOS_VM_BR_TABLE_OP(EOS_VM_CREATE_BR_TABLE_TYPE) EOS_VM_RETURN_OP(EOS_VM_CREATE_CONTROL_FLOW_TYPES) EOS_VM_CALL_OPS(EOS_VM_CREATE_CALL_TYPES) EOS_VM_CALL_IMM_OPS(EOS_VM_CREATE_CALL_IMM_TYPES) EOS_VM_PARAMETRIC_OPS(EOS_VM_CREATE_TYPES) EOS_VM_VARIABLE_ACCESS_OPS(EOS_VM_CREATE_VARIABLE_ACCESS_TYPES) EOS_VM_MEMORY_OPS(EOS_VM_CREATE_MEMORY_TYPES) EOS_VM_I32_CONSTANT_OPS(EOS_VM_CREATE_I32_CONSTANT_TYPE) EOS_VM_I64_CONSTANT_OPS(EOS_VM_CREATE_I64_CONSTANT_TYPE) EOS_VM_F32_CONSTANT_OPS(EOS_VM_CREATE_F32_CONSTANT_TYPE) EOS_VM_F64_CONSTANT_OPS(EOS_VM_CREATE_F64_CONSTANT_TYPE) EOS_VM_COMPARISON_OPS(EOS_VM_CREATE_TYPES) EOS_VM_NUMERIC_OPS(EOS_VM_CREATE_TYPES) EOS_VM_CONVERSION_OPS(EOS_VM_CREATE_TYPES) EOS_VM_EXIT_OP(EOS_VM_CREATE_EXIT_TYPE) EOS_VM_EMPTY_OPS(EOS_VM_CREATE_TYPES) EOS_VM_ERROR_OPS(EOS_VM_CREATE_TYPES) using opcode = variant< EOS_VM_CONTROL_FLOW_OPS(EOS_VM_IDENTITY) EOS_VM_BR_TABLE_OP(EOS_VM_IDENTITY) EOS_VM_RETURN_OP(EOS_VM_IDENTITY) EOS_VM_CALL_OPS(EOS_VM_IDENTITY) EOS_VM_CALL_IMM_OPS(EOS_VM_IDENTITY) EOS_VM_PARAMETRIC_OPS(EOS_VM_IDENTITY) EOS_VM_VARIABLE_ACCESS_OPS(EOS_VM_IDENTITY) EOS_VM_MEMORY_OPS(EOS_VM_IDENTITY) EOS_VM_I32_CONSTANT_OPS(EOS_VM_IDENTITY) EOS_VM_I64_CONSTANT_OPS(EOS_VM_IDENTITY) EOS_VM_F32_CONSTANT_OPS(EOS_VM_IDENTITY) EOS_VM_F64_CONSTANT_OPS(EOS_VM_IDENTITY) EOS_VM_COMPARISON_OPS(EOS_VM_IDENTITY) EOS_VM_NUMERIC_OPS(EOS_VM_IDENTITY) EOS_VM_CONVERSION_OPS(EOS_VM_IDENTITY) EOS_VM_EXIT_OP(EOS_VM_IDENTITY) EOS_VM_EMPTY_OPS(EOS_VM_IDENTITY) EOS_VM_ERROR_OPS(EOS_VM_IDENTITY_END) >; }} // namespace eosio::vm
38.41
66
0.787555
pizzachain
d1112cc9ba8a907848b28fc67ed6bbfbefee1454
6,818
cxx
C++
Servers/ServerManager/vtkSMLookupTableProxy.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
Servers/ServerManager/vtkSMLookupTableProxy.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
Servers/ServerManager/vtkSMLookupTableProxy.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html 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 notice for more information. =========================================================================*/ #include "vtkSMLookupTableProxy.h" #include "vtkClientServerStream.h" #include "vtkObjectFactory.h" #include "vtkProcessModule.h" #include "vtkSMIntVectorProperty.h" #include "vtkSMDoubleVectorProperty.h" #include "vtkMath.h" vtkStandardNewMacro(vtkSMLookupTableProxy); vtkCxxRevisionMacro(vtkSMLookupTableProxy, "$Revision$"); //--------------------------------------------------------------------------- vtkSMLookupTableProxy::vtkSMLookupTableProxy() { this->SetVTKClassName("vtkLookupTable"); this->ArrayName = 0; this->LowOutOfRangeColor[0] = this->LowOutOfRangeColor[1] = this->LowOutOfRangeColor[2] = 0; this->HighOutOfRangeColor[0] = this->HighOutOfRangeColor[1] = this->HighOutOfRangeColor[2] = 1; this->UseLowOutOfRangeColor = 0; this->UseHighOutOfRangeColor = 0; } //--------------------------------------------------------------------------- vtkSMLookupTableProxy::~vtkSMLookupTableProxy() { this->SetVTKClassName(0); this->SetArrayName(0); } //--------------------------------------------------------------------------- void vtkSMLookupTableProxy::CreateVTKObjects() { if (this->ObjectsCreated) { return; } this->SetServers(vtkProcessModule::CLIENT | vtkProcessModule::RENDER_SERVER); this->Superclass::CreateVTKObjects(); } //--------------------------------------------------------------------------- void vtkSMLookupTableProxy::UpdateVTKObjects(vtkClientServerStream& stream) { this->Superclass::UpdateVTKObjects(stream); this->Build(); } //--------------------------------------------------------------------------- void vtkSMLookupTableProxy::Build() { vtkClientServerStream stream; vtkSMProperty* p; vtkSMIntVectorProperty* intVectProp; vtkSMDoubleVectorProperty* doubleVectProp; int numberOfTableValues; double hueRange[2]; double saturationRange[2]; double valueRange[2]; p = this->GetProperty("NumberOfTableValues"); intVectProp = vtkSMIntVectorProperty::SafeDownCast(p); numberOfTableValues = intVectProp->GetElement(0); p = this->GetProperty("HueRange"); doubleVectProp = vtkSMDoubleVectorProperty::SafeDownCast(p); hueRange[0] = doubleVectProp->GetElement(0); hueRange[1] = doubleVectProp->GetElement(1); p = this->GetProperty("ValueRange"); doubleVectProp = vtkSMDoubleVectorProperty::SafeDownCast(p); valueRange[0] = doubleVectProp->GetElement(0); valueRange[1] = doubleVectProp->GetElement(1); p = this->GetProperty("SaturationRange"); doubleVectProp = vtkSMDoubleVectorProperty::SafeDownCast(p); saturationRange[0] = doubleVectProp->GetElement(0); saturationRange[1] = doubleVectProp->GetElement(1); if (hueRange[0]<1.1) // Hack to deal with sandia color map. { // not Sandia interpolation. stream << vtkClientServerStream::Invoke << this->GetID() << "ForceBuild" << vtkClientServerStream::End; int numColors = (numberOfTableValues < 1) ? 1 : numberOfTableValues; if (this->UseLowOutOfRangeColor) { stream << vtkClientServerStream::Invoke << this->GetID() << "SetTableValue" << 0 << this->LowOutOfRangeColor[0] << this->LowOutOfRangeColor[1] << this->LowOutOfRangeColor[2] << 1 << vtkClientServerStream::End; } if (this->UseHighOutOfRangeColor) { stream << vtkClientServerStream::Invoke << this->GetID() << "SetTableValue" << numColors-1 << this->HighOutOfRangeColor[0] << this->HighOutOfRangeColor[1] << this->HighOutOfRangeColor[2] << 1 << vtkClientServerStream::End; } } else { //now we need to loop through the number of colors setting the colors //in the table stream << vtkClientServerStream::Invoke << this->GetID() << "SetNumberOfTableValues" << numberOfTableValues << vtkClientServerStream::End; int j; double rgba[4]; double xyz[3]; double lab[3]; //only use opaque colors rgba[3]=1; int numColors= numberOfTableValues - 1; if (numColors<=0) numColors=1; for (j=0;j<numberOfTableValues;j++) { // Get the color lab[0] = hueRange[0]+(hueRange[1]-hueRange[0])/(numColors)*j; lab[1] = saturationRange[0]+(saturationRange[1]-saturationRange[0])/ (numColors)*j; lab[2] = valueRange[0]+(valueRange[1]-valueRange[0])/ (numColors)*j; vtkMath::LabToXYZ(lab,xyz); vtkMath::XYZToRGB(xyz,rgba); stream << vtkClientServerStream::Invoke << this->GetID() << "SetTableValue" << j << rgba[0] << rgba[1] << rgba[2] << rgba[3] << vtkClientServerStream::End; } if (this->UseLowOutOfRangeColor) { stream << vtkClientServerStream::Invoke << this->GetID() << "SetTableValue 0" << this->LowOutOfRangeColor[0] << this->LowOutOfRangeColor[1] << this->LowOutOfRangeColor[2] << 1 << vtkClientServerStream::End; } if (this->UseHighOutOfRangeColor) { stream << vtkClientServerStream::Invoke << this->GetID() << "SetTableValue" << numColors-1 << this->HighOutOfRangeColor[0] << this->HighOutOfRangeColor[1] << this->HighOutOfRangeColor[2] << 1 << vtkClientServerStream::End; } } vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); pm->SendStream(this->ConnectionID, this->Servers, stream); } //--------------------------------------------------------------------------- void vtkSMLookupTableProxy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "ArrayName: " << (this->ArrayName?this->ArrayName:"(none)") << endl; os << indent << "LowOutOfRangeColor: " << this->LowOutOfRangeColor[0] << " " << this->LowOutOfRangeColor[1] << " " << this->LowOutOfRangeColor[2] << endl; os << indent << "HighOutOfRangeColor: " << this->HighOutOfRangeColor[0] << " " << this->HighOutOfRangeColor[1] << " " << this->HighOutOfRangeColor[2] << endl; os << indent << "UseLowOutOfRangeColor: " << this->UseLowOutOfRangeColor << endl; os << indent << "UseHighOutOfRangeColor: " << this->UseHighOutOfRangeColor << endl; }
34.09
79
0.601496
matthb2
d1113b9fefec12a5e6eee6acf59642f0769b9b9f
7,343
cpp
C++
sounddev/SoundDeviceBase.cpp
Wapitiii/openmpt
339c5f7f7e2c4a522415b42f0b6a9f4b2e2ab3bd
[ "BSD-3-Clause" ]
4
2020-06-15T07:02:08.000Z
2021-08-01T22:38:46.000Z
sounddev/SoundDeviceBase.cpp
glowcoil/microplug
5c2708b89837dbc38a1f0e7cd793e5e53838e4a4
[ "BSD-3-Clause" ]
null
null
null
sounddev/SoundDeviceBase.cpp
glowcoil/microplug
5c2708b89837dbc38a1f0e7cd793e5e53838e4a4
[ "BSD-3-Clause" ]
1
2021-06-07T03:14:59.000Z
2021-06-07T03:14:59.000Z
/* * SoundDeviceBase.cpp * ------------------- * Purpose: Sound device drivers base class. * Notes : (currently none) * Authors: Olivier Lapicque * OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "SoundDeviceBase.h" OPENMPT_NAMESPACE_BEGIN namespace SoundDevice { Base::Base(SoundDevice::Info info, SoundDevice::SysInfo sysInfo) : m_Source(nullptr) , m_MessageReceiver(nullptr) , m_Info(info) , m_SysInfo(sysInfo) , m_StreamPositionOutputFrames(0) , m_RequestFlags(0) { MPT_TRACE_SCOPE(); m_DeviceUnavailableOnOpen = false; m_IsPlaying = false; m_StreamPositionRenderFrames = 0; m_StreamPositionOutputFrames = 0; m_RequestFlags.store(0); } Base::~Base() { MPT_TRACE_SCOPE(); return; } SoundDevice::DynamicCaps Base::GetDeviceDynamicCaps(const std::vector<uint32> &baseSampleRates) { MPT_TRACE_SCOPE(); SoundDevice::DynamicCaps result; result.supportedSampleRates = baseSampleRates; return result; } bool Base::Init(const SoundDevice::AppInfo &appInfo) { MPT_TRACE_SCOPE(); if(IsInited()) { return true; } m_AppInfo = appInfo; m_Caps = InternalGetDeviceCaps(); return m_Caps.Available; } bool Base::Open(const SoundDevice::Settings &settings) { MPT_TRACE_SCOPE(); if(IsOpen()) { Close(); } m_Settings = settings; if(m_Settings.Latency == 0.0) m_Settings.Latency = m_Caps.DefaultSettings.Latency; if(m_Settings.UpdateInterval == 0.0) m_Settings.UpdateInterval = m_Caps.DefaultSettings.UpdateInterval; m_Settings.Latency = std::clamp(m_Settings.Latency, m_Caps.LatencyMin, m_Caps.LatencyMax); m_Settings.UpdateInterval = std::clamp(m_Settings.UpdateInterval, m_Caps.UpdateIntervalMin, m_Caps.UpdateIntervalMax); m_Flags = SoundDevice::Flags(); m_DeviceUnavailableOnOpen = false; m_RequestFlags.store(0); return InternalOpen(); } bool Base::Close() { MPT_TRACE_SCOPE(); if(!IsOpen()) return true; Stop(); bool result = InternalClose(); m_RequestFlags.store(0); return result; } uint64 Base::SourceGetReferenceClockNowNanoseconds() const { MPT_TRACE_SCOPE(); if(!m_Source) { return 0; } uint64 result = m_Source->SoundSourceGetReferenceClockNowNanoseconds(); //MPT_LOG(LogDebug, "sounddev", mpt::format(U_("clock: %1"))(result)); return result; } uint64 Base::SourceLockedGetReferenceClockNowNanoseconds() const { MPT_TRACE_SCOPE(); if(!m_Source) { return 0; } uint64 result = m_Source->SoundSourceLockedGetReferenceClockNowNanoseconds(); //MPT_LOG(LogDebug, "sounddev", mpt::format(U_("clock-rt: %1"))(result)); return result; } void Base::SourceNotifyPreStart() { MPT_TRACE_SCOPE(); if(m_Source) { m_Source->SoundSourcePreStartCallback(); } } void Base::SourceNotifyPostStop() { MPT_TRACE_SCOPE(); if(m_Source) { m_Source->SoundSourcePostStopCallback(); } } bool Base::SourceIsLockedByCurrentThread() const { MPT_TRACE_SCOPE(); if(!m_Source) { return false; } return m_Source->SoundSourceIsLockedByCurrentThread(); } void Base::SourceFillAudioBufferLocked() { MPT_TRACE_SCOPE(); if(m_Source) { SourceLockedGuard lock(*m_Source); InternalFillAudioBuffer(); } } void Base::SourceLockedAudioReadPrepare(std::size_t numFrames, std::size_t framesLatency) { MPT_TRACE_SCOPE(); if(!InternalHasTimeInfo()) { SoundDevice::TimeInfo timeInfo; if(InternalHasGetStreamPosition()) { timeInfo.SyncPointStreamFrames = InternalHasGetStreamPosition(); timeInfo.SyncPointSystemTimestamp = SourceLockedGetReferenceClockNowNanoseconds(); timeInfo.Speed = 1.0; } else { timeInfo.SyncPointStreamFrames = m_StreamPositionRenderFrames + numFrames; timeInfo.SyncPointSystemTimestamp = SourceLockedGetReferenceClockNowNanoseconds() + mpt::saturate_round<int64>(GetEffectiveBufferAttributes().Latency * 1000000000.0); timeInfo.Speed = 1.0; } timeInfo.RenderStreamPositionBefore = StreamPositionFromFrames(m_StreamPositionRenderFrames); timeInfo.RenderStreamPositionAfter = StreamPositionFromFrames(m_StreamPositionRenderFrames + numFrames); timeInfo.Latency = GetEffectiveBufferAttributes().Latency; SetTimeInfo(timeInfo); } m_StreamPositionRenderFrames += numFrames; if(!InternalHasGetStreamPosition() && !InternalHasTimeInfo()) { m_StreamPositionOutputFrames = m_StreamPositionRenderFrames - framesLatency; } else { // unused, no locking m_StreamPositionOutputFrames = 0; } if(m_Source) { m_Source->SoundSourceLockedReadPrepare(m_TimeInfo); } } void Base::SourceLockedAudioRead(void *buffer, const void *inputBuffer, std::size_t numFrames) { MPT_TRACE_SCOPE(); if(numFrames <= 0) { return; } if(m_Source) { m_Source->SoundSourceLockedRead(GetBufferFormat(), numFrames, buffer, inputBuffer); } } void Base::SourceLockedAudioReadDone() { MPT_TRACE_SCOPE(); if(m_Source) { m_Source->SoundSourceLockedReadDone(m_TimeInfo); } } void Base::SendDeviceMessage(LogLevel level, const mpt::ustring &str) { MPT_TRACE_SCOPE(); MPT_LOG(level, "sounddev", str); if(m_MessageReceiver) { m_MessageReceiver->SoundDeviceMessage(level, str); } } bool Base::Start() { MPT_TRACE_SCOPE(); if(!IsOpen()) return false; if(!IsPlaying()) { m_StreamPositionRenderFrames = 0; { m_StreamPositionOutputFrames = 0; } SourceNotifyPreStart(); m_RequestFlags.fetch_and((~RequestFlagRestart).as_bits()); if(!InternalStart()) { SourceNotifyPostStop(); return false; } m_IsPlaying = true; } return true; } void Base::Stop() { MPT_TRACE_SCOPE(); if(!IsOpen()) return; if(IsPlaying()) { InternalStop(); m_RequestFlags.fetch_and((~RequestFlagRestart).as_bits()); SourceNotifyPostStop(); m_IsPlaying = false; m_StreamPositionOutputFrames = 0; m_StreamPositionRenderFrames = 0; } } void Base::StopAndAvoidPlayingSilence() { MPT_TRACE_SCOPE(); if(!IsOpen()) { return; } if(!IsPlaying()) { return; } InternalStopAndAvoidPlayingSilence(); m_RequestFlags.fetch_and((~RequestFlagRestart).as_bits()); SourceNotifyPostStop(); m_IsPlaying = false; m_StreamPositionOutputFrames = 0; m_StreamPositionRenderFrames = 0; } void Base::EndPlayingSilence() { MPT_TRACE_SCOPE(); if(!IsOpen()) { return; } if(IsPlaying()) { return; } InternalEndPlayingSilence(); } SoundDevice::StreamPosition Base::GetStreamPosition() const { MPT_TRACE_SCOPE(); if(!IsOpen()) { return StreamPosition(); } int64 frames = 0; if(InternalHasGetStreamPosition()) { frames = InternalGetStreamPositionFrames(); } else if(InternalHasTimeInfo()) { const uint64 now = SourceGetReferenceClockNowNanoseconds(); const SoundDevice::TimeInfo timeInfo = GetTimeInfo(); frames = mpt::saturate_round<int64>( timeInfo.SyncPointStreamFrames + ( static_cast<double>(static_cast<int64>(now - timeInfo.SyncPointSystemTimestamp)) * timeInfo.Speed * m_Settings.Samplerate * (1.0 / (1000.0 * 1000.0)) ) ); } else { frames = m_StreamPositionOutputFrames; } return StreamPositionFromFrames(frames); } SoundDevice::Statistics Base::GetStatistics() const { MPT_TRACE_SCOPE(); SoundDevice::Statistics result; result.InstantaneousLatency = m_Settings.Latency; result.LastUpdateInterval = m_Settings.UpdateInterval; result.text = mpt::ustring(); return result; } } // namespace SoundDevice OPENMPT_NAMESPACE_END
20.397222
169
0.74234
Wapitiii
d1139d7bdcff4c9e08d8f74bf3d09b42a3febf52
1,111
cpp
C++
Algorithms/Easy/53.maximum-subarray.cpp
jtcheng/leetcode
db58973894757789d060301b589735b5985fe102
[ "MIT" ]
null
null
null
Algorithms/Easy/53.maximum-subarray.cpp
jtcheng/leetcode
db58973894757789d060301b589735b5985fe102
[ "MIT" ]
null
null
null
Algorithms/Easy/53.maximum-subarray.cpp
jtcheng/leetcode
db58973894757789d060301b589735b5985fe102
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=53 lang=cpp * * [53] Maximum Subarray * * https://leetcode.com/problems/maximum-subarray/description/ * * algorithms * Easy (42.60%) * Total Accepted: 456.2K * Total Submissions: 1.1M * Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]' * * Given an integer array nums, find the contiguous subarrayย (containing at * least one number) which has the largest sum and return its sum. * * Example: * * * Input: [-2,1,-3,4,-1,2,1,-5,4], * Output: 6 * Explanation:ย [4,-1,2,1] has the largest sum = 6. * * * Follow up: * * If you have figured out the O(n) solution, try coding another solution using * the divide and conquer approach, which is more subtle. * */ class Solution { public: int maxSubArray(vector<int>& nums) { int sum = nums[0]; int smax = nums[0]; pair<int, int> indexes; for (int i = 1, len = nums.size(); i < len; ++i) { if (nums[i] > sum + nums[i]) { sum = nums[i]; indexes.first = i; } else { sum = sum + nums[i]; } if (sum > smax) { smax = sum; indexes.second = i; } } return smax; } };
20.574074
79
0.588659
jtcheng
d11403f76131eec16664899bfef104119a86aa00
6,449
cpp
C++
src/Engine/Renderer/RenderTechnique/RenderTechnique.cpp
hoshiryu/Radium-Engine
2bc3c475a8fb1948dad84d1278bf4d61258f3cda
[ "Apache-2.0" ]
null
null
null
src/Engine/Renderer/RenderTechnique/RenderTechnique.cpp
hoshiryu/Radium-Engine
2bc3c475a8fb1948dad84d1278bf4d61258f3cda
[ "Apache-2.0" ]
null
null
null
src/Engine/Renderer/RenderTechnique/RenderTechnique.cpp
hoshiryu/Radium-Engine
2bc3c475a8fb1948dad84d1278bf4d61258f3cda
[ "Apache-2.0" ]
null
null
null
#include <Engine/Renderer/RenderTechnique/RenderTechnique.hpp> #include <Engine/Renderer/Material/BlinnPhongMaterial.hpp> #include <Engine/Renderer/RenderTechnique/RenderParameters.hpp> #include <Engine/Renderer/RenderTechnique/ShaderConfigFactory.hpp> #include <Engine/Renderer/RenderTechnique/ShaderProgramManager.hpp> #include <Core/Utils/Log.hpp> namespace Ra { namespace Engine { using namespace Core::Utils; // log std::shared_ptr<Ra::Engine::RenderTechnique> RadiumDefaultRenderTechnique {nullptr}; RenderTechnique::RenderTechnique() : m_numActivePass {0} { for ( auto p = Index( 0 ); p < s_maxNbPasses; ++p ) { m_activePasses[p] = std::move( PassConfiguration( ShaderConfiguration(), nullptr ) ); m_passesParameters[p] = nullptr; } } RenderTechnique::RenderTechnique( const RenderTechnique& o ) : m_numActivePass {o.m_numActivePass}, m_dirtyBits {o.m_dirtyBits}, m_setPasses {o.m_setPasses} { for ( auto p = Index( 0 ); p < m_numActivePass; ++p ) { if ( hasConfiguration( p ) ) { m_activePasses[p] = o.m_activePasses[p]; m_passesParameters[p] = o.m_passesParameters[p]; } } } RenderTechnique::~RenderTechnique() = default; void RenderTechnique::setConfiguration( const ShaderConfiguration& newConfig, Core::Utils::Index pass ) { m_numActivePass = std::max( m_numActivePass, pass + 1 ); m_activePasses[pass] = std::move( PassConfiguration( newConfig, nullptr ) ); setDirty( pass ); setConfiguration( pass ); } const ShaderProgram* RenderTechnique::getShader( Core::Utils::Index pass ) const { if ( hasConfiguration( pass ) ) { return m_activePasses[pass].second; } return nullptr; } void RenderTechnique::setParametersProvider( std::shared_ptr<ShaderParameterProvider> provider, Core::Utils::Index pass ) { if ( m_numActivePass == 0 ) { LOG( logERROR ) << "Unable to set pass parameters : is passes configured using setConfiguration ? "; return; } if ( pass.isValid() ) { if ( hasConfiguration( pass ) ) { m_passesParameters[pass] = provider; } } else { for ( int i = 0; i < m_numActivePass; ++i ) { if ( hasConfiguration( i ) ) { m_passesParameters[i] = provider; } } } // add the provider specific properties to the configuration addPassProperties( provider->getPropertyList() ); } void RenderTechnique::addPassProperties( const std::list<std::string>& props, Core::Utils::Index pass ) { if ( m_numActivePass == 0 ) { LOG( logERROR ) << "Unable to set pass properties : is passes configured using setConfiguration ? "; return; } if ( pass.isValid() && hasConfiguration( pass ) ) { m_activePasses[pass].first.addProperties( props ); setDirty( pass ); } else { for ( int i = 0; i < m_numActivePass; ++i ) { if ( hasConfiguration( i ) ) { m_activePasses[i].first.addProperties( props ); setDirty( i ); } } } } const ShaderParameterProvider* RenderTechnique::getParametersProvider( Core::Utils::Index pass ) const { if ( hasConfiguration( pass ) ) { return m_passesParameters[pass].get(); } return nullptr; } void RenderTechnique::updateGL() { for ( auto p = Index( 0 ); p < m_numActivePass; ++p ) { if ( hasConfiguration( p ) && ( ( nullptr == m_activePasses[p].second ) || isDirty( p ) ) ) { m_activePasses[p].second = ShaderProgramManager::getInstance()->getShaderProgram( m_activePasses[p].first ); clearDirty( p ); } } for ( auto p = Index( 0 ); p < m_numActivePass; ++p ) { if ( m_passesParameters[p] ) { m_passesParameters[p]->updateGL(); } } } /////////////////////////////////////////////// Ra::Engine::RenderTechnique RenderTechnique::createDefaultRenderTechnique() { if ( RadiumDefaultRenderTechnique != nullptr ) { return *( RadiumDefaultRenderTechnique.get() ); } std::shared_ptr<Material> mat( new BlinnPhongMaterial( "DefaultGray" ) ); auto rt = new Ra::Engine::RenderTechnique; auto builder = EngineRenderTechniques::getDefaultTechnique( "BlinnPhong" ); if ( !builder.first ) { LOG( logERROR ) << "Unable to create the default technique : is the Engine initialized ? "; } builder.second( *rt, false ); rt->setParametersProvider( mat ); RadiumDefaultRenderTechnique.reset( rt ); return *( RadiumDefaultRenderTechnique.get() ); } /////////////////////////////////////////////// //// Radium defined technique /// /////////////////////////////////////////////// namespace EngineRenderTechniques { /// Map that stores each technique builder function static std::map<std::string, DefaultTechniqueBuilder> EngineTechniqueRegistry; /** register a new default builder for a technique * @return true if builder added, false else (e.g, a builder with the same name exists) */ bool registerDefaultTechnique( const std::string& name, DefaultTechniqueBuilder builder ) { auto result = EngineTechniqueRegistry.insert( {name, builder} ); return result.second; } /** remove a default builder * @return true if builder removed, false else (e.g, a builder with the same name does't exists) */ bool removeDefaultTechnique( const std::string& name ) { std::size_t removed = EngineTechniqueRegistry.erase( name ); return ( removed == 1 ); } /** * @param name name of the technique to construct * @return a pair containing the search result and, if true, the functor to call to build the * technique. */ std::pair<bool, DefaultTechniqueBuilder> getDefaultTechnique( const std::string& name ) { auto search = EngineTechniqueRegistry.find( name ); if ( search != EngineTechniqueRegistry.end() ) { return {true, search->second}; } auto result = std::make_pair( false, [name]( RenderTechnique&, bool ) -> void { LOG( logERROR ) << "Undefined default technique for " << name << " !"; } ); return result; } bool cleanup() { EngineTechniqueRegistry.clear(); return true; } } // namespace EngineRenderTechniques } // namespace Engine } // namespace Ra
34.486631
99
0.627849
hoshiryu
d1172b49c256ce5be60183c366fa7adf6977eaf4
479
hpp
C++
src/atlas/graphics/Earth.hpp
Groutcho/atlas
b69b7759be0361ffdcbbba64501e07feb79143be
[ "MIT" ]
5
2018-12-13T03:41:12.000Z
2020-08-27T04:45:11.000Z
src/atlas/graphics/Earth.hpp
Groutcho/atlas
b69b7759be0361ffdcbbba64501e07feb79143be
[ "MIT" ]
1
2020-09-08T07:26:59.000Z
2020-09-08T09:21:44.000Z
src/atlas/graphics/Earth.hpp
Groutcho/atlas
b69b7759be0361ffdcbbba64501e07feb79143be
[ "MIT" ]
5
2018-12-20T10:31:09.000Z
2021-09-07T07:38:49.000Z
//#ifndef ATLAS_GRAPHICS_EARTH_HPP //#define ATLAS_GRAPHICS_EARTH_HPP // //#include "AtlasGraphics.hpp" //#include "Node.hpp" //#include "SurfaceTile.hpp" // //namespace atlas //{ // namespace graphics // { // /** // * @brief The Earth node manages the rendering of the surface of the earth. // */ // class Earth : public Node // { // public: // Earth(); // ~Earth(); // }; // } //} // //#endif
19.958333
89
0.517745
Groutcho
d11818a9e60220e0a8c6ef0f7075d8f9b21b1c69
1,184
hpp
C++
IcarusDetector/Checkers/ArmorCheckerBase.hpp
RoboPioneers/ProjectIcarus
85328c0206d77617fe7fbb81b2ca0cda805de849
[ "MIT" ]
1
2021-10-05T03:43:57.000Z
2021-10-05T03:43:57.000Z
IcarusDetector/Checkers/ArmorCheckerBase.hpp
RoboPioneers/ProjectIcarus
85328c0206d77617fe7fbb81b2ca0cda805de849
[ "MIT" ]
null
null
null
IcarusDetector/Checkers/ArmorCheckerBase.hpp
RoboPioneers/ProjectIcarus
85328c0206d77617fe7fbb81b2ca0cda805de849
[ "MIT" ]
null
null
null
#pragma once #include "../Framework/CheckerBase.hpp" #include "../Components/PONElement.hpp" #include <cmath> namespace Icarus { /// Distance scenario based light bar checker base class. class ArmorCheckerBase : public CheckerBase<PONElement> { public: double MaxLeaningAngle {}; double MaxDeltaAngle {}; ArmorCheckerBase() { CheckerBase::PatternTags = {"Armor"}; } void LoadConfiguration() override { MaxLeaningAngle = Configurator->Get<double>("Armor/Base/MaxLeaningAngle").value_or(20); MaxDeltaAngle = Configurator->Get<double>("Armor/Base/MaxDeltaAngle").value_or(20); } protected: /// Check distance scenario. bool CheckScenario(PONElement *candidate) override { if (candidate->Feature.Angle < (180.0 - MaxLeaningAngle) && candidate->Feature.Angle > MaxLeaningAngle) return false; if (std::fabs(candidate->ContourA->Feature.Angle - candidate->ContourB->Feature.Angle) > MaxDeltaAngle) return false; return true; } }; }
30.358974
99
0.597973
RoboPioneers
d1182965d6ae73674b0acea284736b76c82b5135
9,867
cc
C++
test/assimp_test.cc
leonlynch/cortex
239ece88de004f35ef31ad3c57fb20b0b0d86bde
[ "MIT" ]
1
2017-11-26T08:37:04.000Z
2017-11-26T08:37:04.000Z
test/assimp_test.cc
leonlynch/cortex
239ece88de004f35ef31ad3c57fb20b0b0d86bde
[ "MIT" ]
null
null
null
test/assimp_test.cc
leonlynch/cortex
239ece88de004f35ef31ad3c57fb20b0b0d86bde
[ "MIT" ]
null
null
null
/** * @file assimp_test.cc * * Copyright (c) 2013 Leon Lynch * * This file is licensed under the terms of the MIT license. * See LICENSE file. */ #include <assimp/DefaultLogger.hpp> #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <iostream> #include <cstdio> static void print_node_recursive(const aiNode* node, unsigned int node_depth = 0) { for (unsigned int i = 0; i < node_depth; ++i) { std::printf("\t"); } std::printf("'%s': mNumMeshes=%u", node->mName.C_Str(), node->mNumMeshes); if (!node->mTransformation.IsIdentity()) { std::printf("; mTransformation=present"); } std::printf("\n"); for (unsigned int i = 0; i < node->mNumChildren; ++i) { print_node_recursive(node->mChildren[i], node_depth + 1); } } static void print_mesh(const struct aiMesh* mesh) { unsigned int mPrimitiveTypes; unsigned int numColors = 0; unsigned int numTextureCoords = 0; std::printf("'%s': ", mesh->mName.C_Str()); std::printf("mPrimitiveTypes="); mPrimitiveTypes = mesh->mPrimitiveTypes; for (unsigned int i = 0; i < 4 && mPrimitiveTypes; ++i) { if (mesh->mPrimitiveTypes & ((1 << i) - 1)) { std::printf(","); } if ((mesh->mPrimitiveTypes & (1 << i)) == aiPrimitiveType_POINT) { std::printf("POINT"); } if ((mesh->mPrimitiveTypes & (1 << i)) == aiPrimitiveType_LINE) { std::printf("LINE"); } if ((mesh->mPrimitiveTypes & (1 << i)) == aiPrimitiveType_TRIANGLE) { std::printf("TRIANGLE"); } if ((mesh->mPrimitiveTypes & (1 << i)) == aiPrimitiveType_POLYGON) { std::printf("POLYGON"); } mPrimitiveTypes &= ~(1 << i); } std::printf("; "); std::printf("mNumVertices=%u {%s%s%s}", mesh->mNumVertices, mesh->mNormals ? "mNormals" : "", mesh->mTangents ? " mTangents" : "", mesh->mBitangents ? " mBitangents" : "" ); for (std::size_t i = 0; i < sizeof(mesh->mColors) / sizeof(mesh->mColors[0]); ++i) { if (mesh->mColors[i]) ++numColors; } if (numColors) { std::printf("; mColors=%u", numColors); } for (std::size_t i = 0; i < sizeof(mesh->mTextureCoords) / sizeof(mesh->mTextureCoords[0]); ++i) { if (mesh->mTextureCoords[i]) ++numTextureCoords; } if (numTextureCoords) { std::printf("; mTextureCoords=%u", numTextureCoords); } std::printf("; mNumFaces=%u; mNumBones=%u", mesh->mNumFaces, mesh->mNumBones); std::printf("; mMaterialIndex=%u\n", mesh->mMaterialIndex); } template <typename T> static void print_material_property_array(const void* data, std::size_t length) { const T* value = reinterpret_cast<const T*>(data); std::size_t count = length / sizeof(T); std::printf("{ "); for (std::size_t i = 0; i < count; ++i) { if (i) std::printf(", "); std::cout << value[i]; } std::printf(" }\n"); } // #define ASSIMP_TEST_ITERATE_MATERIAL_PROPERTIES #ifdef ASSIMP_TEST_ITERATE_MATERIAL_PROPERTIES static void print_material(const struct aiMaterial* material) { aiReturn ret; aiString name; ret = material->Get(AI_MATKEY_NAME, name); if (ret == aiReturn_SUCCESS) { std::printf("'%s':\n", name.C_Str()); } else { std::printf("(none):\n"); } for (unsigned int i = 0; i < material->mNumProperties; ++i) { const struct aiMaterialProperty* property = material->mProperties[i]; std::printf("\t%s = ", property->mKey.C_Str()); if (property->mSemantic == aiTextureType_NONE) { switch (property->mType) { case aiPTI_Float: std::printf("[Float/%u] ", property->mDataLength); print_material_property_array<float>(property->mData, property->mDataLength); break; case aiPTI_Double: std::printf("[Double/%u] ", property->mDataLength); print_material_property_array<double>(property->mData, property->mDataLength); break; case aiPTI_String: { aiString s; ret = material->Get(property->mKey.C_Str(), property->mSemantic, property->mIndex, s); std::printf("[String] '%s'\n", s.C_Str()); break; } case aiPTI_Integer: std::printf("[Integer/%u] ", property->mDataLength); print_material_property_array<unsigned int>(property->mData, property->mDataLength); break; case aiPTI_Buffer: std::printf("[Buffer/%u]\n", property->mDataLength); break; default: std::printf("[Unknown/%u]\n", property->mDataLength); } } else { switch (property->mType) { case aiPTI_String: { aiString s; ret = material->Get(property->mKey.C_Str(), property->mSemantic, property->mIndex, s); std::printf("[Texture] '%s'\n", s.C_Str()); break; } case aiPTI_Integer: { std::printf("[Texture] "); print_material_property_array<unsigned int>(property->mData, property->mDataLength); break; } default: std::printf("[Texture/%u]\n", property->mDataLength); } } } } #else static void print_material(const struct aiMaterial* material) { aiReturn ret; aiString name; int twosided; enum aiShadingMode shading; enum aiBlendMode blend; float opacity; float shininess; float shininess_strength; aiColor3D diffuse; aiColor3D ambient; aiColor3D specular; ret = material->Get(AI_MATKEY_NAME, name); if (ret == aiReturn_SUCCESS) { std::printf("'%s':\n", name.C_Str()); } else { std::printf("'':\n"); } ret = material->Get(AI_MATKEY_TWOSIDED, twosided); if (ret == aiReturn_SUCCESS) { std::printf("\tTwo sided = %s\n", twosided ? "true" : "false"); } ret = material->Get(AI_MATKEY_SHADING_MODEL, shading); if (ret == aiReturn_SUCCESS) { std::printf("\tShading = %d\n", shading); } ret = material->Get(AI_MATKEY_BLEND_FUNC, blend); if (ret == aiReturn_SUCCESS) { std::printf("\tBlend = %d\n", blend); } ret = material->Get(AI_MATKEY_OPACITY, opacity); if (ret == aiReturn_SUCCESS) { std::printf("\tOpacity = %f\n", opacity); } ret = material->Get(AI_MATKEY_SHININESS, shininess); if (ret == aiReturn_SUCCESS) { std::printf("\tShininess = %f\n", shininess); } ret = material->Get(AI_MATKEY_SHININESS_STRENGTH, shininess_strength); if (ret == aiReturn_SUCCESS) { std::printf("\tShininess strength = %f\n", shininess_strength); } ret = material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse); if (ret == aiReturn_SUCCESS) { std::printf("\tDiffuse = { %f, %f, %f }\n", diffuse.r, diffuse.g, diffuse.b); } ret = material->Get(AI_MATKEY_COLOR_AMBIENT, ambient); if (ret == aiReturn_SUCCESS) { std::printf("\tAmbient = { %f, %f, %f }\n", ambient.r, ambient.g, ambient.b); } ret = material->Get(AI_MATKEY_COLOR_SPECULAR, specular); if (ret == aiReturn_SUCCESS) { std::printf("\tSpecular = { %f, %f, %f }\n", specular.r, specular.g, specular.b); } const aiTextureType texture_types[] = { aiTextureType_NONE, aiTextureType_DIFFUSE, aiTextureType_SPECULAR, aiTextureType_AMBIENT, aiTextureType_EMISSIVE, aiTextureType_HEIGHT, aiTextureType_NORMALS, aiTextureType_SHININESS, aiTextureType_OPACITY, aiTextureType_DISPLACEMENT, aiTextureType_LIGHTMAP, aiTextureType_REFLECTION, aiTextureType_BASE_COLOR, aiTextureType_NORMAL_CAMERA, aiTextureType_EMISSION_COLOR, aiTextureType_METALNESS, aiTextureType_DIFFUSE_ROUGHNESS, aiTextureType_AMBIENT_OCCLUSION, aiTextureType_UNKNOWN }; for (auto&& texture_type : texture_types) { ret = AI_SUCCESS; for (unsigned int idx = 0; ret == AI_SUCCESS; ++idx) { aiString filename; ret = material->Get(AI_MATKEY_TEXTURE(texture_type, idx), filename); if (ret == AI_SUCCESS) { std::printf("\tTexture(%u,%u) = '%s'\n", texture_type, idx, filename.C_Str()); continue; } int texture_idx; ret = material->Get(AI_MATKEY_TEXTURE(texture_type, idx), texture_idx); if (ret == AI_SUCCESS) { std::printf("\tTexture(%u,%u) = #%u\n", texture_type, idx, texture_idx); continue; } }; } } #endif static void print_texture(unsigned int idx, const struct aiTexture* texture) { if (texture->mHeight) { // uncompressed texture std::printf("\t[%u]: %ux%u, ARGB8888\n", idx, texture->mWidth, texture->mHeight); } else { // compressed texture std::printf("\t[%u]: %u bytes, %s\n", idx, texture->mWidth, texture->achFormatHint); } } static int import_scene(const char* filename) { Assimp::Importer importer; const aiScene* scene; scene = importer.ReadFile(filename, aiProcessPreset_TargetRealtime_MaxQuality // aiProcess_JoinIdenticalVertices | // aiProcess_Triangulate | // aiProcess_ValidateDataStructure | // aiProcess_RemoveRedundantMaterials | // aiProcess_SortByPType ); if (!scene) { Assimp::DefaultLogger::get()->error(importer.GetErrorString()); return -1; } std::printf("\n%s summary:\n" "\tmNumMeshes=%u\n" "\tmNumMaterials=%u\n" "\tmNumAnimations=%u\n" "\tmNumTextures=%u\n" "\tmNumLights=%u\n" "\tmNumCameras=%u\n", filename, scene->mNumMeshes, scene->mNumMaterials, scene->mNumAnimations, scene->mNumTextures, scene->mNumLights, scene->mNumCameras ); std::printf("\n%s nodes:\n", filename); print_node_recursive(scene->mRootNode); std::printf("\n%s meshes[%u]:\n", filename, scene->mNumMeshes); for (unsigned int i = 0; i < scene->mNumMeshes; ++i) { print_mesh(scene->mMeshes[i]); } std::printf("\n%s materials[%u]:\n", filename, scene->mNumMaterials); for (unsigned int i = 0; i < scene->mNumMaterials; ++i) { print_material(scene->mMaterials[i]); } std::printf("\n%s textures[%u]:\n", filename, scene->mNumTextures); for (unsigned int i = 0; i < scene->mNumTextures; ++i) { print_texture(i, scene->mTextures[i]); } return 0; } int main(int argc, char** argv) { int r; if (argc != 2) { std::fprintf(stderr, "No import file specified\n"); return 1; } Assimp::DefaultLogger::create(nullptr, Assimp::Logger::VERBOSE, aiDefaultLogStream_STDERR); r = import_scene(argv[1]); if (r) { std::fprintf(stderr, "Failed to import scene from '%s'\n", argv[1]); } Assimp::DefaultLogger::kill(); return r; }
26.595687
99
0.666869
leonlynch
d11a5b1a0844f875585961a98af58bfd3e57f57c
983
hpp
C++
app/dml/src/dml/dml_paras.hpp
alexrenz/bosen-2
c61ac4e892ba2f6e02bd4595632b15f9e53450e2
[ "BSD-3-Clause" ]
370
2015-06-30T09:46:17.000Z
2017-01-21T07:14:00.000Z
app/dml/src/dml/dml_paras.hpp
alexrenz/bosen-2
c61ac4e892ba2f6e02bd4595632b15f9e53450e2
[ "BSD-3-Clause" ]
3
2016-11-08T19:45:19.000Z
2016-11-11T13:21:19.000Z
app/dml/src/dml/dml_paras.hpp
alexrenz/bosen-2
c61ac4e892ba2f6e02bd4595632b15f9e53450e2
[ "BSD-3-Clause" ]
159
2015-07-03T05:58:31.000Z
2016-12-29T20:59:01.000Z
#ifndef APPS_DML_SRC_DML_DML_PARAS_H_ #define APPS_DML_SRC_DML_DML_PARAS_H_ struct DmlParas{ // original feature dimension int src_feat_dim; // target feature dimension int dst_feat_dim; // tradeoff parameter float lambda; // distance threshold float thre; // learning rate float learn_rate; int epoch; // number of total pts int num_total_pts; // number of similar pairs int num_simi_pairs; // num of dissimilar pairs int num_diff_pairs; // number of total evaluation pts int num_total_eval_pts; // size of mini batch int size_mb; // num iters to do evaluation int num_iters_evaluate; // num smps to evaluate int num_smps_evaluate; // uniform initialization range float unif_x; float unif_y; char data_file[512]; char simi_pair_file[512]; char diff_pair_file[512]; }; void LoadDmlParas(DmlParas * para, const char * file_dml_para); void PrintDmlParas(const DmlParas para); #endif // APPS_DML_SRC_DML_DML_PARAS_H_
22.340909
63
0.743642
alexrenz
d11a707cd6e98882ae3ce8c991b6c3f63662d5ad
1,953
cpp
C++
STL_C++/STL_String.cpp
rsghotra/AbdulBari
2d2845608840ddda6e5153ec91966110ca7e25f5
[ "Apache-2.0" ]
1
2020-12-02T09:21:52.000Z
2020-12-02T09:21:52.000Z
STL_C++/STL_String.cpp
rsghotra/AbdulBari
2d2845608840ddda6e5153ec91966110ca7e25f5
[ "Apache-2.0" ]
null
null
null
STL_C++/STL_String.cpp
rsghotra/AbdulBari
2d2845608840ddda6e5153ec91966110ca7e25f5
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { string s1{"happy"}; string s2{" birthday"}; string s3; cout << "s1 is \"" << s1 << "\"; s2 is \"" << s2 << "\"; s3 is \"" << s3 << '\"' << "\n\nThe results of comparing s2 and s1:" << boolalpha << "\n\nS2==S1 yields " << (s2 == s1) << "\n\nS2!=S1 yields " << (s2 != s1) << "\n\nS2>S1 yields " << (s2 > s1) << "\n\nS2<S1 yields " << (s2 < s1) << "\n\nS2>=S1 yields " << (s2 >= s1) << "\n\nS2<=S1 yields " << (s2 <= s1); //test string function emptu cout << "\n\nTesting s3.empty():\n"; if(s3.empty()) { cout << "s3 is empty; assigning s1 to s3;\n"; s3 = s1; cout << "s3 is \"" << s3 << "\""; } //string concatenation cout << "\n\ns1+=s2 yields s1 = "; s1+=s2; cout << s1; //test conatenation with c-string // test string concatenation with a C string cout << "\n\ns1 += \" to you\" yields\n"; s1 += " to you"; cout << "s1 = " << s1; // test string concatenation with a C++14 string-object literal cout << "\n\ns1 += \", have a great day!\" yields\n"; s1 += ", have a great day!"s; cout << "s1 = " << s1; //test substr "to end of string" option cout << "The substring of s1 starting at\n" << "location 15,s1.substr(15), is:\n" << s1.substr(15) << endl; string s4{s1}; cout << "\ns4 = " << s4 << "\n\n"; cout << "assigning s4 to s4\n"; s4 = s4; cout << "s4 = " << s4; // test using overloaded subscript operator to crate lvalue s1[0] = 'H'; s1[6] = 'B'; cout << "\n\ns1 after s1[0] = 'H' and s1[6] = 'B' is:\n" << s1 << "\n\n"; try { cout << "Attempt to assign 'd' to s1.at(100) yields:\n"; s1.at(100) = 'd'; } catch(out_of_range& ex) { cout << "An exception occurred: " << ex.what() << endl; } }
27.507042
71
0.47363
rsghotra
d11f94c143954afbbea823f954593499d5a789a8
2,938
cpp
C++
AfxHookGoldSrc/Store.cpp
markusforss/advancedfx
0c427594e23c30b88081139c6b80f2688b7c211f
[ "MIT" ]
339
2018-01-09T13:12:38.000Z
2022-03-22T21:25:59.000Z
AfxHookGoldSrc/Store.cpp
markusforss/advancedfx
0c427594e23c30b88081139c6b80f2688b7c211f
[ "MIT" ]
474
2018-01-01T18:58:41.000Z
2022-03-27T11:09:44.000Z
AfxHookGoldSrc/Store.cpp
markusforss/advancedfx
0c427594e23c30b88081139c6b80f2688b7c211f
[ "MIT" ]
77
2018-01-24T11:47:04.000Z
2022-03-30T12:25:59.000Z
#include "stdafx.h" #include "Store.h" #include <stdexcept> using namespace std; //////////////////////////////////////////////////////////////////////////////// class FrequentStoreItem : public IStoreItem { public: FrequentStoreItem * NextFree; FrequentStoreItem(FrequentStoreManager * manager); ~FrequentStoreItem(); void Aquire(); virtual StoreValue GetValue(); virtual void Release(); private: bool m_Aquired; FrequentStoreManager * m_Manager; StoreValue m_Value; void Delist(); void Enlist(); }; class FrequentStoreManager { public: FrequentStoreItem * FreeItem; FrequentStoreManager(IStoreFactory * factory); ~FrequentStoreManager(); IStoreItem * Aquire(void); IStoreFactory * GetFactory(); void Pack(void); private: IStoreFactory * m_Factory; }; // FrequentStore ///////////////////////////////////////////////////////// FrequentStore::FrequentStore(IStoreFactory * factory) { m_Manager = new FrequentStoreManager(factory); } FrequentStore::~FrequentStore() { delete m_Manager; } IStoreItem * FrequentStore::Aquire(void) { return m_Manager->Aquire(); } void FrequentStore::Pack(void) { m_Manager->Pack(); } // FrequentStoreManager ////////////////////////////////////////////////// FrequentStoreManager::FrequentStoreManager(IStoreFactory * factory) { FreeItem = 0; m_Factory = factory; } FrequentStoreManager::~FrequentStoreManager() { while(FreeItem) delete FreeItem; } IStoreItem * FrequentStoreManager::Aquire(void) { FrequentStoreItem * item = FreeItem; if(!item) item = new FrequentStoreItem(this); item->Aquire(); return item; } IStoreFactory * FrequentStoreManager::GetFactory() { return m_Factory; } void FrequentStoreManager::Pack(void) { while(FreeItem) delete FreeItem; } // FrequentStoreItem ///////////////////////////////////////////////////// FrequentStoreItem::FrequentStoreItem(FrequentStoreManager * manager) { NextFree = 0; m_Aquired = false; m_Manager = manager; m_Value = manager->GetFactory()->ConstructValue(); Enlist(); } FrequentStoreItem::~FrequentStoreItem() { //if(m_Aquired) // throw logic_error(""); Delist(); m_Manager->GetFactory()->DestructValue(m_Value); } void FrequentStoreItem::Aquire() { if(m_Aquired) throw logic_error(""); Delist(); m_Aquired = true; } void FrequentStoreItem::Delist() { m_Manager->FreeItem = NextFree; NextFree = 0; } void FrequentStoreItem::Enlist() { NextFree = m_Manager->FreeItem; m_Manager->FreeItem = this; } StoreValue FrequentStoreItem::GetValue() { return m_Value; } void FrequentStoreItem::Release() { if(!m_Aquired) throw logic_error(""); m_Aquired = false; Enlist(); } // Store /////////////////////////////////////////////////////////////////////// Store::~Store() { }
16.505618
81
0.607216
markusforss
d1261471d3344588b1edeee41b378ac3b103d969
1,522
cpp
C++
findLargestWordInDictionary.cpp
harshallgarg/CPP
4d15c5e5d426bb00d192368d21924ec9f017445f
[ "MIT" ]
2
2020-08-09T02:09:50.000Z
2020-08-09T07:07:47.000Z
findLargestWordInDictionary.cpp
harshallgarg/CPP
4d15c5e5d426bb00d192368d21924ec9f017445f
[ "MIT" ]
null
null
null
findLargestWordInDictionary.cpp
harshallgarg/CPP
4d15c5e5d426bb00d192368d21924ec9f017445f
[ "MIT" ]
4
2020-05-25T10:24:14.000Z
2021-05-03T07:52:35.000Z
//leetcode solution class Solution { public: bool isSubsequence(string word,string s) { int m=word.length(),n=s.length(); int i,j; for(i=0,j=0;i<m&&j<n;j++) if(word.at(i)==s.at(j)) i++; return i==m; } string findLongestWord(string s, vector<string>& d) { string result=""; for(string word:d) { if(result.length()<=word.length()&&isSubsequence(word,s)&&(result>word||result.length()<word.length())) { result=word; } } return result; } }; //geeksforgeeks solution #include <iostream> #include <string> #include <vector> using namespace std; bool isSubsequence(string word,string s) { int m=word.length(),n=s.length(); int i,j; for(i=0,j=0;i<m&&j<n;j++) if(word.at(i)==s.at(j)) i++; return i==m; } string findLongestWord(string s, vector<string>& d) { string result; int length=0; for(string word:d) { if(length<word.length()&&isSubsequence(word,s)) { result=word; length=word.length(); } } return result; } int main() { int cases; cin>>cases; while(cases--) { int n; cin>>n; vector<string> dict; while(n--) { string x; cin>>x; dict.push_back(x); } string s; cin>>s; cout<<findLongestWord(s,dict)<<endl; } }
19.766234
115
0.489488
harshallgarg
d1274674e98c07b167b67cc3c6fda955077c5ef6
8,592
cpp
C++
src/libraries/criterion/cpu/ForceAlignmentCriterion.cpp
lithathampan/wav2letter
8abf8431d99da147cc4aefc289ad33626e13de6f
[ "BSD-3-Clause" ]
null
null
null
src/libraries/criterion/cpu/ForceAlignmentCriterion.cpp
lithathampan/wav2letter
8abf8431d99da147cc4aefc289ad33626e13de6f
[ "BSD-3-Clause" ]
null
null
null
src/libraries/criterion/cpu/ForceAlignmentCriterion.cpp
lithathampan/wav2letter
8abf8431d99da147cc4aefc289ad33626e13de6f
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "libraries/criterion/cpu/ForceAlignmentCriterion.h" #include <algorithm> #include <cmath> #include "libraries/common/Utils.h" #include "libraries/common/Workspace.h" #include "libraries/criterion/cpu/CriterionUtils.h" namespace { template <class Float> struct WorkspacePtrs { WorkspacePtrs(void* workspace, int B, int T, int N, int L) { w2l::Workspace<> ws(workspace); ws.request(&scale, B); ws.request(&alpha, B, T, L); ws.request(&alphaGrad, B, T, L); ws.request(&transBatchGrad, B, N, N); ws.request(&transBuf1, B, L); ws.request(&transBuf2, B, L); ws.request(&transBufGrad1, B, L); ws.request(&transBufGrad2, B, L); requiredSize = ws.requiredSize(); } Float* scale; double* alpha; double* alphaGrad; Float* transBatchGrad; Float* transBuf1; Float* transBuf2; Float* transBufGrad1; Float* transBufGrad2; size_t requiredSize; }; } // namespace namespace w2l { namespace cpu { template <class Float> size_t ForceAlignmentCriterion<Float>::getWorkspaceSize(int B, int T, int N, int L) { WorkspacePtrs<Float> dummy(nullptr, B, T, N, L); return dummy.requiredSize; } template <class Float> void ForceAlignmentCriterion<Float>::forward( int B, int T, int N, int _L, CriterionScaleMode scaleMode, const Float* _input, const int* _target, const int* targetSize, const Float* trans, Float* loss, void* workspace) { WorkspacePtrs<Float> ws(workspace, B, T, N, _L); CriterionUtils<Float>::computeScale(B, T, N, scaleMode, targetSize, ws.scale); #pragma omp parallel for num_threads(B) for (int b = 0; b < B; ++b) { auto* alpha = &ws.alpha[b * T * _L]; auto* input = &_input[b * T * N]; auto* target = &_target[b * _L]; auto* transBuf1 = &ws.transBuf1[b * _L]; auto* transBuf2 = &ws.transBuf2[b * _L]; int L = targetSize[b]; alpha[0] = input[target[0]]; for (int i = 0; i < L; ++i) { transBuf1[i] = trans[target[i] * N + target[i]]; transBuf2[i] = i > 0 ? trans[target[i] * N + target[i - 1]] : 0; } for (int t = 1; t < T; ++t) { auto* inputCur = &input[t * N]; auto* alphaPrev = &alpha[(t - 1) * L]; auto* alphaCur = &alpha[t * L]; int high = t < L ? t : L; int low = T - t < L ? L - (T - t) : 1; if (T - t >= L) { alphaCur[0] = alphaPrev[0] + transBuf1[0] + inputCur[target[0]]; } if (t < L) { alphaCur[high] = alphaPrev[high - 1] + transBuf2[high] + inputCur[target[high]]; } for (int i = low; i < high; ++i) { double s1 = alphaPrev[i] + transBuf1[i]; double s2 = alphaPrev[i - 1] + transBuf2[i]; // lse = logSumExp(s1, s2) double lse = s1 < s2 ? s2 + log1p(exp(s1 - s2)) : s1 + log1p(exp(s2 - s1)); alphaCur[i] = lse + inputCur[target[i]]; } } loss[b] = alpha[T * L - 1] * ws.scale[b]; } } template <class Float> void ForceAlignmentCriterion<Float>::backward( int B, int T, int N, int _L, const int* _target, const int* targetSize, const Float* grad, Float* _inputGrad, Float* transGrad, void* workspace) { WorkspacePtrs<Float> ws(workspace, B, T, N, _L); setZero(_inputGrad, B * T * N); setZero(transGrad, N * N); setZero(ws.alphaGrad, B * T * _L); setZero(ws.transBatchGrad, B * N * N); setZero(ws.transBufGrad1, B * _L); setZero(ws.transBufGrad2, B * _L); #pragma omp parallel for num_threads(B) for (int b = 0; b < B; ++b) { auto* alpha = &ws.alpha[b * T * _L]; auto* alphaGrad = &ws.alphaGrad[b * T * _L]; auto* inputGrad = &_inputGrad[b * T * N]; auto* target = &_target[b * _L]; auto* transBatchGrad = &ws.transBatchGrad[b * N * N]; auto* transBuf1 = &ws.transBuf1[b * _L]; auto* transBuf2 = &ws.transBuf2[b * _L]; auto* transBufGrad1 = &ws.transBufGrad1[b * _L]; auto* transBufGrad2 = &ws.transBufGrad2[b * _L]; int L = targetSize[b]; alphaGrad[T * L - 1] = 1; for (int t = T - 1; t > 0; --t) { auto* inputCurGrad = &inputGrad[t * N]; auto* alphaPrev = &alpha[(t - 1) * L]; auto* alphaCurGrad = &alphaGrad[t * L]; auto* alphaPrevGrad = &alphaGrad[(t - 1) * L]; int high = t < L ? t : L; int low = T - t < L ? L - (T - t) : 1; int high1 = t < L ? t + 1 : L; int low1 = T - t < L ? L - (T - t) : 0; for (int i = low1; i < high1; ++i) { inputCurGrad[target[i]] += alphaCurGrad[i]; } if (T - t >= L) { alphaPrevGrad[0] += alphaCurGrad[0]; transBufGrad1[0] += alphaCurGrad[0]; } if (t < L) { alphaPrevGrad[high - 1] += alphaCurGrad[high]; transBufGrad2[high] += alphaCurGrad[high]; } for (int i = low; i < high; ++i) { double s1 = alphaPrev[i] + transBuf1[i]; double s2 = alphaPrev[i - 1] + transBuf2[i]; // d1, d2 = dLogSumExp(s1, s2) double d1, d2; if (s1 < s2) { d2 = 1 / (1 + exp(s1 - s2)); d1 = 1 - d2; } else { d1 = 1 / (1 + exp(s2 - s1)); d2 = 1 - d1; } alphaPrevGrad[i] += d1 * alphaCurGrad[i]; alphaPrevGrad[i - 1] += d2 * alphaCurGrad[i]; transBufGrad1[i] += d1 * alphaCurGrad[i]; transBufGrad2[i] += d2 * alphaCurGrad[i]; } } inputGrad[target[0]] += alphaGrad[0]; auto gradScale = grad[b] * ws.scale[b]; for (int i = 0; i < T * N; ++i) { inputGrad[i] *= gradScale; } for (int i = 0; i < L; ++i) { transBatchGrad[target[i] * N + target[i]] += transBufGrad1[i]; if (i > 0) { transBatchGrad[target[i] * N + target[i - 1]] += transBufGrad2[i]; } } } for (int b = 0; b < B; ++b) { auto transBatchGrad = ws.transBatchGrad + b * N * N; auto gradScale = grad[b] * ws.scale[b]; for (int i = 0; i < N * N; ++i) { transGrad[i] += gradScale * transBatchGrad[i]; } } } template <class Float> void ForceAlignmentCriterion<Float>::viterbi( int B, int T, int N, int _L, const Float* _input, const int* _target, const int* targetSize, const Float* trans, int* bestPaths, void* workspace) { WorkspacePtrs<Float> ws(workspace, B, T, N, _L); #pragma omp parallel for num_threads(B) for (int b = 0; b < B; ++b) { double* alpha = &ws.alpha[b * T * _L]; const Float* input = &_input[b * T * N]; const int* target = &_target[b * _L]; Float* transBuf1 = &ws.transBuf1[b * _L]; Float* transBuf2 = &ws.transBuf2[b * _L]; int L = targetSize[b]; alpha[0] = input[target[0]]; for (int i = 0; i < L; ++i) { transBuf1[i] = trans[target[i] * N + target[i]]; transBuf2[i] = i > 0 ? trans[target[i] * N + target[i - 1]] : 0; } for (int t = 1; t < T; ++t) { const Float* inputCur = &input[t * N]; double* alphaPrev = &alpha[(t - 1) * L]; double* alphaCur = &alpha[t * L]; int high = t < L ? t : L; int low = T - t < L ? L - (T - t) : 1; // Handle edge cases. // If (T - t >= L), then we can conceivably still be at the initial blank if (T - t >= L) { alphaCur[0] = alphaPrev[0] + transBuf1[0] + inputCur[target[0]]; } // If (t < L), then the highest position can only be be computed // by transitioning. (We couldn't have been at position `high` // at the previous timestep). if (t < L) { alphaCur[high] = alphaPrev[high - 1] + transBuf2[high] + inputCur[target[high]]; } for (int i = low; i < high; ++i) { double s1 = alphaPrev[i] + transBuf1[i]; double s2 = alphaPrev[i - 1] + transBuf2[i]; alphaCur[i] = inputCur[target[i]] + fmax(s1, s2); } } auto ltrIdx = L - 1; int* bestPath = bestPaths + b * T; for (auto t = T - 1; t > 0; t--) { bestPath[t] = target[ltrIdx]; auto* alphaPrev = &alpha[(t - 1) * L]; if (ltrIdx > 0) { double s1 = alphaPrev[ltrIdx] + transBuf1[ltrIdx]; double s2 = alphaPrev[ltrIdx - 1] + transBuf2[ltrIdx]; if (s2 > s1) { ltrIdx--; } } } bestPath[0] = target[ltrIdx]; } } template struct ForceAlignmentCriterion<float>; template struct ForceAlignmentCriterion<double>; } // namespace cpu } // namespace w2l
28.170492
80
0.551443
lithathampan
d12930a94255a4ec9b44c1f3f3a5906d763baae9
1,766
cpp
C++
drazy/sieve_phi.cpp
gbuenoandrade/Manual-da-Sarrada
dc44666b8f926428164447997b5ea8363ebd6fda
[ "MIT" ]
null
null
null
drazy/sieve_phi.cpp
gbuenoandrade/Manual-da-Sarrada
dc44666b8f926428164447997b5ea8363ebd6fda
[ "MIT" ]
null
null
null
drazy/sieve_phi.cpp
gbuenoandrade/Manual-da-Sarrada
dc44666b8f926428164447997b5ea8363ebd6fda
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define DEBUG_ON 1 #define INF 0x3f3f3f3f #define NSYNC ios::sync_with_stdio(false); #define FOR(i,a,b) for(int i=a; i<(b); ++i) #define FOR0(i,b) for(int i=0; i<(b); ++i) #define TRAV(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it) #define RTRAV(it,c) for(__typeof((c).rbegin()) it=(c).rbegin(); it!=(c).rend(); ++it) #define DBG(x) if(DEBUG_ON) cout << #x << " == " << x << endl #define DBGP(x) if(DEBUG_ON) cout << "(" << (x).first << ", " << (x).second << ")" << endl #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define R(x) scanf(" %d",&(x)) #define RR(x,y) scanf(" %d %d",&(x), &(y)) #define RRR(x,y,z) scanf(" %d %d %d",&(x), &(y),&(z)) #define CLR(v) memset(v, 0, sizeof(v)) #define SET(v) memset(v, -1, sizeof(v)) typedef long long ll; typedef int int_type; typedef pair<int_type, int_type> pii; typedef vector<int_type> vi; typedef vector<vi> vii; const int MAXN = 10000010; int pr[MAXN]; int divisor[MAXN]; int phi[MAXN]; void sieve(int n) { FOR0(i,n+1) pr[i] = true; pr[0] = pr[1] = false; for(int i=2; i*i<=n; ++i) { if(!pr[i]) continue; int k = i*i; while(k<=n) { divisor[k] = i; pr[k] = false; k += i; } } } void calc_phi(int n) { FOR(i,1,n+1) phi[i] = i; FOR(i,2,n+1) if(pr[i]) { for(int j=i; j<=n; j+=i) { phi[j] -= phi[j]/i; } } } inline int get_div(int n) { if(pr[n]) return n; return divisor[n]; } int factorize(int v[], int n) { if(n<=1) return 0; int sz=0; while(n>1) { int p = get_div(n); v[sz++] = p; n/=p; } return sz; } int main() { sieve(1000); calc_phi(100); DBG(phi[80]); DBG(phi[77]); DBG(phi[50]); // DBG(phi(80)); // FOR(i,1,11) cout << "phi(" << i << ") = " << phi[i] << endl; return 0; }
21.277108
90
0.556059
gbuenoandrade
d12954839358b9d5ed89bb220b0da36a5a437e1d
8,991
cpp
C++
MasterControl/screensharing.cpp
CrankZ/ScreenSharing-FileTransfer-in-LAN
a6959e2c9c0ca725cf115d43509250d210bf0f17
[ "MIT" ]
87
2018-11-12T14:49:27.000Z
2022-03-13T06:42:28.000Z
MasterControl/screensharing.cpp
55gY/ScreenSharing-FileTransfer-in-LAN
4b034b70f3e42f4a66eaf8aae1ebc13ca7886e3c
[ "MIT" ]
3
2018-11-20T06:20:52.000Z
2019-06-07T17:20:07.000Z
MasterControl/screensharing.cpp
55gY/ScreenSharing-FileTransfer-in-LAN
4b034b70f3e42f4a66eaf8aae1ebc13ca7886e3c
[ "MIT" ]
54
2018-11-13T02:11:08.000Z
2021-12-30T14:30:59.000Z
#include "screensharing.h" ScreenSharing::ScreenSharing(int num=1) { quality = 60; mutex = new QMutex; mutex->lock(); flag = 0; lock = true; readSettings(); sender = new Sender(); QScreen *src = QApplication::primaryScreen(); QPixmap firstPixmap1 = src->grabWindow(QApplication::desktop()->winId()); img1 = firstPixmap1.toImage(); } ScreenSharing::~ScreenSharing() { } void ScreenSharing::readSettings() { QString readName = "settings.ini"; if(readName.isEmpty()) { //็ฉบๅญ—็ฌฆไธฒไธๅค„็†๏ผŒ่ฟ”ๅ›ž qDebug() << "ๆ–‡ไปถๅไธ่ƒฝไธบ็ฉบ๏ผ"; return; } else { //ๅฎšไน‰ๆ–‡ไปถๅฏน่ฑก QFile fileIn(readName); if(!fileIn.open(QIODevice::ReadOnly)) { // qDebug() << "ๆ–‡ไปถไธๅญ˜ๅœจ๏ผ"; return; //ไธๅค„็†ๆ–‡ไปถ } //่ฏปๅ–ๅนถ่งฃๆžๆ–‡ไปถ while(!fileIn.atEnd()) { //่ฏปๅ–ไธ€่กŒ QByteArray ba = fileIn.readAll(); QString Settings = QString::fromUtf8(ba); if(Settings.isEmpty()) { qDebug() << "ๆ–‡ไปถไธบ็ฉบ๏ผŒไธ่ฏปๅ–"; } else { QStringList SettingsList = Settings.split("quality:"); QStringList temp = SettingsList[1].split("\n"); QString strQuality = temp[0]; if(strQuality.toInt() > 100) { quality = 100; } else if (strQuality.toInt() <= 0) { quality = 1; } else { quality = strQuality.toInt(); } qDebug() << "quality:" << quality; } } } } /** * ๅ›พ็‰‡ๅทฎๅผ‚ๅฏนๆฏ” * ๅฏนๆฏ”ไธคๅผ ๅ›พ็‰‡็š„ๆ‰€ๆœ‰ๅƒ็ด ็‚นx * @todo ๅ…ณไบŽไธคไธชๅƒ็ด ็‚นไน‹้—ด็š„่ท็ฆป้—ฎ้ข˜๏ผŒๅบ”่ฏฅ่ฟ˜ๆœ‰ไผ˜ๅŒ–็ฉบ้—ด */ bool ScreenSharing::compareImg(QImage img1,QImage img2) { int w = img1.width(); int h = img1.height(); // ไธคไธชๅƒ็ด ็‚นไน‹้—ด็š„่ท็ฆป int distance = 30; if(!img2.isNull() && !img1.isNull()) { for(int x = 0;x < w;x += distance) { for(int y = 0;y < h;y += distance) { QRgb *rgb1 = (QRgb*)img1.pixel(x,y); QRgb *rgb2 = (QRgb*)img2.pixel(x,y); // ๅฆ‚ๆžœไธคๅผ ๅ›พ็‰‡๏ผŒๆœ‰ไธ€ไธชๅƒ็ด ็‚นไธไธ€ๆ ท๏ผŒๅฐฑ่ฏดๆ˜Ž่ฟ™ไธคๅผ ๅ›พ็‰‡่‚ฏๅฎšไธไธ€ๆ ท // ๅฆ‚ๆžœไธคๅผ ๅ›พ็‰‡๏ผŒๆœ‰ไธ€ไธชๅƒ็ด ็‚นไธ€ๆ ท๏ผŒไธไธ€ๅฎš่ฏดๆ˜Ž่ฟ™ไธคไธชๅ›พ็‰‡็›ธๅŒ if(rgb1 != rgb2) { qDebug() << "ไธไธ€ๆ ท"; return false; } } } } // ๅชๆœ‰็ญ‰ไธคๅผ ๅ›พ็‰‡๏ผŒๅฏนๆฏ”ๅฎŒ๏ผŒๆ‰€ๆœ‰ๅƒ็ด ็‚น้ƒฝๆฒกๆœ‰ไธ็›ธๅŒๆ—ถ๏ผŒๆ‰็ฎ—่ฟ™ไธคๅผ ๅ›พ็‰‡ไธ€ๆ ท // qDebug() << "ไธ€ๆ ท"; return true; } void ScreenSharing::run() { while (1) { if (0 == flag) mutex->lock(); if (2 == flag) break; CURSORINFO cursorInfo; cursorInfo.cbSize = sizeof(cursorInfo); GetCursorInfo(&cursorInfo); // ไธ‹้ขๆ˜ฏๅ„็งๅ…‰ๆ ‡็š„ไฟกๆฏ HCURSOR APPSTARTING = LoadCursor(NULL, IDC_APPSTARTING); HCURSOR ARROW = LoadCursor(NULL, IDC_ARROW); HCURSOR CROSS = LoadCursor(NULL, IDC_CROSS ); HCURSOR HAND = LoadCursor(NULL, IDC_HAND ); HCURSOR HELP = LoadCursor(NULL, IDC_HELP ); HCURSOR IBEAM = LoadCursor(NULL, IDC_IBEAM ); HCURSOR ICON = LoadCursor(NULL, IDC_ICON ); HCURSOR NO = LoadCursor(NULL, IDC_NO ); HCURSOR SIZE = LoadCursor(NULL, IDC_SIZE ); HCURSOR SIZEALL = LoadCursor(NULL, IDC_SIZEALL); HCURSOR SIZENESW = LoadCursor(NULL, IDC_SIZENESW); HCURSOR SIZENS = LoadCursor(NULL, IDC_SIZENS); HCURSOR SIZENWSE = LoadCursor(NULL, IDC_SIZENWSE); HCURSOR SIZEWE = LoadCursor(NULL, IDC_SIZEWE); HCURSOR UPARROW = LoadCursor(NULL, IDC_UPARROW); HCURSOR WAIT = LoadCursor(NULL, IDC_WAIT); HCURSOR currentCursorType = cursorInfo.hCursor; if(currentCursorType == IBEAM) { cursorType = "IBEAM"; } else { //ๅ…ถไป–ๆ‰€ๆœ‰็š„้ƒฝ็”จ่ฟ™ไธชๆฅๆผ”็คบ cursorType = "ELSE"; } QPixmap tempPixmap1; QScreen *src = QApplication::primaryScreen(); tempPixmap1 = src->grabWindow(QApplication::desktop()->winId()); // QScreen *src = QApplication::screens().last(); // tempPixmap1 = src->grabWindow(0, src->geometry().x(), src->geometry().y(), src->size().width(), src->size().height()); QImage img2 = tempPixmap1.toImage(); // ๅฆ‚ๆžœไธไธ€ๆ ท๏ผŒๅˆ™ๅ‘้€ // ๅทฎๅผ‚ๆฏ”่พƒ if(!compareImg(img1, img2) || firstScreen) { // ๅˆšๅผ€ๅง‹็š„ๆ—ถๅ€™๏ผŒไธ็ฎกๆœ‰ๆฒกๆœ‰ๅ˜ๅŒ–๏ผŒ้ƒฝ่ฆๅ‘ไธ€ๅธงใ€‚ firstScreen = false; // matrix.rotate(90); // QPixmap tempPixmap = pixmap.transformed(matrix); QBuffer buffer; tempPixmap1.save(&buffer,"jpg",quality); //ไธๅˆ†ๅŒ… // udp->writeDatagram(buffer.data().data(), buffer.data().size(), // QHostAddress(ui->lineEditIP->text()), ui->lineEditPort->text().toInt()); //ๅˆ†ๅŒ…ๅผ€ๅง‹+++++++++++++++++++++++++++ // ๅฟ…้กปๅˆ†ๅŒ…๏ผŒๅ› ไธบUDPๅฏนไผ ่พ“ๅคงๅฐๆœ‰้™ๅˆถ๏ผŒไธ่ƒฝ็›ดๆŽฅไผ ่พ“ๆ•ดไธชๆ–‡ไปถ int dataLength=buffer.data().size(); unsigned char *dataBuffer=(unsigned char *)buffer.data().data(); buffer.close(); int packetNum = 0; int lastPaketSize = 0; packetNum = dataLength / UDP_MAX_SIZE; lastPaketSize = dataLength % UDP_MAX_SIZE; int currentPacketIndex = 0; if (lastPaketSize != 0) { packetNum = packetNum + 1; } PackageHeader packageHead; packageHead.uTransPackageHdrSize = sizeof(packageHead); packageHead.uDataSize = dataLength; packageHead.uDataPackageNum = packetNum; unsigned char frameBuffer[1024]; memset(frameBuffer,0,1024); QUdpSocket *udp = new QUdpSocket; while (currentPacketIndex < packetNum) { int udpMaxSizeTemp = UDP_MAX_SIZE; if (currentPacketIndex >= (packetNum-1)) { udpMaxSizeTemp = dataLength-currentPacketIndex*UDP_MAX_SIZE; } packageHead.uTransPackageSize = sizeof(PackageHeader)+ udpMaxSizeTemp; packageHead.uDataPackageCurrIndex = currentPacketIndex+1; packageHead.uDataPackageOffset = currentPacketIndex*UDP_MAX_SIZE; memcpy(frameBuffer, &packageHead, sizeof(PackageHeader)); memcpy(frameBuffer+sizeof(PackageHeader), dataBuffer+packageHead.uDataPackageOffset, udpMaxSizeTemp); QByteArray byteArray = QByteArray((const char*)frameBuffer, packageHead.uTransPackageSize); ////////// QByteArray bytes; //ๅญ—่Š‚ๆ•ฐ็ป„ //QDataStream็ฑปๆ˜ฏๅฐ†ๅบๅˆ—ๅŒ–็š„ไบŒ่ฟ›ๅˆถๆ•ฐๆฎ้€ๅˆฐio่ฎพๅค‡๏ผŒๅ› ไธบๅ…ถๅฑžๆ€งไธบๅชๅ†™ QDataStream out(&bytes, QIODevice::WriteOnly);//outไธบๅพ…ๅ‘้€ int msgType = CM_tScreen1; out << msgType << byteArray; // out << getCurrentCursorPos(); //////////// // ๅŽ‹็ผฉlevel0-9๏ผŒ้ป˜่ฎคไธบ-1๏ผŒๆˆ‘ไนŸไธ็Ÿฅ้“-1ๅ•ฅๆ„ๆ€ QByteArray compressedBytes = qCompress(bytes); // ่ฟ”ๅ›žๅ‘้€ๆˆๅŠŸ็š„bytesๅคงๅฐ int sentSuccessfullyBytesSize = udp->writeDatagram( compressedBytes.data(), compressedBytes.size(), QHostAddress::Broadcast, PORT); // ่ฟ™ไธชๅ…ณ้—ญๅฟ…้กปๆœ‰๏ผŒๅฆๅˆ™ไผ ่พ“ไผšๅ‡บ็Žฐ้—ฎ้ข˜ udp->close(); // ๅฆ‚ๆžœๅ‘้€ๆˆๅŠŸ็š„bytesๅคงๅฐไธ็ญ‰ไบŽๅŽ‹็ผฉๅŽ็š„ๅคงๅฐ๏ผŒ่ฏดๆ˜Žๅ‘้€ๅคฑ่ดฅ if(sentSuccessfullyBytesSize != compressedBytes.size()) { qDebug()<<"Failed to send image"; } currentPacketIndex++; } //ๅˆ†ๅŒ…็ป“ๆŸ+++++++++++++++++++++++++++ } img1 = img2; sendCursorInfo(); } sender->sendCommand(CM_tOpenScreen); } void ScreenSharing::sendCursorInfo() { sender->sendCursorInfo(CM_tCursorPos, getCurrentScreenSize(), cursorType, getCurrentCursorPos()); } /** * ่Žทๅ–ๅฝ“ๅ‰ๅฑๅน•ๅˆ†่พจ็އ */ QSize ScreenSharing::getCurrentScreenSize() { QDesktopWidget *desktop = QApplication::desktop(); QRect screen = desktop->screenGeometry(); int screenWidth = screen.width(); int screenHeight = screen.height(); QSize currentScreenSize; currentScreenSize.setWidth(screenWidth); currentScreenSize.setHeight(screenHeight); return currentScreenSize; } /** * ่Žทๅพ—ๅฝ“ๅ‰้ผ ๆ ‡ๅœจๆ•ดไธชๅฑๅน•ไธญ็š„ๅๆ ‡ */ QPoint ScreenSharing::getCurrentCursorPos() { QCoreApplication::processEvents(); QPoint globalCursorPos = QCursor::pos(); int mouseScreen = QApplication::desktop()->screenNumber(globalCursorPos); QRect mouseScreenGeometry = QApplication::desktop()->screen(mouseScreen)->geometry(); QPoint currentCursorPos = globalCursorPos - mouseScreenGeometry.topLeft(); return currentCursorPos; } void ScreenSharing::pause() { flag = 0; } void ScreenSharing::goOn() { readSettings(); flag = 1; mutex->unlock(); } void ScreenSharing::down() { flag = 2; mutex->unlock(); }
32.225806
148
0.542987
CrankZ
d12db1b8334448197c74b2e31a0fef8b48169f77
3,297
cpp
C++
src/Server.cpp
sempr-tk/sempr_ros
55f12bddc2d0d461d9fb0799a85d630e07012c4b
[ "BSD-3-Clause" ]
null
null
null
src/Server.cpp
sempr-tk/sempr_ros
55f12bddc2d0d461d9fb0799a85d630e07012c4b
[ "BSD-3-Clause" ]
null
null
null
src/Server.cpp
sempr-tk/sempr_ros
55f12bddc2d0d461d9fb0799a85d630e07012c4b
[ "BSD-3-Clause" ]
null
null
null
#include <sempr/nodes/ECNodeBuilder.hpp> #include <sempr/component/TextComponent.hpp> #include <sempr/component/TripleContainer.hpp> #include <sempr/component/TripleVector.hpp> #include <sempr/component/TriplePropertyMap.hpp> #include <sempr/component/AffineTransform.hpp> #include <sempr/component/GeosGeometry.hpp> #include <sempr/SeparateFileStorage.hpp> #include <sempr/Core.hpp> #include <sempr-gui/DirectConnectionBuilder.hpp> #include "ROSConnectionServer.hpp" #include <ros/ros.h> using namespace sempr; using namespace sempr::gui; int main(int argc, char** args) { ::ros::init(argc, args, "sempr_server"); // Create a "sempr_data" directory in the working dir if it does not // already exist. This is the place where everything will be stored in. // TODO: Make this a configuration option/parameter. // ::ros::NodeHandle nh("~"); std::string dbPath; nh.param<std::string>("directory", dbPath, "./sempr_data"); if (!fs::exists(dbPath)) fs::create_directory(dbPath); auto db = std::make_shared<SeparateFileStorage>(dbPath); // create a sempr-instance Core sempr(db, db); // use the storage for persistence and id generation sempr.loadPlugins(); // and load everything that has been persisted previously. auto savedEntities = db->loadAll(); for (auto& e : savedEntities) { sempr.addEntity(e); } // Create a mutex to get a lock on when working with sempr. std::mutex semprMutex; // create a direct connection implementing the interface for the gui auto directConnection = std::make_shared<DirectConnection>(&sempr, semprMutex); // wrap the connection in a ROSConnectionServer to expose it in the network sempr::ros::ROSConnectionServer connection(directConnection); // Before the connection fully works we need to insert it into the reasoner. // Well, also register the node builders we might need. // TODO: This is tedious, and I probably forgot a whole bunch of builders. // Maybe a plugin-system to would be cool, to just initialize // everything that's available on the system? rete::RuleParser& parser = sempr.parser(); // the next to are used to create a connection between the reasoner and the // "directConnection" object parser.registerNodeBuilder<ECNodeBuilder<Component>>(); parser.registerNodeBuilder<DirectConnectionBuilder>(directConnection); parser.registerNodeBuilder<DirectConnectionTripleBuilder>(directConnection); // add rules that actually implement the connection into the network sempr.addRules( "[connectionEC: EC<Component>(?e ?c) -> DirectConnection(?e ?c)]" "[connectionTriple: (?s ?p ?o) -> DirectConnectionTriple(?s ?p ?o)]" ); /* // add rules that allow you to add new rules as data sempr.addRules( "[inferRules: (?a <type> <Rules>), EC<TextComponent>(?a ?c)," "text:value(?text ?c)" "->" "constructRules(?text)]" "[extractTriples: EC<TripleContainer>(?e ?c) -> ExtractTriples(?c)]" ); */ ::ros::Rate rate(10); while (::ros::ok()) { ::ros::spinOnce(); sempr.performInference(); rate.sleep(); } return 0; }
33.30303
83
0.672733
sempr-tk
d12f2665d4e92753df196e57c7058703da1c4a9f
2,477
cpp
C++
DRCHEF.cpp
ankiiitraj/questionsSolved
8452b120935a9c3d808b45f27dcdc05700d902fc
[ "MIT" ]
null
null
null
DRCHEF.cpp
ankiiitraj/questionsSolved
8452b120935a9c3d808b45f27dcdc05700d902fc
[ "MIT" ]
1
2020-02-24T19:45:57.000Z
2020-02-24T19:45:57.000Z
DRCHEF.cpp
ankiiitraj/questionsSolved
8452b120935a9c3d808b45f27dcdc05700d902fc
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; void __print(int x) {cerr << x;} void __print(long x) {cerr << x;} void __print(long long x) {cerr << x;} void __print(unsigned x) {cerr << x;} void __print(unsigned long x) {cerr << x;} void __print(unsigned long long x) {cerr << x;} void __print(float x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} void __print(bool x) {cerr << (x ? "true" : "false");} template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";} void _print() {cerr << "]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #ifndef ONLINE_JUDGE #define debug(x...) cerr << "[" << #x << "] = ["; _print(x) #else #define debug(x...) #endif int main() { #ifndef ONLINE_JUDGE freopen("ip.txt", "r", stdin); freopen("op.txt", "w", stdout); #endif int t; scanf("%d", &t); for(int test = 0; test < t; ++test) { long long n, x, temp; scanf("%lld%lld", &n, &x); multiset<long long> s; for(int itr = 0; itr < n; ++itr) { scanf("%lld", &temp); s.insert(temp); } long long cnt = 0; while(!s.empty()){ // if(cnt > 10) // break; auto itr = (s.lower_bound(x)); cnt++; if(x < *s.begin()){ long long cur = *s.rbegin(); s.erase(s.find(*s.rbegin())); if((cur - x)*2 > 0) s.insert(min((cur - x)*2, cur)); x *= 2; // debug(x, s, '1'); continue; } if(itr == s.end()){ itr = s.lower_bound(*s.rbegin()); }else if(*itr != x and itr != s.begin()){ --itr; } auto new_itr = s.find(*itr); temp = *new_itr; temp = min(max(0LL, (*new_itr - x)*2), temp); if(x > min(x, *new_itr)*2 and x < *s.rbegin()){ long long cur = *s.rbegin(); s.erase(s.find(*s.rbegin())); if((cur - x)*2 > 0) s.insert(min(cur, (cur - x)*2)); x *= 2; // debug(x, s, '2'); continue; } x = min(x, *new_itr)*2; if(temp != *new_itr){ if(temp != 0) s.insert(temp); s.erase(new_itr); } // debug(x, s, '3'); } cout << cnt << endl; } }
24.524752
118
0.520791
ankiiitraj
d131fd6621072f48196c39832098e8eb8011b366
113
cpp
C++
demo/main.cpp
Nolnocn/Bayesian-Inference
76ee29171c6e3a4a69b752c1f68ae3fef2526f92
[ "MIT" ]
1
2021-07-07T02:45:55.000Z
2021-07-07T02:45:55.000Z
demo/main.cpp
Nolnocn/Bayes-Classifier
76ee29171c6e3a4a69b752c1f68ae3fef2526f92
[ "MIT" ]
null
null
null
demo/main.cpp
Nolnocn/Bayes-Classifier
76ee29171c6e3a4a69b752c1f68ae3fef2526f92
[ "MIT" ]
null
null
null
#include "GolfDemo.hpp" int main( int argc, const char* argv[] ) { GolfDemo gd; gd.init(); return 0; }
10.272727
40
0.60177
Nolnocn
d134d5a6294862e54fcc64dcba2e7c16bde8c9dc
1,289
hpp
C++
cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/lognormal_rng.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/lognormal_rng.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/lognormal_rng.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_SCAL_PROB_LOGNORMAL_RNG_HPP #define STAN_MATH_PRIM_SCAL_PROB_LOGNORMAL_RNG_HPP #include <boost/random/lognormal_distribution.hpp> #include <boost/random/variate_generator.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> namespace stan { namespace math { template <class RNG> inline double lognormal_rng(double mu, double sigma, RNG& rng) { using boost::variate_generator; using boost::random::lognormal_distribution; static const char* function("lognormal_rng"); check_finite(function, "Location parameter", mu); check_positive_finite(function, "Scale parameter", sigma); variate_generator<RNG&, lognormal_distribution<> > lognorm_rng(rng, lognormal_distribution<>(mu, sigma)); return lognorm_rng(); } } } #endif
32.225
64
0.73623
yizhang-cae
d135a6ff9d3f6c6ec2db5836170015563bfaf28c
1,297
hpp
C++
libadb/include/libadb/api/interactions/data/interaction-data-command-option.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
1
2022-03-10T15:14:13.000Z
2022-03-10T15:14:13.000Z
libadb/include/libadb/api/interactions/data/interaction-data-command-option.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
9
2022-03-07T21:00:08.000Z
2022-03-15T23:14:52.000Z
libadb/include/libadb/api/interactions/data/interaction-data-command-option.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <variant> #include <optional> #include <cstdint> #include <vector> #include <libadb/libadb.hpp> #include <nlohmann/json_fwd.hpp> #include <libadb/api/interactions/data/application-command-option-type.hpp> namespace adb::api { /** * @brief Application Command Interaction Data Option * @details https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-interaction-data-option-structure */ struct InteractionDataCommandOption { /// the name of the parameter std::string name; /// value of application command option type ApplicationCommandOptionType type; /// the value of the option resulting from user input std::optional<std::variant<int64_t, double, std::string>> value; /// present if this option is a group or subcommand std::optional<std::vector<InteractionDataCommandOption>> options; /// true if this option is the currently focused option for autocomplete std::optional<bool> focused; }; LIBADB_API void to_json(nlohmann::json& j, const InteractionDataCommandOption& option); LIBADB_API void from_json(const nlohmann::json& j, InteractionDataCommandOption& option); }
38.147059
166
0.720123
faserg1
d136cd8109bd2a87c64d24ed66563d217d0f15e5
23,064
cpp
C++
libraries/eosiolib/tester/tester.cpp
James-Mart/Eden
0ccc405a94575c5044f6ecfdfbcf65a28ed00f90
[ "MIT" ]
null
null
null
libraries/eosiolib/tester/tester.cpp
James-Mart/Eden
0ccc405a94575c5044f6ecfdfbcf65a28ed00f90
[ "MIT" ]
null
null
null
libraries/eosiolib/tester/tester.cpp
James-Mart/Eden
0ccc405a94575c5044f6ecfdfbcf65a28ed00f90
[ "MIT" ]
null
null
null
#include <eosio/abi.hpp> #include <eosio/from_string.hpp> #include <eosio/tester.hpp> namespace { using cb_alloc_type = void* (*)(void* cb_alloc_data, size_t size); extern "C" { // clang-format off [[clang::import_name("tester_create_chain2")]] uint32_t tester_create_chain2(const char* snapshot, uint32_t snapshot_size, uint64_t state_size); [[clang::import_name("tester_destroy_chain")]] void tester_destroy_chain(uint32_t chain); [[clang::import_name("tester_exec_deferred")]] bool tester_exec_deferred(uint32_t chain_index, void* cb_alloc_data, cb_alloc_type cb_alloc); [[clang::import_name("tester_execute")]] int32_t tester_execute(const char* command, uint32_t command_size); [[clang::import_name("tester_finish_block")]] void tester_finish_block(uint32_t chain_index); [[clang::import_name("tester_get_chain_path")]] uint32_t tester_get_chain_path(uint32_t chain, char* dest, uint32_t dest_size); [[clang::import_name("tester_get_head_block_info")]] void tester_get_head_block_info(uint32_t chain_index, void* cb_alloc_data, cb_alloc_type cb_alloc); [[clang::import_name("tester_push_transaction")]] void tester_push_transaction(uint32_t chain_index, const char* args_packed, uint32_t args_packed_size, void* cb_alloc_data, cb_alloc_type cb_alloc); [[clang::import_name("tester_read_whole_file")]] bool tester_read_whole_file(const char* filename, uint32_t filename_size, void* cb_alloc_data, cb_alloc_type cb_alloc); [[clang::import_name("tester_replace_account_keys")]] void tester_replace_account_keys(uint32_t chain_index, uint64_t account, uint64_t permission, const char* key, uint32_t key_size); [[clang::import_name("tester_replace_producer_keys")]] void tester_replace_producer_keys(uint32_t chain_index, const char* key, uint32_t key_size); [[clang::import_name("tester_select_chain_for_db")]] void tester_select_chain_for_db(uint32_t chain_index); [[clang::import_name("tester_shutdown_chain")]] void tester_shutdown_chain(uint32_t chain); [[clang::import_name("tester_sign")]] uint32_t tester_sign(const void* key, uint32_t keylen, const void* digest, void* sig, uint32_t siglen); [[clang::import_name("tester_start_block")]] void tester_start_block(uint32_t chain_index, int64_t skip_miliseconds); [[clang::import_name("tester_get_history")]] uint32_t tester_get_history(uint32_t chain_index, uint32_t block_num, char* dest, uint32_t dest_size); // clang-format on } template <typename Alloc_fn> inline bool read_whole_file(const char* filename_begin, uint32_t filename_size, Alloc_fn alloc_fn) { return tester_read_whole_file(filename_begin, filename_size, &alloc_fn, [](void* cb_alloc_data, size_t size) -> void* { // return (*reinterpret_cast<Alloc_fn*>(cb_alloc_data))(size); }); } template <typename Alloc_fn> inline void get_head_block_info(uint32_t chain, Alloc_fn alloc_fn) { tester_get_head_block_info(chain, &alloc_fn, [](void* cb_alloc_data, size_t size) -> void* { // return (*reinterpret_cast<Alloc_fn*>(cb_alloc_data))(size); }); } template <typename Alloc_fn> inline void push_transaction(uint32_t chain, const char* args_begin, uint32_t args_size, Alloc_fn alloc_fn) { tester_push_transaction(chain, args_begin, args_size, &alloc_fn, [](void* cb_alloc_data, size_t size) -> void* { // return (*reinterpret_cast<Alloc_fn*>(cb_alloc_data))(size); }); } template <typename Alloc_fn> inline bool exec_deferred(uint32_t chain, Alloc_fn alloc_fn) { return tester_exec_deferred(chain, &alloc_fn, [](void* cb_alloc_data, size_t size) -> void* { // return (*reinterpret_cast<Alloc_fn*>(cb_alloc_data))(size); }); } } // namespace std::vector<char> eosio::read_whole_file(std::string_view filename) { std::vector<char> result; if (!::read_whole_file(filename.data(), filename.size(), [&](size_t size) { result.resize(size); return result.data(); })) check(false, "read " + std::string(filename) + " failed"); return result; } int32_t eosio::execute(std::string_view command) { return ::tester_execute(command.data(), command.size()); } eosio::asset eosio::string_to_asset(const char* s) { return eosio::convert_from_string<asset>(s); } namespace { // TODO: move struct tester_permission_level_weight { eosio::permission_level permission = {}; uint16_t weight = {}; }; EOSIO_REFLECT(tester_permission_level_weight, permission, weight); // TODO: move struct tester_wait_weight { uint32_t wait_sec = {}; uint16_t weight = {}; }; EOSIO_REFLECT(tester_wait_weight, wait_sec, weight); // TODO: move struct tester_authority { uint32_t threshold = {}; std::vector<eosio::key_weight> keys = {}; std::vector<tester_permission_level_weight> accounts = {}; std::vector<tester_wait_weight> waits = {}; }; EOSIO_REFLECT(tester_authority, threshold, keys, accounts, waits); } // namespace /** * Validates the status of a transaction. If expected_except is nullptr, then the * transaction should succeed. Otherwise it represents a string which should be * part of the error message. */ void eosio::expect(const transaction_trace& tt, const char* expected_except) { if (expected_except) { if (tt.status == transaction_status::executed) eosio::check(false, "transaction succeeded, but was expected to fail with: " + std::string(expected_except)); if (!tt.except) eosio::check(false, "transaction has no failure message. expected: " + std::string(expected_except)); if (tt.except->find(expected_except) == std::string::npos) eosio::check(false, "transaction failed with <<<" + *tt.except + ">>>, but was expected to fail with: <<<" + expected_except + ">>>"); } else { if (tt.status == transaction_status::executed) return; if (tt.except) eosio::print("transaction has exception: ", *tt.except, "\n"); eosio::check(false, "transaction failed with status " + to_string(tt.status)); } } eosio::signature eosio::sign(const eosio::private_key& key, const eosio::checksum256& digest) { auto raw_digest = digest.extract_as_byte_array(); auto raw_key = eosio::convert_to_bin(key); constexpr uint32_t buffer_size = 80; std::vector<char> buffer(buffer_size); unsigned sz = ::tester_sign(raw_key.data(), raw_key.size(), raw_digest.data(), buffer.data(), buffer.size()); buffer.resize(sz); if (sz > buffer_size) { ::tester_sign(raw_key.data(), raw_key.size(), raw_digest.data(), buffer.data(), buffer.size()); } return eosio::convert_from_bin<eosio::signature>(buffer); } void eosio::internal_use_do_not_use::hex(const uint8_t* begin, const uint8_t* end, std::ostream& os) { std::ostreambuf_iterator<char> dest(os.rdbuf()); auto nibble = [&dest](uint8_t i) { if (i <= 9) *dest++ = '0' + i; else *dest++ = 'A' + i - 10; }; while (begin != end) { nibble(((uint8_t)*begin) >> 4); nibble(((uint8_t)*begin) & 0xf); ++begin; } } std::ostream& eosio::operator<<(std::ostream& os, const block_timestamp& obj) { return os << obj.slot; } std::ostream& eosio::operator<<(std::ostream& os, const name& obj) { return os << obj.to_string(); } std::ostream& eosio::operator<<(std::ostream& os, const asset& obj) { return os << obj.to_string(); } const eosio::public_key eosio::test_chain::default_pub_key = public_key_from_string("EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV"); const eosio::private_key eosio::test_chain::default_priv_key = private_key_from_string("5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3"); // We only allow one chain to exist at a time in the tester. // If we ever find that we need multiple chains, this will // need to be kept in sync with whatever updates the native layer. static eosio::test_chain* current_chain = nullptr; eosio::test_chain::test_chain(const char* snapshot, uint64_t state_size) : id{::tester_create_chain2(snapshot ? snapshot : "", snapshot ? strlen(snapshot) : 0, state_size)} { current_chain = this; } eosio::test_chain::~test_chain() { current_chain = nullptr; ::tester_destroy_chain(id); } void eosio::test_chain::shutdown() { ::tester_shutdown_chain(id); } std::string eosio::test_chain::get_path() { size_t len = tester_get_chain_path(id, nullptr, 0); std::string result(len, 0); tester_get_chain_path(id, result.data(), len); return result; } void eosio::test_chain::replace_producer_keys(const eosio::public_key& key) { std::vector<char> packed = pack(key); ::tester_replace_producer_keys(id, packed.data(), packed.size()); } void eosio::test_chain::replace_account_keys(name account, name permission, const eosio::public_key& key) { std::vector<char> packed = pack(key); ::tester_replace_account_keys(id, account.value, permission.value, packed.data(), packed.size()); } void eosio::test_chain::replace_account_keys(name account, const eosio::public_key& key) { std::vector<char> packed = pack(key); ::tester_replace_account_keys(id, account.value, "owner"_n.value, packed.data(), packed.size()); ::tester_replace_account_keys(id, account.value, "active"_n.value, packed.data(), packed.size()); } void eosio::test_chain::start_block(int64_t skip_miliseconds) { head_block_info.reset(); if (skip_miliseconds >= 500) { // Guarantee that there is a recent block for fill_tapos to use. ::tester_start_block(id, skip_miliseconds - 500); ::tester_start_block(id, 0); } else { ::tester_start_block(id, skip_miliseconds); } } void eosio::test_chain::start_block(std::string_view time) { uint64_t value; check(string_to_utc_microseconds(value, time.data(), time.data() + time.size()), "bad time"); start_block(time_point{microseconds(value)}); } void eosio::test_chain::start_block(time_point tp) { finish_block(); auto head_tp = get_head_block_info().timestamp.to_time_point(); auto skip = (tp - head_tp).count() / 1000 - 500; start_block(skip); } void eosio::test_chain::finish_block() { head_block_info.reset(); ::tester_finish_block(id); } const eosio::block_info& eosio::test_chain::get_head_block_info() { if (!head_block_info) { std::vector<char> bin; ::get_head_block_info(id, [&](size_t size) { bin.resize(size); return bin.data(); }); head_block_info = convert_from_bin<block_info>(bin); } return *head_block_info; } void eosio::test_chain::fill_tapos(transaction& t, uint32_t expire_sec) { auto& info = get_head_block_info(); t.expiration = time_point_sec(info.timestamp) + expire_sec; t.ref_block_num = info.block_num; memcpy(&t.ref_block_prefix, info.block_id.extract_as_byte_array().data() + 8, sizeof(t.ref_block_prefix)); } eosio::transaction eosio::test_chain::make_transaction(std::vector<action>&& actions, std::vector<action>&& cfa) { transaction t{time_point_sec{}}; fill_tapos(t); t.actions = std::move(actions); t.context_free_actions = std::move(cfa); return t; } [[nodiscard]] eosio::transaction_trace eosio::test_chain::push_transaction( const transaction& trx, const std::vector<private_key>& keys, const std::vector<std::vector<char>>& context_free_data, const std::vector<signature>& signatures) { std::vector<char> packed_trx = pack(trx); std::vector<char> args; (void)convert_to_bin(packed_trx, args); (void)convert_to_bin(context_free_data, args); (void)convert_to_bin(signatures, args); (void)convert_to_bin(keys, args); std::vector<char> bin; ::push_transaction(id, args.data(), args.size(), [&](size_t size) { bin.resize(size); return bin.data(); }); return convert_from_bin<transaction_trace>(bin); } eosio::transaction_trace eosio::test_chain::transact(std::vector<action>&& actions, const std::vector<private_key>& keys, const char* expected_except) { auto trace = push_transaction(make_transaction(std::move(actions)), keys); expect(trace, expected_except); return trace; } eosio::transaction_trace eosio::test_chain::transact(std::vector<action>&& actions, const char* expected_except) { return transact(std::move(actions), {default_priv_key}, expected_except); } [[nodiscard]] std::optional<eosio::transaction_trace> eosio::test_chain::exec_deferred() { std::vector<char> bin; if (!::exec_deferred(id, [&](size_t size) { bin.resize(size); return bin.data(); })) return {}; return convert_from_bin<transaction_trace>(bin); } void build_history_result(eosio::test_chain::get_history_result& history_result, eosio::ship_protocol::get_blocks_result_v0& blocks_result) { history_result.result = blocks_result; if (blocks_result.block) { history_result.block.emplace(); (void)from_bin(*history_result.block, *blocks_result.block); } if (blocks_result.traces) { (void)from_bin(history_result.traces, *blocks_result.traces); } if (blocks_result.deltas) { (void)from_bin(history_result.deltas, *blocks_result.deltas); } } #if 0 void build_history_result(eosio::test_chain::get_history_result& history_result, eosio::ship_protocol::get_blocks_result_v1& blocks_result) { history_result.result = blocks_result; if (blocks_result.block) { history_result.block = std::move(*blocks_result.block); } if (!blocks_result.traces.empty()) { blocks_result.traces.unpack(history_result.traces); } if (blocks_result.deltas.empty()) { blocks_result.deltas.unpack(history_result.deltas); } } #endif template <typename T> void build_history_result(eosio::test_chain::get_history_result&, const T&) { eosio::check(false, "test_chain::get_history: unexpected result type"); } std::optional<eosio::test_chain::get_history_result> eosio::test_chain::get_history( uint32_t block_num) { std::optional<get_history_result> ret; auto size = ::tester_get_history(id, block_num, nullptr, 0); if (!size) return ret; ret.emplace(); ret->memory.resize(size); ::tester_get_history(id, block_num, ret->memory.data(), size); ship_protocol::result r; (void)convert_from_bin(r, ret->memory); std::visit([&ret](auto& v) { build_history_result(*ret, v); }, r); return ret; } eosio::transaction_trace eosio::test_chain::create_account(name ac, const public_key& pub_key, const char* expected_except) { tester_authority simple_auth{ .threshold = 1, .keys = {{pub_key, 1}}, }; return transact({action{{{"eosio"_n, "active"_n}}, "eosio"_n, "newaccount"_n, std::make_tuple("eosio"_n, ac, simple_auth, simple_auth)}}, expected_except); } eosio::transaction_trace eosio::test_chain::create_account(name ac, const char* expected_except) { return create_account(ac, default_pub_key, expected_except); } eosio::transaction_trace eosio::test_chain::create_code_account(name account, const public_key& pub_key, bool is_priv, const char* expected_except) { tester_authority simple_auth{ .threshold = 1, .keys = {{pub_key, 1}}, }; tester_authority code_auth{ .threshold = 1, .keys = {{pub_key, 1}}, .accounts = {{{account, "eosio.code"_n}, 1}}, }; return transact( { action{{{"eosio"_n, "active"_n}}, "eosio"_n, "newaccount"_n, std::make_tuple("eosio"_n, account, simple_auth, code_auth)}, action{{{"eosio"_n, "active"_n}}, "eosio"_n, "setpriv"_n, std::make_tuple(account, is_priv)}, }, expected_except); } eosio::transaction_trace eosio::test_chain::create_code_account(name ac, const public_key& pub_key, const char* expected_except) { return create_code_account(ac, pub_key, false, expected_except); } eosio::transaction_trace eosio::test_chain::create_code_account(name ac, bool is_priv, const char* expected_except) { return create_code_account(ac, default_pub_key, is_priv, expected_except); } eosio::transaction_trace eosio::test_chain::create_code_account(name ac, const char* expected_except) { return create_code_account(ac, default_pub_key, false, expected_except); } eosio::transaction_trace eosio::test_chain::set_code(name ac, const char* filename, const char* expected_except) { return transact({action{{{ac, "active"_n}}, "eosio"_n, "setcode"_n, std::make_tuple(ac, uint8_t{0}, uint8_t{0}, read_whole_file(filename))}}, expected_except); } eosio::transaction_trace eosio::test_chain::set_abi(name ac, const char* filename, const char* expected_except) { auto json = read_whole_file(filename); json.push_back(0); json_token_stream stream(json.data()); abi_def def{}; from_json(def, stream); auto bin = convert_to_bin(def); return transact( {action{{{ac, "active"_n}}, "eosio"_n, "setabi"_n, std::make_tuple(ac, std::move(bin))}}, expected_except); } eosio::transaction_trace eosio::test_chain::create_token(name contract, name signer, name issuer, asset maxsupply, const char* expected_except) { return transact( {action{{{signer, "active"_n}}, contract, "create"_n, std::make_tuple(issuer, maxsupply)}}, expected_except); } eosio::transaction_trace eosio::test_chain::issue(const name& contract, const name& issuer, const asset& amount, const char* expected_except) { return transact({action{{{issuer, "active"_n}}, contract, "issue"_n, std::make_tuple(issuer, amount, std::string{"issuing"})}}, expected_except); } eosio::transaction_trace eosio::test_chain::transfer(const name& contract, const name& from, const name& to, const asset& amount, const std::string& memo, const char* expected_except) { return transact( {action{ {{from, "active"_n}}, contract, "transfer"_n, std::make_tuple(from, to, amount, memo)}}, expected_except); } eosio::transaction_trace eosio::test_chain::issue_and_transfer(const name& contract, const name& issuer, const name& to, const asset& amount, const std::string& memo, const char* expected_except) { return transact( { action{{{issuer, "active"_n}}, contract, "issue"_n, std::make_tuple(issuer, amount, std::string{"issuing"})}, action{{{issuer, "active"_n}}, contract, "transfer"_n, std::make_tuple(issuer, to, amount, memo)}, }, expected_except); } std::ostream& eosio::ship_protocol::operator<<(std::ostream& os, eosio::ship_protocol::transaction_status t) { return os << to_string(t); } std::ostream& eosio::ship_protocol::operator<<( std::ostream& os, const eosio::ship_protocol::account_auth_sequence& aas) { return os << eosio::convert_to_json(aas); } std::ostream& eosio::ship_protocol::operator<<(std::ostream& os, const eosio::ship_protocol::account_delta& ad) { return os << eosio::convert_to_json(ad); } extern "C" { void send_inline(char* serialized_action, size_t size) { eosio::check(current_chain != nullptr, "Cannot send an action without a blockchain"); current_chain->transact({eosio::unpack<eosio::action>(serialized_action, size)}); } }
37.260097
219
0.588319
James-Mart
d13c8b1eb83ddcfc22baa0d4fe0557ae6afd97bf
986
cpp
C++
matrizes/c.cpp
RuthMaria/algoritmo
ec9ebf629598dd75a05e33861706f1a6bc956cd5
[ "MIT" ]
null
null
null
matrizes/c.cpp
RuthMaria/algoritmo
ec9ebf629598dd75a05e33861706f1a6bc956cd5
[ "MIT" ]
null
null
null
matrizes/c.cpp
RuthMaria/algoritmo
ec9ebf629598dd75a05e33861706f1a6bc956cd5
[ "MIT" ]
null
null
null
#include<stdio.h> #include<conio.h> main(){ float mat[3][3]; int lin, col, maior = 0, menor = 999, plinha = 0, pcol = 0, plinha1 = 0, pcol1 = 0; maior = mat[0][0]; for(lin = 0; lin < 3; lin++){ printf("\n"); for(col = 0; col < 3; col++){ printf("Linha %d e coluna %d: ", lin, col); scanf("%f", &mat[lin][col]); if (mat[lin][col] > maior){ maior = mat[lin][col]; plinha1 = lin; pcol1 = col; } if(mat[lin][col] < menor){ menor = mat[lin][col]; plinha = lin; pcol = col; } } } printf("\n Maior numero:%d, esta na linha:%d e coluna:%d", maior, plinha1, pcol1); printf("\n Menor numero:%d, esta na linha:%d e coluna:%d", menor, plinha, pcol); getch(); }
29
90
0.389452
RuthMaria
d13f5c6bc6b6719d6f59776a2b84b64e053ddbd9
452
hpp
C++
vm/os-solaris-x86.64.hpp
erg/factor
134e416b132a1c4f95b0ae15ab2f9a42893b6b6f
[ "BSD-2-Clause" ]
null
null
null
vm/os-solaris-x86.64.hpp
erg/factor
134e416b132a1c4f95b0ae15ab2f9a42893b6b6f
[ "BSD-2-Clause" ]
null
null
null
vm/os-solaris-x86.64.hpp
erg/factor
134e416b132a1c4f95b0ae15ab2f9a42893b6b6f
[ "BSD-2-Clause" ]
null
null
null
#include <ucontext.h> namespace factor { #define UAP_STACK_POINTER(ucontext) (((ucontext_t *)ucontext)->uc_mcontext.gregs[RSP]) #define UAP_PROGRAM_COUNTER(ucontext) (((ucontext_t *)ucontext)->uc_mcontext.gregs[RIP]) #define UAP_SET_TOC_POINTER(uap, ptr) (void)0 #define CODE_TO_FUNCTION_POINTER(code) (void)0 #define CODE_TO_FUNCTION_POINTER_CALLBACK(vm, code) (void)0 #define FUNCTION_CODE_POINTER(ptr) ptr #define FUNCTION_TOC_POINTER(ptr) ptr }
30.133333
88
0.794248
erg
d141213cb5a0dacb18be219f9b0eadb3e0853b6b
2,027
cpp
C++
core/base/Request.cpp
forrestsong/fpay_demo
7b254a1389b011c799497ad7d08bb8d8d349e557
[ "MIT" ]
1
2018-08-12T15:08:49.000Z
2018-08-12T15:08:49.000Z
core/base/Request.cpp
forrestsong/fpay_demo
7b254a1389b011c799497ad7d08bb8d8d349e557
[ "MIT" ]
null
null
null
core/base/Request.cpp
forrestsong/fpay_demo
7b254a1389b011c799497ad7d08bb8d8d349e557
[ "MIT" ]
null
null
null
#include <iostream> #include "Request.h" using namespace std; Request::Request() : up(NULL, 0) , cmd(NULL) , parser(NULL) , cpBuffer(NULL) , od(NULL) , os(0) , protoType(PROTO_NONE) { } Request::Request(const char *data, uint32_t sz, PROTO_T proto) : up(data, sz) , cmd(NULL) , parser(NULL) , cpBuffer(NULL) , od(data) , os(sz) , protoType(proto) { } Request::Request(const char *data, uint32_t sz, bool copy, PROTO_T proto) : up(data, sz) , cmd(NULL) , parser(NULL) , cpBuffer(NULL) , od(data) , os(sz) , protoType(proto) { if (copy) { cpBuffer = new char[sz]; memcpy(cpBuffer, data, sz); up.reset(cpBuffer, sz); od = cpBuffer; } } #define PROTO_MAGIC_SHIFT 29 #define PROTO_MAGIC_MASK ~(111 << PROTO_MAGIC_SHIFT) PROTO_T Request::getProtoType(uint32_t len, uint32_t& realLength) { uint32_t top3Bit = len >> PROTO_MAGIC_SHIFT; PROTO_T proto = PROTO_MAX; switch (top3Bit) { case PROTO_JSON: proto = PROTO_JSON; break; case PROTO_BIN: proto = PROTO_BIN; break; case PROTO_HTTP: proto = PROTO_HTTP; break; default: break; } realLength = len & PROTO_MAGIC_MASK; return proto; } void Request::popHeader() { switch (protoType) { case PROTO_BIN: { len = up.readUint32(); uri = up.readUint32(); appId = up.readUint16(); } break; case PROTO_HTTP: break; default: break; } } Request::~Request() { if (parser && cmd) { parser->destroyForm(cmd); } if (cpBuffer != NULL) { delete[] cpBuffer; } } void Request::setFormHandler(IFormHandle *h) { parser = h; cmd = parser->handlePacket(up); } void Request::leftPack(std::string &out) { out.assign(up.data(), up.size()); }
18.768519
73
0.537247
forrestsong
d14c6abb008fe02142c74237630e9626edcdea4b
3,960
cpp
C++
src/Nokia5110.cpp
intoyuniot/Nokia5110
7d240b17aab230b661a8054ed998a256bbd608ca
[ "MIT" ]
null
null
null
src/Nokia5110.cpp
intoyuniot/Nokia5110
7d240b17aab230b661a8054ed998a256bbd608ca
[ "MIT" ]
null
null
null
src/Nokia5110.cpp
intoyuniot/Nokia5110
7d240b17aab230b661a8054ed998a256bbd608ca
[ "MIT" ]
null
null
null
/* Adapted for IntoRobot by Robin, Sept 19, 2015 7-17-2011 Spark Fun Electronics 2011 Nathan Seidle Modified on 03-12-2014 by ionpan This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license). */ #include "Nokia5110.h" #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) Nokia5110::Nokia5110(uint8_t _SCE, uint8_t _RESET, uint8_t _DC, uint8_t _SDIN, uint8_t _SCLK) { SCE = _SCE; RESET = _RESET; DC = _DC; SDIN = _SDIN; SCLK = _SCLK; // configure control pins pinMode(SCE, OUTPUT); pinMode(RESET, OUTPUT); pinMode(DC, OUTPUT); pinMode(SDIN, OUTPUT); pinMode(SCLK, OUTPUT); // set default display values COLS = 84; ROWS = 48; mode = 0x0C; // set to normal contrast = 0xBC; } void Nokia5110::setContrast(uint16_t _contrast) { contrast = _contrast; } void Nokia5110::setDimensions(int _COLS, int _ROWS) { COLS = _COLS; ROWS = _ROWS; } void Nokia5110::invert() { if (mode == 0x0C) { mode = 0x0D; // change to inverted } else if (mode == 0x0D) { mode = 0x0C; // change to normal } } void Nokia5110::gotoXY(int _x, int _y) { write(0, 0x80 | _x); // column. write(0, 0x40 | _y); // row. ? } // this takes a large array of bits and sends them to the LCD void Nokia5110::bitmap(char _bitmapArray[]) { for (int index = 0; index < (COLS * ROWS / 8); index++) { write(LCD_DATA, _bitmapArray[index]); } } void Nokia5110::progBitmap(char const _bitmapArray[]) { for (int index = 0; index < (COLS * ROWS / 8); index++) { write(LCD_DATA, pgm_read_byte(& _bitmapArray[index])); } } // This function takes in a character, looks it up in the font table/array // And writes it to the screen // Each character is 8 bits tall and 5 bits wide. We pad one blank column of // pixels on the right side of the character for readability. void Nokia5110::character(char _character) { //LCDWrite(LCD_DATA, 0x00); // blank vertical line padding before character for (int index = 0; index < 5 ; index++) { write(LCD_DATA, pgm_read_byte(&(ASCII[_character - 0x20][index]))); } //0x20 is the ASCII character for Space (' '). The font table starts with this character write(LCD_DATA, 0x00); // blank vertical line padding after character } // given a string of characters, one by one is passed to the LCD void Nokia5110::string(char* _characters) { while (*_characters) { character(*_characters++); } } // clears the LCD by writing zeros to the entire screen void Nokia5110::clear(void) { for (int index = 0; index < (COLS * ROWS / 8); index++) { write(LCD_DATA, 0x00); } gotoXY(0, 0); // after we clear the display, return to the home position } // this sends the magical commands to the PCD8544 void Nokia5110::init(void) { // reset the LCD to a known state digitalWrite(RESET, LOW); digitalWrite(RESET, HIGH); write(LCD_COMMAND, 0x21); // tell LCD that extended commands follow write(LCD_COMMAND, contrast); // set LCD Vop (Contrast): Try 0xB1(good @ 3.3V) or 0xBF if your display is too dark write(LCD_COMMAND, 0x04); // set Temp coefficent write(LCD_COMMAND, 0x14); // LCD bias mode 1:48: Try 0x13 or 0x14 write(LCD_COMMAND, 0x20); // we must send 0x20 before modifying the display control mode write(LCD_COMMAND, mode); // set display control, normal mode. 0x0D for inverse } // There are two memory banks in the LCD, data/RAM and commands. This // function sets the DC pin high or low depending, and then sends // the data byte void Nokia5110::write(byte _data_or_command, byte _data) { digitalWrite(DC, _data_or_command); // tell the LCD that we are writing either to data or a command // send the data digitalWrite(SCE, LOW); shiftOut(SDIN, SCLK, MSBFIRST, _data); digitalWrite(SCE, HIGH); }
26.577181
118
0.658838
intoyuniot
d152e81423b8065f9304559d0862c3b60e4a6cee
7,696
cpp
C++
src/abs.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
15
2017-11-01T11:39:32.000Z
2021-04-02T02:42:59.000Z
src/abs.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
6
2017-07-26T17:55:27.000Z
2020-11-15T22:04:35.000Z
src/abs.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
5
2018-05-09T13:42:17.000Z
2020-01-17T06:22:59.000Z
#include <abs.hpp> #include <cassert> #include <exception> #include <fstream> #include <iostream> #include <queue> #include <sstream> Abs::Abs(const std::string& s) { load(s); } void Abs::crop(const cv::Rect& roi) { const int rows = valid.rows; const int cols = valid.cols; for (int r = 0; r < rows; ++r) for (int c = 0; c < cols; ++c) { cv::Point p(r, c); if (!roi.contains(p)) valid.at<uchar>(r, c) = false; } } void Abs::crop(const cv::Point3d& center, double dist) { const int rows = valid.rows; const int cols = valid.cols; dist *= dist; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) if (valid.at<uchar>(i, j) && pow(center.x - depth.at<cv::Vec3d>(i, j)[0], 2.0) + pow(center.y - depth.at<cv::Vec3d>(i, j)[1], 2.0) > dist) valid.at<uchar>(i, j) = false; } int Abs::read_int(const std::string& str) { std::stringstream ss; ss << str; int num; ss >> num; return num; } std::vector<cv::Point3d> Abs::to_points() const { std::vector<cv::Point3d> points; const int rows = valid.rows; const int cols = valid.cols; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) if (valid.at<uchar>(i, j) - '0') points.emplace_back(depth.at<cv::Vec3d>(i, j)); return points; } cv::Mat Abs::to_mat() const { cv::Mat depth_img(valid.rows, valid.cols, CV_32F); for (int i = 0; i < valid.rows; i++) for (int j = 0; j < valid.cols; j++) if (valid.at<uchar>(i, j) - '0') depth_img.at<float>(i, j) = depth.at<cv::Vec3d>(i, j)[2]; else depth_img.at<float>(i, j) = 0; return depth_img; } std::vector<cv::Point2d> Abs::to_pixels() const { std::vector<cv::Point2d> pixels; const int rows = valid.rows; const int cols = valid.cols; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) if (valid.at<uchar>(i, j) - '0') pixels.emplace_back(i, j); return pixels; } void Abs::print_registered_pcloud(const cv::Mat& img) const { const int rows = valid.rows; const int cols = valid.cols; for (int i = 0; i < rows; ++i) for (int j = 0; j < cols; ++j) if (valid.at<uchar>(i, j)) printf("v %.4lf %.4lf %.4lf %u %u %u\n", depth.at<cv::Vec3d>(i, j)[0], depth.at<cv::Vec3d>(i, j)[1], depth.at<cv::Vec3d>(i, j)[2], (unsigned int)img.at<cv::Vec3b>(i, j)[0], (unsigned int)img.at<cv::Vec3b>(i, j)[1], (unsigned int)img.at<cv::Vec3b>(i, j)[2]); } void Abs::load(const std::string& filename) { std::ifstream f(filename); if (!f) throw std::runtime_error("Unable to open image file."); // read the headers std::string l1, l2, l3; std::getline(f, l1); std::getline(f, l2); std::getline(f, l3); const int rows = read_int(l1); const int cols = read_int(l2); // create matrices depth.create(rows, cols, CV_64FC3); valid.create(rows, cols, CV_8U); // read the contents for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) f >> valid.at<uchar>(i, j); // read x coordinates for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) f >> depth.at<cv::Vec3d>(i, j)[0]; // read y coordinates for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) f >> depth.at<cv::Vec3d>(i, j)[1]; // read z coordinates for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) f >> depth.at<cv::Vec3d>(i, j)[2]; } cv::Point3d Abs::at(const int i, const int j) const { if (valid.at<uchar>(i, j) == '0') return cv::Point3d(0, 0, 0); return cv::Point3d(depth.at<cv::Vec3d>(i, j)); } cv::Point3d Abs::at(const cv::Point p) const { if (valid.at<uchar>(p) == '0') return cv::Point3d(0, 0, 0); return cv::Point3d(depth.at<cv::Vec3d>(p)); } cv::Point3d Abs::closest_point_to(const int i, const int j) const { // check input boundaries if (i < 0 || i >= valid.rows || j < 0 || j >= valid.cols) throw std::runtime_error("Out of boundaries"); // prepare breadth first search cv::Mat mask(valid.size(), CV_8U); mask.setTo(0); std::queue<int> qi, qj; qi.push(i); qj.push(j); mask.at<uchar>(i, j) = 1; // breadth first search while (!qi.empty()) { const int i = qi.front(); const int j = qj.front(); qi.pop(); qj.pop(); if (valid.at<uchar>(i, j) == '1') return at(i, j); const std::vector<int> i_neighbor = {1, -1, 0, 0}; const std::vector<int> j_neighbor = {0, 0, 1, -1}; for (int k = 0; k < 4; k++) { const int next_i = i + i_neighbor[k]; const int next_j = j + j_neighbor[k]; if (next_i >= 0 && next_i < mask.rows && next_j >= 0 && next_j < mask.cols && !mask.at<uchar>(next_i, next_j)) { qi.push(next_i); qj.push(next_j); mask.at<uchar>(next_i, next_j) = 1; } } } throw std::runtime_error("No valid point in entire abs"); } AbsCalibration::AbsCalibration(const Abs& abs) : abs(abs) { const std::vector<cv::Point3d> points = abs.to_points(); const std::vector<cv::Point2d> pixels = abs.to_pixels(); // compute mean mean = cv::Point3d(0, 0, 0); for (cv::Point3d point : points) mean += point; mean /= static_cast<double>(points.size()); assert(pixels.size() == points.size()); const int max_points = points.size(); cv::Mat X(max_points * 2, 11, CV_64F), Y(max_points * 2, 1, CV_64F); int n = 0; for (int i = 0, len = points.size(); i < len; i++, n += 2) { Y.at<double>(n, 0) = pixels[i].x; Y.at<double>(n + 1, 0) = pixels[i].y; X.at<double>(n, 0) = (points[i].x - mean.x); X.at<double>(n, 1) = (points[i].y - mean.y); X.at<double>(n, 2) = (points[i].z - mean.z); X.at<double>(n, 3) = 1.0; X.at<double>(n, 4) = 0.0; X.at<double>(n, 5) = 0.0; X.at<double>(n, 6) = 0.0; X.at<double>(n, 7) = 0.0; X.at<double>(n, 8) = -pixels[i].x * (points[i].x - mean.x); X.at<double>(n, 9) = -pixels[i].x * (points[i].y - mean.y); X.at<double>(n, 10) = -pixels[i].x * (points[i].z - mean.z); X.at<double>(n + 1, 0) = 0.0; X.at<double>(n + 1, 1) = 0.0; X.at<double>(n + 1, 2) = 0.0; X.at<double>(n + 1, 3) = 0.0; X.at<double>(n + 1, 4) = (points[i].x - mean.x); X.at<double>(n + 1, 5) = (points[i].y - mean.y); X.at<double>(n + 1, 6) = (points[i].z - mean.z); X.at<double>(n + 1, 7) = 1.0; X.at<double>(n + 1, 8) = -pixels[i].y * (points[i].x - mean.x); X.at<double>(n + 1, 9) = -pixels[i].y * (points[i].y - mean.y); X.at<double>(n + 1, 10) = -pixels[i].y * (points[i].z - mean.z); } cv::Mat tmp_c = (X.t() * X).inv(cv::DECOMP_LU) * X.t() * Y; cmatrix.create(3, 4, CV_64F); for (int i = 0; i < 11; i++) cmatrix.at<double>(i / 4, i % 4) = tmp_c.at<double>(i, 0); cmatrix.at<double>(2, 3) = 1.0; } cv::Point3d AbsCalibration::depth_to_xyz(const float x, const float y, const float z) const { return abs.at(y, x); } cv::Point AbsCalibration::xyz_to_depth(const cv::Point3d& p) const { cv::Point2d ret; const double q = (p.x - mean.x) * cmatrix.at<double>(2, 0) + (p.y - mean.y) * cmatrix.at<double>(2, 1) + (p.z - mean.z) * cmatrix.at<double>(2, 2) + cmatrix.at<double>(2, 3); ret.y = ((p.x - mean.x) * cmatrix.at<double>(0, 0) + (p.y - mean.y) * cmatrix.at<double>(0, 1) + (p.z - mean.z) * cmatrix.at<double>(0, 2) + cmatrix.at<double>(0, 3)) / q; ret.x = ((p.x - mean.x) * cmatrix.at<double>(1, 0) + (p.y - mean.y) * cmatrix.at<double>(1, 1) + (p.z - mean.z) * cmatrix.at<double>(1, 2) + cmatrix.at<double>(1, 3)) / q; return ret; }
29.829457
78
0.539891
ivision-ufba
d1609ecde0285d306a818ae8faf7a136157a2529
175
cpp
C++
100000569/B/another.cpp
gongbo2018/codeup_contest
c61cd02f145c764b0eb2728fb2b3405314d522ca
[ "MIT" ]
1
2020-08-14T09:33:51.000Z
2020-08-14T09:33:51.000Z
100000569/B/another.cpp
gongbo2018/codeup_contest
c61cd02f145c764b0eb2728fb2b3405314d522ca
[ "MIT" ]
null
null
null
100000569/B/another.cpp
gongbo2018/codeup_contest
c61cd02f145c764b0eb2728fb2b3405314d522ca
[ "MIT" ]
null
null
null
#include <cstdio> int main() { int data[10]; for (int i=0;i<10;i++) { scanf("%d", &data[i]); } for (int j=9; j>=0;j--) { printf("%d\n", data[j]); } return 0; }
10.9375
26
0.474286
gongbo2018
d163f38fe1ea06fb34d229d3b3c5e5ab722fbd36
11,463
hpp
C++
include/caffe/loss_layers.hpp
xiaomi646/caffe_2d_mlabel
912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65
[ "BSD-2-Clause" ]
1
2015-07-08T15:30:06.000Z
2015-07-08T15:30:06.000Z
include/caffe/loss_layers.hpp
xiaomi646/caffe_2d_mlabel
912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65
[ "BSD-2-Clause" ]
null
null
null
include/caffe/loss_layers.hpp
xiaomi646/caffe_2d_mlabel
912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2014 BVLC and contributors. #ifndef CAFFE_LOSS_LAYERS_HPP_ #define CAFFE_LOSS_LAYERS_HPP_ #include <string> #include <utility> #include <vector> #include "leveldb/db.h" #include "pthread.h" #include "boost/scoped_ptr.hpp" #include "hdf5.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layer.hpp" #include "caffe/neuron_layers.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { const float kLOG_THRESHOLD = 1e-20; /* LossLayer Takes two inputs of same num (a and b), and has no output. The gradient is propagated to a. */ template <typename Dtype> class LossLayer : public Layer<Dtype> { public: explicit LossLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void SetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void FurtherSetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {} virtual inline int ExactNumBottomBlobs() const { return 2; } virtual inline int MaxTopBlobs() const { return 1; } // We usually cannot backpropagate to the labels; ignore force_backward for // these inputs. virtual inline bool AllowForceBackward(const int bottom_index) const { return bottom_index != 1; } }; // Forward declare SoftmaxLayer for use in SoftmaxWithLossLayer. template <typename Dtype> class SoftmaxLayer; /* SoftmaxWithLossLayer Implements softmax and computes the loss. It is preferred over separate softmax + multinomiallogisticloss layers due to more numerically stable gradients. In test, this layer could be replaced by simple softmax layer. */ template <typename Dtype> class SoftmaxWithLossLayer : public Layer<Dtype> { public: explicit SoftmaxWithLossLayer(const LayerParameter& param) : Layer<Dtype>(param), softmax_layer_(new SoftmaxLayer<Dtype>(param)) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual inline LayerParameter_LayerType type() const { return LayerParameter_LayerType_SOFTMAX_LOSS; } virtual inline int MaxTopBlobs() const { return 2; } // We cannot backpropagate to the labels; ignore force_backward for these // inputs. virtual inline bool AllowForceBackward(const int bottom_index) const { return bottom_index != 1; } protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); shared_ptr<SoftmaxLayer<Dtype> > softmax_layer_; // prob stores the output probability of the layer. Blob<Dtype> prob_; // Vector holders to call the underlying softmax layer forward and backward. vector<Blob<Dtype>*> softmax_bottom_vec_; vector<Blob<Dtype>*> softmax_top_vec_; }; /* SigmoidCrossEntropyLossLayer */ template <typename Dtype> class SigmoidCrossEntropyLossLayer : public LossLayer<Dtype> { public: explicit SigmoidCrossEntropyLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param), sigmoid_layer_(new SigmoidLayer<Dtype>(param)), sigmoid_output_(new Blob<Dtype>()) {} virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual inline LayerParameter_LayerType type() const { return LayerParameter_LayerType_SIGMOID_CROSS_ENTROPY_LOSS; } virtual inline int MaxTopBlobs() const { return 2; } // We cannot backpropagate to the labels; ignore force_backward for these // inputs. virtual inline bool AllowForceBackward(const int bottom_index) const { return bottom_index != 1; } protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); shared_ptr<SigmoidLayer<Dtype> > sigmoid_layer_; // sigmoid_output stores the output of the sigmoid layer. shared_ptr<Blob<Dtype> > sigmoid_output_; // Vector holders to call the underlying sigmoid layer forward and backward. vector<Blob<Dtype>*> sigmoid_bottom_vec_; vector<Blob<Dtype>*> sigmoid_top_vec_; }; /* MultiLabelLossLayer, now it only computes Sigmoid Loss, but could be extended to use HingeLoss */ template <typename Dtype> class MultiLabelLossLayer : public LossLayer<Dtype> { public: explicit MultiLabelLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param), sigmoid_layer_(new SigmoidLayer<Dtype>(param)), sigmoid_output_(new Blob<Dtype>()) {} virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual inline LayerParameter_LayerType type() const { return LayerParameter_LayerType_MULTI_LABEL_LOSS; } virtual inline int MaxTopBlobs() const { return 2; } // We cannot backpropagate to the labels; ignore force_backward for these // inputs. virtual inline bool AllowForceBackward(const int bottom_index) const { return bottom_index != 1; } protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); shared_ptr<SigmoidLayer<Dtype> > sigmoid_layer_; // sigmoid_output stores the output of the sigmoid layer. shared_ptr<Blob<Dtype> > sigmoid_output_; // Vector holders to call the underlying sigmoid layer forward and backward. vector<Blob<Dtype>*> sigmoid_bottom_vec_; vector<Blob<Dtype>*> sigmoid_top_vec_; }; /* EuclideanLossLayer Compute the L_2 distance between the two inputs. loss = (1/2 \sum_i (a_i - b_i)^2) a' = 1/I (a - b) */ template <typename Dtype> class EuclideanLossLayer : public LossLayer<Dtype> { public: explicit EuclideanLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param), diff_() {} virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual inline LayerParameter_LayerType type() const { return LayerParameter_LayerType_EUCLIDEAN_LOSS; } // Unlike most loss layers, in the EuclideanLossLayer we can backpropagate // to both inputs. virtual inline bool AllowForceBackward(const int bottom_index) const { return true; } protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); Blob<Dtype> diff_; }; /* InfogainLossLayer */ template <typename Dtype> class InfogainLossLayer : public LossLayer<Dtype> { public: explicit InfogainLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param), infogain_() {} virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual inline LayerParameter_LayerType type() const { return LayerParameter_LayerType_INFOGAIN_LOSS; } protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); Blob<Dtype> infogain_; }; /* HingeLossLayer */ template <typename Dtype> class HingeLossLayer : public LossLayer<Dtype> { public: explicit HingeLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param) {} virtual inline LayerParameter_LayerType type() const { return LayerParameter_LayerType_HINGE_LOSS; } protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); }; /* MultinomialLogisticLossLayer */ template <typename Dtype> class MultinomialLogisticLossLayer : public LossLayer<Dtype> { public: explicit MultinomialLogisticLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param) {} virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual inline LayerParameter_LayerType type() const { return LayerParameter_LayerType_MULTINOMIAL_LOGISTIC_LOSS; } protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom); }; /* AccuracyLayer Note: not an actual loss layer! Does not implement backwards step. Computes the accuracy of argmax(a) with respect to b. */ template <typename Dtype> class AccuracyLayer : public Layer<Dtype> { public: explicit AccuracyLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual inline LayerParameter_LayerType type() const { return LayerParameter_LayerType_ACCURACY; } virtual inline int ExactNumBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) { NOT_IMPLEMENTED; } int top_k_; }; /* MultiLabelAccuracyLayer Note: not an actual loss layer! Does not implement backwards step. Computes the accuracy of a with respect to b. */ template <typename Dtype> class MultiLabelAccuracyLayer : public Layer<Dtype> { public: explicit MultiLabelAccuracyLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual inline LayerParameter_LayerType type() const { return LayerParameter_LayerType_MULTI_LABEL_ACCURACY; } virtual inline int ExactNumBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) { NOT_IMPLEMENTED; } }; } // namespace caffe #endif // CAFFE_LOSS_LAYERS_HPP_
33.615836
78
0.730524
xiaomi646
d164bcc51b3bc70b7a3fbab916f75eba623a4f38
4,183
cpp
C++
MonoNative.Tests/mscorlib/System/Security/Cryptography/mscorlib_System_Security_Cryptography_MACTripleDES_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Security/Cryptography/mscorlib_System_Security_Cryptography_MACTripleDES_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Security/Cryptography/mscorlib_System_Security_Cryptography_MACTripleDES_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Security.Cryptography // Name: MACTripleDES // C++ Typed Name: mscorlib::System::Security::Cryptography::MACTripleDES #include <gtest/gtest.h> #include <mscorlib/System/Security/Cryptography/mscorlib_System_Security_Cryptography_MACTripleDES.h> #include <mscorlib/System/IO/mscorlib_System_IO_Stream.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Security { namespace Cryptography { //Constructors Tests //MACTripleDES() TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,DefaultConstructor) { mscorlib::System::Security::Cryptography::MACTripleDES *value = new mscorlib::System::Security::Cryptography::MACTripleDES(); EXPECT_NE(NULL, value->GetNativeObject()); } //MACTripleDES(std::vector<mscorlib::System::Byte*> rgbKey) TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,Constructor_2) { mscorlib::System::Security::Cryptography::MACTripleDES *value = new mscorlib::System::Security::Cryptography::MACTripleDES(); EXPECT_NE(NULL, value->GetNativeObject()); } //MACTripleDES(mscorlib::System::String strTripleDES, std::vector<mscorlib::System::Byte*> rgbKey) TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,Constructor_3) { mscorlib::System::Security::Cryptography::MACTripleDES *value = new mscorlib::System::Security::Cryptography::MACTripleDES(); EXPECT_NE(NULL, value->GetNativeObject()); } //Public Methods Tests // Method Initialize // Signature: TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,Initialize_Test) { } //Public Properties Tests // Property Padding // Return Type: mscorlib::System::Security::Cryptography::PaddingMode::__ENUM__ // Property Get Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_Padding_Test) { } // Property Padding // Return Type: mscorlib::System::Security::Cryptography::PaddingMode::__ENUM__ // Property Set Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,set_Padding_Test) { } // Property Key // Return Type: mscorlib::System::Byte* // Property Get Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_Key_Test) { } // Property Key // Return Type: mscorlib::System::Byte* // Property Set Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,set_Key_Test) { } // Property CanTransformMultipleBlocks // Return Type: mscorlib::System::Boolean // Property Get Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_CanTransformMultipleBlocks_Test) { } // Property CanReuseTransform // Return Type: mscorlib::System::Boolean // Property Get Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_CanReuseTransform_Test) { } // Property Hash // Return Type: mscorlib::System::Byte* // Property Get Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_Hash_Test) { } // Property HashSize // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_HashSize_Test) { } // Property InputBlockSize // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_InputBlockSize_Test) { } // Property OutputBlockSize // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_OutputBlockSize_Test) { } } } } }
25.662577
130
0.696629
brunolauze
d1694b72f720450f38bfa8b0d5c914f6ce7cc91b
2,128
cpp
C++
python/_nimblephysics/realtime/Ticker.cpp
jyf588/nimblephysics
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
[ "BSD-2-Clause" ]
2
2021-09-30T06:23:29.000Z
2022-03-09T09:59:09.000Z
python/_nimblephysics/realtime/Ticker.cpp
jyf588/nimblephysics
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
[ "BSD-2-Clause" ]
null
null
null
python/_nimblephysics/realtime/Ticker.cpp
jyf588/nimblephysics
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
[ "BSD-2-Clause" ]
1
2021-08-20T13:56:14.000Z
2021-08-20T13:56:14.000Z
#include <iostream> #include <Python.h> #include <dart/realtime/Ticker.hpp> #include <pybind11/functional.h> #include <pybind11/pybind11.h> namespace py = pybind11; namespace dart { namespace python { void Ticker(py::module& m) { ::py::class_<dart::realtime::Ticker, std::shared_ptr<dart::realtime::Ticker>>( m, "Ticker") .def(::py::init<s_t>(), ::py::arg("secondsPerTick")) .def( "registerTickListener", +[](dart::realtime::Ticker* self, std::function<void(long)> callback) -> void { std::function<void(long now)> wrappedCallback = [callback](long now) { /* Acquire GIL before calling Python code */ py::gil_scoped_acquire acquire; try { callback(now); } catch (::py::error_already_set& e) { if (e.matches(PyExc_KeyboardInterrupt)) { std::cout << "Nimble caught a keyboard interrupt in a " "callback from registerTickListener(). Exiting " "with code 0." << std::endl; exit(0); } else { std::cout << "Nimble caught an exception calling " "callback from registerTickListener():" << std::endl << std::string(e.what()) << std::endl; } } }; self->registerTickListener(wrappedCallback); }, ::py::arg("listener")) .def( "start", &dart::realtime::Ticker::start, ::py::call_guard<py::gil_scoped_release>()) .def("stop", &dart::realtime::Ticker::stop) .def("clear", &dart::realtime::Ticker::clear); } } // namespace python } // namespace dart
33.777778
80
0.43797
jyf588
d16aedd116d8d31f861454b4a121c38b77986f1a
436
cpp
C++
Codeforces/746A - Compote.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/746A - Compote.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/746A - Compote.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); #ifndef ONLINE_JUDGE freopen("files/input.txt", "r", stdin); freopen("files/output.txt", "w", stdout); #endif int a, b, c; cin >> a >> b >> c; int count = 0; while(a >= 1 && b >= 2 && c >= 4) { a--; b -= 2; c -= 4; count++; } cout << count * 7 << endl; return 0; }
18.166667
45
0.465596
naimulcsx
d172df46567e2c2e55e3d573eee798a578f58eb0
3,500
hpp
C++
sources/include/structure/parameter.hpp
sydelity-net/EDACurry
20cbf9835827e42efeb0b3686bf6b3e9d72417e9
[ "MIT" ]
null
null
null
sources/include/structure/parameter.hpp
sydelity-net/EDACurry
20cbf9835827e42efeb0b3686bf6b3e9d72417e9
[ "MIT" ]
null
null
null
sources/include/structure/parameter.hpp
sydelity-net/EDACurry
20cbf9835827e42efeb0b3686bf6b3e9d72417e9
[ "MIT" ]
null
null
null
/// @file parameter.hpp /// @author Enrico Fraccaroli (enrico.fraccaroli@gmail.com) /// @copyright Copyright (c) 2021 sydelity.net (info@sydelity.com) /// Distributed under the MIT License (MIT) (See accompanying LICENSE file or /// copy at http://opensource.org/licenses/MIT) #pragma once #include "features/object_reference.hpp" #include "features/named_object.hpp" #include "features/object_list.hpp" #include "object.hpp" #include "enums.hpp" #include "value.hpp" namespace edacurry::structure { /// @brief Represent a parameter. class Parameter : public Object, public features::ObjectReference { public: /// @brief Construct a new Parameter object. /// @param left the right value of the parameter. /// @param right the initial right value of the parameter. /// @param type the parameter's type. /// @param reference The reference to another parameter. /// @param hide_left hide the left-hand side value during code generation. Parameter(Value *left, Value *right, ParameterType type = param_assign, structure::Object *reference = nullptr, bool hide_left = false); /// @brief Destroy the Parameter object. ~Parameter() override; /// @brief Returns the initial value of the parameter. /// @return The initial value of the parameter. Value *getRight() const; /// @brief Sets the initial value of the data parameter. /// @param value the initial value of the data parameter to be set. /// @return The old initial value of the data parameter if it is /// different from the new one, nullptr otherwise. Value *setRight(Value *value); /// @brief Returns the initial value of the parameter. /// @return The initial value of the parameter. Value *getLeft() const; /// @brief Sets the initial value of the data parameter. /// @param value the initial value of the data parameter to be set. /// @return The old initial value of the data parameter if it is /// different from the new one, nullptr otherwise. Value *setLeft(Value *value); /// @brief Sets the type of parameter. /// @param type the parameter's type. inline void setType(ParameterType type) { _type = type; } /// @brief Returns the type of parameter. /// @return the type of parameter. inline auto getType() const { return _type; } /// @brief Sets if the left-hand side value is hidden during code generation. /// @param hide_left if the left-hand side value should be hidden. inline void setHideLeft(bool hide_left) { _hide_left = hide_left; } /// @brief Sets if the left-hand side value is hidden during code generation. /// @return if the left-hand side value should be hidden. inline bool getHideLeft() const { return _hide_left; } /// @brief Provides a string representation of the object for **debugging** purposes. /// @return the string representation. std::string toString() const override; /// @brief Accepts a visitor. /// @param visitor the visitor. inline void accept(features::Visitor *visitor) const override { visitor->visit(this); } private: /// The value on the left of the parameter. Value *_left; /// The value on the right of the parameter. Value *_right; /// The type of parameter. ParameterType _type; /// Hide the left-hand side value during code generation. bool _hide_left; }; } // namespace edacurry::structure
33.980583
140
0.679714
sydelity-net
ab6c16aacbe6605846db36584cbe96ea1a14369a
3,544
hpp
C++
test/unit/detail/load_store_matrix_coop_sync.hpp
mkarunan/rocWMMA
390a2e793699a1e17c18e46d7fe51e245907f012
[ "MIT" ]
null
null
null
test/unit/detail/load_store_matrix_coop_sync.hpp
mkarunan/rocWMMA
390a2e793699a1e17c18e46d7fe51e245907f012
[ "MIT" ]
1
2022-03-16T20:41:26.000Z
2022-03-16T20:41:26.000Z
test/unit/detail/load_store_matrix_coop_sync.hpp
mkarunan/rocWMMA
390a2e793699a1e17c18e46d7fe51e245907f012
[ "MIT" ]
2
2022-03-17T16:47:29.000Z
2022-03-18T14:12:22.000Z
/******************************************************************************* * * MIT License * * Copyright 2021-2022 Advanced Micro Devices, Inc. * * 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. * *******************************************************************************/ #ifndef ROCWMMA_DETAIL_LOAD_STORE_MATRIX_COOP_SYNC_HPP #define ROCWMMA_DETAIL_LOAD_STORE_MATRIX_COOP_SYNC_HPP #include "device/load_store_matrix_coop_sync.hpp" #include "load_store_matrix_sync.hpp" namespace rocwmma { template <uint32_t BlockM, uint32_t BlockN, typename DataT, typename Layout> struct LoadStoreMatrixCoopSyncKernelA final : public LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout> { private: using Base = LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout>; protected: typename Base::KernelFunc kernelImpl() const final { return typename Base::KernelFunc(LoadStoreMatrixCoopSyncA<BlockM, BlockN, DataT, Layout>); } }; template <uint32_t BlockM, uint32_t BlockN, typename DataT, typename Layout> struct LoadStoreMatrixCoopSyncKernelB final : public LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout> { private: using Base = LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout>; protected: typename Base::KernelFunc kernelImpl() const final { return typename Base::KernelFunc(LoadStoreMatrixCoopSyncB<BlockM, BlockN, DataT, Layout>); } }; template <uint32_t BlockM, uint32_t BlockN, typename DataT, typename Layout> struct LoadStoreMatrixCoopSyncKernelAcc final : public LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout> { private: using Base = LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout>; protected: typename Base::KernelFunc kernelImpl() const final { return typename Base::KernelFunc( LoadStoreMatrixCoopSyncAcc<BlockM, BlockN, DataT, Layout>); } }; using LoadStoreMatrixCoopSyncGeneratorA = LoadStoreMatrixSyncGenerator<LoadStoreMatrixCoopSyncKernelA>; using LoadStoreMatrixCoopSyncGeneratorB = LoadStoreMatrixSyncGenerator<LoadStoreMatrixCoopSyncKernelB>; using LoadStoreMatrixCoopSyncGeneratorAcc = LoadStoreMatrixSyncGenerator<LoadStoreMatrixCoopSyncKernelAcc>; } // namespace rocwmma #endif // ROCWMMA_DETAIL_LOAD_STORE_MATRIX_COOP_SYNC_HPP
38.945055
99
0.69921
mkarunan
ab6c6cdf53c0c6cc26129c919f5797523bf0f34b
1,178
cpp
C++
Leetcode/WordSearch.cpp
zhanghuanzj/C-
b271de02885466e97d6a2072f4f93f87625834e4
[ "Apache-2.0" ]
null
null
null
Leetcode/WordSearch.cpp
zhanghuanzj/C-
b271de02885466e97d6a2072f4f93f87625834e4
[ "Apache-2.0" ]
null
null
null
Leetcode/WordSearch.cpp
zhanghuanzj/C-
b271de02885466e97d6a2072f4f93f87625834e4
[ "Apache-2.0" ]
null
null
null
class Solution { public: bool exist(vector<vector<char> > &board, string word) { if(board.empty()) return false; if(word.empty()) return true; int m = board.size(); int n = board.front().size(); vector<vector<bool>> visited(m,vector<bool>(n,false)); for(int i=0;i<m;++i){ for(int j=0;j<n;++j){ if(board[i][j]==word[0]&&dfs(board,visited,i,j,1,word)){ return true; } } } return false; } bool dfs(const vector<vector<char> > &board,vector<vector<bool>> &visited,int x,int y,int n,const string& word){ if(n==word.size()) return true; visited[x][y] = true; int dx[] = {0,0,1,-1}; int dy[] = {1,-1,0,0}; for(int i=0;i<4;++i){ int px = x+dx[i]; int py = y+dy[i]; if(px>=0&&px<board.size()&&py>=0&&py<board.front().size()&&word[n]==board[px][py]&&!visited[px][py]){ if(dfs(board,visited,px,py,n+1,word)){ return true; } } } visited[x][y] = false; return false; } };
33.657143
116
0.457555
zhanghuanzj
ab7130c5aab5368ffa946eba554bcbdeb4c3b3c7
1,234
cpp
C++
Dynamic Range Sum Queries/sol.cpp
glaucogithub/CSES-Problem-Set
62e96c5aedf920dac339cf1a5f1ff8665735b766
[ "MIT" ]
1
2022-01-14T00:42:32.000Z
2022-01-14T00:42:32.000Z
Dynamic Range Sum Queries/sol.cpp
glaucogithub/CSES-Problem-Set
62e96c5aedf920dac339cf1a5f1ff8665735b766
[ "MIT" ]
null
null
null
Dynamic Range Sum Queries/sol.cpp
glaucogithub/CSES-Problem-Set
62e96c5aedf920dac339cf1a5f1ff8665735b766
[ "MIT" ]
null
null
null
// author: glaucoacassioc // created on: September 22, 2021 1:04 AM // Problem: Dynamic Range Sum Queries // URL: https://cses.fi/problemset/task/1648/ // Time Limit: 1000 ms // Memory Limit: 512 MB #include <bits/stdc++.h> using namespace std; #define LSONE(S) ((S & (-S))) mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); vector<int64_t> ft, v; void update(int k, int val) { for (; k < (int)ft.size(); k += LSONE(k)) { ft[k] += val; } } void build(int n) { ft.assign(n + 1, 0); for (int i = 1; i <= n; ++i) { update(i, v[i]); } } int64_t query(int b) { int64_t sum = 0; for (; b; b -= LSONE(b)) { sum += ft[b]; } return sum; } int64_t query(int l, int r) { return query(r) - (l == 1 ? 0 : query(l - 1)); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); #endif int n, q; cin >> n >> q; v.assign(n + 1, 0); for (int i = 1; i <= n; ++i) { cin >> v[i]; } build(n); while (q--) { int op; cin >> op; if (op == 1) { int k, u; cin >> k >> u; update(k, u - v[k]); v[k] = u; } else { int l, r; cin >> l >> r; cout << query(l, r) << '\n'; } } }
17.138889
71
0.536467
glaucogithub
ab730d7d79f157393452fa99ba3c334e8a70b274
3,603
cpp
C++
onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorMatMul.cpp
MaximKalininMS/onnxruntime
1d79926d273d01817ce93f001f36f417ab05f8a0
[ "MIT" ]
4
2019-06-06T23:48:57.000Z
2021-06-03T11:51:45.000Z
onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorMatMul.cpp
Montaer/onnxruntime
6dc25a60f8b058a556964801d99d5508641dcf69
[ "MIT" ]
10
2019-03-25T21:47:46.000Z
2019-04-30T02:33:05.000Z
onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorMatMul.cpp
Montaer/onnxruntime
6dc25a60f8b058a556964801d99d5508641dcf69
[ "MIT" ]
3
2019-05-07T01:29:04.000Z
2020-08-09T08:36:12.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "precomp.h" namespace Dml { class DmlOperatorMatMul : public DmlOperator { enum InputTensors { IN_A, IN_B }; public: DmlOperatorMatMul(const MLOperatorKernelCreationContext& kernelInfo) : DmlOperator(kernelInfo) { // MatMul has two inputs, but DML GEMM requires 3 input bindings (a null binding for the C Tensor). ML_CHECK_VALID_ARGUMENT(kernelInfo.GetInputCount() == 2); std::vector<std::optional<uint32_t>> inputIndices = { 0, 1, std::nullopt }; DmlOperator::Initialize(kernelInfo, inputIndices); std::vector<DimensionType> inputShape0 = kernelInfo.GetTensorShapeDescription().GetInputTensorShape(0); std::vector<DimensionType> inputShape1 = kernelInfo.GetTensorShapeDescription().GetInputTensorShape(1); std::vector<DimensionType> outputShape = kernelInfo.GetTensorShapeDescription().GetOutputTensorShape(0); // Get the padded input shapes and undo the effect of padding removal from the output shape if (inputShape1.size() == 1) { inputShape1.push_back(1); outputShape.push_back(1); } if (inputShape0.size() == 1) { inputShape0.insert(inputShape0.begin(), 1); outputShape.insert(outputShape.end() - 1, 1); } // Remove the batch dimensions from each input, then re-add the broadcasted batch dimensions // based on the output shape inputShape0.erase(inputShape0.begin(), inputShape0.end() - 2); inputShape1.erase(inputShape1.begin(), inputShape1.end() - 2); inputShape0.insert(inputShape0.begin(), outputShape.begin(), outputShape.end() - 2); inputShape1.insert(inputShape1.begin(), outputShape.begin(), outputShape.end() - 2); // Initialize the input descriptions with broadcasting m_inputTensorDescs[0] = CreateTensorDescFromInput(kernelInfo, 0, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, inputShape0); m_inputTensorDescs[1] = CreateTensorDescFromInput(kernelInfo, 1, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, inputShape1); // Initialize the output description while overriding the shape m_outputTensorDescs[0] = CreateTensorDescFromOutput(kernelInfo, 0, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, outputShape); std::vector<DML_TENSOR_DESC> inputDescs = GetDmlInputDescs(); std::vector<DML_TENSOR_DESC> outputDescs = GetDmlOutputDescs(); std::optional<ActivationOperatorDesc> fusedActivation = FusionHelpers::TryGetFusedActivationDesc(kernelInfo); DML_OPERATOR_DESC fusedActivationDmlDesc = fusedActivation ? fusedActivation->GetDmlDesc() : DML_OPERATOR_DESC(); DML_GEMM_OPERATOR_DESC gemmDesc = {}; gemmDesc.ATensor = &inputDescs[0]; gemmDesc.BTensor = &inputDescs[1]; gemmDesc.CTensor = nullptr; gemmDesc.OutputTensor = &outputDescs[0]; gemmDesc.TransA = DML_MATRIX_TRANSFORM_NONE; gemmDesc.TransB = DML_MATRIX_TRANSFORM_NONE; gemmDesc.Alpha = 1.0f; gemmDesc.Beta = 0.0f; gemmDesc.FusedActivation = fusedActivation ? &fusedActivationDmlDesc : nullptr; DML_OPERATOR_DESC opDesc = { DML_OPERATOR_GEMM, &gemmDesc }; SetDmlOperatorDesc(opDesc, kernelInfo); } }; DML_OP_DEFINE_CREATION_FUNCTION(MatMul, DmlOperatorMatMul); DML_OP_DEFINE_CREATION_FUNCTION(FusedMatMul, DmlOperatorMatMul); } // namespace Dml
44.481481
154
0.706356
MaximKalininMS
ab73bc776134f3e88c7e8b1c24b2ba0d167f698b
1,740
cpp
C++
ural/1706.cpp
jffifa/algo-solution
af2400d6071ee8f777f9473d6a34698ceef08355
[ "MIT" ]
5
2015-07-14T10:29:25.000Z
2016-10-11T12:45:18.000Z
ural/1706.cpp
jffifa/algo-solution
af2400d6071ee8f777f9473d6a34698ceef08355
[ "MIT" ]
null
null
null
ural/1706.cpp
jffifa/algo-solution
af2400d6071ee8f777f9473d6a34698ceef08355
[ "MIT" ]
3
2016-08-23T01:05:26.000Z
2017-05-28T02:04:20.000Z
#include<iostream>//boj 1178 #include<cstdio> #include<cstring> #include<algorithm> #include<queue> #include<cmath> using namespace std; typedef long long ll; const int maxn =10100; const int maxv =10100; int a[maxn],sa[maxn],container[maxn],wy[maxn],wv[maxn],wx[maxv],rk[maxn],h[maxn]; int cmp(int *r,int a,int b,int l) { return (r[a]==r[b]) &&(r[a+l]==r[b+l]); } void suffix(int *r, int n,int *sa,int m) { int i,j,*t,*x=wx,*y=wy,p; memset(container,0,sizeof(int)*m); for(i=0; i<n; i++) container[x[i]=r[i]]++; for(i=1; i<m; i++) container[i]+=container[i-1]; for(i=n-1; i>=0; i--) sa[--container[x[i]]]=i; for(p=0,j=1; p<n; j<<=1, m=p) { for(p=0,i=n-j; i<n; i++) y[p++]=i; for(i=0; i<n; i++) if(sa[i]>=j) y[p++]=sa[i]-j; for(i=0; i<n; i++) wv[i]=x[y[i]]; memset(container,0,sizeof(int)*m); for(i=0; i<n; i++) container[wv[i]]++; for(i=1; i<m; i++) container[i]+=container[i-1]; for(i=n-1;i>=0; i--) sa[--container[wv[i]]]=y[i]; for(t=x,x=y,y=t,x[sa[0]]=0,p=1,i=1;i<n; i++) x[sa[i]]=cmp(y,sa[i],sa[i-1],j)?p-1:p++; } } void cal(int *r,int *sa,int n) { int i,j,k=0; for(i=1; i<=n; i++) rk[sa[i]]=i; for(i=0; i<n; h[rk[i++]]=k) for(k?k--:0,j=sa[rk[i]-1]; r[i+k]==r[j+k]; k++); } char ch[10000]; int main() { //freopen("in","r",stdin); //freopen("std","w",stdout); int i,j,k; int n,m; scanf("%d", &k); scanf("%s",ch); int len=strlen(ch); for(i=0,j=len; i<len; i++,j++) ch[j]=ch[i]; ch[j]=0; n=len*2; for(i=0; i<n;i++) { a[i]=ch[i]; } for(i=0; i<len; i++) { int tp=a[i+k]; a[i+k]=0; suffix(&a[i],k+1,sa,300); cal(&a[i],sa,k); int ans=0; for(j=1; j<=k; j++) ans+=h[j]; ans=k*(k+1)/2-ans; cout<<ans; if(i==len-1) puts(""); else printf(" "); a[i+k]=tp; } }
21.219512
81
0.520115
jffifa
ab772c758b026ba889a5aea1ba4ca80c8e9f811f
34,224
hpp
C++
include/ldaplusplus/utils.hpp
angeloskath/supervised-lda
fe3a39bb0d6c7d0c2a33f069440869ad70774da8
[ "MIT" ]
22
2017-05-25T11:59:02.000Z
2021-08-30T08:51:41.000Z
include/ldaplusplus/utils.hpp
angeloskath/supervised-lda
fe3a39bb0d6c7d0c2a33f069440869ad70774da8
[ "MIT" ]
22
2016-06-30T15:51:18.000Z
2021-12-06T10:43:16.000Z
include/ldaplusplus/utils.hpp
angeloskath/supervised-lda
fe3a39bb0d6c7d0c2a33f069440869ad70774da8
[ "MIT" ]
4
2017-09-28T14:58:01.000Z
2020-12-21T14:22:38.000Z
#ifndef _LDAPLUSPLUS_UTILS_HPP_ #define _LDAPLUSPLUS_UTILS_HPP_ #include <cmath> #include <memory> #include <mutex> #include <array> #include <Eigen/Core> namespace ldaplusplus { namespace math_utils { static const std::array<double, 1024> exp_lut = { 1.000000000000000000e+00, 1.000977995032110268e+00, 1.001956946538503423e+00, 1.002936855454606535e+00, 1.003917722716761274e+00, 1.004899549262225911e+00, 1.005882336029174207e+00, 1.006866083956698077e+00, 1.007850793984808035e+00, 1.008836467054433639e+00, 1.009823104107424596e+00, 1.010810706086551880e+00, 1.011799273935508392e+00, 1.012788808598910073e+00, 1.013779311022296792e+00, 1.014770782152132789e+00, 1.015763222935808230e+00, 1.016756634321639652e+00, 1.017751017258871515e+00, 1.018746372697675762e+00, 1.019742701589154477e+00, 1.020740004885339447e+00, 1.021738283539193493e+00, 1.022737538504611798e+00, 1.023737770736421915e+00, 1.024738981190385756e+00, 1.025741170823199822e+00, 1.026744340592495863e+00, 1.027748491456842661e+00, 1.028753624375746245e+00, 1.029759740309651228e+00, 1.030766840219941249e+00, 1.031774925068940307e+00, 1.032783995819913647e+00, 1.033794053437068428e+00, 1.034805098885555052e+00, 1.035817133131467616e+00, 1.036830157141844788e+00, 1.037844171884671818e+00, 1.038859178328879640e+00, 1.039875177444347321e+00, 1.040892170201902722e+00, 1.041910157573322726e+00, 1.042929140531334564e+00, 1.043949120049617374e+00, 1.044970097102801754e+00, 1.045992072666471984e+00, 1.047015047717166691e+00, 1.048039023232378630e+00, 1.049064000190557788e+00, 1.050089979571109833e+00, 1.051116962354399220e+00, 1.052144949521748529e+00, 1.053173942055440682e+00, 1.054203940938718942e+00, 1.055234947155788250e+00, 1.056266961691815665e+00, 1.057299985532932585e+00, 1.058334019666233861e+00, 1.059369065079780903e+00, 1.060405122762600127e+00, 1.061442193704686288e+00, 1.062480278897001806e+00, 1.063519379331478110e+00, 1.064559496001017402e+00, 1.065600629899492224e+00, 1.066642782021747449e+00, 1.067685953363600948e+00, 1.068730144921844483e+00, 1.069775357694244589e+00, 1.070821592679543466e+00, 1.071868850877460533e+00, 1.072917133288692426e+00, 1.073966440914914777e+00, 1.075016774758782656e+00, 1.076068135823932126e+00, 1.077120525114980021e+00, 1.078173943637526611e+00, 1.079228392398154712e+00, 1.080283872404432577e+00, 1.081340384664913001e+00, 1.082397930189135327e+00, 1.083456509987626770e+00, 1.084516125071902204e+00, 1.085576776454466152e+00, 1.086638465148812793e+00, 1.087701192169428399e+00, 1.088764958531790450e+00, 1.089829765252370297e+00, 1.090895613348632942e+00, 1.091962503839038812e+00, 1.093030437743044203e+00, 1.094099416081102172e+00, 1.095169439874664308e+00, 1.096240510146180736e+00, 1.097312627919101669e+00, 1.098385794217878519e+00, 1.099460010067964122e+00, 1.100535276495814507e+00, 1.101611594528889571e+00, 1.102688965195653736e+00, 1.103767389525577958e+00, 1.104846868549139272e+00, 1.105927403297823020e+00, 1.107008994804122848e+00, 1.108091644101542705e+00, 1.109175352224596844e+00, 1.110260120208811818e+00, 1.111345949090726037e+00, 1.112432839907892657e+00, 1.113520793698878908e+00, 1.114609811503268100e+00, 1.115699894361659616e+00, 1.116791043315671139e+00, 1.117883259407939311e+00, 1.118976543682119518e+00, 1.120070897182888547e+00, 1.121166320955944595e+00, 1.122262816048008816e+00, 1.123360383506825988e+00, 1.124459024381165184e+00, 1.125558739720821544e+00, 1.126659530576616719e+00, 1.127761398000400428e+00, 1.128864343045050456e+00, 1.129968366764475096e+00, 1.131073470213612486e+00, 1.132179654448433048e+00, 1.133286920525939934e+00, 1.134395269504169912e+00, 1.135504702442194480e+00, 1.136615220400120752e+00, 1.137726824439093010e+00, 1.138839515621292930e+00, 1.139953295009941581e+00, 1.141068163669298974e+00, 1.142184122664666734e+00, 1.143301173062388099e+00, 1.144419315929849024e+00, 1.145538552335479299e+00, 1.146658883348754321e+00, 1.147780310040194429e+00, 1.148902833481367791e+00, 1.150026454744889959e+00, 1.151151174904425867e+00, 1.152276995034690277e+00, 1.153403916211449332e+00, 1.154531939511520555e+00, 1.155661066012775517e+00, 1.156791296794139168e+00, 1.157922632935592278e+00, 1.159055075518171440e+00, 1.160188625623970404e+00, 1.161323284336141404e+00, 1.162459052738896270e+00, 1.163595931917506432e+00, 1.164733922958305579e+00, 1.165873026948688995e+00, 1.167013244977116226e+00, 1.168154578133110855e+00, 1.169297027507261832e+00, 1.170440594191225259e+00, 1.171585279277724378e+00, 1.172731083860551582e+00, 1.173878009034568626e+00, 1.175026055895707744e+00, 1.176175225540974090e+00, 1.177325519068444182e+00, 1.178476937577269901e+00, 1.179629482167676935e+00, 1.180783153940967667e+00, 1.181937953999521618e+00, 1.183093883446795669e+00, 1.184250943387326727e+00, 1.185409134926731500e+00, 1.186568459171707834e+00, 1.187728917230036485e+00, 1.188890510210581342e+00, 1.190053239223290316e+00, 1.191217105379197339e+00, 1.192382109790423028e+00, 1.193548253570175355e+00, 1.194715537832750751e+00, 1.195883963693536112e+00, 1.197053532269008791e+00, 1.198224244676737937e+00, 1.199396102035385825e+00, 1.200569105464708963e+00, 1.201743256085558542e+00, 1.202918555019882207e+00, 1.204095003390724949e+00, 1.205272602322229991e+00, 1.206451352939639676e+00, 1.207631256369297246e+00, 1.208812313738647726e+00, 1.209994526176237706e+00, 1.211177894811718669e+00, 1.212362420775846328e+00, 1.213548105200482397e+00, 1.214734949218595261e+00, 1.215922953964261755e+00, 1.217112120572667600e+00, 1.218302450180108965e+00, 1.219493943923992907e+00, 1.220686602942839150e+00, 1.221880428376280747e+00, 1.223075421365065640e+00, 1.224271583051056878e+00, 1.225468914577234614e+00, 1.226667417087696776e+00, 1.227867091727659954e+00, 1.229067939643461393e+00, 1.230269961982558780e+00, 1.231473159893532010e+00, 1.232677534526085195e+00, 1.233883087031045545e+00, 1.235089818560366925e+00, 1.236297730267128969e+00, 1.237506823305539294e+00, 1.238717098830934837e+00, 1.239928557999781411e+00, 1.241141201969676811e+00, 1.242355031899350593e+00, 1.243570048948665407e+00, 1.244786254278618332e+00, 1.246003649051341977e+00, 1.247222234430105381e+00, 1.248442011579315558e+00, 1.249662981664517947e+00, 1.250885145852397962e+00, 1.252108505310782105e+00, 1.253333061208639077e+00, 1.254558814716080661e+00, 1.255785767004363285e+00, 1.257013919245888234e+00, 1.258243272614204322e+00, 1.259473828284007002e+00, 1.260705587431141694e+00, 1.261938551232603123e+00, 1.263172720866537091e+00, 1.264408097512241813e+00, 1.265644682350168804e+00, 1.266882476561923987e+00, 1.268121481330269251e+00, 1.269361697839122449e+00, 1.270603127273560284e+00, 1.271845770819817423e+00, 1.273089629665289824e+00, 1.274334704998533629e+00, 1.275580998009267830e+00, 1.276828509888375152e+00, 1.278077241827902721e+00, 1.279327195021063623e+00, 1.280578370662237786e+00, 1.281830769946973314e+00, 1.283084394071987600e+00, 1.284339244235168209e+00, 1.285595321635574440e+00, 1.286852627473438426e+00, 1.288111162950165367e+00, 1.289370929268336408e+00, 1.290631927631708420e+00, 1.291894159245215112e+00, 1.293157625314969250e+00, 1.294422327048262655e+00, 1.295688265653568649e+00, 1.296955442340541387e+00, 1.298223858320018742e+00, 1.299493514804022753e+00, 1.300764413005760733e+00, 1.302036554139626157e+00, 1.303309939421200658e+00, 1.304584570067254479e+00, 1.305860447295748017e+00, 1.307137572325832497e+00, 1.308415946377851968e+00, 1.309695570673343301e+00, 1.310976446435038634e+00, 1.312258574886865814e+00, 1.313541957253949288e+00, 1.314826594762612100e+00, 1.316112488640376332e+00, 1.317399640115964887e+00, 1.318688050419302149e+00, 1.319977720781515540e+00, 1.321268652434935964e+00, 1.322560846613100471e+00, 1.323854304550751593e+00, 1.325149027483840003e+00, 1.326445016649525188e+00, 1.327742273286175889e+00, 1.329040798633372544e+00, 1.330340593931907733e+00, 1.331641660423787732e+00, 1.332943999352233400e+00, 1.334247611961681068e+00, 1.335552499497784540e+00, 1.336858663207415976e+00, 1.338166104338666340e+00, 1.339474824140847842e+00, 1.340784823864494379e+00, 1.342096104761362874e+00, 1.343408668084433932e+00, 1.344722515087914516e+00, 1.346037647027237272e+00, 1.347354065159063197e+00, 1.348671770741282527e+00, 1.349990765033014739e+00, 1.351311049294611877e+00, 1.352632624787657667e+00, 1.353955492774970404e+00, 1.355279654520602728e+00, 1.356605111289844068e+00, 1.357931864349220863e+00, 1.359259914966498561e+00, 1.360589264410682508e+00, 1.361919913952018835e+00, 1.363251864861995788e+00, 1.364585118413345954e+00, 1.365919675880045814e+00, 1.367255538537318182e+00, 1.368592707661632879e+00, 1.369931184530708501e+00, 1.371270970423512425e+00, 1.372612066620263693e+00, 1.373954474402432790e+00, 1.375298195052744088e+00, 1.376643229855176065e+00, 1.377989580094962641e+00, 1.379337247058595173e+00, 1.380686232033823124e+00, 1.382036536309655395e+00, 1.383388161176360986e+00, 1.384741107925471670e+00, 1.386095377849781762e+00, 1.387450972243349678e+00, 1.388807892401500377e+00, 1.390166139620824470e+00, 1.391525715199181779e+00, 1.392886620435700218e+00, 1.394248856630779132e+00, 1.395612425086089514e+00, 1.396977327104575117e+00, 1.398343563990454008e+00, 1.399711137049220122e+00, 1.401080047587643707e+00, 1.402450296913773320e+00, 1.403821886336936497e+00, 1.405194817167741750e+00, 1.406569090718078785e+00, 1.407944708301120951e+00, 1.409321671231325457e+00, 1.410699980824435151e+00, 1.412079638397479409e+00, 1.413460645268776350e+00, 1.414843002757932622e+00, 1.416226712185845837e+00, 1.417611774874705466e+00, 1.418998192147993942e+00, 1.420385965330488220e+00, 1.421775095748260442e+00, 1.423165584728680377e+00, 1.424557433600415424e+00, 1.425950643693432385e+00, 1.427345216338999023e+00, 1.428741152869684949e+00, 1.430138454619362953e+00, 1.431537122923210559e+00, 1.432937159117710912e+00, 1.434338564540654337e+00, 1.435741340531139221e+00, 1.437145488429574014e+00, 1.438551009577677897e+00, 1.439957905318482112e+00, 1.441366176996331516e+00, 1.442775825956885694e+00, 1.444186853547120286e+00, 1.445599261115328327e+00, 1.447013050011121349e+00, 1.448428221585431164e+00, 1.449844777190509859e+00, 1.451262718179933353e+00, 1.452682045908600061e+00, 1.454102761732734450e+00, 1.455524867009887036e+00, 1.456948363098935717e+00, 1.458373251360087552e+00, 1.459799533154880313e+00, 1.461227209846182706e+00, 1.462656282798196594e+00, 1.464086753376458105e+00, 1.465518622947838745e+00, 1.466951892880546948e+00, 1.468386564544128747e+00, 1.469822639309470436e+00, 1.471260118548798346e+00, 1.472699003635681070e+00, 1.474139295945030570e+00, 1.475580996853103288e+00, 1.477024107737501923e+00, 1.478468629977176318e+00, 1.479914564952424794e+00, 1.481361914044895922e+00, 1.482810678637589197e+00, 1.484260860114857028e+00, 1.485712459862404966e+00, 1.487165479267294810e+00, 1.488619919717944162e+00, 1.490075782604128651e+00, 1.491533069316983262e+00, 1.492991781249003447e+00, 1.494451919794046457e+00, 1.495913486347332677e+00, 1.497376482305447176e+00, 1.498840909066340599e+00, 1.500306768029331161e+00, 1.501774060595105320e+00, 1.503242788165719546e+00, 1.504712952144601212e+00, 1.506184553936550596e+00, 1.507657594947741764e+00, 1.509132076585724125e+00, 1.510608000259423100e+00, 1.512085367379143008e+00, 1.513564179356566397e+00, 1.515044437604757155e+00, 1.516526143538160953e+00, 1.518009298572606580e+00, 1.519493904125307715e+00, 1.520979961614864262e+00, 1.522467472461262794e+00, 1.523956438085879439e+00, 1.525446859911479880e+00, 1.526938739362221575e+00, 1.528432077863654648e+00, 1.529926876842723216e+00, 1.531423137727767392e+00, 1.532920861948523950e+00, 1.534420050936127655e+00, 1.535920706123113710e+00, 1.537422828943417308e+00, 1.538926420832376962e+00, 1.540431483226734288e+00, 1.541938017564636221e+00, 1.543446025285636569e+00, 1.544955507830696240e+00, 1.546466466642186122e+00, 1.547978903163887310e+00, 1.549492818840993102e+00, 1.551008215120110112e+00, 1.552525093449259819e+00, 1.554043455277879682e+00, 1.555563302056824915e+00, 1.557084635238369597e+00, 1.558607456276208003e+00, 1.560131766625456162e+00, 1.561657567742653185e+00, 1.563184861085763044e+00, 1.564713648114174793e+00, 1.566243930288705677e+00, 1.567775709071600909e+00, 1.569308985926536115e+00, 1.570843762318618220e+00, 1.572380039714387445e+00, 1.573917819581817312e+00, 1.575457103390318192e+00, 1.576997892610736862e+00, 1.578540188715358505e+00, 1.580083993177908486e+00, 1.581629307473553459e+00, 1.583176133078902703e+00, 1.584724471472009455e+00, 1.586274324132372682e+00, 1.587825692540938194e+00, 1.589378578180100199e+00, 1.590932982533702855e+00, 1.592488907087041161e+00, 1.594046353326863175e+00, 1.595605322741370236e+00, 1.597165816820220074e+00, 1.598727837054526590e+00, 1.600291384936862515e+00, 1.601856461961259637e+00, 1.603423069623211461e+00, 1.604991209419673881e+00, 1.606560882849066951e+00, 1.608132091411276221e+00, 1.609704836607653400e+00, 1.611279119941019689e+00, 1.612854942915664891e+00, 1.614432307037350967e+00, 1.616011213813311809e+00, 1.617591664752255909e+00, 1.619173661364366579e+00, 1.620757205161304615e+00, 1.622342297656209409e+00, 1.623928940363699613e+00, 1.625517134799875363e+00, 1.627106882482319827e+00, 1.628698184930099879e+00, 1.630291043663768535e+00, 1.631885460205365623e+00, 1.633481436078419557e+00, 1.635078972807948450e+00, 1.636678071920462774e+00, 1.638278734943964698e+00, 1.639880963407951864e+00, 1.641484758843416936e+00, 1.643090122782850715e+00, 1.644697056760241693e+00, 1.646305562311079607e+00, 1.647915640972355433e+00, 1.649527294282563172e+00, 1.651140523781701841e+00, 1.652755331011276363e+00, 1.654371717514299123e+00, 1.655989684835291964e+00, 1.657609234520286634e+00, 1.659230368116827670e+00, 1.660853087173972398e+00, 1.662477393242293600e+00, 1.664103287873880177e+00, 1.665730772622339151e+00, 1.667359849042796993e+00, 1.668990518691900959e+00, 1.670622783127820865e+00, 1.672256643910250196e+00, 1.673892102600407883e+00, 1.675529160761039638e+00, 1.677167819956419725e+00, 1.678808081752352521e+00, 1.680449947716172732e+00, 1.682093419416749169e+00, 1.683738498424484087e+00, 1.685385186311316064e+00, 1.687033484650720894e+00, 1.688683395017712918e+00, 1.690334918988847468e+00, 1.691988058142221085e+00, 1.693642814057473966e+00, 1.695299188315791517e+00, 1.696957182499905015e+00, 1.698616798194093835e+00, 1.700278036984186558e+00, 1.701940900457563410e+00, 1.703605390203156267e+00, 1.705271507811451093e+00, 1.706939254874489942e+00, 1.708608632985871179e+00, 1.710279643740752142e+00, 1.711952288735850036e+00, 1.713626569569443481e+00, 1.715302487841374512e+00, 1.716980045153049694e+00, 1.718659243107441892e+00, 1.720340083309091384e+00, 1.722022567364107859e+00, 1.723706696880171751e+00, 1.725392473466535792e+00, 1.727079898734026564e+00, 1.728768974295046057e+00, 1.730459701763572999e+00, 1.732152082755164635e+00, 1.733846118886958720e+00, 1.735541811777673971e+00, 1.737239163047612056e+00, 1.738938174318660046e+00, 1.740638847214290630e+00, 1.742341183359564338e+00, 1.744045184381131319e+00, 1.745750851907231782e+00, 1.747458187567699328e+00, 1.749167192993960951e+00, 1.750877869819039478e+00, 1.752590219677554240e+00, 1.754304244205723951e+00, 1.756019945041367158e+00, 1.757737323823904463e+00, 1.759456382194358959e+00, 1.761177121795359790e+00, 1.762899544271141927e+00, 1.764623651267548610e+00, 1.766349444432032456e+00, 1.768076925413657907e+00, 1.769806095863101225e+00, 1.771536957432653825e+00, 1.773269511776222718e+00, 1.775003760549332510e+00, 1.776739705409126735e+00, 1.778477348014370074e+00, 1.780216690025448578e+00, 1.781957733104373443e+00, 1.783700478914779897e+00, 1.785444929121931423e+00, 1.787191085392719092e+00, 1.788938949395664890e+00, 1.790688522800922389e+00, 1.792439807280278741e+00, 1.794192804507155570e+00, 1.795947516156611412e+00, 1.797703943905343493e+00, 1.799462089431687950e+00, 1.801221954415622939e+00, 1.802983540538769303e+00, 1.804746849484392790e+00, 1.806511882937405389e+00, 1.808278642584366214e+00, 1.810047130113484837e+00, 1.811817347214621288e+00, 1.813589295579288496e+00, 1.815362976900653402e+00, 1.817138392873539177e+00, 1.818915545194426331e+00, 1.820694435561454716e+00, 1.822475065674424632e+00, 1.824257437234799051e+00, 1.826041551945704944e+00, 1.827827411511934841e+00, 1.829615017639948382e+00, 1.831404372037874539e+00, 1.833195476415512726e+00, 1.834988332484334128e+00, 1.836782941957484150e+00, 1.838579306549783521e+00, 1.840377427977729852e+00, 1.842177307959500077e+00, 1.843978948214950675e+00, 1.845782350465620780e+00, 1.847587516434733068e+00, 1.849394447847195311e+00, 1.851203146429602153e+00, 1.853013613910237112e+00, 1.854825852019074128e+00, 1.856639862487778458e+00, 1.858455647049709336e+00, 1.860273207439921306e+00, 1.862092545395165555e+00, 1.863913662653891468e+00, 1.865736560956249512e+00, 1.867561242044091241e+00, 1.869387707660971953e+00, 1.871215959552152475e+00, 1.873045999464600042e+00, 1.874877829146990305e+00, 1.876711450349709764e+00, 1.878546864824856444e+00, 1.880384074326241439e+00, 1.882223080609391808e+00, 1.884063885431551011e+00, 1.885906490551681580e+00, 1.887750897730465560e+00, 1.889597108730307617e+00, 1.891445125315335929e+00, 1.893294949251403514e+00, 1.895146582306090899e+00, 1.897000026248707005e+00, 1.898855282850291371e+00, 1.900712353883615258e+00, 1.902571241123184098e+00, 1.904431946345238380e+00, 1.906294471327756090e+00, 1.908158817850454048e+00, 1.910024987694789234e+00, 1.911892982643961236e+00, 1.913762804482913360e+00, 1.915634454998335068e+00, 1.917507935978662870e+00, 1.919383249214082099e+00, 1.921260396496529133e+00, 1.923139379619692946e+00, 1.925020200379016666e+00, 1.926902860571699128e+00, 1.928787361996697314e+00, 1.930673706454727245e+00, 1.932561895748265979e+00, 1.934451931681553383e+00, 1.936343816060594136e+00, 1.938237550693158839e+00, 1.940133137388786233e+00, 1.942030577958784976e+00, 1.943929874216234976e+00, 1.945831027975989169e+00, 1.947734041054675735e+00, 1.949638915270699435e+00, 1.951545652444242940e+00, 1.953454254397269940e+00, 1.955364722953525147e+00, 1.957277059938537400e+00, 1.959191267179620555e+00, 1.961107346505876148e+00, 1.963025299748193842e+00, 1.964945128739254310e+00, 1.966866835313530570e+00, 1.968790421307289762e+00, 1.970715888558594475e+00, 1.972643238907305641e+00, 1.974572474195082972e+00, 1.976503596265387408e+00, 1.978436606963483113e+00, 1.980371508136438585e+00, 1.982308301633128655e+00, 1.984246989304236930e+00, 1.986187573002256235e+00, 1.988130054581491502e+00, 1.990074435898061544e+00, 1.992020718809899504e+00, 1.993968905176756401e+00, 1.995918996860201577e+00, 1.997870995723625365e+00, 1.999824903632240414e+00, 2.001780722453083250e+00, 2.003738454055016494e+00, 2.005698100308730414e+00, 2.007659663086745372e+00, 2.009623144263412708e+00, 2.011588545714916076e+00, 2.013555869319274994e+00, 2.015525116956345730e+00, 2.017496290507822643e+00, 2.019469391857240392e+00, 2.021444422889975279e+00, 2.023421385493248792e+00, 2.025400281556126725e+00, 2.027381112969523613e+00, 2.029363881626201849e+00, 2.031348589420776563e+00, 2.033335238249714294e+00, 2.035323830011336987e+00, 2.037314366605823768e+00, 2.039306849935211385e+00, 2.041301281903396436e+00, 2.043297664416138471e+00, 2.045295999381059993e+00, 2.047296288707649570e+00, 2.049298534307263164e+00, 2.051302738093126798e+00, 2.053308901980336110e+00, 2.055317027885860792e+00, 2.057327117728544597e+00, 2.059339173429108882e+00, 2.061353196910152619e+00, 2.063369190096155492e+00, 2.065387154913478795e+00, 2.067407093290368536e+00, 2.069429007156956324e+00, 2.071452898445260704e+00, 2.073478769089190710e+00, 2.075506621024545861e+00, 2.077536456189019720e+00, 2.079568276522200776e+00, 2.081602083965573780e+00, 2.083637880462522407e+00, 2.085675667958331481e+00, 2.087715448400187856e+00, 2.089757223737183089e+00, 2.091800995920314765e+00, 2.093846766902488277e+00, 2.095894538638519045e+00, 2.097944313085134738e+00, 2.099996092200975717e+00, 2.102049877946599477e+00, 2.104105672284479311e+00, 2.106163477179008314e+00, 2.108223294596501596e+00, 2.110285126505196285e+00, 2.112348974875254637e+00, 2.114414841678765811e+00, 2.116482728889747644e+00, 2.118552638484149320e+00, 2.120624572439850919e+00, 2.122698532736667865e+00, 2.124774521356352253e+00, 2.126852540282593296e+00, 2.128932591501020877e+00, 2.131014676999206436e+00, 2.133098798766665638e+00, 2.135184958794859700e+00, 2.137273159077198059e+00, 2.139363401609037929e+00, 2.141455688387690071e+00, 2.143550021412417461e+00, 2.145646402684438847e+00, 2.147744834206929632e+00, 2.149845317985024540e+00, 2.151947856025819394e+00, 2.154052450338372893e+00, 2.156159102933708827e+00, 2.158267815824817415e+00, 2.160378591026657524e+00, 2.162491430556158889e+00, 2.164606336432223888e+00, 2.166723310675729319e+00, 2.168842355309527736e+00, 2.170963472358450552e+00, 2.173086663849310263e+00, 2.175211931810900001e+00, 2.177339278273997980e+00, 2.179468705271368378e+00, 2.181600214837763563e+00, 2.183733809009925864e+00, 2.185869489826588907e+00, 2.188007259328480725e+00, 2.190147119558325084e+00, 2.192289072560843710e+00, 2.194433120382758062e+00, 2.196579265072790665e+00, 2.198727508681668219e+00, 2.200877853262122930e+00, 2.203030300868894731e+00, 2.205184853558733060e+00, 2.207341513390398191e+00, 2.209500282424664785e+00, 2.211661162724322338e+00, 2.213824156354178285e+00, 2.215989265381058448e+00, 2.218156491873810587e+00, 2.220325837903306176e+00, 2.222497305542441737e+00, 2.224670896866141057e+00, 2.226846613951356524e+00, 2.229024458877072234e+00, 2.231204433724306213e+00, 2.233386540576111301e+00, 2.235570781517576489e+00, 2.237757158635831800e+00, 2.239945674020046962e+00, 2.242136329761435398e+00, 2.244329127953256009e+00, 2.246524070690814501e+00, 2.248721160071466496e+00, 2.250920398194617533e+00, 2.253121787161727507e+00, 2.255325329076311114e+00, 2.257531026043940514e+00, 2.259738880172246223e+00, 2.261948893570921104e+00, 2.264161068351720818e+00, 2.266375406628466482e+00, 2.268591910517046006e+00, 2.270810582135417199e+00, 2.273031423603609102e+00, 2.275254437043724209e+00, 2.277479624579939799e+00, 2.279706988338511042e+00, 2.281936530447773226e+00, 2.284168253038142193e+00, 2.286402158242117455e+00, 2.288638248194284408e+00, 2.290876525031316113e+00, 2.293116990891975071e+00, 2.295359647917114998e+00, 2.297604498249684379e+00, 2.299851544034726469e+00, 2.302100787419383732e+00, 2.304352230552896952e+00, 2.306605875586610122e+00, 2.308861724673969995e+00, 2.311119779970530974e+00, 2.313380043633953775e+00, 2.315642517824010760e+00, 2.317907204702585933e+00, 2.320174106433678052e+00, 2.322443225183401072e+00, 2.324714563119988586e+00, 2.326988122413794269e+00, 2.329263905237294541e+00, 2.331541913765090346e+00, 2.333822150173909371e+00, 2.336104616642608711e+00, 2.338389315352174869e+00, 2.340676248485729083e+00, 2.342965418228526886e+00, 2.345256826767960323e+00, 2.347550476293561950e+00, 2.349846368997005275e+00, 2.352144507072106983e+00, 2.354444892714828708e+00, 2.356747528123281477e+00, 2.359052415497723931e+00, 2.361359557040568546e+00, 2.363668954956380297e+00, 2.365980611451881099e+00, 2.368294528735950255e+00, 2.370610709019628004e+00, 2.372929154516116412e+00, 2.375249867440782925e+00, 2.377572850011160810e+00, 2.379898104446951823e+00, 2.382225632970029761e+00, 2.384555437804440015e+00, 2.386887521176404459e+00, 2.389221885314321003e+00, 2.391558532448767593e+00, 2.393897464812503539e+00, 2.396238684640471295e+00, 2.398582194169800452e+00, 2.400927995639806412e+00, 2.403276091291996597e+00, 2.405626483370069568e+00, 2.407979174119918575e+00, 2.410334165789632888e+00, 2.412691460629500906e+00, 2.415051060892011492e+00, 2.417412968831856190e+00, 2.419777186705932781e+00, 2.422143716773345279e+00, 2.424512561295406599e+00, 2.426883722535642551e+00, 2.429257202759791401e+00, 2.431633004235808748e+00, 2.434011129233866644e+00, 2.436391580026358472e+00, 2.438774358887899840e+00, 2.441159468095329910e+00, 2.443546909927716282e+00, 2.445936686666354110e+00, 2.448328800594770094e+00, 2.450723253998724260e+00, 2.453120049166212180e+00, 2.455519188387466745e+00, 2.457920673954961277e+00, 2.460324508163410417e+00, 2.462730693309773233e+00, 2.465139231693255883e+00, 2.467550125615311618e+00, 2.469963377379646552e+00, 2.472378989292218332e+00, 2.474796963661240135e+00, 2.477217302797182441e+00, 2.479640009012775703e+00, 2.482065084623012119e+00, 2.484492531945147409e+00, 2.486922353298704813e+00, 2.489354551005475091e+00, 2.491789127389519631e+00, 2.494226084777173114e+00, 2.496665425497044843e+00, 2.499107151880022748e+00, 2.501551266259272488e+00, 2.503997770970243231e+00, 2.506446668350667206e+00, 2.508897960740563704e+00, 2.511351650482239517e+00, 2.513807739920292939e+00, 2.516266231401615538e+00, 2.518727127275393052e+00, 2.521190429893109819e+00, 2.523656141608549230e+00, 2.526124264777797279e+00, 2.528594801759243005e+00, 2.531067754913583379e+00, 2.533543126603823303e+00, 2.536020919195279166e+00, 2.538501135055579727e+00, 2.540983776554670559e+00, 2.543468846064813604e+00, 2.545956345960592504e+00, 2.548446278618911709e+00, 2.550938646419000921e+00, 2.553433451742416871e+00, 2.555930696973045091e+00, 2.558430384497103027e+00, 2.560932516703141371e+00, 2.563437095982046721e+00, 2.565944124727044251e+00, 2.568453605333699930e+00, 2.570965540199921850e+00, 2.573479931725964232e+00, 2.575996782314427858e+00, 2.578516094370263190e+00, 2.581037870300773918e+00, 2.583562112515616516e+00, 2.586088823426805128e+00, 2.588618005448712456e+00, 2.591149660998072424e+00, 2.593683792493982843e+00, 2.596220402357906742e+00, 2.598759493013676369e+00, 2.601301066887493185e+00, 2.603845126407932309e+00, 2.606391674005943848e+00, 2.608940712114855121e+00, 2.611492243170373762e+00, 2.614046269610588613e+00, 2.616602793875974164e+00, 2.619161818409390996e+00, 2.621723345656088444e+00, 2.624287378063707266e+00, 2.626853918082283634e+00, 2.629422968164247365e+00, 2.631994530764428575e+00, 2.634568608340057683e+00, 2.637145203350768075e+00, 2.639724318258598323e+00, 2.642305955527996186e+00, 2.644890117625817716e+00, 2.647476807021333478e+00, 2.650066026186227663e+00, 2.652657777594602084e+00, 2.655252063722977951e+00, 2.657848887050299869e+00, 2.660448250057934949e+00, 2.663050155229678140e+00, 2.665654605051753112e+00, 2.668261602012815370e+00, 2.670871148603954914e+00, 2.673483247318696243e+00, 2.676097900653003681e+00, 2.678715111105283153e+00, 2.681334881176383078e+00, 2.683957213369597472e+00, 2.686582110190669503e+00, 2.689209574147792381e+00, 2.691839607751612018e+00, 2.694472213515231029e+00, 2.697107393954207843e+00, 2.699745151586563363e+00, 2.702385488932778745e+00, 2.705028408515801619e+00, 2.707673912861047416e+00, 2.710322004496400261e+00, 2.712972685952216967e+00, 2.715625959761328811e+00, 2.718281828459045091e+00 }; template<typename Scalar> static inline Scalar fast_exp(Scalar x) { if (x < 0) return 1/fast_exp(-x); if (x > 100) return std::exp(x); int cnt = 0; while (x >= 1) { x = x/2; cnt++; } x = exp_lut[static_cast<int>(x*1024)]; while (cnt-- > 0) { x *= x; } return x; } /** * @brief This function is used for the calculation of the digamma function, * which is the logarithmic derivative of the Gamma Function. The digamma * function is computable via Taylor approximations (Abramowitz and Stegun, * 1970) **/ template <typename Scalar> static inline Scalar digamma(Scalar x) { Scalar result = 0, xx, xx2, xx4; for (; x < 7; ++x) { result -= 1/x; } x -= 1.0/2.0; xx = 1.0/x; xx2 = xx*xx; xx4 = xx2*xx2; result += std::log(x)+(1./24.)*xx2-(7.0/960.0)*xx4+(31.0/8064.0)*xx4*xx2-(127.0/30720.0)*xx4*xx4; return result; } template <typename Scalar> struct CwiseDigamma { const Scalar operator()(const Scalar &x) const { return digamma(x); } }; template <typename Scalar> struct CwiseLgamma { const Scalar operator()(const Scalar &x) const { return std::lgamma(x); } }; template <typename Scalar> struct CwiseFastExp { const Scalar operator()(const Scalar &x) const { return fast_exp(x); } }; template <typename Scalar> struct CwiseIsNaN { const bool operator()(const Scalar &x) const { return std::isnan(x); } }; template <typename Scalar> struct CwiseIsInf { const bool operator()(const Scalar &x) const { return std::isinf(x); } }; template <typename Scalar> struct CwiseScalarDivideByMatrix { CwiseScalarDivideByMatrix(Scalar y) : y_(y) {} const Scalar operator()(const Scalar &x) const { if (x != 0) return y_ / x; return 0; } Scalar y_; }; /** * Reshape a matrix into a vector by copying the matrix into the vector in a * way to avoid errors by Eigen expressions. */ template <typename Scalar> void reshape_into( const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> &src, Eigen::Matrix<Scalar, Eigen::Dynamic, 1> &dst ) { size_t srcR = src.rows(); size_t srcC = src.cols(); for (int c=0; c<srcC; c++) { dst.segment(c*srcR, srcR) = src.col(c); } } /** * Reshape a vector into a matrix by copying the vector into the matrix in a * way to avoid errors by Eigen expressions. */ template <typename Scalar> void reshape_into( const Eigen::Matrix<Scalar, Eigen::Dynamic, 1> &src, Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> &dst ) { size_t dstR = dst.rows(); size_t dstC = dst.cols(); for (int c=0; c<dstC; c++) { dst.col(c) = src.segment(c*dstR, dstR); } } /** * Normalize in place a matrix of row vectors so that they sum to 1. Avoid NaN * by checking for 0 explicitly. */ template <typename Derived> void normalize_rows(Eigen::DenseBase<Derived> &x) { typename Eigen::DenseBase<Derived>::Scalar s; for (int i=0; i<x.rows(); i++) { s = x.row(i).sum(); if (s != 0) { x.row(i).array() /= s; } } } /** * Normalize in place a matrix of column vectors so that they sum to 1. Avoid * NaN by checking for 0 explicitly. */ template <typename Derived> void normalize_cols(Eigen::DenseBase<Derived> &x) { typename Eigen::DenseBase<Derived>::Scalar s; for (int i=0; i<x.cols(); i++) { s = x.col(i).sum(); if (s != 0) { x.col(i).array() /= s; } } } /** * Compute the product ignoring zeros. */ template <typename Derived> typename Eigen::DenseBase<Derived>::Scalar product_of_nonzeros( const Eigen::DenseBase<Derived> &x ) { typename Eigen::DenseBase<Derived>::Scalar p = 1; for (int j=0; j<x.cols(); j++) { for (int i=0; i<x.rows(); i++) { if (x(i, j) != 0) p *= x(i, j); } } return p; } /** * Sum the rows scaled by another vector */ template <typename Derived1, typename Derived2, typename Derived3> void sum_rows_scaled( const Eigen::MatrixBase<Derived1> & x, const Eigen::MatrixBase<Derived2> & y, Eigen::MatrixBase<Derived3> & result ) { for (int i=0; i<x.rows(); i++) { // this is done so that the multiplication can never result in NaN if (y[i] == 0) continue; result += y[i] * x.row(i); } } /** * Sum the cols scaled by another vector */ template <typename Derived1, typename Derived2, typename Derived3> void sum_cols_scaled( const Eigen::MatrixBase<Derived1> & x, const Eigen::MatrixBase<Derived2> & y, Eigen::MatrixBase<Derived3> & result ) { for (int i=0; i<x.cols(); i++) { // this is done so that the multiplication can never result in NaN if (y[i] == 0) continue; result += y[i] * x.col(i); } } /** * Wrap a PRNG with this class in order to be able to pass it around even * to other threads and protect its internal state from being corrupted. * * see UniformRandomBitGenerator C++ concept * http://en.cppreference.com/w/cpp/concept/UniformRandomBitGenerator */ template <typename PRNG> class ThreadSafePRNG { public: typedef typename PRNG::result_type result_type; static constexpr result_type min() { return PRNG::min(); } static constexpr result_type max() { return PRNG::max(); } ThreadSafePRNG(int random_state) { prng_mutex_ = std::make_shared<std::mutex>(); prng_ = std::make_shared<PRNG>(random_state); } result_type operator()() { std::lock_guard<std::mutex> lock(*prng_mutex_); return (*prng_)(); } private: std::shared_ptr<std::mutex> prng_mutex_; std::shared_ptr<PRNG> prng_; }; } // namespace math_utils } // namespace ldaplusplus #endif // _LDAPLUSPLUS_UTILS_HPP_
55.022508
101
0.769314
angeloskath
ab7b47f17b3292e2937294b990f633b91ff24918
1,571
cpp
C++
lib/smooth/application/network/mqtt/packet/Unsubscribe.cpp
luuvt/lms
8f53ddeb62e9ca328acb36b922bf72e223ff3753
[ "Apache-2.0" ]
283
2017-07-18T15:31:42.000Z
2022-03-30T12:05:03.000Z
lib/smooth/application/network/mqtt/packet/Unsubscribe.cpp
luuvt/lms
8f53ddeb62e9ca328acb36b922bf72e223ff3753
[ "Apache-2.0" ]
131
2017-08-23T18:49:03.000Z
2021-11-29T08:03:21.000Z
lib/smooth/application/network/mqtt/packet/Unsubscribe.cpp
luuvt/lms
8f53ddeb62e9ca328acb36b922bf72e223ff3753
[ "Apache-2.0" ]
53
2017-12-31T13:34:21.000Z
2022-02-04T11:26:49.000Z
/* Smooth - A C++ framework for embedded programming on top of Espressif's ESP-IDF Copyright 2019 Per Malmberg (https://gitbub.com/PerMalmberg) 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 "smooth/application/network/mqtt/packet/Unsubscribe.h" #include "smooth/core/util/advance_iterator.h" #include "smooth/application/network/mqtt/packet/IPacketReceiver.h" namespace smooth::application::network::mqtt::packet { void Unsubscribe::visit(IPacketReceiver& receiver) { receiver.receive(*this); } void Unsubscribe::get_topics(std::vector<std::string>& topics) const { calculate_remaining_length_and_variable_header_offset(); auto it = get_variable_header_start() + get_variable_header_length(); bool end_reached = false; do { auto s = get_string(it); topics.push_back(s); // Move to next string, add two for the length bits end_reached = !core::util::advance(it, data.end(), s.length() + 2); } while (!end_reached && it != data.end()); } }
33.425532
79
0.703374
luuvt
ab7e18d51f9318cccc2a369994175e31d0a50100
6,819
cpp
C++
src/scrollbar/cocScrollbar.cpp
codeoncanvas/coc-ui
d1b6389adba5234254665c07382a028716016dce
[ "MIT" ]
1
2018-01-08T21:37:42.000Z
2018-01-08T21:37:42.000Z
src/scrollbar/cocScrollbar.cpp
codeoncanvas/coc-ui
d1b6389adba5234254665c07382a028716016dce
[ "MIT" ]
null
null
null
src/scrollbar/cocScrollbar.cpp
codeoncanvas/coc-ui
d1b6389adba5234254665c07382a028716016dce
[ "MIT" ]
1
2020-04-21T00:30:27.000Z
2020-04-21T00:30:27.000Z
/** * * โ”Œโ”€โ”โ•”โ•โ•—โ”Œโ”ฌโ”โ”Œโ”€โ” * โ”‚ โ•‘ โ•‘ โ”‚โ”‚โ”œโ”ค * โ””โ”€โ”˜โ•šโ•โ•โ”€โ”ดโ”˜โ””โ”€โ”˜ * โ”Œโ”€โ”โ”Œโ”€โ”โ•”โ•—โ•”โ”ฌ โ”ฌโ”Œโ”€โ”โ”Œโ”€โ” * โ”‚ โ”œโ”€โ”คโ•‘โ•‘โ•‘โ””โ”โ”Œโ”˜โ”œโ”€โ”คโ””โ”€โ” * โ””โ”€โ”˜โ”ด โ”ดโ•โ•šโ• โ””โ”˜ โ”ด โ”ดโ””โ”€โ”˜ * * Copyright (c) 2014-2016 Code on Canvas Pty Ltd, http://CodeOnCanvas.cc * * This software is distributed under the MIT license * https://tldrlegal.com/license/mit-license * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code * **/ #include "cocScrollbar.h" namespace coc { //-------------------------------------------------------------- Scrollbar::Scrollbar(): type(Type::Vertical), position(0.0), contentRatio(0.5), ease(0.0), thumbOffset(0.0), bThumbPressed(false), bPositionChangeInternal(false), bPositionChangeExternal(false) { // } Scrollbar::~Scrollbar() { // } //-------------------------------------------------------------- ScrollbarRef Scrollbar::create() { ScrollbarRef scrollbar = ScrollbarRef(new Scrollbar()); scrollbar->setup(); return scrollbar; } void Scrollbar::setup() { track = initButton(); thumb = initButton(); } //-------------------------------------------------------------- void Scrollbar::setType(coc::Scrollbar::Type value) { type = value; } coc::Scrollbar::Type Scrollbar::getType() const { return type; } //-------------------------------------------------------------- void Scrollbar::setRect(coc::Rect value) { rect = value; } const coc::Rect & Scrollbar::getRect() const { return rect; } //-------------------------------------------------------------- void Scrollbar::setContentRatio(float value) { contentRatio = value; } float Scrollbar::getContentRatio() const { return contentRatio; } //-------------------------------------------------------------- void Scrollbar::setThumbOffset(float value) { thumbOffset = value; } float Scrollbar::getThumbOffset() const { return thumbOffset; } //-------------------------------------------------------------- void Scrollbar::setEase(float value) { ease = value; } float Scrollbar::getEase() const { return ease; } //-------------------------------------------------------------- void Scrollbar::setPosition(float value) { bPositionChangeExternal = (position != value); position = value; } float Scrollbar::getPosition() const { return position; } //-------------------------------------------------------------- void Scrollbar::setEnabled(bool value) { track->setEnabled(value); thumb->setEnabled(value); } //-------------------------------------------------------------- void Scrollbar::update() { bPositionChangeInternal = false; const coc::Rect & trackRect = rect; coc::Rect thumbRect = trackRect; if(type == Type::Vertical) { float trackRectY = trackRect.getY(); float trackRectH = trackRect.getH(); float thumbRectH = trackRectH * contentRatio; float thumbRectY = coc::map(position, 0.0, 1.0, trackRectY - thumbOffset, trackRectY + trackRectH - thumbRectH + thumbOffset, true); thumbRect.setH(thumbRectH); thumbRect.setY(thumbRectY); } else if(type == Type::Horizontal) { float trackRectX = trackRect.getX(); float trackRectW = trackRect.getW(); float thumbRectW = trackRectW * contentRatio; float thumbRectX = coc::map(position, 0.0, 1.0, trackRectX - thumbOffset, trackRectX + trackRectW - thumbRectW + thumbOffset, true); thumbRect.setW(thumbRectW); thumbRect.setX(thumbRectX); } track->setRect(trackRect); track->update(); thumb->setRect(thumbRect); thumb->update(); if(thumb->pressedInside()) { track->reset(); // when thumb is pressed, cancel events going down to the track. thumbPressStartPos.x = thumb->getRect().getX(); thumbPressStartPos.y = thumb->getRect().getY(); thumbPressInsidePos = thumb->getPointPosLast(); bThumbPressed = true; } else if(thumb->releasedInside() || thumb->releasedOutside()) { bThumbPressed = false; } bool bTrackPressed = track->pressedInside(); bool bUpdateThumbPos = false; bUpdateThumbPos = bUpdateThumbPos || bThumbPressed; bUpdateThumbPos = bUpdateThumbPos || bTrackPressed; if(bUpdateThumbPos) { const glm::ivec2 & thumbPressPos = thumb->getPointPosLast(); const glm::ivec2 & trackPressPos = track->getPointPosLast(); coc::Rect thumbRect = thumb->getRect(); int thumbMin = 0; int thumbMax = 0; int thumbDrag = 0; int thumbPos = 0; float thumbPosNorm = 0; if(type == coc::Scrollbar::Type::Vertical) { if(bThumbPressed) { thumbDrag = thumbPressPos.y - thumbPressInsidePos.y; thumbPos = thumbPressStartPos.y + thumbDrag; } else if(bTrackPressed) { thumbPos = trackPressPos.y - (thumbRect.getH() * 0.5); } thumbMin = trackRect.getY(); thumbMax = thumbMin + trackRect.getH() - thumbRect.getH(); thumbPosNorm = coc::map(thumbPos, thumbMin, thumbMax, 0.0, 1.0, true); thumbPos = coc::map(thumbPosNorm, 0.0, 1.0, thumbMin - thumbOffset, thumbMax + thumbOffset); thumbRect.setY(thumbPos); } else if(type == coc::Scrollbar::Type::Horizontal) { if(bThumbPressed) { thumbDrag = thumbPressPos.x - thumbPressInsidePos.x; thumbPos = thumbPressStartPos.x + thumbDrag; } else if(bTrackPressed) { thumbPos = trackPressPos.x - (thumbRect.getW() * 0.5); } thumbMin = trackRect.getX(); thumbMax = thumbMin + trackRect.getW() - thumbRect.getW(); thumbPosNorm = coc::map(thumbPos, thumbMin, thumbMax, 0.0, 1.0, true); thumbPos = coc::map(thumbPosNorm, 0.0, 1.0, thumbMin - thumbOffset, thumbMax + thumbOffset); thumbRect.setX(thumbPos); } bPositionChangeInternal = (position != thumbPosNorm); position = thumbPosNorm; thumb->setRect(thumbRect); } bPositionChangeExternal = false; } //-------------------------------------------------------------- void Scrollbar::pointMoved(int x, int y) { track->pointMoved(x, y); thumb->pointMoved(x, y); } void Scrollbar::pointPressed(int x, int y) { track->pointPressed(x, y); thumb->pointPressed(x, y); } void Scrollbar::pointDragged(int x, int y) { track->pointDragged(x, y); thumb->pointDragged(x, y); } void Scrollbar::pointReleased(int x, int y) { track->pointReleased(x, y); thumb->pointReleased(x, y); } }
28.294606
140
0.543335
codeoncanvas
ab8185b6c8942cc7c789c30d993bb1a6fda4f1c2
795
hpp
C++
kernel/meta/compiler.hpp
panix-os/Panix
1047fc384696684a7583bda035fa580da4adbd5b
[ "MIT" ]
68
2020-10-10T03:56:04.000Z
2021-07-22T19:15:47.000Z
kernel/meta/compiler.hpp
panix-os/Panix
1047fc384696684a7583bda035fa580da4adbd5b
[ "MIT" ]
88
2020-10-01T23:36:44.000Z
2021-07-22T03:11:43.000Z
kernel/meta/compiler.hpp
panix-os/Panix
1047fc384696684a7583bda035fa580da4adbd5b
[ "MIT" ]
5
2021-06-25T16:56:46.000Z
2021-07-21T02:38:41.000Z
/** * @file compiler.hpp * @author Keeton Feavel (keetonfeavel@cedarville.edu) * @brief Compiler meta directives * @version 0.1 * @date 2021-06-17 * * @copyright Copyright the Xyris Contributors (c) 2021 * */ #pragma once // Function attributes #define NORET __attribute__((noreturn)) #define OPTIMIZE(x) __attribute__((optimize("O"#x))) #define ALWAYS_INLINE __attribute__((always_inline)) // Constructors / Destructors #define CONSTRUCTOR __attribute__ ((constructor)) #define DESTRUCTOR __attribute__ ((destructor)) // Branch prediction #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) // Data attributes #define USED __attribute__ ((used)) #define PACKED __attribute__ ((__packed__)) #define ALIGN(x) __attribute__ ((aligned ((x))))
26.5
55
0.734591
panix-os
ab829bcfdb5e536bd2556c5acd0c195b4e57b807
258
hpp
C++
DLOCRModel.Calculate/DLOCRModel.Calculate.hpp
Frederisk/DeepLearning-OpticalCharacterRecognition-Model
52998e877cdf1e849cc2648e7d07dee6ae865cc1
[ "MIT" ]
null
null
null
DLOCRModel.Calculate/DLOCRModel.Calculate.hpp
Frederisk/DeepLearning-OpticalCharacterRecognition-Model
52998e877cdf1e849cc2648e7d07dee6ae865cc1
[ "MIT" ]
1
2020-12-16T03:32:56.000Z
2020-12-16T03:32:56.000Z
DLOCRModel.Calculate/DLOCRModel.Calculate.hpp
Frederisk/DeepLearning-OpticalCharacterRecognition-Model
52998e877cdf1e849cc2648e7d07dee6ae865cc1
[ "MIT" ]
null
null
null
๏ปฟ#pragma once using namespace System; using MathNet::Numerics::LinearAlgebra::Matrix; namespace DLOCRModel { namespace Calculate { public ref class FeedforwardNetworkPiece sealed { public: private: }; } }
14.333333
57
0.627907
Frederisk
ab839c9d1069d6dce421d13fed082e5107abf190
4,871
cpp
C++
projects/atest/test_context.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
projects/atest/test_context.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
136
2020-03-29T11:15:38.000Z
2020-10-14T06:21:23.000Z
projects/atest/test_context.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
1
2020-08-04T09:56:53.000Z
2020-08-04T09:56:53.000Z
#ifndef __clang__ export module atest:test_context; import :test_suite; #endif namespace atest { //! \private export class TestContext { struct TestContextWrapper { TestContext *context = nullptr; std::atomic<int> instances{}; }; public: TestContext() noexcept : parentContext{TestContext::current().context} { this->initialize_global_test_suite(); if (TestContext::current().instances.load() != 0) { TestContext::current().context = this; } ++TestContext::current().instances; } TestContext(const TestContext &other) = delete; TestContext(TestContext &&other) noexcept = delete; ~TestContext() { try { TestContext::current().context = this->parentContext; --TestContext::current().instances; } catch (...) { } } auto add_test(const char *name, auto(*body)()->void, const std::source_location &sourceLocation) noexcept { try { this->currentTestSuite->tests.emplace_back(Test{name, body, sourceLocation}); } catch (...) { } } auto add_test_suite(const char *name, auto(*body)()->void, const std::source_location &sourceLocation) noexcept -> int { try { try { this->currentTestSuite = &this->testSuites.emplace_back(TestSuite{name, sourceLocation}); body(); this->currentTestSuite = &this->testSuites.front(); return 0; } catch (const std::exception &exception) { std::cout << "ERROR: Exception thrown during registration of '" << name << "' test suite (" << typeid(exception).name() << "): " << exception.what() << '\n'; } catch (...) { std::cout << "ERROR: Unknown exception thrown during registration of '" << name << "' test suite.\n"; } } catch (...) { // Suppress any further exceptions as this // function is usually run outside of main // and no exception can be caught. See // clang-tidy check: cert-err58-cpp. } return 1; } [[nodiscard]] static auto current() noexcept -> TestContextWrapper & { static TestContext globalContext{nullptr}; static TestContextWrapper wrapper{.context = &globalContext}; return wrapper; } [[nodiscard]] auto current_test() noexcept -> Test & { return *this->currentTest; } auto initialize_global_test_suite() noexcept -> void { try { this->currentTestSuite = &this->testSuites.emplace_back(TestSuite{.name = "Global"}); } catch (...) { } } auto reset() -> void { for (TestSuite &testSuite : this->testSuites) { TestContext::reset_test_suites(testSuite); } } auto set_current_test(Test &test) noexcept -> void { this->currentTest = &test; } auto sort_test_suites() -> void { const auto sorter = [](const TestSuite &left, const TestSuite &right) { return std::string{left.sourceLocation.file_name()} < std::string{right.sourceLocation.file_name()}; }; std::sort(++this->testSuites.begin(), this->testSuites.end(), sorter); } [[nodiscard]] auto test_suites() noexcept -> std::vector<TestSuite> & { return this->testSuites; } auto operator=(const TestContext &other) -> TestContext & = delete; auto operator=(TestContext &&other) noexcept -> TestContext & = delete; private: TestContext(TestContext *context) noexcept : parentContext{context} { this->initialize_global_test_suite(); } static auto reset_test(Test &test) -> void { test.expectations = 0; test.failedExpectations = 0; test.duration = std::chrono::microseconds::zero(); test.failures.clear(); } static auto reset_test_suites(TestSuite &testSuite) -> void { for (Test &test : testSuite.tests) { TestContext::reset_test(test); } } std::vector<TestSuite> testSuites; TestSuite *currentTestSuite = nullptr; Test *currentTest = nullptr; TestContext *parentContext = nullptr; }; //! \private export [[nodiscard]] auto test_context() -> TestContext & { return *TestContext::current().context; } }
26.048128
112
0.53295
agnesoft
ab85331c3970fe232bb9914251791c6a4ccd641c
2,259
cpp
C++
segmentation/Ncuts/util/mex_math.cpp
sfikas/sfikasLibrary
b99ac0bf01289c23d46c27bd9003e7891f026eb4
[ "MIT" ]
7
2016-10-03T12:43:59.000Z
2020-07-18T08:17:44.000Z
segmentation/Ncuts/util/mex_math.cpp
sfikas/duguepes-matroutines
b99ac0bf01289c23d46c27bd9003e7891f026eb4
[ "MIT" ]
null
null
null
segmentation/Ncuts/util/mex_math.cpp
sfikas/duguepes-matroutines
b99ac0bf01289c23d46c27bd9003e7891f026eb4
[ "MIT" ]
null
null
null
/*================================================================ // Timothee Cour, 29-Aug-2006 07:49:15 mex_math = used by a couple of mex functions *=================================================================*/ # include "math.h" int round2(double x) { //return floor(x+0.5); return x>=0 ? (int)(x+0.5) : (int) (x-0.5); } /* Problem: when compiling on opteron, says error: new declaration int round(double x) { //return floor(x+0.5); return x>=0 ? (int)(x+0.5) : (int) (x-0.5); }*/ double min(double x,double y) { return x<y?x:y; } double max(double x,double y) { return x>y?x:y; } int max(int x,int y) { return x>y?x:y; } int min(int x,int y) { return x<y?x:y; } double vec_max(double *x,int n) { double res=x[0]; for(int i=1;i<n;i++) if(res<x[i]) res=x[i]; return res; } int vec_max(int *x,int n) { int res=x[0]; for(int i=1;i<n;i++) if(res<x[i]) res=x[i]; return res; } int vec_min(int *x,int n) { int res=x[0]; for(int i=1;i<n;i++) if(res>x[i]) res=x[i]; return res; } double vec_min(double *x,int n) { double res=x[0]; for(int i=1;i<n;i++) if(res>x[i]) res=x[i]; return res; } double dot(double *x,double *y, int n) { double temp = 0; for(int i=0;i!=n;i++) temp+=*x++ * *y++; return temp; } void scalar_times_vec(double a, double *x,double *y, int n) { // y=a*x for(int i=0;i!=n;i++) *y++ = *x++ * a; } void scalar_plus_vec_self(int a, int *x, int n) { // x=a+x for(int i=0;i!=n;i++) *x++ += a; } void vec_plus_vec(double *x1, double *x2,double *y, int n) { // y=x1+x2 for(int i=0;i!=n;i++) y[i] = x1[i] + x2[i]; //*y++ = *x1++ + *x2++; } void ind2sub(int*ind,int*indi,int*indj,int p,int q,int n){ //caution: output is in matlab conventions//TODO;correct this [mex_ind2sub int i; int*pindi=indi; int*pindj=indj; int*pind=ind; int temp; for(i=0;i<n;i++){ temp=*pind++-1; *pindi++=temp%p+1; *pindj++=temp/p+1; } } //void symmetrize_sparse()
21.932039
76
0.463922
sfikas
ab857925febd450c0ad4441b9f5341b548ca54c6
2,037
hpp
C++
rocsolver/clients/include/rocsolver_test.hpp
LuckyBoyDE/rocSOLVER
6431459ce3f68b5a4c14b28b4ec35c25d664f0bc
[ "BSD-2-Clause" ]
null
null
null
rocsolver/clients/include/rocsolver_test.hpp
LuckyBoyDE/rocSOLVER
6431459ce3f68b5a4c14b28b4ec35c25d664f0bc
[ "BSD-2-Clause" ]
null
null
null
rocsolver/clients/include/rocsolver_test.hpp
LuckyBoyDE/rocSOLVER
6431459ce3f68b5a4c14b28b4ec35c25d664f0bc
[ "BSD-2-Clause" ]
null
null
null
/* ************************************************************************ * Copyright (c) 2018-2020 Advanced Micro Devices, Inc. * ************************************************************************ */ #ifndef S_TEST_H_ #define S_TEST_H_ #include <boost/format.hpp> #include <cstdarg> #include <limits> #define ROCSOLVER_BENCH_INFORM(case) \ do \ { \ if(case == 2) \ rocblas_cout << "Invalid value in arguments ..." << std::endl; \ else if(case == 1) \ rocblas_cout << "Invalid size arguments..." << std::endl; \ else \ rocblas_cout << "Quick return..." << std::endl; \ rocblas_cout << "No performance data to collect." << std::endl; \ rocblas_cout << "No computations to verify." << std::endl; \ } while(0) template <typename T> constexpr double get_epsilon() { using S = decltype(std::real(T{})); return std::numeric_limits<S>::epsilon(); } template <typename T> inline void rocsolver_test_check(double max_error, int tol) { #ifdef GOOGLE_TEST ASSERT_LE(max_error, tol * get_epsilon<T>()); #endif } inline void rocsolver_bench_output() { // empty version rocblas_cout << std::endl; } template <typename T, typename... Ts> inline void rocsolver_bench_output(T arg, Ts... args) { using boost::format; format f("%|-15|"); rocblas_cout << f % arg; rocsolver_bench_output(args...); } template <typename T, std::enable_if_t<!is_complex<T>, int> = 0> inline T sconj(T scalar) { return scalar; } template <typename T, std::enable_if_t<is_complex<T>, int> = 0> inline T sconj(T scalar) { return std::conj(scalar); } #endif
29.521739
78
0.471772
LuckyBoyDE
ab889664886083babd8ffdebf49f7ea22422ce8d
23,207
cpp
C++
font.cpp
Yours3lf/text_game
32c934a7cb396d2412a3f0847cd7c7da9d46e3c0
[ "MIT" ]
null
null
null
font.cpp
Yours3lf/text_game
32c934a7cb396d2412a3f0847cd7c7da9d46e3c0
[ "MIT" ]
null
null
null
font.cpp
Yours3lf/text_game
32c934a7cb396d2412a3f0847cd7c7da9d46e3c0
[ "MIT" ]
null
null
null
#include "font.h" #include <fstream> #include "ft2build.h" #include FT_FREETYPE_H #define MAX_TEX_SIZE 8192 #define MIN_TEX_SIZE 128 #define FONT_VERTEX 0 #define FONT_TEXCOORD 1 #define FONT_VERTSCALEBIAS 2 #define FONT_TEXSCALEBIAS 3 #define FONT_COLOR 4 #define FONT_FACE 5 #define FONT_TRANSFORM 6 #define FONT_FILTER 7 wchar_t buf[2] = { -1, L'\0' }; std::wstring cachestring = std::wstring( buf ) + L" 0123456789a๏ฟฝbcde๏ฟฝfghi๏ฟฝjklmno๏ฟฝ๏ฟฝ๏ฟฝpqrstu๏ฟฝ๏ฟฝ๏ฟฝvwxyzA๏ฟฝBCDE๏ฟฝFGHI๏ฟฝJKLMNO๏ฟฝ๏ฟฝ๏ฟฝPQRSTU๏ฟฝ๏ฟฝ๏ฟฝVWXYZ+!%/=()|$[]<>#&@{},.~-?:_;*`^'\""; struct glyph { float offset_x; float offset_y; float w; float h; float texcoords[4]; FT_Glyph_Metrics metrics; FT_Vector advance; FT_UInt glyphid; unsigned int cache_index; }; library::library() : the_library( 0 ), tex( 0 ), texsampler_point( 0 ), texsampler_linear( 0 ), vao( 0 ), the_shader( 0 ), is_set_up( false ) { for( int c = 0; c < FONT_LIB_VBO_SIZE; ++c ) vbos[c] = 0; FT_Error error; error = FT_Init_FreeType( (FT_Library*)&the_library ); if( error ) { std::cerr << "Error initializing the freetype library." << std::endl; } } void library::destroy() { glDeleteSamplers( 1, &texsampler_point ); glDeleteSamplers( 1, &texsampler_linear ); glDeleteTextures( 1, &tex ); glDeleteVertexArrays( 1, &vao ); glDeleteBuffers( FONT_LIB_VBO_SIZE, vbos ); glDeleteProgram( the_shader ); } library::~library() { if( the_library ) { FT_Error error; error = FT_Done_FreeType( (FT_Library)the_library ); if( error ) { std::cerr << "Error destroying the freetype library." << std::endl; } } } void library::delete_glyphs() { texture_pen = mm::uvec2( 1 ); texture_row_h = 0; texsize = mm::uvec2( 0 ); font_data.clear(); for( auto& c : instances ) { ( *c->the_face->glyphs ).clear(); } } void library::set_up() { if( is_set_up ) return; texture_pen = mm::uvec2( 0 ); texsize = mm::uvec2( 0 ); glGenTextures( 1, &tex ); glGenSamplers( 1, &texsampler_point ); glGenSamplers( 1, &texsampler_linear ); glSamplerParameteri( texsampler_point, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glSamplerParameteri( texsampler_point, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glSamplerParameteri( texsampler_point, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glSamplerParameteri( texsampler_point, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glSamplerParameteri( texsampler_linear, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glSamplerParameteri( texsampler_linear, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glSamplerParameteri( texsampler_linear, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glSamplerParameteri( texsampler_linear, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); std::vector<unsigned> faces; std::vector<float> vertices; std::vector<float> texcoords; faces.resize( 2 * 3 ); vertices.resize( 4 * 2 ); texcoords.resize( 4 * 2 ); faces[0 * 3 + 0] = 2; faces[0 * 3 + 1] = 1; faces[0 * 3 + 2] = 0; faces[1 * 3 + 0] = 0; faces[1 * 3 + 1] = 3; faces[1 * 3 + 2] = 2; vertices[0 * 2 + 0] = 0; vertices[0 * 2 + 1] = 0; vertices[1 * 2 + 0] = 0; vertices[1 * 2 + 1] = 1; vertices[2 * 2 + 0] = 1; vertices[2 * 2 + 1] = 1; vertices[3 * 2 + 0] = 1; vertices[3 * 2 + 1] = 0; texcoords[0 * 2 + 0] = 0; texcoords[0 * 2 + 1] = 0; texcoords[1 * 2 + 0] = 0; texcoords[1 * 2 + 1] = 1; texcoords[2 * 2 + 0] = 1; texcoords[2 * 2 + 1] = 1; texcoords[3 * 2 + 0] = 1; texcoords[3 * 2 + 1] = 0; glGenVertexArrays( 1, &vao ); glBindVertexArray( vao ); glGenBuffers( 1, &vbos[FONT_VERTEX] ); glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_VERTEX] ); glBufferData( GL_ARRAY_BUFFER, sizeof(float)* 2 * vertices.size(), &vertices[0], GL_STATIC_DRAW ); glEnableVertexAttribArray( FONT_VERTEX ); glVertexAttribPointer( FONT_VERTEX, 2, GL_FLOAT, false, 0, 0 ); glGenBuffers( 1, &vbos[FONT_TEXCOORD] ); glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_TEXCOORD] ); glBufferData( GL_ARRAY_BUFFER, sizeof(float)* 2 * texcoords.size(), &texcoords[0], GL_STATIC_DRAW ); glEnableVertexAttribArray( FONT_TEXCOORD ); glVertexAttribPointer( FONT_TEXCOORD, 2, GL_FLOAT, false, 0, 0 ); glGenBuffers( 1, &vbos[FONT_VERTSCALEBIAS] ); glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_VERTSCALEBIAS] ); glEnableVertexAttribArray( FONT_VERTSCALEBIAS ); glVertexAttribPointer( FONT_VERTSCALEBIAS, 4, GL_FLOAT, false, sizeof( mm::vec4 ), 0 ); glVertexAttribDivisor( FONT_VERTSCALEBIAS, 1 ); glGenBuffers( 1, &vbos[FONT_TEXSCALEBIAS] ); glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_TEXSCALEBIAS] ); glEnableVertexAttribArray( FONT_TEXSCALEBIAS ); glVertexAttribPointer( FONT_TEXSCALEBIAS, 4, GL_FLOAT, false, sizeof( mm::vec4 ), 0 ); glVertexAttribDivisor( FONT_TEXSCALEBIAS, 1 ); glGenBuffers( 1, &vbos[FONT_COLOR] ); glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_COLOR] ); glEnableVertexAttribArray( FONT_COLOR ); glVertexAttribPointer( FONT_COLOR, 4, GL_FLOAT, false, sizeof( mm::vec4 ), 0 ); glVertexAttribDivisor( FONT_COLOR, 1 ); glGenBuffers( 1, &vbos[FONT_FACE] ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vbos[FONT_FACE] ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)* 3 * faces.size(), &faces[0], GL_STATIC_DRAW ); glGenBuffers( 1, &vbos[FONT_TRANSFORM] ); glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_TRANSFORM] ); for( int c = 0; c < 4; ++c ) { glEnableVertexAttribArray( FONT_TRANSFORM + c ); glVertexAttribPointer( FONT_TRANSFORM + c, 4, GL_FLOAT, false, sizeof( mm::mat4 ), ( (char*)0 ) + sizeof( mm::vec4 ) * c ); glVertexAttribDivisor( FONT_TRANSFORM + c, 1 ); } glGenBuffers( 1, &vbos[FONT_FILTER] ); glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_FILTER] ); glEnableVertexAttribArray( FONT_FILTER + 3 ); glVertexAttribPointer( FONT_FILTER + 3, 1, GL_FLOAT, false, sizeof( float ), 0 ); glVertexAttribDivisor( FONT_FILTER + 3, 1 ); glBindVertexArray( 0 ); is_set_up = true; } bool library::expand_tex() { glBindTexture( GL_TEXTURE_RECTANGLE, tex ); if( texsize.x == 0 || texsize.y == 0 ) { texsize.x = MAX_TEX_SIZE; texsize.y = MIN_TEX_SIZE; GLubyte* buf = new GLubyte[texsize.x * texsize.y]; memset( buf, 0, texsize.x * texsize.y * sizeof( GLubyte ) ); glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE ); glTexImage2D( GL_TEXTURE_RECTANGLE, 0, GL_R8, texsize.x, texsize.y, 0, GL_RED, GL_UNSIGNED_BYTE, buf ); texture_pen.x = 1; texture_pen.y = 1; texture_row_h = 0; delete[] buf; } else { GLubyte* buf = new GLubyte[texsize.x * texsize.y]; glGetTexImage( GL_TEXTURE_RECTANGLE, 0, GL_RED, GL_UNSIGNED_BYTE, buf ); int tmp_height = texsize.y; texsize.y += MIN_TEX_SIZE; if( texsize.y > MAX_TEX_SIZE ) //can't expand tex further { return false; } GLubyte* tmpbuf = new GLubyte[texsize.x * texsize.y]; memset( tmpbuf, 0, texsize.x * texsize.y * sizeof( GLubyte ) ); glTexImage2D( GL_TEXTURE_RECTANGLE, 0, GL_R8, texsize.x, texsize.y, 0, GL_RED, GL_UNSIGNED_BYTE, tmpbuf ); glTexSubImage2D( GL_TEXTURE_RECTANGLE, 0, 0, 0, texsize.x, tmp_height, GL_RED, GL_UNSIGNED_BYTE, buf ); delete[] buf; delete[] tmpbuf; } return true; } font_inst::face::face() : size( 0 ), the_face( 0 ), glyphs( 0 ) { } font_inst::face::face( const std::string& filename, unsigned int index ) { FT_Error error; error = FT_New_Face( (FT_Library)library::get().get_library(), filename.c_str(), index, (FT_Face*)&the_face ); upos = 0; uthick = 0; FT_Matrix matrix = { (int)( ( 1.0 / 64.0f ) * 0x10000L ), (int)( ( 0.0 ) * 0x10000L ), (int)( ( 0.0 ) * 0x10000L ), (int)( ( 1.0 ) * 0x10000L ) }; FT_Select_Charmap( *(FT_Face*)&the_face, FT_ENCODING_UNICODE ); FT_Set_Transform( *(FT_Face*)&the_face, &matrix, NULL ); glyphs = new std::map< unsigned int, std::map<uint32_t, glyph> >(); if( error ) { std::cerr << "Error loading font face: " << filename << std::endl; the_face = 0; } } font_inst::face::~face() { //TODO invalidate glyphs in the library, and its tex FT_Done_Face( (FT_Face)the_face ); delete glyphs; } void font_inst::face::set_size( unsigned int val ) { if( the_face ) { size = val; FT_Set_Char_Size( (FT_Face)the_face, size * 100.0f * 64.0f, 0.0f, 72 * 64.0f, 72 ); asc = ( ( (FT_Face)the_face )->size->metrics.ascender / 64.0f ) / 100.0f; desc = ( ( (FT_Face)the_face )->size->metrics.descender / 64.0f ) / 100.0f; h = ( ( (FT_Face)the_face )->size->metrics.height / 64.0f ) / 100.0f; gap = h - asc + desc; upos = ( (FT_Face)the_face )->underline_position / ( 64.0f*64.0f ) * size; upos = std::round( upos ); if( upos > -2 ) { upos = -2; } uthick = ( (FT_Face)the_face )->underline_thickness / ( 64.0f*64.0f ) * size; uthick = std::round( uthick ); if( uthick < 1 ) { uthick = 1; } FT_Set_Char_Size( (FT_Face)the_face, size * 64.0f, 0.0f, 72 * 64.0f, 72 ); } } bool font_inst::face::load_glyph( unsigned int val ) { if( ( *glyphs )[size].count( val ) == 0 && the_face ) { FT_Error error; FT_GlyphSlot theglyph = FT_GlyphSlot(); if( val != wchar_t( -1 ) ) { error = FT_Load_Char( (FT_Face)the_face, (const FT_UInt)val, FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT ); if( error ) { std::cerr << "Error loading character: " << (wchar_t)val << std::endl; } theglyph = ( (FT_Face)the_face )->glyph; } else { theglyph = new FT_GlyphSlotRec_(); theglyph->advance.x = 0; theglyph->advance.y = 0; static unsigned char data[4 * 4 * 3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; theglyph->bitmap.buffer = data; theglyph->bitmap.rows = 4; theglyph->bitmap.width = 4; theglyph->bitmap_left = 0; theglyph->bitmap_top = 0; } auto texsize = library::get().get_texsize(); auto& texpen = library::get().get_texture_pen(); auto& texrowh = library::get().get_tex_row_h(); if( texsize.x == 0 || texsize.y == 0 ) { library::get().expand_tex(); } FT_Bitmap* bitmap = &theglyph->bitmap; if( texpen.x + bitmap->width + 1 > (int)texsize.x ) { texpen.y += texrowh + 1; texpen.x = 1; texrowh = 0; } if( texpen.y + bitmap->rows + 1 > (int)texsize.y ) { if( !library::get().expand_tex() ) { //tex expansion unsuccessful return false; } } GLubyte* data; int glyph_size = bitmap->width * bitmap->rows; data = new GLubyte[glyph_size]; int c = 0; for( int y = 0; y < bitmap->rows; y++ ) { for( int x = 0; x < bitmap->width; x++ ) { data[x + ( bitmap->rows - 1 - y ) * bitmap->width] = bitmap->buffer[c++]; } } GLint uplast; glGetIntegerv( GL_UNPACK_ALIGNMENT, &uplast ); if( uplast != 1 ) { glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); } glBindTexture( GL_TEXTURE_RECTANGLE, library::get().get_tex() ); glTexSubImage2D( GL_TEXTURE_RECTANGLE, 0, texpen.x, texpen.y, bitmap->width, bitmap->rows, GL_RED, GL_UNSIGNED_BYTE, data ); delete[] data; if( uplast != 1 ) { glPixelStorei( GL_UNPACK_ALIGNMENT, uplast ); } glyph* g = &( *glyphs )[size][val]; g->glyphid = FT_Get_Char_Index( (FT_Face)the_face, (const FT_ULong)val ); g->offset_x = (float)theglyph->bitmap_left; g->offset_y = (float)theglyph->bitmap_top; g->w = (float)bitmap->width; g->h = (float)bitmap->rows; if( val != wchar_t( -1 ) ) { g->texcoords[0] = (float)texpen.x - 0.5f; g->texcoords[1] = (float)texpen.y - 0.5f; g->texcoords[2] = (float)texpen.x + (float)bitmap->width + 0.5f; g->texcoords[3] = (float)texpen.y + (float)bitmap->rows + 0.5f; } else { g->texcoords[0] = (float)texpen.x; g->texcoords[1] = (float)texpen.y; g->texcoords[2] = (float)texpen.x + (float)bitmap->width; g->texcoords[3] = (float)texpen.y + (float)bitmap->rows; } texpen.x += bitmap->width + 1; if( bitmap->rows > texrowh ) { texrowh = bitmap->rows; } g->advance = theglyph->advance; } return true; } float font_inst::face::kerning( const uint32_t prev, const uint32_t next ) { if( the_face ) { if( next && FT_HAS_KERNING( ( (FT_Face)the_face ) ) ) { FT_Vector kern; FT_Get_Kerning( (FT_Face)the_face, prev, next, FT_KERNING_UNFITTED, &kern ); return ( kern.x / ( 64.0f*64.0f ) ); } else { return 0; } } else { return 0; } } float font_inst::face::advance( const uint32_t current ) { return ( ( *glyphs )[size][current].advance.x / 64.0f ); } float font_inst::face::height() { return h; } float font_inst::face::linegap() { return gap; } float font_inst::face::ascender() { return asc; } float font_inst::face::descender() { return desc; } float font_inst::face::underline_position() { return upos; } float font_inst::face::underline_thickness() { return uthick; } glyph& font_inst::face::get_glyph( uint32_t i ) { return ( *glyphs )[size][i]; } bool font_inst::face::has_glyph( uint32_t i ) { try { ( *glyphs ).at( size ).at( i ); return true; } catch( ... ) { return false; } } void font::set_size( font_inst& font_ptr, unsigned int s ) { font_ptr.the_face->set_size( s ); std::for_each( cachestring.begin(), cachestring.end(), [&]( wchar_t & c ) { add_glyph( font_ptr, c ); } ); } void font::add_glyph( font_inst& font_ptr, uint32_t c, int counter ) { if( font_ptr.the_face->has_glyph( c ) ) return; if( !font_ptr.the_face->load_glyph( c ) ) { if( counter > 9 ) //at max 10 tries { exit( 1 ); //couldn't get enough memory or something... (extreme case) } library::get().delete_glyphs(); add_glyph( font_ptr, c, ++counter ); return; } auto& g = font_ptr.the_face->get_glyph( c ); g.cache_index = library::get().get_font_data_size(); mm::vec2 vertbias = mm::vec2( g.offset_x - 0.5f, -0.5f - ( g.h - g.offset_y ) ); mm::vec2 vertscale = mm::vec2( g.offset_x + g.w + 0.5f, 0.5f + g.h - ( g.h - g.offset_y ) ) - vertbias; //texcoords mm::vec2 texbias = mm::vec2( g.texcoords[0], g.texcoords[1] ); mm::vec2 texscale = mm::vec2( g.texcoords[2], g.texcoords[3] ) - texbias; library::get().add_font_data( fontscalebias( vertscale, vertbias, texscale, texbias ) ); } void font::load_font( const std::string& filename, font_inst& font_ptr, unsigned int size ) { std::cout << "-Loading: " << filename << std::endl; std::fstream f( filename.c_str(), std::ios::in ); if( !f ) std::cerr << "Couldn't open file: " << filename << std::endl; f.close(); library::get().set_up(); resize( screensize ); //load directly from font font_ptr.the_face = new font_inst::face( filename, 0 ); set_size( font_ptr, size ); library::get().instances.push_back( &font_ptr ); } void font::resize( const mm::uvec2& ss ) { screensize = ss; font_frame.set_ortographic( 0.0f, (float)ss.x, 0.0f, (float)ss.y, 0.0f, 1.0f ); } static std::vector<mm::vec4> vertscalebias; static std::vector<mm::vec4> texscalebias; static std::vector<mm::vec4> fontcolor; static std::vector<mm::mat4> transform; static std::vector<float> filter; //these special unicode characters denote the text markup begin/end #define FONT_UNDERLINE_BEGIN L'\uE000' #define FONT_UNDERLINE_END L'\uE001' #define FONT_OVERLINE_BEGIN L'\uE002' #define FONT_OVERLINE_END L'\uE003' #define FONT_STRIKETHROUGH_BEGIN L'\uE004' #define FONT_STRIKETHROUGH_END L'\uE005' #define FONT_HIGHLIGHT_BEGIN L'\uE006' #define FONT_HIGHLIGHT_END L'\uE007' bool is_special( wchar_t c ) { return c == FONT_UNDERLINE_BEGIN || c == FONT_UNDERLINE_END || c == FONT_OVERLINE_BEGIN || c == FONT_OVERLINE_END || c == FONT_STRIKETHROUGH_BEGIN || c == FONT_STRIKETHROUGH_END || c == FONT_HIGHLIGHT_BEGIN || c == FONT_HIGHLIGHT_END; } mm::vec2 font::add_to_render_list( const std::wstring& txt, font_inst& font_ptr, const mm::vec4& color, const mm::mat4& mat, const mm::vec4& highlight_color, float line_height, float f ) { static bool underline = false; static bool overline = false; static bool strikethrough = false; static bool highlight = false; float yy = 0; float xx = 0; float vert_advance = font_ptr.the_face->height() - font_ptr.the_face->linegap(); vert_advance *= line_height; yy += vert_advance; for( int c = 0; c < int( txt.size() ); c++ ) { char bla = txt[c]; if( txt[c] == L'\n' ) { yy += vert_advance; xx = 0; } if( c > 0 && txt[c] != L'\n' && !is_special( txt[c] ) ) { xx += font_ptr.the_face->kerning( txt[c - 1], txt[c] ); } if( txt[c] == FONT_UNDERLINE_BEGIN ) underline = true; else if( txt[c] == FONT_UNDERLINE_END ) underline = false; else if( txt[c] == FONT_OVERLINE_BEGIN ) overline = true; else if( txt[c] == FONT_OVERLINE_END ) overline = false; else if( txt[c] == FONT_STRIKETHROUGH_BEGIN ) strikethrough = true; else if( txt[c] == FONT_STRIKETHROUGH_END ) strikethrough = false; else if( txt[c] == FONT_HIGHLIGHT_BEGIN ) highlight = true; else if( txt[c] == FONT_HIGHLIGHT_END ) highlight = false; float finalx = xx; mm::vec3 pos = mm::vec3( finalx, (float)screensize.y - yy, 0 ); float advancex = 0; int i = 0; for( i = c; i < txt.size(); ++i ) { if( !is_special( txt[i] ) ) break; } advancex = font_ptr.the_face->advance( txt[i] ); if( highlight ) { unsigned int datapos = font_ptr.the_face->get_glyph( wchar_t( -1 ) ).cache_index; fontscalebias& fsb = library::get().get_font_data( datapos ); fontscalebias copy = fsb; //vert bias copy.vertscalebias.w = font_ptr.the_face->descender(); //hori bias copy.vertscalebias.z = 0.0f; //hori scale copy.vertscalebias.x = advancex; //vert scale copy.vertscalebias.y = font_ptr.the_face->height() + font_ptr.the_face->linegap(); vertscalebias.push_back( mm::vec4( copy.vertscalebias.xy, copy.vertscalebias.zw + pos.xy ) ); texscalebias.push_back( copy.texscalebias ); fontcolor.push_back( highlight_color ); transform.push_back( mat ); filter.push_back( f ); } if( strikethrough ) { unsigned int datapos = font_ptr.the_face->get_glyph( wchar_t( -1 ) ).cache_index; fontscalebias& fsb = library::get().get_font_data( datapos ); fontscalebias copy = fsb; //vert bias copy.vertscalebias.w = font_ptr.the_face->ascender() * 0.33f; //hori bias copy.vertscalebias.z = 0; //hori scale copy.vertscalebias.x = advancex; //vert scale copy.vertscalebias.y = font_ptr.the_face->underline_thickness(); vertscalebias.push_back( mm::vec4( copy.vertscalebias.xy, copy.vertscalebias.zw + pos.xy ) ); texscalebias.push_back( copy.texscalebias ); fontcolor.push_back( color ); transform.push_back( mat ); filter.push_back( f ); } if( underline ) { unsigned int datapos = font_ptr.the_face->get_glyph( wchar_t( -1 ) ).cache_index; fontscalebias& fsb = library::get().get_font_data( datapos ); fontscalebias copy = fsb; //vert bias copy.vertscalebias.w = font_ptr.the_face->underline_position(); //hori bias copy.vertscalebias.z = 0.0f; //hori scale copy.vertscalebias.x = advancex; //vert scale copy.vertscalebias.y = font_ptr.the_face->underline_thickness(); vertscalebias.push_back( mm::vec4( copy.vertscalebias.xy, copy.vertscalebias.zw + pos.xy ) ); texscalebias.push_back( copy.texscalebias ); fontcolor.push_back( color ); transform.push_back( mat ); filter.push_back( f ); } if( overline ) { unsigned int datapos = font_ptr.the_face->get_glyph( wchar_t( -1 ) ).cache_index; fontscalebias& fsb = library::get().get_font_data( datapos ); fontscalebias copy = fsb; //vert bias copy.vertscalebias.w = font_ptr.the_face->ascender(); //hori bias copy.vertscalebias.z = 0.0f; //hori scale copy.vertscalebias.x = advancex; //vert scale copy.vertscalebias.y = font_ptr.the_face->underline_thickness(); vertscalebias.push_back( mm::vec4( copy.vertscalebias.xy, copy.vertscalebias.zw + pos.xy ) ); texscalebias.push_back( copy.texscalebias ); fontcolor.push_back( color ); transform.push_back( mat ); filter.push_back( f ); } if( c < txt.size() && txt[c] != L' ' && txt[c] != L'\n' && !is_special( txt[c] ) ) { add_glyph( font_ptr, txt[c] ); unsigned int datapos = font_ptr.the_face->get_glyph( txt[c] ).cache_index; auto thefsb = library::get().get_font_data( datapos ); vertscalebias.push_back( mm::vec4( thefsb.vertscalebias.xy, thefsb.vertscalebias.zw + pos.xy ) ); texscalebias.push_back( thefsb.texscalebias ); fontcolor.push_back( color ); transform.push_back( mat ); filter.push_back( f ); } if( !is_special( txt[c] ) ) xx += font_ptr.the_face->advance( txt[c] ); } yy -= vert_advance; return mm::vec2( xx, yy ); } void font::render() { glDisable( GL_CULL_FACE ); glDisable( GL_DEPTH_TEST ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); library::get().bind_shader(); //mvp is now only the projection matrix mm::mat4 mat = font_frame.projection_matrix; glUniformMatrix4fv( 0, 1, false, &mat[0].x ); glActiveTexture( GL_TEXTURE0 ); library::get().bind_texture(); library::get().bind_vao(); library::get().update_scalebiascolor( FONT_VERTSCALEBIAS, vertscalebias ); library::get().update_scalebiascolor( FONT_TEXSCALEBIAS, texscalebias ); library::get().update_scalebiascolor( FONT_COLOR, fontcolor ); library::get().update_scalebiascolor( FONT_TRANSFORM, transform ); library::get().update_scalebiascolor( FONT_FILTER, filter ); glDrawElementsInstanced( GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0, vertscalebias.size() ); glBindVertexArray( 0 ); glUseProgram( 0 ); glDisable( GL_BLEND ); glEnable( GL_DEPTH_TEST ); glEnable( GL_CULL_FACE ); vertscalebias.clear(); texscalebias.clear(); fontcolor.clear(); transform.clear(); filter.clear(); }
27.302353
186
0.630887
Yours3lf
ab8db9f0f7d107703c0285f716a5c922921b245f
4,154
cpp
C++
unit_test/gtest_cell_index.cpp
Tokumasu-Lab/md_fdps
eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff
[ "MIT" ]
null
null
null
unit_test/gtest_cell_index.cpp
Tokumasu-Lab/md_fdps
eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff
[ "MIT" ]
null
null
null
unit_test/gtest_cell_index.cpp
Tokumasu-Lab/md_fdps
eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff
[ "MIT" ]
null
null
null
//======================================================================================= // This is unit test of MD_EXT::CellIndex. // module location: ./generic_ext/cell_index.hpp //======================================================================================= #include <gtest/gtest.h> #include <particle_simulator.hpp> #include <random> #include <cell_index.hpp> //--- unit test definition, CANNOT use "_" in test/test_case name. TEST(CellIndex, init){ MD_EXT::CellIndex<int> cell_index; cell_index.initDomain( PS::F32vec{-1.0, -1.0, -1.0}, PS::F32vec{ 2.0, 2.0, 2.0} ); EXPECT_EQ(cell_index.get_domain(), std::make_pair(PS::F32vec{-1.0, -1.0, -1.0}, PS::F32vec{ 2.0, 2.0, 2.0})); cell_index.initIndex(3, 6, 12); EXPECT_EQ(cell_index.get_grid_size().x, 3); EXPECT_EQ(cell_index.get_grid_size().y, 6); EXPECT_EQ(cell_index.get_grid_size().z, 12); EXPECT_FLOAT_EQ(cell_index.get_cell_size().x, 1.0); EXPECT_FLOAT_EQ(cell_index.get_cell_size().y, 0.5); EXPECT_FLOAT_EQ(cell_index.get_cell_size().z, 0.25); cell_index.init( PS::F32vec{0.0, 0.0, 0.0}, PS::F32vec{2.0, 4.0, 3.0}, 0.24 ); EXPECT_EQ(cell_index.get_grid_size().x, 10); EXPECT_EQ(cell_index.get_grid_size().y, 18); EXPECT_EQ(cell_index.get_grid_size().z, 14); EXPECT_FLOAT_EQ(cell_index.get_cell_size().x, 2.0/10.0); EXPECT_FLOAT_EQ(cell_index.get_cell_size().y, 4.0/18.0); EXPECT_FLOAT_EQ(cell_index.get_cell_size().z, 3.0/14.0); } TEST(CellIndex, neighborList){ const int seed = 19937; const int n = 8192; const double l_domain = 100.0; const double r_search = 9.0; std::mt19937 mt; std::uniform_real_distribution<> dist_real(0.0, l_domain); mt.seed(seed); //--- test target std::vector<PS::F32vec> pos; MD_EXT::CellIndex<size_t> cell_index; std::vector<std::vector<size_t>> pair_list_ref; //--- make pos data pos.clear(); for(int i=0; i<n; ++i){ pos.push_back( PS::F32vec{ static_cast<PS::F32>(dist_real(mt)), static_cast<PS::F32>(dist_real(mt)), static_cast<PS::F32>(dist_real(mt)) } ); } //--- make 1D pair list (direct method, reference data) pair_list_ref.clear(); pair_list_ref.resize(n); const double r2_search = r_search*r_search; for(int i=0; i<n; ++i){ pair_list_ref.at(i).clear(); for(int j=0; j<n; ++j){ if(j == i) continue; PS::F32vec r_pos = pos.at(j) - pos.at(i); PS::F32 r2 = r_pos*r_pos; if(r2 <= r2_search){ pair_list_ref.at(i).push_back(j); } } } //--- init cell index cell_index.init( PS::F32vec{0.0, 0.0, 0.0}, PS::F32vec{l_domain, l_domain, l_domain}, r_search ); //--- make index table in cell for(int i=0; i<n; ++i){ cell_index.add(pos.at(i), i); } //--- compare result (internal buffer) for(int i=0; i<n; ++i){ const auto& list_ref = pair_list_ref.at(i); const auto cell_data = cell_index.get_data_list(pos.at(i), r_search); for(const auto tgt : list_ref){ size_t n_tgt = std::count(cell_data.begin(), cell_data.end(), tgt); EXPECT_EQ(n_tgt, 1) << " i= " << i << " tgt= " << tgt; } } //--- compare result (const interface for outside buffer) std::vector<MD_EXT::CellIndex<size_t>::index_type> cell_list; std::vector<MD_EXT::CellIndex<size_t>::value_type> cell_data; for(int i=0; i<n; ++i){ const auto& list_ref = pair_list_ref.at(i); cell_list.clear(); cell_data.clear(); cell_index.get_data_list(pos.at(i), r_search, cell_list, cell_data); for(const auto tgt : list_ref){ size_t n_tgt = std::count(cell_data.begin(), cell_data.end(), tgt); EXPECT_EQ(n_tgt, 1) << " i= " << i << " tgt= " << tgt; } } } #include "gtest_main.hpp"
34.907563
89
0.546221
Tokumasu-Lab
ab9af8c4d401cf7813a4789505c8f92cbd2753ee
16,385
cpp
C++
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Sensors Geolocation Sample Driver (UMDF Version 1)/C++/RadioManagerGPS/SampleRadioManager.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Sensors Geolocation Sample Driver (UMDF Version 1)/C++/RadioManagerGPS/SampleRadioManager.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Sensors Geolocation Sample Driver (UMDF Version 1)/C++/RadioManagerGPS/SampleRadioManager.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2020-10-19T23:36:26.000Z
2020-10-22T12:59:37.000Z
#include "precomp.h" #pragma hdrstop CSampleRadioManager::CSampleRadioManager() : _pSensorManagerEvents(nullptr), _hPnPEventThread(nullptr), _hPnPEventThreadEvent(nullptr), _hPnPEventWindow(nullptr) { } HRESULT CSampleRadioManager::FinalConstruct() { HRESULT hr = S_OK; // Create Sensor Manager to use to connect to sensor hr = _spSensorManager.CoCreateInstance(CLSID_SensorManager, nullptr, CLSCTX_INPROC_SERVER); if (SUCCEEDED(hr)) { // Add the one radio that is managed if it is present HRESULT hrTemp = S_OK; { // Brackets for sensorComm scope CSensorCommunication sensorComm = CSensorCommunication(); hrTemp = sensorComm.Initialize(); } if (SUCCEEDED(hrTemp)) { hr = _AddInstance(SENSOR_GUID_STRING, nullptr); } // Listen for sensor add events if (SUCCEEDED(hr)) { // Will be deleted in _Cleanup _pSensorManagerEvents = new CSensorManagerEvents(this, _spSensorManager); if (nullptr != _pSensorManagerEvents) { hr = _pSensorManagerEvents->Initialize(); } else { hr = E_OUTOFMEMORY; } } // Listen for sensor leave events. // Listen for PnP events instead of subscribing to sensor events as subscribing // to sensor events will create a persistent connection to the driver. _InitializeSensorLeaveEvents(); } if (FAILED(hr)) { _Cleanup(); } return hr; } HRESULT CSampleRadioManager::_InitializeSensorLeaveEvents() { HRESULT hr = S_OK; // Create an event so we can be notified when the thread is initialized. _hPnPEventThreadEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr); if (nullptr != _hPnPEventThreadEvent) { _hPnPEventThread = ::CreateThread( nullptr, 0, s_ThreadPnPEvent, this, 0, nullptr); if (nullptr == _hPnPEventThread) { hr = GetLastError(); } else { (void)::WaitForSingleObject(_hPnPEventThreadEvent, INFINITE); } ::CloseHandle(_hPnPEventThreadEvent); _hPnPEventThreadEvent = nullptr; } else { hr = GetLastError(); } return hr; } void CSampleRadioManager::FinalRelease() { _Cleanup(); } void CSampleRadioManager::_Cleanup() { POSITION p; while (nullptr != (p = _listRadioInstances.GetHeadPosition())) { INSTANCE_LIST_OBJ *pListObj = _listRadioInstances.GetAt(p); if (nullptr != pListObj) { _listRadioInstances.SetAt(p, nullptr); _listRadioInstances.RemoveHeadNoReturn(); delete pListObj; } } if (nullptr != _pSensorManagerEvents) { delete _pSensorManagerEvents; } // Destory the window if (nullptr != _hPnPEventWindow) { if (0 != PostMessage(_hPnPEventWindow, WM_DESTROY, 0, 0)) { _hPnPEventWindow = nullptr; // Wait for the destroy window to be processed if (nullptr != _hPnPEventThread) { (void)::WaitForSingleObject(_hPnPEventThread, INFINITE); } } } if (nullptr != _hPnPEventThread) { CloseHandle(_hPnPEventThread); _hPnPEventThread = nullptr; } } IFACEMETHODIMP CSampleRadioManager::GetRadioInstances(_Out_ IRadioInstanceCollection **ppCollection) { CAutoVectorPtr<IRadioInstance *> rgpIRadioInstance; HRESULT hr = S_OK; DWORD cInstance; if (nullptr == ppCollection) { return E_INVALIDARG; } *ppCollection = nullptr; CComCritSecLock<CComAutoCriticalSection> lock(_criticalSection); cInstance = static_cast<DWORD>(_listRadioInstances.GetCount()); if (cInstance > 0) { if (!rgpIRadioInstance.Allocate(cInstance)) { hr = E_OUTOFMEMORY; } if (SUCCEEDED(hr)) { ZeroMemory(rgpIRadioInstance, sizeof(rgpIRadioInstance[0]) * cInstance); DWORD dwIndex = 0; for (POSITION p = _listRadioInstances.GetHeadPosition(); nullptr != p; _listRadioInstances.GetNext(p)) { hr = (_listRadioInstances.GetAt(p))->spRadioInstance.QueryInterface(&(rgpIRadioInstance[dwIndex])); if (FAILED(hr)) { break; } else { dwIndex++; } } } } if (SUCCEEDED(hr)) { hr = CRadioInstanceCollection_CreateInstance(cInstance, rgpIRadioInstance, ppCollection); } for (DWORD dwIndex = 0; dwIndex < cInstance; dwIndex++) { if (nullptr != rgpIRadioInstance[dwIndex]) { rgpIRadioInstance[dwIndex]->Release(); } } return hr; } IFACEMETHODIMP CSampleRadioManager::OnSystemRadioStateChange( _In_ SYSTEM_RADIO_STATE sysRadioState, _In_ UINT32 uTimeoutSec) { HRESULT hr = S_OK; CAutoPtr<SET_SYS_RADIO_JOB> spSetSysRadioJob; bool fRefAdded = false; spSetSysRadioJob.Attach(new SET_SYS_RADIO_JOB); if (nullptr == spSetSysRadioJob) { hr = E_OUTOFMEMORY; } if (SUCCEEDED(hr)) { spSetSysRadioJob->hr = E_FAIL; spSetSysRadioJob->srsTarget = sysRadioState; spSetSysRadioJob->pSampleRM = this; // Add ref to object to avoid object release before working thread return this->AddRef(); fRefAdded = true; HANDLE hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr); if (nullptr == hEvent) { hr = HRESULT_FROM_WIN32(GetLastError()); } else { spSetSysRadioJob->hEvent.Attach(hEvent); } } if (SUCCEEDED(hr)) { if (!QueueUserWorkItem(CSampleRadioManager::s_ThreadSetSysRadio, spSetSysRadioJob, WT_EXECUTEDEFAULT)) { hr = HRESULT_FROM_WIN32(GetLastError()); } } if (SUCCEEDED(hr)) { DWORD dwIgnore; hr = CoWaitForMultipleHandles(0, uTimeoutSec * 1000, 1, reinterpret_cast<LPHANDLE>(&(spSetSysRadioJob->hEvent)), &dwIgnore); if (RPC_S_CALLPENDING == hr) { spSetSysRadioJob.Detach(); } else { hr = spSetSysRadioJob->hr; } } if (fRefAdded) { this->Release(); } return hr; } IFACEMETHODIMP CSampleRadioManager::OnInstanceRadioChange( _In_ BSTR bstrRadioInstanceID, _In_ DEVICE_RADIO_STATE radioState) { return _FireEventOnInstanceRadioChange(bstrRadioInstanceID, radioState); } HRESULT CSampleRadioManager::_FireEventOnInstanceAdd(_In_ IRadioInstance *pRadioInstance) { HRESULT hr; Lock(); for (IUnknown** ppUnkSrc = m_vec.begin(); ppUnkSrc < m_vec.end(); ppUnkSrc++) { if ((nullptr != ppUnkSrc) && (nullptr != *ppUnkSrc)) { CComPtr<IMediaRadioManagerNotifySink> spSink; hr = (*ppUnkSrc)->QueryInterface(IID_PPV_ARGS(&spSink)); if (SUCCEEDED(hr)) { spSink->OnInstanceAdd(pRadioInstance); } } } Unlock(); return S_OK; } HRESULT CSampleRadioManager::_FireEventOnInstanceRemove(_In_ BSTR bstrRadioInstanceID) { HRESULT hr; Lock(); for (IUnknown** ppUnkSrc = m_vec.begin(); ppUnkSrc < m_vec.end(); ppUnkSrc++) { if ((nullptr != ppUnkSrc) && (nullptr != *ppUnkSrc)) { CComPtr<IMediaRadioManagerNotifySink> spSink; hr = (*ppUnkSrc)->QueryInterface(IID_PPV_ARGS(&spSink)); if (SUCCEEDED(hr)) { spSink->OnInstanceRemove(bstrRadioInstanceID); } } } Unlock(); return S_OK; } HRESULT CSampleRadioManager::_FireEventOnInstanceRadioChange( _In_ BSTR bstrRadioInstanceID, _In_ DEVICE_RADIO_STATE radioState ) { HRESULT hr; Lock(); for (IUnknown** ppUnkSrc = m_vec.begin(); ppUnkSrc < m_vec.end(); ppUnkSrc++) { if ((nullptr != ppUnkSrc) && (nullptr != *ppUnkSrc)) { CComPtr<IMediaRadioManagerNotifySink> spSink; hr = (*ppUnkSrc)->QueryInterface(IID_PPV_ARGS(&spSink)); if (SUCCEEDED(hr)) { spSink->OnInstanceRadioChange(bstrRadioInstanceID, radioState); } } } Unlock(); return S_OK; } HRESULT CSampleRadioManager::_AddInstance(_In_ PCWSTR pszKeyName, _Out_opt_ IRadioInstance **ppRadioInstance) { HRESULT hr = S_OK; CComPtr<ISampleRadioInstanceInternal> spRadioInstance; CAutoPtr<INSTANCE_LIST_OBJ> spInstanceObj; CComCritSecLock<CComAutoCriticalSection> lock(_criticalSection); spInstanceObj.Attach(new INSTANCE_LIST_OBJ); if (nullptr == spInstanceObj) { hr = E_OUTOFMEMORY; } if (SUCCEEDED(hr)) { CComPtr<ISampleRadioManagerInternal> spRMInternal = this; hr = CSampleRadioInstance_CreateInstance(pszKeyName, spRMInternal, &spRadioInstance); } if (SUCCEEDED(hr)) { spInstanceObj->fExisting = true; spInstanceObj->spRadioInstance = spRadioInstance; _ATLTRY { spInstanceObj->strRadioInstanceID = pszKeyName; _listRadioInstances.AddTail(spInstanceObj); spInstanceObj.Detach(); } _ATLCATCH(e) { hr = e; } if (SUCCEEDED(hr)) { if (ppRadioInstance != nullptr) { hr = spRadioInstance->QueryInterface(IID_PPV_ARGS(ppRadioInstance)); } } } return hr; } HRESULT CSampleRadioManager::_SetSysRadioState(_In_ SYSTEM_RADIO_STATE sysRadioState) { HRESULT hr = S_OK; CComCritSecLock<CComAutoCriticalSection> lock(_criticalSection); for (POSITION p = _listRadioInstances.GetHeadPosition(); nullptr != p; _listRadioInstances.GetNext(p)) { INSTANCE_LIST_OBJ *pInstanceObj = _listRadioInstances.GetAt(p); hr = pInstanceObj->spRadioInstance->OnSysRadioChange(sysRadioState); if (FAILED(hr)) { break; } } return hr; } DWORD WINAPI CSampleRadioManager::s_ThreadSetSysRadio(LPVOID pThis) { SET_SYS_RADIO_JOB *pJob = reinterpret_cast<SET_SYS_RADIO_JOB *>(pThis); pJob->hr = pJob->pSampleRM->_SetSysRadioState(pJob->srsTarget); SetEvent(pJob->hEvent); return ERROR_SUCCESS; } void CSampleRadioManager::SensorAdded() { CComPtr<IRadioInstance> spRadioInstance; HRESULT hr = _AddInstance(SENSOR_GUID_STRING, &spRadioInstance); if (SUCCEEDED(hr)) { _FireEventOnInstanceAdd(spRadioInstance); } } void CSampleRadioManager::SensorRemoved() { // Remove deleted instance from list POSITION p = _listRadioInstances.GetHeadPosition(); while (nullptr != p) { INSTANCE_LIST_OBJ *pRadioInstanceObj = _listRadioInstances.GetAt(p); if (pRadioInstanceObj != nullptr && 0 == pRadioInstanceObj->strRadioInstanceID.Compare(SENSOR_GUID_STRING)) { POSITION pTmp = p; _listRadioInstances.GetPrev(pTmp); _listRadioInstances.RemoveAt(p); CComBSTR bstrTmp = pRadioInstanceObj->strRadioInstanceID.AllocSysString(); if (nullptr != bstrTmp) { _FireEventOnInstanceRemove(bstrTmp); } delete pRadioInstanceObj; p = pTmp; } if (nullptr != p) { _listRadioInstances.GetNext(p); } else { p = _listRadioInstances.GetHeadPosition(); } } } DWORD WINAPI CSampleRadioManager::s_ThreadPnPEvent(LPVOID pThat) { // This thread creates a window that will listen for PnP Events CSampleRadioManager* pThis = reinterpret_cast<CSampleRadioManager *>(pThat); CComBSTR bstrClassName = CComBSTR("RadioManger_"); (void)bstrClassName.Append(SENSOR_GUID_STRING); // Register and create the window. WNDCLASSEXW wndclass = {0}; wndclass.cbSize = sizeof(wndclass); wndclass.lpfnWndProc = _PnPEventWndProc; wndclass.lpszClassName = bstrClassName; wndclass.hInstance = g_hInstance; (void)::RegisterClassEx(&wndclass); pThis->_hPnPEventWindow = ::CreateWindowEx( 0, bstrClassName, L"", 0, 0, 0, 0, 0, nullptr, nullptr, g_hInstance, (LPVOID)(pThis) ); if (nullptr != pThis->_hPnPEventWindow) { // Register for PnP events DEV_BROADCAST_DEVICEINTERFACE devBroadcastInterface = {0}; devBroadcastInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); devBroadcastInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastInterface.dbcc_name[0] = 0; devBroadcastInterface.dbcc_classguid = SENSOR_TYPE_LOCATION_GPS; HDEVNOTIFY hdevNotify = ::RegisterDeviceNotification( pThis->_hPnPEventWindow, &devBroadcastInterface, DEVICE_NOTIFY_WINDOW_HANDLE); if (nullptr != hdevNotify) { // Signal the event so that the main thread knows the HWND is set. (void)::SetEvent(pThis->_hPnPEventThreadEvent); MSG msg; while (::GetMessage(&msg, nullptr, 0, 0)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::UnregisterDeviceNotification(hdevNotify); } } ::UnregisterClass(bstrClassName, g_hInstance); return 0; } LRESULT WINAPI CSampleRadioManager::_PnPEventWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // Window Proc that receives PnP Events. Used to detect when a sensor leaves. LRESULT lRes = 0; CSampleRadioManager* pThis = nullptr; if (WM_CREATE == uMsg) { // On first run, give the window access to the parent this pointer SetLastError(ERROR_SUCCESS); // Required to detect if return value of 0 from SetWindowLongPtr is null or error pThis = reinterpret_cast<CSampleRadioManager*>(((LPCREATESTRUCT)lParam)->lpCreateParams); if (0 == SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pThis)) { // Return value of 0 could be that pervious pointer was null HRESULT hr = HRESULT_FROM_WIN32(GetLastError()); if (FAILED(hr)) { lRes = -1; } } } else if (uMsg == WM_DESTROY) { ::SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)NULL); PostQuitMessage(0); } else if (uMsg == WM_DEVICECHANGE) { // Determine if this device event is the sensor leaving the system pThis = reinterpret_cast<CSampleRadioManager*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); if (nullptr != pThis && NULL != lParam && DBT_DEVICEREMOVECOMPLETE == wParam) { PDEV_BROADCAST_DEVICEINTERFACE pDevIF = reinterpret_cast<PDEV_BROADCAST_DEVICEINTERFACE>(lParam); if ((DBT_DEVTYP_DEVICEINTERFACE == pDevIF->dbcc_devicetype) && (IsEqualGUID(SENSOR_TYPE_LOCATION_GPS, pDevIF->dbcc_classguid))) { // Make sure this is the correct sensor by comparing Sensor ID in device path // Device path is contained in pDevIF->dbcc_name // Check to see if sensor id matches WCHAR* pRefString = wcsrchr(pDevIF->dbcc_name, L'\\'); if (nullptr != pRefString) { pRefString++; // skip past backslash if (0 == _wcsicmp(SENSOR_GUID_STRING, pRefString)) { pThis->SensorRemoved(); } } } } } if (0 == lRes) { lRes = DefWindowProc(hWnd, uMsg, wParam, lParam); } return lRes; }
27.724196
118
0.595606
zzgchina888
ab9d1614d83ef9bcca23fdc89da22a7a64a5c25a
714
cpp
C++
test/algorithm/has_identity.cpp
muqsitnawaz/mate
0353bb9bd04db0b7b4a547878e76617ed547b337
[ "MIT" ]
null
null
null
test/algorithm/has_identity.cpp
muqsitnawaz/mate
0353bb9bd04db0b7b4a547878e76617ed547b337
[ "MIT" ]
null
null
null
test/algorithm/has_identity.cpp
muqsitnawaz/mate
0353bb9bd04db0b7b4a547878e76617ed547b337
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "mate/algorithm/has_identity.hpp" TEST(IdentityTest, Additive) { const mate::Set_type<int> set { 1, 2, 3, 4, 5 }; EXPECT_FALSE(mate::has_identity<mate::Addition>(set)); const mate::Set_type<int> set1 { 0, 1, 2, 3, 4, 5 }; EXPECT_TRUE(mate::has_identity<mate::Addition>(set1)); } TEST(IdentityTest, Multiplicative) { const mate::Set_type<int> set { 2, 3, 4, 5 }; EXPECT_FALSE(mate::has_identity<mate::Multiplication>(set)); const mate::Set_type<int> set1 { 1, 2, 3, 4, 5 }; EXPECT_TRUE(mate::has_identity<mate::Multiplication>(set1)); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
25.5
64
0.665266
muqsitnawaz
aba103dacd5a9d35d1adb833cbfea4d3c88d308e
7,170
cpp
C++
Build/hosEngine/AudioSource.cpp
Game-institute-1st-While-true/hosEngine
2cc0b464740a976a8b37afd7a9e3479fe7484cf0
[ "MIT" ]
null
null
null
Build/hosEngine/AudioSource.cpp
Game-institute-1st-While-true/hosEngine
2cc0b464740a976a8b37afd7a9e3479fe7484cf0
[ "MIT" ]
null
null
null
Build/hosEngine/AudioSource.cpp
Game-institute-1st-While-true/hosEngine
2cc0b464740a976a8b37afd7a9e3479fe7484cf0
[ "MIT" ]
2
2021-07-14T00:14:18.000Z
2021-07-27T04:16:53.000Z
#include "AudioSource.h" #include "Transform.h" #include "GameObject.h" #include "Scene.h" #include "AudioListener.h" using namespace hos; // FL FR C LFE BL BR SL SR //Degree(0~360) 334 26 0 360 260 100 217.5 142.5 static float EmitterAngle[] = { 5.8294f, //Front Left 0.453786f, //Front Right 0.f, //Center X3DAUDIO_2PI, //Low-frequency effects 3.7960911f, //Back Left 1.74533f, //Back Right 4.53786f, //Surround Left 2.4870942f, //Surround Right }; hos::com::AudioSource::AudioSource() : Component(L"AudioSource") { Reset(); } hos::com::AudioSource::~AudioSource() { Stop(); SafeDelete(Source); } hos::com::AudioSource::AudioSource(const AudioSource& dest) : Component(dest), Clip(dest.Clip), Mute(dest.Mute), Loop(dest.Loop), PlayOnAwake(dest.PlayOnAwake), Volume(dest.Volume), Is3D(dest.Is3D), Range(dest.Range), Source(nullptr) { if (Clip && Clip->Sound) { dest.Source->Stop(); Source = Clip->Sound->CreateInstance(DirectX::SoundEffectInstance_Use3D | DirectX::SoundEffectInstance_ReverbUseFilters).release(); if (Source) { SetVolume(Volume); if (Is3D) { Emitter.ChannelCount = Clip->Sound->GetFormat()->nChannels; Emitter.pChannelAzimuths = EmitterAngle; Emitter.CurveDistanceScaler = Range; Emitter.pVolumeCurve = const_cast<X3DAUDIO_DISTANCE_CURVE*>(&X3DAudioDefault_LinearCurve); } } } } void hos::com::AudioSource::SetAudioClip(AudioClip* clip) { Stop(); SafeDelete(Source); Clip = clip; if (Clip) { Source = Clip->Sound->CreateInstance(DirectX::SoundEffectInstance_Use3D | DirectX::SoundEffectInstance_ReverbUseFilters).release(); if (Source) { if (Is3D) { Emitter.ChannelCount = Clip->Sound->GetFormat()->nChannels; Emitter.pChannelAzimuths = EmitterAngle; Emitter.CurveDistanceScaler = Range; Emitter.pVolumeCurve = const_cast<X3DAUDIO_DISTANCE_CURVE*>(&X3DAudioDefault_LinearCurve); } } } } void hos::com::AudioSource::SetAudioClip(string_view name) { Stop(); SafeDelete(Source); AudioClip* _Clip = g_DataManager->GetAudioClip(name); if (_Clip) { Clip = _Clip; Source = Clip->Sound->CreateInstance(DirectX::SoundEffectInstance_Use3D | DirectX::SoundEffectInstance_ReverbUseFilters).release(); if (Source) { if (Is3D) { Emitter.ChannelCount = Clip->Sound->GetFormat()->nChannels; Emitter.pChannelAzimuths = EmitterAngle; Emitter.CurveDistanceScaler = Range; Emitter.pVolumeCurve = const_cast<X3DAUDIO_DISTANCE_CURVE*>(&X3DAudioDefault_LinearCurve); } } } } void hos::com::AudioSource::SetMute(bool b) { Mute = b; if (Mute) { if (Source) { Source->SetVolume(0); } } else { if (Source) { Source->SetVolume(Volume); } } } void hos::com::AudioSource::SetLoop(bool b) { Loop = b; if (Source) { if (Source->GetState() == DirectX::SoundState::PLAYING) { Source->Stop(); Source->Play(Loop); } } } void hos::com::AudioSource::SetPlayOnAwake(bool b) { PlayOnAwake = b; } void hos::com::AudioSource::SetIs3D(bool b) { Is3D = b; } void hos::com::AudioSource::SetVolume(float volume) { Volume = Max(0.f, Min(volume, 1.f)); if (!Mute) { if (Source) { Source->SetVolume(Volume); } } } void hos::com::AudioSource::SetRange(float range) { Range = range; if (Source) { Emitter.CurveDistanceScaler = Range; } } bool hos::com::AudioSource::GetMute() const { return Mute; } bool hos::com::AudioSource::GetLoop() const { return Loop; } bool hos::com::AudioSource::GetPlayOnAwake() const { return PlayOnAwake; } bool hos::com::AudioSource::GetIs3D() const { return Is3D; } float hos::com::AudioSource::GetVolume() const { return Volume; } float hos::com::AudioSource::GetRange() const { return Range; } com::AudioSource* hos::com::AudioSource::Clone() const { return new AudioSource(*this); } void hos::com::AudioSource::Reset() { Clip = nullptr; Stop(); SafeDelete(Source); Emitter = DirectX::AudioEmitter(); Mute = false; Loop = false; PlayOnAwake = true; Volume = DEFAULT_VOLUME; Is3D = true; Range = DEFAULT_RANGE; } void hos::com::AudioSource::Awake() { if (Clip) { if (Mute) { Source->SetVolume(0); } if(m_GameObject->GetActive() && GetActive()) { if (PlayOnAwake) { Stop(); Play(); } } } Component::Awake(); } void hos::com::AudioSource::Update() { if (Is3D) { if (Source) { //Emitter.SetPosition(transform->GetPosition()); Emitter.Update(m_GameObject->transform->GetPosition(), m_GameObject->transform->GetUp(), (float)Time->DeltaTime()); Source->Apply3D(m_GameObject->m_Scene->GetAudioListener()->Get(), Emitter, false); } } } void hos::com::AudioSource::OnEnable() { } void hos::com::AudioSource::OnDisable() { Stop(); } const std::vector<U8> hos::com::AudioSource::Serialize() { mbstring name = ut::UTF16ToAnsi(GetName()); mbstring clipName; if (Clip) { clipName = ut::UTF16ToAnsi(Clip->GetName()); } flexbuffers::Builder builder; builder.Map([&] { builder.String("Name", name); builder.Bool("IsActive", GetActive()); builder.Bool("Mute", Mute); builder.Bool("Loop", Loop); builder.Bool("PlayOnAwake", PlayOnAwake); builder.Bool("Is3D", Is3D); builder.Float("Volume", Volume); builder.Float("Range", Range); builder.String("AudioClip", clipName); }); builder.Finish(); return builder.GetBuffer(); } bool hos::com::AudioSource::Deserialize(mbstring_view data) { if (data.size() <= 0) { return false; } auto m = flexbuffers::GetRoot(reinterpret_cast<const uint8_t*>(data.data()), data.size()).AsMap(); mbstring sn = m["Name"].AsString().str(); string name = ut::AnsiToUTF16(sn); if (name != GetName()) { Debug->LogConsole(L"DataManager", L"AudioSource try Deserialize to" + name); return false; } bool active = m["IsActive"].AsBool(); SetActive(active); Mute = m["Mute"].AsBool(); Loop = m["Loop"].AsBool(); PlayOnAwake = m["PlayOnAwake"].AsBool(); Is3D = m["Is3D"].AsBool(); Volume = m["Volume"].AsFloat(); Range = m["Range"].AsFloat(); mbstring t = m["AudioClip"].AsString().str(); string clipName = ut::AnsiToUTF16(t); Clip = g_DataManager->GetAudioClip(clipName); if (!Clip) { Clip = g_DataManager->LoadAudioClip(g_Path + AudioClip::FILE_PATH + clipName + AudioClip::FILE_EXTENSION); } if (Clip) { if (Clip->Sound) Source = Clip->Sound->CreateInstance(DirectX::SoundEffectInstance_Use3D | DirectX::SoundEffectInstance_ReverbUseFilters).release(); } return true; } void hos::com::AudioSource::Play() { if (Source) { Source->SetVolume(Volume); if (Source->GetState() != DirectX::PLAYING) { Source->Play(Loop); } } } void hos::com::AudioSource::Stop() { if (Source) { Source->Stop(); } } void hos::com::AudioSource::Pause() { if (Source) { if (Source->GetState() == DirectX::PLAYING) { Source->Pause(); } } } DirectX::SoundState hos::com::AudioSource::GetState() { if (Source) { return Source->GetState(); } return DirectX::SoundState::STOPPED; } void hos::com::AudioSource::SetPitch(float pitch) { if (Source) { Source->SetPitch(std::clamp(pitch, -1.f, 1.f)); } }
18.868421
134
0.665411
Game-institute-1st-While-true
aba28b08d7e832242a5481ff7f3f6ef9a524e350
7,243
cpp
C++
include/cinolib/isocontour.cpp
goodengineer/cinolib
7de4de6816ed617e76a0517409e3e84c4546685e
[ "MIT" ]
null
null
null
include/cinolib/isocontour.cpp
goodengineer/cinolib
7de4de6816ed617e76a0517409e3e84c4546685e
[ "MIT" ]
null
null
null
include/cinolib/isocontour.cpp
goodengineer/cinolib
7de4de6816ed617e76a0517409e3e84c4546685e
[ "MIT" ]
null
null
null
/******************************************************************************** * This file is part of CinoLib * * Copyright(C) 2016: Marco Livesu * * * * The MIT License * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. 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. * * * * Author(s): * * * * Marco Livesu (marco.livesu@gmail.com) * * http://pers.ge.imati.cnr.it/livesu/ * * * * Italian National Research Council (CNR) * * Institute for Applied Mathematics and Information Technologies (IMATI) * * Via de Marini, 6 * * 16149 Genoa, * * Italy * *********************************************************************************/ #include <cinolib/isocontour.h> #include <cinolib/cino_inline.h> #include <cinolib/interval.h> #include <queue> namespace cinolib { template<class M, class V, class E, class P> CINO_INLINE Isocontour<M,V,E,P>::Isocontour() { iso_value = 0; } template<class M, class V, class E, class P> CINO_INLINE Isocontour<M,V,E,P>::Isocontour(AbstractPolygonMesh<M,V,E,P> & m, float iso_value) : iso_value(iso_value) { for(uint pid=0; pid<m.num_polys(); ++pid) for(uint i=0; i< m.poly_tessellation(pid).size()/3; ++i) { uint vid0 = m.poly_tessellation(pid).at(3*i+0),vid1 = m.poly_tessellation(pid).at(3*i+1),vid2 = m.poly_tessellation(pid).at(3*i+2); float f0=m.vert_data(vid0).uvw[0],f1=m.vert_data(vid1).uvw[0],f2=m.vert_data(vid2).uvw[0]; // There are seven possible cases: // 1) the curve coincides with (v0,v1) // 2) the curve coincides with (v1,v2) // 3) the curve coincides with (v2,v0) // 4) the curve enters from (v0,v1) and exits from (v0,v2) // 5) the curve enters from (v0,v1) and exits from (v1,v2) // 6) the curve enters from (v1,v2) and exits from (v2,v0) // 7) the does not pass fromm here bool through_v0=(iso_value == f0),through_v1=(iso_value==f1),through_v2=(iso_value==f2); bool crosses_v0_v1 = is_into_interval<float>(iso_value, f0, f1, true),crosses_v1_v2 = is_into_interval<float>(iso_value, f1, f2, true),crosses_v2_v0 = is_into_interval<float>(iso_value, f2, f0, true); float alpha0 = std::fabs(iso_value - f0)/fabs(f1 - f0),alpha1 = std::fabs(iso_value - f1)/fabs(f2 - f1),alpha3 = std::fabs(iso_value - f2)/fabs(f0 - f2);; if (through_v0 && through_v1) // case 1) the curve coincides with (v0,v1) { segs.push_back(m.vert(vid0)); segs.push_back(m.vert(vid1)); } else if (through_v1 && through_v2) // case 2) the curve coincides with (v1,v2) { segs.push_back(m.vert(vid1)); segs.push_back(m.vert(vid2)); } else if (through_v2 && through_v0) // 3) the curve coincides with (v2,v0) { segs.push_back(m.vert(vid2)); segs.push_back(m.vert(vid0)); } else if (crosses_v0_v1 && crosses_v1_v2) // case 4) the curve enters from (v0,v1) and exits from (v0,v2) { //float alpha0 = std::fabs(iso_value - f0)/fabs(f1 - f0),alpha1 = std::fabs(iso_value - f1)/fabs(f2 - f1); segs.push_back((1.0-alpha0)*m.vert(vid0) + alpha0*m.vert(vid1)); segs.push_back((1.0-alpha1)*m.vert(vid1) + alpha1*m.vert(vid2)); } else if (crosses_v0_v1 && crosses_v2_v0) // case 5) the curve enters from (v0,v1) and exits from (v1,v2) { //float alpha0 = std::fabs(iso_value - f0)/fabs(f1 - f0),alpha1 = std::fabs(iso_value - f2)/fabs(f0 - f2); segs.push_back((1.0-alpha0)*m.vert(vid0) + alpha0*m.vert(vid1)); segs.push_back((1.0-alpha3)*m.vert(vid2) + alpha3*m.vert(vid0)); } else if (crosses_v1_v2 && crosses_v2_v0) // 6) the curve enters from (v1,v2) and exits from (v2,v0) { //float alpha0 = std::fabs(iso_value - f1)/fabs(f2 - f1),alpha1 = std::fabs(iso_value - f2)/fabs(f0 - f2); segs.push_back((1.0-alpha1)*m.vert(vid1) + alpha1*m.vert(vid2)); segs.push_back((1.0-alpha3)*m.vert(vid2) + alpha3*m.vert(vid0)); } } } template<class M, class V, class E, class P> CINO_INLINE std::vector<uint> Isocontour<M,V,E,P>::tessellate(Trimesh<M,V,E,P> & m) const { typedef std::pair<uint,float> split_data; std::set<split_data,std::greater<split_data>> edges_to_split; // from highest to lowest id for(uint eid=0; eid<m.num_edges(); ++eid) { float f0 = m.vert_data(m.edge_vert_id(eid,0)).uvw[0],f1 = m.vert_data(m.edge_vert_id(eid,1)).uvw[0]; if (is_into_interval<float>(iso_value, f0, f1)) { float alpha = std::fabs(iso_value - f0)/fabs(f1 - f0); edges_to_split.insert(std::make_pair(eid,alpha)); } } std::vector<uint> new_vids; for(auto e : edges_to_split) { uint vid = m.edge_split(e.first, e.second); m.vert_data(vid).uvw[0] = iso_value; new_vids.push_back(vid); } return new_vids; } }
51.368794
208
0.510976
goodengineer
aba6181e7c5734b80cc6e6a560af90fb33a2d409
1,725
cpp
C++
source/Task.cpp
acs9307/alib-cpp
56eb3d31d979ef1b412d197e7ea8d10bac686077
[ "MIT" ]
1
2017-05-02T09:51:05.000Z
2017-05-02T09:51:05.000Z
source/Task.cpp
acs9307/alib-cpp
56eb3d31d979ef1b412d197e7ea8d10bac686077
[ "MIT" ]
null
null
null
source/Task.cpp
acs9307/alib-cpp
56eb3d31d979ef1b412d197e7ea8d10bac686077
[ "MIT" ]
null
null
null
#include "includes/Task.h" namespace alib { /****Initializers****/ void Task::init(task_callback callback, void* taskArg, alib_free_value freeArg, uint8_t loopsPerCallback) { tcb = callback; arg = taskArg; freeArgCb = freeArg; loopsPerCall = loopsPerCallback; /* Default init other members. */ loopCount = 0; } /********************/ /****Constructors****/ Task::Task() {} Task::Task(task_callback callback, void* taskArg, alib_free_value freeArg) : tcb(callback), arg(taskArg), freeArgCb(freeArg) {} Task::Task(task_callback callback, void* taskArg, alib_free_value freeArg, uint8_t loopsPerCallback) : tcb(callback), arg(taskArg), freeArgCb(freeArg), loopsPerCall(loopsPerCallback) {} /********************/ /****Getters****/ task_callback Task::getCallback() const { return(tcb); } void* Task::getArg()const { return(arg); } alib_free_value Task::getFreeArgCb()const { return(freeArgCb); } uint8_t Task::getLoopsPerCall() const { return(loopsPerCall); } /***************/ /****Setters****/ void Task::setCallback(task_callback callback) { tcb = callback; } void Task::setArg(void* taskArg, alib_free_value freeTaskArg) { if (arg && freeArgCb) freeArgCb(arg); arg = taskArg; freeArgCb = freeTaskArg; } void Task::setLoopsPerCall(uint8_t loopsPerCallback) { loopsPerCall = loopsPerCallback; if (loopCount > loopsPerCall) loopCount = loopsPerCall; } /***************/ void Task::loop() { if (!loopCount) { tcb(*this); loopCount = loopsPerCall; } else --loopCount; } void Task::free(void* _task) { if(!_task)return; Task* task = (Task*)_task; delete(task); } Task::~Task() { if (arg && freeArgCb) freeArgCb(arg); } }
22.402597
84
0.649275
acs9307
aba6f7ae9aadd6b2bfa8e803f56bce4c0f92a1b1
326
cc
C++
ultra_fast_mathematician.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
null
null
null
ultra_fast_mathematician.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
3
2021-01-04T18:33:39.000Z
2021-01-04T19:37:21.000Z
ultra_fast_mathematician.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
null
null
null
#include <iostream> #include <string> int main() { std::string a, b, c = ""; std::getline(std::cin, a); std::getline(std::cin, b); for (int i = 0; i < a.size(); ++i) { if (a[i] != b[i]) { c += "1"; } else { c += "0"; } } std::cout << c; return 0; }
19.176471
40
0.383436
maximilianbrine
aba83b2fb430d3a70dcec3c0cc5f05f4a01049cf
7,381
hpp
C++
DT3Core/Scripting/ScriptingRadioButton.hpp
nemerle/DT3
801615d507eda9764662f3a34339aa676170e93a
[ "MIT" ]
3
2016-01-27T13:17:18.000Z
2019-03-19T09:18:25.000Z
DT3Core/Scripting/ScriptingRadioButton.hpp
nemerle/DT3
801615d507eda9764662f3a34339aa676170e93a
[ "MIT" ]
1
2016-01-28T14:39:49.000Z
2016-01-28T22:12:07.000Z
DT3Core/Scripting/ScriptingRadioButton.hpp
adderly/DT3
e2605be091ec903d3582e182313837cbaf790857
[ "MIT" ]
3
2016-01-25T16:44:51.000Z
2021-01-29T19:59:45.000Z
#pragma once #ifndef DT3_SCRIPTINGPAGEFLIPPER #define DT3_SCRIPTINGPAGEFLIPPER //============================================================================== /// /// File: ScriptingRadioButton.hpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== #include "DT3Core/Scripting/ScriptingBase.hpp" //============================================================================== //============================================================================== namespace DT3 { //============================================================================== /// Forward declarations //============================================================================== //============================================================================== /// Boolean sequencer. //============================================================================== class ScriptingRadioButton: public ScriptingBase { public: DEFINE_TYPE(ScriptingRadioButton,ScriptingBase) DEFINE_CREATE_AND_CLONE DEFINE_PLUG_NODE ScriptingRadioButton (void); ScriptingRadioButton (const ScriptingRadioButton &rhs); ScriptingRadioButton & operator = (const ScriptingRadioButton &rhs); virtual ~ScriptingRadioButton (void); virtual void archive (const std::shared_ptr<Archive> &archive); /// Object was added to a world /// world world that object was added to virtual void add_to_world (World *world); /// Object was removed from a world virtual void remove_from_world (void); public: /// Called to initialize the object virtual void initialize (void); // Event handlers for each input void in1 (PlugNode *sender) { flip(sender,&_in1); } void in2 (PlugNode *sender) { flip(sender,&_in2); } void in3 (PlugNode *sender) { flip(sender,&_in3); } void in4 (PlugNode *sender) { flip(sender,&_in4); } void in5 (PlugNode *sender) { flip(sender,&_in5); } void in6 (PlugNode *sender) { flip(sender,&_in6); } void in7 (PlugNode *sender) { flip(sender,&_in7); } void in8 (PlugNode *sender) { flip(sender,&_in8); } void in9 (PlugNode *sender) { flip(sender,&_in9); } void in10 (PlugNode *sender) { flip(sender,&_in10); } void in11 (PlugNode *sender) { flip(sender,&_in11); } void in12 (PlugNode *sender) { flip(sender,&_in12); } void in13 (PlugNode *sender) { flip(sender,&_in13); } void in14 (PlugNode *sender) { flip(sender,&_in14); } void in15 (PlugNode *sender) { flip(sender,&_in15); } void in16 (PlugNode *sender) { flip(sender,&_in16); } void in17 (PlugNode *sender) { flip(sender,&_in17); } void in18 (PlugNode *sender) { flip(sender,&_in18); } void in19 (PlugNode *sender) { flip(sender,&_in19); } void in20 (PlugNode *sender) { flip(sender,&_in20); } private: void flip (PlugNode *sender, Event *in); Event _in1; Event _in2; Event _in3; Event _in4; Event _in5; Event _in6; Event _in7; Event _in8; Event _in9; Event _in10; Event _in11; Event _in12; Event _in13; Event _in14; Event _in15; Event _in16; Event _in17; Event _in18; Event _in19; Event _in20; Event _set1; Event _reset1; Event _set2; Event _reset2; Event _set3; Event _reset3; Event _set4; Event _reset4; Event _set5; Event _reset5; Event _set6; Event _reset6; Event _set7; Event _reset7; Event _set8; Event _reset8; Event _set9; Event _reset9; Event _set10; Event _reset10; Event _set11; Event _reset11; Event _set12; Event _reset12; Event _set13; Event _reset13; Event _set14; Event _reset14; Event _set15; Event _reset15; Event _set16; Event _reset16; Event _set17; Event _reset17; Event _set18; Event _reset18; Event _set19; Event _reset19; Event _set20; Event _reset20; }; //============================================================================== //============================================================================== } // DT3 #endif
49.536913
109
0.315811
nemerle
abaaca90eeb532ebd9937cf4f79f689e5e51d02b
1,602
cpp
C++
Cpp/Docker/ASM.cpp
lehtojo/Evie
f41b3872f6a1a7da1778c241c7b01823b36ac78d
[ "MIT" ]
12
2020-07-12T06:22:11.000Z
2022-02-27T13:19:19.000Z
Cpp/Docker/ASM.cpp
lehtojo/Evie
f41b3872f6a1a7da1778c241c7b01823b36ac78d
[ "MIT" ]
2
2020-07-12T06:22:48.000Z
2021-11-28T01:23:25.000Z
Cpp/Docker/ASM.cpp
lehtojo/Evie
f41b3872f6a1a7da1778c241c7b01823b36ac78d
[ "MIT" ]
3
2021-09-16T19:02:19.000Z
2021-11-28T00:50:15.000Z
#include "../../H/Docker/ASM.h" #include "../../H/UI/Safe.h" void ASM::ASM_Analyzer(vector<string>& Output) { //here we will just make an prototype from every label. Parser can analyse wich one is a function, and what is not. //and after that we want to give Evie Core the "use "filename"" without the preprosessor so that Evie Core can implement an //post-prosessing include vector<string> Header_Data = DOCKER::Get_Header(DOCKER::FileName.back()); if (Header_Data.size() < 1) Header_Data = DOCKER::Get_Header("asm..e"); if (Header_Data.size() < 1) Header_Data = DOCKER::Default_ASM_Header_Data; if (Header_Data.size() < 1) Report(Observation(ERROR, "Docker didn't find Header file for " + DOCKER::FileName.back(), Position())); //DOCKER::Separate_Identification_Patterns(Header_Data); vector<uint8_t> tmp = DOCKER::Get_Char_Buffer_From_File(DOCKER::FileName.back(), DOCKER::Working_Dir.back().second); string buffer = string((char*)tmp.data(), tmp.size()); Section Function_Section = DOCKER::Get_Section_From_String(buffer); string Tmp = string((char*)Function_Section.start, Function_Section.size); auto Types = DOCKER::Separate_Identification_Patterns(Header_Data); vector<pair<string, string>> Raw_Data = DOCKER::Get_Names_Of(Tmp, Types); for (auto& i : Raw_Data) { if (i.second.find("global ") != -1) i.second.erase(i.second.find("global "), 7); } DOCKER::Append(Output, Raw_Data); // //Syntax_Correcter(Raw_Data); //now make the obj token for YASM DOCKER::Assembly_Source_File.push_back(DOCKER::Working_Dir.back().second + DOCKER::FileName.back()); return; }
45.771429
124
0.730337
lehtojo
abb39c4e6463162fa3d0647f590f9a85288fbcb8
8,657
cpp
C++
sources/data/planet.cpp
n0dev/space-explorer
87088bbd620128d09467aed7e188b717a19367ab
[ "MIT" ]
null
null
null
sources/data/planet.cpp
n0dev/space-explorer
87088bbd620128d09467aed7e188b717a19367ab
[ "MIT" ]
null
null
null
sources/data/planet.cpp
n0dev/space-explorer
87088bbd620128d09467aed7e188b717a19367ab
[ "MIT" ]
null
null
null
#include <math.h> #include <fstream> #include <FTGL/ftgl.h> #include <GL/glew.h> #include "rapidjson/document.h" #include "../include/data/planet.h" #include "../include/gui.h" #include "../textures/loadpng.h" #include "../gameplay/observer.h" using namespace rapidjson; Planet *mercury; Planet *venus; Planet *earth; Planet *mars; Planet *jupiter; Planet *saturn; Planet *uranus; Planet *neptune; Planet *pluto; const std::string g_planetPath = "planets/"; const std::string g_texturePath = "planets/textures/"; inline double deg2rad(double deg) { return deg * 3.1415 / 180.0; } Planet::Planet(std::string json_file) { // Open and parse json file std::string json_path = g_planetPath; json_path += json_file; std::ifstream file(json_path); if (!file.good()) { std::cerr << "Cannot open " << json_file << std::endl; exit(1); } std::string json((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); Document document; document.Parse(json.c_str()); // Store all mandatory values m_name = document["Name"].GetString(); m_radius = document["Radius"].GetDouble(); // Load the ground texture std::string texturePath = g_texturePath; texturePath += std::string(document["GroundTexture"].GetString()); if (!(m_ground_texture = loadPNGTexture(texturePath.c_str()))) { std::cerr << "Failed to load " << texturePath << "! aborting" << std::endl; exit(1); } if (document.HasMember("AxialTilt")) { m_axialTilt = static_cast<GLfloat>(document["AxialTilt"].GetDouble()); } // Load orbit information and creates it if (document.HasMember("Orbit")) { if (document["Orbit"].HasMember("Aphelion")) { m_orbit.Aphelion = document["Orbit"]["Aphelion"].GetDouble(); } if (document["Orbit"].HasMember("Perihelion")) { m_orbit.Perihelion = document["Orbit"]["Perihelion"].GetDouble(); } if (document["Orbit"].HasMember("SemiMajorAxis")) { m_orbit.SemiMajorAxis = document["Orbit"]["SemiMajorAxis"].GetDouble(); } if (document["Orbit"].HasMember("Eccentricity")) { m_orbit.Eccentricity = document["Orbit"]["Eccentricity"].GetDouble(); } if (document["Orbit"].HasMember("Inclination")) { m_orbit.Inclination = document["Orbit"]["Inclination"].GetDouble(); } if (document["Orbit"].HasMember("ArgumentOfPeriapsis")) { m_orbit.ArgumentOfPeriapsis = document["Orbit"]["ArgumentOfPeriapsis"].GetDouble(); } if (document["Orbit"].HasMember("LongitudeOfAscendingNode")) { m_orbit.LongitudeOfAscendingNode = document["Orbit"]["LongitudeOfAscendingNode"].GetDouble(); } if (document["Orbit"].HasMember("MeanAnomaly")) { m_orbit.MeanAnomaly = document["Orbit"]["MeanAnomaly"].GetDouble(); } if (document["Orbit"].HasMember("OrbitalPeriod")) { m_orbit.OrbitalPeriod = document["Orbit"]["OrbitalPeriod"].GetDouble(); } if (document["Orbit"].HasMember("OrbitalSpeed")) { m_orbit.OrbitalSpeed = document["Orbit"]["OrbitalSpeed"].GetDouble(); } createOrbit(); } // Load rings information and creates it if (document.HasMember("Rings")) { m_inner_radius = document["Rings"]["InnerDistance"].GetDouble(); m_outer_radius = document["Rings"]["OuterDistance"].GetDouble(); std::string ringTexturePath = g_texturePath; ringTexturePath += std::string(document["Rings"]["Texture"].GetString()); if (!(m_ring_texture = loadPNGTexture(ringTexturePath.c_str()))) { fprintf(stderr, "failed to load saturn! aborting\n"); exit(1); } createRings(); } // Create the planet mesh GLUquadricObj *sphere = NULL; sphere = gluNewQuadric(); gluQuadricDrawStyle(sphere, GLU_FILL); gluQuadricNormals(sphere, GLU_SMOOTH); gluQuadricTexture(sphere, 1); list = glGenLists(1); glNewList(list, GL_COMPILE); gluSphere(sphere, m_radius, 1000, 1000); glEndList(); gluDeleteQuadric(sphere); // Misc loc = new FTPoint(0.0, 0.0); // Lights sunLight = new GLShader("../sources/shaders/sunlight.vert", "../sources/shaders/sunlight.frag"); idGroundMap = glGetUniformLocation(sunLight->program, "tex"); idSunPosition = glGetUniformLocation(sunLight->program, "sunPosition"); } void draw_disk(double inner_radius, double outer_radius, int slices) { double theta; glBegin(GL_QUAD_STRIP); for (int inc = 0; inc <= slices; inc++) { theta = inc * 2.0 * M_PI / slices; glTexCoord2f(1.0, 0.0); glVertex3d(outer_radius * cos(theta), outer_radius * sin(theta), 0.0); glTexCoord2f(0.0, 0.0); glVertex3d(inner_radius * cos(theta), inner_radius * sin(theta), 0.0); } glEnd(); } void Planet::createRings() { GLUquadricObj *ring = NULL; ring = gluNewQuadric(); gluQuadricDrawStyle(ring, GLU_FILL); gluQuadricNormals(ring, GLU_SMOOTH); gluQuadricTexture(ring, 1); m_ring_list = glGenLists(2); glNewList(m_ring_list, GL_COMPILE); draw_disk(m_inner_radius, m_outer_radius, 800); glEndList(); gluDeleteQuadric(ring); m_is_ring = true; } double t = 0.0; void Planet::draw(void) { const GLdouble a = m_orbit.SemiMajorAxis; const GLdouble b = a * sqrt(1.0 - m_orbit.Eccentricity * m_orbit.Eccentricity); glPushMatrix(); glTranslated(-spaceship->pos.x, -spaceship->pos.y, -spaceship->pos.z); if (m_orbit.LongitudeOfAscendingNode != 0.0) { glRotated(m_orbit.LongitudeOfAscendingNode, 0, 0, 1); } if (m_orbit.ArgumentOfPeriapsis != 0.0) { glRotated(m_orbit.ArgumentOfPeriapsis, 0, 0, 1); } if (m_orbit.Inclination != 0.0) { glRotated(m_orbit.Inclination, 1, 0, 0); } if (m_displayOrbit) { glCallList(m_orbit_list); } // Compute position of the planet if (m_orbit.OrbitalSpeed > 10.0) { m_positionX = a * cos(t += 0.00001); m_positionY = b * sin(t += 0.00001); } else { m_positionX = a; m_positionY = 0.0; } glTranslated(m_positionX, m_positionY, 0.0); if (m_axialTilt != 0) { glRotatef(m_axialTilt, 1, 0, 0); } glPushMatrix(); glTranslated(0.0, 0.0, 1.5 * m_radius); glRasterPos2f(0, 0); font->Render(m_name.c_str(), -1, *loc); glPopMatrix(); sunLight->begin(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_ground_texture); glUniform1i(idGroundMap, 1); const GLfloat vecSunPosition[3] = {(GLfloat) -spaceship->pos.x, (GLfloat) -spaceship->pos.y, (GLfloat) -spaceship->pos.z}; glUniform3fv(idSunPosition, 1, vecSunPosition); glCallList(this->list); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE0); sunLight->end(); if (m_is_ring) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_ring_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); glCallList(m_ring_list); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); } glPopMatrix(); } void Planet::lookAt() { spaceship->lookAt(m_positionX - spaceship->pos.x, m_positionY - spaceship->pos.y, m_positionZ - spaceship->pos.z); } void Planet::createOrbit() { // Set information const int edges = 6000; // Build the orbit const GLdouble a = m_orbit.SemiMajorAxis; const GLdouble b = a * sqrt(1.0 - m_orbit.Eccentricity * m_orbit.Eccentricity); GLdouble x, y, z, r; GLUquadricObj *o = NULL; o = gluNewQuadric(); gluQuadricNormals(o, GLU_SMOOTH); m_orbit_list = glGenLists(2); glNewList(m_orbit_list, GL_COMPILE); glBegin(GL_LINE_LOOP); for (int t = 0; t <= edges; t += 1) { r = deg2rad(360.0 * t / edges); x = a * cos(r); y = b * sin(r); z = 0; glVertex3d(x, y, z); } glEnd(); glEndList(); gluDeleteQuadric(o); // Set the new position of the planet here m_positionX = m_orbit.SemiMajorAxis; } void Planet::displayOrbit(bool b) { m_displayOrbit = b; }
31.944649
118
0.631859
n0dev
abb67a710058c771ece4227facb9d97f4c223d47
15,580
cpp
C++
sdl1/f1spirit/F1Spirit-auxiliar.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/f1spirit/F1Spirit-auxiliar.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/f1spirit/F1Spirit-auxiliar.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
#ifdef _WIN32 #include <windows.h> #include <windowsx.h> #else #include <sys/time.h> #include <time.h> #endif #include <stdio.h> #include <stdlib.h> #include "ctype.h" #include "string.h" #include "math.h" #include "SDL.h" #include "SDL_image.h" #include "SDL_mixer.h" #include "auxiliar.h" #include "List.h" #include "sound.h" #include "F1Spirit-auxiliar.h" #ifdef KITSCHY_DEBUG_MEMORY #include "debug_memorymanager.h" #endif SDL_Surface *frame_corner[4] = {0, 0, 0, 0}; SDL_Surface *frame_h[2] = {0, 0}, *frame_v[2] = {0, 0}; int linear_base [ 16] = {0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2}; int corner_base1[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }; int corner_base2[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }; void free_auxiliar_menu_surfaces(void) { int i; for (i = 0;i < 4;i++) { if (frame_corner[i] != 0) SDL_FreeSurface(frame_corner[i]); frame_corner[i] = 0; } if (frame_h[0] != 0) SDL_FreeSurface(frame_h[0]); frame_h[0] = 0; if (frame_h[1] != 0) SDL_FreeSurface(frame_h[1]); frame_h[1] = 0; if (frame_v[0] != 0) SDL_FreeSurface(frame_v[0]); frame_v[0] = 0; if (frame_v[1] != 0) SDL_FreeSurface(frame_v[1]); frame_v[1] = 0; } /* free_auxiliar_menu_surfaces */ SDL_Surface *load_bmp_font(char *filename, int first, int last) { SDL_Surface *bitmap_font = 0; SDL_Surface *sfc = IMG_Load(filename); if (sfc != 0) { int w = (sfc->w / (last - first)); bitmap_font = SDL_CreateRGBSurface(SDL_SWSURFACE, w * 256, sfc->h, 32, RMASK, GMASK, BMASK, AMASK); SDL_SetAlpha(bitmap_font, 0, 0); SDL_FillRect(bitmap_font, 0, 0); } if (bitmap_font != 0) { int i, j, k, s; Uint32 color; s = sfc->w / (last - first); for (k = 0;k < 256;k++) { if (k >= first && k < last) { for (i = 0;i < s;i++) { for (j = 0;j < sfc->h;j++) { SDL_LockSurface(sfc); color = getpixel(sfc, (k - first) * s + i, j); SDL_UnlockSurface(sfc); SDL_LockSurface(bitmap_font); putpixel(bitmap_font, k*s + i, j, color); SDL_UnlockSurface(bitmap_font); } } } } } return bitmap_font; } /* load_bmp_font */ SDL_Surface *draw_menu(int MAX_OPTIONS, char *title, char *options, int *option_type, int selected, float sel_factor, float enter_factor, SDL_Surface *font, int *first_option) { SDL_Surface *sfc; int w = 0, h = 0; int title_w = 0, title_h = 0; int options_w = 0, options_h = 0; int n_options = 0; /* Compute the number of options: */ { int i; i = 0; while (options != 0 && options[i] != 0) { if (options[i] == '\n') n_options++; i++; } } if (selected < *first_option) { *first_option = selected; } if ((*first_option) + (MAX_OPTIONS - 1) < selected) { *first_option = selected - (MAX_OPTIONS - 1); } /* Compute the size of the surface: */ /* title + options + frame */ if (title != 0) { title_w = get_text_width_bmp((unsigned char *)title, font, 0); title_h = font->h + 8; } { int count = 0; int i, j, s; char text_tmp[256]; i = j = 0; s = font->w / 256; while (options != 0 && options[i] != 0) { text_tmp[j] = options[i]; if (options[i] == '\n') { text_tmp[j] = 0; if (option_type != 0 && (option_type[count] == 11)) { if (int(strlen(text_tmp))*s + 7 > options_w) options_w = strlen(text_tmp) * s + 7; } else { if (int(strlen(text_tmp))*s > options_w) options_w = strlen(text_tmp) * s; } if (count >= *first_option && count < (*first_option + MAX_OPTIONS)) { options_h += font->h - 2; } count++; j = 0; } else { j++; } i++; } options_h += 2; } if (options != 0) { options_w += 32; /* 8*2 : frame + 8*2 : gap between text and frame */ options_h += 32; /* 8*2 : frame + 8*2 : gap between text and frame */ } w = max(title_w, options_w); h = title_h + options_h; if (w > 0 && h > 0) { int y = 0; int max_y = h; if (title != 0) max_y -= font->h + 8; max_y -= 32; max_y = int(max_y * enter_factor); max_y += 32; if (title != 0) max_y += font->h + 8; sfc = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, RMASK, GMASK, BMASK, AMASK); SDL_SetAlpha(sfc, 0, 0); SDL_FillRect(sfc, 0, 0); /* Draw the elements of the menu: */ /* title: */ if (title != 0) { SDL_Rect r; print_left_bmp((unsigned char *)title, font, sfc, 0, 0, 0); r.x = 0; r.y = 0; r.w = get_text_width_bmp((unsigned char *)title, font, 0); r.h = font->h; surface_fader(sfc, 1, 1, 1, enter_factor, &r); y += font->h + 8; } else { y++; } y = y + 16; /* options: */ { int i, j, count = 0, s, sel = 0; char text_tmp[256]; i = j = 0; s = font->w / 256; while (options != 0 && options[i] != 0 && y < max_y) { text_tmp[j] = options[i]; if (options[i] == '\n') { if (sel >= *first_option && sel < (*first_option + MAX_OPTIONS)) { text_tmp[j] = 0; print_left_bmp((unsigned char *)text_tmp, font, sfc, 16, y, 0); if (option_type != 0 && (option_type[count] == 11)) { int w = get_text_width_bmp((unsigned char *)text_tmp, font, 0); Uint32 color = SDL_MapRGB(sfc->format, 255, 255, 255); Uint32 color2 = SDL_MapRGB(sfc->format, 0, 0, 0); /* Draw triangle that denotes that the option leads to a submenu: */ putpixel(sfc, 16 + w + 4, y + 6, color); putpixel(sfc, 16 + w + 4, y + 7, color); putpixel(sfc, 16 + w + 4, y + 8, color); putpixel(sfc, 16 + w + 4, y + 9, color); putpixel(sfc, 16 + w + 4, y + 10, color); putpixel(sfc, 16 + w + 5, y + 7, color); putpixel(sfc, 16 + w + 5, y + 8, color); putpixel(sfc, 16 + w + 5, y + 9, color); putpixel(sfc, 16 + w + 6, y + 8, color); /* bloack outline: */ putpixel(sfc, 16 + w + 3, y + 6, color2); putpixel(sfc, 16 + w + 3, y + 7, color2); putpixel(sfc, 16 + w + 3, y + 8, color2); putpixel(sfc, 16 + w + 3, y + 9, color2); putpixel(sfc, 16 + w + 3, y + 10, color2); putpixel(sfc, 16 + w + 4, y + 5, color2); putpixel(sfc, 16 + w + 4, y + 11, color2); putpixel(sfc, 16 + w + 5, y + 6, color2); putpixel(sfc, 16 + w + 5, y + 10, color2); putpixel(sfc, 16 + w + 6, y + 7, color2); putpixel(sfc, 16 + w + 6, y + 9, color2); putpixel(sfc, 16 + w + 7, y + 8, color2); } /* Selected option: */ if (sel == selected) { SDL_Rect r; r.x = 16; r.y = y; r.w = get_text_width_bmp((unsigned char *)text_tmp, font, 0); r.h = font->h; if (option_type != 0 && (option_type[count] == 11)) r.w += 7; surface_fader(sfc, sel_factor, sel_factor, sel_factor, 1, &r); } if (option_type != 0 && (option_type[count] < 0)) { SDL_Rect r; r.x = 16; r.y = y; r.w = get_text_width_bmp((unsigned char *)text_tmp, font, 0); r.h = font->h; surface_fader(sfc, 0.5F, 0.5F, 0.5F, 1, &r); } y += font->h - 2; } count++; j = 0; sel++; } else { j++; } i++; } y += 2; } { /* Delete the options that have been drawn and shouldn't: */ SDL_Rect r; r.x = 0; r.y = max_y - 16; r.w = w; r.h = y - (max_y - 16); SDL_FillRect(sfc, &r, 0); } /* frame: */ if (title != 0) y = font->h + 8; else y = 2; draw_menu_frame(sfc, 0, y, w, max_y - y); /* flechas de scroll: */ if (enter_factor == 1) { if (*first_option > 0) { Uint32 color = SDL_MapRGB(sfc->format, 255, 255, 255); putpixel(sfc, w / 2, y + 13, color); putpixel(sfc, (w / 2) - 1, y + 14, color); putpixel(sfc, (w / 2), y + 14, color); putpixel(sfc, (w / 2) + 1, y + 14, color); putpixel(sfc, (w / 2) - 2, y + 15, color); putpixel(sfc, (w / 2) - 1, y + 15, color); putpixel(sfc, (w / 2), y + 15, color); putpixel(sfc, (w / 2) + 1, y + 15, color); putpixel(sfc, (w / 2) + 2, y + 15, color); } if ((*first_option + (MAX_OPTIONS)) < n_options) { Uint32 color = SDL_MapRGB(sfc->format, 255, 255, 255); putpixel(sfc, w / 2, max_y - 13, color); putpixel(sfc, (w / 2) - 1, max_y - 14, color); putpixel(sfc, (w / 2), max_y - 14, color); putpixel(sfc, (w / 2) + 1, max_y - 14, color); putpixel(sfc, (w / 2) - 2, max_y - 15, color); putpixel(sfc, (w / 2) - 1, max_y - 15, color); putpixel(sfc, (w / 2), max_y - 15, color); putpixel(sfc, (w / 2) + 1, max_y - 15, color); putpixel(sfc, (w / 2) + 2, max_y - 15, color); } } if (enter_factor < 0.510) surface_fader(sfc, 1, 1, 1, enter_factor*2, 0); return sfc; } return 0; } /* draw_menu */ void draw_menu_frame(SDL_Surface *sfc, int x, int y, int dx, int dy, int a) { if (frame_corner[0] == 0) { int i, j; // float /*d,x,y,*/c; Uint32 color; /* Compute the frame graphics: */ frame_corner[0] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 16, 32, RMASK, GMASK, BMASK, AMASK); frame_corner[1] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 16, 32, RMASK, GMASK, BMASK, AMASK); frame_corner[2] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 16, 32, RMASK, GMASK, BMASK, AMASK); frame_corner[3] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 16, 32, RMASK, GMASK, BMASK, AMASK); frame_v[0] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 1, 32, RMASK, GMASK, BMASK, AMASK); frame_h[0] = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, 16, 32, RMASK, GMASK, BMASK, AMASK); frame_v[1] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 1, 32, RMASK, GMASK, BMASK, AMASK); frame_h[1] = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, 16, 32, RMASK, GMASK, BMASK, AMASK); SDL_SetAlpha(frame_corner[0], 0, 0); SDL_SetAlpha(frame_corner[1], 0, 0); SDL_SetAlpha(frame_corner[2], 0, 0); SDL_SetAlpha(frame_corner[3], 0, 0); SDL_SetAlpha(frame_v[0], 0, 0); SDL_SetAlpha(frame_v[1], 0, 0); SDL_SetAlpha(frame_h[0], 0, 0); SDL_SetAlpha(frame_h[1], 0, 0); for (i = 0;i < 16;i++) { if (linear_base[i] == 0) color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, 0); if (linear_base[i] == 1) color = SDL_MapRGBA(frame_corner[0]->format, 255, 255, 255, 255); if (linear_base[i] == 2) color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, a); putpixel(frame_v[0], i, 0, color); putpixel(frame_h[0], 0, i, color); putpixel(frame_v[1], 15 - i, 0, color); putpixel(frame_h[1], 0, 15 - i, color); } // for for (i = 0;i < 16;i++) { for (j = 0;j < 16;j++) { if (corner_base1[j + i*16] == 0) color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, 0); if (corner_base1[j + i*16] == 1) color = SDL_MapRGBA(frame_corner[0]->format, 255, 255, 255, 255); if (corner_base1[j + i*16] == 2) color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, a); putpixel(frame_corner[0], i, j, color); putpixel(frame_corner[3], 15 - i, 15 - j, color); if (corner_base2[j + i*16] == 0) color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, 0); if (corner_base2[j + i*16] == 1) color = SDL_MapRGBA(frame_corner[0]->format, 255, 255, 255, 255); if (corner_base2[j + i*16] == 2) color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, a); putpixel(frame_corner[2], i, 15 - j, color); putpixel(frame_corner[1], 15 - i, j, color); } // for } // for } SDL_Rect r; int i, j; r.x = x; r.y = y; SDL_BlitSurface(frame_corner[0], 0, sfc, &r); r.x = x + dx - 16; r.y = y; SDL_BlitSurface(frame_corner[1], 0, sfc, &r); r.x = x; r.y = y + dy - 16; SDL_BlitSurface(frame_corner[2], 0, sfc, &r); r.x = x + dx - 16; r.y = y + dy - 16; SDL_BlitSurface(frame_corner[3], 0, sfc, &r); for (i = y + 16;i < y + dy - 16;i++) { r.x = x; r.y = i; SDL_BlitSurface(frame_v[0], 0, sfc, &r); r.x = x + dx - 16; r.y = i; SDL_BlitSurface(frame_v[1], 0, sfc, &r); } for (i = x + 16;i < x + dx - 16;i++) { r.x = i; r.y = y; SDL_BlitSurface(frame_h[0], 0, sfc, &r); r.x = i; r.y = y + dy - 16; SDL_BlitSurface(frame_h[1], 0, sfc, &r); } { Uint8 *p; for (j = 10;j < dy - 10;j++) { p = (Uint8 *)sfc->pixels + (y + j) * sfc->pitch + (x + 10) * 4; for (i = 10;i < dx - 10;i++, p += 4) { /* FIXME: for some weird reason, changing the AOFFSET here doesn't work instead on alpha it uses red (ROFFSET)... probably has something to do with bitshifting and endianness this works, but should be fixed! */ #if SDL_BYTEORDER == SDL_BIG_ENDIAN *((Uint32 *)p) = ((*(Uint32 *)p) | ((Uint32)a << (ROFFSET * 8))); #else *((Uint32 *)p) = ((*(Uint32 *)p) | ((Uint32)a << (AOFFSET * 8))); #endif } } } } void draw_menu_frame(SDL_Surface *sfc, int x, int y, int dx, int dy) { draw_menu_frame(sfc, x, y, dx, dy, 192); } SOUNDT load_sfx(char *folder, char *default_folder, char *sample) { char tmp[256]; SOUNDT stmp; sprintf(tmp, "%s%s", folder, sample); if (Sound_file_test(tmp)) { stmp = Sound_create_sound(tmp); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("%s: %p\n", tmp, stmp); #endif return stmp; } sprintf(tmp, "%s%s", default_folder, sample); stmp = Sound_create_sound(tmp); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("%s: %p\n", tmp, stmp); #endif return stmp; } /* load_sfx */
25.625
175
0.508023
pdpdds
abb7de1094601dbf1560777070d4c17f69bae869
3,767
cpp
C++
tf2_src/hammer/replacetexdlg.cpp
IamIndeedGamingAsHardAsICan03489/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/hammer/replacetexdlg.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/hammer/replacetexdlg.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //=============================================================================// #include "stdafx.h" #include "hammer.h" #include "ReplaceTexDlg.h" #include "MainFrm.h" #include "GlobalFunctions.h" #include "TextureBrowser.h" #include "TextureSystem.h" #include "mapdoc.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> CReplaceTexDlg::CReplaceTexDlg(int nSelected, CWnd* pParent /*=NULL*/) : CDialog(CReplaceTexDlg::IDD, pParent) { //{{AFX_DATA_INIT(CReplaceTexDlg) m_iSearchAll = nSelected ? FALSE : TRUE; m_strFind = _T(""); m_strReplace = _T(""); m_iAction = 0; m_bMarkOnly = FALSE; m_bHidden = FALSE; m_bRescaleTextureCoordinates = false; //}}AFX_DATA_INIT m_nSelected = nSelected; } void CReplaceTexDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CReplaceTexDlg) DDX_Control(pDX, IDC_FIND, m_cFind); DDX_Control(pDX, IDC_REPLACE, m_cReplace); DDX_Control(pDX, IDC_REPLACEPIC, m_cReplacePic); DDX_Control(pDX, IDC_FINDPIC, m_cFindPic); DDX_Radio(pDX, IDC_INMARKED, m_iSearchAll); DDX_Text(pDX, IDC_FIND, m_strFind); DDX_Text(pDX, IDC_REPLACE, m_strReplace); DDX_Radio(pDX, IDC_ACTION, m_iAction); DDX_Check(pDX, IDC_MARKONLY, m_bMarkOnly); DDX_Check(pDX, IDC_HIDDEN, m_bHidden); DDX_Check(pDX, IDC_RESCALETEXTURECOORDINATES, m_bRescaleTextureCoordinates); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CReplaceTexDlg, CDialog) //{{AFX_MSG_MAP(CReplaceTexDlg) ON_BN_CLICKED(IDC_BROWSEREPLACE, OnBrowsereplace) ON_BN_CLICKED(IDC_BROWSEFIND, OnBrowsefind) ON_EN_UPDATE(IDC_FIND, OnUpdateFind) ON_EN_UPDATE(IDC_REPLACE, OnUpdateReplace) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CReplaceTexDlg message handlers void CReplaceTexDlg::BrowseTex(int iEdit) { CString strTex; CWnd *pWnd = GetDlgItem(iEdit); pWnd->GetWindowText(strTex); CTextureBrowser *pBrowser = new CTextureBrowser(GetMainWnd()); pBrowser->SetUsed(iEdit == IDC_FIND); pBrowser->SetInitialTexture(strTex); if (pBrowser->DoModal() == IDOK) { IEditorTexture *pTex = g_Textures.FindActiveTexture(pBrowser->m_cTextureWindow.szCurTexture); char szName[MAX_PATH]; if (pTex != NULL) { pTex->GetShortName(szName); } else { szName[0] = '\0'; } pWnd->SetWindowText(szName); } delete pBrowser; } void CReplaceTexDlg::OnBrowsereplace() { BrowseTex(IDC_REPLACE); } void CReplaceTexDlg::OnBrowsefind() { BrowseTex(IDC_FIND); } // // find/replace text string updates: // void CReplaceTexDlg::OnUpdateFind() { // get texture window and set texture in there CString strTex; m_cFind.GetWindowText(strTex); IEditorTexture *pTex = g_Textures.FindActiveTexture(strTex); m_cFindPic.SetTexture(pTex); } void CReplaceTexDlg::OnUpdateReplace() { // get texture window and set texture in there CString strTex; m_cReplace.GetWindowText(strTex); IEditorTexture *pTex = g_Textures.FindActiveTexture(strTex); m_cReplacePic.SetTexture(pTex); } BOOL CReplaceTexDlg::OnInitDialog() { CDialog::OnInitDialog(); if(!m_nSelected) { CWnd *pWnd = GetDlgItem(IDC_INMARKED); pWnd->EnableWindow(FALSE); } OnUpdateFind(); return TRUE; } void CReplaceTexDlg::DoReplaceTextures() { CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); if ( pDoc ) { pDoc->ReplaceTextures( m_strFind, m_strReplace, m_iSearchAll, m_iAction | ( m_bMarkOnly ? 0x100 : 0 ), m_bHidden, (m_bRescaleTextureCoordinates != 0) ); } }
22.289941
95
0.68171
IamIndeedGamingAsHardAsICan03489
abc0c946edd3d6dfabe817ff8e86c87b3aecf71c
7,107
cpp
C++
BCG/BCGPToolbarSystemMenuButton.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
BCG/BCGPToolbarSystemMenuButton.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
BCG/BCGPToolbarSystemMenuButton.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of the BCGControlBar Library // Copyright (C) 1998-2014 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // BCGToolbarSystemMenuButton.cpp: implementation of the CBCGPToolbarSystemMenuButton class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <afxpriv.h> #include "BCGPToolBar.h" #include "BCGPToolbarSystemMenuButton.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif IMPLEMENT_SERIAL(CBCGPToolbarSystemMenuButton, CBCGPToolbarMenuButton, VERSIONABLE_SCHEMA | 1) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBCGPToolbarSystemMenuButton::CBCGPToolbarSystemMenuButton() { m_hSysMenuIcon = NULL; m_hSystemMenu = NULL; } //**************************************************************************************** CBCGPToolbarSystemMenuButton::CBCGPToolbarSystemMenuButton (HMENU hSystemMenu, HICON hSystemIcon) : CBCGPToolbarMenuButton (0, hSystemMenu, -1) { m_hSysMenuIcon = hSystemIcon; m_hSystemMenu = hSystemMenu; if (m_hSysMenuIcon == NULL) { m_hSysMenuIcon = globalData.m_hiconApp; } } //**************************************************************************************** CBCGPToolbarSystemMenuButton::~CBCGPToolbarSystemMenuButton() { } //**************************************************************************************** void CBCGPToolbarSystemMenuButton::CopyFrom (const CBCGPToolbarButton& s) { CBCGPToolbarMenuButton::CopyFrom (s); const CBCGPToolbarSystemMenuButton& src = (const CBCGPToolbarSystemMenuButton&) s; m_hSysMenuIcon = src.m_hSysMenuIcon; m_hSystemMenu = src.m_hSystemMenu; } //**************************************************************************************** SIZE CBCGPToolbarSystemMenuButton::OnCalculateSize (CDC* /*pDC*/, const CSize& sizeDefault, BOOL /*bHorz*/) { return CSize (::GetSystemMetrics (SM_CXMENUSIZE), sizeDefault.cy); } //**************************************************************************************** void CBCGPToolbarSystemMenuButton::OnDraw (CDC* pDC, const CRect& rect, CBCGPToolBarImages* /*pImages*/, BOOL /*bHorz*/, BOOL /*bCustomizeMode*/, BOOL /*bHighlight*/, BOOL /*bDrawBorder*/, BOOL /*bGrayDisabledButtons*/) { if (m_hSysMenuIcon != NULL) { CSize size (min (::GetSystemMetrics (SM_CXSMICON), ::GetSystemMetrics (SM_CXMENUSIZE)), min (::GetSystemMetrics (SM_CYSMICON), ::GetSystemMetrics (SM_CYMENUSIZE))); int iOffset = (rect.Height () - size.cy) / 2; ::DrawIconEx (*pDC, rect.left, rect.top + iOffset, m_hSysMenuIcon, size.cx, size.cy, 0, NULL, DI_NORMAL); } else { pDC->FillSolidRect(rect, RGB(255, 0, 0)); } } //**************************************************************************************** void CBCGPToolbarSystemMenuButton::OnDblClick (CWnd* pWnd) { if (CBCGPToolBar::IsCustomizeMode ()) { return; } ASSERT (pWnd != NULL); ////////////////////////////////////////////// // Make sure to close the popup menu and // find the MDI frame correctly. //-------------------------------------------- OnCancelMode (); CFrameWnd* pParentFrame = BCGPGetParentFrame (pWnd); if(pParentFrame != NULL && pParentFrame->IsKindOf (RUNTIME_CLASS (CMiniDockFrameWnd))) { pParentFrame = (CFrameWnd*) pParentFrame->GetParent (); } CMDIFrameWnd* pMDIFrame = DYNAMIC_DOWNCAST (CMDIFrameWnd, pParentFrame); if (pMDIFrame != NULL) { CMDIChildWnd* pChild = pMDIFrame->MDIGetActive (); ASSERT_VALID (pChild); BOOL bCloseIsDisabled = FALSE; CMenu* pSysMenu = pChild->GetSystemMenu (FALSE); if (pSysMenu != NULL) { MENUITEMINFO menuInfo; ZeroMemory(&menuInfo,sizeof(MENUITEMINFO)); menuInfo.cbSize = sizeof(MENUITEMINFO); menuInfo.fMask = MIIM_STATE; pSysMenu->GetMenuItemInfo (SC_CLOSE, &menuInfo); bCloseIsDisabled = ((menuInfo.fState & MFS_GRAYED) || (menuInfo.fState & MFS_DISABLED)); } if (!bCloseIsDisabled) { pChild->SendMessage (WM_SYSCOMMAND, SC_CLOSE); } } //-------------------------------------------- ////////////////////////////////////////////// } //**************************************************************************************** void CBCGPToolbarSystemMenuButton::CreateFromMenu (HMENU hMenu) { m_hSystemMenu = hMenu; } //**************************************************************************************** HMENU CBCGPToolbarSystemMenuButton::CreateMenu () const { ASSERT (m_hSystemMenu != NULL); HMENU hMenu = CBCGPToolbarMenuButton::CreateMenu (); if (hMenu == NULL) { return NULL; } //--------------------------------------------------------------------- // System menu don't produce updating command statuses via the // standard MFC idle command targeting. So, we should enable/disable // system menu items according to the standard system menu status: //--------------------------------------------------------------------- CMenu* pMenu = CMenu::FromHandle (hMenu); ASSERT_VALID (pMenu); CMenu* pSysMenu = CMenu::FromHandle (m_hSystemMenu); ASSERT_VALID (pSysMenu); int iCount = (int) pSysMenu->GetMenuItemCount (); for (int i = 0; i < iCount; i ++) { UINT uiState = pSysMenu->GetMenuState (i, MF_BYPOSITION); UINT uiCmd = pSysMenu->GetMenuItemID (i); if (uiState & MF_CHECKED) { pMenu->CheckMenuItem (uiCmd, MF_CHECKED); } if (uiState & MF_DISABLED) { pMenu->EnableMenuItem (uiCmd, MF_DISABLED); } if (uiState & MF_GRAYED) { pMenu->EnableMenuItem (uiCmd, MF_GRAYED); } } return hMenu; } //**************************************************************************************** void CBCGPToolbarSystemMenuButton::OnCancelMode () { if (m_pPopupMenu != NULL && ::IsWindow (m_pPopupMenu->m_hWnd)) { if (m_pPopupMenu->InCommand ()) { return; } m_pPopupMenu->SaveState (); m_pPopupMenu->m_bAutoDestroyParent = FALSE; m_pPopupMenu->CloseMenu (); } m_pPopupMenu = NULL; m_bToBeClosed = FALSE; } //**************************************************************************************** void CBCGPToolbarSystemMenuButton::OnAfterCreatePopupMenu () { if (m_pPopupMenu != NULL && ::IsWindow (m_pPopupMenu->m_hWnd)) { CFrameWnd* pParentFrame = BCGCBProGetTopLevelFrame (m_pPopupMenu); if(pParentFrame != NULL && pParentFrame->IsKindOf (RUNTIME_CLASS (CMiniDockFrameWnd))) { pParentFrame = (CFrameWnd*) pParentFrame->GetParent (); } CMDIFrameWnd* pMDIFrame = DYNAMIC_DOWNCAST (CMDIFrameWnd, pParentFrame); if (pMDIFrame != NULL) { CMDIChildWnd* pChild = pMDIFrame->MDIGetActive (); ASSERT_VALID (pChild); m_pPopupMenu->SetMessageWnd (pChild); } } }
29.736402
99
0.556071
11Zero
abc4fb0ba91b9695df580ed90da3745bd7cf5ba4
1,454
cpp
C++
Leetcode/L1510.cpp
yanjinbin/Foxconn
d8340d228deb35bd8ec244f6156374da8a1f0aa0
[ "CC0-1.0" ]
8
2021-02-14T01:48:09.000Z
2022-01-29T09:12:55.000Z
Leetcode/L1510.cpp
yanjinbin/Foxconn
d8340d228deb35bd8ec244f6156374da8a1f0aa0
[ "CC0-1.0" ]
null
null
null
Leetcode/L1510.cpp
yanjinbin/Foxconn
d8340d228deb35bd8ec244f6156374da8a1f0aa0
[ "CC0-1.0" ]
null
null
null
#include <vector> #include <iostream> #include <queue> #include <map> #include <algorithm> #include <functional> #include <stack> using namespace std; const int INF = 0x3F3F3F3F; const int MOD = 1E9 + 7; #define ready ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #define debug puts("pigtoria bling bling โšก๏ธโšก๏ธ"); #define FOR(i, a, b) for (int i = a; i < b; i++) #define pii pair<int, int> #define LL long long #define LD long double #define PB push_back #define EB emplace_back #define MP make_pair #define FI first #define SE second // ็ŸณๅญๆธธๆˆIV class Solution { public: vector<int> dp; bool winnerSquareGame(int n) { dp.resize(n + 1, -1); dp[0] = 0;// 0 lose 1 win -1 unknown return dfs(n); } // top-down bool dfs(int n) { if (dp[n] != -1) { return dp[n]; } for (int i = 1; i * i <= n; i++) { if (dfs(n - i * i) == 0) { // ๅฆ‚ๆžœๅฏนๆ–นไผš่พ“,ๅˆ™ไฝ ๆœ‰่ตขๅพ—ๆœบไผš dp[n] = 1; return true; } } dp[n] = 0; return false; } // bottom-up bool winnerSquareGame_(int n) { vector<bool> dp(n + 1, false); for (int i = 1; i <= n; i++) { for (int j = 1; j * j <= i; ++j) { if (!dp[i - j * j]) { dp[i] = true; break; } } } return dp[n]; } }; int main() { return 0; }
21.382353
72
0.486245
yanjinbin
abc72cde4ceb89ad6ce76afd70301195b5a726ec
1,362
cpp
C++
src/get_coords.cpp
ropensci/geoops
e83b0e98a3d532f9081f3adab787f8f719c9ffc1
[ "MIT" ]
11
2018-05-19T08:37:37.000Z
2020-09-14T05:36:52.000Z
src/get_coords.cpp
cran/geoops
ec6c9300b7a48a4a604ba3a4243da7d0360e85a3
[ "MIT" ]
3
2018-03-19T18:37:19.000Z
2020-05-15T21:49:48.000Z
src/get_coords.cpp
cran/geoops
ec6c9300b7a48a4a604ba3a4243da7d0360e85a3
[ "MIT" ]
2
2018-09-01T12:26:15.000Z
2019-10-14T14:18:34.000Z
#include <Rcpp.h> #include "json.h" using json = nlohmann::json; // Checks if coordinates contains a number bool contains_number(std::string coordinates) { auto jj = json::parse(coordinates); if (jj.size() > 1 && jj[0].is_number() && jj[1].is_number()) { return true; } if (jj[0].is_array() && jj[0].size()) { return contains_number(jj[0].dump()); } throw std::runtime_error("coordinates must only contain numbers"); } // Checks if coordinates contains a number std::string check_contain(std::string x) { if (contains_number(x)) { return x; } else { throw std::runtime_error("No valid coordinates"); }; }; // [[Rcpp::export]] std::string get_coords(std::string x) { std::string z = x; auto j = json::parse(z); std::string out; if (j.is_array()) { // array std::string out = z; std::string res = check_contain(out); return res; // return out; } else if (j["coordinates"].is_array()) { // geometry object std::string out = j["coordinates"].dump(); std::string res = check_contain(out); return res; } else if (j["geometry"]["coordinates"].is_array()) { // feature std::string out = j["geometry"]["coordinates"].dump(); // return out; std::string res = check_contain(out); return res; } else { throw std::runtime_error("No valid coordinates"); }; };
24.763636
68
0.621145
ropensci
abca2b38f15a78dd26c059d92b69175c083018ae
369
cpp
C++
Engine/EngineProject/DiceGameObject.cpp
joshuaRMS/BoardChampions-
b1146f721dd4e49b3fecba8243182efce64249f9
[ "MIT" ]
1
2019-12-09T13:53:40.000Z
2019-12-09T13:53:40.000Z
Engine/EngineProject/DiceGameObject.cpp
joshuaRMS/BoardChampions-
b1146f721dd4e49b3fecba8243182efce64249f9
[ "MIT" ]
null
null
null
Engine/EngineProject/DiceGameObject.cpp
joshuaRMS/BoardChampions-
b1146f721dd4e49b3fecba8243182efce64249f9
[ "MIT" ]
null
null
null
#include "DiceGameObject.h" void DiceGameObject::rollDices() { Dice1 = rand() % 6 + 1; Dice2 = rand() % 6 + 1; std::cout << Dice1 << std::endl; } void DiceGameObject::DrawDices() { } void DiceGameObject::init() { rollDices(); } void DiceGameObject::update(float elapsedTime) { } DiceGameObject::DiceGameObject() { } DiceGameObject::~DiceGameObject() { }
10.542857
46
0.661247
joshuaRMS
abcbb26b1b2bdd7ef7356308bc5fdb0b8aa510cb
1,064
cpp
C++
NestedRangesCheck.cpp
zuhaib786/CSES_SOLUTIONS
d506d25919b9ebc9b2b809e1cd5327c14872e4a9
[ "MIT" ]
1
2021-06-18T01:48:37.000Z
2021-06-18T01:48:37.000Z
NestedRangesCheck.cpp
zuhaib786/CSES_SOLUTIONS
d506d25919b9ebc9b2b809e1cd5327c14872e4a9
[ "MIT" ]
null
null
null
NestedRangesCheck.cpp
zuhaib786/CSES_SOLUTIONS
d506d25919b9ebc9b2b809e1cd5327c14872e4a9
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct range { int first; int second; int index; }; bool compare(range range1, range range2) { if (range1.first== range2.first) { return range1.second > range2.second; } return range1.first < range2.first; } int main() { int n; cin>>n; vector<range> v(n); vector<int> contains(n, 0); vector<int> is_contained(n, 0); for(int i = 0; i<n;i++) { int a, b; cin>>a>>b; v[i] = {a, b, i}; } sort(v.begin(), v.end(), compare); int max_range = 0, min_range = 1e9+7, i = 0, j = n-1; for(; i<n && j>=0; i++, j--) { range r1 = v[i]; if (r1.second <= max_range) { is_contained[v[i].index] = 1; } max_range = max(max_range, r1.second); range r2 = v[j]; if (r2.second >= min_range) { contains[v[j].index] = 1; } min_range = min(min_range, r2.second); } for(int i = 0; i<n;i++) { cout<< contains[i]<<" "; } cout<<endl; for(int i = 0; i<n;i++) { cout<< is_contained[i]<<" "; } cout<<endl; return 0; }
18.033898
55
0.531955
zuhaib786
abcec6dfcedef9a428b6ad69cd6fb01a057be837
268
cpp
C++
libs/core/render/src/detail/bksge_core_render_detail_index_array_base.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/render/src/detail/bksge_core_render_detail_index_array_base.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/render/src/detail/bksge_core_render_detail_index_array_base.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
๏ปฟ/** * @file bksge_core_render_detail_index_array_base.cpp * * @brief IndexArrayBase ใฎๅฎŸ่ฃ… * * @author myoukaku */ #include <bksge/fnd/config.hpp> #if !defined(BKSGE_HEADER_ONLY) #include <bksge/core/render/detail/inl/index_array_base_inl.hpp> #endif
20.615385
65
0.720149
myoukaku
abd4da0a61e24c5dfb3f3c38d60cbafc05a0a009
2,419
cc
C++
src/q_151_200/q0200.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
2
2021-09-28T18:41:03.000Z
2021-09-28T18:42:57.000Z
src/q_151_200/q0200.cc
vNaonLu/Daily_LeetCode
30024b561611d390931cef1b22afd6a5060cf586
[ "MIT" ]
16
2021-09-26T11:44:20.000Z
2021-11-28T06:44:02.000Z
src/q_151_200/q0200.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
1
2021-11-22T09:11:36.000Z
2021-11-22T09:11:36.000Z
#include <gtest/gtest.h> #include <iostream> #include <queue> #include <vector> using namespace std; /** * This file is generated by leetcode_add.py v1.0 * * 200. * Number of Islands * * โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ Description โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ * * Given an โ€˜m x nโ€™ 2D binary grid โ€˜gridโ€™ which represents a map of โ€˜'1'โ€™ * s (land) and โ€˜'0'โ€™ s (water), return โ€œthe number of islandsโ€ * An โ€œislandโ€ is surrounded by water and is formed by connecting * adjacent lands horizontally or vertically. You may assume all four * edges of the grid are all surrounded by water. * * โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ Constraints โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ * * โ€ข โ€˜m = grid.lengthโ€™ * โ€ข โ€˜n = grid[i].lengthโ€™ * โ€ข โ€˜1 โ‰ค m, n โ‰ค 300โ€™ * โ€ข โ€˜grid[i][j]โ€™ is โ€˜'0'โ€™ or โ€˜'1'โ€™ . * */ struct q200 : public ::testing::Test { // Leetcode answer here class Solution { private: vector<int> dir = {-1, 0, 1, 0, 0, 1, 0, -1}; public: int numIslands(vector<vector<char>>& grid) { int res = 0; int m = grid.size(), n = grid[0].size(); queue<pair<int, int>> island; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == '1') { island.push({i, j}); grid[i][j] = '0'; while (!island.empty()) { auto& p = island.front(); for (int k = 0; k < dir.size(); ++k) { int x = p.first + dir[k], y = p.second + dir[++k]; if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { grid[x][y] = '0'; island.emplace(x, y); } } island.pop(); } ++res; } } } return res; } }; class Solution *solution; }; TEST_F(q200, sample_input01) { solution = new Solution(); vector<vector<char>> grid = {{'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}}; int exp = 1; EXPECT_EQ(solution->numIslands(grid), exp); delete solution; } TEST_F(q200, sample_input02) { solution = new Solution(); vector<vector<char>> grid = {{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}}; int exp = 3; EXPECT_EQ(solution->numIslands(grid), exp); delete solution; }
29.144578
139
0.446465
vNaonLu
abd9de720def75125a9f45c56f58d0dbe5d584b1
1,215
cpp
C++
src/Graphics/TextureCPU.cpp
StarNuik/poi.Graphics
551ef5eeb8f1576c4d7ac0d5dee4ff8faee8cc3c
[ "MIT" ]
null
null
null
src/Graphics/TextureCPU.cpp
StarNuik/poi.Graphics
551ef5eeb8f1576c4d7ac0d5dee4ff8faee8cc3c
[ "MIT" ]
null
null
null
src/Graphics/TextureCPU.cpp
StarNuik/poi.Graphics
551ef5eeb8f1576c4d7ac0d5dee4ff8faee8cc3c
[ "MIT" ]
null
null
null
#include <stb_image.h> #include <string> #include <GL/glew.h> #include "Graphics/TextureCPU.hpp" #include "Graphics/Enums/TextureFormatGPU.hpp" #include "Graphics/Enums/TextureFormatCPU.hpp" using namespace poi::Graphics; namespace /* Project constants */ { using namespace poi; const int32 InternalChannelsCount = 4; // const TextureFormatGPU InternalTextureFormat = TextureFormatGPU::RGBA; const TexturePixelType InternalPixelType = TexturePixelType::UnsignedByte; // inline uint8 FormatToChannels(TextureFormatCPU f) // { // return (f == TextureFormatCPU::RGB ? 3 : 4); // } } TextureCPU::TextureCPU(const uint16 width, const uint16 height, const TextureFormatCPU format) { this->width = width; this->height = height; this->format = format; this->channels = (uint8)format; const uint32 arraySize = sizeof(uint8) * width * height * channels; pixels = new uint8[arraySize]; } TextureCPU::~TextureCPU() { delete[] pixels; } TextureFormatGPU TextureCPU::GetCPUFormat() { return (format == TextureFormatCPU::RGB ? TextureFormatGPU::RGB : TextureFormatGPU::RGBA); } TexturePixelType TextureCPU::GetCPUPixelType() { return InternalPixelType; }
24.795918
95
0.720165
StarNuik