blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
37d527d2103b2b2c295a13704377a58ac2c61244
dd64a33ddef2f91d4b8f8f5de342388346cf1fe3
/SmartPult/Common/Libs/Containers/Array.hpp
c81c2387d986780802d965ea4b47f22f37b9eef5
[]
no_license
YoYoYoCool/SmartPultRepo
24ba7bb01704e5d8899808d2c95b09b1566b7805
fee682a6f748914ddc958afd75c9114fb09bef74
refs/heads/master
2023-03-22T23:53:41.633200
2023-03-10T07:46:22
2023-03-10T07:46:22
166,993,654
1
1
null
null
null
null
WINDOWS-1252
C++
false
false
1,148
hpp
Array.hpp
/* * Array.hpp * * Created on: 6 ÿíâ. 2019 ã. * Author: KapustinIV */ #ifndef LIBS_CONTAINERS_ARRAY_HPP_ #define LIBS_CONTAINERS_ARRAY_HPP_ #include "stdint.h" #include "stddef.h" namespace Containers { template<typename TData> class Array { protected: TData* data; size_t size; public: inline Array(TData* data, size_t size) : data(data){ } inline Array(TData* dataArr, size_t size, TData initData) : data(dataArr), size(size){ setAll(initData); } inline void setAll(TData& data) { for (size_t i = 0; i< size; i++) { this->data[i] = data; } } inline TData& operator[](size_t i) { return data[i]; }; inline size_t getSize() {return size;}; }; template<typename TData, size_t arraySize> class ArrayStatic : public Array<TData> { protected: TData arr[arraySize]; public: inline ArrayStatic() : Array<TData>(arr, arraySize){ } inline ArrayStatic(TData initData) : Array<TData>(arr, arraySize, initData) { } }; } /* namespace Containers */ #endif /* LIBS_CONTAINERS_ARRAY_HPP_ */
0746e769922cb8bdfcb0787b5dbec00a8ba16a9e
73b329e4becd3045989e17fbc0c6aed3d46b5854
/Likelihood/11231LikelihoodDistance/EvaluateLikelihoodDistance.cpp
429b38a1e6273781359390d73015bd7f3c5fc02a
[]
no_license
FHead/PhysicsHiggsProperties
36ee6edd9b4a744c41ae8eda58d3b0979e02868d
25e2cf36b633403a7661488167279a917b76882c
refs/heads/master
2023-06-01T12:58:09.411729
2020-05-05T20:47:51
2020-05-05T20:47:51
377,256,404
0
0
null
null
null
null
UTF-8
C++
false
false
7,352
cpp
EvaluateLikelihoodDistance.cpp
//---------------------------------------------------------------------------- #include <iostream> #include <fstream> #include <string> using namespace std; //---------------------------------------------------------------------------- #include "DrawRandom2.h" #include "ProgressBar.h" //---------------------------------------------------------------------------- int main(); bool MapCompatibilityCheck(string Map1Location, string Map2Location); double CalculateIntegral(string MapLocation); void DoToysAndEvaluateLikelihood(string Map1Location, string Map2Location, string OutputFileName, double Map1Integral, double Map2Integral, int TotalCount); //---------------------------------------------------------------------------- int main() { // Map locations string Map1Location = "All_Scalar.map"; string Map2Location = "All_PseudoScalar.map"; // Sanity check from the file header if(MapCompatibilityCheck(Map1Location, Map2Location) == false) { cerr << "Maps not compatible with each other. Exiting..." << endl; return -1; } // First calculate the integral of the maps for normalization purposes // In principle this can be done along the way, but let's keep it simple // Timewise speaking this adds about 2 minutes to the total run time, which is fine (for now) double Integral1 = CalculateIntegral(Map1Location); double Integral2 = CalculateIntegral(Map2Location); // LL locations (output) string Result1Location = "SortedLL_Scalar.toyll"; string Result2Location = "SortedLL_PseudoScalar.toyll"; // Now evaluate the toys and write out result DoToysAndEvaluateLikelihood(Map1Location, Map2Location, Result1Location, Integral1, Integral2, 10000000); DoToysAndEvaluateLikelihood(Map2Location, Map1Location, Result2Location, Integral2, Integral1, 10000000); return 0; } //---------------------------------------------------------------------------- bool MapCompatibilityCheck(string Map1Location, string Map2Location) { bool Compatible = true; ifstream in1(Map1Location.c_str()); ifstream in2(Map2Location.c_str()); for(int i = 0; i < 2 + 6 + 12; i++) { // 2 for the Z and H masses // 6 for the bin count in each dimension // 12 for the ranges in each dimension double Temp1 = -999, Temp2 = -999; in1 >> Temp1; in2 >> Temp2; if(Temp1 < -900 || Temp2 < -900) // something's wrong Compatible = false; if(fabs(Temp1 - Temp2) > 1e-5) // not the same number Compatible = false; } in2.close(); in1.close(); cout << "Checking map compatibility (header-only)"; if(Compatible == true) cout << "......good" << endl; else cout << "......not compatible" << endl; cout << endl; return Compatible; } //---------------------------------------------------------------------------- double CalculateIntegral(string MapLocation) { double Total = 0; ifstream in(MapLocation.c_str()); double ZMass = -1, HMass = -1; in >> HMass >> ZMass; int NBinsMass = -1, NBinsPhi0 = -1, NBinsTheta0 = -1, NBinsPhi = -1, NBinsTheta1 = -1, NBinsTheta2 = -1; in >> NBinsPhi0 >> NBinsTheta0 >> NBinsPhi >> NBinsTheta1 >> NBinsTheta2 >> NBinsMass; double Phi0Min = 0, Phi0Max = 0; double Theta0Min = 0, Theta0Max = 0; double PhiMin = 0, PhiMax = 0; double Theta1Min = 0, Theta1Max = 0; double Theta2Min = 0, Theta2Max = 0; double MassMin = 0, MassMax = 0; in >> Phi0Min >> Phi0Max; in >> Theta0Min >> Theta0Max; in >> PhiMin >> PhiMax; in >> Theta1Min >> Theta1Max; in >> Theta2Min >> Theta2Max; in >> MassMin >> MassMax; if(ZMass < 0 || HMass < 0 || NBinsMass < 0 || NBinsPhi0 < 0 || NBinsTheta1 < 0 || NBinsTheta2 < 0) { cerr << "INPUTFILE ERROR! REQUIRED PARAMETERS ARE NEGATIVE!!" << endl; return -1; } ProgressBar Bar(cout, NBinsPhi0 * NBinsTheta0); Bar.SetStyle(1); cout << "Start to calculate integral of map from file \"" << MapLocation << "\"" << endl; for(int iPhi0 = 0; iPhi0 < NBinsPhi0; iPhi0++) { for(int iTheta0 = 0; iTheta0 < NBinsTheta0; iTheta0++) { Bar.Update(iPhi0 * NBinsTheta0 + iTheta0 + 1); Bar.Print(); for(int iPhi = 0; iPhi < NBinsPhi; iPhi++) { for(int iTheta1 = 0; iTheta1 < NBinsTheta1; iTheta1++) { for(int iTheta2 = 0; iTheta2 < NBinsTheta2; iTheta2++) { for(int iMass = 0; iMass < NBinsMass; iMass++) { double Value = -1; in >> Value; Total = Total + Value; } } } } } } Bar.PrintLine(); cout << "Final Integral = " << Total << endl; cout << endl; in.close(); return Total; } //---------------------------------------------------------------------------- void DoToysAndEvaluateLikelihood(string Map1Location, string Map2Location, string OutputFileName, double Map1Integral, double Map2Integral, int TotalCount) { cout << "Start generating toys from map \"" << Map1Location << "\" and "; cout << "evaluate likelihood difference on both maps" << endl; cout << " and write to file \"" << OutputFileName << "\"" << endl; // Inputs ifstream in1(Map1Location.c_str()); ifstream in2(Map2Location.c_str()); ofstream out(OutputFileName.c_str()); double LogIntegral1 = log(Map1Integral); double LogIntegral2 = log(Map2Integral); // Prepare random number generator RandomBase Random; // Read dimensions (and discard other parts of header) double ZMass = -1, HMass = -1; in1 >> HMass >> ZMass; in2 >> HMass >> ZMass; long long NBinsMass = -1, NBinsPhi0 = -1, NBinsTheta0 = -1, NBinsPhi = -1, NBinsTheta1 = -1, NBinsTheta2 = -1; in1 >> NBinsPhi0 >> NBinsTheta0 >> NBinsPhi >> NBinsTheta1 >> NBinsTheta2 >> NBinsMass; in2 >> NBinsPhi0 >> NBinsTheta0 >> NBinsPhi >> NBinsTheta1 >> NBinsTheta2 >> NBinsMass; for(int i = 0; i < 12; i++) // ranges of the dimensions - discard here { double Temp = -1; in1 >> Temp; in2 >> Temp; } // Now loop over all bins and generate toys & evaluate likelihoods ProgressBar Bar(cout, NBinsMass * NBinsPhi0 * NBinsTheta0 * NBinsPhi * NBinsTheta1 * NBinsTheta2); Bar.SetStyle(1); for(long long i = 0; i < NBinsMass * NBinsPhi0 * NBinsTheta0 * NBinsPhi * NBinsTheta1 * NBinsTheta2; i++) { if(i % (NBinsTheta0 * NBinsPhi * NBinsTheta1 * NBinsTheta2) == 0) { Bar.Update(i); Bar.Print(); } double Value1 = -1; in1 >> Value1; double Value2 = -1; in2 >> Value2; double TargetCount = Value1 / Map1Integral * TotalCount; int RealCount = Random.DrawPoissonInt(TargetCount); double LLDistance = (log(Value1) - LogIntegral1) - (log(Value2) - LogIntegral2); for(int j = 0; j < RealCount; j++) out << LLDistance << endl; } Bar.Update(NBinsMass * NBinsPhi0 * NBinsTheta0 * NBinsPhi * NBinsTheta1 * NBinsTheta2); Bar.Print(); Bar.PrintLine(); cout << "Done!" << endl; cout << endl; // Clean up out.close(); in2.close(); in1.close(); } //----------------------------------------------------------------------------
fe2a32ed9726f4c05ec7145831b6860d304f52f1
876c7dba66959a02d00ba300adcf64285085ae85
/Info/Make them odd/main.cpp
da55386ee7c6824307a88c1272452bd61cc700a8
[]
no_license
viftode4/PBINFOOOO
69b36ce9458e03061fec67981904b3fb2485430b
8aebb5488f91735218404c36a983e23d833f2d1d
refs/heads/master
2023-04-23T12:39:14.031554
2021-05-18T17:54:51
2021-05-18T17:54:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
719
cpp
main.cpp
#include <bits/stdc++.h> using namespace std; #define st first #define nd second int t, n; int a[200005]; int main() { cin >> t; while( t-- ) { cin >> n; map<int, int>m; int sol = 0; for( int i = 1; i <= n; i++ ) { cin >> a[i]; int nr = 0; while( a[i]%2==0 ) { nr++; a[i] /= 2; } m[a[i]] = max( m[a[i]], nr ); } for( auto it : m ) sol += it.nd; cout << sol << '\n'; } return 0; }
7a7994e28984e1f863c9666b4e4a0d73a47bdc11
135dfa52b096716e3aa7cec643667b5b34f5166c
/toy_tracer/core/rendertext.h
594b4a682f56b9ba95369a731cf0f86092286405
[]
no_license
Sefaice/toy-renderer
d944e64b487407b0d5aad9621eb1c3b15e75f27e
876d15d2b2864ebda0ad66d4aecd6018d092a1f3
refs/heads/master
2022-12-04T03:27:34.422136
2020-06-24T10:11:45
2020-06-24T10:11:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
527
h
rendertext.h
#pragma once #include "core/geometry.h" #include "glad/glad.h" struct Character { GLuint TextureID; // ID handle of the glyph texture Vector2i Size; // Size of glyph Vector2i Bearing; // Offset from baseline to left/top of glyph GLuint Advance; // Offset to advance to next glyph }; void renderTextAtTopLeft(const std::string& txt, Float scale); void renderTextAtTopRight(const std::string& txt, Float scale); void renderText(const std::string& txt, Point2f startPos, Float scale);
0568baf1fd19b56d1318f220e8bd4a2697dec297
efe44bbc64cf788768d73e35cfb1baa2098181f6
/pmlc/dialect/pxa/analysis/uses.cc
da90b8dadf5845cf2175c7823608c8e7612dbda7
[ "Apache-2.0" ]
permissive
plaidml/plaidml
d2dd18f8228d3959ec875b66aa4ff31f6c29ef00
49fbaa5ac387e621f11ba0b81f49461e4b2d02ef
refs/heads/plaidml-v1
2023-08-09T18:38:07.681422
2023-07-23T20:15:07
2023-07-23T20:15:07
100,326,126
4,779
516
Apache-2.0
2023-02-14T21:33:05
2017-08-15T01:43:24
C++
UTF-8
C++
false
false
5,326
cc
uses.cc
// Copyright 2020 Intel Corporation #include "pmlc/dialect/pxa/analysis/uses.h" #include "llvm/ADT/TypeSwitch.h" #include "pmlc/dialect/layer/ir/ops.h" #include "pmlc/dialect/stdx/ir/ops.h" #include "pmlc/util/logging.h" using namespace mlir; // NOLINT namespace pmlc::dialect::pxa { Value getPrevIndirectDef(OpResult def) { return TypeSwitch<Operation *, Value>(def.getOwner()) .Case<AffineParallelOp>([&](auto op) { auto yield = cast<AffineYieldOp>(op.getBody()->getTerminator()); return yield.getOperand(def.getResultNumber()); }) .Case<AffineIfOp>([&](auto op) { auto yield = cast<AffineYieldOp>(op.getThenBlock()->getTerminator()); return yield.getOperand(def.getResultNumber()); }) .Case<layer::BoxOp>([&](auto op) { return op.getOperand(def.getResultNumber()); // }) .Case<PrngOp>([&](auto op) { if (op.getResult(def.getResultNumber()) == op.result_tensor()) { return op.tensor(); } if (op.getResult(def.getResultNumber()) == op.result_state()) { return op.new_state(); } return Value(); }) .Case<PxaReduceOp>([&](auto op) { return op.memref(); }) .Case<PxaStoreOp>([&](auto op) { return op.memref(); }) .Case<PxaVectorReduceOp>([&](auto op) { return op.memref(); }) .Case<PxaGenericOp>( [&](auto op) { return op.outputs()[def.getResultNumber()]; }) .Case<stdx::ReshapeOp>([&](auto op) { return op.tensor(); }) .Default([](auto op) { return nullptr; }); } Value getNextIndirectUse(mlir::OpOperand &use) { return TypeSwitch<Operation *, Value>(use.getOwner()) .Case<AffineYieldOp>([&](auto op) { return op->getParentOp()->getResult(use.getOperandNumber()); }) .Case<layer::BoxOp>([&](auto op) { return op.getResult(use.getOperandNumber()); // }) .Case<PxaReduceOp>([&](auto op) { return op.result(); }) .Case<PxaStoreOp>([&](auto op) { return op.result(); }) .Case<PxaVectorReduceOp>([&](auto op) { return op.result(); }) .Case<PxaGenericOp>([&](auto op) { if (use.getOperandNumber() >= op.getNumInputs() && use.getOperandNumber() < op.getNumInputs() + op.getNumOutputs()) return op.getResult(use.getOperandNumber() - op.getNumInputs()); return Value(); }) .Case<PrngOp>([&](auto op) { if (op.getOperand(use.getOperandNumber()) == op.tensor()) { return op.result_tensor(); } if (op.getOperand(use.getOperandNumber()) == op.new_state()) { return op.result_state(); } return Value(); }) .Case<stdx::ReshapeOp>([&](auto op) { return op.result(); }) .Default([](auto op) { return nullptr; }); } Operation *getPrevWriter(Value value) { while (auto opResult = value.dyn_cast<OpResult>()) { auto op = opResult.getOwner(); if (isa<AffineParallelOp, AffineIfOp>(op)) { value = getPrevIndirectDef(opResult); } else { return op; } } return nullptr; } Value getIndirectDef(Value value) { while (auto opResult = value.dyn_cast<OpResult>()) { value = getPrevIndirectDef(opResult); if (!value) { return opResult; } } return value; } Value getIndirectDefOutsideScope(Value value, Operation *scope) { while (auto opResult = value.dyn_cast<OpResult>()) { auto op = opResult.getOwner(); if (!scope->isAncestor(op)) { return opResult; } value = getPrevIndirectDef(opResult); if (!value) { return nullptr; } } return value; } IndirectValuesIterator &IndirectValuesIterator::operator++() { for (OpOperand &use : curValue.getUses()) { if (auto next = getNextIndirectUse(use)) { enqueueNext(next); } } if (workQueue.empty()) { curValue = nullptr; } else { curValue = workQueue.front(); workQueue.pop(); } return *this; } void IndirectValuesIterator::enqueueNext(Value value) { if (!visited.count(value)) { visited.insert(value); workQueue.push(value); } } IndirectValuesRange getIndirectValues(Value value) { return {IndirectValuesIterator(value), IndirectValuesIterator()}; } IndirectUsesIterator::IndirectUsesIterator(Value value) : inner(value), curIt(value.use_begin()) { nextValue(); } IndirectUsesIterator &IndirectUsesIterator::operator++() { ++curIt; nextValue(); return *this; } void IndirectUsesIterator::nextValue() { while (curIt == Value::use_iterator()) { ++inner; if (inner == IndirectValuesIterator()) { return; } curIt = inner.getValue().use_begin(); } } IndirectUsesRange getIndirectUses(Value value) { return {IndirectUsesIterator(value), IndirectUsesIterator()}; } IndirectAccessUsesIterator &IndirectAccessUsesIterator::operator++() { ++inner; skipNonAccess(); return *this; } void IndirectAccessUsesIterator::skipNonAccess() { while (inner != IndirectUsesIterator()) { if (isa<PxaGenericOp, PxaLoadOp, PxaReduceOp, PxaStoreOp, PxaVectorLoadOp, PxaVectorReduceOp>(inner->getOwner())) { break; } ++inner; } } IndirectAccessUsesRange getIndirectAccessUses(Value value) { return {IndirectAccessUsesIterator(value), IndirectAccessUsesIterator()}; } } // namespace pmlc::dialect::pxa
07c99c3c6f51252fd6ca4a5d6bd47d2c70fae33f
bf20c75c2c957429eb592fc81ac4317f1a7d1a22
/HW3/scene/property_render.cpp
8c3ce6904b20812573ad5daad6bcd493fcfabd54
[]
no_license
SonSang/Course-Project_Advanced-Animation
ae43c4dd7e4638d81e2c6bb4f4ad51a20ffb90bb
9f81d30834c2fffea33cc84f5214d7db78291cc6
refs/heads/master
2022-12-08T19:43:34.875697
2020-08-30T08:06:27
2020-08-30T08:06:27
291,422,686
0
0
null
null
null
null
UTF-8
C++
false
false
484
cpp
property_render.cpp
#include "property_render.hpp" property_render::property_render(const std::string &name_) : name(name_) { } const std::string &property_render::get_name() const noexcept { return this->name; } void property_render::set_name(const std::string &name) { this->name = name; } bool property_render::is_valid() const noexcept { return this->valid; } void property_render::set_valid(bool v) { this->valid = v; } void property_render::render() const noexcept { return; }
926d22c2e3c7ff3903897e32456f34c3b5114fdc
54faf1a50bee9ad9f6f17beab4df1ba78cd176aa
/src/GpsMarker/SdkModel/GpsMarkerController.h
2a49981129c2cf242b479e1785f7c26b2646303b
[ "BSD-2-Clause" ]
permissive
TomHaygarth/eegeo-example-app
b3a4a4f38e41b625acc131234b8a43cd39ebe635
74712ff59a20f80682f1d884660151fb21457643
refs/heads/master
2021-01-14T08:10:40.177330
2017-02-14T13:08:02
2017-02-14T13:08:02
82,004,395
1
0
null
2017-02-15T00:51:29
2017-02-15T00:51:29
null
UTF-8
C++
false
false
3,909
h
GpsMarkerController.h
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #pragma once #include "IGpsMarkerController.h" #include "GpsMarker.h" #include "BidirectionalBus.h" #include "ICallback.h" #include "ModalityChangedMessage.h" #include "Rendering.h" #include "IVisualMapService.h" namespace ExampleApp { namespace GpsMarker { namespace SdkModel { class GpsMarkerController : public IGpsMarkerController { public: GpsMarkerController(GpsMarkerModel& model, GpsMarkerView& view, GpsMarkerAnchorView& anchorView, Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel, Eegeo::Rendering::EnvironmentFlatteningService& environmentFlatteningService, VisualMap::SdkModel::IVisualMapService& visualMapService, const Eegeo::Rendering::ScreenProperties& screenProperties, ExampleAppMessaging::TMessageBus& messageBus); ~GpsMarkerController(); void Update(float dt, const Eegeo::Camera::RenderCamera& renderCamera); private: const static float DefaultUpdatePeriod; int m_visibilityCount; float m_viewTransitionParam; int m_currentFloorIndex; float m_screenPixelScale; float m_screenOversampleScale; GpsMarkerModel& m_model; GpsMarkerView& m_view; GpsMarkerAnchorView& m_anchorView; Eegeo::Resources::Interiors::InteriorInteractionModel& m_interiorInteractionModel; Eegeo::Rendering::EnvironmentFlatteningService& m_environmentFlatteningService; VisualMap::SdkModel::IVisualMapService& m_visualMapService; ExampleAppMessaging::TMessageBus& m_messageBus; Eegeo::Helpers::TCallback0<GpsMarkerController> m_floorSelectedCallback; Eegeo::Helpers::TCallback1<GpsMarkerController, const Modality::ModalityChangedMessage&> m_modalityChangedHandlerBinding; Eegeo::Helpers::TCallback1<GpsMarkerController, const GpsMarkerVisibilityMessage&> m_visibilityChangedHandlerBinding; Eegeo::Helpers::TCallback1<GpsMarkerController, const InteriorsExplorer::InteriorsExplorerStateChangedMessage&> m_interiorsExplorerStateChangedCallback; void OnFloorSelected(); void OnModalityChangedMessage(const Modality::ModalityChangedMessage& message); void OnVisibilityChangedMessage(const GpsMarkerVisibilityMessage& message); void OnInteriorsExplorerStateChangedMessage(const InteriorsExplorer::InteriorsExplorerStateChangedMessage& message); void UpdateTransition(bool isVisible, float dt); void CreateModelViewProjectionMatrix(Eegeo::m44& out_modelViewProjection, const Eegeo::dv3& location, const float heading, const Eegeo::v3& cameraRelativeLocation, const Eegeo::v3& scale, const Eegeo::Camera::RenderCamera& renderCamera, bool flipUpDirection); void GetCurrentVisualMapTime(std::string& currentTime, std::string& currentWeather); }; } } }
60343f18f3821b9efd1371886af58a410e4d35ad
97eb17ce805e762982c1b09647ea3f251fa0ea0b
/Hoe3D/src/sound.h
052848672922a414e8d2cd6b4e2d7a616b043d20
[]
no_license
HeimdallTeam/Hoe3D
8ca6d434b298773abc3d8c324822df3b97f5d19a
62c6547ee5751ca6da31fa5379c6a0b78bafe5bd
refs/heads/master
2021-01-15T14:24:35.777027
2014-10-03T23:11:14
2014-10-03T23:11:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,984
h
sound.h
/** @file sound.h @date Sep 2004 @version $Revision: 1.10 $ @brief Hlavni soubor se zvukem. */ #ifndef _HOE_SOUND_ #define _HOE_SOUND_ #include "../include/hoeinterfaces.h" #if defined (_USE_D3D9_) || defined (_USE_D3D8_) #include "sound_ds.h" #endif #ifdef _USE_OPENGL_ #include "sound_al.h" #endif /** @brief Uloziste zvuku */ class HoeSoundBuffer : public IHoeSound #ifdef _HOE_OPENAL_ , public HoeALBuffer #endif #ifdef _HOE_DS8_ , public HoeDSBuffer #endif { bool m_ctrl3D; public: HoeSoundBuffer(bool ctrl3D); /** * Provizorni nacteni ze souboru * @todo predelat nacitani z file systemu */ bool LoadFromFile(const char * filename); virtual void HOEAPI Play(bool loop) {}; virtual void HOEAPI Stop() {}; virtual void HOEAPI Delete() { delete this; } }; /** @brief Prehravac zvuku */ class HoeSoundPlayer #ifdef _HOE_OPENAL_ : public HoeALPlayer #endif #ifdef _HOE_DS8_ : public HoeDSPlayer #endif { }; /** @brief Zvuk, obsahuje jeden Player a nekolik Bufferu */ class HoeSound : public HoeSoundBuffer { HoeSoundPlayer player; /**< player */ public: HoeSound() : HoeSoundBuffer(false) {} /** * Prehraje aktualni buffer */ virtual void HOEAPI Play(bool loop); virtual void HOEAPI Stop(); virtual void HOEAPI Delete() { delete this; } friend class SoundSystem; }; /** @brief Hlavni objekt pro vytvareni zvuku. */ class SoundSystem #ifdef _HOE_OPENAL_ : public SoundSystemAl #endif #ifdef _HOE_DS8_ : public SoundSystemDS #endif { protected: /** * Nahrani bufferu ze souboru * @param name Jmeno zvuku, ktery se hleda ve File systemu */ HoeSoundBuffer * GetBuffer(const char * name); public: /** Konstruktor */ SoundSystem(); /** Destruktor */ ~SoundSystem(); /** * Vytvoreni zvuku * @param name Jmeno zvuku, ktery se hleda ve File systemu * @param ctrl3d Zvuk se prehrava ve 3d */ HoeSoundBuffer * GetSound(const char * name, bool ctrl3d); }; #endif // _HOE_SOUND_
4680d869311c0524229205072021c1b2ce92d5b4
ffb568806e34199501c4ca6b61ac86ee9cc8de2e
/poke_lib/pml/src/personal/pml_GrowTableCache.cpp
48ae6854ce34f8e3934423e649acd453745e1449
[]
no_license
Fumikage8/gen7-source
433fb475695b2d5ffada25a45999f98419b75b6b
f2f572b8355d043beb468004f5e293b490747953
refs/heads/main
2023-01-06T00:00:14.171807
2020-10-20T18:49:53
2020-10-20T18:49:53
305,500,113
3
1
null
null
null
null
UTF-8
C++
false
false
3,753
cpp
pml_GrowTableCache.cpp
//============================================================================= /** * @brief 成長曲線テーブルのキャッシュ管理 * @file pml_GrowTableCache.cpp * @author obata_toshihiro * @date 2011.01.11 */ //============================================================================= #include <heap/include/gfl2_Heap.h> #include <pml/include/pml_Type.h> #include <pml/include/personal/pml_GrowTable.h> #include "pml_GrowTableCache.h" namespace pml { namespace personal { //------------------------------------------------------------------------- /** * @brief コンストラクタ * @param heap キャッシュの確保に使用するヒープ * @param cache_size キャッシュするテーブルの数 */ //------------------------------------------------------------------------- GrowTableCache::GrowTableCache( gfl2::heap::HeapBase* heap, u32 cache_size ) : m_cacheData( NULL ), m_maxDataNum( cache_size ), m_registerPos( 0 ) { m_cacheData = GFL_NEW( heap ) GrowTable*[ cache_size ]; for( u32 i=0; i<cache_size; i++ ) { m_cacheData[i] = GFL_NEW( heap ) GrowTable(); } } //------------------------------------------------------------------------- /** * @brief デストラクタ */ //------------------------------------------------------------------------- GrowTableCache::~GrowTableCache() { for( u32 i=0; i<m_maxDataNum; i++ ) { GFL_DELETE m_cacheData[i]; } GFL_DELETE[] m_cacheData; } //------------------------------------------------------------------------- /** * @brief キャッシュからデータを取得する * @param[in] grow_type 成長曲線タイプ * @param[out] buffer 取得したデータの格納先 * @return キャッシュにヒットしたか? */ //------------------------------------------------------------------------- bool GrowTableCache::GetTable( u32 grow_type, GrowTable* buffer ) const { u32 index = 0; bool hit = SearchData( grow_type, &index ); if( hit ) { m_cacheData[ index ]->Copy( buffer ); } return hit; } /** * @brief 指定した条件に該当するデータを検索し, インデックスを取得する * @param[in] grow_type 成長曲線タイプ * @param[out] index 該当データのインデックスの格納先 * @retval true キャッシュにヒットした場合 * @retval false キャッシュにヒットしなかった場合 */ bool GrowTableCache::SearchData( s32 grow_type, u32* index ) const { for( int i=0; i<m_maxDataNum; i++ ) { if( m_cacheData[i]->GetGrowType() == grow_type ) { *index = i; return true; } } return false; } //------------------------------------------------------------------------- /** * @brief 指定したデータをキャッシュに登録する * @param table 登録するデータ */ //------------------------------------------------------------------------- void GrowTableCache::RegisterTable( const GrowTable& table ) { u32 index = 0; u32 grow_type = table.GetGrowType(); if( SearchData( grow_type, &index ) == false ) { // 登録 table.Copy( m_cacheData[ m_registerPos ] ); // 次に登録する場所を進める m_registerPos = ( m_registerPos + 1 ) % m_maxDataNum; } } } // namespace personal } // namespace pml
383c6ecd1fa29b06174ec466b977739f360babb3
17353cfd2c984f2b57ab09dce5b793f34b051f19
/src/plugProjectMorimuraU/egg.cpp
edcdb566f993a7aa2eefa6c02cc9c773959ec099
[]
no_license
mxygon/pikmin2
573df84b127b27f1c5db6be22680b63fd34565d5
fa16b706d562d3f276406d8a87e01ad541515737
refs/heads/main
2023-09-02T06:56:56.216154
2021-11-12T09:34:26
2021-11-12T09:34:26
427,367,127
1
0
null
2021-11-12T13:19:54
2021-11-12T13:19:53
null
UTF-8
C++
false
false
25,322
cpp
egg.cpp
#include "types.h" namespace Game { /* * --INFO-- * Address: 8034BB30 * Size: 000020 */ void Egg::Obj::setParameters(void) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) bl -0x248F64 lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } } // namespace Game /* * --INFO-- * Address: 8034BB50 * Size: 000020 */ void birth__Q34Game3Egg3ObjFR10Vector3f f(void) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) bl -0x24915C lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } namespace Game { /* * --INFO-- * Address: 8034BB70 * Size: 000150 */ void Egg::Obj::onInit(Game::CreatureInitArg*) { /* .loc_0x0: stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1C(r1) mr r31, r3 bl -0x24A12C lwz r0, 0x1E0(r31) mr r3, r31 rlwinm r0,r0,0,25,23 stw r0, 0x1E0(r31) lwz r0, 0x1E0(r31) rlwinm r0,r0,0,29,27 stw r0, 0x1E0(r31) lwz r0, 0x1E0(r31) rlwinm r0,r0,0,24,22 stw r0, 0x1E0(r31) bl -0x24A1A8 lwz r3, 0x1E0(r31) li r0, 0 mr r4, r31 li r5, 0 oris r3, r3, 0x40 li r6, 0 stw r3, 0x1E0(r31) stb r0, 0x2BC(r31) lwz r3, 0x2C0(r31) lwz r12, 0x0(r3) lwz r12, 0xC(r12) mtctr r12 bctrl mr r3, r31 bl -0x2441C0 rlwinm. r0,r3,0,24,31 bne- .loc_0x13C lwz r0, 0x1E0(r31) ori r0, r0, 0x400 stw r0, 0x1E0(r31) lwz r3, -0x6CF8(r13) cmplwi r3, 0 beq- .loc_0xDC lfs f1, 0x18C(r31) addi r4, r1, 0x8 lfs f0, 0x28(r2) stfs f1, 0x8(r1) lfs f1, 0x190(r31) stfs f1, 0xC(r1) fadds f0, f1, f0 lfs f1, 0x194(r31) stfs f1, 0x10(r1) stfs f0, 0xC(r1) lwz r12, 0x4(r3) lwz r12, 0x28(r12) mtctr r12 bctrl stfs f1, 0x190(r31) .loc_0xDC: lwz r4, 0x188(r31) li r0, 0 mr r3, r31 stb r0, 0x24(r4) lwz r12, 0x0(r31) lwz r12, 0x1D8(r12) mtctr r12 bctrl addi r3, r31, 0x138 addi r4, r31, 0x168 addi r5, r31, 0x1A4 addi r6, r31, 0x18C bl 0xDC65C lwz r4, 0x174(r31) addi r3, r31, 0x138 lwz r4, 0x8(r4) addi r4, r4, 0x24 bl -0x2619C4 lwz r3, 0x174(r31) lwz r3, 0x8(r3) lwz r12, 0x0(r3) lwz r12, 0x10(r12) mtctr r12 bctrl .loc_0x13C: lwz r0, 0x24(r1) lwz r31, 0x1C(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 8034BCC0 * Size: 000138 */ Egg::Obj::Obj(void) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) extsh. r0, r4 stw r31, 0xC(r1) mr r31, r3 stw r30, 0x8(r1) beq- .loc_0x40 addi r0, r31, 0x2C4 lis r3, 0x804B stw r0, 0x17C(r31) subi r3, r3, 0x5988 li r0, 0 stw r3, 0x2C4(r31) stw r0, 0x2C8(r31) stw r0, 0x2CC(r31) .loc_0x40: mr r3, r31 li r4, 0 bl -0x24A968 lis r3, 0x804E addi r4, r31, 0x2C4 subi r3, r3, 0x3F88 li r0, 0 stw r3, 0x0(r31) addi r5, r3, 0x1B0 addi r6, r3, 0x2FC li r3, 0x2C stw r5, 0x178(r31) lwz r5, 0x17C(r31) stw r6, 0x0(r5) lwz r5, 0x17C(r31) sub r4, r4, r5 stw r4, 0xC(r5) stw r0, 0x2C0(r31) bl -0x327EA4 mr. r30, r3 beq- .loc_0xD4 bl -0x2243E0 lis r3, 0x804E lis r4, 0x804B subi r0, r3, 0x40A0 lis r3, 0x804F stw r0, 0x0(r30) subi r4, r4, 0x4678 subi r3, r3, 0x4200 li r0, 0 stw r4, 0x10(r30) stw r3, 0x10(r30) stb r0, 0x28(r30) stw r0, 0x1C(r30) stw r0, 0x14(r30) stb r0, 0x28(r30) stw r0, 0x20(r30) .loc_0xD4: stw r30, 0x184(r31) li r3, 0x1C bl -0x327EF8 mr. r4, r3 beq- .loc_0x108 lis r5, 0x804B lis r3, 0x804E subi r0, r5, 0x680 li r5, -0x1 stw r0, 0x0(r4) subi r0, r3, 0x40C4 stw r5, 0x18(r4) stw r0, 0x0(r4) .loc_0x108: lwz r12, 0x0(r31) mr r3, r31 lwz r12, 0x2F8(r12) mtctr r12 bctrl lwz r0, 0x14(r1) mr r3, r31 lwz r31, 0xC(r1) lwz r30, 0x8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034BDF8 * Size: 00004C */ void Egg::Obj::setFSM(Game::Egg::FSM*) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xC(r1) mr r31, r3 stw r4, 0x2C0(r3) mr r4, r31 lwz r3, 0x2C0(r3) lwz r12, 0x0(r3) lwz r12, 0x8(r12) mtctr r12 bctrl li r0, 0 stw r0, 0x2B4(r31) lwz r0, 0x14(r1) lwz r31, 0xC(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034BE44 * Size: 00006C */ void Egg::Obj::doUpdate(void) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 mr r4, r3 stw r0, 0x14(r1) lwz r0, 0xC8(r3) cmplwi r0, 0 beq- .loc_0x30 lfs f0, 0x2C(r2) stfs f0, 0x1D4(r4) stfs f0, 0x1D8(r4) stfs f0, 0x1DC(r4) b .loc_0x48 .loc_0x30: lfs f0, 0x1C8(r4) stfs f0, 0x1D4(r4) lfs f0, 0x1CC(r4) stfs f0, 0x1D8(r4) lfs f0, 0x1D0(r4) stfs f0, 0x1DC(r4) .loc_0x48: lwz r3, 0x2C0(r4) lwz r12, 0x0(r3) lwz r12, 0x10(r12) mtctr r12 bctrl lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034BEB0 * Size: 000004 */ void Egg::Obj::doDirectDraw(Graphics&) { } /* * --INFO-- * Address: 8034BEB4 * Size: 000020 */ void Egg::Obj::doDebugDraw(Graphics&) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) bl -0x246054 lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034BED4 * Size: 00004C */ void Egg::Obj::doSimulation(float) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) lwz r4, 0xB8(r3) cmplwi r4, 0 beq- .loc_0x38 lfs f2, 0x2C(r4) lfs f1, 0x1C(r4) lfs f0, 0xC(r4) stfs f0, 0x18C(r3) stfs f1, 0x190(r3) stfs f2, 0x194(r3) bl -0x248634 b .loc_0x3C .loc_0x38: bl -0x2474B4 .loc_0x3C: lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034BF20 * Size: 000128 */ void Egg::Obj::doAnimationCullingOff(void) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) li r0, 0 stw r31, 0xC(r1) stw r30, 0x8(r1) mr r30, r3 lwz r4, 0x188(r3) stb r0, 0x24(r4) lwz r12, 0x0(r3) lwz r12, 0x1D8(r12) mtctr r12 bctrl lwz r3, 0xB8(r30) lfs f3, 0x164(r30) cmplwi r3, 0 lfs f2, 0x154(r30) lfs f1, 0x144(r30) beq- .loc_0x84 lfs f0, 0xC(r3) li r31, 0 lfs f4, 0x2C(r3) fcmpu cr0, f1, f0 lfs f0, 0x1C(r3) bne- .loc_0x74 fcmpu cr0, f2, f0 bne- .loc_0x74 fcmpu cr0, f3, f4 beq- .loc_0xC4 .loc_0x74: addi r4, r30, 0x138 li r31, 0x1 bl -0x261CD0 b .loc_0xC4 .loc_0x84: lfs f0, 0x18C(r30) li r31, 0 fcmpu cr0, f0, f1 bne- .loc_0xAC lfs f0, 0x190(r30) fcmpu cr0, f0, f2 bne- .loc_0xAC lfs f0, 0x194(r30) fcmpu cr0, f0, f3 beq- .loc_0xC4 .loc_0xAC: addi r3, r30, 0x138 addi r4, r30, 0x168 addi r5, r30, 0x1A4 addi r6, r30, 0x18C li r31, 0x1 bl 0xDC2F8 .loc_0xC4: rlwinm. r0,r31,0,24,31 bne- .loc_0xDC mr r3, r30 bl -0x244CB8 rlwinm. r0,r3,0,24,31 bne- .loc_0x110 .loc_0xDC: lwz r4, 0x174(r30) addi r3, r30, 0x138 lwz r4, 0x8(r4) addi r4, r4, 0x24 bl -0x261D40 lwz r3, 0x174(r30) lwz r3, 0x8(r3) lwz r12, 0x0(r3) lwz r12, 0x10(r12) mtctr r12 bctrl lwz r3, 0x114(r30) bl -0x216590 .loc_0x110: lwz r0, 0x14(r1) lwz r31, 0xC(r1) lwz r30, 0x8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034C048 * Size: 000008 */ u32 Egg::Obj::pressCallBack(Game::Creature*, float, CollPart*) { return 0x0; } /* * --INFO-- * Address: 8034C050 * Size: 000054 */ void Egg::Obj::bounceCallback(Sys::Triangle*) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xC(r1) mr r31, r3 lbz r0, 0x2BC(r3) cmplwi r0, 0 bne- .loc_0x2C bl -0x244644 rlwinm. r0,r3,0,24,31 beq- .loc_0x40 .loc_0x2C: lwz r0, 0x1E0(r31) lfs f0, 0x2C(r2) ori r0, r0, 0x800 stw r0, 0x1E0(r31) stfs f0, 0x200(r31) .loc_0x40: lwz r0, 0x14(r1) lwz r31, 0xC(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034C0A4 * Size: 000090 */ void Egg::Obj::collisionCallback(Game::CollEvent&) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xC(r1) mr r31, r4 stw r30, 0x8(r1) mr r30, r3 bl -0x245AB0 mr r3, r30 bl -0x24469C rlwinm. r0,r3,0,24,31 beq- .loc_0x78 lwz r3, 0x0(r31) cmplwi r3, 0 beq- .loc_0x78 lwz r12, 0x0(r3) lwz r12, 0x7C(r12) mtctr r12 bctrl rlwinm. r0,r3,0,24,31 bne- .loc_0x78 mr r3, r30 bl -0x244D08 cmpwi r3, 0 bne- .loc_0x78 lwz r0, 0x1E0(r30) lfs f0, 0x2C(r2) ori r0, r0, 0x800 stw r0, 0x1E0(r30) stfs f0, 0x200(r30) .loc_0x78: lwz r0, 0x14(r1) lwz r31, 0xC(r1) lwz r30, 0x8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034C134 * Size: 000050 */ void Egg::Obj::getShadowParam(Game::ShadowParam&) { /* .loc_0x0: lfs f0, 0x18C(r3) lfs f5, 0x30(r2) stfs f0, 0x0(r4) lfs f3, 0x2C(r2) lfs f0, 0x190(r3) lfs f2, 0x34(r2) stfs f0, 0x4(r4) lfs f1, 0x28(r2) lfs f4, 0x194(r3) lfs f0, 0x38(r2) stfs f4, 0x8(r4) lfs f4, 0x190(r3) fadds f4, f5, f4 stfs f4, 0x4(r4) stfs f3, 0xC(r4) stfs f2, 0x10(r4) stfs f3, 0x14(r4) stfs f1, 0x18(r4) stfs f0, 0x1C(r4) blr */ } /* * --INFO-- * Address: 8034C184 * Size: 000048 */ void Egg::Obj::needShadow(void) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xC(r1) mr r31, r3 bl -0x244D88 rlwinm. r0,r3,0,24,31 bne- .loc_0x28 li r3, 0 b .loc_0x34 .loc_0x28: lwz r0, 0xB8(r31) cntlzw r0, r0 rlwinm r3,r0,27,5,31 .loc_0x34: lwz r0, 0x14(r1) lwz r31, 0xC(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034C1CC * Size: 0000A0 */ void Egg::Obj::onStartCapture(void) { /* .loc_0x0: stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1C(r1) mr r31, r3 lwz r5, 0xB8(r3) cmplwi r5, 0 beq- .loc_0x8C lfs f2, 0x2C(r5) addi r4, r1, 0x8 lfs f1, 0x1C(r5) lfs f0, 0xC(r5) stfs f0, 0x8(r1) stfs f1, 0xC(r1) stfs f2, 0x10(r1) lwz r12, 0x0(r3) lwz r12, 0x70(r12) mtctr r12 bctrl lfs f0, 0x2C(r2) stfs f0, 0x1C8(r31) stfs f0, 0x1CC(r31) stfs f0, 0x1D0(r31) stfs f0, 0x1D4(r31) stfs f0, 0x1D8(r31) stfs f0, 0x1DC(r31) lwz r0, 0x1E0(r31) ori r0, r0, 0x400 stw r0, 0x1E0(r31) lwz r0, 0x1E0(r31) ori r0, r0, 0x1 stw r0, 0x1E0(r31) lwz r0, 0x1E0(r31) rlwinm r0,r0,0,26,24 stw r0, 0x1E0(r31) .loc_0x8C: lwz r0, 0x24(r1) lwz r31, 0x1C(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 8034C26C * Size: 000040 */ void Egg::Obj::onEndCapture(void) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xC(r1) mr r31, r3 bl -0x244B14 li r0, 0x1 stb r0, 0x2BC(r31) lwz r0, 0x1E0(r31) ori r0, r0, 0x40 stw r0, 0x1E0(r31) lwz r31, 0xC(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8034C2AC * Size: 0005F4 */ void Egg::Obj::genItem(void) { /* .loc_0x0: stwu r1, -0xF0(r1) mflr r0 stw r0, 0xF4(r1) stfd f31, 0xE0(r1) psq_st f31,0xE8(r1),0,0 stw r31, 0xDC(r1) stw r30, 0xD8(r1) stw r29, 0xD4(r1) lfs f2, 0x2C(r2) mr r29, r3 lfs f1, 0x3C(r2) li r30, 0x2 stfs f2, 0x20(r1) lfs f0, 0x30(r2) stfs f1, 0x24(r1) stfs f2, 0x28(r1) lfs f1, 0x18C(r3) stfs f1, 0x14(r1) lfs f1, 0x190(r3) stfs f1, 0x18(r1) fadds f0, f1, f0 lfs f1, 0x194(r3) stfs f1, 0x1C(r1) stfs f0, 0x18(r1) bl -0x282D6C xoris r3, r3, 0x8000 lis r0, 0x4330 stw r3, 0xB4(r1) lwz r3, 0xC0(r29) stw r0, 0xB0(r1) lfd f2, 0x60(r2) lfd f1, 0xB0(r1) lfs f0, 0x40(r2) fsubs f1, f1, f2 lfs f2, 0x81C(r3) fdivs f1, f1, f0 fcmpo cr0, f1, f2 bge- .loc_0xA0 li r30, 0x2 b .loc_0xFC .loc_0xA0: lfs f0, 0x844(r3) fadds f2, f2, f0 fcmpo cr0, f1, f2 bge- .loc_0xB8 li r30, 0x3 b .loc_0xFC .loc_0xB8: lfs f0, 0x86C(r3) fadds f2, f2, f0 fcmpo cr0, f1, f2 bge- .loc_0xD0 li r30, 0x4 b .loc_0xFC .loc_0xD0: lfs f0, 0x894(r3) fadds f2, f2, f0 fcmpo cr0, f1, f2 bge- .loc_0xE8 li r30, 0x5 b .loc_0xFC .loc_0xE8: lfs f0, 0x8BC(r3) fadds f2, f2, f0 fcmpo cr0, f1, f2 bge- .loc_0xFC li r30, 0x6 .loc_0xFC: lbz r4, 0x8D0(r3) cmplwi r4, 0 beq- .loc_0x10C subi r30, r4, 0x1 .loc_0x10C: lbz r0, 0x8D1(r3) cmplwi r0, 0 beq- .loc_0x15C cmpwi r30, 0x5 bne- .loc_0x13C lwz r3, -0x6B70(r13) li r4, 0x1D bl -0x164FF4 rlwinm. r0,r3,0,24,31 bne- .loc_0x15C li r30, 0x2 b .loc_0x15C .loc_0x13C: cmpwi r30, 0x6 bne- .loc_0x15C lwz r3, -0x6B70(r13) li r4, 0x1E bl -0x165018 rlwinm. r0,r3,0,24,31 bne- .loc_0x15C li r30, 0x2 .loc_0x15C: cmpwi r30, 0x3 li r31, 0 beq- .loc_0x2F4 bge- .loc_0x184 cmpwi r30, 0x1 beq- .loc_0x218 bge- .loc_0x298 cmpwi r30, 0 bge- .loc_0x198 b .loc_0x5D0 .loc_0x184: cmpwi r30, 0x7 bge- .loc_0x5D0 cmpwi r30, 0x5 bge- .loc_0x568 b .loc_0x47C .loc_0x198: bl -0x282EA4 xoris r3, r3, 0x8000 lis r0, 0x4330 stw r3, 0xB4(r1) addi r3, r1, 0x88 lfd f3, 0x60(r2) li r4, 0x1 stw r0, 0xB0(r1) lfs f1, 0x40(r2) lfd f2, 0xB0(r1) lfs f0, 0x44(r2) fsubs f2, f2, f3 fdivs f1, f2, f1 fmuls f0, f0, f1 fctiwz f0, f0 stfd f0, 0xB8(r1) lwz r5, 0xBC(r1) bl -0x1E5914 lwz r3, -0x6CE0(r13) addi r4, r1, 0x88 bl -0x1DEFD4 addi r4, r1, 0x14 mr r30, r3 li r5, 0 bl -0x2112FC mr r3, r30 addi r4, r1, 0x20 lwz r12, 0x0(r30) lwz r12, 0x68(r12) mtctr r12 bctrl b .loc_0x5D0 .loc_0x218: bl -0x282F24 xoris r3, r3, 0x8000 lis r0, 0x4330 stw r3, 0xBC(r1) addi r3, r1, 0x60 lfd f3, 0x60(r2) li r4, 0x5 stw r0, 0xB8(r1) lfs f1, 0x40(r2) lfd f2, 0xB8(r1) lfs f0, 0x44(r2) fsubs f2, f2, f3 fdivs f1, f2, f1 fmuls f0, f0, f1 fctiwz f0, f0 stfd f0, 0xB0(r1) lwz r5, 0xB4(r1) bl -0x1E5994 lwz r3, -0x6CE0(r13) addi r4, r1, 0x60 bl -0x1DF054 addi r4, r1, 0x14 mr r31, r3 li r5, 0 bl -0x21137C mr r3, r31 addi r4, r1, 0x20 lwz r12, 0x0(r31) lwz r12, 0x68(r12) mtctr r12 bctrl b .loc_0x5D0 .loc_0x298: lwz r3, -0x6BB0(r13) lwz r12, 0x0(r3) lwz r12, 0xA4(r12) mtctr r12 bctrl mr. r0, r3 beq- .loc_0x5D0 mr r30, r0 li r4, 0 bl -0x2115A0 li r0, 0 mr r3, r30 stb r0, 0x1E0(r30) addi r4, r1, 0x14 li r5, 0 bl -0x2113D8 mr r3, r30 addi r4, r1, 0x20 lwz r12, 0x0(r30) lwz r12, 0x68(r12) mtctr r12 bctrl b .loc_0x5D0 .loc_0x2F4: bl -0x283000 xoris r3, r3, 0x8000 lis r0, 0x4330 stw r3, 0xBC(r1) li r31, 0 lfd f3, 0x60(r2) stw r0, 0xB8(r1) lfs f1, 0x40(r2) lfd f2, 0xB8(r1) lfs f0, 0x48(r2) fsubs f2, f2, f3 fdivs f1, f2, f1 fmuls f31, f0, f1 .loc_0x328: lwz r3, -0x6BB0(r13) lwz r12, 0x0(r3) lwz r12, 0xA4(r12) mtctr r12 bctrl lfs f2, 0x20(r1) cmplwi r3, 0 lfs f1, 0x24(r1) lfs f0, 0x28(r1) stfs f2, 0x8(r1) stfs f1, 0xC(r1) stfs f0, 0x10(r1) beq- .loc_0x46C xoris r4, r31, 0x8000 lis r0, 0x4330 stw r4, 0xBC(r1) mr r30, r3 lfd f2, 0x60(r2) stw r0, 0xB8(r1) lfs f3, 0x4C(r2) lfd f1, 0xB8(r1) lfs f0, 0x2C(r2) fsubs f2, f1, f2 lfs f1, 0x50(r2) fmadds f2, f3, f2, f31 fcmpo cr0, f2, f0 bge- .loc_0x3C0 lfs f0, 0x54(r2) lis r3, 0x8050 addi r3, r3, 0x71A0 fmuls f0, f2, f0 fctiwz f0, f0 stfd f0, 0xB0(r1) lwz r0, 0xB4(r1) rlwinm r0,r0,3,18,28 lfsx f0, r3, r0 fneg f0, f0 b .loc_0x3E4 .loc_0x3C0: lfs f0, 0x58(r2) lis r3, 0x8050 addi r3, r3, 0x71A0 fmuls f0, f2, f0 fctiwz f0, f0 stfd f0, 0xC0(r1) lwz r0, 0xC4(r1) rlwinm r0,r0,3,18,28 lfsx f0, r3, r0 .loc_0x3E4: fmuls f1, f1, f0 lfs f0, 0x2C(r2) fcmpo cr0, f2, f0 stfs f1, 0x8(r1) bge- .loc_0x3FC fneg f2, f2 .loc_0x3FC: lfs f0, 0x58(r2) lis r3, 0x8050 addi r0, r3, 0x71A0 lfs f1, 0x50(r2) fmuls f0, f2, f0 mr r3, r30 li r4, 0 fctiwz f0, f0 stfd f0, 0xC8(r1) lwz r5, 0xCC(r1) rlwinm r5,r5,3,18,28 add r5, r0, r5 lfs f0, 0x4(r5) fmuls f0, f1, f0 stfs f0, 0x10(r1) bl -0x21171C li r0, 0 mr r3, r30 stb r0, 0x1E0(r30) addi r4, r1, 0x14 li r5, 0 bl -0x211554 mr r3, r30 addi r4, r1, 0x8 lwz r12, 0x0(r30) lwz r12, 0x68(r12) mtctr r12 bctrl .loc_0x46C: addi r31, r31, 0x1 cmpwi r31, 0x2 blt+ .loc_0x328 b .loc_0x5D0 .loc_0x47C: lwz r3, -0x6E20(r13) li r4, 0x44 bl -0x23EA8C mr. r30, r3 beq- .loc_0x504 addi r3, r1, 0x2C bl -0x21DB1C lfs f0, 0x18C(r29) stfs f0, 0x2C(r1) lfs f0, 0x190(r29) stfs f0, 0x30(r1) lfs f0, 0x194(r29) stfs f0, 0x34(r1) bl -0x2831BC xoris r3, r3, 0x8000 lis r0, 0x4330 stw r3, 0xCC(r1) mr r3, r30 lfs f0, 0x5C(r2) addi r4, r1, 0x2C stw r0, 0xC8(r1) addi r6, r1, 0x20 lfd f3, 0x60(r2) li r5, 0xA lfd f1, 0xC8(r1) lfs f2, 0x40(r2) fsubs f3, f1, f3 lfs f1, 0x48(r2) stfs f0, 0x24(r1) fdivs f0, f3, f2 fmuls f0, f1, f0 stfs f0, 0x38(r1) bl 0x21688 mr r31, r3 .loc_0x504: cmplwi r31, 0 bne- .loc_0x5D0 lwz r3, -0x6BB0(r13) lwz r12, 0x0(r3) lwz r12, 0xA4(r12) mtctr r12 bctrl mr. r0, r3 beq- .loc_0x5D0 mr r30, r0 li r4, 0 bl -0x211814 li r0, 0 mr r3, r30 stb r0, 0x1E0(r30) addi r4, r1, 0x14 li r5, 0 bl -0x21164C mr r3, r30 addi r4, r1, 0x20 lwz r12, 0x0(r30) lwz r12, 0x68(r12) mtctr r12 bctrl b .loc_0x5D0 .loc_0x568: lwz r3, -0x6BB0(r13) lwz r12, 0x0(r3) lwz r12, 0xA4(r12) mtctr r12 bctrl mr. r0, r3 beq- .loc_0x5D0 mr r31, r0 li r4, 0 bl -0x211870 li r0, 0x1 cmpwi r30, 0x6 stb r0, 0x1E0(r31) bne- .loc_0x5A8 li r0, 0x2 stb r0, 0x1E0(r31) .loc_0x5A8: mr r3, r31 addi r4, r1, 0x14 li r5, 0 bl -0x2116B8 mr r3, r31 addi r4, r1, 0x20 lwz r12, 0x0(r31) lwz r12, 0x68(r12) mtctr r12 bctrl .loc_0x5D0: psq_l f31,0xE8(r1),0,0 lwz r0, 0xF4(r1) lfd f31, 0xE0(r1) lwz r31, 0xDC(r1) lwz r30, 0xD8(r1) lwz r29, 0xD4(r1) mtlr r0 addi r1, r1, 0xF0 blr */ } /* * --INFO-- * Address: 8034C8A0 * Size: 000004 */ void Egg::Obj::setInitialSetting(Game::EnemyInitialParamBase*) { } /* * --INFO-- * Address: 8034C8A4 * Size: 000010 */ void Egg::Obj::isLivingThing(void) { /* .loc_0x0: lwz r0, 0xB8(r3) cntlzw r0, r0 rlwinm r3,r0,27,5,31 blr */ } /* * --INFO-- * Address: 8034C8B4 * Size: 000008 */ u32 Egg::Obj::getEnemyTypeID(void) { return 0x25; } /* * --INFO-- * Address: 8034C8BC * Size: 000008 */ void Egg::Obj::getDownSmokeScale(void) { /* .loc_0x0: lfs f1, 0x68(r2) blr */ } } // namespace Game /* * --INFO-- * Address: 8034C8C4 * Size: 000014 */ void @708 @12 @Game::EnemyBase::viewOnPelletKilled(void) { /* .loc_0x0: li r11, 0xC lwzx r11, r3, r11 add r3, r3, r11 subi r3, r3, 0x2C4 b -0x245FB8 */ } /* * --INFO-- * Address: 8034C8D8 * Size: 000014 */ void @708 @12 @Game::EnemyBase::viewStartCarryMotion(void) { /* .loc_0x0: li r11, 0xC lwzx r11, r3, r11 add r3, r3, r11 subi r3, r3, 0x2C4 b -0x246240 */ } /* * --INFO-- * Address: 8034C8EC * Size: 000014 */ void @708 @12 @Game::EnemyBase::viewStartPreCarryMotion(void) { /* .loc_0x0: li r11, 0xC lwzx r11, r3, r11 add r3, r3, r11 subi r3, r3, 0x2C4 b -0x246234 */ } /* * --INFO-- * Address: 8034C900 * Size: 000014 */ void @708 @12 @Game::EnemyBase::view_finish_carrymotion(void) { /* .loc_0x0: li r11, 0xC lwzx r11, r3, r11 add r3, r3, r11 subi r3, r3, 0x2C4 b -0x245E98 */ } /* * --INFO-- * Address: 8034C914 * Size: 000014 */ void @708 @12 @Game::EnemyBase::view_start_carrymotion(void) { /* .loc_0x0: li r11, 0xC lwzx r11, r3, r11 add r3, r3, r11 subi r3, r3, 0x2C4 b -0x245ED8 */ } /* * --INFO-- * Address: 8034C928 * Size: 000014 */ void @708 @12 @Game::EnemyBase::viewGetShape(void) { /* .loc_0x0: li r11, 0xC lwzx r11, r3, r11 add r3, r3, r11 subi r3, r3, 0x2C4 b -0x246298 */ }
a6f4b35bd48d29ed6e06f39ffe8489766f84b50f
29ec7606e313717eac54023f6646ef84b30259b0
/ardurover1.2.ino
699336035455f6bd4ae4a29834e5b685b469e935
[]
no_license
sTVG/ardurover1.2
82ebab2214198766b511a826fd9d2730f3a47ed7
844012d1f9c54f084911885c4e5fb4f062fcfb7d
refs/heads/master
2020-05-18T16:33:21.055068
2015-04-29T18:48:59
2015-04-29T18:48:59
34,814,464
0
0
null
null
null
null
UTF-8
C++
false
false
6,714
ino
ardurover1.2.ino
/* This is my first public code, and draws heavily on code from Iain Portalupi L298N_Dual_H_Bridge This program controls an ultrasonic sensor rover using L298N H Bridge Chip and SG04 sensor Made with the help of http://themakerspace.co.za *THE MOTOR SUBROUTINES WORK AS FOLLOWS* motorA(mode, speed) % replace A with B to control motor B % mode is a number 0 -> 3 that determines what the motor will do. 0 = coast/disable the H bridge 1 = turn motor clockwise 2 = turn motor counter clockwise 3 = brake motor speed is a number 0 -> 100 that represents percentage of motor speed. 0 = off 50 = 50% of full motor speed 100 = 100% of full motor speed EXAMPLE Say you need to have motor A turn clockwise at 33% of its full speed. The subroutine call would be the following... motorA(1, 33); Created by Iain Portalupi http://www.youtube.com/iainportalupi 1/2/2014 This code is in the public domain. */ #include <NewPing.h> #define runEvery(t) for (static typeof(t) _lasttime;(typeof(t))((typeof(t))millis() - _lasttime) > (t);_lasttime += (t)) #define TRIGGER_PIN A0 // Arduino pin tied to trigger pin on ping sensor. #define ECHO_PIN A1 // Arduino pin tied to echo pin on ping sensor. #define MAX_DISTANCE 160 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. #define ENA 6 //enable A on pin 6 (needs to be a pwm pin) #define ENB 5 //enable B on pin 5 (needs to be a pwm pin) #define IN1 10 //IN1 on pin 10 conrtols one side of bridge A #define IN2 11 //IN2 on pin 11 controls other side of A #define IN3 8 //IN3 on pin 8 conrtols one side of bridge B #define IN4 9 //IN4 on pin 9 controls other side of B #define SenA A3 //current sensing from H-Bridge to pin 12 of arduino (hope it doesnt blow it) #define SenB A2 //current sensing from H-Bridge NewPing Roboeyes(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // distance sensor called Roboeyes int SR04; int cm2crash; int currentz; void setup() { //set all of the outputs { pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT); Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results. delay(3000); } } void loop() { Distance2crash(); if (1 < cm2crash && cm2crash <=15) //very close to object - reverse { motorA(2, 75); //motor A reverse 75% motorB(2, 50); //motor B reverse 75% delay(1000); } else if (15 < cm2crash && cm2crash <30) //moderately close to object - tight turn left { //motorA(1, 50); //have motor A turn clockwise at 80% speed //motorB(2, 50); //have motor B turn anticlockwise at 80% speed delay(500); } else if (cm2crash >= 30 && cm2crash < 50) //far from object - turn left { motorA(1, 66); //have motor A turn clockwise at 80% speed motorB(2, 50); //have motor B turn clockwise at 80% speed delay(500); } else // cruise { motorA(1, 66); //have motor A turn clockwise at 80% speed motorB(1, 66); //have motor B turn clockwise at 80% speed } } //****************** Current sense from H-bridge ** /* void currentsense() { runEvery(100) { currentz = SenA; } Serial.println(currentz); } */ //****************** Sonar ultrasonic ******************* void Distance2crash() { runEvery(100) //loop for ultrasonic measurement { SR04 = Roboeyes.ping(); cm2crash = SR04 / US_ROUNDTRIP_CM; if (SR04 == NO_ECHO) // if the sensor did not get a ping { cm2crash = MAX_DISTANCE; //so the distance must be bigger then the max vaulue of the sensor } // Serial.print("Ping: "); //to check distance on the serial monitor // Serial.println(cm2crash); } } //****************** Motor A control ******************* void motorA(int mode, int percent) { //change the percentage range of 0 -> 100 into the PWM //range of 0 -> 255 using the map function int duty = map(percent, 0, 100, 0, 255); switch(mode) { case 0: //disable/coast digitalWrite(ENA, LOW); //set enable low to disable A break; case 1: //turn clockwise //setting IN1 high connects motor lead 1 to +voltage digitalWrite(IN1, HIGH); //setting IN2 low connects motor lead 2 to ground digitalWrite(IN2, LOW); //use pwm to control motor speed through enable pin analogWrite(ENA, duty); break; case 2: //turn counter-clockwise //setting IN1 low connects motor lead 1 to ground digitalWrite(IN1, LOW); //setting IN2 high connects motor lead 2 to +voltage digitalWrite(IN2, HIGH); //use pwm to control motor speed through enable pin analogWrite(ENA, duty); break; case 3: //brake motor //setting IN1 low connects motor lead 1 to ground digitalWrite(IN1, LOW); //setting IN2 high connects motor lead 2 to ground digitalWrite(IN2, LOW); //use pwm to control motor braking power //through enable pin analogWrite(ENA, duty); break; } } //********************************************************** //****************** Motor B control ******************* void motorB(int mode, int percent) { //change the percentage range of 0 -> 100 into the PWM //range of 0 -> 255 using the map function int duty = map(percent, 0, 100, 0, 255); switch(mode) { case 0: //disable/coast digitalWrite(ENB, LOW); //set enable low to disable B break; case 1: //turn clockwise //setting IN3 high connects motor lead 1 to +voltage digitalWrite(IN3, HIGH); //setting IN4 low connects motor lead 2 to ground digitalWrite(IN4, LOW); //use pwm to control motor speed through enable pin analogWrite(ENB, duty); break; case 2: //turn counter-clockwise //setting IN3 low connects motor lead 1 to ground digitalWrite(IN3, LOW); //setting IN4 high connects motor lead 2 to +voltage digitalWrite(IN4, HIGH); //use pwm to control motor speed through enable pin analogWrite(ENB, duty); break; case 3: //brake motor //setting IN3 low connects motor lead 1 to ground digitalWrite(IN3, LOW); //setting IN4 high connects motor lead 2 to ground digitalWrite(IN4, LOW); //use pwm to control motor braking power //through enable pin analogWrite(ENB, duty); break; } }
592a9bd80c67daf346641cb916f38089e75eeefe
e0d8f27f590a0b7b2330b5a391319b07ba823635
/source/Rendering/Renderer.cpp
1e1437c0af35b94859a3a35cce64cb12520a323c
[]
no_license
FiskNi/Project-Kiddo
0c2a74b6989ac6236f88d94aa3004d40c5debd50
516ef59ea503ccca211d231aa4d2eb14d929e2cc
refs/heads/master
2021-07-10T02:56:42.479967
2020-08-24T13:17:41
2020-08-24T13:17:41
180,403,595
0
0
null
null
null
null
UTF-8
C++
false
false
23,276
cpp
Renderer.cpp
#include "Renderer.h" Renderer::Renderer() { boneBuffer = 0; gVertexBuffer = 0; gVertexAttribute = 0; gVertexBufferMain = 0; gVertexAttributeMain = 0; gVertexBufferPause = 0; gVertexAttributePause = 0; gVertexBufferCollectible = 0; gVertexAttributeCollectible = 0; initWindow(WIDTH, HEIGHT); // Creates the frame buffer for shadow mapping shadowMap.CreateFrameBufferSM(); } Renderer::~Renderer() { glDeleteFramebuffers(1, &gFbo); glDeleteTextures(2, gFboTextureAttachments); glDeleteVertexArrays(1, &gVertexAttribute); glDeleteVertexArrays(1, &gVertexAttributeMain); glDeleteVertexArrays(1, &gVertexAttributePause); glDeleteVertexArrays(1, &gVertexAttributeCollectible); glDeleteBuffers(1, &gVertexBuffer); glDeleteBuffers(1, &gVertexBufferMain); glDeleteBuffers(1, &gVertexBufferPause); glDeleteBuffers(1, &gVertexBufferCollectible); } GLFWwindow* Renderer::getWindow() { return gWindow; } //============================================================= // Handles stuff for the fullscreen quad. // Usefull for rendering techniques. //============================================================= void Renderer::firstPassRenderTemp(Shader gShaderProgram, float gClearColour[]) { // first pass // render all geometry to a framebuffer object glBindFramebuffer(GL_FRAMEBUFFER, gFbo); glClearColor(gClearColour[0], gClearColour[1], gClearColour[2], gClearColour[3]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(gShaderProgram.getShader()); glBindVertexArray(gShaderProgram.getVertexAttributes()); glEnable(GL_DEPTH_TEST); } //============================================================= // Handles stuff for the fullscreen quad. // Usefull for rendering techniques. //============================================================= void Renderer::secondPassRenderTemp(Shader gShaderProgram) { // first pass is done! // now render a second pass // bind default framebuffer glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(gShaderProgram.getShader()); glBindVertexArray(gShaderProgram.getVertexAttributes()); glDisable(GL_DEPTH_TEST); // bind texture drawn in the first pass! glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, gFboTextureAttachments[0]); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, gFboTextureAttachments[1]); glBindTexture(GL_TEXTURE_2D, shadowMap.getDepthMapAttachment()); } void Renderer::secondPassRenderPauseOverlay(Shader gShaderProgram, GLuint pauseOverlayTexture) { // Renders alternative Full Screen Quad to cover the screen with a Pause Screen Overlay // bind default framebuffer glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(gShaderProgram.getShader()); glBindVertexArray(gShaderProgram.getVertexAttributes()); glDisable(GL_DEPTH_TEST); // Binds the pauseOverlayTexture instead of gFboTextureAttachments[0], this is the overlay texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, pauseOverlayTexture); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, gFboTextureAttachments[1]); glBindTexture(GL_TEXTURE_2D, shadowMap.getDepthMapAttachment()); } //============================================================= // Pre pass render needed to generate depth map for shadows. //============================================================= void Renderer::ShadowmapRender(Shader gShaderProgram, const std::vector<Mesh*>& objects, Camera camera, float gClearColour[3], std::vector<DirectionalLight> dirLightArr) { //PrePass render for Shadow mapping shadowMap.bindForWriting(); // tell opengl we want to use the gShaderProgram glUseProgram(gShaderProgram.getShader()); glBindVertexArray(gVertexAttribute); // tell opengl we are going to use the VAO we described earlier unsigned int startIndex = 0; for (int i = 0; i < objects.size(); i++) { shadowMap.CreateShadowMatrixData(dirLightArr[0].GetPos(), gShaderProgram.getShader()); CreateModelMatrix(objects[i]->GetPosition(), objects[i]->GetRotation(), objects[i]->GetScale(), gShaderProgram.getShader()); glUniformMatrix4fv(1, 1, GL_FALSE, glm::value_ptr(MODEL_MAT)); glUniformMatrix4fv(2, 1, GL_FALSE, glm::value_ptr(shadowMap.getShadowMatrix())); glDrawArrays(GL_TRIANGLES, startIndex, objects[i]->GetVertexCount()); startIndex += objects[i]->GetVertexCount(); } } //============================================================= // Main render pass //============================================================= void Renderer::Render(Shader gShaderProgram, std::vector<Mesh*>& objects, Camera camera, float gClearColour[3], std::vector<Light>& lightArr, std::vector<DirectionalLight>& dirLightArr, std::vector<Material*>& materials) { // Position in shader // set the color TO BE used (this does not clear the screen right away) glClearColor(gClearColour[0], gClearColour[1], gClearColour[2], 1.0f); // use the color to clear the color buffer (clear the color buffer only) glClear(GL_COLOR_BUFFER_BIT); // tell opengl we want to use the gShaderProgram glUseProgram(gShaderProgram.getShader()); // Shadowmap ViewProjection matrix shadowMap.CreateShadowMatrixData(dirLightArr[0].GetPos(), gShaderProgram.getShader()); // Per shader uniforms glUniformMatrix4fv(view_matrix, 1, GL_FALSE, glm::value_ptr(camera.GetViewMatrix())); glUniformMatrix4fv(projection_matrix, 1, GL_FALSE, glm::value_ptr(camera.GetProjectionMatrix())); glUniformMatrix4fv(shadow_matrix, 1, GL_FALSE, glm::value_ptr(shadowMap.getShadowMatrix())); glUniform3fv(cam_pos, 1, glm::value_ptr(camera.GetPosition())); dirLightArr[0].SendToShader(gShaderProgram); //Sending all the lights to shader. for (int i = 0; i < POINTLIGHTS; i++) { lightArr[i].SendToShader(gShaderProgram, i); } // Main render queue // Currently the render swaps buffer for every object which could become slow further on // If possible the rendercalls could be improved glBindVertexArray(gVertexAttribute); unsigned int startIndex = 0; for (int i = 0; i < objects.size(); i++) { // Per object uniforms CreateModelMatrix(objects[i]->GetPosition(), objects[i]->GetRotation(), objects[i]->GetScale(), gShaderProgram.getShader()); glUniformMatrix4fv(model_matrix, 1, GL_FALSE, glm::value_ptr(MODEL_MAT)); glUniform1ui(has_normal, materials[objects[i]->GetMaterialID()]->hasNormal()); glUniform1ui(has_albedo, materials[objects[i]->GetMaterialID()]->hasAlbedo()); // Vertex animation buffer if (objects[i]->GetSkeleton().animations.size() >= 1) { glUniform1ui(hasAnimation, true); SkinDataBuffer boneData; ComputeAnimationMatrix(&boneData, objects[i]->GetSkeleton().currentAnimTime, objects[i]); unsigned int boneDataIndex = glGetUniformBlockIndex(gShaderProgram.getShader(), "SkinDataBlock"); glUniformBlockBinding(gShaderProgram.getShader(), boneDataIndex, 1); glBindBufferBase(GL_UNIFORM_BUFFER, 1, boneBuffer); glBufferData(GL_UNIFORM_BUFFER, sizeof(SkinDataBuffer), &boneData, GL_STATIC_DRAW); } else { glUniform1ui(hasAnimation, false); } // Binds the albedo texture from a material passTextureData(GL_TEXTURE0, materials[objects[i]->GetMaterialID()]->getAlbedo(), gShaderProgram.getShader(), "diffuseTex", 0); // Binds the normal texture from a material if (materials[objects[i]->GetMaterialID()]->hasNormal()) { passTextureData(GL_TEXTURE1, materials[objects[i]->GetMaterialID()]->getNormal(), gShaderProgram.getShader(), "normalTex", 1); } glUniform3fv(ambient, 1, glm::value_ptr(materials[objects[i]->GetMaterialID()]->getAmbient())); glUniform3fv(diffuse, 1, glm::value_ptr(materials[objects[i]->GetMaterialID()]->getDiffuse())); glUniform3fv(specular, 1, glm::value_ptr(materials[objects[i]->GetMaterialID()]->getSpecular())); glUniform3fv(emissive, 1, glm::value_ptr(materials[objects[i]->GetMaterialID()]->getEmissive())); // Binds the shadowmap (handles by the renderer) passTextureData(GL_TEXTURE2, shadowMap.getDepthMapAttachment(), gShaderProgram.getShader(), "shadowMap", 2); // Draw call // As the buffer is swapped for each object the drawcall currently always starts at index 0 // This is what could be improved with one large buffer and then advance the start index for each object glDrawArrays(GL_TRIANGLES, startIndex, objects[i]->GetVertexCount()); startIndex += objects[i]->GetVertexCount(); } } //============================================================= // Creates a vertexbuffer from all the recieved vertex data //============================================================= void Renderer::CompileVertexData(int vertexCount, vertexPolygon* vertices) { //glDeleteVertexArrays(1, &gVertexAttribute); // Vertex Array Object (VAO), description of the inputs to the GPU glGenVertexArrays(1, &gVertexAttribute); // bind is like "enabling" the object to use it glBindVertexArray(gVertexAttribute); // this activates the first and second attributes of this VAO // think of "attributes" as inputs to the Vertex Shader glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); // create a vertex buffer object (VBO) id (out Array of Structs on the GPU side) glGenBuffers(1, &gVertexBuffer); // Bind the buffer ID as an ARRAY_BUFFER glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer); // This "could" imply copying to the GPU, depending on what the driver wants to do, and // the last argument (read the docs!) glBufferData(GL_ARRAY_BUFFER, vertexCount * sizeof(vertexPolygon), vertices, GL_STATIC_DRAW); // tell OpenGL about layout in memory (input assembler information) glVertexAttribPointer( 0, // location in shader 3, // how many elements of type (see next argument) GL_FLOAT, // type of each element GL_FALSE, // integers will be normalized to [-1,1] or [0,1] when read... sizeof(vertexPolygon), // distance between two vertices in memory (stride) BUFFER_OFFSET(0) // offset of FIRST vertex in the list. ); glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof(vertexPolygon), BUFFER_OFFSET(sizeof(float) * 3) ); glVertexAttribPointer( 2, 3, GL_FLOAT, GL_FALSE, sizeof(vertexPolygon), BUFFER_OFFSET(sizeof(float) * 5) ); glVertexAttribPointer( 3, 3, GL_FLOAT, GL_FALSE, sizeof(vertexPolygon), BUFFER_OFFSET(sizeof(float) * 8) ); glVertexAttribPointer( 4, 3, GL_FLOAT, GL_FALSE, sizeof(vertexPolygon), BUFFER_OFFSET(sizeof(float) * 11) ); glVertexAttribPointer( 5, 4, GL_FLOAT, GL_FALSE, sizeof(vertexPolygon), BUFFER_OFFSET(sizeof(float) * 14) ); glVertexAttribIPointer( 6, 4, GL_INT, sizeof(vertexPolygon), BUFFER_OFFSET(sizeof(float) * 18) ); //SkinDataBuffer glGenBuffers(1, &boneBuffer); glBindBuffer(GL_UNIFORM_BUFFER, boneBuffer); glBufferData(GL_UNIFORM_BUFFER, sizeof(glm::mat4) * 64, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } //============================================================== // Render pass for the main menu and pause menu //============================================================= void Renderer::RenderMenu(Shader gShaderProgram, std::vector<MenuButton> objects, float gClearColour[3], std::vector<GLuint> textures, ACTIVEMENU activeMenu) { // set the color TO BE used (this does not clear the screen right away) glClearColor(gClearColour[0], gClearColour[1], gClearColour[2], 1.0f); // use the color to clear the color buffer (clear the color buffer only) glClear(GL_COLOR_BUFFER_BIT); // tell opengl we want to use the gShaderProgram glUseProgram(gShaderProgram.getShader()); //glDisable(GL_DEPTH_TEST); //glEnable(GL_DEPTH_TEST); // Main render queue // Currently the render swaps buffer for every object which could become slow further on // If possible the rendercalls could be improved if (activeMenu == PAUSEACTIVE) { glBindVertexArray(gVertexAttributePause); } else if (activeMenu == COLLECTIBLEACTIVE) { glBindVertexArray(gVertexAttributeCollectible); } else if (activeMenu == HTPACTIVE) { glBindVertexArray(gVertexAttributeHtp); } else { glBindVertexArray(gVertexAttributeMain); } unsigned int startIndex = 0; for (int i = 0; i < objects.size(); i++) { //Binds the albedo texture from a material passTextureData(GL_TEXTURE0, textures[objects[i].GetTextureID()], gShaderProgram.getShader(), "diffuseTex", 0); //passTextureData(GL_TEXTURE0, textures[i], gShaderProgram.getShader(), "diffuseTex", 0); // Draw call // As the buffer is swapped for each object the drawcall currently always starts at index 0 // This is what could be improved with one large buffer and then advance the start index for each object glDrawArrays(GL_TRIANGLES, startIndex, (int)objects[i].GetVertexCount() ); startIndex += objects[i].GetVertexCount(); } } //============================================================= // Creates a vertexbuffer from the menu data to be rendered //============================================================= void Renderer::CompileMenuVertexData(int vertexCount, ButtonVtx* vertices, ACTIVEMENU activeMenu) { if (activeMenu == PAUSEACTIVE) { glGenVertexArrays(1, &gVertexAttributePause); glBindVertexArray(gVertexAttributePause); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glGenBuffers(1, &gVertexBufferPause); glBindBuffer(GL_ARRAY_BUFFER, gVertexBufferPause); } else if (activeMenu == COLLECTIBLEACTIVE) { glGenVertexArrays(1, &gVertexAttributeCollectible); glBindVertexArray(gVertexAttributeCollectible); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glGenBuffers(1, &gVertexBufferCollectible); glBindBuffer(GL_ARRAY_BUFFER, gVertexBufferCollectible); } else if (activeMenu == HTPACTIVE) { glGenVertexArrays(1, &gVertexAttributeHtp); glBindVertexArray(gVertexAttributeHtp); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glGenBuffers(1, &gVertexBufferHtp); glBindBuffer(GL_ARRAY_BUFFER, gVertexBufferHtp); } else { glBindVertexArray(gVertexAttributeMain); // Vertex Array Object (VAO), description of the inputs to the GPU glGenVertexArrays(1, &gVertexAttributeMain); // bind is like "enabling" the object to use it glBindVertexArray(gVertexAttributeMain); // this activates the first and second attributes of this VAO // think of "attributes" as inputs to the Vertex Shader glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); // create a vertex buffer object (VBO) id (out Array of Structs on the GPU side) glGenBuffers(1, &gVertexBufferMain); // Bind the buffer ID as an ARRAY_BUFFER glBindBuffer(GL_ARRAY_BUFFER, gVertexBufferMain); } // This "could" imply copying to the GPU, depending on what the driver wants to do, and // the last argument (read the docs!) glBufferData(GL_ARRAY_BUFFER, vertexCount * sizeof(ButtonVtx), vertices, GL_STATIC_DRAW); // tell OpenGL about layout in memory (input assembler information) glVertexAttribPointer( 0, // location in shader 3, // how many elements of type (see next argument) GL_FLOAT, // type of each element GL_FALSE, // integers will be normalized to [-1,1] or [0,1] when read... sizeof(ButtonVtx), // distance between two vertices in memory (stride) BUFFER_OFFSET(0) // offset of FIRST vertex in the list. ); glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof(ButtonVtx), BUFFER_OFFSET(sizeof(float) * 3) ); } //============================================================= // From template - Needs explanation // Has to do with the fullscreen quad //============================================================= int Renderer::CreateFrameBuffer() { int err = 0; // =================== COLOUR BUFFER ======================================= // add "Attachments" to the framebuffer (textures to write to/read from) glGenTextures(2, gFboTextureAttachments); glBindTexture(GL_TEXTURE_2D, gFboTextureAttachments[0]); // define storage for texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); // define sampler settings glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // attach texture to framebuffer object // ===================== DEPTH BUFFER ==================================== glBindTexture(GL_TEXTURE_2D, gFboTextureAttachments[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, WIDTH, HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glGenFramebuffers(1, &gFbo); glBindFramebuffer(GL_FRAMEBUFFER, gFbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gFboTextureAttachments[0], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, gFboTextureAttachments[1], 0); // check if framebuffer is complete (usable): if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) err = 0; else err = -1; // bind default framebuffer glBindFramebuffer(GL_FRAMEBUFFER, 0); return err; } //============================================================= // Initialized the opengl window // Could be a window class instead //============================================================= void Renderer::initWindow(unsigned int w, unsigned int h) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); gWindow = glfwCreateWindow(w, h, "Project Kiddo", NULL, NULL); if (!gWindow) { fprintf(stderr, "error creating window\n"); exit(-1); } glfwMakeContextCurrent(gWindow); glewExperimental = GL_TRUE; // mouse callback // glfwSetCursorPosCallback(gWindow, mouseMoved); glfwSwapInterval(1); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "Error GLEW: %s\n", glewGetErrorString(err)); } const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); //fprintf(stderr, "Renderer: %s\n", renderer); //fprintf(stderr, "OpenGL version %s\n", version); cout << "Renderer: " << renderer << endl; cout << "OpenGL version: " << version << endl; // start up time // timerStart = glfwGetTime(); glClearColor(0.9f, 0.2f, 0.2f, 0.0f); glClearDepth(1.0f); glViewport(0, 0, w, h); return; } //============================================================= // Sets the main viewport, usually used after swapping shaders //============================================================= void Renderer::SetViewport() { glViewport(0, 0, WIDTH, HEIGHT); } //============================================================= // Updates the model matrix for an object // Need to lookup quick matrix multiplication etc for rotation stuff // and what not. //============================================================= void Renderer::CreateModelMatrix(glm::vec3 translation, glm::quat rotation, glm::vec3 scale, GLuint shaderProg) { // This calculation assumes the vertice position (not the vec3 position) are in their global 0 position MODEL_MAT = glm::mat4(1.0f); glm::mat4 translationMatrix = glm::translate(MODEL_MAT, translation); glm::mat4 rotationMatrix = glm::mat4_cast(rotation); glm::mat4 scaleMatrix = glm::scale(MODEL_MAT, scale); MODEL_MAT = translationMatrix * rotationMatrix * scaleMatrix; } void Renderer::ComputeAnimationMatrix(SkinDataBuffer* boneList, float anim_time, Mesh* mesh) { // use animation 0 for now.... SkeletonD::AnimationD& anim = mesh->GetSkeleton().animations[0]; // time must be less than duration. if (anim_time > anim.duration) return; //anim_time = 0.0f; // keyframes involved. int k1 = (int)(anim_time * anim.rate); k1 = fmaxf(k1, anim.keyframeFirst); int k2 = fminf(k1 + 1, anim.keyframeLast); // keyframes in anim_time terms float k1_time = k1 / anim.rate; float k2_time = k2 / anim.rate; // time rescaled into [0..1] as a percentage between k1 and k2 float t = (anim_time - k1_time) / (k2_time - k1_time); int boneCount = (int)mesh->GetSkeleton().joints.size(); glm::mat4 bones_global_pose[MAXBONES]{ glm::mat4(1.0f) }; for (int i = 0; i < MAXBONES; i++) bones_global_pose[i] = glm::mat4(1.0f); glm::vec3 translation_r = glm::vec3(anim.keyframes[k1].local_joints_T[0] * (1 - t) + anim.keyframes[k2].local_joints_T[0] * t); glm::vec3 scaling_r = glm::vec3(anim.keyframes[k1].local_joints_S[0] * (1 - t) + anim.keyframes[k2].local_joints_S[0] * t); glm::quat quaternion_r = glm::slerp(anim.keyframes[k1].local_joints_R[0], anim.keyframes[k2].local_joints_R[0], t); MODEL_MAT = glm::mat4(1.0f); glm::mat4 translationMatrix_r = glm::translate(MODEL_MAT, translation_r); glm::mat4 rotationMatrix_r = glm::mat4_cast(quaternion_r); glm::mat4 scaleMatrix_r = glm::scale(MODEL_MAT, scaling_r); glm::mat4 local_r = translationMatrix_r * rotationMatrix_r * scaleMatrix_r; bones_global_pose[0] = local_r; boneList->bones[0] = bones_global_pose[0] * mesh->GetSkeleton().joints[0].invBindPose; //boneList->bones[0] = glm::inverse(mesh->GetSkeleton().joints[0].invBindPose); for (int bone = 1; bone < boneCount; bone++) { glm::vec3 translation = glm::vec3(anim.keyframes[k1].local_joints_T[bone] * (1 - t) + anim.keyframes[k2].local_joints_T[bone] * t); glm::vec3 scaling = glm::vec3(anim.keyframes[k1].local_joints_S[bone] * (1 - t) + anim.keyframes[k2].local_joints_S[bone] * t); glm::quat quaternion = glm::slerp(anim.keyframes[k1].local_joints_R[bone], anim.keyframes[k2].local_joints_R[bone], t); MODEL_MAT = glm::mat4(1.0f); glm::mat4 translationMatrix = glm::translate(MODEL_MAT, translation); glm::mat4 rotationMatrix = glm::mat4_cast(quaternion); glm::mat4 scaleMatrix = glm::scale(MODEL_MAT, scaling); glm::mat4 local = translationMatrix * rotationMatrix * scaleMatrix; bones_global_pose[bone] = bones_global_pose[mesh->GetSkeleton().joints[bone].parentIndex] * local; boneList->bones[bone] = bones_global_pose[bone] * mesh->GetSkeleton().joints[bone].invBindPose; //boneList->bones[bone] = glm::inverse(mesh->GetSkeleton().joints[bone].invBindPose); } } //============================================================= // Used to activate and bind the generated texture. // Called during the render loop of objects. // Sends the information of texture to specified shader program. //============================================================= void Renderer::passTextureData(GLuint TextureUnit, GLuint texID, GLuint shaderProg, GLchar* uniformName, int loc) { glActiveTexture(TextureUnit); glBindTexture(GL_TEXTURE_2D, texID); glUniform1i(glGetUniformLocation(shaderProg, uniformName), loc); }
9b2299c4cec243eec069fdfecde00b9eda3b12d7
7ddc1283ec3398ac556b85a2714bdfd4e4252e6b
/ctci/arras_and_strings/test.cpp
1c95aa8ac07079972841ccca016060401ce8cad1
[]
no_license
sathishkumark27/LearningNewCPPFeatures
fdbc5e4ec25d04fa49086e03a91d3fbd0b55adc5
0240520781b644a31258e7e3e59622d8eec06815
refs/heads/master
2021-03-16T21:15:00.798668
2020-03-12T23:32:03
2020-03-12T23:32:03
246,944,017
0
0
null
null
null
null
UTF-8
C++
false
false
525
cpp
test.cpp
#include<iostream> #include<vector> #include<utility> #include<unordered_map> using namespace std; int main() { vector<pair<int, int>> index; auto idx = make_pair(10, 20.2); unordered_map<int, int> umap; for (auto i=0; i<5; i++) { //cout<<"at "<< umap.at(1)<<endl; -- throus out of range error cout<<"[] "<< umap[1]<<endl; umap[i]++; } for (auto i : umap) { cout<<"at "<< umap.at(1)<<endl; cout<<i.first << " and "<<i.second<<endl; } }
76ef3f6b59c1aef8d1a8c0cc1881741cdb024889
1a78ff572bdde1537a26d1370f4aa8ff9fbc0cd5
/bronze/16jan/angry-cows.cpp
97ef54e67f07c9ead8cbdcac5d12038723e614f9
[]
no_license
ktxfish/usaco
97816fccbf677f92659338f4e2cb1ed08950ea24
5f21ccd90d7a5a907f09a4c5fe8ce55d1e6bfb50
refs/heads/master
2023-02-27T06:05:10.332272
2021-01-28T16:06:33
2021-01-28T16:06:33
325,891,186
0
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
angry-cows.cpp
#include <algorithm> #include <fstream> #define MAX_N 100 std::ifstream fin("angry.in"); std::ofstream fout("angry.out"); int N; int loc[MAX_N]; int max_x; int get_right(int n, int t) { int i = n + 1; while (i < N && loc[i] - loc[n] <= t) ++i; if (i == n + 1) return n; return get_right(i - 1, t + 1); } int get_left(int n, int t) { int i = n - 1; while (i >= 0 && loc[n] - loc[i] <= t) --i; if (i == n - 1) return n; return get_left(i + 1, t + 1); } int main() { fin >> N; for (int n = 0; n < N; ++n) fin >> loc[n]; std::sort(loc, loc + N); for (int n = 0; n < N; ++n) { int x = get_right(n, 1) - get_left(n, 1) + 1; if (x > max_x) max_x = x; } fout << max_x << '\n'; return 0; }
9dbd7abee5765978c861c39cf66ddaad3a10e968
74de01e33ac16a4972a9dffb1829337d1ba14a45
/src/Interpreter/Interpreter.h
dc2774f9fcbea66988dc7c4da5d8278bd6a368e5
[]
no_license
pierre-24/nxt-interpreter
bbf3b94cd7783bd39b92680a35acb70334d9545e
f7752c2bfa78664cd5a41e1de02a4beac1539f22
refs/heads/master
2021-05-23T08:11:49.767035
2020-05-04T19:12:51
2020-05-04T19:12:51
253,191,704
1
0
null
null
null
null
UTF-8
C++
false
false
2,127
h
Interpreter.h
// // Created by pierre on 06/04/2020. // #include <list> class RXEFile; class System; class VMMemory; class InterpreterThread; /*! * @abstract Interpreter object, implement a basic threading mechanism. * @discussion Every scheduled clump run on a different virtual thread. * When `runForTicks()` is called, every thread is executed sequentially once during an equal period of time * (except, of course, if it is waiting). */ class Interpreter { const RXEFile *file; System *system; std::list<InterpreterThread*> threads; public: /*! * @abstract Constructs an Interpreter. * @discussion Execution always starts at the first clump, based on the * order in the clump data array in the RXE file. The interpreter does not * take ownership of any of the objects passed into it, they all have to be * deleted manually after the interpreter is deleted. * @param file The RXE file to execute. * @param memory A memory object, which has to have been created with the * same RXE file. * @param system The System interface used for IO and syscalls. */ Interpreter(const RXEFile *file, System *system); /*! * @abstract Executes code for the specified number of seconds. * Return false if there is nothing more to execute. * @discussion Executes Lego bytecode until at least the time specified here * has run out. There is no more code to execute, it exits immediately and return false, * while for lengthy operations, it can return after significantly more than the * minimal time. * @param nticks The time to execute for. */ bool runForTicks(unsigned int nticks); /*! * @abstract schedule the clump * @param clump: clump to schedule */ void scheduleClump(unsigned clump); /*! * @abstract for a given clump, schedule the dependant clumps, from start to end (included) * @param clump: the clump * @param start: first dependent clump to schedule * @param end: last dependent clump to schedule */ void scheduleDependantClumps(unsigned clump, unsigned start, unsigned end); };
2fa23054acb5cd48b6d33413e26c52c951c41412
de0524250a32e3734b3d972618b663738dbdaa45
/Zadania_Programowanie/SPOJ/hangman.cpp
e3ad017e747ba41f61a484727194865ed870e604
[]
no_license
Kitee666/UMK
9702b8e83520194aae586aa48e27f5cb8e502d25
62ce69ba0e4ac323b6b702e80ef5f6c83f009c74
refs/heads/main
2023-05-28T09:40:27.913257
2021-06-07T10:32:45
2021-06-07T10:32:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,601
cpp
hangman.cpp
#include <iostream> #include <string> #include <algorithm> using namespace std; void wypisz1(int blad) { char skos = 92; string l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14; // 0 bledow l1 = "+---------------------+\n"; l2 = "| ____________ |\n"; l3 = "| |/ |\n"; l4 = "| | |\n"; l5 = "| | |\n"; l6 = "| | |\n"; l7 = "| | |\n"; l8 = "| | |\n"; l9 = "| | |\n"; l10 = "| | |\n"; l11 = "| | |\n"; l12 = "| | |\n"; l13 = "| __|__ |\n"; l14 = "+---------------------+\n"; //1 blad if (blad >= 1) { l3 = "| |/ | |\n"; l4 = "| | | |\n"; l5 = "| | | |\n"; l6 = "| | & |\n"; } // 2 blady if (blad >= 2) { l5 = "| | (_) |\n"; l6 = "| | & |\n"; } // 3 bledy if (blad >= 3) { l7 = "| | | |\n"; l8 = "| | | |\n"; l9 = "| | | |\n"; } // 4 bledy if (blad >= 4) { l7 = "| | /| |\n"; l8 = "| | / | |\n"; l9 = "| | | |\n"; } // 5 bledow if (blad >= 5) { l7 = "| | /|"; l7 += skos; l7 += " |\n"; l8 = "| | / | "; l8 += skos; l8 += " |\n"; l9 = "| | | |\n"; } // 6 bledow if (blad >= 6) { l10 = "| | / |\n"; l11 = "| | / |\n"; } // 7 bledow if (blad >= 7) { l10 = "| | / "; l10 += skos; l10 += " |\n"; l11 = "| | / "; l11 += skos; l11 += " |\n"; } cout << l1 << l2 << l3 << l4 << l5 << l6 << l7 << l8 << l9 << l10 << l11 << l12 << l13 << l14; } int main() { int i, j, k, l, a, b, c, bledy, zostalo; string slowo, sekret, proby, znaki, poprawne; char znak; bool prawda, wstaw, wypis; cin >> a; for (i = 0; i < a; i++) { bledy = 0; slowo = ""; proby = "-"; cout << "Welcome to the Hangman Game!\n"; wypisz1(bledy); cout << "Secret word:\n"; cin >> sekret; for (j = 0; j < sekret.size(); j++) sekret[j] = toupper(sekret[j]); poprawne = sekret; zostalo = sekret.size(); for (j = 0; j < zostalo; j++) { if (j > 0) cout << " "; slowo += "_"; cout << slowo[j]; } cout << endl << endl; znaki = ""; cin >> b; for (j = 0; j < b; j++) { cin >> znak; znaki += znak; } for (j = 0; j < b; j++) { znak = znaki[j]; wypis = false; cout << "Number of mistakes left: " << 7 - bledy << endl; cout << "Guesses: " << proby << endl; if (j == 0) proby = ""; cout << "Please guess a letter!\n"; cout << "Your choice: " << znak << endl; int ascii = znak; // nie litera if (ascii < 65 || (ascii > 90 && ascii < 97) || ascii > 122) { cout << "Only Latin alphabet letters!\n"; bledy++; wypis = true; } else { znak = toupper(znak); prawda = true; for (k = 0; k < proby.size(); k++) { if (proby[k] == znak) { prawda = false; break; } } // czy byla juz uzyta if (!prawda) { cout << "You've already guessed that letter!\n"; bledy++; wypis = true; } else { wstaw = false; proby += znak; for (k = 0; k < sekret.size(); k++) { if (sekret[k] == znak) { wstaw = true; slowo[k] = znak; zostalo--; } } // czy byla w slowie if (!wstaw) { cout << "Nope!\n"; bledy++; wypis = true; } else { // czy wstawiona if (wstaw && zostalo > 0) { cout << "Nice!\n"; cout << "Secret word:\n"; for (k = 0; k < slowo.size(); k++) { if (k > 0) cout << " "; cout << slowo[k]; } cout << endl; } else // czy wygrana if (wstaw && zostalo == 0) { cout << "\n"; cout << "You won!\n" << "Secret: " << poprawne; j = b; } } } } // czy jakis blad if (wypis) wypisz1(bledy); cout << "\n"; // limit bledow przegrana if (bledy == 7) { cout << "Game Over!\n" << "Secret: " << poprawne << endl; j = b; } } cout << endl; } return 0; }
1f5b1b08781ae36b4289cb26cd423ae27074c598
ff18be417439435d0db3756181a9e98c55cf25e3
/ACM-ICPC/ACM-ICPC_12/Amritapuri/online contest/ACM-ICPC Amritapuri 2012 Online Competition Accepted Solutions/B/cpp/00004014_B_STICKS_amicpc120090.cpp
2079ff6add9cafd64aac6d3ab3d7ece8bd6888dc
[]
no_license
rovinbhandari/Programming_Scripting
3952b45636f10e46c05dede29492eb0828857448
ee67f9289883d3686ed5cf41dbae13e1313bcfb0
refs/heads/master
2023-06-22T13:52:03.559222
2023-06-20T13:40:32
2023-06-20T13:47:22
4,378,004
6
1
null
2019-03-25T14:44:18
2012-05-19T12:25:13
C++
UTF-8
C++
false
false
1,139
cpp
00004014_B_STICKS_amicpc120090.cpp
// LIBRARIES #include<iostream> #include<cstdio> #include<cmath> #include<sstream> #include<algorithm> // DATA STRUCTURES #include<string> #include<list> #include<queue> #include<stack> #include<vector> #include<map> // OTHERS #define L(a) list< a > #define V(a) vector< a > #define S(a) stack< a > #define Q(a) queue< a > #define P(a,b) pair< a , b > #define M(a,b) map< a , b > #define H(a) priority_queue< a > #define Hm(a) priority_queue< a, vector<a>, greater<a> > #define FOR(i,a,b) for(int i=a;i<b;i++) #define FOR_D(i,a,b) for(int i=a-1;i>=b;i--) #define f first #define s second #define pb push_back typedef long long int lli; using namespace std; int main() { int t; scanf("%d",&t); while(t--) { long long int n,m,i,d,l,h,b; double x,max_d=0; scanf("%lld%lld",&n,&m); double a[n]; for(i=0;i<n;i++) scanf("%lf",&a[i]); for(i=0;i<m;i++) { scanf("%lld%lld%lld",&l,&b,&h); d=max(l*l+b*b,b*b+h*h); d=max(d,h*h+l*l); d=max(d,l*l+b*b+h*h); x=sqrt((double)d); if(x>max_d) max_d=x; } int count=0; for(i=0;i<n;i++) if(a[i]<=max_d) count++; printf("%d\n",count); } return 0; }
6ffcee48515c55365db0f3a4985e8913c25a38fa
a5d35f7adb05489c16579d987c3d8da1fa0e7920
/HackerEarth/CodeMonk/DynP/hanoi.cpp
877bfb32aa50a2202a247035a1d8d15e04632681
[]
no_license
rajdosi/Codes
56cfcc7d73bce0399e34ef171210a05ae34a2724
9cf9bdd58bc6239d5096f18040c7df0b4cbf50ae
refs/heads/master
2022-01-09T23:35:17.571544
2022-01-08T11:58:49
2022-01-08T11:58:49
70,044,918
0
0
null
null
null
null
UTF-8
C++
false
false
818
cpp
hanoi.cpp
# include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while (t--) { int n; cin>>n; vector<pair<long long, long long>> radiusHeightPairs; for (int i=0;i<n;i++) { long long rI,hI; cin>>rI>>hI; radiusHeightPairs.push_back(make_pair(rI,hI)); } sort(radiusHeightPairs.begin(),radiusHeightPairs.end()); vector<long long> dp(n); dp[0] = radiusHeightPairs[0].second; long long incrMax = dp[0]; for (int i=1;i<n;i++) { dp[i] = radiusHeightPairs[i].second; for (int j=0;j<i;j++) { if (radiusHeightPairs[i].first > radiusHeightPairs[j].first && radiusHeightPairs[i].second > radiusHeightPairs[j].second) { dp[i] = max(dp[i], dp[j] + radiusHeightPairs[i].second); } } incrMax = max(incrMax, dp[i]); } cout<<incrMax<<endl; } return 0; }
27bed6ddf7a1626ba72e13b6f78fe3c69014ef56
cc8c46b5b02e707420b78af16d53100ede933726
/src/cards_abstraction/bucketing_provider.h
c3dd4bb6c34084d1527c435b7434ffe7a3228e59
[]
no_license
martun/evn_open_poker
918aa10c0d257995c836a1e005ec7040d8b66b4a
2047ff655ed08c6e7df9666e7e41f91135b0ff82
refs/heads/master
2021-01-25T14:33:50.665656
2018-09-12T08:10:28
2018-09-12T08:10:28
123,712,244
2
2
null
2018-04-12T18:53:41
2018-03-03T16:55:11
C++
UTF-8
C++
false
false
1,165
h
bucketing_provider.h
#pragma once #include <stdint.h> #include <vector> #include "bucket_config.h" #include "card.h" #include "Utils.h" // Abstract class for all bucketing providers. class BucketingProvider { public: BucketingProvider(const BucketConfig& config); /** \brief Given public cards already dealt, returns the bucket number in the current round. * \param[in] hole_cards Hole cards of the player. * \param[in] public_cards Public cards on the table. */ virtual uint32_t get_bucket_number( const std::vector<Card>& hole_cards, const std::vector<Card>& public_cards) = 0; /** \brief Given all 5 public cards, returns a vector of bucket numbers for all the rounds. * \param[in] hole_cards Hole cards of the player. * \param[in] public_cards Public cards on the table. * \param[out] buckets_out A vector of 4 elements, containing bucket numbers for Preflop, Flop, Turn and River. */ virtual void get_bucket_numbers( const std::vector<Card>& hole_cards, const std::vector<Card>& public_cards, std::vector<uint32_t>& buckets_out) = 0; protected: // Bucketing algorithm configuration. BucketConfig config_; };
5ea9ca24e693360c8a9014c4712a5bef1df4d3c2
12bc46a83e8d1d1295613e26250ed2d13f2fff13
/Chapter5/Hash Table Separate Chaining/Src/Hash_Tab.cpp
80443eec9772e126902b5b2109283cda3e4f3319
[]
no_license
baidengtian/Data-Structures-and-Algorithm-Analysis-in-C-
99c79c9a519ca06d42f41e671d256d509e97eba7
da99d42639999adef171eaa54dba30f082745d95
refs/heads/master
2022-07-17T19:25:45.971537
2020-05-07T08:34:59
2020-05-07T08:34:59
261,414,809
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
239
cpp
Hash_Tab.cpp
/* * @Author: your name * @Date: 2020-02-11 16:31:25 * @LastEditTime : 2020-02-13 21:45:34 * @LastEditors : Please set LastEditors * @Description: SplayTree Àà * @FilePath: \Splay Tree\Src\SplayTree.cpp */ #include "Hash_Tab.h"
eebe2d96d99a1b3bb66f177e2987cc29fda8799b
6c05da7dc517898a0b8662a7348e799213f5cd9d
/DesignPatternCode/DesignPatternCode/factory/ConcreteProduct.h
18730376d2809315134a8b036acc0bf9c10f07cc
[]
no_license
howard-scu/DesignPatternNotes
fa1ecb50424daee3db6cf7c6997f0cfba040a0af
060d4bb0ab149ecd479130f3823a4cde7e18135a
refs/heads/master
2020-07-11T22:31:39.053535
2019-09-26T08:24:23
2019-09-26T08:24:23
204,657,743
0
0
null
null
null
null
UTF-8
C++
false
false
322
h
ConcreteProduct.h
#ifndef ConcreteProduct_h #define ConcreteProduct_h #include "Product.h" class ConcreteProduct : public Product { public: ConcreteProduct() { cout << "ConcreteProduct::ConcreteProduct()" << endl; } ~ConcreteProduct() { cout << "ConcreteProduct::~ConcreteProduct()" << endl; } }; #endif // !ConcreteProduct_h
87ce6d6d32f365c87359d66b6150666ddd7569ff
0b15c7a046d703e153b6e6054cb57a0664a2d4df
/RobWork/src/rw/common/PropertyBase.hpp
c6a0e1c477b07518fceb4f96f8c0993049088331
[ "Apache-2.0" ]
permissive
skyellen/robwork-mirror
bf5d97ce19775c2928432854a93fb87ab2f7cd26
5a74a49d9ef98eff7c75f48fe48c2e655480e9b3
refs/heads/master
2020-04-16T06:10:11.359979
2018-09-06T09:26:01
2018-09-06T09:26:01
165,335,340
4
0
null
2019-01-12T02:01:40
2019-01-12T02:01:40
null
UTF-8
C++
false
false
3,912
hpp
PropertyBase.hpp
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef RW_COMMON_PROPERTYBASE_HPP #define RW_COMMON_PROPERTYBASE_HPP /** * @file PropertyBase.hpp */ #include "PropertyType.hpp" #include "Ptr.hpp" #include "Event.hpp" #include <boost/function.hpp> #include <string> namespace rw { namespace common { /** @addtogroup common */ /*@{*/ /** * @brief Base class for Property handling */ class PropertyBase { public: //! @brief smart pointer type to this class typedef rw::common::Ptr<PropertyBase> Ptr; /** * @brief Constructor * * @param identifier [in] identifier for the property * @param description [in] description of the property */ PropertyBase(const std::string& identifier, const std::string& description); /** * @brief Constructor * * @param identifier [in] identifier for the property * @param description [in] description of the property * @param type [in] type of the property */ PropertyBase(const std::string& identifier, const std::string& description, const PropertyType& type); /** * @brief Destroys PropertyBase */ virtual ~PropertyBase(); /** * @brief Returns the Property identifier * @return string identifier */ const std::string& getIdentifier() const; /** * @brief Returns description * @return string description */ const std::string& getDescription() const; /** * @brief set description */ void setDescription(const std::string& desc){ _description = desc;} /** @brief Construct a clone of the property. */ virtual PropertyBase* clone() const = 0; /** * @brief Method signature for a callback function */ typedef boost::function<void(PropertyBase*)> PropertyListener; //! @brief Type for changed property events. typedef rw::common::Event<PropertyListener, PropertyBase*> ChangedEvent; /** * @brief get changed event * * to add listener use: * changedEvent().add(...) * */ ChangedEvent& changedEvent() { return _changedEvent; } /** * @brief Returns the PropertyType * @return the PropertyType */ const PropertyType& getType() const; private: /** * @brief Identifiers */ std::string _identifier; /** * @brief Description */ std::string _description; /** * @brief Type of property */ PropertyType _propertyType; //! changed event handler ChangedEvent _changedEvent; private: PropertyBase(const PropertyBase&); PropertyBase& operator=(const PropertyBase&); }; /** @} */ }} // end namespaces #endif // end include guard
682259a92838c6771e4ae9be228b563b14689d63
36c88dd4a7a67fa3b375ee32a033ab1108b0d37d
/oops/ASS3/1.cpp
7ddd229953fa752c638a4aef053c823374f1c982
[]
no_license
Shivamsg/CollegeCodes
a4eff73c56606f613357a76742bcff3ab03f2d2b
d62003450eec6367db446c843e66c323c7648b1e
refs/heads/master
2020-04-19T04:29:23.622860
2019-01-28T13:24:50
2019-01-28T13:24:50
167,963,973
0
0
null
null
null
null
UTF-8
C++
false
false
1,377
cpp
1.cpp
#include<iostream> using namespace std; class complex{ int real,img; public: complex() { } complex(int num) { real = num; img = num; } complex(int a,int b) { real = a; img = b; } friend complex add(complex&,complex&); friend void display(complex); }; complex add(complex& obj1,complex& obj2) { complex obj3; obj3.real=obj1.real+obj2.real; obj3.img=obj1.img+obj2.img; return obj3; } void display(complex obj) { cout<<"Result is "<<obj.real<<" + i"<<obj.img<<endl; } int main() { int p,q; complex obj,obj1,obj2; cout<<"\tAddition of two Complex Numbers"<<endl; cout<<"\nDetails of 1st Number"<<endl; cout<<"Real part:"; cin>>p; cout<<"Imaginary part:"; cin>>q; cout<<"Entered number is "<<p<<" + i"<<q<<"\n\n"; if (p==q) { complex test(p); obj1=test; } else { complex test(p,q); obj1=test; } cout<<"Details of 2nd Number"<<endl; cout<<"Real part:"; cin>>p; cout<<"Imaginary part:"; cin>>q; cout<<"Entered number is "<<p<<" + i"<<q<<"\n\n"; if (p==q) { complex test(p); obj2=test; } else { complex test(p,q); obj2=test; } obj=add(obj1,obj2); display(obj); return 0; }
748aa8ce3be803c93c64d5be7b1f5e8970242ac7
47b285b9eecd4dca6832419bb299ed2e69b9e584
/include/FreeCV/Stereo/UndistortAndRectify.h
b13e5d6105f29f99ccef186e4b1b02ca86a01457
[]
no_license
arrfou90/FreeCV
444f020133b4bf4542f481fe1158a379b10966c1
1392d8fcc0cfd14236f77f44b3cc480ec63e0396
refs/heads/master
2021-01-22T08:14:15.464860
2016-06-17T15:03:40
2016-06-17T15:13:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
734
h
UndistortAndRectify.h
/* * UndistortAndRectify.h * * Created on: 10.11.2015 * Author: andreas */ #ifndef FREECV_INCLUDE_FREECV_IMAGE_UNDISTORTANDRECTIFY_H_ #define FREECV_INCLUDE_FREECV_IMAGE_UNDISTORTANDRECTIFY_H_ #include "FreeCV/Image/Image.h" #include "FreeCV/Core/Matrix.h" namespace fcv { class UndistortAndRectify { public: UndistortAndRectify(); virtual ~UndistortAndRectify(); bool initUndistortRectifyMap(Matrix3x3f K, float k1, float k2, float k3, float p1, float p2, Matrix3x3f Knew, int width, int height); bool remap(Image* distImg1, Image* distImg2, Image* undistImg1, Image* undistImg2); private: float* mapX; float* mapY; }; } // namespace fcv #endif /* FREECV_INCLUDE_FREECV_IMAGE_UNDISTORTANDRECTIFY_H_ */
748e0a1c04ed7daf8dbe2fa96ddfbe7a2af9d7d5
88a6dcb6149300c0a3724fe454a882397711d4a3
/State/src/main.cpp
6d7014144f1b14a90cf42f289522e5faa5cc9a4c
[ "MIT" ]
permissive
rafaelfigueredog/EmbeddedDesignPatterns
3fe08278917523fffc4d63826366cde0102c2529
298a05c7907f28a9470cee6bb367c2ba34487a9c
refs/heads/main
2023-03-03T13:29:16.683915
2023-02-20T21:01:09
2023-02-20T21:01:09
317,401,440
1
0
null
2020-12-03T03:45:10
2020-12-01T02:23:14
C++
UTF-8
C++
false
false
1,460
cpp
main.cpp
#include <iostream> #include <typeinfo> class Context; class State { protected: Context *context; public: virtual ~State() { } void setContext(Context *context) { this->context = context; } virtual void Handle1() = 0; virtual void Handle2() = 0; }; class Context { private: State *state; public: Context(State *state) : state(nullptr) { this->handleTo(state); } ~Context() { delete state; } void handleTo(State *state) { std::string str = (std::string) typeid(*state).name(); std::cout << "Mudando para estado: " << str.substr(1,str.length()) << ".\n"; if (this->state != nullptr) delete this->state; this->state = state; this->state->setContext(this); } void button1() { this->state->Handle1(); } void button2() { this->state->Handle2(); } }; class StateA : public State { public: void Handle1() override { std::cout << "Led Azul Ligado\n"; } void Handle2() override; }; class StateB : public State { public: void Handle1() override { std::cout << "Led Verde Ligado\n"; } void Handle2() override { this->context->handleTo(new StateA); } }; void StateA::Handle2() { this->context->handleTo(new StateB); } void Cliente() { Context *context = new Context(new StateA); context->button1(); context->button2(); context->button1(); context->button2(); delete context; } int main() { Cliente(); return 0; }
781f345b7565a871747bd4b3deeac778b110958c
94def6788b9b77ac8728e18ad2bed5cb116c2345
/QuienEsQuien_resuelta/src/main.cpp
56ae3a307481432ec7d73793031e8581e28a4264
[]
no_license
layoel/QuienEsQuien
9c22fe66201531ddb7b1905c8324604604249f22
ed5acf1c7c0d11b1b1ca9f6299ac3954c3922517
refs/heads/master
2020-03-08T00:02:56.203345
2018-04-02T18:51:07
2018-04-02T18:51:07
127,796,709
0
0
null
null
null
null
UTF-8
C++
false
false
5,399
cpp
main.cpp
#include <fstream> #include <iostream> #include <string> #include <math.h> #include "../include/quienesquien.h" using namespace std; int main(int argc, char * argv[]){ bool jugar = false; bool limpiar = false; QuienEsQuien quienEsQuien; if(argc == 2){ string parametroAleatorio = "aleatorio"; if(argv[1]== parametroAleatorio){ cout << "Creando un QuienEsQuien aleatorio"<< endl; int numero_de_personajes; int numero_de_atributos; do{ cout << "¿Número de personajes? "; cin >>numero_de_personajes; }while(numero_de_personajes<=0); quienEsQuien.tablero_aleatorio(numero_de_personajes); quienEsQuien.mostrar_estructuras_leidas(); string nombreFicheroSalida = string("datos/tablero") + "-num-per="+to_string(numero_de_personajes)+".csv"; cout << "Guardando tablero aleatorio en "<<nombreFicheroSalida<<endl; ofstream archivoDeSalida(nombreFicheroSalida); archivoDeSalida << quienEsQuien; cout << "Guardado"<<endl; return 0; }else{ cout << "Cargando fichero para jugar'"<< argv[1] <<"'"<< endl; ifstream f (argv[1]); if (!f){ cout<<"No puedo abrir el fichero "<<argv[1]<<endl; return 1; } f>> quienEsQuien; jugar = true; } } else if(argc == 3 ){ string parametroLimpiar = "limpiar"; if(parametroLimpiar== argv[2]){ cout << "Cargando fichero para limpiar (sin jugar) '"<< argv[1] <<"'"<< endl; ifstream f (argv[1]); if (!f){ cout<<"No puedo abrir el fichero "<<argv[1]<<endl; return 1; } f>> quienEsQuien; jugar = false; } else{ cout << "Modo '"<<argv[2]<<"' no reconocido"<<endl; return 1; } } else { cout << "No se reconocen los argumentos. Ejemplos de uso:" << endl; cout << "\tJugar: ./bin/quienesquien RUTA_FICHERO"<< endl; cout << "\tLimpiar sin jugar: ./bin/quienesquien RUTA_FICHERO limpiar"<< endl; cout << "\tGenerar aleatorio: ./bin/quienesquien aleatorio"<< endl; return 1; } quienEsQuien.mostrar_estructuras_leidas(); bool mejor; string mi_respuesta; do{ cout << "¿Como quieres construir el arbol? (basica o mejora): "; cin >> mi_respuesta; cout << endl; }while(mi_respuesta != "mejora" && mi_respuesta != "basica"); if(mi_respuesta == "mejora") quienEsQuien.usar_arbol(quienEsQuien.crear_arbol(1)); if(mi_respuesta == "basica") quienEsQuien.usar_arbol(quienEsQuien.crear_arbol(0)); cout << "=========== Arbol en crudo ===========" << endl; quienEsQuien.escribir_arbol_completo(); cout << "Profundidad promedio de las hojas del arbol: "; cout << quienEsQuien.profundidad_promedio_hojas() << endl; cout << "======================================" << endl << endl << endl; bool car; string resp , nombre; vector<bool> caracteristicas(quienEsQuien.num_atributos()); quienEsQuien.eliminar_nodos_redundantes(); cout << "=========== Arbol ===================="<<endl; quienEsQuien.escribir_arbol_completo(); cout << "Profundidad promedio de las hojas del arbol: "; cout << quienEsQuien.profundidad_promedio_hojas()<<endl; cout << "======================================" << endl << endl << endl; string reiniciar; do{ if(mi_respuesta == "basica"){ //CREAR NUEVO PERSONAJE cout << "¿Quieres añadir nuevos personajes al juego? (si no)"<<endl; cin >> resp; while( !(resp == "no" || resp == "No" || resp == "NO"|| resp == "nO" )){ if(resp == "si" || resp == "Si" || resp == "SI"|| resp == "sI" ){ cout<< "¿Cómo se llama?"<<endl; cin >> nombre; cout << "Introduce los atributos (como 0 o 1)"<<endl; for(int i=0; i<quienEsQuien.num_atributos(); i++) { cin>>car; caracteristicas[i]=car; } quienEsQuien.aniade_personaje(nombre, caracteristicas); } cout << "¿Quieres añadir nuevos personajes? (si no)"<<endl; cin >> resp; } cout << "=========== Arbol + Personajes nuevos ===================="<<endl; quienEsQuien.escribir_arbol_completo(); cout << "Profundidad promedio de las hojas del arbol: "; cout << quienEsQuien.profundidad_promedio_hojas()<<endl; cout << "======================================" << endl << endl << endl; } //ELIMINAR PERSONAJE EXISTENTE cout << "¿Quieres eliminar un personaje del juego? (si no)"<<endl; cin >> resp; while( !(resp == "no" || resp == "No" || resp == "NO"|| resp == "nO" )){ if(resp == "si" || resp == "Si" || resp == "SI"|| resp == "sI" ){ cout<< "¿Cómo se llama?"<<endl; cin >> nombre; quienEsQuien.elimina_personaje(nombre); } cout << "¿Quieres eliminar otro personaje? (si no)"<<endl; cin >> resp; } //INICIAR JUEGO if(jugar) quienEsQuien.iniciar_juego(); cout << "¿Quieres volver a jugar? (responde no, para salir)" << endl; cin >> reiniciar; //REINICIAR JUEGO if(!(reiniciar == "no" || reiniciar == "No" || reiniciar == "NO"|| reiniciar == "nO" )){ do{ cout << "¿Como quieres construir el arbol? (basica o mejora): "; cin >> mi_respuesta; cout << endl; }while(mi_respuesta != "mejora" && mi_respuesta != "basica"); if(mi_respuesta == "mejora") quienEsQuien.usar_arbol(quienEsQuien.crear_arbol(1)); if(mi_respuesta == "basica") quienEsQuien.usar_arbol(quienEsQuien.crear_arbol(0)); } }while(!(reiniciar == "no" || reiniciar == "No" || reiniciar == "NO"|| reiniciar == "nO" )); return 0; }
b6188d7a70e84ab73b49b9dd7f042381791b77a2
b18ea10bd7dd81a705b0b9a19b15da73393e5ed4
/DBModuleSolution/DBSchemaMaintainer/DBSchemaTableView.cpp
8b2e5efa92c2d8ad64d191edf13af349764061c7
[]
no_license
yedaoq/YedaoqCodeSpace
90f56c37fbb0ba2e5b1d0854714acc531e3d9f42
523eb2eab61c958abba5dd5eeeb5944dee43b9a9
refs/heads/master
2021-01-02T09:52:25.642868
2018-07-03T12:36:44
2018-07-03T12:36:44
2,127,456
1
1
null
null
null
null
GB18030
C++
false
false
12,558
cpp
DBSchemaTableView.cpp
// DBSchemaTableView.cpp : CDBSchemaTableView 类的实现 // #include "stdafx.h" #include "DBSchemaMaintainer.h" #include "DBSchemaMaintainerDoc.h" #include "DBSchemaTableView.h" #include "DBSchemaInfoRecord.h" #include "Helper.h" #ifdef _DEBUG #define new DEBUG_NEW #endif using namespace NSYedaoqLayout; // CDBSchemaTableView IMPLEMENT_DYNCREATE(CDBSchemaTableView, CView) BEGIN_MESSAGE_MAP(CDBSchemaTableView, CView) // 标准打印命令 ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CDBSchemaTableView::OnFilePrintPreview) ON_COMMAND(EIDC_BTNMERGE, &CDBSchemaTableView::OnBtnMergeClicked) ON_NOTIFY(GVN_SELCHANGED, EIDC_GRIDTBL, &CDBSchemaTableView::OnGridTblSelChanged) ON_NOTIFY(GVN_SELCHANGED, EIDC_GRIDCOL, &CDBSchemaTableView::OnGridColSelChanged) ON_NOTIFY(GVN_ENDLABELEDIT, EIDC_GRIDCOL, &CDBSchemaTableView::OnGridColTxtChanged) ON_WM_CREATE() ON_WM_SIZE() END_MESSAGE_MAP() // CDBSchemaTableView 构造/析构 CDBSchemaTableView::CDBSchemaTableView() : Layouter(EnumLayoutDirection::Vertical), GridColViewer(&GridCol, 1), GridTabViewer(&GridTab, 1), CurrentTableIndex(-1) { // TODO: 在此处添加构造代码 Grid_Select = CDBColumnViewInfo( TEXT(""), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleBool::GetInstance(), 20, false); GridTab_Name = CDBColumnViewInfo( TEXT("名称"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleNone::GetInstance(), 140, true); GridTab_DBName = CDBColumnViewInfo( TEXT("数据库名"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleNone::GetInstance(), 140, true); GridTab_BuildIn = CDBColumnViewInfo( TEXT("内置"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleBool::GetInstance(), 35, true); GridTab_DBExist = CDBColumnViewInfo( TEXT("存在"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleBool::GetInstance(), 35, true); GridTab_State = CDBColumnViewInfo( TEXT(""), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleNone::GetInstance(), 20, true); GridTblColumns.AppendVirtual(&Grid_Select); GridTblColumns.Append(&GridTab_State); GridTblColumns.Append(&GridTab_Name); GridTblColumns.Append(&GridTab_DBName); GridTblColumns.Append(&GridTab_BuildIn); GridTblColumns.Append(&GridTab_DBExist); GridCol_State = CDBColumnViewInfo( TEXT(""), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleNone::GetInstance(), 20, true); GridCol_Name = CDBColumnViewInfo( TEXT("名称"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleNone::GetInstance(), 120, true); GridCol_DBName = CDBColumnViewInfo( TEXT("数据库名"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleNone::GetInstance(), 120, true); GridCol_Buildin = CDBColumnViewInfo( TEXT("内置"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleBool::GetInstance(), 35, true); GridCol_DBExist = CDBColumnViewInfo( TEXT("存在"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleBool::GetInstance(), 35, true); GridCol_CppType = CDBColumnViewInfo( TEXT("类型"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleNone::GetInstance(), 80, false); GridCol_DBType = CDBColumnViewInfo( TEXT("数据库类型"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleNone::GetInstance(), 80, true); GridCol_KeyCol = CDBColumnViewInfo( TEXT("关键列"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleBool::GetInstance(), 40, false); GridCol_DBPK = CDBColumnViewInfo( TEXT("主键"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleBool::GetInstance(), 40, true); GridCol_DBNull = CDBColumnViewInfo( TEXT("可空"), &CTextFormatSwitcherNone::GetInstance(), &CEditStyleBool::GetInstance(), 40, true); GridCol_RelyTbl = CDBColumnViewInfo( TEXT("外表"), &GridCol_RelyTblFormat, &GridCol_RelyTblStyle, 140, false); GridCol_RelyCol = CDBColumnViewInfo( TEXT("外键"), &GridCol_RelyColFormat, &GridCol_RelyColStyle, 120, false); GridCol_VisiCol = CDBColumnViewInfo( TEXT("视图列"), &GridCol_RelyColFormat, &GridCol_RelyColStyle, 120, false); GridColColumns.AppendVirtual(&Grid_Select); GridColColumns.Append(&GridCol_State); GridColColumns.Append(&GridCol_Name); GridColColumns.Append(&GridCol_DBName); GridColColumns.Append(&GridCol_Buildin); GridColColumns.Append(&GridCol_DBExist); GridColColumns.Append(&GridCol_CppType); GridColColumns.Append(&GridCol_DBType); GridColColumns.Append(&GridCol_KeyCol); GridColColumns.Append(&GridCol_DBPK); GridColColumns.Append(&GridCol_DBNull); GridColColumns.Append(&GridCol_RelyTbl); GridColColumns.Append(&GridCol_RelyCol); GridColColumns.Append(&GridCol_VisiCol); } CDBSchemaTableView::~CDBSchemaTableView() { } BOOL CDBSchemaTableView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: 在此处通过修改 // CREATESTRUCT cs 来修改窗口类或样式 //cs.style ^= WS_BORDER; return CView::PreCreateWindow(cs); } int CDBSchemaTableView::OnCreate(LPCREATESTRUCT lpcs) { if (CView::OnCreate(lpcs) == -1) return -1; RECT rect = {0, 0, lpcs->cx, lpcs->cy}; GridCol.Create(rect, this, EIDC_GRIDCOL, WS_CHILD | WS_TABSTOP | WS_VISIBLE); GridTab.Create(rect, this, EIDC_GRIDTBL, WS_CHILD | WS_TABSTOP | WS_VISIBLE); CreateButton(BtnMerge, EIDC_BTNMERGE, this, TEXT("合并")); //RECT rect1 = { 0, 0, 150, 28 }; //CmbTab.Create(CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP, rect1, this, 3); //CmbTab.ShowWindow(SW_SHOW); CFlowLayout* pFlow = Layouter.AddFlow(EnumLayoutDirection::Horizon); pFlow->AddCtrl(BtnMerge.GetSafeHwnd()); pFlow = Layouter.AddFlow( EnumLayoutDirection::Horizon, ResizeInfo::FillInfo); pFlow->AddCtrl( GridTab.GetSafeHwnd(), ResizeInfo(EnumResizeMode::Fixed, 400), ResizeInfo::FillInfo); pFlow->AddCtrl( GridCol.GetSafeHwnd(), ResizeInfo::FillInfo, ResizeInfo::FillInfo); GridTab.SetColumnCount(6); GridTabViewer.Initialize(GridTblColumns); GridCol.SetColumnCount(14); GridColViewer.Initialize(GridColColumns); return S_OK; } // CDBSchemaTableView 绘制 void CDBSchemaTableView::OnDraw(CDC* /*pDC*/) { CDBSchemaMaintainerDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: 在此处为本机数据添加绘制代码 } // CDBSchemaTableView 打印 void CDBSchemaTableView::OnFilePrintPreview() { AFXPrintPreview(this); } BOOL CDBSchemaTableView::OnPreparePrinting(CPrintInfo* pInfo) { // 默认准备 return DoPreparePrinting(pInfo); } void CDBSchemaTableView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: 添加额外的打印前进行的初始化过程 } void CDBSchemaTableView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: 添加打印后进行的清理过程 } void CDBSchemaTableView::OnRButtonUp(UINT nFlags, CPoint point) { ClientToScreen(&point); OnContextMenu(this, point); } void CDBSchemaTableView::OnContextMenu(CWnd* pWnd, CPoint point) { theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE); } afx_msg void CDBSchemaTableView::OnSize(UINT nType, int cx, int cy) { Layouter.Layout(LayoutPoint(0, 0), LayoutSize(cx, cy)); } // CDBSchemaTableView 诊断 #ifdef _DEBUG void CDBSchemaTableView::AssertValid() const { CView::AssertValid(); } void CDBSchemaTableView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CDBSchemaMaintainerDoc* CDBSchemaTableView::GetDocument() const // 非调试版本是内联的 { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CDBSchemaMaintainerDoc))); return (CDBSchemaMaintainerDoc*)m_pDocument; } #endif //_DEBUG void CDBSchemaTableView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { CDBModule& module = GetDocument()->GetDBModule(); DBTblNameEnumerator = std::auto_ptr<IEnumerator<tstring>>(module.Tables().EnumName()); GridCol_RelyTblStyle.Options = DBTblNameEnumerator.get(); GridCol_RelyTblFormat = CTextConverter4DBTblNameIdx(&module.Tables()); GridCol_RelyColFormat.SetModule(&GetDocument()->GetDBModule()); CurrentTableIndex = -1; GridTabViewer.Clear(); GridColViewer.Clear(); CDBTableInfoEnumerator pEnumTbl(&module); GridTabViewer.Fill(pEnumTbl); } // CDBSchemaTableView 消息处理程序 void CDBSchemaTableView::OnGridColSelChanged(NMHDR *pNotifyStruct, LRESULT* pResult) { CCellRange range = GridCol.GetSelectedCellRange(); //TTRACE(TEXT("Row Select - %d\r\n"), range.GetMinRow()); if(!range.IsValid() || range.GetMinRow() < GRIDHEADERROWCOUNT) { return; } CDBModule& module = GetDocument()->GetDBModule(); CDBRecordAuto rec; GridColViewer.GetCurRecord(&rec); tstring strRelayTblID = rec.GetField(CDBColumnInfoRecord::RelyTbl); int relyTblID = -1; if(!strRelayTblID.empty()) { relyTblID = boost::lexical_cast<int>(rec.GetField(CDBColumnInfoRecord::RelyTbl)); } TTRACE(TEXT("依赖表 : %d\r\n"), relyTblID); if( relyTblID >= 0) { GridCol_RelyColStyle.SetTable(&GetDocument()->GetDBModule().Tables()[relyTblID]->GetSchema()); } } void CDBSchemaTableView::OnGridTblSelChanged(NMHDR *pNotifyStruct, LRESULT* pResult) { CCellRange range = GridTab.GetSelectedCellRange(); if(range.IsValid() && range.GetMinRow() >= GRIDHEADERROWCOUNT) { ShowColumnsOfTable(range.GetMinRow() - GRIDHEADERROWCOUNT); } } void CDBSchemaTableView::OnGridColTxtChanged(NMHDR *pNotifyStruct, LRESULT* pResult) { NM_GRIDVIEW* pItem = (NM_GRIDVIEW*) pNotifyStruct; if(pItem->iRow < GRIDHEADERROWCOUNT || pItem->iRow >= GridCol.GetRowCount()) { return; } CDBTableCollection& tables = GetDocument()->GetDBModule().Tables(); if(CurrentTableIndex < 0 || CurrentTableIndex >= tables.Count()) { _ASSERT(FALSE); return; } CDBColumnInfoRecord col(&tables[CurrentTableIndex]->GetSchema()[pItem->iRow - GRIDHEADERROWCOUNT]); CDBRecordAuto rec; GridColViewer.GetRecordAt(pItem->iRow - GRIDHEADERROWCOUNT, &rec); int fieldIdx = GridColColumns.GetColumnByViewCol(pItem->iColumn)->IdxRecord; col.SetField(fieldIdx, rec.GetField(fieldIdx)); TTRACE(TEXT("Column %s : field %d changed to %s\r\n"), col.GetField(CDBColumnInfoRecord::Name).c_str(), fieldIdx, col.GetField(fieldIdx)); //TRACE("Grid Edited...\r\n"); } void CDBSchemaTableView::OnBtnMergeClicked() { int iSelectedRowCount = 0; int iSelectedRows[2]; for(int i = GRIDHEADERROWCOUNT; i < GridTab.GetRowCount(); ++i) { CGridCellBase* pCell = GridTab.GetCell(i, 0); if(CEditStyleBool::GetInstance().strTrue == pCell->GetText()) { iSelectedRows[iSelectedRowCount++] = i - GRIDHEADERROWCOUNT; if(iSelectedRowCount >= 2) break; } } if(iSelectedRowCount == 2) { GetDocument()->MergeTable(iSelectedRows[0], iSelectedRows[1]); } iSelectedRowCount = 0; for(int i = GRIDHEADERROWCOUNT; i < GridCol.GetRowCount(); ++i) { CGridCellBase* pCell = GridCol.GetCell(i, 0); TTRACE(pCell->GetText()); if(CEditStyleBool::GetInstance().strTrue == pCell->GetText()) { iSelectedRows[iSelectedRowCount++] = i - GRIDHEADERROWCOUNT; if(iSelectedRowCount >= 2) break; } } if(iSelectedRowCount == 2) { GetDocument()->MergeColumn(GridTabViewer.GetCurRecord(0), iSelectedRows[0], iSelectedRows[1]); } } int CDBSchemaTableView::ShowColumnsOfTable(int idxTbl) { CDBTableCollection& tables = GetDocument()->GetDBModule().Tables(); _ASSERT(idxTbl >= 0 && idxTbl < tables.Count()); CurrentTableIndex = idxTbl; GridCol_RelyColFormat.SetTable(idxTbl); GridColViewer.Clear(); GridColViewer.Fill(CDBColumnInfoEnumerator(&tables[idxTbl]->GetSchema())); return 1; } void CDBSchemaTableView::CreateButton(CButton& btn, UINT id, CWnd* pParent, LPCTSTR lpTitle, UINT width, UINT height, DWORD dwStyle, CFont* pFont) { static CFont* pDefaultFont = 0; if(!pDefaultFont) { pDefaultFont = new CFont; pDefaultFont->CreateFont(16, // nHeight 0, // nWidth 0, // nEscapement 0, // nOrientation 0, // nWeight FALSE, // bItalic FALSE, // bUnderline 0, // cStrikeOut ANSI_CHARSET, // nCharSet OUT_DEFAULT_PRECIS, // nOutPrecision CLIP_DEFAULT_PRECIS, // nClipPrecision DEFAULT_QUALITY, // nQuality DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily _T( "Arial ")); // lpszFac } RECT rect = {0, 0, width, height}; btn.Create(lpTitle, dwStyle, rect, pParent, id); if(!pFont) pFont = pDefaultFont; btn.SetFont(pFont); btn.ShowWindow(SW_SHOW); }
190fc182b7ad0598ef6af6ba9856871af076e60f
f0610b8452d1addcb026144516550829a558616f
/UVA/10860 - Many a Little makes a Mickle.cpp
81238e0d50686085a84acf026a5deb399c933102
[]
no_license
ahmedelsaie/AlgorithmsProblems
dd8578e04590e71c13f7aa0cb02f77bea4599beb
acdfc86ef642c5249a15f59bcea10a31d7c58d0d
refs/heads/master
2021-09-17T11:23:48.711877
2018-06-26T01:07:16
2018-06-26T01:07:16
115,373,592
0
0
null
null
null
null
UTF-8
C++
false
false
2,061
cpp
10860 - Many a Little makes a Mickle.cpp
#include <stdio.h> #include <cstring> char arr[10005]; struct word { char str[105]; int l; }; word subwords[55]; int dp[10005]; int dp2[10005][55]; int length, num_subwords; const int inf = 99999999; int fn(int left); int fit(int x, int sub); int min(int x, int y); void reset(); int main() { int cases, p = 1, ans; scanf("%d", &cases); while(cases--) { scanf("%s", arr); scanf("%d", &num_subwords); length = strlen(arr); for(int i = 0; i < num_subwords; i++) { scanf("%s", subwords[i].str); subwords[i].l = strlen(subwords[i].str); } reset(); ans = fn(0); printf("Set %d: ", p); if(ans == inf) printf("Not possible."); else printf("%d.", ans); //if(cases) printf("\n"); p++; } return 0; } int fn(int left) { if(left > length) return inf; if(left == length) return 0; int &ret = dp[left]; if(ret != -1) return ret; ret = inf; for(int i = 0; i < num_subwords; i++) { int help = fit(left, i); if(help != -1) ret = min(ret, fn(help) + 1); } return ret; } int fit(int x, int sub) { if(subwords[sub].l > length - x) return -1; int &ret = dp2[x][sub]; if(ret != -2) return ret; int i = x; for(int j = 0; j < subwords[sub].l; j++) { if(arr[i] != subwords[sub].str[j]) { ret = -1; break; } i++; } if(ret != -1) return ret = i; i = x; for(int j = subwords[sub].l - 1; j >= 0; j--) { if(arr[i] != subwords[sub].str[j]) return ret = -1; i++; } return ret = i; } int min(int x, int y) { if(x < y) return x; else return y; } void reset() { for(int i = 0; i < length + 2; i++) { dp[i] = -1; for(int j = 0; j < num_subwords + 2; j++) dp2[i][j] = -2; } }
04fa7a8731340c7dc96d6dba50070b1801eb2734
f585f8a210ba9020331173d8109bc2a28c9ed4ef
/homeworks/hw08/solutions/task04.cpp
9bb3f33942ee33bc6f1772a18b4364417a8c9a02
[]
no_license
geosabev/FMI-DSA-2020-2021
76de63f476b0d50c3b0612dfb9e7c854f83ca350
97824c6237a68fb8032207cb0568932c0a1ded59
refs/heads/main
2023-06-14T02:22:20.451257
2021-07-12T09:18:25
2021-07-12T09:18:25
317,488,917
0
0
null
null
null
null
UTF-8
C++
false
false
3,287
cpp
task04.cpp
#include <iostream> #include <iomanip> #include <algorithm> #include <cmath> #include <climits> #include <vector> using namespace std; long long n, k, q; vector<vector<long long>> points; long long distance(const vector<long long>& point1, const vector<long long>& point2) { long long result = 0; for (long long i = 0; i < k; i++) result += (point1[i] - point2[i]) * (point1[i] - point2[i]); return result; } struct point_comparator { long long dimension; point_comparator(long long dimension = 0) : dimension(dimension) {} bool operator()(const vector<long long>& point1, const vector<long long>& point2) { return (point1[dimension] < point2[dimension]); } }; struct Node { vector<long long> point; long long axis; Node* left; Node* right; Node(const vector<long long>& point) { this->point = point; this->axis = 0; this->left = nullptr; this->right = nullptr; } }; class KD_Tree { public: KD_Tree(vector<vector<long long>> p, long long d) { this->k = d; this->root = build(p, 0, p.size() - 1, 0); } double closest_point(const vector<long long>& p) { return (sqrt(this->nearest_neighbour(this->root, p))); } private: long long k; Node* root; Node* build(vector<vector<long long>>& points, long long from, long long to, long long axis) { if (from > to) return nullptr; long long mid = (from + to) / 2; nth_element(points.begin() + from, points.begin() + mid, points.begin() + to + 1, point_comparator(axis)); Node* node = new Node(points[mid]); node->axis = axis; node->left = build(points, from, mid - 1, (axis + 1) % k); node->right = build(points, mid + 1, to, (axis + 1) % k); return node; } long long nearest_neighbour(Node* node, const vector<long long>& p) { if (node == nullptr) return LLONG_MAX; long long result = distance(node->point, p); if (node->point[node->axis] <= p[node->axis]) { result = min(result, nearest_neighbour(node->right, p)); if (node->left && p[node->axis] - sqrt(result) <= node->point[node->axis]) result = min(result, nearest_neighbour(node->left, p)); } else { result = min(result, nearest_neighbour(node->left, p)); if (node->right && p[node->axis] + sqrt(result) >= node->point[node->axis]) result = min(result, nearest_neighbour(node->right, p)); } return result; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> n >> k; points.resize(n); for (long long i = 0; i < n; i++) { vector<long long> point(k); for (long long j = 0; j < k; j++) cin >> point[j]; points[i] = point; } KD_Tree tree(points, k); cin >> q; cout << fixed << setprecision(3); for (long long i = 0; i < q; i++) { vector<long long> point(k); for (long long j = 0; j < k; j++) cin >> point[j]; cout << tree.closest_point(point) << '\n'; } }
c500cc9b3d89cd87fd58209a8b5976d47fee14d0
a2f6660488fed555d720cc0df72ae2cfd526d0ec
/src/mpepc/evaluation/path_summary.cpp
5d09238836e76f8063322c3f850ad924c5eaf885
[ "MIT" ]
permissive
h2ssh/Vulcan
91a517fb89dbed8ec8c126ee8165dc2b2142896f
cc46ec79fea43227d578bee39cb4129ad9bb1603
refs/heads/master
2022-05-03T02:31:24.433878
2019-05-04T17:12:12
2019-05-04T17:12:12
184,834,960
6
11
NOASSERTION
2022-04-29T02:03:07
2019-05-04T00:21:10
C++
UTF-8
C++
false
false
1,952
cpp
path_summary.cpp
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * @file * @author Collin Johnson * * Definition of PathSummary. */ #include <mpepc/evaluation/path_summary.h> #include <mpepc/evaluation/mpepc_log.h> #include <mpepc/evaluation/utils.h> #include <boost/range/iterator_range.hpp> namespace vulcan { namespace mpepc { utils::PoseTrace extract_trace_from_log(MPEPCLog& log); PathSummary::PathSummary(const std::string& filename) { auto resultsLogs = load_results_logs(filename); for(auto& results : resultsLogs) { MPEPCLog log(results.logName); auto trace = extract_trace_from_log(log); switch(results.version) { case MPEPCVersion::regular: regularPoses_.emplace_back(std::move(trace)); break; case MPEPCVersion::social: socialPoses_.emplace_back(std::move(trace)); break; case MPEPCVersion::unknown: default: std::cerr << "ERROR: Unknown log version type for " << results.logName << '\n'; break; } } std::cout << "INFO: PathSummary: Loaded traces: \n" << version_to_name(MPEPCVersion::regular) << " : " << regularPoses_.size() << version_to_name(MPEPCVersion::social) << " : " << socialPoses_.size() << '\n'; } utils::PoseTrace extract_trace_from_log(MPEPCLog& log) { utils::PoseTrace trace(0.025f, 10000000); log.loadAll(); for(auto& motion : boost::make_iterator_range(log.beginMotionState(), log.endMotionState())) { trace.addPose(motion.pose); } return trace; } } // namespace mpepc } // namespace vulcan
593e48f3ab3096732e16f59364fbbcf020bde305
59d05137eaa1c0db25c6e8aebd3f978b5a8fef56
/database/clickhouse_redundancy_t.hpp
c479a5aafc873f1029b6d1b1ba3669dec2e1c86b
[ "MIT" ]
permissive
dioptra-io/diamond-miner-cpp
9e6925a1379e1591210270e0eb1ad6aadddb9a02
8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5
refs/heads/master
2021-01-08T23:24:56.381179
2020-11-19T09:47:44
2020-11-19T09:47:44
242,174,772
0
1
MIT
2020-07-26T11:20:14
2020-02-21T15:48:44
C++
UTF-8
C++
false
false
343
hpp
clickhouse_redundancy_t.hpp
// // Created by System Administrator on 2019-07-23. // #ifndef HEARTBEAT_CLICKHOUSE_REDUNDANCY_T_HPP #define HEARTBEAT_CLICKHOUSE_REDUNDANCY_T_HPP #include <clickhouse_t.hpp> class clickhouse_redundancy_t : public clickhouse_t{ clickhouse_redundancy_t(const std::string& host); }; #endif //HEARTBEAT_CLICKHOUSE_REDUNDANCY_T_HPP
44639b0c961a467ddb14694b6c2aa6b1d753a8bb
e9cb1818bde5c0c544df0366d51420863b0a5c54
/day03/ex01/ScavTrap.hpp
0a23acb5b49b13fe0c7529605254676bc3b7898f
[]
no_license
vdoroshyn/42-cpp-piscine
2ba1ac72a74a2b8e1980b041d4411bd95139f160
3f795bd2bf6666007606aff14a8b5d0925168f11
refs/heads/master
2021-05-16T15:58:57.590386
2018-01-30T12:58:12
2018-01-30T12:58:12
119,534,885
0
0
null
null
null
null
UTF-8
C++
false
false
1,089
hpp
ScavTrap.hpp
#ifndef SCAVTRAP_HPP #define SCAVTRAP_HPP #include <iostream> #include <string> #include <cstdlib> #include <ctime> class ScavTrap { public: ScavTrap(); ScavTrap(std::string name); ScavTrap(ScavTrap const& src); ~ScavTrap(); void rangedAttack(std::string const& target); void meleeAttack(std::string const& target); void takeDamage(unsigned int amount); void beRepaired(unsigned int amount); void challengeNewcomer(); std::string getName() const; int getHitPoints() const; int getMaxHitPoints() const; int getEnergyPoints() const; int getMaxEnergyPoints() const; int getLevel() const; int getMeleeAttackDamage() const; int getRangedAttackDamage() const; int getArmorDamageReduction() const; ScavTrap& operator=(ScavTrap const& rhs); protected: private: std::string _name; unsigned int _hitPoints; unsigned int _maxHitPoints; unsigned int _energyPoints; unsigned int _maxEnergyPoints; unsigned int _level; unsigned int _meleeAttackDamage; unsigned int _rangedAttackDamage; unsigned int _armorDamageReduction; }; #endif
8179a39570ad3062db2c81fb282236ff369a6439
3e1c801efa0ccec9e018e35ed2720d9ff0b4f81f
/src/gameplay/bgeffects/top_cubetunnel.h
bb5b61ab5fdef72d830f2135035b7bbe46a0853b
[ "MIT" ]
permissive
kayateia/feetoffury
4f3304b8371ab4aefdde28b5a6fb926b1c0342c6
b3613c11dfdc8b287bd55f3b10dea70306de6261
refs/heads/master
2020-03-31T04:26:02.393040
2018-10-07T04:07:26
2018-10-07T04:07:26
151,904,873
9
1
null
null
null
null
UTF-8
C++
false
false
524
h
top_cubetunnel.h
/* Feet of Fury gameplay/bgeffects/top_cubetunnel.h Copyright (C)2002 Cryptic Allusion, LLC */ #ifndef __TOP_CUBETUNNEL_H #define __TOP_CUBETUNNEL_H #include "cubetunnel.h" // A bubble field (like char select) class TopCubeTunnel : public TopDrawable { public: TopCubeTunnel(Texture * txr, bool out) { CubeTunnel * ct = new CubeTunnel(txr, out); subAdd(ct); } virtual ~TopCubeTunnel() { } virtual void draw(ObjType list) { Drawable::draw(list); } }; #endif /* __TOP_CUBETUNNEL_H */
a6b4317f51c664723bf4627a50680c860f33e441
a8fdd77a0b6af032033f1d0466410e9b27612d33
/vme_drs_v5.1_tdc/daq/src/exec_daq_main.cc
c7a82ce1f68247a1b9b473f0fc546a6811ab5cf5
[]
no_license
HidemitsuAsano/daqmw_elph201710
e3093ed1845b4ec6665d97697e7916adac1ee592
ae3df8d44660ef5f6b1d587e7858cef4c42f0cf3
refs/heads/master
2021-08-23T10:17:47.423251
2017-11-12T06:07:11
2017-11-12T06:07:11
108,068,665
0
0
null
null
null
null
UTF-8
C++
false
false
616
cc
exec_daq_main.cc
#include"control_funcs.hh" #include"daq_funcs.hh" int main(int argc, char* argv[]){ if(1 == argc){ std::cout << "Usage\n"; std::cout << "exec_daq [ip address] [run_no] [event_no]" << std::endl; return 0; } (void) signal(SIGINT, UserStop_FromCtrlC); // body ------------------------------------------------------ char* board_ip = argv[1]; int runno = atoi(argv[2]); int eventno = atoi(argv[3]); rbcp_header rbcpHeader; rbcpHeader.type = UDPRBCP::rbcp_ver_; rbcpHeader.id = 0; daq_reg(board_ip, &rbcpHeader); daq(board_ip, &rbcpHeader, runno, eventno); return 0; }
56bb2b00a6054a8136065685a865b253f36f78e9
93294d148df93b4378f59ac815476919273d425f
/src/FedSrv/CSteamAchievements.cpp
7dc4e31910c3ebc8f7f7547fe3cb9f5eb4fc9652
[ "MIT" ]
permissive
FreeAllegiance/Allegiance
f1addb3b26efb6b8518705a0b0300974820333c3
3856ebcd8c35a6d63dbf398a4bc7f0264d6c823c
refs/heads/master
2023-07-06T17:53:24.363387
2023-06-29T00:24:26
2023-06-29T00:24:26
98,829,929
86
34
MIT
2023-06-28T03:57:34
2017-07-30T23:09:14
C++
UTF-8
C++
false
false
15,557
cpp
CSteamAchievements.cpp
#include "pch.h" #include <inttypes.h> // BT - STEAM // BT - STEAM CSteamAchievements::CSteamAchievements(CSteamID &steamID) : m_steamID(steamID), m_gotRequestStatsResponse(false), m_gotSuccessfulRequestStatsResponse(false), m_gotStatsStoredResponse(false), m_gotSuccessfulStatsStoredResponse(false), m_nanAchievementEarned(false) { sprintf(m_szSteamID, "%" PRIu64, steamID.ConvertToUint64()); // Do not call InitiateStatsRequest() from here, the constructor must complete first } void CSteamAchievements::InitiateStatsRequest() { // Do not block here. We are going to assume that because the login process takes some time, this call result // should be triggered long before anyone actually tries to hit it. Because this object will be hooked onto // the player object, it will be available anywhere we want to hit stats. SteamAPICall_t hSteamApiCall = SteamGameServerStats()->RequestUserStats(m_steamID); m_UserStatsRequestedCallResult.Set(hSteamApiCall, this, &CSteamAchievements::OnUserStatsReceived); } // Always use this to ensure that stats are available before you try to set anything. Because this should have been loaded // when the user logged into the server, this call should always return immediately. bool CSteamAchievements::InitiateStatsRequestAndWaitForStatsFromSteamServer() { // We only need to initialize this once per CSteamAchievements object. SteamAPI will track the stats after that. if (m_gotRequestStatsResponse == true) return true; SteamAPICall_t hSteamApiCall = SteamGameServerStats()->RequestUserStats(m_steamID); m_UserStatsRequestedCallResult.Set(hSteamApiCall, this, &CSteamAchievements::OnUserStatsReceived); // Wait 10 seconds max for stats to come back. This operation will block the thread, so don't want to wait too long. // Setting a very fast spin here so the user isn't waiting too long. for (int i = 0; i < 10 * 500 && m_gotRequestStatsResponse == false; i++) { SteamGameServer_RunCallbacks(); Sleep(5); } return m_gotRequestStatsResponse && m_gotSuccessfulRequestStatsResponse; } bool CSteamAchievements::GetStat(EStats theStat, int * pVal) { // Must block until steam triggers the callback before you can actually use the stats. InitiateStatsRequestAndWaitForStatsFromSteamServer(); if (SteamGameServerStats()->GetUserStat(m_steamID, m_Stats[theStat], pVal) == false) { debugf("SteamGameServerStats()->GetUserStat (%s) - response not recieved from Steam Server\n", m_szSteamID); return false; } return true; } bool CSteamAchievements::SetStat(EStats theStat, int val) { // Must block until steam triggers the callback before you can actually use the stats. if (InitiateStatsRequestAndWaitForStatsFromSteamServer() == false) { debugf("InitiateStatsRequestAndWaitForStatsFromSteamServer (%s) - response not recieved from Steam Server\n", m_szSteamID); return false; } if (SteamGameServerStats()->SetUserStat(m_steamID, m_Stats[theStat], val) == false) { debugf("SteamGameServerStats()->SetUserStat (%s) - Failed to set stat.\n", m_szSteamID); return false; } return true; } bool CSteamAchievements::GetAchievement(EAchievements achievement) { bool toReturn; // Must block until steam triggers the callback before you can actually use the stats. InitiateStatsRequestAndWaitForStatsFromSteamServer(); if (SteamGameServerStats()->GetUserAchievement(m_steamID, m_Achievements[achievement], &toReturn) == false) { debugf("SteamGameServerStats()->GetUserAchievement (%s) - response not recieved from Steam Server\n", m_szSteamID); return false; } return true; } bool CSteamAchievements::SetAchievement(EAchievements achievement) { // Must block until steam triggers the callback before you can actually use the stats. InitiateStatsRequestAndWaitForStatsFromSteamServer(); if (m_gotRequestStatsResponse == false) { debugf("SteamGameServerStats()->RequestUserStats (%s) - response not received from Steam server.\n", m_szSteamID); return false; } if (m_gotSuccessfulRequestStatsResponse == false) { debugf("SteamGameServerStats()->RequestUserStats (%s) - unsuccessful response getting steam stats for user from Steam server.\n", m_szSteamID); return false; } // Now that we have the stats back from the server, we can update them. if (SteamGameServerStats()->SetUserAchievement(m_steamID, m_Achievements[achievement]) == false) { debugf("SteamGameServerStats()->SetUserAchievement (%s) - Could not set achievement for user.\n", m_szSteamID); return false; } return true; } bool CSteamAchievements::SaveStats() { SteamAPICall_t hSteamApiCall = SteamGameServerStats()->StoreUserStats(m_steamID); m_UserStatsStoredCallResult.Set(hSteamApiCall, this, &CSteamAchievements::OnUserStatsStored); return true; // No Need to block, Steam will guarantee completion after this point. //// Timeout after 10 seconds. //for (int i = 0; i < 100 && m_gotStatsStoredResponse == false; i++) //{ // SteamGameServer_RunCallbacks(); // Sleep(100); //} //if (m_gotStatsStoredResponse == false) //{ // debugf("SteamGameServerStats()->StoreUserStats - response not received from Steam server.\n"); // return false; //} //if (m_gotSuccessfulStatsStoredResponse == false) //{ // debugf("SteamGameServerStats()->StoreUserStats - unsuccessful response storing steam stats for user to steam."); // return false; //} //return true; } void CSteamAchievements::OnUserStatsReceived(GSStatsReceived_t *pCallback, bool bIOFailure) { // we may get callbacks for other user's stats arriving, ignore them if (m_steamID == pCallback->m_steamIDUser) { if (k_EResultOK == pCallback->m_eResult) { debugf("OnUserStatsReceived(): Received stats and achievements from Steam (%s) \n", m_szSteamID); m_gotSuccessfulRequestStatsResponse = true; } else { char buffer[128]; _snprintf(buffer, 128, "OnUserStatsReceived(): RequestStats (%s) - failed, %d\n", m_szSteamID, pCallback->m_eResult); debugf(buffer); } m_gotRequestStatsResponse = true; } } void CSteamAchievements::OnUserStatsStored(GSStatsStored_t *pCallback, bool bIOFailure) { // we may get callbacks for other games' stats arriving, ignore them if (m_steamID == pCallback->m_steamIDUser) { if (k_EResultOK == pCallback->m_eResult) { m_gotSuccessfulStatsStoredResponse = true; debugf("OnUserStatsStored(): Stored stats for Steam (%s) \n", m_szSteamID); } else { char buffer[128]; _snprintf(buffer, 128, "OnUserStatsStored(): StatsStored (%s) - failed, %d\n", m_szSteamID, pCallback->m_eResult); debugf(buffer); } m_gotStatsStoredResponse = true; } } // This is only for testing, and shouldn't be used normally. bool CSteamAchievements::RemoveAchievement(EAchievements achievement) { // Must block until steam triggers the callback before you can actually use the stats. InitiateStatsRequestAndWaitForStatsFromSteamServer(); if (m_gotRequestStatsResponse == false) { debugf("SteamGameServerStats()->RequestUserStats (%s) - response not received from Steam server.\n", m_szSteamID); return false; } if (m_gotSuccessfulRequestStatsResponse == false) { debugf("SteamGameServerStats()->RequestUserStats (%s) - unsuccessful response getting steam stats for user from Steam server.\n", m_szSteamID); return false; } // Now that we have the stats back from the server, we can update them. if (SteamGameServerStats()->ClearUserAchievement(m_steamID, m_Achievements[achievement]) == false) { debugf("SteamGameServerStats()->SetUserAchievement (%s) - Could not set achievement for user.\n", m_szSteamID); return false; } SteamAPICall_t hSteamApiCall = SteamGameServerStats()->StoreUserStats(m_steamID); m_UserStatsStoredCallResult.Set(hSteamApiCall, this, &CSteamAchievements::OnUserStatsStored); // Timeout after 10 seconds. for (int i = 0; i < 100 && m_gotStatsStoredResponse == false; i++) { SteamGameServer_RunCallbacks(); Sleep(100); } if (m_gotStatsStoredResponse == false) { debugf("SteamGameServerStats()->StoreUserStats (%s) - response not received from Steam server.\n", m_szSteamID); return false; } if (m_gotSuccessfulStatsStoredResponse == false) { debugf("SteamGameServerStats()->StoreUserStats (%s) - unsuccessful response storing steam stats for user to steam.\n", m_szSteamID); return false; } // If not then we can't set achievements yet return false; } void CSteamAchievements::AwardBetaParticipation() { time_t timev; time(&timev); time_t startTime = 1504567654; // 9/4/2017 time_t endTime = 1506729599; // 9/29/2017 23:59:59 UTC if (timev > startTime && timev < endTime) SetAchievement(EAchievements::BETA_ACHIEVEMENT_1_0); } void CSteamAchievements::AwardKillAchievement(PilotType pt) { switch (pt) { case c_ptBuilder: { SetAchievement(EAchievements::FIRST_CON_KILL_1_2); break; } case c_ptMiner: { SetAchievement(EAchievements::FIRST_MINER_KILL_1_1); break; } case c_ptPlayer: { SetAchievement(EAchievements::FIRST_FORCE_EJECT_1_3); break; } }; } void CSteamAchievements::AwardBaseKillOrCapture(bool kill) { if (kill) SetAchievement(EAchievements::FIRST_BASE_KILL_1_4); else //Capture SetAchievement(EAchievements::FIRST_BASE_CAP_1_5); } void CSteamAchievements::AwardIGCAchievements(AchievementMask am) { if ((am & c_achmProbeKill) > 0) SetAchievement(EAchievements::FIRST_PROBE_KILL_1_9); if ((am & c_achmProbeSpot) > 0) SetAchievement(EAchievements::PROBE_SPOT_1_10); if ((am & c_achmNewRepair) > 0 && !m_nanAchievementEarned) { SetAchievement(EAchievements::NANITE_REPAIR_1_11); m_nanAchievementEarned = true; //I was concerned about potentially calling set achievement too much } if ((am & c_achmGarrSpot) > 0) SetAchievement(EAchievements::SPOT_GARRISON_1_14); } void CSteamAchievements::AwardRecoverTechAchievement() { if (SetAchievement(EAchievements::RECOVER_TECH_1_8)) SaveStats(); } void CSteamAchievements::AwardPodPickup() { SetAchievement(EAchievements::PICKUP_POD_1_13); } void CSteamAchievements::AwardGetRescued() { SetAchievement(EAchievements::GET_RESCUED_1_12); } void CSteamAchievements::AddUserStats(PlayerScoreObject* ppso, IshipIGC * pIship) { int tempStat; bool getSucceed; int minerKills = ppso->GetMinerKills(); if (minerKills > 0) { getSucceed = GetStat(EStats::MINER_KILLS, &tempStat); if (getSucceed) //only set stat if get passes otherwise we risk resetting the stat { SetStat(EStats::MINER_KILLS, tempStat + minerKills); if ((tempStat + minerKills) >= 50) SetAchievement(EAchievements::KILL_50_MINERS_1_16); } } int conKills = ppso->GetBuilderKills(); if (conKills > 0) { getSucceed = GetStat(EStats::CON_KILLS, &tempStat); if (getSucceed) SetStat(EStats::CON_KILLS, tempStat + conKills); } int forceEjects = ppso->GetPlayerKills(); if (forceEjects > 0) { getSucceed = GetStat(EStats::FORCE_EJECT, &tempStat); if (getSucceed) { SetStat(EStats::FORCE_EJECT, tempStat + forceEjects); if ((tempStat + forceEjects) >= 100) SetAchievement(EAchievements::FORCE_100_EJECTS_1_15); } } int baseKills = ppso->GetBaseKills(); if (baseKills > 0) { getSucceed = GetStat(EStats::BASE_KILLS, &tempStat); if (getSucceed) SetStat(EStats::BASE_KILLS, tempStat + baseKills); } //int(ppso->GetBaseCaptures()), int(ppso->GetScore()), ppso->GetAssists(), ppso->); int baseCaps = ppso->GetBaseCaptures(); if (baseCaps > 0) { getSucceed = GetStat(EStats::BASE_CAPS, &tempStat); if (getSucceed) SetStat(EStats::BASE_CAPS, tempStat + baseCaps); } int score = ppso->GetScore(); if (score > 0) { getSucceed = GetStat(EStats::SUM_SCORE_2, &tempStat); if (getSucceed) { SetStat(EStats::SUM_SCORE_2, tempStat + score); CheckRank(tempStat + score); } } if (ppso->GetWinner()) { getSucceed = GetStat(EStats::PLAYER_WINS, &tempStat); if (getSucceed) { SetStat(EStats::PLAYER_WINS, tempStat + 1); int wins = tempStat + 1; if (wins >= 10) SetAchievement(EAchievements::WIN_10_GAMES_1_17); if (wins >= 50) SetAchievement(EAchievements::WIN_50_GAMES_1_18); if (wins >= 100) SetAchievement(EAchievements::WIN_100_GAMES_1_19); } } if (ppso->GetLoser()) { getSucceed = GetStat(EStats::PLAYER_LOSS, &tempStat); if (getSucceed) SetStat(EStats::PLAYER_LOSS, tempStat + 1); } int repair = floor(100 * ppso->GetRepair()); if (repair > 0.0) { getSucceed = GetStat(EStats::REPAIR_PERCENT, &tempStat); if (getSucceed) SetStat(EStats::REPAIR_PERCENT, tempStat + repair); } } int CSteamAchievements::GetCommELO() { bool getSucceed; int playerELO; getSucceed = GetStat(EStats::COMM_ELO, &playerELO); if (getSucceed) return playerELO; else return -1; } void CSteamAchievements::UpdateCommanderStats(int opponentELO, bool win) { bool getSucceed; int numGames; double K; int playerELO; double expectedScore; getSucceed = GetStat(EStats::COMM_GAMES, &numGames); getSucceed = getSucceed && GetStat(EStats::COMM_ELO, &playerELO); if (getSucceed) { playerELO = playerELO*numGames + opponentELO + 400 * (win?1:-1); numGames += 1; if (playerELO > 0) playerELO = floor(playerELO / numGames); else playerELO = 0; SetStat(EStats::COMM_GAMES, numGames); SetStat(EStats::COMM_ELO, playerELO); } } static DWORD WINAPI UpdateLeaderboardThread(LPVOID pThreadParameter) { char *pUrl = (char *)pThreadParameter; MaClient client; int result = client.getRequest(pUrl); int response = client.getResponseCode(); debugf("Leaderboard Update(%ld): %s\n", response, pUrl); SteamGameServer_ReleaseCurrentThreadMemory(); delete pUrl; return 0; } void CSteamAchievements::UpdateLeaderboard(PlayerScoreObject* ppso) { char steamID[100]; sprintf(steamID, "%" PRIu64, this->m_steamID.ConvertToUint64()); ZString url = ZString(g.szLeaderboardUpdateUrl) + ZString("?apiKey=") + ZString(g.szApiKey); url += "&steamID=" + ZString(steamID); url += "&assists=" + ZString(ppso->GetAssists()); url += "&baseCaptures=" + ZString(ppso->GetBaseCaptures()); url += "&baseKills=" + ZString(ppso->GetBaseKills()); url += "&ejects=" + ZString(ppso->GetEjections()); url += "&kills=" + ZString(ppso->GetKills()); url += "&score=" + ZString(ppso->GetScore()); url += "&playtimeMinutes=" + ZString(int(ppso->GetTimePlayed() / 60)); url += "&constructorKills=" + ZString(ppso->GetBuilderKills()); url += "&minerKills=" + ZString(ppso->GetMinerKills()); url += "&commandTimeMinutes=" + ZString(int(ppso->GetTimeCommanded() / 60)); char * szUrl = new char[2064]; strcpy(szUrl, (char *)(PCC)url); DWORD dwId; CreateThread(NULL, 0, UpdateLeaderboardThread, szUrl, 0, &dwId); } bool CSteamAchievements::CheckRank(int currentScore) { int currentRank, earnedRank; bool getSucceed; getSucceed = GetStat(EStats::PLAYER_RANK_2, &currentRank); if (getSucceed) { if (currentRank >= 5) SetAchievement(EAchievements::RANK_5_1_6); if (currentRank >= 10) SetAchievement(EAchievements::RANK_10_1_7); } earnedRank = currentRank; if (getSucceed && (currentRank < 50)) { if (currentScore > RANK_REQUIREMENTS[earnedRank + 1]) { earnedRank++; SetStat(EStats::PLAYER_RANK_2, earnedRank); return true; //add return for a future level up splash } } return false; } RankID CSteamAchievements::GetRank() { int rank; bool getSucceed; int currentScore; getSucceed = GetStat(EStats::SUM_SCORE_2, &currentScore); getSucceed = GetStat(EStats::PLAYER_RANK_2, &rank); if (getSucceed) return RankID(rank); else return 0; }
25a43ee7d94318c67fd8f687c12f000ec0eb7d2d
4dc83b8492043e29e7d1fac8a79c124aedbb78c4
/Lecture 7/array_basics.cpp
1c056f3986878cf515537d61a0d63d25447cbf76
[]
no_license
khandelwalpranav05/Launchpad-11-August
887bdf9b131bfbd3caa11de0a93fb028a2740fd0
fff86c27a16c627f0c863f5be6ea30941f61facc
refs/heads/master
2021-07-10T07:38:27.508235
2020-10-06T03:32:41
2020-10-06T03:32:41
202,844,125
8
15
null
2020-10-06T03:32:43
2019-08-17T06:22:11
C++
UTF-8
C++
false
false
458
cpp
array_basics.cpp
#include <iostream> using namespace std; void swap(int arr[],int i,int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } int main(){ int arr[] = {1,2,3,4,5,6,7}; for(int i=0;i<7;i++){ cout<<arr[i]<<" "; } cout<<endl; cout<<"*************************"<<endl; cout<<arr<<endl; cout<<(arr+1)<<endl; cout<<"**************************"<<endl; swap(arr,0,6); for(int i=0;i<7;i++){ cout<<arr[i]<<" "; } cout<<endl; return 0; }
06b55448125aeb5628cf5e9beaa540afd13cec0a
55e0545f6475f1e9e01f797b1f72cc15fd2d30f9
/C++/10.装饰器模式/DecoratorPatternDemo.cpp
bb31f374b2982b13a5d433fc1cd9a89b0d3304cf
[]
no_license
hustwbxs/DesignPattern
b1ef9bde5a5ffa9491135020257cd02ba02e00c4
1bcba8517850a34e3c4d6fa585db7e81d157706f
refs/heads/master
2023-04-26T09:33:34.361737
2020-11-22T09:10:05
2020-11-22T09:10:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
851
cpp
DecoratorPatternDemo.cpp
/** * @file DecoratorPatternDemo.cpp * @author {Layne} ({shu_huanglei@163.com}) * @brief * @version 0.1 * @date 2019-11-08 * * @copyright Copyright (c) 2019 * */ #include "Circle.h" #include "Rectangle.h" #include "RedShapeDecorator.h" int main(int argc, char const *argv[]) { std::shared_ptr<Shape> circle = std::make_shared<Circle>(); std::shared_ptr<ShapeDecorator> red_circle = std::make_shared<RedShapeDecorator>(std::make_shared<Circle>()); std::shared_ptr<ShapeDecorator> red_rectangle = std::make_shared<RedShapeDecorator>(std::make_shared<Rectangle>()); std::cout << "Circle with normal border" << std::endl; circle->Draw(); std::cout << "\nCircle of red border" << std::endl; red_circle->Draw(); std::cout << "\nRectangle of red border" << std::endl; red_rectangle->Draw(); return 0; }
922ea910e4d9ca1a7af72e4fbdcbfa4b061c5702
7415e2d8c0d15cb6b1abe569ed311196824b7e2c
/compiler/Serialization/VMDeviceTableBuilder.cpp
c2d746c828a0a0d61e3f2333e88c8eb2c903c456
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
monkeyking/iree
26b729a782282a731f4537e6d415343843044037
d72d304f0d8bea62566e9c0dbc8767fd54bb5dc6
refs/heads/master
2021-06-22T23:08:50.934251
2019-09-18T22:46:56
2019-09-18T23:05:14
209,453,419
2
0
Apache-2.0
2019-09-19T03:19:58
2019-09-19T03:19:58
null
UTF-8
C++
false
false
1,576
cpp
VMDeviceTableBuilder.cpp
// Copyright 2019 Google LLC // // 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 // // https://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 "third_party/mlir_edge/iree/compiler/Serialization/VMDeviceTableBuilder.h" namespace mlir { namespace iree_compiler { VMDeviceTableBuilder::VMDeviceTableBuilder( ::flatbuffers::FlatBufferBuilder *fbb) : fbb_(fbb) {} LogicalResult VMDeviceTableBuilder::AddDevice( ::flatbuffers::Offset<iree::DeviceDef> deviceDef) { deviceDefs_.push_back(deviceDef); return success(); } LogicalResult VMDeviceTableBuilder::AddDeviceGroup( ::flatbuffers::Offset<iree::DeviceGroupDef> deviceGroupDef) { deviceGroupDefs_.push_back(deviceGroupDef); return success(); } ::flatbuffers::Offset<iree::DeviceTableDef> VMDeviceTableBuilder::Finish() { auto devicesOffset = fbb_->CreateVector(deviceDefs_); auto deviceGroupsOffset = fbb_->CreateVector(deviceGroupDefs_); iree::DeviceTableDefBuilder dtdb(*fbb_); dtdb.add_devices(devicesOffset); dtdb.add_device_groups(deviceGroupsOffset); return dtdb.Finish(); } } // namespace iree_compiler } // namespace mlir
e3b3603695196d7c4c55e432ee6ae7f2f1b5e0c3
3f9663fc8fbadc73bb073291037a98a0294f895f
/8th/8.11.cpp
2d663cd1e4b1345827fc4ca504607b32f880aa13
[]
no_license
Layty/CppPrimer
f2bad75aa0db6725ed9e86bc8d03a5e70e96e252
bd8bbcd18da1a481dec1442eb3f201bf48204086
refs/heads/master
2020-12-05T10:28:24.982799
2020-05-03T07:23:24
2020-05-03T07:23:24
232,079,873
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
8.11.cpp
/* 8.11 本节的程序在外层while循环中定义了istringstream对象。 如果record对象定义在循环之外,你需要对程序做怎样的修改? 重写程序,将record的定义移到while循环之外,验证你设想的修改方法是否正确。 */ //使用string的clear
5eff60625a83eed67cbe733c71eb1b27fd60e9e7
edc7434dd5738c11d002297a0a1cf01d0aed4aa1
/include/mesh_conversion.h
606bfe59981b3109c89885deef808b24637d5009
[ "BSD-2-Clause" ]
permissive
Carlos2181/poreflow
1d8db502cfbbd442fcb55753dc701d6bd7f2b49d
7f54a633bfdb893ad093b8f91e717a401bf45bb8
refs/heads/master
2020-06-03T19:18:55.264606
2015-03-04T23:28:20
2015-03-04T23:28:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,326
h
mesh_conversion.h
/* Copyright (C) 2010 Imperial College London and others. * * Please see the AUTHORS file in the main source directory for a * full list of copyright holders. * * Gerard Gorman * Applied Modelling and Computation Group * Department of Earth Science and Engineering * Imperial College London * * g.gorman@imperial.ac.uk * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef MESH_CONVERSION_H #define MESH_CONVERSION_H #include <string> #include <vector> int create_domain(int axis, std::vector<double> &xyz, std::vector<int> &tets, std::vector<int> &facets, std::vector<int> &facet_ids); double read_resolution_from_nhdr(std::string filename); void read_tarantula_mesh_file(std::string filename, std::string nhdr_filename, bool toggle_material, std::vector<double> &xyz, std::vector<int> &tets); void read_vtk_mesh_file(std::string filename, std::string nhdr_filename, std::vector<double> &xyz, std::vector<int> &tets); double volume(const double *x0, const double *x1, const double *x2, const double *x3); #endif
001c69f6e6cdc1b7de88988ce6d9d2a5a681f6e8
f4ecb727bf7a9766370d515e138c93e2cbbfc45c
/Sampling.h
bc005ceee744c4e4fad41fb1b8daf81b96f9a108
[ "MIT" ]
permissive
RexYing/DTW-approx
da06d268e0b8b5c67e50f1b639a2b6e04c94b366
9f63d6edf245a22e3164b991e8d9d424dd884042
refs/heads/master
2021-01-17T09:26:34.858982
2016-06-13T06:15:05
2016-06-13T06:15:05
35,592,323
2
1
null
2017-02-27T04:29:12
2015-05-14T05:19:01
C++
UTF-8
C++
false
false
1,507
h
Sampling.h
#include <unordered_map> #include "WSPD.h" using namespace std; struct pairhash { public: template <typename T, typename U> std::size_t operator()(const std::pair<T, U> &x) const { return std::hash<T>()(x.first) ^ std::hash<U>()(x.second); } }; typedef vector<Point_2> Curve; typedef pair<long, long> GridIndex; // a pair of point sets in grid typedef pair<Curve*, Curve*> SetPair; typedef unordered_map<GridIndex, SetPair, pairhash> Grid; typedef unordered_map<GridIndex, QuadTreeTwoClasses*, pairhash> QuadTreeGrid; /* * Sampling from the dynamic programming matrix for dtw, edit distance */ class Sampling { public: Sampling(const Curve &curve1, const Curve &curve2, double lb, double ub, double eps); void init(); void sample(); string view_samples(); ~Sampling(); private: Curve curve1_; Curve curve2_; double lb_; double ub_; double eps_; // the side length of individual grid cells long len_cell_; QuadTreeTwoClasses* qt_; unordered_map<GridIndex, SetPair, pairhash> grid_; unordered_map<GridIndex, pair<vector<int>*, vector<int>*>, pairhash> grid_indices_; unordered_map<GridIndex, QuadTreeTwoClasses*, pairhash> quadtrees_; // map from diagonal number to sample points unordered_map<long, vector<pair<long, long>>* > diagonal_samples_; void insert_grid(); void print_grid(Grid grid); void add_samples_WSPD(QuadTreeTwoClasses* grid_qt1, QuadTreeTwoClasses* grid_qt2); };
42a0abd072720065893f90b419670ee0c17d73ee
a909df0ba2abf695df4a7d15350312d4c6463c48
/TIOJ/1930.cpp
e70d62995180ebb088934d659ca7df5670a3df50
[]
no_license
SayaUrobuchi/uvachan
1dadd767a96bb02c7e9449c48e463847480e98ec
c213f5f3dcfc72376913a21f9abe72988a8127a1
refs/heads/master
2023-07-23T03:59:50.638063
2023-07-16T04:31:23
2023-07-16T04:31:23
94,064,326
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
1930.cpp
#include <iostream> using namespace std; const int N = 2000005; int front[N], back[N]; int ans_list[N]; inline void conn(int a, int b) { front[b] = a; back[a] = b; } int main() { int count, n, m, i, t, st, a, b, c, cmd, ans; long long cnt; scanf("%d", &count); while (count--) { scanf("%d%d%d", &n, &m, &st); for (i=1; i<=n; i++) { front[i] = back[i] = -1; } conn(0, st); conn(st, n+1); for (i=0, cnt=0, ans=0; i<m; i++) { scanf("%d%d%d%d", &cmd, &a, &b, &c); if (cmd == 1) { if (c == 1) { b = front[b]; } conn(a, back[b]); conn(b, a); } else if (cmd == 2) { conn(front[a], back[b]); conn(front[c], a); conn(b, c); } else { cnt += b; if (c == 1) { t = back[a]; for (; b&&a; --b, a=front[a]) { ans_list[ans] = a; ++ans; } conn(a, t); } else { t = front[a]; for (; b&&a<=n; --b, a=back[a]) { ans_list[ans] = a; ++ans; } conn(t, a); } } } printf("%lld\n", cnt-n); for (i=0; i<n; i++) { printf("%d\n", ans_list[i]); } } return 0; }
a38a8b04e84e57d000782e0ed03d4d382d51f761
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5634697451274240_0/C++/m11121/rev.cpp
c12d4ccebb7bd5fd2ba902a50360fc578e2b8ec9
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
372
cpp
rev.cpp
#include <iostream> #include <string> using namespace std; int main() { int t; cin>>t; for(int ic=1;ic<=t;++ic) { cout<<"Case #"<<ic<<": "; string s; cin>>s; int ans=0,total=0; for(auto it = s.rbegin();it!=s.rend();++it) { if(*it=='-' && total%2==0 || *it=='+' && total%2) { ++total; ++ans; } } cout<<ans<<endl; } return 0; }
c165dfd119fae4362335fbec0aa1ce7ff49db9f1
585ff546e639fdebe21a5480acfdf03bf4b0e9ae
/Somnium/src/Graphics/Shaders/Shader.cpp
63e5411ee576ba69ba2c861146ae8c377610fbfb
[ "MIT" ]
permissive
MrLukeKR/SOMNIUM-Engine
0636780d34abfb8f497ccf182701b466d64243c5
3e8ae8825e3c0b1a853eb86b107aa94ce9445c3e
refs/heads/development
2022-11-15T11:17:07.435291
2020-07-11T10:20:54
2020-07-11T10:20:54
274,182,254
0
1
MIT
2020-06-26T09:30:55
2020-06-22T15:58:31
C
UTF-8
C++
false
false
3,210
cpp
Shader.cpp
#include "Shader.h" #include <string> #include <vector> #include <iostream> #include "../../Utilities/FileUtilities.h" using namespace std; using namespace Somnium; using namespace Utilities; using namespace Maths; namespace Somnium { namespace Graphics { namespace Shaders { Shader::Shader(const char* vertexFilePath, const char* fragmentFilePath) :m_VertexFilePath(vertexFilePath), m_FragmentFilePath(fragmentFilePath) { m_ShaderID = load(); } Shader::~Shader() { glDeleteProgram(m_ShaderID); } GLuint Shader::load() { GLint result; GLuint program = glCreateProgram(); GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); #ifdef WEB_BUILD string vertexSource = File::readFile((string(m_VertexFilePath) + string("es")).c_str()); string fragmentSource = File::readFile((string(m_FragmentFilePath) + string("es")).c_str()); #else string vertexSource = File::readFile(m_VertexFilePath); string fragmentSource = File::readFile(m_FragmentFilePath); #endif GLuint shaders[2] = { vertexShader, fragmentShader }; if (vertexSource.empty() || fragmentSource.empty()){ cerr << "ERROR LOADING SHADER" << endl; return 0; } const char * const vs = vertexSource.c_str(); const char * const fs = fragmentSource.c_str(); const char * const *sources[2] = { &vs, &fs }; for (int i = 0; i < 2; i++) { glShaderSource(shaders[i], 1, sources[i], NULL); glCompileShader(shaders[i]); glGetShaderiv(shaders[i], GL_COMPILE_STATUS, &result); if (!result) { GLint length; glGetShaderiv(shaders[i], GL_INFO_LOG_LENGTH, &length); vector<char> error(length); glGetShaderInfoLog(shaders[i], length, &length, &error[0]); cerr << &error[0] << endl; glDeleteShader(shaders[i]); return 0; } } for (int i = 0; i < 2; i++) glAttachShader(program, shaders[i]); glLinkProgram(program); glValidateProgram(program); glUseProgram(program); for (int i = 0; i < 2; i++) glDeleteShader(shaders[i]); return program; } GLint Shader::getUniformLocation(const GLchar* name) { return glGetUniformLocation(m_ShaderID, name); } void Shader::setInt(const GLchar* name, int value) { glUniform1i(getUniformLocation(name), value); } void Shader::setFloat(const GLchar* name, float value) { glUniform1f(getUniformLocation(name), value); } void Shader::setVector2(const GLchar* name, const Vector2& vector) { glUniform2f(getUniformLocation(name), vector.x, vector.y); } void Shader::setVector3(const GLchar* name, const Vector3& vector) { glUniform3f(getUniformLocation(name), vector.x, vector.y, vector.z); } void Shader::setVector4(const GLchar* name, const Vector4& vector) { glUniform4f(getUniformLocation(name), vector.x, vector.y, vector.z, vector.w); } void Shader::setMatrix4(const GLchar* name, const Matrix4& matrix) { glUniformMatrix4fv(getUniformLocation(name), 1, GL_FALSE, matrix.elements); } void Shader::enable() const { glUseProgram(m_ShaderID); } void Shader::disable() const { glUseProgram(0); } } } }
5a5ce0064eab2e5b3cb4c281b1d9aea8c5e16f05
a3f754560184f0158ddba8c113b674fa6d5df22a
/test/iterator.cpp
25cf093a41af82e9064627caaeb23dcbf62249cb
[ "Apache-2.0" ]
permissive
asutton/stl2
be9c843ee2780d89d9e1a8a0cbddd1e91c21371b
84808fdb535b2496b13e0a2ba78c9efb32c3c68c
refs/heads/master
2021-01-10T14:02:31.579996
2016-03-31T12:43:16
2016-03-31T12:43:16
53,437,814
3
0
null
null
null
null
UTF-8
C++
false
false
684
cpp
iterator.cpp
#include <std/iterator.hpp> #include <forward_list> #include <list> #include <vector> using fiter = std::forward_list<int>::iterator; using biter = std::list<int>::iterator; using riter = std::vector<int>::iterator; template<stl::ForwardIterator I> constexpr bool test_forward_iterator() { return true; } template<stl::BidirectionalIterator I> constexpr bool test_bidirectional_iterator() { return true; } template<stl::RandomAccessIterator I> constexpr bool test_random_access_iterator() { return true; } static_assert(test_forward_iterator<fiter>()); static_assert(test_bidirectional_iterator<biter>()); static_assert(test_random_access_iterator<riter>()); int main() { }
8f99d54203c61649c5de7ece47cb23d5791a58ab
c896ca2e53872690a6cb4a9be4418d802ac3c6ef
/CPP03/ex03/ClapTrap.cpp
42c75aa8b5bcfa3860810886e60c3cb61a74b6d4
[]
no_license
paspd/CPP_ALL
a1f66648798765085cfaf2b8558d2a76cfeb20c2
c4120a7b61b2a7243a3338dee335a151db0b6c52
refs/heads/master
2023-09-04T08:21:10.802507
2021-11-09T10:02:01
2021-11-09T10:02:01
405,879,580
0
1
null
null
null
null
UTF-8
C++
false
false
1,600
cpp
ClapTrap.cpp
#include "ClapTrap.hpp" ClapTrap::ClapTrap(void): _name("default"), _hitPoints(10), _energyPoints(10), _attackDamage(0) { std::cout << "ClapTrap default constructor called" << std::endl; return; } ClapTrap::ClapTrap(std::string name): _name(name), _hitPoints(10), _energyPoints(10), _attackDamage(0) { std::cout << "ClapTrap constructor called" << std::endl; return; } ClapTrap::ClapTrap(const ClapTrap &copy) { std::cout << "ClapTrap constructor by copy called" << std::endl; *this = copy; } ClapTrap::~ClapTrap(void) { std::cout << "ClapTrap destructor called" << std::endl; return; } ClapTrap &ClapTrap::operator=(ClapTrap const &rhs) { this->_name = rhs.getName(); this->_hitPoints = rhs.getHitPoints(); this->_energyPoints = rhs.getEnergyPoints(); this->_attackDamage = rhs.getAttackDamage(); return *this; } std::string ClapTrap::getName(void) const { return this->_name; } int ClapTrap::getHitPoints(void) const { return this->_hitPoints; } int ClapTrap::getEnergyPoints(void) const { return this->_energyPoints; } int ClapTrap::getAttackDamage(void) const { return this->_attackDamage; } void ClapTrap::attack(std::string const &target) { std::cout << "ClapTrap " << this->_name << " attack " << target << ", causing " << this->_attackDamage << " points of damage" << std::endl; } void ClapTrap::takeDamage(unsigned int amount) { std::cout << "ClapTrap " << this->_name << " take " << amount << " damage" << std::endl; } void ClapTrap::beRepaired(unsigned int amount) { std::cout << "ClapTrap " << this->_name << " heal " << amount << " points" << std::endl; }
f5ec3ecc87a1ec1af69848b1776a83e667d24003
184e94519f5b6106f9b79b73129ff53edc7d2337
/AnimationExample/Player.h
fc5104f1fec88698f04d3ac7070c1264b3ef5ec6
[]
no_license
chuwilliamson/sfw-AIE-Framework
e6c8aabdcce432fbdfd18585613ca21bfa857af4
a373a894b7c15dc768007ef985d7089ecb5258ec
refs/heads/master
2016-08-11T16:37:10.109963
2015-12-14T20:56:09
2015-12-14T20:56:09
48,000,813
0
2
null
null
null
null
UTF-8
C++
false
false
690
h
Player.h
#pragma once #include "GameObject.h" /* See GameObject.h for rationale! Inheriting from gameobject, we can adopt all of the properties it has and contribute some of our own. A player, for example, may want to update it's position based on input. */ class GameState; class Player : public GameObject { public: float speed; float fireDelay; float rateOfFire; Player() : speed(100), rateOfFire(0.1f), fireDelay(0.f) { width = 200; height = 200; animationName = "NOTVERYBOOM"; textureName = "Explosion"; } virtual void onCollision(GameObject &go, float distance) { animTimer = 0; animationName = "NOTVERYBOOM"; } virtual void update(); // Moved to the .cpp! };
34a05ef4bc5d643058d57f95fc55d4430f94875b
93ae19390a0d8b3aab8dc655fc93f607d093672f
/hdoj/1879.cpp
66fb0e089ce900ba5e91029e2f8c8aee28f0e226
[]
no_license
scusword/acm
4f038c83fca9b95b607f7b600c292665fe66437f
7c9be9c8ef66d08fb5a4b0ace0a9cf8d758aee31
refs/heads/master
2020-03-28T19:36:32.955429
2018-11-03T06:18:31
2018-11-03T06:18:31
148,992,050
0
0
null
null
null
null
UTF-8
C++
false
false
3,301
cpp
1879.cpp
/* Problem Description 省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。 Input 测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。 当N为0时输入结束。 Output 每个测试用例的输出占一行,输出全省畅通需要的最低成本。 Sample Input 3 1 2 1 0 1 3 2 0 2 3 4 0 3 1 2 1 0 1 3 2 0 2 3 4 1 3 1 2 1 0 1 3 2 1 2 3 4 1 0 Sample Output 3 1 0 */ #include <iostream> #include <cstring> #include <queue> #include <algorithm> #include <cstdio> int p[100]; int rank[100]; int villages[100][100]; struct road { int v, u, cost; }; bool road_comp(const road& r1, const road& r2) { return r1.cost < r2.cost; } road roads[5005]; inline void init_union_set(int n) { for (int i = 0; i < n; i++) { p[i] = i; rank[i] = 1; } } int find(int x) { if (p[x] == x) { return x; } return p[x] = find(p[x]); } bool is_same_group(int x, int y) { return find(x) == find(y); } void merge(int x, int y) { int px = find(x); int py = find(y); if (px == py) { return; } if (rank[px] > rank[py]) { p[py] = px; } else { p[px] = py; if (rank[px] == rank[py]) { rank[py]++; } } } int kruskal2(int roads_cnt) { int min_cost = 0; std::sort(roads, roads + roads_cnt, road_comp); for (int i = 0; i < roads_cnt; i++) { if (!is_same_group(roads[i].v, roads[i].u)) { merge(roads[i].v, roads[i].u); min_cost += roads[i].cost; } } return min_cost; } /* int kruskal(int n) { int min_cost = 0; std::priority_queue<road> q; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (villages[i][j] != 0 && !is_same_group(i, j)) { q.push(road(i, j, villages[i][j])); } } } while (!q.empty()) { const road& r = q.top(); if (!is_same_group(r.v, r.u)) { min_cost += r.cost; merge(r.v, r.u); } q.pop(); } return min_cost; } */ int main() { int N, a, b, c, d; while (scanf("%d", &N) && N) { int t = N * (N - 1) / 2; int road_cnt = 0; //memset(villages, 0, sizeof(villages)); init_union_set(N); while (t--) { scanf("%d %d %d %d", &a, &b, &c, &d); a--; b--; if (d == 1) { merge(a, b); } else { roads[road_cnt].v = a; roads[road_cnt].u = b; roads[road_cnt++].cost = c; } } std::cout<<kruskal2(road_cnt)<<std::endl; } return 0; }
7aed8e7316576fedd7a1c7ca98937b3ffa0336e3
bef312468baf3c199e92d1d465bd938593cd25ad
/src/TestCommon/TestStringConvertor.h
417dc2fe2984015863667c685f48d90d78e4b3e8
[]
no_license
yunbj/common
a2f66e756fa95e39f6026284e699934c8b93e5bc
79cb49cdf9600477066a0c44bdaba029ec938c0b
refs/heads/master
2020-07-07T04:40:04.193535
2019-03-22T02:28:11
2019-03-22T02:28:11
203,251,773
0
0
null
null
null
null
UTF-8
C++
false
false
233
h
TestStringConvertor.h
#ifndef TESTSTRINGCONVERTOR_H #define TESTSTRINGCONVERTOR_H class TestStringConvertor { public: TestStringConvertor(); virtual ~TestStringConvertor(); void DoTest(); }; #endif // TESTSTRINGCONVERTOR_H
e514c28bed73bb3ccd7675c8f838924cece786bf
c6759b857e55991fea3ef0b465dbcee53fa38714
/gvsoc/gvsoc/models/cpu/iss/sa/src/loader.cpp
07eb9f1e3ca61a3e421a1c3986ba5e6651247339
[ "Apache-2.0" ]
permissive
GreenWaves-Technologies/gap_sdk
1b343bba97b7a5ce62a24162bd72eef5cc67e269
3fea306d52ee33f923f2423c5a75d9eb1c07e904
refs/heads/master
2023-09-01T14:38:34.270427
2023-08-10T09:04:44
2023-08-10T09:04:44
133,324,605
145
96
Apache-2.0
2023-08-27T19:03:52
2018-05-14T07:50:29
C
UTF-8
C++
false
false
10,765
cpp
loader.cpp
/* * Copyright (C) 2020 GreenWaves Technologies, SAS, ETH Zurich and * University of Bologna * * 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. */ /* * Authors: Germain Haugou, GreenWaves Technologies (germain.haugou@greenwaves-technologies.com) */ #include "sa_iss.hpp" static int look_for_symbol_group(bfd *abfd, const char *sec_name, unsigned int Flag, const char *s1, unsigned int *v1, const char *s2, unsigned int *v2, const char *s3, unsigned int *v3, const char *s4, unsigned int *v4) { int storage_needed; static asymbol **symbol_table = NULL; static int init_done = 0; static int number_of_symbols = 0; int i; int found_v1 = 0, found_v2 = 0, found_v3 = 0, found_v4 = 0; if (!init_done) { init_done = 1; storage_needed = bfd_get_symtab_upper_bound (abfd); if (storage_needed <= 0) return 0; symbol_table = (asymbol **) malloc (storage_needed); if (symbol_table == NULL) return 0; number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table); if (number_of_symbols < 0) return 0; } for (i = 0; i < number_of_symbols; i++) { asymbol *sym = symbol_table[i]; if (s1 && !found_v1 && (strcmp(sym->name, s1) == 0) && (sym->flags & Flag) && (strcmp(sym->section->name, sec_name) == 0)) { *v1 = sym->value + sym->section->vma; found_v1 = 1; } else if (s2 && !found_v2 && (strcmp(sym->name, s2) == 0) && (sym->flags & Flag) && (strcmp(sym->section->name, sec_name) == 0)) { *v2 = sym->value + sym->section->vma; found_v2 = 1; } else if (s3 && !found_v3 && (strcmp(sym->name, s3) == 0) && (sym->flags & Flag) && (strcmp(sym->section->name, sec_name) == 0)) { *v3 = sym->value + sym->section->vma; found_v3 = 1; } else if (s4 && !found_v4 && (strcmp(sym->name, s4) == 0) && (sym->flags & Flag) && (strcmp(sym->section->name, sec_name) == 0)) { *v4 = sym->value + sym->section->vma; found_v4 = 1; } } return ((!s1 || (s1 && found_v1)) && (!s2 || (s1 && found_v2)) && (!s3 || (s1 && found_v3)) && (!s4 || (s1 && found_v4))); } static int handle_argc_argc(iss_t *iss, struct bfd *abfd, char **prog_argv) { unsigned int a_argc, a_argv, a_argbuf, a_stack, a_base, a_size; char *name = bfd_get_filename (abfd); int len = strlen (name) + 1; bfd_byte buf[4]; int my_argc = 0; int Ok = 1; int i; static int Trace = 0; if (look_for_symbol_group(abfd, ".data", BSF_GLOBAL, "argc", &a_argc, "argv", &a_argv, "argbuf", &a_argbuf, "stack", &a_stack)) { iss->a_argc = a_argc; iss->a_argv = a_argv; iss->a_argbuf = a_argbuf; iss->a_stack = a_stack; for (i = 0; prog_argv[i] != NULL; my_argc++, i++) len += strlen (prog_argv[i]) + 1; if (Trace) { fprintf (stderr, "Found argc=0x%X [%d], argv=0x%X [%d], argbuf=0x%X [%d], stack=0x%X\n", a_argc, (a_argv-a_argc), a_argv, (a_argbuf-a_argv), a_argbuf, (a_stack-a_argbuf), a_stack); fprintf (stderr, "Total buffer length=%d\n", len); for (i = 0; i<my_argc; i++) fprintf (stderr, " argv[%d] = \"%s\", L:%d\n", i, prog_argv[i], (int) strlen(prog_argv[i])+1); } } else { if (prog_argv && prog_argv[1] != NULL) { fprintf (stderr, "Program argc, argv error: Trying to pass arguments but at least one of [argc,argv,argbuf,stack] is undefined\n"); fprintf (stderr, " Check your crt0\n"); } Ok = 0; } if (Ok) { Ok &= ((a_argv>a_argc) && (a_argbuf>a_argv) && (a_stack>a_argbuf)); // In the following order: argc,argv,argbuf,stack if (!((a_argv>a_argc) && (a_argbuf>a_argv) && (a_stack>a_argbuf))) { fprintf (stderr, "Program argc, argv error: expecting &argc>argv>&argbuf>&stack\n"); fprintf (stderr, " Reading argc=0x%X [%d], argv=0x%X [%d], argbuf=0x%X [%d], stack=0x%X\n", a_argc, (a_argv-a_argc), a_argv, (a_argbuf-a_argv), a_argbuf, (a_stack-a_argbuf), a_stack); } Ok &= ((a_argc & 0x3)==0); // int aligned if (!((a_argc & 0x3)==0)) { fprintf (stderr, "Program argc, argv error: argc is not 4 byte aligned\n"); fprintf (stderr, " Reading argc=0x%X [%d], argv=0x%X [%d], argbuf=0x%X [%d], stack=0x%X\n", a_argc, (a_argv-a_argc), a_argv, (a_argbuf-a_argv), a_argbuf, (a_stack-a_argbuf), a_stack); } Ok &= ((a_argbuf & 0x3)==0); // int aligned if (!((a_argbuf & 0x3)==0)) { fprintf (stderr, "Program argc, argv error: arg buffer is not 4 byte aligned\n"); fprintf (stderr, " Reading argc=0x%X [%d], argv=0x%X [%d], argbuf=0x%X [%d], stack=0x%X\n", a_argc, (a_argv-a_argc), a_argv, (a_argbuf-a_argv), a_argbuf, (a_stack-a_argbuf), a_stack); } Ok &= (a_argv == (a_argc+4)); // argv right after argc if (!(a_argv == (a_argc+4))) { fprintf (stderr, "Program argc, argv error: expecting &argv = &argc+4\n"); fprintf (stderr, " Reading argc=0x%X [%d], argv=0x%X [%d], argbuf=0x%X [%d], stack=0x%X\n", a_argc, (a_argv-a_argc), a_argv, (a_argbuf-a_argv), a_argbuf, (a_stack-a_argbuf), a_stack); } Ok &= (my_argc <= ((a_argbuf - a_argv)>>2)); // Enough room for argv pointers if (!(my_argc <= ((a_argbuf - a_argv)>>2))) { fprintf (stderr, "Program argc, argv error: Max requested argc exceeded: %d\n", my_argc); fprintf (stderr, " Reading argc=0x%X [%d], argv=0x%X [%d], argbuf=0x%X [%d], stack=0x%X\n", a_argc, (a_argv-a_argc), a_argv, (a_argbuf-a_argv), a_argbuf, (a_stack-a_argbuf), a_stack); } Ok &= (len <= (a_stack - a_argbuf)); // Enough space in the buffer if (!(len <= (a_stack - a_argbuf))) { fprintf (stderr, "Program argc, argv error: Max argv buffer (argbuf) size exceeded: %d\n", len); fprintf (stderr, " Reading argc=0x%X [%d], argv=0x%X [%d], argbuf=0x%X [%d], stack=0x%X\n", a_argc, (a_argv-a_argc), a_argv, (a_argbuf-a_argv), a_argbuf, (a_stack-a_argbuf), a_stack); } if (Ok) { int j; storeWord (iss, a_argc, my_argc); for (i = 0; (Ok && (i < my_argc)); i++, a_argv += 4) { size_t strln = strlen (prog_argv[i]) + 1; storeWord (iss, a_argv, a_argbuf); for (j=0; j<strln; j++) storeByte(iss, a_argbuf+j, prog_argv[i][j]); a_argbuf += (unsigned int) strln; } if (!Ok) { if (Trace) fprintf (stderr, "At least on write command for argc, argv failed\n"); storeWord (iss, a_argc, 0); } else if (Trace) fprintf (stderr, "Sucessfull argc, argv initialization\n"); } else if (Trace) fprintf (stderr, "Failed to check pre conditions for using argc, argv\n"); } else if (Trace) fprintf (stderr, "One of argc, argv, argbuf, stack symbols was not found in loaded elf file\n"); if (look_for_symbol_group(abfd, ".text", BSF_LOCAL, "__mem_base", &a_base, "__mem_size", &a_size, NULL, NULL, NULL, NULL)) { unsigned int base, size; loadWord(iss, a_base, &base); loadWord(iss, a_size, &size); if (Trace) fprintf(stderr, "Mem Base: [%X] = %X, Mem Size: [%X] = %X\n", a_base, base, a_size, size); if ((base+size) > iss->mem_size) { fprintf(stderr, "crt0: __mem_base+_mem_size (%X+%X) exceeds simulator allocated memory: %lX\n", base, size, iss->mem_size); Ok=0; } } else { fprintf(stderr, "crt0: can't find __mem_base and/or __mem_size symbols\n"); Ok=0; } return Ok; } int load_binary(iss_t *iss, const char *name, int argc, char **argv, iss_reg_t *bootaddr) { bfd *abfd; int trace = 0; char *myname; asection *s; int lma_p = 0; int verbose_p = 10; int found_loadable_section = 0; unsigned long data_count = 0; /* Number of bytes transferred to memory */ struct timeval start_time; abfd = bfd_openr (name, 0); // printf("%p\n", abfd); if (!abfd) { fprintf (stderr, "%s: can't open %s: %s\n", myname, name, bfd_errmsg (bfd_get_error ())); exit (1); } if (!bfd_check_format (abfd, bfd_object)) { fprintf (stderr, "%s: can't load %s: %s\n", myname, name, bfd_errmsg (bfd_get_error ())); exit (1); } for (s = abfd->sections; s; s = s->next) if (strcmp (bfd_get_section_name (abfd, s), ".text") == 0) { iss->textSection = s; iss->textSectionStart = bfd_get_section_vma (abfd, s); iss->textSectionEnd = bfd_get_section_vma (abfd, s) + bfd_section_size (abfd, s); break; } for (s = abfd->sections; s; s = s->next) { if (s->flags & SEC_LOAD) { bfd_size_type size; size = bfd_get_section_size (s); if (size > 0) { unsigned char *buffer; bfd_vma lma; buffer = (unsigned char *)malloc (size); if (buffer == NULL) { printf("%s: insufficient memory to load \"%s\"\n", myname, name); return -1; } if (lma_p) lma = bfd_section_lma (abfd, s); else lma = bfd_section_vma (abfd, s); if (verbose_p) { printf("Loading section %s, size 0x%lx %s ", bfd_get_section_name (abfd, s), (unsigned long) size, (lma_p ? "lma" : "vma")); printf("%lx", lma); printf("\n"); } data_count += size; bfd_get_section_contents (abfd, s, buffer, 0, size); memcpy(iss->mem_array + lma, buffer, size); found_loadable_section = 1; free (buffer); } } } if (!found_loadable_section) { printf( "%s: no loadable sections \"%s\"\n", myname, name); return -1; } if (verbose_p) { printf("Start address 0x%lx\n", bfd_get_start_address (abfd)); } if (!handle_argc_argc(iss, abfd, argv)) { printf("Failed to initialize argc/argv\n"); return -1; } iss->abfd = abfd; if (bootaddr) *bootaddr = bfd_get_start_address (abfd); return 0; }
acc12d028e747b05d8f23e0b5359baf9c89a0752
ee455bf2e210f94e89035b74de43cb70ced9e8e1
/MailboxTableDlg.cpp
3338a54c8d5bec1fe17aed43fcd48756f43ff7f9
[]
no_license
15831944/mfcmapi-1
ee8d020eec0e9ee840c1f05920f127ff993bb37b
92781f695b6170e7ebfd9dc617f48a240a823171
refs/heads/master
2023-03-17T12:44:16.397759
2014-08-26T16:14:35
2014-08-26T16:14:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,593
cpp
MailboxTableDlg.cpp
// MailboxTableDlg.cpp : implementation file // #include "stdafx.h" #include "MailboxTableDlg.h" #include "ContentsTableListCtrl.h" #include "MapiObjects.h" #include "MAPIFunctions.h" #include "MAPIStoreFunctions.h" #include "SingleMAPIPropListCtrl.h" #include "ColumnTags.h" #include "MFCUtilityFunctions.h" #include "UIFunctions.h" #include "Editor.h" #include "PropertyTagEditor.h" #include "InterpretProp2.h" static TCHAR* CLASS = _T("CMailboxTableDlg"); ///////////////////////////////////////////////////////////////////////////// // CMailboxTableDlg dialog CMailboxTableDlg::CMailboxTableDlg( _In_ CParentWnd* pParentWnd, _In_ CMapiObjects* lpMapiObjects, _In_z_ LPCTSTR lpszServerName, _In_ LPMAPITABLE lpMAPITable ) : CContentsTableDlg( pParentWnd, lpMapiObjects, IDS_MAILBOXTABLE, mfcmapiDO_NOT_CALL_CREATE_DIALOG, lpMAPITable, (LPSPropTagArray)&sptMBXCols, NUMMBXCOLUMNS, MBXColumns, IDR_MENU_MAILBOX_TABLE_POPUP, MENU_CONTEXT_MAILBOX_TABLE ) { TRACE_CONSTRUCTOR(CLASS); HRESULT hRes = S_OK; EC_H(CopyString(&m_lpszServerName, lpszServerName, NULL)); CreateDialogAndMenu(IDR_MENU_MAILBOX_TABLE); } // CMailboxTableDlg::CMailboxTableDlg CMailboxTableDlg::~CMailboxTableDlg() { TRACE_DESTRUCTOR(CLASS); MAPIFreeBuffer(m_lpszServerName); } // CMailboxTableDlg::~CMailboxTableDlg BEGIN_MESSAGE_MAP(CMailboxTableDlg, CContentsTableDlg) ON_COMMAND(ID_OPENWITHFLAGS, OnOpenWithFlags) END_MESSAGE_MAP() void CMailboxTableDlg::OnInitMenu(_In_ CMenu* pMenu) { if (pMenu) { if (m_lpContentsTableListCtrl) { int iNumSel = m_lpContentsTableListCtrl->GetSelectedCount(); pMenu->EnableMenuItem(ID_OPENWITHFLAGS, DIMMSOK(iNumSel)); } } CContentsTableDlg::OnInitMenu(pMenu); } // CMailboxTableDlg::OnInitMenu void CMailboxTableDlg::CreateDialogAndMenu(UINT nIDMenuResource) { DebugPrintEx(DBGCreateDialog, CLASS, _T("CreateDialogAndMenu"), _T("id = 0x%X\n"), nIDMenuResource); CContentsTableDlg::CreateDialogAndMenu(nIDMenuResource); UpdateMenuString( m_hWnd, ID_CREATEPROPERTYSTRINGRESTRICTION, IDS_MBRESMENU); } // CMailboxTableDlg::CreateDialogAndMenu void CMailboxTableDlg::DisplayItem(ULONG ulFlags) { HRESULT hRes = S_OK; CWaitCursor Wait; // Change the mouse to an hourglass while we work. LPMAPISESSION lpMAPISession = m_lpMapiObjects->GetSession(); // do not release if (!lpMAPISession) return; LPMDB lpMDB = m_lpMapiObjects->GetMDB(); // do not release LPMDB lpGUIDMDB = NULL; if (!lpMDB) { EC_H(OpenMessageStoreGUID(lpMAPISession, pbExchangeProviderPrimaryUserGuid, &lpGUIDMDB)); } LPMDB lpSourceMDB = NULL; // do not release lpSourceMDB = lpMDB ? lpMDB : lpGUIDMDB; if (lpSourceMDB) { LPMDB lpNewMDB = NULL; TCHAR* szMailboxDN = NULL; int iItem = -1; SortListData* lpListData = NULL; do { hRes = S_OK; lpListData = m_lpContentsTableListCtrl->GetNextSelectedItemData(&iItem); if (lpListData) { szMailboxDN = lpListData->data.Contents.szDN; if (szMailboxDN) { EC_H(OpenOtherUsersMailbox( lpMAPISession, lpSourceMDB, m_lpszServerName, szMailboxDN, ulFlags, false, &lpNewMDB)); if (lpNewMDB) { EC_H(DisplayObject( (LPMAPIPROP)lpNewMDB, NULL, otStore, this)); lpNewMDB->Release(); lpNewMDB = NULL; } } } } while (iItem != -1); } if (lpGUIDMDB) lpGUIDMDB->Release(); } // CMailboxTableDlg::DisplayItem void CMailboxTableDlg::OnDisplayItem() { DisplayItem(OPENSTORE_USE_ADMIN_PRIVILEGE | OPENSTORE_TAKE_OWNERSHIP); } // CMailboxTableDlg::OnDisplayItem void CMailboxTableDlg::OnOpenWithFlags() { HRESULT hRes = S_OK; CEditor MyPrompt( this, IDS_OPENWITHFLAGS, IDS_OPENWITHFLAGSPROMPT, 1, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyPrompt.SetPromptPostFix(AllFlagsToString(PROP_ID(PR_PROFILE_OPEN_FLAGS), true)); MyPrompt.InitPane(0, CreateSingleLinePane(IDS_CREATESTORENTRYIDFLAGS, NULL, false)); MyPrompt.SetHex(0, OPENSTORE_USE_ADMIN_PRIVILEGE | OPENSTORE_TAKE_OWNERSHIP); WC_H(MyPrompt.DisplayDialog()); if (S_OK == hRes) { DisplayItem(MyPrompt.GetHex(0)); } } // CMailboxTableDlg::OnOpenWithFlags void CMailboxTableDlg::OnCreatePropertyStringRestriction() { HRESULT hRes = S_OK; LPSRestriction lpRes = NULL; CPropertyTagEditor MyPropertyTag( IDS_PROPRES, NULL, // prompt PR_DISPLAY_NAME, m_bIsAB, m_lpContainer, this); WC_H(MyPropertyTag.DisplayDialog()); if (S_OK == hRes) { CEditor MyData( this, IDS_SEARCHCRITERIA, IDS_MBSEARCHCRITERIAPROMPT, 2, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyData.SetPromptPostFix(AllFlagsToString(flagFuzzyLevel, true)); MyData.InitPane(0, CreateSingleLinePane(IDS_NAME, NULL, false)); MyData.InitPane(1, CreateSingleLinePane(IDS_ULFUZZYLEVEL, NULL, false)); MyData.SetHex(1, FL_IGNORECASE | FL_PREFIX); WC_H(MyData.DisplayDialog()); if (S_OK != hRes) return; // Allocate and create our SRestriction EC_H(CreatePropertyStringRestriction( CHANGE_PROP_TYPE(MyPropertyTag.GetPropertyTag(), PT_TSTRING), MyData.GetString(0), MyData.GetHex(1), NULL, &lpRes)); if (hRes != S_OK) { MAPIFreeBuffer(lpRes); lpRes = NULL; } m_lpContentsTableListCtrl->SetRestriction(lpRes); SetRestrictionType(mfcmapiNORMAL_RESTRICTION); } } // CMailboxTableDlg::OnCreatePropertyStringRestriction
ef310cf2588cb11b3de780d3e4f7085267b70209
c037f3092d3f94a7e6f380184507ab133639cc3d
/src/components/system_media_controls/webos/system_media_controls_webos.cc
8467b904cd298d440254176489a563697111f403
[ "BSD-3-Clause" ]
permissive
webosose/chromium79
bab17fe53458195b41251e4d5adfa29116ae89a9
57b21279f43f265bf0476d2ebf8fe11c8dee4bba
refs/heads/master
2022-11-10T03:27:02.861486
2020-10-29T11:30:27
2020-11-09T05:19:01
247,589,218
3
6
null
2022-10-23T11:12:07
2020-03-16T02:06:18
null
UTF-8
C++
false
false
17,926
cc
system_media_controls_webos.cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/system_media_controls/webos/system_media_controls_webos.h" #include <memory> #include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/memory/singleton.h" #include "base/process/process.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "build/branding_buildflags.h" #include "components/system_media_controls/system_media_controls_observer.h" #include "components/system_media_controls/webos/system_media_controls_stub.h" #include "content/public/browser/media_session.h" #include "content/public/browser/web_contents.h" #include "media/base/bind_to_current_loop.h" #include "services/media_session/public/cpp/features.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "third_party/jsoncpp/source/include/json/json.h" namespace system_media_controls { // static SystemMediaControls* SystemMediaControls::GetInstance() { if (!base::FeatureList::IsEnabled( media_session::features::kMediaControllerService)) return internal::SystemMediaControlsStub::GetInstance(); return internal::SystemMediaControlsWebOS::GetInstance();; } namespace internal { namespace { const char kAppId[] = "appId"; const char kMediaId[] = "mediaId"; const char kSubscribe[] = "subscribe"; const char kSubscribed[] = "subscribed"; const char kReturnValue[] = "returnValue"; const char kKeyEvent[] = "keyEvent"; const char kMediaMetaData[] = "mediaMetaData"; const char kMediaMetaDataTitle[] = "title"; const char kMediaMetaDataArtist[] = "artist"; const char kMediaMetaDataAlbum[] = "album"; const char kMediaMetaDataTotalDuration[] = "totalDuration"; const char kMediaPlayStatus[] = "playStatus"; const char kMediaPlayStatusStopped[] = "PLAYSTATE_STOPPED"; const char kMediaPlayStatusPaused[] = "PLAYSTATE_PAUSED"; const char kMediaPlayStatusPlaying[] = "PLAYSTATE_PLAYING"; const char kMediaMuteStatus[] = "muteStatus"; const char kMediaMuteStatusMuted[] = "MUTE"; const char kMediaMuteStatusUnmuted[] = "UNMUTE"; const char kMediaPlayPosition[] = "playPosition"; const char kPlayEvent[] = "play"; const char kPauseEvent[] = "pause"; const char kNextEvent[] = "next"; const char kPreviousEvent[] = "previous"; const char kMuteEvent[] = "mute"; const char kUnmuteEvent[] = "unmute"; const char kRegisterMediaSession[] = "registerMediaSession"; const char kUnregisterMediaSession[] = "unregisterMediaSession"; const char kActivateMediaSession[] = "activateMediaSession"; const char kDeactivateMediaSession[] = "deactivateMediaSession"; const char kSetMediaMetaData[] = "setMediaMetaData"; const char kSetMediaPlayStatus[] = "setMediaPlayStatus"; const char kSetMediaMuteStatus[] = "setMediaMuteStatus"; const char kSetMediaPlayPosition[] = "setMediaPlayPosition"; } // namespace #define BIND_TO_CURRENT_LOOP(function) \ (media::BindToCurrentLoop( \ base::BindRepeating(function, base::Unretained(this)))) // static SystemMediaControlsWebOS* SystemMediaControlsWebOS::GetInstance() { return base::Singleton<SystemMediaControlsWebOS>::get(); } SystemMediaControlsWebOS::SystemMediaControlsWebOS() = default; SystemMediaControlsWebOS::~SystemMediaControlsWebOS() { UnregisterMediaSession(); } void SystemMediaControlsWebOS::AddObserver( SystemMediaControlsObserver* observer) { observers_.AddObserver(observer); // If the service is already ready, inform the observer. if (registered_) { observer->OnServiceReady(); service_ready_status_ = ServiceReadyStatus::kCompleted; return; } service_ready_status_ = ServiceReadyStatus::kPending; } void SystemMediaControlsWebOS::RemoveObserver( SystemMediaControlsObserver* observer) { observers_.RemoveObserver(observer); } void SystemMediaControlsWebOS::SetEnabled(bool value) { // TODO: Propogate the status to MCS after MCS provides such APIs } void SystemMediaControlsWebOS::SetIsNextEnabled(bool value) { // TODO: Propogate the status to MCS after MCS provides such APIs } void SystemMediaControlsWebOS::SetIsPreviousEnabled(bool value) { // TODO: Propogate the status to MCS after MCS provides such APIs } void SystemMediaControlsWebOS::SetIsPlayEnabled(bool value) { // TODO: Propogate the status to MCS after MCS provides such APIs } void SystemMediaControlsWebOS::SetIsPauseEnabled(bool value) { // TODO: Propogate the status to MCS after MCS provides such APIs } void SystemMediaControlsWebOS::SetIsStopEnabled(bool value) { // TODO: Propogate the status to MCS after MCS provides such APIs } void SystemMediaControlsWebOS::SetPlaybackStatus(PlaybackStatus value) { auto status = [&]() { switch (value) { case PlaybackStatus::kPlaying: return std::string(kMediaPlayStatusPlaying); case PlaybackStatus::kPaused: return std::string(kMediaPlayStatusPaused); case PlaybackStatus::kStopped: return std::string(kMediaPlayStatusStopped); } NOTREACHED() << __func__ << " Invalid playback status. session_id: " << session_id_; return std::string("Unidentified"); }; SetPlaybackStatusInternal(status()); } void SystemMediaControlsWebOS::SetTitle(const base::string16& value) { SetMetadataPropertyInternal(kMediaMetaDataTitle, value); } void SystemMediaControlsWebOS::SetArtist(const base::string16& value) { SetMetadataPropertyInternal(kMediaMetaDataArtist, value); } void SystemMediaControlsWebOS::SetAlbum(const base::string16& value) { SetMetadataPropertyInternal(kMediaMetaDataAlbum, value); } void SystemMediaControlsWebOS::SetThumbnail(const SkBitmap& bitmap) { // TODO: Propogate the status to MCS after MCS provides such APIs } void SystemMediaControlsWebOS::ClearThumbnail() { // TODO: Propogate the status to MCS after MCS provides such APIs } void SystemMediaControlsWebOS::ClearMetadata() { VLOG(1) << __func__; SetTitle(base::string16()); SetArtist(base::string16()); SetAlbum(base::string16()); } void SystemMediaControlsWebOS::UpdateDisplay() { // TODO: Propogate the status to MCS after MCS provides such APIs } void SystemMediaControlsWebOS::SetMediaSessionId( const base::Optional<base::UnguessableToken>& session_id) { if (session_id.has_value()) application_id_ = GetAppIdFromSession(session_id.value()); if (application_id_.empty()) { LOG(ERROR) << __func__ << " Could not obtain app_id."; return; } if (!luna_service_client_.get()) { luna_service_client_.reset( new base::LunaServiceClient(application_id_)); } if (!session_id_.empty()) { // Previous session is active. Deactivate it. UnregisterMediaSession(); } if (!session_id.has_value()) { LOG(ERROR) << __func__ << "session_id not received."; return; } if (!RegisterMediaSession(session_id->ToString())) { LOG(ERROR) << __func__ << " Register session failed."; return; } if (!ActivateMediaSession(session_id->ToString())) { LOG(ERROR) << __func__ << " Activate session failed."; return; } session_id_ = session_id->ToString(); } void SystemMediaControlsWebOS::SetMuteStatus(bool muted) { if (session_id_.empty()) { LOG(ERROR) << __func__ << " No active session."; return; } Json::Value mutestatus_root; mutestatus_root[kMediaId] = session_id_; mutestatus_root[kMediaMuteStatus] = muted ? kMediaMuteStatusMuted : kMediaMuteStatusUnmuted; Json::FastWriter mutestatus_writer; std::string mutestatus_payload = mutestatus_writer.write(mutestatus_root); VLOG(1) << __func__ << " mutestatus_payload: " << mutestatus_payload; luna_service_client_->CallAsync( base::LunaServiceClient::GetServiceURI( base::LunaServiceClient::URIType::MEDIACONTROLLER, kSetMediaMuteStatus), mutestatus_payload, BIND_TO_CURRENT_LOOP( &SystemMediaControlsWebOS::CheckReplyStatusMessage)); } void SystemMediaControlsWebOS::SetMediaPosition( const base::Optional<media_session::MediaPosition>& position) { if (!position.has_value()) { LOG(ERROR) << __func__ << "media position value is not available."; return; } base::TimeDelta new_duration = position->duration(); base::TimeDelta new_position = position->GetPosition(); SetMediaPositionInternal(new_position); if (duration_ == new_duration) return; duration_ = new_duration; SetMetadataPropertyInternal(kMediaMetaDataTotalDuration, base::NumberToString16(duration_.InSecondsF())); } bool SystemMediaControlsWebOS::RegisterMediaSession( const std::string& session_id) { if (session_id.empty()) { LOG(ERROR) << __func__ << "Invalid session id."; return false; } Json::Value register_root; register_root[kMediaId] = session_id; register_root[kAppId] = application_id_; register_root[kSubscribe] = true; Json::FastWriter register_writer; std::string register_paylaod = register_writer.write(register_root); LOG(INFO) << __func__ << " payload: " << register_paylaod; luna_service_client_->Subscribe( base::LunaServiceClient::GetServiceURI( base::LunaServiceClient::URIType::MEDIACONTROLLER, kRegisterMediaSession), register_paylaod, &subscribe_key_, BIND_TO_CURRENT_LOOP(&SystemMediaControlsWebOS::HandleMediaKeyEvent)); registered_ = true; return true; } void SystemMediaControlsWebOS::UnregisterMediaSession() { if (!registered_) { LOG(ERROR) << __func__ << " Session is already unregistered."; return; } if (session_id_.empty()) { LOG(ERROR) << __func__ << " No registered session."; return; } Json::Value unregister_root; unregister_root[kMediaId] = session_id_; Json::FastWriter unregister_writer; std::string unregister_payload = unregister_writer.write(unregister_root); VLOG(1) << __func__ << " payload: " << unregister_payload; luna_service_client_->CallAsync( base::LunaServiceClient::GetServiceURI( base::LunaServiceClient::URIType::MEDIACONTROLLER, kUnregisterMediaSession), unregister_payload, BIND_TO_CURRENT_LOOP(&SystemMediaControlsWebOS::CheckReplyStatusMessage)); luna_service_client_->Unsubscribe(subscribe_key_); registered_ = false; session_id_ = std::string(); } bool SystemMediaControlsWebOS::ActivateMediaSession( const std::string& session_id) { if (session_id.empty()) { LOG(ERROR) << __func__ << "Invalid session id."; return false; } Json::Value activate_root; activate_root[kMediaId] = session_id; Json::FastWriter activate_writer; std::string activate_paylaod = activate_writer.write(activate_root); VLOG(1) << __func__ << " payload: " << activate_paylaod; luna_service_client_->CallAsync( base::LunaServiceClient::GetServiceURI( base::LunaServiceClient::URIType::MEDIACONTROLLER, kActivateMediaSession), activate_paylaod, BIND_TO_CURRENT_LOOP(&SystemMediaControlsWebOS::CheckReplyStatusMessage)); return true; } void SystemMediaControlsWebOS::DeactivateMediaSession() { if (session_id_.empty()) { LOG(ERROR) << __func__ << " No active session."; return; } Json::Value deactivate_root; deactivate_root[kMediaId] = session_id_; Json::FastWriter deactivate_writer; std::string deactivate_payload = deactivate_writer.write(deactivate_root); VLOG(1) << __func__ << " payload: " << deactivate_payload; luna_service_client_->CallAsync( base::LunaServiceClient::GetServiceURI( base::LunaServiceClient::URIType::MEDIACONTROLLER, kDeactivateMediaSession), deactivate_payload, BIND_TO_CURRENT_LOOP(&SystemMediaControlsWebOS::CheckReplyStatusMessage)); } void SystemMediaControlsWebOS::SetPlaybackStatusInternal( const std::string& play_status) { Json::Value playstatus_root; playstatus_root[kMediaId] = session_id_; playstatus_root[kMediaPlayStatus] = play_status; Json::FastWriter playstatus_writer; std::string playstatus_paylaod = playstatus_writer.write(playstatus_root); VLOG(1) << __func__ << " payload: " << playstatus_paylaod; luna_service_client_->CallAsync( base::LunaServiceClient::GetServiceURI( base::LunaServiceClient::URIType::MEDIACONTROLLER, kSetMediaPlayStatus), playstatus_paylaod, BIND_TO_CURRENT_LOOP(&SystemMediaControlsWebOS::CheckReplyStatusMessage)); } void SystemMediaControlsWebOS::SetMetadataPropertyInternal( const std::string& property, const base::string16& value) { Json::Value metadata; metadata[property] = base::UTF16ToUTF8(value); Json::Value metadata_root; metadata_root[kMediaId] = session_id_; metadata_root[kMediaMetaData] = metadata; Json::FastWriter metadata_writer; std::string metadata_paylaod = metadata_writer.write(metadata_root); VLOG(1) << __func__ << " payload: " << metadata_paylaod; luna_service_client_->CallAsync( base::LunaServiceClient::GetServiceURI( base::LunaServiceClient::URIType::MEDIACONTROLLER, kSetMediaMetaData), metadata_paylaod, BIND_TO_CURRENT_LOOP(&SystemMediaControlsWebOS::CheckReplyStatusMessage)); } void SystemMediaControlsWebOS::SetMediaPositionInternal( const base::TimeDelta& position) { if (session_id_.empty()) { LOG(ERROR) << __func__ << " No active session."; return; } Json::Value playposition_root; playposition_root[kMediaId] = session_id_; playposition_root[kMediaPlayPosition] = std::to_string(position.InSecondsF()); Json::FastWriter playposition_writer; std::string playposition_payload = playposition_writer.write(playposition_root); VLOG(1) << __func__ << " playposition_payload: " << playposition_payload; luna_service_client_->CallAsync( base::LunaServiceClient::GetServiceURI( base::LunaServiceClient::URIType::MEDIACONTROLLER, kSetMediaPlayPosition), playposition_payload, BIND_TO_CURRENT_LOOP( &SystemMediaControlsWebOS::CheckReplyStatusMessage)); } void SystemMediaControlsWebOS::HandleMediaKeyEvent(const std::string& payload) { VLOG(1) << __func__ << " payload: " << payload; Json::Value response; Json::Reader reader; if (reader.parse(payload, response) && response.isMember(kReturnValue) && response[kReturnValue].asBool() && response.isMember(kSubscribed) && response[kSubscribed].asBool()) { if (response.isMember(kKeyEvent)) { HandleMediaKeyEventInternal(response[kKeyEvent].asString()); } else { if (service_ready_status_ == ServiceReadyStatus::kPending) { for (SystemMediaControlsObserver& obs : observers_) obs.OnServiceReady(); service_ready_status_ == ServiceReadyStatus::kCompleted; } LOG(INFO) << __func__ << " Successfully Registered with MCS, session_id: " << session_id_; } } else { LOG(ERROR) << " Failed to Register with MCS, session_id: " << session_id_; } } void SystemMediaControlsWebOS::CheckReplyStatusMessage( const std::string& message) { Json::Value response; Json::Reader reader; if (!(reader.parse(message, response) && response.isMember(kReturnValue) && response[kReturnValue].asBool())) { LOG(ERROR) << __func__ << " MCS call Failed. message: " << message << " session_id: " << session_id_; } else { VLOG(1) << __func__ << " MCS call Success. message: " << message << " session_id: " << session_id_; } } std::string SystemMediaControlsWebOS::GetAppIdFromSession( const base::UnguessableToken& request_id) { content::WebContents* web_contents = content::MediaSession::GetWebContentsFromRequestId(request_id); if (web_contents) { blink::mojom::RendererPreferences* renderer_prefs = web_contents->GetMutableRendererPrefs(); if (renderer_prefs) return renderer_prefs->application_id; } return std::string(); } void SystemMediaControlsWebOS::HandleMediaKeyEventInternal( const std::string& key_event) { VLOG(1) << __func__ << " key_event: " << key_event; static std::map<std::string, MediaKeyEvent> kEventKeyMap = { {kPlayEvent, SystemMediaControlsWebOS::MediaKeyEvent::kPlay}, {kPauseEvent, SystemMediaControlsWebOS::MediaKeyEvent::kPause}, {kNextEvent, SystemMediaControlsWebOS::MediaKeyEvent::kNext}, {kPreviousEvent, SystemMediaControlsWebOS::MediaKeyEvent::kPrevious}, {kMuteEvent, SystemMediaControlsWebOS::MediaKeyEvent::kMute}, {kUnmuteEvent, SystemMediaControlsWebOS::MediaKeyEvent::kUnmute} }; auto get_event_type = [&](const std::string& key) { std::map<std::string, MediaKeyEvent>::iterator it; it = kEventKeyMap.find(key); if (it != kEventKeyMap.end()) return it->second; return SystemMediaControlsWebOS::MediaKeyEvent::kUnsupported; }; MediaKeyEvent event_type = get_event_type(key_event); for (SystemMediaControlsObserver& obs : observers_) { switch (event_type) { case SystemMediaControlsWebOS::MediaKeyEvent::kPlay: obs.OnPlay(); break; case SystemMediaControlsWebOS::MediaKeyEvent::kPause: obs.OnPause(); break; case SystemMediaControlsWebOS::MediaKeyEvent::kNext: obs.OnNext(); break; case SystemMediaControlsWebOS::MediaKeyEvent::kPrevious: obs.OnPrevious(); break; case SystemMediaControlsWebOS::MediaKeyEvent::kMute: obs.OnMuteStateChanged(true); break; case SystemMediaControlsWebOS::MediaKeyEvent::kUnmute: obs.OnMuteStateChanged(false); break; default: NOTREACHED() << " key_event: " << key_event << " Not Handled !!!"; break; } } } } // namespace internal } // namespace system_media_controls
19e73417f1c5c552f500bc681017d5969a171918
0454cd70885ae579312f318d6a2239ec5aadcf74
/rpn-calc/src/test.cpp
d3e777b9da39788e7de5a217fdb7217e84f9066c
[]
no_license
xfbs/rpn
3bff19183831ec32f2331691edb6dee415c182f6
37246ca926b91f92880f58dab8353b99485ff5e1
refs/heads/master
2020-07-23T22:22:40.158775
2019-09-25T08:16:58
2019-09-25T08:16:58
207,723,655
0
0
null
null
null
null
UTF-8
C++
false
false
1,486
cpp
test.cpp
#include "calc.h" #include <cassert> #include <cmath> #include <iostream> void test_parse(); void test_execute(); int main(int argc, char *argv[]) { std::deque<double> state; test_parse(); test_execute(); std::cout << "ok" << std::endl; return EXIT_SUCCESS; } template<typename T> void assert_type(std::string str) { Command *cmd = Command::parse(str); if(dynamic_cast<T *>(cmd) == nullptr) { std::cout << "error: string '" << str << "' does not map to type " << typeid(T).name() << "." << std::endl; exit(EXIT_FAILURE); } delete cmd; } void assert_result(double result, size_t num, ...) { va_list args; va_start(args, num); std::deque<double> state; for(size_t pos = 0; pos < num; pos++) { const char *arg = va_arg(args, const char *); Command *cmd = Command::parse(arg); cmd->execute(state); } assert(state.size() == 1); if(std::isnan(result)) { assert(std::isnan(state.at(0))); } else { assert(state.at(0) == result); } } void test_parse() { assert_type<Add>("+"); assert_type<Sub>("-"); assert_type<Mul>("*"); assert_type<Div>("/"); assert_type<Number>("0"); assert_type<Number>("0.5"); assert_type<Number>("nan"); } void test_execute() { assert_result(1.0, 1, "1"); assert_result(1.5, 1, "1.5"); assert_result(NAN, 1, "nan"); }
c3bb9ebc816cd4ef1461c6acc68365d63df37246
9b9d9e1de5d4dc6d0b8420f8113f6ac8077b8193
/misc/lab4_2.cpp
5c93ff42552ff5947f8c657e3003a57dcda9de53
[]
no_license
rohangoel96/data-structures-algorithms
3e367f38e55f1119d81fd45efed2f390cdccb82a
fb4fc7950c75cb86f5704cc311f87de012380f03
refs/heads/master
2020-04-09T10:38:50.084093
2016-04-24T04:43:24
2016-04-24T04:43:24
52,091,893
1
0
null
null
null
null
UTF-8
C++
false
false
1,928
cpp
lab4_2.cpp
#include <iostream> using namespace std; long long int findClosestSocket(long long int *working_sockets, long long int n, long long int allotted_index, long long int l){ long long int low = 0; long long int high = n; long long int mid = (low+high)/2; long long int ans_index; long long int low_to_alloted=0,high_to_alloted=n; while(low<high){ mid = (low+high)/2; if (working_sockets[mid]==allotted_index) { ans_index = mid; return mid; break; } else if(allotted_index>working_sockets[mid]){ low = mid+1; } else{ high = mid-1; } } low_to_alloted = low; high_to_alloted = low+1; // cout << high<< " " << low<<n<<endl; if (low<n && low > -1) { if (high==-1) { if (working_sockets[0] - allotted_index<=l) return 0; else return -1; } long long int length_to_left = allotted_index - working_sockets[low_to_alloted]; long long int length_to_right = working_sockets[high_to_alloted] - allotted_index; if (length_to_left <= l || length_to_right <= l) { if (length_to_right<length_to_left) { ans_index = high_to_alloted; } else{ ans_index = low_to_alloted; } } else{ ans_index = -1; } } else{ if (low>=n) { long long int length_to_left = allotted_index - working_sockets[n-1]; // cout <<length_to_left<<endl; if (length_to_left <= l) { ans_index = n-1; } else{ ans_index = -1; } } } return ans_index; } int main() { long long int n,q,assigned,length; double temp_length; cin>>n>>q; long long int working[n]; for (long long int i = 0; i < n; ++i){cin>>working[i];} for (long long int i = 0; i < q; ++i){ cin>>assigned>>temp_length; length = (long long int) temp_length /2; long long int a = findClosestSocket(working,n,assigned,length); if (a!=-1) { cout<<working[a]<<endl; } else cout<<-1<<endl; } }
0ec3c8a3ae94e4ff75e7b89b1015a01ff4c42c7f
da7cda3b3a6f3265c792b43f09c0596a8b18cd2e
/sample/Windows-QT/src/mainwindow.cpp
02fa5cdc67a73391224c7941fa1101738ad9dfb8
[]
no_license
dborota/Onboard-SDK
0a498591e98e38c3fa1fc9a6a88f574e7852c635
a2c5ea4b21c37e02bc430df190c87304770df1ef
refs/heads/master
2021-01-22T01:38:21.481416
2015-11-25T04:10:48
2015-11-25T04:10:48
47,061,782
1
0
null
2015-11-29T11:58:27
2015-11-29T11:58:26
null
UTF-8
C++
false
false
11,856
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <stdint.h> #include <QSerialPortInfo> #include <QtSerialPort/QSerialPort> #include <QDebug> #include <QMessageBox> #include <QTimer> #include "about.h" #include <QSettings> #include <QFile> #include <QFileDialog> #include <QByteArray> #include "DJI_Pro_Sample.h" MainWindow *MainWindow::mainwindow_object = (MainWindow*)NULL; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); time = new QTimer(this); TakeoffDelay = new QTimer(this); keybuf = new QByteArray(DEFAULT_KEY); foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { qDebug() <<"Name : "<<info.portName().toStdString().data(); qDebug() <<"Description : "<<info.description().toStdString().data(); qDebug() <<"Manufacturer: "<<info.manufacturer().toStdString().data(); // Example use QSerialPort ui->serial_comboBox->addItem(info.portName()); printf(" \n"); } ui->btn_open_serialport->setText(OPEN_SERIAL); ui->btn_nav_open_close->setText(NAV_OPEN); connect(time, SIGNAL(timeout()), this, SLOT(Timeout_handle())); connect(TakeoffDelay, SIGNAL(timeout()), this, SLOT(TakeoffDelay_handle())); connect(ui->actionAbout, SIGNAL(triggered()),this, SLOT(btn_About())); connect(this,SIGNAL(recv_data_signal(QByteArray)),this,SLOT(recv_data(QByteArray))); time->start(50); QFile *f = new QFile("Setting.ini"); if(f->open(QIODevice::ReadOnly | QIODevice::Text)) { f->close(); QSettings *configIni = new QSettings(SETTING_FILENAMES, QSettings::IniFormat); int sum = configIni->value("Check",0).toInt(); if(Get_Check(configIni) != sum || 0 == sum) { Set_Default_Ini(); } delete configIni; } else { Set_Default_Ini(); } delete f; Read_Setting(); DJI_Pro_Register_Transparent_Transmission_Callback(MainWindow_Transparent_Transmission_Callback); } MainWindow::~MainWindow() { delete ui; } MainWindow* MainWindow::Create_Instance(void) { if(mainwindow_object == (MainWindow*)NULL) { mainwindow_object = new MainWindow; } return mainwindow_object; } MainWindow* MainWindow::Get_Instance(void) { return Create_Instance(); } void MainWindow::MainWindow_Activate_Callback(unsigned short res) { char result[][50]={{"SDK_ACTIVATION_SUCCESS"},{"SDK_ACTIVE_PARAM_ERROR"},{"SDK_ACTIVE_DATA_ENC_ERROR"},\ {"SDK_ACTIVE_NEW_DEVICE"},{"SDK_ACTIVE_DJI_APP_NOT_CONNECT"},{" SDK_ACTIVE_DIJ_APP_NO_INTERNET"},\ {"SDK_ACTIVE_SERVER_REFUSED"},{"SDK_ACTIVE_LEVEL_ERROR"},{"SDK_ACTIVE_SDK_VERSION_ERROR"}}; if(res >= 0 && res < 9) { MainWindow::Get_Instance()->ui->label_Activation_Status->setText(*(result+res)); } else { MainWindow::Get_Instance()->ui->label_Activation_Status->setText("Unkown ERROR"); } } void MainWindow::on_BtnActivation_clicked() { user_act_data.app_id = ui->AppID->text().toInt(); user_act_data.app_api_level = ui->AppLevel->currentText().toInt(); user_act_data.app_ver = SDK_VERSION; user_act_data.app_bundle_id[0] = user_act_data.app_bundle_id[1] = 0x12; *keybuf = ui->AppKey->text().toLocal8Bit(); user_act_data.app_key = keybuf->data(); Save_Setting(); ui->label_Activation_Status->setText("Activating,Waiting..."); DJI_Pro_Activate_API(&user_act_data,MainWindow::MainWindow_Activate_Callback); } void MainWindow::on_btn_open_serialport_clicked() { DJI_Pro_Hw *hw_instance = DJI_Pro_Hw::Pro_Hw_Get_Instance(); if(OPEN_SERIAL == ui->btn_open_serialport->text()) { if(true == hw_instance->Pro_Hw_Setup(ui->serial_comboBox->currentText(),\ ui->baud_comboBox->currentText().toInt())) { hw_instance->start(); //QMessageBox::information(this, tr(" "), "Port Open Succeed", QMessageBox::Ok); ui->btn_open_serialport->setIcon(QIcon(":/icon/Images/ok.png")); ui->btn_open_serialport->setText(CLOSE_SERIAL); } else { //QMessageBox::warning(this, tr("Warning"), "Port Open Failed", QMessageBox::Ok); ui->btn_open_serialport->setIcon(QIcon(":/icon/Images/err.png")); } } else if(CLOSE_SERIAL == ui->btn_open_serialport->text()) { hw_instance->Pro_Hw_Close(); ui->btn_open_serialport->setText(OPEN_SERIAL); ui->btn_open_serialport->setIcon(QIcon(":/icon/Images/err.png")); } } void MainWindow::on_btn_nav_open_close_clicked() { if(NAV_OPEN == ui->btn_nav_open_close->text()) { DJI_Pro_Control_Management(1,NULL); ui->btn_nav_open_close->setText(NAV_CLOSE); } else { DJI_Pro_Control_Management(0,NULL); ui->btn_nav_open_close->setText(NAV_OPEN); } } void MainWindow::on_btn_Takeoff_clicked() { DJI_Pro_Status_Ctrl(4,0); ui->btn_Takeoff->setEnabled(false); ui->btn_Landing->setEnabled(false); TakeoffDelay->start(10*1000); } void MainWindow::on_btn_Landing_clicked() { DJI_Pro_Status_Ctrl(6,0); ui->btn_Takeoff->setEnabled(false); ui->btn_Landing->setEnabled(false); TakeoffDelay->start(10*1000); } void MainWindow::on_btn_GoHome_clicked() { DJI_Pro_Status_Ctrl(1,0); } void MainWindow::on_btn_update_com_clicked() { ui->serial_comboBox->clear(); foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { qDebug() << "Name : " << info.portName(); qDebug() << "Description : " << info.description(); qDebug() << "Manufacturer: " << info.manufacturer(); // Example use QSerialPort ui->serial_comboBox->addItem(info.portName()); qDebug()<<"\n"; } } void MainWindow::Timeout_handle() { static int count0 = 0; static int count1 = 0; unsigned char bat = 0; api_ctrl_info_data_t ctrl_info; char info[][32]={{"Remote controller"}, {"Mobile device"}, {"Onboard device"}, }; statusBar()->showMessage( tr("RX: %1").arg(DJI_Pro_Hw::Pro_Hw_Get_Instance()->load_con)); /* refresh battery capacity per second */ if(++ count0 == 20) { QString str; DJI_Pro_Get_Bat_Capacity(&bat); str.setNum((uint)bat); str += '%'; ui->label_Battery_Capacity->setText(str); count0 = 0; } /* refresh ctrl info per 500ms */ if(++ count1 == 10) { DJI_Pro_Get_CtrlInfo(&ctrl_info); ui->label_Control_Device->setText(*(info + ctrl_info.cur_ctrl_dev_in_navi_mode)); count1 = 0; } } void MainWindow::TakeoffDelay_handle() { TakeoffDelay->stop(); ui->btn_Takeoff->setEnabled(true); ui->btn_Landing->setEnabled(true); } void MainWindow::btn_About() { About about; about.exec(); } int MainWindow::Get_Check(QSettings *set) { QStringList keys = set->allKeys(); int sum = 0; QString str; keys.removeOne("Check"); foreach (str, keys) { int i=0,len = 0; len = set->value(str,-1).toString().size(); for(i=0; i<len; i++) { sum += (int)set->value(str,-1).toByteArray().at(i); } } return sum; } void MainWindow::Set_Default_Ini() { QSettings *configIni = new QSettings(SETTING_FILENAMES, QSettings::IniFormat); configIni->beginGroup("user"); configIni->setValue("AppID", 10086); configIni->setValue("Key",DEFAULT_KEY); configIni->setValue("ApiLevel", 2); configIni->endGroup(); configIni->setValue("Check",Get_Check(configIni)); delete configIni; Read_Setting(); } void MainWindow::Read_Setting() { QSettings *configIni = new QSettings(SETTING_FILENAMES, QSettings::IniFormat); int sum = configIni->value("Check",0).toInt(); if(Get_Check(configIni) == sum) { configIni->beginGroup("user"); ui->AppID->setText(configIni->value("AppID").toString()); ui->AppKey->setText(configIni->value("Key").toString()); ui->AppLevel->setCurrentIndex(ui->AppLevel->findText(configIni->value("ApiLevel").toString())); configIni->endGroup(); } else { printf("%s,SettingFile Err\n", __func__); Set_Default_Ini(); } } void MainWindow::Save_Setting() { QSettings *configIni = new QSettings(SETTING_FILENAMES, QSettings::IniFormat); configIni->beginGroup("user"); configIni->setValue("AppID", user_act_data.app_id); configIni->setValue("Key",user_act_data.app_key); configIni->setValue("ApiLevel", user_act_data.app_api_level); configIni->endGroup(); configIni->setValue("Check",Get_Check(configIni)); delete configIni; } void MainWindow::on_btn_gimbal_ctrl_clicked() { if(DJI_Sample_Gimbal_Ctrl()< 0) { QMessageBox::warning(this,tr("Warning"),tr("Please waiting current sample finish"),QMessageBox::Ok); } } void MainWindow::on_btn_atti_ctrl_clicked() { int ret = QMessageBox::warning(this, tr("Warning"), tr("Attention for flight safety.\n" "Make sure you are in a wide area if you are not using simulator."), QMessageBox::Ok | QMessageBox::Cancel); if(QMessageBox::Ok == ret) { if(DJI_Sample_Atti_Ctrl() < 0) { QMessageBox::warning(this,tr("Warning"),tr("Please waiting current sample finish"),QMessageBox::Ok); } } if(QMessageBox::Cancel == ret) { } } void MainWindow::on_btn_capture_clicked() { DJI_Sample_Camera_Shot(); printf("Take a picture\n"); } void MainWindow::on_btn_start_video_clicked() { DJI_Sample_Camera_Video_Start(); ui->btn_start_video->setDown(true); printf("Start video\n"); } void MainWindow::on_btn_stop_video_clicked() { DJI_Sample_Camera_Video_Stop(); ui->btn_start_video->setDown(false); printf("Stop video\n"); } void MainWindow::on_btn_draw_circle_clicked() { if(DJI_Sample_Funny_Ctrl(DRAW_CIRCLE_SAMPLE) < 0) { QMessageBox::warning(this,tr("Warning"),tr("Please waiting current sample finish"),QMessageBox::Ok); } else { printf("Start to draw circle\n"); } } void MainWindow::on_btn_draw_square_clicked() { if(DJI_Sample_Funny_Ctrl(DRAW_SQUARE_SAMPLE) < 0 ) { QMessageBox::warning(this,tr("Warning"),tr("Please waiting current sample finish"),QMessageBox::Ok); } else { printf("Start to draw square\n"); } } void MainWindow::on_btn_way_point_clicked() { if(DJI_Sample_Funny_Ctrl(WAY_POINT_SAMPLE) < 0 ) { QMessageBox::warning(this,tr("Warning"),tr("Please waiting current sample finish"),QMessageBox::Ok); } else { printf("Start to way point sample\n"); } } void MainWindow::recv_data(QByteArray data) { ui->TB_Recv->insertPlainText(data); } void MainWindow::MainWindow_Transparent_Transmission_Callback(unsigned char *buf,unsigned char len) { QByteArray byte_array; byte_array.append((const char*)buf,len); emit MainWindow::Get_Instance()->recv_data_signal(byte_array); } void MainWindow::on_btn_Send_clicked() { QString string = ui->plainTextEdit_Send->toPlainText(); unsigned char *data; QByteArray byte_array; byte_array = string.toLatin1(); data = (unsigned char*)byte_array.data(); DJI_Pro_Send_To_Mobile_Device(data,byte_array.length(),0); } void MainWindow::on_btn_Clear_clicked() { ui->TB_Recv->clear(); ui->plainTextEdit_Send->clear(); }
249c17089005a6e1c1ee016eeea299f99c0b4e92
bb813d550b7dd9a1c0c49ea2908d05ce50ede21a
/localconnectivityservice/obexsendservices/obexservicesendutils/src/BTSBIPController.cpp
ae1e800adf24bc82e573f64a3ee0ae5750a7f52c
[]
no_license
SymbianSource/oss.FCL.sf.mw.shortlinkconn
c0c38a5660b69f5367a2d77b21651782d06a6e1a
39618d5dc6d43cee9c38a3ee08c9716c21c2a8a8
refs/heads/master
2021-01-12T10:45:30.329969
2010-05-17T08:02:52
2010-05-17T08:02:52
72,676,078
0
0
null
null
null
null
UTF-8
C++
false
false
22,549
cpp
BTSBIPController.cpp
/* * Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Image push implementation * */ // INCLUDE FILES #include "BTSBIPController.h" #include "BTSUDebug.h" #include "BTSUImageConverter.h" #include "BTSUXmlParser.h" #include <Obexutils.rsg> // CONSTANTS // image push target header _LIT8( KBIPImagePushID, "\xE3\x3D\x95\x45\x83\x74\x4A\xD7\x9E\xC5\xC1\x6B\xE3\x1E\xDE\x8E" ); // type headers _LIT8( KBTSBIPCapabilities, "x-bt/img-capabilities\0"); _LIT8( KBTSBIPImageType, "x-bt/img-img\0"); _LIT8( KBTSBIPThmType, "x-bt/img-thm\0"); // imageBTS descriptor _LIT8( KBTSBIPDescriptorStart, "<image-descriptor version=\"1.0\">\r" ); _LIT8( KBTSBIPDescriptorEncoding, "<image encoding=\"" ); _LIT8( KBTSBIPDescriptorPixel, "\" pixel=\"" ); _LIT8( KBTSBIPDescriptorSize, "\" size=\"" ); _LIT8( KBTSBIPDescriptorEnd, "\"/>\r</image-descriptor>" ); // temp file path for capabilities object //temp file path drive letter _LIT(KBTSBIPTempPathDrive,"c:"); const TInt KBTSUMaxPathLenght=256; const TInt KBTSUMaxPrivatePathLenght=20; // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CBTSBIPController::CBTSBIPController // C++ default constructor can NOT contain any code, that // might leave. // ----------------------------------------------------------------------------- // CBTSBIPController::CBTSBIPController( MBTServiceObserver* aObserver, CBTServiceParameterList* aList ) : iListPtr( aList ), iObserverPtr( aObserver ) { } // ----------------------------------------------------------------------------- // CBTSBIPController::ConstructL // Symbian 2nd phase constructor can leave. // ----------------------------------------------------------------------------- // void CBTSBIPController::ConstructL( const TUint aRemotePort, const TBTDevAddr& aRemoteDeviceAddr ) { FLOG(_L("[BTSU]\t CBTSBIPController::ConstructL()")); // Add image push target header // CObexHeader* header = CObexHeader::NewL(); CleanupStack::PushL( header ); header->SetByteSeqL( KBTSUTargetHeader, KBIPImagePushID ); RArray<CObexHeader*> headerList; CleanupClosePushL( headerList ); headerList.Append( header ); CreateClientL ( this, aRemoteDeviceAddr, aRemotePort, headerList ); CleanupStack::Pop( 2 ); //header, headerlist headerList.Close(); FLOG(_L("[BTSU]\t CBTSBIPController::ConstructL() completed")); } // ----------------------------------------------------------------------------- // CBTSBIPController::NewL // Two-phased constructor. // ----------------------------------------------------------------------------- // CBTSBIPController* CBTSBIPController::NewL( MBTServiceObserver* aObserver, const TUint aRemotePort, const TBTDevAddr& aRemoteDeviceAddr, CBTServiceParameterList* aList ) { CBTSBIPController* self = new( ELeave ) CBTSBIPController( aObserver, aList ); CleanupStack::PushL( self ); self->ConstructL( aRemotePort, aRemoteDeviceAddr ); CleanupStack::Pop(self); return self; } // Destructor CBTSBIPController::~CBTSBIPController() { DeleteTempFile( iThumbnailFileName ); } // ----------------------------------------------------------------------------- // CBTSBIPController::ConnectCompleted // ----------------------------------------------------------------------------- // void CBTSBIPController::ConnectCompleted( TInt aStatus ) { FLOG(_L("[BTSU]\t CBTSBIPController::ConnectCompleted()")); if ( aStatus == KErrNone ) { iFileIndex = 0; // get remote device capabilities // TRAPD( error, GetL() ); if ( error != KErrNone ) { iObserverPtr->ControllerComplete( EBTSGettingFailed ); } } else { //Error on Obex level // iObserverPtr->ControllerComplete( EBTSConnectingFailed ); } FLOG(_L("[BTSU]\t CBTSBIPController::ConnectCompleted() completed")); } // ----------------------------------------------------------------------------- // CBTSBIPController::ClientConnectionClosed // ----------------------------------------------------------------------------- // void CBTSBIPController::ClientConnectionClosed() { FLOG(_L("[BTSU]\t CBTSBIPController::ClientConnectionClosed()")); // Everything ready, stop service // iObserverPtr->ControllerComplete( EBTSNoError ); FLOG(_L("[BTSU]\t CBTSBIPController::ClientConnectionClosed() completed")); } // ----------------------------------------------------------------------------- // CBTSBIPController::PutCompleted // ----------------------------------------------------------------------------- // void CBTSBIPController::PutCompleted( TInt aStatus, const CObexHeaderSet* aPutResponse ) { FLOG(_L("[BTSU]\t CBTSBIPController::PutCompleted()")); // Remove temporary thumbnail file // DeleteTempFile( iThumbnailFileName ); if ( aStatus == KErrNone ) { iFileIndex++; // Send was ok. Start sending next image // TRAPD( error, SendL() ); if ( error ) { FTRACE(FPrint(_L("[BTSU]\t CBTSBPPController::Send leaved with %d"), error )); iObserverPtr->ControllerComplete( EBTSPuttingFailed); } } else if ( aStatus == KErrIrObexRespPartialContent ) { // Remote device has requested a thumbnail image // TRAPD( error, SendThumbnailL(aPutResponse ) ); if ( error ) { FTRACE(FPrint(_L("[BTSU]\t CBTSBPPController::Send thumbnail leaved with %d"), error )); iObserverPtr->ControllerComplete( EBTSPuttingFailed ); } } else { // Some error on Obex level // iObserverPtr->ControllerComplete( EBTSPuttingFailed); } FLOG(_L("[BTSU]\t CBTSBIPController::PutCompleted() done")); } // ----------------------------------------------------------------------------- // CBTSBIPController::GetCompleted // ----------------------------------------------------------------------------- // void CBTSBIPController::GetCompleted( TInt aStatus, CObexBufObject* aGetResponse ) { FLOG(_L("[BTSU]\t CBTSBIPController::GetCompleted()")); if ( aStatus == KErrAbort ) { // Connection is cancelled // iObserverPtr->ControllerComplete( EBTSGettingFailed ); } else if ( aStatus == KErrNone ) { TRAPD( error, HandleGetCompleteIndicationL( aGetResponse ) ); if ( error != KErrNone ) { DeleteTempFile( iTempFileName ); // Error on capability handling // iObserverPtr->ControllerComplete( EBTSGettingFailed ); } } else if( aStatus != KErrAbort && aGetResponse->BytesReceived()==0 ) { TRAPD( error,iObserverPtr->LaunchProgressNoteL( iClient, iListPtr->ImageListSize(),iListPtr->ImageCount() ) ); error=KErrNone; TRAP(error, SendL() ); if ( error != KErrNone ) { iObserverPtr->ControllerComplete( EBTSPuttingFailed ); } } else if ( aStatus != KErrNone && aGetResponse->BytesReceived()>0 ) { // Error on Obex level // iObserverPtr->ControllerComplete( EBTSGettingFailed ); } FLOG(_L("[BTSU]\t CBTSBIPController::GetCompleted() done")); } // ----------------------------------------------------------------------------- // CBTSBIPController::SendL // ----------------------------------------------------------------------------- // void CBTSBIPController::SendL() { FLOG(_L("[BTSU]\t CBTSBIPController::SendL()")); if ( iListPtr->ImageCount() > 0 && iFileIndex < iListPtr->ImageCount()) { RArray<CObexHeader*> headerList; CleanupClosePushL( headerList ); // Add Type header // CObexHeader* typeHeader = CObexHeader::NewL(); CleanupStack::PushL( typeHeader ); typeHeader->SetByteSeqL( KBTSUTypeHeader, KBTSBIPImageType ); headerList.Append( typeHeader ); // Add image descriptor // HBufC8* imagedescriptor = CreateImageDescriptorL( ); CleanupStack::PushL( imagedescriptor ); CObexHeader* imageDescriptorHeader = CObexHeader::NewL(); CleanupStack::PushL( imageDescriptorHeader ); imageDescriptorHeader->SetByteSeqL( KBTSUImgDescriptorHeader, imagedescriptor->Des() ); headerList.Append( imageDescriptorHeader ); // Send image // TBTSUImageParam imageparam = iListPtr->ImageAtL( iFileIndex ); RBuf filename; filename.CreateL(256); CleanupClosePushL(filename); imageparam.iFile.Name(filename); iObserverPtr->UpdateProgressNoteL(imageparam.iFileSize,iFileIndex,filename); CleanupStack::PopAndDestroy(&filename); iListPtr->MarkAsSendL(iFileIndex); iClient->PutObjectL( headerList, imageparam.iFile ); CleanupStack::Pop(4); // headerList, imageDescriptorHeader, typeHeader, imagedescriptor delete imagedescriptor; headerList.Close(); } else { FLOG(_L("[BTSU]\t CBTSBIPController::SendL() all images sent, closing connection")); // All images sent, close client connection. // iClient->CloseClientConnection(); } FLOG(_L("[BTSU]\t CBTSBIPController::SendL() completed")); } // ----------------------------------------------------------------------------- // CBTSBIPController::GetL // ----------------------------------------------------------------------------- // void CBTSBIPController::GetL() { FLOG(_L("[BTSU]\t CBTSBIPController::GetL()")); RArray<CObexHeader*> headerList; CleanupClosePushL(headerList); // Add capabilities type header // CObexHeader* typeHeader = CObexHeader::NewL(); CleanupStack::PushL( typeHeader ); typeHeader->SetByteSeqL( KBTSUTypeHeader, KBTSBIPCapabilities ); headerList.Append( typeHeader ); // Get capabilities object from remote device // iClient->GetObjectL( headerList ); CleanupStack::Pop(2); // headerList, typeHeader headerList.Close(); } // ----------------------------------------------------------------------------- // CBTSBIPController::SendThumbnailL // ----------------------------------------------------------------------------- // void CBTSBIPController::SendThumbnailL( const CObexHeaderSet *aPutResponse ) { FLOG(_L("[BTSU]\t CBTSBIPController::SendThumbnail()")); // Create thumbnail for sending // Delete the created thumbnail on PutComplete // // Fill header array // RArray<CObexHeader*> headerList; CleanupClosePushL(headerList); // Add ImageHandle header // CObexHeader* imageHandleHeader = CObexHeader::NewL(); CleanupStack::PushL( imageHandleHeader ); aPutResponse->First(); User::LeaveIfError(aPutResponse->Find(KBTSUImageHandleHeader, *imageHandleHeader ) ); headerList.Append( imageHandleHeader ); // Add Type header // CObexHeader* typeHeader = CObexHeader::NewL(); CleanupStack::PushL( typeHeader ); typeHeader->SetByteSeqL( KBTSUTypeHeader, KBTSBIPThmType ); headerList.Append( typeHeader ); CreateTempFileL( iThumbnailFileName ); CBTSUImageConverter* imageConverter = CBTSUImageConverter::NewL(); CleanupStack::PushL( imageConverter ); TBTSUImageParam imgparam = iListPtr->ImageAtL( iFileIndex ); imageConverter->CreateThumbnailL(imgparam.iFile, iThumbnailFileName ); CleanupStack::PopAndDestroy(imageConverter); // Add Name header // TParse parse; User::LeaveIfError( parse.Set( iThumbnailFileName, NULL, NULL ) ); CObexHeader* nameHeader = CObexHeader::NewL(); CleanupStack::PushL( nameHeader ); nameHeader->SetUnicodeL( KBTSUNameHeader, parse.NameAndExt() ); headerList.Append( nameHeader ); // send thumbnail // iClient->PutObjectL( headerList, iThumbnailFileName ); // Cleanup // CleanupStack::Pop(4); // headerList, imageHandleHeader, typeHeader, nameHeader headerList.Close(); } // ----------------------------------------------------------------------------- // CBTSBIPController::CreateTempFileL // ----------------------------------------------------------------------------- // void CBTSBIPController::CreateTempFileL( TFileName& aFileName ) { FLOG(_L("[BTSU]\t CBTSBIPController::CreateTempFileL()")); RFs fileSession; RFile file; TBuf<KBTSUMaxPrivatePathLenght> privatepath; TBuf<KBTSUMaxPathLenght> tempPath; User::LeaveIfError( fileSession.Connect() ); CleanupClosePushL( fileSession ); User::LeaveIfError(fileSession.CreatePrivatePath(EDriveC)); User::LeaveIfError(fileSession.PrivatePath(privatepath)); tempPath.Append(KBTSBIPTempPathDrive()); tempPath.Append(privatepath); User::LeaveIfError( file.Temp( fileSession, privatepath, aFileName, EFileWrite ) ); file.Flush(); file.Close(); CleanupStack::Pop(); // Close fileSession fileSession.Close(); } // ----------------------------------------------------------------------------- // CBTSBIPController::GenerateTempFileNameL // ----------------------------------------------------------------------------- // void CBTSBIPController::GenerateTempFileNameL( TFileName& aFileName ) { FLOG(_L("[BTSU]\t CBTSBIPController::GenerateTempFileNameL()")); RFs fileSession; RFile file; TBuf<KBTSUMaxPrivatePathLenght> privatepath; TBuf<KBTSUMaxPathLenght> tempPath; User::LeaveIfError( fileSession.Connect() ); CleanupClosePushL( fileSession ); User::LeaveIfError(fileSession.CreatePrivatePath(EDriveC)); User::LeaveIfError(fileSession.PrivatePath(privatepath )); tempPath.Append(KBTSBIPTempPathDrive()); tempPath.Append(privatepath); User::LeaveIfError(file.Temp( fileSession, tempPath, aFileName, EFileWrite ) ); file.Flush(); file.Close(); // Delete the file so that only a unique name is created fileSession.Delete( aFileName ); CleanupStack::Pop(); // Close fileSession fileSession.Close(); } // ----------------------------------------------------------------------------- // CBTSBIPController::DeleteTempFileL // ----------------------------------------------------------------------------- // void CBTSBIPController::DeleteTempFile( TFileName& aFileName ) { FLOG(_L("[BTSU]\t CBTSBIPController::DeleteTempFile()")); if ( &aFileName != NULL ) { if ( aFileName.Length() > 0 ) { RFs fileSession; TInt retVal = fileSession.Connect(); if (retVal == KErrNone) { fileSession.Delete( aFileName ); } fileSession.Close(); } } FLOG(_L("[BTSU]\t CBTSBIPController::DeleteTempFile() complete")); } // ----------------------------------------------------------------------------- // CBTSBIPController::CreateImageDescriptorL // ----------------------------------------------------------------------------- // HBufC8* CBTSBIPController::CreateImageDescriptorL() { FLOG(_L("[BTSU]\t CBTSBIPController::CreateImageDescriptorL()")); // Example image descriptor of an small jpeg picture // with size 160*120 pixels and a size of 5000 bytes. // // <image-descriptor version=\"1.0\"> // <image encoding=\"JPEG\" pixel=\"160*120\" size=\"5000\"/> // </image-descriptor> TBTSUImageParam param = iListPtr->ImageAtL( iFileIndex ); // Add start of image description // TBuf8<KBTSUMaxStringLength> string( KBTSBIPDescriptorStart ); // Add image encoding // string.Append( KBTSBIPDescriptorEncoding ); string.Append( *param.iDisplayName ); // Add image pixel size // string.Append( KBTSBIPDescriptorPixel ); string.AppendNum( param.iPixelSize.iWidth ); string.Append( '*' ); string.AppendNum( param.iPixelSize.iHeight ); // Add image size // string.Append( KBTSBIPDescriptorSize ); string.AppendNum( param.iFileSize ); // Add end of image description // string.Append( KBTSBIPDescriptorEnd ); FLOG(_L("[BTSU]\t CBTSBIPController::CreateImageDescriptorL() completed")); return string.AllocL(); } // ----------------------------------------------------------------------------- // CBTSBIPController::HandleGetCompleteIndicationL // ----------------------------------------------------------------------------- // void CBTSBIPController::HandleGetCompleteIndicationL( CObexBufObject* aGetResponse ) { FLOG(_L("[BTSU]\t CBTSBIPController::HandleGetCompleteIndicationL()")); TBool found; TBool allSupported; TInt picindex,capindex; TInt confirm=0; CBTSUXmlParser* xmlParser = CBTSUXmlParser::NewL(); CleanupStack::PushL( xmlParser ); GenerateTempFileNameL( iTempFileName ); aGetResponse->WriteToFile( iTempFileName ); aGetResponse->Reset(); // Parse capability object and create a list of supported image encodings // RArray<TBTSUImageCap>* remoteCapabilityList = xmlParser->GetImgCapabilityListL( iTempFileName ); // Delete the temp file since we dont need it anymore // DeleteTempFile( iTempFileName ); // Go through all the images on our sending list and check // if remote device is capable of receiving those. // allSupported= ETrue; for (picindex=0; picindex< iListPtr->ImageCount(); picindex++ ) { found=EFalse; for (capindex=0; capindex < remoteCapabilityList->Count(); capindex++) { //Find first is encoding suported if((iListPtr->ImageAtL( picindex ).iDisplayName->Compare(*(*remoteCapabilityList)[capindex].iEncoding))==0) { found=ETrue; //Check pixel size if((*remoteCapabilityList)[capindex].iMinPixelSize.iHeight>=0) { if(((*remoteCapabilityList)[capindex].iMaxPixelSize.iWidth < iListPtr->ImageAtL( picindex ).iPixelSize.iWidth) || ((*remoteCapabilityList)[capindex].iMaxPixelSize.iHeight < iListPtr->ImageAtL( picindex ).iPixelSize.iHeight)|| ((*remoteCapabilityList)[capindex].iMinPixelSize.iHeight > iListPtr->ImageAtL( picindex ).iPixelSize.iHeight)|| ((*remoteCapabilityList)[capindex].iMinPixelSize.iWidth > iListPtr->ImageAtL( picindex ).iPixelSize.iWidth) ) { found=EFalse; } } //Check byte size if((*remoteCapabilityList)[capindex].iMaxByteSize>=0) { if((*remoteCapabilityList)[capindex].iMaxByteSize<iListPtr->ImageAtL( picindex ).iFileSize) { found=EFalse; } } // If file is supported, stop the loop. // if ( found ) break; } } allSupported = found & allSupported; } for (TInt index=0; index < remoteCapabilityList->Count(); index++) { if((*remoteCapabilityList)[index].iEncoding) { delete ((*remoteCapabilityList)[index].iEncoding); } } remoteCapabilityList->Close(); delete remoteCapabilityList; CleanupStack::PopAndDestroy( xmlParser ); if(!allSupported && iListPtr->ImageCount() > 1) { confirm=iObserverPtr->LaunchConfirmationQuery(R_BT_NOT_SEND_ALL_QUERY_MIXED); if(confirm==EAknSoftkeyYes) { // Everything went ok. Start sending images // iObserverPtr->LaunchProgressNoteL( iClient, iListPtr->ImageListSize(),iListPtr->ImageCount() ); // Start sending images // SendL(); } } else if ( !allSupported && iListPtr->ImageCount() == 1) { // We allow user to choose wheather to send the image file which is not supported on target device // Original codeline: iObserverPtr->ControllerComplete( EBTSBIPOneNotSend ); confirm=iObserverPtr->LaunchConfirmationQuery(R_BT_NOT_SEND_ALL_QUERY_SINGLE); if(confirm==EAknSoftkeyYes) { // Everything went ok. Start sending the images // iObserverPtr->LaunchProgressNoteL( iClient, iListPtr->ImageListSize(),iListPtr->ImageCount() ); // Start sending images // SendL(); } } else if( allSupported ) { iObserverPtr->LaunchProgressNoteL( iClient, iListPtr->ImageListSize() + iListPtr->ObjectListSizeL(),iListPtr->ImageCount() + iListPtr->ObjectCount()); // Start sending images // SendL(); } FLOG(_L("[BTSU]\t CBTSBIPController::HandleGetCompleteIndicationL() #3")); } //----------------------------------------------------------------------------- // void CBTSBIPController::ConnectTimedOut() // ----------------------------------------------------------------------------- // void CBTSBIPController::ConnectTimedOut() { iObserverPtr->ConnectTimedOut(); } // End of File
b6f440d61cf4edaf1d1ab039856c34e8901b5338
f2ae4870e0c8e4411927ac6f20939a35bb50d6e2
/Sensor_color_continuity.ino
29c073d8422bdd488641302ad7bbb012ce5e085b
[]
no_license
Micros2/Sensor_color
8cb5148d8a525b93f112e030ee907c90bdc9734d
b74b169180f110f0867eeb026c020ce4e058ac3b
refs/heads/master
2021-01-23T14:17:11.267425
2017-09-14T13:39:09
2017-09-14T13:39:09
102,681,747
0
0
null
null
null
null
UTF-8
C++
false
false
3,191
ino
Sensor_color_continuity.ino
/* * Terminal Description * GND Power supply ground. * OUT Output Freq. * S0, S1 Scaling freq selection. * S2, S3 Photodiode type selection inputs. * LED Supply voltaje for LED. * VCC Supply voltage * */ const int s0=1; const int s1=2; const int s2=3; const int s3=4; const int out=5; const int btn=6; //los valores que regresará de cada color según la refracción int rojo=0; int verde=0; int azul =0; int rojoa=0; int verdea=0; int azula =0; bool pushed=true; int diferenciar=0; int diferenciaa=0; int diferenciav=0; void setup() { Serial.begin(9600); //Son las salidas que encienden los leds pinMode (s0,OUTPUT); pinMode (s1,OUTPUT); pinMode (s2,OUTPUT); pinMode (s3,OUTPUT); pinMode (btn,INPUT); //la entrada que recibe el pulso y lo cuantifica pinMode (out,INPUT); // Calibra la frecuencia de salida según la tabla de abajo digitalWrite(s0,HIGH); digitalWrite(s1,HIGH); /* * s0 s1 Outfreq * L L Power down * L H 2% * H L 20% * H H 100% */ } void loop() { color(); Serial.print(" "); Serial.print(rojo,DEC); Serial.print(" "); Serial.print(verde,DEC); Serial.print(" "); Serial.print(azul,DEC); Serial.print(pushed); /* if (rojo<15 && verde <rojo && verde>azul) { Serial.println(" Rojo"); }else if (azul>5 && verde<rojo && verde >azul){ Serial.println(" Verde"); }else if (verde> azul && azul <6 && azul<rojo){ Serial.println(" Azul"); }else {Serial.println(" ");} */ while (pushed){ rojoa=rojo; azula=azul; verdea=verde; color(); diferenciar=rojoa-rojo; if (diferenciar>=-1 && diferenciar>=1) {}else {Serial.println("Discontinuidad Rojo ");} diferenciaa=azula-azul; /* if (diferenciaa!=0 || diferenciaa!=1 || diferenciaa!=-1) {Serial.println("Discontunuidad azul");} diferenciar=verdea-verde; if (diferenciav!=0 || diferenciav!=1 || diferenciav!=-1) {Serial.println("Discontunuidad verde");} */ delay(100); if (btn==HIGH){ pushed=not pushed; delay(100);} } if (btn==HIGH){ pushed=not pushed; delay(100);} if (rojo<verde && rojo<azul){ Serial.println(" Rojo"); }else if (azul< rojo && azul<verde && azul<15){Serial.println(" Azul");} else if (verde<rojo && verde<azul){Serial.println(" Verde");} else if (rojo<7 && verde<7 && azul<7){Serial.println(" Blanco");} else if (rojo>17 && verde>17 && azul>14){Serial.println(" Negra");}else {Serial.println(" ");} delay(900); } void color(){ //para las salidas s2 y s3 low low=enciende el color rojo //Para las salidas s2 y s3 low high= enciende el color azul //Para las salidas s2 y s3 high high=enciende el color verde digitalWrite(s2,LOW); digitalWrite(s3,LOW); rojo=pulseIn(out, digitalRead(out)==HIGH ? LOW : HIGH); delay(100); // rojo= map(rojo,150,600,255,0); //Se hace un mapeo para relacionar los valores de la frecuencia con los del RGB convencionales digitalWrite(s3,HIGH); azul=pulseIn(out, digitalRead(out)==HIGH ? LOW : HIGH); delay(100); // azul= map(rojo,150,600,255,0); digitalWrite(s2,HIGH); verde=pulseIn(out, digitalRead(out)==HIGH ? LOW : HIGH); // verde= map(rojo,150,600,255,0); }
c318da286a9121912b0c634d3c0844423e2ee527
ccb806d6d79e2d5f18e8a0173ca8d048aef686e5
/1DAE10_Verberckmoes_Thibau_BindingOfIsaac/Game.cpp
6606e2ba28db84963a6c28aba4f46f853e290acc
[]
no_license
ThibauVB/Thibau_Verberckmoes_Binding_Of_Isaac_Remake
ea4702f9274edbce2ccac44fce9b2d2e68b0af5b
50d936ee54ab272a8677ae94ec30b08dd7ddbecd
refs/heads/master
2022-10-11T05:06:39.077926
2020-04-19T23:32:33
2020-04-19T23:32:33
255,368,524
0
0
null
null
null
null
UTF-8
C++
false
false
5,384
cpp
Game.cpp
#include "pch.h" #include "Game.h" Game::Game(const Window& window) :m_Window{ window }, m_DungeonGenerator(Vector2f{ m_Window.width,m_Window.height }), m_Isaac(Point2f{ m_Window.width / 2,m_Window.height / 2 }, Point2f{ m_Window.width,m_Window.height }), m_Camera(m_Window.width, m_Window.height), m_StartScreen(false), m_TextureStartScreen("../Resources/Backgrounds/StartingScreen.jpg"), m_TearManager(), m_TimeCounter(0) { Initialize(); } Game::~Game() { Cleanup(); } void Game::Initialize() { m_DungeonGenerator.StartDungeonGeneration(); m_Camera.SetLevelBoundaries(Rectf{ 0,0,m_Window.width,m_Window.height }); } void Game::Cleanup() { } void Game::Update(float elapsedSec) { // Check keyboard state if (m_StartScreen == false) { const Uint8* pStates = SDL_GetKeyboardState(nullptr); if (pStates[SDL_SCANCODE_W] == true && pStates[SDL_SCANCODE_D] == true) { m_Isaac.SetDirection(Isaac::MovingRightUP); } if (pStates[SDL_SCANCODE_W] == true && pStates[SDL_SCANCODE_A] == true) { m_Isaac.SetDirection(Isaac::MovingLeftUp); } if (pStates[SDL_SCANCODE_S] == true && pStates[SDL_SCANCODE_D] == true) { m_Isaac.SetDirection(Isaac::MovingRightDown); } if (pStates[SDL_SCANCODE_S] == true && pStates[SDL_SCANCODE_A] == true) { m_Isaac.SetDirection(Isaac::MovingLeftDown); } if (m_Isaac.GetMotionState()) { if (pStates[SDL_SCANCODE_W]) { m_Isaac.SetDirection(Isaac::movingUp); } if (pStates[SDL_SCANCODE_D]) { m_Isaac.SetDirection(Isaac::movingRight); } if (pStates[SDL_SCANCODE_S]) { m_Isaac.SetDirection(Isaac::movingDown); } if (pStates[SDL_SCANCODE_A]) { m_Isaac.SetDirection(Isaac::movingLeft); } } //left , right , bottom , top if (m_TimeCounter > 0.3f) { if (pStates[SDL_SCANCODE_UP]) { //std::cout << "Shooting Up" << std::endl; //m_DungeonGenerator.Changeroom(2); m_TearManager.CreateTear(m_Isaac.GetPostion(), utils::ShootingUp); } if (pStates[SDL_SCANCODE_RIGHT]) { //std::cout << "Shooting Right" << std::endl; //m_DungeonGenerator.Changeroom(3); m_TearManager.CreateTear(m_Isaac.GetPostion(), utils::ShootingRight); } if (pStates[SDL_SCANCODE_DOWN]) { //std::cout << "Shooting Down" << std::endl; //m_DungeonGenerator.Changeroom(0); m_TearManager.CreateTear(m_Isaac.GetPostion(), utils::ShootingDown); } if (pStates[SDL_SCANCODE_LEFT]) { //std::cout << "Shooting Left" << std::endl; //m_DungeonGenerator.Changeroom(1); m_TearManager.CreateTear(m_Isaac.GetPostion(), utils::ShootingLeft); } m_TimeCounter = 0; } m_TimeCounter += elapsedSec; m_Isaac.UpdateIsaac(elapsedSec); m_Isaac.SetDirection(Isaac::notMoving); m_DungeonGenerator.UpdateCurrentshownRoom(m_Isaac.GetPostion(), m_Isaac); m_TearManager.UpdateTears(elapsedSec); } else { } } void Game::Draw() const { ClearBackground(); if (m_StartScreen == false) { utils::SetColor(Color4f{ 1.f,1.f,1.f,1.f }); utils::DrawPoint(Point2f{ m_Window.width / 2,m_Window.height / 2 }, 10); m_DungeonGenerator.DrawDungeon(); m_Camera.Draw(m_Isaac.GetShape()); m_Isaac.DrawIsaac(); m_TearManager.DrawTears(); } else { DrawStartScreen(); } } void Game::ProcessKeyDownEvent(const SDL_KeyboardEvent& e) { switch (e.keysym.scancode) { case SDL_SCANCODE_I:ShowControls(); break; } } void Game::ProcessKeyUpEvent(const SDL_KeyboardEvent& e) { //std::cout << "KEYUP event: " << e.keysym.sym << std::endl; //switch ( e.keysym.sym ) //{ //case SDLK_LEFT: // //std::cout << "Left arrow key released\n"; // break; //case SDLK_RIGHT: // //std::cout << "`Right arrow key released\n"; // break; //case SDLK_1: //case SDLK_KP_1: // //std::cout << "Key 1 released\n"; // break; //} } void Game::ProcessMouseMotionEvent(const SDL_MouseMotionEvent& e) { //std::cout << "MOUSEMOTION event: " << e.x << ", " << e.y << std::endl; } void Game::ProcessMouseDownEvent(const SDL_MouseButtonEvent& e) { //std::cout << "MOUSEBUTTONDOWN event: "; //switch ( e.button ) //{ //case SDL_BUTTON_LEFT: // std::cout << " left button " << std::endl; // break; //case SDL_BUTTON_RIGHT: // std::cout << " right button " << std::endl; // break; //case SDL_BUTTON_MIDDLE: // std::cout << " middle button " << std::endl; // break; //} } void Game::ProcessMouseUpEvent(const SDL_MouseButtonEvent& e) { //std::cout << "MOUSEBUTTONUP event: "; //switch ( e.button ) //{ //case SDL_BUTTON_LEFT: // std::cout << " left button " << std::endl; // break; //case SDL_BUTTON_RIGHT: // std::cout << " right button " << std::endl; // break; //case SDL_BUTTON_MIDDLE: // std::cout << " middle button " << std::endl; // break; //} } void Game::ClearBackground() const { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); } void Game::DrawStartScreen() const { m_TextureStartScreen.Draw(Point2f{ 0,0 }); } void Game::ShowControls() { std::cout << "Move Up: W or Z key (depending on settings)" << std::endl; std::cout << "Move Right: D" << std::endl; std::cout << "Move Down: S" << std::endl; std::cout << "Move Left: A or Q" << std::endl; std::cout << "Shoot Up: ArrowUpKey" << std::endl; std::cout << "Shoot Right: ArrowRightKey" << std::endl; std::cout << "shoot Down: ArrowDownKey" << std::endl; std::cout << "Shoot Left: ArrowLeftKey" << std::endl; }
c9ba138058ffdc02087dcfbe66aef6c19c365f6b
a7764174fb0351ea666faa9f3b5dfe304390a011
/src/IGESDraw/IGESDraw.cxx
53f2bfc7a72ad2a3d7b55c502769a8608aaab87a
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
1,076
cxx
IGESDraw.cxx
#include <IGESDraw.ixx> #include <IGESDraw_Protocol.hxx> #include <IGESDraw_GeneralModule.hxx> #include <IGESDraw_ReadWriteModule.hxx> #include <IGESDraw_SpecificModule.hxx> #include <Interface_GeneralLib.hxx> #include <Interface_ReaderLib.hxx> #include <IGESData_WriterLib.hxx> #include <IGESData_SpecificLib.hxx> #include <IGESDimen.hxx> // Ancillary data to work on a Package of IGES Entities with a Protocol // (Modules are created and loaded in appropriate libraries, once by Init) static Handle(IGESDraw_Protocol) protocol; void IGESDraw::Init () { IGESDimen::Init(); if (protocol.IsNull()) { protocol = new IGESDraw_Protocol; Interface_GeneralLib::SetGlobal (new IGESDraw_GeneralModule, protocol); Interface_ReaderLib::SetGlobal (new IGESDraw_ReadWriteModule,protocol); IGESData_WriterLib::SetGlobal (new IGESDraw_ReadWriteModule,protocol); IGESData_SpecificLib::SetGlobal (new IGESDraw_SpecificModule, protocol); } } Handle(IGESDraw_Protocol) IGESDraw::Protocol () { return protocol; }
2640b73d4f9fcaff707dbc513b754d5459a4a371
28179e957db221dba9fb2d1a2061936b5859d30f
/include/utils.h
6c384444d329636e4b5a7b779ab9f3d17b0ee401
[]
no_license
kurmis/QuadCopter
441b839c274ab2c95e341db6bb98b52bb23ad033
2880423b34058acb2439283cb4e0f08cf9ff765a
refs/heads/master
2021-01-20T11:30:37.653880
2014-12-05T20:28:30
2014-12-05T20:28:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
716
h
utils.h
#ifndef __UTILS_H #define __UTILS_H #include "stm32f30x.h" #include "main.h" void Delay(__IO uint32_t nTime); uint8_t strlen(char* str); void add(float* result, float* a, float* b); void diff(float* result, float* a, float* b); //multiply a vector by a constant void mult(float* result, float* a, float b); //dot product float mult(float* a, float* b); //cross product void mult(float* result, float* a, float* b); class Sleeper { private: unsigned int m_from; public: void FromNow(); void For(unsigned int ms); }; void Isort(float *a, int n); float FindMedian(float *data, int arraySize); float Max(float a, float b); float Min(float a, float b); float Constrain(float c, float min, float max); #endif
527e81c4572e015e4b8ac1ec8a14ac8271b8ed0e
9bd55740fda6050bd695b863b5f5419fbbd3b552
/CannonView.cpp
58503b660960c4efe11235ecebf265c5b7ad452e
[ "MIT" ]
permissive
15831944/DikuEdit
e65dd2bb93148095174bf407b9dfdc5fcc9b78c8
135f49bba7ce2faf5faac12a355da9813c28d0fa
refs/heads/master
2021-06-08T14:51:49.035757
2014-11-04T06:26:21
2014-11-04T06:27:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,950
cpp
CannonView.cpp
// CannonView.cpp : implementation file // #include "stdafx.h" #include "WinDE.h" #include "CannonView.h" #include "ShipUpgrades.h" #include "CannonBuilder.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CannonView dialog CannonView::CannonView(CWnd* pParent /*=NULL*/) : CTabPageSSL(CannonView::IDD, pParent) { //{{AFX_DATA_INIT(CannonView) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CannonView::DoDataExchange(CDataExchange* pDX) { CTabPageSSL::DoDataExchange(pDX); //{{AFX_DATA_MAP(CannonView) DDX_Control(pDX, IDC_CANNON_LIST, m_CannonList); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CannonView, CTabPageSSL) //{{AFX_MSG_MAP(CannonView) ON_WM_SHOWWINDOW() ON_WM_LBUTTONUP() ON_NOTIFY(NM_DBLCLK, IDC_CANNON_LIST, OnDblclkCannonList) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CannonView message handlers BOOL CannonView::OnInitDialog() { CTabPageSSL::OnInitDialog (); CRect rect; DWORD dwStyle = ::SendMessage(m_CannonList, LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0); dwStyle |= LVS_EX_FULLROWSELECT; ::SendMessage(m_CannonList, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, dwStyle); m_CannonList.GetClientRect(rect); m_CannonList.InsertColumn(0, "Name", LVCFMT_LEFT, rect.Width()-(rect.Width()/5)); m_CannonList.InsertColumn(1, "Price", LVCFMT_LEFT, rect.Width()/5); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CannonView::OnShowWindow(BOOL bShow, UINT nStatus) { CTabPageSSL::OnShowWindow(bShow, nStatus); CString str; Cannon *cannon; int i; if(bShow == 1) { i = 0; m_CannonList.DeleteAllItems(); for(cannon = CannonList::cannons.first; cannon; cannon = cannon->next) { if(cannon) { m_CannonList.InsertItem(i, StripAnsiChars(cannon->name), 0); str.Format("%d", cannon->value); m_CannonList.SetItem(i, 1, LVIF_TEXT, str, 1, 0, 0, 0); m_CannonList.SetItemData(i, (DWORD)cannon); i++; } } } } void CannonView::OnDblclkCannonList(NMHDR* pNMHDR, LRESULT* pResult) { CannonBuilder cannon_dlg(this); CListCtrl *list; POSITION pos; int i; CString str; list = (CListCtrl*)GetDlgItem(IDC_CANNON_LIST); pos = list->GetFirstSelectedItemPosition(); i = list->GetNextSelectedItem(pos); if(i < 0) { MessageBox("Please select the cannon you wish to edit."); return; } cannon_dlg.cannon = (Cannon*)list->GetItemData(i); if(cannon_dlg.DoModal() == IDOK) { list->DeleteItem(i); list->InsertItem(i, StripAnsiChars(cannon_dlg.cannon->name), 0); str.Format("%d", cannon_dlg.cannon->value); list->SetItem(i, 1, LVIF_TEXT, str, 1, 0, 0, 0); list->SetItemData(i, (DWORD)cannon_dlg.cannon); } *pResult = 0; }
3ab226b74a959cb8ef4b9e923e118e4319c59767
4d67d7da5d633645c0be6a6fef76a102d8bf4255
/Операторы цикла/Упражнение_2.cpp
037b66d97ddaf141d0a8ed67a9c65066fd5b6007
[]
no_license
Alexander-Saad/Newtech
59db6695c5e3fb01ea726c58a55ae9bc287e6dc3
bf1b00b6a3b5713f4d529717284099d7573c42a2
refs/heads/main
2023-01-01T11:22:19.532032
2020-10-25T08:50:22
2020-10-25T08:50:22
300,924,229
0
0
null
null
null
null
UTF-8
C++
false
false
344
cpp
Упражнение_2.cpp
#include <clocale> #include <iostream> #include <Windows.h> #include <math.h> using namespace std; int main() { setlocale(LC_ALL, "Russian"); // Вывод нечетных значение от 1 до 20 int a = 1, b = 20; for (int i = a; i <= b; i+=2) { cout << i << " "; } system("pause"); return 0; }
8e90690a7d2285a8ad55bcf44f62746f47f5887d
58f4d56dba6ddfdd7c9851e5e47def69b4338c18
/cocciobj.h
87714743acb749a0564144c77e135a88c152105f
[]
no_license
yuetianle/occi
83efd31a6d802df0f4a1ad264bec526d995ff7d1
6cd0fff1ab74c42d9c4c2d004574df34c94565fe
refs/heads/master
2020-05-07T21:19:46.754303
2015-01-22T10:42:13
2015-01-22T10:42:13
29,644,434
0
0
null
null
null
null
UTF-8
C++
false
false
1,072
h
cocciobj.h
#ifndef COCCIOBJ_H #define COCCIOBJ_H #include <memory> #include <cstring> #include "crecord.h" #include "coccicommon.h" #include "coccipool.h" /** * @brief 数据库单个对象. * 数据库初始化、插入、查询、删除等操作 */ class COCCIObj { public: COCCIObj(const DB_USER_INFO &db_user_info); virtual ~COCCIObj(); /** * @brief 初始化occi-API. * @warning 调用occi初始化函数、调用一次 */ bool Init(); /** * @brief 反初始化occi-API. * @warning 调用occi初始化函数、调用一次 */ void Uninit(); bool Query(const string&cmd, CRecord *result); bool Insert(const string&cmd, void* data); bool Delete(const string&cmd); /** * */ protected: /** * @brief 查询字符串格式是否正确. * @param [in] cmd */ bool CheckQueryCmd(const string&cmd); private: DB_USER_INFO db_user_info_; /**< 数据库用户配置信息*/ string cmd; /**< 完整命令语句*/ Environment *env_; COCCIPool *occi_pool_; }; #endif // COCCIOBJ_H
f0f117096ab0b0868fbaa6e613074525eb65e640
f7724aebc82a5f1bbc5f5020940f8acd0aaeab21
/JosephusKill.cpp
5bfb5949d7c24988c707fe12b3b087b7c4cf46e7
[]
no_license
pw-ethan/LinkedList
c3468d3e92069579a561374a5d90f13a3a1fc24c
934e7a3643757ea66e2d39cd097b949848e47ebf
refs/heads/master
2020-06-01T06:30:41.635914
2017-06-15T08:40:58
2017-06-15T08:40:58
94,065,422
0
0
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
JosephusKill.cpp
#include "JosephusKill.h" std::shared_ptr<Node> JosephusKill(std::shared_ptr<Node> head, int m) { if(head == nullptr || head->next == nullptr || m < 1) { return head; } std::shared_ptr<Node> last = head; while(last->next != head) { last = last->next; } int cnt = 0; while(head != last) { if(++cnt == m) { last->next = head->next; cnt = 0; } else { last = last->next; } head = last->next; } return head; } std::shared_ptr<Node> JosephusKillEx(std::shared_ptr<Node> head, int m) { if(head == nullptr || head->next == nullptr || m < 1) { return head; } std::shared_ptr<Node> cur = head->next; int tmp = 1; while(cur != head) { tmp++; cur = cur->next; } tmp = getLive(tmp, m); while(--tmp != 0) { head = head->next; } head->next = head; return head; } int getLive(int i, int m) { if(i == 1) { return 1; } return (getLive(i - 1, m) + m - 1) % i + 1; }
9eec5e0b0d2e8d11ea3967588cd542066a89e8a7
f6b472898b10a53b949ab3c08588051550543ebf
/Turtle/Turtle.h
3e0aa56a3f67c7b92c4ff0ce4b8f95ee161bcd92
[ "BSD-2-Clause" ]
permissive
mirek-fidler/Turtle
37fcf1987e96baf7e9d2452b7fe92007c54f7bdd
fd413460c3d92c9a85fc620f6f3db50d96f3be2f
refs/heads/master
2023-05-14T17:37:33.379280
2021-06-10T21:32:42
2021-06-10T21:32:42
326,928,313
2
0
null
null
null
null
UTF-8
C++
false
false
5,900
h
Turtle.h
#ifndef _VirtualGui_Turtle_h #define _VirtualGui_Turtle_h #include <CtrlLib/CtrlLib.h> namespace Upp { class TurtleServer : public VirtualGui { public: TurtleServer() {} TurtleServer(const String& host, int port) { Host(host).HtmlPort(port).WsPort(port + 1); } TurtleServer(const String& ip, String& host, int port) { Bind(ip).Host(host).HtmlPort(port).WsPort(port + 1); } TurtleServer& Bind(const String& addr) { TurtleServer::ip = addr; return *this; } TurtleServer& Host(const String& host) { TurtleServer::host = host; return *this; } TurtleServer& HtmlPort(int port) { TurtleServer::html_port = port; return *this; } TurtleServer& WsPort(int port) { TurtleServer::ws_port = port; return *this; } TurtleServer& MaxConnections(int limit) { TurtleServer::connection_limit = max(1, limit); return *this; } static void DebugMode(bool b = true) { TurtleServer::debugmode = b; } static Event<int, String> WhenConnect; static Event<int> WhenTerminate; static Event<> WhenDisconnect; private: virtual dword GetOptions() { return GUI_SETMOUSECURSOR; } virtual Size GetSize() { return desktopsize; } virtual dword GetMouseButtons() { return mousebuttons; } virtual dword GetModKeys() { return modifierkeys; } virtual bool IsMouseIn() { return mousein; } virtual bool ProcessEvent(bool *quit); virtual void WaitEvent(int ms); virtual bool IsWaitingEvent(); virtual void SetMouseCursor(const Image& image); virtual void SetCaret(const Rect& caret) {} virtual SystemDraw& BeginDraw(); virtual void CommitDraw(); virtual void WakeUpGuiThread() {} virtual void Quit() { WhenDisconnect(); } private: void MouseButton(dword event, CParser& p); void MouseWheel(CParser& p); void MouseMove(CParser& p); void KeyDown(const String& event, CParser& p); void KeyUp(const String& event, CParser& p); void KeyPress(const String& event, CParser& p); void Resize(CParser& p); void ReadModifierKeys(CParser& p); dword TranslateWebKeyToK(dword key); static void Broadcast(int signal); void SyncClient(); public: struct Stream : OutStream { Stream(); void Out(const void *data, dword size) final; String FlushStream(); void Reset(); Zlib zlib; bool hasdata; }; struct ImageSysData { ImageSysData(); ~ImageSysData(); void Init(const Image& img); Image image; int handle; }; struct Draw : SDraw { Draw(); void Init(const Size& sz); void PutImage(Point p, const Image& img, const Rect& src) final; void PutRect(const Rect& r, Color color) final; Point pos; SystemDraw sysdraw; }; friend struct TurtleServer::Draw; friend struct TurtleServer::ImageSysData; public: enum Commands { RECT = 0, IMAGE = 1, SETIMAGE = 2, INVERTRECT = 3, STD_CURSORIMAGE = 4, SETCURSORIMAGE = 5, MOUSECURSOR = 6, DISABLESENDING = 7, UPDATESERIAL = 8, IMAGEPP = 9, IMAGENP = 10, IMAGEPN = 11, IMAGENN = 12, RECTPP = 13, RECTNP = 14, RECTPN = 15, RECTNN = 16, SETCARET = 17, HORZDRAGLINE = 18, VERTDRAGLINE = 19, OPENLINK = 20, }; private: static void Put8(int x); static void Put16(int x); static void Put32(int x); static void Put(Point p); static void Put(Size sz); static void Put(const Rect& r); static void Put(const String& s); static void Flush(); static void SetCanvasSize(const Size& sz); static void ResetImageCache(); private: static WebSocket websocket; static dword mousebuttons; static dword modifierkeys; static Size desktopsize; static int mainpid; static int64 update_serial; static int64 recieved_update_serial; static int64 serial_0; static int serial_time0; static bool quit; static String host; static int html_port; static int ws_port; static String ip; static int connection_limit; static bool debugmode; static bool mousein; public: // Statistics. static Time stat_started; static int64 stat_data_send; static int stat_putrect; static int stat_putimage; static int stat_setimage; static int64 stat_setimage_len; static int stat_roundtrip_ms; static int stat_client_ms; private: static bool StartSession(); friend void RunTurtleGui(TurtleServer&, Event<>); }; void RunTurtleGui(TurtleServer& gui, Event<> app_main); } #endif
9530ca9123279830407f03ea20abf81a5ad20dc7
4aec42ce0ae1134e12e6e57b2bee10fb4b759f6c
/hector_serialization_test/src/udp.cpp
e84a92a5408c1f77435adde60b744ad59cec4d64
[]
no_license
jinjin2018/hector_serialization
bedf5a15686ef7cc607a4731628bf735eab924e3
5ea8442032c2f362cd97383acfb315bbf1b9b33b
refs/heads/master
2021-05-27T00:22:47.543313
2013-01-31T15:12:04
2013-01-31T15:12:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,220
cpp
udp.cpp
//================================================================================================= // Copyright (c) 2012, Johannes Meyer, TU Darmstadt // 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 Flight Systems and Automatic Control group, // TU Darmstadt, nor the names of its contributors may be used to // endorse or promote products derived from this software without // specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //================================================================================================= #include <hector_serialization/socket/udp.h> #include <hector_serialization/serialization.h> #include <rosserial_msgs/TopicInfo.h> using namespace hector_serialization; int main(int argc, char **argv) { unsigned int listen_port = 3000, send_port = 3000; if (argc > 1) listen_port = boost::lexical_cast<unsigned int>(argv[1]); if (argc > 2) send_port = boost::lexical_cast<unsigned int>(argv[2]); socket::Udp socket; socket::Udp::Endpoint local_endpoint(boost::asio::ip::address_v4::loopback(), listen_port); socket::Udp::Endpoint remote_endpoint(boost::asio::ip::address_v4::loopback(), send_port); socket.open(local_endpoint.protocol()); socket.setOption(boost::asio::socket_base::broadcast(true)); socket.setOption(boost::asio::socket_base::reuse_address(true)); socket.bind(local_endpoint); // socket.connect(socket::Udp::Endpoint(boost::asio::ip::address_v4::loopback(), send_port)); socket.wait(1.0); rosserial_msgs::TopicInfo topic_info; topic_info.message_type = "rosserial_msgs/TopicInfo"; if (socket.write(serialize(topic_info), socket::Udp::ContextElement(remote_endpoint))) { std::cout << "Sent: " << std::endl << topic_info << std::endl; } while (socket.wait(10.0) && socket.size() > 0) { deserialize(socket, topic_info); std::cout << "Received: " << std::endl << topic_info << std::endl; } socket.disconnect(); }
878fd00d0141b94d1d0e48248eba8fcc8db4b46d
ec2ca75c541dedc55635cbec240c825d9327502a
/gui/graphform.cpp
4ebe0a6c369b72618ce9b5bc869202e1b04b97cf
[ "Apache-2.0" ]
permissive
ivandzen/RMCS
5f921c0da648f3852acb8b2216663e2ba6494a0d
a695725212f1e32845bc04c1d9197535c2aa3732
refs/heads/master
2020-03-26T09:52:25.546248
2018-08-14T17:20:16
2018-08-14T17:20:16
144,769,627
0
0
null
null
null
null
UTF-8
C++
false
false
4,958
cpp
graphform.cpp
#include "graphform.h" #include "ui_graphform.h" #include <QDebug> GraphForm::GraphForm(QWidget *parent) : QWidget(parent), ui(new Ui::GraphForm) { ui->setupUi(this); startTimer(30); } GraphForm::~GraphForm() { delete ui; } bool GraphForm::addOParam(QOParamController * param) { if(_graphs.contains(param)) return false; GraphSet newSet(param->count()); for(int i = 0; i < param->count(); ++i) { QCPGraph * newGraph = ui->plot->addGraph(); newGraph->setPen(QPen(Qt::GlobalColor(rand() % (int)Qt::darkYellow))); newSet.append(newGraph); } _graphs.insert(param, newSet); /* param->setHandler([this](QOParamController * param, ParamDataID id, const QVector<QVariant> & values) { GraphSet & set = _graphs[param]; for(int i = 0; i < values.size(); ++i) { QCPGraph * graph = set[i]; if(graph == nullptr) { qDebug() << "GraphForm::onBufferFull Nullptr граф"; return; } bool found; QCPRange xrange = graph->getKeyRange(found); double x = id; x /= 3.0; //if(found) // x = xrange.upper + 1; bool ok =false; double fvalue = values[i].toDouble(&ok); if(!ok) { qDebug() << "GraphForm::onBufferFull unable to convert value to float"; return; } //if(fvalue != 0.0) graph->addData(x, fvalue); xrange = graph->getKeyRange(found); if(!found) { qDebug() << "GraphForm::onBufferFull Key range for graph not found. Exit"; return; } QCPRange yrange = graph->getValueRange(found); if(!found) { qDebug() << "GraphForm::onBufferFull Value range for graph not found. Exit"; return; } if(xrange.upper > ui->plot->xAxis->range().upper) { ui->plot->xAxis->setRangeUpper(xrange.upper); ui->plot->xAxis->setRangeLower(ui->plot->xAxis->range().upper - 2000); } //if(xrange.lower < ui->plot->xAxis->range().lower) if(yrange.lower < ui->plot->yAxis->range().lower) ui->plot->yAxis->setRangeLower(yrange.lower); if(yrange.upper > ui->plot->yAxis->range().upper) ui->plot->yAxis->setRangeLower(yrange.upper); } }); */ //connect(param, SIGNAL(bufferFull()), this, SLOT(onBufferFull())); return true; } void GraphForm::timerEvent(QTimerEvent *event) { ui->plot->replot(); } void GraphForm::onBufferFull() { QOParamController * param = qobject_cast<QOParamController*>(QObject::sender()); if(param == nullptr) { qDebug() << "GraphForm::onBufferFull Сендер не является QOParamController"; return; } if(!_graphs.contains(param)) { qDebug() << "GraphForm::onBufferFull Граф для истоника сигнала не найден"; return; } GraphSet & set = _graphs[param]; /* param->map([this, &set](const QVariant & value) { QCPGraph * graph = set.next(); if(graph == nullptr) { qDebug() << "GraphForm::onBufferFull Nullptr граф"; return; } bool found; QCPRange xrange = graph->getKeyRange(found); double x = 0; if(found) x = xrange.upper + 1; bool ok =false; double fvalue = value.toDouble(&ok); if(!ok) { qDebug() << "GraphForm::onBufferFull unable to convert value to float"; return; } //if(fvalue != 0.0) graph->addData(x, fvalue); xrange = graph->getKeyRange(found); if(!found) { qDebug() << "GraphForm::onBufferFull Key range for graph not found. Exit"; return; } QCPRange yrange = graph->getValueRange(found); if(!found) { qDebug() << "GraphForm::onBufferFull Value range for graph not found. Exit"; return; } if(xrange.upper > ui->plot->xAxis->range().upper) { ui->plot->xAxis->setRangeUpper(xrange.upper); ui->plot->xAxis->setRangeLower(ui->plot->xAxis->range().upper - 2000); } //if(xrange.lower < ui->plot->xAxis->range().lower) if(yrange.lower < ui->plot->yAxis->range().lower) ui->plot->yAxis->setRangeLower(yrange.lower); if(yrange.upper > ui->plot->yAxis->range().upper) ui->plot->yAxis->setRangeLower(yrange.upper); }); param->reset(); */ ui->plot->replot(); }
654e931c25fc562b203144d3b27b2cafb6cfc6f9
b2b83f1c59d6bdf0673588a3f1d310e849ab9161
/Numbers Manipulation/reverse_integer.cpp
8049d5ae9a2333c77c65ba19a3be3165bbd02d03
[ "MIT" ]
permissive
dalalsunil1986/Common-coding-puzzles
ac735841697715b406973dcd38d3dc7b280e7713
c9a73c0ff2abc7e0acdb53e545bb219eeeb23421
refs/heads/master
2023-07-03T07:25:55.091004
2021-08-15T11:11:16
2021-08-15T11:11:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
reverse_integer.cpp
/*! * @description Reverse digits of an integer (int32_t) * @restriction Returns 0 if the reversed integer overflows int32_t */ class Solution { public: int reverse(long long x) { int res=0; while(x){ if(res>INT_MAX/10 || res<INT_MIN/10) return 0; res=res*10+x%10; x/=10; } return res; } };
e2f0005e64f2fd809bfc636f8ffd9a03166e6135
ee893c80d52e222a6e8ce9e15f72cb4031b4f532
/Command.h
e67470671e5e9a8606e668a3b01e6d9e64bae8d3
[]
no_license
matthewgraham1/nutshell
38b3775cab8d05737f61c5f2d2312d91cb5556bb
58c01fa56849ae66d316140e92022bfafa8da61b
refs/heads/master
2023-04-03T08:23:21.483884
2021-04-16T03:20:03
2021-04-16T03:20:03
353,462,101
0
1
null
2021-04-15T20:58:19
2021-03-31T19:04:40
C++
UTF-8
C++
false
false
1,373
h
Command.h
#pragma once #include <list> #include <vector> #include <string> #include <functional> #include <map> class Command { public: inline Command() { expand_PATH(); } struct Node { std::string name; std::vector<std::string> arguments; struct Output { std::string from; std::string to; bool append { false }; }; std::vector<Output> output; std::string input_file; }; void add_command(const Node&); enum RunIn { Background, Foreground, }; int run(RunIn); private: int run(Node&, int from, int to); void expand_PATH(); std::list<Node> m_commands; int** m_pipes; std::vector<std::string> m_path; }; class BuiltinCommandTable { public: using BuiltinTableType = std::map<std::string, std::function<void(const std::vector<std::string>&)>>; using PairType = std::pair<std::string, std::function<int(const std::vector<std::string>&)>>; static BuiltinCommandTable& the(); const BuiltinTableType& internal_table() const { return m_builtin_table; } int run(const std::string& builtin_name, const std::vector<std::string>& arguments); inline BuiltinTableType::iterator get(const std::string& name) { return m_builtin_table.find(name); } private: BuiltinCommandTable(); BuiltinTableType m_builtin_table; };
129b3f06aaeafc2c3c82fc9a27811726a51cb336
2022856b750cf5cfaa0ceb1369844cb1e878b2b1
/project/project/mainwindow.h
77d0d1c91f1888cf8ac4bf17e6b1e00872aac7e4
[]
no_license
devilYD/Analog_Calculator
6df312adeeebd4cfc80b2db4ae0179867a50c68a
c9335108e89fd40f1c5db87806d63e34074e7233
refs/heads/main
2023-06-02T08:35:07.884056
2021-06-21T08:46:10
2021-06-21T08:46:10
374,940,766
2
0
null
null
null
null
UTF-8
C++
false
false
2,189
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include<QPushButton> #include<QLineEdit> #include <QLabel> #include<QHBoxLayout> #include<QVBoxLayout> #include<QGridLayout> #include<QString> #include<QStack> #include<QTime> #include<iterator> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_Formula_linkActivated(const QString &link); void buttonZeroClicked(); void buttonOneClicked(); void buttonTwoClicked(); void buttonThreeClicked(); void buttonFourClicked(); void buttonFiveClicked(); void buttonSixClicked(); void buttonSevenClicked(); void buttonEightClicked(); void buttonNineClicked(); void buttonAddClicked();//+ void buttonSubClicked();//- void buttonMulClicked();//乘 void buttonDivClicked();//除 void buttonTimClicked(); //时间 void buttonDecClicked();//小数点 void buttonBotClicked(); //加减号 void buttonEquClicked();//等于号 void buttonLefClicked();//左括号 void buttonRigClicked();//右括号 void buttonCEClicked();//CE void buttonACClicked();//AC private: QLineEdit *inputLine;//显示框 QString input="0"; //输入框 bool flat=false; //0-9按钮 QPushButton *zeroButton; QPushButton *oneButton; QPushButton *twoButton; QPushButton *threeButton; QPushButton *fourButton; QPushButton *fiveButton; QPushButton *sixButton; QPushButton *sevenButton; QPushButton *eightButton; QPushButton *nineButton; QLabel *label; QPushButton *addButton; QPushButton *subButton; QPushButton *divButton; QPushButton *mulButton; QPushButton *equButton; QPushButton *timButton; //Time QPushButton *decButton; QPushButton *botButton; QPushButton *CEButton; QPushButton *ACButton; QPushButton *lefButton; QPushButton *rigButton; Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
b4cf898e9302293b6cd2e8aa6cfa4e48a89b3649
980a4702cf5396ab54cb0e9282055e1e2d3edd1d
/libnd4j/tests_cpu/layers_tests/DeclarableOpsTests4.cpp
56e5e213a0bb4a6712363f6e46838533ac99c08c
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
pxiuqin/deeplearning4j
5d7abea2102ad3c8d6455803f7afc5e7641062a1
e11ddf3c24d355b43d36431687b807c8561aaae4
refs/heads/master
2022-12-02T00:09:48.450622
2020-08-13T10:32:14
2020-08-13T10:32:14
277,511,646
1
0
Apache-2.0
2020-08-13T10:32:16
2020-07-06T10:28:22
null
UTF-8
C++
false
false
101,828
cpp
DeclarableOpsTests4.cpp
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #include "testlayers.h" #include <ops/declarable/CustomOperations.h> #include <helpers/helper_hash.h> #include <array/NDArray.h> #include <array/NDArrayList.h> using namespace sd; using namespace sd::graph; class DeclarableOpsTests4 : public testing::Test { public: DeclarableOpsTests4() { printf("\n"); fflush(stdout); sd::ops::adjust_hue op0; sd::ops::adjust_saturation op1; } }; template <typename T> class TypedDeclarableOpsTests4 : public testing::Test { public: TypedDeclarableOpsTests4() { printf("\n"); fflush(stdout); sd::ops::adjust_hue op0; sd::ops::adjust_saturation op1; } }; typedef ::testing::Types<double, float> TestingTypes; TYPED_TEST_CASE(TypedDeclarableOpsTests4, TestingTypes); ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_1) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 4, 4, 2}); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 2}, {6.f, 7.f, 10.f, 11.f, 22.f, 23.f, 26.f, 27.f, 38.f, 39.f, 42.f, 43.f, 54.f, 55.f, 58.f, 59.f}); x.linspace(1); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {}, {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_2) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 4, 4, 2}); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 2}, {6.f, 7.f, 10.f, 11.f, 22.f, 23.f, 26.f, 27.f, 38.f, 39.f, 42.f, 43.f, 54.f, 55.f, 58.f, 59.f}); x.linspace(1); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {}, {2, 2, 2, 2, 0, 0, 1, 1, 0, 1, 1}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_3) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 5, 5, 2}); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 3, 3, 2}, {7.f, 8.f, 11.f, 12.f, 14.f, 15.f, 27.f, 28.f, 31.f, 32.f, 34.f, 35.f, 42.f, 43.f, 46.f, 47.f, 49.f, 50.f, 57.f, 58.f, 61.f, 62.f, 64.f, 65.f, 77.f, 78.f, 81.f, 82.f, 84.f, 85.f, 92.f, 93.f, 96.f, 97.f, 99.f, 100.f,}); x.linspace(1); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {}, {2, 2, 2, 2, 0, 0, 1, 1, 1, 0, 1}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_4) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 5, 5, 2}); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 2}, {7.f, 8.f, 11.f, 12.f, 27.f, 28.f, 31.f, 32.f, 57.f, 58.f, 61.f, 62.f, 77.f, 78.f, 81.f, 82.f}); x.linspace(1); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {}, {2, 2, 2, 2, 0, 0, 1, 1, 0, 1, 1}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_5) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 2, 5, 5}); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 3, 3}, {1.f, 2.5f, 4.5f, 8.5f, 10.f, 12.f, 18.5f, 20.f, 22.f, 26.f, 27.5f, 29.5f, 33.5f, 35.f, 37.f, 43.5f, 45.f, 47.f, 51.f, 52.5f, 54.5f, 58.5f, 60.f, 62.f, 68.5f, 70.f, 72.f, 76.f, 77.5f, 79.5f, 83.5f, 85.f, 87.f, 93.5f, 95.f, 97.f}); x.linspace(1); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {}, {2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_6) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 2, 5, 5}); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 3, 3}, {0.25f, 1.25f, 2.25f, 4.25f, 10.f, 12.f, 9.25f, 20.f, 22.f, 6.5f, 13.75f, 14.75, 16.75f, 35.f, 37.f, 21.75f, 45.f, 47.f, 12.75f, 26.25f, 27.25f, 29.25f, 60.f, 62.f, 34.25f, 70.f, 72.f, 19.f, 38.75f, 39.75f, 41.75f, 85.f, 87.f, 46.75f, 95.f, 97.f}); x.linspace(1); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {}, {2, 2, 2, 2, 1, 1, 1, 1, 0, 1, 0}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_7) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 2, 5, 5}); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 3, 3}, {4.f, 6.f, 7.5f, 14.f, 16.f, 17.5f, 21.5f, 23.5f, 25.f, 29.f, 31.f, 32.5f, 39.f, 41.f, 42.5f, 46.5f, 48.5f, 50.f, 54.f, 56.f, 57.5f, 64.f, 66.f, 67.5f, 71.5f, 73.5f, 75.f, 79.f, 81.f, 82.5f, 89.f, 91.f, 92.5f, 96.5f, 98.5f, 100.f}); x.linspace(1); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {}, {2, 2, 2, 2, 0, 0, 1, 1, 1, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_8) { auto x = NDArrayFactory::create<TypeParam>('c', {1, 1, 3, 3}); auto exp = NDArrayFactory::create<TypeParam>('c', {1, 1, 2, 2}, {3.f, 4.f, 6.f, 7.f}); x.linspace(1); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {}, {2, 2, 1, 1, 0, 0, 1, 1, 0, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_9) { auto x = NDArrayFactory::create<TypeParam>('c', {1, 1, 3, 3}); auto exp = NDArrayFactory::create<TypeParam>('c', {1, 1, 3, 3}, {3.f, 4.f, 4.5f, 6.f, 7.f, 7.5f, 7.5f, 8.5f, 9.f}); x.linspace(1); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {}, {2, 2, 1, 1, 0, 0, 1, 1, 1, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); //z->printShapeInfo("z shape:"); //z->printBuffer("z buffer:"); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, avgpool2d_10) { auto input = NDArrayFactory::create<TypeParam>('c', {4, 10, 10, 3}, {9.37125111f, 2.20166993f, 2.91434479f, 5.43639755f, -2.10573769f, 4.08528662f, 5.86908436f, -4.46203756f, 2.21057916f, 5.35849190f, 0.01394637f, 4.40566349f, 7.07982206f, -0.09633455f, 2.42429352f, 3.97301817f, -1.89553940f, 1.99690318f, 6.33141708f, 0.55401880f, 1.70707977f, 5.55204201f, -0.03513752f, 1.60011971f, 2.62700319f, -2.74582434f, 3.06697464f, 1.06277943f, -1.16075921f, -0.78095782f, 9.72352791f, -1.22686064f, 1.99644792f, 7.35571337f, 1.40607321f, 0.11390255f, 9.53334427f, 2.28303599f, -1.66728830f, 6.16678810f, -0.04532295f, -1.97708666f, 9.74906158f, 1.46223176f, -1.46734393f, 4.30761862f, -1.23790228f, 1.24823606f, 6.13938427f, -3.83689475f, -1.19625473f, 7.91535568f, 6.05868721f, -3.22946382f, 8.81633949f, -0.19967777f, 0.66053957f, 2.30919123f, 0.74543846f, -0.39347672f, 11.11058044f, 0.53720862f, 1.52645731f, 5.70012379f, -1.15213466f, 1.16451406f, 7.00526333f, 1.57362783f, -2.44384766f, 5.54213285f, -1.98828590f, -0.70483637f, 7.88281822f, -3.59875536f, 0.80745387f, 13.41578484f, -1.55507684f, -0.65855008f, 9.32583523f, -0.14544789f, 0.73436141f, 3.61176538f, -1.71268058f, -2.58490300f, 9.09280205f, -3.27405524f, -2.04569697f, 4.44761324f, -0.62955856f, -2.61917663f, 8.04890442f, 0.54579324f, 0.85929775f, 9.82259560f, -1.93825579f, 0.77703512f, 4.67090321f, -4.79267597f, -2.38906908f, 9.31265545f, 0.96026313f, -1.14109385f, 11.54231834f, -0.01417295f, -0.39500344f, 8.49191666f, 0.55300158f, 2.79490185f, 6.92466164f, 1.72254205f, 2.82222271f, 8.83112717f, 2.95033407f, 2.18054962f, 6.73509789f, -2.22272944f, 0.51127720f, -1.04563558f, 2.15747333f, -2.30959272f, 9.55441570f, 1.50396204f, 1.77370787f, 7.38146257f, -1.79076433f, 3.20961165f, 7.18864202f, 2.91217351f, 0.43018937f, 7.11078024f, -1.17386127f, -0.16817921f, 6.12327290f, -2.82205725f, 3.30696845f, 13.51291752f, -1.30856836f, -2.38332748f, 11.09487438f, -1.47190213f, -0.53050828f, 4.38285351f, -5.07309771f, 1.50714362f, 5.72274446f, -2.85825086f, -0.89673209f, 3.73791552f, -0.67708802f, -4.13149452f, -0.00671843f, -0.26566532f, 0.32961160f, 7.14501762f, -1.41608179f, -4.96590328f, 12.26205540f, -0.65158135f, -0.88641000f, 6.95777559f, -0.79058206f, -0.10260171f, 7.87169170f, 1.35921454f, 1.11759663f, 5.46187401f, -2.57214499f, 2.48484039f, 4.04043484f, -2.07137156f, -1.42709637f, 9.25487137f, -0.12605135f, -2.66949964f, 2.89412403f, 0.74451172f, -2.96250391f, 3.99258423f, 0.27084303f, 0.32213116f, 5.42332172f, -0.44414216f, 1.70881832f, 6.69346905f, 0.53058422f, -4.73146200f, 4.22051668f, 2.24834967f, 0.66996074f, 4.30173683f, 0.11849818f, -4.07520294f, 8.27318478f, -2.54398274f, -2.86705542f, 10.11775303f, -0.99382895f, 0.65881538f, 7.93556786f, -1.27934420f, -1.69343162f, 9.68042564f, -1.02609646f, -1.18189347f, 5.75370646f, -1.67888868f, -4.48871994f, 4.79537392f, -0.79212248f, -0.19855022f, 6.15060997f, -0.01081491f, 3.64454579f, 10.82562447f, 1.58859253f, -2.65847278f, 8.60093212f, -1.59196103f, 0.07635692f, 11.76175690f, -1.17453325f, 0.10122013f, 6.86458445f, -2.18891335f, -2.74004745f, 8.07066154f, 0.71818852f, -2.03035975f, 6.31053686f, 0.51509416f, 1.39789927f, 9.43515587f, 2.04256630f, 0.13985133f, 4.65010691f, 2.40911126f, -0.36255789f, -3.06867862f, -0.45225358f, -1.56778407f, 6.05917358f, -1.09891272f, 1.77184200f, 6.46248102f, 0.96042323f, -0.24346280f, 4.63436460f, -4.69907761f, 1.25187206f, 11.46173859f, -2.21917558f, 1.28007793f, 6.92173195f, 2.11268163f, -3.47389889f, 5.08722782f, -3.03950930f, -4.17154264f, 11.30568314f, 0.80361372f, 2.53214502f, 7.18707085f, -4.49114513f, 2.85449266f, 10.14906883f, -0.31974933f, -0.84472644f, -0.52459574f, 0.12921631f, -1.81390119f, 2.76170087f, 1.03982210f, 2.91744232f, -0.29048753f, 5.87453508f, -1.53684759f, 1.85800636f, -0.91404629f, 1.28954852f, 5.11354685f, -2.47475505f, -1.33179152f, 2.58552408f, 1.37316465f, -3.32339454f, 1.54122913f, 3.24953628f, -0.29758382f, 2.82391763f, -1.51142192f, -1.22699404f, 6.75745535f, 0.65452754f, -3.29385471f, 2.06008053f, 2.53172946f, -4.23532820f, -1.53909743f, -0.07010663f, -1.42173731f, 7.29031610f, -0.18448229f, 4.59496164f, 6.73027277f, 0.73441899f, 0.14426160f, 4.14915276f, -2.97010231f, 6.05851364f, 4.95218086f, -2.39145470f, 2.40494704f, 2.10288811f, 0.53503096f, 1.44511235f, 6.66344261f, -3.05803776f, 7.21418667f, 3.30303526f, -0.24163735f, 3.47409391f, 3.64520788f, 2.15189481f, -3.11243272f, 3.62310791f, 0.37379482f, 0.40865007f, -0.83132005f, -4.78246069f, 2.07030797f, 6.51765442f, 3.16178989f, 5.06180477f, 3.78434467f, -0.96689719f, 0.35965276f, 5.89967585f, 1.40294051f, 1.11952639f, 10.59778214f, 0.26739889f, -1.61297631f, 6.24801159f, -0.93914318f, -0.57812452f, 9.92604542f, -0.73025000f, -3.38530874f, 2.45646000f, -2.47949195f, 0.51638460f, 10.65636063f, 1.97816694f, -3.00407791f, 2.66914415f, -0.81951088f, -0.23316640f, 2.40737987f, -2.70007610f, 1.51531935f, 4.08860207f, -0.27552786f, -1.31721711f, 7.11568260f, -3.33498216f, -4.02545023f, 7.22675610f, -0.81690705f, -2.52689576f, 1.04016697f, -0.79291463f, -0.34875512f, 10.00498390f, -4.24167728f, 1.46162593f, 11.82569408f, -1.70359993f, -0.30161047f, 16.44085884f, -0.82253462f, -0.09435523f, 6.13080597f, -0.20259480f, 0.68308711f, 6.15663004f, -6.61776876f, 0.33295766f, 2.55449438f, -0.17819691f, -1.14892209f, 5.56776142f, 1.99279118f, 1.33035934f, 4.45823956f, 3.34916544f, -2.59905386f, 6.16164446f, -2.03881931f, -2.45273542f, 12.46793365f, -2.22743297f, 2.83738565f, 8.48628139f, -1.39347959f, -1.30867767f, 11.08041477f, -4.00363779f, 2.09183025f, 11.30395889f, -2.20504737f, 1.37426853f, 8.98735619f, 1.04676604f, -0.72757077f, 8.28050232f, -6.70741081f, -0.65798020f, 5.68592072f, -0.60760021f, 0.35854483f, 6.26852131f, 1.94100165f, 1.32112014f, 0.80987954f, -1.74617672f, -0.25434083f, 7.16045523f, 1.58884013f, -2.64847064f, 13.14820385f, 1.21393633f, -2.47258949f, 9.41650105f, -0.79384226f, 2.48954105f, 10.95629311f, 0.47723705f, 4.02126694f, 8.02593136f, -2.20726371f, -1.18794477f, 1.50836647f, 0.93118095f, -1.73513174f, 8.85493565f, -2.99670315f, -0.79055870f, 2.39473820f, 2.05046916f, -2.38055134f, 11.82299423f, 0.15609655f, 0.68744308f, 5.66401434f, -0.69281673f, 2.09855556f, 7.74626589f, -0.34283102f, 1.00542057f, 9.95838642f, 0.80161905f, 2.33455157f, 9.80057335f, -0.93561798f, 2.56991577f, 8.29711342f, 0.94213426f, 0.44209945f, 11.70259857f, 0.92710167f, 2.60957146f, 0.24971688f, -0.86529571f, 3.78628922f, 6.80884457f, -0.68178189f, 2.21103406f, 3.18895817f, 0.60283208f, -2.92716241f, 6.72060776f, -1.06625068f, 2.56543374f, 9.97404480f, 3.58080721f, -0.94936347f, 10.16736984f, -1.38464379f, 1.18191063f, 6.66179037f, -3.56115270f, 0.32329530f, 10.90870762f, 2.20638227f, 0.19653285f, 7.34650040f, -3.63859272f, -1.03027737f, 5.98829985f, -3.66606474f, -3.89746714f, 8.63469028f, 1.22569811f, 1.63240814f, 3.74385309f, 0.58243257f, -0.56981975f, 3.69260955f, 1.00979900f, -1.44030499f, 8.57058144f, -1.10648811f, 1.20474911f, 5.43133020f, -2.14822555f, -0.07928789f, 11.25825310f, 0.19645604f, -5.49546146f, 10.41917038f, -0.68178523f, -2.99639869f, 6.50054455f, 0.46488351f, -5.42328453f, 9.09500027f, -2.82107449f, 0.05601966f, 15.34610748f, -0.06820253f, 3.86699796f, 10.73316956f, -3.04795432f, -0.14702171f, 5.64813185f, 1.44028485f, -2.47596145f, 0.07280898f, -3.03187990f, -1.35183525f, 9.35835648f, 2.72966957f, 1.88199532f, 10.36187744f, -0.22834805f, -3.26738238f, 6.92025137f, -2.34061313f, 4.77379704f, 5.28559113f, -2.96323752f, -1.76186585f, 5.94436455f, 0.38647744f, -5.73869514f, 6.76849556f, 1.40892124f, -1.19068217f, 5.37919092f, -6.65328646f, 3.62782669f, 12.34744644f, 2.44762444f, -4.19242620f, 6.14906216f, 0.08121119f, 0.61355996f, 2.69666457f, -1.88962626f, -0.55314136f, 1.84937525f, 1.56048691f, 1.17460012f, 3.75674725f, 1.06198275f, -5.74625874f, 5.41645575f, -1.28946674f, -1.51689398f, 4.32400894f, -0.05222082f, -4.83948946f, 1.80747867f, 1.63144708f, -2.73887825f, 1.63975775f, -2.02163982f, -0.16210437f, 2.93518686f, 1.14427686f, -2.83246303f, 4.79283667f, 2.69697428f, -3.12678456f, -1.19225168f, -2.37022972f, -3.09429741f, 1.94225383f, -1.13747168f, -2.55048585f, 5.40242243f, 1.12777328f, 3.43713188f, 3.62658787f, -2.16878843f, 0.30164462f, 2.97407579f, -0.07275413f, -1.31149673f, 4.70066261f, -2.01323795f, 4.85255766f, 4.59128904f, 1.68084168f, 1.60336494f, 6.58138466f, -1.04759812f, 2.69906545f, 3.55769277f, -0.74327278f, 2.65819693f, 5.39528131f, 2.11248922f, -1.06446671f, 5.24546766f, -2.43146014f, 4.58907509f, 0.06521678f, -2.24503994f, 2.45722699f, 6.94863081f, 0.35258654f, 2.83396196f, 9.92525196f, -1.12225175f, -0.34365177f, 7.19116688f, -4.39813757f, 0.46517885f, 13.22028065f, -2.57483673f, -6.37226963f, 7.58046293f, -2.74600363f, 0.42231262f, 8.04881668f, 0.17289802f, -0.53447008f, 16.55157471f, -5.63614368f, 0.39288223f, 3.37079263f, 1.26484549f, -0.12820500f, 8.46440125f, -4.39304399f, 2.97676420f, 0.65650189f, 0.83158541f, -1.11556435f, 6.32885838f, -0.36087769f, 2.80724382f, 9.90292645f, 1.15936041f, 0.20947981f, 6.91249275f, -2.67404819f, 2.93782163f, 6.65656614f, -2.30828357f, 2.98214006f, 6.80611229f, -4.93821478f, -7.66555262f, 7.59763002f, -0.54159302f, 3.87403512f, 12.42607784f, 2.59284401f, -0.23375344f, 8.95293331f, -0.71807784f, 0.61873478f, 8.66713524f, 1.24289191f, -2.37835455f, 2.08071637f, -0.88315344f, -3.41891551f, 6.85245323f, 1.73007369f, 1.02169311f, 7.69170332f, -2.85411978f, 2.69790673f, 8.12906551f, -1.19351399f, -2.26442742f, 12.26104450f, -0.75579089f, -1.73274946f, 10.68729019f, 2.20655656f, -0.90522075f, 12.42165184f, -1.67929137f, 2.44851565f, 9.31565762f, -0.06645700f, 1.52762020f, 6.18427515f, -1.68882596f, 3.70261097f, 3.02252960f, -3.44125366f, -1.31575799f, 2.84617424f, -0.96849400f, -4.52356243f, 9.95027161f, 0.19966406f, -0.78874779f, 8.18595028f, -4.08300209f, 1.75126517f, 0.96418417f, -4.04913044f, -0.95200396f, 12.03637886f, -0.03041124f, 0.41642749f, 8.88267422f, -3.24985337f, -2.24919462f, 7.32566118f, 0.16964148f, -2.74123430f, 7.05264473f, -3.30191112f, 0.17163286f, 4.81851053f, -1.64463484f, -0.85933101f, 7.29276276f, 2.34066939f, -2.14860010f, 3.46148157f, -0.01782012f, 1.51504040f, 4.79304934f, 1.85281146f, -1.70663762f, 6.93470192f, -4.15440845f, -1.25983095f, 10.52491760f, 0.42930329f, -1.85146868f, 11.70042324f, -0.41704914f, 3.83796859f, 9.21148491f, -2.79719448f, 0.79470479f, 6.26926661f, -5.85230207f, 3.95105338f, 7.84790897f, -1.38680744f, -1.78099084f, 11.95235348f, -2.99841452f, -1.34507811f, 6.15714645f, -1.07552516f, -2.81228638f, 1.66234732f, -4.55166149f, -1.92601109f, 8.64634514f, -0.48158705f, 3.31595659f, 7.67371941f, 2.56964207f, 0.12107098f, 4.56467867f, -0.93541539f, 1.39432955f, 11.99714088f, 1.05353570f, -2.13099813f, 3.67617917f, 3.45895386f, 1.37365830f, 8.74344158f, -4.17585802f, 1.43908918f, 6.28764772f, 3.97346330f, -0.69144285f, 9.07983303f, -0.41635889f, -0.14965028f, 8.85469818f, 1.11306190f, 2.59440994f, 5.38982344f, -1.07948279f, 1.37252975f, 10.26984596f, -0.09318046f, 2.73104119f, 12.45902252f, -1.55446684f, -2.76124811f, 12.19395065f, -0.51846564f, 1.02764034f, 11.42673588f, -0.95940983f, -0.04781032f, 8.78379822f, -4.88957930f, 0.32534006f, 11.97696400f, -3.35108662f, 1.95104563f, 4.46915388f, -2.32061648f, 3.45230985f, 8.29983711f, 2.81034684f, -2.35529327f, 6.07801294f, -0.98105043f, -0.05359888f, 2.52291036f, -0.01986909f, -2.35321999f, 10.51954269f, 2.11145401f, 3.53506470f, 7.29093266f, 0.03721160f, -1.13496494f, 7.43886709f, -5.84201956f, 2.50796294f, 12.14647675f, 2.77490377f, -2.18896222f, 6.05641937f, 5.32617044f, 1.04221284f, 10.79106712f, -2.95749092f, -2.75414610f, 11.30037117f, -3.40654182f, -2.24673963f, 7.49126101f, 0.70811015f, -6.18003702f, 13.83951187f, -1.01204085f, 1.36298490f, -1.04451632f, 2.42435336f, -0.02346706f, -0.85528886f, 1.04731262f, 0.22192979f, 4.15708160f, 0.34933877f, 0.04814529f, 2.24107265f, 0.49676740f, -1.47752666f, 0.45040059f, -0.70471478f, -1.19759345f, 0.21711677f, 0.88461423f, -2.76830935f, 5.52066898f, 1.97664857f, -1.75381601f, 3.45877838f, 1.52617192f, -1.61350942f, 0.85337949f, 1.97610760f, -3.40310287f, 3.40319014f, -3.38691044f, -0.71319139f, 1.65463758f, -0.60680127f, -1.80700517f, 8.02592373f, 2.59627104f, 2.65895891f, 5.93043184f, -4.48425817f, 3.92670918f, 4.19496679f, -2.28286791f, 6.41634607f, 5.72330523f, 1.16269672f, -0.28753027f, 2.46342492f, 0.36693189f, 0.26712441f, 6.37652683f, -2.50139046f, 2.43923736f, 5.56310415f, 0.98065847f, 1.04267502f, 4.16403675f, -0.04966142f, 4.40897894f, 3.72905660f, -3.46129870f, 3.59962773f, 1.34830284f, -1.76661730f, 0.47943926f, 5.29946661f, -1.12711561f, 1.26970029f, 15.17655945f, -1.50971997f, 5.81345224f, 8.48562050f, -4.36049604f, 2.48144460f, 8.23780441f, -3.46030426f, -0.84656560f, 5.94946814f, 1.12747943f, -2.65683913f, 8.69085693f, 1.31309867f, -2.79958344f, 8.76840591f, -1.56444156f, 1.62710834f, 2.41177034f, -0.72804940f, 5.70619011f, 4.67169666f, -0.86167198f, -1.83803177f, 2.96346045f, 2.82692933f, -2.81557131f, 7.11113358f, -1.90071094f, 2.54244423f, 11.19284058f, -0.06298946f, -1.71517313f, 12.98388577f, 0.84510714f, 3.00816894f, 2.57200313f, 0.03899818f, -1.49330592f, 9.60099125f, -3.59513044f, -1.30045319f, 7.09241819f, -0.65233821f, -2.33627677f, 8.81366920f, 0.84154201f, 1.03312039f, 9.85289097f, 0.19351870f, 1.78496623f, 7.34631205f, -2.16530800f, -0.65016162f, 2.46842360f, 0.24016285f, -1.24308395f, 4.78175163f, -0.97682536f, 2.20942235f, 6.68382788f, 3.76786447f, -1.44454038f, 6.26453733f, -3.23575711f, -2.30137897f, 9.53092670f, -5.55222607f, 3.25999236f, 9.37559509f, 1.86339056f, -0.23551451f, 10.23400211f, 3.93031883f, -0.52629089f, 7.85724449f, -2.91549587f, 4.46612740f, 5.66530371f, -2.70820427f, 4.81359577f, 10.31247330f, 1.92230141f, 2.53931546f, 0.74986327f, 1.70303428f, 0.48063779f, 5.31099129f, -0.78976244f, 3.75864220f, 4.23051405f, 2.34042454f, -7.98193836f, 9.83987141f, -1.46722627f, 3.54497814f, 10.36455154f, -4.51249075f, 0.77715248f, 7.78694630f, -4.59989023f, -2.49585629f, 9.90296268f, 1.38535416f, 1.17441154f, 10.10452843f, -0.98628229f, 0.60194463f, 9.12639141f, -3.90754628f, 2.88526392f, 7.24123430f, -0.15283313f, -0.75728363f, -1.15116858f, -2.53791571f, 0.77229571f, 6.44114161f, 0.02646767f, 4.95463037f, 7.21066380f, 1.79384065f, 0.73250306f, 8.04447937f, 0.32576546f, -0.79447043f, 10.12717724f, 2.33392906f, 1.30716443f, 12.36073112f, -0.36694977f, -1.20438910f, 7.03105593f, 0.59557682f, 0.69267452f, 10.18113136f, 2.49944925f, -0.42229167f, 8.83143330f, -1.18805945f, -2.87509322f, 4.53596449f, 4.09732771f, -3.39088297f, -1.02536607f, 0.82119560f, -3.47302604f, 9.29991817f, 0.21001509f, 4.97036457f, 9.50018406f, 1.04420102f, 1.96560478f, 10.74769592f, -6.22709799f, 3.11690164f, 5.06759691f, -1.23724771f, -3.05831861f, 8.12925529f, -1.93435478f, -1.10151744f, 9.32263088f, -0.04249470f, -5.98547363f, 10.49398136f, 0.26400441f, -0.78915191f, 13.28219604f, 2.99276900f, 0.74853164f, 2.49364305f, -3.43529654f, 4.05278301f, 2.13498688f, -2.35444307f, -0.79900265f, 4.66968822f, -0.31095147f, 3.60674143f, 12.37222099f, -0.07855003f, -3.30292702f, 12.15215874f, 0.60886210f, 2.87075138f, 7.75271845f, 0.38044083f, 3.34402204f, 6.40583277f, -0.87888050f, 0.67438459f, 6.91080809f, 1.98332930f, -0.08303714f, 8.08630371f, -0.16772588f, -2.74058914f, 7.17253590f, -2.69122696f, 1.48173678f, 8.99470139f, -1.43302310f, -0.88651133f, 2.66944790f, -0.29186964f, 2.00838661f, 5.09587479f, -0.76676071f, -2.88322186f, 8.31110573f, -0.14550979f, -1.37726915f, 10.28355122f, -1.60575438f, -0.04118848f, 9.97510815f, 0.14440438f, -3.24632120f, 9.00034523f, 4.14319563f, -1.31023729f, 7.16950464f, -0.70428526f, 2.01559544f, 7.26155043f, 2.40816474f, 2.09847403f, 7.31264496f, -0.75401551f, 2.13392544f, 7.03648758f, 1.04036045f, -1.15636516f, 1.09634531f, -0.06340861f, -0.58107805f, -0.65623116f, 1.18972754f, -0.80717683f, 1.40118241f, -0.61932516f, -3.60596156f, 1.59904599f, -2.23774099f, -1.13721037f, 3.89620137f, -0.09115922f, -7.51356888f, 2.36975193f, -1.42520905f, -2.34173775f, 3.33830214f, -2.74016523f, -3.04115510f, 6.00119495f, -1.36084354f, -2.45065260f, 4.56992292f, -3.02825928f, -3.74182844f, 5.11069250f, -0.91531068f, -2.31385994f, 1.83399653f, 3.39370203f, -3.60886002f}); auto exp = NDArrayFactory::create<TypeParam>('c', {4, 4, 4, 3}, {7.97172260f, 0.06878620f, 2.27749538f, 7.29276514f, -0.14074677f, 0.65480286f, 5.70313978f, -0.06546132f, 0.35443667f, 3.70382833f, -0.84020567f, 0.63826996f, 8.60301399f, -0.38236514f, 1.55177069f, 7.37542057f, -0.99374938f, -0.29971302f, 8.84352493f, -0.67121059f, 0.43132120f, 4.78175592f, -1.25070143f, -1.91523600f, 6.03855371f, -0.00292124f, -1.11214364f, 7.90158176f, -0.57949901f, -0.96735370f, 7.81192017f, -0.53255427f, -0.48009714f, 3.16953635f, 0.08353355f, -1.54299748f, 3.74821687f, 1.69396687f, 0.72724354f, 5.42915201f, -1.13686812f, -0.71793109f, 5.78376389f, -0.72239977f, -0.60055625f, 2.53636408f, 0.56777251f, -2.07892323f, 6.08064651f, 0.68620735f, 2.54017019f, 5.65828180f, -0.68255502f, 1.47283304f, 6.10842514f, -0.39655915f, 0.28380761f, 1.96707797f, -1.98206317f, 0.94027776f, 4.71811438f, 0.32104525f, -0.92409706f, 8.34588146f, -1.05581069f, -0.55217457f, 9.58440876f, -0.96549922f, 0.45820439f, 5.65453672f, -2.50953507f, -0.71441835f, 8.03059578f, -0.21281289f, 0.92125505f, 9.26900673f, -0.35963219f, -0.70039093f, 8.59924412f, -1.22358346f, 0.81318003f, 3.85920119f, -0.01305223f, -1.09234154f, 6.33158875f, 1.28094780f, -1.48926139f, 4.94969177f, -0.77126902f, -1.97033751f, 5.64381838f, -0.16285487f, -1.31277227f, 2.39893222f, -1.32902908f, -1.39609122f, 6.47572327f, -0.45267010f, 1.55727172f, 6.70965624f, -1.68735468f, -0.05672536f, 7.25092363f, -0.64613032f, 0.67050058f, 3.60789680f, -2.05948973f, 2.22687531f, 8.15202713f, -0.70148355f, 1.28314006f, 8.14842319f, -1.88807654f, -1.04808438f, 8.45500565f, -0.76425624f, 0.94542569f, 4.56179953f, -0.28786001f, -2.04502511f, 8.46278095f, -0.31019822f, 0.07339200f, 9.34214592f, -0.61948007f, 0.52481830f, 8.32515621f, -1.52418160f, 0.49678251f, 5.11082315f, -1.09908783f, -0.52969611f, 5.27806664f, 0.88632923f, 0.66754371f, 4.75839233f, 0.48928693f, -0.68036932f, 6.56925392f, -0.02949905f, -2.99189186f, 4.46320581f, -0.64534980f, -0.29516968f, 8.60809517f, -1.13120568f, 3.41720533f, 5.84243155f, -1.24109328f, 0.89566326f, 5.99578333f, -0.42496428f, 2.07076764f, 3.17812920f, -0.81566459f, -0.14363396f, 6.55184317f, 0.39633346f, -0.43852386f, 8.70214558f, -2.24613595f, 0.30708700f, 8.73882294f, -0.53545928f, 1.54409575f, 4.49452257f, -0.16509305f, 0.19028664f, 8.24897003f, 0.44750381f, 2.15448594f, 8.97640514f, -0.77728152f, 0.57272542f, 9.03467560f, 0.47173575f, -1.10807717f, 3.30056310f, -0.43268481f, -0.41470885f, 3.53798294f, -0.08546703f, -2.16840744f, 6.18733406f, -0.17871059f, -2.59837723f, 5.94218683f, -1.02990067f, -0.49760687f, 3.76938033f, 0.86383581f, -1.91504073f}); sd::ops::avgpool2d op; auto result = op.evaluate({&input}, {3,3, 3,3, 0,0, 1,1,1, 0,1}); ASSERT_EQ(Status::OK(), result.status()); auto z = result.at(0); // z->printIndexedBuffer("z"); // exp.printIndexedBuffer("e"); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, avgpool2d_11) { int inOutH = 5;// 35; int inOutW = 5;// 35; int inOutC = 10;// 192; auto x = NDArrayFactory::create<double>('c', {1, inOutH, inOutW, inOutC}); x.linspace(1.0); sd::ops::avgpool2d op; auto result = op.evaluate({&x}, {3,3, 1,1, 0,0, 1,1, 1, 0, 1}); ASSERT_EQ(Status::OK(), result.status()); auto z = result.at(0); int totalPadHeight = (inOutH - 1) * 1 + 3 - inOutH; int padTop = totalPadHeight / 2; int padBottom = totalPadHeight - totalPadHeight / 2; int k = 3; auto m = NDArrayFactory::create<double>('c', {1, inOutH, inOutW, inOutC}); auto c = NDArrayFactory::create<double>('c', {1, inOutH, inOutW, inOutC}); for (int h = 0; h < inOutH; h++) { for (int w = 0; w < inOutW; w++) { int hFrom = h - padTop; int wFrom = w - padBottom; int hTo = hFrom + k; int wTo = wFrom + k; hFrom = sd::math::nd4j_max<int>(0, hFrom); wFrom = sd::math::nd4j_max<int>(0, wFrom); hTo = sd::math::nd4j_min<int>(inOutH, hTo); wTo = sd::math::nd4j_min<int>(inOutW, wTo); int idxOut[4]; int idxIn[4]; for (int ch = 0; ch < inOutC; ch++) { idxOut[1] = h; idxOut[2] = w; idxOut[3] = ch; idxIn[3] = ch; for (int kh = hFrom; kh < hTo; kh++) { for (int kw = wFrom; kw < wTo; kw++) { idxIn[1] = kh; idxIn[2] = kw; auto inVal = x.e<double>(0, kh, kw, ch); m.p(0, h, w, ch, inVal + m.e<double>(0, h, w, ch)); c.p(0, h, w, ch, 1 + c.e<int>(0, h, w, ch)); } } } } } m /= c; ASSERT_EQ(m, *z); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, avgpool2d_12) { int bS=4, iH=10,iW=10, iC=3, kH=3,kW=3, sH=3,sW=3, pH=0,pW=0, dH=1,dW=1; int oH=4, oW=4; int paddingMode = 1; // 1-SAME, 0-VALID int dataFormat = 1; // 1-NHWC, 0-NDHW auto input = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}); auto expected = NDArrayFactory::create<double>('c', {bS, oH, oW, iC}, { 17.5, 18.5, 19.5, 25. , 26. , 27. , 34. , 35. , 36. , 41.5, 42.5, 43.5, 92.5, 93.5, 94.5, 100. , 101. , 102. , 109. , 110. , 111. , 116.5, 117.5, 118.5, 182.5, 183.5, 184.5, 190. , 191. , 192. , 199. , 200. , 201. , 206.5, 207.5, 208.5, 257.5, 258.5, 259.5, 265. , 266. , 267. , 274. , 275. , 276. , 281.5, 282.5, 283.5, 317.5, 318.5, 319.5, 325. , 326. , 327. , 334. , 335. , 336. , 341.5, 342.5, 343.5, 392.5, 393.5, 394.5, 400. , 401. , 402. , 409. , 410. , 411. , 416.5, 417.5, 418.5, 482.5, 483.5, 484.5, 490. , 491. , 492. , 499. , 500. , 501. , 506.5, 507.5, 508.5, 557.5, 558.5, 559.5, 565. , 566. , 567. , 574. , 575. , 576. , 581.5, 582.5, 583.5, 617.5, 618.5, 619.5, 625. , 626. , 627. , 634. , 635. , 636. , 641.5, 642.5, 643.5, 692.5, 693.5, 694.5, 700. , 701. , 702. , 709. , 710. , 711. , 716.5, 717.5, 718.5, 782.5, 783.5, 784.5, 790. , 791. , 792. , 799. , 800. , 801. , 806.5, 807.5, 808.5, 857.5, 858.5, 859.5, 865. , 866. , 867. , 874. , 875. , 876. , 881.5, 882.5, 883.5, 917.5, 918.5, 919.5, 925. , 926. , 927. , 934. , 935. , 936. , 941.5, 942.5, 943.5, 992.5, 993.5, 994.5,1000. , 1001. , 1002. ,1009. , 1010. , 1011. ,1016.5, 1017.5, 1018.5, 1082.5, 1083.5, 1084.5,1090. , 1091. , 1092. ,1099. , 1100. , 1101. ,1106.5, 1107.5, 1108.5,1157.5, 1158.5, 1159.5,1165. , 1166. , 1167. ,1174. , 1175. , 1176. ,1181.5, 1182.5, 1183.5}); input.linspace(1.); sd::ops::avgpool2d op; auto results = op.evaluate({&input}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, 0, dataFormat}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); //output->printIndexedBuffer("output"); //expected.printIndexedBuffer("expected"); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, avgpool2d_13) { const int bS = 2; // batch size const int iD = 1; // input depth (number of picture channels, for example rgb=3) const int iH = 28; // picture height in pixels const int iW = 28; // picture width in pixels const int kH = 5; // kernel height in pixels const int kW = 5; // kernel width in pixels const int sH = 1; // stride step in horizontal direction const int sW = 1; // stride step in vertical direction const int pH = 0; // padding height const int pW = 0; // padding width const int dH = 2; // dilation height const int dW = 2; // dilation width const int oH = (iH - kH - (kH-1)*(dH-1) + 2*pH)/sH + 1; // output height const int oW = (iW - kW - (kW-1)*(dW-1) + 2*pW)/sW + 1; // output width auto x = NDArrayFactory::create_<float>('c', {bS,iD,iH,iW}); auto exp = NDArrayFactory::create<float>('c',{bS,iD,oH,oW}); // auto z('c',{bS,iD,oH,oW}); auto variableSpace = new VariableSpace(); variableSpace->putVariable(-1, x); // variableSpace->putVariable(1, &z); auto block = new Context(1, variableSpace, false); block->fillInputs({-1}); std::vector<int>* argI = block->getIArguments(); *argI = {kH,kW, sH,sW, pH,pW, dW,dH, 0, 0, 0}; // 0,1 - kernel Height/Width; 2,3 - stride Height/Width; 4,5 - pad Height/Width; 6,7 - dilation Height/Width; 8 - same mode; sd::ops::avgpool2d pooling; Nd4jStatus status = pooling.execute(block); ASSERT_EQ(ND4J_STATUS_OK, status); auto result = variableSpace->getVariable(block->getNodeId())->getNDArray(); ASSERT_TRUE(exp.isSameShape(result)); delete variableSpace; delete block; } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, avgpool2d_14) { const int bS = 2; const int iD = 1; const int iH = 28; const int iW = 28; const int kH = 5; const int kW = 5; const int sH = 1; const int sW = 1; const int pH = 0; const int pW = 0; const int dH = 1; const int dW = 1; const int oH = (iH - kH - (kH-1)*(dH-1) + 2*pH)/sH + 1; // output height const int oW = (iW - kW - (kW-1)*(dW-1) + 2*pW)/sW + 1; // output width auto x = NDArrayFactory::create_<float>('c', {bS,iD,iH,iW}); auto exp = NDArrayFactory::create<float>('c',{bS,iD,oH,oW}); // auto z('c',{bS,iD,oH,oW}); auto variableSpace = new VariableSpace(); variableSpace->putVariable(-1, x); // variableSpace->putVariable(1, &z); auto block = new Context(1, variableSpace, false); block->fillInputs({-1}); std::vector<int>* argI = block->getIArguments(); *argI = {kH,kW, sH,sW, pH,pW, dW,dH, 0, 0, 0}; // 0,1 - kernel Height/Width; 2,3 - stride Height/Width; 4,5 - pad Height/Width; 6,7 - dilation Height/Width; 8 - same mode; sd::ops::avgpool2d pooling; Nd4jStatus status = pooling.execute(block); ASSERT_EQ(ND4J_STATUS_OK, status); auto result = variableSpace->getVariable(block->getNodeId())->getNDArray(); // result->printShapeInfo(); ASSERT_TRUE(exp.isSameShape(result)); delete variableSpace; delete block; } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, Avgpool2d_test15) { const int bS = 2; const int iD = 1; const int iH = 28; const int iW = 28; const int kH = 5; const int kW = 5; const int sH = 1; const int sW = 1; const int pH = 0; const int pW = 0; const int dH = 1; const int dW = 1; const int oH = (int) sd::math::nd4j_ceil<float, int>(iH * 1.f / sH); const int oW = (int) sd::math::nd4j_ceil<float, int>(iW * 1.f / sW); auto x = NDArrayFactory::create_<float>('c', {bS,iD,iH,iW}); auto exp = NDArrayFactory::create<float>('c',{bS,iD,oH,oW}); // auto z('c',{bS,iD,oH,oW}); auto variableSpace = new VariableSpace(); variableSpace->putVariable(-1, x); // variableSpace->putVariable(1, &z); auto block = new Context(1, variableSpace, false); block->fillInputs({-1}); std::vector<int>* argI = block->getIArguments(); *argI = {kH,kW, sH,sW, pH,pW, dW,dH, 1, 0, 0}; // 0,1 - kernel Height/Width; 2,3 - stride Height/Width; 4,5 - pad Height/Width; 6,7 - dilation Height/Width; 8 - same mode; sd::ops::avgpool2d pooling; Nd4jStatus status = pooling.execute(block); ASSERT_EQ(ND4J_STATUS_OK, status); auto result = variableSpace->getVariable(block->getNodeId())->getNDArray(); // result->printShapeInfo(); ASSERT_TRUE(exp.isSameShape(result)); delete variableSpace; delete block; } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, avgpool2d_16) { int bS=2, iH=4,iW=4, iC=2, kH=2,kW=2, sH=2,sW=2, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int paddingMode = 1; // 1-SAME, 0-VALID int dataFormat = 1; // 1-NHWC, 0-NDHW NDArray input('c', {bS, iH, iW, iC}, sd::DataType::FLOAT32); NDArray output('f', {bS, oH, oW, iC}, sd::DataType::FLOAT32); NDArray expected('c', {bS, oH, oW, iC}, {6.f, 7.f, 10.f, 11.f, 22.f, 23.f, 26.f, 27.f, 38.f, 39.f, 42.f, 43.f, 54.f, 55.f, 58.f, 59.f}, sd::DataType::FLOAT32); input.linspace(1.); sd::ops::avgpool2d op; auto status = op.execute({&input}, {&output}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, 0, dataFormat}, {}); ASSERT_EQ(Status::OK(), status); // output.printBuffer(); //expected.printIndexedBuffer("expected"); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, biasadd_1) { auto x = NDArrayFactory::create<double>('c', {2, 3, 3, 2}); auto bias = NDArrayFactory::create<double>('c', {2}, {1, 2}); auto exp = NDArrayFactory::create<double>('c', {2, 3, 3, 2}, {1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f, 1.f, 2.f}); sd::ops::biasadd op; auto result = op.evaluate({&x, &bias}, {}, {}, {}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, biasadd_2) { auto x = NDArrayFactory::create<double>('c', {2, 2, 3, 3}); auto bias = NDArrayFactory::create<double>('c', {2}, {1, 2}); auto exp = NDArrayFactory::create<double>('c', {2, 2, 3, 3}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2}); sd::ops::biasadd op; auto result = op.evaluate({&x, &bias}, {}, {}, {true}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, biasadd_3) { auto x = NDArrayFactory::create<double>('c', {2, 3}); auto row = NDArrayFactory::create<double>('c', {3}, {1, 2, 3}); auto exp = NDArrayFactory::create<double>('c', {2, 3}, {1, 2, 3, 1, 2, 3}); sd::ops::biasadd op; auto result = op.evaluate({&x, &row}, {}, {}, {true}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, biasadd_bp_1) { NDArray x('c', {2,2,2,3}, {1.,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}, sd::DataType::FLOAT32); NDArray gradO('c', {2,2,2,3}, sd::DataType::FLOAT32); NDArray bias('c', {3}, {-1., -2, -3}, sd::DataType::FLOAT32); NDArray expGradB('c', {3}, {9.2, 10. , 10.8}, sd::DataType::FLOAT32); gradO.linspace(0.1, 0.1); sd::ops::biasadd_bp op; auto result = op.evaluate({&x, &bias, &gradO}, {}, {}, {false}); // NHWC ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto gradI = result.at(0); auto gradB = result.at(1); ASSERT_TRUE(gradI->isSameShape(gradO)); ASSERT_TRUE(gradI->equalsTo(gradO)); ASSERT_TRUE(gradB->isSameShape(expGradB)); ASSERT_TRUE(gradB->equalsTo(expGradB)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, biasadd_bp_2) { NDArray x('c', {2,3,2,2}, {1.,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}, sd::DataType::FLOAT32); NDArray gradO('c', {2,3,2,2}, sd::DataType::FLOAT32); NDArray bias('c', {3}, {-1., -2, -3}, sd::DataType::FLOAT32); NDArray expGradB('c', {3}, {6.8, 10., 13.2}, sd::DataType::FLOAT32); gradO.linspace(0.1, 0.1); sd::ops::biasadd_bp op; auto result = op.evaluate({&x, &bias, &gradO}, {}, {}, {true}); // NCHW ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto gradI = result.at(0); auto gradB = result.at(1); ASSERT_TRUE(gradI->isSameShape(gradO)); ASSERT_TRUE(gradI->equalsTo(gradO)); ASSERT_TRUE(gradB->isSameShape(expGradB)); ASSERT_TRUE(gradB->equalsTo(expGradB)); } TEST_F(DeclarableOpsTests4, biasadd_4) { if (!Environment::getInstance().isExperimentalBuild()) return; auto x = NDArrayFactory::create<double>('c', {2, 3}); auto y = NDArrayFactory::create<float>('c', {3}, {1.f, 2.f, 3.f}); auto z = NDArrayFactory::create<float>('c', {2, 3}); auto exp = NDArrayFactory::create<float>('c', {2, 3}, {1.f, 2.f, 3.f, 1.f, 2.f, 3.f}); sd::ops::biasadd op; auto status = op.execute({&x, &y}, {&z}, {}, {}, {true}); ASSERT_EQ(Status::OK(), status); ASSERT_EQ(exp, z); } TEST_F(DeclarableOpsTests4, Test_Fill_1) { auto x = NDArrayFactory::create<int>('c', {1, 3}, {3, 2, 4}); auto v = NDArrayFactory::create<double>(2.); auto exp = NDArrayFactory::create<double>('c', {3, 2, 4}); exp.assign(2.0f); sd::ops::fill op; auto result = op.evaluate({&x, &v}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_FirasSparce_1) { auto x = NDArrayFactory::create<double>('c', {1, 81}); auto exp = NDArrayFactory::create<double>('c', {1, 2}, {0, 1}); x.p(51, 1); x.p(52, 0); x.p(60, 1); x.p(61, 0); sd::ops::firas_sparse op; auto result = op.evaluate({&x}, {0, 1}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); // z->printIndexedBuffer("FIRAS"); // z->printShapeInfo("OUTSHAPE"); // ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_FlattenTests_1) { auto x = NDArrayFactory::create<double>('c', {3, 3, 3, 3}); auto exp = NDArrayFactory::create<double>('c', {81}); x.linspace(1); exp.linspace(1); sd::ops::flatten op; auto result = op.evaluate({&x}, {}, {'c'}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); // z->printIndexedBuffer("Flatten1"); // z->printShapeInfo("Flatten1 shape"); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_FlattenTests_2) { auto x = NDArrayFactory::create<double>('c', {3, 3, 3, 3}); auto y = NDArrayFactory::create<double>('c', {3, 3}); auto exp = NDArrayFactory::create<double>('c', {90}); x.linspace(1); y.linspace(82); exp.linspace(1); sd::ops::flatten op; auto result = op.evaluate({&x, &y}, {}, {'c'}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); // z->printIndexedBuffer("Flatten2"); // z->printShapeInfo("Flatten2 shape"); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_FlattenTests_3) { NDArray x('c', {2,2}, {1, 2, 3, 4}, sd::DataType::INT32); NDArray y('f', {2,2}, sd::DataType::INT32); NDArray exp('c', {8}, {1, 2, 3, 4, 1, 2, 3, 4}, sd::DataType::INT32); y.assign(x); sd::ops::flatten op; auto result = op.evaluate({&x, &y}, {}, {'c'}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_FlattenTests_4) { NDArray x('c', {2,2}, {1, 2, 3, 4}, sd::DataType::INT32); NDArray y('f', {2,2}, sd::DataType::INT32); NDArray exp('c', {8}, {1, 3, 2, 4, 1, 3, 2, 4}, sd::DataType::INT32); y.assign(x); sd::ops::flatten op; auto result = op.evaluate({&x, &y}, {}, {'f'}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_FloorTests_1) { auto x = NDArrayFactory::create<double>('c', {3, 3}, {1.5, 2.3, 3.4, 4.3, 5.9, 6.1, 7.2, 8.9, 9.7}); auto exp = NDArrayFactory::create<double>('c', {3,3}); exp.linspace(1); sd::ops::Floor op; auto result = op.evaluate({&x}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); // z->printIndexedBuffer("Flatten1"); // z->printShapeInfo("Flatten1 shape"); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_Split_1) { auto x = NDArrayFactory::create<double>('c', {5, 30}); auto sizes = NDArrayFactory::create<int>('c', {1, 3}, {4, 15, 11}); std::vector<Nd4jLong> list0({0,0, 0,4}); std::vector<Nd4jLong> list1({0,0, 4,19}); std::vector<Nd4jLong> list2({0,0, 19,30}); auto sub0 = x(list0, true); auto sub1 = x(list1, true); auto sub2 = x(list2, true); sub0.assign(0.0); sub1.assign(1.0); sub2.assign(2.0); sd::ops::split_v op; auto result = op.evaluate({&x, &sizes}, {}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); ASSERT_EQ(3, result.size()); auto z0 = result.at(0); auto z1 = result.at(1); auto z2 = result.at(2); ASSERT_TRUE(sub0.isSameShape(z0)); ASSERT_TRUE(sub1.isSameShape(z1)); ASSERT_TRUE(sub2.isSameShape(z2)); ASSERT_TRUE(sub0.equalsTo(z0)); ASSERT_TRUE(sub1.equalsTo(z1)); ASSERT_TRUE(sub2.equalsTo(z2)); } // special test for TF mode, when axis goes first TEST_F(DeclarableOpsTests4, Test_Split_2) { auto x = NDArrayFactory::create<double>('c', {5, 12}); auto axis = NDArrayFactory::create<double>('c', {1, 1}, {1.f}); std::vector<Nd4jLong> list0 = {0,0, 0,3}; std::vector<Nd4jLong> list1 = {0,0, 3,6}; std::vector<Nd4jLong> list2 = {0,0, 6,9}; std::vector<Nd4jLong> list3 = {0,0, 9,12}; auto sub0 = x(list0, true); auto sub1 = x(list1, true); auto sub2 = x(list2, true); auto sub3 = x(list3, true); sub0.assign(0.0f); sub1.assign(1.0f); sub2.assign(2.0f); sub3.assign(3.0f); sd::ops::split op; auto result = op.evaluate({&axis, &x}, {}, {4}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z0 = result.at(0); auto z1 = result.at(1); auto z2 = result.at(2); auto z3 = result.at(3); ASSERT_TRUE(sub0.isSameShape(z0)); ASSERT_TRUE(sub1.isSameShape(z1)); ASSERT_TRUE(sub2.isSameShape(z2)); ASSERT_TRUE(sub3.isSameShape(z3)); ASSERT_TRUE(sub0.equalsTo(z0)); ASSERT_TRUE(sub1.equalsTo(z1)); ASSERT_TRUE(sub2.equalsTo(z2)); ASSERT_TRUE(sub3.equalsTo(z3)); } // special test for TF mode, when axis goes first TEST_F(DeclarableOpsTests4, Test_Split_3) { auto x = NDArrayFactory::create<double>('c', {6, 12}); auto axis = NDArrayFactory::create<double>('c', {1, 1}, {0.f}); std::vector<Nd4jLong> list0 = {0,2, 0,0}; std::vector<Nd4jLong> list1 = {2,4, 0,0}; std::vector<Nd4jLong> list2 = {4,6, 0,0}; auto sub0 = x(list0, true); auto sub1 = x(list1, true); auto sub2 = x(list2, true); sub0.assign(0.0f); sub1.assign(1.0f); sub2.assign(2.0f); sd::ops::split op; auto result = op.evaluate({&axis, &x}, {}, {3}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z0 = result.at(0); auto z1 = result.at(1); auto z2 = result.at(2); ASSERT_TRUE(sub0.isSameShape(z0)); ASSERT_TRUE(sub1.isSameShape(z1)); ASSERT_TRUE(sub2.isSameShape(z2)); ASSERT_TRUE(sub0.equalsTo(z0)); ASSERT_TRUE(sub1.equalsTo(z1)); ASSERT_TRUE(sub2.equalsTo(z2)); } /////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, split_test4) { auto input = NDArrayFactory::create<double>('c', {10},{1.f,2.f,3.f,4.f,5.f,6.f,7.f,8.f,9.f,10.f}); auto axis = NDArrayFactory::create<double>(-1); auto exp1 = NDArrayFactory::create<double>('c', {5}, {1.f,2.f,3.f,4.f,5.f}); auto exp2 = NDArrayFactory::create<double>('c', {5}, {6.f,7.f,8.f,9.f,10.f}); sd::ops::split op; auto results = op.evaluate({&input, &axis}, {}, {2}, {}); ASSERT_EQ(ND4J_STATUS_OK, results.status()); auto out1 = results.at(0); auto out2 = results.at(1); ASSERT_TRUE(exp1.isSameShape(out1)); ASSERT_TRUE(exp2.isSameShape(out2)); ASSERT_TRUE(exp1.equalsTo(out1)); ASSERT_TRUE(exp2.equalsTo(out2)); } /////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, split_test5) { auto input = NDArrayFactory::create<double>('c', {3,8},{1.f,2.f,3.f,4.f,5.f,6.f,7.f,8.f,9.f,10.f,11.f,12.f,13.f,14.f,15.f,16.f,17.f,18.f,19.f,20.f,21.f,22.f,23.f,24.f}); auto exp1 = NDArrayFactory::create<double>('c', {3,4}, {1.f,2.f,3.f,4.f, 9.f,10.f,11.f,12.f, 17.f,18.f,19.f,20.f}); auto exp2 = NDArrayFactory::create<double>('c', {3,4}, {5.f,6.f,7.f,8.f, 13.f,14.f,15.f,16.f, 21.f,22.f,23.f,24.f}); sd::ops::split op; auto results = op.evaluate({&input}, {}, {2,-1},{}); ASSERT_EQ(ND4J_STATUS_OK, results.status()); auto out1 = results.at(0); auto out2 = results.at(1); ASSERT_TRUE(exp1.isSameShape(out1)); ASSERT_TRUE(exp2.isSameShape(out2)); ASSERT_TRUE(exp1.equalsTo(out1)); ASSERT_TRUE(exp2.equalsTo(out2)); } /////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, split_test6) { NDArray input('c', {0,4}, sd::DataType::FLOAT32); std::vector<Nd4jLong> expShape = {0,1}; const int numSplits = 4; const int axis = 1; sd::ops::split op; auto results = op.evaluate({&input}, {}, {numSplits, axis}, {}); ASSERT_EQ(ND4J_STATUS_OK, results.status()); for (int i = 0; i < numSplits; ++i) ASSERT_TRUE(results.at(i)->isSameShape(expShape)); } /////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, split_test7) { NDArray input('c', {0,4}, sd::DataType::FLOAT32); std::vector<Nd4jLong> expShape = {0,4}; const int numSplits = 4; const int axis = 0; sd::ops::split op; auto results = op.evaluate({&input}, {}, {numSplits, axis}, {}); ASSERT_EQ(ND4J_STATUS_OK, results.status()); for (int i = 0; i < numSplits; ++i) ASSERT_TRUE(results.at(i)->isSameShape(expShape)); } TEST_F(DeclarableOpsTests4, Test_Squeeze_args_1) { auto x = NDArrayFactory::create<double>('c', {2, 1, 1, 1, 2}, {1, 2, 3, 4}); auto exp = NDArrayFactory::create<double>('c', {2, 1, 2}, {1, 2, 3, 4}); sd::ops::squeeze op; auto result = op.evaluate({&x}, {}, {1, 3}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_Squeeze_args_2) { auto x = NDArrayFactory::create<double>('c', {2, 1, 1, 1, 2}, {1, 2, 3, 4}); auto y = NDArrayFactory::create<double>('c', {2}, {1.f, 3.f}); auto exp = NDArrayFactory::create<double>('c', {2, 1, 2}, {1, 2, 3, 4}); sd::ops::squeeze op; auto result = op.evaluate({&x, &y}, {}, {}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_Squeeze_args_3) { auto x = NDArrayFactory::create<double>('c', {2, 1, 1, 1, 2}, {1, 2, 3, 4}); auto exp = NDArrayFactory::create<double>('c', {2, 1, 2}, {1, 2, 3, 4}); sd::ops::squeeze op; auto result = op.evaluate({&x}, {}, {-2, -3}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_SpaceToDepth_1) { auto x = NDArrayFactory::create<double>('c', {1, 2, 2, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto exp = NDArrayFactory::create<double>('c', {1, 1, 1, 12}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); sd::ops::space_to_depth op; auto result = op.evaluate({&x}, {}, {2, 1}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_SpaceToDepth_2) { auto x = NDArrayFactory::create<double>('c', {1, 3, 2, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto exp = NDArrayFactory::create<double>('c', {1, 12, 1, 1}, {1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12}); sd::ops::space_to_depth op; auto result = op.evaluate({&x}, {}, {2, 0}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_DepthToSpace_1) { auto x = NDArrayFactory::create<double>('c', {1, 1, 1, 12}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto exp = NDArrayFactory::create<double>('c', {1, 2, 2, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); sd::ops::depth_to_space op; auto result = op.evaluate({&x}, {}, {2, 1}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_DepthToSpace_2) { auto x = NDArrayFactory::create<double>('c', {1, 12, 1, 1}, {1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12}); auto exp = NDArrayFactory::create<double>('c', {1, 3, 2, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); sd::ops::depth_to_space op; auto result = op.evaluate({&x}, {}, {2, 0}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_DepthToSpace_3) { auto x = NDArrayFactory::create<double>('c', {4, 4, 16, 16}); auto exp = NDArrayFactory::create<double>('c', {4, 16, 64, 1}); sd::ops::depth_to_space op; auto result = op.evaluate({&x}, {}, {4, 1}); ASSERT_EQ(Status::OK(), result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); } TEST_F(DeclarableOpsTests4, Test_Cross_1) { auto a = NDArrayFactory::create<double>('c', {3}, {1, 2, 3}); auto b = NDArrayFactory::create<double>('c', {3}, {6, 7, 8}); auto exp = NDArrayFactory::create<double>('c', {3}, {-5, 10, -5}); sd::ops::cross op; auto result = op.evaluate({&a, &b}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_Cross_2) { auto a = NDArrayFactory::create<double>('c', {2, 3}, {1, 2, 3, 1, 2, 3}); auto b = NDArrayFactory::create<double>('c', {2, 3}, {6, 7, 8, 6, 7, 8}); auto exp = NDArrayFactory::create<double>('c', {2, 3}, {-5, 10, -5, -5, 10, -5}); sd::ops::cross op; auto result = op.evaluate({&a, &b}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_Cross_3) { auto a = NDArrayFactory::create<double>('c', {3, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); auto b = NDArrayFactory::create<double>('c', {3, 3}, {2, 3, 4, 7, 6, 5, 6, 3, 2}); auto exp = NDArrayFactory::create<double>('c', {3, 3}, { -1, 2, -1, -11, 22, -11, -11, 40, -27}); sd::ops::cross op; auto result = op.evaluate({&a, &b}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_Add_119) { auto a = NDArrayFactory::create<double>('c', {1, 4}, {1, 2, 3, 4}); auto b = NDArrayFactory::create<double>('c', {4}, {1, 2, 3, 4}); auto exp = NDArrayFactory::create<double>('c', {1, 4}, {2, 4, 6, 8}); sd::ops::add op; auto result = op.evaluate({&a, &b}); ASSERT_EQ(ND4J_STATUS_OK, result.status()); auto z = result.at(0); ASSERT_EQ(2, z->rankOf()); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_TileToShape_1) { auto x = NDArrayFactory::create<double>('c', {2, 1, 3}); auto exp = NDArrayFactory::create<double>('c', {2, 4, 3}, {1.f, 2.f, 3.f,1.f, 2.f, 3.f,1.f, 2.f, 3.f,1.f, 2.f, 3.f, 4.f, 5.f, 6.f,4.f, 5.f, 6.f,4.f, 5.f, 6.f,4.f, 5.f, 6.f}); x.linspace(1.f); sd::ops::tile_to_shape op; auto result = op.evaluate({&x},{}, {2, 4, 3}); ASSERT_EQ(Status::OK(), result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_StridedSlice_Alex_1) { auto x = NDArrayFactory::create<double>('c', {3, 4, 5}); x.linspace(1); auto exp = NDArrayFactory::create<double>('c', {1,3,4,5}); exp.linspace(1); sd::ops::strided_slice op; auto result = op.evaluate({&x}, {}, {0,0,0,1,0, -999,0,0,0, -999,3,4,5, -999,1,1,1}); ASSERT_EQ(Status::OK(), result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_StridedSlice_Alex_2) { auto x = NDArrayFactory::create<double>('c', {3, 4, 5}); auto begin = NDArrayFactory::create<double>('c', {4}, {-999,0,0,0}); auto end = NDArrayFactory::create<double>('c', {4}, {-999,3,4,5}); auto stride = NDArrayFactory::create<double>('c', {4}, {-999,1,1,1}); x.linspace(1); auto exp = NDArrayFactory::create<double>('c', {1,3,4,5}); exp.linspace(1); sd::ops::strided_slice op; auto result = op.evaluate({&x, &begin, &end, &stride}, {}, {0,0,0,1,0}); ASSERT_EQ(Status::OK(), result.status()); ASSERT_EQ(Status::OK(), result.status()); auto z = result.at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); } TEST_F(DeclarableOpsTests4, Test_StridedSlice_Alex_3) { int axis = 0; auto x = NDArrayFactory::create<double>('c', {1}, {10}); auto begin = NDArrayFactory::create<int>('c', {1}, {axis}); auto end = NDArrayFactory::create<int>('c', {1}, {axis}); auto stride = NDArrayFactory::create<int>('c', {1}, {1}); //x.linspace(1); //auto exp = NDArrayFactory::create<double>('c', {1,3,4,5}); //exp.linspace(1); sd::ops::strided_slice op; auto result = op.evaluate({&x, &begin, &end, &stride}, {}, {1,0,0,0,0}); ASSERT_EQ(Status::OK(), result.status()); auto z = result.at(0); ASSERT_TRUE(z->isEmpty()); } TEST_F(DeclarableOpsTests4, Test_StridedSlice_Alex_4) { auto x = NDArrayFactory::create<double>('c', {1,3}, {1, 2, 3}); auto begin = NDArrayFactory::create<double>('c', {2}, {0, 0}); auto end = NDArrayFactory::create<double>('c', {2}, {0,1}); auto stride = NDArrayFactory::create<double>('c', {2}, {1,1}); // x.linspace(1); auto exp = NDArrayFactory::create<double>('c', {1}, {1}); //exp.linspace(1); sd::ops::strided_slice op; auto result = op.evaluate({&x, &begin, &end, &stride}, {}, {1,0,1,0,2}); ASSERT_EQ(Status::OK(), result.status()); auto z = result.at(0); ASSERT_TRUE(z->lengthOf() == 1); ASSERT_TRUE(exp.equalsTo(z)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, parallel_stack_test1) { auto x1 = NDArrayFactory::create<double>('c', {2,2,2}); auto x2 = NDArrayFactory::create<double>('c', {2,2,2}); auto x3 = NDArrayFactory::create<double>('c', {2,2,2}); x1.linspace(1); x2.linspace(9); x3.linspace(17); auto expected = NDArrayFactory::create<double>('c', {3,2,2,2}); expected.linspace(1); sd::ops::parallel_stack op; auto results = op.evaluate({&x1, &x2, &x3}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, parallel_stack_test2) { auto x1 = NDArrayFactory::create<double>('c', {1,2}, {1,2}); auto x2 = NDArrayFactory::create<double>('c', {1,2}, {3,4}); auto x3 = NDArrayFactory::create<double>('c', {1,2}, {5,6}); auto expected = NDArrayFactory::create<double>('c', {3,1,2}, {1,2,3,4,5,6}); sd::ops::parallel_stack op; auto results = op.evaluate({&x1, &x2, &x3}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, parallel_stack_test3) { auto x1 = NDArrayFactory::create<double>('c', {2,1}, {1,2}); auto x2 = NDArrayFactory::create<double>('c', {2,1}, {3,4}); auto x3 = NDArrayFactory::create<double>('c', {2,1}, {5,6}); auto expected = NDArrayFactory::create<double>('c', {3,2,1}, {1,2,3,4,5,6}); sd::ops::parallel_stack op; auto results = op.evaluate({&x1, &x2, &x3}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } \ ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, parallel_stack_test4) { auto x1 = NDArrayFactory::create<double>('c', {2}, {1,2}); auto x2 = NDArrayFactory::create<double>('c', {2}, {3,4}); auto x3 = NDArrayFactory::create<double>('c', {2}, {5,6}); auto expected = NDArrayFactory::create<double>('c', {3,2}, {1,2,3,4,5,6}); sd::ops::parallel_stack op; auto results = op.evaluate({&x1, &x2, &x3}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, parallel_stack_test5) { auto x1 = NDArrayFactory::create<double>('c', {1}, {1}); auto x2 = NDArrayFactory::create<double>('c', {1}, {3}); auto x3 = NDArrayFactory::create<double>('c', {1}, {5}); auto expected = NDArrayFactory::create<double>('c', {3,1}, {1,3,5}); sd::ops::parallel_stack op; auto results = op.evaluate({&x1, &x2, &x3}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, parallel_stack_test6) { auto x1 = NDArrayFactory::create<double>(1.); auto x2 = NDArrayFactory::create<double>(3.); auto x3 = NDArrayFactory::create<double>(5.); auto expected = NDArrayFactory::create<double>('c', {3}, {1,3,5}); sd::ops::parallel_stack op; auto results = op.evaluate({&x1, &x2, &x3}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, parallel_stack_test7) { auto x1 = NDArrayFactory::create<double>(1.); auto expected = NDArrayFactory::create<double>('c', {1}, {1.}); sd::ops::parallel_stack op; auto results = op.evaluate({&x1}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, meshgrid_test1) { auto in0 = NDArrayFactory::create<double>('c', {2}, {1, 2}); auto in1 = NDArrayFactory::create<double>('c', {3}, {10, 20, 30}); auto in2 = NDArrayFactory::create<double>('c', {4}, {100, 200, 300, 400}); auto exp0 = NDArrayFactory::create<double>('c', {2,3,4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}); auto exp1 = NDArrayFactory::create<double>('c', {2,3,4}, {10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 30, 30, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 30, 30}); auto exp2 = NDArrayFactory::create<double>('c', {2,3,4}, {100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400}); sd::ops::meshgrid op; auto results = op.evaluate({&in0, &in1, &in2}, {}, {0}); auto out0 = results.at(0); auto out1 = results.at(1); auto out2 = results.at(2); // out0->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp0.isSameShape(out0)); ASSERT_TRUE(exp0.equalsTo(out0)); ASSERT_TRUE(exp1.isSameShape(out1)); ASSERT_TRUE(exp1.equalsTo(out1)); ASSERT_TRUE(exp2.isSameShape(out2)); ASSERT_TRUE(exp2.equalsTo(out2)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, meshgrid_test2) { auto in0 = NDArrayFactory::create<double>('c', {2}, {1, 2}); auto in1 = NDArrayFactory::create<double>('c', {3}, {10, 20, 30}); auto in2 = NDArrayFactory::create<double>('c', {4}, {100, 200, 300, 400}); auto exp0 = NDArrayFactory::create<double>('c', {3,2,4}, {1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2}); auto exp1 = NDArrayFactory::create<double>('c', {3,2,4}, {10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20, 30, 30, 30, 30, 30, 30, 30, 30}); auto exp2 = NDArrayFactory::create<double>('c', {3,2,4}, {100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400}); sd::ops::meshgrid op; auto results = op.evaluate({&in0, &in1, &in2}); auto out0 = results.at(0); auto out1 = results.at(1); auto out2 = results.at(2); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp0.isSameShape(out0)); ASSERT_TRUE(exp0.equalsTo(out0)); ASSERT_TRUE(exp1.isSameShape(out1)); ASSERT_TRUE(exp1.equalsTo(out1)); ASSERT_TRUE(exp2.isSameShape(out2)); ASSERT_TRUE(exp2.equalsTo(out2)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, meshgrid_test3) { auto in0 = NDArrayFactory::create<double>('c', {2}, {1, 2}); auto in1 = NDArrayFactory::create<double>('c', {1,3}, {10, 20, 30}); auto in2 = NDArrayFactory::create<double>('c', {2,2}, {100, 200, 300, 400}); auto exp0 = NDArrayFactory::create<double>('c', {3,2,4}, {1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2}); auto exp1 = NDArrayFactory::create<double>('c', {3,2,4}, {10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20, 30, 30, 30, 30, 30, 30, 30, 30}); auto exp2 = NDArrayFactory::create<double>('c', {3,2,4}, {100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400}); sd::ops::meshgrid op; auto results = op.evaluate({&in0, &in1, &in2}); auto out0 = results.at(0); auto out1 = results.at(1); auto out2 = results.at(2); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp0.isSameShape(out0)); ASSERT_TRUE(exp0.equalsTo(out0)); ASSERT_TRUE(exp1.isSameShape(out1)); ASSERT_TRUE(exp1.equalsTo(out1)); ASSERT_TRUE(exp2.isSameShape(out2)); ASSERT_TRUE(exp2.equalsTo(out2)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, meshgrid_test4) { auto in0 = NDArrayFactory::create<double>('c', {1,2}, {1, 2}); auto in1 = NDArrayFactory::create<double>('c', {3,1}, {10, 20, 30}); auto in2 = NDArrayFactory::create<double>('c', {1,4,1}, {100, 200, 300, 400}); auto exp0 = NDArrayFactory::create<double>('c', {2,3,4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}); auto exp1 = NDArrayFactory::create<double>('c', {2,3,4}, {10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 30, 30, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 30, 30}); auto exp2 = NDArrayFactory::create<double>('c', {2,3,4}, {100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400}); sd::ops::meshgrid op; auto results = op.evaluate({&in0, &in1, &in2}, {}, {0}); auto out0 = results.at(0); auto out1 = results.at(1); auto out2 = results.at(2); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp0.isSameShape(out0)); ASSERT_TRUE(exp0.equalsTo(out0)); ASSERT_TRUE(exp1.isSameShape(out1)); ASSERT_TRUE(exp1.equalsTo(out1)); ASSERT_TRUE(exp2.isSameShape(out2)); ASSERT_TRUE(exp2.equalsTo(out2)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, meshgrid_test5) { auto in0 = NDArrayFactory::create<double>(1); auto in1 = NDArrayFactory::create<double>(2); auto in2 = NDArrayFactory::create<double>(3); auto exp0 = NDArrayFactory::create<double>('c', {1,1,1}, {1}); auto exp1 = NDArrayFactory::create<double>('c', {1,1,1}, {2}); auto exp2 = NDArrayFactory::create<double>('c', {1,1,1}, {3}); sd::ops::meshgrid op; auto results = op.evaluate({&in0, &in1, &in2}, {}, {0}); auto out0 = results.at(0); auto out1 = results.at(1); auto out2 = results.at(2); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp0.isSameShape(out0)); ASSERT_TRUE(exp0.equalsTo(out0)); ASSERT_TRUE(exp1.isSameShape(out1)); ASSERT_TRUE(exp1.equalsTo(out1)); ASSERT_TRUE(exp2.isSameShape(out2)); ASSERT_TRUE(exp2.equalsTo(out2)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, meshgrid_test6) { auto in0 = NDArrayFactory::create<double>('c', {2,2},{1,2,3,4}); auto in1 = NDArrayFactory::create<double>(5); auto in2 = NDArrayFactory::create<double>(6); auto exp0 = NDArrayFactory::create<double>('c', {4,1,1}, {1,2,3,4}); auto exp1 = NDArrayFactory::create<double>('c', {4,1,1}, {5,5,5,5}); auto exp2 = NDArrayFactory::create<double>('c', {4,1,1}, {6,6,6,6}); sd::ops::meshgrid op; auto results = op.evaluate({&in0, &in1, &in2}, {}, {0}); auto out0 = results.at(0); auto out1 = results.at(1); auto out2 = results.at(2); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp0.isSameShape(out0)); ASSERT_TRUE(exp0.equalsTo(out0)); ASSERT_TRUE(exp1.isSameShape(out1)); ASSERT_TRUE(exp1.equalsTo(out1)); ASSERT_TRUE(exp2.isSameShape(out2)); ASSERT_TRUE(exp2.equalsTo(out2)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, meshgrid_test7) { auto in0 = NDArrayFactory::create<double>('c', {2,2},{1,2,3,4}); auto in1 = NDArrayFactory::create<double>(5); auto in2 = NDArrayFactory::create<double>(6); auto exp0 = NDArrayFactory::create<double>('c', {1,4,1}, {1,2,3,4}); auto exp1 = NDArrayFactory::create<double>('c', {1,4,1}, {5,5,5,5}); auto exp2 = NDArrayFactory::create<double>('c', {1,4,1}, {6,6,6,6}); sd::ops::meshgrid op; auto results = op.evaluate({&in0, &in1, &in2}, {}, {1}); auto out0 = results.at(0); auto out1 = results.at(1); auto out2 = results.at(2); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp0.isSameShape(out0)); ASSERT_TRUE(exp0.equalsTo(out0)); ASSERT_TRUE(exp1.isSameShape(out1)); ASSERT_TRUE(exp1.equalsTo(out1)); ASSERT_TRUE(exp2.isSameShape(out2)); ASSERT_TRUE(exp2.equalsTo(out2)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, meshgrid_test8) { auto in0 = NDArrayFactory::create<double>(5); auto exp0 = NDArrayFactory::create<double>('c', {1}, {5}); sd::ops::meshgrid op; auto results = op.evaluate({&in0}, {}, {0}); auto out0 = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp0.isSameShape(out0)); ASSERT_TRUE(exp0.equalsTo(out0)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, meshgrid_test9) { auto in0 = NDArrayFactory::create<double>(5); auto exp0 = NDArrayFactory::create<double>('c', {1}, {5}); sd::ops::meshgrid op; auto results = op.evaluate({&in0}, {}, {1}); auto out0 = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp0.isSameShape(out0)); ASSERT_TRUE(exp0.equalsTo(out0)); } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, WeightedCrossEntropyWithLogits_1) { auto input = NDArrayFactory::create<double>('c', {2, 3}, {11.f, 13.f, 4.f, 15.f, 6.f, 3.f}); auto targets = NDArrayFactory::create<double>('c', {2, 3}, {15.5f, 15.7f, 5.f , 15.f, 5.f, 6.f}); auto weight = NDArrayFactory::create<double>(0.7f); auto expected = NDArrayFactory::create<double>('c', {2, 3}, {-159.50006, -191.1, -16.009075, -210., -24.001238, -15.03887}); //Targets {15.5f, 15.7f, 5.f , 15.f, 5.f, 6.f}; //---------- //Inputs {11.f, 13.f, 4.f, 15.f, 6.f, 3.f}; //---------- //Weights [0.7] //Result {-159.50006, -191.1, -16.009075, -210., -24.001238, -15.03887} sd::ops::weighted_cross_entropy_with_logits op; auto results = op.evaluate({&targets, &input, &weight}); auto output = results.at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, WeightedCrossEntropyWithLogits_2) { auto input = NDArrayFactory::create<double>('c', {2, 3}, {11.f, 13.f, 4.f, 15.f, 6.f, 3.f}); auto targets = NDArrayFactory::create<double>('c', {2, 3}, {15.5f, 15.7f, 5.f, 15.f, 5.f, 6.f}); auto weights = NDArrayFactory::create<double>({0.5f, 0.7f, 1.0f}) ; auto expected = NDArrayFactory::create<double>('c', {2, 3}, {-159.5001f, -191.1f, -15.98185f, -210.f, -24.001238f, -14.951412f}); sd::ops::weighted_cross_entropy_with_logits op; auto results = op.evaluate({&targets, &input, &weights}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } /////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, lstm_test1) { const int time = 5; const int batchSize = 3; const int inSize = 3; const int numProj = 3; const int numUnits = 3; auto x = NDArrayFactory::create<double>('c', {time, batchSize, inSize}); auto h0 = NDArrayFactory::create<double>('c', {batchSize, numProj}); auto c0 = NDArrayFactory::create<double>('c', {batchSize, numUnits}); auto Wx = NDArrayFactory::create<double>('c', {inSize, 4*numUnits}); auto Wh = NDArrayFactory::create<double>('c', {numProj, 4*numUnits}); auto Wc = NDArrayFactory::create<double>('c', {3*numUnits}); auto Wp = NDArrayFactory::create<double>('c', {numUnits, numProj}); auto b = NDArrayFactory::create<double>('c', {4*numUnits}); x.linspace(0.5, 0.5); h0 = 1.; c0 = 2.; Wx = 0.003; Wh = 0.006; Wc = 0.; Wp = 0.; b = 0.5; auto expH = NDArrayFactory::create<double>('c', {time, batchSize, numProj}, {0.57574,0.57574,0.57574,0.58006,0.58006,0.58006,0.58434,0.58434,0.58434, 0.55114,0.55114,0.55114,0.55732,0.55732,0.55732,0.56338,0.56338,0.56338, 0.53763,0.53763,0.53763,0.54534,0.54534,0.54534,0.55287,0.55287,0.55287, 0.53626,0.53626,0.53626,0.54487,0.54487,0.54487,0.55327,0.55327,0.55327, 0.54484,0.54484,0.54484,0.55379,0.55379,0.55379,0.5625 ,0.5625 ,0.5625}); auto expClast = NDArrayFactory::create<double>('c', {1, batchSize, numProj}, {1.1589154,1.1589154,1.1589154,1.1892855,1.1892855,1.1892855,1.219861 ,1.219861 ,1.219861}); sd::ops::lstm op; auto results = op.evaluate({&x, &h0, &c0, &Wx, &Wh, &Wc, &Wp, &b}, {0., 0., 0.}, {0, 0}); ASSERT_EQ(ND4J_STATUS_OK, results.status()); auto *h = results.at(0); auto *c = results.at(1); auto cLast = (*c)({4,5,0,0,0,0},true); ASSERT_TRUE(expH.isSameShape(h)); ASSERT_TRUE(expH.equalsTo(h)); ASSERT_TRUE(expClast.isSameShape(&cLast)); ASSERT_TRUE(expClast.equalsTo(&cLast)); } /////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, relu6_test1) { auto input = NDArrayFactory::create<double>('c', {2,4}, {-13.,10,-5,0,2,7,6,12}); auto expected = NDArrayFactory::create<double>('c', {2,4}, {0., 6., 0., 0.,2., 6., 6., 6.}); sd::ops::relu6 op; auto results = op.evaluate({&input}, {0.}, {}); ASSERT_EQ(ND4J_STATUS_OK, results.status()); auto output = results.at(0); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } /////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, relu6_bp_test1) { auto input = NDArrayFactory::create<double>('c', {2,4}, {-13.,10, -5, 0, 2, 7, 6, 5}); auto gradO = NDArrayFactory::create<double>('c', {2,4}, {-1., -2., 0., 4., 5., 6., 7., 8.}); auto expected = NDArrayFactory::create<double>('c', {2,4}, {0., 0., 0., 0., 5., 0., 0., 8.}); sd::ops::relu6_bp op; auto results = op.evaluate({&input, &gradO}, {0.}); ASSERT_EQ(ND4J_STATUS_OK, results.status()); auto output = results.at(0); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } //////////////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, LrnTest_1) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 2}, { 5.5f, 0.f, 0.3f, 5.5f, 8.6f, 0.f, 0.f, 0.4f, 1.5f, 1.f, 1.3f, 1.5f, 2.6f, 2.f, 3.f, 1.4f} ); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 2}, { 0.98386997f, 0.f, 0.05358852f, 0.9824562f, 0.99330735f, 0.f, 0.f, 0.37139067f, 0.72760683f, 0.4850712f, 0.5848977f, 0.67488194f, 0.7581754f, 0.58321184f, 0.86747235f, 0.4048204f} ); sd::ops::lrn op; auto results = op.evaluate({&x}, {1.0, 1.0, 0.5}, {5}); auto out = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp.isSameShape(out)); // out->printIndexedBuffer("LRN out"); // exp.printIndexedBuffer("LRN exp"); ASSERT_TRUE(exp.equalsTo(out)); } //////////////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, LrnTest_2) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 2}, { 5.5f, 0.f, 0.3f, 5.5f, 8.6f, 0.f, 0.f, 0.4f, 1.5f, 1.f, 1.3f, 1.5f, 2.6f, 2.f, 3.f, 1.4f}); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 2}, { 0.98386997f, 0.f, 0.05358852f, 0.9824562f, 0.99330735f, 0.f, 0.f, 0.37139067f, 0.72760683f, 0.4850712f, 0.5848977f, 0.67488194f, 0.7581754f, 0.58321184f, 0.86747235f, 0.4048204f}); sd::ops::lrn op; auto results = op.evaluate({&x}, {1.0, 1.0, 0.5}, {2}); auto out = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp.isSameShape(out)); // out->printIndexedBuffer("LRN out"); // exp.printIndexedBuffer("LRN exp"); ASSERT_TRUE(exp.equalsTo(out)); } //////////////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, LrnTest_3) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 4}, { 5.5f, 0.f, 0.3f, 5.5f, 1.5f, 0.f, 1.3f, 6.5f, 8.6f, 0.f, 0.f, 0.4f, 2.5f, 1.f, 0.3f, 4.5f, 1.5f, 1.f, 1.3f, 1.5f, 3.5f, 0.f, 1.3f, 2.5f, 2.6f, 2.f, 3.f, 1.4f, 4.5f, 1.f, 0.3f, 0.5f} ); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 4}, { 0.9824562f, 0.f, 0.03822664f, 0.9824562f, 0.67488194f, 0.f, 0.18924236f, 0.96960944f, 0.99330735f, 0.f, 0.f, 0.37139067f, 0.86567914f, 0.18702209f, 0.05610663f, 0.9520745f, 0.6154575f, 0.34942827f, 0.45425674f, 0.6154575f, 0.905509f, 0.f, 0.2824086f, 0.8361251f, 0.57063663f, 0.41959068f, 0.629386f, 0.3504383f, 0.9520745f, 0.21039814f, 0.06311944f, 0.3268602f } ); sd::ops::lrn op; auto results = op.evaluate({&x}, {1.0, 1.0, 0.5}, {2}); auto out = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp.isSameShape(out)); // out->printIndexedBuffer("LRN out"); // exp.printIndexedBuffer("LRN exp"); ASSERT_TRUE(exp.equalsTo(out)); } //////////////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, LrnTest_4) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 4}, { 5.5f, 0.f, 0.3f, 5.5f, 1.5f, 0.f, 1.3f, 6.5f, 8.6f, 0.f, 0.f, 0.4f, 2.5f, 1.f, 0.3f, 4.5f, 1.5f, 1.f, 1.3f, 1.5f, 3.5f, 0.f, 1.3f, 2.5f, 2.6f, 2.f, 3.f, 1.4f, 4.5f, 1.f, 0.3f, 0.5f} ); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 4}, { 0.70082176f, 0.f, 0.03822664f, 0.70082176f, 0.21835658f, 0.f, 0.18924236f, 0.9462118f, 0.9922489f, 0.f, 0.f, 0.04615111f, 0.46755522f, 0.18702209f, 0.05610663f, 0.8415994f, 0.5241424f, 0.34942827f, 0.45425674f, 0.5241424f, 0.76033086f, 0.f, 0.2824086f, 0.54309344f, 0.54546785f, 0.41959068f, 0.629386f, 0.29371348f, 0.94679165f, 0.21039814f, 0.06311944f, 0.10519907f} ); sd::ops::lrn op; auto results = op.evaluate({&x}, {1.0, 1.0, 0.5}, {5}); auto out = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp.isSameShape(out)); // out->printIndexedBuffer("LRN out"); // exp.printIndexedBuffer("LRN exp"); ASSERT_TRUE(exp.equalsTo(out)); } //////////////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedDeclarableOpsTests4, LrnTest_5) { auto x = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 4}, { 5.5f, 0.f, 0.3f, 5.5f, 1.5f, 0.f, 1.3f, 6.5f, 8.6f, 0.f, 0.f, 0.4f, 2.5f, 1.f, 0.3f, 4.5f, 1.5f, 1.f, 1.3f, 1.5f, 3.5f, 0.f, 1.3f, 2.5f, 2.6f, 2.f, 3.f, 1.4f, 4.5f, 1.f, 0.3f, 0.5f} ); auto eps = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 4}, { 0.70082176f, 0.f, 0.03822664f, 0.70082176f, 0.21835658f, 0.f, 0.18924236f, 0.9462118f, 0.9922489f, 0.f, 0.f, 0.04615111f, 0.46755522f, 0.18702209f, 0.05610663f, 0.8415994f, 0.5241424f, 0.34942827f, 0.45425674f, 0.5241424f, 0.76033086f, 0.f, 0.2824086f, 0.54309344f, 0.54546785f, 0.41959068f, 0.629386f, 0.29371348f, 0.94679165f, 0.21039814f, 0.06311944f, 0.10519907f} ); auto exp = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 4}); sd::ops::lrn_bp op; auto results = op.evaluate({&x, &eps}, {1.0, 1.0, 0.5}, {5}, {}, {}, false); auto out = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(exp.isSameShape(out)); // out->printIndexedBuffer("LRN out"); // exp.printIndexedBuffer("LRN exp"); // ASSERT_TRUE(exp.equalsTo(out)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, tri_test1) { const int rows = 3; const int cols = 5; auto expected = NDArrayFactory::create<float>('c', {rows, cols}, {1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f, 0.f}); sd::ops::tri op; auto results = op.evaluate({}, {}, {rows, cols}); auto output = results.at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, tri_test2) { const int rows = 3; const int cols = 5; const int diag = 2; auto expected = NDArrayFactory::create<float>('c', {rows, cols}, {1.f, 1.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f, 1.f}); sd::ops::tri op; auto results = op.evaluate({}, {}, {rows, cols, diag}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, tri_test3) { const int rows = 3; const int cols = 5; const int diag = -1; auto expected = NDArrayFactory::create<float>('c', {rows, cols}, {0.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f}); sd::ops::tri op; auto results = op.evaluate({}, {}, {rows, cols, diag}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, tri_test4) { const int rows = 3; const int cols = 5; const int diag = -2; auto expected = NDArrayFactory::create<float>('c', {rows, cols}, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f}); sd::ops::tri op; auto results = op.evaluate({}, {}, {rows, cols, diag}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, tri_test5) { const int rows = 5; auto expected = NDArrayFactory::create<float>('c', {rows, rows}, {1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f, 1.f}); sd::ops::tri op; auto results = op.evaluate({}, {}, {rows}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, tri_test6) { const int rows = 3; const int cols = 5; const int diag = -20; auto expected = NDArrayFactory::create<float>('c', {rows, cols}, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}); sd::ops::tri op; auto results = op.evaluate({}, {}, {rows, cols, diag}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, tri_test7) { const int rows = 3; const int cols = 5; const int diag = 20; auto expected = NDArrayFactory::create<float>('c', {rows, cols}, {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f}); sd::ops::tri op; auto results = op.evaluate({}, {}, {rows, cols, diag}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test1) { auto input = NDArrayFactory::create<double>('c', {4, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto expected = NDArrayFactory::create<double>('c', {4, 3}, {1, 2, 3, 0, 5, 6, 0, 0, 9, 0, 0, 0}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test2) { auto input = NDArrayFactory::create<double>('c', {4, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto expected = NDArrayFactory::create<double>('c', {4, 3}, {1, 2, 3,4, 5, 6,0, 8, 9,0, 0, 12}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {-1}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test3) { auto input = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto expected = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2,3, 4,0, 6,7, 8,9,10,0,12}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {-1}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test4) { auto input = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto expected = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2,0, 4,0, 0,7, 8,0, 10,0, 0}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test5) { auto input = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto expected = NDArrayFactory::create<double>('c', {2, 3, 2}, {0, 2,0, 0,0, 0,0, 8,0, 0,0, 0}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {1}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test6) { auto input = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto expected = NDArrayFactory::create<double>('c', {2, 3, 2}, {0, 0,0, 0,0, 0,0, 0,0, 0,0, 0}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {10}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test7) { auto input = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto expected = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {-10}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test8) { auto input = NDArrayFactory::create<double>('c', {6}, {1, 2, 3, 4, 5, 6}); auto expected = NDArrayFactory::create<double>('c', {6, 6}, {1, 2, 3, 4, 5, 6,0, 2, 3, 4, 5, 6,0, 0, 3, 4, 5, 6,0, 0, 0, 4, 5, 6,0, 0, 0, 0, 5, 6,0, 0, 0, 0, 0, 6}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test9) { auto input = NDArrayFactory::create<double>('c', {6}, {1, 2, 3, 4, 5, 6}); auto expected = NDArrayFactory::create<double>('c', {6, 6}, {1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 0, 2, 3, 4, 5, 6, 0, 0, 3, 4, 5, 6}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {-3}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test10) { auto input = NDArrayFactory::create<double>('c', {6}, {1, 2, 3, 4, 5, 6}); auto expected = NDArrayFactory::create<double>('c', {6, 6}, {0, 0, 0, 4, 5, 6, 0, 0, 0, 0, 5, 6, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {3}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_test11) { auto input = NDArrayFactory::create<double>('c', {6}, {1, 2, 3, 4, 5, 6}); auto expected = NDArrayFactory::create<double>('c', {6, 6}, {1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6}); sd::ops::triu op; auto results = op.evaluate({&input}, {}, {-58}); auto output = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_bp_test1) { auto input = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto gradO = NDArrayFactory::create<double>('c', {2, 3, 2}); gradO = 0.5; auto expected = NDArrayFactory::create<double>('c', {2, 3, 2}, {0.,0.5,0.,0. ,0.,0. ,0.,0.5,0.,0. ,0.,0.}); sd::ops::triu_bp op; auto results = op.evaluate({&input, &gradO}, {}, {1}); auto gradI = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(gradI)); ASSERT_TRUE(expected.equalsTo(gradI)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_bp_test2) { auto input = NDArrayFactory::create<double>('c', {2, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); auto gradO = NDArrayFactory::create<double>('c', {2, 3, 2}); gradO = 0.5; auto expected = NDArrayFactory::create<double>('c', {2, 3, 2}, {0.5,0.5,0. ,0.5,0. ,0. ,0.5,0.5,0. ,0.5,0. ,0.}); sd::ops::triu_bp op; auto results = op.evaluate({&input, &gradO}, {}, {}); auto gradI = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(gradI)); ASSERT_TRUE(expected.equalsTo(gradI)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_bp_test3) { auto input = NDArrayFactory::create<double>('c', {6}, {1, 2, 3, 4, 5, 6}); auto gradO = NDArrayFactory::create<double>('c', {6,6}); gradO = 0.5; auto expected = NDArrayFactory::create<double>('c', {6,6}, {0.5, 0.5, 0.5, 0.5, 0.5, 0.5,0.5, 0.5, 0.5, 0.5, 0.5, 0.5,0.5, 0.5, 0.5, 0.5, 0.5, 0.5,0. , 0.5, 0.5, 0.5, 0.5, 0.5,0. , 0. , 0.5, 0.5, 0.5, 0.5,0. , 0. , 0. , 0.5, 0.5, 0.5}); sd::ops::triu_bp op; auto results = op.evaluate({&input, &gradO}, {}, {-2}); auto gradI = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(gradI)); ASSERT_TRUE(expected.equalsTo(gradI)); } ////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests4, triu_bp_test4) { auto input = NDArrayFactory::create<double>('c', {2,3}, {1, 2, 3, 4, 5, 6}); auto gradO = NDArrayFactory::create<double>('c', {2,3}); gradO = 0.5; auto expected = NDArrayFactory::create<double>('c', {2,3}, {0., 0., 0., 0., 0., 0.}); sd::ops::triu_bp op; auto results = op.evaluate({&input, &gradO}, {}, {10}); auto gradI = results.at(0); ASSERT_EQ(Status::OK(), results.status()); ASSERT_TRUE(expected.isSameShape(gradI)); ASSERT_TRUE(expected.equalsTo(gradI)); }
ef9cc6ef39ee6d4c091116d5326f2e25cd31dccb
c60123141640829a7659a6a585fd955d2b7dc860
/A4/src/DeckOfCardsT.h
39a5452b3a9dda46b8c18b38c03e5aef540bc51b
[]
no_license
Ghasemih/Architecture-Design-Assignments
93a1bee8fa493acf70e9ee943a1a5b2f59294165
61889f8de155ef7a134a89235254ea7e7b70149e
refs/heads/master
2021-05-22T23:34:42.255743
2020-04-05T01:43:20
2020-04-05T01:43:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
584
h
DeckOfCardsT.h
#ifndef DECKOFCARDST_H #define DECKOFCARDST_H #include "CardT.h" #include <string> using namespace std; class DeckOfCardsT { private: //variable card with a pointer to deck CardT deck[Size]; //keep track of what card you are dealing with int currentCard; public: // Default constructor: assigns the 52 cards to deck DeckOfCardsT(); //It finds the color of the card string color(CardT a); //shuffles the deck once all the cards are assigned void shuffle(); //deals out one card from the deck of 52, refrences class card CardT dealCard(); }; #endif
def2647c154bea87a4bd46b76b1f96c4e104d6c5
3baf8b6b4d6295d8e2335f706cf9f5f1041de0cb
/src/search/reverse_pairs/solution.cc
4d4d867023dcde695b2318ac533ad063f6e14416
[]
no_license
huntinux/leetcode
710225b935232b5bed388bb1a5a74d0e7eb8628c
9c676364a4ba4a56035e0f4bc18fe2e18a8db9a6
refs/heads/master
2023-03-05T06:35:34.078539
2023-02-28T15:29:56
2023-02-28T15:29:56
48,361,845
0
0
null
2021-04-23T15:08:04
2015-12-21T09:06:31
C
UTF-8
C++
false
false
1,341
cc
solution.cc
#include "solution.h" // 分析 // // 解法1: // 暴力解法,两层循环,时间复杂度O(n^2) // // 解法2: // 分治,联想归并排序 // ref: https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/solution/jian-zhi-offer-51-shu-zu-zhong-de-ni-xu-pvn2h/ int Solution::ReversePairs(vector<int>& nums) { if (nums.size() <= 1) return 0; ReverseHelper(nums, 0, nums.size() - 1); return reverse_pair_count_; } void Solution::ReverseHelper(vector<int>& nums, int start, int end) { if (start >= end) return ; int mid = start + (end - start) / 2; ReverseHelper(nums, start, mid); ReverseHelper(nums, mid + 1, end); ReverseHelperImpl(nums, start, mid, end); } void Solution::ReverseHelperImpl(vector<int>& nums, int start, int mid, int end) { int i = start, j = mid + 1; int n = end - start + 1; vector<int> sorted; int m = 0; sorted.resize(n); while (i <= mid && j <= end) { if (nums[i] > nums[j]) { //if (nums[i] > (2 * nums[j])) { sorted[m++] = nums[j++]; reverse_pair_count_ += (mid - i + 1); // 更新逆序数量 } else { sorted[m++] = nums[i++]; } } while (i <= mid) { sorted[m++] = nums[i++]; } while (j <= end) { sorted[m++] = nums[j++]; } for (size_t i = 0; i < sorted.size(); ++i) { nums[start + i] = sorted[i]; } }
fb102129d7d7a6c53854e9ef6e2566d84627869d
aec9472e49d46f0d1cb2a26c330c02c44ca81d6b
/BFS.cpp
35d7bf87818fe964f7fa2220764980bcfded1b48
[]
no_license
SanGuillao/SokobanSolver
36854249295256034d0367914bcc3d26b5648d1e
0647de30be7d997ffda509c7acf0e409077b3729
refs/heads/master
2020-06-08T05:55:33.723089
2019-09-23T18:54:53
2019-09-23T18:54:53
193,171,736
5
1
null
null
null
null
UTF-8
C++
false
false
1,429
cpp
BFS.cpp
#include "Sokoban.h" bool Sokoban::BFS(Stage& current, list<Stage>& closedList) { time(&begin); std::queue<Stage> queueStages; int counter = 0; closedList.push_back(current); GetRobot(current); do { if (!MoveRight(current).isDead) { queueStages.push(MoveRight(current)); } if (!MoveUp(current).isDead) { queueStages.push(MoveUp(current)); } if (!MoveLeft(current).isDead) { queueStages.push(MoveLeft(current)); } if (!MoveDown(current).isDead) { queueStages.push(MoveDown(current)); } //Display(current); //cout << queueStages.size() << endl; if (queueStages.size() != 0) { CopyStages(current, queueStages.front()); queueStages.pop(); while (CompareStages(current, closedList) && queueStages.size() != 0) { CopyStages(current, queueStages.front()); queueStages.pop(); PutSBack(current); } PutSBack(current); closedList.push_back(current); GetRobot(current); } else { cout << "BFS could not find a solution. Exiting now..." << endl; return false; } } while (!CheckIfEnd(current)); time(&end); cout << "BFS has found a solution. Outputting to BFS_Output.txt now..." << endl; OutputList(closedList, "BFS"); while (!queueStages.empty()) { queueStages.pop(); } while (!closedList.empty()) { closedList.pop_front(); } return true; }
ae1e0ecdd0178137279ba19716faabf130653ab9
2953868456602b71391eeae06d2d1dc0d74cb223
/src/mods/mod_prelogon.hpp
4eaf00c95498b686bbf961150fc271a76e10ab31
[ "Zlib" ]
permissive
M-griffin/Oblivion2-XRM
653357bc9056c8d2b25fde9eb59d3dfa1c991623
7b4147f34fcde18ba75a46fdb5aa5f460bb7a887
refs/heads/develop
2023-09-04T06:24:40.364355
2023-04-26T07:27:33
2023-04-26T07:27:33
43,869,148
90
12
NOASSERTION
2022-06-13T07:28:10
2015-10-08T07:10:42
C++
UTF-8
C++
false
false
7,554
hpp
mod_prelogon.hpp
#ifndef MOD_PRELOGON_HPP #define MOD_PRELOGON_HPP #include "mod_base.hpp" #include "../model-sys/structures.hpp" #include "../data-sys/text_prompts_dao.hpp" #include "../session_data.hpp" #include "../session_io.hpp" #include "../deadline_timer.hpp" #include <memory> #include <vector> #include <functional> class Config; typedef std::shared_ptr<Config> config_ptr; class ProcessorAnsi; typedef std::shared_ptr<ProcessorAnsi> processor_ansi_ptr; //using std::asio::deadline_timer; /** * @class ModPreLogin * @author Michael Griffin * @date 3/17/2016 * @file mod_logon.hpp * @brief System PreLogin Module */ class ModPreLogon : public std::enable_shared_from_this<ModPreLogon> , public ModBase { public: ModPreLogon(session_data_ptr session_data, config_ptr config, processor_ansi_ptr ansi_process) : ModBase(session_data, config, ansi_process) , m_session_io(session_data) , m_filename("mod_prelogon.yaml") , m_text_prompts_dao(new TextPromptsDao(GLOBAL_DATA_PATH, m_filename)) , m_deadline_timer(new DeadlineTimer()) , m_mod_function_index(MOD_DETECT_EMULATION) , m_is_text_prompt_exist(false) , m_is_esc_detected(false) , m_input_buffer("") , m_x_position(0) , m_y_position(0) , m_term_type("undetected") { // Push function pointers to the stack. m_setup_functions.push_back(std::bind(&ModPreLogon::setupEmulationDetection, this)); m_setup_functions.push_back(std::bind(&ModPreLogon::setupAskANSIColor, this)); m_setup_functions.push_back(std::bind(&ModPreLogon::setupAskCodePage, this)); m_mod_functions.push_back(std::bind(&ModPreLogon::emulationDetection, this, std::placeholders::_1)); m_mod_functions.push_back(std::bind(&ModPreLogon::askANSIColor, this, std::placeholders::_1)); m_mod_functions.push_back(std::bind(&ModPreLogon::askCodePage, this, std::placeholders::_1)); // Check of the Text Prompts exist. m_is_text_prompt_exist = m_text_prompts_dao->fileExists(); if(!m_is_text_prompt_exist) { createTextPrompts(); } // Loads all Text Prompts for current module m_text_prompts_dao->readPrompts(); // On Initial Startup, setup user record with system colors for menu system // this is overwritten once the user logs in, otherwise the menu system // will use these defaults for theming. session_data->m_user_record->sRegColor = m_config->default_color_regular; session_data->m_user_record->sPromptColor = m_config->default_color_prompt; session_data->m_user_record->sInputColor = m_config->default_color_input; session_data->m_user_record->sInverseColor = m_config->default_color_inverse; session_data->m_user_record->sStatColor = m_config->default_color_stat; session_data->m_user_record->sBoxColor = m_config->default_color_box; } virtual ~ModPreLogon() override { std::vector<std::function< void()> >().swap(m_setup_functions); std::vector<std::function< void(const std::string &)> >().swap(m_mod_functions); } virtual bool update(const std::string &character_buffer, const bool &) override; virtual bool onEnter() override; virtual bool onExit() override; // This matches the index for and key for setup -> mod_functions.push_back enum { MOD_DETECT_EMULATION, MOD_ASK_ANSI_COLOR, MOD_ASK_CODEPAGE }; // Create Prompt Constants, these are the keys for key/value lookup const std::string PROMPT_DETECT_EMULATION = "detect_emu"; const std::string PROMPT_DETECTED_ANSI = "detected_ansi"; const std::string PROMPT_DETECTED_NONE = "detected_none"; const std::string PROMPT_USE_ANSI = "use_ansi"; const std::string PROMPT_USE_INVALID = "ansi_invalid"; const std::string PROMPT_ANSI_SELECTED = "ansi_selected"; const std::string PROMPT_ASCII_SELECTED = "ascii_selected"; const std::string PROMPT_DETECT_TERMOPTS = "detect_term"; const std::string PROMPT_DETECTED_TERM = "detected_term"; const std::string PROMPT_DETECTED_SIZE = "detected_size"; const std::string PROMPT_ASK_CP437 = "use_cp437"; const std::string PROMPT_ASK_UTF8 = "use_utf8"; const std::string PROMPT_CP437_SELECTED = "cp437_selected"; const std::string PROMPT_UTF8_SELECTED = "utf8_selected"; /** * @brief Create Default Text Prompts for module */ void createTextPrompts(); /** * @brief Sets an individual module index. * @param mod_function_index */ void changeModule(int mod_function_index); /** * @brief Redisplay's the current module prompt. * @param mod_function_index */ void redisplayModulePrompt(); /** * @brief Pull and Display Prompts * @param prompt */ void displayPrompt(const std::string &prompt); /** * @brief Pull and Display Prompts with following newline * @param prompt */ void displayPromptAndNewLine(const std::string &prompt); /** * @brief Start ANSI ESC[6n ANSI Detection * @return */ void setupEmulationDetection(); /** * @brief Detection Completed, display results. * @return */ void setupAskANSIColor(); /** * @brief Displays Terminal Detection after Emulation Detection. */ void displayTerminalDetection(); /** * @brief Displays Terminal Detection before Asking CodePage. * @return */ void setupDisplayTerminalDetection(); /** * @brief Ask Setup CodePage CP437 / UTF-8 * @return */ void setupAskCodePage(); /** * @brief Quick Timer Methods left in the Header. */ /** * @brief Start ANSI Detection timer */ void startDetectionTimer() { // Add Deadline Timer for 1.5 seconds for complete Telopt Sequences responses m_deadline_timer->setWaitInMilliseconds(1500); m_deadline_timer->asyncWait( std::bind(&ModPreLogon::handleDetectionTimer, shared_from_this()) ); } /** * @brief Deadline Detection Timer for ANSI Detection * @param timer */ void handleDetectionTimer() { // Jump to Emulation completed. emulationCompleted(); } /** * @brief After Emulation Detection is completed * @param input */ void emulationCompleted(); private: /** * @brief Detect ANSI Emulation * @return */ bool emulationDetection(const std::string &input); /** * @brief ASK ANSI Color * @return */ bool askANSIColor(const std::string &input); /** * @brief ASK CodePage CP437 / UTF-8 * @return */ bool askCodePage(const std::string &input); // Function Input Vector. std::vector<std::function< void()> > m_setup_functions; std::vector<std::function< void(const std::string &)> > m_mod_functions; SessionIO m_session_io; std::string m_filename; text_prompts_dao_ptr m_text_prompts_dao; deadline_timer_ptr m_deadline_timer; int m_mod_function_index; bool m_is_text_prompt_exist; bool m_is_esc_detected; std::string m_input_buffer; int m_x_position; int m_y_position; std::string m_term_type; }; #endif // MOD_PRELOGON_HPP
62557002a59e5aad5a6d47e7695ff0828443c317
521175d39fc4adbf833529dd937017f1469b4db2
/src/sparse.cpp
fa99eaf9de38ed090dbe7754098b938a966b01e7
[]
no_license
brentonk/polywog
d0bf2e7441a832aed2d0fc4df305be0847d28e64
512f73fb6894cafc5f6ee496b5d8b50ab07be97b
refs/heads/master
2021-01-15T14:32:19.020957
2018-04-20T19:30:45
2018-04-20T19:30:45
16,388,091
2
3
null
2018-08-02T14:26:53
2014-01-30T19:23:45
R
UTF-8
C++
false
false
1,158
cpp
sparse.cpp
// Utility functions for working with sparse matrices #include <Rcpp.h> // Extract a specified column (by zero-based index) from a sparse matrix Rcpp::NumericVector columnFromSparse(Rcpp::S4 X, int j) { // Set up the output as an appropriately-sized vector of 0s Rcpp::IntegerVector dim = X.slot("Dim"); int nrow = dim[0]; Rcpp::NumericVector res(nrow, 0.0); // The values of a "dgCMatrix" object X are stored as follows: // o X@p contains the cumulative number of non-zero values by column // o The indices of the non-zero values of the j'th column are contained // in X@i[X@p[j]:(X@p[j+1]-1)] // o The corresponding values are stored in X@x[X@p[j]:(X@p[j+1]-1)] Rcpp::IntegerVector p = X.slot("p"); int ind_start = p[j]; int ind_end = p[j+1]; // Loop through the indices corresponding to the j'th column and fill in // the result vector appropriately int ind; Rcpp::IntegerVector indices = X.slot("i"); Rcpp::NumericVector values = X.slot("x"); for (int i = ind_start; i < ind_end; i++) { ind = indices[i]; res[ind] = values[i]; } return res; }
4642d6e291c77a6aeb32bc1d6e8467c4d85bb7ec
d7abac20980dcdab8e52f644cfbb201eb28ed944
/11653.cpp
a5467de94727e0699951d7cd152f17dc0fdf44e5
[]
no_license
HwangYoungHa/BaekJoon
1976f159a35218a37f25a32592677cd6144bd7a9
7a00f62a7ab89494f4a8bbba7ba8c010329a8063
refs/heads/master
2023-03-03T22:37:54.097359
2021-02-17T00:20:59
2021-02-17T00:20:59
294,125,886
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
11653.cpp
#include <stdio.h> void factorization(int n){ int i=0; while(true){ if(n <= 1) return; i=2; while(true){ if(n % i == 0){ printf("%d\n", i); n = n / i; break; } else{ i++; } } } return; } int main(){ int n; scanf("%d", &n); factorization(n); return 0; }
87b62a4803cd599b95f1bcef47bcb5468a2c9c3e
cc5730e4bc12df0e35e9bcbf208ef27f8b149238
/programs/inhertiance protected.cpp
dfbad398782afbd87d90316a0e51795e780cf074
[]
no_license
RAzaALy/Cpp_Programming
4ff601f018c135b801a30dc5601e3f13ab6924d5
a55bbb3e8681e57e07a33cf7cf183241b06fae70
refs/heads/main
2023-06-14T20:30:30.671126
2021-06-23T07:08:35
2021-06-23T07:08:35
378,995,882
0
0
null
null
null
null
UTF-8
C++
false
false
512
cpp
inhertiance protected.cpp
#include <iostream> #include <conio.h> using namespace std; class base { private: int c; public: int a; protected: int b; }; //public and protected members of base class are protected of derived class: class derived:protected base { public: void input() { cout<<"ENTER VALUE OF A:"; cin>>a; cout<<"ENTER VALUE OF B:"; cin>>b; } void output() { cout<<"a="<<a<<" b="<<b; } }; int main() { derived obj; obj.input(); obj.output(); getch(); return 0; }
ee81c57ca0f8bbb7a3dde3d9c7613504d8b1a7c8
f2bb41ab831f4a8ac9806b84424009f40b6ca153
/3Dアクションゲーム/WizardAdventure/WizardAdventure/sphere_particle.cpp
d8f57c5daa81df9ac687d021db899749281b55c2
[]
no_license
sugawaratukasa/-3DGame
6f6e6774412dd0e1d4da3941a71e55795ee3885c
c07fe1021d4b4ae973cd1a89292917f67b792c8b
refs/heads/master
2023-04-13T03:45:02.291401
2021-04-26T07:12:11
2021-04-26T07:12:11
328,649,456
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,342
cpp
sphere_particle.cpp
//****************************************************************************** // 球のパーティクルエミッター [sphere_particle.cpp] // Author : 管原 司 //****************************************************************************** //****************************************************************************** // インクルードファイル //****************************************************************************** #include "main.h" #include "manager.h" #include "renderer.h" #include "sphere_particle.h" //****************************************************************************** // マクロ定義 //****************************************************************************** #define SUB_SCALE_VALUE (0.005f) // 拡大率減算値 #define SUB_COLOR_VALUE (0.005f) // 色減算値 #define MIN_SCALE_VALUE (0.0f) // 拡大率最小値 #define MIN_COLOR_VALUE (0.0f) // 色の最小値 //****************************************************************************** // コンストラクタ //****************************************************************************** CSphere_Particle::CSphere_Particle(int nPrirority) { m_move = INIT_D3DXVECTOR3; m_fMinScale = INIT_FLOAT; m_fMinColor = INIT_FLOAT; } //****************************************************************************** // デストラクタ //****************************************************************************** CSphere_Particle::~CSphere_Particle() { } //****************************************************************************** // 生成関数 //****************************************************************************** CSphere_Particle * CSphere_Particle::Create(D3DXVECTOR3 pos, D3DXVECTOR3 size, D3DXVECTOR3 rot, D3DXCOLOR col, D3DXVECTOR3 move, CParticle::TEX_TYPE TexType) { // CParticle_Fireクラスのポインタ CSphere_Particle *pSphere_Particle; // メモリ確保 pSphere_Particle = new CSphere_Particle; // 初期化 pSphere_Particle->Init(pos, size, rot, col, move, TexType); // ポインタを返す return pSphere_Particle; } //****************************************************************************** // 初期化 //****************************************************************************** HRESULT CSphere_Particle::Init(D3DXVECTOR3 pos, D3DXVECTOR3 size, D3DXVECTOR3 rot, D3DXCOLOR col, D3DXVECTOR3 move, CParticle::TEX_TYPE TexType) { // 初期化 CParticle::Init(pos, size, rot, col, TexType); // 移動量 m_move = move; // 拡大率減算値 m_fMinScale = SUB_SCALE_VALUE; // カラー減算値 m_fMinColor = SUB_COLOR_VALUE; return S_OK; } //****************************************************************************** // 終了関数 //****************************************************************************** void CSphere_Particle::Uninit(void) { // 終了 CParticle::Uninit(); } //****************************************************************************** // 更新関数 //****************************************************************************** void CSphere_Particle::Update(void) { // 更新 CParticle::Update(); // 位置座標取得 D3DXVECTOR3 pos = GetPosition(); // 色取得 D3DXCOLOR col = GetColor(); // 拡大率取得 float fScale = GetScale(); // カラー減算 col.a -= m_fMinColor; // aの値が0以下の場合 if (col.a <= MIN_COLOR_VALUE) { col.a = MIN_COLOR_VALUE; } // サイズ減算 fScale -= m_fMinScale; // サイズ設定 SetScale(fScale); // 色設定 SetColor(col); // 位置更新 pos += m_move; // 位置座標設定 SetPosition(pos); // 拡大率が0.0f以下の場合 if (fScale <= MIN_SCALE_VALUE) { // 終了 Uninit(); return; } // αが0.0f以下の場合 if (col.a <= MIN_COLOR_VALUE) { // 終了 Uninit(); return; } } //****************************************************************************** // 描画関数 //****************************************************************************** void CSphere_Particle::Draw(void) { // レンダラー取得 LPDIRECT3DDEVICE9 pDevice = CManager::GetRenderer()->GetDevice(); // 加算合成の設定 pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); // 描画 CParticle::Draw(); // 元に戻す pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); }
08c760b0786d26ec268961b634e007e49d78a1b6
af828ccfbf4a30657d2adcd7e16d973830de1c39
/Apps/Pong/GameState.h
bda552191d6b8ce6584fc97edf043d6a9547e235
[]
no_license
thejoggeli/matrix-raspi-3d
0d682c4ab8bc5e78a5cb59731c526a5477d92959
7f62b741ac618bb6d4e08ea0b9bddbaa42532216
refs/heads/master
2021-06-26T21:48:06.459979
2020-10-26T10:56:26
2020-10-26T10:56:26
172,988,332
0
0
null
null
null
null
UTF-8
C++
false
false
844
h
GameState.h
#pragma once #include <vector> #include "Ledlib2d/State.h" #include "Ledlib/Util/Timer.h" #include "Ledlib/Util/ColorHsl.h" #include "Ledlib2d/WeakPointerList.h" using namespace Ledlib; namespace Ledlib { class Client; class Bitmap; } class Ball; class Paddle; class GameState : public State { public: bool playing = false; std::shared_ptr<Bitmap> bgBitmap; float bgAngle = 0; float bgHue = 0; Timer beatTimer; Timer introTimer; ColorHsl borderColor; std::vector<std::weak_ptr<Client>> startClients; WeakPointerList<Paddle> paddles; WeakPointerList<Ball> balls; GameState(); ~GameState(); void OnStart(); void OnUpdate(); void OnRender(); void OnAfterRender(); void AssignClientToFreePaddle(std::shared_ptr<Client> client); void AddStartClient(std::shared_ptr<Client> client); std::shared_ptr<Ball> GetBall(); };
ea5da23999c602b824fbd454d321f4d86b79edaa
dcce3076bbe5920c0323c8b4354c534f98f32f99
/HeapManager/Source/FixedSizeAllocator.h
1d192219e46eb20937b7c58dc5cf851b9f9c00bc
[]
no_license
ChuanChinLai/HeapManager
d553d2f3bab2c795109ae046970c9869c6f8a385
ff68a255c7cd4da356db87e18665c49183c5f735
refs/heads/master
2021-01-11T20:50:46.550632
2017-10-24T07:40:32
2017-10-24T07:40:32
79,197,337
0
0
null
null
null
null
UTF-8
C++
false
false
936
h
FixedSizeAllocator.h
#pragma once #include <cstdint> namespace Engine { namespace Memory { class HeapManager; class BitArray; class FSA_INFO { public: FSA_INFO() { } FSA_INFO(size_t i_BlockSize, size_t i_NumBlocks) : BlockSize(i_BlockSize), NumBlocks(i_NumBlocks) { } size_t BlockSize; size_t NumBlocks; }; class FixedSizeAllocator { public: static FixedSizeAllocator* _Create(const FSA_INFO i_INFO, HeapManager* i_pHeapManager); void* _Alloc(); bool _Free(const void* i_pMemory); inline void _Clear(); inline void _Destroy(); inline bool _IsAvailable() const; inline const FSA_INFO& _GetINFO() const; private: FixedSizeAllocator(void* i_pMemoryPool, const size_t i_NumBlocks, const size_t i_BlockSize); size_t m_SIZE; //Total SIZE FSA_INFO m_INFO; uintptr_t m_pMemoryPool; BitArray* m_pStates; }; } } #include <FixedSizeAllocator_inline.h>
a31a0ec2e89a3f7a8329e6ccb598a31652084247
ede79e2e55f6a029d0593ea257ea45896c911ee5
/src/10929 You can say 11.cpp
6162c4244f02584e65d7e6145e55fdf28bb47a57
[]
no_license
LRih/UVa-Problems
52ab997a964112993c0bc5842a510739b00ca1d3
d517fe77fb403acad3f8ef663a03a81b30bf36f2
refs/heads/master
2016-08-12T18:53:29.271538
2015-10-29T02:12:01
2015-10-29T02:12:01
36,557,277
0
0
null
null
null
null
UTF-8
C++
false
false
795
cpp
10929 You can say 11.cpp
#include <cstdio> #include <iostream> using namespace std; string num; bool isDiv11() { int sum = 0; for (int i = 0; i < num.length(); i++) { if (i % 2 == 0) sum += num[i] - 48; else sum -= num[i] - 48; } return sum % 11 == 0; } int main() { while (true) { getline(cin, num); if (num.length() == 1 && num[0] == '0') break; if (isDiv11()) cout << num << " is a multiple of 11." << endl; else cout << num << " is not a multiple of 11." << endl; } } /* 112233 30800 2937 323455693 5038297 112234 0 112233 is a multiple of 11. 30800 is a multiple of 11. 2937 is a multiple of 11. 323455693 is a multiple of 11. 5038297 is a multiple of 11. 112234 is not a multiple of 11. */
471027e125e09870ab6aac2b4cbb18700502d0d6
34e69cf4ad31174ee1857a07d5ce147a81939f51
/include/statement.hh
83d246b42fe68b52e18b34fc17a1950befc86d39
[]
no_license
mohammadreza33/peylang
5d61a82940148d9ddf1fc7f04f2b039d15344b57
a1d267f22a782385ca8d1477c7c7938324423bb3
refs/heads/master
2023-01-05T20:21:54.853192
2020-10-29T20:52:29
2020-10-29T20:52:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,908
hh
statement.hh
// compiler's internal statements // TODO: switch to visitor design pattern in future #ifndef STATEMENT_HH_ #define STATEMENT_HH_ #include <exception.hh> #include <expression.hh> #include <list> #include <symtable.hh> namespace pey { class Statement { public: virtual int eval(Symtable &smtbl) const = 0; virtual ~Statement() {} }; class Statements { private: std::list<Statement *> _statements; public: ~Statements(); void add(Statement *stmnt); int eval(Symtable &smtbl) const; }; class Define : public Statement { private: std::string _ident; public: Define(const std::string &ident); int eval(Symtable &smtbl) const; }; class Assign : public Statement { private: std::string _ident; Expression *_expr; public: Assign(const std::string &nm, Expression *expr); ~Assign(); int eval(Symtable &smtbl) const; }; class DefAssign : public Statement { private: std::string _ident; Expression *_expr; public: DefAssign(const std::string &ident, Expression *expr); ~DefAssign(); int eval(Symtable &smtbl) const; }; class Print : public Statement { private: Expression *_expr; public: Print(Expression *expr); ~Print(); int eval(Symtable &smtbl) const; }; class Input : public Statement { private: std::string _ident; public: Input(std::string ident); int eval(Symtable &smtbl) const; }; class IfElse : public Statement { private: Expression *_condition; Statements *_true_list, *_false_list; public: IfElse(Expression *condition, Statements *true_list); IfElse(Expression *condition, Statements *true_list, Statements *false_list); ~IfElse(); int eval(Symtable &smtbl) const; }; class While : public Statement { private: Expression *_condition; Statements *_true_list; public: While(Expression *condition, Statements *true_list); ~While(); int eval(Symtable &smtbl) const; }; } // namespace pey #endif // STATEMENT_HH_
b54d781df4629e5fa2b16f05cd29cd0261e9c86a
23b25124dbd1b55dc4af17cc1716422e1b30f5cd
/leetcode-cn/160.cpp
b3485c3c9c62298667f393ccd59394b2b3074661
[]
no_license
qinzuoyan/exercise
428d08b8abb02239eea4d4a9cb970f80fbabac87
50c15e6722b601bb3c8fbb18676b613f223d9a7b
refs/heads/master
2022-04-30T12:54:08.239699
2022-03-24T13:12:45
2022-03-24T13:12:45
48,578,652
0
1
null
null
null
null
UTF-8
C++
false
false
779
cpp
160.cpp
#include <stack> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if (!headA || !headB) return nullptr; stack<ListNode*> sa, sb; ListNode *a = headA, *b = headB; while (a) { sa.push(a); a = a->next; } while (b) { sb.push(b); b = b->next; } ListNode* p = nullptr; while (!sa.empty() && !sb.empty() && sa.top() == sb.top()) { p = sa.top(); sa.pop(); sb.pop(); } return p; } };
6cab8bf7e6611fcd1d38c896b29355f9d29c4783
72414e441408d6d63d24e2154a3694e243a4f2a9
/Multi-JSON-Interface/include/mjsoni/generic_json_config_reader.hpp
0df3276345768bd2864c7b2ee4ca5c86dbfdfb8b
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
IAmTrial/Multi-JSON-Interface
75f11174ae17b83e90a59ff6d33675af8f3f02c7
95f9e6c2d953af9e104a9f43532ef17daaf2f1bb
refs/heads/master
2021-06-16T16:15:49.814767
2021-04-07T03:29:16
2021-04-07T03:29:16
192,013,888
0
0
null
null
null
null
UTF-8
C++
false
false
15,840
hpp
generic_json_config_reader.hpp
/** * Multi JSON Interface * Copyright (C) 2019 Mir Drualga * * This file is part of Multi JSON Interface. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MJSONI_GENERIC_JSON_CONFIG_READER_HPP_ #define MJSONI_GENERIC_JSON_CONFIG_READER_HPP_ #include <cstdint> #include <deque> #include <filesystem> #include <initializer_list> #include <map> #include <set> #include <string> #include <string_view> #include <unordered_map> #include <unordered_set> #include <vector> namespace mjsoni { template<typename DOC, typename OBJ, typename VAL> class GenericConfigReader { using JsonDocument = DOC; using JsonObject = OBJ; using JsonValue = VAL; public: GenericConfigReader() = delete; explicit GenericConfigReader( std::filesystem::path config_file_path ); /* Read and Write */ bool Read(); bool Write(int indent_width); /* Functions for Generic Types */ template <typename ...Args> bool ContainsKey( const Args&... keys ) const; template <typename ...Args> const JsonValue& GetValueRef( const Args&... keys ) const; template <typename Container, typename ...Args> Container GetArrayCopy( const Args&... keys ) const; template <typename Iter, typename ...Args> void SetArray( Iter first, Iter last, const Args&... keys ); template <typename Iter, typename ...Args> void SetDeepArray( Iter first, Iter last, const Args&... keys ); template <typename ...Args> void SetValue( JsonValue value, const Args&... keys ); template <typename ...Args> void SetDeepValue( JsonValue value, const Args&... keys ); /* Functions for bool */ template <typename ...Args> bool GetBool( const Args&... keys ) const; template <typename ...Args> bool GetBoolOrDefault( bool default_value, const Args&... keys ) const; template <typename ...Args> bool HasBool( const Args&... keys ) const; template <typename ...Args> void SetBool( bool value, const Args&... keys ); template <typename ...Args> void SetDeepBool( bool value, const Args&... keys ); /* Functions for std::deque */ template <typename T, typename ...Args> std::deque<T> GetDeque( const Args&... keys ) const; template <typename T, typename ...Args> std::deque<T> GetDequeOrDefault( const std::deque<T>& default_value, const Args&... keys ) const; template <typename T, typename ...Args> std::deque<T> GetDequeOrDefault( std::deque<T>&& default_value, const Args&... keys ) const; template <typename ...Args> bool HasDeque( const Args&... keys ) const; template <typename T, typename ...Args> void SetDeque( const std::deque<T>& value, const Args&... keys ); template <typename ...Args> void SetDeque( const std::deque<std::string_view>& value, const Args&... keys ); template <typename T, typename ...Args> void SetDeque( std::deque<T>&& value, const Args&... keys ); template <typename T, typename ...Args> void SetDeepDeque( const std::deque<T>& value, const Args&... keys ); template <typename T, typename ...Args> void SetDeepDeque( std::deque<T>&& value, const Args&... keys ); /* Functions for int */ template <typename ...Args> int GetInt( const Args&... keys ) const; template <typename ...Args> int GetIntOrDefault( int default_value, const Args&... keys ) const; template <typename ...Args> bool HasInt( const Args&... keys ) const; template <typename ...Args> void SetInt( int value, const Args&... keys ); template <typename ...Args> void SetDeepInt( int value, const Args&... keys ); /* Functions for std::int32_t */ template <typename ...Args> std::int32_t GetInt32( const Args&... keys ) const; template <typename ...Args> std::int32_t GetInt32OrDefault( std::int32_t default_value, const Args&... keys ) const; template <typename ...Args> bool HasInt32( const Args&... keys ) const; template <typename ...Args> void SetInt32( std::int32_t value, const Args&... keys ); template <typename ...Args> void SetDeepInt32( std::int32_t value, const Args&... keys ); /* Functions for std::int64_t */ template <typename ...Args> std::int64_t GetInt64( const Args&... keys ) const; template <typename ...Args> std::int64_t GetInt64OrDefault( std::int64_t default_value, const Args&... keys ) const; template <typename ...Args> bool HasInt64( const Args&... keys ) const; template <typename ...Args> void SetInt64( std::int64_t value, const Args&... keys ); template <typename ...Args> void SetDeepInt64( std::int64_t value, const Args&... keys ); /* Functions for long */ template <typename ...Args> long GetLong( const Args&... keys ) const; template <typename ...Args> long GetLongOrDefault( long default_value, const Args&... keys ) const; template <typename ...Args> bool HasLong( const Args&... keys ) const; template <typename ...Args> void SetLong( long value, const Args&... keys ); template <typename ...Args> void SetDeepLong( long value, const Args&... keys ); /* Functions for long long */ template <typename ...Args> long long GetLongLong( const Args&... keys ) const; template <typename ...Args> long long GetLongLongOrDefault( long long default_value, const Args&... keys ) const; template <typename ...Args> bool HasLongLong( const Args&... keys ) const; template <typename ...Args> void SetLongLong( long long value, const Args&... keys ); template <typename ...Args> void SetDeepLongLong( long long value, const Args&... keys ); /* Functions for std::filesystem::path */ template <typename ...Args> std::filesystem::path GetPath( const Args&... keys ) const; template <typename ...Args> std::filesystem::path GetPathOrDefault( const std::filesystem::path& default_value, const Args&... keys ) const; template <typename ...Args> std::filesystem::path GetPathOrDefault( std::filesystem::path&& default_value, const Args&... keys ) const; template <typename ...Args> bool HasPath( const Args&... keys ) const; template <typename ...Args> void SetPath( const std::filesystem::path& value, const Args&... keys ); template <typename ...Args> void SetDeepPath( const std::filesystem::path& value, const Args&... keys ); /* Functions for std::set */ template <typename T, typename ...Args> std::set<T> GetSet( const Args&... keys ) const; template <typename T, typename ...Args> std::set<T> GetSetOrDefault( const std::set<T>& default_value, const Args&... keys ) const; template <typename T, typename ...Args> std::set<T> GetSetOrDefault( std::set<T>&& default_value, const Args&... keys ) const; template <typename ...Args> bool HasSet( const Args&... keys ) const; template <typename T, typename ...Args> void SetSet( const std::set<T>& value, const Args&... keys ); template <typename T, typename ...Args> void SetSet( std::set<T>&& value, const Args&... keys ); template <typename T, typename ...Args> void SetDeepSet( const std::set<T>& value, const Args&... keys ); template <typename T, typename ...Args> void SetDeepSet( std::set<T>&& value, const Args&... keys ); /* Functions for std::string */ template <typename ...Args> std::string GetString( const Args&... keys ) const; template <typename ...Args> std::string GetStringOrDefault( const std::string& default_value, const Args&... keys ) const; template <typename ...Args> std::string GetStringOrDefault( std::string&& default_value, const Args&... keys ) const; template <typename ...Args> bool HasString( const Args&... keys ) const; template <typename ...Args> void SetString( const std::string& value, const Args&... keys ); template <typename ...Args> void SetString( std::string&& value, const Args&... keys ); template <typename ...Args> void SetDeepString( const std::string& value, const Args&... keys ); template <typename ...Args> void SetDeepString( std::string&& value, const Args&... keys ); /* Functions for unsigned int */ template <typename ...Args> unsigned int GetUnsignedInt( const Args&... keys ) const; template <typename ...Args> unsigned int GetUnsignedIntOrDefault( unsigned int default_value, const Args&... keys ) const; template <typename ...Args> bool HasUnsignedInt( const Args&... keys ) const; template <typename ...Args> void SetUnsignedInt( unsigned int value, const Args&... keys ); template <typename ...Args> void SetDeepUnsignedInt( unsigned int value, const Args&... keys ); /* Functions for std::uint32_t */ template <typename ...Args> std::uint32_t GetUnsignedInt32( const Args&... keys ) const; template <typename ...Args> std::uint32_t GetUnsignedInt32OrDefault( std::uint32_t default_value, const Args&... keys ) const; template <typename ...Args> bool HasUnsignedInt32( const Args&... keys ) const; template <typename ...Args> void SetUnsignedInt32( std::uint32_t value, const Args&... keys ); template <typename ...Args> void SetDeepUnsignedInt32( std::uint32_t value, const Args&... keys ); /* Functions for std::uint64_t */ template <typename ...Args> std::uint64_t GetUnsignedInt64( const Args&... keys ) const; template <typename ...Args> std::uint64_t GetUnsignedInt64OrDefault( std::uint64_t default_value, const Args&... keys ) const; template <typename ...Args> bool HasUnsignedInt64( const Args&... keys ) const; template <typename ...Args> void SetUnsignedInt64( std::uint64_t value, const Args&... keys ); template <typename ...Args> void SetDeepUnsignedInt64( std::uint64_t value, const Args&... keys ); /* Functions for unsigned long */ template <typename ...Args> unsigned long GetUnsignedLong( const Args&... keys ) const; template <typename ...Args> unsigned long GetUnsignedLongOrDefault( unsigned long default_value, const Args&... keys ) const; template <typename ...Args> bool HasUnsignedLong( const Args&... keys ) const; template <typename ...Args> void SetUnsignedLong( unsigned long value, const Args&... keys ); template <typename ...Args> void SetDeepUnsignedLong( unsigned long value, const Args&... keys ); /* Functions for unsigned long long */ template <typename ...Args> unsigned long long GetUnsignedLongLong( const Args&... keys ) const; template <typename ...Args> unsigned long long GetUnsignedLongLongOrDefault( unsigned long long default_value, const Args&... keys ) const; template <typename ...Args> bool HasUnsignedLongLong( const Args&... keys ) const; template <typename ...Args> void SetUnsignedLongLong( unsigned long long value, const Args&... keys ); template <typename ...Args> void SetDeepUnsignedLongLong( unsigned long long value, const Args&... keys ); /* Functions for std::unordered_set */ template <typename T, typename ...Args> std::unordered_set<T> GetUnorderedSet( const Args&... keys ) const; template <typename T, typename ...Args> std::unordered_set<T> GetUnorderedSetOrDefault( const std::unordered_set<T>& default_value, const Args&... keys ) const; template <typename T, typename ...Args> std::unordered_set<T> GetUnorderedSetOrDefault( std::unordered_set<T>&& default_value, const Args&... keys ) const; template <typename ...Args> bool HasUnorderedSet( const Args&... keys ) const; template <typename T, typename ...Args> void SetUnorderedSet( const std::unordered_set<T>& value, const Args&... keys ); template <typename T, typename ...Args> void SetUnorderedSet( std::unordered_set<T>&& value, const Args&... keys ); template <typename T, typename ...Args> void SetDeepUnorderedSet( const std::unordered_set<T>& value, const Args&... keys ); template <typename T, typename ...Args> void SetDeepUnorderedSet( std::unordered_set<T>&& value, const Args&... keys ); /* Functions for std::vector */ template <typename T, typename ...Args> std::vector<T> GetVector( const Args&... keys ) const; template <typename T, typename ...Args> std::vector<T> GetVectorOrDefault( const std::vector<T>& default_value, const Args&... keys ) const; template <typename T, typename ...Args> std::vector<T> GetVectorOrDefault( std::vector<T>&& default_value, const Args&... keys ) const; template <typename ...Args> bool HasVector( const Args&... keys ) const; template <typename T, typename ...Args> void SetVector( const std::vector<T>& value, const Args&... keys ); template <typename T, typename ...Args> void SetVector( std::vector<T>&& value, const Args&... keys ); template <typename T, typename ...Args> void SetDeepVector( const std::vector<T>& value, const Args&... keys ); template <typename T, typename ...Args> void SetDeepVector( std::vector<T>&& value, const Args&... keys ); /* Getter and Setters */ constexpr const std::filesystem::path& config_file_path() const noexcept { return this->config_file_path_; } constexpr const JsonDocument& json_document() const noexcept { return this->json_document_; } private: std::filesystem::path config_file_path_; JsonDocument json_document_; template <typename ...Args> bool ContainsKeyRecursive( const JsonObject& object, std::string_view current_key, const Args&... keys ) const; template <typename ...Args> JsonValue& GetValueRefRecursive( JsonObject& object, std::string_view current_key, const Args&... keys ); template <typename ...Args> const JsonValue& GetValueRefRecursive( const JsonObject& object, std::string_view current_key, const Args&... keys ) const; template <typename ...Args> void SetValueRecursive( JsonValue value, JsonObject& object, std::string_view current_key, const Args&... keys ); template <typename ...Args> void SetDeepValueRecursive( JsonValue value, JsonObject& object, std::string_view current_key, const Args&... keys ); }; } // namespace mjsoni #endif // MJSONI_GENERIC_JSON_CONFIG_READER_HPP_
1fa2454b1c93381860b8b4e666305b0ca9e7d2a3
ba8ad508ca0bc9196fc3425ba3341565a912c3b8
/indie-studio/script/source/default/Default.cpp
acd8826a0b2c8579204d1c7c3077624c3c68df20
[]
no_license
Unreality3D/Unreality3D
05fa92a0e6913da6e5d85e0747907a68bd8359f1
9f08c24c4a72a1b653f492609a277e578aae66e7
refs/heads/master
2021-01-19T02:31:42.723787
2016-06-09T11:21:42
2016-06-09T11:21:42
60,762,894
3
2
null
2016-06-09T11:21:42
2016-06-09T09:19:54
C++
UTF-8
C++
false
false
787
cpp
Default.cpp
// // Default.hpp for in /home/gandoulf/epitech/cpp_indie_studio/indie-studio/script/source/default // // Made by Gandoulf // Login <gandoulf@epitech.net> // // Started on Tue May 24 17:53:57 2016 Gandoulf // Last update Mon May 30 14:02:27 2016 Gandoulf // #include "default/Default.hpp" #include "IndieStudio/GameManager.hpp" Default::Default(indie::GameObject *&_gameObject) : AScript(_gameObject) { } Default::~Default() { } void Default::Start() { std::cout << "default start" << std::endl; } void Default::Update() { gameObject->setPosition(Ogre::Vector3(gameObject->getPosition().x + 1, gameObject->getPosition().y, gameObject->getPosition().z)); } void Default::OnCollisionEnter(indie::GameObject *coll) { indie::GameManager::destroy(coll, 3000); }
dd42ed929391327cfc324f2339420cb2ad1f3c01
43b1903f35fa75bf6490bff605410d2d12f82382
/Realization/Search/BinSortTree/BinSortTree.h
b8ac21a879ff44c35efbd746bc94a5f144c137d6
[]
no_license
Trouvaille0198/DataStructure
1a1ad2f27055338c0edd588a170a9e84c2c3e791
6ce4a1c9e76dcbc2fc97568f46c5e4d4a38595b7
refs/heads/main
2023-06-01T11:44:04.411907
2021-06-17T10:16:43
2021-06-17T10:16:43
316,417,692
4
3
null
null
null
null
UTF-8
C++
false
false
4,437
h
BinSortTree.h
#include "../../Tree/BinaryTree/BinaryTree.h" #include <bits/stdc++.h> using namespace std; template <class T> class BinSortTree : public BinaryTree<T> { // 继承二叉树的根节点数据成员 public: BinSortTree(T refvalue) : BinaryTree<T>(refvalue){}; BinSortTree(T *a, int n); // 插入数组元素构建二叉排序树, 不用判断 ~BinSortTree() {} void Insert(const T &x, BinTreeNode<T> *&p); // 以p为根节点, 按大小插入元素 /*判定是否为二叉排序树*/ bool IsBST_Recursive(BinTreeNode<T> *r, T *pre, bool *result); // 递归方式判断是否为二叉排序树 bool IsBST_Recursive(); void DisplayLarger(BinTreeNode<T> *p, const T &x); // 从大到小输出不小于x的元素 void DisplayLarger(const T &x) { DisplayLarger(this->_root, x); cout << endl; } bool Find_NoRecursive(BinTreeNode<T> *&root, const T &x); // 在以root为根的子树中查找x bool Find_NoRecursive(const T &x) { return Find_NoRecursive(this->_root, x); } void Insert_NoRecursive(BinTreeNode<T> *&root, const T &x); // 在以root为根的子树中插入x void Insert_NoRecursive(const T &x) { Insert_NoRecursive(this->_root, x); } bool SearchOrInsert(T &x); }; template <class T> BinSortTree<T>::BinSortTree(T *a, int n) { for (int i = 0; i < n; i++) Insert(a[i], this->_root); } template <class T> void BinSortTree<T>::Insert(const T &x, BinTreeNode<T> *&p) { if (p == NULL) p = new BinTreeNode<T>(x); else { if (x < p->_data) Insert(x, p->_leftChild); else if (x > p->_data) Insert(x, p->_rightChild); else cout << "Error Inserting!" << endl; } } template <class T> bool BinSortTree<T>::IsBST_Recursive(BinTreeNode<T> *r, T *pre, bool *result) // 以r为根节点, 利用递归中序遍历, 判断是否为二叉排序树 { if (!r) { *result = true; //*pre = NULL; return *result; } if (r->_leftChild && *result) // 从树的最左开始判断, *result 默认为真 IsBST_Recursive(r->_leftChild, pre, result); // 此时pre被赋值为当前节点的中序前驱 if (r->_data < *pre) // 与其中序前驱相比较 *result = false; *pre = r->_data; // 赋中序值 if (r->_rightChild && *result) // 遍历右子树咯 IsBST_Recursive(r->_rightChild, pre, result); return *result; } template <class T> bool BinSortTree<T>::IsBST_Recursive() { T pre; bool result = true; BinTreeNode<T> *p = this->_root; if (!p) { cout << "树为空!" << endl; return result; } IsBST_Recursive(p, &pre, &result); return result; } template <class T> void BinSortTree<T>::DisplayLarger(BinTreeNode<T> *p, const T &x) // 逆中序遍历 { if (p) { DisplayLarger(p->_rightChild, x); if (p->_data > x) cout << p->_data << " "; else return; DisplayLarger(p->_leftChild, x); } } template <class T> bool BinSortTree<T>::Find_NoRecursive(BinTreeNode<T> *&root, const T &x) { if (root == NULL) // 树空 return false; BinTreeNode<T> *temp = root; while (temp != NULL) { if (x == temp->_data) { return true; } if (x < temp->_data) temp = temp->_leftChild; else temp = temp->_rightChild; } return false; } template <class T> bool BinSortTree<T>::SearchOrInsert(T &x) { if (Find_NoRecursive(x)) { return true; } else { Insert_NoRecursive(x); return false; } } template <class T> void BinSortTree<T>::Insert_NoRecursive(BinTreeNode<T> *&root, const T &x) { if (root == NULL) // 空树 { root = new BinTreeNode<T>(x); return; } BinTreeNode<T> *temp = root, *parent = NULL; while (temp != NULL) { if (x == temp->_data) { cout << "要插入的值已存在!" << endl; return; } parent = temp; //记录最后时刻的父节点 if (x < temp->_data) temp = temp->_leftChild; else temp = temp->_rightChild; } temp = new BinTreeNode<T>(x); if (x < parent->_data) parent->_leftChild = temp; else parent->_rightChild = temp; }
7eb78d5c666e28e7525df66121c94484a123de7f
39eac74fa6a244d15a01873623d05f480f45e079
/LabCustomFieldListItemEditor.h
ded873b7e4118bfdc28a3d5d07e75a9ef67f199f
[]
no_license
15831944/Practice
a8ac8416b32df82395bb1a4b000b35a0326c0897
ae2cde9c8f2fb6ab63bd7d8cd58701bd3513ec94
refs/heads/master
2021-06-15T12:10:18.730367
2016-11-30T15:13:53
2016-11-30T15:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,234
h
LabCustomFieldListItemEditor.h
// (r.gonet 09/21/2011) - PLID 45606 - Added #pragma once #include "LabCustomField.h" #include "AdministratorRc.h" using namespace NXTIMELib; using namespace NXDATALIST2Lib; // CLabCustomFieldListItemEditor dialog class CLabCustomFieldListItemEditor : public CNxDialog { DECLARE_DYNAMIC(CLabCustomFieldListItemEditor) private: // Enums enum EValueTypeListColumn { evtlcID = 0, evtlcName, }; // Controls CNxStatic m_nxsHeader; CNxStatic m_nxsValueType; NXDATALIST2Lib::_DNxDataListPtr m_pValueTypeList; CNxStatic m_nxsDescription; CNxEdit m_nxeditDescription; CNxStatic m_nxsValue; NxButton m_radioBoolValueTrue; NxButton m_radioBoolValueFalse; CNxEdit m_nxeditTextValue; CNxEdit m_nxeditIntValue; CNxEdit m_nxeditFloatValue; NXTIMELib::_DNxTimePtr m_nxtimeDateTimeValue; CNxIconButton m_btnOK; CNxIconButton m_btnCancel; CNxIconButton m_btnHelp; // Data // (r.gonet 09/21/2011) - PLID 45606 - The item to edit. CLabCustomListFieldItem &m_lclfiItem; // (r.gonet 09/21/2011) - PLID 45606 - Copy of the item that will hold all intermediate changes. CLabCustomListFieldItem m_lclfiTempItem; public: CLabCustomFieldListItemEditor(CLabCustomListFieldItem &lclfiItem, CWnd* pParent); virtual ~CLabCustomFieldListItemEditor(); // Dialog Data enum { IDD = IDD_LAB_CUSTOM_FIELD_LIST_ITEM_EDITOR }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() private: void LoadValueTypeList(); void LoadControlValues(); void EnsureControls(); public: virtual BOOL OnInitDialog(); DECLARE_EVENTSINK_MAP() afx_msg void OnBnClickedOk(); afx_msg void OnBnClickedCancel(); afx_msg void OnBnClickedListItemBoolValueTrue(); afx_msg void OnBnClickedListItemBoolValueFalse(); void SelChosenListItemDataTypeList(LPDISPATCH lpRow); afx_msg void OnEnChangeListItemDescriptionEdit(); afx_msg void OnEnSetfocusListItemDescriptionEdit(); afx_msg void OnEnKillfocusListItemDescriptionEdit(); afx_msg void OnEnKillfocusListItemFloatValue(); afx_msg void OnEnKillfocusListItemTextValue(); afx_msg void OnEnKillfocusListItemIntegerValue(); void KillFocusListItemDatetimeValue(); afx_msg void OnBnClickedListItemEditorHelpBtn(); void SaveValue(); };
0b6d33ec402e7a533e392865f0c4f76a5e2e2569
eccc7e990f2c3e7a1f6facf96016666ed6910961
/Heaps/integerSteamMedian.cpp
0f9e64cc0fe12e8b0a8dcd1e940db5a7962a748c
[]
no_license
diyamahendru/Data-Structures-Challenges
3617e34306528a0e8993c498958bec38afa1a135
c0445e9a985f4d7b81216f5717f509001ace8b2f
refs/heads/master
2023-01-29T19:48:16.469864
2020-12-09T10:20:09
2020-12-09T10:20:09
265,329,457
1
0
null
null
null
null
UTF-8
C++
false
false
1,428
cpp
integerSteamMedian.cpp
#include<iostream> #include<queue> using namespace std; int main(){ int t,n,d; cin>>t; while(t--){ priority_queue<int> left; //max heap priority_queue<int, vector<int>, greater<int>> right; //min heap cin>>n>>d; left.push(d); int median=d; cout<<median<<" "; for(int i=1; i<n; i++){ cin>>d; if(left.size()>right.size()){ if(d<median){ right.push(left.top()); left.pop(); left.push(d); } else{ right.push(d); } median=(right.top()+left.top())/2; } else if(left.size()==right.size()){ if(d<median){ left.push(d); median=left.top(); } else{ right.push(d); median=right.top(); } } else{ if(d>median){ left.push(right.top()); right.pop(); right.push(d); } else{ left.push(d); } median=(right.top()+left.top())/2; } cout<<median<<" "; } cout<<endl; } return 0; }
8d04cf630efe46bf7b8ba4877ac984ccf2372340
b09623cfcc9c98686329cafb22bec499f44b4d76
/online_clustering/hmp/src/omp.cpp
830e3da4af85a613bf9588d292e66355d0237e1b
[]
no_license
mmmonkeytao/onlineclust
339ab30b956aa41af31574b7bc2ecf9b3edccfde
9180587546e83df6a4b2a748afcf318453705698
refs/heads/master
2016-09-06T01:21:36.755797
2015-01-25T15:25:29
2015-01-25T15:25:29
24,497,502
0
0
null
null
null
null
UTF-8
C++
false
false
3,755
cpp
omp.cpp
#include "hmp.h" #include <stdexcept> #include <cmath> #include <iostream> #include <fstream> void onlineclust::omp::Batch_OMP( Eigen::MatrixXd const& X, Eigen::MatrixXd const& D, uint SPlevel, Eigen::MatrixXd &Gamma ) { auto Xrow = X.rows(), Xcol = X.cols(), Drow = D.rows(), Dcol = D.cols(); if( !Xrow || !Xcol || !Drow || !Dcol || Xrow != Drow) throw std::runtime_error("\nInput parameters are wrong in OMP::Bach_OMP.\n"); // compute matrix G = D' D, G: Dcol by Dcol Eigen::MatrixXd G = D.transpose() * D; // compute apha^0 = D' x, alpha0: Dcol by Xcol Eigen::MatrixXd alpha0 = D.transpose() * X; // initialization Gamma = Eigen::MatrixXd::Zero(Dcol, Xcol); // iteration no. of obersations in X for(auto i = 0; i < Xcol; ++i){ // I stores ordered max_k std::vector<uint> I; // initialize L Eigen::MatrixXd L{1,1}; L << 1; // initialize std::vector for if same atom is selected std::vector<bool> selected(Dcol,false); uint k; Eigen::VectorXd a_I{1}, r_I{1}; bool flag; Eigen::VectorXd alpha = alpha0.col(i); // inner loop for no. of atoms in D for(uint j = 0; j < SPlevel; ++j){ maxIdxVec(alpha, k); double alpha_k = alpha(k); if(selected[k] || alpha_k*alpha_k < 1e-14) break; if(j > 0){ flag = true; onlineclust::omp::updateL(L, G, I, k, flag); if(flag == false) break; } selected[k] = true; I.push_back(k); // retrieve sub- std::vector of alpha(i) if(j > 0){ a_I.conservativeResize(j+1,1); r_I = Eigen::VectorXd(j+1); } a_I(j) = alpha(k); LL_solver(L, a_I, "LL", r_I); // get G_I Eigen::MatrixXd G_I{Dcol, j+1}; uint counter = 0; for(auto &x: I){ G_I.col(counter++) = G.col(x); } alpha = alpha0.col(i) - G_I * r_I; } uint count = 0; if(I.size() > 0) for(auto &x: I) Gamma(x,i) = r_I(count++); } } void onlineclust::omp::updateL( Eigen::MatrixXd & L, Eigen::MatrixXd const& G, std::vector<uint> const& I, uint k, bool& flag) { if(static_cast<uint>(L.rows()) != I.size()) throw std::runtime_error("\nInput dimensions do not match(updateL).\n"); auto dim = L.cols(); Eigen::VectorXd g{dim}; for(auto i = 0; i < dim; ++i) g(i) = G(k, I[i]); // solve for w linear system L * w = g using Cholesky decomposition Eigen::VectorXd omega{dim}; LL_solver(L, g, "L", omega); //cout << omega.transpose() << endl; // update L = [ L 0; w^T sqrt(1 - w'w)] L.conservativeResize(dim+1, dim+1); L.bottomLeftCorner(1,dim) = omega.transpose(); L.rightCols(1) = Eigen::MatrixXd::Zero(dim+1,1); double sum = 1 - omega.dot(omega); if(sum <= 1e-14){ flag = false; return; } L(dim, dim) = sqrt(sum); } void onlineclust::omp::LL_solver(Eigen::MatrixXd const& L, Eigen::VectorXd const& b, const char* type, Eigen::VectorXd& x) { if(L.cols() != b.size() || !x.size()) throw std::runtime_error("\nInput dimension errors(LL_solver).\n"); Eigen::VectorXd w{b.size()}, b1{b}; // L^T * w = b/L for(auto i = 0; i < b.size(); ++i){ for(auto j = 0; j < i; ++j) b1(i) -= w(j)*L(i,j); w(i) = (double)b1(i)/L(i,i); } if(!strcmp("L", type)) { x = w; return; } // w = x/L^T for(int i = b.size()-1; i >= 0; --i){ for(int j = b.size()-1; j > i; --j) w(i) -= x(j)*L(j,i); x(i) = (double)w(i)/L(i,i); } } void onlineclust::omp::maxIdxVec(Eigen::VectorXd const& v, uint &maxIdx) { double max = -1; for(uint i = 0; i < v.size(); i++){ if(fabs(v.coeff(i)) > max){ max = fabs(v.coeff(i)); maxIdx = i; } } }
c52242387f14fcc59cc24d598d3eccb352d38748
5157d68de16510161bd04c43c86d5749f8803d3b
/C++ Projects/EncryptionSystems/EncryptionSystems/main.cpp
1b87cdf160d2ff3191d570ac0622ffa8cf07d234
[]
no_license
TaylorZaneKirk/XombyGit
8d864eba7ff44b1e03f06d98329660005e848c20
4d8b5c870fffe7dab535208da311da5debbfadeb
refs/heads/master
2020-12-24T05:31:08.923719
2016-11-26T02:50:59
2016-11-26T02:50:59
8,965,880
0
0
null
null
null
null
UTF-8
C++
false
false
931
cpp
main.cpp
#include <iostream> #include <queue> using namespace std; void main(void){ char String[] = "I CANNOT SOLVE THIS IN LESS THAN A CHILIAD"; queue<int> Modified; int ModChar; for each(char i in String){ switch (i){ case 'A': ModChar = 0; break; case 'C': ModChar = 2; break; case 'D': ModChar = 3; break; case 'E': ModChar = 4; break; case 'H': ModChar = 7; break; case 'I': ModChar = 8; break; case 'L': ModChar = 11; break; case 'N': ModChar = 13; break; case 'O': ModChar = 14; break; case 'S': ModChar = 18; break; case 'T': ModChar = 19; break; case 'V': ModChar = 21; break; case ' ': ModChar = 26; break; default: cout << "Unexpected Letter" << endl; } ModChar = (ModChar + 7) % 27; Modified.push(ModChar); } while (Modified.empty() == false){ cout << Modified.front() << endl; Modified.pop(); } }
aa1e5c20b4284d3be88e2b8097dc9f07143561ac
9aa9abf6e479d9c1ae838aabed1fba9019b4bdd1
/cg_eig_bad/cg_solver.cpp
bacc2abd0377f5f8c9b2a5f4832c32cbd3369fdb
[]
no_license
rpeng233/TreePCG
443be0b4d56cbf51ddf2125c17df0ae5a9c6a9bb
a09b06fdf90fc3e6941bf6e237654e612ca4ddd3
refs/heads/master
2021-06-20T11:06:38.325504
2017-07-10T21:00:08
2017-07-10T21:00:08
63,903,737
0
1
null
null
null
null
UTF-8
C++
false
false
988
cpp
cg_solver.cpp
// Copyright 2016 Haoran Xu #include "../haoran_code/io.h" #include "../haoran_code/graph.h" #include "cg.h" #include "../haoran_code/jacobiprecon.h" int main(int argc, char *argv[]) { string dir = argv[1]; if (dir[dir.length()-1] != '/') dir+="/"; Mat L = IO::readMML(dir+"mat.mtx"); // Mat tree = IO::readMML(dir+"tree.mtx"); // Vec x(A.n); // rep(i,0,A.n-1) x[i]=(double(rand())/double(RAND_MAX)-0.5)*10; // Vec b=A*x; Vec x = IO::readMMVec(dir+"x.vec"); Vec b = L*x; AbstractSolver S = PCG(L,x); int flag; FLOAT relres; int iter; vector<FLOAT> resvec; clock_t t_start = clock(); tie(x, flag, relres, iter, resvec) = S.solve(b, 1e-20, 100); clock_t t_end = clock(); double tcost = static_cast<double>(t_end - t_start) / static_cast<double>(CLOCKS_PER_SEC); printf("n = %d iter = %d time = %.3lfs relres = %.16lf\n", L.n, iter, tcost, printFloat((L*x-b).norm()/b.norm())); return 0; }
05c4f156552724986e1b79c3bb7c70d89c667435
243eeb70c76c2bdfc29036d5bc9ce3ba144aedbc
/src/000-060/033.search-in-rotated-sorted-array/solution.h
fe16556c664f51cbda1d54246cf37af10f46784e
[]
no_license
879229629/LeetCode
45aab925424b701452117fa92ef2718594d01ec8
0ba8eced95954ace354d049645bb8ecbf0f8d940
refs/heads/master
2020-06-30T20:17:39.881898
2017-01-04T15:25:06
2017-01-04T15:25:06
74,355,045
1
0
null
2016-11-25T09:37:07
2016-11-21T11:02:55
C++
UTF-8
C++
false
false
204
h
solution.h
#ifndef LEETCODE_033_SOLUTION_H_ #define LEETCODE_033_SOLUTION_H_ #include <vector> class solution { public: int search(std::vector<int>& nums, int target); }; #endif // LEETCODE_033_SOLUTION_H_
ba0f296e7ccdac52bd0989e8bc5da7af725f6ad9
0cb62390faa669d2827914e21c05b959be0f8de4
/src/server/ez_mysql.cpp
e924a0df1f83fd6598750197af10eecd76d58e16
[]
no_license
sanderau/myChat
1314132032963c96b0a317a42fe6546de87f3d35
a48d0a3dccad51addc6b56899f7e84a183f17949
refs/heads/master
2022-07-06T06:15:24.733589
2020-05-15T15:14:41
2020-05-15T15:14:41
264,306,797
0
0
null
null
null
null
UTF-8
C++
false
false
3,368
cpp
ez_mysql.cpp
#include "ez_mysql.hpp" /* Standard C++ includes */ #include <stdlib.h> #include <string.h> #include <iostream> #include <cstdlib> /* Include directly the different headers from cppconn/ and mysql_driver.h + mysql_util.h (and mysql_connection.h). This will reduce your build time! */ /* MySQL Libraries */ #include "mysql_connection.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> EZ_MySQL::EZ_MySQL() { /* * function name: constructor * description: initializes connection to MySQL db used for application * parameters: n/a * returns: will throw exception if something goes wrong */ /* will check to see if the env var for the mysql root password exists. If it doesn't it will throw exc and exit */ if( std::getenv("ROOT_PASS") == NULL ) { throw std::string( "missing root password in env vars. expecting: ROOT_PASS" ); return; } const char *root_pass = std::getenv("ROOT_PASS"); // root password for MySQL /* attempt connection at MySQL db */ try { /* create the connection to the MySQL container */ this->driver = get_driver_instance(); this->con = (this->driver)->connect("tcp://127.0.0.1:3306", "root", root_pass); /* connect to the MySQL test database */ (this->con)->setSchema("myChat"); } catch (sql::SQLException &e) { /* print error and throw exception */ std::cout << "# ERR: SQLException in " << __FILE__; std::cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << std::endl; std::cout << "# ERR: " << e.what(); std::cout << " (MySQL error code: " << e.getErrorCode(); std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl; throw std::string("Error connecting to MySQL"); return; } } EZ_MySQL::EZ_MySQL(const char *root_pass) { /* * function name: constructor * description: initializes connection to MySQL db used for application * parameters: the root password to the MySQL db * returns: will throw exception if something goes wrong. */ try { /* create the connection to the MySQL container */ this->driver = get_driver_instance(); this->con = (this->driver)->connect("tcp://127.0.0.1:3306", "root", root_pass); /* connect to the MySQL test database */ (this->con)->setSchema("myChat"); } catch (sql::SQLException &e) { std::cout << "# ERR: SQLException in " << __FILE__; std::cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << std::endl; std::cout << "# ERR: " << e.what(); std::cout << " (MySQL error code: " << e.getErrorCode(); std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl; return; } } EZ_MySQL::~EZ_MySQL() { // delete this->driver; // delete this->con; } bool EZ_MySQL::does_user_exist(std::string username) { /* * name: does_user_exist * description: Used to check if a user exists already in the databse. * parameters: string username - the username you would like to check * return: true if the user exists, false if they does not */ std::string query = "SELECT EXISTS(SELECT * from users where username like \"%"; query += username; query += "%\");"; sql::Statement *stmt = (this->con)->createStatement(); sql::ResultSet *res = stmt->executeQuery(query); while(res->next()) { if( res->getString(1) == "1") { return true; } else { return false; } } return false; }
4869ba6144e6ab114fce52727da119f9dc328cab
e0654961ba79338e82a0ba03360e97ead4465285
/include/argot/concepts/immediate_executor.hpp
3ebda0c66237daa02d6f3cb7e669e7f6994d949e
[ "BSL-1.0" ]
permissive
blockspacer/argot
68f0e2a56fb4686989b47d0ad0f6127167ea0a9a
97349baaf27659c9dc4d67cf8963b2e871eaedae
refs/heads/master
2022-11-25T02:57:08.808025
2020-08-04T21:15:00
2020-08-04T21:15:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,543
hpp
immediate_executor.hpp
/*============================================================================== Copyright (c) 2017, 2018, 2019 Matt Calabrese Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef ARGOT_CONCEPTS_IMMEDIATE_EXECUTOR_HPP_ #define ARGOT_CONCEPTS_IMMEDIATE_EXECUTOR_HPP_ //[description /*` ImmediateExecutor is an [argot_gen_concept] for `Executor` types that complete the execution of Invocables that they are given before returning from `execute` operations. */ //] #include <argot/concepts/detail/concepts_preprocessing_helpers.hpp> #include <argot/concepts/executor.hpp> #include <argot/gen/explicit_concept.hpp> namespace argot { #define ARGOT_DETAIL_PREPROCESSED_CONCEPT_HEADER_NAME() \ s/immediate_executor.h #ifdef ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER #include ARGOT_CONCEPTS_DETAIL_PREPROCESSED_HEADER #else #include <argot/concepts/detail/preprocess_header_begin.hpp> ARGOT_CONCEPTS_DETAIL_CREATE_LINE_DIRECTIVE( __LINE__ ) // TODO(mattcalabrese) Requires the executor to return the result of the call. template< class Exec > ARGOT_EXPLICIT_CONCEPT( ImmediateExecutor ) ( Executor< Exec > ); #include <argot/concepts/detail/preprocess_header_end.hpp> #endif // ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER } // namespace argot #endif // ARGOT_CONCEPTS_IMMEDIATE_EXECUTOR_HPP_
006c16255efc4d35faf2a0a072096063655c84f7
ef66e297a49d04098d98a711ca3fda7b8a9a657c
/LeetCodeR3/54-Spiral Matrix/solution.cpp
e469db35f1c3002ef706c9cfc87ebc84b8045508
[]
no_license
breezy1812/MyCodes
34940357954dad35ddcf39aa6c9bc9e5cd1748eb
9e3d117d17025b3b587c5a80638cb8b3de754195
refs/heads/master
2020-07-19T13:36:05.270908
2018-12-15T08:54:30
2018-12-15T08:54:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,135
cpp
solution.cpp
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int m = matrix.size(); if (m == 0) { return {}; } int n = matrix[0].size(); if (n == 0) { return {}; } int l = 0, r = n - 1, t = 0, b = m - 1; vector<int> ans; while (l <= r && t <= b) { // Top for (int j = l; j <= r; j++) { ans.push_back(matrix[t][j]); } // Right if (b - t > 0) { for (int i = t + 1; i <= b; i++) { ans.push_back(matrix[i][r]); } } // Bottom if (b - t > 0 && r - l > 0) { for (int j = r - 1; j >= l; j--) { ans.push_back(matrix[b][j]); } } // Left if (b - t > 1 && r - l > 0) { for (int i = b - 1; i >= t + 1; i--) { ans.push_back(matrix[i][l]); } } l++, r--, t++, b--; } return ans; } };
2fa16ce6a9d0b2a9fe75826b6f1e5054987d238b
2de171611767f496a5a1f8d5ff24831870888c4a
/T06_01_SortAlgorithms/SortAlgorithms.cpp
541577977b51b81fb9ffb16b7998716aa492deb8
[ "Apache-2.0" ]
permissive
liubincodelife/DataStructureTasks
70151a7916e775e495a24d36763e26cd1f62e38b
c2d540e0740877a53e8676a58c9abaa2e315ece5
refs/heads/master
2020-05-05T08:23:29.068064
2019-05-14T15:40:26
2019-05-14T15:40:26
179,862,279
0
0
null
null
null
null
GB18030
C++
false
false
5,333
cpp
SortAlgorithms.cpp
#include <iostream> using namespace std; //交换函数 void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } //冒泡排序 //时间复杂度:最好:O(n) 最差:O(n^2) //空间复杂度:O(1) bool Bubble_Sort(int array[], int length) { if (length <= 1) return false; for (int i = 0; i < length; i++) { bool flag = false; for (int j = 0; j < length - i - 1; j++) { if (array[j] > array[j + 1]) { int tmp = array[j]; array[j] = array[j + 1]; array[j + 1] = tmp; flag = true; } } if (!flag) { break; } } return true; } //插入排序 //时间复杂度:O(n^2) //空间复杂度:O(1) bool Insertion_Sort(int array[], int length) { if (length <= 1) return false; for (int i = 1; i < length; i++) { int value = array[i]; //保存需要插入的数字 int j = i - 1; for (; j >=0; j--) { if (array[j] > value) { array[j + 1] = array[j]; //进行数据搬移,直到找到数字插入的位置 } else { break; } } array[j + 1] = value; } return true; } //选择排序 //时间复杂度:O(n^2) //空间复杂度:O(1) bool Selection_Sort(int array[], int length) { if (length <= 1) return false; for (int i = 0; i < length; i++) { //先找到未排序区间的最小值索引 int min = i; for (int j = i + 1; j < length; j++) { if (array[j] < array[min]) { min = j; } } int temp = array[i]; array[i] = array[min]; array[min] = temp; } return true; } //归并排序 //时间复杂度:O(nlogn) //空间复杂度:O(n) void Merge(int a[], int left, int mid, int right) { //两段区间的长度 int length1 = mid - left + 1; int length2 = right - mid; //分配两段新的内存空间存储原内容 int *l1 = new int[length1]; int *l2 = new int[length2]; for (int i = 0; i < length1; ++i) { l1[i] = a[left + i]; } for (int j = 0; j < length2; ++j) { l2[j] = a[j + mid + 1]; } //存入原内容之后,比较两个序列 int i = 0, j = 0; int k = length1; //比较两个序列的重合部分,进行排序 while (i < length1 && j < length2) { if (l1[i] < l2[j]) { a[left++] = l1[i++]; } else { a[left++] = l2[j++]; } } //两序列的剩余部分分别放于结尾 while (i < length1) { a[left++] = l1[i++]; } while (j < length2) { a[left++] = l2[j++]; } //分配的内存需要释放掉 delete[]l1; delete[]l2; } bool Merge_Sort(int array[], int low, int high) { if (low < high) { int mid = (low + high) / 2; //首先进行分区,然后递归操作 Merge_Sort(array, low, mid); Merge_Sort(array, mid + 1, high);//第一次将其分为两个区间,进行合并操作 Merge(array, low, mid, high); } return true; } //快速排序 //时间复杂度:最好:O(nlogn) 最差:O(n^2) //空间复杂度:O(1) int partition(int array[], int low, int high) { int pivot = array[high]; int i = low; for (int j = low; j < high; j++) { if (array[j] < pivot) { swap(array + i, array + j); i++; } } swap(array + i, array + high); return i; } void Quick_Sort(int array[], int low, int high) { if (low >= high) return; int mid = partition(array, low, high); Quick_Sort(array, low, mid - 1); Quick_Sort(array, mid + 1, high); } void Quick_Sort(int array[], int length) { Quick_Sort(array, 0, length - 1); } void print(int array[], int length) { cout << "the array after sorted is: " <<endl; for (int i = 0; i < length; i++) { cout << array[i] << " "; } cout << endl; } void test1() { cout << "test1 Bubble sorted running......" << endl; int array[10] = { 1, 3, 6, 2, 4, 9, 5, 8, 7, 0 }; int length = sizeof(array) / sizeof(int); Bubble_Sort(array, length); print(array, length); } void test2() { cout << "test2 Insertion sorted running......" << endl; int array[10] = { 1, 3, 6, 2, 4, 9, 5, 8, 7, 0 }; int length = sizeof(array) / sizeof(int); Insertion_Sort(array, length); print(array, length); } void test3() { cout << "test3 Selection sorted running......" << endl; int array[10] = { 1, 3, 6, 2, 4, 9, 5, 8, 7, 0 }; int length = sizeof(array) / sizeof(int); Selection_Sort(array, length); print(array, length); } void test4() { cout << "test4 Quick sorted running......" << endl; int array[10] = { 1, 3, 6, 2, 4, 9, 5, 8, 7, 0 }; //int array[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; int length = sizeof(array) / sizeof(int); Quick_Sort(array, length); print(array, length); } int main(int argc, char** argv) { test3(); test4(); getchar(); return 0; }
ed21ff9e10478f8a980cf0150d2103fddba528ac
75106c3a7a7d16f643e6ebe54fcbfe636b2da174
/BitManipulation/25_checkMultipleBy9.cpp
bded6f9547ba6d029902acd828d5d6acb00c9860
[]
no_license
i7sharath/geeks4geeks
b7f604189111c6ba45008d6d5ac5491533a7576e
9c02e45dc2b73a007db2c2bba96a9491538818c7
refs/heads/master
2021-05-01T17:00:36.132885
2016-09-17T17:44:08
2016-09-17T17:44:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
378
cpp
25_checkMultipleBy9.cpp
#include <iostream> #include <cmath> #include <cstdio> #include <string> using namespace std; bool checkMultipleOf9(int n) { if(n==0 || n==9) return true; if(n<9) return false; // If n is greater than 9, then recur for [floor(n/9) - n%8] return checkMultipleOf9((int)(n>>3) - (int)(n&7)); } int main() { int n; cin>>n; cout<<checkMultipleOf9(n)<<endl; return 0; }
ac448b7c6c1b1e100a0a0ba3c8a21123cff5ddfa
a6590941fea4880593d5b1cd23eedfe696f4e446
/Other/mitsuiBank2020/f.cpp
fb57c6524d1b780a35f2bc036f9c9d0a8a25c982
[]
no_license
cod4i3/MyAtcoder
9fb92f2dd06c5b6217e925a82d8db4f91355a70f
53bdac3fa7eb4ac48ca6d5c70461639beb6aa81d
refs/heads/master
2023-02-17T09:15:16.282873
2021-01-15T13:34:03
2021-01-15T13:34:03
232,006,424
0
0
null
null
null
null
UTF-8
C++
false
false
798
cpp
f.cpp
#include <iostream> using namespace std; typedef long long ll; int main() { ll T1, T2, A1, A2, B1, B2; cin >> T1 >> T2 >> A1 >> A2 >> B1 >> B2; if (T1 * A1 + T2 * A2 == T1 * B1 + T2 * B2) { cout << "infinity" << endl; return 0; } ll D1 = 0, D2 = 0; ll ans = 1; for (ll i = T1; i == 0; i--) { if (D1 < D2 && D1 + A1 * T1 >= D2 + B1 * T1) ans++; else if (D1 > D2 && D1 + A1 * T1 <= D2 + B1 * T1) ans++; else break; D1 += A1 * T1; D2 += B1 * T1; for (ll j = T2; j == 0; j--) { if (D1 < D2 && D1 + A2 * T2 >= D2 + B2 * D2) ans++; else if (D1 > D2 && D1 + A2 * T2 <= D2 + B2 * D2) ans++; else break; D1 += A2 * T2; D2 += B2 * T2; } } cout << ans << endl; return 0; }
07d42e070e410f59912f85adc935a3d9a456000e
d053e0e8687f122d120bcd0fa1f9076deb35afa5
/Olymp/CF/294/D.cpp
ae53b88e9ae7229c9aa2a6ded7608624d21dc9ed
[]
no_license
shaihitdin/CP
e8911bc543932866d6fc83eb1d48d9cf79918c61
dc90082f3ebedaccbfb0818cc68539c887f86553
refs/heads/master
2021-01-11T17:10:20.356635
2017-10-05T08:53:56
2017-10-05T08:53:56
79,729,913
1
0
null
null
null
null
UTF-8
C++
false
false
2,490
cpp
D.cpp
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 3; typedef long long ll; struct node { ll x, add; int cnt; unsigned short y; node *l, *r; node () { x = y = 0; add = 0; l = r = 0; cnt = 1; } node (const ll &element) { x = element; y = rand(); l = r = 0; add = 0; cnt = 1; } }; inline void push (node *t) { if (t && t -> add) { t -> x += t -> add; if (t -> l) t -> l -> add += t -> add; if (t -> r) t -> r -> add += t -> add; t -> add = 0; } } inline int cnt (node *t) { return t ? t -> cnt : 0; } inline void upd (node *t) { if (t) t -> cnt = 1 + cnt (t -> l) + cnt (t -> r); } inline void Split (node *t, node *&l, node *&r, const int &x) { push (t); if (!t) l = r = 0; else if (t -> x <= x) Split (t -> r, t -> r, r, x), l = t; else Split (t -> l, l, t -> l, x), r = t; upd (l); upd (r); upd (t); } inline void Merge (node *&t, node *l, node *r) { push (l); push (r); if (!l || !r) t = l ? l : r; else if (l -> y > r -> y) Merge (l -> r, l -> r, r), t = l; else Merge (r -> l, l, r -> l), t = r; upd (l); upd (r); upd (t); } inline void adding (node *t, const ll &to_add) { if (t) t -> add += to_add; } int sz; int a[256]; string s; vector <int> v[30]; node elements[N * 3]; node *root, *zero_el, *L, *R, *mid, *R1, *temp; ll ans; ll sum[N]; inline void out (node *t) { push (t); if (!t) return; out (t -> l); fprintf (stderr, "%d ", t -> x); out (t -> r); } int main () { #ifndef ONLINE_JUDGE freopen ("in", "r", stdin); freopen ("out", "w", stdout); #endif srand (53489340); ios_base :: sync_with_stdio (0); for (int i = 'a'; i <= 'z'; ++i) cin >> a[i]; cin >> s; int n = s.size(); s = '#' + s; for (int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + a[s[i]]; for (int i = n; i; --i) v[s[i] - 'a'].push_back (i); for (int i = 0; i < 26; ++i) { root = zero_el = 0; for (int j = 0; j < v[i].size(); ++j) { Split (root, L, R, -1); Split (R, mid, R1, 0); ans += cnt (mid); Merge (R, mid, R1); Merge (root, L, R); if (j + 1 == v[i].size()) break; adding (root, a[i + 'a']); Split (root, L, R, -1); temp = &elements[sz++]; *temp = node (0); Merge (R, temp, R); Merge (root, L, R); adding (root, sum[v[i][j] - 1] - sum[v[i][j + 1]]); /* cerr << "add here " << a[i + 'a'] << " " << sum[v[i][j] - 1] - sum[v[i][j + 1]] << "\n"; out (root); fprintf (stderr, "\n"); */ } } cout << ans; return 0; }