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
782e35e477ca07fda8cbac7b61b2b4cf845f2dd3
367e8612cb116ac46d08856127a05d78d1fc03f1
/Engine/OGF-Core/Core/Core.h
d585025851d2cd2d83eca77cb4f2f3b1456b5e34
[ "MIT" ]
permissive
simon-bourque/OpenGameFramework
a1c848ec9b203d23831a07dbca978b93495fb41d
e0fed3895000a5ae244fc1ef696f4256af29865b
refs/heads/master
2023-02-08T17:44:21.387079
2020-12-22T20:52:48
2020-12-22T20:52:48
83,928,624
5
0
MIT
2020-12-22T20:52:50
2017-03-04T22:24:01
C++
UTF-8
C++
false
false
212
h
Core.h
#pragma once #include "Core/Types.h" #include "Core/Logging.h" #include <string> using std::string; #ifdef DEBUG_BUILD #define DEBUG_LOG(msg) printToConsole(msg) #else #define DEBUG_LOG(msg) ((void)0) #endif
26018c963253be28e08dc5e50b2c41d18c76230d
79db16655c9bca2921ddda74797f5cbf16c30051
/1 convolution/main.cpp
3b982ec0151d96a5f8ad71ab7b698205b671e31c
[]
no_license
mchernigovskaya/opencl
ca249b1f6ace04243c994fb433ace08e7243d0d4
fa59ce5859399d5c710f06e4b96a85c9245804bc
refs/heads/master
2021-09-06T04:52:37.169393
2018-02-02T13:41:04
2018-02-02T13:41:04
119,895,401
0
0
null
null
null
null
UTF-8
C++
false
false
3,857
cpp
main.cpp
#define __CL_ENABLE_EXCEPTIONS #define CL_USE_DEPRECATED_OPENCL_1_1_APIS #include <CL/cl.h> #include "cl.hpp" #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <iterator> #include <math.h> typedef double elem_type; void generate_input(size_t n, size_t m){ std::ofstream out("input.txt"); out << n << ' ' << m << "\n"; for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ out << "1 "; } out << "\n"; } for (int i = 0; i < m; ++i){ for (int j = 0; j < m; ++j){ out << "1 "; } out << "\n"; } } void read_one_matrix(std::ifstream &in, std::vector<elem_type> &M, size_t size) { for (size_t i = 0; i < size; ++i) { for (size_t j = 0; j < size; ++j) { in >> M[i * size + j]; } } } void write_output(std::vector<elem_type> &C, size_t size) { FILE *out = fopen("output.txt", "w"); for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { fprintf(out, "%0.3f ", C[i * size + j]); } fprintf(out, "\n"); } fclose(out); // for (int i = 0; i < size; ++i) { // for (int j = 0; j < size; ++j) { // std::cout << C[i * size + j] << " "; // } // std::cout << "\n"; // } } int main() { std::vector<cl::Platform> platforms; std::vector<cl::Device> devices; std::vector<cl::Kernel> kernels; try { //generate_input(1024, 9); // create platform cl::Platform::get(&platforms); platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices); // create context cl::Context context(devices); // create command queue cl::CommandQueue queue(context, devices[0]); // load opencl source std::ifstream cl_file("matrix_conv.cl"); std::string cl_string(std::istreambuf_iterator<char>(cl_file), (std::istreambuf_iterator<char>())); cl::Program::Sources source(1, std::make_pair(cl_string.c_str(), cl_string.length() + 1)); // create program cl::Program program(context, source); // compile opencl source program.build(devices); // create a message to send to kernel std::ifstream in("input.txt"); size_t n, m; in >> n >> m; size_t matrix_size = n * n; std::vector<elem_type> A(matrix_size, 0), B(m * m, 0), C(matrix_size, 0); read_one_matrix(in, A, n); read_one_matrix(in, B, m); // allocate device buffer to hold message cl::Buffer dev_a(context, CL_MEM_READ_ONLY, sizeof(elem_type) * matrix_size); cl::Buffer dev_b(context, CL_MEM_READ_ONLY, sizeof(elem_type) * matrix_size); cl::Buffer dev_c(context, CL_MEM_WRITE_ONLY, sizeof(elem_type) * matrix_size); // copy from cpu to gpu queue.enqueueWriteBuffer(dev_a, CL_TRUE, 0, sizeof(elem_type) * matrix_size, A.data()); queue.enqueueWriteBuffer(dev_b, CL_TRUE, 0, sizeof(elem_type) * matrix_size, B.data()); // load named kernel from opencl source cl::Kernel kernel(program, "convolution"); size_t const block_size = 16; size_t const global_size = ((matrix_size + block_size - 1) / block_size) * block_size; cl::KernelFunctor convolution(kernel, queue, cl::NullRange, cl::NDRange(global_size, global_size), cl::NDRange(block_size, block_size)); convolution(dev_a, dev_b, dev_c, (int) n, (int) m); queue.enqueueReadBuffer(dev_c, CL_TRUE, 0, sizeof(elem_type) * matrix_size, C.data()); write_output(C, n); } catch (cl::Error e) { std::cout << std::endl << e.what() << " : " << e.err() << std::endl; } return 0; }
ab5cd097c55e47f627b32eca00aa9de6dbef128c
05987d0c8946838ba05eb84d5e7973ecf712ff02
/AbdulBari_ReversingAString/main.cpp
95db2eba7fb1aec84e47b70922a2a2e942851eb8
[ "Apache-2.0" ]
permissive
ATomar2150/DataStructuresAndAlgorithm
d3c455bc57492138c98ca3a8522be7f289e1c02b
b1cbea4ea4b27e396ebbada464417818d2862283
refs/heads/main
2023-01-27T20:00:23.956688
2020-12-06T02:43:22
2020-12-06T02:43:22
300,453,572
0
0
null
null
null
null
UTF-8
C++
false
false
833
cpp
main.cpp
#include <iostream> using namespace std; //METHOD 1 // int main() // { // char A[] = "Python"; // int len = 0; // for(int i = 0; A[i] != '\0'; i++) // { // len++; // } // cout <<"Length of the string is: "<< len <<endl; // char B[len+1]; // int i, j; // for(i = 0; A[i] != '\0'; i++) // { // } // i = i - 1; // for(j = 0; i >= 0 ; i--, j++) // { // B[j] = A[i]; // } // B[j] = '\0'; // cout << B; // return 0; // } //METHOD 2 (Reversing within the same array) int main() { char A[] = "Python"; int i,j, temp; for(j = 0; A[j] != '\0'; j++) { } j = j - 1; for(i = 0; i < j; i++, j--) { temp = A[i]; A[i] = A[j]; A[j] = temp; } cout << A; return 0; }
c2ed5850bdb87e26365057f5553843af8903b4f8
53733f73b922407a958bebde5e674ec7f045d1ba
/ABC/ABC191/D/main2.cpp
9c4b25f8e182bd939e2a50b2e620ca14cdc68280
[]
no_license
makio93/atcoder
040c3982e5e867b00a0d0c34b2a918dd15e95796
694a3fd87b065049f01f7a3beb856f8260645d94
refs/heads/master
2021-07-23T06:22:59.674242
2021-03-31T02:25:55
2021-03-31T02:25:55
245,409,583
0
0
null
null
null
null
UTF-8
C++
false
false
2,106
cpp
main2.cpp
#include <bits/stdc++.h> #include <atcoder/all> using namespace std; using namespace atcoder; using ll = long long; using ull = unsigned long long; #define v(t) vector<t> #define p(t) pair<t, t> #define p2(t, s) pair<t, s> #define vp(t) v(p(t)) #define rep(i, n) for (int i=0,i##_len=((int)(n)); i<i##_len; ++i) #define rep2(i, a, n) for (int i=((int)(a)),i##_len=((int)(n)); i<=i##_len; ++i) #define repr(i, n) for (int i=((int)(n)-1); i>=0; --i) #define rep2r(i, a, n) for (int i=((int)(n)),i##_len=((int)(a)); i>=i##_len; --i) #define repi(itr, c) for (__typeof((c).begin()) itr=(c).begin(); itr!=(c).end(); ++itr) #define repir(itr, c) for (__typeof((c).rbegin()) itr=(c).rbegin(); itr!=(c).rend(); ++itr) #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define SORT(v, n) sort(v, v+n); #define VSORT(v) sort(v.begin(), v.end()); #define RSORT(x) sort(rall(x)); #define pb push_back #define eb emplace_back #define INF (1e9) #define LINF (1e18) #define PI (acos(-1)) #define EPS (1e-7) #define DEPS (1e-10) // 動画解説を見た後で実装 ll in() { double x; cin >> x; return (ll)(round(x*(1e4))); } bool ok(ll x, ll x2, ll y, ll y2, ll r) { return ((y2-y)*(y2-y) + (x2-x)*(x2-x) <= r*r); } ll cnt(ll x, ll y, ll r, ll lx=0, ll ly=0) { ll llim = x + lx * 10000LL; if (llim%10000LL != 0) { if (llim >= 0) llim = (llim + 9999LL) / 10000LL * 10000LL; else llim = llim / 10000LL * 10000LL; } ll res = 0, rlim = llim; for (ll i=(ll)(1e9)+50000LL; i>=y+ly*10000LL; i-=10000LL) { while (ok(x,rlim,y,i,r)) rlim += 10000LL; res += max(0LL, rlim-llim) / 10000LL; } return res; } int main(){ ll x, y, r; x = in(); y = in(); r = in(); x %= 10000; y %= 10000; ll lx = (x==0?1:0), ly = (y==0?1:0); ll ans = cnt(x, y, r); ans += cnt(-x, y, r, lx, 0LL); ans += cnt(x, -y, r, 0LL, ly); ans += cnt(-x, -y, r, lx, ly); cout << ans << endl; return 0; }
e4edfe848032a76db9d8535ced10e78a2edfa9d7
18f66cb9a08030afab48494b96536e6a80277435
/acm.timus.ru_33735/1023.cpp
901f8c43c40f848f807647c012ede2b4be9f8c16
[]
no_license
Rassska/acm
aa741075a825080637bebab128d763b64c7f73ae
18aaa37e96b6676334c24476e47cd17d22ca9541
refs/heads/master
2023-03-15T16:57:59.274305
2015-02-24T21:36:34
2015-02-24T21:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
482
cpp
1023.cpp
#include "stdafx.h" #include <iostream> #include <cmath> using namespace std; bool isprime(int x) { int b = sqrt((double)x); for(int i=2; i <= b;i++) if( x % i == 0) return false; return true; } void main() { int k,s,min = 0; bool f = false; cin>>k; if(k==4 || k == 100000000) min = 3; else if(isprime(k)) min = k-1; else { s=sqrt((double)k); for(int i = 3; i<=k;i++) if(k%i == 0) { if(min>i-1 || min == 0) min = i-1; } } cout<<min; }
be66015c2dd8d0fa2ff423c3734d811ca2ecc9a7
91a3c034dae129eb16e0d21dc96816e67155f42c
/Image Process/03_image_process_itk.cxx
36754a735350b1b07af42417c50394df1a0859a8
[ "MIT" ]
permissive
mateoflorido/CVAlgorithms
86ef4934c7fb27f61b1fc833f5df779a6e89d5f9
da8472d44dab68fb7f6c8075123d2d11d96c5120
refs/heads/master
2022-11-23T00:12:27.935863
2020-07-20T17:51:12
2020-07-20T17:51:12
239,562,241
0
0
null
null
null
null
UTF-8
C++
false
false
14,142
cxx
03_image_process_itk.cxx
#include <cmath> #include <cstdlib> #include <limits> #include <iostream> #include <string> #include <sstream> #include <itkImage.h> #include <itkRGBPixel.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkImageRegionConstIteratorWithIndex.h> #include <itkImageRegionIteratorWithIndex.h> #include <itkIdentityTransform.h> #include <itkResampleImageFilter.h> // Image type: 2-dimensional 1-byte rgb const unsigned int Dim = 2; typedef unsigned char TRGBResolution; typedef itk::RGBPixel< TRGBResolution > TRGBPixel; typedef itk::Image< TRGBPixel, Dim > TColorImage; // Types definition typedef itk::ImageFileReader< TColorImage > TReader; typedef itk::ImageRegionConstIteratorWithIndex< TColorImage > TIterator; typedef itk::ImageRegionIteratorWithIndex< TColorImage > TColorIterator; typedef itk::ImageFileWriter< TColorImage > TWriter; typedef itk::IdentityTransform<double, 2> TransformType; typedef itk::ResampleImageFilter< TColorImage, TColorImage > ResampleImageFilterType; // ------------------------------------------------------------------------- int main( int argc, char* argv[] ) { // Get command line arguments if( argc < 2 ) { std::cerr << "Usage: " << argv[ 0 ] << " image_file" << std::endl; return( -1 ); } // fi // Review given command line arguments std::cout << "-------------------------" << std::endl; for( int a = 0; a < argc; a++ ) std::cout << argv[ a ] << std::endl; std::cout << "-------------------------" << std::endl; // Read an image TReader::Pointer reader = TReader::New( ); reader->SetFileName( argv[ 1 ] ); try { reader->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt TColorImage* img = reader->GetOutput( ); // Create color channel images // red channel TColorImage::Pointer rImg = TColorImage::New( ); rImg->SetSpacing( img->GetSpacing( ) ); rImg->SetOrigin( img->GetOrigin( ) ); rImg->SetLargestPossibleRegion( img->GetLargestPossibleRegion( ) ); rImg->SetRequestedRegion( img->GetRequestedRegion( ) ); rImg->SetBufferedRegion( img->GetBufferedRegion( ) ); rImg->Allocate( ); // green channel TColorImage::Pointer gImg = TColorImage::New( ); gImg->SetSpacing( img->GetSpacing( ) ); gImg->SetOrigin( img->GetOrigin( ) ); gImg->SetLargestPossibleRegion( img->GetLargestPossibleRegion( ) ); gImg->SetRequestedRegion( img->GetRequestedRegion( ) ); gImg->SetBufferedRegion( img->GetBufferedRegion( ) ); gImg->Allocate( ); // blue channel TColorImage::Pointer bImg = TColorImage::New( ); bImg->SetSpacing( img->GetSpacing( ) ); bImg->SetOrigin( img->GetOrigin( ) ); bImg->SetLargestPossibleRegion( img->GetLargestPossibleRegion( ) ); bImg->SetRequestedRegion( img->GetRequestedRegion( ) ); bImg->SetBufferedRegion( img->GetBufferedRegion( ) ); bImg->Allocate( ); // composite image (RGB) TColorImage::Pointer rgbImg = TColorImage::New( ); rgbImg->SetSpacing( img->GetSpacing( ) ); rgbImg->SetOrigin( img->GetOrigin( ) ); rgbImg->SetLargestPossibleRegion( img->GetLargestPossibleRegion( ) ); rgbImg->SetRequestedRegion( img->GetRequestedRegion( ) ); rgbImg->SetBufferedRegion( img->GetBufferedRegion( ) ); rgbImg->Allocate( ); // Initialize created images in black TRGBPixel black; black.SetRed( 0 ); black.SetGreen( 0 ); black.SetBlue( 0 ); rImg->FillBuffer( black ); gImg->FillBuffer( black ); bImg->FillBuffer( black ); rgbImg->FillBuffer( black ); // Fill color channel images TIterator it( img, img->GetLargestPossibleRegion( ) ); TColorIterator crIt( rImg, rImg->GetLargestPossibleRegion( ) ); TColorIterator cgIt( gImg, gImg->GetLargestPossibleRegion( ) ); TColorIterator cbIt( bImg, bImg->GetLargestPossibleRegion( ) ); it.GoToBegin( ); crIt.GoToBegin( ); cgIt.GoToBegin( ); cbIt.GoToBegin( ); for( ; !it.IsAtEnd( ) && !crIt.IsAtEnd( ) && !cgIt.IsAtEnd( ) && !cbIt.IsAtEnd( ); ++it, ++crIt, ++cgIt, ++cbIt ) { TRGBPixel value, pixel; pixel = it.Get( ); value.SetRed( pixel.GetRed( ) ); value.SetGreen( 0 ); value.SetBlue( 0 ); crIt.Set( value ); value.SetRed( 0 ); value.SetGreen( pixel.GetGreen( ) ); value.SetBlue( 0 ); cgIt.Set( value ); value.SetRed( 0 ); value.SetGreen( 0 ); value.SetBlue( pixel.GetBlue( ) ); cbIt.Set( value ); } // rof // Write channels std::stringstream ss( argv[ 1 ] ); std::string basename; getline( ss, basename, '.' ); TWriter::Pointer writer = TWriter::New( ); writer->SetInput( rImg ); writer->SetFileName( basename + "_R.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt writer->SetInput( gImg ); writer->SetFileName( basename + "_G.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt writer->SetInput( bImg ); writer->SetFileName( basename + "_B.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt //Output Sizes for each color TColorImage::SizeType inputSize = img->GetLargestPossibleRegion( ).GetSize( ); std::cout << "Image input size: " << inputSize << std::endl; TColorImage::SizeType outputSizeR; TColorImage::SizeType outputSizeG; TColorImage::SizeType outputSizeB; outputSizeR[ 0 ] = inputSize[ 0 ] * 0.75 ; outputSizeR[ 1 ] = inputSize[ 1 ] * 0.75 ; outputSizeG[ 0 ] = inputSize[ 0 ] * 0.5 ; outputSizeG[ 1 ] = inputSize[ 1 ] * 0.5 ; outputSizeB[ 0 ] = inputSize[ 0 ] * 0.25 ; outputSizeB[ 1 ] = inputSize[ 1 ] * 0.25 ; //Output Spacing for each color //Red outputSpacing TColorImage::SpacingType outputSpacingR; outputSpacingR[ 0 ] = img->GetSpacing( )[ 0 ] * ( static_cast< double >( inputSize[ 0 ] ) / static_cast< double >( outputSizeR[ 0 ] ) ); outputSpacingR[ 1 ] = img->GetSpacing( )[ 1 ] * ( static_cast< double >( inputSize[ 1 ] ) / static_cast< double >( outputSizeR[ 1 ] ) ); //Green outputSpacing TColorImage::SpacingType outputSpacingG; outputSpacingG[ 0 ] = img->GetSpacing( )[ 0 ] * ( static_cast< double >( inputSize[ 0 ] ) / static_cast< double >( outputSizeG[ 0 ] ) ); outputSpacingG[ 1 ] = img->GetSpacing( )[ 1 ] * ( static_cast< double >( inputSize[ 1 ] ) / static_cast< double >( outputSizeG[ 1 ] ) ); //Blue outputSpacing TColorImage::SpacingType outputSpacingB; outputSpacingB[ 0 ] = img->GetSpacing( )[ 0 ] * ( static_cast< double >( inputSize[ 0 ] ) / static_cast< double >( outputSizeB[ 0 ] ) ); outputSpacingB[ 1 ] = img->GetSpacing( )[ 1 ] * ( static_cast< double >( inputSize[ 1 ] ) / static_cast< double >( outputSizeB[ 1 ] ) ); // Rescale rImg ResampleImageFilterType::Pointer resampleFilterR = ResampleImageFilterType::New( ); resampleFilterR->SetTransform( TransformType::New( ) ); resampleFilterR->SetInput( rImg ); resampleFilterR->SetSize( outputSizeR ); resampleFilterR->SetOutputSpacing( outputSpacingR ); resampleFilterR->UpdateLargestPossibleRegion( ); // Rescale gImg ResampleImageFilterType::Pointer resampleFilterG = ResampleImageFilterType::New( ); resampleFilterG->SetTransform( TransformType::New( ) ); resampleFilterG->SetInput( gImg ); resampleFilterG->SetSize( outputSizeG ); resampleFilterG->SetOutputSpacing( outputSpacingG ); resampleFilterG->UpdateLargestPossibleRegion( ); // Rescale bImg ResampleImageFilterType::Pointer resampleFilterB = ResampleImageFilterType::New( ); resampleFilterB->SetTransform( TransformType::New( ) ); resampleFilterB->SetInput( bImg ); resampleFilterB->SetSize( outputSizeB ); resampleFilterB->SetOutputSpacing( outputSpacingB ); resampleFilterB->UpdateLargestPossibleRegion( ); // Write channels rescaled writer = TWriter::New( ); writer->SetInput( resampleFilterR->GetOutput() ); writer->SetFileName( basename + "_sR.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt writer->SetInput( resampleFilterG->GetOutput() ); writer->SetFileName( basename + "_sG.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt writer->SetInput( resampleFilterB->GetOutput() ); writer->SetFileName( basename + "_sB.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt //Output Sizes for each color to expand TColorImage::SizeType outputSizeREx; TColorImage::SizeType outputSizeGEx; TColorImage::SizeType outputSizeBEx; outputSizeREx[ 0 ] = outputSizeR[ 0 ] * 1.333333333333333333333333333333 ; outputSizeREx[ 1 ] = outputSizeR[ 1 ] * 1.333333333333333333333333333333 ; outputSizeGEx[ 0 ] = outputSizeG[ 0 ] * 2 ; outputSizeGEx[ 1 ] = outputSizeG[ 1 ] * 2 ; outputSizeBEx[ 0 ] = outputSizeB[ 0 ] * (4) ; outputSizeBEx[ 1 ] = outputSizeB[ 1 ] * (4) ; //Output Spacing for each color to expand //Red outputSpacing outputSpacingR[ 0 ] = outputSpacingR[ 0 ]/1.333333333333333333333333333333; outputSpacingR[ 1 ] = outputSpacingR[ 1 ]/1.333333333333333333333333333333; //Green outputSpacing outputSpacingG[ 0 ] = outputSpacingG[ 0 ]/(2); outputSpacingG[ 1 ] = outputSpacingG[ 1 ]/(2); //Blue outputSpacing outputSpacingB[ 0 ] = outputSpacingB[ 0 ]/(4); outputSpacingB[ 1 ] = outputSpacingB[ 1 ]/(4); // Rescale rImg ResampleImageFilterType::Pointer resampleFilterREx = ResampleImageFilterType::New( ); resampleFilterREx->SetTransform( TransformType::New( ) ); resampleFilterREx->SetInput( resampleFilterR->GetOutput() ); resampleFilterREx->SetSize( outputSizeREx ); resampleFilterREx->SetOutputSpacing( outputSpacingR ); resampleFilterREx->UpdateLargestPossibleRegion( ); // Rescale gImg ResampleImageFilterType::Pointer resampleFilterGEx = ResampleImageFilterType::New( ); resampleFilterGEx->SetTransform( TransformType::New( ) ); resampleFilterGEx->SetInput( resampleFilterG->GetOutput() ); resampleFilterGEx->SetSize( outputSizeGEx ); resampleFilterGEx->SetOutputSpacing( outputSpacingG ); resampleFilterGEx->UpdateLargestPossibleRegion( ); // Rescale bImg ResampleImageFilterType::Pointer resampleFilterBEx = ResampleImageFilterType::New( ); resampleFilterBEx->SetTransform( TransformType::New( ) ); resampleFilterBEx->SetInput( resampleFilterB->GetOutput() ); resampleFilterBEx->SetSize( outputSizeBEx ); resampleFilterBEx->SetOutputSpacing( outputSpacingB ); resampleFilterBEx->UpdateLargestPossibleRegion( ); writer->SetInput( resampleFilterREx->GetOutput() ); writer->SetFileName( basename + "_ssR.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt writer->SetInput( resampleFilterGEx->GetOutput() ); writer->SetFileName( basename + "_ssG.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt writer->SetInput( resampleFilterBEx->GetOutput() ); writer->SetFileName( basename + "_ssB.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt // From color channel expanded images, reconstruct the original color image TColorIterator rgbIt( img, img->GetLargestPossibleRegion() ); TColorIterator cRIt( resampleFilterREx->GetOutput(), resampleFilterREx->GetOutput()->GetLargestPossibleRegion() ); TColorIterator cGIt( resampleFilterGEx->GetOutput(), resampleFilterGEx->GetOutput()->GetLargestPossibleRegion() ); TColorIterator cBIt( resampleFilterBEx->GetOutput(), resampleFilterBEx->GetOutput()->GetLargestPossibleRegion() ); rgbIt.GoToBegin( ); cRIt.GoToBegin( ); cGIt.GoToBegin( ); cBIt.GoToBegin( ); for( ; !rgbIt.IsAtEnd( ) && !cRIt.IsAtEnd( ) && !cGIt.IsAtEnd( ) && !cBIt.IsAtEnd( ); ++rgbIt, ++cRIt, ++cGIt, ++cBIt ) { TRGBPixel value, pixel; value = cRIt.Get( ); pixel.SetRed( value.GetRed( ) ); value = cGIt.Get( ); pixel.SetGreen( value.GetGreen( ) ); value = cBIt.Get( ); pixel.SetBlue( value.GetBlue( ) ); rgbIt.Set( pixel ); } // rof //Write de rescaled RGB Image writer->SetInput( img ); writer->SetFileName( basename + "_rRGB.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt //Find diferences TColorImage* diferences = reader->GetOutput( ); //Compare Original and Rescaled Images TColorIterator difIt( diferences, diferences->GetLargestPossibleRegion( ) ); difIt.GoToBegin( ); crIt.GoToBegin( ); cgIt.GoToBegin( ); cbIt.GoToBegin( ); cRIt.GoToBegin( ); cGIt.GoToBegin( ); cBIt.GoToBegin( ); for( ; !cbIt.IsAtEnd( ) && !cgIt.IsAtEnd( ) && !crIt.IsAtEnd( ) && !cBIt.IsAtEnd( ) && !cGIt.IsAtEnd( ) && !cRIt.IsAtEnd( ) && !difIt.IsAtEnd(); ++cbIt, ++cgIt, ++crIt, ++cBIt, ++cGIt, ++cRIt, ++difIt) { TRGBPixel value, pixel; value = crIt.Get()-cRIt.Get(); pixel.SetRed(value.GetRed()); value = cgIt.Get()-cGIt.Get(); pixel.SetGreen(value.GetGreen()); value = cbIt.Get()-cBIt.Get(); pixel.SetBlue(value.GetBlue()); difIt.Set(pixel); } // rof //Write diferences writer->SetInput( diferences ); writer->SetFileName( basename + "_diff.png" ); try { writer->Update( ); } catch( itk::ExceptionObject& err ) { std::cerr << "Error: " << err << std::endl; return( 1 ); } // yrt return( 0 ); } // eof - 03_image_process_itk.cxx
586d2588096815f39e5cffe9e2ca9bea0349d1ce
b8cb96a844b8a13d9dbdee473955abc0e50dd421
/排序算法/Sorting Algorithm/Project1/main.cpp
1c237d0ed022bc63615adfb147bc0845697140bf
[]
no_license
ljw-wakeup/algorithem-project-sets
fdc6693a6f9832e0a4735da09ec1e4b182324a63
17b419d0adba8f1c391b8c5b4c1e30d04f585d48
refs/heads/master
2020-05-26T14:02:50.949450
2019-06-01T07:35:04
2019-06-01T07:35:04
188,255,796
0
0
null
null
null
null
UTF-8
C++
false
false
2,669
cpp
main.cpp
#include<iostream> #include "HeapSort.h" #include "QuickSort.h" #include "MergeSort.h" #include "InsertSort.h" #include "Windows.h" #include "time.h" #define TEST #define WINDOWS_IMPL long randomList[1000000] = { 0 }; long randomList1[1000000] = { 0 }; long numlist[7] = { 1000, 10000, 50000, 100000, 200000, 500000, 1000000 }; using namespace std; void renew() { for (long i = 0; i < 1000000; i++) { randomList1[i] = randomList[i]; } } int main(void) { long* consequence = NULL; long i; int k; #ifdef TEST long testlist[7] = { 4, 12, 8, 6, 11, 5, 9 }; HeapSort heapSortTest(testlist, 7); consequence = heapSortTest.SortConsequence(); for (i = 0; i < 7; i++) { cout << consequence[i] << '\t'; } cout << endl; #endif #ifdef NOTEST for (k = 0; k < 10; k++){ cout << "experiment:" << k + 1 << endl; srand((unsigned)time(NULL)); for (i = 0; i < 1000000; i++) { randomList[i] = rand() % 100000; //cout << randomList[i] << '\t'; } //cout << endl; for (i = 6; i <= 6; i++) { cout << "scale is" << numlist[i] << endl; DWORD start_time1 = GetTickCount64(); QuickSort quickSort(randomList1, numlist[i]); renew(); DWORD end_time1 = GetTickCount64(); cout << "Time of quick_sort is" << end_time1 - start_time1 << "ms." << endl; cout << "scale is" << numlist[i] << endl; DWORD start_time = GetTickCount64(); InsertSort insertSort(randomList1, numlist[i]); renew(); DWORD end_time = GetTickCount64(); cout << "Time of insert_sort is" << end_time - start_time << "ms." << endl; cout << "scale is" << numlist[i] << endl; start_time = GetTickCount64(); HeapSort heapSort(randomList1, numlist[i]); renew(); end_time = GetTickCount64(); cout << "Time of heap_sort is" << end_time - start_time << "ms." << endl; cout << "scale is" << numlist[i] << endl; start_time = GetTickCount64(); MergeSort mergeSort(randomList1, numlist[i]); renew(); end_time = GetTickCount64(); cout << "Time of merge_sort is" << end_time - start_time << "ms." << endl; } } #endif } /* consequence = insertSort.SortConsequence(); for (i = 0; i < MAXNUM; i++) { cout << consequence[i] << '\t'; } cout << endl; consequence = heapSort.SortConsequence(); for (i = 0; i < MAXNUM; i++) { cout << consequence[i] << '\t'; } cout << endl; /*QuickSort quickSort(randomList, length); consequence = quickSort.SortConsequence(); for (i = 0; i < MAXNUM; i++) { //cout << consequence[i] << '\t'; } cout << endl; MergeSort mergeSort(randomList, length); consequence = mergeSort.SortConsequence(); for (i = 0; i < MAXNUM; i++) { cout << consequence[i] << '\t'; } cout << endl; */
e9fd83d3b00f7279690ca09d86a041a71b8eafd0
db0be31627c3732c66815f2d10bf3ee81bcbf818
/GA_ST_GUI/principal.cpp
0320d91a73efb7995374146afc73b207539480df
[]
no_license
andreyvro/SMT-GA
b9d2ddd3e27c288311d0e11988846fe415ee2b32
08c3f9aa4e55caf4f10aad57c73f21e51763ab47
refs/heads/master
2021-07-10T19:20:01.708658
2020-06-09T23:36:57
2020-06-09T23:36:57
134,194,979
3
0
null
null
null
null
UTF-8
C++
false
false
17,768
cpp
principal.cpp
#include "principal.h" #include "ui_principal.h" //std::cout << qPrintable(arqNome) << std::endl; Principal::Principal(QWidget *parent) : QMainWindow(parent), ui(new Ui::Principal) { ui->setupUi(this); this->setFixedSize(width(), height()); const QRect availableGeometry = QApplication::desktop()->availableGeometry(this); //resize(availableGeometry.width() / 3, availableGeometry.height() / 2); move((availableGeometry.width() - width()) / 2, (availableGeometry.height() - height()) / 2); sena = new QGraphicsScene(this); sena->setSceneRect(0, 0, ui->grph_grafo->width()-10, ui->grph_grafo->height()-10); ui->grph_grafo->setScene(sena); arqConfig = QDir::toNativeSeparators("config.ini"); arqProblemas = QDir::toNativeSeparators("grafos/problemas/"); arqSolucoes = QDir::toNativeSeparators("grafos/solucoes/"); arqPrograma = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() + "/GA_SMT_CORE"); arqSaida = QDir::toNativeSeparators("saida/"); carregarConfigs(); listarArquivos(); desenharGrafico(); } void Principal::listarArquivos() { QDir dir(arqProblemas); dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); dir.setSorting(QDir::Size | QDir::Reversed); QFileInfoList lista = dir.entryInfoList(); ui->cmb_grafo->addItem(""); for (int i = 0; i < lista.size(); ++i) { QFileInfo fileInfo = lista.at(i); QString arqNome = fileInfo.fileName(); ui->cmb_grafo->addItem(arqNome); } } void Principal::on_cmb_grafo_currentIndexChanged(const QString &arg1) { grafoSel = arg1; ui->btn_iniciar->setEnabled(false); carregarGrafo(); if (grafoSel != "") { ui->btn_iniciar->setEnabled(true); } desenharGrafo(); } void Principal::on_chk_previsualizar_stateChanged() { desenharGrafo(); } void Principal::carregarGrafo() { grafo.clear(); solucao.clear(); // Problema QFile arq1(arqProblemas + grafoSel); if (!arq1.open(QIODevice::ReadOnly | QIODevice::Text)) { qtdVerticesGrafo = solucao_smt = solucao_mst = qtdPontosSteiner = 0; } else { QTextStream texto1(&arq1); QString linha = texto1.readLine(); // 1° Linha - Qtd de vértices qtdVerticesGrafo = linha.toInt(); while (!texto1.atEnd()) { linha = texto1.readLine(); QStringList lstLinha = linha.split(" "); QString x = lstLinha.at(0); QString y = lstLinha.at(1); Vertice vert = {x.toFloat(), y.toFloat()}; grafo.append(vert); } arq1.close(); } // Solucao QFile arq2(arqSolucoes + grafoSel); if (!arq2.open(QIODevice::ReadOnly | QIODevice::Text)) { solucao_smt = solucao_mst = qtdPontosSteiner = 0; } else { QTextStream texto2(&arq2); QString linha = texto2.readLine(); // 1° Linha - SMT solucao_smt = linha.toDouble(); linha = texto2.readLine(); // 2° Linha - MST solucao_mst = linha.toDouble(); linha = texto2.readLine(); // 3° Linha - Qtd. Pontos Steiner qtdPontosSteiner = linha.toInt(); while (!texto2.atEnd()) { linha = texto2.readLine(); QStringList lstLinha = linha.split(" "); QString x = lstLinha.at(0); QString y = lstLinha.at(1); Vertice vert = {x.toFloat(), y.toFloat()}; solucao.append(vert); } arq2.close(); } setLimiteXY(); QString qtdVert = (qtdVerticesGrafo == 0) ? "?" : QString::number(qtdVerticesGrafo); ui->lbl_qtd_vert->setText("Qtd. Pts. Fixos: " + qtdVert); QString qtdPtSt = (qtdPontosSteiner == 0) ? "?" : QString::number(qtdPontosSteiner); ui->lbl_qtd_ptst->setText("Qtd. Pts. Steiner: " + qtdPtSt); QString solSmt = (solucao_smt == 0) ? "?" : QString::number(solucao_smt, 'f', 9); ui->lbl_smt->setText("SMT: " + solSmt); QString solMst = (solucao_mst == 0) ? "?" : QString::number(solucao_mst, 'f', 9); ui->lbl_mst->setText("MST: " + solMst); QString solreducao = (solucao_mst == 0) ? "?" : QString::number(((solucao_mst - solucao_smt) * 100) / solucao_mst) + "%"; ui->lbl_reducao->setText("Redução: " + solreducao); } void Principal::setLimiteXY() { unsigned int tam = grafo.size(); if (grafoSel == "" || tam == 0) { xMin = xMax = yMin = yMax = 0; } else { xMin = xMax = grafo.at(0).x; yMin = yMax = grafo.at(0).y; for (unsigned int i = 1; i < tam; i++) { float x = grafo.at(i).x; float y = grafo.at(i).y; if (x < xMin) { xMin = x; // Margem Esquerda } else if (x > xMax) { xMax = x; // Margem Direita } if (y < yMin) { yMin = y; // Margem Superior } else if (y > yMax) { yMax = y; // Margem Inferior } } } } float Principal::reajustarPosicao(float valor, char xy) { float valorMin, valorMax, valorJanela; if (xy == 'x') { valorMin = xMin; valorMax = xMax; valorJanela = sena->width() - 20; } else { valorMin = yMin; valorMax = yMax; valorJanela = sena->height() - 20; } float ret = valor - valorMin; // Faz escala começar em zero ret = round((ret * valorJanela) / valorMax) + 10; // Reajusta escala para tela return ret; } void Principal::desenharGrafo() { sena->clear(); if (ui->chk_previsualizar->isChecked()) { QPen semBorda(Qt::NoPen); QPen canetaPreto(Qt::black); canetaPreto.setWidth(2); QBrush verde(Qt::green); QBrush amarelo(QColor(255, 255, 0, 100)); QBrush vermelho(Qt::red); // Desenha Grafo unsigned int tam = grafo.size(); for (unsigned int i = 0; i < tam; i++) { float x = reajustarPosicao(grafo.at(i).x, 'x'); float y = reajustarPosicao(grafo.at(i).y, 'y'); sena->addEllipse(x-4, y-4, 8, 8, canetaPreto, verde); QGraphicsTextItem *texto = sena->addText(QString::number(i), QFont("Arial", 9)); texto->setPos(x, y); texto->setDefaultTextColor(Qt::green); } // Desenha pontos Steiner da Solução tam = solucao.size(); for (unsigned int i = 0; i < tam; i++) { float x = reajustarPosicao(solucao.at(i).x, 'x'); float y = reajustarPosicao(solucao.at(i).y, 'y'); sena->addEllipse(x-12, y-12, 24, 24, semBorda, amarelo); sena->addEllipse(x-2, y-2, 4, 4, canetaPreto, vermelho); } } } bool Principal::carregarSaida(QString arqSel) { saidaPtSteiner.clear(); saidaCromo.clear(); saidaExecucao.clear(); QFile arq(arqSel); bool retorno = true; if (!arq.open(QIODevice::ReadOnly | QIODevice::Text)) { saidaDataset = ""; saidaTempo = saidaQtdIndi = saidaMuta = saidaCruza = saidaQtdGera = saidaSemRnd = saidaFitness = saidaQtdPtSt = 0; std::cout << "Não foi possivel abrir arquivo de saida!" << std::endl; retorno = false; } else { QTextStream texto(&arq); QString linha = texto.readLine(); // 1° - Nome do arquivo de grafo QFileInfo arquivo(linha); saidaDataset = arquivo.fileName(); if (grafoSel != saidaDataset) { // Seleciona Dataset correto no combobox int index = ui->cmb_grafo->findText(saidaDataset); if (index != -1) { ui->cmb_grafo->setCurrentIndex(index); } else { std::cout << "Carregue o grafo \"" << qPrintable(saidaDataset) << "\" e tente carregar a solução novamente."<< std::endl; arq.close(); return false; } } linha = texto.readLine(); // 2° - Tempo de execução saidaTempo = linha.toFloat(); linha = texto.readLine(); // 2° - qtdInd, indMut, indCruz, qtdGer, sementeRnd QStringList lstLinha = linha.split(" "); QString txt = lstLinha.at(0); saidaQtdIndi = txt.toInt(); txt = lstLinha.at(1); saidaCruza = txt.toFloat(); txt = lstLinha.at(2); saidaMuta = txt.toFloat(); txt = lstLinha.at(3); saidaQtdGera = txt.toInt(); txt = lstLinha.at(4); saidaSemRnd = txt.toInt(); linha = texto.readLine(); // 3° - Fitness saidaFitness = linha.toDouble(); linha = texto.readLine(); // 4° - Qtd de pontos Steiner saidaQtdPtSt = linha.toInt(); for (unsigned int i = 0; i < saidaQtdPtSt; i++) { linha = texto.readLine(); // 5° - Pontos Steiner QStringList lstLinha = linha.split(" "); QString x = lstLinha.at(0); QString y = lstLinha.at(1); Vertice vert = {x.toFloat(), y.toFloat()}; saidaPtSteiner.append(vert); } linha = texto.readLine(); // 6º - tamanho do cromossomo unsigned int tamCrom = linha.toInt(); saidaCromo.resize(tamCrom); for (unsigned int i = 0; i < tamCrom; i++) { saidaCromo[i].resize(tamCrom); } for (unsigned int i = 0; i < tamCrom-1; i++) { linha = texto.readLine(); // 7° - Cromossomo unsigned int k = 0; for (unsigned int j = i + 1; j < tamCrom; j++) { QString gene = linha.at(k); bool geneBool = gene.toInt(); saidaCromo[i][j] = geneBool; saidaCromo[j][i] = geneBool; k++; } } while (!texto.atEnd()) { linha = texto.readLine(); // 8° - Execução saidaExecucao.append(linha.toFloat()); } arq.close(); } ui->txt_saida_grafo->setText(saidaDataset); ui->txt_saida_qtdInd->setText(QString::number(saidaQtdIndi)); ui->txt_saida_cruza->setText(QString::number(saidaCruza) + "%"); ui->txt_saida_muta->setText(QString::number(saidaMuta) + "%"); ui->txt_saida_qtdGera->setText(QString::number(saidaQtdGera)); ui->txt_saida_semRnd->setText(QString::number(saidaSemRnd)); ui->txt_saida_qtdPtSt->setText(QString::number(saidaQtdPtSt)); ui->txt_saida_fitness->setText(QString::number(saidaFitness, 'f', 9)); ui->txt_saida_tempo->setText(QString::number(saidaTempo)); QString reducao = (solucao_mst == 0) ? "?" : QString::number(((solucao_mst - saidaFitness) * 100) / solucao_mst) + "%"; ui->txt_saida_reducao->setText(reducao); return retorno; } void Principal::desenharSaida() { if (ui->chk_previsualizar->isChecked()) { desenharGrafo(); QPen canetaPreto(Qt::black); canetaPreto.setWidth(2); QBrush vermelho(Qt::red); // Desenha pontos Steiner unsigned int tam = saidaPtSteiner.size(); for (unsigned int i = 0; i < tam; i++) { float x = reajustarPosicao(saidaPtSteiner.at(i).x, 'x'); float y = reajustarPosicao(saidaPtSteiner.at(i).y, 'y'); sena->addEllipse(x-3, y-3, 6, 6, canetaPreto, vermelho); QGraphicsTextItem *texto = sena->addText(QString::number(qtdVerticesGrafo + i), QFont("Arial", 9)); texto->setPos(x-18, y-18); texto->setDefaultTextColor(Qt::red); } // Printa o cromossomo /*std::cout << std::endl; tam = saidaCromo.size(); for (unsigned int i = 0; i < tam; i ++) { for (unsigned int j = 0; j < tam; j ++) { std::cout << saidaCromo[i][j] << " "; } std::cout << std::endl; }*/ // Desenha vértices tam = saidaCromo.size(); for (unsigned int i = 0; i < tam-1; i++) { for (unsigned int j = i + 1; j < tam; j++) { if (saidaCromo[i][j] == 1) { float Ax, Ay, Bx, By; if (i < qtdVerticesGrafo) { // Vertice do grafo Ax = reajustarPosicao(grafo.at(i).x, 'x'); Ay = reajustarPosicao(grafo.at(i).y, 'y'); } else { // Vértice do ponto steiner Ax = reajustarPosicao(saidaPtSteiner.at(i - qtdVerticesGrafo).x, 'x'); Ay = reajustarPosicao(saidaPtSteiner.at(i - qtdVerticesGrafo).y, 'y'); } if (j < qtdVerticesGrafo) { // Vertice do grafo Bx = reajustarPosicao(grafo.at(j).x, 'x'); By = reajustarPosicao(grafo.at(j).y, 'y'); } else { // Vértice do ponto steiner Bx = reajustarPosicao(saidaPtSteiner.at(j - qtdVerticesGrafo).x, 'x'); By = reajustarPosicao(saidaPtSteiner.at(j - qtdVerticesGrafo).y, 'y'); } sena->addLine(Ax, Ay, Bx, By, canetaPreto); } } } } } void Principal::desenharGrafico() { // generate some data: QVector<double> geracao; unsigned int tam = saidaExecucao.size(); for (unsigned int i = 1; i <= tam; i++) { geracao.append(i); } // create graph and assign data to it: ui->plt_grafico->addGraph(); ui->plt_grafico->graph(0)->setData(geracao, saidaExecucao); // give the axes some labels: ui->plt_grafico->xAxis->setLabel("Geração"); ui->plt_grafico->yAxis->setLabel("Fitness"); // set axes ranges, so we see all data: ui->plt_grafico->xAxis->setRange(1, tam); double min = *std::min_element(saidaExecucao.constBegin(), saidaExecucao.constEnd()); double max = *std::max_element(saidaExecucao.constBegin(), saidaExecucao.constEnd()); float margem = ((max-min) * 10) / 100; // 10 % de margem ui->plt_grafico->yAxis->setRange(min - margem, max + margem); ui->plt_grafico->replot(); } void Principal::on_btn_iniciar_pressed() { // Parametros QString arqGrafo = arqProblemas + grafoSel; QString amsIndi = QString::number(ui->spn_ams_individuos->value()); QString amsCruz = QString::number(ui->spn_ams_cruzamento->value()); QString amsMuta = QString::number(ui->spn_ams_mutacao->value()); QString amsGera = QString::number(ui->spn_ams_geracoes->value()); QString semeRnd = ui->txt_random->text(); QDateTime agora = QDateTime::currentDateTime(); QString dataHora = agora.toString("dd-MM-yyyy_hh:mm:ss"); QString amsArqSaida = arqSaida + dataHora + ".ams.txt"; QStringList argumentos; argumentos << arqGrafo << amsIndi << amsCruz << amsMuta << amsGera << QString::number(solucao_smt, 'f', 9) << amsArqSaida; if (semeRnd != "") { argumentos << semeRnd; } // Inicia Processo QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); QProcess *processo = new QProcess(this); processo->start(arqPrograma, argumentos); processo->waitForFinished(-1); //std::cout << qPrintable(processo->readAllStandardOutput()) << std::endl; if (carregarSaida(amsArqSaida)) { desenharSaida(); desenharGrafico(); } QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor)); } void Principal::on_act_abrir_solucao_triggered() { QString arqNome = QFileDialog::getOpenFileName(this, "Selecione um Arquivo.", arqSaida); if (arqNome != "") { if (carregarSaida(arqNome)) { desenharSaida(); desenharGrafico(); } } } void Principal::carregarConfigs() { QSettings config(arqConfig, QSettings::NativeFormat); bool previzualizar = config.value("preVisu", false).toBool(); ui->chk_previsualizar->blockSignals(true); ui->chk_previsualizar->setChecked(previzualizar); ui->chk_previsualizar->blockSignals(false); unsigned int amsIndividuos = config.value("amsIndi", 2).toInt(); ui->spn_ams_individuos->setValue(amsIndividuos); float amsCruzamento = config.value("amsCruz", 100).toFloat(); ui->spn_ams_cruzamento->setValue(amsCruzamento); float amsMutacao = config.value("amsMuta", 100).toFloat(); ui->spn_ams_mutacao->setValue(amsMutacao); unsigned int amsGeracoes = config.value("amsGera", 1000).toInt(); ui->spn_ams_geracoes->setValue(amsGeracoes); QString sementeRnd = config.value("semeRnd", "").toString(); ui->txt_random->setText(sementeRnd); } void Principal::salvarConfigs() { QSettings config(arqConfig, QSettings::NativeFormat); bool previzualizar = ui->chk_previsualizar->isChecked(); config.setValue("preVisu", previzualizar); unsigned int amsIndividuos = ui->spn_ams_individuos->value(); config.setValue("amsIndi", amsIndividuos); float amsCruzamento = ui->spn_ams_cruzamento->value(); config.setValue("amsCruz", amsCruzamento); float amsMutacao = ui->spn_ams_mutacao->value(); config.setValue("amsMuta", amsMutacao); unsigned int amsGeracoes = ui->spn_ams_geracoes->value(); config.setValue("amsGera", amsGeracoes); QString sementeRnd = ui->txt_random->text(); config.setValue("semeRnd", sementeRnd); } void Principal::on_txt_random_textChanged(const QString &arg1) { if ((arg1 != "") && (arg1 != "-")) { ui->txt_random->setText(QString::number(arg1.toInt())); } } void Principal::on_act_fechar_triggered() { QApplication::quit(); } void Principal::on_act_sobre_triggered() { frmSobre.show(); } Principal::~Principal() { salvarConfigs(); delete ui; }
d69e10acfa9dfbea1c948ef6705f7c4b5ccb2b74
ab1b93e96102daab136a5a94b59699684660c266
/include/icsneo/device/tree/radgigastar/radgigastarusb.h
f4b10bba3a6b991b7b7abc52b0e2a01d4371aade
[ "BSD-2-Clause" ]
permissive
drebbe-intrepid/libicsneo
b8ed945c86e9dc53f8920fc90b2d2fb962f4a81f
4e901676d289decc4fa7a5f294356fcc78620dc9
refs/heads/master
2021-06-14T11:39:23.856645
2021-06-07T21:03:56
2021-06-07T21:03:56
178,077,739
0
0
NOASSERTION
2019-03-27T21:33:31
2019-03-27T21:33:30
null
UTF-8
C++
false
false
744
h
radgigastarusb.h
#ifndef __RADGIGASTAR_USB_H_ #define __RADGIGASTAR_USB_H_ #ifdef __cplusplus #include "icsneo/device/tree/radgigastar/radgigastar.h" #include "icsneo/platform/ftdi3.h" namespace icsneo { class RADGigastarUSB : public RADGigastar { public: static constexpr const uint16_t PRODUCT_ID = 0x1204; static std::vector<std::shared_ptr<Device>> Find() { std::vector<std::shared_ptr<Device>> found; for(auto neodevice : FTDI3::FindByProduct(PRODUCT_ID)) found.emplace_back(new RADGigastarUSB(neodevice)); // Creation of the shared_ptr return found; } private: RADGigastarUSB(neodevice_t neodevice) : RADGigastar(neodevice) { initialize<FTDI3, RADGigastarSettings>(); productId = PRODUCT_ID; } }; } #endif // __cplusplus #endif
52caf6b59e1d1645d56eb69947af1532ad8f09e1
269c78119f31562e87757f30eb29b3eeb8dbe1f5
/Classes/GameResource.cpp
894e2449c2a93d4560e9bc4e49f33d43ecc05a21
[ "MIT" ]
permissive
rayxuln/tudo_push_box
9fd9c32289e8c26620902d6ef91a2714244911ff
95a6c9aa636c91cd7de8616c4e9cf8b7c1c3f22d
refs/heads/master
2021-06-19T15:12:22.217397
2017-07-25T11:15:31
2017-07-25T11:15:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,861
cpp
GameResource.cpp
#include "GameResource.h" #include "GameHelper.h" using namespace cocos2d; using namespace tudo_push_box; using namespace std; GameResource *GameResource::Instance(){ static GameResource gr; return &gr; } void GameResource::LoadGameCfgFile(string path){ string text = FileUtils::getInstance()->getStringFromFile(path); //msg_box(text,"a"); game_cfg = json_object_type::phraze(text); //msg_box("ok"); //msg_box(json_object_type::json_object_type_to_string(game_cfg,0),"b"); //msg_box(convert_int_to_string(GetGameDataNowLevel())); //SaveGameData(5); //msg_box(convert_int_to_string(GetLevelNums())); } void GameResource::SaveGameData(int now_level){ auto save_data = json_object_type::phraze("{\"now_level\":0}"); save_data["now_level"].put_int(now_level); string data_file = FileUtils::getInstance()->getWritablePath() + game_cfg["save_file"].get_string(); //msg_box(data_file); fstream f_out(data_file,ios::out | ios::trunc); f_out<<json_object_type::json_object_type_to_string(save_data); f_out.close(); } int GameResource::GetGameDataNowLevel(){ string data_file = FileUtils::getInstance()->getWritablePath() + game_cfg["save_file"].get_string(); if(FileUtils::getInstance()->isFileExist(data_file)){ string text = FileUtils::getInstance()->getStringFromFile(data_file); auto save_data = json_object_type::phraze(text); return save_data["now_level"].get_int(); }else{ return 0; } } int GameResource::GetLevelNums(){ int i=0; for(;FileUtils::getInstance()->isFileExist(MakeLeveFilePath(i));++i); return i; } json_object_type GameResource::GetLevelData(int n){ string text = FileUtils::getInstance()->getStringFromFile(MakeLeveFilePath(n)); return json_object_type::phraze(text); } string GameResource::MakeLeveFilePath(int l){ return GetLevelDir()+std::string("/level_")+convert_int_to_string(l)+string(".json"); }
822feee08e2f609745d82ed79544d07dd07d2d7a
4cfaeb9bd567dc41ab6b9e48a254265bac7301e2
/component_animation.cpp
b68d64178661a323b99e4ecb3b100a831fd66c99
[]
no_license
zDonik1/DungeonCrawler_RPG
ce2411a173eadf676b06beeb62fae23cdea9894c
572275195b3f5b3f8e5dfb2840d21832005f9376
refs/heads/master
2020-05-18T05:37:36.858860
2019-04-30T07:43:17
2019-04-30T07:43:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,332
cpp
component_animation.cpp
#include "component_animation.h" // Constructor / Destructor Component_Animation::Component_Animation(sf::Sprite &l_sprite, sf::Texture &l_textureSheet) : sprite(l_sprite) , textureSheet(l_textureSheet) , lastAnimation(nullptr) , priorityAnimation(nullptr) { } Component_Animation::~Component_Animation() { for (auto &itr : animations) { delete itr.second; } } // Accessors const bool &Component_Animation::isDone(const std::string key) { return animations[key]->isDone(); } // Functions void Component_Animation::addAnimation(const std::string key, float l_animationTimer, int startFrame_x, int startFrame_y, int frames_x, int frames_y, int l_width, int l_height) { animations[key] = new Animation(sprite, textureSheet, l_animationTimer, startFrame_x, startFrame_y, frames_x, frames_y, l_width, l_height); } const bool &Component_Animation::play(const std::string key, const float &dt, const bool priority) { if (priorityAnimation) { if (priorityAnimation == animations[key]) { if (lastAnimation != animations[key]) { if (lastAnimation == nullptr) { lastAnimation = animations[key]; } else { lastAnimation->reset(); lastAnimation = animations[key]; } } // If priority animation is done, remove it if (animations[key]->play(dt)) { priorityAnimation = nullptr; } } } else { if (priority) { priorityAnimation = animations[key]; } if (lastAnimation != animations[key]) { if (lastAnimation == nullptr) { lastAnimation = animations[key]; } else { lastAnimation->reset(); lastAnimation = animations[key]; } } animations[key]->play(dt); } return animations[key]->isDone(); } const bool &Component_Animation::play(const std::string key, const float &dt, const float &modifier, const float &modifierMax, const bool priority) { if (priorityAnimation) { if (priorityAnimation == animations[key]) { if (lastAnimation != animations[key]) { if (lastAnimation == nullptr) { lastAnimation = animations[key]; } else { lastAnimation->reset(); lastAnimation = animations[key]; } } // If priority animation is done, remove it if (animations[key]->play(dt, abs(modifier / modifierMax))) { priorityAnimation = nullptr; } } } else { if (priority) { priorityAnimation = animations[key]; } if (lastAnimation != animations[key]) { if (lastAnimation == nullptr) { lastAnimation = animations[key]; } else { lastAnimation->reset(); lastAnimation = animations[key]; } } animations[key]->play(dt, abs(modifier / modifierMax)); } return animations[key]->isDone(); }
8481f27cfade89df39b1aa06c36b979193658325
a2ee7bdda1ec77faf3f68b158da3523de425987e
/tp-entrega-03/common/xml/ParserXml.h
a02ab394ebe5387cf541b0877389117448ecad6b
[]
no_license
MauroToscano/Taller-de-Programacion-I-Grupo-8
e495cbc27b76533619e0fc36c9826fe8a51e1645
1b5e6c6e3eda8eb1c11ab905fa75e75a571234a5
refs/heads/master
2022-07-20T04:00:08.267771
2020-02-25T23:44:10
2020-02-25T23:44:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,755
h
ParserXml.h
#ifndef _PARSERXML_H_ #define _PARSERXML_H_ /* @autor sabris */ #include <stdio.h> #include <algorithm> #include <iterator> #include <set> #include <map> #include <string> using namespace std; #include "tinyxml2.h" using namespace tinyxml2; #include "MensajeXml.h" #include "ClienteXml.h" #include "ServidorXml.h" #include "../Log.h" #define MAX_PUERTO 65535 #define MIN_PUERTO 1024 #define MAX_RUTA 200 #define XML_DEF_SERVIDOR "xmlDefaultServidor.xml" #define XML_DEF_CLIENTE "xmlDefaultCliente.xml" #define XML_DEF_SPRITE "error.bmp" class ParserXml { private: //contiene el document tinyxml2::XMLDocument xmlDoc; //mapa con los IDs de los sprites map<string,int> mapaSpriteIds; public: ParserXml(); virtual ~ParserXml(); //CLIENTE int levantarXMLCliente(char * ruta); int crearXmlCliente(); //esta funcion realiza la carga del xml del cliente void cargarXmlCliente(int argc, char* argv[]); //SERVIDOR int levantarXMLServidor(char * ruta); int crearXmlServidor(); //esta funcion realiza la carga del xml del SERVIDOR void cargarXmlServidor(int argc, char* argv[]); //validaciones static int isValidIp(char * strIp); static int isValidInt(char * strValor); static int isValidDouble(char * strValor); static int isValidChar(char * strValor); static int isValidString(char * strString); static int isValidPuerto(char * strPuerto); static int isValidTipo(char * strTipo); static int isValidValor(char * strValor,int tipo); static int convertTipoToInt(char * strTipo); static int isIgualAPatronMayuscula(char * cadena,char * patronMayus); //carga de datos //CLIENTE ClienteXml * createDataClienteXml(); void createDataConexionXml(ClienteXml * clienteXml,XMLElement* elemConex); void createDataListMensajeXml(ClienteXml * clienteXml,XMLElement* listMensajes); MensajeXml * createDataMensajeXml(XMLElement* elemMensaje); MensajeXml * createMensajeXml(int id, int tipo,char * valor); //SERVIDOR ServidorXml * createDataServidorXml(); void createDataVentanaXml(ServidorXml *servidorXml,XMLElement* elemVentana); void createDataListSpriteXml(ServidorXml *servidorXml,XMLElement* listSprites); SpriteXml * createDataSpriteXml(XMLElement* elemSprite,int idxSps); void createDataListEscenariosXml(ServidorXml *servidorXml,XMLElement* listEscenarios); EscenarioXml * createDataEscenarioXml(XMLElement* elemEscenario,int idxEs); void createDataFondoXml(EscenarioXml *escenarioXml,XMLElement* elemFondo); void createDataListElementosXml(EscenarioXml *escenarioXml,XMLElement* listElementos); ElementoXml * createDataElementoXml(XMLElement* elemE,int idxE); void createDataListAvionXml(ServidorXml *servidorXml,XMLElement* listAviones); AvionXml * createDataAvionXml(XMLElement* elemAvion,int idxAvs); void createDataListEnemigoXml(EscenarioXml *escenarioXml,XMLElement* listEnemigo); AvionEnemigoXml * createDataEnemigoXml(XMLElement* elemEnemigo,int idxEne); void createDataListPowerXml(EscenarioXml *escenarioXml,XMLElement* listPower); PowerUpXml * createDataPowerXml(XMLElement* elemPower,int idxPow); int findSpriteIdByName(char * strIdSprite); int tipoPowerToInt(char * strTipoPow); int tipoEnemigoToInt(char * strTipoEne); int modoToint(char * modo); //validacion de xml //CLIENTE int validarXmlArchivoCliente(); int validarClienteXml(XMLElement* elemCliente); int validarConexionXml(XMLElement* elemConex); int validarListaMensajesXml(XMLElement* listMensajes); int validarMensajeXml(XMLElement* elemMensaje,set<int> &setClaves); //SERVIDOR int validarXmlArchivoServidor(); int validarServidorXml(XMLElement* elemServidor); int validarVentanaXml(XMLElement* elemVentana); int validarListaSpriteXml(XMLElement* listSprites); int validarSpriteXml(XMLElement* elemSprite,set<string> &setClaves); int validarListaEscenarioXml(XMLElement* listEscenario); int validarEscenarioXml(XMLElement* elemEscenario); int validarFondoXml(XMLElement* elemFondo); int validarListaElementosXml(XMLElement* listElementos); int validarElementoXml(XMLElement* elemE); int validarPosicionXml(XMLElement* posicion); int validarListaAvionXml(XMLElement* listAviones); int validarAvionXml(XMLElement* elemAvion); int validarListEnemigoXml(XMLElement* listEnemigo); int validarEnemigoXml(XMLElement* elemEnemigo); int validarListPowerXml(XMLElement* listPower); int validarPowerXml(XMLElement* elemPower); //metodo para vincular y validar entidades del servidor , se puede usar tambien del lado del cliente void vincularYValidarEntidades(ServidorXml *servidorXml); bool existeFile(char * nomFile); }; #endif //_PARSERXML_H_
6a86f5d91e34e04daf02b625f7ba02fd9923c027
2489f20116dfa10e4514b636cbf92a6036edc21a
/tojcode/2350.cpp
1bc1876d0417a79579fc0c4a429b195cff633911
[]
no_license
menguan/toj_code
7db20eaffce976932a3bc8880287f0111a621a40
f41bd77ee333c58d5fcb26d1848a101c311d1790
refs/heads/master
2020-03-25T04:08:41.881068
2018-08-03T05:02:38
2018-08-03T05:02:38
143,379,558
1
0
null
null
null
null
UTF-8
C++
false
false
755
cpp
2350.cpp
#include<iostream> #include<cstring> using namespace std; int dir[4][2]={-1,0,0,1,1,0,0,-1}; int map[60][60]; int main() { int t,n,r; cin>>t; while(t--) {cin>>n>>r; memset(map,0,sizeof(map)); int a,b; for(int i=0;i<r;i++) { cin>>a>>b; map[a][b]=1; } cin>>a>>b; int tt; if(a==0) tt=2; else if(a==n+1) tt=0; else if(b==0) tt=1; else tt=3; do{ a+=dir[tt][0];b+=dir[tt][1]; if(map[a][b]) tt=(tt+1)%4; }while(a&&a!=n+1&&b&&b!=n+1); cout<<a<<" "<<b<<endl; } }
828cc9ebaccd1fd57729590399ce30b311d49689
a776940eca535aee58aad97eacf4a5b727f6aa8a
/operator-overloading/globally-overloaded-operators/main.cpp
528612a252f59d9429868a9fef9f88836b89e766
[]
no_license
itsabhianant/learning
0712faa57e5e941d7811c0dde7747e9e8d4a7f88
95a98db742d822bad90c1efae6146efaf320042d
refs/heads/master
2023-06-11T07:59:05.450943
2021-07-01T05:09:46
2021-07-01T05:09:46
369,283,703
0
0
null
2021-07-01T05:09:46
2021-05-20T17:12:51
C++
UTF-8
C++
false
false
3,530
cpp
main.cpp
#include "declarations.hpp" int main() { /* Implementing the overloaded operators */ // - cout << "\n===========================" << endl; cout << "Overloaded (-)" << endl; Mystring upper {"UPPER"}; upper.display(); //UPPER Mystring lower = -upper; lower.display(); //upper cout << "===========================\n" << endl; // + cout << "\n===========================" << endl; cout << "Overloaded (+)" << endl; Mystring first_name = "Abhishek"; first_name.display(); //Abhishek Mystring middle_name = " Anant"; middle_name.display(); // Anant Mystring name = first_name + middle_name + " Singh"; name.display(); //Abhishek Anant Singh; cout << "===========================\n" << endl; // += cout << "\n===========================" << endl; cout << "Overloaded (+=)" << endl; Mystring s1 = "abc"; s1.display(); //abc s1 += "ABC"; s1.display(); //abcAbc Mystring s2 = "xyz"; s2.display(); //xyz s2 += "XYZ"; s2.display(); //xyzXYZ s1 += s2; s1.display(); //abcABCxyzXYZ cout << "===========================\n" << endl; // * cout << "\n===========================" << endl; cout << "Overloaded (*)" << endl; Mystring s3 = "123"; s3.display(); //123 Mystring s4 = s3 * 4; s4.display(); //123123123123 cout << "===========================\n" << endl; // *= cout << "\n===========================" << endl; cout << "Overloaded (*=)" << endl; Mystring s5 = "12345"; s5.display(); //12345 s5 *= 5; s5.display(); //1234512345123451234512345 cout << "===========================\n" << endl; cout << "\n+++++++++++++++++++++++++++++++++++++++++++++++++" << endl; Mystring a = "abc"; a.display(); //abc Mystring a_ = "abc"; a_.display(); //abc Mystring b = "bac"; b.display(); //bac Mystring c = "cab"; c.display(); //cab // == cout << "\n===========================" << endl; cout << "Overloaded (==)" << endl; cout << (a == a_) << endl; //1(not false) cout << (a == b) << endl; //0(false) cout << "===========================\n" << endl; // != cout << "\n===========================" << endl; cout << "Overloaded (!=)" << endl; cout << (a != b) << endl; //1(not false) cout << (a != a_) << endl; //0(false) cout << "===========================\n" << endl; // < cout << "\n===========================" << endl; cout << "Overloaded (<)" << endl; cout << (b < c) << endl; //1(not false) cout << (c < b) << endl; //0(false) cout << "===========================\n" << endl; // > cout << "\n===========================" << endl; cout << "Overloaded (>)" << endl; cout << (c > b) << endl; //1(not false) cout << (b > c) << endl; //0(false) cout << "===========================" << endl; cout << "+++++++++++++++++++++++++++++++++++++++++++++++++\n" << endl; return 0; }
b4ea9777b82589a65df7a253cf5197d9a38fcfb3
f3a44b78a7ee1dcbf32a2bd654728b5ac3753d88
/Arduino/ard_py/sketch/sketch.ino
d6ccfb7999862fbcfcdcd6b0db46e400271c797e
[]
no_license
Tokunn/vim
7251d338214a15cd37dcb9670716de396ec08007
ef38c7d5ebb5cb1f5ac1bcd4319082e196dd5e8e
refs/heads/master
2016-09-06T09:55:28.437282
2015-10-27T09:18:04
2015-10-27T09:18:04
21,315,484
0
0
null
null
null
null
UTF-8
C++
false
false
610
ino
sketch.ino
byte val = 0; int led1 = 10; int led2 = 13; void setup(){ pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); Serial.begin(9600); } void loop() { if (Serial.available() > 0) { val = Serial.read(); Serial.print(val); //for debug if (val == '1') { digitalWrite(led1, HIGH); delay(1000); } else if (val == '2'){ digitalWrite(led2, HIGH); delay(1000); } else if (val == '0'){ digitalWrite(led1, LOW); digitalWrite(led2, LOW); delay(1000); } } }
2bb0789bf43720f7ad0f2916e1ee33a0990b4c78
b709e1b162eb44bb54364ab09671264535a0ce01
/lecture-1/src/exercise_d.cpp
a0a20eaffd49a6975f823c8771c0239bd1b8faf8
[]
no_license
dangerousplay/estrutura-de-dados
aedbd61a06ce4676c7d0de9d56891a95340520ff
bfa9faa67b41c7a2b671112fdc47c065d428b50e
refs/heads/master
2021-03-03T01:45:53.514471
2020-07-05T19:32:51
2020-07-05T19:32:51
245,923,003
0
0
null
null
null
null
UTF-8
C++
false
false
751
cpp
exercise_d.cpp
#include <cstdio> int main() { char campo, opcao; int num, cont; float valor, nota; double temp, taxa; printf("char campo = %p witch is of size %ld byte\n", &campo, sizeof(campo)); printf("char opcao = %p witch is of size %ld byte\n", &opcao, sizeof(opcao)); printf("int num = %p witch is of size %ld bytes\n", &num, sizeof(num)); printf("int cont = %p witch is of size %ld bytes\n", &cont, sizeof(cont)); printf("float valor = %p witch is of size %ld bytes\n", &valor, sizeof(valor)); printf("float nota = %p witch is of size %ld bytes\n", &nota, sizeof(nota)); printf("double temp = %p witch is of size %ld bytes\n", &temp, sizeof(temp)); printf("double taxa = %p witch is of size %ld bytes\n", &taxa, sizeof(taxa)); }
c45a6a1a4b0af69f2a89ca7567eb6b5ce2187831
d3e123962c7452113a20dd2724e779bb1731a59f
/code/01_Convert_Char_to_Int/converter.cpp
c7d575a6cf56a57f07430413eddd113f34b2d9bf
[]
no_license
daveherzig/cs_vorkurs_hfict
4180e344d55eb439c44cf4a0afbe989936fabc1c
1bfc8d0048837c14b4e74527d956f83514090e85
refs/heads/master
2018-09-28T04:30:35.048196
2018-06-16T07:07:20
2018-06-16T07:07:20
119,808,842
0
0
null
null
null
null
UTF-8
C++
false
false
431
cpp
converter.cpp
/******************************************************** * Organization: hf-ict.ch * Developer: p.suetterlin@hf-ict.info * Date: 2018-03-19 * * This program prints the ascii number of a character * to the console. * ********************************************************/ #include <iostream> using namespace std; int main (int argc, char ** argv) { char a = 'F'; cout << (int)a; return 0; }
568b7c457ccf23a1a4abdffa3722063e1ea3c894
6ede10141823ddc8febe4b658a74c93b66e6e47b
/nbu/CSCB325/down_right_max_sum_dp.cpp
d714d14b16c075c87188e2f13ea6a629082522ff
[]
no_license
petervalkov/edu
8c544ae0f2fc9813bb37c61399bc412c8f28083d
8ab060fdfebe01d6472326f57dc16d7ebbbb2b39
refs/heads/master
2023-04-01T06:20:15.050351
2021-03-28T20:35:40
2021-03-28T20:35:40
280,419,728
0
0
null
null
null
null
UTF-8
C++
false
false
911
cpp
down_right_max_sum_dp.cpp
/*Input: 2 3 0 1 1 0 4 2 1 1 1 5 1 1 1 1 1 0 0 3 4 3 0 1 2 0 1 1 1 1 0 1 2 4 0 4 0 Output: 8 15 */ #include <bits/stdc++.h> using namespace std; #define MAX 110 int F[MAX][MAX]; int S[MAX][MAX]; int main(){ int input_count; cin >> input_count; for (int i = 0; i < input_count; i++){ int size; cin >> size; for (int row = 0; row < size; row++) for (int col = 0; col < size; col++) cin >> F[row][col]; S[0][0] = F[0][0]; for (int i = 1; i < size; i++) S[0][i] = S[0][i-1] + F[0][i]; for (int row = 1; row < size; row++){ S[i][0] = S[i-1][0] + F[i][0]; for (int col = 1; col < size; col++) S[row][col] = max(F[row][col] + S[row-1][col], F[row][col] + S[row][col-1]); } cout << S[size - 1][size - 1] << endl; } return 0; }
e832abc25a49f5db9a6306f87fc55cdba376377f
0be9e0989a8d8ee51f9bcddf7f966ce95cd5a1cc
/CPPTest/CPPTest/IOTest/IOTest.h
6b3e4f168cada097a1ec87d887e45250d87eea81
[]
no_license
MagusXuekt/CPPTest
5438c87a1787d12710a930667b107cdced54b585
e5352cbc776fb867060e99dc4b404283efcf64bf
refs/heads/master
2020-05-18T05:23:18.681985
2019-08-05T07:53:35
2019-08-05T07:53:35
184,204,699
0
0
null
null
null
null
UTF-8
C++
false
false
185
h
IOTest.h
#ifndef IOTEST_H #define IOTEST_H namespace IOTest { //ScanfAndPrintfTest void ScanfTest(); void PrintfTest(); //GetAndGetlineTest void GetAndGetlineTest(); } #endif //~IOTEST_H
2eb8add4a4b01e562b49552edc33eedda34cffad
312a4c158d62c8482eb129c01473d8e8325ad6b1
/lab2/main.cpp
6512da66efba2d34a9285759326469e728f21300
[]
no_license
BSUIR450503/450503_vershilo
cec5beec8dd9587cc7e075a12aff66f9fd1a2f69
826e3acf84e188913619f32d17b54f0bfa8a4196
refs/heads/master
2021-01-17T07:10:01.154297
2016-06-20T00:32:14
2016-06-20T00:32:14
53,447,683
0
1
null
null
null
null
UTF-8
C++
false
false
225
cpp
main.cpp
#include "librariesh.h" #include "func.cpp" void main(int argc, char* argv[]) { Myprocess P; if (argc == 2) { #ifdef _WIN32 P.printString(atoi(argv[1])); #endif } else P.Work_Process(argv[0]); return; }
fd8a5e64a8507b38bfd69a3b6af9af465716207b
2af15d28492c10be1cc2e27c6ac3bcfd5ea3b525
/opm/core/props/pvt/PvtPropertiesBasic.hpp
5ccbc858c6899ff94db67f5b16f1f6e51ca97e14
[]
no_license
OPM/opm-simulators-legacy
62e22354a4ea276acc40a1638317f41f84a46c6d
b027361cc3c5b09d15288cfbbbbaf8e4bb8336e5
refs/heads/master
2020-04-06T23:17:46.852136
2019-03-13T10:06:59
2019-03-13T10:06:59
157,864,384
1
3
null
2019-03-13T10:07:01
2018-11-16T12:25:53
C++
UTF-8
C++
false
false
3,853
hpp
PvtPropertiesBasic.hpp
/* Copyright 2012 SINTEF ICT, Applied Mathematics. This file is part of the Open Porous Media project (OPM). OPM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OPM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OPM. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPM_PVTPROPERTIESBASIC_HEADER_INCLUDED #define OPM_PVTPROPERTIESBASIC_HEADER_INCLUDED #include <opm/common/utility/parameters/ParameterGroup.hpp> #include <opm/core/props/BlackoilPhases.hpp> #include <vector> namespace Opm { /// Class collecting simple pvt properties for 1-3 phases. /// All phases are incompressible and have constant viscosities. /// For all the methods, the following apply: p, T and z are unused. /// Output arrays shall be of size n*numPhases(), and must be valid /// before calling the method. /// NOTE: This class is intentionally similar to BlackoilPvtProperties. class PvtPropertiesBasic { public: /// Default constructor. PvtPropertiesBasic(); /// Initialize from parameters. /// The following parameters are accepted (defaults): /// - num_phases (2) -- Must be 1, 2 or 3. /// - rho1, rho2, rho3 (1.0e3) -- Density in kg/m^3 /// - mu1, mu2, mu3 (1.0) -- Viscosity in cP void init(const ParameterGroup& param); /// Initialize from arguments. /// Basic multi phase fluid pvt properties. void init(const int num_phases, const std::vector<double>& rho, const std::vector<double>& visc); /// Number of active phases. int numPhases() const; /// \return Object describing the active phases. PhaseUsage phaseUsage() const; /// Densities of stock components at surface conditions. /// \return Array of size numPhases(). const double* surfaceDensities() const; /// Viscosity as a function of p, T and z. void mu(const int n, const double* p, const double* T, const double* z, double* output_mu) const; /// Formation volume factor as a function of p, T and z. void B(const int n, const double* p, const double* T, const double* z, double* output_B) const; /// Formation volume factor and p-derivative as functions of p, T and z. void dBdp(const int n, const double* p, const double* T, const double* z, double* output_B, double* output_dBdp) const; /// Solution factor as a function of p and z. void R(const int n, const double* p, const double* z, double* output_R) const; /// Solution factor and p-derivative as functions of p and z. void dRdp(const int n, const double* p, const double* z, double* output_R, double* output_dRdp) const; private: // The PVT properties. We need to store one value per PVT // region. std::vector<double> density_; std::vector<double> viscosity_; std::vector<double> formation_volume_factor_; }; } #endif // OPM_PVTPROPERTIESBASIC_HEADER_INCLUDED
99d24ada84712da3adfe6057ae91a602562d3e95
2c7bbc527afde84d317594e61b6a74e2c4ae9b42
/src/ContourDetector.cpp
da68bd3abcdf1e4a8ea648e1e60e957aa96ac3b3
[ "MIT" ]
permissive
sdrobotics101/raspberry-pi
684f565796743363cb4a89e4865e82d45d6f98e4
5f12538f9164590094e4710aace2d019ba6f7c98
refs/heads/master
2020-05-31T17:50:15.973438
2015-06-26T02:33:25
2015-06-26T02:33:25
20,842,659
0
0
null
null
null
null
UTF-8
C++
false
false
3,397
cpp
ContourDetector.cpp
#include <opencv2/opencv.hpp> #include "Contour.hpp" #include "ContourDetector.hpp" #include "HSVImage.hpp" ContourDetector::Params::Params() { filter_by_hue = false; min_hue = 0; max_hue = 255; filter_by_saturation = false; min_saturation = 0; max_saturation = 255; filter_by_value = false; min_value = 0; max_value = 255; filter_by_area = false; min_area = 0; max_area = 1e6; filter_with_canny = true; min_canny = 0; max_canny = 50; filter_with_blur = true; } ContourDetector::ContourDetector(const ContourDetector:: Params & parameters):params(parameters) { } std::vector < Contour > ContourDetector::detect(cv::Mat image) { HSVImage hsv_image = HSVImage(image); cv::Mat hue_thresholded_lower; cv::Mat hue_thresholded_upper; cv::Mat hue_thresholded; cv::Mat saturation_thresholded_lower; cv::Mat saturation_thresholded_upper; cv::Mat saturation_thresholded; cv::Mat value_thresholded_lower; cv::Mat value_thresholded_upper; cv::Mat value_thresholded; cv::Mat threshold_out; cv::Mat blur_out; cv::Mat canny_out; cv::Mat processed_img; cv::threshold(hsv_image.hue, hue_thresholded_lower, params.min_hue, 255, CV_THRESH_BINARY); cv::threshold(hsv_image.hue, hue_thresholded_upper, params.max_hue, 255, CV_THRESH_BINARY_INV); hue_thresholded = hue_thresholded_lower & hue_thresholded_upper; cv::threshold(hsv_image.saturation, saturation_thresholded_lower, params.min_saturation, 255, CV_THRESH_BINARY); cv::threshold(hsv_image.saturation, saturation_thresholded_upper, params.max_saturation, 255, CV_THRESH_BINARY_INV); saturation_thresholded = saturation_thresholded_lower & saturation_thresholded_upper; cv::threshold(hsv_image.value, value_thresholded_lower, params.min_value, 255, CV_THRESH_BINARY); cv::threshold(hsv_image.value, value_thresholded_upper, params.max_value, 255, CV_THRESH_BINARY_INV); value_thresholded = value_thresholded_lower & value_thresholded_upper; threshold_out = hue_thresholded.clone(); if (params.filter_by_saturation) threshold_out = threshold_out & saturation_thresholded; if (params.filter_by_value) threshold_out = threshold_out & value_thresholded; if (params.filter_with_blur) { cv::Mat blur_tmp; cv::pyrDown(threshold_out, blur_tmp, cv::Size(threshold_out.cols / 2, threshold_out.rows / 2)); cv::pyrUp(blur_tmp, blur_out, threshold_out.size()); } else blur_out = threshold_out.clone(); if (params.filter_with_canny) { cv::Canny(blur_out, canny_out, params.min_canny, params.max_canny, 5); cv::dilate(canny_out, canny_out, cv::Mat(), cv::Point(-1, -1)); } else canny_out = blur_out.clone(); std::vector < std::vector < cv::Point > >all_contours_raw; cv::findContours(canny_out, all_contours_raw, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); std::vector < Contour > all_contours; for (uint i = 0; i < all_contours_raw.size(); i++) all_contours.push_back(Contour(all_contours_raw.at(i))); std::vector < Contour > area_filtered_contours; if (params.filter_by_area) { for (uint i = 0; i < all_contours.size(); i++) { if (all_contours.at(i).get_area() > params.min_area && area_filtered_contours.at(i).get_area() < params.max_area) area_filtered_contours.push_back(all_contours. at(i)); } } else area_filtered_contours = all_contours; return area_filtered_contours; }
a5aabc648593db12879a0a8f4afd7003da6847a3
abb743655f437aa17d3d3cbdab74fff32b70c5c1
/Sources/SampleApp/VkResources/FrameBuffer.hpp
9a1b06e407dc2b9208ef1b6a80d7be219561c03e
[]
no_license
darkoffalex/vulkan
13eb786ea1eada68409cc31f4d173fd52d3e1b8c
5c82bfc2868afe4fb469ff4bd7c91f55263c49b7
refs/heads/master
2021-07-16T12:47:34.057260
2021-05-30T21:17:21
2021-05-30T21:17:21
125,894,187
18
1
null
null
null
null
UTF-8
C++
false
false
10,497
hpp
FrameBuffer.hpp
#pragma once #include "../VkTools/Tools.h" #include "../VkTools/Image.hpp" namespace vk { namespace resources { /** * Инициализирующая структура описывающая вложение кадрового буфера */ struct FrameBufferAttachmentInfo { // Если передан указать на объект изображения - оно не будет создаваться // Это полезно если у нас уже есть изображение (например из swap-chain) const vk::Image* pImage = nullptr; // Тип изображения (1D, 2D, 3D) vk::ImageType imageType = vk::ImageType::e2D; // Формат изображения vk::Format format; // Флаг использования (в качестве чего будет использовано изображение, используется если pImage равен nullptr) vk::ImageUsageFlags usageFlags; // Флаг доступа к под-ресурсам (слоям) изображения vk::ImageAspectFlags aspectFlags; }; /** * Класс обертка для работы с кадровым буфером Vulkan */ class FrameBuffer { private: /// Готов ли кадровый буфер bool isReady_; /// Указатель на устройство владеющее кадровым буфером (создающее его) const vk::tools::Device* pDevice_; /// Разрешение vk::Extent3D extent_; /// Объект кадрового буфера Vulkan (smart pointer) vk::UniqueFramebuffer frameBuffer_; /// Массив вложений (изображений) кадрового буфера std::vector<vk::tools::Image> attachments_; public: /** * Конструктор по умолчанию */ FrameBuffer():isReady_(false),pDevice_(nullptr){} /** * Запрет копирования через инициализацию * @param other Ссылка на копируемый объекта */ FrameBuffer(const FrameBuffer& other) = delete; /** * Запрет копирования через присваивание * @param other Ссылка на копируемый объекта * @return Ссылка на текущий объект */ FrameBuffer& operator=(const FrameBuffer& other) = delete; /** * Конструктор перемещения * @param other R-value ссылка на другой объект * @details Нельзя копировать объект, но можно обменяться с ним ресурсом */ FrameBuffer(FrameBuffer&& other) noexcept:FrameBuffer(){ std::swap(isReady_,other.isReady_); std::swap(pDevice_,other.pDevice_); std::swap(extent_, other.extent_); frameBuffer_.swap(other.frameBuffer_); attachments_.swap(other.attachments_); } /** * Перемещение через присваивание * @param other R-value ссылка на другой объект * @return Ссылка на текущий объект */ FrameBuffer& operator=(FrameBuffer&& other) noexcept { if (this == &other) return *this; this->destroyVulkanResources(); isReady_ = false; pDevice_ = nullptr; std::swap(isReady_,other.isReady_); std::swap(pDevice_,other.pDevice_); std::swap(extent_,other.extent_); frameBuffer_.swap(other.frameBuffer_); attachments_.swap(other.attachments_); return *this; } /** * Основной конструктор кадрового буфера * @param pDevice Указатель на устройство создающее кадровый буфер (и владеющее им) * @param renderPass Целевой проход рендеринга, в котором будет использован данный кадровый буфер * @param extent Расширение (разрешение) буфера * @param attachmentsInfo Массив структур описывающих вложения */ explicit FrameBuffer( const vk::tools::Device* pDevice, const vk::UniqueRenderPass& renderPass, const vk::Extent3D& extent, const std::vector<vk::resources::FrameBufferAttachmentInfo>& attachmentsInfo): isReady_(false), pDevice_(pDevice), extent_(extent) { // Проверить устройство if(pDevice_ == nullptr || !pDevice_->isReady()){ throw vk::DeviceLostError("Device is not available"); } // Массив объектов imageView вложений для создания кадрового буфера std::vector<vk::ImageView> attachmentsImageViews; // Пройти по всем объектам инициализации вложений буфера for(const auto& info : attachmentsInfo) { // Если объект изображения не был передан if(info.pImage == nullptr){ // Создать вложение создавая изображение и выделяя память attachments_.emplace_back(vk::tools::Image( pDevice_, info.imageType, info.format, extent, info.usageFlags, info.aspectFlags, vk::MemoryPropertyFlagBits::eDeviceLocal, pDevice_->isPresentAndGfxQueueFamilySame() ? vk::SharingMode::eExclusive : vk::SharingMode::eConcurrent)); } // Если объект изображения был передан else{ attachments_.emplace_back(vk::tools::Image( pDevice_, *(info.pImage), info.imageType, info.format, info.aspectFlags)); } // Добавить image-view объект в массив attachmentsImageViews.push_back(attachments_.back().getImageView().get()); } // Создать объект кадрового буфера Vulkan vk::FramebufferCreateInfo frameBufferCreateInfo{}; frameBufferCreateInfo.renderPass = renderPass.get(); frameBufferCreateInfo.attachmentCount = attachmentsImageViews.size(); frameBufferCreateInfo.pAttachments = attachmentsImageViews.data(); frameBufferCreateInfo.width = extent_.width; frameBufferCreateInfo.height = extent_.height; frameBufferCreateInfo.layers = 1; frameBuffer_ = pDevice_->getLogicalDevice()->createFramebufferUnique(frameBufferCreateInfo); // Объект инициализирован isReady_ = true; } /** * Де-инициализация ресурсов Vulkan */ void destroyVulkanResources() { // Если объект инициализирован и устройство доступно if(isReady_ && pDevice_!= nullptr && pDevice_->isReady()) { // Очистка массива вложений (деструкторы объектов vk::tools::Image очистят ресурсы Vulkan) attachments_.clear(); // Удалить созданный объект кадрового буфера pDevice_->getLogicalDevice()->destroyFramebuffer(frameBuffer_.get()); frameBuffer_.release(); isReady_ = false; } } /** * Деструктор */ ~FrameBuffer() { destroyVulkanResources(); } /** * Получить разрешение * @return объект структуры Extent3D */ vk::Extent3D getExtent() const { return extent_; } /** * Получить кадровый буфер Vulkan * @return ссылка на unique smart pointer объекта буфера */ const vk::UniqueFramebuffer& getVulkanFrameBuffer() const { return frameBuffer_; } /** * Получить список объектов вложений * @return ссылка на массив изображений */ const std::vector<vk::tools::Image>& getAttachmentImages() const { return attachments_; } /** * Получить указатель на владеющее устройство * @return Константный указатель */ const vk::tools::Device* getOwnerDevice() const { return pDevice_; } }; } }
f269742d420ed212d971462a606b9ad7647e6f10
f22851ebe4ec1999c6b2942dae8672ddf65897f9
/src/TextConsole.h
08ff01e671c699afebb84277e20e35018a37a574
[ "MIT" ]
permissive
gaoyaoxin/WDict
759a3da6d2784bcc7cedde02aaee137ed8baa7b7
35bcf332343735865dfea908459c2114d2d256bf
refs/heads/master
2021-01-18T21:06:38.869560
2016-05-31T15:27:46
2016-05-31T15:27:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
616
h
TextConsole.h
#ifndef _TEXTCONSOLE_H_ #define _TEXTCONSOLE_H_ #include <libdict.h> #include <libui.h> #include <libtextdb.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include "WordConsole.h" #include "EvaluateStrategy.h" using namespace std; /// 文本分析器界面 class TextConsole : public ConsoleComponent { protected: /// 文件名、单词输入框 TextInputConsole txtFilename, txtWord; /// 文件名,单词 string filename; vector<string> Words; public: ///构造 TextConsole(Console &Root); bool Show() override; }; #endif // _TEXTCONSOLE_H_
8fc743f8842a1adf2018d53c3d57c20912fc636e
9badd534130eba5ab4fb63221822abdb933a7ee6
/DSnP/HW/HW1/b06901063_hw1/p2/p2Json.cpp
5405cbd6083b42c77d995bf502688d9aa68bfffe
[]
no_license
chris94137/ntuee_dsnp
6624bdc5ee17fe0acc72eddb44c013f8c684f491
245403957be25a2798274da20f0ff01ef9b696e2
refs/heads/master
2020-04-02T09:27:50.800107
2019-01-03T10:17:06
2019-01-03T10:17:06
154,293,943
0
0
null
null
null
null
UTF-8
C++
false
false
2,817
cpp
p2Json.cpp
/**************************************************************************** FileName [ p2Json.cpp ] PackageName [ p2 ] Synopsis [ Define member functions of class Json and JsonElem ] Author [ Chung-Yang (Ric) Huang ] Copyright [ Copyleft(c) 2018-present DVLab, GIEE, NTU, Taiwan ] ****************************************************************************/ #include <iostream> #include <string> #include <fstream> #include <iomanip> #include "p2Json.h" using namespace std; // Implement member functions of class Row and Table here bool Json::read(const string& JsonFile) { fstream file; file.open(JsonFile, fstream::in); if(!file.is_open()) return false; else { string trashstr; string readkey; int readvalue; while(1) { file >> trashstr; // first:{ , else:, if(trashstr == "}") break; file >> readkey; // key if(readkey == "}") break; file >> trashstr; // : file >> readvalue;// value readkey = readkey.substr(1, readkey.size() - 2); _obj.push_back(JsonElem(readkey, readvalue)); } } file.close(); return true; } ostream& operator << (ostream& os, const JsonElem& j) { return (os << "\"" << j._key << "\" : " << j._value); } bool Json::elemExist() { if(_obj.size() == 0) { cerr << "Error: No element found!!\n"; return false; } return true; } void Json::print() { cout << "{\n"; for(unsigned int i = 0; i < _obj.size(); i++) { cout << " " << _obj[i]; if(i != _obj.size() - 1) cout << ","; cout << endl; } cout << "}\n"; } int Json::getSum() { int sum = 0; for(unsigned int i = 0; i < _obj.size(); i++) sum += _obj[i].getValue(); return sum; } void Json::showSum() { if(elemExist()) cout << "The summation of the values is: " << getSum() << ".\n"; } void Json::showAve() { if(elemExist()) { double average = double(getSum())/double(_obj.size()); cout << "The average of the values is: " << fixed << setprecision(1) << average << ".\n"; } } void Json::showMax() { if(elemExist()) { string maxKey = _obj[0].getKey(); int maxValue = _obj[0].getValue(); for(unsigned int i = 0; i < _obj.size(); i++) if(maxValue < _obj[i].getValue()) { maxKey = _obj[i].getKey(); maxValue = _obj[i].getValue(); } cout << "The maximum element is: { \"" << maxKey << "\" : " << maxValue << " }.\n"; } } void Json::showMin() { if(elemExist()) { string minKey = _obj[0].getKey(); int minValue = _obj[0].getValue(); for(unsigned int i = 0; i < _obj.size(); i++) if(minValue > _obj[i].getValue()) { minKey = _obj[i].getKey(); minValue = _obj[i].getValue(); } cout << "The minimum element is: { \"" << minKey << "\" : " << minValue << " }.\n"; } } void Json::add(const string& newKey, const int& newValue) { _obj.push_back(JsonElem(newKey, newValue)); }
d1e460c997eec312d9049f6b57f061fac7685795
1917cc3414598031b02f6530a48af20ccc5dd2a6
/kodilib/src/handler/KKeyRecorder.h
988eda5b96c5a1af895544fa6f1a8159e67cdef8
[ "LicenseRef-scancode-warranty-disclaimer", "Unlicense" ]
permissive
Mistress-Anna/kiki
8cebcf4b7b737bb214bbea8908bbdc61bc325cb5
2f615044d72de6b3ca869e2230abdd0aced2aa00
refs/heads/master
2022-04-29T16:34:45.812039
2018-06-24T09:13:39
2020-01-04T23:38:22
42,407,357
2
1
Unlicense
2022-03-16T08:11:09
2015-09-13T18:23:04
C++
UTF-8
C++
false
false
699
h
KKeyRecorder.h
/* * KKeyRecorder.h * kodisein */ #ifndef __KKeyRecorder #define __KKeyRecorder #include "KKeyHandler.h" // -------------------------------------------------------------------------------------------------------- class KKeyRecorder : public KKeyHandler { INTROSPECTION protected: bool recording; std::string recorded_sequence; unsigned int num_recorded_keys; unsigned int max_num_recorded_keys; public: KKeyRecorder (); void startRecordingSequence ( KObject *, KSetStringPtr, int = 2 ); void stopRecording (); bool isRecording () const { return recording; } bool handleKey ( const KKey & ); }; #endif
db93a8e35f03cbb1dfbe6fe2bb22fb7c142e5a89
22d3b0f1eb297a15a4f42b8037b5ff50533737e8
/Practica4_Backtracking_B&B/grupal/tsp_B&B.cpp
222edd00a94fae044167155bd26d23c1f8603cb7
[ "MIT" ]
permissive
dcabezas98/Algoritmica
96584f23c4613e694ba9c6c12ee66ed331f11a2d
8abc2f63171815299bd9537940ce41b44bfd7482
refs/heads/master
2021-03-30T16:37:05.644584
2018-06-28T11:24:56
2018-06-28T11:24:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,538
cpp
tsp_B&B.cpp
// Requiere // ulimit -s unlimited // para funcionar #include <iostream> using namespace std; #include <vector> #include <cmath> #include <cassert> #include <algorithm> #include <fstream> #include <climits> #include <set> void printVector(vector<int> v){ for(int i = 0; i < v.size()-1; i++) cout << v[i] << ", "; cout << v.back() << endl; } void mostrarInfo(){ cerr << "Ejemplo: ./tsp ulysses16\n"; } struct node{ vector<int> visited; int bound; int currentWeight; bool operator<(node other) const { return bound < other.bound; } }; int prune(multiset<node> &s, int minimum){ static int pruned = 0; multiset<node>::iterator it; while(!s.empty() && (*s.rbegin()).bound >= minimum){ it = s.end(); --it; s.erase(it); pruned++; } return pruned; } class TSP{ private: int n; vector<vector<int>> map; public: vector<double> xCords, yCords; TSP(string file){ ifstream f(file); if(!f){ cerr << "Error de lectura del archivo " << file << endl; mostrarInfo(); exit(-1); } string trash; f >> trash; f >> n; int i, j; double c; //Leo los datos del fichero for(j = 0; j < n; j++){ f >> i; f >> c; xCords.push_back(c); f >> c; yCords.push_back(c); } f.close(); int distance; vector<vector<int>> aux(n); for(i = 1; i < n; i++){ for(j = 0; j < i; j++){ distance = (int) rint(sqrt(pow(xCords[i]-xCords[j],2) + pow((yCords[i]-yCords[j]),2))); aux[i].push_back(distance); } } map = aux; } int getN() const{ return n; } void printMap() const{ int i, j; for(i = 0; i < n; i++){ for(j = 0; j < i; j++){ cout << map[i][j] << "\t"; } cout << endl; } } int getDistance(int i, int j) const{ if(0 <= i && i < n && 0 <= j && j < n && i != j) return map[max(i,j)][min(i,j)]; return INT_MAX; // Para evitar considerar la distancia de una ciudad a sí misma } int totalWeight(vector<int> solution) const{ assert(solution.size() == n); int weight = 0; for(int i = 0; i < n; i++) weight += getDistance(solution[i],solution[(i-1+n)%n]); return weight; } // Devuelve la distancia de city a su ciudad más cercana int bestDistance(int city) const{ int minD = getDistance(city,0); for(int j = 1; j < n; j++) if(getDistance(city,j) < minD) minD = getDistance(city,j); return minD; } int weightBound(const vector<int> &visited, int currentWeight) const{ int bound = currentWeight; for(int i = 1; i < n; i++) if(find(visited.begin(),visited.end(),i)==visited.end()) bound += bestDistance(i); bound += bestDistance(visited.front()); return bound; } }; void BandB(const TSP& tsp, multiset<node> &alive_nodes, vector<int> &bestSol, int& minimumWeight, int &maxsize, int &expanded, int &pruned){ if(alive_nodes.size() > maxsize) maxsize = alive_nodes.size(); if(alive_nodes.empty()) return; node n = *alive_nodes.begin(); alive_nodes.erase(alive_nodes.begin()); if(n.bound >= minimumWeight) return; if(n.visited.size() == tsp.getN()){ n.currentWeight += tsp.getDistance(n.visited.front(), n.visited.back()); if(n.currentWeight < minimumWeight){ minimumWeight = n.currentWeight; bestSol = n.visited; pruned = prune(alive_nodes,minimumWeight); } BandB(tsp, alive_nodes, bestSol, minimumWeight, maxsize, expanded, pruned); } else { node aux; expanded++; for(int i = 1; i < tsp.getN(); i++){ if(find(n.visited.begin(), n.visited.end(), i) == n.visited.end()){ aux = n; aux.visited.push_back(i); aux.currentWeight += tsp.getDistance(i, n.visited.back()); aux.bound = tsp.weightBound(aux.visited, aux.currentWeight); alive_nodes.insert(aux); } } BandB(tsp, alive_nodes, bestSol, minimumWeight, maxsize, expanded, pruned); } } int main(int argc, char* argv[]){ if(argc < 2){ cerr << "Formato incorrecto\n"; mostrarInfo(); exit(-1); } string nombre_entrada(argv[1]); string nombre_salida(argv[1]); nombre_entrada="datosTSP/" + nombre_entrada + ".tsp"; nombre_salida="salidas/B&B/" + nombre_salida + "_solved.tsp"; TSP tsp(nombre_entrada); tsp.printMap(); cout << endl; vector<int> bestSol(tsp.getN()); vector<int> visited; clock_t t1, t2; t1 = clock(); for(int i = 0; i < tsp.getN(); i++) bestSol[i] = i; // Solución de referencia inicial int weight = tsp.totalWeight(bestSol); visited.push_back(0); node nod = {visited, 0, 0}; multiset<node> alive; alive.insert(nod); int maxsize = 0, expanded = 0, pruned = 0; BandB(tsp, alive, bestSol, weight, maxsize, expanded, pruned); t2 = clock(); cout << "Recorrido:\n"; printVector(bestSol); cout << "Peso total: " << weight << endl; cout << "Tamaño\ttiempo" << endl; cout << tsp.getN() << "\t" << (t2-t1)/(float)CLOCKS_PER_SEC << endl; cout << "Nodos expandidos: " << expanded << endl; cout << "Podas: " << alive.size()+pruned << endl; cout << "Tamaño máximo de la cola de nodos vivos: " << maxsize << endl; ofstream of(nombre_salida); if(!of){ cerr << "Error en la apertura de " << nombre_salida << endl; mostrarInfo(); exit(-1); } of << "DIMENSIÓN: " << tsp.getN() << endl; for(int i=0; i<tsp.getN(); i++) of << bestSol[i]+1 << " " << tsp.xCords[bestSol[i]] << " " << tsp.yCords[bestSol[i]] << endl; of.close(); }
d4f6c62f9149d6dd91b7f31bd659e99b474ae566
ea5609228135adcfddc179494d2e697fd7449fb7
/parse_arguments.cpp
9a870039c8229426190ab978834493b8800865cd
[]
no_license
nkyle04/progrom_assist
e1b114d74eec3a0dc477e48e2bbd7f6e4fb2bf29
7d209cf2aeeff2a9778bd17aefa5874bd22321b7
refs/heads/master
2021-01-21T19:12:21.707843
2017-06-06T03:06:28
2017-06-06T03:06:28
92,125,089
0
0
null
null
null
null
UTF-8
C++
false
false
1,498
cpp
parse_arguments.cpp
/*! * @file parse_arguments.cpp * @brief example for parse arguments */ #include <stdio.h> #include <string> #include <iostream> #include <unistd.h> #include "parse_arguments.h" namespace arguments { void print_usage() { std::cout << "\tUsage:" << std::endl << "\t\t-t\tnumber of threads." << std::endl << "\t\t-s\tsymbol file to be used." << std::endl << "\t\t-p\tparam file to be used." << std::endl << "\t\t-i\timages file to be predicted." << std::endl << "\t\t-l\tlabels file to be check result." << std::endl << "\t\t-h\tprint this usage." << std::endl << std::endl; } int parse_arguments(int argc, char* argv[], Arguments &args) { int opt = 0; while ((opt = getopt(argc, argv, "t:s:p:i:l:h")) != -1) { switch (opt) { case 't': args.thread_num = atoi(optarg); break; case 's': args.symbol_file = optarg; break; case 'p': args.params_file = optarg; break; case 'i': args.test_images_file = optarg; break; case 'l': args.test_labels_file = optarg; break; case 'h': print_usage(); return 0; default: print_usage(); return -1; } } return 0; } }
73497794be00d6ad28e9fa4f02de24edecac20a6
a0832d2f99103d4e0663656a088870c92876c538
/Object/Brdf/Phong.cpp
16bef3c2d30e5e07188c87cc193cf0f7311ba776
[]
no_license
mattfischer/raytrace
1c5225f28a34a9f4b02c18e1d9174992189fbf5b
b30e733678c71a827cce3ba34087b05df8a07a58
refs/heads/master
2023-08-17T07:45:32.527349
2023-07-30T03:17:59
2023-07-30T03:17:59
6,740,319
1
1
null
null
null
null
UTF-8
C++
false
false
2,399
cpp
Phong.cpp
#define _USE_MATH_DEFINES #include "Object/Brdf/Phong.hpp" #include "Math/Normal.hpp" #include "Math/Vector.hpp" #include "Math/OrthonormalBasis.hpp" #include <cmath> #include <algorithm> namespace Object { namespace Brdf { Phong::Phong(float strength, float power) { mStrength = strength; mPower = power; } Math::Color Phong::reflected(const Math::Vector &dirIn, const Math::Normal &nrm, const Math::Vector &dirOut, const Math::Color &) const { Math::Vector dirReflect = -(dirIn - Math::Vector(nrm) * (2 * (nrm * dirIn))); float dot = dirReflect * dirOut; float coeff = 0; if(dot > 0) { coeff = std::pow(dot, mPower); } return Math::Color(1, 1, 1) * mStrength * coeff * (mPower + 1) / (2 * (float)M_PI); } Math::Color Phong::transmitted(const Math::Vector &, const Math::Normal &, const Math::Color &) const { return Math::Color(1, 1, 1) * (1.0f - mStrength); } Math::Vector Phong::sample(Math::Sampler::Base &sampler, const Math::Normal &nrm, const Math::Vector &dirOut) const { Math::Point2D samplePoint = sampler.getValue2D(); float phi = 2 * M_PI * samplePoint.u(); float theta = std::acos(std::pow(samplePoint.v(), 1.0f / (mPower + 1))); Math::OrthonormalBasis basis(dirOut); Math::Vector dirReflect = basis.localToWorld(Math::Vector::fromPolar(phi, M_PI / 2 - theta, 1)); Math::Vector dirIn = -(dirReflect - Math::Vector(nrm) * (dirReflect * nrm * 2)); return dirIn; } float Phong::pdf(const Math::Vector &dirIn, const Math::Normal &nrm, const Math::Vector &dirOut) const { float coeff = 0; Math::Vector dirReflect = -(dirIn - Math::Vector(nrm) * (dirIn * nrm * 2)); float dot = dirReflect * dirOut; if (dot > 0) { coeff = std::pow(dot, mPower); } float pdf = coeff * (mPower + 1) / (2 * M_PI); return std::min(pdf, 1000.0f); } void Phong::writeProxy(BrdfProxy &proxy) const { proxy.type = BrdfProxy::Type::Phong; proxy.phong.strength = mStrength; proxy.phong.power = mPower; } } }
2b348668373c5a78a69596d8e783acda41f0d33c
cc6fc80b8b3f83816720faf52146b34ada6b88f2
/ComplexNumber.h
14591d0df3b57ce384f369c087df4d286f28d8de
[ "MIT" ]
permissive
jaojao1/number
83bfbca80e17f7b75400dda181f3e90688fa009e
fb31ffc60096b351ff747da72a449a23dd672648
refs/heads/master
2020-03-21T04:57:28.191046
2018-06-21T14:50:16
2018-06-21T14:50:16
138,136,389
0
0
null
null
null
null
UTF-8
C++
false
false
378
h
ComplexNumber.h
fndef ComplexNumber_h #define ComplexNumber_h #include"AbstractNumber.h" #include<iostream> using namespace std; class ComplexNumber :public AbstractNumber { public: ComplexNumber(double a, double b); ComplexNumber& add(const ComplexNumber&other); ComplexNumber& mul(const ComplexNumber&other); virtual void print(); private: double n1; double n2; }; #endif
6b1eee5ec68ec368b919a47f048d4a1b8ebe9171
e249448284216e9b696aa02fe9293ed7ae4eeefe
/src/network/degree_distribution/inc/power_law_degree_distribution.h
2de146f1b364c5e18d77415f7a960d19152bedf2
[]
no_license
shepherd92/inf_prop_simulator
5a6204b1a146bd064a0ec2a9ada9dd1e0cfb83a4
0df9a2e569196e972d6f59b8e8f9d5fef3f34d6f
refs/heads/master
2023-03-26T11:54:58.729581
2021-03-27T13:39:35
2021-03-27T13:39:35
259,058,361
0
0
null
null
null
null
UTF-8
C++
false
false
1,367
h
power_law_degree_distribution.h
#ifndef __POWER_LAW_DEGREE_DISTRIBUTION_H__ #define __POWER_LAW_DEGREE_DISTRIBUTION_H__ #include <random> #include "types.h" #include "int_degree_distribution.h" namespace simulator { class power_law_degree_distribution final : public int_degree_distribution { public: explicit power_law_degree_distribution(const degree kMin, const double parameter, const uint32_t numOfNodes, std::mt19937 &randomNumberGenerator); virtual void generate_distribution() override; virtual degree get_random_degree() const override; const degree_distribution_range &get_range() const; double get_parameter() const; const std::piecewise_constant_distribution<double> &get_distribution() const; power_law_degree_distribution (const power_law_degree_distribution&) = delete; power_law_degree_distribution& operator=(const power_law_degree_distribution&) = delete; power_law_degree_distribution& operator=(power_law_degree_distribution&&) = delete; private: degree calculate_k_max(const uint32_t numOfNodes); degree_distribution_range mRange; const double mParameter; mutable std::piecewise_constant_distribution<double> mDistribution; std::mt19937 &mRandomNumberGenerator; }; } // namespace simulator #endif
3d03a8ee885d3e043f485da8f00031b3cb49b48d
e1825eda73c111c85e07dceeab91b630475db07a
/2022/robot-firmwares/Motor_Test/lib/Grove_Motor_Driver_TB6612FNG/Grove_Motor_Driver_TB6612FNG.cpp
41d061ad86095430f7096c64864854abe032751e
[ "MIT" ]
permissive
venki666/CpE476_demos
e9c043d42c76cb28b806b037f7f2e5e0f25e4fca
f2863ab2752de242bca1a2dffd04d2544bf95ecb
refs/heads/master
2023-08-14T10:20:57.060908
2023-08-10T05:32:03
2023-08-10T05:32:03
211,710,922
0
2
null
null
null
null
UTF-8
C++
false
false
3,006
cpp
Grove_Motor_Driver_TB6612FNG.cpp
#include "Grove_Motor_Driver_TB6612FNG.h" MotorDriver::MotorDriver() { } void MotorDriver::init(uint8_t addr) { _addr = addr; standby(); } void MotorDriver::standby() { I2Cdev::writeByte(_addr, GROVE_MOTOR_DRIVER_I2C_CMD_STANDBY, 0); delay(1); } void MotorDriver::notStandby() { I2Cdev::writeByte(_addr, GROVE_MOTOR_DRIVER_I2C_CMD_NOT_STANDBY, 0); delay(1); } void MotorDriver::setI2cAddr(uint8_t addr) { if (addr == 0x00) { return; } else if (addr >= 0x80) { return; } I2Cdev::writeByte(_addr, GROVE_MOTOR_DRIVER_I2C_CMD_SET_ADDR, addr); _addr = addr; delay(100); } void MotorDriver::dcMotorRun(motor_channel_type_t chl, int16_t speed) { if (speed > 255) { speed = 255; } else if (speed < -255) { speed = -255; } if (speed >= 0) { _buffer[0] = GROVE_MOTOR_DRIVER_I2C_CMD_CW; } else { _buffer[0] = GROVE_MOTOR_DRIVER_I2C_CMD_CCW; } _buffer[1] = chl; if (speed >= 0) { _buffer[2] = speed; } else { _buffer[2] = (uint8_t)(-speed); } I2Cdev::writeBytes(_addr, _buffer[0], 2, _buffer + 1); delay(1); } void MotorDriver::dcMotorBrake(motor_channel_type_t chl) { I2Cdev::writeByte(_addr, GROVE_MOTOR_DRIVER_I2C_CMD_BRAKE, chl); delay(1); } void MotorDriver::dcMotorStop(motor_channel_type_t chl) { I2Cdev::writeByte(_addr, GROVE_MOTOR_DRIVER_I2C_CMD_STOP, chl); delay(1); } void MotorDriver::stepperRun(stepper_mode_type_t mode, int16_t steps, uint16_t rpm) { uint8_t cw = 0; // 0.1ms_per_step uint16_t ms_per_step = 0; if (steps > 0) { cw = 1; } // stop else if (steps == 0) { stepperStop(); return; } else if (steps == -32768) { steps = 32767; } else { steps = -steps; } if (rpm < 1) { rpm = 1; } else if (rpm > 300) { rpm = 300; } ms_per_step = (uint16_t)(3000.0 / (float)rpm); _buffer[0] = mode; _buffer[1] = cw; //(cw=1) => cw; (cw=0) => ccw _buffer[2] = steps; _buffer[3] = (steps >> 8); _buffer[4] = ms_per_step; _buffer[5] = (ms_per_step >> 8); I2Cdev::writeBytes(_addr, GROVE_MOTOR_DRIVER_I2C_CMD_STEPPER_RUN, 6, _buffer); delay(1); } void MotorDriver::stepperStop() { I2Cdev::writeByte(_addr, GROVE_MOTOR_DRIVER_I2C_CMD_STEPPER_STOP, 0); delay(1); } void MotorDriver::stepperKeepRun(stepper_mode_type_t mode, uint16_t rpm, bool is_cw) { // 4=>infinite ccw 5=>infinite cw uint8_t cw = (is_cw) ? 5 : 4; // 0.1ms_per_step uint16_t ms_per_step = 0; if (rpm < 1) { rpm = 1; } else if (rpm > 300) { rpm = 300; } ms_per_step = (uint16_t)(3000.0 / (float)rpm); _buffer[0] = mode; _buffer[1] = cw; //(cw=1) => cw; (cw=0) => ccw _buffer[2] = ms_per_step; _buffer[3] = (ms_per_step >> 8); I2Cdev::writeBytes(_addr, GROVE_MOTOR_DRIVER_I2C_CMD_STEPPER_KEEP_RUN, 4, _buffer); delay(1); }
effa0187a56c2827c8f0687b4953fe6e5017f7b4
ac86d0ed6d2a48bc3333cf9369f045bab30e77a0
/7-reverseinteger.cpp
ad5b1e32738f2afe835300381788e4d19f7d7d00
[]
no_license
jasonliu19/LeetCodeSolutions
ecbfe28702e5f6a3ae25447e818a07f70f3700a4
0ebea729c8726f9dd1231ad68e64559c6f5b447b
refs/heads/master
2021-09-07T22:21:05.450019
2018-03-02T02:49:19
2018-03-02T02:49:19
119,224,087
0
0
null
null
null
null
UTF-8
C++
false
false
353
cpp
7-reverseinteger.cpp
class Solution { public: int reverse(int x) { int reversed = 0; while(x!=0){ int temp = reversed*10; if((temp)/10 != reversed) return 0; reversed= temp + x%10; x/=10; } return reversed; } };
a851dafbe9f465929e95f0e2800a6c422c6bc582
acfc42e160b51343673a45c348ecdfd0b1ebabb9
/codeforces/1600~1699/1633/c.cc
f529795fda8c6b1f2e7b8b57c135a4a762463f86
[]
no_license
kiddos/notes
3209237921cd52600a07b62202661898a56cbed1
4ef828b94ef235b43be0840f735e2f23616847fc
refs/heads/master
2023-09-01T01:46:38.987675
2023-08-19T14:05:46
2023-08-19T14:05:46
80,524,342
0
1
null
null
null
null
UTF-8
C++
false
false
776
cc
c.cc
#include <bits/stdc++.h> using namespace std; typedef long long LONG; bool can_win(LONG hc, LONG dc, LONG hm, LONG dm) { return (hc + dm - 1) / dm >= (hm + dc - 1) / dc; } bool solve(LONG hc, LONG dc, LONG hm, LONG dm, LONG k, LONG w, LONG a) { if (dc > hm) return true; for (int i = 0; i <= k; ++i) { if (can_win(hc + i * a, dc + (k-i) * w, hm, dm)) return true; } return false; } int main(void) { ios::sync_with_stdio(false); cin.tie(0); int T = 0; cin >> T; for (int t = 0; t < T; ++t) { LONG hc = 0, dc = 0, hm = 0, dm = 0, k = 0, w = 0, a = 0; cin >> hc >> dc >> hm >> dm >> k >> w >> a; bool ans = solve(hc, dc, hm, dm, k, w, a); if (ans) cout << "YES\n"; else cout << "NO\n"; } cout << flush << endl; return 0; }
4ee61896c362a595e93090c132d8f3b22b645dc9
c08a26d662bd1df1b2beaa36a36d0e9fecc1ebac
/classicui_plat/options_menu_api/inc/EIKMENUP.H
1867d3fdc81a31a86bf2eee2f193c7cf4417ff6f
[]
no_license
SymbianSource/oss.FCL.sf.mw.classicui
9c2e2c31023256126bb2e502e49225d5c58017fe
dcea899751dfa099dcca7a5508cf32eab64afa7a
refs/heads/master
2021-01-11T02:38:59.198728
2010-10-08T14:24:02
2010-10-08T14:24:02
70,943,916
1
0
null
null
null
null
WINDOWS-1250
C++
false
false
35,173
h
EIKMENUP.H
/* * Copyright (c) 1997-1999 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: * */ #if !defined(__EIKMENUP_H__) #define __EIKMENUP_H__ #if !defined(__EIKBCTRL_H__) #include <eikbctrl.h> #endif #if !defined(__EIKDEF_H__) #include <eikdef.h> #endif #if !defined(__EIKSBOBS_H__) #include <eiksbobs.h> // for TEikScrollEvent #endif #include <bidi.h> // FORWARD DECLARATIONS class MEikMenuObserver; class CEikHotKeyTable; class CEikMenuPaneTitle; class CEikButtonBase; class CEikScrollBarFrame; class CEikScrollBar; class TEikScrollBarModel; class CGulIcon; class CEikMenuPaneExtension ; class CEikCba; class CAknItemActionMenuData; // CONSTANTS const TInt KScaleableTextSeparator = 0x0001; /** * A helper class for extending CEikMenuPaneItem without breaking binary * compability. */ class CExtendedItemData : public CBase { public: /** * Destructor. */ ~CExtendedItemData(); public: /** Two packaked bitmaps: bitmap icon and mask for it. */ CGulIcon* iIcon; /** Scalable text buffer. */ HBufC* iScaleableText; }; /** * The @c CEikMenuPaneItem class encapsulates the data needed to define a menu * pane item and provides some of the functionality required to display the * item. * * @since ER5U */ class CEikMenuPaneItem : public CBase { public: /** Struct to menu pane item. */ struct SData { /** Nominal text length.*/ enum { ENominalTextLength=40 }; /** * ID of the command to issue when the menu item using this @c SData is * selected. */ TInt iCommandId; /** Resource ID of a menu pane to cascade from this item. */ TInt iCascadeId; /** * Flags used internally by @c CEikMenuPane and accessible through * functions such as @c CEikMenuPane::SetItemDimmed(). */ TInt iFlags; /** The text buffer displayed in the main area of the menu item. */ TBuf<ENominalTextLength> iText; // less than this actually stored /** * Additional descriptive text about the item. This is used by @c * CEikMenuPane to display hotkey names. */ TBuf<1> iExtraText; }; public: /** * C++ default constructor. */ IMPORT_C CEikMenuPaneItem(); /** * Destructor. */ IMPORT_C ~CEikMenuPaneItem(); /** * Sets a menu item icon. This replaces any icon already set for the menu * item. * * @param aIcon Menu item icon consisting of a picture bitmap and a mask * bitmap. */ IMPORT_C void SetIcon(CGulIcon* aIcon); /** * Draws the menu item icon. * * @param aGc Graphics context to which the icon is drawn. * @param aRect Rectangle in which the icon is drawn. * @param aDimmed If @c ETrue the icon is drawn dimmed. * @param aBitmapSpaceRequired Length of one side of the square required to * contain the bitmap. */ IMPORT_C void DrawItemIcon(CWindowGc& aGc, TRect aRect, TBool aDimmed, TInt aBitmapSpaceRequired) const; /** * Construct an icon from bitmaps. * * Constructs a new icon for the menu item, taking ownership of the picture * bitmap aBitmap and the mask bitmap aMask unless the bitmaps are * externally owned. * * @param aBitmap Picture bitmap. * @param aMask Mask bitmap. */ IMPORT_C void CreateIconL(CFbsBitmap* aBitmap, CFbsBitmap* aMask); /** * Gets a pointer to the menu item's icon picture bitmap. This does not * imply transfer of ownership. * * @return Picture bitmap. */ IMPORT_C CFbsBitmap* IconBitmap() const; /** * Gets a pointer to the menu item's icon mask bitmap. This does not imply * transfer of ownership. * * @return Mask bitmap. */ IMPORT_C CFbsBitmap* IconMask() const; /** * Sets icon bitmap ownership. * Sets the menu item's icon bitmaps as externally owned if @c * aOwnedExternally is @c ETrue. * * @param aOwnedExternally If @c ETrue bitmaps are set as externally owned. * @c If EFalse bitmaps are set as not being externally owned. */ IMPORT_C void SetBitmapsOwnedExternally(TBool aOwnedExternally); /** * Sets the picture bitmap. Transfers ownership unless the bitmaps are * already owned externally. * * @param aBitmap Picture bitmap. */ IMPORT_C void SetIconBitmapL(CFbsBitmap* aBitmap); /** * Sets the mask bitmap. Transfers ownership unless the bitmaps are already * owned externally. * * @param aMask Mask bitmap. */ IMPORT_C void SetIconMaskL(CFbsBitmap* aMask); /** * Returns scaleable text. If there isn't scaleable text available then * this method returns @c iData.iText. * * @return Pointer to TPtrC object that contains scaleable text. */ IMPORT_C TPtrC ScaleableText() const; /** * Sets scaleable text. @c iData.iText is set to first text version. * * @param aText Scalable text. */ IMPORT_C void SetScaleableTextL(const TDesC& aText); private: inline void CreateExtendedDataBlock(); inline TBool IsScaleableText(const TDesC& aText) const; TPtrC GetNominalText(const TDesC& aText); public: /** The y position of the menu pane item. */ TInt iPos; /** The menu pane item's hotkey text. */ TInt iHotKeyCode; /** Information from an SData struct. */ SData iData; private: CExtendedItemData* iExtendedData; }; inline void CEikMenuPaneItem::CreateExtendedDataBlock() { if (!iExtendedData) { TRAPD(err, ( iExtendedData = new (ELeave) CExtendedItemData() ) ); } } inline TBool CEikMenuPaneItem::IsScaleableText(const TDesC& aText) const { return aText.Locate( TChar( KScaleableTextSeparator ) ) != KErrNotFound; } /** * Menu panes are opened by activating the menu title * @c (CEikMenuPaneTitle / MENU_TITLE) which is displayed in the menu bar @c * (CEikMenuBar / MENU_BAR). They can also be cascaded from a menu item @c * (CEikMenuPaneItem / MENU_ITEM) or launched by a menu button @c * (CEikMenuButton). * * Menu panes may be defined using a @c MENU_PANE resource. */ class CEikMenuPane : public CEikBorderedControl { private: enum {ENothingSelected=-1}; class CMenuScroller; friend class CMenuScroller; friend class CEikMenuPaneExtension; public: /** The text to be displayed for a hotkey. */ typedef TBuf<20> THotKeyDisplayText; public: /** * This class provides a constructor to create an array of menu pane items * and a destructor to destroy an array of menu pane items. */ class CItemArray:public CArrayPtrFlat<CEikMenuPaneItem> { public: /** * C++ default constructor that creates a flat array of menu pane * items. */ IMPORT_C CItemArray(); /** * Destructor. */ IMPORT_C ~CItemArray(); /** * Appends @c CEikMenuPaneItem class object to array. * * @param aMenuItem The menu item to add. */ IMPORT_C void AddItemL(CEikMenuPaneItem* aMenuItem); }; public: /** * Destructor. */ IMPORT_C ~CEikMenuPane(); /** * C++ default constructor. Constructs a menu pane object with the * specified observer. * * @param aMenuObserver Menu observer. */ IMPORT_C CEikMenuPane(MEikMenuObserver* aMenuObserver); /** * Handles 2nd base construction. Completes construction of a menu pane object. * * @param aOwner Menu pane owner ( for cascade menu ). * @param aEditMenuObserver Observer for the edit menu. In default this is * @c NULL. */ IMPORT_C void ConstructL(CEikMenuPane* aOwner, MEikMenuObserver* aEditMenuObserver = NULL); /** * Destroys the menu pane's item array. */ IMPORT_C void Reset(); public: // framework /** * From @c CcoeControl. * * Handles key events offered to the menu by the control environment and * provides an appropriate implementation of @c * CCoeControl::OfferKeyEventL(). * * @param aKeyEvent The key event. * @param aType The type of key event: @c EEventKey, @c EEventKeyUp or @c * EEventKeyDown. */ IMPORT_C TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType); /** * From @c CcoeControl. * * Handles a pointer event on the menu. * * @param aPointerEvent The pointer event to handle. */ IMPORT_C void HandlePointerEventL(const TPointerEvent& aPointerEvent); /** * From @c CcoeControl. * * Gets the list of logical colours employed in the drawing of the control, * paired with an explanation of how they are used. Appends the list into * @c aColorUseList. * * @since 005u * @param aColorUseList The list of colours paired with explanations. */ IMPORT_C virtual void GetColorUseListL( CArrayFix<TCoeColorUse>& aColorUseList) const; /** * From @c CcoeControl. * * Handles a change to the menu's resources which are shared across the * environment. For example, colours or fonts. * * @since 005u * @param aType The type of resource that has changed. */ IMPORT_C virtual void HandleResourceChange(TInt aType); // not available before Release 005u private: // from base class /** * Not implemented. * * @param Not used. * @return NULL */ IMPORT_C void* ExtensionInterface( TUid aInterface ); public: // from MCoeInputObserver /** * From @c CCoeControl. * * Gets the list box’s input capabilities as set through the list box flags. * * @return List box input capabilities. */ IMPORT_C TCoeInputCapabilities InputCapabilities() const; protected: // from base class /** * From @c CCoeControl * * Draw a control called by window server. * * All controls, except blank controls, should implement this function. The * default implementation draws a blank control. This function is used for * window server-initiated redrawing of controls, and for some * application-initiated drawing. It should be implemented by each control, * but is only called from within @c CCoeControl's member functions, and * not from the derived class. For this reason it is a private member * function of @c CCoeControl. * * The rectangle aRect indicates the region of the control that needs to be * redrawn. The implementation of @c Draw() must always draw to every pixel * within this rectangle. * * @param aRect The region of the control to be redrawn. * Co-ordinates are relative to the control's origin (top left * corner). Optional, not used currently. */ IMPORT_C void Draw(const TRect& aRect) const; /** * From @c CCoeControl. * * Takes any action required when the menu pane gains or loses focus, * to change its appearance for example. * * @param aDrawNow If @c EDrawNow the menu pane is redrawn. If @c * ENoDrawNow the menu pane is not redrawn. */ IMPORT_C void FocusChanged(TDrawNow aDrawNow); /** * From @c CCoeControl. * * Constructs the menu pane using the specified resource reader. * Fills the menu item array with the list of menu items provided by the * resource file. * * @param aReader The resource reader to use. * @leave KErrNoMemory Memory allocation failure earlier construction. */ IMPORT_C void ConstructFromResourceL(TResourceReader& aReader); public: // new functions /** * Adds a menu item dynamically by creating a new menu item, setting its * data to @c aMenuItem and appending it to the pane's menu item array. * Updates the menu's scroll bar to take account of the new item. * * @param aMenuItem The menu item to add. * NOTICE that @c SData is a structure so all fields in it should be * set to avoid any unexpected behaviour. */ IMPORT_C void AddMenuItemL(const CEikMenuPaneItem::SData& aMenuItem); /** * Adds a menu item dynamically by creating a new menu item, setting its * data to @c aMenuItem and inserting it into the pane's menu item array. * Updates the menu's scroll bar to take account of the new item. * * @param aMenuItem The menu item to add. NOTICE that @c SData is a * structure so all fields in it should be set to avoid any * unexpected behaviour. * @param aPreviousId The id of the item after which the new item should be * added. */ IMPORT_C void AddMenuItemL(const CEikMenuPaneItem::SData& aMenuItem, TInt aPreviousId); /** * Adds menu items dynamically by creating new menu items from resource * and inserts them into the pane's menu item array. * * @param aResourceId The ID of the resource for the menu item. * @param aPreviousId The ID of the previous menu item, after which this * newly created item should be added. * @param aAddSeperator Shouldn't be used as separator is not not supported * anymore. */ IMPORT_C void AddMenuItemsL(TInt aResourceId, TInt aPreviousId = 0, TBool aAddSeperator = EFalse); /** * Deletes the specified item in the menu pane. * * @param aCommandId The ID for the item to be deleted. */ IMPORT_C void DeleteMenuItem(TInt aCommandId); /** * Deletes the items between specified items. * * @param aStartIndex The index of the item after which items should be * deleted. * @param aEndIndex The index of the item up to which items should be * deleted. */ IMPORT_C void DeleteBetweenMenuItems(TInt aStartIndex, TInt aEndIndex); /** * Gets a reference to the data in the specified menu item. * * @param aCommandId The command ID of the menu item for which data is * obtained. * @return Reference to struct that contains command id. */ IMPORT_C CEikMenuPaneItem::SData& ItemData(TInt aCommandId); /** * Gets a pointer to the specified menu item. Also gets the position of the * item within the menu pane. Panics if there are no menu items in the menu * pane. Panics if the menu pane id does not identify any menu pane item in * the array. * * @param aCommandId The ID of the menu item for which a pointer is * returned. * @param aPos On return, the position of the menu item with an ID of * aCommandId. * @return A pointer to the menu item. * @panic EEikPanicNoSuchMenuItem Panics if there are no menu items in the * menu pane or if the menu pane id does not * identify any menu pane item in the array. */ IMPORT_C CEikMenuPaneItem* ItemAndPos(TInt aCommandId,TInt& aPos); /** * Displays the menu pane with the corner identified by @c aTargetType in * the position specified by @c aTargetPos. This function uses @c * aMinTitleWidth to calculate the area required to display the menu pane, * taking into account whether the menu is a cascading menu or popup menu. * * @param aHotKeyTable Optional hotkey table. * @param aTargetPos Position of the corner of the menu pane identified by * @c aTargetType. * @param aMenuPaneTitle The menu pane's title. * @param aMinWidth Minimum width of the menu's title. * @param aTargetType The corner of the menu pane to which @c aTargetPos * relates. The default is the top left corner. Possible: @c * EPopupTargetTopLeft, @c EPopupTargetTopRight, * @cEPopupTargetBottomLeft, @c EPopupTargetBottomRight. */ IMPORT_C void StartDisplayingMenuPane( const CEikHotKeyTable* aHotKeyTable, const TPoint& aTargetPos, const CEikMenuPaneTitle* aMenuPaneTitle, TInt aMinWidth, TPopupTargetPosType aTargetType = EPopupTargetTopLeft); /** * Sets the text in a menu item. * * @param aCommandId The command (as defined in an .hrh file) associated * with this menu item. This identifies the menu item whose text is * to be set. * @param aDes New item text. */ IMPORT_C void SetItemTextL(TInt aCommandId, const TDesC& aDes); /** * Sets the text in a menu item from resource. * * @param aCommandId The command (as defined in an .hrh file) associated * with this menu item. This identifies the menu item whose text is * to be set. * @param aRid The resource ID of the menu item text. */ IMPORT_C void SetItemTextL(TInt aCommandId, TInt aRid); /** * Dims (greys out) or undims a menu item. Dimming indicates that user * input is not accepted. * * @param aCommandId The command (as defined in an .hrh file) associated * with this menu item. This identifies the menu item whose text is * to be dimmed or un-dimmed. * @param aDimmed @c ETrue to dim this menu item. @c EFalse to un-dim this * menu item. */ IMPORT_C void SetItemDimmed(TInt aCommandId, TBool aDimmed); /** * Sets the item to be indicated or not. It should be used to change the * state of radio buttons or check box items. It has real effect only * starting from S60 v3.0. * * @param aCommandId The command (as defined in an .hrh file) associated * with this menu item. This identifies the menu item for which the * state is set or unset. * @param aButtonState should be @c EEikMenuItemSymbolOn or @c * EEikMenuItemSymbolIndeterminate */ IMPORT_C void SetItemButtonState(TInt aCommandId, TInt aButtonState); /** * Sets the selected menu item. * * @param aSelectedItem The index of the item to get selected */ IMPORT_C void SetSelectedItem(TInt aSelectedItem); /** * Gets the position of the selected menu item. * * @return The position of the selected menu item. */ IMPORT_C TInt SelectedItem() const; /** * Closes and destroys any current cascade menu and takes focus back. Does * nothing if no cascade menu exists. */ IMPORT_C void CloseCascadeMenu(); /** * Sets the array containing the list of menu items for the current menu * pane. * * @param aItemArray The menu item array for the menu pane. */ IMPORT_C void SetItemArray(CItemArray* aItemArray); /** * Set menu item array ownership. * * @param aOwnedExternally If @c ETrue the menu pane's menu item array is * set as externally owned. If @c EFalse the menu pane's menu item * array is set as not externally owned. */ IMPORT_C void SetItemArrayOwnedExternally(TBool aOwnedExternally); /** * Sets the specified button to launch the menu pane. Doesn't have any * effect in current implementation. * * @param aButton The button to set as launching the menu. */ IMPORT_C void SetLaunchingButton(CEikButtonBase* aButton); /** * Moves the menu pane highlight to a newly selected menu item identified * by @c aNewSelectedItem. Scrolls the menu to show the new selected item * if necessary and redraws only the newly selected item and the currently * selected item if possible. * * @param aNewSelectedItem The newly selected menu item index. */ IMPORT_C void MoveHighlightTo(TInt aNewSelectedItem); /** * Gets the number of menu items within the menu pane. * * @return Number of menu items within menu pane. */ IMPORT_C TInt NumberOfItemsInPane() const; /** * Closes the menu pane. */ IMPORT_C void Close(); /** * From @ CCoeControl * * Handles key events offered to the menu by the control environment. * * @since Platform 004. * @param aKeyEvent The key event. * @param aType The type of key event: @c EEventKey, @c EEventKeyUp or @c * EEventKeyDown. * @param aConsumeAllKeys If @c ETrue this function returns @c * EKeyWasConsumed regardless of whether it was used. If @c EFalse * the key event is consumed if possible and either @c * EKeyWasConsumed or @c EKeyWasNotConsumed is returned as * appropriate. */ IMPORT_C TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType, TBool aConsumeAllKeys); // not available before Platform 004 /** * Sets whether the scroll bar occupies the left side of the menu pane. * * @param aOnLeft If @c ETrue the scroll bar will occupy the left side of * the menu pane. */ IMPORT_C void SetScrollBarOnLeft(TBool aOnLeft); /** * Sets whether the menu pane uses an arrow head scroll bar. * * @param aArrowHead If @c ETrue the menu pane uses an arrow head scroll * bar. */ IMPORT_C void SetArrowHeadScrollBar(TBool aArrowHead); // new for AVKON /** * Moves highlight to the next item or to the first one if last item is * selected. */ IMPORT_C void NavigateToNextItem(); /** * Inserts the menu item to the specified position. * * @param aMenuItem The menu item to add. NOTICE @c SData is the structure * and all fileds should be initialized. * @param aPosition The position of newly created item in the array. */ IMPORT_C void InsertMenuItemL(const CEikMenuPaneItem::SData& aMenuItem, TInt aPosition); /** * Checks whether menu pane contains the menu item and returns position of * it if the item is found. * * @param[in] aCommandId The command ID of the item to be searched for. * @param[out] aPosition On return contains position of the item. * @return @c ETrue if item was found. Otherwise @c EFalse. */ IMPORT_C TBool MenuItemExists(TInt aCommandId, TInt& aPosition); /** * Checks whether the menu pane is a cascade menu or a main menu. * * @return @c ETrue if the menu pane is cascade menu and @c EFalse if the * menu pane is the main menu. */ IMPORT_C TBool IsCascadeMenuPane() const; /** * Enables or disables text scrolling functionality. It is disabled by * default. * * @param aEnable @c ETrue to enable text scrolling functionality. */ IMPORT_C void EnableMarqueeL(const TBool aEnable); /** * Report that selection was done for the currently highlighted item. */ void ActivateCurrentItemL(); /** * Closes cascade menu if there is one and it is active. */ TBool CancelActiveMenuPane(); /** * Deletes dimmed items from the menu item array. */ void FilterDimmedItems(); /** * Gets the menu pane for the cascade menu. * * @return The menu pane for the cascade menu. */ IMPORT_C CEikMenuPane* CascadeMenuPane(); /** * Gets a reference to the data in the specified menu item. * * @since S60 3.1 * @param aItemIndex The index of the item in the items array. * @return The menu item's data. * @leave KErrArgument Wrong @aItemIndex. */ IMPORT_C CEikMenuPaneItem::SData& ItemDataByIndexL(TInt aItemIndex); /** * Creates and enables a special characters row to be used in the edit * menu. * * @since S60 3.1 * @param aSpecialChars Buffer that holds the selected characters after * user has selected them. */ IMPORT_C void ConstructMenuSctRowL( TDes& aSpecialChars ); /** * Returns the command id of the specified menu item. The function panics * if aIndex doesn't exist or is out of range. * @param aIndex The index of the menu item for which the command ID is returned. * @since 3.1 */ IMPORT_C TInt MenuItemCommandId( TInt aIndex ) const; /** * Creates and enables a special characters row to be used in the edit menu. * The special character row is constructed from the given special character table. * * @param aSpecialChars Buffer that holds the selected characters after * user has selected them. * @param aResourceId The special character table resource id to define the * characters in the row. * * @since S60 3.1 */ IMPORT_C void ConstructMenuSctRowL( TDes& aSpecialChars, TInt aResourceId ); /** * Creates and enables a special characters row to be used in the edit menu. * The special character row is constructed from the given special character dialog. * * @param aSpecialChars Buffer that holds the selected characters after * user has selected them. * @param aResourceId The special character dialog resource id that contains a special character table * * @since S60 3.2 */ IMPORT_C void ConstructMenuSctRowFromDialogL( TDes& aSpecialChars, TInt aResourceId ); /** * Creates and enables a special characters row to be used in the edit menu. * The special character row is constructed from the given special character dialog. * * @param aCharCase the charcase used by menu sct * @param aSpecialChars Buffer that holds the selected characters after * user has selected them. * @param aResourceId The special character dialog resource id that contains a special character table * * @since S60 3.2 */ IMPORT_C void ConstructMenuSctRowFromDialogL( TInt aCharCase, TDes& aSpecialChars, TInt aResourceId ); /** * Sets menu item as item specific command. * * @param aCommandId The command associated with this menu item. * @param aItemSpecific ETrue to define the menu item item specific, * EFalse otherwise. */ IMPORT_C void SetItemSpecific( TInt aCommandId, TBool aItemSpecific ); /** * Sets the embedded cba to options menu * * @param aCba Cba to embed to menu * * @since S60 v5.2 */ void SetEmbeddedCba( CEikCba* aCba ); /** * Closes and destroys any current cascade menu and takes focus back. Does * nothing if no cascade menu exists. * * @param aMainMenuClosing ETrue if main menu is also to be closed. */ void CloseCascadeMenu( TBool aMainMenuClosing ); /** * Symbian two-phased constructor for menu panes that are created for * item specific menus. * * @internal * @since S60 v5.2 * @return Created menu pane. Ownership transfers to caller. */ static CEikMenuPane* NewItemCommandMenuL( MEikMenuObserver* aObserver ); /** * Sets item specific commands dimmed. * * @internal * @since S60 v5.2 */ void SetItemCommandsDimmed(); /** * Adds menu items to this menu and item action menu data. * * @internal * @since S60 v5.2 * @param aMenuData Item action menu data. */ void AddMenuItemsToItemActionMenuL( CAknItemActionMenuData& aMenuData ); /** * Adds cascade menu items to item action menu data. * * @internal * @since S60 v5.2 * @param aCascadeId Cascade menu id. * @param aItemSpecific If ETrue, adds only item specific items. * @param aMenuData Item action menu data. */ void AddCascadeMenuItemsToActionMenuL( TInt aCascadeId, TBool aItemSpecific, CAknItemActionMenuData& aMenuData ); /** * Enables the default highlight in menu */ void SetDefaultHighlight(); private: enum { EInvalidCurrentSize=0x01, EBackgroundFaded=0x02 }; private: // new functions TRect CalculateSizeAndPosition() ; enum THighlightType {ENoHighlight,EDrawHighlight,ERemoveHighlight}; void DrawItem( TInt aItem, THighlightType aHighlight ) const; void DrawItem(CWindowGc& aGc,TInt aItem, THighlightType aHighlight) const; void ReportSelectionMadeL( TBool aAbortTransition = ETrue ); void ReportCanceled(); void LaunchCascadeMenuL(TInt aCascadeMenuId); void DoLaunchCascadeMenuL(TInt aCascadeMenuId); void TryLaunchCascadeMenuL(const CEikMenuPaneItem& aItem); void PrepareGcForDrawingItems(CGraphicsContext& aGc) const; TBool ItemArrayOwnedExternally() const; TBool IsHotKeyL(const TInt modifiers,const TInt aCode); TBool MoveToItemL(TInt aCode, TInt aModifiers); void HandleScrollEventL(CEikScrollBar* aScrollBar,TEikScrollEvent aEventType); void CreateScrollBarFrame(); void UpdateScrollBar(); void DoUpdateScrollBarL(); void UpdateScrollBarThumbs(); static TInt UpdateScrollBarCallBackL(TAny* aObj); TRect ViewRect() const; TInt TotalItemHeight() const; void ScrollToMakeItemVisible(TInt aItemIndex); void Scroll(TInt aAmount); TBool CheckCreateScroller(); void CheckCreateScrollerL(); void ResetItemArray(); void CreateItemArrayL(); void CreateIconFromResourceL(TResourceReader& aReader, CEikMenuPaneItem& aItem) const; // Skin support for menu void UpdateBackgroundContext(const TRect& aWindowRect); // Support method for highlight animation void RepaintHighlight() const; private: // from CCoeControl IMPORT_C void Reserved_1(); IMPORT_C void Reserved_2(); private : // new functions void LoadCascadeBitmapL() ; // Support for check mark, from v3.0 void LoadCheckMarkBitmapL(); TBool MenuHasCheckBoxOn() const; // Support for radio button, from v3.0 void LoadRadioButtonBitmapL(); TBool IsItemMemberOfRadioButtonGroup(TInt aItem) const ; // for drawing,from v3.0 TBool MenuHasIcon() const; TRect CalculateSizeAndPositionScalable( const TRect& aWindowRect, TInt aNumItemsInPane ) ; TRect HighlightRect() const; void PrepareHighlightFrame() const; void SetCascadedIconSize() const; // fixes marquee flickering friend class CAknMarqueeControl; CEikMenuPaneExtension* Extension() const; /** * Creates menu pane's extension object if it doesn't exist yet. */ void CheckCreateExtensionL(); protected: // from CoeControl /** * From @c CCoeControl. * * Retrieves an object of the same type as that encapsulated in aId. Other * than in the case where @c NULL is returned, the object returned must be * of the same object type - that is, the @c ETypeId member of the object * pointed to by the pointer returned by this function must be equal to the * @c iUid member of @c aId. * * @since SDK 7.0s * @param aId An encapsulated object type ID. * @return Encapsulates the pointer to the object provided. Note that the * encapsulated pointer may be @c NULL. */ IMPORT_C TTypeUid::Ptr MopSupplyObject(TTypeUid aId); public: // From CoeControl. /** * From @c CoeControl. * * Gets the number of controls contained in a compound control. This * function should be implemented by all compound controls. * * Note: * In SDK 6.1 this was changed from protected to public. * * @return The number of component controls contained by this control. */ IMPORT_C TInt CountComponentControls() const; /** * From @c CoeControl. * * Gets the specified component of a compound control. This function should? * be implemented by all compound controls. * * Note: * Within a compound control, each component control is identified by an * index, where the index depends on the order the controls were added: the * first is given an index of 0, the next an index of 1, and so on. * * @param[in, out] aIndex The index of the control to get. * @return The component control with an index of @c aIndex. */ IMPORT_C CCoeControl* ComponentControl(TInt aIndex) const; protected: // new functions /** * Gets the maximum number of items which can be seen simultaneously. * * @return The maximum number of items which can be seen simultaneously. */ TInt NumberOfItemsThatFitInView() const; private: // data friend class CEikMenuButton; MEikMenuObserver* iMenuObserver; MEikMenuObserver* iEditMenuObserver; CEikMenuPane* iCascadeMenuPane; const CEikMenuPaneTitle* iMenuPaneTitle; const CEikHotKeyTable* iHotKeyTable; CEikMenuPane* iOwner; CItemArray* iItemArray; TBool iArrayOwnedExternally; TBool iAllowPointerUpEvents; TInt iNumberOfDragEvents; TInt iSelectedItem; TInt iItemHeight; TInt iBaseLine; TInt iHotkeyColWidth; TInt iFlags; CEikScrollBarFrame* iSBFrame; CMenuScroller* iScroller; CEikButtonBase* iLaunchingButton; // for popouts only TInt iSubPopupWidth; // 0..2 TInt iSpare; CEikMenuPaneExtension* iExtension ; }; #endif
e25851c32b87f955f45ec7a4b3868e9d54a02d40
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-codebuild/include/aws/codebuild/CodeBuildClient.h
810c4562c46fe73cc78ab00694856afd77c10959
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
75,251
h
CodeBuildClient.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/codebuild/CodeBuild_EXPORTS.h> #include <aws/core/client/ClientConfiguration.h> #include <aws/core/client/AWSClient.h> #include <aws/core/client/AWSClientAsyncCRTP.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/codebuild/CodeBuildServiceClientModel.h> namespace Aws { namespace CodeBuild { /** * <fullname>CodeBuild</fullname> <p>CodeBuild is a fully managed build service in * the cloud. CodeBuild compiles your source code, runs unit tests, and produces * artifacts that are ready to deploy. CodeBuild eliminates the need to provision, * manage, and scale your own build servers. It provides prepackaged build * environments for the most popular programming languages and build tools, such as * Apache Maven, Gradle, and more. You can also fully customize build environments * in CodeBuild to use your own build tools. CodeBuild scales automatically to meet * peak build requests. You pay only for the build time you consume. For more * information about CodeBuild, see the <i> <a * href="https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html">CodeBuild * User Guide</a>.</i> </p> */ class AWS_CODEBUILD_API CodeBuildClient : public Aws::Client::AWSJsonClient, public Aws::Client::ClientWithAsyncTemplateMethods<CodeBuildClient> { public: typedef Aws::Client::AWSJsonClient BASECLASS; static const char* SERVICE_NAME; static const char* ALLOCATION_TAG; typedef CodeBuildClientConfiguration ClientConfigurationType; typedef CodeBuildEndpointProvider EndpointProviderType; /** * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ CodeBuildClient(const Aws::CodeBuild::CodeBuildClientConfiguration& clientConfiguration = Aws::CodeBuild::CodeBuildClientConfiguration(), std::shared_ptr<CodeBuildEndpointProviderBase> endpointProvider = Aws::MakeShared<CodeBuildEndpointProvider>(ALLOCATION_TAG)); /** * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ CodeBuildClient(const Aws::Auth::AWSCredentials& credentials, std::shared_ptr<CodeBuildEndpointProviderBase> endpointProvider = Aws::MakeShared<CodeBuildEndpointProvider>(ALLOCATION_TAG), const Aws::CodeBuild::CodeBuildClientConfiguration& clientConfiguration = Aws::CodeBuild::CodeBuildClientConfiguration()); /** * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied, * the default http client factory will be used */ CodeBuildClient(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider, std::shared_ptr<CodeBuildEndpointProviderBase> endpointProvider = Aws::MakeShared<CodeBuildEndpointProvider>(ALLOCATION_TAG), const Aws::CodeBuild::CodeBuildClientConfiguration& clientConfiguration = Aws::CodeBuild::CodeBuildClientConfiguration()); /* Legacy constructors due deprecation */ /** * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ CodeBuildClient(const Aws::Client::ClientConfiguration& clientConfiguration); /** * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ CodeBuildClient(const Aws::Auth::AWSCredentials& credentials, const Aws::Client::ClientConfiguration& clientConfiguration); /** * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied, * the default http client factory will be used */ CodeBuildClient(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider, const Aws::Client::ClientConfiguration& clientConfiguration); /* End of legacy constructors due deprecation */ virtual ~CodeBuildClient(); /** * <p>Deletes one or more builds.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchDeleteBuilds">AWS * API Reference</a></p> */ virtual Model::BatchDeleteBuildsOutcome BatchDeleteBuilds(const Model::BatchDeleteBuildsRequest& request) const; /** * A Callable wrapper for BatchDeleteBuilds that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename BatchDeleteBuildsRequestT = Model::BatchDeleteBuildsRequest> Model::BatchDeleteBuildsOutcomeCallable BatchDeleteBuildsCallable(const BatchDeleteBuildsRequestT& request) const { return SubmitCallable(&CodeBuildClient::BatchDeleteBuilds, request); } /** * An Async wrapper for BatchDeleteBuilds that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename BatchDeleteBuildsRequestT = Model::BatchDeleteBuildsRequest> void BatchDeleteBuildsAsync(const BatchDeleteBuildsRequestT& request, const BatchDeleteBuildsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::BatchDeleteBuilds, request, handler, context); } /** * <p>Retrieves information about one or more batch builds.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuildBatches">AWS * API Reference</a></p> */ virtual Model::BatchGetBuildBatchesOutcome BatchGetBuildBatches(const Model::BatchGetBuildBatchesRequest& request) const; /** * A Callable wrapper for BatchGetBuildBatches that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename BatchGetBuildBatchesRequestT = Model::BatchGetBuildBatchesRequest> Model::BatchGetBuildBatchesOutcomeCallable BatchGetBuildBatchesCallable(const BatchGetBuildBatchesRequestT& request) const { return SubmitCallable(&CodeBuildClient::BatchGetBuildBatches, request); } /** * An Async wrapper for BatchGetBuildBatches that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename BatchGetBuildBatchesRequestT = Model::BatchGetBuildBatchesRequest> void BatchGetBuildBatchesAsync(const BatchGetBuildBatchesRequestT& request, const BatchGetBuildBatchesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::BatchGetBuildBatches, request, handler, context); } /** * <p>Gets information about one or more builds.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuilds">AWS * API Reference</a></p> */ virtual Model::BatchGetBuildsOutcome BatchGetBuilds(const Model::BatchGetBuildsRequest& request) const; /** * A Callable wrapper for BatchGetBuilds that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename BatchGetBuildsRequestT = Model::BatchGetBuildsRequest> Model::BatchGetBuildsOutcomeCallable BatchGetBuildsCallable(const BatchGetBuildsRequestT& request) const { return SubmitCallable(&CodeBuildClient::BatchGetBuilds, request); } /** * An Async wrapper for BatchGetBuilds that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename BatchGetBuildsRequestT = Model::BatchGetBuildsRequest> void BatchGetBuildsAsync(const BatchGetBuildsRequestT& request, const BatchGetBuildsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::BatchGetBuilds, request, handler, context); } /** * <p>Gets information about one or more build projects.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetProjects">AWS * API Reference</a></p> */ virtual Model::BatchGetProjectsOutcome BatchGetProjects(const Model::BatchGetProjectsRequest& request) const; /** * A Callable wrapper for BatchGetProjects that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename BatchGetProjectsRequestT = Model::BatchGetProjectsRequest> Model::BatchGetProjectsOutcomeCallable BatchGetProjectsCallable(const BatchGetProjectsRequestT& request) const { return SubmitCallable(&CodeBuildClient::BatchGetProjects, request); } /** * An Async wrapper for BatchGetProjects that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename BatchGetProjectsRequestT = Model::BatchGetProjectsRequest> void BatchGetProjectsAsync(const BatchGetProjectsRequestT& request, const BatchGetProjectsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::BatchGetProjects, request, handler, context); } /** * <p> Returns an array of report groups. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetReportGroups">AWS * API Reference</a></p> */ virtual Model::BatchGetReportGroupsOutcome BatchGetReportGroups(const Model::BatchGetReportGroupsRequest& request) const; /** * A Callable wrapper for BatchGetReportGroups that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename BatchGetReportGroupsRequestT = Model::BatchGetReportGroupsRequest> Model::BatchGetReportGroupsOutcomeCallable BatchGetReportGroupsCallable(const BatchGetReportGroupsRequestT& request) const { return SubmitCallable(&CodeBuildClient::BatchGetReportGroups, request); } /** * An Async wrapper for BatchGetReportGroups that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename BatchGetReportGroupsRequestT = Model::BatchGetReportGroupsRequest> void BatchGetReportGroupsAsync(const BatchGetReportGroupsRequestT& request, const BatchGetReportGroupsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::BatchGetReportGroups, request, handler, context); } /** * <p> Returns an array of reports. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetReports">AWS * API Reference</a></p> */ virtual Model::BatchGetReportsOutcome BatchGetReports(const Model::BatchGetReportsRequest& request) const; /** * A Callable wrapper for BatchGetReports that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename BatchGetReportsRequestT = Model::BatchGetReportsRequest> Model::BatchGetReportsOutcomeCallable BatchGetReportsCallable(const BatchGetReportsRequestT& request) const { return SubmitCallable(&CodeBuildClient::BatchGetReports, request); } /** * An Async wrapper for BatchGetReports that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename BatchGetReportsRequestT = Model::BatchGetReportsRequest> void BatchGetReportsAsync(const BatchGetReportsRequestT& request, const BatchGetReportsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::BatchGetReports, request, handler, context); } /** * <p>Creates a build project.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateProject">AWS * API Reference</a></p> */ virtual Model::CreateProjectOutcome CreateProject(const Model::CreateProjectRequest& request) const; /** * A Callable wrapper for CreateProject that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename CreateProjectRequestT = Model::CreateProjectRequest> Model::CreateProjectOutcomeCallable CreateProjectCallable(const CreateProjectRequestT& request) const { return SubmitCallable(&CodeBuildClient::CreateProject, request); } /** * An Async wrapper for CreateProject that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename CreateProjectRequestT = Model::CreateProjectRequest> void CreateProjectAsync(const CreateProjectRequestT& request, const CreateProjectResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::CreateProject, request, handler, context); } /** * <p> Creates a report group. A report group contains a collection of reports. * </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateReportGroup">AWS * API Reference</a></p> */ virtual Model::CreateReportGroupOutcome CreateReportGroup(const Model::CreateReportGroupRequest& request) const; /** * A Callable wrapper for CreateReportGroup that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename CreateReportGroupRequestT = Model::CreateReportGroupRequest> Model::CreateReportGroupOutcomeCallable CreateReportGroupCallable(const CreateReportGroupRequestT& request) const { return SubmitCallable(&CodeBuildClient::CreateReportGroup, request); } /** * An Async wrapper for CreateReportGroup that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename CreateReportGroupRequestT = Model::CreateReportGroupRequest> void CreateReportGroupAsync(const CreateReportGroupRequestT& request, const CreateReportGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::CreateReportGroup, request, handler, context); } /** * <p>For an existing CodeBuild build project that has its source code stored in a * GitHub or Bitbucket repository, enables CodeBuild to start rebuilding the source * code every time a code change is pushed to the repository.</p> <p>If * you enable webhooks for an CodeBuild project, and the project is used as a build * step in CodePipeline, then two identical builds are created for each commit. One * build is triggered through webhooks, and one through CodePipeline. Because * billing is on a per-build basis, you are billed for both builds. Therefore, if * you are using CodePipeline, we recommend that you disable webhooks in CodeBuild. * In the CodeBuild console, clear the Webhook box. For more information, see step * 5 in <a * href="https://docs.aws.amazon.com/codebuild/latest/userguide/change-project.html#change-project-console">Change * a Build Project's Settings</a>.</p> <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateWebhook">AWS * API Reference</a></p> */ virtual Model::CreateWebhookOutcome CreateWebhook(const Model::CreateWebhookRequest& request) const; /** * A Callable wrapper for CreateWebhook that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename CreateWebhookRequestT = Model::CreateWebhookRequest> Model::CreateWebhookOutcomeCallable CreateWebhookCallable(const CreateWebhookRequestT& request) const { return SubmitCallable(&CodeBuildClient::CreateWebhook, request); } /** * An Async wrapper for CreateWebhook that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename CreateWebhookRequestT = Model::CreateWebhookRequest> void CreateWebhookAsync(const CreateWebhookRequestT& request, const CreateWebhookResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::CreateWebhook, request, handler, context); } /** * <p>Deletes a batch build.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteBuildBatch">AWS * API Reference</a></p> */ virtual Model::DeleteBuildBatchOutcome DeleteBuildBatch(const Model::DeleteBuildBatchRequest& request) const; /** * A Callable wrapper for DeleteBuildBatch that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename DeleteBuildBatchRequestT = Model::DeleteBuildBatchRequest> Model::DeleteBuildBatchOutcomeCallable DeleteBuildBatchCallable(const DeleteBuildBatchRequestT& request) const { return SubmitCallable(&CodeBuildClient::DeleteBuildBatch, request); } /** * An Async wrapper for DeleteBuildBatch that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename DeleteBuildBatchRequestT = Model::DeleteBuildBatchRequest> void DeleteBuildBatchAsync(const DeleteBuildBatchRequestT& request, const DeleteBuildBatchResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::DeleteBuildBatch, request, handler, context); } /** * <p> Deletes a build project. When you delete a project, its builds are not * deleted. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteProject">AWS * API Reference</a></p> */ virtual Model::DeleteProjectOutcome DeleteProject(const Model::DeleteProjectRequest& request) const; /** * A Callable wrapper for DeleteProject that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename DeleteProjectRequestT = Model::DeleteProjectRequest> Model::DeleteProjectOutcomeCallable DeleteProjectCallable(const DeleteProjectRequestT& request) const { return SubmitCallable(&CodeBuildClient::DeleteProject, request); } /** * An Async wrapper for DeleteProject that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename DeleteProjectRequestT = Model::DeleteProjectRequest> void DeleteProjectAsync(const DeleteProjectRequestT& request, const DeleteProjectResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::DeleteProject, request, handler, context); } /** * <p> Deletes a report. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteReport">AWS * API Reference</a></p> */ virtual Model::DeleteReportOutcome DeleteReport(const Model::DeleteReportRequest& request) const; /** * A Callable wrapper for DeleteReport that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename DeleteReportRequestT = Model::DeleteReportRequest> Model::DeleteReportOutcomeCallable DeleteReportCallable(const DeleteReportRequestT& request) const { return SubmitCallable(&CodeBuildClient::DeleteReport, request); } /** * An Async wrapper for DeleteReport that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename DeleteReportRequestT = Model::DeleteReportRequest> void DeleteReportAsync(const DeleteReportRequestT& request, const DeleteReportResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::DeleteReport, request, handler, context); } /** * <p>Deletes a report group. Before you delete a report group, you must delete its * reports. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteReportGroup">AWS * API Reference</a></p> */ virtual Model::DeleteReportGroupOutcome DeleteReportGroup(const Model::DeleteReportGroupRequest& request) const; /** * A Callable wrapper for DeleteReportGroup that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename DeleteReportGroupRequestT = Model::DeleteReportGroupRequest> Model::DeleteReportGroupOutcomeCallable DeleteReportGroupCallable(const DeleteReportGroupRequestT& request) const { return SubmitCallable(&CodeBuildClient::DeleteReportGroup, request); } /** * An Async wrapper for DeleteReportGroup that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename DeleteReportGroupRequestT = Model::DeleteReportGroupRequest> void DeleteReportGroupAsync(const DeleteReportGroupRequestT& request, const DeleteReportGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::DeleteReportGroup, request, handler, context); } /** * <p> Deletes a resource policy that is identified by its resource ARN. * </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteResourcePolicy">AWS * API Reference</a></p> */ virtual Model::DeleteResourcePolicyOutcome DeleteResourcePolicy(const Model::DeleteResourcePolicyRequest& request) const; /** * A Callable wrapper for DeleteResourcePolicy that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename DeleteResourcePolicyRequestT = Model::DeleteResourcePolicyRequest> Model::DeleteResourcePolicyOutcomeCallable DeleteResourcePolicyCallable(const DeleteResourcePolicyRequestT& request) const { return SubmitCallable(&CodeBuildClient::DeleteResourcePolicy, request); } /** * An Async wrapper for DeleteResourcePolicy that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename DeleteResourcePolicyRequestT = Model::DeleteResourcePolicyRequest> void DeleteResourcePolicyAsync(const DeleteResourcePolicyRequestT& request, const DeleteResourcePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::DeleteResourcePolicy, request, handler, context); } /** * <p> Deletes a set of GitHub, GitHub Enterprise, or Bitbucket source credentials. * </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteSourceCredentials">AWS * API Reference</a></p> */ virtual Model::DeleteSourceCredentialsOutcome DeleteSourceCredentials(const Model::DeleteSourceCredentialsRequest& request) const; /** * A Callable wrapper for DeleteSourceCredentials that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename DeleteSourceCredentialsRequestT = Model::DeleteSourceCredentialsRequest> Model::DeleteSourceCredentialsOutcomeCallable DeleteSourceCredentialsCallable(const DeleteSourceCredentialsRequestT& request) const { return SubmitCallable(&CodeBuildClient::DeleteSourceCredentials, request); } /** * An Async wrapper for DeleteSourceCredentials that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename DeleteSourceCredentialsRequestT = Model::DeleteSourceCredentialsRequest> void DeleteSourceCredentialsAsync(const DeleteSourceCredentialsRequestT& request, const DeleteSourceCredentialsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::DeleteSourceCredentials, request, handler, context); } /** * <p>For an existing CodeBuild build project that has its source code stored in a * GitHub or Bitbucket repository, stops CodeBuild from rebuilding the source code * every time a code change is pushed to the repository.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteWebhook">AWS * API Reference</a></p> */ virtual Model::DeleteWebhookOutcome DeleteWebhook(const Model::DeleteWebhookRequest& request) const; /** * A Callable wrapper for DeleteWebhook that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename DeleteWebhookRequestT = Model::DeleteWebhookRequest> Model::DeleteWebhookOutcomeCallable DeleteWebhookCallable(const DeleteWebhookRequestT& request) const { return SubmitCallable(&CodeBuildClient::DeleteWebhook, request); } /** * An Async wrapper for DeleteWebhook that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename DeleteWebhookRequestT = Model::DeleteWebhookRequest> void DeleteWebhookAsync(const DeleteWebhookRequestT& request, const DeleteWebhookResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::DeleteWebhook, request, handler, context); } /** * <p>Retrieves one or more code coverage reports.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DescribeCodeCoverages">AWS * API Reference</a></p> */ virtual Model::DescribeCodeCoveragesOutcome DescribeCodeCoverages(const Model::DescribeCodeCoveragesRequest& request) const; /** * A Callable wrapper for DescribeCodeCoverages that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename DescribeCodeCoveragesRequestT = Model::DescribeCodeCoveragesRequest> Model::DescribeCodeCoveragesOutcomeCallable DescribeCodeCoveragesCallable(const DescribeCodeCoveragesRequestT& request) const { return SubmitCallable(&CodeBuildClient::DescribeCodeCoverages, request); } /** * An Async wrapper for DescribeCodeCoverages that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename DescribeCodeCoveragesRequestT = Model::DescribeCodeCoveragesRequest> void DescribeCodeCoveragesAsync(const DescribeCodeCoveragesRequestT& request, const DescribeCodeCoveragesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::DescribeCodeCoverages, request, handler, context); } /** * <p> Returns a list of details about test cases for a report. </p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DescribeTestCases">AWS * API Reference</a></p> */ virtual Model::DescribeTestCasesOutcome DescribeTestCases(const Model::DescribeTestCasesRequest& request) const; /** * A Callable wrapper for DescribeTestCases that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename DescribeTestCasesRequestT = Model::DescribeTestCasesRequest> Model::DescribeTestCasesOutcomeCallable DescribeTestCasesCallable(const DescribeTestCasesRequestT& request) const { return SubmitCallable(&CodeBuildClient::DescribeTestCases, request); } /** * An Async wrapper for DescribeTestCases that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename DescribeTestCasesRequestT = Model::DescribeTestCasesRequest> void DescribeTestCasesAsync(const DescribeTestCasesRequestT& request, const DescribeTestCasesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::DescribeTestCases, request, handler, context); } /** * <p>Analyzes and accumulates test report values for the specified test * reports.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/GetReportGroupTrend">AWS * API Reference</a></p> */ virtual Model::GetReportGroupTrendOutcome GetReportGroupTrend(const Model::GetReportGroupTrendRequest& request) const; /** * A Callable wrapper for GetReportGroupTrend that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename GetReportGroupTrendRequestT = Model::GetReportGroupTrendRequest> Model::GetReportGroupTrendOutcomeCallable GetReportGroupTrendCallable(const GetReportGroupTrendRequestT& request) const { return SubmitCallable(&CodeBuildClient::GetReportGroupTrend, request); } /** * An Async wrapper for GetReportGroupTrend that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename GetReportGroupTrendRequestT = Model::GetReportGroupTrendRequest> void GetReportGroupTrendAsync(const GetReportGroupTrendRequestT& request, const GetReportGroupTrendResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::GetReportGroupTrend, request, handler, context); } /** * <p> Gets a resource policy that is identified by its resource ARN. * </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/GetResourcePolicy">AWS * API Reference</a></p> */ virtual Model::GetResourcePolicyOutcome GetResourcePolicy(const Model::GetResourcePolicyRequest& request) const; /** * A Callable wrapper for GetResourcePolicy that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename GetResourcePolicyRequestT = Model::GetResourcePolicyRequest> Model::GetResourcePolicyOutcomeCallable GetResourcePolicyCallable(const GetResourcePolicyRequestT& request) const { return SubmitCallable(&CodeBuildClient::GetResourcePolicy, request); } /** * An Async wrapper for GetResourcePolicy that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename GetResourcePolicyRequestT = Model::GetResourcePolicyRequest> void GetResourcePolicyAsync(const GetResourcePolicyRequestT& request, const GetResourcePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::GetResourcePolicy, request, handler, context); } /** * <p> Imports the source repository credentials for an CodeBuild project that has * its source code stored in a GitHub, GitHub Enterprise, or Bitbucket repository. * </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ImportSourceCredentials">AWS * API Reference</a></p> */ virtual Model::ImportSourceCredentialsOutcome ImportSourceCredentials(const Model::ImportSourceCredentialsRequest& request) const; /** * A Callable wrapper for ImportSourceCredentials that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ImportSourceCredentialsRequestT = Model::ImportSourceCredentialsRequest> Model::ImportSourceCredentialsOutcomeCallable ImportSourceCredentialsCallable(const ImportSourceCredentialsRequestT& request) const { return SubmitCallable(&CodeBuildClient::ImportSourceCredentials, request); } /** * An Async wrapper for ImportSourceCredentials that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ImportSourceCredentialsRequestT = Model::ImportSourceCredentialsRequest> void ImportSourceCredentialsAsync(const ImportSourceCredentialsRequestT& request, const ImportSourceCredentialsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ImportSourceCredentials, request, handler, context); } /** * <p>Resets the cache for a project.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/InvalidateProjectCache">AWS * API Reference</a></p> */ virtual Model::InvalidateProjectCacheOutcome InvalidateProjectCache(const Model::InvalidateProjectCacheRequest& request) const; /** * A Callable wrapper for InvalidateProjectCache that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename InvalidateProjectCacheRequestT = Model::InvalidateProjectCacheRequest> Model::InvalidateProjectCacheOutcomeCallable InvalidateProjectCacheCallable(const InvalidateProjectCacheRequestT& request) const { return SubmitCallable(&CodeBuildClient::InvalidateProjectCache, request); } /** * An Async wrapper for InvalidateProjectCache that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename InvalidateProjectCacheRequestT = Model::InvalidateProjectCacheRequest> void InvalidateProjectCacheAsync(const InvalidateProjectCacheRequestT& request, const InvalidateProjectCacheResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::InvalidateProjectCache, request, handler, context); } /** * <p>Retrieves the identifiers of your build batches in the current * region.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatches">AWS * API Reference</a></p> */ virtual Model::ListBuildBatchesOutcome ListBuildBatches(const Model::ListBuildBatchesRequest& request) const; /** * A Callable wrapper for ListBuildBatches that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListBuildBatchesRequestT = Model::ListBuildBatchesRequest> Model::ListBuildBatchesOutcomeCallable ListBuildBatchesCallable(const ListBuildBatchesRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListBuildBatches, request); } /** * An Async wrapper for ListBuildBatches that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListBuildBatchesRequestT = Model::ListBuildBatchesRequest> void ListBuildBatchesAsync(const ListBuildBatchesRequestT& request, const ListBuildBatchesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListBuildBatches, request, handler, context); } /** * <p>Retrieves the identifiers of the build batches for a specific * project.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatchesForProject">AWS * API Reference</a></p> */ virtual Model::ListBuildBatchesForProjectOutcome ListBuildBatchesForProject(const Model::ListBuildBatchesForProjectRequest& request) const; /** * A Callable wrapper for ListBuildBatchesForProject that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListBuildBatchesForProjectRequestT = Model::ListBuildBatchesForProjectRequest> Model::ListBuildBatchesForProjectOutcomeCallable ListBuildBatchesForProjectCallable(const ListBuildBatchesForProjectRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListBuildBatchesForProject, request); } /** * An Async wrapper for ListBuildBatchesForProject that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListBuildBatchesForProjectRequestT = Model::ListBuildBatchesForProjectRequest> void ListBuildBatchesForProjectAsync(const ListBuildBatchesForProjectRequestT& request, const ListBuildBatchesForProjectResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListBuildBatchesForProject, request, handler, context); } /** * <p>Gets a list of build IDs, with each build ID representing a single * build.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuilds">AWS * API Reference</a></p> */ virtual Model::ListBuildsOutcome ListBuilds(const Model::ListBuildsRequest& request) const; /** * A Callable wrapper for ListBuilds that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListBuildsRequestT = Model::ListBuildsRequest> Model::ListBuildsOutcomeCallable ListBuildsCallable(const ListBuildsRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListBuilds, request); } /** * An Async wrapper for ListBuilds that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListBuildsRequestT = Model::ListBuildsRequest> void ListBuildsAsync(const ListBuildsRequestT& request, const ListBuildsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListBuilds, request, handler, context); } /** * <p>Gets a list of build identifiers for the specified build project, with each * build identifier representing a single build.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildsForProject">AWS * API Reference</a></p> */ virtual Model::ListBuildsForProjectOutcome ListBuildsForProject(const Model::ListBuildsForProjectRequest& request) const; /** * A Callable wrapper for ListBuildsForProject that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListBuildsForProjectRequestT = Model::ListBuildsForProjectRequest> Model::ListBuildsForProjectOutcomeCallable ListBuildsForProjectCallable(const ListBuildsForProjectRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListBuildsForProject, request); } /** * An Async wrapper for ListBuildsForProject that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListBuildsForProjectRequestT = Model::ListBuildsForProjectRequest> void ListBuildsForProjectAsync(const ListBuildsForProjectRequestT& request, const ListBuildsForProjectResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListBuildsForProject, request, handler, context); } /** * <p>Gets information about Docker images that are managed by * CodeBuild.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListCuratedEnvironmentImages">AWS * API Reference</a></p> */ virtual Model::ListCuratedEnvironmentImagesOutcome ListCuratedEnvironmentImages(const Model::ListCuratedEnvironmentImagesRequest& request) const; /** * A Callable wrapper for ListCuratedEnvironmentImages that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListCuratedEnvironmentImagesRequestT = Model::ListCuratedEnvironmentImagesRequest> Model::ListCuratedEnvironmentImagesOutcomeCallable ListCuratedEnvironmentImagesCallable(const ListCuratedEnvironmentImagesRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListCuratedEnvironmentImages, request); } /** * An Async wrapper for ListCuratedEnvironmentImages that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListCuratedEnvironmentImagesRequestT = Model::ListCuratedEnvironmentImagesRequest> void ListCuratedEnvironmentImagesAsync(const ListCuratedEnvironmentImagesRequestT& request, const ListCuratedEnvironmentImagesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListCuratedEnvironmentImages, request, handler, context); } /** * <p>Gets a list of build project names, with each build project name representing * a single build project.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListProjects">AWS * API Reference</a></p> */ virtual Model::ListProjectsOutcome ListProjects(const Model::ListProjectsRequest& request) const; /** * A Callable wrapper for ListProjects that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListProjectsRequestT = Model::ListProjectsRequest> Model::ListProjectsOutcomeCallable ListProjectsCallable(const ListProjectsRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListProjects, request); } /** * An Async wrapper for ListProjects that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListProjectsRequestT = Model::ListProjectsRequest> void ListProjectsAsync(const ListProjectsRequestT& request, const ListProjectsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListProjects, request, handler, context); } /** * <p> Gets a list ARNs for the report groups in the current Amazon Web Services * account. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListReportGroups">AWS * API Reference</a></p> */ virtual Model::ListReportGroupsOutcome ListReportGroups(const Model::ListReportGroupsRequest& request) const; /** * A Callable wrapper for ListReportGroups that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListReportGroupsRequestT = Model::ListReportGroupsRequest> Model::ListReportGroupsOutcomeCallable ListReportGroupsCallable(const ListReportGroupsRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListReportGroups, request); } /** * An Async wrapper for ListReportGroups that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListReportGroupsRequestT = Model::ListReportGroupsRequest> void ListReportGroupsAsync(const ListReportGroupsRequestT& request, const ListReportGroupsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListReportGroups, request, handler, context); } /** * <p> Returns a list of ARNs for the reports in the current Amazon Web Services * account. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListReports">AWS * API Reference</a></p> */ virtual Model::ListReportsOutcome ListReports(const Model::ListReportsRequest& request) const; /** * A Callable wrapper for ListReports that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListReportsRequestT = Model::ListReportsRequest> Model::ListReportsOutcomeCallable ListReportsCallable(const ListReportsRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListReports, request); } /** * An Async wrapper for ListReports that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListReportsRequestT = Model::ListReportsRequest> void ListReportsAsync(const ListReportsRequestT& request, const ListReportsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListReports, request, handler, context); } /** * <p> Returns a list of ARNs for the reports that belong to a * <code>ReportGroup</code>. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListReportsForReportGroup">AWS * API Reference</a></p> */ virtual Model::ListReportsForReportGroupOutcome ListReportsForReportGroup(const Model::ListReportsForReportGroupRequest& request) const; /** * A Callable wrapper for ListReportsForReportGroup that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListReportsForReportGroupRequestT = Model::ListReportsForReportGroupRequest> Model::ListReportsForReportGroupOutcomeCallable ListReportsForReportGroupCallable(const ListReportsForReportGroupRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListReportsForReportGroup, request); } /** * An Async wrapper for ListReportsForReportGroup that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListReportsForReportGroupRequestT = Model::ListReportsForReportGroupRequest> void ListReportsForReportGroupAsync(const ListReportsForReportGroupRequestT& request, const ListReportsForReportGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListReportsForReportGroup, request, handler, context); } /** * <p> Gets a list of projects that are shared with other Amazon Web Services * accounts or users. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSharedProjects">AWS * API Reference</a></p> */ virtual Model::ListSharedProjectsOutcome ListSharedProjects(const Model::ListSharedProjectsRequest& request) const; /** * A Callable wrapper for ListSharedProjects that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListSharedProjectsRequestT = Model::ListSharedProjectsRequest> Model::ListSharedProjectsOutcomeCallable ListSharedProjectsCallable(const ListSharedProjectsRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListSharedProjects, request); } /** * An Async wrapper for ListSharedProjects that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListSharedProjectsRequestT = Model::ListSharedProjectsRequest> void ListSharedProjectsAsync(const ListSharedProjectsRequestT& request, const ListSharedProjectsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListSharedProjects, request, handler, context); } /** * <p> Gets a list of report groups that are shared with other Amazon Web Services * accounts or users. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSharedReportGroups">AWS * API Reference</a></p> */ virtual Model::ListSharedReportGroupsOutcome ListSharedReportGroups(const Model::ListSharedReportGroupsRequest& request) const; /** * A Callable wrapper for ListSharedReportGroups that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListSharedReportGroupsRequestT = Model::ListSharedReportGroupsRequest> Model::ListSharedReportGroupsOutcomeCallable ListSharedReportGroupsCallable(const ListSharedReportGroupsRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListSharedReportGroups, request); } /** * An Async wrapper for ListSharedReportGroups that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListSharedReportGroupsRequestT = Model::ListSharedReportGroupsRequest> void ListSharedReportGroupsAsync(const ListSharedReportGroupsRequestT& request, const ListSharedReportGroupsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListSharedReportGroups, request, handler, context); } /** * <p> Returns a list of <code>SourceCredentialsInfo</code> objects. </p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSourceCredentials">AWS * API Reference</a></p> */ virtual Model::ListSourceCredentialsOutcome ListSourceCredentials(const Model::ListSourceCredentialsRequest& request) const; /** * A Callable wrapper for ListSourceCredentials that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename ListSourceCredentialsRequestT = Model::ListSourceCredentialsRequest> Model::ListSourceCredentialsOutcomeCallable ListSourceCredentialsCallable(const ListSourceCredentialsRequestT& request) const { return SubmitCallable(&CodeBuildClient::ListSourceCredentials, request); } /** * An Async wrapper for ListSourceCredentials that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename ListSourceCredentialsRequestT = Model::ListSourceCredentialsRequest> void ListSourceCredentialsAsync(const ListSourceCredentialsRequestT& request, const ListSourceCredentialsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::ListSourceCredentials, request, handler, context); } /** * <p> Stores a resource policy for the ARN of a <code>Project</code> or * <code>ReportGroup</code> object. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/PutResourcePolicy">AWS * API Reference</a></p> */ virtual Model::PutResourcePolicyOutcome PutResourcePolicy(const Model::PutResourcePolicyRequest& request) const; /** * A Callable wrapper for PutResourcePolicy that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename PutResourcePolicyRequestT = Model::PutResourcePolicyRequest> Model::PutResourcePolicyOutcomeCallable PutResourcePolicyCallable(const PutResourcePolicyRequestT& request) const { return SubmitCallable(&CodeBuildClient::PutResourcePolicy, request); } /** * An Async wrapper for PutResourcePolicy that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename PutResourcePolicyRequestT = Model::PutResourcePolicyRequest> void PutResourcePolicyAsync(const PutResourcePolicyRequestT& request, const PutResourcePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::PutResourcePolicy, request, handler, context); } /** * <p>Restarts a build.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuild">AWS * API Reference</a></p> */ virtual Model::RetryBuildOutcome RetryBuild(const Model::RetryBuildRequest& request) const; /** * A Callable wrapper for RetryBuild that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename RetryBuildRequestT = Model::RetryBuildRequest> Model::RetryBuildOutcomeCallable RetryBuildCallable(const RetryBuildRequestT& request) const { return SubmitCallable(&CodeBuildClient::RetryBuild, request); } /** * An Async wrapper for RetryBuild that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename RetryBuildRequestT = Model::RetryBuildRequest> void RetryBuildAsync(const RetryBuildRequestT& request, const RetryBuildResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::RetryBuild, request, handler, context); } /** * <p>Restarts a failed batch build. Only batch builds that have failed can be * retried.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuildBatch">AWS * API Reference</a></p> */ virtual Model::RetryBuildBatchOutcome RetryBuildBatch(const Model::RetryBuildBatchRequest& request) const; /** * A Callable wrapper for RetryBuildBatch that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename RetryBuildBatchRequestT = Model::RetryBuildBatchRequest> Model::RetryBuildBatchOutcomeCallable RetryBuildBatchCallable(const RetryBuildBatchRequestT& request) const { return SubmitCallable(&CodeBuildClient::RetryBuildBatch, request); } /** * An Async wrapper for RetryBuildBatch that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename RetryBuildBatchRequestT = Model::RetryBuildBatchRequest> void RetryBuildBatchAsync(const RetryBuildBatchRequestT& request, const RetryBuildBatchResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::RetryBuildBatch, request, handler, context); } /** * <p>Starts running a build.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuild">AWS * API Reference</a></p> */ virtual Model::StartBuildOutcome StartBuild(const Model::StartBuildRequest& request) const; /** * A Callable wrapper for StartBuild that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename StartBuildRequestT = Model::StartBuildRequest> Model::StartBuildOutcomeCallable StartBuildCallable(const StartBuildRequestT& request) const { return SubmitCallable(&CodeBuildClient::StartBuild, request); } /** * An Async wrapper for StartBuild that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename StartBuildRequestT = Model::StartBuildRequest> void StartBuildAsync(const StartBuildRequestT& request, const StartBuildResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::StartBuild, request, handler, context); } /** * <p>Starts a batch build for a project.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuildBatch">AWS * API Reference</a></p> */ virtual Model::StartBuildBatchOutcome StartBuildBatch(const Model::StartBuildBatchRequest& request) const; /** * A Callable wrapper for StartBuildBatch that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename StartBuildBatchRequestT = Model::StartBuildBatchRequest> Model::StartBuildBatchOutcomeCallable StartBuildBatchCallable(const StartBuildBatchRequestT& request) const { return SubmitCallable(&CodeBuildClient::StartBuildBatch, request); } /** * An Async wrapper for StartBuildBatch that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename StartBuildBatchRequestT = Model::StartBuildBatchRequest> void StartBuildBatchAsync(const StartBuildBatchRequestT& request, const StartBuildBatchResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::StartBuildBatch, request, handler, context); } /** * <p>Attempts to stop running a build.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuild">AWS * API Reference</a></p> */ virtual Model::StopBuildOutcome StopBuild(const Model::StopBuildRequest& request) const; /** * A Callable wrapper for StopBuild that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename StopBuildRequestT = Model::StopBuildRequest> Model::StopBuildOutcomeCallable StopBuildCallable(const StopBuildRequestT& request) const { return SubmitCallable(&CodeBuildClient::StopBuild, request); } /** * An Async wrapper for StopBuild that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename StopBuildRequestT = Model::StopBuildRequest> void StopBuildAsync(const StopBuildRequestT& request, const StopBuildResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::StopBuild, request, handler, context); } /** * <p>Stops a running batch build.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuildBatch">AWS * API Reference</a></p> */ virtual Model::StopBuildBatchOutcome StopBuildBatch(const Model::StopBuildBatchRequest& request) const; /** * A Callable wrapper for StopBuildBatch that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename StopBuildBatchRequestT = Model::StopBuildBatchRequest> Model::StopBuildBatchOutcomeCallable StopBuildBatchCallable(const StopBuildBatchRequestT& request) const { return SubmitCallable(&CodeBuildClient::StopBuildBatch, request); } /** * An Async wrapper for StopBuildBatch that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename StopBuildBatchRequestT = Model::StopBuildBatchRequest> void StopBuildBatchAsync(const StopBuildBatchRequestT& request, const StopBuildBatchResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::StopBuildBatch, request, handler, context); } /** * <p>Changes the settings of a build project.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateProject">AWS * API Reference</a></p> */ virtual Model::UpdateProjectOutcome UpdateProject(const Model::UpdateProjectRequest& request) const; /** * A Callable wrapper for UpdateProject that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename UpdateProjectRequestT = Model::UpdateProjectRequest> Model::UpdateProjectOutcomeCallable UpdateProjectCallable(const UpdateProjectRequestT& request) const { return SubmitCallable(&CodeBuildClient::UpdateProject, request); } /** * An Async wrapper for UpdateProject that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename UpdateProjectRequestT = Model::UpdateProjectRequest> void UpdateProjectAsync(const UpdateProjectRequestT& request, const UpdateProjectResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::UpdateProject, request, handler, context); } /** * <p>Changes the public visibility for a project. The project's build results, * logs, and artifacts are available to the general public. For more information, * see <a * href="https://docs.aws.amazon.com/codebuild/latest/userguide/public-builds.html">Public * build projects</a> in the <i>CodeBuild User Guide</i>.</p> <p>The * following should be kept in mind when making your projects public:</p> <ul> <li> * <p>All of a project's build results, logs, and artifacts, including builds that * were run when the project was private, are available to the general public.</p> * </li> <li> <p>All build logs and artifacts are available to the public. * Environment variables, source code, and other sensitive information may have * been output to the build logs and artifacts. You must be careful about what * information is output to the build logs. Some best practice are:</p> <ul> <li> * <p>Do not store sensitive values, especially Amazon Web Services access key IDs * and secret access keys, in environment variables. We recommend that you use an * Amazon EC2 Systems Manager Parameter Store or Secrets Manager to store sensitive * values.</p> </li> <li> <p>Follow <a * href="https://docs.aws.amazon.com/codebuild/latest/userguide/webhooks.html#webhook-best-practices">Best * practices for using webhooks</a> in the <i>CodeBuild User Guide</i> to limit * which entities can trigger a build, and do not store the buildspec in the * project itself, to ensure that your webhooks are as secure as possible.</p> * </li> </ul> </li> <li> <p>A malicious user can use public builds to distribute * malicious artifacts. We recommend that you review all pull requests to verify * that the pull request is a legitimate change. We also recommend that you * validate any artifacts with their checksums to make sure that the correct * artifacts are being downloaded.</p> </li> </ul> <p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateProjectVisibility">AWS * API Reference</a></p> */ virtual Model::UpdateProjectVisibilityOutcome UpdateProjectVisibility(const Model::UpdateProjectVisibilityRequest& request) const; /** * A Callable wrapper for UpdateProjectVisibility that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename UpdateProjectVisibilityRequestT = Model::UpdateProjectVisibilityRequest> Model::UpdateProjectVisibilityOutcomeCallable UpdateProjectVisibilityCallable(const UpdateProjectVisibilityRequestT& request) const { return SubmitCallable(&CodeBuildClient::UpdateProjectVisibility, request); } /** * An Async wrapper for UpdateProjectVisibility that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename UpdateProjectVisibilityRequestT = Model::UpdateProjectVisibilityRequest> void UpdateProjectVisibilityAsync(const UpdateProjectVisibilityRequestT& request, const UpdateProjectVisibilityResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::UpdateProjectVisibility, request, handler, context); } /** * <p> Updates a report group. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateReportGroup">AWS * API Reference</a></p> */ virtual Model::UpdateReportGroupOutcome UpdateReportGroup(const Model::UpdateReportGroupRequest& request) const; /** * A Callable wrapper for UpdateReportGroup that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename UpdateReportGroupRequestT = Model::UpdateReportGroupRequest> Model::UpdateReportGroupOutcomeCallable UpdateReportGroupCallable(const UpdateReportGroupRequestT& request) const { return SubmitCallable(&CodeBuildClient::UpdateReportGroup, request); } /** * An Async wrapper for UpdateReportGroup that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename UpdateReportGroupRequestT = Model::UpdateReportGroupRequest> void UpdateReportGroupAsync(const UpdateReportGroupRequestT& request, const UpdateReportGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::UpdateReportGroup, request, handler, context); } /** * <p> Updates the webhook associated with an CodeBuild build project. </p> * <p> If you use Bitbucket for your repository, <code>rotateSecret</code> is * ignored. </p> <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateWebhook">AWS * API Reference</a></p> */ virtual Model::UpdateWebhookOutcome UpdateWebhook(const Model::UpdateWebhookRequest& request) const; /** * A Callable wrapper for UpdateWebhook that returns a future to the operation so that it can be executed in parallel to other requests. */ template<typename UpdateWebhookRequestT = Model::UpdateWebhookRequest> Model::UpdateWebhookOutcomeCallable UpdateWebhookCallable(const UpdateWebhookRequestT& request) const { return SubmitCallable(&CodeBuildClient::UpdateWebhook, request); } /** * An Async wrapper for UpdateWebhook that queues the request into a thread executor and triggers associated callback when operation has finished. */ template<typename UpdateWebhookRequestT = Model::UpdateWebhookRequest> void UpdateWebhookAsync(const UpdateWebhookRequestT& request, const UpdateWebhookResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const { return SubmitAsync(&CodeBuildClient::UpdateWebhook, request, handler, context); } void OverrideEndpoint(const Aws::String& endpoint); std::shared_ptr<CodeBuildEndpointProviderBase>& accessEndpointProvider(); private: friend class Aws::Client::ClientWithAsyncTemplateMethods<CodeBuildClient>; void init(const CodeBuildClientConfiguration& clientConfiguration); CodeBuildClientConfiguration m_clientConfiguration; std::shared_ptr<Aws::Utils::Threading::Executor> m_executor; std::shared_ptr<CodeBuildEndpointProviderBase> m_endpointProvider; }; } // namespace CodeBuild } // namespace Aws
9ad3bbd48092df6b6f0a235835db5e5196522107
5816f1fcafab854c576ebdc201038cac6a1c8d46
/fem_ofv/src/FEM/boundarycondition.h
eedd850971515b056021070006ca56e15c1f10f9
[ "CC0-1.0", "LicenseRef-scancode-generic-cla" ]
permissive
OlegJakushkin/ARL_Topologies
26edb221d3e27e68eee324dc74522c8971c1d2c0
2c0d3d806b34171c824705b3e1a00e12460c0930
refs/heads/master
2021-09-25T07:55:32.474242
2018-10-19T20:30:53
2018-10-19T20:30:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,631
h
boundarycondition.h
/* * ARL_Topologies - An extensible topology optimization program * * Written in 2017 by Raymond A. Wildman <raymond.a.wildman.civ@mail.mil> * This project constitutes a work of the United States Government and is not * subject to domestic copyright protection under 17 USC Sec. 105. * Release authorized by the US Army Research Laboratory * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. * */ #ifndef BOUNDARYCONDITION_H #define BOUNDARYCONDITION_H #include <string> #include <vector> #include "UTIL/topologiesdefs.h" #include "REP/cgal_types.h" #include "geometricentity.h" namespace Topologies{ struct TOMesh; struct TOMesh3D; struct TOMesh2D; } //! Class that defines a boundary condition as a set of nodes from a mesh class BoundaryCondition { public: //! Constructor defining a BoundaryCondition from an Exodus mesh file BoundaryCondition(BCType inBC, bool inFX, bool inFY, bool inFZ, unsigned nodeSetID, Topologies::MeshFileFormat inMFF, const std::string& meshFileName, unsigned dim); //! Constructor defining a 2D BoundaryCondition from a GeometricEntity file BoundaryCondition(BCType inBC, bool inFX, bool inFY, std::unique_ptr<GeometricEntity> inGE); //! Constructor defining a 3D BoundaryCondition from a GeometricEntity file BoundaryCondition(BCType inBC, bool inFX, bool inFY, bool inFZ, std::unique_ptr<GeometricEntity> inGE); BoundaryCondition(const BoundaryCondition& inBC); BoundaryCondition(BoundaryCondition&& rhs); BoundaryCondition& operator=(BoundaryCondition rhs); void swap(BoundaryCondition& rhs); ~BoundaryCondition(); //! Determines the set of nodes of inMesh corresponding to the boundary condition defined by this object std::vector<std::size_t> applyBC(const Topologies::TOMesh * const inMesh) const; //! Returns whether or not any node of inMesh coincides with this boundary condition bool checkValidity(const Topologies::TOMesh* const inMesh) const; //! Returns the boundary condition type BCType BCType getBCT(); //! Returns the fixed coordinates std::vector<bool> getFixedCoords() const; private: BCType type; bool fixX, fixY, fixZ; std::unique_ptr<GeometricEntity> upGE; std::vector<std::size_t> nodeIDVec; static const double tol; }; inline BCType BoundaryCondition::getBCT() { return type; } #endif
fe367e02d22e00eae7098b4f6dd0c647e3f0b052
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/abc099/C/2830877.cpp
ff8bcce79fe867447b3c06e235f9f31d5d3506f3
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
278
cpp
2830877.cpp
# include <cstdio> int N ; int main () { scanf ("%d" ,& N ); int res = N ; for ( int i =0; i <= N ; i ++) { int cc =0; int t = i ; while (t >0) cc += t %6 , t /=6; t=N - i ; while (t >0) cc += t %9 , t /=9; if ( res > cc ) res = cc ; } printf ("%d\n " , res ); }
344acdcac1111a0334dc7026d6d93b736fd681c4
73bd731e6e755378264edc7a7b5d16132d023b6a
/SPOJ/SUMITR (Sums in a Triangle).cpp
401c129f7e6d37a7e94a903e356adbf7fea2e776
[]
no_license
IHR57/Competitive-Programming
375e8112f7959ebeb2a1ed6a0613beec32ce84a5
5bc80359da3c0e5ada614a901abecbb6c8ce21a4
refs/heads/master
2023-01-24T01:33:02.672131
2023-01-22T14:34:31
2023-01-22T14:34:31
163,381,483
0
3
null
null
null
null
UTF-8
C++
false
false
242
cpp
SUMITR (Sums in a Triangle).cpp
#include <iostream> using namespace std; int main(){int r,t,a,n,s[101][101]={0};cin>>t;while(t--){cin>>n;r=0;for(int i=1;i<=n;i++){for(int j=1;j<=i;j++){cin>>a;s[i][j]=max(s[i-1][j],s[i-1][j-1])+a;r=max(s[i][j],r);}}cout<<r<<endl;}return 0;}
c3ad0a9308350b1090bb8626fdd4bb5149ff52ac
3be2d0cb41d68b055914e1c745caf1a0a01b2c65
/src/Utils.h
f84e3bb3aa166b8b7535b9fbc40ded3642a3608e
[]
no_license
cyinv/Close-VIS
89ae9579c2b615c12caf1da127678d14c8f6e541
779ee3658bf170e2b2b5cd193a25974e1ce2e7c7
refs/heads/master
2020-06-03T02:45:54.073819
2015-07-09T07:14:19
2015-07-09T07:14:19
34,965,631
0
0
null
null
null
null
UTF-8
C++
false
false
932
h
Utils.h
/* * Util.h * * Created on: Mar 16, 2015 * Author: vincy */ #ifndef SRC_UTILS_H_ #define SRC_UTILS_H_ #include <iostream> #include <fstream> #include <math.h> #include <vector> #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace std; static inline void help(char* progName) { cout << endl << "This is an demo for auto-calibration program of photometric stereo. " << endl << progName << " [image_name] " << endl << endl; } std::vector<std::string> split(const std::string &s, char delim); int filterImage(cv::Mat& img, cv::Mat& output, int windowSize=3, float sigma=10); /** * if the fourth parameter is set, then * the we will pick height or width that makes this image smallest. * */ int rescaleImage(cv::Mat& img, int height, int width, int fixedRatio = 1); int cropImage(cv::Mat& img, cv::Mat& result, int ratio ); #endif /* SRC_UTILS_H_ */
3975aee90c7d61312e7e56c8810e8d5f0aed8273
68538debc80228ea96d406035141051935ca4e62
/include/Simpleton/Box2D/limit velocity.hpp
83e9a8e7ddf8d954d5e8cdb8d7121d1ce9387d83
[ "MIT" ]
permissive
KUflower/EnTT-Pacman
ccac1c4836f7f3b4e6ffd9eb159c18ce329e94ad
ebcbc5e6005e44ea89711ced913333ae7fa468bd
refs/heads/master
2020-08-01T12:06:04.635995
2019-09-23T09:37:02
2019-09-23T09:37:02
210,991,308
2
0
MIT
2019-09-26T03:26:03
2019-09-26T03:26:02
null
UTF-8
C++
false
false
1,094
hpp
limit velocity.hpp
// // limit velocity.hpp // Simpleton Engine // // Created by Indi Kernick on 28/12/17. // Copyright © 2017 Indi Kernick. All rights reserved. // #ifndef engine_box2d_limit_velocity_hpp #define engine_box2d_limit_velocity_hpp #include "../Math/clamp.hpp" #include <Box2D/Common/b2Math.h> namespace B2 { b2Vec2 limitVel(const b2Vec2 vel, const b2Vec2 groundVel, const b2Vec2 maxSpeed) { const b2Vec2 relVel = vel - groundVel; return { Math::clampMag(relVel.x, maxSpeed.x) + groundVel.x, Math::clampMag(relVel.y, maxSpeed.y) + groundVel.y }; } b2Vec2 limitVel(const b2Vec2 vel, const b2Vec2 groundVel, const float maxSpeed) { return limitVel(vel, groundVel, {maxSpeed, maxSpeed}); } b2Vec2 limitVelX(const b2Vec2 vel, const b2Vec2 groundVel, const float maxSpeed) { return limitVel(vel, groundVel, {maxSpeed, std::numeric_limits<float>::infinity()}); } b2Vec2 limitVelY(const b2Vec2 vel, const b2Vec2 groundVel, const float maxSpeed) { return limitVel(vel, groundVel, {std::numeric_limits<float>::infinity(), maxSpeed}); } } #endif
920dd62a89332f849ef07903b0666e357789f3f6
7efabf599aaf53728a681639bc57cadc3abe6bde
/cpp/include/cugraph/partition_manager.hpp
309b169e64674ec334203e9dbf714f819f2fa5ca
[ "Apache-2.0" ]
permissive
rapidsai/cugraph
49b5378271c72c155f55d916a3c1cc1fbe05ceca
cafded113c9545e5e7211cc965f53c00939307c0
refs/heads/branch-23.10
2023-08-26T19:36:33.631587
2023-08-25T13:49:23
2023-08-25T13:49:23
157,752,451
1,403
310
Apache-2.0
2023-09-13T17:01:25
2018-11-15T18:07:11
Cuda
UTF-8
C++
false
false
6,359
hpp
partition_manager.hpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cugraph/utilities/host_scalar_comm.hpp> #include <cugraph/utilities/shuffle_comm.cuh> #include <raft/core/comms.hpp> #include <raft/core/handle.hpp> #include <string> namespace cugraph { /** * managed the mapping between graph partitioning and GPU partitioning */ class partition_manager { public: // we 2D partition both a graph adjacency matrix and the GPUs. The graph adjacency matrix is 2D // partitioned along the major axis and the minor axis. The GPUs are 2D partitioned to // gpu_col_comm_size * gpu_row_comm_size where gpu_col_comm_size is the size of the column // direction communicator (GPUs in the same column in the GPU 2D partitioning belongs to the same // column sub-communicator) and row_comm_size is the size of the row direction communicator (GPUs // in the same row belongs to the same row sub-communicator). GPUs in the same GPU row // communicator have consecutive process IDs (and may be physically closer in hierarchical // interconnects). Graph algorithms require communications due to the graph adjacency matrix // partitioning along the major axis (major sub-communicator is responsible for this) and along // the minor axis (minor sub-communicator is responsible for this). This variable controls whether // to map the major sub-communicator to the GPU row communicator or the GPU column communicator. static constexpr bool map_major_comm_to_gpu_row_comm = true; #ifdef __CUDACC__ __host__ __device__ #endif static int compute_global_comm_rank_from_vertex_partition_id(int major_comm_size, int minor_comm_size, int vertex_partition_id) { return map_major_comm_to_gpu_row_comm ? vertex_partition_id : (vertex_partition_id % major_comm_size) * minor_comm_size + (vertex_partition_id / major_comm_size); } #ifdef __CUDACC__ __host__ __device__ #endif static int compute_global_comm_rank_from_graph_subcomm_ranks(int major_comm_size, int minor_comm_size, int major_comm_rank, int minor_comm_rank) { return map_major_comm_to_gpu_row_comm ? (minor_comm_rank * major_comm_size + major_comm_rank) : (major_comm_rank * minor_comm_size + minor_comm_rank); } #ifdef __CUDACC__ __host__ __device__ #endif static int compute_vertex_partition_id_from_graph_subcomm_ranks(int major_comm_size, int minor_comm_size, int major_comm_rank, int minor_comm_rank) { return map_major_comm_to_gpu_row_comm ? compute_global_comm_rank_from_graph_subcomm_ranks( major_comm_size, minor_comm_size, major_comm_rank, minor_comm_rank) : minor_comm_rank * major_comm_size + major_comm_rank; } static std::string major_comm_name() { return std::string(map_major_comm_to_gpu_row_comm ? "gpu_row_comm" : "gpu_col_comm"); } static std::string minor_comm_name() { return std::string(map_major_comm_to_gpu_row_comm ? "gpu_col_comm" : "gpu_row_comm"); } template <typename vertex_t> static std::vector<vertex_t> compute_partition_range_lasts(raft::handle_t const& handle, vertex_t local_partition_size) { auto& comm = handle.get_comms(); auto const comm_size = comm.get_size(); auto& major_comm = handle.get_subcomm(cugraph::partition_manager::major_comm_name()); auto const major_comm_size = major_comm.get_size(); auto const major_comm_rank = major_comm.get_rank(); auto& minor_comm = handle.get_subcomm(cugraph::partition_manager::minor_comm_name()); auto const minor_comm_size = minor_comm.get_size(); auto const minor_comm_rank = minor_comm.get_rank(); auto vertex_counts = host_scalar_allgather(comm, local_partition_size, handle.get_stream()); auto vertex_partition_ids = host_scalar_allgather(comm, partition_manager::compute_vertex_partition_id_from_graph_subcomm_ranks( major_comm_size, minor_comm_size, major_comm_rank, minor_comm_rank), handle.get_stream()); std::vector<vertex_t> vertex_partition_range_offsets(comm_size + 1, 0); for (int i = 0; i < comm_size; ++i) { vertex_partition_range_offsets[vertex_partition_ids[i]] = vertex_counts[i]; } std::exclusive_scan(vertex_partition_range_offsets.begin(), vertex_partition_range_offsets.end(), vertex_partition_range_offsets.begin(), vertex_t{0}); return std::vector<vertex_t>(vertex_partition_range_offsets.begin() + 1, vertex_partition_range_offsets.end()); } static void init_subcomm(raft::handle_t& handle, int gpu_row_comm_size) { auto& comm = handle.get_comms(); auto rank = comm.get_rank(); int row_idx = rank / gpu_row_comm_size; int col_idx = rank % gpu_row_comm_size; handle.set_subcomm("gpu_row_comm", std::make_shared<raft::comms::comms_t>(comm.comm_split(row_idx, col_idx))); handle.set_subcomm("gpu_col_comm", std::make_shared<raft::comms::comms_t>(comm.comm_split(col_idx, row_idx))); }; }; } // namespace cugraph
3ddde2dad47d01042ab9def8dc681d5e8828ba4e
b644c75125099d0bfb3dcee26c4d478fbc8b9d77
/src/Enemy.h
02e1753db1578aa56018dd3b158565e5556f33b3
[]
no_license
smurakami/GPGame
e53ac4dc7723861ac8fcb85d6bfba064699c0e53
2db4bf272e68bd344abef8acc7e3164a623e0890
refs/heads/master
2021-01-18T00:18:33.194891
2014-01-24T11:02:26
2014-01-24T11:02:26
15,985,225
0
0
null
null
null
null
UTF-8
C++
false
false
521
h
Enemy.h
#include "ofMain.h" #include "Stage.h" #include "Keys.h" #include "MainChara.h" #pragma once class Enemy{ private: Stage * _stage; float _defaultX; float _defaultY; float _posX; float _posY; float _speedX; float _speedY; bool _dead; bool _outside; bool _active; public: Enemy(); Enemy(Stage * stage); ~Enemy(); void update(); void draw(float gamePosX, float gamePosY); float getPosX(); float getPosY(); bool isDead(); void setDefaultPosition(Stage * stage, float x, float y); };
4ee5ae94f0f2555353353619a10c655b3c1a9d0c
e9e00f7c4a416adf110c77bc24e74b52dc34661c
/Develop/Projects/Qt/Prodigy/mainwindow.cpp
96a6cfc7064fa6b959e7bc918b3a218fe212d5ee
[]
no_license
minskowl/MY
ce10665cd09cfcc33c9bc35c40c2a91390401730
3bf29ce8c78ec63585ff321bd8e3d57933f90b9d
refs/heads/master
2023-06-09T15:54:39.602155
2022-11-30T08:28:26
2022-11-30T08:28:26
73,079,178
2
0
null
2023-05-31T19:20:00
2016-11-07T13:06:59
C#
UTF-8
C++
false
false
720
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "pagewords.h" #include "mainmenu.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); MainMenu *m=new MainMenu(); QObject::connect(m,SIGNAL(showForm(Page)),SLOT(showPage(Page))); addWidget(m); } int MainWindow::addWidget(QWidget *w) { return ui->stackedWidget->addWidget(w); } void MainWindow::showWords() { } void MainWindow::showPage(Page page) { switch(page) { case Words: int index= this->addWidget(new PageWords()); this->ui->stackedWidget->setCurrentIndex(index); break; } } MainWindow::~MainWindow() { delete ui; }
c50a858163bae9f564eda4a6eb0dbea298d3e43d
2d0bada349646b801a69c542407279cc7bc25013
/src/vai_runtime/vart/buffer-object/src/buffer_object_fd.cpp
70515d65681b64a567250ea9180a699e3d451804
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSD-3-Clause-Open-MPI", "LicenseRef-scancode-free-unknown", "Libtool-exception", "GCC-exception-3.1", "LicenseRef-scancode-mit-old-style", "OFL-1.1", "JSON", "LGPL-2.1-only", "LGPL-2.0-or-later", "ICU", "LicenseRef-scancode-other-permissive", "GPL-2.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-issl-2018", "MIT", "LGPL-2.1-or-later", "LicenseRef-scancode-unicode", "LGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "GPL-3.0-or-later", "Zlib", "BSD-Source-Code", "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "ISC", "NCSA", "LicenseRef-scancode-proprietary-license", "GPL-2.0-only", "CC-BY-4.0", "FSFULLR", "Minpack", "Unlicense", "BSL-1.0", "NAIST-2003", "LicenseRef-scancode-protobuf", "LicenseRef-scancode-public-domain", "Libpng", "Spencer-94", "BSD-2-Clause", "Intel", "GPL-1.0-or-later", "MPL-2.0" ]
permissive
Xilinx/Vitis-AI
31e664f7adff0958bb7d149883ab9c231efb3541
f74ddc6ed086ba949b791626638717e21505dba2
refs/heads/master
2023-08-31T02:44:51.029166
2023-07-27T06:50:28
2023-07-27T06:50:28
215,649,623
1,283
683
Apache-2.0
2023-08-17T09:24:55
2019-10-16T21:41:54
Python
UTF-8
C++
false
false
2,327
cpp
buffer_object_fd.cpp
/* * Copyright 2022-2023 Advanced Micro Devices Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "./buffer_object_fd.hpp" #include <fcntl.h> #include <glog/logging.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <cassert> #include <unordered_map> namespace vitis { namespace xir { template <typename T> struct WeakSingleton { template <typename... Args> static std::shared_ptr<T> create(Args&&... args) { static std::weak_ptr<T> the_instance_; std::shared_ptr<T> ret; if (the_instance_.expired()) { ret = std::make_shared<T>(std::forward<Args>(args)...); the_instance_ = ret; } ret = the_instance_.lock(); assert(ret != nullptr); return ret; } }; template <typename K, typename T> struct WeakStore { template <typename... Args> static std::shared_ptr<T> create(const K& key, Args&&... args) { static std::unordered_map<K, std::weak_ptr<T>> the_store_; std::shared_ptr<T> ret; if (the_store_[key].expired()) { ret = std::make_shared<T>(std::forward<Args>(args)...); the_store_[key] = ret; } ret = the_store_[key].lock(); assert(ret != nullptr); return ret; } }; std::shared_ptr<buffer_object_fd> buffer_object_fd::create( const std::string& name, int flags) { // return std::make_shared<buffer_object_fd>(name, flags); return WeakStore<std::string, buffer_object_fd>::create(name, name, flags); } static int my_open(const std::string& name, int flags) { auto fd = open(name.c_str(), flags); CHECK_GT(fd, 0) << ", open(" << name << ") failed."; return fd; } buffer_object_fd::buffer_object_fd(const std::string& name, int flags) : fd_{my_open(name, flags)} {} buffer_object_fd::~buffer_object_fd() { close(fd_); } } // namespace xir } // namespace vitis
f07e4558ed51a5a5f710d85eb59ea63bcc449d15
f8d76935f342abceff51a90a2844110ac57a4d2e
/solution/srm201_rpgrobot.cpp
fe2942a5481cc7c85558b38e38b032191f68ecc1
[]
no_license
rick-qiu/topcoder
b36cc5bc571f1cbc7be18fdc863a1800deeb5de1
04adddbdc49e35e10090d33618be90fc8d3b8e7d
refs/heads/master
2021-01-01T05:59:41.264459
2014-05-22T06:14:43
2014-05-22T06:14:43
11,315,215
1
0
null
null
null
null
UTF-8
C++
false
false
36,205
cpp
srm201_rpgrobot.cpp
/******************************************************************************* * Automatically generated code for TopCode SRM Problem * Problem URL: http://community.topcoder.com/stat?c=problem_statement&pm=2888 *******************************************************************************/ #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class RPGRobot { public: vector<string> where(vector<string> map, string movements); }; vector<string> RPGRobot::where(vector<string> map, string movements) { vector<string> ret; return ret; } int test0() { vector<string> map = {"* *", "| |", "*-*"}; string movements = "N"; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1"}; if(result == expected) { cout << "Test Case 0: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 0: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test1() { vector<string> map = {"* *-*", "| | |", "* * *", "| | |", "*-*-*"}; string movements = "N; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,3"}; if(result == expected) { cout << "Test Case 1: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 1: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test2() { vector<string> map = {"*-*-*", " ", "* * *", " ", "* * *"}; string movements = "SWE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1", "3,1"}; if(result == expected) { cout << "Test Case 2: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 2: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test3() { vector<string> map = {"* *-* *", "| |", "* *-* *", "| |", "* *-* *"}; string movements = "NSE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1", "1,3"}; if(result == expected) { cout << "Test Case 3: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 3: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test4() { vector<string> map = {"* *-*", "| | |", "* * *", "| | |", "*-*-*"}; string movements = "N; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"3,3"}; if(result == expected) { cout << "Test Case 4: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 4: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test5() { vector<string> map = {"*-*", "| |", "*-*"}; string movements = "N"; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {}; if(result == expected) { cout << "Test Case 5: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 5: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test6() { vector<string> map = {"* * * *", " ", "*-*-*-*"}; string movements = "NWE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1", "3,1", "5,1"}; if(result == expected) { cout << "Test Case 6: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 6: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test7() { vector<string> map = {"* *", " ", "*-*"}; string movements = "NWE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1"}; if(result == expected) { cout << "Test Case 7: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 7: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test8() { vector<string> map = {"* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *"}; string movements = "NSWE"; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1", "1,3", "1,5", "1,7", "1,9", "1,11", "1,13", "1,15", "1,17", "1,19", "1,21", "1,23", "1,25", "1,27", "1,29", "1,31", "1,33", "1,35", "1,37", "1,39", "1,41", "1,43", "1,45", "1,47", "3,1", "3,3", "3,5", "3,7", "3,9", "3,11", "3,13", "3,15", "3,17", "3,19", "3,21", "3,23", "3,25", "3,27", "3,29", "3,31", "3,33", "3,35", "3,37", "3,39", "3,41", "3,43", "3,45", "3,47", "5,1", "5,3", "5,5", "5,7", "5,9", "5,11", "5,13", "5,15", "5,17", "5,19", "5,21", "5,23", "5,25", "5,27", "5,29", "5,31", "5,33", "5,35", "5,37", "5,39", "5,41", "5,43", "5,45", "5,47", "7,1", "7,3", "7,5", "7,7", "7,9", "7,11", "7,13", "7,15", "7,17", "7,19", "7,21", "7,23", "7,25", "7,27", "7,29", "7,31", "7,33", "7,35", "7,37", "7,39", "7,41", "7,43", "7,45", "7,47", "9,1", "9,3", "9,5", "9,7", "9,9", "9,11", "9,13", "9,15", "9,17", "9,19", "9,21", "9,23", "9,25", "9,27", "9,29", "9,31", "9,33", "9,35", "9,37", "9,39", "9,41", "9,43", "9,45", "9,47", "11,1", "11,3", "11,5", "11,7", "11,9", "11,11", "11,13", "11,15", "11,17", "11,19", "11,21", "11,23", "11,25", "11,27", "11,29", "11,31", "11,33", "11,35", "11,37", "11,39", "11,41", "11,43", "11,45", "11,47", "13,1", "13,3", "13,5", "13,7", "13,9", "13,11", "13,13", "13,15", "13,17", "13,19", "13,21", "13,23", "13,25", "13,27", "13,29", "13,31", "13,33", "13,35", "13,37", "13,39", "13,41", "13,43", "13,45", "13,47", "15,1", "15,3", "15,5", "15,7", "15,9", "15,11", "15,13", "15,15", "15,17", "15,19", "15,21", "15,23", "15,25", "15,27", "15,29", "15,31", "15,33", "15,35", "15,37", "15,39", "15,41", "15,43", "15,45", "15,47", "17,1", "17,3", "17,5", "17,7", "17,9", "17,11", "17,13", "17,15", "17,17", "17,19", "17,21", "17,23", "17,25", "17,27", "17,29", "17,31", "17,33", "17,35", "17,37", "17,39", "17,41", "17,43", "17,45", "17,47", "19,1", "19,3", "19,5", "19,7", "19,9", "19,11", "19,13", "19,15", "19,17", "19,19", "19,21", "19,23", "19,25", "19,27", "19,29", "19,31", "19,33", "19,35", "19,37", "19,39", "19,41", "19,43", "19,45", "19,47", "21,1", "21,3", "21,5", "21,7", "21,9", "21,11", "21,13", "21,15", "21,17", "21,19", "21,21", "21,23", "21,25", "21,27", "21,29", "21,31", "21,33", "21,35", "21,37", "21,39", "21,41", "21,43", "21,45", "21,47", "23,1", "23,3", "23,5", "23,7", "23,9", "23,11", "23,13", "23,15", "23,17", "23,19", "23,21", "23,23", "23,25", "23,27", "23,29", "23,31", "23,33", "23,35", "23,37", "23,39", "23,41", "23,43", "23,45", "23,47", "25,1", "25,3", "25,5", "25,7", "25,9", "25,11", "25,13", "25,15", "25,17", "25,19", "25,21", "25,23", "25,25", "25,27", "25,29", "25,31", "25,33", "25,35", "25,37", "25,39", "25,41", "25,43", "25,45", "25,47", "27,1", "27,3", "27,5", "27,7", "27,9", "27,11", "27,13", "27,15", "27,17", "27,19", "27,21", "27,23", "27,25", "27,27", "27,29", "27,31", "27,33", "27,35", "27,37", "27,39", "27,41", "27,43", "27,45", "27,47", "29,1", "29,3", "29,5", "29,7", "29,9", "29,11", "29,13", "29,15", "29,17", "29,19", "29,21", "29,23", "29,25", "29,27", "29,29", "29,31", "29,33", "29,35", "29,37", "29,39", "29,41", "29,43", "29,45", "29,47", "31,1", "31,3", "31,5", "31,7", "31,9", "31,11", "31,13", "31,15", "31,17", "31,19", "31,21", "31,23", "31,25", "31,27", "31,29", "31,31", "31,33", "31,35", "31,37", "31,39", "31,41", "31,43", "31,45", "31,47", "33,1", "33,3", "33,5", "33,7", "33,9", "33,11", "33,13", "33,15", "33,17", "33,19", "33,21", "33,23", "33,25", "33,27", "33,29", "33,31", "33,33", "33,35", "33,37", "33,39", "33,41", "33,43", "33,45", "33,47", "35,1", "35,3", "35,5", "35,7", "35,9", "35,11", "35,13", "35,15", "35,17", "35,19", "35,21", "35,23", "35,25", "35,27", "35,29", "35,31", "35,33", "35,35", "35,37", "35,39", "35,41", "35,43", "35,45", "35,47", "37,1", "37,3", "37,5", "37,7", "37,9", "37,11", "37,13", "37,15", "37,17", "37,19", "37,21", "37,23", "37,25", "37,27", "37,29", "37,31", "37,33", "37,35", "37,37", "37,39", "37,41", "37,43", "37,45", "37,47", "39,1", "39,3", "39,5", "39,7", "39,9", "39,11", "39,13", "39,15", "39,17", "39,19", "39,21", "39,23", "39,25", "39,27", "39,29", "39,31", "39,33", "39,35", "39,37", "39,39", "39,41", "39,43", "39,45", "39,47", "41,1", "41,3", "41,5", "41,7", "41,9", "41,11", "41,13", "41,15", "41,17", "41,19", "41,21", "41,23", "41,25", "41,27", "41,29", "41,31", "41,33", "41,35", "41,37", "41,39", "41,41", "41,43", "41,45", "41,47", "43,1", "43,3", "43,5", "43,7", "43,9", "43,11", "43,13", "43,15", "43,17", "43,19", "43,21", "43,23", "43,25", "43,27", "43,29", "43,31", "43,33", "43,35", "43,37", "43,39", "43,41", "43,43", "43,45", "43,47", "45,1", "45,3", "45,5", "45,7", "45,9", "45,11", "45,13", "45,15", "45,17", "45,19", "45,21", "45,23", "45,25", "45,27", "45,29", "45,31", "45,33", "45,35", "45,37", "45,39", "45,41", "45,43", "45,45", "45,47", "47,1", "47,3", "47,5", "47,7", "47,9", "47,11", "47,13", "47,15", "47,17", "47,19", "47,21", "47,23", "47,25", "47,27", "47,29", "47,31", "47,33", "47,35", "47,37", "47,39", "47,41", "47,43", "47,45", "47,47"}; if(result == expected) { cout << "Test Case 8: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 8: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test9() { vector<string> map = {"* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *"}; string movements = "N"; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {}; if(result == expected) { cout << "Test Case 9: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 9: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test10() { vector<string> map = {"* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *", " ", "* * * * * * * * * * * * * * * * * * * * * * * * *"}; string movements = "NSWE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1", "1,3", "1,5", "3,1", "3,3", "3,5", "5,1", "5,3", "5,5", "7,1", "7,3", "7,5", "9,1", "9,3", "9,5", "11,1", "11,3", "11,5", "13,1", "13,3", "13,5", "15,1", "15,3", "15,5", "17,1", "17,3", "17,5", "19,1", "19,3", "19,5", "21,1", "21,3", "21,5", "23,1", "23,3", "23,5", "25,1", "25,3", "25,5", "27,1", "27,3", "27,5", "29,1", "29,3", "29,5", "31,1", "31,3", "31,5", "33,1", "33,3", "33,5", "35,1", "35,3", "35,5", "37,1", "37,3", "37,5", "39,1", "39,3", "39,5", "41,1", "41,3", "41,5", "43,1", "43,3", "43,5", "45,1", "45,3", "45,5", "47,1", "47,3", "47,5"}; if(result == expected) { cout << "Test Case 10: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 10: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test11() { vector<string> map = {"*-* *-*-*-*-* *", "| | | | ", "* * *-* *-*-*-*"}; string movements = "SE"; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1", "7,1"}; if(result == expected) { cout << "Test Case 11: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 11: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test12() { vector<string> map = {"* * *-* * * * *", " | | | |", "*-*-*-*-* *-*-*", "| | | ", "*-* *-* *-* * *", " | | | | |", "* * *-* * *-* *", "| | | |", "*-* * *-* * * *", " | | | |", "*-*-* *-* * * *", "| | | | | |", "* * *-*-*-* * *"}; string movements = "NSWE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"7,5"}; if(result == expected) { cout << "Test Case 12: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 12: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test13() { vector<string> map = {"* *-*-*-*", " | | | |", "*-*-*-*-*", " |", "*-* *-*-*", "| | | ", "* * *-*-*", "| | ", "* * * * *", "| |", "* * * *-*", " | | | |", "* * *-*-*", "| | | ", "*-*-*-* *", " | | ", "*-* *-* *", "| | | |", "*-* *-* *"}; string movements = "SWE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"5,7"}; if(result == expected) { cout << "Test Case 13: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 13: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test14() { vector<string> map = {"* * * *-* * * *-*-* * * * * *-* *", " | | | | | | ", "* * *-* * *-* * * * * * * * *-* *", "| | | | | | | | |", "* * *-*-* *-*-*-* * * * * * *-*-*", " | | | | | | | | |", "*-* *-* * *-*-* *-*-*-* * *-* *-*", " | | | | | | | | ", "*-*-* *-*-*-*-* *-*-*-* *-*-* * *", "| | | | | | | ", "*-*-* * * *-* *-*-* * * * *-*-* *", " | | | | | | | | | | | ", "*-* *-* * * *-* *-*-* *-* * *-*-*", " | | | | | | | | | | | ", "*-* * * *-* * *-*-*-* * * * * * *", "| | | | | | | | | ", "* *-*-*-*-*-* *-* * * *-* *-* *-*", " | | | | | | | | ", "* * *-*-*-* *-* *-*-*-*-*-*-*-*-*", "| | | | | | | | | |", "* *-* * *-* *-*-*-*-* * *-*-*-* *", " | | | | | | | | | | | ", "* *-*-*-*-* *-*-* *-* *-*-* * *-*", " | | | | | | | | | ", "*-*-*-* *-*-* * *-* *-* * * *-*-*", "| | | | | | | |", "* *-* * * *-*-* *-*-*-* *-* * *-*", " | | | | | | |", "*-* * * * * *-*-* * * * * *-* * *", "| | | | | | |", "* * *-*-* *-*-* * * *-*-* * * *-*", "| | | | | | | | | | | | | |", "*-* * *-* * * * * * *-* *-* *-*-*", " | | | | | | |", "*-* *-* *-* * * * *-* *-* *-*-*-*"}; string movements = "NW; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,23"}; if(result == expected) { cout << "Test Case 14: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 14: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test15() { vector<string> map = {"* * * * * * * * * * * * * * * * * * * * * * * *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " ", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *", " | | | | | | | | | | | | | | | | | | | | | | |", "* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *-* *"}; string movements = "NSWE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"5,9", "5,13", "5,17", "5,21", "5,25", "5,29", "5,33", "5,37", "9,9", "9,13", "9,17", "9,21", "9,25", "9,29", "9,33", "9,37", "13,9", "13,13", "13,17", "13,21", "13,25", "13,29", "13,33", "13,37", "17,9", "17,13", "17,17", "17,21", "17,25", "17,29", "17,33", "17,37", "21,9", "21,13", "21,17", "21,21", "21,25", "21,29", "21,33", "21,37", "25,9", "25,13", "25,17", "25,21", "25,25", "25,29", "25,33", "25,37", "29,9", "29,13", "29,17", "29,21", "29,25", "29,29", "29,33", "29,37", "33,9", "33,13", "33,17", "33,21", "33,25", "33,29", "33,33", "33,37", "37,9", "37,13", "37,17", "37,21", "37,25", "37,29", "37,33", "37,37", "41,9", "41,13", "41,17", "41,21", "41,25", "41,29", "41,33", "41,37", "45,1", "45,5", "45,9", "45,13", "45,17", "45,21", "45,25", "45,29", "45,33", "45,37"}; if(result == expected) { cout << "Test Case 15: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 15: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test16() { vector<string> map = {"*-*-* * * *-*-*-* * *-*-* * *-* *-* *-*-*-*", "| | | | | | | | | | | | | | |", "*-*-* * * * * *-*-* * * *-*-*-*-*-*-*-* * *", "| | | | | | ", "*-*-*-* * *-*-* *-* *-*-*-* *-* * * *-*-*-*", " | | | | | | | | | | | ", "* * * *-* * *-*-*-* *-* * * *-* *-*-* *-* *", "| | | | | | | | | | | ", "*-* *-*-*-* *-* *-*-* *-* * * *-*-*-*-*-*-*", "| | | | | | | | | | | | ", "*-* * *-*-* * * * * * * * * *-*-* * *-* *-*", " | | | | | | | | | | ", "* * * *-*-*-*-* *-*-* * *-*-* *-* *-* * * *", " | | | | | | | | | | ", "* * *-*-* *-* * *-* * * *-* * *-* *-*-* *-*", " | | | | | | | | | |", "* *-*-* *-*-*-*-* * *-* *-* *-* * * * *-* *"}; string movements = "S"; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"11,5", "17,15", "23,1", "29,11", "37,5", "39,1", "39,9", "41,1"}; if(result == expected) { cout << "Test Case 16: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 16: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test17() { vector<string> map = {"* * * *-* * * *-*-* * * * * *-* *", " | | | | | | ", "* * *-* * *-* * * * * * * * *-* *", "| | | | | | | | |", "* * *-*-* *-*-*-* * * * * * *-*-*", " | | | | | | | | |", "*-* *-* * *-*-* *-*-*-* * *-* *-*", " | | | | | | | | ", "*-*-* *-*-*-*-* *-*-*-* *-*-* * *", "| | | | | | | ", "*-*-* * * *-* *-*-* * * * *-*-* *", " | | | | | | | | | | | ", "*-* *-* * * *-* *-*-* *-* * *-*-*", " | | | | | | | | | | | ", "*-* * * *-* * *-*-*-* * * * * * *", "| | | | | | | | | ", "* *-*-*-*-*-* *-* * * *-* *-* *-*", " | | | | | | | | ", "* * *-*-*-* *-* *-*-*-*-*-*-*-*-*", "| | | | | | | | | |", "* *-* * *-* *-*-*-*-* * *-*-*-* *", " | | | | | | | | | | | ", "* *-*-*-*-* *-*-* *-* *-*-* * *-*", " | | | | | | | | | ", "*-*-*-* *-*-* * *-* *-* * * *-*-*", "| | | | | | | |", "* *-* * * *-*-* *-*-*-* *-* * *-*", " | | | | | | |", "*-* * * * * *-*-* * * * * *-* * *", "| | | | | | |", "* * *-*-* *-*-* * * *-*-* * * *-*", "| | | | | | | | | | | | | |", "*-* * *-* * * * * * *-* *-* *-*-*", " | | | | | | |", "*-* *-* *-* * * * *-* *-* *-*-*-*"}; string movements = "NW; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,23"}; if(result == expected) { cout << "Test Case 17: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 17: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test18() { vector<string> map = {"* * * *", " ", "*-*-*-*"}; string movements = "NWE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1", "3,1", "5,1"}; if(result == expected) { cout << "Test Case 18: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 18: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test19() { vector<string> map = {"* *-*", "| | |", "* * *", "| | |", "*-*-*"}; string movements = "N; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,3"}; if(result == expected) { cout << "Test Case 19: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 19: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test20() { vector<string> map = {"* * *", " ", "* * *", " ", "* * *"}; string movements = "NSWE"; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {"1,1", "1,3", "3,1", "3,3"}; if(result == expected) { cout << "Test Case 20: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 20: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test21() { vector<string> map = {"* *-*", "| |", "*-*-*"}; string movements = "NE; RPGRobot* pObj = new RPGRobot(); clock_t start = clock(); vector<string> result = pObj->where(map, movements); clock_t end = clock(); delete pObj; vector<string> expected = {}; if(result == expected) { cout << "Test Case 21: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 21: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int main(int argc, char* argv[]) { int passed = 0; int failed = 0; test0() == 0 ? ++passed : ++failed; test1() == 0 ? ++passed : ++failed; test2() == 0 ? ++passed : ++failed; test3() == 0 ? ++passed : ++failed; test4() == 0 ? ++passed : ++failed; test5() == 0 ? ++passed : ++failed; test6() == 0 ? ++passed : ++failed; test7() == 0 ? ++passed : ++failed; test8() == 0 ? ++passed : ++failed; test9() == 0 ? ++passed : ++failed; test10() == 0 ? ++passed : ++failed; test11() == 0 ? ++passed : ++failed; test12() == 0 ? ++passed : ++failed; test13() == 0 ? ++passed : ++failed; test14() == 0 ? ++passed : ++failed; test15() == 0 ? ++passed : ++failed; test16() == 0 ? ++passed : ++failed; test17() == 0 ? ++passed : ++failed; test18() == 0 ? ++passed : ++failed; test19() == 0 ? ++passed : ++failed; test20() == 0 ? ++passed : ++failed; test21() == 0 ? ++passed : ++failed; cout << "Total Test Case: " << passed + failed << "; Passed: " << passed << "; Failed: " << failed << endl; return failed == 0 ? 0 : 1; } /******************************************************************************* * Top Submission URL: * http://community.topcoder.com/stat?c=problem_solution&cr=275071&rd=5872&pm=2888 ******************************************************************************** /* * Hey, stop reading this code right this instant! * You don't know what it could do to your fragile mind! */ #include <string> #include <vector> #include <algorithm> #include <iostream> #include <sstream> #include <deque> #include <stack> #include <cmath> #include <cstdio> #include <cctype> #include <cstdlib> #include <climits> #include <set> #include <map> #include <numeric> #include <ctime> #include <functional> #include <regex.h> #include <queue> //#include <brains> /* commented out to avoid compile error -- brains not found */ using namespace std; #define debug(x) cout << #x << " = " << x << endl #define len length() #define si size() typedef vector<int> vi; typedef vector<string> vs; typedef vector<bool> vb; typedef vector<vi> vvi; typedef vector<vb> vvb; typedef long long ii; #define mod(A, B) ((((A) % (B)) + (B)) % (B)) #define b2e(A) (A).begin(), (A).end() #define e2b(A) (A).rbegin(), (A).rend() #define rev(A) std::reverse(b2e(A)) #define s(A) std::sort(b2e(A)) #define ss(A) std::stable_sort(b2e(A)) #define un(A) std::unique(b2e(A)) #define er(A) (A).erase(un(A), (A).end()) #define Fill(A,B) std::fill(b2e(A), B) #define minelt(A) *min_element(b2e(A)) #define maxelt(A) *max_element(b2e(A)) #define nextp(A) next_permutation(b2e(A)) #define prevp(A) prev_permutation(b2e(A)) #define pb(x) push_back((x)); string itos (int i) {stringstream s; s << i; return s.str();} string lltos (long long i) {stringstream s; s << i; return s.str();} int ipow(int a, int b) {return (int) (std::pow((double) (a), (double) (b)));} template <class T> ostream& operator << (ostream& os, vector<T> temp) { os << "{"; for (int i = 0; i < temp.si; i++) os << (i?", ":"") << temp[i]; os << "}"; return os; } template<class S,class T> ostream& operator << (ostream &os ,const pair<S,T> &a) { os << "(" << a.first << ", " << a.second << ")"; return os; } ii gcd(ii a, ii b) {if (a<0&&b<0) return gcd(-a,-b); if (a==0) return b; if (b==0) return a; if (a > b) return gcd(b, a); if (!(b % a)) return a; return gcd(a, b % a);} int dx[] = {-2,0,2,0}, dy[] = {0,2,0,-2}; int dx2[] = {-1,0,1,0}, dy2[] = {0,1,0,-1}; //int dx[] = {1,1,1,0,0,-1,-1,-1}, dy[] = {1,0,-1,1,-1,1,0,-1}; /* public class antimatter extends Idiot { String[] codeSolution(String[] problemStatement) { //re-code this method! //it always returns quickly, but is often incorrect (about 33% of the time) return null; } } */ //---------------------------- struct pt { int first, second, x, y; }; bool operator < (const pt &a, const pt &b) { if (a.x != b.x) return a.x < b.x; return a.y < b.y; } ostream& operator << (ostream &os , const pt &a) { os << "(" << a.first << ", " << a.second << ")"; return os; } map<char,int> dir; vs m; int R, C; class RPGRobot { public: void cango(string dirs, vector<pt> &vp) { debug(dirs); for (int x = 0; x < vp.si; x++) { bool d[4] = {0,0,0,0}, e[4] = {0,0,0,0}; for (int i = 0; i < dirs.si; i++) { e[dir[dirs[i]]] = 1; } for (int i = 0; i < 4; i++) { int tx = vp[x].first + dx2[i], ty = vp[x].second + dy2[i]; if (tx < 0 || ty < 0 || tx >= R || ty >= C) { d[i] = e[i] = 1; } else if (m[tx][ty] == ' ') d[i] = 1; } // printf("%i %i %i %i %i %i %i %i\n", d[0],d[1],d[2],d[3],e[0],e[1],e[2],e[3]); for (int i = 0; i < 4; i++) { if (e[i] != d[i]) { vp.erase(vp.begin()+x); x--; goto done; } } done:; } } void mv(char d, vector<pt> &vp) { int D = dir[d]; for (int i = 0; i < vp.si; i++) { vp[i].first += dx[D]; vp[i].second += dy[D]; } } vector <string> where(vector <string> mp, string movements) { dir['N'] = 0; dir['E'] = 1; dir['S'] = 2; dir['W'] = 3; m = mp; R = mp.si, C = mp[0].si; vector<pt> vp; for (int i = 1; i < mp.si; i += 2) for (int j = 1; j < mp[0].si; j += 2) if (mp[i][j] == ' ') { pt temp = {i,j,i,j}; vp.pb(temp); } for (int i = 0; i < movements.si; i++) if (movements[i] == ',') movements[i] = ' '; stringstream S(movements); vs move; string v; while (S >> v) move.pb(v); cango(move[0],vp); // debug(vp); for (int i = 1; i < move.si; i += 2) { mv(move[i][0], vp); // debug(vp); cango(move[i+1],vp); // debug(vp); } for (int i = 0; i < vp.si; i++) { swap(vp[i].x, vp[i].y); } s(vp); vs ret; for (int i = 0; i < vp.si; i++) { char buf[100]; sprintf(buf, "%i,%i", vp[i].x, vp[i].y); ret.push_back(string(buf)); } return ret; } }; // Powered by PopsEdit ******************************************************************************** *******************************************************************************/
c59e0a90a45a3dd33295424e38d46e01ebd7f4ad
6d9891a14feecce886c44dd5030185fc41860196
/usqcd/chroma/chroma-org/other_libs/sse_wilson_dslash/tests/testSiteDslash.h
73d0c7ea1ab2a90c6ca0b57ae5d50844bfd6d5b6
[ "FSFAP", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
CCTLib/cibench
ffe28235d6986143a9d46e01890c6ca413ebf9da
c1a07cc6ec8e05b3e787f3f1596d6d8224f839fc
refs/heads/master
2022-11-14T08:06:51.974065
2020-07-07T02:05:42
2020-07-07T02:05:42
259,185,438
9
0
null
null
null
null
UTF-8
C++
false
false
1,516
h
testSiteDslash.h
#ifndef TEST_SITE_DSLASH #define TEST_SITE_DSLASH #ifndef UNITTEST_H #include "unittest.h" #endif class testSiteDslash0PlusForward : public TestFixture { public: void run(void); }; class testSiteDslash0PlusBackwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash1PlusForwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash1PlusBackwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash2PlusForwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash2PlusBackwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash3PlusForwardAdd: public TestFixture { public: void run(void); }; class testSiteDslash3PlusBackwardAddStore : public TestFixture { public: void run(void); }; class testSiteDslash0MinusForward : public TestFixture { public: void run(void); }; class testSiteDslash0MinusBackwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash1MinusForwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash1MinusBackwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash2MinusForwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash2MinusBackwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash3MinusForwardAdd : public TestFixture { public: void run(void); }; class testSiteDslash3MinusBackwardAddStore : public TestFixture { public: void run(void); }; #endif
2cff9d8b6280dd5d892b86bb0ea08b78e18dc557
56c558f4bbcd79447cf072cce75b01f4dc76eb43
/project/Trash/RobotTransmitter/RobotTransmitter.ino
a0f6b2563cfd0a99de121374a18931883f9f0179
[]
no_license
parzival111/Mobile-Robotics
c4f7846ea96618aa9aed1fc84f45e10f41e44d2f
bb6a0760126f344b488bc0445d423c3730de37c2
refs/heads/master
2020-09-26T07:55:45.993869
2020-02-19T16:07:15
2020-02-19T16:07:15
226,208,558
0
0
null
null
null
null
UTF-8
C++
false
false
2,024
ino
RobotTransmitter.ino
/*RobotTransmitter.ino Authors: Carlotta Berry, Ricky Rung modified: 11/23/16 This program will set up the laptop to use a nRF24L01 wireless transceiver to communicate wirelessly with a mobile robot the transmitter is an Arduino Mega connected to the laptop the receiver is on an Arduino Mega mounted on the robot HARDWARE CONNECTIONS: https://www.arduino.cc/en/Hacking/PinMapping2560 Arduino MEGA nRF24L01 connections CE pin 7 CSN pin 8 MOSI pin 51 MISO pin 50 SCK pin 52 VCC 3.3 V GND GND Arduino Uno nRF24L01 connections http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo http://www.theengineeringprojects.com/2015/07/interfacing-arduino-nrf24l01.html 1 - GND 2 - VCC 3.3V !!! NOT 5V 3 - CE to Arduino pin 7 4 - CSN to Arduino pin 8 5 - SCK to Arduino pin 13 6 - MOSI to Arduino pin 11 7 - MISO to Arduino pin 12 8 - UNUSED */ #include <SPI.h>//include serial peripheral interface library #include <RF24.h>//include wireless transceiver library #include <nRF24L01.h> #include <printf.h> #include <RF24_config.h> // Set up the wireless transceiver pins #define CE_PIN 7 #define CSN_PIN 8 #define test_LED 13 #define team_channel 123 //transmitter and receiver on same channel between 1 & 125 const uint64_t pipe = 0xE8E8F0F0E1LL; //define the radio transmit pipe (5 Byte configurable) RF24 radio(CE_PIN, CSN_PIN); //create radio object uint8_t data[1]; //variable to hold transmit data void setup() { Serial.begin(9600);//start serial communication radio.begin();//start radio radio.setChannel(team_channel);//set the transmit and receive channels to avoid interference radio.openWritingPipe(pipe);//open up writing pipe } void loop() { //use serial monitor to send 0 and 1 to blink LED on digital pin 13 on robot microcontroller if (Serial.available() > 0) { data[0] = Serial.parseInt(); Serial.println(data[0]); radio.write(data, sizeof(data)); } }
5559cab43cfedf90ffc678f7b37640fea38c3414
d77ee0d058463df2b49f79d1623c44438c1006dc
/src/GravityPoint.cpp
5a7e664dc6d94442879560a76565a6b4d000fd91
[]
no_license
bacsmar/ParticleSystem
9a96c3886bc51f8ac31f6e9142349f708132b12f
0dbb4056f167c72d0bd7c3074471bc3781657524
refs/heads/master
2020-12-25T22:29:15.450269
2012-09-05T22:45:30
2012-09-05T22:45:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
502
cpp
GravityPoint.cpp
/* * GravityPoint.cpp * * Created on: Aug 29, 2012 * Author: stashell */ #include "GravityPoint.h" GravityPoint::GravityPoint() { forceActive = false; weight = 0; } GravityPoint::~GravityPoint() { } float GravityPoint::getWeight() const { return weight; } void GravityPoint::setWeight(float p_weight) { weight = p_weight; } void GravityPoint::setForceActive(bool forceActive) { this->forceActive = forceActive; } bool GravityPoint::isForceActive() const { return forceActive; }
f20896f99f32f6ee4b0ac32a7649532bd92c8789
a9f678119a8ed6b852f30aa4c35ee8d75ee55c10
/editDistance.cpp
6bdf7cdb35ac3217b89092a8ef48089f3ee21e9f
[]
no_license
gaolu/Leetcode
0ae73c04be1f1cb75b499d957ed24fde78684074
10d1091c20b1692d9a9fa91b41d23a1f8ba9424a
refs/heads/master
2021-01-13T02:06:45.626985
2014-03-18T04:26:39
2014-03-18T04:26:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,231
cpp
editDistance.cpp
class Solution { public: int minDistance(string word1, string word2) { // Start typing your C/C++ solution below // DO NOT write int main() function int numOfRows = word1.size(); int numOfCols = word2.size(); if(numOfRows == 0) return numOfCols; else if(numOfCols == 0) return numOfRows; int distance[numOfRows + 1][numOfCols + 1]; for(int i = 0; i < numOfRows + 1; i++) distance[i][0] = i; for(int j = 0; j < numOfCols + 1; j++) distance[0][j] = j; for(int i = 1; i < numOfRows + 1; i++){ char rowChar = word1[i - 1]; for(int j = 1; j < numOfCols + 1; j++){ char colChar = word2[j - 1]; if(rowChar == colChar) distance[i][j] = distance[i - 1][j - 1]; else{ int change = distance[i - 1][j - 1] + 1; int add = distance[i][j -1] + 1; int del = distance[i - 1][j] + 1; distance[i][j] = min(change, min(add, del)); } } } return distance[numOfRows][numOfCols]; } };
d6df7babe23803d43e59d040f94488788bf5b204
8a61f3ea38e51c9bf502dc5b7aed34f4be1fc3d3
/Epoll.cpp
3e89c7ee794863c9699619621e27f292547a72bb
[]
no_license
100156994/Http
bb354cba6cca0ad0274d91d537eddec6e0136334
8693a29aab3ebc5a7bc74a4bda14e97d46fc2cbf
refs/heads/master
2022-04-02T16:23:45.207661
2020-02-22T17:23:25
2020-02-22T17:23:25
238,974,947
1
0
null
null
null
null
GB18030
C++
false
false
3,863
cpp
Epoll.cpp
#include"Channel.h" #include <assert.h> #include <errno.h> #include <poll.h> #include <sys/epoll.h> #include <unistd.h> #include"TimerQueue.h" namespace detail { size_t now(); } using namespace detail; const int EVENTSNUM = 16;//最初默认一次接收的事件最大值 到阈值翻倍 const int kNew = -1; //当前不在epoll map中 没有被监听 const int kAdded = 1; //在epoll map中 监听 const int kDeleted = 2; //在epool map,没有监听 Epoller::Epoller(EventLoop* loop) :loop_(loop), epollfd_(epoll_create1(EPOLL_CLOEXEC)), events_(EVENTSNUM) { assert(epollfd_>0); } Epoller::~Epoller() { close(epollfd_); } //返回wait return的时间 并且将对应活动的chennel加入activeChannels size_t Epoller::poll(int timeoutMs,ChannelList* activeChannels) { assertInLoopThread(); struct epoll_event event; int eventsNum=epoll_wait(epollfd_,&*events_.begin(),static_cast<int>(events_.size()),timeoutMs); size_t receiveTime=now(); if(eventsNum>0)//成功 { fillActiveChannels(eventsNum,activeChannels); if(static_cast<int>(events_.size()) == eventsNum ) { events_.resize(events_.size()*2); } }else if(eventsNum==0)//超时 { //log }else//出错 { //log } return receiveTime; } void Epoller::updateChannel(Channel *channel) { assertInLoopThread(); const int index = channel->index(); if(index ==kNew || index == kDeleted)//add { int fd = channel->fd(); if (index == kNew) { assert(channels_.find(fd) == channels_.end()); channels_[fd] = channel; }else // index == kDeleted { assert(channels_.find(fd) != channels_.end()); assert(channels_[fd] == channel); } channel->set_index(kAdded); update(EPOLL_CTL_ADD,channel); }else//修改 { int fd =channel->fd(); assert(channels_.find(fd)!=channels_.end()); assert(channels_[fd]==channel); assert(index==kAdded); if(channel->isNoneEvent()) { update(EPOLL_CTL_DEL,channel); channel->set_index(kDeleted); }else { update(EPOLL_CTL_MOD,channel); } } } void Epoller::removeChannel(Channel* channel) { assertInLoopThread(); int fd = channel->fd(); int index= channel->index(); assert(channels_.find(fd)!=channels_.end()); assert(channels_[fd]==channel); assert(index==kAdded||index==kDeleted); size_t n = channels_.erase(fd); assert(n==1); if(index==kAdded) { update(EPOLL_CTL_DEL,channel); } channel->set_index(kNew); } bool Epoller::hasChannel(Channel* channel) { assertInLoopThread(); ChannelMap::const_iterator it = channels_.find(channel->fd()); return it != channels_.end() && it->second == channel; } void Epoller::fillActiveChannels(int eventsNum,ChannelList* activeChannels)const { assert(static_cast<size_t>(eventsNum) <= events_.size()); for(int i = 0; i < eventsNum; ++i) { Channel* channel = static_cast<Channel*>(events_[i].data.ptr); #ifndef NDEBUG int fd = channel->fd(); ChannelMap::const_iterator it = channels_.find(fd); assert(it != channels_.end()); assert(it->second == channel); #endif channel->set_revents(events_[i].events); activeChannels->push_back(channel); } } void Epoller::assertInLoopThread(){loop_->assertInLoopThread();} //把channel指针放进 event void Epoller::update(int operation, Channel* channel) { struct epoll_event event; event.events=channel->events(); event.data.ptr=channel; const int fd =channel->fd(); if(epoll_ctl(epollfd_,operation,fd,&event)<0)//error { //log } }
31f268273010efddf7f54012d7fd7831128b41de
ba5a03c4b1a47203f2e3fd339a7deaeb21a28877
/unit_test/burn_cell/burn_cell.H
2ff0a61387cb864aed1e7630ba86dbc24dd0c8d4
[ "BSD-3-Clause" ]
permissive
maxpkatz/Microphysics
f65ec154e4e846046273dd779c7887fd65b9e4da
bcf06921ae6144e0f1d24ceb8181af43357e9f84
refs/heads/master
2023-08-30T13:51:38.678408
2023-06-01T12:00:11
2023-06-01T12:00:11
160,952,852
1
0
NOASSERTION
2022-03-12T16:24:44
2018-12-08T15:36:24
Jupyter Notebook
UTF-8
C++
false
false
6,245
h
burn_cell.H
#ifndef BURN_CELL_H #define BURN_CELL_H #include <extern_parameters.H> #include <eos.H> #include <network.H> #include <burner.H> #include <fstream> #include <iostream> #include <iomanip> #include <react_util.H> using namespace unit_test_rp; void burn_cell_c() { Real massfractions[NumSpec] = {-1.0}; // Make sure user set all the mass fractions to values in the interval [0, 1] for (int n = 1; n <= NumSpec; ++n) { massfractions[n-1] = get_xn(n); if (massfractions[n-1] < 0 || massfractions[n-1] > 1) { amrex::Error("mass fraction for " + short_spec_names_cxx[n-1] + " not initialized in the interval [0,1]!"); } } // Echo initial conditions at burn and fill burn state input std::cout << "Maximum Time (s): " << tmax << std::endl; std::cout << "State Density (g/cm^3): " << density << std::endl; std::cout << "State Temperature (K): " << temperature << std::endl; for (int n = 0; n < NumSpec; ++n) { std::cout << "Mass Fraction (" << short_spec_names_cxx[n] << "): " << massfractions[n] << std::endl; } burn_t burn_state; eos_t eos_state; eos_state.rho = density; eos_state.T = temperature; for (int n = 0; n < NumSpec; n++) { eos_state.xn[n] = massfractions[n]; } #ifdef AUX_THERMO set_aux_comp_from_X(eos_state); #endif eos(eos_input_rt, eos_state); burn_state.rho = eos_state.rho; burn_state.T = eos_state.T; for (int n = 0; n < NumSpec; ++n) { burn_state.xn[n] = massfractions[n]; } #if NAUX_NET > 0 for (int n = 0; n < NumAux; ++n) { burn_state.aux[n] = eos_state.aux[n]; } #endif burn_state.i = 0; burn_state.j = 0; burn_state.k = 0; burn_state.T_fixed = -1.0_rt; // normalize -- just in case if (! skip_initial_normalization) { normalize_abundances_burn(burn_state); } // call the EOS to set initial e -- it actually doesn't matter to // the burn but we need to keep track of e to get a valid // temperature for the burn if we substep eos(eos_input_rt, burn_state); // output just the instantaneous RHS Array1D<Real, 1, neqs> ydot; actual_rhs(burn_state, ydot); std::cout << "RHS at t = 0" << std::endl; for(int n = 0; n < NumSpec; ++n){ const std::string& element = short_spec_names_cxx[n]; std::cout << std::setw(6) << element << " " << ydot(n+1) << std::endl; } // output initial burn type data std::ofstream state_over_time("state_over_time.txt"); // we will divide the total integration time into nsteps that are // logarithmically spaced if (tfirst == 0.0_rt) { if (nsteps == 1) { tfirst = tmax; } else { tfirst = tmax / nsteps; } } Real dlogt = 0.0_rt; if (nsteps == 1) { dlogt = (std::log10(tmax) - std::log10(tfirst)); } else { dlogt = (std::log10(tmax) - std::log10(tfirst)) / (nsteps - 1); } // save the initial state -- we'll use this to determine // how much things changed over the entire burn burn_t burn_state_in = burn_state; // output the data in columns, one line per timestep state_over_time << std::setw(25) << "# Time"; state_over_time << std::setw(25) << "Temperature"; for(int x = 0; x < NumSpec; ++x){ const std::string& element = short_spec_names_cxx[x]; state_over_time << std::setw(25) << element; } state_over_time << std::endl; state_over_time << std::setprecision(15); Real t = 0.0; state_over_time << std::setw(25) << t; state_over_time << std::setw(25) << burn_state.T; for (double X : burn_state.xn) { state_over_time << std::setw(25) << X; } state_over_time << std::endl; // store the initial internal energy -- we'll update this after // each substep Real energy_initial = burn_state.e; // loop over steps, burn, and output the current state int nstep_int = 0; for (int n = 0; n < nsteps; n++){ // compute the time we wish to integrate to Real tend = std::pow(10.0_rt, std::log10(tfirst) + dlogt * n); Real dt = tend - t; burner(burn_state, dt); nstep_int += burn_state.n_step; // state.e represents the change in energy over the burn (for // just this sybcycle), so turn it back into a physical energy burn_state.e += energy_initial; // reset the initial energy for the next subcycle energy_initial = burn_state.e; // get the updated T if (call_eos_in_rhs) { eos(eos_input_re, burn_state); } t += dt; state_over_time << std::setw(25) << t; state_over_time << std::setw(25) << burn_state.T; for (double X : burn_state.xn) { state_over_time << std::setw(25) << X; } state_over_time << std::endl; } state_over_time.close(); // output diagnostics to the terminal std::cout << "------------------------------------" << std::endl; std::cout << "successful? " << burn_state.success << std::endl; std::cout << " - Hnuc = " << (burn_state.e - burn_state_in.e) / tmax << std::endl; std::cout << " - added e = " << burn_state.e - burn_state_in.e << std::endl; std::cout << " - final T = " << burn_state.T << std::endl; std::cout << "------------------------------------" << std::endl; std::cout << "e initial = " << burn_state_in.e << std::endl; std::cout << "e final = " << burn_state.e << std::endl; std::cout << "------------------------------------" << std::endl; std::cout << "new mass fractions: " << std::endl; for (int n = 0; n < NumSpec; ++n) { const std::string& element = short_spec_names_cxx[n]; std::cout << element << " " << burn_state.xn[n] << std::endl; } std::cout << "------------------------------------" << std::endl; std::cout << "species creation rates: " << std::endl; for (int n = 0; n < NumSpec; ++n) { std::cout << "omegadot(" << short_spec_names_cxx[n] << "): " << (burn_state.xn[n] - burn_state_in.xn[n]) / tmax << std::endl; } std::cout << "number of steps taken: " << nstep_int << std::endl; } #endif
1224422d0aaa033d8f440a6b5a4ba1dba8f7541d
74837c92508b3190f8639564eaa7fa4388679f1d
/xic/include/promptline.h
b9bdc1e6082de321653fc58f300416dd90988e99
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
frankhoff/xictools
35d49a88433901cc9cb88b1cfd3e8bf16ddba71c
9ff0aa58a5f5137f8a9e374a809a1cb84bab04fb
refs/heads/master
2023-03-21T13:05:38.481014
2022-09-18T21:51:41
2022-09-18T21:51:41
197,598,973
1
0
null
2019-07-18T14:07:13
2019-07-18T14:07:13
null
UTF-8
C++
false
false
18,116
h
promptline.h
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * Xic Integrated Circuit Layout and Schematic Editor * * * *========================================================================* $Id:$ *========================================================================*/ #ifndef PROMPTLINE_H #define PROMPTLINE_H #include "cd_hypertext.h" // Defines for the Hypertext Editor // Passed to the text editing functions in cPromptLine and // cPromptEdit, determines response to button presses in drawing // window while editing: // PLedEndBtn: Button press acts like <Return>. // PLedIgnoreBtn: No "hypertext", press ignored. // enum PLedMode { PLedNormal, PLedEndBtn, PLedIgnoreBtn }; // Passed to the text editing functions in cPromptLine, determines how // the passed text string is handled. // PLedStart: Start of editing, initialize to string. // PLedInsert: String is inserted at cursor, other arguments are // ignored. // PLedUpdate: Prompt and string are updated. // enum PLedType { PLedStart, PLedInsert, PLedUpdate }; enum HYstate {hyOFF, hyACTIVE, hyESCAPE}; // cursor height #define CURHT 1 #define TOEND -1 #define UNDRAW false #define DRAW true // Text elements. // struct sHtxt { sHtxt() { h_c[0] = 0; h_c[1] = 0; h_type = HLrefEnd; h_ent = 0; h_str = 0; } void set_ent(char *str, hyEnt *ent) { h_c[0] = 0; h_c[1] = 0; h_type = HLrefEnd; h_ent = 0; h_str = 0; if (ent && str) { h_ent = ent; h_str = str; if (ent->ref_type() == HYrefNode) h_type = HLrefNode; else if (ent->ref_type() == HYrefBranch) h_type = HLrefBranch; else if (ent->ref_type() == HYrefDevice) h_type = HLrefDevice; } } void set_char(char ch) { h_c[0] = ch; h_c[1] = 0; h_type = HLrefText; h_ent = 0; h_str = 0; } void set_unichar(const char *cp) { char *c = h_c; while ((*c++ = *cp++) != 0) ; h_type = HLrefText; h_ent = 0; h_str = 0; } void set_lt(char *str) { h_c[0] = 0; h_c[1] = 0; h_type = HLrefLongText; h_ent = 0; h_str = str; } void upd_type(HLrefType t) { h_type = t; } void clear_free() { h_c[0] = 0; h_c[1] = 0; h_type = HLrefEnd; delete h_ent; h_ent = 0; delete [] h_str; h_str = 0; } const char *chr() const { return (h_c); } HLrefType type() const { return (h_type); } hyEnt *hyent() const { return (h_ent); } const char *string() const { return (h_str); } private: char h_c[8]; // Unicode character, if type == HLrefText HLrefType h_type; // reference type hyEnt *h_ent; // point struct for HLrefNode, HLrefBranch, HLrefDevice char *h_str; // string for HLrefNode, HLrefBranch, HLrefDevice }; // Prompt line buffer, allowing arbitrary line length. // struct sPromptBuffer { sPromptBuffer() { pb_size = 256; pb_hbuf = new sHtxt[pb_size]; pb_tsize = pb_size; pb_tbuf = new char[pb_tsize]; *pb_tbuf = 0; } // No destructor, allocated once in singleton. void set_ent(char *str, hyEnt *ent, int col) { if (check_size(col)) pb_hbuf[col].set_ent(str, ent); } void set_char(char ch, int col) { if (check_size(col)) pb_hbuf[col].set_char(ch); } void set_lt(char *str, int col) { if (check_size(col)) pb_hbuf[col].set_lt(str); } void upd_type(HLrefType t, int col) { if (check_size(col)) pb_hbuf[col].upd_type(t); } void clear_free(int col) { if (check_size(col)) pb_hbuf[col].clear_free(); } sHtxt *element(int col) { if (check_size(col)) return (pb_hbuf + col); return (0); } int size() { return (pb_size); } void insert(sHtxt*, int); void replace(sHtxt*, int); void swap(int, int); void remove(int); int endcol(); void clear_to_end(int); char *set_plain_text(const char*); char *get_plain_text(int); hyList *get_hyList(int, bool); private: bool check_size(int col) { if (col < 0) return (false); if (col >= pb_size) { sHtxt *tmp = new sHtxt[2*pb_size]; memcpy(tmp, pb_hbuf, pb_size*sizeof(sHtxt)); // Zero pointers for delete. memset((void*)pb_hbuf, 0, pb_size*sizeof(sHtxt)); delete [] pb_hbuf; pb_hbuf = tmp; pb_size += pb_size; } return (true); } sHtxt *pb_hbuf; // Hypertext main buffer. char *pb_tbuf; // Plain text, for editor return. int pb_size; // Size of main hypertext buffer. int pb_tsize; // Length of pb_tbuf. }; struct sUni; // Callback prototype for long text pop-up. typedef void(*LongTextCallback)(hyList*, void*); // Prompt-line text editor. // class cPromptEdit : virtual public GRdraw { public: cPromptEdit(); virtual ~cPromptEdit() { } void set_no_graphics() { pe_disabled = true; } void init(); void set_prompt(char*); char *get_prompt(); hyList *get_hyList(bool = false); char *edit_plain_text(const char*, const char*, const char*, PLedType, PLedMode); hyList *edit_hypertext(const char*, hyList*, const char*, bool, PLedType, PLedMode, LongTextCallback, void*); void init_edit(PLedMode = PLedNormal); bool editor(); void abort_long_text(); void abort(); void finish(bool); void insert(sHtxt*); void insert(const char*); void insert(hyList*); void replace(int, sHtxt*); void rotate_plotpts(int, int); void del_col(int, int); void show_del(int); void clear_cols_to_end(int); void set_col(int, bool=false); void set_offset(int); void text(const char*, int); void draw_text(bool, int, bool); void draw_cursor(bool); void draw_marks(bool); void redraw(); int bg_pixel(); void indicate(bool); bool key_handler(int, const char*, int); void button1_handler(bool); int find_ent(hyEnt*); void process_b1_text(char*, hyEnt*); void button_press_handler(int, int, int); void button_release_handler(int, int, int); void pointer_motion_handler(int, int); void lt_btn_press_handler(); void select(int, int); void deselect(bool = false); char *get_sel(); // Toolkit-specific functions. virtual void flash_msg(const char*, ...) = 0; // Pop up a message just above the prompt line for a couple // of seconds. virtual void flash_msg_here(int, int, const char*, ...) = 0; // As above, but let user pass position. virtual void save_line() = 0; // Save text in register 0. virtual int win_width(bool = false) = 0; // Return pixel width of rendering area, or width in chars // if arg is true. virtual void set_focus() = 0; // Set keyboard focus to this. virtual void set_indicate() = 0; // Turn on/off "editing" indicator. virtual void show_lt_button(bool) = 0; // Pop up/down the "L" button. virtual void get_selection(bool) = 0; // Push current selection into editor. virtual void *setup_backing(bool) = 0; // Initialize for drawing. virtual void restore_backing(void*) = 0; // Clean up after drawing. virtual void init_window() = 0; // Window initialization. virtual bool check_pixmap() = 0; // Reinitialize pixmap. virtual void init_selection(bool) = 0; // Text is selected or deselected. virtual void warp_pointer() = 0; // Move mouse pointer into editor. bool is_active() { return (pe_active == hyACTIVE); } bool is_off() { return (pe_active == hyOFF); } bool is_using_popup() { return (pe_using_popup); } void set_using_popup(bool b) { pe_using_popup = b; } bool is_long_text_mode() { return (pe_long_text_mode); } void set_long_text_mode(bool b) { pe_long_text_mode = b; } void set_col_min(int c) { pe_colmin = c; } bool exec_down_callback() { if (pe_down_callback) { (*pe_down_callback)(); return (true); } return (false); } bool exec_up_callback() { if (pe_up_callback) { (*pe_up_callback)(); return (true); } return (false); } bool exec_ctrl_d_callback() { if (pe_ctrl_d_callback) { (*pe_ctrl_d_callback)(); return (true); } return (false); } void set_down_callback(void(*c)()) { pe_down_callback = c; } void set_up_callback(void(*c)()) { pe_up_callback = c; } void set_ctrl_d_callback(void(*c)()) { pe_ctrl_d_callback = c; } bool is_obscure_mode() { return (pe_obscure_mode); } void set_obscure_mode(bool b) { pe_obscure_mode = b; } protected: GReditPopup *pe_lt_popup; // long text string editor void (*pe_down_callback)(); // misc. configurable callbacks void (*pe_up_callback)(); void (*pe_ctrl_d_callback)(); CDs *pe_pxdesc; // hooks for the button1_handler hyEnt *pe_pxent; HYstate pe_active; // true when editing int pe_colmin; // minimum cursor location int pe_cwid; // current cursor width in cols int pe_xpos, pe_ypos; // lower left coords of string int pe_offset; // drawing offset int pe_fntwid; // font size int pe_column; // current cursor column bool pe_firstinsert; // true before first insertion or cursor mvmt bool pe_indicating; // true when editing bool pe_disabled; // suppress actions bool pe_obscure_mode; // obscure text, for password entry bool pe_using_popup; // ShowPrompt() using pop-up bool pe_long_text_mode; // long text directive bool pe_in_select; // selection in progress bool pe_entered; // mouse pointer is in prompt area // For plot mark drag. bool pe_down; int pe_press_x; int pe_press_y; char *pe_last_string; hyEnt *pe_last_ent; // For text selection in non-editing mode. bool pe_has_drag; bool pe_dragged; int pe_drag_x; int pe_drag_y; int pe_sel_start; int pe_sel_end; // Transient unicode to utf8 encoder. sUni *pe_unichars; // Text buffer. sPromptBuffer pe_buf; }; // Struct to hold misc. context related to prompt line. // struct sPromptContext { struct stringlist_list { stringlist_list(stringlist *sl, stringlist_list *n) { list = sl; next = n; } stringlist *list; stringlist_list *next; }; sPromptContext() { pc_stuff_buf = 0; pc_prompt_stack = 0; pc_prompt_bak = 0; pc_saved_prompt = 0; pc_last_prompt = 0; pc_last_prompt_len = 0; pc_tee_fp1 = 0; pc_tee_fp2 = 0; } void stuff_string(const char*); char *pop_stuff(); void redirect(const char*); void open_fp1(const char*); void set_fp2(FILE*); char *cat_prompts(char*); void save_prompt(); void restore_prompt(); void push_prompt(const char*); void pop_prompt(); void save_last(const char*); const char *get_last(); private: stringlist *pc_stuff_buf; // List of pending editor input stringlist *pc_prompt_stack; // List of prefix strings for display stringlist_list *pc_prompt_bak; // Prompt stack storage stringlist *pc_saved_prompt; // Saved prompt strings char *pc_last_prompt; // The most recent prompt message int pc_last_prompt_len; // Allocated length of LastPrompt FILE *pc_tee_fp1; // User output redirection FILE *pc_tee_fp2; // Internal output redirection }; inline class cPromptLine *PL(); // Main class for prompt-line control // class cPromptLine { static cPromptLine *ptr() { if (!instancePtr) on_null_ptr(); return (instancePtr); } static void on_null_ptr(); public: friend inline cPromptLine *PL() { return (cPromptLine::ptr()); } cPromptLine(); // Initialization void SetNoGraphics(); void Init(); // Prompt line text display. void ShowPrompt(const char*); void ShowPromptV(const char*, ...); void ShowPromptNoTee(const char*); void ShowPromptNoTeeV(const char*, ...); char *GetPrompt(); hyList *List(bool = false); const char *GetLastPrompt(); void ErasePrompt(); void SavePrompt(); void RestorePrompt(); void PushPrompt(const char*); void PushPromptV(const char*, ...); void PopPrompt(); void TeePromptUser(const char*); void TeePrompt(FILE*); void FlashMessage(const char*); void FlashMessageV(const char*, ...); void FlashMessageHere(int, int, const char*); void FlashMessageHereV(int, int, const char*, ...); // Prompt line editing. bool IsEditing(); char *EditPrompt(const char*, const char*, PLedType = PLedStart, PLedMode = PLedNormal, bool = false); hyList *EditHypertextPrompt(const char*, hyList*, bool, PLedType = PLedStart, PLedMode = PLedNormal, void(*)(hyList*, void*) = 0, void* = 0); void RegisterArrowKeyCallbacks(void(*)(), void(*)()); void RegisterCtrlDCallback(void(*)()); void StuffEditBuf(const char*); void AbortLongText(); void AbortEdit(); // Functions for keypress buffer. Yes, this is handled here, too. void GetTextBuf(WindowDesc*, char*); void SetTextBuf(WindowDesc*, const char*); void ShowKeys(WindowDesc*); void SetKeys(WindowDesc*, const char*); void BspKeys(WindowDesc*); void CheckExec(WindowDesc*, bool); char *KeyBuf(WindowDesc*); int KeyPos(WindowDesc*); void SetEdit(cPromptEdit *e) { pl_edit = e; } private: void setupInterface(); sPromptContext pl_cx; cPromptEdit *pl_edit; static cPromptLine *instancePtr; }; // Unicode to UTF8 translation. struct sUni { sUni() { u_nchars = 0; } bool addc(int c) { // Up to 8 chars. if (u_nchars < 8 && isxdigit(c)) { u_buf[u_nchars++] = c; return (true); } return (false); } const char *utf8_encode(); private: int u_nchars; char u_buf[12]; }; #endif
978f4387fa1644ab60488fc2ef97aa8883e588b6
7e92933ea34318363395297a37e0e7d0951daefd
/single_hx711.ino
b8f1a97db8d409089ae88ae1736cdae4c98c0a1b
[]
no_license
navoneel07/engg1320-mylitnesspal
597f3ddaefee54c395da0bce08e8961967c0b591
5758d3a3ca8b015ad122f1c7518d492a6d8b3b60
refs/heads/master
2020-05-14T19:56:10.424074
2019-08-09T07:07:25
2019-08-09T07:07:25
181,937,293
2
1
null
2019-04-20T14:22:23
2019-04-17T17:19:41
Python
UTF-8
C++
false
false
512
ino
single_hx711.ino
#include "HX711.h" HX711 scale; //HX711 scale(6, 5); float calibration_factor = -417; float units; float ounces; void setup() { Serial.begin(9600); Serial.println("HX711 weighing"); scale.begin(3,2); scale.set_scale(calibration_factor); scale.tare(); Serial.println("Readings:"); } void loop() { Serial.print("Reading:"); units = scale.get_units(),10; if (units < 0) { units = 0.00; } ounces = units * 0.035274; Serial.print(units); Serial.println(" grams"); delay(1000); }
bc17c140d39769c35c7fd553753294eb406ad27d
263b0e4e43827bf79da675a9ba188632ddfc2560
/Induction.cpp
5c42749d37c782fad9687e260bcf0c4daf4cdd11
[]
no_license
ruishaopu561/algorithms
a0c24db96cdf3573422fabf78639a3f0c302869e
441e802c96a53fe9447733755bc7aed7e55e1ab9
refs/heads/master
2020-03-30T07:48:56.608501
2018-11-15T10:43:28
2018-11-15T10:43:28
150,968,413
0
0
null
2018-11-15T10:43:29
2018-09-30T13:11:22
null
UTF-8
C++
false
false
3,200
cpp
Induction.cpp
// EXPREC int power(int x, int n) { int y = 1; if (n == 0) { return y; } else { y = power(x, n / 2); y = y * y; if (n & 1) { y = x * y; } return y; } } // EXP void toBinary(vector<int> &d, int n) { while (n != 0) { d.push_back(n % 2); n /= 2; } d.push_back(n); } int power(int x, int n) { int y = 1; vector<int> d; toBinary(d, n); for (int i = d.size() - 1; i >= 0; i--) { y = y * y; if (d[i] == 1) { y = x * y; } } return y; } // HORNER(即秦九韶算法,不再赘述。) // PERMUTATIONS1 // print函数,无关紧要 void print(vector<int> vec) { int len = vec.size(); for (int i = 0; i < len; i++) { cout << vec[i] << " "; } cout << endl; } // 最常见的打印全排列的方式 void perm(int m, int n, vector<int> vec) { if (m == n) { print(vec); //count++; } else { for (int j = m - 1; j < n; j++) { int tem = vec[j]; vec[j] = vec[m - 1]; vec[m - 1] = tem; perm(m + 1, n, vec); tem = vec[j]; vec[j] = vec[m - 1]; vec[m - 1] = tem; } } } int main() { int n = 3; vector<int> vec; for (int i = 1; i < n + 1; i++) { vec.push_back(i); } perm(1, n, vec); //cout << count << endl; } // PERMUTATIONS2 void print(vector<int> vec) { int len = vec.size(); for (int i = 0; i < len; i++) { cout << vec[i] << " "; } cout << endl; } void perm(int m, vector<int> vec) { int n = vec.size(); if (m == 0) { print(vec); count++; } else { for (int j = 0; j < n; j++) { if (vec[j] == 0) { vec[j] = m; perm(m - 1, vec); vec[j] = 0; } } } } int main() { int n; cin >> n; vector<int> vec; for (int i = 0; i < n; i++) { vec.push_back(0); } perm(n, vec); cout << count << endl; } // MAJORITY #include <iostream> #include <vector> using namespace std; int majority(int n, vector<int> a) { int c = candidate(1, a); int count = 0; for (int j = 0; j < n; j++) { if (a[j] == c) { count++; } } if (count > a.size() / 2) { return c; } else { return -1; } } int candidate(int m, vector<int> a) { int j = m, c = a[m], count = 1, n = a.size(); while (j < n && count > 0) { j++; if (a[j] == c) { count++; } else { count--; } } if (j == n) { return c; } return candidate(j + 1, a); } int main() { int n; cin >> n; vector<int> a = {1, 2, 1, 3, 3, 2, 1, 2, 3, 2, 2, 2, 1, 1, 2, 2, 2, 1, 1, 2}; int out = majority(n, a); if (out > 0) { cout << out << endl; } else { cout << "none" << endl; } }
b4dc11406b6a4a4828739e38327009255fc05fa5
871433805fa810a8cba8ec800c54f8c2c2118224
/worldengine/source/plates.cpp
8cb4fba515dad5330ad97aaf4264ed6b12ffed6f
[ "MIT" ]
permissive
hiive/worldengine-cpp
efd540926dac0086492a944058ba87589a7e2d7b
9f7961aaf62db2633fc9d44b6018384812a6704e
refs/heads/master
2023-05-09T16:39:52.811356
2021-06-09T03:04:27
2021-06-09T03:04:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,661
cpp
plates.cpp
#include "worldengine/plates.h" #include "worldengine/generation.h" #include "worldengine/world.h" #include <chrono> #include <random> #include <boost/log/trivial.hpp> #include <boost/random.hpp> #include <platecapi.hpp> namespace WorldEngine { /** * @brief Create a new world based on an initial plates simulation * @param name World name * @param width Width in pixels * @param height Height in pixels * @param seed Random seed value * @param temps A list of six temperatures * @param humids A list of seven humidity values * @param gammaCurve Gamma value for temperature and precipitation on gamma * correction curve * @param curveOffset Adjustment value for temperature and precipitation gamma * correction curve * @param numPlates Number of plates * @param oceanLevel The elevation representing the ocean level * @param step Generation steps to perform * @return A new world */ static std::shared_ptr<World> PlatesSimulation(const std::string& name, uint32_t width, uint32_t height, uint32_t seed, const std::vector<float>& temps = DEFAULT_TEMPS, const std::vector<float>& humids = DEFAULT_HUMIDS, float gammaCurve = DEFAULT_GAMMA_CURVE, float curveOffset = DEFAULT_CURVE_OFFSET, uint32_t numPlates = DEFAULT_NUM_PLATES, float oceanLevel = DEFAULT_OCEAN_LEVEL, const Step& step = DEFAULT_STEP); std::shared_ptr<World> WorldGen(const std::string& name, uint32_t width, uint32_t height, uint32_t seed, const std::vector<float>& temps, const std::vector<float>& humids, float gammaCurve, float curveOffset, uint32_t numPlates, float oceanLevel, const Step& step, bool fadeBorders) { std::chrono::steady_clock::time_point startTime; std::chrono::steady_clock::time_point endTime; startTime = std::chrono::steady_clock::now(); std::shared_ptr<World> world = PlatesSimulation(name, width, height, seed, temps, humids, gammaCurve, curveOffset, numPlates, oceanLevel, step); CenterLand(*world); endTime = std::chrono::steady_clock::now(); auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime) .count(); BOOST_LOG_TRIVIAL(debug) << "WorldGen(): setElevation, setPlates, centerLand complete. " << "Elapsed time " << elapsedTime << "ms."; startTime = std::chrono::steady_clock::now(); std::mt19937 generator(seed); boost::random::uniform_int_distribution<uint32_t> distribution(0, UINT32_MAX); AddNoiseToElevation(*world, distribution(generator)); endTime = std::chrono::steady_clock::now(); elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime) .count(); BOOST_LOG_TRIVIAL(debug) << "WorldGen(): elevation noise added. " << "Elapsed time " << elapsedTime << "ms."; startTime = std::chrono::steady_clock::now(); if (fadeBorders) PlaceOceansAtMapBorders(*world); InitializeOceanAndThresholds(*world); endTime = std::chrono::steady_clock::now(); elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime) .count(); BOOST_LOG_TRIVIAL(debug) << "WorldGen(): oceans initialized. " << "Elapsed time " << elapsedTime << "ms."; GenerateWorld(*world, step, distribution(generator)); return world; } void* GeneratePlatesSimulation(float** heightmap, uint32_t** platesmap, long seed, uint32_t width, uint32_t height, float seaLevel, uint32_t erosionPeriod, float foldingRatio, uint32_t aggrOverlapAbs, float aggrOverlapRel, uint32_t cycleCount, uint32_t numPlates) { std::chrono::steady_clock::time_point startTime; std::chrono::steady_clock::time_point endTime; startTime = std::chrono::steady_clock::now(); void* p = platec_api_create(seed, width, height, seaLevel, erosionPeriod, foldingRatio, aggrOverlapAbs, aggrOverlapRel, cycleCount, numPlates); // Note: To rescale the world's heightmap to roughly Earth's scale, multiply // by 2000 while (!platec_api_is_finished(p)) { platec_api_step(p); } *heightmap = platec_api_get_heightmap(p); *platesmap = platec_api_get_platesmap(p); endTime = std::chrono::steady_clock::now(); auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime) .count(); BOOST_LOG_TRIVIAL(debug) << "GeneratePlatesSimulation() complete. " << "Elapsed time " << elapsedTime << "ms."; return p; } void PlatecApiDestroy(void* p) { platec_api_destroy(p); } static std::shared_ptr<World> PlatesSimulation(const std::string& name, uint32_t width, uint32_t height, uint32_t seed, const std::vector<float>& temps, const std::vector<float>& humids, float gammaCurve, float curveOffset, uint32_t numPlates, float oceanLevel, const Step& step) { float* heightmap; uint32_t* platesmap; void* p = GeneratePlatesSimulation(&heightmap, &platesmap, seed, width, height, DEFAULT_SEA_LEVEL, DEFAULT_EROSION_PERIOD, DEFAULT_FOLDING_RATIO, DEFAULT_AGGR_OVERLAP_ABS, DEFAULT_AGGR_OVERLAP_REL, DEFAULT_CYCLE_COUNT, numPlates); std::shared_ptr<World> world = std::shared_ptr<World>( new World(name, Size(width, height), seed, GenerationParameters(numPlates, oceanLevel, step), temps, humids, gammaCurve, curveOffset)); world->SetElevationData(heightmap); world->SetPlatesData(platesmap); PlatecApiDestroy(p); return world; } } // namespace WorldEngine
a788c7304b2399b119e0922efbf4fc6101a0f80b
dbf38fdd01888c0f6828a7d0e112f5fc2268b26c
/main1c.cpp
e5fa26732cb0f64fddfa3ae30570927dd26031a8
[]
no_license
tfeher/trt_type_examples
1d3221dfb3c540ae754e32217b11c504c0dfffa2
f8d4b55fa44930829f188949040f4fd6dd8cd824
refs/heads/master
2023-02-25T02:31:02.736886
2021-01-26T21:09:55
2021-01-26T21:29:41
276,362,474
0
0
null
null
null
null
UTF-8
C++
false
false
7,945
cpp
main1c.cpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "buffers.h" #include "common.h" #include "logger.h" #include "NvInfer.h" #include <iostream> #include <sstream> #include <string> #include <vector> const std::string gSampleName = "Type1c"; /** * This example is derived from the TensorRT samples published at * https://github.com/NVIDIA/TensorRT. The aim of this example is to test * TensorRT networks that have tensors with multiple types. */ class TrtExample { template <typename T> using SampleUniquePtr = std::unique_ptr<T, samplesCommon::InferDeleter>; public: TrtExample() : mEngine(nullptr) {} //! //! \brief Function builds the network engine //! bool build(); //! //! \brief Runs the TensorRT inference engine for this sample //! bool infer(); private: std::shared_ptr<nvinfer1::ICudaEngine> mEngine; //!< The TensorRT engine used to run the network //! //! \brief Uses the TensorRT API to create the Network //! bool constructNetwork(SampleUniquePtr<nvinfer1::IBuilder> &builder, SampleUniquePtr<nvinfer1::INetworkDefinition> &network, SampleUniquePtr<nvinfer1::IBuilderConfig> &config); //! //! \brief Reads the input and stores the result in a managed buffer //! bool processInput(const samplesCommon::BufferManager &buffers); //! //! \brief Classifies digits and verify result //! bool verifyOutput(const samplesCommon::BufferManager &buffers); }; //! //! \brief Creates the network, configures the builder and creates the engine //! //! \details This function creates the network by using the API to create a //! model and builds the engine that will be used to run the network //! //! \return Returns true if the engine was created successfully and false //! otherwise //! bool TrtExample::build() { auto builder = SampleUniquePtr<nvinfer1::IBuilder>( nvinfer1::createInferBuilder(gLogger.getTRTLogger())); if (!builder) { return false; } uint32_t flags = 1U << static_cast<int>( nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH); auto network = SampleUniquePtr<nvinfer1::INetworkDefinition>( builder->createNetworkV2(flags)); if (!network) { return false; } auto config = SampleUniquePtr<nvinfer1::IBuilderConfig>(builder->createBuilderConfig()); if (!config) { return false; } config->setFlag(nvinfer1::BuilderFlag::kFP16); config->setFlag(nvinfer1::BuilderFlag::kINT8); config->setFlag(BuilderFlag::kSTRICT_TYPES); auto constructed = constructNetwork(builder, network, config); if (!constructed) { return false; } return true; } //! //! \brief Uses the API to create the Network //! bool TrtExample::constructNetwork( SampleUniquePtr<nvinfer1::IBuilder> &builder, SampleUniquePtr<nvinfer1::INetworkDefinition> &network, SampleUniquePtr<nvinfer1::IBuilderConfig> &config) { nvinfer1::Dims dims{4, {1, 2, 3, 1}}; nvinfer1::ITensor *input = network->addInput("input", nvinfer1::DataType::kINT8, dims); assert(input); input->setDynamicRange(-128.0f, 127.0f); nvinfer1::IActivationLayer *A = network->addActivation(*input, nvinfer1::ActivationType::kRELU); assert(A); A->setName("A"); A->setOutputType(0, nvinfer1::DataType::kINT8); nvinfer1::ITensor *x = A->getOutput(0); x->setDynamicRange(-128.0f, 127.0f); auto *B = network->addUnary(*x, nvinfer1::UnaryOperation::kNEG); // auto *B = network->addElementWise(*x, *x, ElementWiseOperation::kSUM); assert(B); B->setName("B"); B->setOutputType(0, nvinfer1::DataType::kINT8); nvinfer1::ITensor *y = B->getOutput(0); y->setDynamicRange(-128.0f, 127.0f); nvinfer1::ITensor *output = B->getOutput(0); output->setName("output"); network->markOutput(*output); switch (output->getType()) { case nvinfer1::DataType::kINT8: gLogInfo << "Otput type is INT8" << std::endl; break; case nvinfer1::DataType::kINT32: gLogInfo << "Otput type is INT32" << std::endl; break; case nvinfer1::DataType::kFLOAT: gLogInfo << "Otput type is FP32" << std::endl; break; case nvinfer1::DataType::kHALF: gLogInfo << "Otput type is FP16" << std::endl; break; default: gLogInfo << "Otput type is unknown" << std::endl; } // Set allowed formats for this tensor. By default all formats are allowed. // Shape tensors may only have row major linear format. // Note that formats here define layout // network->getInput(0)->setAllowedFormats(formats); // network->getOutput(0)->setAllowedFormats(formats); config->setMaxWorkspaceSize(16_MiB); mEngine = std::shared_ptr<nvinfer1::ICudaEngine>( builder->buildEngineWithConfig(*network, *config), samplesCommon::InferDeleter()); if (!mEngine) { return false; } gLogInfo << "Engine constructed successfully" << std::endl; return true; } //! //! \brief Runs the TensorRT inference engine for this sample //! //! \details This function is the main execution function of the sample. It //! allocates the buffer, //! sets inputs and executes the engine. //! bool TrtExample::infer() { auto context = SampleUniquePtr<nvinfer1::IExecutionContext>( mEngine->createExecutionContext()); if (!context) { return false; } // Create RAII buffer manager object samplesCommon::BufferManager buffers(mEngine, 0, context.get()); int n_inputs = 0; for (int i = 0; i < mEngine->getNbBindings(); i++) { if (mEngine->bindingIsInput(i)) n_inputs++; } if (n_inputs > 0) { auto input_dims = context->getBindingDimensions(0); std::vector<float> values{-2, -1, 0, 1, 2, 3}; // Read the input data into the managed buffers uint8_t *hostShapeBuffer = static_cast<uint8_t *>(buffers.getHostBuffer("input")); for (int i = 0; i < values.size(); i++) { std::cout << "Setting input value " << i << ": " << values[i] << "\n"; hostShapeBuffer[i] = values[i]; } // Memcpy from host input buffers to device input buffers buffers.copyInputToDevice(); } bool status = context->executeV2(buffers.getDeviceBindings().data()); if (!status) { return false; } // Memcpy from device output buffers to host output buffers buffers.copyOutputToHost(); // Verify results std::vector<float> expected_output{0, 0, 0, -1, -2, -3}; float *res = static_cast<float *>(buffers.getHostBuffer("output")); // int *res = static_cast<int *>(buffers.getHostBuffer("output")); std::cout << "\nOutput:\n" << std::endl; bool correct = true; for (int i = 0; i < expected_output.size(); i++) { if (std::abs(res[i] - expected_output[i]) > 0.025) { std::cout << i << ": error incorrect value " << res[i] << " vs " << expected_output[i] << "\n"; correct = false; } else { std::cout << i << ": " << res[i] << "\n"; } } return correct; } int main(int argc, char **argv) { auto sampleTest = gLogger.defineTest(gSampleName, argc, argv); gLogger.reportTestStart(sampleTest); TrtExample sample; gLogInfo << "Building and running inference engine for shape example" << std::endl; if (!sample.build()) { return gLogger.reportFail(sampleTest); } if (!sample.infer()) { return gLogger.reportFail(sampleTest); } return gLogger.reportPass(sampleTest); }
974afae7c98cb5edd492a84f9be40f10d6f2068c
0a264c136331aa7c926df48061bbeaeae34afec6
/template/dispatcher.cpp
85e50a099764860f26185bd01ef852eb3e613227
[]
no_license
wenwuge/EasyLib
e28b64238cc5ebd4dafbcfb8f2eabb483cdbe52f
2151e0246ec971024200c318d61694e23ec7df1f
refs/heads/master
2022-10-25T15:58:09.725483
2022-10-19T07:37:24
2022-10-19T07:37:24
42,303,639
20
16
null
null
null
null
UTF-8
C++
false
false
1,875
cpp
dispatcher.cpp
#include <iostream> #include <map> #include <string> #include <boost/function.hpp> #include <boost/bind.hpp> using namespace std; class Message{ }; class Message1:public Message{ }; class Message2:public Message{ }; class CallbackBase{ public: virtual void output(Message* message) = 0; }; template <typename T> class CallbackT: public CallbackBase{ public: typedef boost::function<void(T*)> CallbackFunc; CallbackT(CallbackFunc func):callback_(func){} void output(Message* message) { callback_(static_cast<T*>(message)); } private: CallbackFunc callback_; }; class Dispatcher{ public: //use template to solve the params question. template <typename T> void RegisterCallback(int id , typename CallbackT<T>::CallbackFunc callback) { //using base and derived class to resolve the callback storage question callback_map_[id] = new CallbackT<T>(callback); } void Run(int id); private: std::map<int, CallbackBase*> callback_map_; }; void Dispatcher::Run(int id) { switch (id){ case 1: { Message1* message1 = new Message1; callback_map_[1]->output(message1); } break; case 2: { Message2* message2 = new Message2; callback_map_[2]->output(message2); } break; default: cout << "not found id" << endl; break; } } void OutputMessage1(Message1 * message) { cout << "output message1" << endl; } void OutputMessage2(Message2 * message) { cout << "outout message2" << endl; } int main(int argc, char** argv) { Dispatcher dispatcher; dispatcher.RegisterCallback<Message1>(1, boost::bind(&OutputMessage1, _1)); dispatcher.RegisterCallback<Message2>(2, boost::bind(&OutputMessage2, _1)); dispatcher.Run(1); dispatcher.Run(2); return 0; }
81795a88d64d4c85622db777214bd991a478f84e
4f7fe96947220db4d2ce19471e02b1151fe00bfb
/src/parse.cpp
56d67e8a9d0b67a196fdc63ed0c3011573c9c5f5
[ "MIT" ]
permissive
henrikt-ma/cadical
f6a8d90909dd5967c04767ca154cb0ef57ba7530
58331fd078cb5f76bae52e25de0e34c6a7dd4c1d
refs/heads/master
2020-04-22T09:40:54.085319
2018-07-15T16:07:14
2018-07-15T16:07:14
170,281,392
0
0
MIT
2019-02-12T08:32:41
2019-02-12T08:32:38
C++
UTF-8
C++
false
false
5,894
cpp
parse.cpp
#include "internal.hpp" /*------------------------------------------------------------------------*/ namespace CaDiCaL { /*------------------------------------------------------------------------*/ // Parsing utilities. inline int Parser::parse_char () { return file->get (); } // Return an non zero error string if a parse error occurred. inline const char * Parser::parse_string (const char * str, char prev) { for (const char * p = str; *p; p++) if (parse_char () == *p) prev = *p; else PER ("expected '%c' after '%c'", *p, prev); return 0; } inline const char * Parser::parse_positive_int (int & ch, int & res, const char * name) { assert (isdigit (ch)); res = ch - '0'; while (isdigit (ch = parse_char ())) { int digit = ch - '0'; if (INT_MAX/10 < res || INT_MAX - digit < 10*res) PER ("too large '%s' in header", name); res = 10*res + digit; } return 0; } inline const char * Parser::parse_lit (int & ch, int & lit, const int vars) { int sign = 0; if (ch == '-') { if (!isdigit (ch = parse_char ())) PER ("expected digit after '-'"); sign = -1; } else if (!isdigit (ch)) PER ("expected digit or '-'"); else sign = 1; lit = ch - '0'; while (isdigit (ch = parse_char ())) { int digit = ch - '0'; if (INT_MAX/10 < lit || INT_MAX - digit < 10*lit) PER ("literal too large"); lit = 10*lit + digit; } if (ch == '\r') ch = parse_char (); if (ch != 'c' && ch != ' ' && ch != '\t' && ch != '\n' && ch != EOF) PER ("expected white space after '%d'", sign*lit); if (lit > vars) PER ("literal %d exceeds maximum variable %d", sign*lit, vars); lit *= sign; return 0; } /*------------------------------------------------------------------------*/ // Parsing function for CNF in DIMACS format. const char * Parser::parse_dimacs_non_profiled () { int ch, vars = 0, clauses = 0; for (;;) { ch = parse_char (); if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\r') continue; if (ch != 'c') break; string buf; while ((ch = parse_char ()) != '\n') if (ch == EOF) PER ("unexpected end-of-file in header comment"); else if (ch != '\r') buf.push_back (ch); const char * o; for (o = buf.c_str (); *o && *o != '-'; o++) ; if (!*o) continue; VRB ("parse-dimacs", "found option '%s'", o); if (*o) internal->opts.set (o); } if (ch != 'p') PER ("expected 'c' or 'p'"); const char * err = parse_string (" cnf ", 'p'); if (err) return err; if (!isdigit (ch = parse_char ())) PER ("expected digit after 'p cnf '"); err = parse_positive_int (ch, vars, "<max-var>"); if (err) return err; if (ch != ' ') PER ("expected ' ' after 'p cnf %d'", vars); if (!isdigit (ch = parse_char ())) PER ("expected digit after 'p cnf %d '", vars); err = parse_positive_int (ch, clauses, "<num-clauses>"); if (err) return err; while (ch == ' ' || ch == '\r') ch = parse_char (); if (ch != '\n') PER ("expected new-line after 'p cnf %d %d'", vars, clauses); MSG ("found 'p cnf %d %d' header", vars, clauses); external->init (vars); int lit = 0, parsed = 0; while ((ch = parse_char ()) != EOF) { if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\r') continue; if (ch == 'c') { COMMENT: while ((ch = parse_char ()) != '\n' && ch != EOF) ; if (ch == EOF) break; continue; } err = parse_lit (ch, lit, vars); if (err) return err; if (ch == 'c') goto COMMENT; external->add (lit); if (!lit && parsed++ >= clauses && !internal->opts.force) PER ("too many clauses"); } if (lit) PER ("last clause without '0'"); if (parsed < clauses && !internal->opts.force) PER ("clause missing"); MSG ("parsed %d clauses in %.2f seconds", parsed, process_time ()); return 0; } /*------------------------------------------------------------------------*/ // Parsing function for a solution in competition output format. const char * Parser::parse_solution_non_profiled () { NEW_ZERO (external->solution, signed_char, external->max_var + 1); int ch; for (;;) { ch = parse_char (); if (ch == EOF) PER ("missing 's' line"); else if (ch == 'c') { while ((ch = parse_char ()) != '\n') if (ch == EOF) PER ("unexpected end-of-file in comment"); } else if (ch == 's') break; else PER ("expected 'c' or 's'"); } const char * err = parse_string (" SATISFIABLE", 's'); if (err) return err; if ((ch = parse_char ()) == '\r') ch = parse_char (); if (ch != '\n') PER ("expected new-line after 's SATISFIABLE'"); int count = 0; for (;;) { ch = parse_char (); if (ch != 'v') PER ("expected 'v' at start-of-line"); if ((ch = parse_char ()) != ' ') PER ("expected ' ' after 'v'"); int lit = 0; ch = parse_char (); do { if (ch == ' ' || ch == '\t') { ch = parse_char (); continue; } err = parse_lit (ch, lit, external->max_var); if (err) return err; if (ch == 'c') PER ("unexpected comment"); if (!lit) break; if (external->solution[abs (lit)]) PER ("variable %d occurs twice", abs (lit)); LOG ("solution %d", lit); external->solution [abs (lit)] = sign (lit); count++; if (ch == '\r') ch = parse_char (); } while (ch != '\n'); if (!lit) break; } MSG ("parsed %d solutions %.2f%%", count, percent (count, external->max_var)); return 0; } /*------------------------------------------------------------------------*/ // Wrappers to profile parsing and at the same time use the convenient // implicit 'return' in PER in the non-profiled versions. const char * Parser::parse_dimacs () { START (parse); const char * err = parse_dimacs_non_profiled (); STOP (parse); return err; } const char * Parser::parse_solution () { START (parse); const char * err = parse_solution_non_profiled (); STOP (parse); return err; } };
dd768e623de46909dcd1c59c0ae061bb9de66ab5
db661ec37fc4fc02c56ddc1f0810454e150e5271
/servo_trial.ino
413934d9488555d3d48272d0b529fcd76fecb069
[]
no_license
vengadam2001/arduino
e4b27b9a04ad3cc3d1e237f4a18417bac7f97d94
2505330e4995f470b246e4feefcf2a27272712eb
refs/heads/master
2020-08-05T23:23:55.922824
2020-03-28T13:40:57
2020-03-28T13:40:57
212,753,590
2
1
null
null
null
null
UTF-8
C++
false
false
387
ino
servo_trial.ino
#include<Servo.h> Servo servo; void setup() { // put your setup code here, to run once: servo.attach(9); Serial.begin(9600); Serial.print("enter the value:"); } void loop() { int x=10; // put your main code here, to run repeatedly: while(Serial.available()==0) { } x=Serial.parseInt(); Serial.print("entered value is : "); Serial.println(x); servo.write(x); }
410ba845dac7eaa7b072b88ad65919f18510e743
c25fa228e19f6ef4d63dc11d59baaae4981101c0
/src_smartcontract_db/schema_table/table/CdbTableColumn.h
10220d3688ce9380b89fa2b87ebaa67904341558
[ "MIT" ]
permissive
alinous-core/codablecash
b994e710144af3f6b69bda2f3d1dff080b2fd2b0
030fa9ee2e79ae2cade33aa80e80fb532c5b66ee
refs/heads/master
2023-08-31T04:30:14.333123
2023-08-12T11:33:06
2023-08-12T11:33:06
129,185,961
11
4
MIT
2023-08-13T14:10:25
2018-04-12T03:14:00
C++
UTF-8
C++
false
false
2,294
h
CdbTableColumn.h
/* * CdbTableColumn.h * * Created on: 2020/05/13 * Author: iizuka */ #ifndef TABLE_CDBTABLECOLUMN_H_ #define TABLE_CDBTABLECOLUMN_H_ #include <cstdint> #include "engine/CdbBinaryObject.h" namespace alinous { class UnicodeString; class ByteBuffer; class AlterModifyCommand; } using namespace alinous; namespace codablecash { class CdbOid; class SchemaObjectIdPublisher; class ScanResultFieldMetadata; class CdbTable; class ColumnModifyContext; class AbstractScanTableTarget; class LocalCdbOid; class CdbTableColumn : public CdbBinaryObject { public: static const constexpr uint8_t CDB_OBJ_TYPE{2}; CdbTableColumn(const CdbTableColumn& inst); explicit CdbTableColumn(uint64_t oid); explicit CdbTableColumn(const CdbOid* oid); virtual ~CdbTableColumn(); const CdbOid* getOid() const noexcept; void setName(const UnicodeString* name) noexcept; const UnicodeString* getName() const noexcept; void setType(uint8_t type, int length) noexcept; void setAttributes(bool notnull, bool unique) noexcept; void setDefaultValue(const UnicodeString* defaultValue) noexcept; const UnicodeString* getDefaultValue() const noexcept { return defaultValue; } bool isUnique() const noexcept { return unique; } bool isNotnull() const noexcept { return notnull; } int getLength() const noexcept { return length; } void assignNewOid(SchemaObjectIdPublisher* publisher); void setOid(uint64_t oid) noexcept; int binarySize() const; void toBinary(ByteBuffer* out) const; void fromBinary(ByteBuffer* in); int getPosition() const noexcept; void setPosition(int position) noexcept; uint8_t getType() const noexcept { return this->type; } ScanResultFieldMetadata* getFieldMetadata(const AbstractScanTableTarget* sourceTarget) const noexcept; ColumnModifyContext* createModifyContextwithChange(const AlterModifyCommand* cmd, const UnicodeString* defaultStr); ColumnModifyContext* createModifyContextwithChange(const AlterModifyCommand* cmd, const UnicodeString* defaultStr, bool update); void __testCheckEquals(CdbTableColumn* other); private: CdbOid* oid; UnicodeString* name; uint8_t type; int length; bool notnull; bool unique; UnicodeString* defaultValue; int position; }; } /* namespace codablecash */ #endif /* TABLE_CDBTABLECOLUMN_H_ */
e5b41d448f6f125a224c1acd32aecc318a93e42b
7d93616b09afdd38ba25f70bf56e84d92d16f8e1
/willow/include/popart/op/ceil.hpp
9e174f8124d1bd7c6ae39ab75cbe8d6006e654a8
[ "MIT", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
graphcore/popart
ac3c71617c5f0ac5dadab179b655f6b2372b453d
efa24e27f09b707865326fe4a30f4a65b7a031fe
refs/heads/sdk-release-3.0
2023-07-08T08:36:28.342159
2022-09-23T12:22:35
2022-09-23T15:10:23
276,412,857
73
13
NOASSERTION
2022-09-29T12:13:40
2020-07-01T15:21:50
C++
UTF-8
C++
false
false
885
hpp
ceil.hpp
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #ifndef POPART_WILLOW_INCLUDE_POPART_OP_CEIL_HPP_ #define POPART_WILLOW_INCLUDE_POPART_OP_CEIL_HPP_ #include <memory> #include <tuple> #include <vector> #include <popart/op/onewayunary.hpp> #include "popart/op.hpp" namespace popart { struct OperatorIdentifier; class CeilOp : public OneWayUnaryOp { public: CeilOp(const OperatorIdentifier &_opid, const Op::Settings &settings_); std::unique_ptr<Op> clone() const override; std::vector<std::tuple<OperatorIdentifier, float>> inplacePriorityDefault() const final; std::unique_ptr<Op> getInplaceVariant(const OperatorIdentifier &) const final; }; class CeilInplaceOp : public OneWayUnaryInPlaceOp { public: CeilInplaceOp(const CeilOp &); std::unique_ptr<Op> clone() const final; }; } // namespace popart #endif // POPART_WILLOW_INCLUDE_POPART_OP_CEIL_HPP_
2ce1c054965842155136d2219ea15d5ef94b0f5d
6c49fad41b5109d4dabc4db0007e1ae931ee4898
/2018 Summer/Assignments/Assignment05/ChoudhryBilal326/Button.cpp
b702ef85a2c5f7748f6cedb7f9b0598443fd7960
[]
no_license
ZainAU/oop
964fbf6701ccac77fe14d04d83fb7f5d11b1cb15
a895b7ce10ed4ec09a2e178005bb82da7b58e32e
refs/heads/master
2022-01-06T21:03:26.842634
2018-09-26T05:35:13
2018-09-26T05:35:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
951
cpp
Button.cpp
#include "Button.h" #include<iostream> using namespace std; Button::Button() { width = 64; height = 64; } Button::Button(LTexture* image, float x, float y) { spriteSheetTexture = image; //Frame 0 spriteClips.x = 0; spriteClips.y = 432; spriteClips.w = 64; spriteClips.h = 64; //Frame 1 spriteClips.x = 64; spriteClips.y = 432; spriteClips.w = 64; spriteClips.h = 64; //Frame 2 spriteClips.x = 128; spriteClips.y = 432; spriteClips.w = 64; spriteClips.h = 64; position.x = x; position.y = y; this->width = spriteClips.w; this->height = spriteClips.h; } void Button::Render(string buttonToDraw,long int& frame, SDL_Renderer* gRenderer, bool debug) { int seq = 0; for(string::iterator it=buttonToDraw.begin(); it!=buttonToDraw.end(); it++) { ch.Render(int(*it),seq,buttonToDraw.length(),frame, gRenderer, false); seq++; } }
32762b0b725860221071b80b94bd6e9df59ea5b1
21dfd5124c2f05ef5f98355996dc2313f1a29f5a
/Src/Modules/Configuration/CameraCalibrator.h
a2c0d53f161cc9fa883f6777a9871471a060ed69
[ "BSD-2-Clause" ]
permissive
fabba/BH2013-with-coach
50244c3f69135cc18004a1af9e01604617b6859f
88d7ddc43456edc5daf0e259c058f6eca2ff8ef6
refs/heads/master
2020-05-16T03:21:29.005314
2015-03-04T10:41:08
2015-03-04T10:41:08
31,651,432
1
0
null
null
null
null
UTF-8
C++
false
false
11,424
h
CameraCalibrator.h
/** * @file CameraCalibrator.h * * This file implements a module that can provide a semiautomatic camera calibration. * * @author Alexander Härtl */ #pragma once #include "Tools/Module/Module.h" #include "Representations/Modeling/RobotPose.h" #include "Representations/Configuration/FieldDimensions.h" #include "Representations/Configuration/CameraCalibration.h" #include "Representations/Configuration/RobotDimensions.h" #include "Representations/Infrastructure/JointData.h" #include "Representations/Infrastructure/CameraInfo.h" #include "Representations/Sensing/TorsoMatrix.h" #include "Tools/Math/YaMatrix.h" #include "Tools/Math/Geometry.h" #include <algorithm> MODULE(CameraCalibrator) REQUIRES(FieldDimensions) REQUIRES(FilteredJointData) REQUIRES(RobotDimensions) REQUIRES(TorsoMatrix) REQUIRES(CameraInfo) USES(RobotPose) USES(CameraMatrix) PROVIDES_WITH_MODIFY(CameraCalibration) DEFINES_PARAMETER(bool, calibrateBothCameras, true) /**< Whether both cameras or only the lower camera should be calibrated */ DEFINES_PARAMETER(bool, errorInImage, true) /**< Whether the error is computed from the distance in the image or on the ground */ DEFINES_PARAMETER(float, terminationCriterion, 0.01f) /**< The difference of two succesive parameter sets that are taken as a convergation */ DEFINES_PARAMETER(float, aboveHorizonError, 1000000.f) /**< The error for a sample the error of which cannot be computed regularly */ DEFINES_PARAMETER(int, numOfFramesToWait, 15) /**< The number of frames to wait between two iterations (necessary to keep the debug connection alive) */ DEFINES_PARAMETER(int, minSuccessiveConvergations, 5) /**< The number of consecutive iterations that fulfil the termination criterion to converge */ END_MODULE class CameraCalibrator : public CameraCalibratorBase { private: /** * The current state of the calibrator. */ ENUM(CalibrationState, Idle, Accumulate, Optimize ); CalibrationState calibrationState; /** * A class representing a single reference point within the calibration procedure. * It contains all information necessary to construct a camera matrix for the point * in time the sample was taken using an arbitrary camera calibration. */ class Sample { public: Vector2<int> pointInImage; TorsoMatrix torsoMatrix; float headYaw, headPitch; bool upperCamera; }; /** * This enum is used to translate between the indices of the parameter vector used in the * optimizer and their actual meaning. */ ENUM(ParameterTranslation, cameraTiltCorrection, cameraRollCorrection, bodyTiltCorrection, bodyRollCorrection, robotPoseCorrectionX, robotPoseCorrectionY, robotPoseCorrectionRot, numOfParametersLowerCamera, upperCameraX = numOfParametersLowerCamera, upperCameraY, upperCameraZ ); std::vector<Sample> samples; /**< The set of samples used to calibrate the camera. */ Vector2<int> lastFetchedPoint; /**< The coordinates of the last fetched point in the image. */ /** * The method to calculate the new camera calibration, depending on the state of the calibrator. * @param cameraCalibration The current calibration of the robot's camera. */ void update(CameraCalibration& cameraCalibration); /** * This method computes the distance of a sampled point to the next field line, either in image * image coordinates using the back projection of the field lines into the image, or in field * coordinates using the projection of the point onto the field plane. The error is computed * using the given camera calibration from which a modified camera matrix is built. * @param sample The sample point for which the distance / error should be computed. * @param cameraCalibration The camera calibration used to compute the error. * @param robotPose The assumed robot pose. * @param inImage Whether the distance in image or in field coordinates should be computed. * @return The distance. */ float computeError(const Sample& sample, const CameraCalibration& cameraCalibration, const RobotPose& robotPose, bool inImage = true) const; /** * This method computes the error value for a sample and a parameter vector. * @param sample The sample point for which the distance / error should be computed. * @param parameters The parameter vector for which the error should be evaluated. * @return The error. */ float computeErrorParameterVector(const Sample& sample, const std::vector<float>& parameters) const; /** * This method converts a parameter vector to a camera calibration and a robot pose they stand for. * @param parameters The parameter vector to be translated. * @param cameraCalibration The camera calibration the values of which are set to the corresponding values in the parameter vector. * @param robotPose The robot pose the values of which are set to the corresponding values in the parameter vector. */ void translateParameters(const std::vector<float>& parameters, CameraCalibration& cameraCalibration, RobotPose& robotPose) const; /** * This method converts a camera calibration and a robot pose to a parameter vector. * @param cameraCalibration The camera calibration to be translated. * @param robotPose The robot pose to be translated. * @param parameters The resulting parameter vector containing the values from the given camera calibration and robot pose. */ void translateParameters(const CameraCalibration& cameraCalibration, const RobotPose& robotPose, std::vector<float>& parameters) const; /** * The method to fetch a point from a click in the image view. */ void fetchPoint(); /** * This method projects a line given in robot relative field coordinates into * the image using an arbitrary camera matrix. * @param lineOnField The field line in robot relative coordinates. * @param cameraMatrix The camera matrix used for the projection. * @param lineInImage The field line projected into the image, if this is possible. * @return Whether a valid result was computed, which is not the case if the field line lies completely behind the camera plane. */ bool projectLineOnFieldIntoImage(const Geometry::Line& lineOnField, const CameraMatrix& cameraMatrix, Geometry::Line& lineInImage) const; /** * This method creates a debug drawing in which all field lines are projected into the image. */ void drawFieldLines(); /** * This class implements the Gauss-Newton algorithm. * A set of parameters is optimized in regard of the sum of squared errors using * a given error function. The jacobian that is computed in each iteration is * approximated numerically. * @tparam M The class that represents a single measurement / sample. * @tparam C The class the error function is a member of. */ template <class M, class C> class GaussNewtonOptimizer { private: const unsigned int numOfMeasurements; /**< The number of measurements. */ const unsigned int numOfParameters; /**< The number of parameters. */ YaMatrix<float> currentParameters; /**< The vector (Nx1-matrix) containing the current parameters. */ YaMatrix<float> currentValues; /**< The vector (Nx1-matrix) containing the current error values for all measurements. */ const std::vector<M>& measurements; /**< A reference to the vector containing all measurements. */ const C& object; /**< The object used to call the error function. */ float(C::*pFunction)(const M& measurement, const std::vector<float>& parameters) const; /**< A pointer to the error function. */ const float delta; /**< The delta used to approximate the partial derivatives of the Jacobian. */ public: GaussNewtonOptimizer(const std::vector<float>& parameters, const std::vector<M>& measurements, const C& object, float(C::*pFunction)(const M& measurement, const std::vector<float>& parameters) const) : numOfMeasurements(measurements.size()), numOfParameters(parameters.size()), currentParameters(numOfParameters, 1), currentValues(numOfMeasurements, 1), measurements(measurements), object(object), pFunction(pFunction), delta(0.001f) { for(unsigned int i = 0; i < numOfParameters; ++i) { currentParameters[i][0] = parameters[i]; } for(unsigned int i = 0; i < numOfMeasurements; ++i) { currentValues[i][0] = (object.*pFunction)(measurements[i], currentParameters.transpose()[0]); } } /** * This method executes one iteration of the Gauss-Newton algorithm. * The new parameter vector is computed by a_i+1 = a_i - (D^T * D)^-1 * D^T * r * where D is the Jacobian, a is the parameter vector and r is the vector containing the current error values. * @return The sum of absolute differences between the old and the new parameter vector. */ float iterate() { // build jacobi matrix YaMatrix<float> jacobiMatrix(numOfMeasurements, numOfParameters); for(unsigned int j = 0; j < numOfParameters; ++j) { // the first derivative is approximated using values slightly above and below the current value const float oldParameter = currentParameters[j][0]; const float parameterAbove = oldParameter + delta; const float parameterBelow = oldParameter - delta; for(unsigned int i = 0; i < numOfMeasurements; ++i) { // approximate first derivation numerically currentParameters[j][0] = parameterAbove; const float valueAbove = (object.*pFunction)(measurements[i], currentParameters.transpose()[0]); currentParameters[j][0] = parameterBelow; const float valueBelow = (object.*pFunction)(measurements[i], currentParameters.transpose()[0]); const float derivation = (valueAbove - valueBelow) / (2.0f * delta); jacobiMatrix[i][j] = derivation; } currentParameters[j][0] = oldParameter; } try { YaMatrix<float> result = (jacobiMatrix.transpose() * jacobiMatrix).inverse() * jacobiMatrix.transpose() * currentValues; currentParameters -= result; for(unsigned int i = 0; i < numOfMeasurements; ++i) { currentValues[i][0] = (object.*pFunction)(measurements[i], currentParameters.transpose()[0]); } float sum = 0; for(unsigned int i = 0; i < numOfParameters; ++i) { sum += std::abs(result[i][0]); } return sum; } catch(...) { return 0.0f; } } /** * The method returns the current parameter vector. * @return The current parameter vector. */ std::vector<float> getParameters() const { return currentParameters.transpose()[0]; } }; GaussNewtonOptimizer<Sample, CameraCalibrator>* optimizer; /**< A pointer to the currently used optimizer, or NULL if there is none. */ int successiveConvergations; /**< The number of consecutive iterations that fulfil the termination criterion. */ int framesToWait; /**< The remaining number of frames to wait for the next iteration. */ const CameraCalibration* currentCameraCalibration; /**< A pointer to the current camera calibration, refreshed in every call of the update method. */ public: /** Default constructor. */ CameraCalibrator(); /** Destructor. */ ~CameraCalibrator(); };
6b1662b1b847c18a5f1970619c34530a2bc928fd
ddd288fbef7dc9e86dae4c1d236da631f8407b3b
/CGP600 AE2/Renderer.h
67e544804da11d51c5c84d16d59de3e3acf37d37
[]
no_license
JamesSkett/Advanced-Games-Programming
752f75575f787cb1412b3ed2dfad68c4884b2ef0
b3b72e922b95a91bfd6c89e3695f1ac97994d1a6
refs/heads/master
2021-09-03T04:32:22.330551
2018-01-05T15:28:16
2018-01-05T15:28:16
108,906,605
0
0
null
null
null
null
UTF-8
C++
false
false
2,670
h
Renderer.h
#pragma once #include <d3d11.h> #include <d3dx11.h> #include <dxerr.h> #include <dinput.h> #include <sstream> #include <DirectXMath.h> using namespace DirectX; #include "Camera.h" #include "CXBOXController.h" #include "text2D.h" #include "Mesh.h" #include "Scene_Node.h" #include "SkyBox.h" #include "Time.h" #include "Planet.h" __declspec(align(16)) class Renderer { public: void* operator new(size_t i) { return _mm_malloc(i, 16); } void operator delete(void* p) { return _mm_free(p); } Renderer(); ~Renderer(); //DirectX Setup HRESULT InitialiseWindow(HINSTANCE hInstance, int nCmdShow); HRESULT InitialiseD3D(); //delete objects from memory before exiting void ShutdownD3D(); //render objects in game void RenderFrame(Scene_Node* rootNode, vector <Planet*> planets); //render object in menu void RenderFrame(Text2D * button1, Text2D * button2, bool &isDone); //Set up the graphics HRESULT InitialiseGraphics(void); //set up the keyboard and mouse input HRESULT InitialiseInput(); void ReadInputState(); bool IsKeyPressed(unsigned char DI_keycode); DIMOUSESTATE mouseCurrState; //These can be used in any class static Camera* camera; static SkyBox* skyBox; static Time time; static ID3D11Device* m_pD3DDevice; static ID3D11DeviceContext* m_pImmediateContext; //matrices for object transforms XMMATRIX identity, projection, view; //Destroys the program window void DestroyWin(); private: //screen properties const float m_screenWidth = 1920.0f; const float m_screenHeight = 1080.0f; //Name of the Game char m_GameName[100] = "Space Game\0"; HINSTANCE m_hInst = NULL; //Drivers D3D_DRIVER_TYPE m_driverType = D3D_DRIVER_TYPE_NULL; D3D_FEATURE_LEVEL m_featureLevel = D3D_FEATURE_LEVEL_11_0; IDXGISwapChain* m_pSwapChain = NULL; //Shader and depth view variables ID3D11RenderTargetView* m_pBackBufferRTView = NULL; ID3D11Buffer* m_pVertexBuffer; ID3D11VertexShader* m_pVertexShader; ID3D11PixelShader* m_pPixelShader; ID3D11InputLayout* m_pInputLayout; ID3D11Buffer* m_pConstantBuffer0; ID3D11DepthStencilView* m_pzBuffer; ID3D11ShaderResourceView* m_pTexture0; ID3D11SamplerState* m_pSampler0; ID3D11BlendState* m_pAlphaBlendEnable; ID3D11BlendState* m_pAlphaBlendDisable; //keyboard and mouse variables IDirectInput8* m_direct_input; IDirectInputDevice8* m_keyboard_device; IDirectInputDevice8* m_mouse_device; unsigned char m_keyboard_keys_state[256]; //Frame counter variables Text2D* m_FPSCount; int m_fps = 0; };
dc0e63bd665b671f016eda50adf6dfadb0e31771
4c86be24a8485c6f6711a76bd1bb1d4f04e8935f
/Source/UnrealCV/Private/ServerConfig.cpp
5bb686c4716be4ba0a253ef2bfd5ea22d213e5d1
[ "MIT" ]
permissive
GeekLiB/unrealcv
c3a1eafdbedfb7c4414ed82ebd359b73516bc9f1
9acfcb5b52c5b085e72e64a0bb46ea4d0adadcdb
refs/heads/master
2020-04-06T04:13:01.935172
2017-02-24T09:12:56
2017-02-24T09:12:56
83,023,414
1
4
null
null
null
null
UTF-8
C++
false
false
1,015
cpp
ServerConfig.cpp
#include "UnrealCVPrivate.h" #include "ServerConfig.h" bool FServerConfig::Load() { if (!GConfig) return false; FString CoreSection = "UnrealCV.Core"; // Assume the value will not be overwrote if the read failed GConfig->GetInt(*CoreSection, TEXT("Port"), this->Port, this->ConfigFile); GConfig->GetInt(*CoreSection, TEXT("Width"), this->Width, this->ConfigFile); GConfig->GetInt(*CoreSection, TEXT("Height"), this->Height, this->ConfigFile); // What will happen if the field not exist return true; } bool FServerConfig::Save() { // Reference: https://wiki.unrealengine.com/Config_Files,_Read_%26_Write_to_Config_Files if (!GConfig) return false; FString CoreSection = "UnrealCV.Core"; GConfig->SetInt(*CoreSection, TEXT("Port"), this->Port, this->ConfigFile); GConfig->SetInt(*CoreSection, TEXT("Width"), this->Width, this->ConfigFile); GConfig->SetInt(*CoreSection, TEXT("Height"), this->Height, this->ConfigFile); bool Read = false; GConfig->Flush(Read, this->ConfigFile); return true; }
f9aac5497a22728ebe5fa852b7a9572ef5615087
703137e3a9caa49c3535aa34497d2a710af9f134
/630C.cpp
8ff1eba32e014d1531d6398508a996daa709a286
[]
no_license
toha993/Codeforces-My-Code
a558d175204d08167cb1b8e70dd0fb0d2b727d0e
8521f325be45775a477c63a4dddb1e21e486d824
refs/heads/master
2022-12-21T06:07:22.131597
2020-10-04T11:50:26
2020-10-04T11:50:26
301,116,681
0
0
null
null
null
null
UTF-8
C++
false
false
192
cpp
630C.cpp
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; long long ans=0; for(int i=1;i<=n;i++) { ans +=pow(2,i); } cout << ans << endl; }
837776a51909b6344423206db193fcd127810ac3
5f6a29fdbe41e7f221536c5fa6c35baf59c77e6b
/Carrito/RemoteControl/motor_control.cpp
5ca628c7fa474ed8f937ae4b53f3291c4b945257
[]
no_license
vladimir1284/Micropython
f971346ca74ce9e3adbfc63313c87b4d1446e101
3b573faf6115b74baa5af31e701888b512aa4feb
refs/heads/master
2022-08-05T04:54:19.373001
2022-07-22T15:06:05
2022-07-22T15:06:05
234,114,591
0
1
null
null
null
null
UTF-8
C++
false
false
1,843
cpp
motor_control.cpp
#include "motor_control.h" #include <Arduino.h> Motor::Motor(int pinEN, int pin1, int pin2, int ledc_chann) { pinSpeed = pinEN; pinM1 = pin1; pinM2 = pin2; channel = ledc_chann; } void Motor::setSpeedFactor(float speedFactor) { sf = speedFactor; } void Motor::run() { if (delayNeeded) { if (millis() - lastStopped > waitTime) { delayNeeded = false; } } } void Motor::init(float speedFactor) { pinMode(pinM1, OUTPUT); pinMode(pinM2, OUTPUT); pinMode(pinSpeed, OUTPUT); ledcAttachPin(pinSpeed, channel); // assign pin to channel // Configure channel ledcSetup(channel, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT); delayNeeded = false; currentState = STOPPED; setSpeedFactor(speedFactor); } void Motor::moveForward(int speed) { if ((currentState != BACKWARD) && !delayNeeded) { digitalWrite(pinM1, LOW); digitalWrite(pinM2, HIGH); ledcWrite(channel, computeSpeed(speed)); currentState = FORWARD; } else { fullStop(); } } void Motor::moveBackward(int speed) { if ((currentState != FORWARD) && !delayNeeded) { digitalWrite(pinM1, HIGH); digitalWrite(pinM2, LOW); ledcWrite(channel, computeSpeed(speed)); currentState = BACKWARD; } else { fullStop(); } } void Motor::fullStop() { if (currentState != STOPPED) { digitalWrite(pinM1, LOW); digitalWrite(pinM2, LOW); ledcWrite(channel, 0); currentState = STOPPED; lastStopped = millis(); delayNeeded = true; } } int Motor::computeSpeed(int speed) { int output = round(speed * ((MAX_SPEED - MIN_SPEED) * sf) / 9 + MIN_SPEED); if (DEBUG) { Serial.print(output); } return output; }
bf5fb9672be93e1df4d31112215a7896af8767ae
98b8aa2733069fdd10130990d8a847e80fbeb1d0
/civilizacion.cpp
b0cb8c996d21ca4383c47c5ae8292429f5a3b329
[]
no_license
alan-martinez/proyecto_civilizaciones
e54e291bf64e52947874ad7d681f4f13eeb4e21c
67b93a906a794aff25c26a9f39cfeb3088524c5c
refs/heads/main
2023-06-03T20:27:33.402500
2021-06-27T23:41:55
2021-06-27T23:41:55
380,572,099
0
0
null
null
null
null
UTF-8
C++
false
false
13,197
cpp
civilizacion.cpp
#include "civilizacion.h" #include <fstream> #include <iostream> //#include <stack> using namespace std; Civilizacion::Civilizacion() { } Civilizacion::Civilizacion(const string &nombre, int ubicacion_x, int ubicacion_y, int puntuacion) { this->nombre = nombre; this->ubicacion_x = ubicacion_x; this->ubicacion_y = ubicacion_y; this->puntuacion = puntuacion; } void Civilizacion::setNombre(const string &nombre) { this->nombre=nombre; } string Civilizacion::getNombre() { return nombre; } void Civilizacion::setUbicacion_x(int ubicacion_x) { this->ubicacion_x = ubicacion_x; } int Civilizacion::getUbicacion_x() { return ubicacion_x; } void Civilizacion::setUbicacion_y(int ubicacion_y) { this->ubicacion_y = ubicacion_y; } int Civilizacion::getUbicacion_y() { return ubicacion_y; } void Civilizacion::setPuntuacion(int puntuacion) { this->puntuacion = puntuacion; } int Civilizacion::getPuntuacion() const { return puntuacion; } void Civilizacion::agregarFinalAldeano(const Aldeano &a) { aldeano.push_back(a); puntuacion = puntuacion + 100; } void Civilizacion::agregarInicioAldeano(const Aldeano &a) { aldeano.push_front(a); puntuacion = puntuacion + 100; } void Civilizacion::mostrar() { cout << left; cout << setw(10) << "Nombre"; cout << setw(12) << "Edad"; cout << setw(12) << "Genero"; cout << setw(10) << "Salud"; cout << endl; for (auto it = aldeano.begin(); it!= aldeano.end(); it++) { cout << *it << endl; } } void Civilizacion::eliminar(const string &nombre) { for (auto it = aldeano.begin(); it != aldeano.end(); it++){ Aldeano &a = *it; if (nombre == a.getNombre()){ aldeano.erase(it); break; } } } // bool comparador(const Aldeano &a) // { // size_t salud; // cout << "Introduce la salud del aldeano: " << endl; // cin >> salud; cin.ignore(); // cout << "Se eliminara los aldeanos de salud menor a: " + salud << endl; // return a.getSalud() < salud; // } void Civilizacion::eliminarSalud(int salud) { //aldeano.remove_if(comparador); aldeano.remove_if([salud](const Aldeano &a){return a.getSalud() < salud;}); } bool comparadorEdad(const Aldeano &a) { return a.getEdad() >= 60; } void Civilizacion::eliminarEdad() { aldeano.remove_if(comparadorEdad); } void Civilizacion::ordenarNombre() { aldeano.sort(); } bool comparadoraEdad(const Aldeano &a1, const Aldeano &a2) { return a1.getEdad() > a2.getEdad(); } void Civilizacion::ordenarEdad() { aldeano.sort(comparadoraEdad); } void Civilizacion::ordenarSalud() { aldeano.sort([](const Aldeano &a1, const Aldeano &a2){return a1.getSalud() > a2.getSalud();}); } Aldeano* Civilizacion::buscar(string nombre) { for (auto it = aldeano.begin(); it != aldeano.end(); it++){ Aldeano &a = *it; if (nombre == a.getNombre()) { return &(*it); } } return nullptr; } void Civilizacion::modificar(Aldeano *ptr) { size_t i; size_t pos = 0; size_t op; string nombreNuevo; int edadNueva; string generoNuevo; int saludNueva; // for (i = 0; i < aldeano.size(); i++) // { // for (auto it = aldeano.begin(); it != aldeano.end(); it++) // { Aldeano &a = *ptr; if (ptr->getNombre() == a.getNombre()) { pos = 1; cout << endl; cout << "Datos del aldeano: " << endl; cout << "Nombre: " << a.getNombre() << endl; cout << "Edad: " << a.getEdad() << endl; cout << "Genero: " << a.getGenero() << endl; cout << "Salud: " << a.getSalud() << endl; cout << endl; cout << "¿Que quieres modificar?: " << endl; cout << "1.- Nombre" << endl; cout << "2.- Edad" << endl; cout << "3.- Genero" << endl; cout << "4.- Salud" << endl; cin >> (op); switch(op) { case 1: cout << "Nombre nuevo: "; cin.ignore(); getline(cin, nombreNuevo); a.setNombre(nombreNuevo); break; case 2: cout << "Edad nueva: "; cin.ignore(); cin >> edadNueva; a.setEdad(edadNueva); break; case 3: cout << "Genero nuevo: "; cin.ignore(); getline(cin, generoNuevo); a.setGenero(generoNuevo); break; case 4: cout << "Salud nueva: "; cin.ignore(); cin >> saludNueva; a.setSalud(saludNueva); break; } cout << "Modificacion exitosa!" << endl; cout << endl; } // } // } } void Civilizacion::respaldarAldeano() { ofstream aldeanos (getNombre()+".txt", ios::out); for (auto it = aldeano.begin(); it != aldeano.end(); it++) { Aldeano& aldeano = *it; aldeanos << aldeano.getNombre() << endl; aldeanos << aldeano.getEdad() << endl; aldeanos << aldeano.getGenero() << endl; aldeanos << aldeano.getSalud() << endl; } aldeanos.close(); } void Civilizacion::recuperarAldeano() { ifstream archivo(getNombre()+ ".txt"); if (archivo.is_open()){ //size_t t; Civilizacion c; //t = stoi(temp); int edad; int salud; string temp; Aldeano a; while (true) { getline (archivo, temp); //t = stoi(temp); if (archivo.eof()){ break; } a.setNombre(temp); getline(archivo, temp); edad = stoi(temp); a.setEdad(edad); getline(archivo, temp); //t = stoi(temp); a.setGenero(temp); getline(archivo, temp); salud = stoi(temp); a.setSalud(salud); agregarFinalAldeano(a); } } archivo.close(); } //TODO ACT 14 // void Civilizacion::agregarBarco(Barco *b) // { // puerto.push_back(b); // } void Civilizacion::capturarBarco( Civilizacion &c) { int id; double combustible; float velocidad, armadura; Barco *b = new Barco(); // b->setVelocidad(0); // b->setArmadura(100); cout << "Id: "; cin >> id; b->setId(id); cout << "Combustible: (0-100) "; cin >> combustible; b->setCombustible(combustible); cin.ignore(); cout << "Velocidad: (0.0 - 14.0) "; cin >> velocidad; b->setVelocidad(velocidad); cout << "Armadura: (0.0 - 100.0) "; cin >> armadura; b->setArmadura(armadura); //Agregar el barco a la civilizacion c.agregarBarco(b); } void Civilizacion::mostrarBarcos(Civilizacion &c) { if (puerto.empty()) { cout << "No hay barcos registrados" << endl; } else{ cout <<"Barcos de " << c.getNombre() << endl; cout << left; cout << setw(10) << "Id"; cout << setw(15) << "Combustible"; cout << setw(12) << "Velocidad"; cout << setw(15) << "Armadura"; cout << setw(10) << "Cant. Guerreros"; cout << endl; // for (auto const &e: puerto){ // cout << *e << endl; //} //} for (auto it = puerto.begin(); it != puerto.end(); it++) { auto &e = *it; //cout << "barco" << endl; cout << *e << endl; } } } void Civilizacion::buscarBarcos(Civilizacion &c) { Guerrero guerrero; int id; cout << "Ingresa el id a buscar: " << endl; cin >> id; cin.ignore(); for (auto it = puerto.begin(); it != puerto.end(); it++){ Barco *b = *it; if (id == b->getId()) { auto &e = *it; //cout << "barco" << endl; cout << endl; cout << "Barco encontrado!" << endl << endl; cout << left; cout << setw(10) << "Id"; cout << setw(15) << "Combustible"; cout << setw(12) << "Velocidad"; cout << setw(15) << "Armadura"; cout << setw(10) << "Cant. Guerreros"; cout << endl; cout << *e << endl; //return *it; size_t opcion; cout << "Menu de Guerreros" << endl; cout << "1.- Agregar guerrero" << endl; cout << "2.- Eliminar guerrero" << endl; cout << "3.- Mostrar ultimo guerrero" << endl; cout << "4.- Mostrar todos los guerrero" << endl; cout << "0.- Salir" << endl; cin >> opcion; cin.ignore(); switch (opcion) { case 1: { Guerrero guerrero; int salud; int id; float fuerza, escudo; //string tipo; string tipo; cout << "Id guerrero: " << endl; cin >> id; cin.ignore(); //getline(cin, id); cin.ignore(); guerrero.setId(id); cout << "Salud: (0-100) "<< endl; cin >> salud; guerrero.setSalud(salud); cout << "Fuerza: (0.0 - 60.0) " << endl; cin >> fuerza; guerrero.setFuerza(fuerza); cout << "Escudo: (0.0 - 30.0) " << endl; cin >> escudo; guerrero.setEscudo(escudo); cin.ignore(); cout << "Tipo: (lancero, arquero, paladin, etc) " << endl; getline (cin, tipo); cin.ignore(); // //cin >> tipo; guerrero.setTipo(tipo); b->agregarGuerrero(guerrero); } break; case 2: { Guerrero guerrero; b->eliminarGuerrero(guerrero); } break; case 3: { //3Guerrero guerrero; b->topeGuerrero(); //cout << &b; cout << endl; //cout << &guerrero; } break; case 4: { // Guerrero c; b->mostrar(); } case 0: break; } /* TODO La opción *Buscar barcos* pedirá el id, si no existe el barco con tal id, mostrar mensaje. Si existe el barco, mostrar el siguiente menú de opciones: - Agregar Guerrero (captura y agrega *-apilar-* un guerrero al *stack* de guerreros del barco). - Eliminar Guerrero (manda llamar al método para eliminar *-desapilar-* guerrero). - Mostrar último guerrero (manda llamar al método de tope). - Mostrar todos los Guerreros (hace una copia del *stack* de guerreros y usa la copia para desapilar y mostrar). */ } } } void Civilizacion::eliminarCombustible(Civilizacion &c ) { float combustible; cout << "Intoduce barco con combustible menor a eliminar: "<< endl; cin >> combustible; cin.ignore(); puerto.remove_if([combustible](Barco* b){ if (b->getCombustible() < combustible){ cout << "Se elimino correctamente" << endl; delete b; return true; } else{ return false; } }); } // bool comparador(const Barco *b) // { // int id; // cout << "Introduce el ID del barco: " << endl; // cin >> id; cin.ignore(); // //cout << "Se eliminara los aldeanos de salud menor a: " + salud << endl; // return b->getId() == id; // //return a.getSalud() < salud; // } void Civilizacion::eliminarId(Civilizacion &c) { int id; cout << "Intoduce barco con ID a eliminar: "<< endl; cin >> id; cin.ignore(); puerto.remove_if([id](Barco* b){ if (b->getId() == id) { cout << "Se elimino correctamente" << endl; delete b; return true; } else { return false; } }); }
32babca0fd07966600e592f94ca0cde32cd67484
2155daba7e51775c32e266b6ac962ec10074b1ac
/counter.ino
9074927c443908a54c66be994efb4caefbc90a03
[]
no_license
ShoolinLab/Arduino
4551bf0cd88ed4035704e9ff8b7a29f32fcf2645
cc7d8ae4a2ddbbd4ddead17ed227af5246aad947
refs/heads/master
2020-03-19T03:05:40.202408
2018-10-30T18:56:09
2018-10-30T18:56:09
135,694,391
2
0
null
null
null
null
UTF-8
C++
false
false
392
ino
counter.ino
#include<LiquidCrystal.h> LiquidCrystal lcd(2, 3, 4, 5, 6, 7); int st = 0; int count = 0; void setup() { // put your setup code here, to run once: lcd.begin(16, 2); pinMode(8, INPUT); } void loop() { // put your main code here, to run repeatedly: st = digitalRead(8); if (st == 1) { count = count + 1; lcd.setCursor(1, 0); lcd.print(count); lcd.clear(); } }
dae6a83380c5a84107d6eadc0daa4432bc7c8719
cd0515449a11d4fc8c3807edfce6f2b3e9b748d3
/src/yb/yql/redis/redisserver/redis_server.h
7ec783ed1c9d870fdca9d8c431ec1578876b213b
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "OpenSSL" ]
permissive
wwjiang007/yugabyte-db
27e14de6f26af8c6b1c5ec2db4c14b33f7442762
d56b534a0bc1e8f89d1cf44142227de48ec69f27
refs/heads/master
2023-07-20T13:20:25.270832
2023-07-11T08:55:18
2023-07-12T10:21:24
150,573,130
0
0
Apache-2.0
2019-07-23T06:48:08
2018-09-27T10:59:24
C
UTF-8
C++
false
false
1,552
h
redis_server.h
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #pragma once #include <string> #include "yb/gutil/macros.h" #include "yb/yql/redis/redisserver/redis_server_options.h" #include "yb/server/server_base.h" #include "yb/tserver/tserver_fwd.h" #include "yb/util/status_fwd.h" namespace yb { namespace redisserver { class RedisServer : public server::RpcAndWebServerBase { public: static const uint16_t kDefaultPort = 6379; static const uint16_t kDefaultWebPort = 11000; explicit RedisServer(const RedisServerOptions& opts, tserver::TabletServerIf* tserver); Status Start(); using server::RpcAndWebServerBase::Shutdown; tserver::TabletServerIf* tserver() const { return tserver_; } const std::shared_ptr<MemTracker>& mem_tracker() const { return mem_tracker_; } const RedisServerOptions& opts() const { return opts_; } private: RedisServerOptions opts_; tserver::TabletServerIf* const tserver_; DISALLOW_COPY_AND_ASSIGN(RedisServer); }; } // namespace redisserver } // namespace yb
c7219b99f6934162930849fc5f0d65b04d3d6641
81b93a8bc16023e31171ce68da0751b3a428696f
/src/fsm/include/state_remote.h
a78cf6ed18c8a3a61b9ad6709a72ce8b2d8e7dc9
[]
no_license
github188/agv
3373b9b86203b0b2b98019abfc1058112eb394e2
3577ea7f0b561eb791241327a4c05e325d76808c
refs/heads/master
2022-04-03T20:29:43.938463
2019-12-19T10:22:05
2019-12-19T10:22:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,230
h
state_remote.h
#ifndef FSM_INCLUDE_STATE_REMOTE_H_ #define FSM_INCLUDE_STATE_REMOTE_H_ #include "ros/ros.h" #include "state_base_machine.h" #include "state_define.h" namespace superg_agv { namespace fsm { class RemoteState : public StateBase { public: RemoteState(int id_, StateMachine *fsm_) : StateBase(id, p_machine) { this->id = id_; this->p_machine = fsm_; this->status_ = 0; this->vms_status_ = 0; time_reset_tip_ = 0; state_status_pub_tip = 0; cur_state_status.time_in = ros::Time::now(); cur_state_status.time_out = ros::Time::now(); cur_state_status.cur_state = REMOTE; ad_status_tip_ = cur_state_status.cur_state; hmi_status_tip_ = cur_state_status.cur_state; } virtual int doStateLoop() { onEnter(); onStay(); onExit(); return cur_state_status.next_state; } virtual void onEnter() { //获取上次状态 cur_state_status.late_state = p_machine->getLateState(); if (time_reset_tip_ == 0) { ROS_INFO("enter %s state, late state is %s", AgvStateStr[cur_state_status.cur_state].c_str(), AgvStateStr[cur_state_status.late_state].c_str()); cur_state_status.time_in = ros::Time::now(); time_reset_tip_ = 1; } //进入动作 doEnterAction(cur_state_status.late_state); } virtual void onStay() { p_machine->doStateMachineSpinOnce(); //判断AD状态 if (ad_status_tip_ != NULL_STATE_ID && status_ > 0) { cur_state_status.next_state = ad_status_tip_; } else { cur_state_status.next_state = cur_state_status.cur_state; } } virtual void onExit() { doExitAction(cur_state_status.next_state); cur_state_status.time_out = ros::Time::now(); status_ = 0; vms_status_ = 0; if (cur_state_status.cur_state != cur_state_status.next_state) { ROS_INFO("%s -->> %.8lf(s) -->> %s", AgvStateStr[cur_state_status.cur_state].c_str(), cur_state_status.time_out.toSec() - cur_state_status.time_in.toSec(), AgvStateStr[cur_state_status.next_state].c_str()); time_reset_tip_ = 0; } } virtual void doEnterAction(int &state_) { //通用初始化状态切换标志 status_ = 0; vms_status_ = 0; node_enable_value_ = p_machine->getNodeEnableValue(); node_enable_status_ = p_machine->getAdEnableValue(); node_fsm_control_ = fsmControlOperation(); //根据前置状态选择不同的动作 if (state_ == STARTUP) { } else if (state_ == EXCEPTION) { } else if (state_ == STANDBY) { } else if (state_ == REMOTE) { } else if (state_ == PLANNING) { } else if (state_ == OPERATION) { } else { } } virtual void doExitAction(int &state_) { //根据后续状态选择不同的动作 node_enable_value_ = changeNodeEnableValue(node_enable_value_, state_); if (state_ == STARTUP) { node_enable_status_ = nodeAdDisable(); node_fsm_control_ = fsmControlNull(); } else if (state_ == EXCEPTION) { node_enable_status_ = nodeAdEnable(); node_fsm_control_ = fsmControlOperation(); //下发任务 p_machine->taskControlPub(node_fsm_control_, state_); } else { node_enable_status_ = nodeAdDisable(); node_fsm_control_ = fsmControlNull(); } //改变控制权 enableNode(node_enable_value_, node_enable_status_); if (1 == state_status_pub_tip) { state_status_pub_tip = 0; //心跳 p_machine->vcuControlPub(); //状态 p_machine->fsmStatusPub(); } } virtual int doAdStatusJudge(const AdStatusValue &cur_ad_status_) { if (isRemoteState(cur_ad_status_)) { return REMOTE; } else if (isExceptionState(cur_ad_status_)) { return EXCEPTION; } else if (isAdStatusOK(cur_ad_status_)) { return STANDBY; } else { return cur_state_status.cur_state; } } public: }; } // namespace fsm } // namespace superg_agv #endif
e8147614e0831b517fdf08e38e2f9bfcc8378970
7b33ac7c4b71d6678b649fc4c22deb37df929577
/1.代码/1.c语言/OJ453.cpp
6a71d0e3345e8ca3b91de548906702b0c679eaab
[]
no_license
dofo-eat/Code_Learned
0c857e3db14a1a2b6678fe2d7e044d47a3dff157
abba556678adbf5033b16bc5c610dae6a36816db
refs/heads/master
2021-07-10T21:20:34.093910
2020-12-12T09:28:33
2020-12-12T09:28:33
224,192,229
1
1
null
null
null
null
UTF-8
C++
false
false
629
cpp
OJ453.cpp
/************************************************************************* > File Name: OJ453.cpp > Author: dofo-eat > Mail:2354787023@qq.com > Created Time: 2019年12月06日 星期五 19时47分43秒 ************************************************************************/ #include<iostream> #include<algorithm> using namespace std; int b[10005]; int main() { int n, m; int temp; cin >> n >> m; int a[10000] = {0}; for(int i = 0; i < n;i++) { cin >> temp; if(b[temp] == 0) a[++a[0]] = temp, b[temp] = 1; } sort(a + 1, a + a[0] + 1); cout << a[m] << endl; return 0; }
af049ae392533f19d4790df0de23a43a2feb94f0
cdf3150fca9c8be880335ebe1e96201c813a4795
/homework/Feldman/05/Row.cpp
34e6a9eea89a8ab63147c35c5bc530d38d08791b
[ "MIT" ]
permissive
mtrempoltsev/msu_cpp_autumn_2017
af2b13377b0132c8204980d484cf07c9673e3165
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
refs/heads/master
2021-09-20T04:08:23.316188
2018-08-03T09:23:51
2018-08-03T09:23:51
104,074,449
10
22
null
2017-09-28T21:35:52
2017-09-19T12:52:20
C++
UTF-8
C++
false
false
349
cpp
Row.cpp
#include <vector> #pragma once template <class T> class Row { public: std::vector<T> row; unsigned int cols; Row(int cols_, T val) :cols(cols_){ for (size_t i = 0; i < cols; ++i) row.push_back(val); } T& operator [] (size_t col) { if (col >= cols) { std::cout << "OUT OF RANGE!" << std::endl; exit(1); } return row[col]; } };
341938dd4742e787c38d2bac1b0909ff8cf1b91d
65f16cfe6932a9c30c5fabb6a33d8621a2d09e5d
/volume003/CF 334 B - Eight Point Sets.cpp
c9520f74bc2d37a19f021936ce4c88eb0ffd3b89
[]
no_license
Daviswww/Submissions-by-UVa-etc
b059d5920964b8f361042fbceeaabc8b27e0ea61
b16a43e54a0563d42b2721ebdaf570cdd24c4840
refs/heads/master
2022-11-09T13:53:37.852564
2022-10-30T08:28:35
2022-10-30T08:28:35
143,992,796
1
0
null
null
null
null
UTF-8
C++
false
false
728
cpp
CF 334 B - Eight Point Sets.cpp
#include <iostream> #include <algorithm> using namespace std; struct P { int x; int y; }; bool comp(P a, P b) { if(a.x == b.x) { return a.y < b.y; } return a.x < b.x; } int main() { P p[8]; for(int i = 0; i < 8; ++i) { cin >> p[i].x >> p[i].y; } sort(p, p + 8, comp); if(p[0].x == p[1].x && p[1].x == p[2].x && p[2].x != p[3].x && p[3].x == p[4].x && p[4].x != p[5].x && p[5].x == p[6].x && p[6].x == p[7].x && p[0].y == p[3].y && p[3].y == p[5].y && p[0].y != p[1].y && p[1].y == p[6].y && p[1].y != p[2].y && p[2].y == p[4].y && p[4].y == p[7].y) { cout << "respectable" << endl; } else { cout << "ugly" << endl; } return 0; }
0288ec224f02eb739a8892e5151ec18c03211f2c
7fd96632466bd0982892adb398b197e3e045dea9
/Bulgarian School Contests/NOI2(National Olympiad in Informatics Round 2)/2011/C/barrels_noi2.cpp
b0debe6b5b051f41b0a81e12578852f877f45bdc
[]
no_license
ivokaragyozov/Programming-Contests
1be413a82d0f8e0f476b77432d67deb4d60547e7
3b0cdbba1afb45b3480f10370107947f0413416c
refs/heads/master
2016-08-10T20:20:00.229319
2016-02-19T09:30:28
2016-02-19T09:30:28
51,910,903
1
0
null
null
null
null
UTF-8
C++
false
false
617
cpp
barrels_noi2.cpp
#include <bits/stdc++.h> #define endl '\n' using namespace std; const int maxN = 105; bool p; int n, k, a[maxN], ans = INT_MAX; bool cmp(int x, int y) { return x > y; } void solve(int curr, int currCnt) { if(curr < 0) return; else if(curr == 0) { if(currCnt < ans) ans = currCnt; return; } for(int i = 0; i < k; i++) { solve(curr - a[i], currCnt + 1); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin>>n>>k; for(int i = 0; i < k; i++) { cin>>a[i]; } sort(a, a + k, cmp); solve(n, 0); cout<<ans<<endl; return 0; }
568bdcf8c8c5ec8c116d1134b7b852508940515b
de9ba30b5c1dcc9fb85ea78b4e2c407c84e7236e
/main.cpp
d7d92801cf689f7d241618dc5d82820d2666333b
[]
no_license
kmdemirtas/threadedsorting
eeeb53c576395c046c7b8c22dc23f7e7f44c8010
8512a497c7a4fbab97ee416934789103c8f410f5
refs/heads/main
2023-06-01T17:40:23.665586
2021-06-14T09:47:12
2021-06-14T09:47:12
376,773,976
0
0
null
null
null
null
UTF-8
C++
false
false
3,355
cpp
main.cpp
#include <iostream> #include <vector> #include <cstdlib> #include <time.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #include <iomanip> #include <chrono> #include "sort.h" struct package { int *arr; int sortType; }; sem_t out; void *threadFunc(void *arg) { auto start = std::chrono::high_resolution_clock::now(); package *p = (package *)arg; switch (p->sortType) { case 0: sem_wait(&out); std::cout << "SELECTION SORT STARTED" << std::endl; sem_post(&out); selectionSort(p->arr); break; case 1: sem_wait(&out); std::cout << "INSERTION SORT STARTED" << std::endl; sem_post(&out); insertionSort(p->arr); break; case 2: sem_wait(&out); std::cout << "BUBBLE SORT STARTED" << std::endl; sem_post(&out); bubbleSort(p->arr); break; case 3: sem_wait(&out); std::cout << "MERGE SORT STARTED" << std::endl; sem_post(&out); mergeSort(p->arr, 0, ARR_SIZE - 1); break; case 4: sem_wait(&out); std::cout << "QUICK SORT STARTED" << std::endl; sem_post(&out); quickSort(p->arr, 0, ARR_SIZE - 1); break; default: break; } auto finish = std::chrono::high_resolution_clock::now(); if (isSorted(p->arr)) { sem_wait(&out); std::cout << std::setw(22); switch (p->sortType) { case 0: std::cout << "SELECTION SORT SUCCESS"; break; case 1: std::cout << "INSERTION SORT SUCCESS"; break; case 2: std::cout << "BUBBLE SORT SUCCESS"; break; case 3: std::cout << "MERGE SORT SUCCESS"; break; case 4: std::cout << "QUICK SORT SUCCESS"; break; default: break; } std::cout << " in: " << std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count() << " ms\n"; sem_post(&out); } else { sem_wait(&out); std::cout << "ERROR" << std::endl; sem_post(&out); } return NULL; } int main(int argc, char **argv) { bool isRandom = true; if (argc > 1 && argv[1] == "sorted") { isRandom = false; } if (argc > 2) { ARR_SIZE = atoi(argv[2]); } sem_init(&out, 0, 1); pthread_t threads[TOTAL_ALG]; std::srand(time(nullptr)); int **arrHolder = (int **)malloc(sizeof(int *) * TOTAL_ALG); for (int i = 0; i < TOTAL_ALG; i++) { arrHolder[i] = (int *)malloc(sizeof(int) * ARR_SIZE); } for (int i = 0; i < ARR_SIZE; i++) { int val = isRandom ? rand() % ARR_SIZE : i; for (int j = 0; j < TOTAL_ALG; j++) { arrHolder[j][i] = val; } } package packages[TOTAL_ALG]; for (int i = 0; i < TOTAL_ALG; i++) { packages[i].arr = arrHolder[i]; packages[i].sortType = i; pthread_create(&(threads[i]), NULL, threadFunc, &packages[i]); } for (int i = 0; i < TOTAL_ALG; i++) { pthread_join(threads[i], NULL); } for (int i = 0; i < TOTAL_ALG; i++) { free(arrHolder[i]); } sem_destroy(&out); free(arrHolder); }
94104d759cce669239e69976c15dc81e9e51b970
1d6f19ced2319e0674ca954a6a4d1994da32b854
/win32/edform_w.cpp
148265e291566535feb362957bee393888750b22
[]
no_license
yojiyojiyoji/AQUASIM
33096096ad81cf84d7adca1afc0fad179ba3f354
83dbdfe625a428c18d1a6ec8672d8146ea2ff0e7
refs/heads/master
2023-07-13T11:58:27.884332
2018-05-09T12:20:01
2018-05-09T12:20:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,974
cpp
edform_w.cpp
// edform_w.cpp : implementation file // #include "stdafx.h" #include "AQUASIM.h" #include "edform_w.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CEdVarForm dialog CEdVarForm::CEdVarForm(CWnd* pParent /*=NULL*/) : CDialog(CEdVarForm::IDD, pParent) { //{{AFX_DATA_INIT(CEdVarForm) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CEdVarForm::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CEdVarForm) DDX_Control(pDX, IDC_ED_UNIT, m_ed_unit); DDX_Control(pDX, IDC_ED_NAME, m_ed_name); DDX_Control(pDX, IDC_ED_EXPR, m_ed_expr); DDX_Control(pDX, IDC_ED_DESCRIPT, m_ed_descript); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CEdVarForm, CDialog) //{{AFX_MSG_MAP(CEdVarForm) //}}AFX_MSG_MAP END_MESSAGE_MAP() int CEdVarForm::DoModal(AQVAR* var, BOOL a) { oldvar = var; fvar = new FORMVAR(oldvar); add = a; return CDialog::DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CEdVarForm message handlers BOOL CEdVarForm::OnInitDialog() { CDialog::OnInitDialog(); char buffer[1024]; if ( fvar->Symbol() != 0 ) { m_ed_name.SetWindowText(fvar->Symbol()); } if ( fvar->Description() != 0 ) { m_ed_descript.SetWindowText(fvar->Description()); } if ( fvar->Unit() != 0 ) { m_ed_unit.SetWindowText(fvar->Unit()); } if ( fvar->UnParse(buffer,sizeof(buffer)) == 0 ) { m_ed_expr.SetWindowText(buffer); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CEdVarForm::OnCancel() { delete fvar; CDialog::OnCancel(); } void CEdVarForm::OnOK() { char buffer[1024]; char buffer1[1024]; m_ed_name.GetWindowText(buffer,sizeof(buffer)); if ( fvar->Symbol(buffer) == FALSE ) { MessageBox(aqapp.ini.T(239), aqapp.ini.T(111), MB_OK+MB_ICONERROR); return; } m_ed_descript.GetWindowText(buffer,sizeof(buffer)); fvar->Description(buffer); m_ed_unit.GetWindowText(buffer,sizeof(buffer)); fvar->Unit(buffer); m_ed_expr.GetWindowText(buffer,sizeof(buffer)); if ( fvar->Parse(buffer,aqsys.Varlist(),buffer1) != 0 ) { MessageBox(aqapp.ini.T(240), aqapp.ini.T(111), MB_OK+MB_ICONERROR); return; } if ( add == TRUE ) { if ( aqsys.AddVar(fvar) == FALSE ) { MessageBox(aqapp.ini.T(241), // UnableAdd aqapp.ini.T(111), MB_OK+MB_ICONERROR); return; } } else { if ( aqsys.ReplaceVar(oldvar,fvar) == FALSE ) { MessageBox(aqapp.ini.T(242), // IllegalVar aqapp.ini.T(111), MB_OK+MB_ICONERROR); return; } } CDialog::OnOK(); }
b90d7e5335619713bb2fbaf8c1f38870adf46a0e
28ba55f26d0e49502a6a7dcd7ca7359f9c9eb2af
/주사위.cpp
568cf13a7d5dd289fa7c205c9a0ed139faf1a56f
[]
no_license
moonshot2/BOJ
7fcea32d703064843050756af403db2043ce299d
37d38608d65a5ba332a57d6b31ef129fedf469a8
refs/heads/master
2023-06-22T20:01:13.693826
2021-07-22T06:55:24
2021-07-22T06:55:24
138,481,939
0
0
null
null
null
null
UTF-8
C++
false
false
689
cpp
주사위.cpp
#include <iostream> #include <algorithm> using namespace std; long long DATA[100001]; int main() { long long m1, m2, m3; long long N, n1, n2, n3 = 4, sum = 0; cin >> N; for (int i = 0; i < 6; ++i) { cin >> DATA[i]; } if (N == 1) { sort(DATA, DATA + 6); for (int i = 0; i < 5; ++i) sum += DATA[i]; cout << sum; return 0; } DATA[0] = min(DATA[0], DATA[5]); DATA[1] = min(DATA[1], DATA[4]); DATA[2] = min(DATA[2], DATA[3]); sort(DATA, DATA + 3); m3 = DATA[0] + DATA[1] + DATA[2]; m2 = DATA[0] + DATA[1]; m1 = DATA[0]; n1 = (N - 1) * (N - 2) * 4 + (N - 2) * (N - 2); n2 = (N - 1) * 4 + (N - 2) * 4; sum += m1 * n1; sum += m2 * n2; sum += m3 * n3; cout << sum; }
efbb490cdd785a2245dc6c4318d091fcc08eb662
8584afff21c31c843f520bd28587a741e6ffd402
/AtCoder/企業コンテスト/三井住友信託銀行プログラミングコンテスト2019/f.cpp
e5abfba98767a393ecc0415a60e2419832eda45e
[]
no_license
YuanzhongLi/CompetitiveProgramming
237e900f1c906c16cbbe3dd09104a1b7ad53862b
f9a72d507d4dda082a344eb19de22f1011dcee5a
refs/heads/master
2021-11-20T18:35:35.412146
2021-08-25T11:39:32
2021-08-25T11:39:32
249,442,987
0
0
null
null
null
null
UTF-8
C++
false
false
2,176
cpp
f.cpp
#include <bits/stdc++.h> using namespace std; #define rep(i,s,n) for (int i = (int)s; i < (int)n; i++) #define ll long long #define pb push_back #define All(x) x.begin(), x.end() #define Range(x, i, j) x.begin() + i, x.begin() + j #define lbidx(x, y) lower_bound(x.begin(), x.end(), y) - x.begin() #define ubidx(x, y) upper_bound(x.begin(), x.end(), y) - x.begin() #define BiSearchRangeNum(x, y, z) lower_bound(x.begin(), x.end(), z) - lower_bound(x.begin(), x.end(), y)turn idx; #define deg_to_rad(deg) ((((double)deg)/((double)360)*2*M_PI)) #define rad_to_deg(rad) ((((double)rad)/(double)2/M_PI)*(double)360) template<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; }; template<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; }; int main() { ll t1, t2; cin >> t1 >> t2; ll a1, a2, b1, b2; cin >> a1 >> a2 >> b1 >> b2; if ((t1 * a1 + t2 * a2) == (b1 * t1 + b2 * t2)) { cout << "infinity" << endl; return 0; } // 高橋くんがt1, t2で進む距離 ll dis_t1 = a1 * t1; ll dis_t2 = a2 * t2; // 青木くんがt1, t2で進む距離 ll dis_a1 = b1 * t1; ll dis_a2 = b2 * t2; if (dis_t1 > dis_a1) { if (dis_t1 + dis_t2 > dis_a1 + dis_a2) { cout << 0 << endl; return 0; } // t1区間での差 ll dif1 = dis_t1 - dis_a1; // t1, t2合計での差 ll dif_all = (dis_a1 + dis_a2) - (dis_t1 + dis_t2); // あまり ll re = dif1 % dif_all; ll ans; if (re == (ll)0) { ans = dif1 / dif_all * (ll) 2; } else { ans = dif1 / dif_all * (ll) 2 + (ll) 1; } cout << ans << endl; } if (dis_a1 > dis_t1) { if (dis_a1 + dis_a2 > dis_t1 + dis_t2) { cout << 0 << endl; return 0; } // t1区間での差 ll dif1 = dis_a1 - dis_t1; // t1, t2合計での差 ll dif_all = (dis_t1 + dis_t2) - (dis_a1 + dis_a2); // あまり ll re = dif1 % dif_all; ll ans; if (re == (ll)0) { ans = dif1 / dif_all * (ll) 2; } else { ans = dif1 / dif_all * (ll) 2 + (ll) 1; } cout << ans << endl; } };
d83fdb681aba81ae18e642cd344a247ff5cce10a
f1aacf2eae829d926794a82ac75b795d35ec4499
/ExpanderPi/demos/demo-io-interrupts.cpp
887174a0f89c8106583a9b903e0a9faaab7182d8
[ "MIT" ]
permissive
abelectronicsuk/ABElectronics_CPP_Libraries
f44482667d9f76f35056ecd9e02c69cb041f6a18
1bce59a25965b32d2a5daa423d0775fe911f5632
refs/heads/master
2023-02-16T23:59:01.347162
2023-02-04T18:41:56
2023-02-04T18:41:56
95,541,193
13
10
MIT
2019-03-04T10:11:07
2017-06-27T09:24:49
C++
UTF-8
C++
false
false
2,505
cpp
demo-io-interrupts.cpp
/* * demo-io-interrupts.cpp * * This example shows how to use the interrupt methods on the IO port. * The interrupts will be enabled and set so that a voltage applied * to pins 1 t 8 will trigger INT A and pins 9 to 16 will trigger INT B. * Using the read_interrupt_capture or read_port methods will * reset the interrupts. * * compile with "g++ demo-io-interrupts.cpp ../ABE_ExpanderPi.cpp -Wall -Wextra -Wpedantic -Woverflow -o demo-io-interrupts" * run with "./demo-io-interrupts" */ #include <stdio.h> #include <stdexcept> #include <time.h> #include <unistd.h> #include <iostream> #include "../ABE_ExpanderPi.h" using namespace std; void clearscreen() { printf("\033[2J\033[1;1H"); } int main(int argc, char **argv) { setvbuf(stdout, NULL, _IONBF, 0); // needed to print to the command line using namespace ABElectronics_CPP_Libraries; try { ExpanderPi expi; // initialise one of the io pi buses on I2C address default address for bus 1 expi.io_set_port_direction(0, 0xFF); // set bank 0 to be inputs expi.io_set_port_direction(1, 0xFF); // set bank 1 to be inputs expi.io_set_port_pullups(0, 0xFF); // disable internal pullups for port 0 expi.io_set_port_pullups(1, 0xFF); // disable internal pullups for port 1 expi.io_invert_port(0, 0xFF); expi.io_invert_port(1, 0xFF); // Set the interrupt polarity to be active high and mirroring disabled, so // pins 1 to 8 trigger INT A and pins 9 to 16 trigger INT B expi.io_set_interrupt_polarity(1); expi.io_mirror_interrupts(1); // Set the interrupts default value to trigger when 5V is applied to any pin expi.io_set_interrupt_defaults(0, 0xFF); expi.io_set_interrupt_defaults(1, 0xFF); // Set the interrupt type to be 1 for ports A and B so an interrupt is // fired when the pin matches the default value expi.io_set_interrupt_type(0, 0xFF); expi.io_set_interrupt_type(1, 0xFF); // Enable interrupts for pins 1 to 16 expi.io_set_interrupt_on_port(0, 0xFF); expi.io_set_interrupt_on_port(1, 0xFF); while (1) { clearscreen(); printf("%d\n", expi.io_read_interrupt_capture(0)); printf("%d\n", expi.io_read_interrupt_capture(1)); usleep(200000); // sleep 0.2 seconds } } catch (exception &e) { cout << e.what(); } (void)argc; (void)argv; return (0); }
f2772ccbb347edf57a88dccd3a655c80bdc5c5ec
1ad4a9f7a9c3350f109b6b5262aa841328a99f9f
/rto_node/include/AnalogInputArrayROS.h
301440419efd47de8d32d4d50f97db8bc429ad07
[]
no_license
KathiWinter/NavPy
8fa44a592f988a419b7b1fc36678ec73d21682ba
6627770f1b5d5ba971538c596e4429842a30a07a
refs/heads/main
2023-03-05T10:51:03.712337
2021-02-14T18:27:20
2021-02-14T18:27:20
322,628,333
0
1
null
null
null
null
UTF-8
C++
false
false
682
h
AnalogInputArrayROS.h
/* * AnalogInputArrayROS.h * * Created on: 08.12.2011 * Author: indorewala@servicerobotics.eu */ #ifndef ANALOGINPUTARRAYROS_H_ #define ANALOGINPUTARRAYROS_H_ #include "rec/robotino/api2/AnalogInputArray.h" #include <ros/ros.h> #include "rto_msgs/AnalogReadings.h" class AnalogInputArrayROS: public rec::robotino::api2::AnalogInputArray { public: AnalogInputArrayROS(); ~AnalogInputArrayROS(); void setTimeStamp(ros::Time stamp); private: ros::NodeHandle nh_; ros::Publisher analog_pub_; rto_msgs::AnalogReadings analog_msg_; ros::Time stamp_; void valuesChangedEvent( const float* values, unsigned int size ); }; #endif /* ANALOGINPUTARRAYROS_H_ */
542fcb99b713f2c67eb84619295ae5c40491f736
175cd7456c11b8c2bcdf91f160f69a5df357e1bc
/expogo.cpp
585c8117f1784e066b6579f11f8df327ba878564
[]
no_license
shubham172995/April20
32224ca3dcb36ad251ae49bc9c37c1ddf4f64621
8282f48100992e43bcaaa3c293783e306c5e9e30
refs/heads/master
2023-06-21T02:48:30.714062
2020-04-30T05:50:28
2020-04-30T05:50:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,281
cpp
expogo.cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int map<pair<ll, ll>, bool> m; string res; bool check(ll x, ll y, int power, ll curx, ll cury, string ans){ //cout<<curx<<" "<<cury<<endl; if(curx==x&&cury==y){ res=ans.length()<res.length()?ans:res; return true; } if(abs(curx)>abs(x)||abs(cury)>abs(y)) return false; pair<ll, ll> p=make_pair(curx, cury); bool flag=false; if(check(x, y, power+1, curx+pow(2,power), cury, ans+'E')){ flag = true; } if(check(x, y, power+1, curx-pow(2,power), cury, ans+'W')){ flag = true; } if(check(x, y, power+1, curx, cury+pow(2,power), ans+'N')){ flag = true; } if(check(x, y, power+1, curx, cury-pow(2,power), ans+'S')){ flag = true; } if(flag) return true; return false; } int main(){ int t; scanf("%d", &t); for(int i=1;i<=t;i++){ res="EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"; ll x, y; cin>>x>>y; pair<ll, ll> p=make_pair(0,0); m[p]=1; bool flag=check(x, y, 0, 0, 0, ""); cout<<"Case #"<<i<<": "; if(flag) cout<<res<<endl; else cout<<"IMPOSSIBLE\n"; } }
92c8562466361a9dad971bad9c99411977744648
07915111c538b8887613ec9400fc25bc89742ae2
/SkiaCode/tools/bench_pictures_main.cpp
b51eaa20d17dcec02ee10d2d240d4ae0861202bc
[ "BSD-3-Clause" ]
permissive
15831944/skiaming
f4f683dafc393263193629545880d1ffbac810c9
d6500ec2afe1ab45b8a42470ac9dff30c7297b57
refs/heads/master
2021-12-05T17:25:46.351775
2012-10-10T09:54:13
2012-10-10T09:54:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,504
cpp
bench_pictures_main.cpp
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "BenchTimer.h" #include "PictureBenchmark.h" #include "SkBenchLogger.h" #include "SkCanvas.h" #include "SkMath.h" #include "SkOSFile.h" #include "SkPicture.h" #include "SkStream.h" #include "SkTArray.h" #include "picture_utils.h" const int DEFAULT_REPEATS = 100; static void usage(const char* argv0) { SkDebugf("SkPicture benchmarking tool\n"); SkDebugf("\n" "Usage: \n" " %s <inputDir>...\n" " [--logFile filename]\n" " [--repeat] \n" " [--mode pow2tile minWidth height[] (multi) | record | simple\n" " | tile width[] height[] (multi) | playbackCreation]\n" " [--pipe]\n" " [--device bitmap" #if SK_SUPPORT_GPU " | gpu" #endif "]" , argv0); SkDebugf("\n\n"); SkDebugf( " inputDir: A list of directories and files to use as input. Files are\n" " expected to have the .skp extension.\n\n" " --logFile filename : destination for writing log output, in addition to stdout.\n"); SkDebugf( " --mode pow2tile minWidht height[] (multi) | record | simple\n" " | tile width[] height[] (multi) | playbackCreation:\n" " Run in the corresponding mode.\n" " Default is simple.\n"); SkDebugf( " pow2tile minWidth height[], Creates tiles with widths\n" " that are all a power of two\n" " such that they minimize the\n" " amount of wasted tile space.\n" " minWidth is the minimum width\n" " of these tiles and must be a\n" " power of two. Simple\n" " rendering using these tiles\n" " is benchmarked.\n" " Append \"multi\" for multithreaded\n" " drawing.\n"); SkDebugf( " record, Benchmark picture to picture recording.\n"); SkDebugf( " simple, Benchmark a simple rendering.\n"); SkDebugf( " tile width[] height[], Benchmark simple rendering using\n" " tiles with the given dimensions.\n" " Append \"multi\" for multithreaded\n" " drawing.\n"); SkDebugf( " playbackCreation, Benchmark creation of the SkPicturePlayback.\n"); SkDebugf("\n"); SkDebugf( " --pipe: Benchmark SkGPipe rendering. Compatible with tiled, multithreaded rendering.\n"); SkDebugf( " --device bitmap" #if SK_SUPPORT_GPU " | gpu" #endif ": Use the corresponding device. Default is bitmap.\n"); SkDebugf( " bitmap, Render to a bitmap.\n"); #if SK_SUPPORT_GPU SkDebugf( " gpu, Render to the GPU.\n"); #endif SkDebugf("\n"); SkDebugf( " --repeat: " "Set the number of times to repeat each test." " Default is %i.\n", DEFAULT_REPEATS); } SkBenchLogger gLogger; static void run_single_benchmark(const SkString& inputPath, sk_tools::PictureBenchmark& benchmark) { SkFILEStream inputStream; inputStream.setPath(inputPath.c_str()); if (!inputStream.isValid()) { SkString err; err.printf("Could not open file %s\n", inputPath.c_str()); gLogger.logError(err); return; } SkPicture picture(&inputStream); SkString filename; sk_tools::get_basename(&filename, inputPath); SkString result; result.printf("running bench [%i %i] %s ", picture.width(), picture.height(), filename.c_str()); gLogger.logProgress(result); benchmark.run(&picture); } static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs, sk_tools::PictureBenchmark*& benchmark) { const char* argv0 = argv[0]; char* const* stop = argv + argc; int repeats = DEFAULT_REPEATS; sk_tools::PictureRenderer::SkDeviceTypes deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType; // Create a string to show our current settings. // TODO: Make it prettier. Currently it just repeats the command line. SkString commandLine("bench_pictures:"); for (int i = 1; i < argc; i++) { commandLine.appendf(" %s", *(argv+i)); } commandLine.append("\n"); bool usePipe = false; bool multiThreaded = false; bool useTiles = false; const char* widthString = NULL; const char* heightString = NULL; bool isPowerOf2Mode = false; const char* mode = NULL; for (++argv; argv < stop; ++argv) { if (0 == strcmp(*argv, "--repeat")) { ++argv; if (argv < stop) { repeats = atoi(*argv); if (repeats < 1) { SkDELETE(benchmark); gLogger.logError("--repeat must be given a value > 0\n"); exit(-1); } } else { SkDELETE(benchmark); gLogger.logError("Missing arg for --repeat\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--pipe")) { usePipe = true; } else if (0 == strcmp(*argv, "--logFile")) { argv++; if (argv < stop) { if (!gLogger.SetLogFile(*argv)) { SkString str; str.printf("Could not open %s for writing.", *argv); gLogger.logError(str); usage(argv0); exit(-1); } } else { gLogger.logError("Missing arg for --logFile\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--mode")) { SkDELETE(benchmark); ++argv; if (argv >= stop) { gLogger.logError("Missing mode for --mode\n"); usage(argv0); exit(-1); } if (0 == strcmp(*argv, "record")) { benchmark = SkNEW(sk_tools::RecordPictureBenchmark); } else if (0 == strcmp(*argv, "simple")) { benchmark = SkNEW(sk_tools::SimplePictureBenchmark); } else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) { useTiles = true; mode = *argv; if (0 == strcmp(*argv, "pow2tile")) { isPowerOf2Mode = true; } ++argv; if (argv >= stop) { SkString err; err.printf("Missing width for --mode %s\n", mode); gLogger.logError(err); usage(argv0); exit(-1); } widthString = *argv; ++argv; if (argv >= stop) { gLogger.logError("Missing height for --mode tile\n"); usage(argv0); exit(-1); } heightString = *argv; ++argv; if (argv < stop && 0 == strcmp(*argv, "multi")) { multiThreaded = true; } else { --argv; } } else if (0 == strcmp(*argv, "playbackCreation")) { benchmark = SkNEW(sk_tools::PlaybackCreationBenchmark); } else { SkString err; err.printf("%s is not a valid mode for --mode\n", *argv); gLogger.logError(err); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--device")) { ++argv; if (argv >= stop) { gLogger.logError("Missing mode for --deivce\n"); usage(argv0); exit(-1); } if (0 == strcmp(*argv, "bitmap")) { deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType; } #if SK_SUPPORT_GPU else if (0 == strcmp(*argv, "gpu")) { deviceType = sk_tools::PictureRenderer::kGPU_DeviceType; } #endif else { SkString err; err.printf("%s is not a valid mode for --device\n", *argv); gLogger.logError(err); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) { SkDELETE(benchmark); usage(argv0); exit(0); } else { inputs->push_back(SkString(*argv)); } } if (useTiles) { sk_tools::TiledPictureBenchmark* tileBenchmark = SkNEW(sk_tools::TiledPictureBenchmark); if (isPowerOf2Mode) { int minWidth = atoi(widthString); if (!SkIsPow2(minWidth) || minWidth < 0) { SkDELETE(tileBenchmark); SkString err; err.printf("--mode %s must be given a width" " value that is a power of two\n", mode); gLogger.logError(err); exit(-1); } tileBenchmark->setTileMinPowerOf2Width(minWidth); } else if (sk_tools::is_percentage(widthString)) { tileBenchmark->setTileWidthPercentage(atof(widthString)); if (!(tileBenchmark->getTileWidthPercentage() > 0)) { SkDELETE(tileBenchmark); gLogger.logError("--mode tile must be given a width percentage > 0\n"); exit(-1); } } else { tileBenchmark->setTileWidth(atoi(widthString)); if (!(tileBenchmark->getTileWidth() > 0)) { SkDELETE(tileBenchmark); gLogger.logError("--mode tile must be given a width > 0\n"); exit(-1); } } if (sk_tools::is_percentage(heightString)) { tileBenchmark->setTileHeightPercentage(atof(heightString)); if (!(tileBenchmark->getTileHeightPercentage() > 0)) { SkDELETE(tileBenchmark); gLogger.logError("--mode tile must be given a height percentage > 0\n"); exit(-1); } } else { tileBenchmark->setTileHeight(atoi(heightString)); if (!(tileBenchmark->getTileHeight() > 0)) { SkDELETE(tileBenchmark); gLogger.logError("--mode tile must be given a height > 0\n"); exit(-1); } } tileBenchmark->setThreading(multiThreaded); tileBenchmark->setUsePipe(usePipe); benchmark = tileBenchmark; } else if (usePipe) { SkDELETE(benchmark); benchmark = SkNEW(sk_tools::PipePictureBenchmark); } if (inputs->count() < 1) { SkDELETE(benchmark); usage(argv0); exit(-1); } if (NULL == benchmark) { benchmark = SkNEW(sk_tools::SimplePictureBenchmark); } benchmark->setRepeats(repeats); benchmark->setDeviceType(deviceType); benchmark->setLogger(&gLogger); // Report current settings: gLogger.logProgress(commandLine); } static void process_input(const SkString& input, sk_tools::PictureBenchmark& benchmark) { SkOSFile::Iter iter(input.c_str(), "skp"); SkString inputFilename; if (iter.next(&inputFilename)) { do { SkString inputPath; sk_tools::make_filepath(&inputPath, input, inputFilename); run_single_benchmark(inputPath, benchmark); } while(iter.next(&inputFilename)); } else { run_single_benchmark(input, benchmark); } } int main(int argc, char* const argv[]) { SkTArray<SkString> inputs; sk_tools::PictureBenchmark* benchmark = NULL; parse_commandline(argc, argv, &inputs, benchmark); for (int i = 0; i < inputs.count(); ++i) { process_input(inputs[i], *benchmark); } SkDELETE(benchmark); }
3badaa694fc815de0871de2d9728f05029f2be05
4efddc6f368533090c68bd806d6327154cfa57a0
/day2/main.cpp
3b864aaa328dbdc86b48867d14c924987b4c8aa1
[]
no_license
Shensd/AdventOfCode2019
e6edcfae513b4fdda9ab58bdd6ed44778726d666
3712f9e23229b001edf4d7d80cb9c834ee649262
refs/heads/master
2022-12-10T01:38:51.353812
2019-12-17T02:22:25
2019-12-17T02:22:25
225,270,494
0
0
null
2022-11-22T04:54:12
2019-12-02T02:44:41
C++
UTF-8
C++
false
false
3,390
cpp
main.cpp
/* The relevant challenge for this portion was far too long to place here, but it was effectively the specification for a very simple opcode language. For the second part of the challenge, if done smart, required no code to be written. The most obvious choice is to use a brute force solution, but by chaning the noun and verb and looking at how it changed the output, by more or less binary search tree guessing the output could be obtained in about 8 or so guesses. */ #include <iostream> #include <fstream> #include <vector> #include <sstream> #define INPUT_LOCATION "./input" typedef unsigned int u_int; /** * Get the file contents of the file at the given location. * * Exits program with error message if file cannot be read. * * @param location file location to read from * @returns string content of file */ std::string get_file_content(std::string location) { std::ifstream input(location); if(!input.is_open()) { std::cout << "Unable to open given input file." << std::endl; exit(-1); } std::string content = ""; while(!input.eof()) { char buffer[1024]; input.getline(buffer, 1024); content += buffer; content += "\n"; } return content; } /** * Given a string source, parse the opcodes into an unsigned int vector. * * @param source opcode source * @returns vector of unsigned integers representing opcodes */ std::vector<u_int> parse_opcodes(std::string source) { std::vector<u_int> opcodes; std::stringstream sstream(source); while(!sstream.eof()) { char buffer[1024]; // opcodes are command delimited sstream.getline(buffer, 1024, ','); opcodes.push_back( std::stoi(buffer) ); } return opcodes; } #define OPCODE_ADD 1 #define OPCODE_MUL 2 #define OPCODE_END 99 /** * Run the program given by a vector of opcodes, the program is run in place and * modifies the vector given * * @param opcodes a vector of opcodes to work as program instructions */ void run_program(std::vector<u_int>& opcodes) { for(int i = 0; i < opcodes.size(); i++) { u_int current_opcode = opcodes[i]; u_int left = opcodes[opcodes[i+1]]; u_int right = opcodes[opcodes[i+2]]; u_int location = opcodes[i+3]; switch(current_opcode) { case OPCODE_ADD: opcodes[location] = left + right; // skip next 4 instructions since they were eaten i+=3; break; case OPCODE_MUL: opcodes[location] = left * right; // skip next 4 instructions since they were eaten i+=3; break; case OPCODE_END: return; default: std::cout << "Unexpected instruction '" << current_opcode << "'" << std::endl; exit(-1); break; } } } int main(int argc, char* argv[]) { std::string content = get_file_content(INPUT_LOCATION); std::vector<unsigned int> opcodes = parse_opcodes(content); run_program(opcodes); // output only the meaningful parts of the end program std::cout << "NOUN : " << opcodes[1] << std::endl; std::cout << "VERB : " << opcodes[2] << std::endl; std::cout << "OUTPUT : " << opcodes[0] << std::endl; }
10af516861cc52e85a57a37e1b98bf7ae3412554
8b52a6e32d65ea9f8201e806ebfebe46b4041f0f
/c++/3/main.cpp
246d61f2b2b50f8a8cc75d07d00778b9c633ed0f
[]
no_license
scoiatael/ThingsIdidAtII
7c93ff7ac2ffde6364c6d05a8bb97b80fdd45836
af85a2b646d81bb1506e3b0651c442b38edfea0a
refs/heads/master
2021-01-17T14:03:22.998616
2016-06-16T21:00:25
2016-06-16T21:00:25
10,513,897
1
0
null
null
null
null
UTF-8
C++
false
false
603
cpp
main.cpp
#include <iostream> #include "pierwsze.cpp" #include <vector> #include <cstdlib> using namespace std; void printV(const vector<long long> &T ) { for(int i=0; i<T.size(); i++) cout << T[i]<<" "; cout << endl; } int main() { prime_numbers::Initialize(); while(true) { long long number; cin>> number; //cout << number << endl; if(prime_numbers::is_prime(number,true)) cout << "is prime" << endl; else printV(prime_numbers::prime_factorization(number)); } //system("pause"); }
0d227bc8e672138c546e865bb37ba536b2327713
79d3d2633f52ac28207a3b7a11d2498630bd0ff4
/SFAStats/include/SFA/Stats/AverageMatchingError.h
ef879e23a77f2a54bfaf04a156f702132edf34de
[]
no_license
mfzhang/StatisticalFaceAnalysis
e7ea0d94bc09fe40996abaa6033c5cf0e6de4ca0
c6616fca911ee85cd7e93bbd50017fe8ff35d9e0
refs/heads/master
2021-01-03T13:14:17.354144
2014-08-06T11:10:27
2014-08-06T11:10:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,116
h
AverageMatchingError.h
////////////////////////////////////////////////////////////////////// /// Statistical Shape Analysis /// /// Copyright (c) 2014 by Jan Moeller /// /// This software is provided "as-is" and does not claim to be /// complete or free of bugs in any way. It should work, but /// it might also begin to hurt your kittens. ////////////////////////////////////////////////////////////////////// #ifndef AVERAGEMATCHINGERROR_H_ #define AVERAGEMATCHINGERROR_H_ #include <iostream> #include <fstream> #include <string> #include <vector> #include <DBGL/System/Log/Log.h> #include "StatRunner.h" #include "SFA/Utility/Model.h" #include "SFA/NearestNeighbor/NearestNeighbor.h" #include "SFA/ICP/ICP.h" #include "SFA/ICP/PCA_ICP.h" namespace sfa { class AverageMatchingError : public StatRunner { public: virtual void run(Model& src, Model& dest, NearestNeighbor& nn, ICP& icp, dbgl::Properties& props); virtual void printResults(dbgl::Properties& props); virtual void writeResults(dbgl::Properties& props); private: void testWithModel(Model& src, Model& dest, NearestNeighbor& nn, ICP& icp); void initCorrectPairs(Model& src, Model& dest, NearestNeighbor& nn, ICP& icp); std::string getPairSelectionFlags(dbgl::Bitmask<> flags); const std::string Prop_RandCycles = "AverageMatching_RandCycles"; const std::string Prop_ICPCycles = "AverageMatching_IcpCycles"; const std::string Prop_MaxRot = "AverageMatching_MaxRot"; const std::string Prop_MinRot = "AverageMatching_MinRot"; const std::string Prop_MaxTrans = "AverageMatching_MaxTrans"; const std::string Prop_MinTrans = "AverageMatching_MinTrans"; const std::string Prop_PairSelection = "AverageMatching_PairSelection"; const std::string Prop_PairSelectionPercent = "AverageMatching_PairSelectionPercent"; const std::string Prop_NoiseLevel = "AverageMatching_NoiseLevel"; const std::string Prop_Holes = "AverageMatching_Holes"; unsigned int randCycles = 100; unsigned int icpCycles = 30; double maxRot = dbgl::pi_4(); double minRot = 0; double maxTrans = 0.3; double minTrans = 0; unsigned int holes = 0; unsigned int noiseLevel = 0; double pairSelectionPercent = 1; std::vector<unsigned int> correctPairs; std::vector<std::vector<double>> algoResults; std::vector<std::vector<double>> realResults; std::vector<std::vector<double>> amountOfMatches; std::vector<double> algoStdDeviation; std::vector<double> realStdDeviation; std::vector<double> pairsStdDeviation; std::vector<double> averageAlgoResults; std::vector<double> averageRealResults; std::vector<double> averageAmountOfMatches; double averageAlgoErrorBegin = 0; double averageRealErrorBegin = 0; double averageRotation = 0; double averageTranslation = 0; double averageSelectedPoints = 0; PCA_ICP pca_icp; std::string pairSelection; unsigned int srcVertices = 0; unsigned int destVertices = 0; dbgl::Properties* props = nullptr; }; } #endif /* AVERAGEMATCHINGERROR_H_ */
ba7371778c8d030cf98a06d34cff3b6b42ba50ee
cb8d1be6b6b1cbb4a1169223504e93061ed11c43
/System/Time/Timer.hpp
48fd622d431cee1e979de16f3cd8e4dc31dcd59f
[]
no_license
RyanBabij/Wildcat
c6ec5fca71968376208995d1cd833c007f44d9d1
4c684506996cf52ad752504e9b8a490f6cd571d0
refs/heads/master
2023-02-21T05:33:38.284612
2023-02-14T23:05:23
2023-02-14T23:05:23
100,090,636
8
0
null
2020-06-07T03:55:26
2017-08-12T05:11:37
C
UTF-8
C++
false
false
2,449
hpp
Timer.hpp
#pragma once #ifndef WILDCAT_SYSTEM_TIME_TIMER_HPP #define WILDCAT_SYSTEM_TIME_TIMER_HPP /* Wildcat: Timer #include <System/Time/Timer.hpp> Linux Implementation (Seems to also work with mingw or whatever) Note that tv_usec resets after each second. Profiling example: Timer t; t.init(); t.start(); // CODE TO TIME t.update(); std::cout<<"Execution time: "<<t.fullSeconds<<".\n"; GetTickCount() returns milliseconds since startup Shorter example: Timer t = Timer().start(); std::cout<<"Execution time: "<<t.update().fullSeconds<<"\n"; TIMER MANAGER int id = timerManager.instanceStart(); timerManager.getSeconds(id); timerManager.waitUntil(id, 1000); */ #if defined WILDCAT_LINUX || defined __MINGW32__ #include <sys/time.h> // I believe this is normally Linux only, but also works with MingW. #else #endif class Timer { public: #if defined WILDCAT_LINUX || defined __MINGW32__ timeval startTime; timeval stopTime; #else unsigned long int startTick; // milliseconds since startup #endif long unsigned int uSeconds; /* This goes only as far as 1 second before resetting. See documentation. */ unsigned int seconds; double fullSeconds; long int totalUSeconds; Timer(bool autoStart = false) { init(); } void init() { uSeconds=0; seconds=0; fullSeconds=0; totalUSeconds=0; #if defined WILDCAT_LINUX || defined __MINGW32__ #else startTick=0; #endif } void start() { #if defined WILDCAT_LINUX || defined __MINGW32__ gettimeofday(&startTime,0); #else startTick = GetTickCount(); #endif } void update() { #if defined WILDCAT_LINUX || defined __MINGW32__ gettimeofday(&stopTime,0); seconds=stopTime.tv_sec-startTime.tv_sec; totalUSeconds = stopTime.tv_usec-startTime.tv_usec + (seconds*1000000); if(stopTime.tv_usec<startTime.tv_usec) { stopTime.tv_usec+=1000000; seconds--; } uSeconds=stopTime.tv_usec-startTime.tv_usec; fullSeconds=seconds+((double)uSeconds/1000000); #else long unsigned int endTick = GetTickCount(); long unsigned int totalTicks = endTick-startTick; uSeconds = (totalTicks%1000)*1000; totalUSeconds = totalTicks*1000; seconds=totalTicks/1000; fullSeconds=seconds+((double)uSeconds/1000000); #endif } }; #endif
6afa60f13100969f8b1b7d5f1c4c7dd2565c32e8
d2049ec4c3b35187717597ebf13cbbb7448efbb4
/Chapter_5/Exercise_1/main.cpp
9c79bb277b225c23dd8c19718f31d35ce7e6124b
[]
no_license
s-konyukhovsky/S_Prata_Exercises
c9bd1d64702dd8ce8ac11378bc74b97242418003
335bc31311eef87b6a69f8b315c5caa467b1c344
refs/heads/master
2020-03-31T00:48:39.207820
2018-10-18T12:07:57
2018-10-18T12:08:22
151,755,153
0
0
null
null
null
null
UTF-8
C++
false
false
300
cpp
main.cpp
#include <iostream> int main() { unsigned int num1 = 0, num2 = 0, sum = 0; std::cout << "Enter N1: "; std::cin >> num1; std::cout << "Enter N2: "; std::cin >> num2; for(unsigned int i = num1; i <= num2; i++) sum += i; std::cout << "Sum: " << sum; return 0; }
e1c1834318193a69f3239c4397ed1039fa3ac15b
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/inetsrv/msmq/src/setup/msmqocm/ocminit.cpp
ef8822ff3d0aa3533ab1e58f589f05a5281bf0d4
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,448
cpp
ocminit.cpp
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: ocminit.cpp Abstract: Code for initialization of OCM setup. Author: Doron Juster (DoronJ) 7-Oct-97 Revision History: Shai Kariv (ShaiK) 10-Dec-97 Modified for NT 5.0 OCM Setup --*/ #include "msmqocm.h" #include "Cm.h" #include "cancel.h" #include "ocminit.tmh" extern MQUTIL_EXPORT CCancelRpc g_CancelRpc; //+------------------------------------------------------------------------- // // Function: SetDirectories // // Synopsis: Generate MSMQ specific directory names and set directory IDs // //-------------------------------------------------------------------------- DWORD SetDirectories( VOID ) { DebugLogMsg(L"Setting Message Queuing folders..."); DWORD err = 0; // // Set root dir for MSMQ // if (_tcslen(g_szMsmqDir) < 1) { GetSystemDirectory(g_szMsmqDir, sizeof(g_szMsmqDir)/sizeof(g_szMsmqDir[0])); lstrcat(g_szMsmqDir, DIR_MSMQ); } DebugLogMsg(L"Setting folder ID for the Message Queuing folder:"); DebugLogMsg(g_szMsmqDir); if (!SetupSetDirectoryId( g_ComponentMsmq.hMyInf, idMsmqDir, g_szMsmqDir )) { err = GetLastError(); return err; } // // Set the exchange connector dir of MSMQ1 / MSMQ2-beta2 // Do we need it for Whistler? // TCHAR szXchangeDir[MAX_PATH]; lstrcpy( szXchangeDir, g_szMsmqDir); lstrcat( szXchangeDir, OCM_DIR_MSMQ_SETUP_EXCHN); DebugLogMsg(L"Setting the folder ID for the Message Queuing Exchange Connector folder (beta2):"); DebugLogMsg(szXchangeDir); if (!SetupSetDirectoryId( g_ComponentMsmq.hMyInf, idExchnConDir, szXchangeDir)) { err = GetLastError(); return err; } // // Set the storage dir // lstrcpy(g_szMsmqStoreDir, g_szMsmqDir); lstrcat(g_szMsmqStoreDir, DIR_MSMQ_STORAGE); DebugLogMsg(L"Setting the folder ID for the Message Queuing storage folder:"); DebugLogMsg(g_szMsmqStoreDir); if (!SetupSetDirectoryId( g_ComponentMsmq.hMyInf, idStorageDir, g_szMsmqStoreDir)) { err = GetLastError(); return err; } // // Set the web dir // lstrcpy(g_szMsmqWebDir, g_szMsmqDir); lstrcat(g_szMsmqWebDir, DIR_MSMQ_WEB); DebugLogMsg(L"Setting the folder ID for the Message Queuing Web folder:"); DebugLogMsg(g_szMsmqWebDir); if (!SetupSetDirectoryId( g_ComponentMsmq.hMyInf, idWebDir, g_szMsmqWebDir)) { err = GetLastError(); return err; } // // Set the mapping dir // lstrcpy(g_szMsmqMappingDir, g_szMsmqDir); lstrcat(g_szMsmqMappingDir, DIR_MSMQ_MAPPING); DebugLogMsg(L"Setting the folder ID for the Message Queuing mapping folder:"); DebugLogMsg(g_szMsmqMappingDir); if (!SetupSetDirectoryId( g_ComponentMsmq.hMyInf, idMappingDir, g_szMsmqMappingDir)) { err = GetLastError(); return err; } // // Set directories for MSMQ1 files // lstrcpy(g_szMsmq1SetupDir, g_szMsmqDir); lstrcat(g_szMsmq1SetupDir, OCM_DIR_SETUP); DebugLogMsg(L"Setting the folder ID for the MSMQ 1.0 setup folder:"); DebugLogMsg(g_szMsmq1SetupDir); if (!SetupSetDirectoryId(g_ComponentMsmq.hMyInf, idMsmq1SetupDir, g_szMsmq1SetupDir)) { err = GetLastError(); return err; } lstrcpy(g_szMsmq1SdkDebugDir, g_szMsmqDir); lstrcat(g_szMsmq1SdkDebugDir, OCM_DIR_SDK_DEBUG); DebugLogMsg(L"Setting the folder ID for the MSMQ 1.0 SDK debug folder:"); DebugLogMsg(g_szMsmq1SdkDebugDir); if (!SetupSetDirectoryId(g_ComponentMsmq.hMyInf, idMsmq1SDK_DebugDir, g_szMsmq1SdkDebugDir)) { err = GetLastError(); return err; } DebugLogMsg(L"Setting the Message Queuing folder IDs was completed successfully!"); return NO_ERROR; } // SetDirectories //+------------------------------------------------------------------------- // // Function: CheckMsmqK2OnCluster // // Synopsis: Checks if we're upgrading MSMQ 1.0 K2 on cluster to NT 5.0. // This is special because of bug 2656 (registry corrupt). // Result is stored in g_fMSMQAlreadyInstalled. // // Returns: BOOL dependes on success. // //-------------------------------------------------------------------------- static BOOL CheckMsmqK2OnCluster() { DebugLogMsg(L"Checking for an upgrade from MSMQ 1.0 k2 in the cluster..."); // // Check in registry if there is MSMQ installation on cluster // if (!Msmq1InstalledOnCluster()) { DebugLogMsg(L"MSMQ 1.0 is not installed in the cluster"); return TRUE; } // // Read the persistent storage directory from registry. // MSMQ directory will be one level above it. // This is a good enough workaround since storage directory is // always on a cluster shared disk. // if (!MqReadRegistryValue( MSMQ_STORE_PERSISTENT_PATH_REGNAME, sizeof(g_szMsmqDir), (PVOID) g_szMsmqDir )) { DebugLogMsg(L"The persistent storage path could not be read from the registry. MSMQ 1.0 was not found"); return TRUE; } TCHAR * pChar = _tcsrchr(g_szMsmqDir, TEXT('\\')); if (pChar) { *pChar = TEXT('\0'); } // // Read type of MSMQ from MachineCache\MQS // DWORD dwType = SERVICE_NONE; if (!MqReadRegistryValue( MSMQ_MQS_REGNAME, sizeof(DWORD), (PVOID) &dwType )) { // // MSMQ installed but failed to read its type // MqDisplayError(NULL, IDS_MSMQ1TYPEUNKNOWN_ERROR, 0); return FALSE; } g_dwMachineType = dwType; g_fMSMQAlreadyInstalled = TRUE; g_fUpgrade = (0 == (g_ComponentMsmq.Flags & SETUPOP_STANDALONE)); g_fServerSetup = FALSE; g_uTitleID = IDS_STR_CLI_ERROR_TITLE; g_fDependentClient = FALSE; switch (dwType) { case SERVICE_PEC: case SERVICE_PSC: case SERVICE_BSC: g_dwDsUpgradeType = dwType; g_dwMachineTypeDs = 1; g_dwMachineTypeFrs = 1; // // Fall through // case SERVICE_SRV: g_fServerSetup = TRUE; g_uTitleID = IDS_STR_SRV_ERROR_TITLE; g_dwMachineTypeDs = 0; g_dwMachineTypeFrs = 1; break; case SERVICE_RCS: g_fServerSetup = TRUE; g_uTitleID = IDS_STR_SRV_ERROR_TITLE; g_dwMachineTypeDs = 0; g_dwMachineTypeFrs = 0; break; case SERVICE_NONE: g_dwMachineTypeDs = 0; g_dwMachineTypeFrs = 0; break; default: MqDisplayError(NULL, IDS_MSMQ1TYPEUNKNOWN_ERROR, 0); return FALSE; break; } return TRUE; } //CheckMsmqK2OnCluster //+------------------------------------------------------------------------- // // Function: CheckWin9xUpgrade // // Synopsis: Checks if we're upgrading Win9x with MSMQ 1.0 to NT 5.0. // Upgrading Win9x is special because registry settings // can not be read during GUI mode. Therefore we use a special // migration DLL during the Win95 part of NT 5.0 upgrade. // // Result is stored in g_fMSMQAlreadyInstalled. // // Returns: BOOL dependes on success. // //-------------------------------------------------------------------------- static BOOL CheckWin9xUpgrade() { DebugLogMsg(L"Checking for an upgrade from Windows 9x..."); // // If this is not OS upgrade from Win95, we got nothing to do here // if (!(g_ComponentMsmq.Flags & SETUPOP_WIN95UPGRADE)) { return TRUE; } // // Generate the info file name (under %WinDir%). // The file was created by MSMQ migration DLL during the // Win95 part of NT 5.0 upgrade. // TCHAR szWindowsDir[MAX_PATH]; TCHAR szMsmqInfoFile[MAX_PATH]; GetSystemWindowsDirectory( szWindowsDir, sizeof(szWindowsDir)/sizeof(szWindowsDir[0]) ); _stprintf(szMsmqInfoFile, TEXT("%s\\%s"), szWindowsDir, MQMIG95_INFO_FILENAME); // // MQMIG95_INFO_FILENAME (msmqinfo.txt) is actually a .ini file. However we do not read it using // GetPrivateProfileString because it is not trustable in GUI-mode setup // (YoelA - 15-Mar-99) // FILE *stream = _tfopen(szMsmqInfoFile, TEXT("r")); if (0 == stream) { // // Info file not found. That means MSMQ 1.0 is not installed // on this machine. Log it. // MqDisplayError(NULL, IDS_MSMQINFO_NOT_FOUND_ERROR, 0); return TRUE; } // // First line should be [msmq]. Check it. // TCHAR szToken[MAX_PATH], szType[MAX_PATH]; // // "[%[^]]s" - Read the string between '[' and ']' (start with '[', read anything that is not ']') // int iScanResult = _ftscanf(stream, TEXT("[%[^]]s"), szToken); if ((iScanResult == 0 || iScanResult == EOF || iScanResult == WEOF) || (_tcscmp(szToken, MQMIG95_MSMQ_SECTION) != 0)) { // // File is currupted. Either a pre-mature EOF, or first line is not [msmq[ // MqDisplayError(NULL, IDS_MSMQINFO_HEADER_ERROR, 0); return TRUE; } // // The first line is in format "directory = xxxx". We first prepate a format string, // And then read according to that format. // The format string will look like "] directory = %[^\r\n]s" - start with ']' (last // character in header), then whitespaces (newlines, etc), then 'directory =', and // from then take everything till the end of line (not \r or \n). // TCHAR szInFormat[MAX_PATH]; _stprintf(szInFormat, TEXT("] %s = %%[^\r\n]s"), MQMIG95_MSMQ_DIR); iScanResult = _ftscanf(stream, szInFormat, g_szMsmqDir); if (iScanResult == 0 || iScanResult == EOF || iScanResult == WEOF) { // // We did not find the "directory =" section. file is corrupted // MqDisplayError(NULL, IDS_MSMQINFO_DIRECTORY_KEY_ERROR, 0); return TRUE; } // // The second line is in format "type = xxx" (after white spaces) // _stprintf(szInFormat, TEXT(" %s = %%[^\r\n]s"), MQMIG95_MSMQ_TYPE); iScanResult =_ftscanf(stream, szInFormat, szType); if (iScanResult == 0 || iScanResult == EOF || iScanResult == WEOF) { // // We did not find the "type =" section. file is corrupted // MqDisplayError(NULL, IDS_MSMQINFO_TYPE_KEY_ERROR, 0); return TRUE; } fclose( stream ); // // At this point we know that MSMQ 1.0 is installed on the machine, // and we got its root directory and type. // g_fMSMQAlreadyInstalled = TRUE; g_fUpgrade = TRUE; g_fServerSetup = FALSE; g_uTitleID = IDS_STR_CLI_ERROR_TITLE; g_dwMachineType = SERVICE_NONE; g_dwMachineTypeDs = 0; g_dwMachineTypeFrs = 0; g_fDependentClient = OcmStringsEqual(szType, MQMIG95_MSMQ_TYPE_DEP); MqDisplayError(NULL, IDS_WIN95_UPGRADE_MSG, 0); return TRUE; } // CheckWin9xUpgrade //+------------------------------------------------------------------------- // // Function: CheckMsmqAcmeInstalled // // Synopsis: Checks if MSMQ 1.0 (ACME) is installed on this computer. // Result is stored in g_fMSMQAlreadyInstalled. // // Returns: BOOL dependes on success. // //-------------------------------------------------------------------------- static BOOL CheckMsmqAcmeInstalled() { DebugLogMsg(L"Checking for installed components of MSMQ 1.0 ACME setup..."); // // Open ACME registry key // HKEY hKey ; LONG rc = RegOpenKeyEx( HKEY_LOCAL_MACHINE, ACME_KEY, 0L, KEY_ALL_ACCESS, &hKey ); if (rc != ERROR_SUCCESS) { DebugLogMsg(L"The ACME registry key could not be opened. MSMQ 1.0 ACME was not found."); return TRUE; } // // Enumerate the values for the first MSMQ entry. // DWORD dwIndex = 0 ; TCHAR szValueName[MAX_STRING_CHARS] ; TCHAR szValueData[MAX_STRING_CHARS] ; DWORD dwType ; TCHAR *pFile, *p; BOOL bFound = FALSE; do { DWORD dwNameLen = MAX_STRING_CHARS; DWORD dwDataLen = sizeof(szValueData) ; rc = RegEnumValue( hKey, dwIndex, szValueName, &dwNameLen, NULL, &dwType, (BYTE*) szValueData, &dwDataLen ); if (rc == ERROR_SUCCESS) { ASSERT(dwType == REG_SZ) ; // Must be a string pFile = _tcsrchr(szValueData, TEXT('\\')) ; if (!pFile) { // // Bogus entry. Must have a backslash. Ignore it. // continue ; } p = CharNext(pFile); if (OcmStringsEqual(p, ACME_STF_NAME)) { // // Found. Cut the STF file name from the full path name. // *pFile = TEXT('\0') ; bFound = TRUE; DebugLogMsg(L"MSMQ 1.0 ACME was found."); // // Delete the MSMQ entry // RegDeleteValue(hKey, szValueName); } else { pFile = CharNext(pFile) ; } } dwIndex++ ; } while (rc == ERROR_SUCCESS) ; RegCloseKey(hKey) ; if (!bFound) { // // MSMQ entry was not found. // DebugLogMsg(L"MSMQ 1.0 ACME was not found."); return TRUE; } // // Remove the "setup" subdirectory from the path name. // pFile = _tcsrchr(szValueData, TEXT('\\')) ; p = CharNext(pFile); *pFile = TEXT('\0') ; if (!OcmStringsEqual(p, ACME_SETUP_DIR_NAME)) { // // That's a problem. It should have been "setup". // Consider ACME installation to be corrupted (not completed successfully). // DebugLogMsg(L"MSMQ 1.0 ACME is corrupted"); return TRUE; } lstrcpy( g_szMsmqDir, szValueData); // // Check MSMQ type (client, server etc.) // DWORD dwMsmqType; BOOL bResult = MqReadRegistryValue( MSMQ_ACME_TYPE_REG, sizeof(DWORD), (PVOID) &dwMsmqType ); if (!bResult) { // // MSMQ 1.0 (ACME) is installed but MSMQ type is unknown. // MqDisplayError(NULL, IDS_MSMQ1TYPEUNKNOWN_ERROR, 0); return FALSE; } g_fMSMQAlreadyInstalled = TRUE; g_fUpgrade = (0 == (g_ComponentMsmq.Flags & SETUPOP_STANDALONE)); g_fServerSetup = FALSE; g_uTitleID = IDS_STR_CLI_ERROR_TITLE; g_dwMachineType = SERVICE_NONE; g_dwMachineTypeDs = 0; g_dwMachineTypeFrs = 0; g_fDependentClient = FALSE; switch (dwMsmqType) { case MSMQ_ACME_TYPE_DEP: { g_fDependentClient = TRUE; break; } case MSMQ_ACME_TYPE_IND: { break; } case MSMQ_ACME_TYPE_RAS: { g_fServerSetup = TRUE; g_uTitleID = IDS_STR_SRV_ERROR_TITLE; g_dwMachineType = SERVICE_RCS; break; } case MSMQ_ACME_TYPE_SRV: { g_fServerSetup = TRUE; g_uTitleID = IDS_STR_SRV_ERROR_TITLE; DWORD dwServerType = SERVICE_NONE; bFound = MqReadRegistryValue( MSMQ_MQS_REGNAME, sizeof(DWORD), (PVOID) &dwServerType ); switch (dwServerType) { case SERVICE_PEC: case SERVICE_PSC: case SERVICE_BSC: { g_dwMachineType = SERVICE_DSSRV; g_dwDsUpgradeType = dwServerType; g_dwMachineTypeDs = 1; g_dwMachineTypeFrs = 1; break; } case SERVICE_SRV: { g_dwMachineType = SERVICE_SRV; g_dwMachineTypeDs = 0; g_dwMachineTypeFrs = 1; break; } default: { // // Unknown MSMQ 1.0 server type. // MqDisplayError(NULL, IDS_MSMQ1SERVERUNKNOWN_ERROR, 0); return FALSE; break ; } } break; } default: { // // Unknown MSMQ 1.0 type // MqDisplayError(NULL, IDS_MSMQ1TYPEUNKNOWN_ERROR, 0); return FALSE; break; } } return TRUE; } // CheckMsmqAcmeInstalled //+------------------------------------------------------------------------- // // Function: CheckInstalledComponents // // Synopsis: Checks if MSMQ is already installed on this computer // // Returns: BOOL dependes on success. The result is stored in // g_fMSMQAlreadyInstalled. // //-------------------------------------------------------------------------- static BOOL CheckInstalledComponents() { g_fMSMQAlreadyInstalled = FALSE; g_fUpgrade = FALSE; DWORD dwOriginalInstalled = 0; DebugLogMsg(L"Checking for installed components..."); if (MqReadRegistryValue( REG_INSTALLED_COMPONENTS, sizeof(DWORD), (PVOID) &dwOriginalInstalled, /* bSetupRegSection = */TRUE )) { // // MSMQ 2.0 Beta 3 or later is installed. // Read MSMQ type and directory from registry // // Note: to improve performance (shorten init time) we can do these // reads when we actually need the values (i.e. later, not at init time). // DebugLogMsg(L"Message Queuing 2.0 Beta3 or later is installed"); if (!MqReadRegistryValue( MSMQ_ROOT_PATH, sizeof(g_szMsmqDir), (PVOID) g_szMsmqDir )) { if (!MqReadRegistryValue( REG_DIRECTORY, sizeof(g_szMsmqDir), (PVOID) g_szMsmqDir, /* bSetupRegSection = */TRUE )) { MqDisplayError(NULL, IDS_MSMQROOTNOTFOUND_ERROR, 0); return FALSE; } } if (!MqReadRegistryValue( MSMQ_MQS_DSSERVER_REGNAME, sizeof(DWORD), (PVOID)&g_dwMachineTypeDs ) || !MqReadRegistryValue( MSMQ_MQS_ROUTING_REGNAME, sizeof(DWORD), (PVOID)&g_dwMachineTypeFrs )) { // // This could be okay if dependent client is installed // if (OCM_MSMQ_DEP_CLIENT_INSTALLED != (dwOriginalInstalled & OCM_MSMQ_INSTALLED_TOP_MASK)) { MqDisplayError(NULL, IDS_MSMQTYPEUNKNOWN_ERROR, 0); return FALSE; } } g_fUpgrade = (0 == (g_ComponentMsmq.Flags & SETUPOP_STANDALONE)); g_fMSMQAlreadyInstalled = TRUE; g_fServerSetup = FALSE; g_uTitleID = IDS_STR_CLI_ERROR_TITLE ; g_dwMachineType = SERVICE_NONE; g_fDependentClient = FALSE; switch (dwOriginalInstalled & OCM_MSMQ_INSTALLED_TOP_MASK) { case OCM_MSMQ_DEP_CLIENT_INSTALLED: g_fDependentClient = TRUE; break; case OCM_MSMQ_IND_CLIENT_INSTALLED: break; case OCM_MSMQ_SERVER_INSTALLED: g_fServerSetup = TRUE; g_uTitleID = IDS_STR_SRV_ERROR_TITLE; switch (dwOriginalInstalled & OCM_MSMQ_SERVER_TYPE_MASK) { case OCM_MSMQ_SERVER_TYPE_PEC: case OCM_MSMQ_SERVER_TYPE_PSC: case OCM_MSMQ_SERVER_TYPE_BSC: g_dwMachineType = SERVICE_DSSRV; break; case OCM_MSMQ_SERVER_TYPE_SUPPORT: g_dwMachineType = SERVICE_SRV; break ; default: // // Beta3 and later, this is ok if DS without FRS installed. // In such case this MSMQ machine is presented to "old" MSMQ machines // as independent client. // if (g_dwMachineTypeDs && !g_dwMachineTypeFrs) { g_dwMachineType = SERVICE_NONE; break; } MqDisplayError(NULL, IDS_MSMQSERVERUNKNOWN_ERROR, 0); return FALSE; break ; } break; case OCM_MSMQ_RAS_SERVER_INSTALLED: g_fServerSetup = TRUE; g_uTitleID = IDS_STR_SRV_ERROR_TITLE; g_dwMachineType = SERVICE_RCS; break; default: MqDisplayError(NULL, IDS_MSMQTYPEUNKNOWN_ERROR, 0); return FALSE; break; } return TRUE; } // MSMQ beta 3 or later #ifndef _DEBUG // // If we're not in OS setup, don't check older versions (beta2, msmq1, etc). // This is a *little* less robust (we expect the user to upgrade msmq only thru OS // upgrade), but decrease init time (ShaiK, 25-Oct-98) // // In we are running as a post-upgrade-on-cluster wizard, do check for old versions. // if (!g_fWelcome || !Msmq1InstalledOnCluster()) { if (0 != (g_ComponentMsmq.Flags & SETUPOP_STANDALONE)) { DebugLogMsg(L"Message Queuing 2.0 Beta3 or later is NOT installed. Skipping check for other versions..."); DebugLogMsg(L"Consider Message Queuing NOT installed on this computer."); return TRUE; } } #endif //_DEBUG if (MqReadRegistryValue( OCM_REG_MSMQ_SETUP_INSTALLED, sizeof(DWORD), (PVOID) &dwOriginalInstalled )) { // // MSMQ 2.0 beta2 or MSMQ 1.0 k2 is installed. // Read MSMQ type and directory from registry // DebugLogMsg(L"Message Queuing 2.0 Beta2 or MSMQ 1.0 k2 is installed."); if (!MqReadRegistryValue( OCM_REG_MSMQ_DIRECTORY, sizeof(g_szMsmqDir), (PVOID) g_szMsmqDir )) { MqDisplayError(NULL, IDS_MSMQROOTNOTFOUND_ERROR, 0); return FALSE; } g_fMSMQAlreadyInstalled = TRUE; g_fUpgrade = (0 == (g_ComponentMsmq.Flags & SETUPOP_STANDALONE)); g_fServerSetup = FALSE; g_uTitleID = IDS_STR_CLI_ERROR_TITLE ; g_dwMachineType = SERVICE_NONE; g_dwMachineTypeDs = 0; g_dwMachineTypeFrs = 0; g_fDependentClient = FALSE; switch (dwOriginalInstalled & OCM_MSMQ_INSTALLED_TOP_MASK) { case OCM_MSMQ_DEP_CLIENT_INSTALLED: g_fDependentClient = TRUE; break; case OCM_MSMQ_IND_CLIENT_INSTALLED: break; case OCM_MSMQ_SERVER_INSTALLED: g_fServerSetup = TRUE; g_uTitleID = IDS_STR_SRV_ERROR_TITLE; switch (dwOriginalInstalled & OCM_MSMQ_SERVER_TYPE_MASK) { case OCM_MSMQ_SERVER_TYPE_PEC: g_dwDsUpgradeType = SERVICE_PEC; g_dwMachineType = SERVICE_DSSRV; g_dwMachineTypeDs = 1; g_dwMachineTypeFrs = 1; break; case OCM_MSMQ_SERVER_TYPE_PSC: g_dwDsUpgradeType = SERVICE_PSC; g_dwMachineType = SERVICE_DSSRV; g_dwMachineTypeDs = 1; g_dwMachineTypeFrs = 1; break; case OCM_MSMQ_SERVER_TYPE_BSC: g_dwDsUpgradeType = SERVICE_BSC; g_dwMachineType = SERVICE_DSSRV; g_dwMachineTypeDs = 1; g_dwMachineTypeFrs = 1; break; case OCM_MSMQ_SERVER_TYPE_SUPPORT: g_dwMachineType = SERVICE_SRV; g_dwMachineTypeFrs = 1; break ; default: MqDisplayError(NULL, IDS_MSMQSERVERUNKNOWN_ERROR, 0); return FALSE; break ; } break; case OCM_MSMQ_RAS_SERVER_INSTALLED: g_fServerSetup = TRUE; g_uTitleID = IDS_STR_SRV_ERROR_TITLE; g_dwMachineType = SERVICE_RCS; break; default: MqDisplayError(NULL, IDS_MSMQTYPEUNKNOWN_ERROR, 0); return FALSE; break; } TCHAR szMsmqVersion[MAX_STRING_CHARS] = {0}; if (MqReadRegistryValue( OCM_REG_MSMQ_PRODUCT_VERSION, sizeof(szMsmqVersion), (PVOID) szMsmqVersion )) { // // Upgrading MSMQ 2.0 beta 2, don't upgrade DS // g_dwDsUpgradeType = 0; } return TRUE; } // MSMQ 2.0 or MSMQ 1.0 k2 // // Check if MSMQ 1.0 (ACME) is installed // BOOL bRetCode = CheckMsmqAcmeInstalled(); if (g_fMSMQAlreadyInstalled) return bRetCode; // // Special case: check if this is MSMQ 1.0 on Win9x upgrade // bRetCode = CheckWin9xUpgrade(); if (g_fMSMQAlreadyInstalled) return bRetCode; // // Special case: workaround for bug 2656, registry corrupt for msmq1 k2 on cluster // return CheckMsmqK2OnCluster(); } // CheckInstalledComponents static bool s_fInitCancelThread = false; //+------------------------------------------------------------------------- // // Function: MqOcmInitComponent // // Synopsis: Called by MsmqOcm() on OC_INIT_COMPONENT // // Arguments: ComponentId -- name of the MSMQ component // Param2 -- pointer to setup info struct // // Returns: Win32 error code // //-------------------------------------------------------------------------- DWORD MqOcmInitComponent( IN const LPCTSTR ComponentId, IN OUT PVOID Param2 ) { DebugLogMsg(L"Starting initialization..."); // // Store per component info // PSETUP_INIT_COMPONENT pInitComponent = (PSETUP_INIT_COMPONENT)Param2; g_ComponentMsmq.hMyInf = pInitComponent->ComponentInfHandle; g_ComponentMsmq.dwProductType = pInitComponent->SetupData.ProductType; g_ComponentMsmq.HelperRoutines = pInitComponent->HelperRoutines; g_ComponentMsmq.Flags = pInitComponent->SetupData.OperationFlags; lstrcpy( g_ComponentMsmq.SourcePath, pInitComponent->SetupData.SourcePath ); lstrcpy( g_ComponentMsmq.ComponentId, ComponentId ); TCHAR sz[100]; DebugLogMsg(L"Dump of OCM flags:"); _stprintf(sz, _T("%s=0x%x"), _T("ProductType"), pInitComponent->SetupData.ProductType); DebugLogMsg(sz); _stprintf(sz, _T("%s=0x%x"), _T("OperationFlags"), pInitComponent->SetupData.OperationFlags); DebugLogMsg(sz); _stprintf(sz, _T("%s=%s"), _T("SourcePath"), pInitComponent->SetupData.SourcePath); DebugLogMsg(sz); _stprintf(sz, _T("%s=%d"), _T("ComponentId"), ComponentId); DebugLogMsg(sz); if (!s_fInitCancelThread) { g_CancelRpc.Init(); s_fInitCancelThread = true; } if (INVALID_HANDLE_VALUE == g_ComponentMsmq.hMyInf) { g_fCancelled = TRUE; DebugLogMsg(L"The value of the handle for Msmqocm.inf is invalid. Setup will not continue."); return NO_ERROR; } if (0 == (g_ComponentMsmq.Flags & SETUPOP_STANDALONE)) { // // OS setup - don't show UI // DebugLogMsg(L"OS setup. Switching to unattended mode..."); g_fBatchInstall = TRUE; } // // Check if wer'e in unattended mode. // if (g_ComponentMsmq.Flags & SETUPOP_BATCH) { g_fBatchInstall = TRUE; lstrcpy( g_ComponentMsmq.szUnattendFile, pInitComponent->SetupData.UnattendFile ); DebugLogMsg(L"Unattended mode. The unattended answer file is:"); DebugLogMsg(g_ComponentMsmq.szUnattendFile); } // // Append layout inf file to our inf file // SetupOpenAppendInfFile( 0, g_ComponentMsmq.hMyInf, 0 ); // // Check if MSMQ is already installed on this machine. // Result is stored in g_fMSMQAlreadyInstalled. // if (!CheckInstalledComponents()) { DebugLogMsg(L"An error occurred during the checking for installed components. Setup will not continue."); g_fCancelled = TRUE; return NO_ERROR; } if (g_fWelcome && Msmq1InstalledOnCluster() && g_dwMachineTypeDs != 0) { // // Running as a post-cluster-upgrade wizard. // MSMQ DS server should downgrade to routing server. // g_dwMachineTypeDs = 0; g_dwMachineTypeFrs = 1; g_dwMachineType = SERVICE_SRV; } // // On fresh install on non domain controller, // default is installing independent client. // if (!g_fMSMQAlreadyInstalled && !g_dwMachineTypeDs) { g_fServerSetup = FALSE; g_fDependentClient = FALSE; g_dwMachineTypeFrs = 0; } if (!InitializeOSVersion()) { DebugLogMsg(L"An error occurred in getting the operating system information. Setup will not continue."); g_fCancelled = TRUE; return NO_ERROR; } // // init number of subcomponent that is depending on platform // if (MSMQ_OS_NTS == g_dwOS || MSMQ_OS_NTE == g_dwOS) { g_dwSubcomponentNumber = g_dwAllSubcomponentNumber; } else { g_dwSubcomponentNumber = g_dwClientSubcomponentNumber; } _stprintf(sz, TEXT("The number of subcomponents is %d"), g_dwSubcomponentNumber); DebugLogMsg(sz); // // User must have admin access rights to run this setup // if (!CheckServicePrivilege()) { g_fCancelled = TRUE; MqDisplayError(NULL, IDS_SERVICEPRIVILEGE_ERROR, 0); return NO_ERROR; } if ((0 == (g_ComponentMsmq.Flags & SETUPOP_STANDALONE)) && !g_fMSMQAlreadyInstalled) { // // GUI mode + MSMQ is not installed // g_fOnlyRegisterMode = TRUE; DebugLogMsg(L"GUI mode and Message Queuing is not installed."); } DebugLogMsg(L"Initialization was completed successfully!"); return NO_ERROR ; } //MqOcmInitComponent bool MqInit() /*++ Routine Description: Handles "lazy initialization" (init as late as possible to shorten OCM startup time) Arguments: None Return Value: None --*/ { static bool fBeenHere = false; static bool fLastReturnCode = true; if (fBeenHere) { return fLastReturnCode; } fBeenHere = true; DebugLogMsg(L"Starting late initialization..."); GetSystemDirectory( g_szSystemDir, sizeof(g_szSystemDir) / sizeof(g_szSystemDir[0]) ); DWORD dwNumChars = sizeof(g_wcsMachineName) / sizeof(g_wcsMachineName[0]); GetComputerName(g_wcsMachineName, &dwNumChars); dwNumChars = sizeof(g_wcsMachineNameDns) / sizeof(g_wcsMachineNameDns[0]); GetComputerNameEx(ComputerNameDnsFullyQualified, g_wcsMachineNameDns, &dwNumChars); // // Create and set MSMQ directories // DWORD dwResult = SetDirectories(); if (NO_ERROR != dwResult) { DebugLogMsg(L"An error occurred in setting the folders. Setup will not continue."); g_fCancelled = TRUE; fLastReturnCode = false; return fLastReturnCode; } // // initialize to use Ev.lib later. We might need it to use registry function // in setup code too. // CmInitialize(HKEY_LOCAL_MACHINE, L""); DebugLogMsg(L"Late initialization was completed successfully!"); fLastReturnCode = true; return fLastReturnCode; }//MqInit
ef783623470b2eecc9fc0cf19c1ad2cd8f3a09c5
2e3e626e7ea4fbaf5d1c3109291cbdc7e43b2679
/OTA_Full/OTA_Full.ino
cac3d7fed88e24cbe45f0aa79f2ef6684bb3edaa
[]
no_license
aofserver/Project-iot
3f2a34ae0092a1c5d6480beeb3192ba918c327c3
aead97bc566d25acd463120c9d3ad4f134ad2192
refs/heads/master
2022-12-05T08:15:04.370093
2020-08-28T03:42:32
2020-08-28T03:42:32
290,943,020
0
0
null
null
null
null
UTF-8
C++
false
false
6,754
ino
OTA_Full.ino
/* ----- HOW TO USE CODE ----- 1. upload this code 2. when update 2.1 select "Network port" before upload (connect local internet) 2.2 open browser go to url login esp (url is local ip esp connect internet) and upload ".bin" only */ #include <WiFi.h> #include <WiFiClient.h> #include <WebServer.h> #include <ESPmDNS.h> #include <Update.h> #include <ESPmDNS.h> #include <WiFiUdp.h> #include <ArduinoOTA.h> #include "TonyS_X1.h" const char* host = "esp32"; const char* ssid = "beam"; const char* password = "beam2539"; WebServer server(80); unsigned long startBlink; unsigned long nowTime; int delayTime = 1000; /* * Login page */ const char* loginIndex = "<form name='loginForm'>" "<table width='20%' bgcolor='A09F9F' align='center'>" "<tr>" "<td colspan=2>" "<center><font size=4><b>ESP32 Login Page</b></font></center>" "<br>" "</td>" "<br>" "<br>" "</tr>" "<td>Username:</td>" "<td><input type='text' size=25 name='userid'><br></td>" "</tr>" "<br>" "<br>" "<tr>" "<td>Password:</td>" "<td><input type='Password' size=25 name='pwd'><br></td>" "<br>" "<br>" "</tr>" "<tr>" "<td><input type='submit' onclick='check(this.form)' value='Login'></td>" "</tr>" "</table>" "</form>" "<script>" "function check(form)" "{" "if(form.userid.value=='admin' && form.pwd.value=='admin')" //set Username and Password "{" "window.open('/serverIndex')" "}" "else" "{" " alert('Error Password or Username')/*displays error message*/" "}" "}" "</script>"; /* * Server Index Page */ const char* serverIndex = "<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>" "<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>" "<input type='file' name='update'>" "<input type='submit' value='Update'>" "</form>" "<div id='prg'>progress: 0%</div>" "<script>" "$('form').submit(function(e){" "e.preventDefault();" "var form = $('#upload_form')[0];" "var data = new FormData(form);" " $.ajax({" "url: '/update'," "type: 'POST'," "data: data," "contentType: false," "processData:false," "xhr: function() {" "var xhr = new window.XMLHttpRequest();" "xhr.upload.addEventListener('progress', function(evt) {" "if (evt.lengthComputable) {" "var per = evt.loaded / evt.total;" "$('#prg').html('progress: ' + Math.round(per*100) + '%');" "}" "}, false);" "return xhr;" "}," "success:function(d, s) {" "console.log('success!')" "}," "error: function (a, b, c) {" "}" "});" "});" "</script>"; /* * setup function */ void setup(void) { Serial.begin(115200); Tony.begin(); //---- begin Library Tony.pinMode(LED_BUILTIN, OUTPUT); //OTA local Network port Serial.println("Booting"); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("Connection Failed! Rebooting..."); delay(5000); ESP.restart(); } ArduinoOTA .onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) type = "sketch"; else // U_SPIFFS type = "filesystem"; // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); }) .onEnd([]() { Serial.println("\nEnd"); }) .onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }) .onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); Serial.println("Ready"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); //OTA webupdate // Connect to WiFi network WiFi.begin(ssid, password); Serial.println(""); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); /*use mdns for host name resolution*/ if (!MDNS.begin(host)) { //http://esp32.local Serial.println("Error setting up MDNS responder!"); while (1) { delay(1000); } } Serial.println("mDNS responder started"); /*return index page which is stored in serverIndex */ server.on("/", HTTP_GET, []() { server.sendHeader("Connection", "close"); server.send(200, "text/html", loginIndex); }); server.on("/serverIndex", HTTP_GET, []() { server.sendHeader("Connection", "close"); server.send(200, "text/html", serverIndex); }); /*handling uploading firmware file */ server.on("/update", HTTP_POST, []() { server.sendHeader("Connection", "close"); server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); ESP.restart(); }, []() { HTTPUpload& upload = server.upload(); if (upload.status == UPLOAD_FILE_START) { Serial.printf("Update: %s\n", upload.filename.c_str()); if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_WRITE) { /* flashing firmware to ESP*/ if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_END) { if (Update.end(true)) { //true to set the size to the current progress Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); } else { Update.printError(Serial); } } }); server.begin(); } void loop(void) { ArduinoOTA.handle(); server.handleClient(); delay(1); nowTime = millis(); if(nowTime - startBlink >= delayTime){ Tony.digitalWrite(LED_BUILTIN, HIGH); startBlink = millis(); } else{ Tony.digitalWrite(LED_BUILTIN, LOW); } }
20bbdd6f4d2b30cde41abc929b1c72a1158be356
29abb25d3f1a0facce3bb8595d8555c51dfa1156
/MemoryManager/MMRBTree.h
403707d3c8cd8d3d3fc3db7d67d10807c95e3207
[]
no_license
Heisenbug/cpp-memory-manager
9ad48a758ee0e646dfc28f1b569ff9a5dd6c6b3e
e93897f8b78728b9f87793dbbe213068b86e9a78
refs/heads/master
2016-09-08T02:37:03.752989
2012-03-21T12:05:18
2012-03-21T12:05:18
33,891,365
1
0
null
null
null
null
UTF-8
C++
false
false
7,969
h
MMRBTree.h
#ifndef MMRBTREE_H_INCLUDE_GUARD #define MMRBTREE_H_INCLUDE_GUARD #include <utility> #include <iostream> #include <string> namespace MM { enum color_type { RED, BLACK }; class rbtree_error {}; template<typename K, typename V> struct rbtnode { rbtnode(const K& k, const V& v, const color_type& c) : key(k), value(v), p(0), l(0), r(0), color(c) { } K key; V value; rbtnode* p; rbtnode* l; rbtnode* r; color_type color; }; template<typename K, typename V> class rbtree { typedef rbtnode<K, V> Node; Node* nil; Node* handle; public: typedef std::pair<K, V> pair; rbtree() : nil(new rbtnode<K, V>(0, 0, BLACK)), handle(nil) { handle->p = nil; } rbtree(const K* keys, const V* values, size_t n) : nil(new rbtnode<K, V>(0, 0, BLACK)), handle(nil) { handle->p = nil; for (size_t i = 0; i < n; ++i) { insert(keys[i], values[i]); } } ~rbtree() { } template<typename Function_Object> void walk(Function_Object do_) { if (handle != nil) walk_(do_, handle); } void insert(const K& k, const V& v) { RBinsert(new Node(k, v, RED)); } void remove(const K& k) { if (handle != nil) { Node* p = search_(k, handle); if (p != nil) { Node* free_node = RBdelete(p); delete free_node; } } else { throw rbtree_error(); } } V minimum() const { if (handle != nil) { Node* p = minimum_(handle); return p->value; } throw rbtree_error(); } pair minimum_p() const { if (handle != nil) { Node* p = minimum_(handle); return std::make_pair(p->key, p->value); } throw rbtree_error(); } V maximum() const { if (handle != nil) { Node* p = maximum_(handle); return p->value; } throw rbtree_error(); } pair maximum_p() const { if (handle != nil) { Node* p = maximum_(handle); return std::make_pair(p->key, p->value); } throw rbtree_error(); } V search(const K& k) const { if (handle != nil) { Node* p = search_(k); return p->value; } throw rbtree_error(); } unsigned int bheight() const { if (handle != nil) return bheight_(handle); else return 0; } private: template<typename Function_Object> void walk_(Function_Object do_, Node* n) { if (n->l != nil) walk_(do_, n->l); do_(std::make_pair(n->key, n->value)); if (n->r != nil) walk_(do_, n->r); } Node* minimum_(Node* x) const { while(x->l != nil) { x = x->l; } return x; } Node* maximum_(Node* x) const { while(x->r != nil) { x = x->r; } return x; } Node* successor_(Node* x) const { if (x != nil) { if (x->r != nil) { return minimum_(x->r); } Node* y = x->p; while (y != nil && x == y->r) { x = y; y = y->p; } return y; } } Node* search_(const K& k, Node* x) const { while (x != nil && k != x->key) { if (k < x->key) x = x->l; else x = x->r; } return x; } unsigned int bheight_(Node* x) const { unsigned int h = 0; while(x->r != nil) { x = x->r; if (x->color == BLACK) { h++; } } return (h + 1); } void left_rotate(Node* x) { if (x->r != nil) { Node* y = x->r; x->r = y->l; if (y->l != nil) { y->l->p = x; } y->p = x->p; if (x->p == nil) { handle = y; } else { if (x->p->l == x) { x->p->l = y; } else { x->p->r = y; } } y->l = x; x->p = y; } } void right_rotate(Node* y) { if (y->l != nil) { Node* x = y->l; y->l = x->r; if (x->r != nil) { x->r->p = y; } x->p = y->p; if (y->p == nil) { handle = x; } else { if (y == y->p->r) { y->p->r = x; } else { y->p->l = x; } } x->r = y; y->p = x; } } void RBdelete_fixup(Node* x) { Node* w = nil; while ((x != handle) && (x->color == BLACK)) { if (x == x->p->l) { w = x->p->r; if (w->color == RED) { w->color = BLACK; x->p->color = RED; left_rotate(x->p); w = x->p->r; } if ((w->l->color == BLACK) && (w->r->color == BLACK)) { w->color = RED; x = x->p; } else { if (w->r->color == BLACK) { w->l->color = BLACK; w->color = RED; right_rotate(w); w = x->p->r; } w->color = x->p->color; x->p->color = BLACK; w->r->color = BLACK; left_rotate(x->p); x = handle; } } else { w = x->p->l; if (w->color == RED) { w->color = BLACK; x->p->color = RED; right_rotate(x->p); w = x->p->l; } if (w->r->color == BLACK && w->l->color == BLACK) { w->color = RED; x = x->p; } else { if (w->l->color == BLACK) { w->r->color = BLACK; w->color = RED; left_rotate(w); w = x->p->l; } w->color = x->p->color; x->p->color = BLACK; w->r->color = BLACK; right_rotate(x->p); x = handle; } } } x->color = BLACK; } Node* RBdelete(Node* z) { Node* x = nil; Node* y = nil; if (z->l == nil || z->r == nil) { y = z; } else { y = successor_(z); } if (y->l != nil) { x = y->l; } else { x = y->r; } x->p = y->p; if (y->p == nil) { handle = x; } else { if (y == y->p->l) { y->p->l = x; } else { y->p->r = x; } } if (y != z) { z->key = y->key; z->value = y->value; } if (y->color == BLACK) { RBdelete_fixup(x); } return y; } void RBinsert_fixup(Node* z) { Node* y = nil; while (z->p->color == RED) { if (z->p == z->p->p->l) { y = z->p->p->r; if (y->color == RED) { z->p->color = BLACK; y->color = BLACK; z->p->p->color = RED; z = z->p->p; } else { if (z == z->p->r) { z = z->p; left_rotate(z); } z->p->color = BLACK; z->p->p->color = RED; right_rotate(z->p->p); } } else { y = z->p->p->l; if (y->color == RED) { z->p->color = BLACK; y->color = BLACK; z->p->p->color = RED; z = z->p->p; } else { if (z == z->p->l) { z = z->p; right_rotate(z); } z->p->color = BLACK; z->p->p->color = RED; left_rotate(z->p->p); } } } handle->color = BLACK; } void RBinsert(Node* new_node) { Node* x = handle; Node* y = nil; while (x != nil) { y = x; if (new_node->key < x->key) { x = x->l; } else { x = x->r; } } new_node->p = y; if (y == nil) { handle = new_node; } else { if (new_node->key < y->key) { y->l = new_node; } else { y->r = new_node; } } new_node->l = nil; new_node->r = nil; RBinsert_fixup(new_node); } }; template<typename K, typename V> struct Show { std::ostream& out; std::string sep; Show(std::ostream& o, const std::string& s = "") : out(o), sep(s) { } void operator()(std::pair<K, V> p) { out << "K: " << p.first << "\t V: " << p.second << sep; } }; } #endif // MMRBTREE_H_INCLUDE_GUARD
787bdce23421651b8913c96daf282441a60a2315
b521694fb2a399dcfdbe196ffa66028fe14cc9d0
/Chapter02/multiplevariables.cpp
acd6cd07a7c61a5e98d6cfaa2352d0c3d8bcb8b1
[]
no_license
nic-cs150-fall-2019/LectureCodes103
7eccddcba27a0add1e89fc19955dc4c95a019848
d5fa40d0dad00c1a88388dfb74ffdf27ee409ec3
refs/heads/master
2020-07-12T05:49:03.748666
2019-11-07T23:23:50
2019-11-07T23:23:50
204,734,593
0
0
null
null
null
null
UTF-8
C++
false
false
543
cpp
multiplevariables.cpp
// multiplevariables.cpp // Description: Declaring multiple variables // Gabe de la Cruz // CS150 103 #include <iostream> using namespace std; int main() { int floors = 15, rooms = 300, suites = 30, capacity = 100000; // WRONG: capacity = 100,000 // Display message to screen cout << "The Grand Hotel has " << floors << " floors" << endl; cout << "with " << rooms << " rooms and " << suites; cout << " suites.\nIt has a max capacity of "; cout << capacity << " people\n"; return 0; }
79429c6891196f684e927579a52be46e209d52c7
6bb513beb7ad0c9c873a0595e9e6f08a9d680d40
/RotateList.cpp
a19a09ce62e8fdb44c903750fba3c3a6e5cea232
[]
no_license
tectronics/Leetcode
921107dbe1f93ebb0accf5bba34674da66d4f78b
2c3956d75b2756d09da4b97edb2154831c3dff4c
refs/heads/master
2018-02-07T23:02:26.684852
2016-10-23T03:23:38
2016-10-23T03:23:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
679
cpp
RotateList.cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { ListNode *last=head; if (head==nullptr) { return head; } int size = 1; while (last->next!=nullptr) { last = last->next; ++size; } int off =(size-k%size)%size; ListNode *pre=head,*newHead=pre->next; if (off==0) { return head; } else { while (--off) { pre = pre->next; newHead = pre->next; } } last->next = head; pre->next = nullptr; head = newHead; return head; } };
04c5fa6ef9159a323bc94d5a21825bebc7da2a02
fa13000f91ef51b37df05211ac2f6d6557b47f9e
/Recursion/NumbersWithDuplicates.cpp
2bbfed9cdc6d121fa3fd7b0f15b9c1b9e57a71cc
[ "MIT" ]
permissive
vatsalagarwal09/CompetitiveProgramming
9c6cbc7b599f35d41431e93ad5ab10f6d29d7c35
2cdc314140e773e033ee6602d2019c6507883a4d
refs/heads/master
2023-01-01T12:17:22.242520
2020-10-20T07:13:04
2020-10-20T07:13:04
292,911,099
1
3
MIT
2020-10-20T07:13:06
2020-09-04T17:44:12
C++
UTF-8
C++
false
false
1,306
cpp
NumbersWithDuplicates.cpp
#include <iostream> using namespace std; #include<algorithm> long numDuplicate(long *input, long n, long *freq, long *fact){ if(n==0 || n==1){ return 0; } long count = 0; long fac_deno = 1; for(long i = 0; i<10; i++){ if(freq[i] != 0){ fac_deno = fac_deno * fact[freq[i]]; } } for(long i = input[0]; i<9; i++){ if(freq[i+1] > 0){ count += freq[i+1]; } } long ans = (count * fact[n-1])/fac_deno ; freq[input[0]]--; long smallAns = numDuplicate(input+1, n-1, freq, fact); return ans + smallAns; } long numberOfNumbersWithDuplicates(long num){ // Write your code here long count = 0; long a = num; for(long i = 0; a != 0; i++){ a = a/10; count++; } long *input = new long[count]; long *fact = new long[count+1]; long freq[10] = {0}; fact[0] = 1; a = num; for(long i = count-1; i>=0; i--){ input[i] = a%10; a = a/10; freq[input[i]]++; } for(long i = 0; i<count; i++){ fact[i+1] = (i+1) * fact[i]; } long final_ans = numDuplicate(input, count, freq, fact); return final_ans; } int main() { long n; cin >> n; cout << numberOfNumbersWithDuplicates(n) << endl; }
956c4c73cddd46a5449fe27ed1d1b49162be65db
4f132c27b64c3844a21ee331655ee2fd87207e83
/type_sequence/concat.hpp
55ebfdacff348d2dba6f63eee783c93a2d8baa27
[]
no_license
scopeview/libtemplate
1e1cefdb61ce0502a812596bb7b0e57e50ce41dc
da46306f223b593c4717449c8ab16852544ca23d
refs/heads/master
2021-01-01T03:34:30.020326
2016-05-09T12:06:42
2016-05-09T12:06:42
58,378,275
0
0
null
null
null
null
UTF-8
C++
false
false
573
hpp
concat.hpp
#ifndef __LIBTEMPLATE_TYPE_SEQUENCE_CONCAT_HPP__ #define __LIBTEMPLATE_TYPE_SEQUENCE_CONCAT_HPP__ namespace libtemplate { namespace type_sequence { template<typename... T> struct concat; template<typename... T1, typename... T2> struct concat<std::tuple<T1...>, std::tuple<T2...>> { typedef std::tuple<T1..., T2...> type; }; template<typename... T1, typename... T2, typename... T3> struct concat<std::tuple<T1...>, std::tuple<T2...>, std::tuple<T3...>> { typedef std::tuple<T1..., T2..., T3...> type; }; }} #endif /* __LIBTEMPLATE_TYPE_SEQUENCE_CONCAT_HPP__ */
c7e25e1431bb0ddb186d8286f360fbc7e7464ccc
e5e4133b900dec453a93605fb0c4a3e02b934630
/src/io/io_lib/ParticleContainer.cpp
f0814204314dea7dbd1c5219f0739d1d4f01074d
[]
no_license
MineClever/claudius
cf73d9c34bebb3fd0ada9078af68857529ee5142
aad9f38afe61c870e2bcd060582b2208f068e3f2
refs/heads/master
2023-07-06T19:58:15.899178
2019-09-12T16:36:11
2019-09-12T16:36:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,303
cpp
ParticleContainer.cpp
// // Created by Jan on 20.04.2019. // #include "ParticleContainer.h" const unsigned int ParticleContainer::particleCount() { return particles.size() / 3; } void ParticleContainer::addParticle(float x, float y, float z) { particles.emplace_back(x); particles.emplace_back(y); particles.emplace_back(z); } const bool ParticleContainer::isEmpty() { return particleCount() == 0; } const float *ParticleContainer::getParticleData() { return particles.data(); } const bool ParticleContainer::hasColorData() { return !colors.empty(); } const int *ParticleContainer::getColorData() { return colors.data(); } void ParticleContainer::addColor(int r, int g, int b) { colors.emplace_back(r); colors.emplace_back(g); colors.emplace_back(b); } const bool ParticleContainer::hasRemissionData() { return !remissions.empty(); } const float *ParticleContainer::getRemissionsData() { return remissions.data(); } void ParticleContainer::addRemission(float r) { remissions.emplace_back(r); } void ParticleContainer::reservePositions(unsigned int count) { particles.reserve(count * 3); } void ParticleContainer::reserveColors(unsigned int count) { colors.reserve(count * 3); } void ParticleContainer::reserveRemissions(unsigned int count) { remissions.reserve(count); }
ededef641b689e9be052de226e736345464fb276
c72b140c8388a276f5f7ef4afc80312c07fa100a
/includes/bc-tools.hpp
4e8a9c036e81f7aa90ba50bdefc240568be57332
[]
no_license
lemenendez/bc-tools
fa6fe9dd5f90bd676ed4b59ce3b4b90014d652ad
877f60706e1f0ebc30670ac26f1ac3dff345b618
refs/heads/master
2020-04-16T21:11:47.847673
2019-01-16T00:28:18
2019-01-16T00:28:18
165,916,580
0
0
null
null
null
null
UTF-8
C++
false
false
1,962
hpp
bc-tools.hpp
#include <bitcoin/bitcoin.hpp> #include <string> #include <array> using namespace bc; class my_bc_tools { std::string my_secret_key; std::string bitcoin_address; ec_secret decoded_secret_ec; wallet::ec_private secret_key; wallet::ec_public public_key; bool decodeSecret(std::string secret); public: std::string getSecretKey(); ec_secret getDecodedSecretKey(); bool setSecretKey(std::string secret); void printSecretKeyHex(); void printPublicKey(); void printBitcoinAddress(); }; void my_bc_tools::printSecretKeyHex() { for (const auto& b: decoded_secret_ec) std::cout << std::hex << (0xFF & b) << ' ' ; std::cout << std::endl; } void my_bc_tools::printPublicKey() { std::cout << public_key.encoded() << std::endl; } ec_secret my_bc_tools::getDecodedSecretKey() { return decoded_secret_ec; } std::string my_bc_tools::getSecretKey() { return my_secret_key; } bool my_bc_tools::setSecretKey(std::string secret) { if(secret.length()!=ec_secret_size * 2) return false; bool decoded = decodeSecret(secret); if(decoded) { my_secret_key = secret; secret_key = wallet::ec_private(decoded_secret_ec, wallet::ec_private::mainnet_p2kh); // generate private key public_key = wallet::ec_public(secret_key); // generate public key bc::data_chunk public_key_data; public_key.to_data(public_key_data); const auto hash = bc::bitcoin_short_hash(public_key_data); // hash bc::data_chunk unencoded_address; unencoded_address.reserve(25); unencoded_address.push_back(0); bc::extend_data(unencoded_address, hash); bc::append_checksum(unencoded_address); bitcoin_address = bc::encode_base58(unencoded_address); } return decoded; } void my_bc_tools::printBitcoinAddress() { std::cout << bitcoin_address << std::endl; } bool my_bc_tools::decodeSecret(std::string secret) { return decode_base16(decoded_secret_ec, secret ); }
b85975f04d2cfbd2c3236a5e1f1cde537529f792
4a54dd5a93bbb3f603a2875d5e6dcb3020fb52f2
/official/zone-2013-10-15-france/src/CharInfoDB.h
fc0d856206a285f86c56103b402d763a95730b0b
[]
no_license
Torashi1069/xenophase
400ebed356cff6bfb735f9c03f10994aaad79f5e
c7bf89281c95a3c5cf909a14d0568eb940ad7449
refs/heads/master
2023-02-02T19:15:08.013577
2020-08-17T00:41:43
2020-08-17T00:41:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
h
CharInfoDB.h
#pragma once #include "shared/ODBC.h" struct MannerPointData; class CCharInfoDB : public CODBC { public: CCharInfoDB(); ~CCharInfoDB(); public: void UpdateItemStoreMoney(int AID, int money); void DeleteItem(int GID); void GetCharacterName(int GID, char* charname); BOOL LoadMPInfo(unsigned long AID, std::list<MannerPointData>* info, int& LastDate); void DeleteMP(unsigned long AID, unsigned long otherGID); BOOL InsertNewMP(unsigned long AID, unsigned long otherGID, int type); BOOL GetCharacterID(char* Name, unsigned long& AID, unsigned long& GID); BOOL UpdatePVPEvent(char* GID, char* Name); BOOL GetPVPEvent(char* GID, char* Name); void GetErrorString(SQLHSTMT hStmt, char* lpszError); int GetShortCutKey(unsigned long GID, unsigned char* pShortCutKey); int UpdateShortCutKey(unsigned long GID, unsigned char* pShortCutKey); int InsertHuntingList(int GID); int InsertTimeList(int GID); int SelectHuntingList(unsigned long GID, unsigned char* buf); int UpdateHuntingList(unsigned long GID, unsigned char* buf, int size); int SelectTimeList(unsigned long GID, unsigned char* buf); int UpdateTimeList(unsigned long GID, unsigned char* buf, int size); };
4a4ea1046aea1404ccf59f2f7027a0e80ad692dd
26c2de5a0cf4ed017f835bae7cc125750d17de82
/dehaze_mkl/dehaze_mkl/AtmosphericMaskCalculator.cpp
84f1e952bbf65f4e0c071f9590d4153a7657c4e1
[]
no_license
wyq1973/Dehaze_CPP_MKL_OPENCV
9d41f9096cff1868d5144a9d3a0a92f6b51da523
99b78f7e99b5ac4f23d969a3d1a2af49e7b41b06
refs/heads/master
2021-10-23T08:05:27.431295
2019-03-15T09:46:17
2019-03-15T09:46:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,880
cpp
AtmosphericMaskCalculator.cpp
#include "pch.h" #include "AtmosphericMaskCalculator.h" //#include <iostream> //#include <math.h> #include <algorithm> AtmosphericMaskCalculator::AtmosphericMaskCalculator(float r, float eps, float w, float maxV) { this->r = r; this->eps = eps; this->w = w; this->maxV = maxV; this->guidedFilter = GuidedFilter::GuidedFilter(r, eps); } struct AtmosphericMask AtmosphericMaskCalculator::calculate(const ImageMat & imageMat) { cv::Mat darkChannelCvMat = cv::Mat(imageMat.rows, imageMat.cols, CV_64FC1); ImageMat darkChannelMat = MKLConverter::fromCVMat(darkChannelCvMat); for (int row = 0; row < imageMat.rows; row++) { for (int col = 0; col < imageMat.cols; col++) { double temp = fmin(imageMat.matData[0][row*imageMat.cols + col], imageMat.matData[1][row*imageMat.cols + col]); double min = fmin(temp, imageMat.matData[2][row*imageMat.cols + col]); darkChannelMat.matData[0][row*imageMat.cols + col] = min; } } ImageMat convertMat(darkChannelMat); for (int i = 0; i <= convertMat.dims; i++) { for (int j = 0; j < convertMat.cols*convertMat.rows; j++) { convertMat.matData[i][j] = 256.0; } } cv::Mat darkChannelFilteredcvMat=cv::Mat(imageMat.rows, imageMat.cols, CV_64FC1); ImageMat convertDarkChannelMat = darkChannelMat * convertMat; MKLConverter::toCVMat(convertDarkChannelMat).copyTo(darkChannelFilteredcvMat); ImageMat darkChannelFilteredMat = this->guidedFilter.apply(darkChannelFilteredcvMat)/convertMat/convertMat; double max_val=0, min_val=0; for (int i = 0; i < darkChannelFilteredMat.cols*darkChannelFilteredMat.rows; i++) { if (darkChannelFilteredMat.matData[0][i] > max_val) { max_val = darkChannelFilteredMat.matData[0][i]; } if (darkChannelFilteredMat.matData[0][i] < min_val) { min_val = darkChannelFilteredMat.matData[0][i]; } } std::vector<double> rangeOfHistogram; for (int i = 0; i <= this->bins; i++) { rangeOfHistogram.push_back(min_val + i * (max_val - min_val) / this->bins ); } std::vector<int>countOfHistogram(this->bins,0); for (int i = 0; i < darkChannelFilteredMat.rows*darkChannelFilteredMat.cols; i++) { //std::cout<< ((darkChannelFilteredMat.matData[0][i]-min_val)/(max_val-min_val)*(this->bins-1)) <<std::endl; countOfHistogram[round((darkChannelFilteredMat.matData[0][i] - min_val) / (max_val - min_val)*(this->bins - 1))] += 1; } int count = 0; int levelMax = 0; for (int i = this->bins - 1; i >= 0; i--) { count += countOfHistogram[i]; if (count >= std::round(darkChannelFilteredMat.cols*darkChannelFilteredMat.rows*(1 - 0.999))) { levelMax = i; break; } } ImageMat convertMat_1(imageMat); for (int i = 0; i <= imageMat.dims; i++) { for (int j = 0; j < convertMat_1.cols*convertMat_1.rows; j++) { convertMat_1.matData[i][j] = 256.0; } } cv::Mat splitedMatrix[3]; ImageMat temp(convertMat_1); temp=temp* imageMat; cv::split(MKLConverter::toCVMat(temp), splitedMatrix); ImageMat channelBMat = MKLConverter::fromCVMat(splitedMatrix[0]); ImageMat channelGMat = MKLConverter::fromCVMat(splitedMatrix[1]); ImageMat channelRMat = MKLConverter::fromCVMat(splitedMatrix[2]); ImageMat meanMat = channelBMat + channelGMat + channelRMat; double max = 0; for (int i = 0; i < darkChannelFilteredMat.rows*darkChannelFilteredMat.cols; i++) { //std::cout << i; //std::cout << darkChannelFilteredMat.matData[0][i] * this->w<<std::endl; if (darkChannelFilteredMat.matData[0][i] >= rangeOfHistogram[levelMax]) { if (meanMat.matData[0][i]>max) { max = meanMat.matData[0][i]; } } if ((darkChannelFilteredMat.matData[0][i] *this->w)>this->maxV ) { darkChannelFilteredMat.matData[0][i] = this->maxV; } } max /= 3.0*256; static AtmosphericMask atmosphericMask; atmosphericMask.maskMat = darkChannelFilteredMat; atmosphericMask.A = max; return atmosphericMask; } AtmosphericMaskCalculator::~AtmosphericMaskCalculator() { }