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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26c401a49d61120bd574708fb859ecae70389c82
|
65fbebdbb29f5cb9fcd455c52441c7d7291c0178
|
/2014.2/source/rotationanimation.h
|
7a86abfe4b14a664c421a32784d9250aa1303e4c
|
[
"CC0-1.0"
] |
permissive
|
DataBeaver/skrolli_gl
|
4cbdb62a646a6b7bb199c2837674bf4eee2c8a44
|
e95bb33d15fc2255804dd3714d73bdef60b67241
|
refs/heads/master
| 2020-06-05T07:43:46.074184
| 2014-10-29T11:15:12
| 2014-10-29T11:15:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 808
|
h
|
rotationanimation.h
|
#ifndef SKROLLIGL_ROTATIONANIMATION_H_
#define SKROLLIGL_ROTATIONANIMATION_H_
#include "animation.h"
namespace SkrolliGL {
/*
Animates an Instance by rotating it around an axis.
*/
class RotationAnimation: public Animation
{
private:
Matrix base_translation;
Matrix base_rotation;
char axis;
float angle;
public:
/* Constructs a fixed-duration RotationAnimation with a total rotation
angle. Axis must be one of 'X', 'Y', 'Z'. */
RotationAnimation(Instance &, char axis, float angle, float duration, EasingType = CUBIC);
/* Constructs a continuous RotationAnimation with a rotation rate. Axis
must be one of 'X', 'Y', 'Z'. */
RotationAnimation(Instance &, char axis, float rate);
private:
void init(char, float);
virtual Matrix compute_matrix(float);
};
} // namespace SkrolliGL
#endif
|
3056c335d9b747473a76d1d390cb752766716e71
|
a243534aa5ab5490b94087fa5ad5513503db4a53
|
/Platformer 1/LevelManager.cpp
|
e3b3969096132881e632c096f4c902056ffa2c2d
|
[] |
no_license
|
Lijmer/platformer_1
|
1ecdd0cb67c2432148c042bb25bdb2913cbeeddc
|
bde7287e253316b1080f571ef341fc135228dc1a
|
refs/heads/master
| 2020-05-17T01:22:41.154110
| 2013-07-03T10:16:06
| 2013-07-03T10:16:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,318
|
cpp
|
LevelManager.cpp
|
#pragma region Includes
#include "LevelManager.h"
#include <allegro5/allegro_native_dialog.h>
#include "GameObjectManager.h"
#include "FileManager.h"
#include "DisplayManager.h"
#include "ImageManager.h"
#include "SoundManager.h"
#include "Background.h"
#include <iostream>
#include <sstream>
#pragma endregion
//Public
LevelManager::LevelManager(void)
{
currentLevel=-1;
saveNum=-1;
}
LevelManager::~LevelManager(void)
{
}
void LevelManager::Init(void)
{
currentLevel=LVL_MENU;
saveNum=0;
LoadLevel(currentLevel);
}
void LevelManager::Save()
{
FileManager::GetInstance().Save(saveNum);
}
void LevelManager::NextLevel()
{
if(++currentLevel>=LVL_SIZE)
{
std::stringstream ss;
ss << "There is no level " << currentLevel;
al_show_native_message_box(DisplayManager::GetInstance().GetDisplay(),
"Error!", "LevelManager", ss.str().c_str(), "Ok", ALLEGRO_MESSAGEBOX_ERROR);
currentLevel=LVL_SIZE-1;
return;
}
LoadLevel(currentLevel);
}
void LevelManager::PreviousLevel()
{
if(--currentLevel<LVL_MENU)
{
std::stringstream ss;
ss << "There is no level " << currentLevel;
al_show_native_message_box(DisplayManager::GetInstance().GetDisplay(),
"Error!", "LevelManager", ss.str().c_str(), "Ok", ALLEGRO_MESSAGEBOX_ERROR);
currentLevel=LVL_MENU;
return;
}
LoadLevel(currentLevel);
}
void LevelManager::RestartLevel()
{
OverrideCamChanged(true);
ReloadLevel();
}
void LevelManager::ChangeLevel(int level)
{
if(level<LVL_MENU || level>=LVL_SIZE)
{
std::stringstream ss;
ss << "There is no level " << level;
al_show_native_message_box(DisplayManager::GetInstance().GetDisplay(),
"Error!", "LevelManager", ss.str().c_str(), "Ok", ALLEGRO_MESSAGEBOX_ERROR);
return;
}
if(currentLevel==level)
{
GameObjectManager::GetInstance().DeleteParticles();
ReloadLevel();
}
else
{
currentLevel=level;
LoadLevel(currentLevel);
}
}
//Private
inline void LevelManager::LoadLevel(int level)
{
LoadImages(level);
LoadSounds(level);
SoundManager::GetInstance().PlayMusic(FileManager::GetInstance().LoadMusicNum(level), true);
Background::GetInstance().LoadBackgroundFromLevel(level);
GameObjectManager::GetInstance().DeleteAllObjects();
FileManager::GetInstance().LoadStaticObjects(level);
FileManager::GetInstance().LoadDynamicObjects(level);
FileManager::GetInstance().LoadMainMenu(level);
}
inline void LevelManager::ReloadLevel()
{
GameObjectManager::GetInstance().DeleteDynamicObjects();
FileManager::GetInstance().LoadDynamicObjects(currentLevel);
if(currentLevel!=LVL_MENU)
FileManager::GetInstance().Load(saveNum);
}
inline void LevelManager::LoadImages(int level)
{
ImageManager::GetInstance().LoadImages(level);
}
inline void LevelManager::LoadSounds(int level)
{
SoundManager::GetInstance().LoadSounds(level);
}
inline void LevelManager::LoadMusic(int level)
{
SoundManager::GetInstance().LoadMusic(level);
}
inline void LevelManager::DeleteDynamicObjects()
{
GameObjectManager::GetInstance().DeleteDynamicObjects();
}
inline void LevelManager::DeleteStaticObjects()
{
GameObjectManager::GetInstance().DeleteStaticObjects();
}
inline void LevelManager::DeleteParticles()
{
GameObjectManager::GetInstance().DeleteParticles();
}
inline void LevelManager::DeleteAllObjects()
{
DeleteDynamicObjects();
DeleteStaticObjects();
DeleteParticles();
}
|
e7bfd0e7d929850353466bfe4b4ac9246dd6c298
|
bef56ea19df6f3e540c101b8517a2114675b804a
|
/APIGame_base/ColliderOfMapSC.h
|
2497e87f2324906d5c2d9e7c4360bdbf1e89d47f
|
[] |
no_license
|
kwt1326/2DProject
|
2b0b829dd7331ca4ad3aa87e5c529fe157e23fb3
|
940f0721ac5e4e216ef9b763ac888260aad34fb0
|
refs/heads/master
| 2022-01-27T23:41:33.703150
| 2022-01-17T00:31:28
| 2022-01-17T00:31:28
| 149,836,434
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 326
|
h
|
ColliderOfMapSC.h
|
#ifndef _COLLIDEROFMAPSC_H_
#define _COLLIDEROFMAPSC_H_
#include "Component.h"
#include "Vector2.h"
#include "Transform.h"
class ColliderOfMapSC : public Component
{
public:
ColliderOfMapSC();
~ColliderOfMapSC();
public:
virtual void Update(float dt);
virtual void Init();
virtual void Release();
public:
};
#endif
|
be6a325fb1abe5404f27f1edb54cc46494d664b7
|
9aa174f735d3450a8c8f653c07731a6d498f89f0
|
/source/itk/vs-convert.cxx
|
3d1c249f1c7b73082becab9ed7e5d265e0f4ae60
|
[] |
no_license
|
cha63506/rdi-reader
|
b5b69f3b17113297f4d37bb67e0bf25b099fb6fc
|
62e0113feaaf3a929fb752a9f4fd288df3d8a365
|
refs/heads/master
| 2017-12-03T18:14:16.215159
| 2015-07-20T02:51:04
| 2015-07-20T02:51:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,644
|
cxx
|
vs-convert.cxx
|
/**
* @file vs-convert.cpp
* @brief command line converter
* @date 2009-07-23
*/
#include <exception>
#include <fstream>
#include <memory>
using namespace std;
#include "itkArchetypeSeriesFileNames.h"
#include "itkExtractImageFilter.h"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageIOBase.h"
#include "itkImageIOFactory.h"
#include "metaCommand.h"
#include "itkVisualSonicsImageIO.h"
#include "itkVisualSonicsImageIOFactory.h"
#include "itkVisualSonicsSeriesReader.h"
/**
* @brief hold the results of command line argument parsing.
*/
struct Args
{
string in_file;
string out_file;
int frame_num;
double start_of_aquisition_speed_of_sound;
double acquisition_speed_of_sound;
double speed_of_sound;
Args():
frame_num(-1),
start_of_aquisition_speed_of_sound( -1. ),
acquisition_speed_of_sound( -1. ),
speed_of_sound( -1. )
{};
};
Args parse_args( int argc, char* argv[] );
int convert_frame( const Args& args );
int convert_all( const Args& args );
int main(int argc, char* argv[])
{
Args args = parse_args( argc, argv );
// An alternative to the below would be to
//
//typedef itk::VisualSonicsImageIO ImageIOType;
//ImageIOType::Pointer rfdio = ImageIOType::New();
//reader->SetImageIO( rfdio );
//
// There is also the plugin mechanism, see
// http://www.itk.org/Wiki/Plugin_IO_mechanisms
itk::VisualSonicsImageIOFactory::RegisterOneFactory();
try
{
if( args.frame_num > 0 )
{
return convert_frame( args );
}
else
{
return convert_all( args );
}
}
catch ( itk::ExceptionObject& e )
{
cerr << "Error: " << e << endl;
return EXIT_FAILURE;
}
catch (ifstream::failure& e)
{
cerr << "Error: failure opening/reading file." << endl;
return EXIT_FAILURE;
}
catch (std::exception& e)
{
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_FAILURE;
}
Args parse_args( int argc, char* argv[] )
{
Args args;
MetaCommand command;
command.AddField("in_file", "Input filepath.", MetaCommand::STRING, true);
command.SetOption("out_file", "o", false, "Output filepath.");
command.SetOptionLongTag("out_file", "output");
command.AddOptionField("out_file", "out_file", MetaCommand::STRING, true);
command.SetOption("frame_num", "f", false, "Requested frame number; if not specified, all frames are obtained. Counts from 1.");
command.SetOptionLongTag("frame_num", "frame");
command.AddOptionField("frame_num", "num", MetaCommand::INT, true);
command.SetOption( "start_of_aquisition_speed_of_sound", "s", false, "Set the assumed speed of sound from the start of the transducer face to the start of data aquisition. [m/s]" );
command.SetOptionLongTag( "start_of_aquisition_speed_of_sound", "soa-sos" );
command.AddOptionField( "start_of_aquisition_speed_of_sound", "start_of_aquisition_speed_of_sound", MetaCommand::FLOAT, true );
command.SetOption( "acquisition_speed_of_sound", "a", false, "Set the assumed speed of sound in the medium. [m/s]" );
command.SetOptionLongTag( "acquisition_speed_of_sound", "a-sos" );
command.AddOptionField( "acquisition_speed_of_sound", "acquisition_speed_of_sound", MetaCommand::FLOAT, true );
command.SetOption( "speed_of_sound", "c", false, "Set the assumed speed of sound. This sets the StartOfAquisitionSpeedOfSound and the AcquisitionSpeedOfSound." );
command.SetOptionLongTag( "speed_of_sound", "sos" );
command.AddOptionField( "speed_of_sound", "speed_of_sound", MetaCommand::FLOAT, true );
command.SetDescription("Read an VisualSonics Raw Data file and convert it into an ITK supported image format");
if( !command.Parse(argc, argv) )
{
throw logic_error( "Could not parse command line arguments." );
}
// -h
if( !command.GetOptionWasSet("in_file") )
throw runtime_error( "Input file was not specified." );
if(command.GetOptionWasSet("frame_num"))
args.frame_num = command.GetValueAsInt("frame_num", "num");
args.in_file = command.GetValueAsString("in_file");
//set output file name
if( !command.GetOptionWasSet("out_file") )
{
// truncate the in_file extension
std::string file_base = args.in_file;
size_t file_base_l = file_base.length();
if(file_base_l > 4)
{
if(!args.in_file.compare(file_base_l - 4, 1, "."))
file_base = file_base.substr(0, file_base_l - 4);
}
args.out_file = file_base + ".nrrd";
}
else
args.out_file = command.GetValueAsString("out_file", "out_file");
if( command.GetOptionWasSet( "start_of_aquisition_speed_of_sound" ) )
args.start_of_aquisition_speed_of_sound = command.GetValueAsFloat( "start_of_aquisition_speed_of_sound", "start_of_aquisition_speed_of_sound" );
if( command.GetOptionWasSet( "acquisition_speed_of_sound" ) )
args.acquisition_speed_of_sound = command.GetValueAsFloat( "acquisition_speed_of_sound", "acquisition_speed_of_sound" );
if( command.GetOptionWasSet( "speed_of_sound" ) )
args.speed_of_sound = command.GetValueAsFloat( "speed_of_sound", "speed_of_sound" );
return args;
}
int convert_frame( const Args& args )
{
typedef signed short PixelType;
typedef itk::Image< PixelType, 3 > InputImageType;
typedef itk::Image< PixelType, 2 > OutputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( args.in_file.c_str() );
writer->SetFileName( args.out_file.c_str() );
typedef itk::ExtractImageFilter< InputImageType, OutputImageType > ExtractFilterType;
ExtractFilterType::Pointer extractor = ExtractFilterType::New();
reader->UpdateOutputInformation();
InputImageType::RegionType in_region =
reader->GetOutput()->GetLargestPossibleRegion();
InputImageType::SizeType size = in_region.GetSize();
if( static_cast<int>( size[2] ) < args.frame_num - 1 ||
args.frame_num < 0 )
throw runtime_error("Requested frame number was greater than the frames available.");
size[2] = 0;
InputImageType::IndexType index = in_region.GetIndex();
index[2] = args.frame_num - 1;
InputImageType::RegionType desired_region;
desired_region.SetSize( size );
desired_region.SetIndex( index );
extractor->SetExtractionRegion( desired_region );
typedef itk::VisualSonicsSeriesReader< InputImageType > VisualSonicsReaderType;
VisualSonicsReaderType::Pointer vsReader = VisualSonicsReaderType::New();
if( vsReader->GetImageIO()->CanReadFile( args.in_file.c_str() ) )
{
typedef itk::ArchetypeSeriesFileNames NameGeneratorType;
NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();
nameGenerator->SetArchetype( args.in_file.c_str() );
vsReader->SetFileNames( nameGenerator->GetFileNames() );
itk::VisualSonicsImageIO * vs_image_io = dynamic_cast< itk::VisualSonicsImageIO * >( vsReader->GetImageIO() );
if ( args.speed_of_sound > 0. )
vs_image_io->SetSpeedOfSound( args.speed_of_sound );
if ( args.start_of_aquisition_speed_of_sound > 0. )
vs_image_io->SetStartOfAquisitionSpeedOfSound( args.start_of_aquisition_speed_of_sound );
if ( args.acquisition_speed_of_sound > 0. )
vs_image_io->SetAcquisitionSpeedOfSound( args.acquisition_speed_of_sound );
extractor->SetInput( vsReader->GetOutput() );
}
else
{
extractor->SetInput( reader->GetOutput() );
}
writer->SetInput( extractor->GetOutput() );
writer->Update();
return EXIT_SUCCESS;
}
int convert_all( const Args& args )
{
typedef signed short PixelType;
typedef itk::Image< PixelType, 3 > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( args.in_file.c_str() );
writer->SetFileName( args.out_file.c_str() );
typedef itk::VisualSonicsSeriesReader< ImageType > VisualSonicsReaderType;
VisualSonicsReaderType::Pointer vsReader = VisualSonicsReaderType::New();
bool isVisualSonicsFile = vsReader->GetImageIO()->CanReadFile( args.in_file.c_str() );
if( isVisualSonicsFile )
{
typedef itk::ArchetypeSeriesFileNames NameGeneratorType;
NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();
nameGenerator->SetArchetype( args.in_file.c_str() );
vsReader->SetFileNames( nameGenerator->GetFileNames() );
itk::VisualSonicsImageIO * vs_image_io = dynamic_cast< itk::VisualSonicsImageIO * >( vsReader->GetImageIO() );
if ( args.speed_of_sound > 0. )
vs_image_io->SetSpeedOfSound( args.speed_of_sound );
if ( args.start_of_aquisition_speed_of_sound > 0. )
vs_image_io->SetStartOfAquisitionSpeedOfSound( args.start_of_aquisition_speed_of_sound );
if ( args.acquisition_speed_of_sound > 0. )
vs_image_io->SetAcquisitionSpeedOfSound( args.acquisition_speed_of_sound );
writer->SetInput( vsReader->GetOutput() );
vsReader->UpdateOutputInformation();
writer->UseInputMetaDataDictionaryOff();
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( args.out_file.c_str(),
itk::ImageIOFactory::WriteMode );
imageIO->SetMetaDataDictionary( vsReader->GetImageIO()->GetMetaDataDictionary() );
writer->SetImageIO( imageIO );
}
else
{
writer->SetInput( reader->GetOutput() );
}
writer->Update();
return EXIT_SUCCESS;
}
|
72063178f1127629a052e94331e5f8a4c2319afa
|
101b8f5ec4936e2aa1cb06e6315df63bf0293e3a
|
/LTMT_Final_Round/DoiTien.cpp
|
04576f1a8179288cf4597b19aa0f8ea26daab145
|
[] |
no_license
|
VincentTr4n/Cpp
|
69075ef51e50499784c67b1f362eb1116e94a542
|
d9874accc67ba2cc807ecb14caa6b4af1124aad0
|
refs/heads/master
| 2020-03-12T13:19:21.781223
| 2019-09-16T15:58:04
| 2019-09-16T15:58:04
| 130,639,446
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 850
|
cpp
|
DoiTien.cpp
|
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <map>
#include <numeric>
#include <vector>
#define REP(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)
#define FORD(i,a,b) for(i=b;i>=a;i--)
#define ford(i,n) FORD(i,0,n-1)
#define sqr(x) ((x)*(x))
#define ll long long
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define vll vector<ll>
#define fi first
#define se second
#define all(a) a.begin(),a.end()
#define add push_back
#define len(arr) arr.size()
#define print(x) cout<<(x)<<endl
using namespace std;
int i,j;
int main() {
ll a[3],m,cnt=0;
ford(i,3) cin>>a[i];
cin>>m;
m*=2;
rep(i,3){
if(m/(3-i)>a[i]){
cnt+=a[i];
m-=a[i]*(3-i);
}else{
cnt+=m/(3-i);
m%=(3-i);
}
}
if(m==0) print(cnt);
else print("KHONG DOI DUOC");
return 0;
}
|
1d7982a51270d4e76e455baa98cd96f253bc4646
|
559a00d4367374b367d4999167743ec6d7387640
|
/algorithms/numbers/prime numbers/primality test/Chinese Primality Test/chinese_primality_test.cpp
|
83b12d6133de7bab191648e33f354ee54c40eb4f
|
[] |
no_license
|
michal367/Algorithms-and-Data-Structures
|
0cd0787393ebefaef19d5d1056b6d9de321e05d7
|
4aee40daac9c3292f3e5ac36010cf789354c26c7
|
refs/heads/master
| 2023-01-02T18:46:24.144935
| 2020-10-28T10:42:06
| 2020-10-28T10:42:06
| 307,850,924
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,243
|
cpp
|
chinese_primality_test.cpp
|
#include <iostream>
#include <cstdlib>
using namespace std;
typedef unsigned long long ulong;
ulong multiply_modulo(ulong a, ulong b, ulong n)
{
ulong sum = 0;
while(b != 0)
{
if(b & 1)
sum = (sum + a) % n;
a = (2*a) % n;
b = b >> 1;
}
return sum;
}
ulong power_modulo(ulong a, ulong e, ulong n)
{
ulong product = 1;
ulong mod = a%n;
if(e & 1)
product = (product * mod) % n;
e = e >> 1;
while(e != 0)
{
mod = multiply_modulo(mod,mod, n);
if(e & 1)
product = multiply_modulo(product,mod, n);
e = e >> 1;
}
return product;
}
int main()
{
cout << "Chinese Primality Test" << endl;
cout << "Checking if a natural number n is prime. (~99,998% correct)" << endl << endl;
ulong n;
cout << "n: ";
do{
cin >> n;
}while(n < 2);
cout << endl;
if(n == 2)
cout << "Number 2 is prime" << endl;
else
{
if(power_modulo(2, n, n) == 2)
cout << "Number " << n << " has ~99.998% chance to be prime" << endl;
else
cout << "Number " << n << " is NOT prime" << endl;
}
cout << endl;
system("pause");
return 0;
}
|
5cb24245abe4ce87bccf1990bd22d94069a644c9
|
417e7a2b5d53feef67b6464fbc18c40613b9c411
|
/src/main.cpp
|
0b7a2e114e25b3b95d4c6ecf6428c817df002a3f
|
[] |
no_license
|
rodolphoess/Laboratorio-01
|
6dbe0d14d335c2b0ed6ba65fbf55486fee54adf0
|
918d46952520161838647b4fd1b0e3d47918b88e
|
refs/heads/master
| 2020-05-22T06:31:00.414486
| 2017-04-02T20:45:00
| 2017-04-02T20:45:00
| 84,679,080
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 630
|
cpp
|
main.cpp
|
/**
* @file main.cpp
* @brief Programa que calcula a área e perímetro para figuras geométricas planas e a área e volume para figuras geométricas espaciais.
* @author Nicolas Ghirello e Rodolpho Erick.
* @since 09/03/2017
* @data 11/03/2017
*/
#include <iostream>
#include "menu.h"
using std::cin;
using std::cout;
using std::endl;
/**
* @brief Função principal.
* @details A função principal encaminha o usuário para a função menu que redirecionará para uma outra função onde haverá outras chamadas para cálculo de área,
* perímetro ou volume.
*/
int main(){
menu();
return 0;
}
|
12c98387baa1812221ffefd0a74463e05277e71b
|
4013c4b81a54d615067b2faa7e8ca278132b7fe5
|
/Quickhull.h
|
3ba38bfc0457832c9852b7093f9c9b5932e3c3f0
|
[] |
no_license
|
vuehrjer/Quickhull_Marius
|
fcdd40ec1b4701f2e6108f97cefc19cbaf88f3d5
|
1104e5b5fa66cfea1330d2b49a3806e47832c0e9
|
refs/heads/master
| 2020-09-23T00:28:50.152553
| 2019-12-02T18:00:37
| 2019-12-02T18:00:37
| 225,353,449
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 582
|
h
|
Quickhull.h
|
#pragma once
#include <vector>
#include "Point.h"
class Quickhull
{
public:
Quickhull(std::vector<Point> p, bool render);
std::vector<Point> findExtremes(std::vector<Point> p);
std::vector<std::vector<Point> >getAllHulls();
std::vector<Point> GetHull();
private:
std::vector<std::vector<Point> > allHulls;
void FindHull(std::vector<Point>& p, const Point& a, const Point& b, bool render);
std::vector<Point> convexHull;
float sign(Point p1, Point p2, Point p3);
float dist(Point p1, Point p2, Point p3);
bool pointInTriangle(Point pt, Point v1, Point v2, Point v3);
};
|
0e2159486520269d8c34455d539dc9921ae1b3f1
|
75d3b0272ce6e615d99d89faed5ee993305d35df
|
/第十二题_矩阵中的路径/solution.cpp
|
1e6d1fb648743159ff08014d57eb25f18b08a584
|
[] |
no_license
|
yukaizhou/CodeInterview
|
efa88a20352fc8abaeca1287d0a3ab820f1eed66
|
3397b607c28ecae07e9a98b6ab7da6d8c5c5f361
|
refs/heads/master
| 2021-10-25T00:48:31.670655
| 2019-03-30T23:54:40
| 2019-03-30T23:54:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,187
|
cpp
|
solution.cpp
|
class Solution {
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
for(int row = 0; row < rows; row++)
for(int col = 0; col < cols; col++)
if(found(matrix, row, col, str, rows, cols))
return true;
return false;
}
bool found(char* m, int row, int col, char *str, int rows, int cols)
{
if(row < 0 || row > rows)
return false;
if(col < 0 || col > cols)
return false;
if(*str != *(m + row * cols + col))
return false;
if(*str == '\0')
return true;
if(*(m + row * cols + col) == '\0')
return false;
bool result;
char temp = *(m + row * cols + col);
*(m + row * cols + col) = '\0';
result = found(m, row + 1, col, str + 1, rows, cols) ||
found(m, row - 1, col, str + 1, rows, cols) ||
found(m, row, col + 1, str + 1, rows, cols) ||
found(m, row, col - 1, str + 1, rows, cols);
*(m + row * cols + col) = temp;
return result;
}
};
|
d362709d23aadcb59195ca1391f7f57992da18a6
|
b04a481521d3fd679254035f4bf751a29a6393cd
|
/Coktel/chefcito.h
|
f8c3e69a833048d690defc6b848abbce99deee02
|
[] |
no_license
|
Igneel-san/cocktel
|
349242485e627a1bb5c45e86ac04b89ff6542546
|
44d6d6426815dc6fa2c94e9654982402844f859f
|
refs/heads/master
| 2021-05-19T00:20:47.197001
| 2020-03-31T03:45:05
| 2020-03-31T03:45:05
| 251,491,688
| 0
| 0
| null | 2020-03-31T03:45:06
| 2020-03-31T03:32:12
|
C++
|
UTF-8
|
C++
| false
| false
| 208
|
h
|
chefcito.h
|
#pragma once
/*
* Chefcito.h
*
* Created on: Mar 23, 2020
* Author: curso
*/
#ifndef CHEFCITO_H_
#define CHEFCITO_H_
class Chefcito {
public:
Chefcito();
virtual ~Chefcito();
};
#endif /* CHEFCITO_H_ */
|
edd50ba9fd4cd06bd5c907bc7080cd70f912a2ed
|
94cd871620957138dbdbe5a0c5416f0e9757a4ff
|
/parser/ast/antlr_tree_walker.cpp
|
302c22e5ba33ffb7d783315dadc30fb14408366f
|
[
"Apache-2.0"
] |
permissive
|
perbone/luascript
|
39cb96372986561894cc154fefd2eedbdd01ed80
|
bc156cd60959060323d1f70578e38aa9813588d1
|
refs/heads/master
| 2023-07-20T01:10:22.984438
| 2023-07-11T00:30:07
| 2023-07-11T00:30:07
| 101,610,955
| 559
| 52
|
Apache-2.0
| 2022-10-11T02:43:56
| 2017-08-28T06:27:19
|
C++
|
UTF-8
|
C++
| false
| false
| 1,964
|
cpp
|
antlr_tree_walker.cpp
|
/*
* This file is part of LuaScript
* https://github.com/perbone/luascrip/
*
* Copyright 2017-2023 Paulo Perbone
*
* 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 "antlr_tree_walker.h"
#include "../generated/LuaLexer.h"
#include <vector>
namespace parser::ast {
AntlrTreeWalker::AntlrTreeWalker() {}
AntlrTreeWalker::~AntlrTreeWalker() {}
AST AntlrTreeWalker::walk(const std::string_view chunk) {
antlr4::ANTLRInputStream input(chunk);
generated::LuaLexer lexer(&input);
antlr4::CommonTokenStream tokens(&lexer);
generated::LuaParser parser(&tokens);
// We instantiate a new collection of methods each time we walk the tree
// so we can move it to the returned AST at the end of the parser.
// The fact that this collection is a data member is just for easy access
// from within the listener functions.
this->methods = Methods{};
antlr4::tree::ParseTree *chunk_tree = parser.chunk();
antlr4::tree::ParseTreeWalker::DEFAULT.walk(this, chunk_tree);
parser.reset();
return std::make_unique<AbstractSyntaxTree>(std::move(this->methods), true);
}
void AntlrTreeWalker::exitStatFunction(generated::LuaParser::StatFunctionContext *ctx) {
std::vector<antlr4::tree::TerminalNode *> names = ctx->funcname()->NAME();
auto token = names[ctx->funcname()->NAME().size() - 1]->getSymbol();
this->methods.push_back(Method{ token->getText(), token->getLine(), token->getCharPositionInLine() + 1 });
}
} // namespace parser::ast
|
8bedc1333e75733b75c833301a792aaa6baf05c7
|
8c89782663a343f7c3d362573620f79d275a6142
|
/src/2000/2581.cpp14.cpp
|
4d9c5cf342210c2c0ba5c95adcf096a8fbe836ed
|
[
"MIT"
] |
permissive
|
upple/BOJ
|
14a8c8e372131b9a50ba7c1e7428ba7e57b4702d
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
refs/heads/master
| 2021-06-21T07:17:57.974279
| 2019-06-28T17:56:30
| 2019-06-28T17:56:30
| 128,779,781
| 13
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 449
|
cpp
|
2581.cpp14.cpp
|
#include<cstdio>
#include<vector>
#include<cmath>
#define INF 1010101010
#define min(x, y) (x<y?x:y)
using namespace std;
int main()
{
int a, b, m=INF, ans=0;
vector<int> prime;
scanf("%d %d", &a, &b);
if (a < 2)
a = 2;
for (int i = a; i <= b; i++)
{
int j;
for (j = 2; j <= sqrt(i); j++)
if (!(i%j))
break;
if(j>sqrt(i))
m = min(m, i), ans += i;
}
if (m == INF)
printf("-1");
else
printf("%d\n%d\n", ans, m);
}
|
6fa035c081c19142608bb3c6de10c66261f2e366
|
2c37015795f9d3a731998602e763788d2a2086f6
|
/Tigger/Resources.h
|
2c6ecc94c307c7c815b5eeaa470097c8e959c7d0
|
[] |
no_license
|
ApostaC/MiniC
|
8e4ac32ad47826394226a0083249138e2825dce3
|
0d950b331d510e624406af4364bf5456b906176c
|
refs/heads/master
| 2020-04-14T01:33:38.866294
| 2018-12-31T07:44:48
| 2018-12-31T07:44:48
| 163,563,025
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,289
|
h
|
Resources.h
|
#ifndef _RESOURCE_HH_
#define _RESOURCE_HH_
#include <string>
#include <vector>
#include <set>
#include <map>
namespace res
{
class RightVariable; /* imm-value or eeyore-var */
class ImmediateVal; /* imm-value */
class EeyoreVariable; /* eeyore-var */
class VarPool; /* Pool for eeyore-var */
//class Register; /* Tigger reg */
using Register = std::string;
class TiggerVariable; /* Tigger glb var */
class GlobalVarMgr;
//class ResourceManager; /* resource mgr */
//class GlobalManager; /* res mgr for glb tigger var */
//class FunctionManager; /* res mgr for local vars */
extern VarPool GlobalPool;
extern GlobalVarMgr globalVars;
extern std::map<int, Register> globalRegs;
using VarList = std::set<res::EeyoreVariable>;
using Liveness = std::map<int, VarList>;
using RegID = int;
class RightVariable
{
private:
public:
/* NOTHING HERE ? */
virtual std::string getName() const = 0;
virtual bool operator<(const RightVariable &r) const
{
return this->getName() < r.getName();
}
public:
static RightVariable *GenRvar(const std::string &n);
};
class EeyoreVariable : public RightVariable
{
private:
std::string name;
EeyoreVariable(const std::string &n) : name(n){}
bool isarr = false;
public:
virtual std::string getName()const override {return name;}
static EeyoreVariable *GenRvar(const std::string &n);
void setArray(){isarr = true;}
bool isArray(){return isarr;}
friend class VarPool;
};
class ImmediateVal : public RightVariable
{
private:
int value;
public:
ImmediateVal(int va){ value = va; }
virtual std::string getName()const override {return std::to_string(value); }
int getval(){return value;}
};
using RVariable = RightVariable;
/* all var in the pool are EeyoreVar, NO imm-val */
class VarPool
{
private:
std::map<std::string, res::EeyoreVariable*> pool;
public:
void InsertNewVar(res::EeyoreVariable *var)
{
pool[var->getName()] = var;
}
/**
* GetVar(varname)
* if var doesn't exist, create one in the pool and return it
*/
res::EeyoreVariable *GetVar(const std::string &vname)
{
if(!pool.count(vname))
InsertNewVar(new res::EeyoreVariable(vname));
return pool[vname];
}
};
class TiggerVariable /* global variable for tigger */
{
private:
std::string name;
size_t size;
bool isArr;
public:
TiggerVariable(const std::string &n, size_t s, bool isa)
: name(n), size(s), isArr(isa) {}
std::string getName()const {return name;}
size_t getSize()const {return size;}
bool isArray(){return isArr;}
};
class GlobalVarMgr
{
/* GlobalVarmgr got a special register: t6 */
private:
std::map<std::string, res::TiggerVariable*> pool;
int varcnt = 0;
private:
std::string _genname()
{
return "v" + std::to_string(varcnt);
}
public:
bool isGlobalVar(res::EeyoreVariable *var);
/**
* return the tigger global var name of a eeyore var
*/
std::string GetVarName(res::EeyoreVariable *var);
/* ABI FOR GLB VAR/ARR DEFINITION */
void AllocGlobalVar(FILE *f,res::EeyoreVariable *var, int initval = 0);
void AllocGlobalArr(FILE *f,res::EeyoreVariable *var, int size);
/**
* if var is variable, reg have it's value
* if var is array, reg have it's address
*/
void gencode_loadvar(FILE *f, res::EeyoreVariable *var, const std::string ®name);
void gencode_storevar(FILE *f, res::EeyoreVariable *var, int offreg, int valreg);
/**
* return the number of global variables
*/
size_t getGlobalVarcnt() {return pool.size();}
std::vector<res::TiggerVariable*> AllTVars();
std::vector<res::EeyoreVariable*> AllEVars();
};
//class ResourceManager
//{
// /* TODO: resource management */
// protected:
// enum Position_t {STK = 0, REG = 1} ;
// using Offset_t = int;
// using Position = std::map<Position_t, Offset_t>;
// using Var = EeyoreVariable;
// using VarPositionTable = std::map<Var, Position>;
// protected:
// ResourceManager *parent; // for finding global variables
// VarPositionTable vpt;
// FILE *f;
//
// public:
// ResourceManager(ResourceManager *p) : parent(p){f = stdout;}
// virtual std::string Load(Var *v) = 0;
// virtual std::string Lea(Var *v) = 0;
// virtual void Store(Var *v) = 0;
// virtual void ToFile(FILE *ff){f=ff;};
//};
//
//class GlobalManager : public ResourceManager
//{
// /* TODO: resource management for global variables */
// /* NO REG HERE! */
// protected:
// int glbvarcnt = 0;
// std::map<Var, TiggerVariable> glbmap;
// public:
// GlobalManager() : ResourceManager(NULL)
// {
// glbvarcnt = 0;
// }
// virtual std::string Load(Var *v) override;
// virtual std::string Lea(Var *v) override;
// virtual void Store(Var *v) override;
// virtual void AllocateArr(Var *v, size_t size); // allocate for global array
// virtual void AllocateVar(Var *v, size_t size, int initval = 0); // allocate for global var
//};
//
//class FunctionManager : public ResourceManager
//{
// /* TODO: resource management for local variables and registers */
// /* TODO: manage a0-a7 when use "setparam" */
// /* TODO: calculate the stack size */
// /* stack structure:
// * | params | data |
// */
// protected:
// size_t stksize;
// size_t stkoff;
//
// public:
// FunctionManager(ResourceManager *parent)
// : ResourceManager(parent)
// {
// }
// void StoreParams();
// virtual std::string Load(Var *v) override;
// virtual std::string Lea(Var *v) override;
// virtual void Store(Var *v) override;
//};
} //namespace res
#endif
|
53fbfd239dec15de381a2cbdcff5c8b08667133f
|
3bbc63175bbff8163b5f6b6af94a4499db10a581
|
/MyPCHunter/bk/MyTaskmgr/MyCMDDlg.cpp
|
d8c8cdbf9a4dc5a83b0054151649e43b48409d2d
|
[] |
no_license
|
chancelee/MyProject
|
76f8eb642544a969efbb10fa4e468daeba5b88ef
|
62f5825b244f36ed50f6c88868e13670e37281d5
|
refs/heads/master
| 2021-09-16T01:31:00.158096
| 2018-06-14T10:08:42
| 2018-06-14T10:08:42
| null | 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 7,194
|
cpp
|
MyCMDDlg.cpp
|
// MyCMDDlg.cpp : implementation file
//
#include "stdafx.h"
#include "MyTaskmgr.h"
#include "MyCMDDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMyCMDDlg dialog
CMyCMDDlg::CMyCMDDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMyCMDDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CMyCMDDlg)
m_csEnter = _T("");
m_csShowCmd = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
hCmdReadPipe = NULL;
hCmdWritePipe = NULL;
hMyReadPipe = NULL;
hMyWritePipe = NULL;
memset(&m_pi, 0, sizeof(PROCESS_INFORMATION));
}
void CMyCMDDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CMyCMDDlg)
DDX_Text(pDX, EDT_ENTER, m_csEnter);
DDX_Text(pDX, EDT_CMDSHOW, m_csShowCmd);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CMyCMDDlg, CDialog)
//{{AFX_MSG_MAP(CMyCMDDlg)
ON_WM_DESTROY()
ON_BN_CLICKED(BTN_RUN, OnRun)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMyCMDDlg message handlers
BOOL CMyCMDDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
//ÉèÖÃsa
SECURITY_ATTRIBUTES sa;
memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
//create pipe
BOOL bRet = FALSE;
// hMyWritePipe <-> hCmdReadPipe
//
// hMyReadPipe <-> hCmdWritePipe
//
bRet = CreatePipe(&hMyReadPipe, &hCmdWritePipe, &sa, 0);
bRet = CreatePipe(&hCmdReadPipe, &hMyWritePipe, &sa, 0);
//startup cmd
STARTUPINFO si;
memset(&si, 0, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = hCmdReadPipe;
si.hStdOutput = hCmdWritePipe;
si.hStdError = hCmdWritePipe;
char szBuf[MAXBYTE] = {0};
GetSystemDirectory(szBuf, MAXBYTE);
strcat(szBuf, "\\cmd.exe");
bRet = CreateProcess(NULL,
szBuf,
NULL,
NULL,
TRUE,
CREATE_NO_WINDOW,
NULL,
NULL,
&si,
&m_pi);
if (bRet == FALSE)
{
AfxMessageBox("CreateProcess bRet == FALSE");
return FALSE;
}
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
void CMyCMDDlg::OnDestroy()
{
CDialog::OnDestroy();
// TODO: Add your message handler code here
//close cmd
DWORD dwWritedBytes = 0;
BOOL bRet = FALSE;
bRet = WriteFile(hMyWritePipe,
"exit\r\n",
strlen("exit\r\n"),
&dwWritedBytes,
NULL
);
if (hCmdReadPipe != NULL)
{
CloseHandle(hCmdReadPipe);
}
if (hCmdWritePipe != NULL)
{
CloseHandle(hCmdWritePipe);
}
if (hMyReadPipe != NULL)
{
CloseHandle(hMyReadPipe);
}
if (hMyWritePipe != NULL)
{
CloseHandle(hMyWritePipe);
}
}
DWORD WINAPI GetCMDWritePipe(LPVOID lpParameter)
{
ASSERT(lpParameter);
PTHREADPARAM pParam = (PTHREADPARAM)lpParameter;
HANDLE hMyReadPipe = pParam->m_hPipe;
char *pszBuf = NULL;
DWORD dwTotalBytesAvail = 0;
DWORD dwReadedBytes = 0;
BOOL bRet = FALSE;
DWORD dwZeroFlag = 0;
while (TRUE)
{
bRet = PeekNamedPipe(hMyReadPipe,
NULL,
0,
NULL,
&dwTotalBytesAvail,
NULL);
if (bRet == FALSE)
{
AfxMessageBox("PeekNamedPipe bRet == FALSE");
return 0;
}
if (dwTotalBytesAvail == 0 && dwZeroFlag != 0)
{
break;
}
if (dwTotalBytesAvail == 0 && dwZeroFlag == 0)
{
dwZeroFlag++;
Sleep(200);
continue;
}
char *pszBuf = new char[dwTotalBytesAvail];
if (pszBuf == NULL)
{
AfxMessageBox("new char[dwTotalBytesAvail] pszBuf == NULL");
return 0;
}
memset(pszBuf, 0, dwTotalBytesAvail);
bRet = ReadFile(hMyReadPipe,
pszBuf,
dwTotalBytesAvail,
&dwReadedBytes,
NULL);
if (bRet == FALSE)
{
AfxMessageBox("ReadFile bRet == FALSE");
return 0;
}
if (dwTotalBytesAvail != 0)
{
*(pParam->m_pcsStr) += pszBuf;
}
if (pszBuf != NULL)
{
delete pszBuf;
pszBuf = NULL;
}
}
return 0;
}
void CMyCMDDlg::OnRun()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_csEnter += "\r\n";
m_csShowCmd = "";
BOOL bRet = FALSE;
DWORD dwReadedBytes = 0;
DWORD dwWritedBytes = 0;
bRet = WriteFile(hMyWritePipe,
m_csEnter.GetBuffer(0),
m_csEnter.GetLength(),
&dwWritedBytes,
NULL
);
//create thread run command line
DWORD dwTid = 0;
PTHREADPARAM pThParam = NULL;
pThParam = new THREADPARAM;
if (pThParam == NULL)
{
AfxMessageBox("pThParam == NULL");
return;
}
memset(pThParam, 0, sizeof(THREADPARAM));
pThParam->m_hPipe = hMyReadPipe;
pThParam->m_pcsStr = &m_csShowCmd;
HANDLE hThread = NULL;
hThread = CreateThread(NULL, 0, GetCMDWritePipe, (LPVOID)pThParam, 0, &dwTid);
if (hThread == NULL)
{
AfxMessageBox("hThread == NULL");
return;
}
WaitForSingleObject(hThread, INFINITE);
UpdateData(FALSE);
if (pThParam != NULL)
{
delete pThParam;
pThParam = NULL;
}
if (hThread != NULL)
{
CloseHandle(hThread);
}
}
|
82189790d60fa05bb4c053b2bd2868762c1f0230
|
0b872963054916ea22c4155b704d66ca56ea42ef
|
/shadow/operators/shuffle_channel_op.hpp
|
d12243e258cba5dcb7d3260265e11f42f1036c45
|
[
"Apache-2.0"
] |
permissive
|
Arui1/shadow
|
2be651e4e1010e5184d4e20cc94a759c505849d4
|
af0c8c6c350bb11a3f4eeec9fd8affe9439ddc00
|
refs/heads/master
| 2022-04-12T23:51:09.184471
| 2020-03-27T03:13:20
| 2020-03-27T03:13:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 753
|
hpp
|
shuffle_channel_op.hpp
|
#ifndef SHADOW_OPERATORS_SHUFFLE_CHANNEL_OP_HPP
#define SHADOW_OPERATORS_SHUFFLE_CHANNEL_OP_HPP
#include "core/operator.hpp"
namespace Shadow {
class ShuffleChannelOp : public Operator {
public:
ShuffleChannelOp(const shadow::OpParam &op_param, Workspace *ws)
: Operator(op_param, ws) {
group_ = get_single_argument<int>("group", 0);
CHECK_GT(group_, 0) << "group must be larger than 0";
}
void Forward() override;
private:
int group_;
};
namespace Vision {
template <typename T>
void ShuffleChannel(const T *in_data, int batch, int channel, int spatial_dim,
int group, T *out_data, Context *context);
} // namespace Vision
} // namespace Shadow
#endif // SHADOW_OPERATORS_SHUFFLE_CHANNEL_OP_HPP
|
407947904be460708dc00a3486f7ce4dd6011af0
|
35e4fc20590772d39caf36d9eb84aa697a4292aa
|
/gr-capture_tools/lib/annotated_to_msg_f_impl.cc
|
da43ef7c8f2c45e08259f2a3f473f6b9b69b6e7c
|
[] |
no_license
|
rubund/capture-tools
|
f991bc0906a28d119e5f28e43e5df8e2c1ca55f3
|
6e9ba6faebf1e99afb159ef7ee7bcbd3910f2aaf
|
refs/heads/master
| 2022-07-28T16:42:30.429650
| 2022-03-31T12:43:01
| 2022-03-31T12:43:01
| 62,948,019
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,798
|
cc
|
annotated_to_msg_f_impl.cc
|
/* -*- c++ -*- */
/*
* Copyright 2017 <+YOU OR YOUR COMPANY+>.
*
* This 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, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gnuradio/io_signature.h>
#include "annotated_to_msg_f_impl.h"
namespace gr {
namespace capture_tools {
annotated_to_msg_f::sptr
annotated_to_msg_f::make()
{
return gnuradio::get_initial_sptr
(new annotated_to_msg_f_impl());
}
/*
* The private constructor
*/
annotated_to_msg_f_impl::annotated_to_msg_f_impl()
: gr::sync_block("annotated_to_msg_f",
gr::io_signature::make(2, 2, sizeof(float)),
gr::io_signature::make(0, 0, 0)),
d_input_buffer(0), d_sync_word(0), d_sync_word_mask(0),
d_sync_word_len(0), d_start_counter(0),
d_n_to_catch(0)
{
d_state = 0;
message_port_register_out(pmt::mp("packets"));
}
/*
* Our virtual destructor.
*/
annotated_to_msg_f_impl::~annotated_to_msg_f_impl()
{
}
void
annotated_to_msg_f_impl::set_sync_word(const std::vector<uint8_t> s)
{
d_sync_word = 0;
d_sync_word_mask = 0;
int swsize = s.size();
if (swsize > 32) {
throw std::runtime_error("Sync word can be max 32 bits long");
}
for(int i=0; i<swsize ;i++) {
d_sync_word = ((d_sync_word << 1) & 0xfffffffe) | (uint32_t)(s[i] & 0x01);
d_sync_word_mask |= (((uint32_t)1) << i);
}
d_sync_word_len = swsize;
printf("d_sync_word: 0x%08x, d_sync_word_mask: 0x%08x, d_sync_word_len: %d\n",d_sync_word, d_sync_word_mask, d_sync_word_len);
}
void
annotated_to_msg_f_impl::set_packet_length(int val)
{
d_n_to_catch = val;
}
int
annotated_to_msg_f_impl::work(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
std::vector<tag_t> tags;
int tagnum = -1;
int nextstrobe = -1;
const float *in = (const float *) input_items[0];
const float *in_th = (const float *) input_items[1];
uint8_t sliced;
int nstate;
get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0) + noutput_items);
for(int i=tagnum+1;i<tags.size();i++){
if (pmt::equal(tags[i].key, pmt::intern("strobe"))) {
nextstrobe = tags[i].offset - nitems_read(0);
tagnum = i;
break;
}
}
// Do <+signal processing+>
for(int i=0;i<noutput_items;i++) {
nstate = d_state;
//if (d_state == 0) {
// if (in_th[i] == 1) {
// d_state = 1;
// d_start_counter = 0;
// d_receive_buffer.clear();
// }
//}
//else if (d_state == 1) {
// if (in_th[i] == 0) {
// d_state = 0;
// pmt::pmt_t pdu_meta = pmt::make_dict();
// pmt::pmt_t pdu_vector = pmt::init_u8vector(d_receive_buffer.size(), d_receive_buffer);
// pdu_meta = pmt::dict_add(pdu_meta, pmt::mp("freq"), pmt::mp("0"));
// pmt::pmt_t out_msg = pmt::cons(pdu_meta, pdu_vector);
// message_port_pub(pmt::mp("packets"), out_msg);
// //printf("Received: ");
// //for(int j=0;j<d_receive_buffer.size();j++){
// // printf("%d", d_receive_buffer[j]);
// //}
// //printf("\n");
// }
//}
if((nextstrobe != -1) && (i == nextstrobe)) {
sliced = (in[i]) > 0.0 ? 1 : 0;
d_input_buffer = ((d_input_buffer << 1) & 0xfffffffe) | ((uint32_t)(sliced & 0x01));
if (d_state == 0) {
if(d_sync_word_len > 0 && d_start_counter >= d_sync_word_len && (d_input_buffer & d_sync_word_mask) == d_sync_word) {
//printf("Match. input_buffer: %08x\n", d_input_buffer);
nstate = 1;
d_packet_counter = 0;
d_receive_buffer.clear();
for(int i=0;i<d_sync_word_len;i++) {
d_receive_buffer.push_back((d_sync_word >> (d_sync_word_len-i-1)) & 0x1);
}
}
if(d_start_counter < 32)
d_start_counter++;
}
else if (d_state == 1) {
d_packet_counter ++;
if(d_packet_counter >= d_n_to_catch) {
//printf("Back to state 0\n");
nstate = 0;
pmt::pmt_t pdu_meta = pmt::make_dict();
pmt::pmt_t pdu_vector = pmt::init_u8vector(d_receive_buffer.size(), d_receive_buffer);
pdu_meta = pmt::dict_add(pdu_meta, pmt::mp("freq"), pmt::mp("0"));
pdu_meta = pmt::dict_add(pdu_meta, pmt::mp("magnitude"), pmt::mp("0"));
pdu_meta = pmt::dict_add(pdu_meta, pmt::mp("id"), pmt::mp("0"));
pmt::pmt_t out_msg = pmt::cons(pdu_meta, pdu_vector);
message_port_pub(pmt::mp("packets"), out_msg);
d_start_counter = 0;
}
}
if(d_state == 1) {
d_receive_buffer.push_back(sliced);
}
nextstrobe = -1;
for(int i=tagnum+1;i<tags.size();i++){
if (pmt::equal(tags[i].key, pmt::intern("strobe"))) {
nextstrobe = tags[i].offset - nitems_read(0);
tagnum = i;
break;
}
}
}
d_state = nstate;
}
// Tell runtime system how many output items we produced.
return noutput_items;
}
} /* namespace capture_tools */
} /* namespace gr */
|
7f0a1e5da88a8bd5351d47bd44a6629de756c09b
|
2e9dd6d2fa156cfc0edbdcc66979870f3a5aca14
|
/EdgeEffect.cxx
|
ffaa2c5c7dc570dd330b62fea1533595b397442b
|
[] |
no_license
|
awiles/DanceWall
|
025b31931a60cef8302e4af9c94432d824e5d714
|
87c7767a5d07edff27de3d1cc01dbe3259a56f32
|
refs/heads/master
| 2020-06-18T09:23:08.346542
| 2017-06-10T17:20:40
| 2017-06-10T17:20:40
| 75,146,970
| 0
| 0
| null | 2017-06-09T18:34:43
| 2016-11-30T03:21:32
|
C++
|
UTF-8
|
C++
| false
| false
| 1,060
|
cxx
|
EdgeEffect.cxx
|
#include "EdgeEffect.h"
EdgeEffect::EdgeEffect()
{
// constructor.
this->init();
}
void EdgeEffect::init()
{
this->m_blurKernelSize = 3;
this->m_cannyThreshold1 = 10;
this->m_cannyThreshold2 = 30;
this->m_cannyApertureSize = 3;
return;
}
void EdgeEffect::drawEffect()
{
if( this->m_lastFrame.empty() )
{
cout << "EdgeEffect Warning: Last frame is empty." << endl;
return;
}
//TODO: this->doBGSubtraction();
// convert to B&W
Mat bwFrame;
cvtColor(this->m_lastFrame, bwFrame, CV_BGR2GRAY);
// blur and call Canny.
blur(bwFrame, this->m_outFrame, Size(m_blurKernelSize,m_blurKernelSize));
Canny(this->m_outFrame, this->m_outFrame, m_cannyThreshold1, m_cannyThreshold2, m_cannyApertureSize);
return;
}
void EdgeEffect::togglePresets()
{
bool bColorMap = (this->m_bApplyColorMap)?false:true;
this->setColorMapApply(bColorMap);
}
void EdgeEffect::getRandomConfig(bool doGrid)
{
AbstractEffect::getRandomConfig(doGrid);
// if doing grid, always apply colormap.
if( this->m_gridOrder > 1 )
this->m_bApplyColorMap = true;
}
|
bf9aec72f03b95b5c5c659714fcbb7e55aa7d686
|
a4be3081b577829057680252a34abd5e79419a04
|
/TuringMachine.cpp
|
02beac24824450bf6f45abb7897a2daf58264c7f
|
[] |
no_license
|
minad/turing
|
4cfe077077f05b460298d8af30dc607c6346dc98
|
cbc8a46c8f223d0edc9e26618c26913817841b28
|
refs/heads/master
| 2023-08-22T18:13:43.861763
| 2017-03-06T20:58:40
| 2017-03-06T20:58:40
| 84,120,275
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,196
|
cpp
|
TuringMachine.cpp
|
#include "TuringMachine.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
const char TuringMachine::Tape::BLANK = '#';
TuringMachine::TuringMachine(const char *program)
: state("INIT"), halted(false)
{
readProgram(program);
}
TuringMachine::TuringMachine(const char *program, const char *tapeStr)
: tape(tapeStr), state("INIT"), halted(false)
{
readProgram(program);
}
void TuringMachine::nextTransition()
{
if (halted || state == "HALT")
{
halted = true;
return;
}
bool programError = true;
for (vector<Transition>::iterator i = transitions.begin();
i != transitions.end(); ++i)
{
//cout << i->state << ',' << i->symbol << ',' << state << ',' << tape.read() <<endl;
if (!strcmp(i->state, state))
{
if (i->symbol == tape.read())
{
state = i->newState;
tape.write(i->newSymbol);
tape.move(i->tapeDir);
return;
}
programError = false;
}
}
if (programError)
throw ProgramException();
else
throw BadTapeException();
}
void TuringMachine::print() const
{
tape.print();
cout << "\nState: " << state << endl;
}
void TuringMachine::readProgram(const char *programFile)
{
FILE *fp = fopen(programFile, "r");
if (!fp)
throw IOException();
while (!feof(fp))
{
char dir;
Transition t;
if (fscanf(fp, "%s %c %s %c %c", t.state, &t.symbol, t.newState, &t.newSymbol, &dir) == 0)
throw new ProgramFormatException();
switch (dir)
{
case 'L': t.tapeDir = Tape::LEFT; break;
case 'R': t.tapeDir = Tape::RIGHT; break;
case 'S': t.tapeDir = Tape::STOP; break;
}
transitions.push_back(t);
}
fclose(fp);
}
TuringMachine::Tape::Tape(const char *str)
: pos(0)
{
for (const char *p = str; *p != '\0'; ++p)
tape.push_back(*p);
if (tape.size() == 0)
tape.push_back('#');
}
void TuringMachine::Tape::move(int dir)
{
pos += dir;
if (pos >= (int)tape.size())
tape.push_back(BLANK);
else if (pos < 0)
{
tape.push_front(BLANK);
pos = 0;
}
}
void TuringMachine::Tape::print() const
{
//for (int i = pos - 40; i < pos + 40; ++i)
for(int i = 0; i < tape.size(); ++i)
{
//if (pos >= (int)tape.size() || pos < 0)
// cout << BLANK;
// else
if (i == pos) cout << "\033[0;40m\033[1;37m" << tape[i] << "\033[0m";
else cout << tape[i];
}
//cout << "\n ^";
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
cerr << "usage: turing <program-file> [tape]" << endl;
exit(EXIT_FAILURE);
}
try
{
TuringMachine machine(argv[1], argc >= 3 ? argv[2] : "");
while (!machine.isHalted())
{
//cout << "\033[H\033[J";
machine.print();
machine.nextTransition();
}
}
catch (const TuringMachine::Exception &e)
{
cerr << "Exception caught: " << e.type() << endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
|
d3ab6967e59f520d9a74ef98ca7db096f2adc0d0
|
a2d74f1929768f584593080f660285b9be34b74b
|
/week6/kwon/2017_02_14_BAEKJOON_11399.cpp
|
f9276e78cd9af4f68fc1c32953e9b3238c68ed00
|
[] |
no_license
|
eubnaraAlgorithmStudy/400617
|
c66091db2106de92dfeacdf10701032a2b888aa3
|
56aef7894e23d64e37efa7b789f3c0da47e98451
|
refs/heads/master
| 2021-01-13T12:17:20.544944
| 2018-02-25T04:35:02
| 2018-02-25T04:35:02
| 78,322,588
| 4
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 829
|
cpp
|
2017_02_14_BAEKJOON_11399.cpp
|
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int N;
int temp;
vector<int> input;
vector<int> result;
void ATM()
{
for (int i = 0; i < N; i++)
{
if (i == 0)
{
result[i] = input[i];
}
else
{
result[i] = result[i - 1] + input[i];
}
}
// 정렬, greedy algorithm에 의해, 앞에서 부터 가장 작은 것들을 더해가는 것이 최선이다.
}
int main(void)
{
// 선언
scanf("%d", &N);
input.resize(N);
result.resize(N);
//초기화
for (int i = 0; i < N; i++)
{
scanf("%d", &input[i]);
}
// 정렬, greedy algorithm에 의해, 앞에서 부터 가장 작은 것들을 더해가는 것이 최선이다.
sort(input.begin(), input.begin() + N);
ATM();
temp = 0;
for (int i = 0; i < N; i++)
{
temp += result[i];
}
printf("%d", temp);
return 0;
}
|
58063095ae22adb05e6fbfed7bad302f582252e9
|
917e551cb9cbc4a1222369e9e826ac4532400e25
|
/100-199/101/141D/c++.cpp
|
2e1acf224b1f651ad2a0c8d1f8ad6687c461d92b
|
[] |
no_license
|
mkut/cf
|
3463329a212b43e1f09a8a68c999793d78026da2
|
cc0876c2047fdabd154748025da3ecef12cfea64
|
refs/heads/master
| 2016-09-01T23:52:59.308588
| 2013-11-19T19:14:40
| 2013-11-19T19:16:17
| 2,326,614
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,155
|
cpp
|
c++.cpp
|
#include <milib/template/aoj>
#include <set>
#include <map>
#include <queue>
#include <vector>
struct state {
int cost;
int pos;
int prev;
int ramp;
state(int cost, int pos, int prev, int ramp) : cost(cost), pos(pos), prev(prev), ramp(ramp) {}
bool operator<(const state& b) const {
return cost > b.cost;
}
};
struct edge {
int next;
int cost;
int ramp;
edge(int next, int cost, int ramp) : next(next), cost(cost), ramp(ramp) {}
bool operator<(const edge& b) const {
if (next < b.next) return true;
if (next > b.next) return false;
if (cost < b.cost) return true;
if (cost > b.cost) return false;
if (ramp < b.ramp) return true;
if (ramp > b.ramp) return false;
return false;
}
};
int main() {
int n, L; cin >> n >> L;
map<int, vector<edge> > linked;
set<int> nodes;
nodes.insert(0); nodes.insert(L);
for (int i = 0; i < n; i++) {
int x, d, t, p; cin >> x >> d >> t >> p;
linked[x-p].push_back(edge(x+d, p+t, i+1));
nodes.insert(x-p);
nodes.insert(x+d);
}
vector<int> vnodes;
for (set<int>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
vnodes.push_back(*it);
}
for (int i = 1; i < vnodes.size(); i++) {
int x = vnodes[i-1];
int y = vnodes[i];
linked[x].push_back(edge(y, y - x, -1));
linked[y].push_back(edge(x, y - x, -1));
}
map<int,int> backs, ramps;
priority_queue<state> Q;
state init(0, 0, -1, -1);
Q.push(init);
while(!Q.empty()) {
state top = Q.top(); Q.pop();
int pos = top.pos;
int cost = top.cost;
int prev = top.prev;
int ramp = top.ramp;
if (pos < 0) {
continue;
}
if (backs.count(pos))
continue;
backs[pos] = prev;
ramps[pos] = ramp;
if (pos == L) {
cout << cost << endl;
break;
}
vector<edge>& edges = linked[pos];
for (int i = 0; i < edges.size(); i++) {
edge& e = edges[i];
Q.push(state(cost + e.cost, e.next, pos, e.ramp));
}
}
vector<int> ans;
int p = L;
while (p != 0) {
if (ramps[p] > 0)
ans.push_back(ramps[p]);
p = backs[p];
}
reverse(ans.begin(), ans.end());
cout << ans.size() << endl;
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
return 0;
}
|
cadc60a62ce7b7aca87417f29a28a895dd49f4c5
|
9b2d99b47ab7b29f71e90ba595b7247f5aa0b14a
|
/week10/poker_chips/main.cpp
|
24745d596771c304df1012aa7aa06e2723584362
|
[] |
no_license
|
hiddely/eth-algolab
|
19204345a99a960aa0d62aad87bc74471f9d6ccf
|
e6633f9c7128f8664c1cacd80783d09de80dabec
|
refs/heads/master
| 2021-10-12T01:09:42.414207
| 2019-01-31T11:41:16
| 2019-01-31T11:41:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,149
|
cpp
|
main.cpp
|
//
// Created by Hidde Lycklama on 1/6/19.
//
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
const bool VERBOSE = false;
struct DefaultMinusOne {
int val = -1;
};
//int combiFour[4][4] = {
// {
// 1, 1, 1, 1
// },
// {
// 1, 1, 1, 0
// },
// {
// 1, 1, 0, 1
// },
// {
// 1, 0, 1, 1
// },
// {
// 0, 1 ,1, 1
// },
// {
// 1, 1, 0, 0
// },
// {
// 1, 0, 0, 1
// },
// {
// 0, 0, 1, 1
// },
// {
// 1, 0, 1, 0
// },
// {
// 1, 1, 0, 1
// },
//};
//
//int combiThree[4][3] = {
// {
// 1, 1, 1
// },
// {
// 0, 1, 1
// },
// {
// 1, 1, 0
// },
// {
// 1, 0, 1
// }
//};
//
//int combiTwo[1][2] = {
// {
// 1, 1
// },
//};
std::map<std::vector<int>, DefaultMinusOne> DP;
//int[][] chooseX(int i, int count, std::vector<int> choices, int num, std::vector<int> &indexes) {
// if (count == num) {
// std::vector<int> v = std::vector<int>();
// return choices;
// }
// for (int a = i; a < n; a++) {
// std::vector<int> ayy = choices;
// ayy.push_back(indexes[a]);
// chooseX(a + 1, count, ayy, num, indexes);
// }
//}
int calc(std::vector<int> pointers, int n, std::vector<std::vector<int>> &stacks) {
if (DP[pointers].val != -1) {
return DP[pointers].val;
}
bool allZero = true;
int sum = 0;
std::map<int, int> counts;
if (VERBOSE) {
for (int i = 0; i < n; i++) { // basic decrement
if (pointers[i] >= 0) {
if (VERBOSE) std::cerr << stacks[i][pointers[i]] << " ";
} else {
if (VERBOSE) std::cerr << "end ";
}
}
if (VERBOSE) std::cerr << std::endl;
}
for (int i = 0; i < n; i++) { // basic decrement
if (pointers[i] != -1) {
allZero = false;
counts[stacks[i][pointers[i]]]++;
std::vector<int> cp = pointers;
cp[i]--;
sum = std::max(sum, calc(cp, n, stacks));
}
}
if (allZero) {
return 0; // base case
}
// check number of items equal
for (auto iter = counts.begin(); iter != counts.end(); iter++) {
if (iter->second > 1) {
std::vector<int> indexes;
for (int i = 0; i < n; i++) {
if (pointers[i] != -1 && stacks[i][pointers[i]] == iter->first) {
indexes.push_back(i);
}
}
// out of indexes, choose
int nums = 1 << iter->second;
for (int i = 0; i < nums; i++) {
int numChosen = 0;
std::vector<int> cp = pointers;
for (int a = 0; a < iter->second; a++) {
if (i & (1 << a)) {
cp[indexes[a]]--;
numChosen++;
}
}
if (numChosen >= 2) {
// at least 2
sum = std::max(sum, ((int) pow(2, numChosen - 2)) + calc(cp, n, stacks));
}
}
//// for (int i = iter->second; i > 1; i++) {
//// // Remove i
////
//// }
//
// std::vector<int> cp = pointers;
// for (int i = 0; i < n; i++) {
// if (cp[i] == -1) {
// continue;
// }
// if (stacks[i][cp[i]] == iter->first) {
// cp[i]--;
// }
// }
//// int x = std::
// int v;
// if (iter->second - 2 == 0) {
// v = 1;
// } else {
// v = ((int)pow(2, iter->second - 2));
// }
//// if ((pointers[2] == 9 && pointers[4] == 9)) {
//// std::cerr << "Found " << iter->first << " " << iter->second << " times! ";
//// std::cerr << v << " + " << calc(cp, n, stacks) << std::endl;
//// }
// sum = std::max(sum, v + calc(cp, n, stacks));
}
}
DP[pointers].val = sum;
// if ((pointers[2] == 10 && pointers[4] == 10) || (pointers[2] == 9 && pointers[4] == 9)) {
// for (int i = 0; i < n; i++) { // basic decrement
// if (pointers[i] != -1) {
// std::cerr << stacks[i][pointers[i]] << " (i: " << pointers[i] << ") ";
// } else {
// std::cerr << "end ";
// }
// }
// std::cerr << " S " << sum << std::endl;
// }
return sum;
}
void testcase() {
int n; std::cin >> n;
std::vector<int> sizes(n);
for (int i = 0; i < n; i++) {
std::cin >> sizes[i];
}
DP = std::map<std::vector<int>, DefaultMinusOne>();
std::vector<std::vector<int>> stacks(n);
for (int i = 0; i < n; i++) {
stacks[i] = std::vector<int>(sizes[i]);
for (int a = 0; a < sizes[i]; a++) {
std::cin >> stacks[i][a];
}
sizes[i]--; // init to pointer arrach
}
int score = calc(sizes, n, stacks);
std::cout << score << std::endl;
if (VERBOSE) {
for (auto iter = DP.begin(); iter != DP.end(); iter++) {
if (iter->first[2] != 16) {
continue;
}
for (int i = 0; i < n; i++) {
std::cerr << iter->first[i] << " ";
}
std::cerr << ": " << iter->second.val << std::endl;
// std::cerr << iter->first <<
}
}
// std::vector<int> k = std::vector<int>(n);
// k[0] = 2;
// k[1] = 4;
// k[2] = 10;
// k[3] = 2;
// k[4] = 10;
// std::cerr << DP[k].val << std::endl;
}
int main() {
std::ios_base::sync_with_stdio(false);
int t; std::cin >> t;
while (t-- > 0) {
testcase();
}
return 0;
}
|
35baa6db4166df5e1640040c5425237672fbb61f
|
4736440cd0d243d85fba9baa01d8bccb06982e41
|
/AksKMap/KMapExp.h
|
97c9a3c0778089eb6afde34860cf8294bbcd2c5d
|
[] |
no_license
|
google-code/aksharamala
|
409b4e9f4d45a95836d44519ce9a003e6c9493eb
|
edc6acdf69e4ca0462132a6e8f602cfce720eb24
|
refs/heads/master
| 2016-08-07T04:04:12.736351
| 2015-03-14T12:50:03
| 2015-03-14T12:50:03
| 32,211,538
| 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 8,366
|
h
|
KMapExp.h
|
// ==================================================================
// Copyright © 2001-2005 Srinivas Annam
//
// History:
// Jan 13, 2001: Increased the ambiguity length (for Chanakya).
// Oct 21, 2002: Added new features - paste bmp, pastelit bmp.
// ==================================================================
#ifndef KMAPEXP_H
#define KMAPEXP_H
#ifdef KMAP_DLL
#define KMAP_DECL __declspec(dllexport)
#else
#define KMAP_DECL __declspec(dllimport)
#endif
#define MAX_MULTI_CHAR_LEN 32
#define MAX_AMBIGUOUS_LEN 64
#define KMAP_SUMMARY_FILE "keymap.ams"
#define BIGWORD 256
#define MAXDICTWORD 32
#define SIZECONTEXT 8
#define MAX_TEXT_LINE 1024
#define MAX_KEYWORD_LEN 15
#define MULTIMAP_MAX_KEYMAPS 10
#define MAX_OPENFILE_BIFSIZ 2048
#define MAX_METAPHONE 4
#define TRANSLIT_NO_MATCH 0xffff
#define SWAP_TOFROM_ENGLISH 0xfffe
#define EAT_ME_SEPARATOR 0xfffd
#define CHAR_PLACE_HOLDER 0xfffc
#define CHAR_SPECIAL_FORMATTING 0xfffb
#define CHAR_REPEAT_PREVIOUS 0xfffa
#define CHECK_MAX(n, max) { if (n > max) goto MaxExceeded; }
typedef enum {
ctNone,
ctVowel,
ctConsonant,
ctNumber,
ctOther,
ctVowelSign, // this is used internally by Translit() logic
} CharType;
typedef enum {
ctxNone,
ctxVowelSign, // a vowel sign
ctxBeforeC, // place before the consonant (used by both vowels and cosonants)
ctxAfterC, // place after the consonant (used by both vowels and cosonants)
ctxAfterAllCs, // moves a consonant after all other consonants
ctxCBeforeSign, // used by consonants to have before sign variation
ctxAltPressed, // alt + char (for kbd layouts)
ctxShiftPressed, // shift + char (for kbd layouts eg. Shift + Esc)
ctxSwap, // swaps with prev char (used by consonants and others)
ctxBeforeWS, // before ws variation (any char)
ctxAfterWS, // after ws variation (any char)
ctxBeforeCSkipVs, // place before the consonant, skip any vowels first
ctxChangePrevious, // change the previous character (used by consonants)
ctxIsolatedForm, // when the character is surrounded by whitespace (any char)
} CharTypeEx;
#pragma pack(push, kmapexp, 1)
typedef struct {
int nID;
CharType ct;
WCHAR sz[MAX_MULTI_CHAR_LEN+1];
char szContext[SIZECONTEXT];
} AksChar;
typedef struct {
int nID;
CharType ct;
WCHAR sz[MAX_MULTI_CHAR_LEN+1];
char szzAmbiguousWith[MAX_AMBIGUOUS_LEN];
char szContext[SIZECONTEXT];
} MapEntry;
typedef struct {
short len;
WCHAR sz[MAX_MULTI_CHAR_LEN+1];
char szContext[SIZECONTEXT];
} MapEntryEx;
typedef enum {
fmtUnknown,
fmtRtf,
fmtHtml,
fmtWmChar,
} Fmt;
class CAksCharsList;
typedef struct {
HWND hWnd;
Fmt fmtWnd;
bool bInEnglish;
UINT uiKMapID;
int nBackspacesSent, nCtrlsSent, nCurrentLetter, nDbID;
char szBuffer[BIGWORD];
// the following member has been added to handle .r
// TODO: remove as many of the above data members
// and modify the code to use the list below
AksChar achPending;
CAksCharsList* pCharList;
} WndContext;
typedef struct {
bool bShiftDown;
bool bAltDown;
} KeyModifiers;
typedef enum {
encUnicode,
encITRANS,
encASCII,
encISCII,
encRTS,
encUtf8,
} Enc;
typedef enum {
fmtKeymap,
fmtNoFormat,
fmtAsSpecified,
} AksFormatting;
typedef enum {
outImmediate,
outOnSeparator,
outOnNewLine,
} AksOutputOption;
#pragma pack(pop, kmapexp)
//-- Exported functions ---------------------------------------------
extern "C" {
LPCSTR KMAP_DECL aksLoadKMap(LPCSTR szFileName);
bool KMAP_DECL aksTranslit(WndContext* ctxt, int& nBackSpaces, WCHAR* lpResult,
short nKeyModifiers = 0);
int KMAP_DECL aksTranslateNumber(UINT uiKMapID, int num, WCHAR* lpResult, int nMaxSize);
HICON KMAP_DECL aksLoadDisabledIcon(UINT uiKMapID);
HICON KMAP_DECL aksLoadEnabledIcon(UINT uiKMapID);
int KMAP_DECL aksGetKMapCount();
LPSTR KMAP_DECL aksGetKMapName(UINT uiKMapID, LPSTR sz, int nSize);
LPSTR KMAP_DECL aksGetKMapFileName(UINT uiKMapID, LPSTR sz, int nSize);
int KMAP_DECL aksGetKMapFontSize(UINT uiKMapID);
LPSTR KMAP_DECL aksGetKMapFontName(UINT uiKMapID, LPSTR sz, int nSize, int* nFS, bool bFmtAsSpecified = false);
LPSTR KMAP_DECL aksGetKMapLanguage(UINT uiKMapID, LPSTR sz, int nSize);
UINT KMAP_DECL aksGetKMapID(LPCSTR sz);
UINT KMAP_DECL aksGetKMapIDByTitle(LPCSTR szTitle);
int KMAP_DECL aksGetIcon(UINT uiKMapID, int nIsEnabled);
int KMAP_DECL aksLoadKMaps(LPCSTR szLanguage = 0);
void KMAP_DECL aksSetHotKey(WORD hotKey, WORD modKey);
void KMAP_DECL aksGetHotKey(WORD *hotKey, WORD *modKey);
void KMAP_DECL aksSetPastelitHotKey(WORD hotKey, WORD modKey);
void KMAP_DECL aksGetPastelitHotKey(WORD *hotKey, WORD *modKey);
void KMAP_DECL aksGetNextHotKey(WORD *hotKey, WORD *modKey);
void KMAP_DECL aksSetNextHotKey(WORD hotKey, WORD modKey);
void KMAP_DECL aksGetMultiMapHotKey(WORD *hotKey, WORD *modKey);
void KMAP_DECL aksSetMultiMapHotKey(WORD hotKey, WORD modKey);
void KMAP_DECL aksGetPasteBmpHotKey(WORD *hotKey, WORD *modKey);
void KMAP_DECL aksSetPasteBmpHotKey(WORD hotKey, WORD modKey);
void KMAP_DECL aksGetPastelitBmpHotKey(WORD *hotKey, WORD *modKey);
void KMAP_DECL aksSetPastelitBmpHotKey(WORD hotKey, WORD modKey);
void KMAP_DECL aksGetPasteUnicodeHotKey(WORD *hotKey, WORD *modKey);
void KMAP_DECL aksSetPasteUnicodeHotKey(WORD hotKey, WORD modKey);
void KMAP_DECL aksGetPasteUtf8HotKey(WORD *hotKey, WORD *modKey);
void KMAP_DECL aksSetPasteUtf8HotKey(WORD hotKey, WORD modKey);
int KMAP_DECL aksProcessFile(LPCSTR szTxtFile);
int KMAP_DECL aksTxt2Bin(LPCSTR szTxtFile, LPCSTR szOutFile);
bool KMAP_DECL aksWriteKMapSummary(LPCSTR szRootPath);
bool KMAP_DECL aksLoadKMapSummary(LPCSTR szDirPath);
void KMAP_DECL aksGetErrorString(LPSTR szError, int n);
bool KMAP_DECL aksIsNonSeparator(UINT uiKMapID, char ch);
LPWSTR KMAP_DECL aksNormalVirama(UINT uiKMapID);
bool KMAP_DECL aksGetKMapStringID(UINT uiKMapID, LPSTR szID, int nSize);
bool KMAP_DECL aksIsAltUsed(UINT uiKMapID);
bool KMAP_DECL aksGetFormat(UINT uiKMapID, LPCSTR szClassName, bool& bRtf, bool& bHtml, bool& bWmChar);
Enc KMAP_DECL aksGetEncoding(UINT uiKMapID);
bool KMAP_DECL aksGetPasteBmpWidth(DWORD& dwWidth);
void KMAP_DECL aksSetPasteBmpWidth(DWORD dwWidth);
LPSTR KMAP_DECL aksGetKMapScheme(UINT uiKMapID, LPSTR sz, int nSize);
void KMAP_DECL aksSetMultiMapEnabled(bool bEnabled);
bool KMAP_DECL aksIsMultiMapEnabled();
void KMAP_DECL aksSetDictionaryEnabled(bool bEnabled);
bool KMAP_DECL aksIsDictionaryEnabled();
bool KMAP_DECL aksGetRegistryString(char* szRegKey, char* szRegValue, int nSize);
void KMAP_DECL aksSetRegistryString(LPCSTR szRegKey, LPCSTR szRegValue);
bool KMAP_DECL aksGetRegistryInt(char* szRegKey, DWORD& val);
int KMAP_DECL aksKMapLastModified();
DWORD KMAP_DECL aksGetFormatting();
void KMAP_DECL aksSetFormatting(AksFormatting nFormatting);
DWORD KMAP_DECL aksGetOutputOption();
void KMAP_DECL aksSetOutputOption(AksOutputOption nOutputOption);
bool KMAP_DECL aksGetFontDetails(LPCSTR szScript, LPSTR szFontName, int nFontNameLen, DWORD* dwFontSize);
void KMAP_DECL aksSetFontDetails(LPCSTR szScript, LPCSTR szFontName, DWORD dwFontSize);
int KMAP_DECL aksGetAlternates(UINT uiKMapID, LPCSTR sz, char* szAlternates, int nSize);
bool KMAP_DECL aksShowDictionary(WndContext* ctxt, int& nBackSpaces, WCHAR* wchResult);
bool KMAP_DECL aksAddToDictionary(LPCSTR szFile, int& nAdded, int& nDuplicates);
void KMAP_DECL aksCloseDB();
bool KMAP_DECL aksIsDictAvailable();
void KMAP_DECL aksSetUniscribeWarningEnabled(bool bEnabled);
bool KMAP_DECL aksIsUniscribeWarningEnabled();
void KMAP_DECL aksSetSkipKeymaps(bool bEnabled);
bool KMAP_DECL aksIsSkipKeymapsOn();
bool KMAP_DECL DbgWriteLn(LPCSTR sz, DWORD dbgLevel);
}
typedef enum {
dbgNone = 0,
dbgDebug = 1,
dbgDetailed = 2,
dbgTrace = 3,
dbgDetailedTrace = 4,
};
#define AKSMAINWND_CLASS "AksMainWndClass"
#define DEFAULT_SCRIPT "Default"
#endif
|
d2c399aed910195c61c972aefca41ed69ed0cd0e
|
5f0a95d0a3cef2fdab8570fa8171d735c8270940
|
/packet-collector/packet-collector.cc
|
5fce824d2480a68ecb1eee9b5096ae5790ba39d2
|
[] |
no_license
|
dtnaylor/cuda-router
|
33fed63c40a79fe1b65d3990523ba4879cb0483d
|
53cfb1c51480561582dce214c68f9ccf3bcee683
|
refs/heads/master
| 2021-01-19T06:58:24.988828
| 2012-12-04T16:42:55
| 2012-12-04T16:42:55
| 6,459,239
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,034
|
cc
|
packet-collector.cc
|
#include "packet-collector.hh"
int batch_size = DEFAULT_BATCH_SIZE;
int batch_wait = DEFAULT_BATCH_WAIT;
#ifdef RETURN_PACKETS_IMMEDIATELY
packet *random_buf = NULL;
#endif
int init_server_socket() {
int sockfd;
struct sockaddr_in servaddr;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
perror("socket");
return -1;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERVER_PORT);
if (bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
perror("bind");
return -1;
}
return sockfd;
}
udpc init_client_socket() {
udpc client;
if ((client.fd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
perror("socket");
return client;
}
memset(&client.sa, 0, sizeof(client.sa));
client.sa.sin_family = AF_INET;
client.sa.sin_port = htons(CLIENT_PORT);
if (inet_aton("127.0.0.1", &client.sa.sin_addr)==0) {
perror("inet_aton");
client.fd = -1;
return client;
}
return client;
}
#ifdef RETURN_PACKETS_IMMEDIATELY
void generate_random_packets() {
if (random_buf != NULL) {
free(random_buf);
}
random_buf = (packet*)malloc( sizeof(packet) * get_batch_size());
for(int i = 0; i < get_batch_size(); i++) {
for(int j = 0; j < IP_HEADER_SIZE; j++) random_buf[i].ip[j] = (char)rand();
for(int j = 0; j < UDP_HEADER_SIZE; j++) random_buf[i].udp[j] = (char)rand();
random_buf[i].payload = (char *)malloc(BUF_SIZE*sizeof(char));
for(int j = 0; j < BUF_SIZE; j++) random_buf[i].payload[j] = (char)rand();
}
}
#endif /* RETURN_PACKETS_IMMEDIATELY */
int set_batch_size(int s) {
if (s > 0) {
batch_size = s;
#ifdef RETURN_PACKETS_IMMEDIATELY
generate_random_packets();
#endif /* RETURN_PACKETS_IMMEDIATELY */
}
return batch_size;
}
int get_batch_size() {
return batch_size;
}
int set_batch_wait(int s) {
if (s > 0) {
batch_wait = s;
}
return batch_wait;
}
int get_batch_wait() {
return batch_wait;
}
void *timer(void *data) {
usleep(batch_wait*1000);
*(int *)data = 1;
return 0;
}
int get_packets(int sockfd, packet* p) {
#ifdef RETURN_PACKETS_IMMEDIATELY
if (random_buf == NULL) generate_random_packets();
memcpy(p, random_buf, sizeof(packet)*get_batch_size());
return get_batch_size();
#endif
int timeout = 0;
pthread_t thread;
struct timeval tout;
tout.tv_sec = 0;
tout.tv_usec = 0;
fd_set rfds;
FD_ZERO(&rfds);
pthread_create(&thread, NULL, timer, &timeout);
int i;
for(i = 0; i < batch_size;) {
FD_SET(sockfd, &rfds);
if(select(sockfd+1, &rfds, NULL, NULL, &tout) > 0) {
p[i].size = recv(sockfd, p[i].payload, BUF_SIZE, 0);
if(p[i].size > IP_HEADER_SIZE + UDP_HEADER_SIZE) {
memcpy(p[i].ip, p[i].payload, IP_HEADER_SIZE);
memcpy(p[i].udp, &p[i].payload[IP_HEADER_SIZE], UDP_HEADER_SIZE);
i++;
}
}
if(timeout == 1) break;
}
pthread_cancel(thread);
return i;
}
int send_packets(udpc client, packet* p, int num_packets, int* a) {
#ifndef RETURN_PACKETS_IMMEDIATELY
for(int i = 0; i < num_packets && a[i] >= 0; i++) {
sendto(client.fd, p[i].payload, p[i].size, 0, (struct sockaddr*)&client.sa, sizeof(client.sa));
}
#endif /* RETURN_PACKETS_IMMEDIATELY */
return 0;
}
#ifndef CUDA_CODE
int main() {
#ifdef RETURN_PACKETS_IMMEDIATELY
genereate_random_packets();
#endif
int server_sockfd = init_server_socket();
if(server_sockfd == -1) {
return -1;
}
udpc client= init_client_socket();
if(client.fd == -1) {
return -1;
}
packet* p = (packet *)malloc(sizeof(packet)*batch_size);
for(int i = 0; i < batch_size; i++) {
p[i].payload = (char *)malloc(BUF_SIZE*sizeof(char));
}
int* a = (int *)malloc(sizeof(int)*batch_size);
memset(a, 0, sizeof(int)*batch_size);
while(1) {
int num_packets = get_packets(server_sockfd, p);
printf("num_packets = %d\n", num_packets);
send_packets(client, p, num_packets, a);
}
}
#endif
|
2a937cdd4c0912d85fc2163b09f729d5b40896ea
|
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
|
/generated/src/aws-cpp-sdk-ssm/include/aws/ssm/model/InstancePatchStateFilter.h
|
36e3e88b1c7cf40212952169daa2ec5184f67680
|
[
"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
| 10,406
|
h
|
InstancePatchStateFilter.h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ssm/SSM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ssm/model/InstancePatchStateOperatorType.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace SSM
{
namespace Model
{
/**
* <p>Defines a filter used in <a>DescribeInstancePatchStatesForPatchGroup</a> to
* scope down the information returned by the API.</p> <p> <b>Example</b>: To
* filter for all managed nodes in a patch group having more than three patches
* with a <code>FailedCount</code> status, use the following for the filter:</p>
* <ul> <li> <p>Value for <code>Key</code>: <code>FailedCount</code> </p> </li>
* <li> <p>Value for <code>Type</code>: <code>GreaterThan</code> </p> </li> <li>
* <p>Value for <code>Values</code>: <code>3</code> </p> </li> </ul><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/InstancePatchStateFilter">AWS
* API Reference</a></p>
*/
class InstancePatchStateFilter
{
public:
AWS_SSM_API InstancePatchStateFilter();
AWS_SSM_API InstancePatchStateFilter(Aws::Utils::Json::JsonView jsonValue);
AWS_SSM_API InstancePatchStateFilter& operator=(Aws::Utils::Json::JsonView jsonValue);
AWS_SSM_API Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The key for the filter. Supported values include the following:</p> <ul> <li>
* <p> <code>InstalledCount</code> </p> </li> <li> <p>
* <code>InstalledOtherCount</code> </p> </li> <li> <p>
* <code>InstalledPendingRebootCount</code> </p> </li> <li> <p>
* <code>InstalledRejectedCount</code> </p> </li> <li> <p>
* <code>MissingCount</code> </p> </li> <li> <p> <code>FailedCount</code> </p>
* </li> <li> <p> <code>UnreportedNotApplicableCount</code> </p> </li> <li> <p>
* <code>NotApplicableCount</code> </p> </li> </ul>
*/
inline const Aws::String& GetKey() const{ return m_key; }
/**
* <p>The key for the filter. Supported values include the following:</p> <ul> <li>
* <p> <code>InstalledCount</code> </p> </li> <li> <p>
* <code>InstalledOtherCount</code> </p> </li> <li> <p>
* <code>InstalledPendingRebootCount</code> </p> </li> <li> <p>
* <code>InstalledRejectedCount</code> </p> </li> <li> <p>
* <code>MissingCount</code> </p> </li> <li> <p> <code>FailedCount</code> </p>
* </li> <li> <p> <code>UnreportedNotApplicableCount</code> </p> </li> <li> <p>
* <code>NotApplicableCount</code> </p> </li> </ul>
*/
inline bool KeyHasBeenSet() const { return m_keyHasBeenSet; }
/**
* <p>The key for the filter. Supported values include the following:</p> <ul> <li>
* <p> <code>InstalledCount</code> </p> </li> <li> <p>
* <code>InstalledOtherCount</code> </p> </li> <li> <p>
* <code>InstalledPendingRebootCount</code> </p> </li> <li> <p>
* <code>InstalledRejectedCount</code> </p> </li> <li> <p>
* <code>MissingCount</code> </p> </li> <li> <p> <code>FailedCount</code> </p>
* </li> <li> <p> <code>UnreportedNotApplicableCount</code> </p> </li> <li> <p>
* <code>NotApplicableCount</code> </p> </li> </ul>
*/
inline void SetKey(const Aws::String& value) { m_keyHasBeenSet = true; m_key = value; }
/**
* <p>The key for the filter. Supported values include the following:</p> <ul> <li>
* <p> <code>InstalledCount</code> </p> </li> <li> <p>
* <code>InstalledOtherCount</code> </p> </li> <li> <p>
* <code>InstalledPendingRebootCount</code> </p> </li> <li> <p>
* <code>InstalledRejectedCount</code> </p> </li> <li> <p>
* <code>MissingCount</code> </p> </li> <li> <p> <code>FailedCount</code> </p>
* </li> <li> <p> <code>UnreportedNotApplicableCount</code> </p> </li> <li> <p>
* <code>NotApplicableCount</code> </p> </li> </ul>
*/
inline void SetKey(Aws::String&& value) { m_keyHasBeenSet = true; m_key = std::move(value); }
/**
* <p>The key for the filter. Supported values include the following:</p> <ul> <li>
* <p> <code>InstalledCount</code> </p> </li> <li> <p>
* <code>InstalledOtherCount</code> </p> </li> <li> <p>
* <code>InstalledPendingRebootCount</code> </p> </li> <li> <p>
* <code>InstalledRejectedCount</code> </p> </li> <li> <p>
* <code>MissingCount</code> </p> </li> <li> <p> <code>FailedCount</code> </p>
* </li> <li> <p> <code>UnreportedNotApplicableCount</code> </p> </li> <li> <p>
* <code>NotApplicableCount</code> </p> </li> </ul>
*/
inline void SetKey(const char* value) { m_keyHasBeenSet = true; m_key.assign(value); }
/**
* <p>The key for the filter. Supported values include the following:</p> <ul> <li>
* <p> <code>InstalledCount</code> </p> </li> <li> <p>
* <code>InstalledOtherCount</code> </p> </li> <li> <p>
* <code>InstalledPendingRebootCount</code> </p> </li> <li> <p>
* <code>InstalledRejectedCount</code> </p> </li> <li> <p>
* <code>MissingCount</code> </p> </li> <li> <p> <code>FailedCount</code> </p>
* </li> <li> <p> <code>UnreportedNotApplicableCount</code> </p> </li> <li> <p>
* <code>NotApplicableCount</code> </p> </li> </ul>
*/
inline InstancePatchStateFilter& WithKey(const Aws::String& value) { SetKey(value); return *this;}
/**
* <p>The key for the filter. Supported values include the following:</p> <ul> <li>
* <p> <code>InstalledCount</code> </p> </li> <li> <p>
* <code>InstalledOtherCount</code> </p> </li> <li> <p>
* <code>InstalledPendingRebootCount</code> </p> </li> <li> <p>
* <code>InstalledRejectedCount</code> </p> </li> <li> <p>
* <code>MissingCount</code> </p> </li> <li> <p> <code>FailedCount</code> </p>
* </li> <li> <p> <code>UnreportedNotApplicableCount</code> </p> </li> <li> <p>
* <code>NotApplicableCount</code> </p> </li> </ul>
*/
inline InstancePatchStateFilter& WithKey(Aws::String&& value) { SetKey(std::move(value)); return *this;}
/**
* <p>The key for the filter. Supported values include the following:</p> <ul> <li>
* <p> <code>InstalledCount</code> </p> </li> <li> <p>
* <code>InstalledOtherCount</code> </p> </li> <li> <p>
* <code>InstalledPendingRebootCount</code> </p> </li> <li> <p>
* <code>InstalledRejectedCount</code> </p> </li> <li> <p>
* <code>MissingCount</code> </p> </li> <li> <p> <code>FailedCount</code> </p>
* </li> <li> <p> <code>UnreportedNotApplicableCount</code> </p> </li> <li> <p>
* <code>NotApplicableCount</code> </p> </li> </ul>
*/
inline InstancePatchStateFilter& WithKey(const char* value) { SetKey(value); return *this;}
/**
* <p>The value for the filter. Must be an integer greater than or equal to 0.</p>
*/
inline const Aws::Vector<Aws::String>& GetValues() const{ return m_values; }
/**
* <p>The value for the filter. Must be an integer greater than or equal to 0.</p>
*/
inline bool ValuesHasBeenSet() const { return m_valuesHasBeenSet; }
/**
* <p>The value for the filter. Must be an integer greater than or equal to 0.</p>
*/
inline void SetValues(const Aws::Vector<Aws::String>& value) { m_valuesHasBeenSet = true; m_values = value; }
/**
* <p>The value for the filter. Must be an integer greater than or equal to 0.</p>
*/
inline void SetValues(Aws::Vector<Aws::String>&& value) { m_valuesHasBeenSet = true; m_values = std::move(value); }
/**
* <p>The value for the filter. Must be an integer greater than or equal to 0.</p>
*/
inline InstancePatchStateFilter& WithValues(const Aws::Vector<Aws::String>& value) { SetValues(value); return *this;}
/**
* <p>The value for the filter. Must be an integer greater than or equal to 0.</p>
*/
inline InstancePatchStateFilter& WithValues(Aws::Vector<Aws::String>&& value) { SetValues(std::move(value)); return *this;}
/**
* <p>The value for the filter. Must be an integer greater than or equal to 0.</p>
*/
inline InstancePatchStateFilter& AddValues(const Aws::String& value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }
/**
* <p>The value for the filter. Must be an integer greater than or equal to 0.</p>
*/
inline InstancePatchStateFilter& AddValues(Aws::String&& value) { m_valuesHasBeenSet = true; m_values.push_back(std::move(value)); return *this; }
/**
* <p>The value for the filter. Must be an integer greater than or equal to 0.</p>
*/
inline InstancePatchStateFilter& AddValues(const char* value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }
/**
* <p>The type of comparison that should be performed for the value.</p>
*/
inline const InstancePatchStateOperatorType& GetType() const{ return m_type; }
/**
* <p>The type of comparison that should be performed for the value.</p>
*/
inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }
/**
* <p>The type of comparison that should be performed for the value.</p>
*/
inline void SetType(const InstancePatchStateOperatorType& value) { m_typeHasBeenSet = true; m_type = value; }
/**
* <p>The type of comparison that should be performed for the value.</p>
*/
inline void SetType(InstancePatchStateOperatorType&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }
/**
* <p>The type of comparison that should be performed for the value.</p>
*/
inline InstancePatchStateFilter& WithType(const InstancePatchStateOperatorType& value) { SetType(value); return *this;}
/**
* <p>The type of comparison that should be performed for the value.</p>
*/
inline InstancePatchStateFilter& WithType(InstancePatchStateOperatorType&& value) { SetType(std::move(value)); return *this;}
private:
Aws::String m_key;
bool m_keyHasBeenSet = false;
Aws::Vector<Aws::String> m_values;
bool m_valuesHasBeenSet = false;
InstancePatchStateOperatorType m_type;
bool m_typeHasBeenSet = false;
};
} // namespace Model
} // namespace SSM
} // namespace Aws
|
24a480b23d7e3aedd14080a04a01c2eed80d0ee9
|
b49c432c23f9fc0e88bba6bc12438e3f56b497be
|
/app/src/main/cpp/io/include/block-inl.h
|
bf6538fdb943baceae8bcb5d36fd36710e30c676
|
[] |
no_license
|
skyformat99/EncryptedIO
|
39bf277bd2f048d4a9cd2ea856ab000b0d186d41
|
9887f3b7652337f8c6911d0305871e4754b3280d
|
refs/heads/master
| 2021-01-20T07:41:12.310428
| 2017-01-06T02:07:51
| 2017-01-06T02:07:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 479
|
h
|
block-inl.h
|
/*
* Author: wangyun
* Date: 2016-12-30
* Email: yun.wang@vmplay.com
* LastUpdateTime: 2017-01-03
* LastUpdateBy: wangyun
*/
#ifndef ENCRYPTED_BLOCK_INL_H
#define ENCRYPTED_BLOCK_INL_H
#include "block.h"
namespace tools {
inline const char* Block::getConstData() const {
return (const char *)mData_;
}
inline char* Block::getData() {
return mData_;
}
inline void Block::clear() {
if (LIKELY(mData_ != NULL))
free(mData_);
mData_ = NULL;
}
}
#endif
|
81677a734f56693c845405fae8794aa5e412466b
|
03d4e39d8fda4d1b8b70628e95b0ca3f6034dd17
|
/Code/mcApp/CmcMvcs.cpp
|
5d92a1177f8998bd7c641f85fbb6bdc607c50fd8
|
[] |
no_license
|
hbdlyao/HVDC-MT
|
ab464e68645f2aae3881bc27547ef5643a55f63d
|
d7ee695d2b136b46402fcf298ffecd18ee662e3a
|
refs/heads/master
| 2021-01-21T20:56:39.518812
| 2017-06-02T03:03:17
| 2017-06-02T03:03:17
| 92,291,963
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,091
|
cpp
|
CmcMvcs.cpp
|
///////////////////////////////////////////////////////////
// CHvdcMvcs.cpp
// Implementation of the Class CHvdcMvcs
// Created on: 24-3月-2017 20:58:52
// Original author: Administrator
///////////////////////////////////////////////////////////
#include "CmcMvcs.h"
#include "CmcParams.h"
#include "CmcVars.h"
#include "CmcRwOrderMvc.h"
#include "CmcRwResultMvc.h"
#include <iostream>
void CmcMvcs::Init()
{
}
void CmcMvcs::Clear()
{
}
void CmcMvcs::Release()
{
}
void CmcMvcs::OnLoad(string vdbf)
{
CmcRwMvc* vRwMvc;
vRwMvc = new CmcRwMvc();
vRwMvc->InitAdo(vdbf);
vRwMvc->InitGrid(CmcVars::pmcHvdcGrid);
vRwMvc->OnLoad(vdbf);
delete vRwMvc;
}
void CmcMvcs::OnSave(string vdbf)
{
CmcRwMvc* vRwMvc;
vRwMvc = new CmcRwMvc();
vRwMvc->InitAdo(vdbf);
vRwMvc->InitGrid(CmcVars::pmcHvdcGrid);
vRwMvc->OnSave(vdbf);
delete vRwMvc;
}
void CmcMvcs::OnLoadOrder(string vdbf)
{
//CmcVars::pmcOrder->CalName = "测试1495529378";
CmcRwOrderMvc* vRwMvc = new CmcRwOrderMvc();
vRwMvc->InitAdo(vdbf);
vRwMvc->Init(CmcVars::pmcOrder);
vRwMvc->OnLoad(vdbf);
delete vRwMvc;
}
void CmcMvcs::OnLoad_PRJ(string vdbf)
{
CmcPRJ_RwMvc * vRwMvc;
vRwMvc = new CmcPRJ_RwMvc();
vRwMvc->InitAdo(CmcParams::PRJFile);
vRwMvc->OnLoad(CmcParams::PRJFile);
delete vRwMvc;
}
void CmcMvcs::OnSave_PRJ(string vdbf)
{
CmcPRJ_RwMvc * vRwMvc;
vRwMvc = new CmcPRJ_RwMvc();
vRwMvc->InitAdo(CmcParams::PRJFile);
vRwMvc->OnSave(CmcParams::PRJFile);
delete vRwMvc;
}
void CmcMvcs::OnLoadResult(string vdbf, CmcResult* vResult)
{
SYSTEMTIME sys_time1;
GetLocalTime(&sys_time1);
cout << "---读入mc计算结果---";
cout << sys_time1.wHour << "时";
cout << sys_time1.wMinute << "分";
cout << sys_time1.wSecond << "秒";
cout<< endl;
//
CmcRwResultMvc* vRwMvc = new CmcRwResultMvc();
vRwMvc->InitAdo(vdbf);
vRwMvc->Init(vResult);
vRwMvc->OnLoad(vdbf);
delete vRwMvc;
SYSTEMTIME sys_time2;
GetLocalTime(&sys_time2);
cout << "---读入结束---";
cout << sys_time2.wHour <<"时";
cout << sys_time2.wMinute << "分";
cout << sys_time2.wSecond << "秒";
//cout << sys_time2.wMilliseconds << "秒";
cout << endl;
/*cout<< sys_time2.wHour - sys_time1.wHour;
cout << "时" << sys_time2.wMinute - sys_time1.wMinute;
cout << "分" << sys_time2.wSecond - sys_time1.wSecond << ".";
cout << sys_time2.wMilliseconds - sys_time1.wMilliseconds << "秒";
cout<< endl*/;
}
void CmcMvcs::OnSaveResult(string vdbf, CmcResult* vResult)
{
SYSTEMTIME sys_time1;
GetLocalTime(&sys_time1);
cout << "---存储mc计算结果---";
cout << sys_time1.wHour << "时";
cout << sys_time1.wMinute << "分";
cout << sys_time1.wSecond << "秒";
cout << endl;
//
CmcRwResultMvc* vRwMvc = new CmcRwResultMvc();
vRwMvc->InitAdo(vdbf);
vRwMvc->Init(vResult);
vRwMvc->OnSave(vdbf);
delete vRwMvc;
SYSTEMTIME sys_time2;
GetLocalTime(&sys_time2);
cout << "---存储结束---";
cout << sys_time2.wHour << "时";
cout << sys_time2.wMinute << "分";
cout << sys_time2.wSecond << "秒";
//cout << sys_time2.wMilliseconds << "秒";
cout << endl;
}
|
2465baac215e2e533438c072d6308d6de97dd735
|
c17cc8590ecd54b6466b0f10ad965c87c616845b
|
/engine/core/clock/RealTimeClock.h
|
a1558329354a67c730777f7311a437152a124a9b
|
[] |
no_license
|
andreduvoisin/CompositeEngine
|
a497d23b01aee18e8dec306a3197da66721da218
|
1370399421980b2d17c4544a982101d4ac2264bd
|
refs/heads/master
| 2023-03-18T19:43:36.573531
| 2020-07-03T06:52:03
| 2020-07-03T06:52:03
| 173,540,984
| 17
| 3
| null | 2021-03-12T01:08:50
| 2019-03-03T06:46:51
|
C++
|
UTF-8
|
C++
| false
| false
| 237
|
h
|
RealTimeClock.h
|
#ifndef _CE_REAL_TIME_CLOCK_H_
#define _CE_REAL_TIME_CLOCK_H_
#include "Clock.h"
#include "common/Singleton.h"
namespace CE
{
class RealTimeClock : public Clock, public Singleton<RealTimeClock> { };
}
#endif // _CE_REAL_TIME_CLOCK_H_
|
893239600039453d77776229c43f12f68b738784
|
b5394dc0bca6410a6b789385eac2cdaacacd92c8
|
/a4/q2tallyVotesMC.cc
|
dc274f013354a0e0f91b67a6a60240bb47208f35
|
[] |
no_license
|
deerishi/CS343-assignments
|
abcc228e90fc0e04371ac4598e919df46262c9b4
|
1e8d9c3046284face3c493656d340d1ca12ade6c
|
refs/heads/master
| 2020-12-03T04:18:10.689139
| 2017-06-30T04:23:55
| 2017-06-30T04:23:55
| 95,847,713
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,002
|
cc
|
q2tallyVotesMC.cc
|
#ifndef PRINT_H
#include "q2printer.h"
#define PRINT_H
#endif
#ifndef STD
#include<iostream>
using namespace std;
#define STD
#endif
#ifndef MPRNG_H
#define MPRNG_H
#include "MPRNG.h"
#endif
//Defining the constructor for the type MC. This has a barging flag
TallyVotes::TallyVotes( unsigned int group, Printer &printer ):barging(false),numBlocked(0),numNeeded(0),group(group),printer(printer),pics(0),statue(0){}
TallyVotes::Tour TallyVotes:: vote( unsigned int id, Tour ballot ){
mutex.acquire();
//Checking for barging task
if(barging){
//printing Barging status
printer.print(id,Voter::States::Barging);
barge.wait(mutex);
}
numNeeded++;
//Now we vote
printer.print(id,Voter::States::Vote,ballot);
if(ballot==TallyVotes::Tour::Picture){
pics++;
}
else{
statue++;
}
//If group is not full
if(numNeeded!=group){
//Release barging task
if(!barge.empty()){
barge.signal();
}
else{
barging=false;
}
//Printing blocking message
printer.print(id,Voter::States::Block,numNeeded);
notFull.wait(mutex);
numNeeded--;
//Printing unblocking message
printer.print(id,Voter::States::Unblock,numNeeded);
}
else{
printer.print(id,Voter::States::Complete);
numNeeded--;
winner=statue>pics;
pics=0;
statue=0;
}
//Finding the result of the election
/*if(numNeeded==0){
//Meaning that this was the last task that was waiting for the results of the group
pics=0;
statue=0;
}*/
//Check if any task is waiting on the mutex queue
if(!notFull.empty()){
barging=true;
notFull.signal();
}
else if(!barge.empty()){ //Release any barging task
barge.signal();
}
else{
barging=false;
}
mutex.release();
return static_cast<TallyVotes::Tour>(winner);
}
|
cd38557f7788fe4659f93fc2a6698c5d8995c7ed
|
5bb92ef8c91d26e1b3369f6ba4862e71ffb79aa2
|
/src/Card.cpp
|
5037eaf181868898a854dacb2c541e4aa01d9601
|
[] |
no_license
|
adrienruault/pokerbot
|
18b23cdef684b15333cb0b4b646cbd09c1fc74f4
|
5ec43b8c38b7c84fe33d04f5ceff014cd6a5778c
|
refs/heads/master
| 2021-08-22T04:51:11.917337
| 2017-06-23T15:02:23
| 2017-06-23T15:02:23
| 112,459,384
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,661
|
cpp
|
Card.cpp
|
/*
* card.cpp
*
* Created on: Mar 5, 2017
* Author: adrien
*/
#include "Card.hpp"
// Default constructor that initializes an empty card (0,0)
Card::Card()
{
mrank=0;
msuit=0;
}
// Constructor that initializes an card with the provided rank and suit
Card::Card(const int rank, const int suit)
{
if ((rank < 1) || (rank > 13))
{
throw ErrorRank();
}
mrank=rank;
if ((suit < 0) || (suit > 4))
{
throw ErrorSuit(suit);
}
msuit=suit;
}
// Constructor that initializes a card using a random generator and takes as input a
// list of forbidden cards.
Card::Card(const std::set<Card>& forbidden_cards)
{
// Pull random rank number [1,13]
mrank = rand() % 13 + 1;
// Pull random suit number [1,4]
msuit = rand() % 4 + 1;
// while loop to check that the random card that has just been pulled does not
// belong to the forbidden list
while (forbidden_cards.find(*this) != forbidden_cards.end())
{
// If we enter the loop it means that a forbidden card has been pulled.
// Therefore another one has to be pulled until an allowed card is pulled.
// Pull random rank number [1,13]
mrank = rand() % 13 + 1;
// Pull random suit number [1,4]
msuit = rand() % 4 + 1;
//std::cout << (*this) << " Card Constructor\n";
//std::cout << (forbidden_cards.find(*this) != forbidden_cards.end()) << "\n";
//std::cout << forbidden_cards.size() << "\t"<< "\n";
}
}
int Card::GetRank() const
{
return mrank;
}
int Card::GetSuit() const
{
return msuit;
}
void Card::SetRank(const int& new_rank)
{
if ((new_rank < 1) || (new_rank > 13))
{
throw ErrorRank();
}
mrank=new_rank;
}
void Card::SetSuit(const int& new_suit)
{
if ((new_suit < 0) || (new_suit > 4))
{
throw ErrorSuit(new_suit);
}
msuit=new_suit;
}
void Card::SetCard(const int& new_rank, const int& new_suit)
{
mrank=new_rank;
msuit=new_suit;
}
// Update the attributes of the Card object by pulling random cards and accounting
// for the forbidden cards.
void Card::PullRandom(const std::set<Card>& forbidden_cards)
{
// Pull random rank number [1,13]
mrank = rand() % 13 + 1;
// Pull random suit number [1,4]
msuit = rand() % 4 + 1;
// while loop to check that the random card that has just been pulled does not
// belong to the forbidden list
while (forbidden_cards.find(*this) != forbidden_cards.end())
{
// If we enter the loop it means that a forbidden card has been pulled.
// Therefore another one has to be pulled until an allowed card is pulled.
// Pull random rank number [1,13]
mrank = rand() % 13 + 1;
// Pull random suit number [1,4]
msuit = rand() % 4 + 1;
}
}
// Overriding of the assignment operator
Card& Card::operator= (const Card& card_to_copy)
{
mrank=card_to_copy.mrank;
msuit=card_to_copy.msuit;
return *this;
}
// Overriding of the less than equal operator in order to make the std::set::find method
// working
bool Card::operator< (const Card& right_card) const
{
// First step is to make the (0,0) cards as greater than any others
if (right_card.mrank==0)
{
return true;
}
if (mrank==0)
{
return false;
}
if (mrank > right_card.mrank)
{
return false;
}
else if (mrank < right_card.mrank)
{
return true;
}
else
{
if (msuit >= right_card.msuit)
{
return false;
}
else
{
return true;
}
}
}
bool Card::operator> (const Card& right_card) const
{
if ((*this) < right_card)
{
return false;
}
else
{
return true;
}
}
std::ostream& operator<< (std::ostream &out, const Card& card_to_print)
{
out << "(" << (card_to_print.mrank>=10) << (card_to_print.mrank%10) << "," << card_to_print.msuit << ")";
return out;
}
|
37f39f682af50d1be115080022612de1a48ed446
|
91942c619314962ed3aabce39a2437e40a1096c6
|
/cpp/binarytrees.gpp-9.c++
|
454496c3a19425d904ddb4541a6b93a324d0c5eb
|
[] |
no_license
|
adenzhang/benchmarksgame
|
e545d95bbf6c385da4bf282dce3b7e6c4b2cf093
|
87377a142988d2576cb9289097cb0625f1792e10
|
refs/heads/master
| 2020-03-29T23:50:19.821578
| 2020-02-07T23:00:57
| 2020-02-07T23:00:57
| 150,491,513
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,097
|
binarytrees.gpp-9.c++
|
/* The Computer Language Benchmarks Game
* https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
*
* contributed by Jon Harrop
* modified by Alex Mizrahi
* modified by Andreas Schäfer
* very minor omp tweak by The Anh Tran
* modified to use apr_pools by Dave Compton
* *reset*
*/
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <apr_pools.h>
#include <chrono>
const size_t LINE_SIZE = 64;
class Apr
{
public:
Apr()
{
apr_initialize();
}
~Apr()
{
apr_terminate();
}
};
struct Node
{
Node *l, *r;
int check() const
{
if ( l )
return l->check() + 1 + r->check();
else
return 1;
}
};
class NodePool
{
public:
NodePool()
{
apr_pool_create_unmanaged( &pool );
}
~NodePool()
{
apr_pool_destroy( pool );
}
Node *alloc()
{
return (Node *)apr_palloc( pool, sizeof( Node ) );
}
void clear()
{
apr_pool_clear( pool );
}
private:
apr_pool_t *pool;
};
Node *make( int d, NodePool &store )
{
Node *root = store.alloc();
if ( d > 0 )
{
root->l = make( d - 1, store );
root->r = make( d - 1, store );
}
else
{
root->l = root->r = 0;
}
return root;
}
int main( int argc, char *argv[] )
{
auto tsStart = std::chrono::steady_clock::now();
Apr apr;
int min_depth = 4;
int max_depth = std::max( min_depth + 2, ( argc == 2 ? atoi( argv[1] ) : 10 ) );
int stretch_depth = max_depth + 1;
// Alloc then dealloc stretchdepth tree
{
NodePool store;
Node *c = make( stretch_depth, store );
std::cout << "stretch tree of depth " << stretch_depth << "\t "
<< "check: " << c->check() << std::endl;
}
NodePool long_lived_store;
Node *long_lived_tree = make( max_depth, long_lived_store );
// buffer to store output of each thread
char *outputstr = (char *)malloc( LINE_SIZE * ( max_depth + 1 ) * sizeof( char ) );
#pragma omp parallel for
for ( int d = min_depth; d <= max_depth; d += 2 )
{
int iterations = 1 << ( max_depth - d + min_depth );
int c = 0;
// Create a memory pool for this thread to use.
NodePool store;
for ( int i = 1; i <= iterations; ++i )
{
Node *a = make( d, store );
c += a->check();
store.clear();
}
// each thread write to separate location
sprintf( outputstr + LINE_SIZE * d, "%d\t trees of depth %d\t check: %d\n", iterations, d, c );
}
auto tsStop = std::chrono::steady_clock::now();
// print all results
for ( int d = min_depth; d <= max_depth; d += 2 )
printf( "%s", outputstr + ( d * LINE_SIZE ) );
free( outputstr );
std::cout << "long lived tree of depth " << max_depth << "\t "
<< "check: " << ( long_lived_tree->check() ) << "\n";
std::cout << " -- cpp time(ms): " << ( tsStop - tsStart ).count() / 1000 / 1000 << std::endl;
return 0;
}
|
|
c17f9e58df97263a9e2ed3c540929dd2d683a70a
|
5acf48b516af6ba29cb2208ff47a7491f6fd758e
|
/src/shapes/curve.h
|
822bc1411bf6cc9baae649ef5cc0b1bfcb0be401
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
mmp/pbrt-v3
|
1342e48431beb32dba2abdee17adfe47c5d3c405
|
13d871faae88233b327d04cda24022b8bb0093ee
|
refs/heads/master
| 2023-09-05T13:56:59.387502
| 2023-09-03T11:37:35
| 2023-09-03T11:37:35
| 37,482,419
| 5,006
| 1,494
|
BSD-2-Clause
| 2023-05-18T05:23:46
| 2015-06-15T18:13:08
|
C++
|
UTF-8
|
C++
| false
| false
| 3,458
|
h
|
curve.h
|
/*
pbrt source code is Copyright(c) 1998-2016
Matt Pharr, Greg Humphreys, and Wenzel Jakob.
This file is part of pbrt.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_MSC_VER)
#define NOMINMAX
#pragma once
#endif
#ifndef PBRT_SHAPES_CURVE_H
#define PBRT_SHAPES_CURVE_H
// shapes/curve.h*
#include "shape.h"
namespace pbrt {
struct CurveCommon;
// CurveType Declarations
enum class CurveType { Flat, Cylinder, Ribbon };
// CurveCommon Declarations
struct CurveCommon {
CurveCommon(const Point3f c[4], Float w0, Float w1, CurveType type,
const Normal3f *norm);
const CurveType type;
Point3f cpObj[4];
Float width[2];
Normal3f n[2];
Float normalAngle, invSinNormalAngle;
};
// Curve Declarations
class Curve : public Shape {
public:
// Curve Public Methods
Curve(const Transform *ObjectToWorld, const Transform *WorldToObject,
bool reverseOrientation, const std::shared_ptr<CurveCommon> &common,
Float uMin, Float uMax)
: Shape(ObjectToWorld, WorldToObject, reverseOrientation),
common(common),
uMin(uMin),
uMax(uMax) {}
Bounds3f ObjectBound() const;
bool Intersect(const Ray &ray, Float *tHit, SurfaceInteraction *isect,
bool testAlphaTexture) const;
Float Area() const;
Interaction Sample(const Point2f &u, Float *pdf) const;
private:
// Curve Private Methods
bool recursiveIntersect(const Ray &r, Float *tHit,
SurfaceInteraction *isect, const Point3f cp[4],
const Transform &rayToObject, Float u0, Float u1,
int depth) const;
// Curve Private Data
const std::shared_ptr<CurveCommon> common;
const Float uMin, uMax;
};
std::vector<std::shared_ptr<Shape>> CreateCurveShape(const Transform *o2w,
const Transform *w2o,
bool reverseOrientation,
const ParamSet ¶ms);
} // namespace pbrt
#endif // PBRT_SHAPES_CURVE_H
|
9b18b3932bad3f8f5ab29068e0fb3ddc8270901d
|
52c0949315583ba8898694cceacfaafaeab6f902
|
/test/include/test_util/ssb/star_schema_query.h
|
4a2de4df264757adede832502bf4d8fd3284d0be
|
[
"MIT"
] |
permissive
|
cmu-db/noisepage
|
97093adcc9474419e063fdd97a5aa7a7ea6f3150
|
79276e68fe83322f1249e8a8be96bd63c583ae56
|
refs/heads/master
| 2023-08-29T05:51:04.628704
| 2021-11-05T14:12:08
| 2021-11-05T14:12:08
| 140,325,970
| 1,245
| 287
|
MIT
| 2022-11-08T02:06:48
| 2018-07-09T18:22:34
|
C++
|
UTF-8
|
C++
| false
| false
| 4,094
|
h
|
star_schema_query.h
|
#include <memory>
#include <tuple>
#include "catalog/catalog_accessor.h"
#include "execution/compiler/executable_query.h"
namespace noisepage::ssb {
class SSBQuery {
public:
/// Static functions to generate executable queries for SSB benchmark. Query plans are hard coded.
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ1Part1(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ1Part2(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ1Part3(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ2Part1(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ2Part2(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ2Part3(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ3Part1(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ3Part2(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ3Part3(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ3Part4(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ4Part1(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ4Part2(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
static std::tuple<std::unique_ptr<execution::compiler::ExecutableQuery>, std::unique_ptr<planner::AbstractPlanNode>>
SSBMakeExecutableQ4Part3(const std::unique_ptr<catalog::CatalogAccessor> &accessor,
const execution::exec::ExecutionSettings &exec_settings);
};
} // namespace noisepage::ssb
|
8f099262fc16010ec66d774194dd4a5e93bb16c6
|
74870e1d278f20027ea0213d9d87ee6128a01f65
|
/Q6593 2.cpp
|
643fadfbf0b406f7599719ca2309a85d9440f715
|
[] |
no_license
|
jleun1403/BOJ_CPP
|
795816db9e8a2828ec48aaf9f8da9276d4b0abef
|
415502a8fd7093f469a3b7bf1c5e756505ae0e76
|
refs/heads/master
| 2020-07-10T01:28:42.157301
| 2019-08-24T11:41:03
| 2019-08-24T11:41:03
| 204,131,610
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,098
|
cpp
|
Q6593 2.cpp
|
#include <bits/stdc++.h>
using namespace std;
char a[33][33][33];
int dx[6] = { 0,1,0,-1,0,0 };
int dy[6] = { 1,0,-1,0,0,0 };
int dz[6] = { 0,0,0,0,1,-1 };
int d[31][31][31];
struct Escape{
int x, y, z;
};
queue <Escape> q;
int main(){
while(true){
int n, m, k;
scanf("%d %d %d", &k, &n, &m);
if(n ==0 && m ==0 && k == 0) break;
int endx, endy, endz;
for(int i=0; i<k; i++){
for(int j=0; j<n; j++){
for(int p=0; p<m; p++){
d[i][j][p] = 987654321;
}
}
}
for(int i=0; i<k; i++){
for(int j=0; j<n; j++){
for(int p=0 ; p<m; p++){
scanf(" %c", &a[i][j][p]);
if(a[i][j][p] == 'S'){
d[i][j][p] = 1;
Escape e;
e.z =i;
e.x = j;
e.y = p;
q.push(e);
}
else if (a[i][j][p] == 'E'){
endx = j; endy = p; endz = i;
}
}
}
}
while(!q.empty()){
int z= q.front().z;
int x = q.front().x;
int y= q.front().y;
q.pop();
for(int i=0; i<6; i++){
int nx = x + dx[i];
int ny = y + dy[i];
int nz = z + dz[i];
if(nx <0 || nx >=n || ny <0 || ny >=m || nz <0 || nz >=k) continue;
if(a[nz][nx][ny] != '#'){
if(d[nz][nx][ny] > d[z][x][y] +1){
d[nz][nx][ny] = d[z][x][y] +1;
Escape e;
e.z =nz;
e.x = nx;
e.y = ny;
q.push(e);
}
}
}
}
if(d[endz][endx][endy] == 987654321) printf("Trapped!\n");
else printf("Escaped in %d minute(s).\n", d[endz][endx][endy]-1);
}
return 0;
}
|
689428858c48ee272cec7707a71dcf9d9273fa88
|
b3280d68f0cd655e5237236a3834fadb3915fb6b
|
/hurdle race.cpp
|
85c06731b1c90e19d8b9dc51ddd1e0969f9f391d
|
[] |
no_license
|
shivani1singh/hacktoberfest2021
|
fcbe336de6349534ce2e3ea5829e93007175384e
|
1956b9e369c5d2068b4f3c822869c3504e5b7afa
|
refs/heads/main
| 2023-08-28T13:55:20.505058
| 2021-10-20T13:19:49
| 2021-10-20T13:19:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 249
|
cpp
|
hurdle race.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,k,i,maxd=0;
cin>>n>>k;
int height[n];
for(i=0;i<n;i++)
{
cin>>height[i];
maxd=max(maxd,height[i]);
}
cout<<max(0,maxd-k);
return 0;
}
|
6e91b6d5b70871b5204f3b42aca9811b9e36ad9d
|
c2233581c9fcf627e3958ad351ccee10eb05ea7d
|
/Mini-FSU_Tool/src/product/DCD9500/ChannelSetDialog/ChannelItemWidget/SignalIdsEditDialog.cpp
|
9f93086116ce8ae18bca05303cf5d80520fc3434
|
[] |
no_license
|
caiweijianGZ/Mygit
|
3b796067f99e53440c581f7c20add0a659dd73ed
|
90652195a04e360ed68c03a3d4b6ca8323b52021
|
refs/heads/master
| 2020-04-23T06:51:01.784298
| 2019-02-17T15:04:39
| 2019-02-17T15:04:39
| 170,987,737
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,012
|
cpp
|
SignalIdsEditDialog.cpp
|
#include "SignalIdsEditDialog.h"
#include "ui_SignalIdsEditDialog.h"
SignalIdsEditDialog::SignalIdsEditDialog(QWidget *parent) :
SignalIdsEditDialog(QByteArray() ,parent)
{
}
SignalIdsEditDialog::SignalIdsEditDialog(const QByteArray &src, QWidget *parent) :
QDialog(parent),
ui(new Ui::SignalIdsEditDialog)
{
ui->setupUi(this);
this->setWindowTitle("信号选择");
QStringList headLabels;
//headLabels << "信号标准名" << "信号类型" << "告警时" << "正常时" << "信号说明" << "信号注释" << "信号ID";
headLabels << "信号标准名" << "信号类型" << "告警时" << "正常时" << "信号ID";
ui->tableWidget->setColumnCount(headLabels.count());
ui->tableWidget->setHorizontalHeaderLabels(headLabels);
ui->tableWidget->setColumnHidden(headLabels.count()-1, true);//隐藏信号ID
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);//选行模式
ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);//复选模式
connect(ui->listWidget, SIGNAL(currentRowChanged(int)), this, SLOT(devTypeChangeSlot(int)));
connect(ui->listWidget_2, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(sigRemoveSlot(QModelIndex)));
connect(ui->tableWidget, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(sigSelectSlot(QModelIndex)));
if ( !src.isEmpty() )
{
m_dictCache = src;
this->addDevType2ListWidget(ui->listWidget);
}
}
SignalIdsEditDialog::SignalIdsEditDialog(const QString &ditPath, QWidget *parent)
: SignalIdsEditDialog(QByteArray(), parent)
{
QFile file(ditPath);
if ( file.open(QIODevice::ReadOnly) )
{
m_dictCache = file.readAll();
file.close();
this->addDevType2ListWidget(ui->listWidget);
}
}
SignalIdsEditDialog::SignalIdsEditDialog(const char *ditPath, QWidget *parent)
: SignalIdsEditDialog(QString(ditPath), parent)
{
}
SignalIdsEditDialog::~SignalIdsEditDialog()
{
delete ui;
}
int SignalIdsEditDialog::setSignalList(const QList<uint64_t> &list)
{
this->sigSelectedListDisaplay(list);
m_sigSelectedList = list;
return 0;
}
int SignalIdsEditDialog::getSignalList(QList<uint64_t> &list)
{
list = m_sigSelectedList;
return 0;
}
int SignalIdsEditDialog::addDevType2ListWidget(QListWidget *widget)
{
QJsonParseError jerror;
QJsonDocument jdoc = QJsonDocument::fromJson(m_dictCache, &jerror);
if ( jerror.error != QJsonParseError::NoError )
{
qDebug() << "数据格式错误1-1";
return -1;
}
if ( !jdoc.isObject() )
{
qDebug() << "数据格式错误1-2";
return -1;
}
QJsonObject jobj = jdoc.object();
QJsonArray jarry = jobj.value(DICT_JSON_VALUE_DEVICES).toArray();
for ( int i=0; i<jarry.count(); i++ )
{
jobj = jarry.at(i).toObject();
QString itemName = jobj.value(DICT_JSON_VALUE_NAME).toString();
widget->addItem(itemName);
m_mapRow2DevType.insert(i, jobj.value(DICT_JSON_VALUE_TYPE).toInt());
}
return 0;
}
int SignalIdsEditDialog::addSigInfo2TableWidget(int devType, QTableWidget *widget)
{
QJsonParseError jerror;
QJsonDocument jdoc = QJsonDocument::fromJson(m_dictCache, &jerror);
if ( jerror.error != QJsonParseError::NoError )
{
qDebug() << "数据格式错误1-1";
return -1;
}
if ( !jdoc.isObject() )
{
qDebug() << "数据格式错误1-2";
return -1;
}
QJsonObject jobj = jdoc.object();
QJsonArray devArry = jobj.value(DICT_JSON_VALUE_DEVICES).toArray();
for ( int i=0; i<devArry.count(); i++ )
{
QJsonObject devObj = devArry.at(i).toObject();
if ( devObj.value(DICT_JSON_VALUE_TYPE).toInt() == devType )
{
QJsonArray sigArry = devObj.value(DICT_JSON_VALUE_SIGNALS).toArray();
for ( int j=0; j<sigArry.count(); j++ )
{
this->appendSigInfo2Table(sigArry.at(j).toObject(), widget);
}
}
}
return 0;
}
int SignalIdsEditDialog::appendSigInfo2Table(const QJsonObject &obj, QTableWidget *tableWidget)
{
int insertIndex = (0 == tableWidget->rowCount()) ? 0 : tableWidget->rowCount();
tableWidget->insertRow(insertIndex);
int rowIndex = tableWidget->rowCount() - 1;
for ( int i=0; i<tableWidget->columnCount(); i++ )
{
tableWidget->setItem(rowIndex, i, new QTableWidgetItem());
}
ui->tableWidget->item(rowIndex, 0)->setText(obj.value(DICT_JSON_VALUE_SIGNAME).toString());
ui->tableWidget->item(rowIndex, 1)->setText(mapChnSigTypes.value(obj.value(DICT_JSON_VALUE_TYPE).toInt()));
ui->tableWidget->item(rowIndex, 2)->setText(obj.value(DICT_JSON_VALUE_ALMMSG).toString());
ui->tableWidget->item(rowIndex, 3)->setText(obj.value(DICT_JSON_VALUE_NORMSG).toString());
//ui->tableWidget->item(rowIndex, 4)->setText("");
//ui->tableWidget->item(rowIndex, 5)->setText("");
ui->tableWidget->item(rowIndex, 4)->setText(QString::number(obj.value(DICT_JSON_VALUE_ID).toInt()));
return 0;
}
int SignalIdsEditDialog::sigSelectedListDisaplay(const QList<uint64_t> &list)
{
QJsonParseError jerror;
QJsonDocument jdoc = QJsonDocument::fromJson(m_dictCache, &jerror);
if ( jerror.error != QJsonParseError::NoError )
{
qDebug() << "数据格式错误1-1";
return -1;
}
if ( !jdoc.isObject() )
{
qDebug() << "数据格式错误1-2";
return -1;
}
QJsonObject jobj = jdoc.object();
QJsonArray devArry = jobj.value(DICT_JSON_VALUE_DEVICES).toArray();
for ( int i=0; i<devArry.count(); i++ )
{
QJsonObject devObj = devArry.at(i).toObject();
QJsonArray sigArry = devObj.value(DICT_JSON_VALUE_SIGNALS).toArray();
for ( int j=0; j<sigArry.count(); j++ )
{
QJsonObject sigObj = sigArry.at(j).toObject();
uint64_t sigId = sigObj.value(DICT_JSON_VALUE_ID).toInt();
QString sigName = sigObj.value(DICT_JSON_VALUE_SIGNAME).toString();
if ( list.contains(sigId) )
{
ui->listWidget_2->addItem(sigName);
}
}
}
return 0;
}
int SignalIdsEditDialog::addSigInfo2SelectedList(int row)
{
QString sigName = ui->tableWidget->item(row, 0)->text();
uint64_t sigId = ui->tableWidget->item(row, ui->tableWidget->columnCount()-1)->text().toULongLong();
if ( m_sigSelectedList.contains(sigId) )
{
return -1;
}
int listRow = ui->listWidget_2->count();
ui->listWidget_2->insertItem(listRow, sigName);
m_sigSelectedList.append(sigId);
return 0;
}
int SignalIdsEditDialog::removeRowAtSelectedList(int row)
{
m_sigSelectedList.removeAt(row);
QListWidgetItem *item = ui->listWidget_2->takeItem(row);
delete item;
return 0;
}
void SignalIdsEditDialog::devTypeChangeSlot(int rowIndex)
{
ui->tableWidget->clearContents();
ui->tableWidget->setRowCount(0);
this->addSigInfo2TableWidget(m_mapRow2DevType.value(rowIndex), ui->tableWidget);
ui->label_2->setText(ui->listWidget->currentItem()->text());
}
void SignalIdsEditDialog::sigSelectSlot(QModelIndex index)
{
this->addSigInfo2SelectedList(index.row());
}
void SignalIdsEditDialog::sigRemoveSlot(QModelIndex index)
{
this->removeRowAtSelectedList(index.row());
}
void SignalIdsEditDialog::on_pushButton_2_clicked()
{
this->close();
}
void SignalIdsEditDialog::on_pushButton_clicked()
{
this->accept();
}
void SignalIdsEditDialog::on_pushButton_3_clicked()
{
static int s_lastSearchLine = 0;
static QString s_lastSearchText;
QString searchText = ui->lineEdit->text();
if ( searchText.isEmpty() )
{
return;
}
int rowCount = ui->tableWidget->rowCount();
int rowStartIndex = 0;
//从上一次查找行的下一行开始找
if ( s_lastSearchText == searchText )
{
rowStartIndex = (s_lastSearchLine == ui->tableWidget->currentRow()) ? s_lastSearchLine + 1 : 0;
}
for ( int i=0,j=rowStartIndex; i<rowCount; i++,j++ )
{
j = ( j < rowCount ) ? j : (rowCount - j);
if ( ui->tableWidget->item(j, 0)->text().contains(searchText) )
{
ui->tableWidget->item(j, 0)->setSelected(true);
ui->tableWidget->selectRow(j);
s_lastSearchLine = j;//保存上次搜索结果
s_lastSearchText = searchText;
break;
}
}
}
void SignalIdsEditDialog::on_pushButton_4_clicked()
{
if ( ui->tableWidget->selectedItems().count() <= 0 )
{
return;
}
this->addSigInfo2SelectedList(ui->tableWidget->currentRow());
}
void SignalIdsEditDialog::on_pushButton_5_clicked()
{
if ( ui->listWidget_2->selectedItems().count() <= 0 )
{
return;
}
this->removeRowAtSelectedList(ui->listWidget_2->currentRow());
}
|
224d4cbd5dd51ef9a4b2052eaab476c823b144a5
|
b6f3cdbe8de6142f48ea5b6a0ef4a118bf300c15
|
/FractalTree-master/FractalTree/Src/Server/UDPServer.h
|
5ea1117e5772f1be7bd0a277bf5826fab89344ed
|
[] |
no_license
|
jwang320/Engine
|
182042cc2b5ea8bb71fe45022296aa00dbbc4e13
|
5fe1d23fc695f5b43f5a484297b6448c5a446f5a
|
refs/heads/master
| 2023-01-01T12:25:18.545583
| 2020-10-28T00:45:05
| 2020-10-28T00:45:05
| 307,857,598
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 741
|
h
|
UDPServer.h
|
#pragma once
#include <queue>
#include "Network\UDPNetworkBase.h"
namespace Network
{
class Client;
class UDPServer : public UDPNetworkBase
{
private:
std::map<std::string, Client*> clients;
protected:
std::string port;
public:
UDPServer(const std::string& port);
void Update();
int SendPacketToClients(const char* data, int dataLength) const;
Client* CreateClient(const Packet& receivedPacket);
//returns NULL if no client exists with the address
Client* getClient(const std::string& clientIPAddress);
protected:
virtual void initialize() override;
virtual bool initializeServerSocket() override;
virtual bool handlePacket(const Packet& packet) override;
private:
void AddClient(Client* client);
};
}
|
9100804b0347b24f4b8867f8898e39baf09ac58e
|
b146c1380315515ad4c388231325294c5902c70f
|
/testGenerator.h
|
ccd01f0dd7995036ad4dfa6efc1964e23c442132
|
[] |
no_license
|
edgarshmavonyan/mergeable_heaps
|
4eda51f0c8dc30943fee1bd0ce648eff2486eabf
|
3422a9ca000fec4437d32f1657bb01e3b85b3f3f
|
refs/heads/master
| 2021-08-30T10:58:03.762295
| 2017-12-17T15:44:42
| 2017-12-17T15:44:42
| 113,308,343
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,342
|
h
|
testGenerator.h
|
#include <random>
#include <vector>
#include "heaplist.h"
void generateSomeValues(size_t size, std::vector<int>& arr) {
std::mt19937 generator(time(0));
arr.resize(size);
for (size_t i = 0; i < size; i++)
arr[i] = generator();
}
void generateHeapOrder(int size, int heapNumber, std::vector<int>& order) {
order.resize(size);
std::mt19937 generator(time(0));
for (int i = 0; i < size; i++)
order[i] = (generator() % heapNumber + heapNumber) % heapNumber;
}
void generateHeaps(int size, int heapNumber, HeapList& heaps, std::vector<int>& order, std::vector<int>& values) {
for (int i = 0; i < std::min(heapNumber, size); i++)
heaps.AddHeap(values[i]);
for (int i = std::min(heapNumber, size); i < size; i++)
heaps.Insert(order[i], values[i]);
}
void generateTestSequences(int heapNumber, int number, std::vector<std::pair<int, std::pair<int, int> > >& seq) {
std::mt19937 generator(time(0));
seq.resize(number);
for (int i = 0; i < number; i++) {
int type = (generator() % 3 + 3) % 3;
seq[i].first = type;
int first = (generator() % heapNumber + heapNumber) % heapNumber;
int second = (generator() % heapNumber + heapNumber) % heapNumber;
seq[i].second.first = first;
seq[i].second.second = second;
}
}
|
80ff50820c4dfa8a8ecb0b30f1f539f644fdb4e0
|
d93fae13dd5019f9ddf89bd91c17893ccb832abd
|
/map.h
|
ebda9754dd8397d2612609841126cc3e1a79c9b9
|
[] |
no_license
|
tren97/No-Name-RPG
|
bdcd42240e0cee290c7a9793e68213a85d3d197e
|
215d9707b8149fffe7991dc32337096448b976d3
|
refs/heads/master
| 2020-04-24T00:33:18.372895
| 2019-02-20T19:21:53
| 2019-02-20T19:21:53
| 171,569,981
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,965
|
h
|
map.h
|
#include <iostream>
#include <vector>
#include "move.h"
using namespace std;
//variables describing the characters used in the map below
const char PLAYER = 'X';
const char MONSTER = 'M';
const char TREASURE = 'T';
const char WALL = '#';
const int REWARD = 25;
const int LOOTREWARD = 10;
bool on_monster = false;
bool on_treasure = false;
//cool string color jazz
const string blue ("\033[1;34m");
const string reset ("\033[0m");
const string red ("\033[1;31m");
const string yellow ("\033[1;33m");
const string grey ("\033[0;37m");
const string green ("\033[1;32m");
const string cyan("\033[1;36m");
//vector holding the whole map
vector<string> map = {
"|----------------------------------|",
"| M|",
"| # '''''' |",
"| M # ''''''''''' |",
"|T # '''''''''''' |",
"|##### '''''''''''' |",
"| '''''''''' |",
"| '''''''' |",
"| '''' |",
"| |",
"| |",
"| M |",
"| |",
"| '''''''' |",
"| ''''''''''' |",
"| ''''''''''''' |",
"| '''''''''''' #######|",
"| '''''''''''' # |",
"| ''''''''' # M |",
"|M # T |",
"|----------------------------------|"
};
//prints the map created above
void print_map(Move cur = {}) {
for (unsigned int i = 0; i < map.size(); i++) {
for (unsigned int j = 0; j < map.at(i).size(); j++) {
if (cur.row != 0 && cur.column != 0 && cur.column != map.at(i).size()-1 && cur.row != map.size() && i == cur.row && j == cur.column) cout << cyan << PLAYER << reset;
else if (map.at(i).at(j) == '\'') {
cout << blue << map.at(i).at(j) << reset;
}
else if (map.at(i).at(j) == 'M'){
cout << red << map.at(i).at(j) << reset;
}
else if (map.at(i).at(j) == 'T'){
cout << yellow << map.at(i).at(j) << reset;
}
else if (map.at(i).at(j) == '#'){
cout << grey << map.at(i).at(j) << reset;
}
else cout << green << map.at(i).at(j) <<reset;
}
cout << endl;
}
}
//Checks to see if a spot is able to walk on
//Returns true if space is empty, a monster, or treasure
bool check_map(Move test, char test_char = ' ') {
if (map.at(test.row).at(test.column) == test_char || map.at(test.row).at(test.column) == TREASURE || map.at(test.row).at(test.column) == MONSTER) {
// checks to see if player has encountered a monster
if (map.at(test.row).at(test.column) == MONSTER) {
map.at(test.row).at(test.column) = ' ';
on_monster = true;
}
//checks to see if player has encountered treasure
if (map.at(test.row).at(test.column) == TREASURE) {
map.at(test.row).at(test.column) = ' ';
on_treasure = true;
}
return true;
}
return false;
}
|
d1f5f1265660b868c80304cac14b5b480be8db51
|
b2d1f5d7637a2c2e7f9c8037748fabacf410c3a1
|
/random.h
|
33b84f401385798caad9da496ec9528b26b6e406
|
[] |
no_license
|
Mortal/opt
|
51a68862110e0d77d12295f5a9a04268cbef7137
|
44e104c042bec496c1eb470677e9bf03a5495457
|
refs/heads/master
| 2021-01-20T10:38:51.040480
| 2012-03-24T20:28:49
| 2012-03-24T20:44:47
| 3,451,936
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 939
|
h
|
random.h
|
#ifndef __RANDOM_H__
#define __RANDOM_H__
#include <vector>
#include <boost/random.hpp>
struct randutil {
inline randutil(uint32_t seed) : random_source(seed) {
}
inline randutil() {
}
boost::mt19937 random_source;
template <typename IT>
void shuffle(IT begin, IT end) {
const int n = end-begin;
for (int i = n; i--;) {
std::iter_swap(begin+i, begin+rand_less_than(i+1));
}
}
int rand_less_than(int bound) {
boost::uniform_smallint<> dist(0,bound-1);
boost::variate_generator<boost::mt19937&, boost::uniform_smallint<> > rng(random_source, dist);
return rng();
}
bool flip_coin() {
boost::uniform_smallint<> dist(0,1);
return dist(random_source);
}
std::vector<char> random_mask(int m, int n) {
std::vector<char> mask(n, 0);
std::fill(mask.begin(), mask.begin()+m, 1);
shuffle(mask.begin(), mask.end());
return mask;
}
};
#endif // __RANDOM_H__
// vim: set sw=4 sts=4 ts=8 noet:
|
79a3598c58cf82db286645290a6646b2a75b951b
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/httpd/gumtree/httpd_new_log_4653.cpp
|
f8e5fbbf0535c91ae5ff6360391761d7b692caa0
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 176
|
cpp
|
httpd_new_log_4653.cpp
|
ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01888)
"Init: Failed to load Crypto Device API `%s'",
mc->szCryptoDevice);
|
23237ebe2b7f218d961d62442d8840c1e3dc1756
|
f21698a712ae2fde47e76acd6577e188bef84c49
|
/tests/MaximumAPosterioriTest.cpp
|
816f3ba4416ce9d6206ec29b4c5ef8e7c64ba8fa
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
agiger/GPR
|
295e8e2cb6abd90a0f9203088229d6eecdd4b748
|
e191cba96c281d9e69ec44fb6998b5d6ca3f3042
|
refs/heads/master
| 2021-06-24T23:40:36.693792
| 2020-11-01T17:13:36
| 2020-11-01T17:13:36
| 139,864,868
| 0
| 0
| null | 2018-07-05T14:58:23
| 2018-07-05T14:58:22
| null |
UTF-8
|
C++
| false
| false
| 21,159
|
cpp
|
MaximumAPosterioriTest.cpp
|
/*
* Copyright 2015 Christoph Jud (christoph.jud@unibas.ch)
*
* 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 <iostream>
#include <memory>
#include <ctime>
#include <cmath>
#include <vector>
#include <Eigen/Dense>
#include <unsupported/Eigen/FFT>
#include <boost/random.hpp>
#include "GaussianProcess.h"
#include "Kernel.h"
#include "Likelihood.h"
#include "LikelihoodUtils.h"
#include "Prior.h"
#include "MatrixIO.h"
// typedefinitions
typedef gpr::Kernel<double> KernelType;
typedef std::shared_ptr<KernelType> KernelTypePointer;
typedef gpr::WhiteKernel<double> WhiteKernelType;
typedef std::shared_ptr<WhiteKernelType> WhiteKernelTypePointer;
typedef gpr::GaussianKernel<double> GaussianKernelType;
typedef std::shared_ptr<GaussianKernelType> GaussianKernelTypePointer;
typedef gpr::PeriodicKernel<double> PeriodicKernelType;
typedef std::shared_ptr<PeriodicKernelType> PeriodicKernelTypePointer;
typedef gpr::SumKernel<double> SumKernelType;
typedef std::shared_ptr<SumKernelType> SumKernelTypePointer;
typedef gpr::GaussianProcess<double> GaussianProcessType;
typedef std::shared_ptr<GaussianProcessType> GaussianProcessTypePointer;
void Test1(){
/*
* Test 1: perform maximum aposteriori
*/
std::cout << "Test 1: maximum log gaussian likelihood + log gaussian prior (gradient descent)... " << std::flush;
typedef GaussianProcessType::VectorType VectorType;
typedef GaussianProcessType::MatrixType MatrixType;
// generating a signal
// ground truth periodic variable
//auto f = [](double x)->double { return std::sin(x)*std::cos(2.2*std::sin(x)); };
auto f = [](double x)->double { return x+10*std::sin(x); };
double val = 0;
unsigned n = 70;
double upper = 30;
MatrixType signal = MatrixType::Zero(2,n);
for(unsigned i=0; i<n; i++){
signal(0,i) = val;
signal(1,i) = f(val);
val += upper/n;
}
// build Gaussian process and add the 1D samples
WhiteKernelTypePointer pk(new WhiteKernelType(0)); // dummy kernel
GaussianProcessTypePointer gp(new GaussianProcessType(pk));
gp->SetSigma(0.01); // zero since with the white kernel (see later) this is considered
for(unsigned i=0; i<n; i++){
VectorType x = VectorType::Zero(1); x[0] = signal(0,i);
VectorType y = VectorType::Zero(1); y[0] = signal(1,i);
gp->AddSample(x,y);
}
bool cout = false;
double p_sigma = 1;
double p_sigma_variance = 1;
double p_scale = 10;
double p_scale_variance = 1;
double p_period = 6.3;
double p_period_variance = 2;
double g_sigma = 100;
double g_sigma_variance = 20;
double g_scale = 60;
double g_scale_variance = 30;
// construct Gaussian log likelihood
typedef gpr::GaussianLogLikelihood<double> GaussianLogLikelihoodType;
typedef std::shared_ptr<GaussianLogLikelihoodType> GaussianLogLikelihoodTypePointer;
GaussianLogLikelihoodTypePointer gl(new GaussianLogLikelihoodType());
// construct Gaussian priors
typedef gpr::GaussianDensity<double> GaussianDensityType;
typedef std::shared_ptr<GaussianDensityType> GaussianDensityTypePointer;
typedef gpr::InverseGaussianDensity<long double> InverseGaussianDensityType;
typedef std::shared_ptr<InverseGaussianDensityType> InverseGaussianDensityTypePointer;
std::vector<InverseGaussianDensityTypePointer> g_densities;
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(p_scale, p_scale_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(p_period, p_period_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(p_sigma, p_sigma_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(g_sigma, g_sigma_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(g_scale, g_scale_variance))));
if(cout){
for(auto p : g_densities){
std::cout << "mode : " << p->mode() << ", variance: " << p->variance() << std::endl;
}
}
double lambda = 1e-6;
double w = 0.8; // weighting of w*likelihood resp. (1-w)*prior
for(unsigned i=0; i<100; i++){
// analytical
try{
PeriodicKernelTypePointer pk(new PeriodicKernelType(p_scale, M_PI/p_period, p_sigma));
GaussianKernelTypePointer gk(new GaussianKernelType(g_sigma, g_scale));
SumKernelTypePointer sk(new SumKernelType(pk,gk));
gp->SetKernel(sk);
gp->SetSigma(0.1);
//gp->DebugOn();
GaussianLogLikelihoodType::ValueDerivativePair lp = gl->GetValueAndParameterDerivatives(gp);
VectorType likelihood = lp.first;
VectorType likelihood_gradient = lp.second;
double prior = 0;
prior += g_densities[0]->log(p_scale);
prior += g_densities[1]->log(p_period);
prior += g_densities[2]->log(p_sigma);
prior += g_densities[3]->log(g_sigma);
prior += g_densities[4]->log(g_scale);
double posterior = -2*(w*likelihood[0]+(1-w)*prior);
MatrixType J = MatrixType::Zero(1,g_densities.size());
//std::cout << likelihood_gradient << std::endl;
J(0,0) = 2*(w*likelihood_gradient[0] + (1-w)*g_densities[0]->GetLogDerivative(p_scale));
J(0,1) = 2*(w*likelihood_gradient[1] + (1-w)*g_densities[1]->GetLogDerivative(p_period));
J(0,2) = 2*(w*likelihood_gradient[2] + (1-w)*g_densities[2]->GetLogDerivative(p_sigma));
J(0,3) = 2*(w*likelihood_gradient[3] + (1-w)*g_densities[3]->GetLogDerivative(g_sigma));
J(0,4) = 2*(w*likelihood_gradient[4] + (1-w)*g_densities[4]->GetLogDerivative(g_scale));
VectorType update = lambda * gpr::pinv<MatrixType>(J.adjoint()*J)*J.adjoint();
if(cout){
std::cout << i << ": likelihood: " << likelihood[0] << ", prior: " << prior << ", posterior: " << posterior;
std::cout << ", scale/period/sigma: " << p_scale << "/" << p_period << "/" << p_sigma << ", sigma/scale: " << g_sigma << "/" << g_scale;
std::cout << ", update: " << update.adjoint() << std::endl;
}
p_scale -= update[0] * posterior;
p_period -= update[1] * posterior;
p_sigma -= update[2] * posterior;
g_sigma -= update[3] * posterior;
g_scale -= update[4] * posterior;
if(p_scale < std::numeric_limits<double>::min()) p_scale = std::numeric_limits<double>::min();
if(p_period < std::numeric_limits<double>::min()) p_period = std::numeric_limits<double>::min();
if(p_sigma < std::numeric_limits<double>::min()) p_sigma = std::numeric_limits<double>::min();
if(g_sigma < std::numeric_limits<double>::min()) g_sigma = std::numeric_limits<double>::min();
if(g_scale < std::numeric_limits<double>::min()) g_scale = std::numeric_limits<double>::min();
}
catch(std::string& s){
std::cout << "[failed] " << s << std::flush;
std::cout << ", scale/period/sigma: " << p_scale << "/" << p_period << "/" << p_sigma << ", sigma/scale: " << g_sigma << "/" << g_scale << std::endl;
return;
}
}
std::vector<double> prediction_y;
std::vector<double> prediction_x;
// predict some stuff:
for(unsigned i=0; i<n; i++){
VectorType x = VectorType::Zero(1); x[0] = signal(0,i);
prediction_y.push_back(gp->Predict(x)[0]);
prediction_x.push_back(signal(0,i));
}
double err = 0;
for(unsigned i=0; i<prediction_x.size(); i++ ){
err += std::abs(prediction_y[i]-signal(1,i));
}
if(err/prediction_x.size() < 0.5){
std::cout << "[passed]" << std::endl;
}
else{
std::stringstream ss; ss<<err/prediction_x.size(); throw ss.str();
}
}
void Test2(){
/*
* Test 1: perform maximum aposteriori
*/
std::cout << "Test 2: maximum log gaussian likelihood + log gaussian prior (gradient descent, only period length)... " << std::flush;
typedef GaussianProcessType::VectorType VectorType;
typedef GaussianProcessType::MatrixType MatrixType;
// generating a signal
// ground truth periodic variable
//auto f = [](double x)->double { return std::sin(x)*std::cos(2.2*std::sin(x)); };
auto f = [](double x)->double { return x+10*std::sin(x); };
double val = 0;
unsigned n = 70;
double upper = 30;
MatrixType signal = MatrixType::Zero(2,n);
for(unsigned i=0; i<n; i++){
signal(0,i) = val;
signal(1,i) = f(val);
val += upper/n;
}
// build Gaussian process and add the 1D samples
WhiteKernelTypePointer pk(new WhiteKernelType(0)); // dummy kernel
GaussianProcessTypePointer gp(new GaussianProcessType(pk));
gp->SetSigma(0.01); // zero since with the white kernel (see later) this is considered
for(unsigned i=0; i<n; i++){
VectorType x = VectorType::Zero(1); x[0] = signal(0,i);
VectorType y = VectorType::Zero(1); y[0] = signal(1,i);
gp->AddSample(x,y);
}
bool cout = false;
double p_sigma = 1;
double p_sigma_variance = 1;
double p_scale = 10;
double p_scale_variance = 1;
double p_period = 5;// should be 6.3
double p_period_variance = 2;
double g_sigma = 100;
double g_sigma_variance = 20;
double g_scale = 60;
double g_scale_variance = 30;
// construct Gaussian log likelihood
typedef gpr::GaussianLogLikelihood<double> GaussianLogLikelihoodType;
typedef std::shared_ptr<GaussianLogLikelihoodType> GaussianLogLikelihoodTypePointer;
GaussianLogLikelihoodTypePointer gl(new GaussianLogLikelihoodType());
// construct Gaussian priors
typedef gpr::GaussianDensity<double> GaussianDensityType;
typedef std::shared_ptr<GaussianDensityType> GaussianDensityTypePointer;
typedef gpr::InverseGaussianDensity<long double> InverseGaussianDensityType;
typedef std::shared_ptr<InverseGaussianDensityType> InverseGaussianDensityTypePointer;
std::vector<InverseGaussianDensityTypePointer> g_densities;
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(p_scale, p_scale_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(p_period, p_period_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(p_sigma, p_sigma_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(g_sigma, g_sigma_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(g_scale, g_scale_variance))));
if(cout){
for(auto p : g_densities){
std::cout << "mode : " << p->mode() << ", variance: " << p->variance() << std::endl;
}
}
double w = 0.5; // weighting of w*likelihood resp. (1-w)*prior
for(unsigned i=0; i<100; i++){
// analytical
try{
PeriodicKernelTypePointer pk(new PeriodicKernelType(p_scale, M_PI/p_period, p_sigma));
GaussianKernelTypePointer gk(new GaussianKernelType(g_sigma, g_scale));
SumKernelTypePointer sk(new SumKernelType(pk,gk));
gp->SetKernel(sk);
gp->SetSigma(0.1);
//gp->DebugOn();
GaussianLogLikelihoodType::ValueDerivativePair lp = gl->GetValueAndParameterDerivatives(gp);
VectorType likelihood = lp.first;
VectorType likelihood_gradient = lp.second;
double prior = 0;
prior += g_densities[0]->log(p_scale);
prior += g_densities[1]->log(p_period);
prior += g_densities[2]->log(p_sigma);
prior += g_densities[3]->log(g_sigma);
prior += g_densities[4]->log(g_scale);
double posterior = -2*(w*likelihood[0]+(1-w)*prior);
double p_dev = 2*(w*likelihood_gradient[1] + (1-w)*g_densities[1]->GetLogDerivative(p_period));
if(cout){
std::cout << i << ": likelihood: " << likelihood[0] << ", prior: " << prior << ", posterior: " << posterior;
std::cout << ", scale/period/sigma: " << p_scale << "/" << p_period << "/" << p_sigma << ", sigma/scale: " << g_sigma << "/" << g_scale << std::endl;
}
p_period -= posterior/p_dev;
if(p_period < std::numeric_limits<double>::min()) p_period = std::numeric_limits<double>::min();
}
catch(std::string& s){
std::cout << "[failed] " << s << std::endl;
std::cout << ", scale/period/sigma: " << p_scale << "/" << p_period << "/" << p_sigma << ", sigma/scale: " << g_sigma << "/" << g_scale << std::endl;
return;
}
}
std::vector<double> prediction_y;
std::vector<double> prediction_x;
// predict some stuff:
for(unsigned i=0; i<n; i++){
VectorType x = VectorType::Zero(1); x[0] = signal(0,i);
prediction_y.push_back(gp->Predict(x)[0]);
prediction_x.push_back(signal(0,i));
}
double err = 0;
for(unsigned i=0; i<prediction_x.size(); i++ ){
err += std::abs(prediction_y[i]-signal(1,i));
}
if(err/prediction_x.size() < 0.1){
std::cout << "[passed]" << std::endl;
}
else{
std::stringstream ss; ss<<err/prediction_x.size(); throw ss.str();
}
}
void Test3(){
/*
* Test 3: perform maximum aposteriori
*/
std::cout << "Test 3: maximum log gaussian likelihood + log gaussian prior (gradient descent only sigma)... " << std::flush;
typedef GaussianProcessType::VectorType VectorType;
typedef GaussianProcessType::MatrixType MatrixType;
// generating a signal
// ground truth periodic variable
//auto f = [](double x)->double { return std::sin(x)*std::cos(2.2*std::sin(x)); };
auto f = [](double x)->double { return x+10*std::sin(x); };
double val = 0;
unsigned n = 30;
double upper = 30;
MatrixType signal = MatrixType::Zero(2,n);
for(unsigned i=0; i<n; i++){
signal(0,i) = val;
signal(1,i) = f(val);
val += upper/n;
}
// build Gaussian process and add the 1D samples
WhiteKernelTypePointer pk(new WhiteKernelType(0)); // dummy kernel
GaussianProcessTypePointer gp(new GaussianProcessType(pk));
gp->SetSigma(0.01); // zero since with the white kernel (see later) this is considered
for(unsigned i=0; i<n; i++){
VectorType x = VectorType::Zero(1); x[0] = signal(0,i);
VectorType y = VectorType::Zero(1); y[0] = signal(1,i);
gp->AddSample(x,y);
}
bool cout = false;
double p_sigma = 0.5;
double p_sigma_variance = 3;
double p_scale = 10;
double p_scale_variance = 1;
double p_period = 6.3;
double p_period_variance = 2;
double g_sigma = 100;
double g_sigma_variance = 20;
double g_scale = 60;
double g_scale_variance = 30;
// construct Gaussian log likelihood
typedef gpr::GaussianLogLikelihood<double> GaussianLogLikelihoodType;
typedef std::shared_ptr<GaussianLogLikelihoodType> GaussianLogLikelihoodTypePointer;
GaussianLogLikelihoodTypePointer gl(new GaussianLogLikelihoodType());
// construct Gaussian priors
typedef gpr::GaussianDensity<double> GaussianDensityType;
typedef std::shared_ptr<GaussianDensityType> GaussianDensityTypePointer;
typedef gpr::InverseGaussianDensity<long double> InverseGaussianDensityType;
typedef std::shared_ptr<InverseGaussianDensityType> InverseGaussianDensityTypePointer;
std::vector<InverseGaussianDensityTypePointer> g_densities;
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(p_scale, p_scale_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(p_period, p_period_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(p_sigma, p_sigma_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(g_sigma, g_sigma_variance))));
g_densities.push_back(InverseGaussianDensityTypePointer( new InverseGaussianDensityType(InverseGaussianDensityType::GetMeanAndLambda(g_scale, g_scale_variance))));
if(cout){
for(auto p : g_densities){
std::cout << "mode : " << p->mode() << ", variance: " << p->variance() << std::endl;
}
}
double lambda = 1e-2;
double w = 0.9; // weighting of w*likelihood resp. (1-w)*prior
for(unsigned i=0; i<500; i++){
// analytical
try{
PeriodicKernelTypePointer pk(new PeriodicKernelType(p_scale, M_PI/p_period, p_sigma));
GaussianKernelTypePointer gk(new GaussianKernelType(g_sigma, g_scale));
SumKernelTypePointer sk(new SumKernelType(pk,gk));
gp->SetKernel(sk);
gp->SetSigma(0.1);
//gp->DebugOn();
GaussianLogLikelihoodType::ValueDerivativePair lp = gl->GetValueAndParameterDerivatives(gp);
VectorType likelihood = lp.first;
VectorType likelihood_gradient = lp.second;
double prior = 0;
prior += g_densities[0]->log(p_scale);
prior += g_densities[1]->log(p_period);
prior += g_densities[2]->log(p_sigma);
prior += g_densities[3]->log(g_sigma);
prior += g_densities[4]->log(g_scale);
double posterior = -2*(w*likelihood[0]+(1-w)*prior);
double p_dev = g_densities[2]->GetLogDerivative(p_sigma);
if(p_dev==0) break;
double update;
if(posterior/p_dev>0){
update = std::log(1+posterior/p_dev);
}
else{
update = -std::log(1+std::fabs(posterior/p_dev));
}
if(cout){
std::cout << i << ": likelihood: " << likelihood[0] << ", prior: " << prior << ", posterior: " << posterior;
std::cout << ", scale/period/sigma: " << p_scale << "/" << p_period << "/" << p_sigma << ", sigma/scale: " << g_sigma << "/" << g_scale;
std::cout << ", gradient p_sigma: " << p_dev << ", update " << update << std::endl;
}
p_sigma -= lambda*update;
if(p_sigma < std::numeric_limits<double>::min()) p_sigma = std::numeric_limits<double>::min();
}
catch(std::string& s){
std::cout << "[failed] " << s << std::flush;
std::cout << ", scale/period/sigma: " << p_scale << "/" << p_period << "/" << p_sigma << ", sigma/scale: " << g_sigma << "/" << g_scale << std::endl;
return;
}
}
std::vector<double> prediction_y;
std::vector<double> prediction_x;
// predict some stuff:
for(unsigned i=0; i<n; i++){
VectorType x = VectorType::Zero(1); x[0] = signal(0,i);
prediction_y.push_back(gp->Predict(x)[0]);
prediction_x.push_back(signal(0,i));
}
double err = 0;
for(unsigned i=0; i<prediction_x.size(); i++ ){
err += std::abs(prediction_y[i]-signal(1,i));
}
if(err/prediction_x.size() < 0.5){
std::cout << "[passed]" << std::endl;
}
else{
std::stringstream ss; ss<<err/prediction_x.size(); throw ss.str();
}
}
int main (int argc, char *argv[]){
std::cout << "Gaussian likelihood kernel test: " << std::endl;
try{
Test1();
Test2();
Test3();
}
catch(std::string& s){
std::cout << "[failed] Error: " << s << std::endl;
return -1;
}
return 0;
}
|
cdb91c7cf5e573f2bc7b6e951400322de0542673
|
ea7808e80a7febe6c758138f57e8525c754a3990
|
/Assignments/Assignment 5: Priority Queue/Assignment 5/src/VectorPQueue.cpp
|
a7603b65b38d63310ca189d639b09d127ff59308
|
[] |
no_license
|
wenxinxu/CS106B-Programming-Abstractions-In-Cpp
|
cd1ddca45920efe6783f5484b55c2c53b5886cc6
|
11684d6492600ab82bce1d672a2ead6b072379db
|
refs/heads/master
| 2020-09-29T06:30:07.144228
| 2019-12-04T12:09:42
| 2019-12-04T12:09:42
| 226,975,795
| 0
| 1
| null | 2019-12-09T21:57:21
| 2019-12-09T21:57:20
| null |
UTF-8
|
C++
| false
| false
| 1,335
|
cpp
|
VectorPQueue.cpp
|
/*************************************************************
* File: VectorPQueue.cpp
*
* Implementation file for the VectorPriorityQueue
* class.
*/
#include "VectorPQueue.h"
#include "error.h"
using namespace std;
VectorPriorityQueue::VectorPriorityQueue() {
// TODO: Fill this in!
}
VectorPriorityQueue::~VectorPriorityQueue() {
// TODO: Fill this in!
}
int VectorPriorityQueue::size() const {
// TODO: Fill this in!
cout << elems.size() << endl;
return elems.size();
}
bool VectorPriorityQueue::isEmpty() const {
// TODO: Fill this in!
return elems.empty();
}
void VectorPriorityQueue::enqueue(const string& value) {
// TODO: Fill this in!
elems.push_back(value);
}
string VectorPriorityQueue::peek() const {
// TODO: Fill this in!
if (isEmpty())
error("This Queue is empty!");
std::string alphabetFirst = *elems.begin();
for (int i = 0; i < elems.size(); ++i) {
if (elems[i] < alphabetFirst)
alphabetFirst = elems[i];
}
return alphabetFirst;
}
string VectorPriorityQueue::dequeueMin() {
// TODO: Fill this in!
std::string alphabetFirst = peek();
int id;
for (int i = 0; i < elems.size(); ++i) {
if (elems[i] == alphabetFirst)
id = i;
}
elems.erase(elems.begin() + id);
return alphabetFirst;
}
|
02137df61a8d9ee1fb95c2bb1bbeb52e953276c6
|
98ec42398374ef91666550255e4958be69820cae
|
/tests/hash_test.cpp
|
d0306855183315036a3540cac22fda9a749562a2
|
[
"LicenseRef-scancode-public-domain-disclaimer"
] |
permissive
|
Zabrane/emilib
|
fde23b7e00f345db7c8a9b4e5b390f686885eff6
|
0d90f4c0cd44813f6898b417bf3f4ef574a5b136
|
refs/heads/master
| 2022-04-23T10:52:29.257760
| 2020-04-23T10:13:57
| 2020-04-23T10:13:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,785
|
cpp
|
hash_test.cpp
|
#include <string>
#include <catch.hpp>
#include <emilib/hash_map.hpp>
#include <emilib/hash_set.hpp>
using namespace std;
TEST_CASE( "[int -> double]", "HashMap" ) {
emilib::HashMap<int, double> map;
REQUIRE(map.empty());
REQUIRE(map.size() == 0);
map.insert(1, 1.0);
REQUIRE(map.size() == 1);
REQUIRE(map[1] == 1.0);
map.insert(2, 2.0);
REQUIRE(map.size() == 2);
REQUIRE(map[2] == 2.0);
map.insert(3, 3.0);
REQUIRE(map.size() == 3);
REQUIRE(map[3] == 3.0);
map.insert(4, 4.0);
REQUIRE(map.size() == 4);
REQUIRE(map[4] == 4.0);
REQUIRE(map.count(2) == 1);
bool did_erase = map.erase(2);
REQUIRE(did_erase);
REQUIRE(map.count(2) == 0);
REQUIRE(map.size() == 3);
REQUIRE(map[4] == 4.0);
}
TEST_CASE( "[string -> string]", "HashMap" ) {
emilib::HashMap<string, string> map;
map["1"] = "one";
map["2"] = "two";
map["3"] = "three";
map["4"] = "four";
map["5"] = "five";
map["6"] = "six";
REQUIRE(map["1"] == "one");
REQUIRE(map["2"] == "two");
REQUIRE(map["3"] == "three");
REQUIRE(map["4"] == "four");
REQUIRE(map["5"] == "five");
REQUIRE(map["6"] == "six");
map["6"] = "sechs";
REQUIRE(map["6"] == "sechs");
map.insert_or_assign("6", "seis");
REQUIRE(map["6"] == "seis");
}
TEST_CASE( "copy+moving", "HashMap" ) {
emilib::HashMap<string, string> map;
map["1"] = "one";
map["2"] = "two";
{
auto copy = map;
REQUIRE(copy.size() == 2);
REQUIRE(copy["1"] == "one");
REQUIRE(copy["2"] == "two");
copy["3"] = "three";
REQUIRE(copy.size() == 3);
REQUIRE(copy["1"] == "one");
REQUIRE(copy["2"] == "two");
REQUIRE(copy["3"] == "three");
REQUIRE(map.size() == 2);
REQUIRE(map["1"] == "one");
REQUIRE(map["2"] == "two");
map = copy;
REQUIRE(map.size() == 3);
REQUIRE(map["1"] == "one");
REQUIRE(map["2"] == "two");
REQUIRE(map["3"] == "three");
REQUIRE(copy.size() == 3);
REQUIRE(copy["1"] == "one");
REQUIRE(copy["2"] == "two");
REQUIRE(copy["3"] == "three");
}
{
auto moved = std::move(map);
REQUIRE(moved.size() == 3);
REQUIRE(moved["1"] == "one");
REQUIRE(moved["2"] == "two");
REQUIRE(moved["3"] == "three");
}
REQUIRE(map.empty());
}
TEST_CASE( "[string]", "HashSet" ) {
emilib::HashSet<string> set;
set.insert("1");
set.insert("2");
set.insert("3");
REQUIRE(set.count("0") == 0);
REQUIRE(set.count("1") == 1);
REQUIRE(set.count("2") == 1);
REQUIRE(set.count("3") == 1);
REQUIRE(set.size() == 3);
set.insert("4");
set.insert("5");
set.insert("6");
REQUIRE(set.count("1") == 1);
REQUIRE(set.count("2") == 1);
REQUIRE(set.count("3") == 1);
REQUIRE(set.count("4") == 1);
REQUIRE(set.count("5") == 1);
REQUIRE(set.count("6") == 1);
REQUIRE(set.size() == 6);
REQUIRE(set.count("2") == 1);
set.erase("2");
REQUIRE(set.size() == 5);
REQUIRE(set.count("2") == 0);
}
|
8e6fad9b9c5707d137b77127cf06db946a362c6f
|
f9d5cb4535d69d904cbcdfd2842e4912ebe1ae2e
|
/Ultrasonictest.ino/Ultrasonictest.ino.ino
|
91e5b7cbf217af43458c2b326248ecfdb44de503
|
[] |
no_license
|
edwinsuubi/arduino-testing
|
5120497cbb4cd72c2d1209ac6f5a36bf2b034f30
|
7d546c240b39e52210a644e66ad32f6b0f83d40e
|
refs/heads/master
| 2020-05-31T17:05:44.591258
| 2019-06-06T08:04:41
| 2019-06-06T08:04:41
| 190,399,704
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 609
|
ino
|
Ultrasonictest.ino.ino
|
int led = 6;
const int trig = 12;
const int echo = 10;
float duration;
int distance;
void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trig, LOW);
delay(2);
digitalWrite(trig, HIGH);
delay(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = (duration/2)*0.343;
Serial.print("distance = ");
if(distance >= 100){
digitalWrite(led, HIGH);
delay(500);
}
else{
digitalWrite(led, LOW);
delay(500);
};
Serial.println(distance);
delay(2000);
}
|
cfba44a4ab2e9c707f68a8c0e7b1fe09f20d8547
|
fef750f91e71daa54ed4b7ccbb5274e77cab1d8f
|
/HDU/3400+/3433.cpp
|
977f9de597d37157880ec5700db1994ce520c146
|
[] |
no_license
|
DongChengrong/ACM-Program
|
e46008371b5d4abb77c78d2b6ab7b2a8192d332b
|
a0991678302c8d8f4a7797c8d537eabd64c29204
|
refs/heads/master
| 2021-01-01T18:32:42.500303
| 2020-12-29T11:29:02
| 2020-12-29T11:29:02
| 98,361,821
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,107
|
cpp
|
3433.cpp
|
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
#define N 55
#define M 250
#define INF 0x3f3f3f3f
int vis[N];
int n, x, y;
int a[N], b[N], dp[N][M];
int check(int mid, int x, int y) {
memset(dp, -1, sizeof(dp));
for (int i = 0; i <= x && i * a[0] <= mid; ++i) dp[0][i] = (mid - a[0] * i) / b[0];
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= x; ++j) {
for (int k = 0; k <= j && k * a[i] <= mid; ++k) {
if (dp[i -1][j - k] != -1) dp[i][j] = max(dp[i][j], dp[i - 1][j - k] + ((mid - a[i] * k) / b[i]));
}
}
}
return dp[n - 1][x] >= y;
}
int main() {
int T; scanf("%d", &T);
for (int kase = 1; kase <= T; ++kase) {
scanf("%d%d%d", &n, &x, &y);
for (int i = 0; i < n; ++i) scanf("%d%d", &a[i], &b[i]);
int l = 1, r = INF, res = -1;
while (l <= r) {
int mid = (l + r) / 2;
if (check(mid, x, y)) { r = mid - 1; res = mid; }
else l = mid + 1;
}
printf("Case %d: %d\n", kase, res);
}
return 0;
}
|
1305335c7bad5ddda5b40a3900d2bc672131d192
|
3adcbbf0cf24668713315f930dd6c4c625514a5c
|
/src/common/ByteOrder.h
|
7ac857b9d262270b7d0915bbeb10545e7737d379
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
ifplusor/rocketmq-client-cpp
|
292d3948f7c24bd5610765338a26b23f99b4a49d
|
560f47145b39245890b2911bfcb52e1094ae609a
|
refs/heads/re_dev
| 2022-07-09T19:28:44.245791
| 2022-03-17T10:01:18
| 2022-03-17T10:01:18
| 163,077,225
| 5
| 2
|
Apache-2.0
| 2021-10-13T10:52:00
| 2018-12-25T11:35:31
|
C++
|
UTF-8
|
C++
| false
| false
| 6,268
|
h
|
ByteOrder.h
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ROCKETMQ_COMMON_BYTEORDER_H_
#define ROCKETMQ_COMMON_BYTEORDER_H_
#include <cstdlib> // std::memcpy
#include <type_traits> // std::enable_if, std::is_integral, std::make_unsigned, std::add_pointer
#include "RocketMQClient.h"
namespace rocketmq {
enum ByteOrder { BO_BIG_ENDIAN, BO_LITTLE_ENDIAN };
/**
* Contains static methods for converting the byte order between different endiannesses.
*/
class ByteOrderUtil {
public:
static constexpr ByteOrder native_order() {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ // __BYTE_ORDER__ is defined by GCC
return ByteOrder::BO_LITTLE_ENDIAN;
#else
return ByteOrder::BO_BIG_ENDIAN;
#endif
}
/** Returns true if the current CPU is big-endian. */
static constexpr bool isBigEndian() { return native_order() == ByteOrder::BO_BIG_ENDIAN; }
//==============================================================================
template <typename T, typename F, typename std::enable_if<sizeof(T) == sizeof(F), int>::type = 0>
static T ReinterpretRawBits(F value) {
return *reinterpret_cast<T*>(&value);
}
static uint8_t swap(uint8_t n) { return n; }
/** Swaps the upper and lower bytes of a 16-bit integer. */
static uint16_t swap(uint16_t n) { return static_cast<uint16_t>((n << 8) | (n >> 8)); }
/** Reverses the order of the 4 bytes in a 32-bit integer. */
static uint32_t swap(uint32_t n) { return (n << 24) | (n >> 24) | ((n & 0x0000ff00) << 8) | ((n & 0x00ff0000) >> 8); }
/** Reverses the order of the 8 bytes in a 64-bit integer. */
static uint64_t swap(uint64_t value) {
return (((uint64_t)swap((uint32_t)value)) << 32) | swap((uint32_t)(value >> 32));
}
//==============================================================================
/** convert integer to little-endian */
template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
static typename std::make_unsigned<T>::type NorminalLittleEndian(T value) {
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
return swap(static_cast<typename std::make_unsigned<T>::type>(value));
#else
return static_cast<typename std::make_unsigned<T>::type>(value);
#endif
}
/** convert integer to big-endian */
template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
static typename std::make_unsigned<T>::type NorminalBigEndian(T value) {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
return swap(static_cast<typename std::make_unsigned<T>::type>(value));
#else
return static_cast<typename std::make_unsigned<T>::type>(value);
#endif
}
//==============================================================================
template <typename T, int Enable = 0>
static T Read(const char* bytes) {
T value;
std::memcpy(&value, bytes, sizeof(T));
return value;
}
template <typename T, typename std::enable_if<sizeof(T) <= 8, int>::value = 0>
static T Read(const char* bytes) {
T value;
for (size_t i = 0; i < sizeof(T); i++) {
((char*)&value)[i] = bytes[i];
}
return value;
}
template <typename T, int Enable = 0>
static void Read(T* value, const char* bytes) {
std::memcpy(value, bytes, sizeof(T));
}
template <typename T, typename std::enable_if<sizeof(T) <= 8, int>::value = 0>
static void Read(T* value, const char* bytes) {
for (size_t i = 0; i < sizeof(T); i++) {
((char*)value)[i] = bytes[i];
}
}
//==============================================================================
template <typename T, int Enable = 0>
static void Write(char* bytes, T value) {
std::memcpy(bytes, &value, sizeof(T));
}
template <typename T, typename std::enable_if<sizeof(T) <= 8, int>::value = 0>
static void Write(char* bytes, T value) {
for (size_t i = 0; i < sizeof(T); i++) {
bytes[i] = ((char*)&value)[i];
}
}
//==============================================================================
template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
static T ReadLittleEndian(const char* bytes) {
auto value = Read<T>(bytes);
return NorminalLittleEndian(value);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
static T ReadBigEndian(const char* bytes) {
auto value = Read<T>(bytes);
return NorminalBigEndian(value);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
static T Read(const char* bytes, bool big_endian) {
return big_endian ? ReadBigEndian<T>(bytes) : ReadLittleEndian<T>(bytes);
}
//==============================================================================
template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
static void WriteLittleEndian(char* bytes, T value) {
value = NorminalLittleEndian(value);
Write(bytes, value);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
static void WriteBigEndian(char* bytes, T value) {
value = NorminalBigEndian(value);
Write(bytes, value);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
static void Write(char* bytes, T value, bool big_endian) {
if (big_endian) {
WriteBigEndian(bytes, value);
} else {
WriteLittleEndian(bytes, value);
}
}
};
} // namespace rocketmq
#endif // ROCKETMQ_COMMON_BYTEORDER_H_
|
cf9eb02105f5068567f84608a60f8edb4a22a80e
|
96f88059d7eae38ab869d31099f4c974bd95a69b
|
/pruitt-igoe/pruitt-igoe/core/components/FPSCounter.h
|
30fc60d72d9202bae14ef320cf6e9436150e8f9d
|
[
"MIT"
] |
permissive
|
mmerchante/pruitt-igoe
|
54e3151d7a608fd5f2489305c264fa5848480ec4
|
3b16b78e05fca18a64c51fc31160a41336b729be
|
refs/heads/master
| 2021-01-23T03:42:58.535821
| 2017-05-03T23:51:29
| 2017-05-03T23:51:29
| 86,111,465
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 374
|
h
|
FPSCounter.h
|
#pragma once
#include "../ui/uicomponent.h"
#include "../ui/uitext.h"
class FPSCounter : public UIComponent, public InputListener
{
public:
void Awake();
void Update();
virtual void OnKeyReleaseEvent(sf::Event::KeyEvent * e);
private:
UIText * text;
int currentFrame;
float currentFrameTimeAverage;
float minTime;
float maxTime;
bool ignoreForcedFramerate;
};
|
f9a7a60028b749ef955a208e950ca9b87c3d8558
|
9e147a9dd159aee503f499e13f52665e414abad5
|
/G3D/src/Engine/G3D_Mesh.h
|
d2f52e770d98a28324a68a7e439a3dc7a2d52002
|
[
"Apache-2.0"
] |
permissive
|
GunnDawg/Gunngine3D
|
ecd062d88c516435bacc0d782ecb2632447c134e
|
f10fa9ae34a537387fcddb4f2323632721a86739
|
refs/heads/master
| 2021-01-05T00:45:00.635126
| 2020-12-11T05:08:44
| 2020-12-11T05:08:44
| 240,815,984
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 682
|
h
|
G3D_Mesh.h
|
#pragma once
#include "Engine/G3D_Shader.h"
#include "Engine/G3D_Texture.h"
#include "Engine/G3D_Light.h"
namespace G3D
{
struct Mesh
{
bool Load();
bool Load(const char* TextureName, const char* ShaderName, DirectX::XMFLOAT3 Position);
void Update(const AmbientLight& AmbientLightSource);
void Draw();
void Unload();
void SwapShader(const char* shaderName);
ID3D11Buffer* VertexBuffer;
ID3D11Buffer* IndexBuffer;
ID3D11Buffer* TransformConstantBuffer;
ID3D11Buffer* LightConstantBuffer;
ID3D11InputLayout* InputLayout;
UINT IndexCount;
G3D::Shader Shader;
G3D::Texture Texture;
bool IsUsingDefault = false;
DirectX::XMMATRIX worldPos;
};
}
|
77c49d9fea50ceb9fd8456c4c313f2bda11031dd
|
d71147e42d2ca53d0137b6f113661d57d452256a
|
/uicontroller.h
|
9bc15912a868efa90893d1495956270001166adc
|
[] |
no_license
|
Kuttuna/QML-C-
|
9190b54b2b306be1ff3c06cf9cdcb1db82aa048e
|
5f27588be83c4ac8c35de97723e7f396446e0cc7
|
refs/heads/master
| 2020-04-13T13:26:46.047795
| 2018-12-27T01:10:15
| 2018-12-27T01:10:15
| 163,230,749
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 318
|
h
|
uicontroller.h
|
#ifndef UICONTROLLER_H
#define UICONTROLLER_H
#include <QObject>
class UiController : public QObject
{
Q_OBJECT
public:
explicit UiController(QObject *parent = nullptr);
Q_INVOKABLE int increase(int value);
Q_INVOKABLE int decrease(int value);
signals:
public slots:
};
#endif // UICONTROLLER_H
|
2e50c3bc0e1ddeff3250d3530b50e1dd69c95f83
|
923354cb388e025d9b0ede222f69f2d4782c7bf1
|
/pulsemover.h
|
9700c7132706fc3ffa2ba7d7f63ec27ca7670484
|
[
"MIT"
] |
permissive
|
reinout/servomover
|
f9367f22dcb4e28d4b3a42e6bfcb604036b6640e
|
4e887569b70001e366881bf609653d9f54e40d37
|
refs/heads/master
| 2021-01-21T13:25:36.430541
| 2016-05-09T20:21:18
| 2016-05-09T20:21:18
| 46,359,587
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 348
|
h
|
pulsemover.h
|
#ifndef pulsemover_h
#define pulsemover_h
#include <arduino.h>
class PulseMover
{
public:
PulseMover(int pin_base,
int pin_actuated);
void init();
void move_to_base();
void move_to_actuated();
void perhaps_update();
private:
int pin_base;
int pin_actuated;
unsigned long stop_pulse_again;
bool done;
};
#endif
|
e8771de117b66bed17cf26ac9f7c13ba44c88c0d
|
efb0d8e9d0111bb3c33b832041efcf18ebb9e923
|
/3980.cpp
|
d6b917e4046c03bfc6659e0206037a06854a7473
|
[] |
no_license
|
sejinik/BOJ
|
f0307f8e9bee9d1210db47df309126b49bb1390b
|
45cb123f073233d5cdec8bbca7b26dd5ae539f13
|
refs/heads/master
| 2020-03-18T12:42:01.694263
| 2018-05-24T17:04:19
| 2018-05-24T17:04:19
| 134,739,551
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 728
|
cpp
|
3980.cpp
|
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int d[(1 << 11)][11];
int arr[11][11];
int t;
int main() {
scanf("%d", &t);
while (t--) {
memset(d, -0x3f, sizeof(d));
memset(arr, 0, sizeof(arr));
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
scanf(" %d", &arr[i][j]);
}
}
for (int i = 0; i < 11; i++) {
for (int j = 0; j < (1 << 11); j++) {
for (int k = 0; k < 11; k++) {
if (!(j&(1 << k)) && arr[i][k]) {
if (i == 0) d[j | (1 << k)][i] = max(d[j | (1 << k)][i], arr[i][k]);
else d[j | (1 << k)][i] = max(d[j | (1 << k)][i], d[j][i - 1] + arr[i][k]);
}
}
}
}
printf("%d\n", (d[(1 << 11) - 1][10]));
}
return 0;
}
|
521c7ba07de2a88c94023e33ce341e9e81d95e45
|
2c6dac9af3257411725082c4a9d31e3f7cd3859d
|
/graph.h
|
3708550f1e98890b9304052341721cd45519d0b8
|
[] |
no_license
|
oURMIo/VS_GL_Grafuk_Mas
|
75bbd4ee1fe26eed0296409ae4f3362825ef8ee5
|
ede54bf92b6833c9f44db23294b1762fc5d12707
|
refs/heads/main
| 2023-04-21T13:56:12.336291
| 2021-05-12T16:24:13
| 2021-05-12T16:24:13
| 366,777,148
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,887
|
h
|
graph.h
|
#ifndef GRAPH_HH
#define GRAPH_HH
#include "alg1.h"
/** ГРАФ: ОПРЕДЕЛЕНИЯ *************************************************/
/** чётко определенные параметры *************************************************/
#define NMAX_VERT 64 // 1024 // graph MAX size (array is not dynamic)
#define NMAX_EDGES (NMAX_VERT*NMAX_VERT) // formally, it is square of nodes quantity
/** субъективные параметры *************************************************/
#define VERTEX_YES 1
#define VERTEX_NO 0
#define EDGE_YES 1
#define EDGE_NO 0
// типы существ
#define LIVE_PHTYPE_NO 0
#define LIVE_PHTYPE_DRAGONFLY 1 // стрекоза
#define LIVE_PHTYPE_HONEYBEE 2 // пчела
#define LIVE_PHTYPE_MAX 2
#define LIVE_REGIME_NOT_SELECTED (-1)
#define LIVE_REGIME_ON 1
#define LIVE_REGIME_OFF 0
//static int K_RAND = 20.0; // possibility of edge existence
/** ГРАФ: предопределение типов *************************************************/
// граф как матрица смежности, размер NMAX*NMAX/2 (вершина и связанные с ней вершины)
typedef struct
{
int ID;
float x, y, z;
int edgeTo[NMAX_VERT];
// extended properties
int physio_type;
bool exists;
int msec_to_live;
float radius;
float azimuth;
float latitude;
float delta_radius;
float delta_azimuth;
float delta_latitude;
} TNode;
// граф как набор рёбер с указанием номеров связанных с ним двух вершин
typedef struct
{
int edge[2];
} TEdge;
typedef unsigned char byte;
/** ГРАФ. ****************************************************************/
class CGraph
{
public:
CGraph();
int N_vert = 32; // graph current size; was macro, but must be changeable
int N_edges = 32; // edges _approximate_ quantity; was macro, but must be changeable
//-------------------------------------------------------------------------------------------------
void AlgImplementation();
void Init();
void InitEdges();
void InitVertexesCoords();
void InitExtended();
void InitExtendedZero();
void StepExtended();
void Draw();
void DrawNode(int id, TNode *gr);
void DrawEdge(int ID1, int ID2, TNode *gr);
bool live;
private:
// собственно граф как набор вершин
TNode graph1[NMAX_VERT];
TEdge edge[NMAX_EDGES];
// параметры "дизайна" (нечёткие, субъективные)
const int big = (NMAX_VERT * 0.8); // "большая" ли сеть
//-------------------------------------------------------------------------------------------------
bool graphIsConnected(TNode *graph1, int N);
bool graphHasCycle(TNode *graph1, int N);
};
#endif // GRAPH_HH
|
d8e13627753ede674ba75ed3b8e25e26d4d62edb
|
aeb3600f0c74ea5ec9c42752531f1f8a9cf7a346
|
/memory/include/GameController.hpp
|
5b52a2ea9e1507b8cf175c4d3729a58318d9e94f
|
[
"MIT"
] |
permissive
|
GPUWorks/OpenGL
|
3e9efb0ef90edc3f8d228de6f9e022563165a01c
|
f80251f03fa65ae632cab3651378bf3b5a57fc84
|
refs/heads/master
| 2020-04-12T10:05:30.962456
| 2018-12-10T22:16:59
| 2018-12-10T22:16:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,021
|
hpp
|
GameController.hpp
|
#ifndef _GAME_CONTROLLER_HPP_
#define _GAME_CONTROLLER_HPP_
#include <cstdlib>
#include <iostream>
#include <vector>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
using namespace glm;
class GameController
{
private:
const GLfloat vbData[34];
GLuint vertexBuffer;
std::pair<int, int> size;
std::vector<int> colorCodes;
std::vector<int> signCodes;
std::vector<std::pair<int, int>> transforms;
std::vector<bool> visible;
public:
GameController(const std::pair<int, int> & size, int numColors, int numSigns);
bool isVisible(int i);
void setVisible(int i);
void drawGame(GLuint pID, const std::pair<int, int> & pos, bool isCurVisible);
int checkKeyPress(GLFWwindow * window);
void checkKeyRelease(GLFWwindow * window, int key);
int moveFrame(int key, int cur);
bool checkSame(int prev, int cur);
private:
void drawSquares(GLuint pID, int col, std::pair<int, int> tr, int frameOffset);
void drawSign(GLuint pID, int i);
};
#endif
|
233a6c04dc06a20192ae2c8b8c8214d30fe6a710
|
e066f9a3b35a59526ff8b12522ec79a49d795b83
|
/chromeos/update_applier.h
|
7fa99a49249689f70f791be53b8447c0b7271693
|
[] |
no_license
|
BlissRoms-x86/vendor_bliss_priv
|
88db4fc6e8aa76c8b32f730ac570ea0f25967fe1
|
f63c12f0db53c6d36bfbd584b5f449d0c3d829bc
|
refs/heads/p9.0
| 2021-07-13T03:59:52.666429
| 2019-02-02T22:22:15
| 2019-02-02T22:22:15
| 155,762,681
| 7
| 4
| null | 2023-05-03T03:09:01
| 2018-11-01T19:05:16
|
C++
|
UTF-8
|
C++
| false
| false
| 1,620
|
h
|
update_applier.h
|
//
// Copyright (C) 2018 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#include <brillo/message_loops/base_message_loop.h>
#include <update_engine/common/action_processor.h>
#include <update_engine/common/error_code.h>
#include <update_engine/common/http_fetcher.h>
#include <update_engine/common/prefs_interface.h>
#include <update_engine/payload_consumer/download_action.h>
#include <update_engine/payload_consumer/install_plan.h>
namespace chromeos_update_engine {
class UpdateApplier : public ActionProcessorDelegate {
public:
UpdateApplier(const InstallPlan &install_plan,
PrefsInterface* prefs,
BootControlInterface* boot_control,
HardwareInterface* hardware,
HttpFetcher *fetcher);
ErrorCode Run();
void ProcessingDone(const ActionProcessor* processor, ErrorCode code) override;
private:
brillo::BaseMessageLoop loop_;
InstallPlanAction install_plan_action_;
DownloadAction download_action_;
ErrorCode error_code_;
DISALLOW_COPY_AND_ASSIGN(UpdateApplier);
};
}
|
b493885010cc98dcdfb1e08bbbfd7d55d53b9598
|
756296ae51864e88e4c1a2ef58af43f85a6319f5
|
/dominios.cpp
|
7d7053a0d5c1bde65ad0147704ef90f82633e1f4
|
[] |
no_license
|
masathayde/unbtp1
|
f26001b85c8a5ca3c921868d8fd19a569169f505
|
e4a3ab4f171859041fd026233751e8078315a88b
|
refs/heads/master
| 2020-09-15T10:59:44.700619
| 2019-11-23T05:07:41
| 2019-11-23T05:07:41
| 223,427,273
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,997
|
cpp
|
dominios.cpp
|
#include "dominios.h"
void CodigoJogo::validar (string input) throw (invalid_argument)
{
if (input.size() != this->size)
throw invalid_argument("Erro: Tamanho incorreto");
for (auto it : input) {
if (it < '0' || it > '9')
throw invalid_argument("Erro: Carater invalido");
}
}
void CodigoJogo::setar (string input)
{
this->validar(input);
this->numero = input;
}
string CodigoJogo::get () const
{
return this->numero;
}
CodigoJogo& CodigoJogo::operator=(const CodigoJogo& outro)
{
this->numero = outro.get();
return *this;
}
//------
void CodigoIngresso::validar (unsigned input) throw (invalid_argument)
{
if (input > maxSize)
throw invalid_argument("Erro: Codigo invalido");
}
void CodigoIngresso::setar (unsigned input)
{
this->validar(input);
this->numero = input;
}
unsigned CodigoIngresso::get ()
{
return this->numero;
}
string CodigoIngresso::getString ()
{
stringstream ss;
ss << setw(5) << setfill('0') << this->numero;
return ss.str();
}
//------
void NomeDoJogo::validar (string input) throw (invalid_argument)
{
if (input.size() > this->maxSize)
throw invalid_argument("Erro: Nome invalido - Tamanho excedido");
int charCount = 0;
char previousChar = '0';
for (auto it : input) {
if (it < '0' || it > '9')
charCount++;
if (previousChar == ' ' && it == ' ')
throw invalid_argument("Erro: Nome invalido - Mais de dois espacos");
previousChar = it;
}
if (charCount == 0)
throw invalid_argument("Erro: Nome invalido - Nenhuma letra");
}
void NomeDoJogo::setar (string input)
{
this->validar(input);
this->nome = input;
}
string NomeDoJogo::get () const
{
return this->nome;
}
//------
void Horario::validar (unsigned short hora, unsigned short minuto) throw (invalid_argument)
{
if (hora < 7 || hora > 22)
throw invalid_argument("Erro: Horario invalido");
if (minuto > 45 || minuto % 15 != 0)
throw invalid_argument("Erro: Horario invalido");
}
void Horario::setar (unsigned short h, unsigned short m)
{
this->validar(h, m);
this->hora = h;
this->minuto = m;
}
void Horario::get (unsigned short* h, unsigned short* m) const
{
*h = this->hora;
*m = this->minuto;
}
Horario& Horario::operator= (const Horario& outro)
{
unsigned short _hora, _min;
outro.get(&_hora, &_min);
this->setar(_hora, _min);
return *this;
}
//------
void Preco::validar (float preco) throw (invalid_argument)
{
if (preco < 0 || preco > max)
throw invalid_argument("Erro: preco invalido");
}
void Preco::setar (float preco)
{
this->validar(preco);
this->valor = preco;
}
float Preco::get () const
{
return this->valor;
}
//------
void NumeroSala::validar (unsigned sala) throw (invalid_argument)
{
if (sala < this->min || sala > this->max)
throw invalid_argument("Erro: sala invalida");
}
void NumeroSala::setar (unsigned num)
{
this->validar(num);
this->valor = num;
}
unsigned NumeroSala::get ()
{
return this->valor;
}
//------
void Cidade::validar (string input) throw (invalid_argument)
{
if (input.size() > this->maxSize)
throw invalid_argument("Erro: Tamanho maximo excedido");
char previousChar = ' ';
for (auto it : input) {
if (it >= '0' && it <= '9')
throw invalid_argument("Erro: Numeros nao sao permitidos");
if (previousChar == ' ' && (it == ' ' || it == '.' ) )
throw invalid_argument("Erro: sequencia invalida");
previousChar = it;
}
}
void Cidade::setar (string input)
{
this->validar(input);
this->nome = input;
}
string Cidade::get () const
{
return this->nome;
}
//------
void Disponibilidade::validar (unsigned input) throw (invalid_argument)
{
if (input > this->max)
throw invalid_argument("Erro: valor invalido");
}
void Disponibilidade::setar (unsigned disp)
{
this->validar(disp);
this->valor = disp;
}
unsigned Disponibilidade::get ()
{
return this->valor;
}
//------
void TipoJogo::validar (unsigned tipo) throw (invalid_argument)
{
if (tipo < min || tipo > max)
throw invalid_argument("Erro: Tipo invalido");
}
void TipoJogo::setar (unsigned tipo)
{
this->validar(tipo);
this->valor = tipo;
}
unsigned TipoJogo::get () const
{
return this->valor;
}
string TipoJogo::getString ()
{
switch(this->valor) {
case 1: return "LOCAL";
case 2: return "ESTADUAL";
case 3: return "NACIONAL";
case 4: return "INTERNACIONAL";
}
}
//------
void Cpf::validar (string input) throw (invalid_argument)
{
// Lembrando de subtrair '0' quando converter char para int
if (input.size() > this->maxSize)
throw invalid_argument("Erro: CPF invalido");
int ver0, ver1;
ver0 = 0;
ver1 = 0;
char rptChar = input[0];
bool repeat = true;
for (int i = 0; i < input.size() - 2; i++) {
if (input[i] != rptChar)
repeat = false;
if (input[i] < '0' || input[i] > '9')
throw invalid_argument("Erro: CPF invalido");
ver0 += (10 - i) * (input[i] - '0');
ver1 += (11 - i) * (input[i] - '0');
}
if (repeat)
throw invalid_argument("Erro: CPF invalido");
// 1o digito
ver0 = ver0 % 11;
if (ver0 < 2)
ver0 = 0;
else
ver0 = 11 - ver0;
if (input[9] - '0' != ver0)
throw invalid_argument("Erro: CPF invalido");
// 2o digito
ver1 += ver0*2;
ver1 = ver1 % 11;
if (ver1 < 2)
ver1 = 0;
else
ver1 = 11 - ver1;
if (input[10] - '0' != ver1)
throw invalid_argument("Erro: CPF invalido");
}
void Cpf::setar (string input)
{
this->validar(input);
this->valor = input;
}
string Cpf::get () const
{
return this->valor;
}
bool Cpf::operator== (const Cpf& outro)
{
return this->get() == outro.get();
}
Cpf& Cpf::operator= (const Cpf& outro)
{
valor = outro.get();
return *this;
}
//------
void Senha::validar (string input) throw (invalid_argument)
{
if (input.size() != this->size)
throw invalid_argument("Erro: Senha invalida");
char previousChar = 0;
bool upperCase = false;
bool lowerCase = false;
bool number = false;
for (auto it : input) {
if (it == previousChar)
throw invalid_argument("Erro: Senha invalida");
if (it >= '0' && it <= '9')
number = true;
else if (it >= 'A' && it <= 'Z')
upperCase = true;
else if (it >= 'a' && it <= 'z')
lowerCase = true;
else
throw invalid_argument("Erro: Senha invalida");
previousChar = it;
}
if (!upperCase || !lowerCase || !number)
throw invalid_argument("Erro: Senha invalida");
}
void Senha::setar (string input)
{
this->validar(input);
this->valor = input;
}
string Senha::get () const
{
return this->valor;
}
// --------
void Estadio::validar (string input) throw (invalid_argument)
{
if (input.size() > this->maxSize)
throw invalid_argument("Erro: Tamanho maximo excedido");
int charCount = 0;
char previousChar = '0';
for (auto it : input) {
if (it < '0' || it > '9')
charCount++;
if (previousChar == ' ' && it == ' ')
throw invalid_argument("Erro: Mais de um espaco em seguida");
previousChar = it;
}
if (charCount == 0)
throw invalid_argument("Erro: Nenhuma letra no nome");
}
void Estadio::setar (string input)
{
this->validar(input);
this->nome = input;
}
string Estadio::get () const
{
return nome;
}
// ---------
void Data::validar (int ano, int mes, int dia) throw (invalid_argument)
{
if (ano < 0 || ano > 99)
throw invalid_argument("Erro: Data invalida");
if (mes < 1 || mes > 12)
throw invalid_argument("Erro: Data invalida");
if (dia < 1 || dia > 31)
throw invalid_argument("Erro: Data invalida");
bool anoBissexto = false;
ano += 2000;
if ( (ano % 4 == 0 && ano % 100 != 0) || ano % 400 == 0 )
anoBissexto = true;
// Teste de dias invalidos meus deus que coisa mais chata
if (mes <= 7 && mes % 2 == 0 && dia > 30)
throw invalid_argument("Erro: Data invalida");
if (mes >= 8 && mes % 2 == 1 && dia > 30)
throw invalid_argument("Erro: Data invalida");
if (mes == 2 && dia > 29)
throw invalid_argument("Erro: Data invalida");
if (mes == 2 && !anoBissexto && dia > 28)
throw invalid_argument("Erro: Data invalida");
}
void Data::setar (int ano, int mes, int dia)
{
this->validar(ano, mes, dia);
this->ano = ano;
this->mes = mes;
this->dia = dia;
}
int Data::getAno () const
{
return ano;
}
int Data::getMes () const
{
return mes;
}
int Data::getDia () const
{
return dia;
}
Data& Data::operator= (const Data& outro)
{
ano = outro.getAno();
mes = outro.getMes();
dia = outro.getDia();
return *this;
}
// --------
Estado::Estado ()
{
// Popular mapa
// Adoro programar :) !!!
stringParaSigla.insert(pair<string, Sigla>("ac", Sigla::AC));
stringParaSigla.insert(pair<string, Sigla>("AC", Sigla::AC));
stringParaSigla.insert(pair<string, Sigla>("al", Sigla::AL));
stringParaSigla.insert(pair<string, Sigla>("AL", Sigla::AL));
stringParaSigla.insert(pair<string, Sigla>("ap", Sigla::AP));
stringParaSigla.insert(pair<string, Sigla>("AP", Sigla::AP));
stringParaSigla.insert(pair<string, Sigla>("am", Sigla::AM));
stringParaSigla.insert(pair<string, Sigla>("AM", Sigla::AM));
stringParaSigla.insert(pair<string, Sigla>("ba", Sigla::BA));
stringParaSigla.insert(pair<string, Sigla>("BA", Sigla::BA));
stringParaSigla.insert(pair<string, Sigla>("ce", Sigla::CE));
stringParaSigla.insert(pair<string, Sigla>("CE", Sigla::CE));
stringParaSigla.insert(pair<string, Sigla>("df", Sigla::DF));
stringParaSigla.insert(pair<string, Sigla>("DF", Sigla::DF));
stringParaSigla.insert(pair<string, Sigla>("es", Sigla::ES));
stringParaSigla.insert(pair<string, Sigla>("ES", Sigla::ES));
stringParaSigla.insert(pair<string, Sigla>("go", Sigla::GO));
stringParaSigla.insert(pair<string, Sigla>("GO", Sigla::GO));
stringParaSigla.insert(pair<string, Sigla>("ma", Sigla::MA));
stringParaSigla.insert(pair<string, Sigla>("MA", Sigla::MA));
stringParaSigla.insert(pair<string, Sigla>("mt", Sigla::MT));
stringParaSigla.insert(pair<string, Sigla>("MT", Sigla::MT));
stringParaSigla.insert(pair<string, Sigla>("ms", Sigla::MS));
stringParaSigla.insert(pair<string, Sigla>("MS", Sigla::MS));
stringParaSigla.insert(pair<string, Sigla>("mg", Sigla::MG));
stringParaSigla.insert(pair<string, Sigla>("MG", Sigla::MG));
stringParaSigla.insert(pair<string, Sigla>("pa", Sigla::PA));
stringParaSigla.insert(pair<string, Sigla>("PA", Sigla::PA));
stringParaSigla.insert(pair<string, Sigla>("pb", Sigla::PB));
stringParaSigla.insert(pair<string, Sigla>("PB", Sigla::PB));
stringParaSigla.insert(pair<string, Sigla>("pr", Sigla::PR));
stringParaSigla.insert(pair<string, Sigla>("PR", Sigla::PR));
stringParaSigla.insert(pair<string, Sigla>("pe", Sigla::PE));
stringParaSigla.insert(pair<string, Sigla>("PE", Sigla::PE));
stringParaSigla.insert(pair<string, Sigla>("pi", Sigla::PI));
stringParaSigla.insert(pair<string, Sigla>("PI", Sigla::PI));
stringParaSigla.insert(pair<string, Sigla>("rj", Sigla::RJ));
stringParaSigla.insert(pair<string, Sigla>("RJ", Sigla::RJ));
stringParaSigla.insert(pair<string, Sigla>("rn", Sigla::RN));
stringParaSigla.insert(pair<string, Sigla>("RN", Sigla::RN));
stringParaSigla.insert(pair<string, Sigla>("rs", Sigla::RS));
stringParaSigla.insert(pair<string, Sigla>("RS", Sigla::RS));
stringParaSigla.insert(pair<string, Sigla>("ro", Sigla::RO));
stringParaSigla.insert(pair<string, Sigla>("RO", Sigla::RO));
stringParaSigla.insert(pair<string, Sigla>("rr", Sigla::RR));
stringParaSigla.insert(pair<string, Sigla>("RR", Sigla::RR));
stringParaSigla.insert(pair<string, Sigla>("sc", Sigla::SC));
stringParaSigla.insert(pair<string, Sigla>("SC", Sigla::SC));
stringParaSigla.insert(pair<string, Sigla>("sp", Sigla::SP));
stringParaSigla.insert(pair<string, Sigla>("SP", Sigla::SP));
stringParaSigla.insert(pair<string, Sigla>("se", Sigla::SE));
stringParaSigla.insert(pair<string, Sigla>("SE", Sigla::SE));
stringParaSigla.insert(pair<string, Sigla>("to", Sigla::TO));
stringParaSigla.insert(pair<string, Sigla>("TO", Sigla::TO));
siglaParaString.insert(pair<Sigla, string>(Sigla::AC, "AC"));
siglaParaString.insert(pair<Sigla, string>(Sigla::AL, "AL"));
siglaParaString.insert(pair<Sigla, string>(Sigla::AP, "AP"));
siglaParaString.insert(pair<Sigla, string>(Sigla::AM, "AM"));
siglaParaString.insert(pair<Sigla, string>(Sigla::CE, "CE"));
siglaParaString.insert(pair<Sigla, string>(Sigla::DF, "DF"));
siglaParaString.insert(pair<Sigla, string>(Sigla::ES, "ES"));
siglaParaString.insert(pair<Sigla, string>(Sigla::GO, "GO"));
siglaParaString.insert(pair<Sigla, string>(Sigla::MA, "MA"));
siglaParaString.insert(pair<Sigla, string>(Sigla::MT, "MT"));
siglaParaString.insert(pair<Sigla, string>(Sigla::MS, "MS"));
siglaParaString.insert(pair<Sigla, string>(Sigla::MG, "MG"));
siglaParaString.insert(pair<Sigla, string>(Sigla::PA, "PA"));
siglaParaString.insert(pair<Sigla, string>(Sigla::PB, "PB"));
siglaParaString.insert(pair<Sigla, string>(Sigla::PR, "PR"));
siglaParaString.insert(pair<Sigla, string>(Sigla::PE, "PE"));
siglaParaString.insert(pair<Sigla, string>(Sigla::PI, "PI"));
siglaParaString.insert(pair<Sigla, string>(Sigla::RJ, "RJ"));
siglaParaString.insert(pair<Sigla, string>(Sigla::RN, "RN"));
siglaParaString.insert(pair<Sigla, string>(Sigla::RO, "RO"));
siglaParaString.insert(pair<Sigla, string>(Sigla::RR, "RR"));
siglaParaString.insert(pair<Sigla, string>(Sigla::SC, "SC"));
siglaParaString.insert(pair<Sigla, string>(Sigla::SP, "SP"));
siglaParaString.insert(pair<Sigla, string>(Sigla::SE, "SE"));
siglaParaString.insert(pair<Sigla, string>(Sigla::TO, "TO"));
}
void Estado::validar (string input) throw (invalid_argument)
{
if (stringParaSigla.find(input) == stringParaSigla.end())
throw invalid_argument("Erro: Sigla invalida");
}
void Estado::setar (string input)
{
this->validar(input);
this->sigla = this->stringParaSigla[input];
}
Sigla Estado::getSigla () const
{
return this->sigla;
}
string Estado::getString () const
{
return siglaParaString.find(sigla)->second;
}
Estado& Estado::operator=(const Estado& outro)
{
this->sigla = outro.getSigla();
return *this;
}
|
bd178f558485df4ea2e2aaf71e0fe40fe51097f6
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5639104758808576_0/C++/squeespoon/1.cpp
|
2578ae070118e740c803e40e9098030242857320
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 724
|
cpp
|
1.cpp
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <vector>
#include <deque>
using namespace std;
char str[1010];
int main(){
freopen("A-small-attempt0.in","r",stdin);
freopen("A-small-attempt0.out","w",stdout);
int t;
cin>>t;
int cas=0;
while(t--){
cas++;
int MAX;
cin>>MAX;
scanf("%s",str);
int len=strlen(str);
int cnt=0;
int ans=0;
for(int i=0;i<len;i++){
str[i]-='0';
cnt+=str[i];
if(cnt<i+1){
int add = i+1-cnt;
cnt+=add;
ans+=add;
}
}
printf("Case #%d: %d\n",cas,ans);
//cout<<ans<<endl;
}
return 0;
}
|
4b87df1ef59bba3cbf0462f74848b4a8da57d335
|
642e07d31f88a5e68f83856d87774a4531733e51
|
/Homework 4/ExtCalc/evaluate.hpp
|
828052d8120ec4e95ba58ad056f815b5602f9b27
|
[] |
no_license
|
draganjovic/Compiler-Design
|
0a9160ac1b02c2cac2862540906bd74f04eee6d0
|
29ad3b2a022e49708f78ca8a90131387e7eeeaa7
|
refs/heads/master
| 2021-01-22T08:02:59.244446
| 2019-12-03T02:26:41
| 2019-12-03T02:26:41
| 81,871,618
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,373
|
hpp
|
evaluate.hpp
|
#ifndef EVALUATE_HPP
#define EVALUATE_HPP
#include "prelude.hpp"
#include "visitor.hpp"
#include "ast.hpp"
struct eval_visitor : expr_visitor
{
// Reference Types and Function Types
void visit(const ref_expr *);
void visit(const func_expr *);
// Literal Expressions
void visit(const int_expr *);
void visit(const bool_expr *);
// Conditional Expression
void visit(const if_then_else_expr *);
// Unary Expressions
void visit(const pos_expr *);
void visit(const neg_expr *);
void visit(const not_expr *);
// Binary Expressions
void visit(const add_expr *);
void visit(const sub_expr *);
void visit(const multi_expr *);
void visit(const div_expr *);
void visit(const modulus_expr *);
void visit(const AND_expr *);
void visit(const OR_expr *);
void visit(const greaterthan_expr *);
void visit(const lessthan_expr *);
void visit(const greaterthanequal_expr *);
void visit(const lessthanequal_expr *);
void visit(const equalequal_expr *);
void visit(const notequal_expr *);
int int_value;
bool bool_value;
int ref_value;
int func_value, bool func_value;
};
int int_evaluate(expr * ast);
bool bool_evaluate(expr * ast);
int ref_evaluate(expr * ast);
int func_evaluate(expr * ast), bool func_evaluate(expr * ast);
#endif
|
c09952701ab55a24299038e3e62b6377185b7374
|
58dd0fe196ccd2738603a03b992bb99816a562bc
|
/c++/a07q02/a07q02/testFib.cpp
|
2dd64dde8cce8e4d957ee1fca7658f858a5c312d
|
[] |
no_license
|
bdpoagdorado1/BrandyProjects
|
3db999ff55d209ce14ff29008e7a74bfe63443e7
|
2182dddcfb85bbd4437989d7459cdb5ffbfff6e7
|
refs/heads/master
| 2021-01-10T21:17:11.410724
| 2014-05-19T15:04:30
| 2014-05-19T15:04:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 566
|
cpp
|
testFib.cpp
|
// File: testFib.cpp
// Name: Brandy Poag
#include <iostream>
#include "Fib.h"
#include "Math.h"
int main()
{
int n1 = 0, n2 = 1, n3 = 0;
std::cout << "Testing Fib: \n";
int i;
int errors = 0;
for (i = 0; i < 10; ++i)
{
if ( i == 0 ) n3 = 1;
std::cout << "Test " << i + 1 << ": " << (Math::fib(i) == n3 ? "pass" : "FAIL" ) << '\n';
if (Math::fib(i) != n3) ++errors;
n3 = n1 + n2;
n1 = n2;
n2 = n3;
}
std::cout << "Number of errors: " << errors << '\n';
std::cout << "Total number of test: " << i << '\n';
return 0;
}
|
8db02c5a514a082468e9eb65cbc3b42e3b03824e
|
8f745d23fb5c305b2b79d369a24a573d64b3dc18
|
/src/cdda.cpp
|
0a7a486b371a5ad362b8f69944c141c6241f2cf3
|
[] |
no_license
|
ianmicheal/dreamcast-common
|
ab2323d1d78bfafb843fb6b138d28d689ab98b1d
|
42153a864fb0f725d5f9b8916b2f919a8217dd7f
|
refs/heads/master
| 2022-01-10T03:35:09.518648
| 2019-03-26T20:58:47
| 2019-03-26T20:58:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 304
|
cpp
|
cdda.cpp
|
#include "dccommon/cdda.hpp"
CCdda::CCdda(void)
{
iRvol=250;
iLvol=250;
bPlay=false;
}
CCdda::~CCdda(void)
{
}
bool CCdda::IsPlaying()
{
int status(0), disc_type(0);
cdrom_reinit();
cdrom_get_status(&status, &disc_type);
if(status==CD_STATUS_PLAYING)
return(true);
else
return(false);
}
|
325802b207f45dcdf3dfd9b0012a7b271fdc6056
|
a99f916b3f244a1ce743f94a57226f510342c0a3
|
/Ch-2(Solution to Linked Lists)/Intersection/Intersection.cpp
|
d176818475ac562dfbc06347256913e08dfc74d2
|
[] |
no_license
|
Aman-Garg/cracking-the-coding-interview
|
d3d2ac9abdcb01160653c24fd0d6e40254c38048
|
3f08b0791712596e31f1534c3019af0c43d1b145
|
refs/heads/master
| 2020-05-04T23:32:24.942332
| 2019-04-13T21:33:20
| 2019-04-13T21:33:20
| 179,546,825
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,663
|
cpp
|
Intersection.cpp
|
#include<iostream>
#include<set>
using namespace std;
//creating some nodes in Linked List
struct node* createNewNode(int *numberToAdd, int size);
void traverse(struct node*);
//function to find the addres of the same node so that i can add it to new list
struct node* findAddress(int n ,struct node *list);
//function to find the length and address of the last node of the list
struct node* findDetails(struct node*);
//fucntion to find the address of the intersection node
struct node* intersectionNodeAddress(struct node *list1 , int list1Len , struct node *list2 , int list2Len);
struct node{
int data;
struct node *next;
};
struct node *start = NULL;
struct node *current =NULL;
int main(){
struct node *list1 , *list2;
int num1[] = {6 , 1 , 7 , 8 , 45 , 56 , 343};
int num2[] = {2 , 9 , 5};
list1 = createNewNode(num1 , 7);
list2 = createNewNode(num2 , 3);
//with this i am getting the address of the 6th node of linked list 1
//and adding this addess to the third node of linked list2
if(findAddress(3 , list2) != NULL && findAddress(6 , list1) != NULL)
findAddress(3 , list2)->next = findAddress(6 , list1);
traverse(list1);
traverse(list2);
//till the above line i have just merged the two linkedList only
struct node *list1Details , *list2Details;
//both these variable contains the length of list and adrres of the last node
list1Details = findDetails(list1);
list2Details = findDetails(list2);
if(list1Details->next->data != list2Details->next->data){
//beacuse last node data is not same
cout<<"\nNo Intersection\n";
}else{
cout<<"\n"<<intersectionNodeAddress(list1 ,list1Details->data , list2 , list2Details->data)->data<<"\n";
}
return 0;
}
struct node* intersectionNodeAddress(struct node *list1 , int list1Len , struct node *list2 , int list2Len){
if(list1Len >= list2Len ){
start = list1;
current = list2;
}else{
start = list2;
current = list1;
}
int noOfDiffElement = abs(list1Len-list2Len);
while(start != NULL){
if(current == start){
return start;
}
if(noOfDiffElement > 0){
noOfDiffElement--;
start = start->next;
}else{
current = current->next;
start = start->next;
}
}
return NULL;
}
struct node* findAddress(int n , struct node *list){
current = list;
int i=1;
while(list != NULL){
if(i==n){
return current ;
}
i++;
current= current->next;
}
return current;
}
//function to find the length
struct node* findDetails(struct node* list){
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->data = 0 ;
temp->next = NULL;
while(list != NULL){
temp->data++;
temp->next = list;
list = list->next;
}
return temp;
}
struct node* createNewNode(int *numberToAdd , int size){
start = NULL;
for(int i=0; i<size ; i++){
struct node *ptr = (struct node*)malloc(sizeof(struct node));
ptr->data=*(numberToAdd+i);
ptr->next = NULL;
if(start == NULL){
start=ptr;
}else{
current = start;
while(current->next != NULL){
current = current->next;
}
current->next = ptr;
}
}
return start;
}
void traverse(struct node* address){
current = address;
cout<<"\n";
while(current != NULL){
cout<<current->data<<" ";
current=current->next;
}
cout<<"\n";
}
|
419ca0715b57389693266b4a171327b3caeb5811
|
0cbe1b1f25cb43b7a007558be47448e42dc4cbc6
|
/P4/color.h
|
9d6b977bf1f48543c2508983147fd5b34f099024
|
[] |
no_license
|
AlbertoLorente92/practicas-IG
|
1d8455e76703b31ecab54b908579919b903adc0f
|
1b6939fad116580dbeff599f3df657e744030ace
|
refs/heads/master
| 2021-01-11T11:07:42.590604
| 2016-02-02T20:38:25
| 2016-02-02T20:38:25
| 50,950,114
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 1,934
|
h
|
color.h
|
/* Práctica 4 - Informática Gráfica (IG)
Componentes del grupo:
Juan Deltell Mendicute.
Alberto Lorente Sánchez.
*/
#ifndef __COLOR_H
#define __COLOR_H
#define Black Color(0.0f,0.0f,0.0f)
#define Red Color(1.0f,0.0f,0.0f)
#define Blue Color(0.0f,0.0f,1.0f)
#define Green Color(0.0f,0.1f,0.0f)
#define Yellow Color(1.0f,1.0f,0.0f)
#define Cyan Color(0.0f,1.0f,1.0f)
#define Magenta Color(1.0f,0.0f,1.0f)
#define White Color(1.0f,1.0f,1.0f)
#define Gray Color(0.5f,0.5f,0.5f)
#define Orange Color(1.0f,0.5f,0.0f)
#define Brown Color(0.647059f,0.164706f,0.164706f)
/**
Implementación del TAD Color.
Las operaciones son:
- Color: float, float, float -> Color. Generadora.
Getters:
- getF1: -> float. Observadora.
- getF2: -> float. Observadora.
- getF3: -> float. Observadora.
Setters:
- setF1: float -> void. Modificadora.
- setF2: float -> void. Modificadora.
- setF3: float -> void. Modificadora.
Metodos:
- difuminar: int -> Color. Modificadora.
- esNegro: -> bool. Observadora.
*/
class Color {
public:
//Constructora:
/**
Constructora de la clase color con 3 parametros.
*/
Color(float a,float b,float c){
_A=a;
_B=b;
_C=c;
}
Color(){}
//Getters:
/**
Devuelve el primer parametro del color.
*/
float getF1() const{
return _A;
}
/**
Devuelve el segundo parametro del color.
*/
float getF2() const{
return _B;
}
/**
Devuelve el tercer parametro del color.
*/
float getF3() const{
return _C;
}
//Setters:
/**
Establece un nuevo primer parametro del color.
*/
void setF1(float f){
_A =f;
}
/**
Establece un nuevo segundo parametro del color.
*/
void setF2(float f){
_B =f;
}
/**
Establece un nuevo tercer parametro del color.
*/
void setF3(float f){
_C =f;
}
//Metodos:
void Color::operator= (const Color& c){
_A = c.getF1();
_B = c.getF2();
_C = c.getF3();
}
private:
float _A;
float _B;
float _C;
};
#endif // __COLOR_H
|
756ae27006822b55f95c46b26bd2edebaf06f4ae
|
e88816b0597e739cb9418cb2f5ae53c4be21d964
|
/pouringWater.cpp
|
92ce441819035c3e2f953afa7e545400f672f300
|
[] |
no_license
|
vaibhavjain2391/Spoj-Practise
|
e62a78f8f18a20d199905ba4753bece71ca488d0
|
d068a209fe92994059890f617cb7b233d7943ccb
|
refs/heads/master
| 2021-01-10T02:13:07.111346
| 2015-11-08T19:54:10
| 2015-11-08T19:54:10
| 45,796,166
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 930
|
cpp
|
pouringWater.cpp
|
#include<iostream>
using namespace std;
int minSteps(int a, int b, int c);
int main()
{
int t,a,b,c,result;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>a>>b>>c;
if(c==0)
cout<<0<<endl;
else
{
result= minSteps(a,b,c);
cout<<result<<endl;
}
}
return 0;
}
//some cases are not considered ..thats y getting wa for ex. : Answer for 10 7 6 is 6
int minSteps(int a, int b, int c)
{
if(a==c || b==c)
return 1;
if(a<c && b<c)
return -1;
int result = -1,tmp;
if(a>c && b>c)
{
if(a<b){
tmp = a;
a=b;
b=tmp;
}
tmp = a-b;
tmp = b - tmp;
if(a-tmp == c)
result = 6;
}
if(a>c)
{
if(((a-c)%b) == 0)
{
result = ((a-c)/b)*2; //1 + (2*x-1) since, no need to throw away last mug
}
else if(c%b == 0)
{
result = 2* (c/b);
}
}
else
{
if(((b-c)%a) == 0)
{
result = ((b-c)/a)*2;
}
else if(c%a == 0)
{
result = 2* (c/a);
}
}
return result;
}
|
20f346854d33d40b88c07610c61d06b3d7a0bd79
|
9915247be962868b70dff74ce423575bfb325512
|
/Easy Problems/URI1080.cpp
|
53e3ff3d937f3c02df2bdb6c6e97999e8fba9366
|
[] |
no_license
|
abdulahad2307/JudgeSite-Practice-Codes
|
16b06fdb59d63dc2f9b86904a1d7e1f47e7ed276
|
9b2e401dc4571da5a8023edc8533d314b924636a
|
refs/heads/master
| 2023-06-25T17:14:29.993088
| 2021-07-29T22:21:26
| 2021-07-29T22:21:26
| 167,986,236
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 240
|
cpp
|
URI1080.cpp
|
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int n , tempmax , pos;
for (int i = 0 ; i < 100 ; i++)
{
scanf("%d", &n);
n = tempmax ;
if (n)
}
return 0;
}
|
d038a842bbf3be7bbd1b29264b35cdfa4a602d2d
|
d1650242d0749cd2aff3078a2591a188b0be3a58
|
/Advanced-lost and found/A1001/A1001/main.cpp
|
656ef866130e42bb456bff7a5f38d0b5efbac2cd
|
[
"MIT"
] |
permissive
|
Eric-Ma-C/PAT-Advanced
|
d92e1503b4e14a7a62964df7afd3b098573daba3
|
ea8b46a780a04b46ab35ebd06c4bf19c3a664380
|
refs/heads/master
| 2020-09-11T10:26:50.288469
| 2019-11-16T03:31:12
| 2019-11-16T03:33:45
| 222,035,114
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 856
|
cpp
|
main.cpp
|
#include<stdio.h>
//60min
int gcd(int a,int b){
if(b==0)
return a;
return gcd(b,a%b);
}
void simple(int *a,int* b){
if(*a==0||*b==0)
return;
int g=gcd(*a,*b);
*a/=g;
*b/=g;
}
bool getSum(int a1,int b1,int a2,int b2,int* a3,int* b3){
*a3=a1*b2+a2*b1;
*b3=b1*b2;
bool positive=true;
if(*a3<0){
*a3=-*a3;
positive=false;
}
simple(a3,b3);
if(!positive){
*a3=-*a3;
}
return positive;
}
int main(){
int n;
scanf("%d",&n);
int a[100][2];
for(int i=0;i<n;i++){
scanf("%d/%d",a[i]+0,a[i]+1);
}
int aa=0,bb=1;
for(int i=0;i<n;i++){
getSum(aa,bb,a[i][0],a[i][1],&aa,&bb);
}
if(aa==0){
printf("0");
return 0;
}
if(aa<0){
printf("-");
aa=-aa;
}
int c=aa/bb;
if(c!=0){
printf("%d",c);
aa-=c*bb;
}
if(aa!=0){
if(c!=0)
printf(" ");
printf("%d/%d",aa,bb);
}
getchar();
getchar();
return 0;
}
|
b8d56572ac3b275a3c3ac3743f2cbbbc4976edda
|
9cdfe0725dc4e22b95a22352491ba7579f5ddab7
|
/lab_1/src/core/action.hpp
|
9ffa46d3bcc7489cfcc9e32f850988e1b96270fb
|
[] |
no_license
|
RullDeef/cpp-lab
|
16722062ec97351e66c75905634d3bb057b0d317
|
9473b22a68a42ed45a582a6624ea6b96548dd16e
|
refs/heads/master
| 2023-06-18T22:35:57.794320
| 2021-07-20T08:58:36
| 2021-07-20T08:58:36
| 387,731,405
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 795
|
hpp
|
action.hpp
|
#pragma once
#include "ext_math.hpp"
namespace core
{
enum class ActionType
{
Init, // initializes viewport
Destroy, // releases model resources
Load, // load model from file
Save, // saves model to file
ComputeProjection, // updates projection, if needed
Translate, // translate model
Rotate, // rotate model
Scale // scale model
};
struct Action
{
ActionType type;
union
{
struct
{
double dx;
double dy;
};
double factor;
viewport viewport;
const char* filename;
};
};
}
|
67f1ab202d91af061ac53b42ecbf27dde15b3242
|
72b73e958eb174220ebaf3f8ebe3da4bf2f8e21b
|
/CodeChef/IIITHC14/1.cpp
|
6c4ce70709bea83669ae1b47549cb019689caa4f
|
[] |
no_license
|
AbhineetJain/Algorithmic-Programming
|
147bf620073ecb37994b0466b1cd1f156c36da2c
|
7980bd466118024c2aa0c4e982a70bc175171c49
|
refs/heads/master
| 2021-01-25T05:34:21.091342
| 2015-05-20T22:28:09
| 2015-05-20T22:28:09
| 26,182,801
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,698
|
cpp
|
1.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<int> VI;
typedef vector<LL> VLL;
#define SI(n) scanf("%d", &n)
#define SLL(n) scanf("%lld", &n)
#define SULL(n) scanf("%llu", &n)
#define sortv(v) sort(v.begin(), v.end())
#define pb(x) push_back(x)
#define mp(x, y) make_pair(x, y)
#define f first
#define s second
int checkRow(char arr[35][35], int i, int n);
int checkCol(char arr[35][35], int i, int n);
int arrCheck[35][35];
int main()
{
int tc, n;
char arr[35][35];
SI(tc);
while(tc--)
{
SI(n);
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
arrCheck[i][j] = 0;
for(int i=0; i<n; i++)
{
scanf("%s", arr[i]);
}
int ans = 1;
int flag = 0;
int i, j;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
if(arrCheck[i][j] == 0 && arr[i][j] == '1')
{
// cout<<i<<j<<" "<<arr[i][j]<<" ";
flag = checkRow(arr, i, n);
// cout<<flag<<" ";
if(not flag)
flag = checkCol(arr, j, n);
// cout<<flag<<"\n";
if(not flag)
break;
}
}
// cout<<flag<<"\n";
if(not flag && j != n)
{
ans = 0;
break;
}
}
if(ans)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
int checkRow(char arr[35][35], int row, int n)
{
int flag = 0;
for(int i=0; i<n; i++)
{
if(arr[row][i] != '1')
flag = 1;
if(flag)
break;
}
if(!flag)
for(int i=0; i<n; i++)
arrCheck[row][i] = 1;
return !flag;
}
int checkCol(char arr[35][35], int col, int n)
{
int flag = 0;
for(int i=0; i<n; i++)
{
if(arr[i][col] != '1')
flag = 1;
if(flag)
break;
}
if(!flag)
for(int i=0; i<n; i++)
arrCheck[i][col] = 1;
return !flag;
}
|
7e95469f2808c9955a2fb946baa8017b9ead4a98
|
8d32836a6c2e7e458a2a6d6f4d89f2e5c659673e
|
/src/ronin-world/Spell/SpellTarget.h
|
9a9118957a0f81405413520099246f38f52a47d8
|
[] |
no_license
|
Sandshroud/Ronin
|
e92e53c81fdab4cefc0de964d2fb8cebc34ee41e
|
94986c95e88abe6cedd240e0ce95f6f213b05d90
|
refs/heads/master
| 2023-05-10T21:58:29.115832
| 2023-04-29T04:26:34
| 2023-04-29T04:26:34
| 74,101,915
| 12
| 7
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,973
|
h
|
SpellTarget.h
|
#pragma once
class SpellTargetClass;
class MapTargetCallback { public: virtual void operator()(SpellTargetClass *spell, uint32 i, uint32 targetType, WorldObject *target) = 0; };
class FillAreaTargetsCallback : public MapTargetCallback { virtual void operator()(SpellTargetClass *spell, uint32 i, uint32 targetType, WorldObject *target); };
class FillAreaFriendliesCallback : public MapTargetCallback { virtual void operator()(SpellTargetClass *spell, uint32 i, uint32 targetType, WorldObject *target); };
class FillInRangeTargetsCallback : public MapTargetCallback { virtual void operator()(SpellTargetClass *spell, uint32 i, uint32 targetType, WorldObject *target); };
class FillInRangeConeTargetsCallback : public MapTargetCallback { virtual void operator()(SpellTargetClass *spell, uint32 i, uint32 targetType, WorldObject *target); };
class FillSpecificGameObjectsCallback : public MapTargetCallback { virtual void operator()(SpellTargetClass *spell, uint32 i, uint32 targetType, WorldObject *target); };
class SpellTargetClass : public SpellEffectClass
{
public:
SpellTargetClass(Unit* caster, SpellEntry *info, uint8 castNumber, WoWGuid itemGuid);
~SpellTargetClass();
virtual void Destruct();
// Checks to see if our effect that triggers the strike will occur regardless of target cone
static bool isSpellAOEStrikeable(SpellEntry *sp, uint8 effIndex);
protected:
// Get Target Type
uint32 GetTargetType(uint32 implicittarget, uint32 i);
// adds a target to the list, performing DidHit checks on units
void _AddTarget(WorldObject* target, const uint32 effIndex);
uint8 _DidHit(Unit* target, float *resistOut = NULL, uint8 *reflectout = NULL);
// If we check friendly or combat support for friendly target checks
bool requiresCombatSupport(uint32 effIndex);
// Some spell effects require the caster to trigger an effect
bool EffectRequiresAnyTarget(uint32 i);
// If we have max targets we can check if we're full on targets
bool IsTargetMapFull(uint32 effIndex, WoWGuid guidCheck = 0);
public:
// Fills specified targets at the area of effect
void FillSpecifiedTargetsInArea(float srcx,float srcy,float srcz, uint32 effIndex, uint32 typeMask);
// Fills specified targets at the area of effect. We suppose we already inited this spell and know the details
void FillSpecifiedTargetsInArea(uint32 i, float srcx,float srcy,float srcz, float r, uint32 typeMask);
// Fills the targets at the area of effect
void FillAllTargetsInArea(uint32 i, float srcx,float srcy,float srcz, float r, bool includegameobjects = false);
// Fills the targets at the area of effect. We suppose we already inited this spell and know the details
void FillAllTargetsInArea(float srcx,float srcy,float srcz, uint32 effIndex);
// Fills the targets at the area of effect. We suppose we already inited this spell and know the details
void FillAllTargetsInArea(LocationVector & location, uint32 effIndex);
// Fills the targets at the area of effect. We suppose we already inited this spell and know the details
void FillAllFriendlyInArea(uint32 i, float srcx,float srcy,float srcz, float r);
// Fills the gameobject targets at the area of effect
void FillAllGameObjectTargetsInArea(uint32 i, float srcx,float srcy,float srcz, float r);
//get single Enemy as target
WoWGuid GetSinglePossibleEnemy(uint32 i, float prange=0);
//get single Enemy as target
WoWGuid GetSinglePossibleFriend(uint32 i, float prange=0);
//generate possible target list for a spell. Use as last resort since it is not acurate
bool GenerateTargets(SpellCastTargets *);
// Fills the target map of the spell effects
void FillTargetMap(bool fromDelayed);
// Spell Targets
void HandleTargetNoObject(uint32 i, float r);
bool AddTarget(uint32 i, uint32 TargetType, WorldObject* obj);
void AddAOETargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
void AddPartyTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
void AddRaidTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets, bool partylimit = false);
void AddChainTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
void AddConeTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
void AddScriptedOrSpellFocusTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
WoWGuid static FindLowestHealthRaidMember(Player* Target, uint32 dist);
static std::map<uint8, uint32> m_implicitTargetFlags;
private:
std::vector<WorldObject*> *m_temporaryStorage;
protected:
AuraApplicationResult CheckAuraApplication(Unit *target);
friend class MapTargetCallback;
friend class FillAreaTargetsCallback;
friend class FillAreaFriendliesCallback;
friend class FillInRangeTargetsCallback;
friend class FillInRangeConeTargetsCallback;
friend class FillSpecificGameObjectsCallback;
};
|
0bdd4caaa9a2c5c802c198cded69174a29c80174
|
316f9700e749be3fb7057cf5c657a0d82e1f73f5
|
/Pong/Tetris/Window.cpp
|
07ab1ac657eb4b2ca7639912e7477db239330da3
|
[] |
no_license
|
StillOP/Pong
|
e2a077a9d19b18fde0e53dee5c88f920b1dae04b
|
31862079f1c764d902651c5dccab6bd54aa756d5
|
refs/heads/master
| 2021-01-20T17:40:04.507150
| 2017-05-10T15:42:32
| 2017-05-10T15:42:32
| 90,881,237
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,380
|
cpp
|
Window.cpp
|
#include "Window.h"
Window::Window()
{
isFullscreen = false;
CreateWindow("Tetris", sf::Vector2u(800, 640));
}
Window::Window(const std::string winTitle, sf::Vector2u winSize)
{
isFullscreen = false;
CreateWindow(winTitle, winSize);
}
Window::~Window() { ShutDown(); }
void Window::CreateWindow(const std::string winTitle, sf::Vector2u winSize)
{
isDone = false;
windowTitle = winTitle;
windowWidth = winSize.x;
windowHeight = winSize.y;
auto style = (isFullscreen ? sf::Style::Fullscreen : sf::Style::Default);
window.create({ windowWidth, windowHeight, 32 }, windowTitle, style);
}
void Window::WindowUpdate()
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
isDone = true;
else
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::F5)
SetFullScreen();
}
}
void Window::SetFullScreen()
{
isFullscreen = !isFullscreen;
ShutDown();
CreateWindow(windowTitle, sf::Vector2u(800, 640));
}
void Window::ShutDown()
{
window.close();
}
void Window::BeginDraw() { window.clear(sf::Color::Black); }
void Window::EndDraw() { window.display(); }
bool Window::IsDone() { return isDone; }
unsigned int Window::GetWindowWidth() { return windowWidth; }
unsigned int Window::GetWindowHeight() { return windowHeight; }
sf::RenderWindow* Window::GetRenderWindow() { return &window; }
|
7db2fe05d50173b2eeaa7dfe142a13dcf0c9d36a
|
30098fb8cb19aee196255ce42c7cedfe3fc087a6
|
/headers/cCustomer.h
|
adbb46bb0c8e9ecd1da340364d747b1b21d3ece0
|
[] |
no_license
|
xrds6/Tring.Touch.POS
|
c9e6c0ccf6df2dc7c34dbedd62c2fe31dd3cba81
|
cc30a17eb46dd9e0ab8c09a595aa77ebb350480d
|
refs/heads/master
| 2021-06-30T19:18:39.177420
| 2017-09-20T09:55:51
| 2017-09-20T09:55:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,500
|
h
|
cCustomer.h
|
#ifndef CUSTOMER_H
#define CUSTOMER_H
#include <QObject>
#include <QString>
#include <QDateTime>
#include <QDebug>
class cCustomer : public QObject
{
Q_OBJECT
Q_PROPERTY(qint32 id READ id WRITE setId
NOTIFY customerChanged)
Q_PROPERTY(QString idc READ idc WRITE setIdc
NOTIFY customerChanged)
Q_PROPERTY(QString vat_number READ vat_number WRITE setVatNumber
NOTIFY customerChanged)
Q_PROPERTY(QString line1 READ line1 WRITE setLine1
NOTIFY customerChanged)
Q_PROPERTY(QString line2 READ line2 WRITE setLine2
NOTIFY customerChanged)
Q_PROPERTY(QString line3 READ line3 WRITE setLine3
NOTIFY customerChanged)
Q_PROPERTY(QString line4 READ line4 WRITE setLine4
NOTIFY customerChanged)
// Q_PROPERTY(QDateTime created READ created WRITE setCreated
// NOTIFY customerChanged)
// Q_PROPERTY(qint32 createdBy READ createdBy WRITE setCreatedBy
// NOTIFY customerChanged)
// Q_PROPERTY(QDateTime modified READ modified WRITE setModified
// NOTIFY customerChanged)
// Q_PROPERTY(qint32 modifiedBy READ modifiedBy WRITE setModifiedBy
// NOTIFY customerChanged)
public:
explicit cCustomer(QObject *parent = 0);
cCustomer(qint32 id, QString idc, QString line1, QString line2,
QString line3, QString line4);
~cCustomer() {}// qDebug() << "Customer dying"; }
qint32 id();
void setId(qint32 id);
QString idc();
void setIdc(QString idc);
QString vat_number();
void setVatNumber(QString vat_number);
QString line1();
void setLine1(QString line1);
QString line2();
void setLine2(QString line2);
QString line3();
void setLine3(QString line3);
QString line4();
void setLine4(QString line4);
// QDateTime created();
// void setCreated(QDateTime created);
// qint32 createdBy();
// void setCreatedBy(qint32 createdBy);
// QDateTime modified();
// void setModified(QDateTime modified);
// qint32 modifiedBy();
// void setModifiedBy(qint32 modifiedBy);
private:
qint32 _id;
QString _idc;
QString _vatNumber;
QString _line1;
QString _line2;
QString _line3;
QString _line4;
// QDateTime _created;
// qint32 _createdBy;
// QDateTime _modified;
// qint32 _modifiedBy;
signals:
void customerChanged();
};
Q_DECLARE_METATYPE(cCustomer*)
#endif // CUSTOMER_H
|
3e8efa07a0b66f0329390f70cfadde3830477ea9
|
96b101112ddad9f748686411b38202072d246a6e
|
/src/main.cpp
|
ced1108a3f6189bb4b2521e4e2121ef1225c14c0
|
[] |
no_license
|
cheshie/Croc-Remake-OpenGL
|
40a4e5fb8176ed1ad503ad3e062c65841c62c154
|
939f72a523c47a85f3387416e2559d85edbb553f
|
refs/heads/master
| 2022-01-28T19:41:15.878744
| 2019-07-16T09:37:51
| 2019-07-16T09:37:51
| 197,160,589
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 62,567
|
cpp
|
main.cpp
|
#include "stdafx.h"
#include <string.h>
void OnRender();
void OnReshape(int, int);
void OnKeyPress(unsigned char, int, int);
void OnKeyDown(unsigned char, int, int);
void OnKeyUp(unsigned char, int, int);
void OnTimer(int);
void OnMouseMove(int, int);
void OnMouseClick(int, int, int, int);
void loadtextures();
void Render_level1();
void Render_level2();
void Render_level3();
void Render_level4();
void Initialize_level1();
void Initialize_level2();
void Initialize_level3();
void Initialize_level4();
void Render_lights();
void dropdiamonds();
void checkandrenderdiamonds(int start, int end);
void checkandrenderspecialdiamonds(int index);
void checkandrenderhearts(int start, int end);
void initializediamonds(int howmanydiamonds);
// // // // // LEVEL 1 DECLARATIONS // // // // //
Sphere * movableSphere;
Terrain * Level1_floor;
Terrain * Level1_rock;
Terrain * Level1_walls;
Enemy * Level1_enemy;
Terrain * Level1_well1_walls;
Terrain * Level1_doors_right;
Terrain * Level1_doors_frame;
Terrain * Level1_doors_left;
Terrain * Level1_pool;
Terrain * Level1_teleportbox;
Scene scene;
Blackbox *trunk1;
Camera * camera;
Player * player;
NormalBox * box1;
Diamond * diamond;
Key * key;
Platform * Level1_platform1;
Platform * Level1_platform2;
Platform * Level1_well1_cover;
Platform * Level1_well1_teleport;
Friend * Level1_friend1;
Well1 * well1;
Wood * wood;
cLava * Level1_lava;
Heart * heart;
vec3 * hearts_coords;
bool * hearts_taken;
vec3 * diamonds_coords;
bool * diamonds_taken;
int window_width, window_height;
vec3 mousePosition;
float diam_rot = 0.0f;
bool captureMouse;
bool light1state = true;
bool light2state = true;
bool light3state = false;
bool lavalightstate = true;
bool goldentrunkstate = true;
bool jump = 0;
bool started_game = 0;
float jump_height = 3.5f;
float jump_temp = 0.0f;
float time_since_start = 0.f;
vec3 * box_coords;
vec3 * trunks_position;
Sphere *playerS;
// // // // // LEVEL 1 DECLARATIONS // // // // //
// // // // // LEVEL 2 DECLARATIONS // // // // //
Terrain * Level2_floor1;
Terrain * Level2_arch;
Terrain * Level2_kopula;
Terrain * Level2_wall1;
Terrain * Level2_floor2;
Terrain * Level2_getbacktolevel1;
Terrain * Level2_getbacktolevel1wall;
Terrain * Level2_teleportboxto1;
Terrain * Level2_floor3;
Terrain * Level2_lastwall;
Terrain * Level2_doorsright1;
Terrain * Level2_doorsleft1;
Terrain * Level2_doorsright2;
Terrain * Level2_doorsleft2;
Terrain * Level2_arch2;
Terrain * Level2_teleportboxfinal;
Platform * Level2_movingplatform1;
Platform * Level2_movingplatform2;
Friend * Level2_friend1;
Terrain * Level2_finalgong;
cLava * Level2_lava;
// // // // // LEVEL 2 DECLARATIONS // // // // //
// // // // // LEVEL 3 DECLARATIONS // // // // //
Terrain * Level3_floor1;
Terrain * Level3_floor2;
Well1 * Level3_well1;
Platform * Level3_well1_teleport;
Platform * Level3_fallingplatform1;
Platform * Level3_fallingplatform2;
Platform * Level3_fallingplatform3;
bool light4state = 0;
float angle_diamonds;
Enemy * Level3_BIGENEMY;
Enemy * Level3_smallenemy;
vec3 * smallenemy_coords;
bool * smallenemy_isalive;
Friend * Level3_friend1;
// // // // // LEVEL 3 DECLARATIONS // // // // //
// // // // // LEVEL 4 DECLARATIONS // // // // //
Terrain * Level4_floor1;
Terrain * Level4_walls;
Terrain * Level4_floor2;
Terrain * Level4_floor_moving1;
Terrain * Level4_floor_moving2;
Terrain * Level4_floor_moving3;
Terrain * Level4_floor_moving4;
Terrain * Level4_floor_moving5;
Terrain * Level4_floor_moving6;
Terrain * Level4_floor_moving7;
Terrain * Level4_floor_moving9;
Terrain * Level4_grid1;
Terrain * Level4_grid2;
Terrain * Level4_hempisphere;
Platform * Level4_platform1;
Platform * Level4_platform2;
Platform * Level4_platform3;
Platform * Level4_platform4;
Platform * Level4_platform5;
Platform * Level4_platform6;
Platform * Level4_platform7;
Platform * Level4_platform8;
Well1 * Level4_well1;
Platform * Level4_teleport;
Friend * Level4_friend;
cLava * Level4_lava;
// // // // // LEVEL 4 DECLARATIONS // // // // //
// MISC //
float diamonds_drop = 0;
bool dropping = 0;
vec3 * dropped_coords;
bool * dropped_state;
float * dropped_size;
Diamond * DDiam;
// MISC //
// MAIN MENU //
bool ismainMenuActive = 1;
//MAIN MENU //
Terrain * daniotest;
Terrain * torus;
Terrain * croc_corpse;
Terrain * croc_eyes;
Terrain * croc_backpack;
// / // / / / / // / / / / / / // /
//Pytania do prowadzacego:
// Kamera - jak zrobic to plynnne obracanie
// Swiatla - dlaczego na 3 lvl nie dzialaja z ta latarka?
// skompilowac kod na windows
// dzwiek - nie dziala openal
//Textury w blenderze - jak tutaj je wrzucic?
// / // / / / / // / / / / / / // /
float T = 0;
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitWindowPosition(100, 100);
glutInitWindowSize(800, 600);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Croc: Gobbos Tribute");
glutDisplayFunc(OnRender);
glutReshapeFunc(OnReshape);
glutKeyboardFunc(OnKeyPress);
glutKeyboardUpFunc(OnKeyUp);
glutTimerFunc(17, OnTimer, 0);
glutPassiveMotionFunc(OnMouseMove);
glutMotionFunc(OnMouseMove);
glutMouseFunc(OnMouseClick);
glClearColor(0.1f, 0.2f, 0.3f, 0.0);
glEnable(GL_DEPTH_TEST);
float gl_amb[] = { 0.0f, 0.0f, 0.0f, 1.0f };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, gl_amb);
glEnable(GL_LIGHTING);
glShadeModel(GL_SMOOTH);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
FreeConsole();
// Camera and player initialization
player = new Player(vec3(2.5f, 1.f, 0.f), vec3(1.f, 0.f, 0.f), vec3(0.f, 0.f, 0.f), vec3(0.01f, 0.01f, 0.01f), 0.f);
player->Load("../Resources/Models/Diamond.obj");
player->textureName = "nope";
scene.AddObject(player);
croc_corpse = new Terrain(vec3(-0.6f, 0.f, 0.f), vec3(0.03, 0.03, 0.03), 180.f, vec3(0.6, 0.2, 0.8));
croc_corpse->load("../Resources/Models/croc_corpse.obj");
croc_corpse->textureName = "croc_corpse";
croc_eyes = new Terrain(vec3(-0.6f, 0.f, 0.f), vec3(0.03, 0.03, 0.03), 180.f, vec3(0.6, 0.2, 0.8));
croc_eyes->load("../Resources/Models/croc_eyes.obj");
croc_eyes->textureName = "croc_eyes";
croc_backpack = new Terrain(vec3(-0.6f, 0.f, 0.f), vec3(0.03, 0.03, 0.03), 180.f, vec3(0.6, 0.2, 0.8));
croc_backpack->load("../Resources/Models/croc_backpack.obj");
croc_backpack->textureName = "croc_backpack";
camera = new Camera(vec3(player->pos.x, player->pos.y, 0.f), vec3(-1.0f, -.5f, 0.0f), vec3(0.f, 0.f, 0.f), 0.f);
scene.AddObject(camera);
torus = new Terrain(vec3(player->pos.x, player->pos.y, 0.f), vec3(0.6, 0.6, 0.6), 0.f, vec3(0.2, 0.6, 0.8));
torus->load("../Resources/Models/Torus_tapniecie.obj");
torus->textureName = "torus";
//Angle diamonds
angle_diamonds = 0.f;
//Initialization of levels
Initialize_level1();
Initialize_level2();
Initialize_level3();
Initialize_level4();
loadtextures();
//starting position
player->pos.x = 2.f;
player->pos.y = 0.8f;
player->pos.z = 0.f;
glutMainLoop();
return 0;
}
bool keystate[256];
void OnKeyPress(unsigned char key, int x, int y) {
if (!keystate[key]) {
OnKeyDown(key, x, y);
}
//else
//OnKeyUp(key,x,y);
keystate[key] = true;
}
void OnKeyDown(unsigned char key, int x, int y) {
if (key == 27) {
if(ismainMenuActive == 1)
exit(0);
//glutLeaveMainLoop();
if (ismainMenuActive == 0)
ismainMenuActive = 1;
//else
glutSetCursor(GLUT_CURSOR_LEFT_ARROW);
captureMouse = false;
}
if (key == 'o')
{
if (ismainMenuActive == 1)
if (started_game == 0)
{
////printf("New Game\n");
glutSetCursor(GLUT_CURSOR_NONE);
captureMouse = true;
glutWarpPointer(window_width / 2, window_height / 2);
player->currentlevel = 1;
ismainMenuActive = 0;
started_game = 1;
}
}
if (key == 'p')
{
if (ismainMenuActive == 1)
if (started_game == 1)
{
////printf("Continue\n");
glutSetCursor(GLUT_CURSOR_NONE);
captureMouse = true;
glutWarpPointer(window_width / 2, window_height / 2);
ismainMenuActive = 0;
}
}
if (key == 'f')
{
player->flyingMode = !player->flyingMode;
}
if (key == '1')
{
light1state = !light1state;
}
if (key == '2')
{
light2state = !light2state;
}
if (key == '3')
{
light3state = !light3state;
}
if (key == '4')
{
player->stop = 1;
//////printf("stop!\n");
}
//Skok - spacja
if (key == 32)
{
//player->onground = 0;
if (player->jumping == 0)
{
player->maxrelativeheight = player->pos.y;
player->makejump();
player->doublejump = 0;
player->falling = 1;
}
if (player->jumping && player->doublejump == 0 && fabs(player->pos.y - player->maxrelativeheight) >= 1.0f && player->timetonextjump == 0.f)
{
player->timetonextjump = 300.f;
player->doublejump = 1;
}
}
if (key == 'c' || player->doublejump == 1)
{
if (sqrt((player->pos.x - Level1_enemy->pos.x)*(player->pos.x - Level1_enemy->pos.x) + (player->pos.z - Level1_enemy->pos.z)*(player->pos.z - Level1_enemy->pos.z)) < 0.4)
{
Level1_enemy->isAlive = 0;
player->showtorus =1;
//Level1_enemy->dissapearanimation();
}
for (int i = 0; i<10; i++)
{
if (sqrt((player->pos.x - smallenemy_coords[i].x)*(player->pos.x - smallenemy_coords[i].x) + (player->pos.z - smallenemy_coords[i].z)*(player->pos.z - smallenemy_coords[i].z)) < 0.5)
{
smallenemy_isalive[i] = 0;
dropping = 1;
player->showtorus =1;
}
}
if(sqrt((player->pos.x - Level2_finalgong->pos.x)*(player->pos.x - Level2_finalgong->pos.x) + (player->pos.z - Level2_finalgong->pos.z)*(player->pos.z - Level2_finalgong->pos.z)) < 0.25 && player->iWonTheGame == 0 && player->specialdiamonds[0] == 1 && player->specialdiamonds[1] == 1 && player->specialdiamonds[2] == 1)
{
player->iWonTheGame = 1;
ismainMenuActive = 0;
}
}
if(key == 'c')
{
player->turn = 1;
}
if (key == 'x')
{
player->direction *= -1;
}
}
void OnKeyUp(unsigned char key, int x, int y) {
keystate[key] = false;
}
void OnMouseMove(int x, int y)
{
mousePosition.x = x;
mousePosition.y = y;
}
void OnMouseClick(int button, int state, int x, int y)
{
if (ismainMenuActive == 1)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
//. glutInitWindowSize(800, 600);
//
// if (mousePosition.x > 202 * glutGet(GLUT_WINDOW_WIDTH) / 800 && mousePosition.x * glutGet(GLUT_WINDOW_WIDTH) / 800 < 560 && mousePosition.y * glutGet(GLUT_INIT_WINDOW_HEIGHT) / 600 > 301 && mousePosition.y * glutGet(GLUT_INIT_WINDOW_HEIGHT) / 600 < 352)
if (mousePosition.x > glutGet(GLUT_WINDOW_WIDTH)/4 && mousePosition.x < (glutGet(GLUT_WINDOW_WIDTH)/2 + glutGet(GLUT_WINDOW_WIDTH)/6) && mousePosition.y > glutGet(GLUT_WINDOW_HEIGHT)/2 && mousePosition.y < (glutGet(GLUT_WINDOW_HEIGHT)/2 + glutGet(GLUT_WINDOW_HEIGHT)/12) )
{
if (started_game == 0)
{
////printf("New Game\n");
glutSetCursor(GLUT_CURSOR_NONE);
captureMouse = true;
glutWarpPointer(window_width / 2, window_height / 2);
player->currentlevel = 1;
ismainMenuActive = 0;
}
}
//if (mousePosition.x > 202 && mousePosition.x < 560 && mousePosition.y > 393 && mousePosition.y < 446)
if (mousePosition.x > glutGet(GLUT_WINDOW_WIDTH)/4 && mousePosition.x < (glutGet(GLUT_WINDOW_WIDTH)/2 + glutGet(GLUT_WINDOW_WIDTH)/6) && mousePosition.y > glutGet(GLUT_WINDOW_HEIGHT)/1.5 && mousePosition.y < (glutGet(GLUT_WINDOW_HEIGHT)/1.5 + glutGet(GLUT_WINDOW_HEIGHT)/12) )
{
if (started_game == 1)
{
////printf("Continue\n");
glutSetCursor(GLUT_CURSOR_NONE);
captureMouse = true;
glutWarpPointer(window_width / 2, window_height / 2);
ismainMenuActive = 0;
}
}
//if (mousePosition.x > 202 && mousePosition.x < 560 && mousePosition.y > 482 && mousePosition.y < 541)
if (mousePosition.x > glutGet(GLUT_WINDOW_WIDTH)/4 && mousePosition.x < (glutGet(GLUT_WINDOW_WIDTH)/2 + glutGet(GLUT_WINDOW_WIDTH)/6) && mousePosition.y > glutGet(GLUT_WINDOW_HEIGHT)/1.2 && mousePosition.y < (glutGet(GLUT_WINDOW_HEIGHT)/1.2 + glutGet(GLUT_WINDOW_HEIGHT)/12) )
{
////printf("Exit\n");
delete[] smallenemy_coords;
delete[] smallenemy_isalive;
delete[] hearts_coords;
delete[] hearts_taken;
delete[] diamonds_coords;
delete[] diamonds_taken;
delete[] dropped_coords;
delete[] dropped_state;
delete[] dropped_size;
delete movableSphere;
delete Level1_floor;
delete Level1_rock;
delete Level1_walls;
delete Level1_enemy;
delete Level1_well1_walls;
delete Level1_doors_right;
delete Level1_doors_frame;
delete Level1_doors_left;
delete Level1_pool;
delete Level1_teleportbox;
delete trunk1;
delete camera;
delete player;
delete box1;
delete diamond;
delete key;
delete Level1_platform1;
delete Level1_platform2;
delete Level1_well1_cover;
delete Level1_well1_teleport;
delete Level1_friend1;
delete well1;
delete wood;
delete Level1_lava;
delete heart;
delete box_coords;
delete trunks_position;
delete playerS;
// // // // // LEVEL 1 DECLARATIONS // // // // //
// // // // // LEVEL 2 DECLARATIONS // // // // //
delete Level2_floor1;
delete Level2_arch;
delete Level2_kopula;
delete Level2_wall1;
delete Level2_floor2;
delete Level2_getbacktolevel1;
delete Level2_getbacktolevel1wall;
delete Level2_teleportboxto1;
delete Level2_floor3;
delete Level2_lastwall;
delete Level2_doorsright1;
delete Level2_doorsleft1;
delete Level2_doorsright2;
delete Level2_doorsleft2;
delete Level2_arch2;
delete Level2_teleportboxfinal;
delete Level2_movingplatform1;
delete Level2_movingplatform2;
delete Level2_lava;
// // // // // LEVEL 2 DECLARATIONS // // // // //
// // // // // LEVEL 3 DECLARATIONS // // // // //
delete Level3_floor1;
delete Level3_floor2;
delete Level3_well1;
delete Level3_well1_teleport;
delete Level3_fallingplatform1;
delete Level3_fallingplatform2;
delete Level3_fallingplatform3;
delete Level3_BIGENEMY;
delete Level3_smallenemy;
delete smallenemy_coords;
delete smallenemy_isalive;
// // // // // LEVEL 3 DECLARATIONS // // // // //
// // // // // LEVEL 4 DECLARATIONS // // // // //
delete Level4_floor1;
delete Level4_walls;
delete Level4_floor2;
delete Level4_floor_moving1;
delete Level4_floor_moving2;
delete Level4_floor_moving3;
delete Level4_floor_moving4;
delete Level4_floor_moving5;
delete Level4_floor_moving6;
delete Level4_floor_moving7;
delete Level4_floor_moving9;
delete Level4_platform1;
delete Level4_platform2;
delete Level4_platform3;
delete Level4_platform4;
delete Level4_lava;
exit(0);
}
}
}
}
void OnTimer(int id) {
float kierunek_horizontal = (float)atan2(player->dir.z, player->dir.x);
float kierunek_vertical = (float)atan2(player->dir.z, player->dir.y);
bool isplayerinmoveu = 0;
bool isplayerinmoved = 0;
bool isplayerinmovel = 0;
bool isplayerinmover = 0;
if (ismainMenuActive == 0)
{
if (keystate['w'] && player->iWonTheGame != 1) {
player->pos = player->pos - (player->dir * player->speed);
}
if (keystate['s'] && player->iWonTheGame != 1) {
player->pos = player->pos + (player->dir * player->speed);
}
if (keystate['a'] && player->iWonTheGame != 1 && player->direction != -1) {
player->rotate += 1.2 * player->direction;
//isplayerinmovel = 1;
}
if (keystate['d']&& player->iWonTheGame != 1 && player->direction != -1) {
//player->velocity_horizontal = 1;
player->rotate -= 1.2 * player->direction;
//isplayerinmover = 1;
}
if (keystate['q']) {
//player->velocity_horizontal = -1;
//player->rotate -= 0.8;
//isplayerinmover = 1;
}
if (keystate['e']) {
//player->velocity_horizontal = 1;
//player->rotate -= 0.8;
//isplayerinmover = 1;
}
if (isplayerinmoveu || isplayerinmoved || isplayerinmovel || isplayerinmover)
player->ismoving = 1;
else
player->ismoving = 0;
}
if (captureMouse)
{
glutWarpPointer(window_width / 2, window_height / 2);
}
if (keystate['e']) {
player->rotate += 0.8;
}
if (keystate['q']) {
player->rotate -= 0.8;
}
if (keystate['o'])
{
}
scene.Update();
glutTimerFunc(17, OnTimer, 0);
}
void OnRender() {
float time_since_start_new = glutGet(GLUT_ELAPSED_TIME);
player->deltatime = time_since_start_new - time_since_start;
camera->deltatime = time_since_start_new - time_since_start;
time_since_start = time_since_start_new;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//scene.CokolwiekDisplay();
if (ismainMenuActive == 0 && player->iWonTheGame == 0)
{
scene.DiamondDisplay();
scene.Diamond1Display(*player);
scene.Diamond2Display(*player);
scene.Diamond3Display(*player);
scene.LifeDisplay();
scene.KeyDisplay(*player);
scene.NumberofDiamondsDisplayd1(*player);
scene.NumberofDiamondsDisplayd2(*player);
scene.NumberofLivesDisplayd1(*player);
scene.NumberofLivesDisplayd2(*player);
scene.FriendDisplay();
scene.NumberoffriendsDisplayd1(*player);
scene.NumberoffriendsDisplayd2(*player);
}
if (ismainMenuActive == 1 && player->iWonTheGame == 0)
{
scene.mainMenuNewGame();
scene.mainMenuContinue();
scene.mainMenuExit();
scene.mainMenuCover();
}
if ( player->iWonTheGame == 1 )
{
scene.mainMenuConGratulations();
scene.ResultDiamond();
scene.ResultDisplayd1(player->diamonds_counter,0);
scene.ResultDisplayd2(player->diamonds_counter,0);
scene.ResultFriend();
scene.ResultDisplayd1(player->friendscounter,20);
scene.ResultDisplayd2(player->friendscounter,20);
scene.ResultLife();
scene.ResultDisplayd1(player->lives_counter,40);
scene.ResultDisplayd2(player->lives_counter,40);
}
camera->myUpdate(*player, scene.boundaryMax, scene.boundaryMin);
//player->test_sphere();
player->Render();
croc_corpse->Render("croc_corpse",*player);
croc_backpack->Render("croc_backpack",*player);
croc_eyes->Render("croc_eyes",*player);
player->Update();
if (player->timetoblink == 0 && player->timesblink > 0)
{
player->timetoblink = 10.f;
player->timesblink--;
}
if (player->currentlevel == 1)
Render_level1();
if (player->currentlevel == 2)
Render_level2();
if (player->currentlevel == 3)
Render_level3();
if (player->currentlevel == 4)
Render_level4();
Render_lights();
if (player->iWonTheGame == 1)
ismainMenuActive = 1;
angle_diamonds += 4;
angle_diamonds = fmod(angle_diamonds, 350.f);
diamonds_drop = fmod(diamonds_drop, 300.f);
if(player->endurance == 1)
player->dropalldiamonds = 1;
if(player->dropalldiamonds == 1 || player->dropalldiamonds == 2)
dropdiamonds();
if(player->showtorus == 1)
{
torus->pos = player->pos;
torus->pos.y = player->pos.y;
torus->Render("torus",*player);
player->torussize+=0.5;
if(player->torussize > 4.f)
player->showtorus = 0;
}
else
player->torussize = 0.6;
glFlush();
glutSwapBuffers();
glutPostRedisplay();
}
void OnReshape(int width, int height) {
window_width = width;
window_height = height;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, width, height);
gluPerspective(60.0f, (float)width / height, .01f, 250.0f);
}
void loadtextures(){
TextureManager::getInstance()->LoadTexture("level1_floor", "../Resources/Textures/level1_floor_grass.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("level1_rock", "../Resources/Textures/clay.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("level1_well1_walls", "../Resources/Textures/moss_stone.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("level1_walls", "../Resources/Textures/level1_walls.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("level1_wood", "../Resources/Textures/wood1.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("level1_well1_cover", "../Resources/Textures/wood1.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("skydome", "../Resources/Textures/skydome.bmp", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("trunk", "../Resources/Textures/Przydatne/BR_PMT_RGBA_4444/CRYSTAL1.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_0", "../Resources/Textures/SCORE_0.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_1", "../Resources/Textures/SCORE_1.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_2", "../Resources/Textures/SCORE_2.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_3", "../Resources/Textures/SCORE_3.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_4", "../Resources/Textures/SCORE_4.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_5", "../Resources/Textures/SCORE_5.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_6", "../Resources/Textures/SCORE_6.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_7", "../Resources/Textures/SCORE_7.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_8", "../Resources/Textures/SCORE_8.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("diamond_counter_9", "../Resources/Textures/SCORE_9.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("heart", "../Resources/Textures/CRYSTAL1.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("croclife", "../Resources/Textures/CROCLIFE.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("questionbox", "../Resources/Textures/questionbox.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("platform_green", "../Resources/Textures/platform_green.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("goldkey", "../Resources/Textures/KEY.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("sdiamond1", "../Resources/Textures/sdiamond1.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("sdiamond2", "../Resources/Textures/sdiamond2.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("sdiamond3", "../Resources/Textures/sdiamond3.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("woodendoor", "../Resources/Textures/wooden_plank_door.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("lava", "../Resources/Textures/lava.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("level1_well1_teleport", "../Resources/Textures/Level1_well1_teleport.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("mainMenuCover", "../Resources/Textures/mainMenuCover.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("mainMenuNewGame", "../Resources/Textures/New_game.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("mainMenuContinue", "../Resources/Textures/Continue.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("mainMenuExit", "../Resources/Textures/Exit.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("mainMenuConGratulations", "../Resources/Textures/ConGratulations.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("level2_floor1", "../Resources/Textures/Level2_floor1.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("diamonds_normal", "../Resources/Textures/diamond.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("level2_arch", "../Resources/Textures/Level2_floor1.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("specialdoorsleft", "../Resources/Textures/specialdoorleft.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("specialdoorsright", "../Resources/Textures/specialdoorright.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("level3_floor1", "../Resources/Textures/sand.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("desertbox", "../Resources/Textures/desertbox.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("level3_well", "../Resources/Textures/brick.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("level2_box", "../Resources/Textures/level2_box.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("level3platform", "../Resources/Textures/Level3_platform.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("friend", "../Resources/Textures/friend.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("Level4_floor1", "../Resources/Textures/snow1.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("Level4_walls", "../Resources/Textures/icewalls1.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("Level1_goldenchest", "../Resources/Textures/golden_chest.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("Level4_lavawater", "../Resources/Textures/icewater.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("level4platform", "../Resources/Textures/iceplatform.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("Level4_well", "../Resources/Textures/Level4_well.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("Level4_box", "../Resources/Textures/snowbox.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("Level4_grid", "../Resources/Textures/grid1.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("Level4_hemisphere", "../Resources/Textures/hemisphere.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("finalgong", "../Resources/Textures/gongend.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
TextureManager::getInstance()->LoadTexture("croc_corpse", "../Resources/Textures/croc_corpse.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("croc_eyes", "../Resources/Textures/eyes.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("croc_backpack", "../Resources/Textures/backpack.jpg", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGR_EXT);
TextureManager::getInstance()->LoadTexture("monkey", "../Resources/Textures/monkey.png", GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_BGRA_EXT);
}
void Render_level1()
{
if(started_game == 0)
{
started_game = 1;
player->pos.x = 3.39f;
player->pos.y = 0.2f;
player->pos.z = 0.4f;
player->makejump(4.f);
}
//daniotest->Render("Danio", *player);
scene.boundaryMin = vec3(-8.5f, -2, -6.5f);
scene.boundaryMax = vec3(5.8f, 3.5, 4.5f);
diamonds_coords[1] = vec3(0.4f, 1.2f, 2.6f);
diamonds_coords[0] = vec3(5.4f, 0.2f, 2.55f);
diamonds_coords[2] = vec3(0.80f, 1.1f, -1.f);
light4state = 0;
light1state = 1;
box1->textureName = "questionbox";
scene.Render();
Level1_floor->Render("floor", *player);
Level1_rock->Render("rock", *player);
Level1_walls->Render("walls", *player);
Level1_doors_right->Render("Level1_wooden_door_right", *player);
Level1_doors_left->Render("Level1_wooden_door_left", *player);
Level1_doors_right->WoodenDoorOpen(*player);
Level1_doors_left->WoodenDoorOpen(*player);
Level1_teleportbox->Render("Level1_teleportbox", *player);
Level1_pool->Render("pool", *player);
Level1_enemy->Render(*player);
Level1_friend1->Render(*player);
wood->Render(*player);
well1->Render(*player);
Level1_platform1->Render(*player, 0);
Level1_platform2->Render(*player, 1);
Level1_well1_cover->Render(*player, 2);
Level1_well1_teleport->Render(*player, 3);
trunk1->Paint(trunks_position[0], *player, 0);
Level1_lava->Draw(*player);
for (int i = 0; i<1; i++)
{
box1->Render(*player, box_coords[i], i);
}
checkandrenderdiamonds(3,6);
checkandrenderspecialdiamonds(0);
checkandrenderhearts(1,2);
}
void Initialize_level1()
{
//daniotest = new Terrain(vec3(0.0f, 0.5f, 0.f), vec3(0.8, 0.6, 0.6), 0.f, vec3(0.6, 0.2, 0.8));
//daniotest->load("../Resources/Models/Danio2.obj");
box1 = new NormalBox(vec3(.80f, 0.3f, 1.6f));
box1->Load("../Resources/Models/Level1_testbox.obj");
box1->textureName = "questionbox";
diamond = new Diamond(vec3(-.80f, 0.1f, 1.0f));
diamond->Load("../Resources/Models/Diamond.obj");
diamond->textureName = "diamonds_normal";
DDiam = new Diamond(vec3(-.80f, 100.1f, 1.0f));
DDiam->Load("../Resources/Models/Diamond.obj");
DDiam->textureName = "diamonds_normal";
heart = new Heart(vec3(-.80f, 0.1f, 1.0f));
heart->Load("../Resources/Models/Heart.obj");
box_coords = new vec3[9];
box_coords[0] = vec3(vec3(1.8f, 0.3f, 3.0f));
box_coords[1] = vec3(vec3(100.9f, 100.3f, 2.6f));
box_coords[2] = vec3(vec3(100.9f, 100.3f, 2.2f));
diamonds_coords = new vec3[44];
diamonds_taken = new bool[44];
diamonds_coords[31] = vec3(-2.80f, 100.1f, -1.f);
diamonds_coords[3] = vec3(.20f, 0.1f, 0.0f);
diamonds_coords[4] = vec3(.80f, 0.1f, .0f);
diamonds_coords[5] = vec3(1.40f, 0.1f, 0.f);
for (int i = 0; i<26; i++)
diamonds_taken[i] = 0;
hearts_coords = new vec3[3];
hearts_taken = new bool[3];
hearts_coords = new vec3[3];
hearts_taken = new bool[3];
hearts_coords[0] = vec3(-1.8f, 0.4f, 1.0f);
hearts_coords[1] = vec3(1.8f, 0.4f, 3.0f);
hearts_coords[2] = vec3(-1.8f, 0.4f, -1.f);
for (int i = 0; i<3; i++)
hearts_taken[i] = 0;
Level1_platform1 = new Platform(vec3(-.35f, 1.4f, 1.39f), 1, 1.f);
Level1_platform1->Load("../Resources/Models/Platform.obj");
Level1_platform1->textureName = "platform_green";
Level1_platform2 = new Platform(vec3(-.35f, 1.4f, -.2f), 2, 1.f);
Level1_platform2->Load("../Resources/Models/Platform.obj");
Level1_platform2->textureName = "platform_green";
Level1_well1_cover = new Platform(vec3(-0.35f, 0.4f, 2.9f), 5, 1.f);
Level1_well1_cover->Load("../Resources/Models/Platform.obj");
Level1_well1_cover->textureName = "level1_well1_cover";
Level1_well1_teleport = new Platform(vec3(-0.35f, 0.01f, 2.9f), 6, 1.f);
Level1_well1_teleport->Load("../Resources/Models/Level1_well1_teleport.obj");
Level1_well1_teleport->textureName = "level1_well1_teleport";
Level1_floor = new Terrain(vec3(-0.6f, 0.f, 0.f), vec3(0.6, 0.6, 0.6), 0.f, vec3(0.6, 0.2, 0.8));
Level1_floor->load("../Resources/Models/Level1_floor1.obj");
Level1_floor->textureName = "level1_floor";
Level1_walls = new Terrain(vec3(-0.8f, 0, 0), vec3(0.6, 0.6, 0.6), 0.f, vec3(0.2, 0.6, 0.8));
Level1_walls->load("../Resources/Models/Level1_walls.obj");
Level1_walls->textureName = "level1_walls";
Level1_pool = new Terrain(vec3(-4.5f, -0.8f, 0), vec3(0.6, 0.6, 0.8), 0.f, vec3(0.2, 0.6, 0.8));
Level1_pool->load("../Resources/Models/Level1_pool.obj");
Level1_pool->textureName = "level1_walls";
Level1_rock = new Terrain(vec3(4.4, 0.1, -3.7), vec3(0.7, 0.7, 0.5), 0.f, vec3(0.2, 0.6, 0.8));
Level1_rock->load("../Resources/Models/Level1_rock.obj");
Level1_rock->textureName = "level1_rock";
well1 = new Well1(vec3(-0.35f, 0.2f, 2.9f));
well1->Load("../Resources/Models/Level1_well1_walls.obj");
well1->textureName = "level1_well1_walls";
Level1_doors_frame = new Terrain(vec3(0, 0, 0), vec3(0.5, 0.5, 0.5), 0.f, vec3(0.2, 0.6, 0.8));
Level1_doors_frame->load("../Resources/Models/Level1_doors_frame.obj");
Level1_doors_right = new Terrain(vec3(-7.53f, 0.0f, -0.65f), vec3(1.3, 0.8, 0.71), 0.f, vec3(0.2, 0.6, 0.8));
Level1_doors_right->load("../Resources/Models/Level1_doors_right.obj");
Level1_doors_right->textureName = "woodendoor";
//Level1_doors_left = new Terrain(vec3(-7.60f, 0.0f, 1.10f), vec3(0.9,0.8,0.71), 180.f ,vec3(0.2,0.6,0.8));
Level1_doors_left = new Terrain(vec3(-7.60f, 0.0f, 1.10f), vec3(0.9, 0.8, 0.71), 180.f, vec3(0.2, 0.6, 0.8));
Level1_doors_left->load("../Resources/Models/Level1_doors_right.obj");
Level1_doors_left->textureName = "woodendoor";
Level1_teleportbox = new Terrain(vec3(-8.8f, 1.3f, 0.0f), vec3(0.1, 0.8, 0.71), 0.f, vec3(0.8, 0.8, 0.8));
Level1_teleportbox->load("../Resources/Models/Level1_teleportbox.obj");
Level1_lava = new cLava(2.f, "level1_lava", vec3(-6.5f, 0.f, -8.f));
trunk1 = new Blackbox();
trunk1->load();
trunk1->load2();
trunk1->textureName = "trunk";
trunks_position = new vec3[1];
trunks_position[0] = vec3(5.5f, 0.f, 2.4f);
wood = new Wood(vec3(-4.4f, 0.0f, .0));
wood->Load("../Resources/Models/Level1_wood.obj");
Level1_enemy = new Enemy(vec3(-2.0f, 0.2f, 1.5f), vec3(1.f, 0.f, 1.f), vec3(0.f, 0.f, 0.f), vec3(0.09f, 0.09f, 0.09f), 0.f);
Level1_friend1 = new Friend(vec3(1.8f, 0.6f, 3.0f), vec3(0.002, 0.002, 0.002), vec3(0.2, 0.2, 0.2), vec3(0.1, 0.1, 0.1), 0.f);
Level1_friend1->Load("../Resources/Models/bunny.obj");
}
void Initialize_level2()
{
key = new Key(vec3(-17.4f, 0.2f, 1.0f));
key->Load("../Resources/Models/Key.obj");
Level2_friend1 = new Friend(vec3(-6.5f, 0.6f, -2.5f), vec3(0.002, 0.002, 0.002), vec3(0.2, 0.2, 0.2), vec3(0.1, 0.1, 0.1), 0.f);
Level2_friend1->Load("../Resources/Models/bunny.obj");
Level2_floor1 = new Terrain(vec3(0.0f, 0.0f, 0.f), vec3(1.0, 0.6, 0.6), 90.f, vec3(0.6, 0.2, 0.8));
Level2_floor1->load("../Resources/Models/Level2_floor1.obj");
Level2_floor1->textureName = "level2_floor1";
Level2_arch = new Terrain(vec3(-4.8f, 0.f, 0.f), vec3(0.6, 0.6, 0.6), 90.f, vec3(0.6, 0.2, 0.8));
Level2_arch->load("../Resources/Models/Level2_arch.obj");
Level2_arch->textureName = "level2_arch";
Level2_kopula = new Terrain(vec3(-4.8f, -1.9f, 0.f), vec3(5.6, 1.8, 0.8), 0.f, vec3(0.6, 0.2, 0.8));
Level2_kopula->load("../Resources/Models/Level2_kopula.obj");
Level2_kopula->textureName = "level2_arch";
Level2_wall1 = new Terrain(vec3(-4.8f, 0.0f, 0.f), vec3(0.6, 0.6, 0.6), 90.f, vec3(0.6, 0.2, 0.8));
Level2_wall1->load("../Resources/Models/Level2_wall1.obj");
Level2_wall1->textureName = "level2_arch";
Level2_floor2 = new Terrain(vec3(-6.0f, 0.0f, 0.f), vec3(1.4, 0.6, 1.2), 0.f, vec3(0.6, 0.2, 0.8));
Level2_floor2->load("../Resources/Models/Level2_floor2.obj");
Level2_floor2->textureName = "level2_arch";
Level2_floor3 = new Terrain(vec3(-18.0f, 0.0f, 0.f), vec3(1.4, 0.6, 2.2), 0.f, vec3(0.6, 0.2, 0.8));
Level2_floor3->load("../Resources/Models/Level2_floor2.obj");
Level2_floor3->textureName = "level2_arch";
Level2_lastwall = new Terrain(vec3(-20.0f, 0.0f, 0.f), vec3(0.6, 1.2, 1.2), 0.f, vec3(0.6, 0.2, 0.8));
Level2_lastwall->load("../Resources/Models/Level2_lastwall.obj");
Level2_lastwall->textureName = "level2_arch";
Level2_getbacktolevel1 = new Terrain(vec3(5.0f, 0.0f, .0f), vec3(0.3, 0.4, 0.1), 90.f, vec3(0.6, 0.2, 0.8));
Level2_getbacktolevel1->load("../Resources/Models/Level2_getbacktolevel1.obj");
Level2_getbacktolevel1->textureName = "level2_arch";
Level2_getbacktolevel1wall = new Terrain(vec3(5.0f, 0.0f, .0f), vec3(0.7, 0.41, 0.1), 90.f, vec3(0.6, 0.2, 0.8));
Level2_getbacktolevel1wall->load("../Resources/Models/Level2_getbacktolevel1wall.obj");
Level2_getbacktolevel1wall->textureName = "level2_arch";
Level2_teleportboxto1 = new Terrain(vec3(5.8f, .2f, 0.0f), vec3(0.7, 0.8, 0.6), 180.f, vec3(0.6, 0.2, 0.8));
Level2_teleportboxto1->load("../Resources/Models/Level1_teleportbox.obj");
//Level2_doorsright1 = new Terrain(vec3(-7.53f, 0.0f, -0.65f), vec3(1.3,0.8,0.71), 0.f ,vec3(0.2,0.6,0.8));
Level2_doorsright1 = new Terrain(vec3(4.40f, 0.0f, -.65f), vec3(1.3, 0.8, 0.71), 0.f, vec3(0.2, 0.6, 0.8));
Level2_doorsright1->load("../Resources/Models/Level1_doors_right.obj");
Level2_doorsright1->textureName = "woodendoor";
//Level2_doorsleft1 = new Terrain(vec3(-7.60f, 0.0f, 1.10f), vec3(0.9,0.8,0.71), 180.f ,vec3(0.2,0.6,0.8));
Level2_doorsleft1 = new Terrain(vec3(4.50f, 0.0f, 1.05f), vec3(1.3, 0.8, 0.71), 180.f, vec3(0.2, 0.6, 0.8));
Level2_doorsleft1->load("../Resources/Models/Level1_doors_right.obj");
Level2_doorsleft1->textureName = "woodendoor";
//Level2_doorsright1 = new Terrain(vec3(-7.53f, 0.0f, -0.65f), vec3(1.3,0.8,0.71), 0.f ,vec3(0.2,0.6,0.8));
Level2_doorsright2 = new Terrain(vec3(-18.10f, 0.0f, -.65f), vec3(1.3, 0.8, 0.71), 0.f, vec3(0.2, 0.6, 0.8));
Level2_doorsright2->load("../Resources/Models/Level1_doors_right.obj");
Level2_doorsright2->textureName = "specialdoorsright";
//Level2_doorsleft1 = new Terrain(vec3(-7.60f, 0.0f, 1.10f), vec3(0.9,0.8,0.71), 180.f ,vec3(0.2,0.6,0.8));
Level2_doorsleft2 = new Terrain(vec3(-18.20f, 0.0f, 1.10f), vec3(1.3, 0.8, 0.71), 180.f, vec3(0.2, 0.6, 0.8));
Level2_doorsleft2->load("../Resources/Models/Level1_doors_right.obj");
Level2_doorsleft2->textureName = "specialdoorsleft";
Level2_arch2 = new Terrain(vec3(-20.2f, 0.0f, 0.3f), vec3(0.4, 0.5, 0.3), 90.f, vec3(0.6, 0.2, 0.8));
Level2_arch2->load("../Resources/Models/Level2_getbacktolevel1.obj");
Level2_arch2->textureName = "level2_arch";
// Level2_teleportboxfinal = new Terrain(vec3(-18.9f, .5f, 0.3f), vec3(0.3, 0.4, 0.3), 0.f, vec3(0.6, 0.2, 0.8));
// Level2_teleportboxfinal->load("../Resources/Models/Level1_teleportbox.obj");
Level2_movingplatform1 = new Platform(vec3(-9.85f, 0.3f, 1.0f), 3, 1.f);
Level2_movingplatform1->Load("../Resources/Models/Platform.obj");
Level2_movingplatform1->textureName = "level2_arch";
Level2_movingplatform2 = new Platform(vec3(-12.55f, 0.3f, -1.0f), 3, -1.4f);
Level2_movingplatform2->Load("../Resources/Models/Platform.obj");
Level2_movingplatform2->textureName = "level2_arch";
//Level2_teleportboxto1 = new Terrain(vec3(5.8f, .2f, 0.0f), vec3(0.7, 0.8, 0.6), 180.f, vec3(0.6, 0.2, 0.8));
//Level2_teleportboxto1->load("../Resources/Models/Level1_teleportbox.obj");
Level2_finalgong = new Terrain(vec3(-18.9f, .4f, 0.3f), vec3(0.3, 0.3, 0.3), 90.f, vec3(0.6, 0.2, 0.8));
Level2_finalgong->load("../Resources/Models/gong.obj");
Level2_finalgong->textureName = "finalgong";
Level2_lava = new cLava(64.f, "level2_lava", vec3(-32.0f, -0.6f, -12.0f));
}
void Render_level2()
{
box1->textureName = "level2_box";
Level2_floor1->Render("Level2_floor1", *player);
Level2_arch->Render("Level2_arch", *player);
Level2_kopula->Render("Level2_kopula", *player);
Level2_wall1->Render("Level2_wall1", *player);
Level2_floor2->Render("Level2_floor2", *player);
Level2_lava->Draw(*player);
Level2_getbacktolevel1->Render("Level2_getbacktolevel1", *player);
Level2_getbacktolevel1wall->Render("Level2_getbacktolevel1wall", *player);
Level2_teleportboxto1->Render("Level2_teleportboxto1", *player);
Level2_floor3->Render("Level2_floor3", *player);
Level2_lastwall->Render("Level2_lastwall", *player);
Level2_friend1->Render(*player);
Level2_doorsright1->Render("Level2_wooden_door_right", *player);
Level2_doorsleft1->Render("Level2_wooden_door_left", *player);
Level2_doorsright1->WoodenDoorOpen(*player);
Level2_doorsleft1->WoodenDoorOpen(*player);
Level2_doorsright2->Render("Level2specialdoorsright", *player);
Level2_doorsleft2->Render("Level2specialdoorsleft", *player);
Level2_doorsright2->WoodenDoorOpen(*player);
Level2_doorsleft2->WoodenDoorOpen(*player);
Level2_arch2->Render("Level2_arch2", *player);
Level2_movingplatform1->Render(*player, 4);
Level2_movingplatform2->Render(*player, 5);
key->Render(*player, Level2_movingplatform2->pos);
Level2_finalgong->Render("finalgong",*player);
//Level2_teleportboxfinal->Render("Level2_teleportboxfinal", *player);
//if(diamonds_taken[6] == 0 || diamonds_taken[7] == 0 ||diamonds_taken[8] == 0 )
// diamonds_coords[0] = vec3( .40f, 100.201f, 0.f);
// diamonds_coords[1] = vec3( - 0.8f, 100.202f, .0f);
// diamonds_coords[2] = vec3( - 2.10f, 100.202f, 0.f);
diamonds_coords[6] = vec3(.40f, 0.201f, 0.f);
diamonds_coords[7] = vec3(-0.8f, 0.202f, .0f);
diamonds_coords[8] = vec3(-2.10f, 0.202f, 0.f);
diamonds_coords[9] = vec3(-6.6f, 0.2f, -2.35f);
diamonds_coords[10] = vec3(-6.35f, 0.2f, -2.35f);
diamonds_coords[11] = vec3(-6.5f, 0.2f, -2.5f);
diamonds_coords[12] = vec3(-6.6f, 0.2f, 2.35f);
diamonds_coords[13] = vec3(-6.35f, 0.2f, 2.35f);
diamonds_coords[14] = vec3(-6.5f, 0.2f, 2.5f);
box_coords[1] = vec3(vec3(-6.5f, 0.3f, -2.5f));
box_coords[2] = vec3(vec3(-6.5f, 0.3f, 2.5f));
for (int i = 1; i<3; i++)
{
box1->Render(*player, box_coords[i], i);
}
if (player->specialdiamonds[0] == 1 && player->specialdiamonds[1] == 1 && player->specialdiamonds[2] == 1)
{
scene.boundaryMin = vec3(-19.1f, -2, -20.5f);
scene.boundaryMax = vec3(20.8f, 3.5, 20.5f);
}
else
{
scene.boundaryMin = vec3(-18.10f, -2, -20.5f);
scene.boundaryMax = vec3(20.8f, 3.5, 20.5f);
}
checkandrenderdiamonds(6,15);
}
void Initialize_level3()
{
Level3_floor1 = new Terrain(vec3(0.0f, 0.0f, 0.f), vec3(1.0, 0.6, 0.6), 0.f, vec3(0.6, 0.2, 0.8));
Level3_floor1->load("../Resources/Models/Level3_floor1.obj");
Level3_floor1->textureName = "level3_floor1";
Level3_floor2 = new Terrain(vec3(-33.0f, 0.5f, 0.f), vec3(0.8, 0.6, 0.8), 0.f, vec3(0.6, 0.2, 0.8));
Level3_floor2->load("../Resources/Models/Level3_floor2.obj");
Level3_floor2->textureName = "level3_floor1";
Level3_well1 = new Well1(vec3(-33.0f, 1.1f, 0.f));
Level3_well1->Load("../Resources/Models/Level1_well1_walls.obj");
Level3_well1->textureName = "level3_well";
Level3_well1_teleport = new Platform(vec3(-33.0f, 1.0f, 0.f), 6, 1.f);
Level3_well1_teleport->Load("../Resources/Models/Level1_well1_teleport.obj");
Level3_well1_teleport->textureName = "level1_well1_teleport";
Level3_fallingplatform1 = new Platform(vec3(-29.0f, 0.5f, 0.0f), 4, 1.f);
Level3_fallingplatform1->Load("../Resources/Models/Platform.obj");
Level3_fallingplatform1->textureName = "level3platform";
Level3_fallingplatform2 = new Platform(vec3(-27.0f, 0.5f, 0.0f), 4, 1.f);
Level3_fallingplatform2->Load("../Resources/Models/Platform.obj");
Level3_fallingplatform2->textureName = "level3platform";
Level3_fallingplatform3 = new Platform(vec3(-24.3f, 0.5f, 0.0f), 4, 1.f);
Level3_fallingplatform3->Load("../Resources/Models/Platform.obj");
Level3_fallingplatform3->textureName = "level3platform";
Level3_BIGENEMY = new Enemy(vec3(21.5f, 0.9f, 6.f), vec3(1.f, 0.f, 1.f), vec3(0.f, 0.f, 0.f), vec3(1.2f, 1.2f, 1.2f), 0.f);
Level3_BIGENEMY->Load("../Resources/Models/enemy_monkey.obj");
Level3_BIGENEMY->textureName = "monkey";
Level3_smallenemy = new Enemy(vec3(21.5f, 0.3f, -1.f), vec3(1.f, 0.f, 1.f), vec3(0.f, 0.f, 0.f), vec3(0.3f, 0.3f, 0.3f), 0.f);
Level3_smallenemy->Load("../Resources/Models/enemy_monkey.obj");
Level3_smallenemy->textureName = "monkey";
Level3_smallenemy->dirmove = 4;
smallenemy_coords = new vec3[10];
smallenemy_isalive = new bool[10];
Level3_friend1 = new Friend(vec3(18.9f, 0.6f, 2.6f), vec3(0.002, 0.002, 0.002), vec3(0.2, 0.2, 0.2), vec3(0.1, 0.1, 0.1), 0.f);
Level3_friend1->Load("../Resources/Models/bunny.obj");
for (int i = 0; i<10; i++)
{
smallenemy_isalive[i] = 0;
}
}
void Render_level3()
{
box1->textureName = "desertbox";
//glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
Level3_BIGENEMY->bigRender(*player);
if (player->lost == 1)
{
for (int i = 0; i<10; i++)
{
smallenemy_isalive[i] = 0;
}
player->lost = 0;
Level3_BIGENEMY->timer_stop2 = 150.f;
}
if (Level3_BIGENEMY->timer_stop2 == 0)
{
for (int i = 0; i<10; i++)
{
if (smallenemy_isalive[i] == 0)
{
smallenemy_coords[i] = Level3_BIGENEMY->pos;
smallenemy_isalive[i] = 1;
Level3_BIGENEMY->timer_stop2 = 100.f;
smallenemy_coords[i].y = 0.3f;
////printf("ENEMY DEPLOYED\n");
break;
}
}
// if(smallenemy_index < 10)
// smallenemy_index ++;
// else
// smallenemy_index = 0;
}
if (player->pos.x < -15.f || Level3_BIGENEMY->pos.x >= player->pos.x)
Level3_BIGENEMY->timer_stop2 = 100.f;
////printf("TIME: %f\n",Level3_BIGENEMY->timer_stop2);
Level3_friend1->Render(*player);
for (int i = 0; i<10; i++)
{
if (smallenemy_isalive[i] == 1)
{
Level3_smallenemy->smallRender(*player, smallenemy_coords[i], smallenemy_isalive[i]);
}
}
Level3_floor1->Render("Level3_floor1", *player);
Level3_floor2->Render("Level3_floor2", *player);
Level3_well1->Render(*player);
Level3_well1_teleport->Render(*player, 1);
Level3_fallingplatform1->Render(*player, 6);
Level3_fallingplatform2->Render(*player, 7);
Level3_fallingplatform3->Render(*player, 8);
box_coords[3] = vec3(vec3(18.9f, 0.3f, 2.6f));
box_coords[4] = vec3(vec3(14.9f, 0.3f, 2.6f));
box_coords[5] = vec3(vec3(18.9f, 0.3f, -2.6f));
box_coords[6] = vec3(vec3(14.9f, 0.3f, -2.6f));
diamonds_coords[0] = vec3(-33.0f, 1000.5f, 0.f);
diamonds_coords[1] = vec3(-33.0f, 1.5f, 0.f);
diamonds_coords[2] = vec3(-33.0f, 1000.5f, 0.f);
diamonds_coords[14] = vec3(18.9f, 0.2f, 2.45f);
diamonds_coords[15] = vec3(18.75f, 0.2f, 2.45f);
diamonds_coords[16] = vec3(18.7f, 0.2f, 2.6f);
diamonds_coords[17] = vec3(14.9f, 0.2f, 2.45f);
diamonds_coords[18] = vec3(14.75f, 0.2f, 2.45f);
diamonds_coords[19] = vec3(14.7f, 0.2f, 2.6f);
diamonds_coords[20] = vec3(18.9f, 0.2f, -2.45f);
diamonds_coords[21] = vec3(18.75f, 0.2f, -2.45f);
diamonds_coords[22] = vec3(18.7f, 0.2f, -2.45f);
diamonds_coords[23] = vec3(14.9f, 0.2f, -2.45f);
diamonds_coords[24] = vec3(14.75f, 0.2f, -2.45f);
diamonds_coords[25] = vec3(14.7f, 0.2f, -2.6f);
diamonds_coords[26] = vec3(-32.0f, 1.1f, 1.45f);
diamonds_coords[27] = vec3(-32.5f, 1.1f, 1.45f);
diamonds_coords[28] = vec3(-33.0f, 1.1f, 1.6f);
diamonds_coords[29] = vec3(-32.0f, 1.1f, -1.45f);
diamonds_coords[30] = vec3(-32.5f, 1.1f, -1.45f);
hearts_coords[0] = vec3(-33.0f, 1.5f, 2.f);
for (int i = 3; i<7; i++)
{
box1->Render(*player, box_coords[i], i);
}
scene.boundaryMin = vec3(-40.10f, -10, -20.5f);
scene.boundaryMax = vec3(25.0f, 3.5, 20.5f);
checkandrenderdiamonds(14,32);
checkandrenderspecialdiamonds(1);
checkandrenderhearts(0,1);
//glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
}
void Initialize_level4()
{
////printf("INIT\n");
Level4_floor1 = new Terrain(vec3(2.0f, 0.6f, 0.f), vec3(1.5, 0.5, 3.5), 0.f, vec3(0.6, 0.2, 0.8));
Level4_floor1->load("../Resources/Models/Level4_floor1.obj");
Level4_floor1->textureName = "Level4_floor1";
Level4_floor2 = new Terrain(vec3(-23.0f, 0.6f, 0.f), vec3(1.5, 0.5, 3.5), 0.f, vec3(0.6, 0.2, 0.8));
Level4_floor2->load("../Resources/Models/Level4_floor1.obj");
Level4_floor2->textureName = "Level4_floor1";
Level4_floor_moving1 = new Terrain(vec3(-2.5f, 0.6f, -10.f), vec3(0.6, 0.5, 0.2), 0.f, vec3(0.5, 0.5, 0.5));
Level4_floor_moving1->load("../Resources/Models/Level4_floor1.obj");
Level4_floor_moving1->textureName = "Level4_floor1";
Level4_floor_moving2 = new Terrain(vec3(-2.5f, 0.6f, -5.f), vec3(0.6, 0.5, 0.2), 0.f, vec3(0.5, 0.5, 0.5));
Level4_floor_moving2->load("../Resources/Models/Level4_floor1.obj");
Level4_floor_moving2->textureName = "Level4_floor1";
Level4_floor_moving3 = new Terrain(vec3(-2.5f, 0.6f, 0.f), vec3(0.6, 0.5, 0.2), 0.f, vec3(0.5, 0.5, 0.5));
Level4_floor_moving3->load("../Resources/Models/Level4_floor1.obj");
Level4_floor_moving3->textureName = "Level4_floor1";
Level4_floor_moving4 = new Terrain(vec3(-2.5f, 0.6f, 5.f), vec3(0.6, 0.5, 0.2), 0.f, vec3(0.5, 0.5, 0.5));
Level4_floor_moving4->load("../Resources/Models/Level4_floor1.obj");
Level4_floor_moving4->textureName = "Level4_floor1";
Level4_floor_moving5 = new Terrain(vec3(-5.5f, 0.6f, -10.f), vec3(0.6, 0.5, 0.2), 0.f, vec3(0.5, 0.5, 0.5));
Level4_floor_moving5->load("../Resources/Models/Level4_floor1.obj");
Level4_floor_moving5->textureName = "Level4_floor1";
Level4_floor_moving6 = new Terrain(vec3(-5.5f, 0.6f, -5.f), vec3(0.6, 0.5, 0.2), 0.f, vec3(0.5, 0.5, 0.5));
Level4_floor_moving6->load("../Resources/Models/Level4_floor1.obj");
Level4_floor_moving6->textureName = "Level4_floor1";
Level4_floor_moving7 = new Terrain(vec3(-5.5f, 0.6f, 0.f), vec3(0.6, 0.5, 0.2), 0.f, vec3(0.5, 0.5, 0.5));
Level4_floor_moving7->load("../Resources/Models/Level4_floor1.obj");
Level4_floor_moving7->textureName = "Level4_floor1";
Level4_floor_moving9 = new Terrain(vec3(-5.5f, 0.6f, 5.f), vec3(0.6, 0.5, 0.2), 0.f, vec3(0.5, 0.5, 0.5));
Level4_floor_moving9->load("../Resources/Models/Level4_floor1.obj");
Level4_floor_moving9->textureName = "Level4_floor1";
Level4_walls = new Terrain(vec3(-12.2f, 0.0f, 0.f), vec3(1.5, 2.5, 1.5), 0.f, vec3(0.6, 0.2, 0.8));
Level4_walls->load("../Resources/Models/Level4_walls.obj");
Level4_walls->textureName = "Level4_walls";
Level4_lava = new cLava(64.f, "Level4_lavawater", vec3(-32.0f, -0.6f, -12.0f));
Level4_platform1 = new Platform(vec3(-8.f, 0.4f, -4.0f), 1, 1.f);
Level4_platform1->Load("../Resources/Models/Platform.obj");
Level4_platform1->textureName = "level4platform";
Level4_platform2 = new Platform(vec3(-9.5f, 0.4f, -3.0f), 1, 1.f);
Level4_platform2->Load("../Resources/Models/Platform.obj");
Level4_platform2->textureName = "level4platform";
Level4_platform3 = new Platform(vec3(-11.f, 0.4f, -2.0f), 1, 1.f);
Level4_platform3->Load("../Resources/Models/Platform.obj");
Level4_platform3->textureName = "level4platform";
Level4_platform4 = new Platform(vec3(-12.5f, 0.4f, -1.0f), 1, 1.f);
Level4_platform4->Load("../Resources/Models/Platform.obj");
Level4_platform4->textureName = "level4platform";
Level4_platform5 = new Platform(vec3(-14.0f, 0.4f, 0.0f), 1, 1.f);
Level4_platform5->Load("../Resources/Models/Platform.obj");
Level4_platform5->textureName = "level4platform";
Level4_platform6 = new Platform(vec3(-16.f, 0.4f, -1.0f), 1, 1.f);
Level4_platform6->Load("../Resources/Models/Platform.obj");
Level4_platform6->textureName = "level4platform";
Level4_platform7 = new Platform(vec3(-17.3f, 0.4f, -2.0f), 1, 1.f);
Level4_platform7->Load("../Resources/Models/Platform.obj");
Level4_platform7->textureName = "level4platform";
Level4_platform8 = new Platform(vec3(-19.f, 0.4f, -3.0f), 1, 1.f);
Level4_platform8->Load("../Resources/Models/Platform.obj");
Level4_platform8->textureName = "level4platform";
Level4_teleport = new Platform(vec3(2.0,0.7,4.f), 18,1.f);
Level4_teleport->Load("../Resources/Models/Platform.obj");
Level4_teleport->textureName = "level1_well1_teleport";
Level4_well1 = new Well1(vec3(2.0f, 0.8f, 4.f));
Level4_well1->Load("../Resources/Models/Level1_well1_walls.obj");
Level4_well1->textureName = "Level4_well";
Level4_grid1 = new Terrain(vec3(-12.2f, 3.2f, 8.f), vec3(0.6, 0.6, 0.6), 0.f, vec3(0.6, 0.6, 0.6));
Level4_grid1->load("../Resources/Models/Level4_grid.obj");
Level4_grid1->textureName = "Level4_grid";
Level4_grid2 = new Terrain(vec3(-7.2f, 3.2f, 8.f), vec3(0.6, 0.6, 0.6), 0.f, vec3(0.6, 0.6, 0.6));
Level4_grid2->load("../Resources/Models/Level4_grid.obj");
Level4_grid2->textureName = "Level4_grid";
Level4_hempisphere = new Terrain(vec3(-21.7f, 0.6f, 7.6f), vec3(0.4, 0.2, 0.4), 0.f, vec3(0.6, 0.6, 0.6));
Level4_hempisphere->load("../Resources/Models/Level4_hemisphere.obj");
Level4_hempisphere->textureName = "Level4_hemisphere";
Level4_friend = new Friend(vec3(-7.8f, 3.3f, 8.f), vec3(0.002, 0.002, 0.002), vec3(0.2, 0.2, 0.2), vec3(0.1, 0.1, 0.1), 0.f);
Level4_friend->Load("../Resources/Models/bunny.obj");
}
void Render_level4()
{
box1->textureName = "Level4_box";
Level4_walls->textureName = "Level4_walls";
// player->standat = 1.f;
// player->pos.y = 1.f;
hearts_coords[2] = vec3(2.0f, 1.4f, 4.f);
scene.boundaryMin = vec3(-40.10f, -10, -10.5f);
scene.boundaryMax = vec3(3.8f, 20.5, 10.5f);
Level4_floor1->Render("Level4_floor1", *player);
Level4_floor2->Render("Level4_floor2", *player);
Level4_floor_moving1->Render("Level4_floor_moving1", *player);
Level4_floor_moving2->Render("Level4_floor_moving2", *player);
Level4_floor_moving3->Render("Level4_floor_moving3", *player);
Level4_floor_moving4->Render("Level4_floor_moving4", *player);
Level4_floor_moving5->Render("Level4_floor_moving5", *player);
Level4_floor_moving6->Render("Level4_floor_moving6", *player);
Level4_floor_moving7->Render("Level4_floor_moving7", *player);
Level4_floor_moving9->Render("Level4_floor_moving9", *player);
Level4_well1->Render(*player);
Level4_teleport->Render(*player,17);
Level4_walls->Render("Level4_walls", *player);
Level4_lava->Draw(*player);
Level4_platform1->Render(*player, 9);
Level4_platform2->Render(*player, 10);
Level4_platform3->Render(*player, 11);
Level4_platform4->Render(*player, 12);
Level4_platform5->Render(*player, 13);
Level4_platform6->Render(*player, 14);
Level4_platform7->Render(*player, 15);
Level4_platform8->Render(*player, 16);
diamonds_coords[32] = vec3(2.f, 1.f, -2.45f);
diamonds_coords[33] = vec3(2.f, 1.f, -4.45f);
diamonds_coords[34] = vec3(2.f, 1.f, -6.45f);
diamonds_coords[35] = vec3(-22.9f, 1.f, 2.45f);
diamonds_coords[36] = vec3(-22.75f, 1.f, 4.45f);
diamonds_coords[37] = vec3(-22.7f, 1.f, 6.6f);
diamonds_coords[2] = vec3(-22.7f, 1.f, 8.6f);
diamonds_coords[0] = vec3(-22.7f, 1000.f, 8.6f);
diamonds_coords[1] = vec3(-22.7f, 1000.f, 8.6f);
diamonds_coords[38] = vec3(2.2f, 0.9f, -8.45f);
diamonds_coords[39] = vec3(2.5f, 0.9f, -8.45f);
diamonds_coords[40] = vec3(2.3f, 0.9f, -8.50f);
diamonds_coords[41] = vec3(-21.75f, 1.f, -10.41f);
diamonds_coords[42] = vec3(-21.75f, 1.f, -10.42f);
diamonds_coords[43] = vec3(-21.75f, 1.f, -10.45f);
box_coords[7] = vec3(vec3(2.4f, 0.9f, -8.46f));
box_coords[8] = vec3(vec3(-22.75f, 0.9f, -8.6f));
Level4_grid1->Render("Level4_grid1", *player);
Level4_grid2->Render("Level4_grid2", *player);
Level4_hempisphere->Render("Level4_hemisphere", *player);
Level4_friend->Render(*player);
for (int i = 7; i<9; i++)
{
box1->Render(*player, box_coords[i], i);
}
checkandrenderdiamonds(32,43);
checkandrenderspecialdiamonds(2);
checkandrenderhearts(2,3);
////printf("INIT2\n");
}
void Render_lights()
{
if (light1state)
{
GLfloat l0_ambient[] = { 0.2f, 0.2f, 0.2f };
GLfloat l0_diffuse[] = { 1.0f, 1.0f, 1.0 };
GLfloat l0_specular[] = { 0.5f, 0.5f, 0.5f };
GLfloat l0_position[] = { 2.f, 2.f, 2.f, 0.0f };
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, l0_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, l0_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, l0_specular);
glLightfv(GL_LIGHT0, GL_POSITION, l0_position);
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.2);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0);
}
else
{
glDisable(GL_LIGHT0);
}
if (light2state)
{
GLfloat l0_ambient[] = { 0.0f, 0.0f, 0.0f };
GLfloat l0_diffuse[] = { 0.5f, 0.5f, 0.5 };
GLfloat l0_specular[] = { 0.2f, 0.2f, 0.2f };
GLfloat l0_position[] = { -player->dir.x, -player->dir.y, -player->dir.z, 0.0f };
glEnable(GL_LIGHT1);
glLightfv(GL_LIGHT1, GL_AMBIENT, l0_ambient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, l0_diffuse);
glLightfv(GL_LIGHT1, GL_SPECULAR, l0_specular);
glLightfv(GL_LIGHT1, GL_POSITION, l0_position);
glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 0);
glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, 0.2);
glLightf(GL_LIGHT1, GL_QUADRATIC_ATTENUATION, 0);
}
else
{
glDisable(GL_LIGHT1);
}
if (light3state)
{
GLfloat l2_ambient[] = { 0.5f, 0.5f, 0.5f, 1.0f };
GLfloat l2_diffuse[] = { 1.0f, 1.0f, 1.0 };
GLfloat l2_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat l2_position[] = { player->pos.x, player->pos.y, player->pos.z, 1.0f };
GLfloat l2_direction[] = { player->dir.x, player->dir.y, player->dir.z };
glLightfv(GL_LIGHT2, GL_DIFFUSE, l2_ambient);
glLightfv(GL_LIGHT2, GL_SPECULAR, l2_specular);
glLightfv(GL_LIGHT2, GL_POSITION, l2_position);
glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, l2_direction);
glLightf(GL_LIGHT2, GL_SPOT_CUTOFF, 20.0f);
glLightf(GL_LIGHT2, GL_CONSTANT_ATTENUATION, 0.f);
glLightf(GL_LIGHT2, GL_LINEAR_ATTENUATION, .2f);
glLightf(GL_LIGHT2, GL_QUADRATIC_ATTENUATION, 0.f);
glEnable(GL_LIGHT2);
}
else
{
glDisable(GL_LIGHT2);
}
if (!goldentrunkstate)
{
GLfloat l0_ambient[] = { 0.2f, 0.2f, 0.2f };
GLfloat l0_diffuse[] = { 1.0f, 1.0f, 1.0 };
GLfloat l0_specular[] = { 0.5f, 0.5f, 0.5f };
GLfloat l0_position[] = { 5.5f, 0.f, 2.4f, 1.0f };
glEnable(GL_LIGHT3);
glLightfv(GL_LIGHT3, GL_AMBIENT, l0_ambient);
glLightfv(GL_LIGHT3, GL_DIFFUSE, l0_diffuse);
glLightfv(GL_LIGHT3, GL_SPECULAR, l0_specular);
glLightfv(GL_LIGHT3, GL_POSITION, l0_position);
glLightf(GL_LIGHT3, GL_CONSTANT_ATTENUATION, 0);
glLightf(GL_LIGHT3, GL_LINEAR_ATTENUATION, 0.2);
glLightf(GL_LIGHT3, GL_QUADRATIC_ATTENUATION, 0);
}
else
{
glDisable(GL_LIGHT4);
}
if (light4state)
{
GLfloat l4_ambient[] = { 0.2f, 0.2f, 0.2f };
GLfloat l4_diffuse[] = { 1.0f, 1.0f, 1.0 };
GLfloat l4_specular[] = { 0.5f, 0.5f, 0.5f };
GLfloat l4_position[] = { player->pos.x + 0.5f, player->pos.y + 0.5f, player->pos.z, 1.0f };
glEnable(GL_LIGHT4);
glLightfv(GL_LIGHT4, GL_AMBIENT, l4_ambient);
glLightfv(GL_LIGHT4, GL_DIFFUSE, l4_diffuse);
glLightfv(GL_LIGHT4, GL_SPECULAR, l4_specular);
glLightfv(GL_LIGHT4, GL_POSITION, l4_position);
glLightf(GL_LIGHT4, GL_CONSTANT_ATTENUATION, 0);
glLightf(GL_LIGHT4, GL_LINEAR_ATTENUATION, 0.4);
glLightf(GL_LIGHT4, GL_QUADRATIC_ATTENUATION, 0);
}
else
{
glDisable(GL_LIGHT4);
}
}
void checkandrenderdiamonds(int start, int end)
{
for (int i = start; i<end; i++)
{
if (sqrt((player->pos.x - diamonds_coords[i].x)*(player->pos.x - diamonds_coords[i].x) + (player->pos.z - diamonds_coords[i].z)*(player->pos.z - diamonds_coords[i].z)) <= 0.3 && diamonds_taken[i] == 0 && player->pos.y < diamonds_coords[i].y + 0.1)
{
diamonds_taken[i] = 1;
if (i >= 3)
{
player->diamonds_counter += 1; player->endurance = 2;
}
}
diamond->Render(*player, diamonds_coords[i], diamonds_taken[i], i, angle_diamonds,0);
}
}
void checkandrenderspecialdiamonds(int index)
{
if (sqrt((player->pos.x - diamonds_coords[index].x)*(player->pos.x - diamonds_coords[index].x) + (player->pos.z - diamonds_coords[index].z)*(player->pos.z - diamonds_coords[index].z)) <= 0.3 && diamonds_taken[index] == 0)
{
if(index == 0 && player->keys_counter == -1)
diamonds_taken[index] = 1; player->specialdiamonds[index] = 1;
if(index == 2 || index == 1)
diamonds_taken[index] = 1; player->specialdiamonds[index] = 1;
}
if (player->specialdiamonds[index] != 1)
diamond->Render(*player, diamonds_coords[index], diamonds_taken[index], index, angle_diamonds,0);
}
void checkandrenderhearts(int start, int end)
{
for (int i = start; i<end; i++)
{
if (sqrt((player->pos.x - hearts_coords[i].x)*(player->pos.x - hearts_coords[i].x) + (player->pos.z - hearts_coords[i].z)*(player->pos.z - hearts_coords[i].z)) <= 0.25 && hearts_taken[i] == 0 && player->pos.y < hearts_coords[i].y + 0.1)
{
hearts_taken[i] = 1;
player->lives_counter += 1;
}
heart->Render(*player, hearts_coords[i], hearts_taken[i]);
}
}
void dropdiamonds()
{
//printf("DROPPING\n");
//printf(" %d \n",player->dropalldiamonds);
if (player->diamonds_counter > 0 && player->dropalldiamonds == 1)
{
//printf("DROPPING\n");
dropped_coords = new vec3[player->diamonds_counter];
dropped_state = new bool[player->diamonds_counter];
for (int i = 0; i<player->diamonds_counter; i++)
{
diamonds_drop += 32.f;
float rotX = (float)cos((diamonds_drop) * 3.14 / 180);
float rotZ = (float)sin((diamonds_drop) * 3.14 / 180);
if(fabs(player->pos.x - (player->pos.x + rotX) > 0.4f ))
rotX/= 2;
if(fabs(player->pos.x - (player->pos.x - rotZ) > 0.4f ))
rotZ/= 2;
dropped_coords[i] = vec3(player->pos.x + rotX, player->pos.y, player->pos.z - rotZ);
dropped_state[i] = 0;
}
player->howmanyweredropped = player->diamonds_counter;
player->dropalldiamonds = 2;
player->diamonds_counter = 0;
}
if (player->dropalldiamonds == 2)
{
for (int i = 0; i<player->howmanyweredropped; i++)
{
//printf("&& %d\n",dropped_state[i]);
if (sqrt((player->pos.x - dropped_coords[i].x)*(player->pos.x - dropped_coords[i].x) + (player->pos.z - dropped_coords[i].z)*(player->pos.z - dropped_coords[i].z)) <= 0.15 && dropped_state[i] == 0 && player->droppedscale > 0.01f)
{
dropped_state[i] = 1;
player->diamonds_counter += 1; player->endurance = 2;
}
if(player->droppedscale > 0.03f)
DDiam->Render(*player, dropped_coords[i], dropped_state[i], 4, angle_diamonds, 1);
else
dropped_state[i] = 1;
}
}
//printf("DROPPED: %d\n",player->dropalldiamonds);
if(player->dropalldiamonds == 2)
{
bool gate = 0;
for (int i = 0; i<player->howmanyweredropped; i++)
{
if(dropped_state[i] == 0)
gate = 1;
}
if(gate == 0 && player->howmanyweredropped != 0)
{
//printf("DONE\n");
player->dropalldiamonds = 0;
player->howmanyweredropped = 0;
player->droppedscale = 0.3f;
diamonds_drop = 0.f;
delete[] dropped_coords;
delete[] dropped_state;
}
}
}
|
c36778c5b99ebab239ec25290fe3bf43e4eaaefc
|
424a7bf0be74de6f6c157b4f7f47e585d5f80711
|
/CS-Banking simulation/Account-def.cpp
|
f699ace77afa64e4f9d723ffb601f68399d35996
|
[] |
no_license
|
utkarsh30singh/OOPs-Lab-program
|
65e12403dfc62aa77459336da8f854397460a5d7
|
6b41625a1a64b236326638b45e2b1979554bb7da
|
refs/heads/master
| 2022-12-25T15:36:06.910697
| 2019-10-30T19:13:12
| 2019-10-30T19:13:12
| 147,157,479
| 0
| 1
| null | 2020-10-02T16:42:27
| 2018-09-03T05:50:45
|
C++
|
UTF-8
|
C++
| false
| false
| 1,472
|
cpp
|
Account-def.cpp
|
#include"Account_dec.h"
int Account::ac_no=10012;
void Account :: deposit()
{
int amount;
cout<<"Enter deposit amount(minimum 1000 for current account initially ) :";
cin>>amount;
if(amount<0)
cout<<"You cannot deposit a negative amount."<<endl;
else
balance+=amount;
display();
}
void Account :: withdrawl()
{
float debit;
cout<<"Enter the amount you want to withdraw:";
cin>>debit;
if(balance<debit)
cout<<"Not enough balance."<<endl;
else if(debit<0)
cout<<"You cannot withdraw a negative amount."<<endl;
else
balance-=debit;
display();
}
void Account :: display()
{
cout<<"\nAccount no: "<<ac_no<<" Name: "<<customer_name<<" Balance: "<<balance<<endl;
}
void Account ::get_chequebook()
{
cout<<"\nYour chequebook number is "<<ac_no<<endl;
display();
}
void Sav_Acct:: calc_interest()
{
interest = balance*(0.06/12);
cout<<"Enter time period in months: ";
cin>>months;
interest=(interest*months);
cout<<"\nInterest = "<<interest;
balance+=interest;
display();
}
void Cur_Acct:: check_min_balance()
{
if(balance>=1000)
return;
else
{
penalty=calc_penalty();
cout<<"Service charge of "<<penalty<<" is imposed for not maintaining minimum balance"<<endl;
balance-=penalty;
display();
}
}
float Cur_Acct ::calc_penalty()
{
penalty = balance*0.2;
return penalty;
}
|
0eb06b5f42c9b1a30204d26e66ff9db7b70c9284
|
d66322fd0d1da3fb6ded8e1cd0ff429b59d9ccc5
|
/SRC/RUSS.CPP
|
57e989351742345acaa67c29383bd77097984e25
|
[] |
no_license
|
tolikk/blank
|
4b796c0c141b5251420eff1e39c34db8f33bcff0
|
3aec7706559c0cdeaef2c6d0b98c2be1253c5a39
|
refs/heads/master
| 2021-01-17T09:12:16.611191
| 2016-04-10T21:43:45
| 2016-04-10T21:43:45
| 1,504,481
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 33,620
|
cpp
|
RUSS.CPP
|
#include <owl.h>
#include <static.h>
#include <dialog.h>
#include <string.h>
#include <edit.h>
#include <stdio.h>
#include <array.h>
#include <window.h>
#pragma hdrfile
#include <pxengine.h>
#include <owl.h>
#include <dialog.h>
#include <edit.h>
#include <pxengine.h>
#include <pxtable.h>
#include <openbase.h>
#include <array.h>
#include <grncard.h>
#include <stdio.h>
#include <string.h>
#include <ruler.h>
#include <window.h>
#include <commdlg.h>
#include <russ.h>
#include "help.h"
#include "math.h"
#include "date.h"
#include "impexp.h"
#include "mand_av2.h"
#include "dateedit.h"
extern char ActivateParadox;
void FillPlacement(TComboBox* PlacementCombo, const char* Key, const char* Sect, int);
void SetAgent(char* ACode, TOpenBase& agents, PTComboBox AgName, int);
char* NumberToWords(double Value);
char* RussianFields[] = {
"Seria", //0
"Number", //1
"PSer", //2
"PNmb", //3
"RegDt", //4
"InsStart", //5
"TmStart", //6
"Period", //7
"InsEnd", //8
"Insurer", //9
"InsurerT", //10
"Owner", //11
"OwnerT", //12
"Marka", //13
"AutoId", //14
"PassSer", //15
"PassNmb", //16
"AutoNmb", //17
"Tarif", //18
"Pay1", //19
"Curr1", //20
"Pay2", //21
"Curr2", //22
"PayDate", //23
"StopDt", //24
"State", //25
"Agent", //26
"AgPcnt", //27
"SpecSr", //28
"SpecNmb", //29
"InsComp", //30
"RetSum", //31
"RetCurr", //32
"TarifGrp", //33
"Charact", //34
"RepDt", //35
"AgType", //36
"Resident", //37
};
char* RussianName = "\\bases\\MANDRUSS";
char* RusIniName = 0;
#define CNT_RUSS_FLDS (sizeof(RussianFields) / sizeof(RussianFields[0]))
//DATE
int RUSSModifyTarif = 1;
double GetRateCurrency(DATE payDate, char* CurrencyField);
class ChangeChecker
{
int* Val;
public:
ChangeChecker(int* V);
~ChangeChecker();
};
Russian::Russian(PTWindowsObject p)
: Dlg_base(p, ActivateParadox ? "Russ" : "RUSSCALC", RussianName, RussianFields, CNT_RUSS_FLDS),
agents(AgentDBName, AgentFields, AgFieldsCount)
{
char strBuffer[48];
if(!GetPrivateProfileString("RUSSIAN", "INI", "", strBuffer, sizeof strBuffer, ININame))
RusIniName = strdup(ININame);
else
RusIniName = strdup(strBuffer);
(m_Seria = new TComboBox(this, 100, 5))->DisableTransfer();
m_Number = new NumberEdit(this, 101, 11, 0);
m_prSeria = new TEdit(this, 102, 5);
m_prNumber = new NumberEdit(this, 103, 11, 0);
m_RegDate = new TDateEdit(this, 115, 11);
m_dtFrom = new TDateEdit(this, 104, 11);
m_tmFrom = new TTimeEdit(this, 108, 6);
m_dtTo = new TDateEdit(this, 105, 11);
m_Insurer = new TEdit(this, 122, 49);
m_InsurerType = new UrFizich(this, 124, 10);
m_Owner = new TEdit(this, 109, 49);
m_OwnerType = new UrFizich(this, 125, 10);
//m_Marka = new TEdit(this, 128, 25);
DynStr buff;
GetPrivateProfileString("RUSSIAN", "AutoMarkFile", RusIniName, buff, buff._sizeof(), RusIniName);
//((INIEdit*)m_Marka)->SetININame(buff);
m_Marka = new INIEdit(buff, "MANDATORY", this, 128, 25, "AutoType%d", "AutoType%d_%d");
m_IdNumber = new TEdit(this, 107, 18);
m_PassSer = new TEdit(this, 131, 5);
m_PassNmb = new NumberEdit(this, 132, 7, 0);
m_AutoNmb = new TEdit(this, 106, 13);
m_Charact = new NumberEdit(this, 111, 4, 0);
m_SpecSer = new TEdit(this, 116, 4);
m_SpecNmb = new NumberEdit(this, 136, 11, 0);
m_Tarif = new NumberEdit(this, 126, 10, 1);
m_Sum1 = new NumberEdit(this, 112, 10, 1);
m_Sum2 = new NumberEdit(this, 113, 10, 1 );
m_PayDate = new TDateEdit(this, 114, 11);
m_RepDate = new TDateEdit(this, 135, 11);
m_Percent = new NumberEdit(this, 117, 6, 1);
m_AgType = new UrFizich(this, 110, 10);
m_StopDate = new TDateEdit(this, 130, 11);
m_RetSum = new NumberEdit(this, 133, 10, 1);
m_Resident = new TCheckBox(this, 137, 0);
(m_Period = new TComboBox(this, 200, 1))->DisableTransfer();
(m_Val1 = new TComboBox(this, 203, 1))->DisableTransfer();
(m_Val2 = new TComboBox(this, 204, 1))->DisableTransfer();
(m_RetVal = new TComboBox(this, 134, 1))->DisableTransfer();
(m_Agent = new TComboBox(this, 205, 1))->DisableTransfer();
(m_State = new TComboBox(this, 206, 1))->DisableTransfer();
(m_Company = new TComboBox(this, 207, 1))->DisableTransfer();
(m_AutoType = new TComboBox(this, 201, 1))->DisableTransfer();
}
void InitVal(TComboBox* cb);
void InitVal2(TComboBox* cb);
void _FillAgents(TOpenBase* agents, TComboBox* AgName, int index);
void AlignCombo(TComboBox*);
void Russian::SetupWindow()
{
Dlg_base::SetupWindow();
m_State->AddString("НОРМАЛЬНЫЙ");
m_State->AddString("УТЕРЯН");
m_State->AddString("ИСПОРЧЕН");
m_State->AddString("РАСТОРГНУТ");
InitVal(m_Val1);
InitVal2(m_Val2);
InitVal2(m_RetVal);
m_Val1->DeleteString(m_Val1->FindExactString("DM", -1));
m_Val2->DeleteString(m_Val2->FindExactString("DM", -1));
m_RetVal->DeleteString(m_RetVal->FindExactString("DM", -1));
_FillAgents(&agents, m_Agent, RUSSIAN_TBL);
char* OldIniName = ININame;
ININame = RusIniName;
FillPlacement(m_Period, "Period%d", "Russian", 0);
FillPlacement(m_Company, "Company%d", "Russian", 0);
FillPlacement(m_Seria, "Seria%d", "Russian", 0);
ININame = OldIniName;
char strBuffer[64];
for(int i = 0;; i++) {
wsprintf(strBuffer, "Vid%d", i);
if(!GetPrivateProfileString("RUSSIAN", strBuffer, "", strBuffer, sizeof strBuffer, RusIniName))
break;
char* ch = strchr(strBuffer, ',');
if(ch) *ch = 0;
m_AutoType->AddString(strBuffer);
}
AlignCombo(m_Period);
AlignCombo(m_Company);
AlignCombo(m_Agent);
AlignCombo(m_AutoType);
AlignCombo(m_Seria);
if(ActivateParadox && base->First())
GetDataFromBase();
else {
date d;
getdate(&d);
char buff[100];
wsprintf(buff, "%02u.%02u.%04u", d.da_day, d.da_mon, d.da_year);
m_dtFrom->SetText(buff);
}
}
void DblToStr(char* str, double V, int Digit = 2);
extern DATE GD(char* str, int = 0);
void DateFBToStr(TOpenBase* base, int field, char* buffer);
void Russian::GetDataFromBase()
{
*OldCurr = 0;
double N;
char strBuffer[64];
ChangeChecker obj(&RUSSModifyTarif);
int PolisState;
(*base)(N, 25);
SetState(PolisState = N);
(*base)(buffer.Seria_, sizeof buffer.Seria_, 0);
m_Seria->SetText(buffer.Seria_);
(*base)(N, 1);
DblToStr(buffer.Number, N, 0);
(*base)(buffer.prSeria, sizeof buffer.prSeria, 2);
(*base)(N, 3);
DblToStr(buffer.prNumber, N, 0);
DateFBToStr(base, 5, buffer.dtFrom);
(*base)(buffer.tmFrom, sizeof buffer.tmFrom, 6);
DateFBToStr(base, 8, buffer.dtTo);
DateFBToStr(base, 35, buffer.RepDate);
m_Period->SetSelIndex(-1);
short Period;
(*base)(Period, 7);
for(int i = 0; i < m_Period->GetCount(); i++) {
char sVal[10];
wsprintf(sVal, "%d ", Period);
m_Period->GetString(strBuffer, i);
if(strstr(strBuffer, sVal) == strBuffer)
m_Period->SetSelIndex(i);
else {
wsprintf(sVal, "%d,", Period);
if(strstr(strBuffer, sVal) == strBuffer)
m_Period->SetSelIndex(i);
}
}
if(m_Period->GetCount() && m_Period->GetSelIndex() == -1 && PolisState != RUSS_BAD)
MessageBox(HWindow, "Не найден период", "Ошибка", MB_OK | MB_ICONSTOP);
m_AutoType->SetSelIndex(-1);
short Autotype;
(*base)(Autotype, 33);
m_AutoType->SetSelIndex(Autotype);
short Charact;
(*base)(Charact, 34);
DblToStr(buffer.Charact, Charact+1e-5, 0);
(*base)(buffer.Insurer, sizeof buffer.Insurer, 9);
(*base)(buffer.Owner, sizeof buffer.Owner, 11);
(*base)(buffer.InsurerType, sizeof buffer.InsurerType, 10);
(*base)(buffer.OwnerType, sizeof buffer.OwnerType, 12);
if(*buffer.InsurerType == 'F') strcpy(buffer.InsurerType, "Физ.лицо");
if(*buffer.InsurerType == 'U') strcpy(buffer.InsurerType, "Юр.лицо");
if(*buffer.OwnerType == 'F') strcpy(buffer.OwnerType, "Физ.лицо");
if(*buffer.OwnerType == 'U') strcpy(buffer.OwnerType, "Юр.лицо");
(*base)(buffer.AgType, sizeof buffer.AgType, 36);
if(*buffer.AgType == 'U') strcpy(buffer.AgType, "Юр.лицо");
if(*buffer.AgType == 'F') strcpy(buffer.AgType, "Физ.лицо");
(*base)(buffer.Marka, sizeof buffer.Marka, 13);
(*base)(buffer.IdNumber, sizeof buffer.IdNumber, 14);
(*base)(buffer.PassSer, sizeof buffer.PassSer, 15);
(*base)(N, 16);
DblToStr(buffer.PassNmb, N, 0);
(*base)(buffer.SpecSer, sizeof buffer.SpecSer, 28);
(*base)(N, 29);
DblToStr(buffer.SpecNumber, N, 0);
(*base)(buffer.AutoNmb, sizeof buffer.AutoNmb, 17);
(*base)(N, 18);
DblToStr(buffer.Tarif, N, 2);
(*base)(N, 31);
DblToStr(buffer.RetSum, N, 2);
(*base)(strBuffer, sizeof strBuffer, 32);
m_RetVal->SetSelIndex(-1);
m_RetVal->SetText(strBuffer);
m_Company->SetSelIndex(-1);
short S;
(*base)(S, 30);
m_Company->SetSelIndex(S);
if(m_Company->GetCount() && m_Company->GetSelIndex() == -1)
MessageBox(HWindow, "Компания не определена", "Ошибка", MB_OK | MB_ICONSTOP);
(*base)(N, 19);
DblToStr(buffer.Sum1, N, 2);
m_Val1->SetSelIndex(-1);
(*base)(strBuffer, sizeof strBuffer, 20);
m_Val1->SetText(strBuffer);
(*base)(N, 21);
DblToStr(buffer.Sum2, N, 2);
m_Val2->SetSelIndex(-1);
(*base)(strBuffer, sizeof strBuffer, 22);
m_Val2->SetText(strBuffer);
if(!*strBuffer) m_Val2->SetSelIndex(0);
DateFBToStr(base, 23, buffer.PayDate);
DateFBToStr(base, 4, buffer.Regdate);
m_Agent->SetSelIndex(-1);
char AGENT[10];
(*base)(AGENT, sizeof AGENT, 26);
SetAgent(AGENT, agents, m_Agent, 0);
(*base)(N, 27);
DblToStr(buffer.Percent, N, 2);
DateFBToStr(base, 24, buffer.StopDate);
if(PolisState == RUSS_BAD)
*buffer.RepDate = 0;
else {
if(!strcmp(buffer.RepDate, buffer.PayDate))
*buffer.RepDate = 0;
}
(*base)(AGENT, sizeof AGENT, 37);
buffer.Resident = (*AGENT == 'Y');
Dlg_base::GetDataFromBase();
}
void Russian::SetButtons()
{
Dlg_base::SetButtons();
}
void Russian::SetState(int State)
{
m_State->SetSelIndex(State);
}
/*
int GetBadTarif(HWND HWindow, char* Curr, char* sBadTarif)
{
char strBuffer[32];
char Key[32];
sprintf(Key, "%sBadTarif", Curr);
if(!GetPrivateProfileString("Russian", Key, "", strBuffer, sizeof strBuffer, ININame)) {
badTraifLbl:MessageBox(HWindow, "Тариф не найден или не правильный", strBuffer, MB_OK | MB_ICONSTOP);
return 0;
}
char* TransStart = strBuffer;
while((*TransStart == ' ' || *TransStart == 8) && *TransStart) TransStart++;
if(!*TransStart) goto badTraifLbl;
char* bad;
double BadTarif = strtod(TransStart, &bad);
if(!*bad) goto badTraifLbl;
if(strlen(Curr) == 0 && !strcmp(bad, "DM")) goto badTraifLbl;
if(strcmp(Curr, "EUR") == 0 && !strcmp(bad, "EUR")) goto badTraifLbl;
DblToStr(sBadTarif, BadTarif);
return 1;
}
*/
void Russian::ChRegDate(RTMessage msg)
{
if(msg.LP.Hi == EN_CHANGE && RUSSModifyTarif) {
// CalcTarif();
InitTime();
}
}
/*
char* Russian::GetCurrency(char* TTN)
{
static char Curr[5];
if(TTN) *TTN = 0;
DATE divDate, div2Date;
PXDateEncode(1, 1 , 2002, &divDate);
PXDateEncode(8, 1 , 2002, &div2Date);
char sDate[32];
m_RegDate->GetText(sDate, sizeof sDate);
DATE rDate = GD(sDate, 1);
if (!rDate)
strcpy(Curr, "?");
else if(rDate >= div2Date) {
strcpy(Curr, "EUR");
if(TTN) strcpy(TTN, "EUR2");
}
else if(rDate >= divDate) {
strcpy(Curr, "EUR");
if(TTN) strcpy(TTN, "EUR");
}
else strcpy(Curr, "");
return Curr;
}
*/
int _IsValidPolisNumber(const char* SECTION, _str s, long n, char* INI, char* Agent);
int Russian::SetDataToBase()
{
Dlg_base::SetDataToBase();
int Index = m_Agent->GetSelIndex();
if(Index == -1) {
SetFocus(m_Agent->HWindow);
return 0;
}
char AgCode_[10];
long _AgValue = SendMessage(m_Agent->HWindow, CB_GETITEMDATA, Index, 9);
memcpy(AgCode_, &_AgValue, 4);
AgCode_[4] = 0;
char strBuffer[64];
int IsBad = 0;
if(!strcmp(buffer.Owner, "ИСПОРЧЕН") || !*buffer.Owner) {
if(MessageBox(HWindow, GetRCStr(506), "Отвечай поскорей", MB_YESNO | MB_ICONINFORMATION | MB_SYSTEMMODAL) == IDNO)
return 0;
m_Tarif->SetText("");
SetState(RUSS_BAD);
m_Insurer->SetText("ИСПОРЧЕН");
strcpy(buffer.Insurer, "ИСПОРЧЕН");
(*base)(9, buffer.Insurer);
(*base)(33, short(-1));
IsBad = 1;
}
m_Seria->GetText(buffer.Seria_, sizeof buffer.Seria_);
(*base)(0, buffer.Seria_);
(*base)(1, atof(buffer.Number));
if(m_State->GetSelIndex() == -1 || (!IsBad && m_State->GetSelIndex() == RUSS_BAD))
SetState(RUSS_NORMAL);
if(!_IsValidPolisNumber("RUSSIAN", base->GetString(0), atol(buffer.Number), RusIniName, AgCode_)) {
SetFocus(m_Number->HWindow);
return 0;
}
DATE PayDate = 0;
if(!IsBad) {
(*base)(9, buffer.Insurer);
(*base)(11, buffer.Owner);
(*base)(18, atof(buffer.Tarif));
if(atof(buffer.Sum1) < 0.01 && !*buffer.prNumber) {
SetFocus(m_Sum1->HWindow);
return 0;
}
(*base)(19, atof(buffer.Sum1)); //SUMM1
m_Val1->GetText(strBuffer, sizeof strBuffer);
if(strlen(strBuffer) == 0 && !*buffer.prNumber) {
SetFocus(m_Sum1->HWindow);
return 0;
}
char Curr1[5];
strcpy(Curr1, strBuffer);
(*base)(20, strBuffer); //VAL CURR 1
m_Val2->GetText(strBuffer, sizeof strBuffer);
(*base)(21, atof(buffer.Sum2)); //SUMM2
(*base)(22, strBuffer); //VAL CURR 2
if(*strBuffer && atof(buffer.Sum2) < 0.01 || !*strBuffer && atof(buffer.Sum2) >= 0.01) {
SetFocus(m_Sum2->HWindow);
return 0;
}
if(!strcmp(strBuffer, Curr1) && !*buffer.prSeria) {
SetFocus(m_Val1->HWindow);
return 0;
}
DATE date = GD(buffer.PayDate);
if(!date) {
SetFocus(m_PayDate->HWindow);
return 0;
}
PayDate = date;
(*base)(23, date);
if(strlen(buffer.Insurer) < 5) {
SetFocus(m_Insurer->HWindow);
return 0;
}
if(strlen(buffer.Owner) < 5) {
SetFocus(m_Owner->HWindow);
return 0;
}
(*base)(9, buffer.Insurer);
(*base)(10, *buffer.InsurerType == 'Ф' ? "F" : "U");
if(!*buffer.InsurerType) {
SetFocus(m_InsurerType->HWindow);
return 0;
}
(*base)(11, buffer.Owner);
(*base)(12, *buffer.OwnerType == 'Ф' ? "F" : "U");
if(!*buffer.OwnerType) {
SetFocus(m_OwnerType->HWindow);
return 0;
}
if(strlen(buffer.Marka) < 3) {
SetFocus(m_Marka->HWindow);
return 0;
}
(*base)(13, buffer.Marka);
if(strlen(buffer.IdNumber) < 5) {
SetFocus(m_IdNumber->HWindow);
return 0;
}
(*base)(14, buffer.IdNumber);
if(strlen(buffer.PassSer) < 2) {
SetFocus(m_PassSer->HWindow);
return 0;
}
(*base)(15, buffer.PassSer);
if(strlen(buffer.PassNmb) < 5) {
SetFocus(m_PassNmb->HWindow);
return 0;
}
(*base)(16, atof(buffer.PassNmb));
//if(strlen(buffer.SpecSer) < 1) {
// SetFocus(m_SpecSer->HWindow);
// return 0;
//}
(*base)(28, buffer.SpecSer);
//if(strlen(buffer.SpecNumber) < 5) {
// SetFocus(m_SpecNmb->HWindow);
// return 0;
//}
(*base)(29, atof(buffer.SpecNumber));
if(strlen(buffer.AutoNmb) < 5) {
SetFocus(m_AutoNmb->HWindow);
return 0;
}
(*base)(17, buffer.AutoNmb);
}
DATE regdate;
DATE date = regdate = GD(buffer.Regdate);
if(!date) {
SetFocus(m_RegDate->HWindow);
return 0;
}
(*base)(4, date);
DATE repdate = *buffer.RepDate ? GD(buffer.RepDate) : -1;
if(!repdate) {
SetFocus(m_RepDate->HWindow);
return 0;
}
if(IsBad/* && repdate == -1*/)
repdate = regdate;
if(!IsBad && repdate == -1)
repdate = PayDate;
(*base)(35, repdate);
if(fabs(repdate - regdate) > 30) {
SetFocus(m_RepDate->HWindow);
return 0;
}
(*base)(26, AgCode_);
if(!IsBad) {
(*base)(36, *buffer.AgType == 'Ф' ? "F" : "U");
if(!*buffer.AgType) {
SetFocus(m_AgType->HWindow);
return 0;
}
}
(*base)(25, (short)m_State->GetSelIndex());
(*base)(30, (short)m_Company->GetSelIndex());
if(m_Company->GetSelIndex() == -1) {
SetFocus(m_Company->HWindow);
return 0;
}
int IsDup = 0;
if(!IsBad) {
if(*buffer.prSeria || atol(buffer.prNumber) > 0) {
char msgStr[128];
sprintf(msgStr, "Вы уверены что полис %s/%s потерялся?", buffer.prSeria, buffer.prNumber);
if(MessageBox(HWindow, msgStr, "Отвечай поскорей", MB_YESNO | MB_ICONINFORMATION | MB_SYSTEMMODAL) == IDNO)
return 0;
char* ShortFields[] = { "Seria", "Number", "State" };
TOpenBase I(RussianName, ShortFields, 3);
if(I.pxErr) {
Err:MessageBox(HWindow, GetRCStr(552), "Ошибка", MB_OK | MB_ICONSTOP);
return 0;
}
I(0, buffer.prSeria);
I(1, atof(buffer.prNumber));
if(PXSrchKey(I.getTblHandle(), I.getRecHandle(), 2, SEARCHFIRST) == PXSUCCESS) {
I.Get();
short State;
I(State, 2);
if(State == RUSS_BAD) {
MessageBox(HWindow, GetRCStr(563), "Ошибка", MB_OK | MB_ICONSTOP);
return 0;
}
I(2, (short)RUSS_LOST);
if(PXRecUpdate(I.getTblHandle(), I.getRecHandle()) != PXSUCCESS)
goto Err;
IsDup = 1;
//Обнуляем суммы
(*base)(19, 0.);
(*base)(20, "");
(*base)(21, 0.);
(*base)(22, "");
(*base)(18, 0.);
m_Sum1->SetText("0");
m_Sum2->SetText("0");
m_Tarif->SetText("0");
}
else {
MessageBox(HWindow, GetRCStr(551), "Ошибка", MB_OK | MB_ICONSTOP);
return 0;
}
}
else {
if(atof(buffer.Tarif) < 0.01) {
SetFocus(m_Tarif->HWindow);
return 0;
}
}
(*base)(2, buffer.prSeria);
(*base)(3, atof(buffer.prNumber));
date = GD(buffer.dtFrom);
if(!date) {
SetFocus(m_dtFrom->HWindow);
return 0;
}
(*base)(5, date);
DATE dateFrom = date;
if(strlen(buffer.tmFrom) < 3 || !strchr(buffer.tmFrom, ':')) {
SetFocus(m_tmFrom->HWindow);
return 0;
}
(*base)(6, buffer.tmFrom);
date = GD(buffer.dtTo);
if(!date) {
SetFocus(m_dtTo->HWindow);
return 0;
}
(*base)(8, date);
DATE dateTo = date;
if(dateFrom >= dateTo || (dateTo - dateFrom) > 366) {
SetFocus(m_dtTo->HWindow);
return 0;
}
if(dateFrom < PayDate) {
SetFocus(m_PayDate->HWindow);
return 0;
}
if(m_Period->GetSelIndex() == -1) {
SetFocus(m_Period->HWindow);
return 0;
}
m_Period->GetText(strBuffer, sizeof strBuffer);
(*base)(7, (short)atoi(strBuffer));
if(IsDup) {
(*base)(27, 0.);
m_Percent->SetText("0");
}
else
(*base)(27, atof(buffer.Percent));
if(atof(buffer.Percent) < 0) {
SetFocus(m_Percent->HWindow);
return 0;
}
(*base)(33, (short)m_AutoType->GetSelIndex());
(*base)(34, (short)atoi(buffer.Charact));
(*base)(37, buffer.Resident ? "Y" : "N");
DATE stopdate = GD(buffer.StopDate, 1);
if(*buffer.StopDate && !stopdate) {
SetFocus(m_StopDate->HWindow);
return 0;
}
if (stopdate) {
if(MessageBox(HWindow, "Полис расторгнут?", "?", MB_YESNO | MB_ICONQUESTION) == IDNO) return 0;
(*base)(24, stopdate);
(*base)(25, (short)3);
(*base)(31, atof(buffer.RetSum));
m_RetVal->GetText(strBuffer, sizeof strBuffer);
(*base)(32, strBuffer);
SetState(RUSS_STOP);
}
else
if(m_State->GetSelIndex() == RUSS_STOP) {
SetState(RUSS_NORMAL);
m_RetVal->SetSelIndex(-1);
m_RetSum->SetText("");
}
}
return 1;
}
Russian::~Russian()
{
delete RusIniName;
}
int auxFindLike(const char* TableName, char* FldName, char* Maska, Array& Strings, TDialog* Dlg, char* ResStr, int IsDigit = 0, char** CheckFld = 0);
void Russian::FindByField(int fldNumber, TEdit* Ctrl)
{
Array Strings(10, 0, 10);
char str[70];
char maska[20];
Ctrl->GetText(maska, sizeof maska);
int Result = auxFindLike(RussianName/*"\\Mandruss"*/, RussianFields[fldNumber], maska, Strings, this, str);
if(Result != 1) return;
(*base)(0, strtok(str, "/"));
(*base)(1, atof(strtok(0, " ")));
if(!PXSrchKey(base->getTblHandle(), base->getRecHandle(), 2, SEARCHFIRST)) {
base->Get();
GetDataFromBase();
}
else
MessageBox(HWindow, "Ошибка", "Ошибка поиска", MB_OK | MB_ICONINFORMATION | MB_SYSTEMMODAL);
}
/*void Russian::ChDNumber(RTMessage msg)
{
if(RUSSModifyTarif && msg.LP.Hi == EN_CHANGE)
CalcTarif();
}
*/
void Russian::FindSN(RTMessage)
{
char buff[32];
m_Seria->GetText(buff, sizeof buff);
(*base)(0, buff);
m_Number->GetText(buff, sizeof buff);
(*base)(1, atof(buff));
if(!PXSrchKey(base->getTblHandle(), base->getRecHandle(), 2, SEARCHFIRST))
{
base->Get();
GetDataFromBase();
}
else
MessageBox(HWindow, GetRCStr(556), "Ошибка поиска", MB_OK | MB_ICONINFORMATION | MB_SYSTEMMODAL);
}
//int auxFindLike(const char* TableName, char* FldName, char* Maska, Array& Strings, TDialog* Dlg, char* str);
void Russian::FindAutoNumber(RTMessage)
{
FindByField(17, m_AutoNmb);
/*
Array Strings(10, 0, 10);
char str[70];
char maska[20];
m_AutoNmb->GetText(maska, sizeof maska);
int Result = auxFindLike("\\Mandruss", "autonmb", maska, Strings, this, str);
if(Result != 1) return;
(*base)(0, strtok(str, "/"));
(*base)(1, atof(strtok(0, " ")));
if(!PXSrchKey(base->getTblHandle(), base->getRecHandle(), 2, SEARCHFIRST)) {
base->Get();
GetDataFromBase();
}
else
MessageBox(HWindow, "Ошибка", "Ошибка поиска", MB_OK | MB_ICONINFORMATION | MB_SYSTEMMODAL);
*/
}
void Russian::FindPrSN(RTMessage)
{
char buff[32];
m_prSeria->GetText(buff, sizeof buff);
(*base)(0, buff);
m_prNumber->GetText(buff, sizeof buff);
(*base)(1, atof(buff));
if(!PXSrchKey(base->getTblHandle(), base->getRecHandle(), 2, SEARCHFIRST))
{
base->Get();
GetDataFromBase();
}
else
MessageBox(HWindow, GetRCStr(556), "Ошибка поиска", MB_OK | MB_ICONINFORMATION | MB_SYSTEMMODAL);
}
void Russian::FindName(RTMessage)
{
FindByField(11, m_Owner);
}
void Russian::FindIns(RTMessage)
{
FindByField(9, m_Insurer);
}
void Spell(char*& dest, char* ch)
{
while(*ch) {
*dest++ = *ch++;
*dest++ = 0;
}
}
void Russian::Print(RTMessage)
{
if(!SetDataToBase()) return;
char SpecNumber[16];
char SpecSer[7];
char AutoId[20];
m_SpecSer->GetText(SpecSer, sizeof SpecSer);
m_SpecNmb->GetText(SpecNumber, sizeof SpecNumber);
m_IdNumber->GetText(AutoId, sizeof AutoId);
GetDataFromBase();
m_SpecSer->SetText(SpecSer);
m_SpecNmb->SetText(SpecNumber);
m_IdNumber->SetText(AutoId);
strcpy(buffer.SpecSer, SpecSer);
strcpy(buffer.SpecNumber, SpecNumber);
strcpy(buffer.IdNumber, AutoId);
char* dest = new char [2500];
char* strdata = dest;
memset(dest, 0, 2400);
m_tmFrom->GetText(buffer.tmFrom, sizeof buffer.tmFrom);
Spell(dest, strtok(buffer.tmFrom, ":;./"));
Spell(dest, strtok(0, ":;./"));
char* start = dest;
m_dtFrom->GetText(buffer.dtFrom, sizeof buffer.dtFrom);
Spell(dest, strtok(buffer.dtFrom, ":;./"));
Spell(dest, strtok(0, ":;./"));
Spell(dest, strtok(0, ":;./") + 2);
m_dtTo->GetText(buffer.dtTo, sizeof buffer.dtTo);
Spell(dest, strtok(buffer.dtTo, ":;./"));
Spell(dest, strtok(0, ":;./"));
Spell(dest, strtok(0, ":;./") + 2);
memmove(dest, start, dest - start);
dest += dest - start;
strcpy(dest, buffer.Insurer);
dest += strlen(dest) + 1;
strcpy(dest, buffer.Owner);
dest += strlen(dest) + 1;
strcpy(dest, buffer.Marka);
dest += strlen(dest) + 1;
for(int i = 0; i < 17; i++) {
if(strlen(buffer.IdNumber) > i)
*dest++ = buffer.IdNumber[i];
*dest++ = 0;
}
for(i = 0; i < 4; i++) {
if(strlen(buffer.PassSer) > i)
*dest++ = buffer.PassSer[i];
*dest++ = 0;
}
for(i = 0; i < 6; i++) {
if(strlen(buffer.PassNmb) > i)
*dest++ = buffer.PassNmb[i];
*dest++ = 0;
}
strcpy(dest, buffer.AutoNmb);
dest += strlen(dest) + 1;
for(i = 0; i < 3; i++) {
if(strlen(buffer.SpecSer) > i)
*dest++ = buffer.SpecSer[i];
*dest++ = 0;
}
for(i = 0; i < 10; i++) {
if(strlen(buffer.SpecNumber) > i)
*dest++ = buffer.SpecNumber[i];
*dest++ = 0;
}
sprintf(dest, "%0.2f (%s) рублей", atof(buffer.Tarif), NumberToWords(atof(buffer.Tarif)));
int Kop = long(atof(buffer.Tarif) * 100 + 0.0001) % 100;
if(Kop) sprintf(dest + strlen(dest), " %02d копеек", Kop);
dest += strlen(dest) + 1;
m_RegDate->GetText(buffer.Regdate, sizeof buffer.Regdate);
strcat(dest, strtok(buffer.Regdate, ":;./"));
dest += strlen(dest) + 1;
strcat(dest, strtok(0, ":;./"));
strcpy(dest, GetRCStr(119 + atoi(dest)));
dest += strlen(dest) + 1;
strcat(dest, strtok(0, ":;./") + 2);
dest += strlen(dest) + 1;
((TRulerWin*)Parent)->SetValues(strdata);
Dlg_base::Print1();
delete strdata;
}
void Russian::Clear()
{
SetFocus(m_Number->HWindow);
char class_name[40];
HWND Child = GetWindow(HWindow, GW_CHILD);
for(;Child;) {
::GetClassName(Child, class_name, sizeof class_name);
if(!strcmpi(class_name, "EDIT"))
SendMessage(Child, WM_SETTEXT, 0, (long)"");
if(!strcmpi(class_name, "COMBOBOX"))
SendMessage(Child, CB_SETCURSEL, -1, 0);
Child = GetWindow(Child, GW_HWNDNEXT);
}
Default();
}
void Russian::Default()
{
date d;
getdate(&d);
char buff[100];
wsprintf(buff, "%02u.%02u.%04u", d.da_day, d.da_mon, d.da_year);
m_dtFrom->SetText(buff);
m_RegDate->SetText(buff);
m_PayDate->SetText(buff);
/* struct time t;
gettime(&t);
wsprintf(buff, "%02u:%02u", t.ti_hour, t.ti_min);
m_RegTime->SetText(buff);
*/
GetPrivateProfileString("Russian", "DefSeria", "", buff, sizeof buff, RusIniName);
m_Seria->SetText(buff);
m_SpecSer->SetText(buff);
if(GetPrivateProfileString("Russian", "DefAgent", "", buff, sizeof buff, RusIniName)) {
//MessageBox(0, buff, buff, 0);
SetAgent(buff, agents, m_Agent, 0);
TMessage msg;
msg.LP.Hi = CBN_SELCHANGE;
ChAgent(msg);
}
m_Company->SetSelIndex(GetPrivateProfileInt("Russian", "DefCompany", 0, RusIniName));
m_Period->SetSelIndex(GetPrivateProfileInt("Russian", "DefPeriod", 0, RusIniName));
m_AutoType->SetSelIndex(GetPrivateProfileInt("Russian", "DefTarif", 0, RusIniName));
CalcEndDate();
CalcTarif();
SetState(RUSS_NORMAL);
}
void Russian::Help(RTMessage msg)
{
if(msg.WParam == 1000)
WinHelp(GetApplication()->MainWindow->HWindow, "blank.hlp", HELP_CONTEXT, HELP_WARTA);
Dlg_base::Help(msg);
}
void Russian::ChAgent(RTMessage msg)
{
int IsUr;
if(msg.LP.Hi == CBN_SELCHANGE) {
m_Percent->SetText(GetAgPercent(SendMessage(m_Agent->HWindow, CB_GETITEMDATA, m_Agent->GetSelIndex(), 0), RUSSIAN_TBL, IsUr));
m_AgType->SetText(IsUr ? "Юр." : "Физ.");
}
}
void Russian::ChPeriod(RTMessage msg)
{
if(msg.LP.Hi == CBN_SELCHANGE && RUSSModifyTarif) {
CalcEndDate();
CalcTarif();
}
}
void Russian::ChAutoType(RTMessage msg)
{
if(msg.LP.Hi == CBN_SELCHANGE && RUSSModifyTarif) {
CalcTarif();
}
}
void Russian::ChStartDate(RTMessage msg)
{
if(msg.LP.Hi == EN_CHANGE && RUSSModifyTarif) {
CalcEndDate();
InitTime();
}
}
DATE aux_incDate(DATE startdate, int inc1, int value);
int getDurationType(char* str, char**);
void Russian::CalcEndDate()
{
char datebuf[15], PeriodName[32];
m_dtFrom->GetText(datebuf, sizeof datebuf);
m_Period->GetText(PeriodName, sizeof PeriodName);
if(!*PeriodName) return;
DATE startdate = GD(datebuf, 1);
if(startdate) {
char* sptr = PeriodName;
int dtype = getDurationType(PeriodName, &sptr);
DATE enddate = aux_incDate(startdate, dtype, atoi(sptr));
int d, m, y;
PXDateDecode(--enddate, &m, &d, &y);
sprintf(datebuf, "%02u.%02u.%04u", d, m, y);
m_dtTo->SetText(datebuf);
}
}
void Russian::CalcTarif()
{
if(!RUSSModifyTarif) return;
char tarifStr[128];
char Key[32];
int IndexAutoType = m_AutoType->GetSelIndex();
int IndexPeriod = m_Period->GetSelIndex();
m_Charact->GetText(tarifStr, sizeof tarifStr);
int Charact = atoi(tarifStr);
//m_InsurerType->GetText(tarifStr, sizeof tarifStr);
m_OwnerType->GetText(tarifStr, sizeof tarifStr);
char PeopleType = *tarifStr == 'Ю' ? 'U' : 'F';
if(IndexAutoType == -1 || IndexPeriod == -1) return;
sprintf(Key, "Vid%d", IndexAutoType);
GetPrivateProfileString("Russian", Key, "", tarifStr, sizeof tarifStr, RusIniName);
char* ch = strchr(tarifStr, ',');
if(ch) ch++;
int CharactGroup = 0;
//Поиск классификации по параметру
if(ch) {
for(;;) {
if(Charact <= atoi(ch)) {
CharactGroup = atoi(ch);
break;
}
ch = strchr(ch, ',');
if(!ch) break;
if(ch) ch++;
}
}
sprintf(tarifStr, "Tarif%s_%c_%d_%d", m_Resident->GetCheck() ? "R" : "", PeopleType, IndexAutoType, CharactGroup);
GetPrivateProfileString("Russian", tarifStr, "", tarifStr, sizeof tarifStr, RusIniName);
char* firstdivider = tarifStr;//strchr(tarifStr, ',');
char* OneTarifStr;// = tarifStr;//strchr(tarifStr, ',');
for(int i = 0; i <= IndexPeriod; i++) {
firstdivider = strchr(OneTarifStr = firstdivider, ',');
if(!firstdivider) break;
*firstdivider = 0;
firstdivider++;
}
if((IndexPeriod - i) > 1) {
m_Tarif->SetText("<не найден>");
return;
}
while(*OneTarifStr == ' ') OneTarifStr++;
m_Tarif->SetText(OneTarifStr);
}
void Russian::SetVal(RTMessage)
{
char buff[26];
m_Tarif->GetText(buff, sizeof buff);
m_Sum1->SetText(buff);
m_Val1->SetText("RUR");
strcpy(OldCurr, "RUR");
m_Sum2->SetText("");
m_Val2->SetSelIndex(0);
}
void Russian::CopyInsurer(RTMessage)
{
char strBuffer[64];
m_Insurer->GetText(strBuffer, sizeof strBuffer);
m_Owner->SetText(strBuffer);
m_InsurerType->GetText(strBuffer, sizeof strBuffer);
m_OwnerType->SetText(strBuffer);
}
void Russian::ChInsurerType(RTMessage msg)
{
if(msg.LP.Hi == EN_CHANGE && RUSSModifyTarif) {
CalcTarif();
}
}
void Russian::ChCharact(RTMessage msg)
{
if(msg.LP.Hi == EN_CHANGE && RUSSModifyTarif) {
CalcTarif();
}
}
/*
void Russian::ChRegDate(RTMessage msg)
{
if(msg.LP.Hi == EN_CHANGE && RUSSModifyTarif) {
InitTime();
}
}
void Russian::ChStartDate(RTMessage msg)
{
if(msg.LP.Hi == EN_CHANGE && RUSSModifyTarif) {
InitTime();
}
}
*/
void Russian::InitTime()
{
char s1[16], s2[16];
m_RegDate->GetText(s1, sizeof s1);
m_dtFrom->GetText(s2, sizeof s2);
DATE regdt = GD(s1, 1);
DATE startdt = GD(s2, 1);
if(regdt == startdt) {
struct time t;
gettime(&t);
wsprintf(s1, "%02u:%02u", t.ti_hour, t.ti_min);
m_tmFrom->SetText(s1);
}
else
m_tmFrom->SetText("00:00");
}
void Russian::ChResident(RTMessage msg)
{
if(msg.LP.Hi == BN_CLICKED)
CalcTarif();
}
static int ImpFunc(TOpenBase* FileDb, TOpenBase* Db, void* Data)
{
if(FileDb->GetDouble(18) != Db->GetDouble(18))
{
DynStr msg;
sprintf(msg, "%s/%5.0f\nБыло %s %5.0f\nСтало %s %5.0f\n$%s", Db->GetString(0).s, Db->GetDouble(1),
Db->GetString(9).s, Db->GetDouble(18), FileDb->GetString(9).s, FileDb->GetDouble(18), GetRCStr(637));
if(MessageBox(GetApplicationObject()->MainWindow->HWindow, msg, "!", MB_ICONQUESTION | MB_YESNO) != IDYES)
{
*strchr(msg, '$') = 0;
((Array*)Data)->add(*new String(msg));
return 0;
}
}
return 1;
}
void Russian::Import()
{
Array list(100);
list.ownsElements(TRUE);
char list1[] = {25, 2, 3, 24, 0};
char list2[] = {25, 2, 3, 24, 26, 5, 6, 7, 8, 18, 19, 20, 21, 22, 23, 31, 32, 35, 0};
long Result = ImportData(RussianName, RussianFields, CNT_RUSS_FLDS, ImpFunc, &list, 26, 25, RUSS_BAD, list1, list2);
if(Result) {
MessageBox(GetApplicationObject()->MainWindow->HWindow, GetRCStr(700+Result), "!", MB_ICONEXCLAMATION);
}
ShowArray(list);
}
void Russian::Export(PTWindowsObject Parent)
{
Priod_Params* data = new Priod_Params;
strcpy(data->filename, RussianName);
if(GetApplicationObject()->ExecDialog(new getDate(Parent, &data->m, &data->y, &data->dm, data->filename)) == IDOK) {
long Error = ExportData(RussianName, RussianFields, CNT_RUSS_FLDS, 0, 0, data->filename, data->m, data->y, data->dm, 26, 8);
sprintf(data->filename, GetRCStr(Error > 0 ? 621: 622), labs(Error));
//if(Error <= 0) unlink(data->filename);
MessageBox(Parent->HWindow, data->filename, "", 0);
}
delete data;
}
void ReplaceCurrs(TEdit* m_PayDate, char* OldCurr, TEdit* m_Pay1, TComboBox* m_Curr1, int);
void ReplaceCurrs2(TEdit* m_PayDate, char* OldCurr, TEdit* m_Pay1, TComboBox* m_Curr1, int IsUr)
{
char currency[5];
m_Curr1->GetText(currency, sizeof currency);
int round = !IsUr || strcmp("BRB", currency)==0;
ReplaceCurrs(m_PayDate, OldCurr, m_Pay1, m_Curr1, !round);
}
void Russian::ChPayCurr(RTMessage msg)
{
if(msg.LP.Hi == CBN_SELCHANGE && *OldCurr) {
m_InsurerType->GetText(buffer.InsurerType, sizeof buffer.InsurerType);
ReplaceCurrs2(m_PayDate, OldCurr, m_Sum1, m_Val1, *buffer.InsurerType == 'Ю');
}
}
void Russian::ChNormal(RTMessage msg)
{
SetState(RUSS_NORMAL);
}
|
581dbc77700089311028385810106213b6a4c0e6
|
e7e2dea158b23da361adf8591e690691162ab342
|
/ConsoleWindow/FileModule/FileButton.h
|
10257b0cef8b7deb4fb8a14f1f21be0b4dfa82b4
|
[] |
no_license
|
390031942/EasyVulkanFramework
|
bc00f7ac46a70becdba21b96e191907922869d97
|
099d5098c82612dc19c7ab9a84a3c2f991f67d66
|
refs/heads/master
| 2022-12-11T05:15:22.596158
| 2020-09-09T08:24:39
| 2020-09-09T08:24:39
| 294,052,201
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 748
|
h
|
FileButton.h
|
#pragma once
#include <QPushButton>
#include <QLabel>
#include <qevent.h>
#include <qmenu.h>
#include <qmessagebox.h>
#include "FileLabel.h"
#include "Easy2DFileDefs.h"
#include <qtimer.h>
class QTimer;
class FileButton : public QPushButton
{
Q_OBJECT
public:
FileButton(QWidget *parent,const QString filename,const QString suffix);
~FileButton();
void SetButtonID(int id);
QString GetFileLabel();
protected:
void mousePressEvent(QMouseEvent *event);
void mouseDoubleClickEvent (QMouseEvent *event);
private:
FileLabel *m_FileLabel;
int m_id;
QMenu *m_contextMenu;
QAction *m_addAction;
QAction *m_delAction;
QPixmap m_Icon;
void OnClick_Add();
void OnClick_Del();
void OnEdit_Finished();
signals:
void DoubleClick(int id);
};
|
111722246d9af82c4b59857e632414dbe815a038
|
f754d089b9c88d4b62cb6b4b2cefe25257bb4cb3
|
/Think Like a Programmer/Chapter2/Exercises/2.6/binaryToDecimal.cpp
|
84ae5ac50c7d8b2ce59ef18048ae144f2d86a198
|
[] |
no_license
|
OscarSandoval21/Book-Exercises
|
6e053f38405781d1cc7a98096e4b3ef4eba42d5a
|
45d75c8dd8c9e35932741fef1ba6c7448cac9d4c
|
refs/heads/main
| 2023-03-11T08:04:18.344929
| 2021-02-21T23:21:39
| 2021-02-21T23:21:39
| 332,649,750
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 676
|
cpp
|
binaryToDecimal.cpp
|
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::string;
int main() {
char digit;
int decimalNumber = 0;
string binaryNumber = "";
int position = 1;
cout << "Enter a binary number to convert to decimal: ";
digit = cin.get();
while (digit != 10)
{
binaryNumber += digit;
if (position % 4 == 0)
binaryNumber += " ";
if (decimalNumber > 0)
decimalNumber *= 2;
decimalNumber += digit - '0';
position++;
digit = cin.get();
}
cout << binaryNumber << " converted into decimal is: " << decimalNumber << "\n";
return 0;
}
|
88fa2812bbc76dcd8c6c09077883526ba3c530e6
|
51ac1d301c8b42235782c0dbe85c262b63a9accf
|
/MissionRndOffline_Prob/Ascen_ofArray_0and1_method2.cpp
|
ac7cc95de08969b3c90bf725eb3f679f400a7579
|
[] |
no_license
|
vineethakagitha/Extra-problems
|
4dc0e8abb3d2a8ec7173b678a01b2c3b9149b3ef
|
86b09bc20f51c8996ec52ed13b1499154316d265
|
refs/heads/master
| 2021-01-18T12:45:09.051233
| 2015-12-24T14:28:27
| 2015-12-24T14:28:27
| 47,631,741
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 504
|
cpp
|
Ascen_ofArray_0and1_method2.cpp
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void sort(int*, int);
void main()
{
int *a, n, i;
scanf_s("%d", &n);
a = (int*)malloc(sizeof(int)*n);
for (i = 0; i < n; i++)
scanf_s("%d", &a[i]);
sort(a, n);
for (i = 0; i < n; i++)
printf("%d\t", a[i]);
_getch();
}
void sort(int *a, int n)
{
int i, j, temp;
do
{
for (i = 0; a[i] != 1; i++);
for (j = n - 1; a[j] != 0; j--);
if (i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}while (i < j && i < n && j >= 0);
}
|
0c355ca1624968ea64f773e0b46bbacf9b4e408a
|
96d9abc30c17993b565637d47e30197b9b7d3b5a
|
/joins/test/algorithms/nop_join_test.cpp
|
b9d1cc11c86344ba4d67cd585fe1ecdcc2b36e86
|
[
"MIT"
] |
permissive
|
wagjamin/HashJoins
|
ff9b0afd96b5d5955d95d50f31f76d2e51662d14
|
143ef7a90d8226ce26b8a5e2ec1be33af0f00d74
|
refs/heads/master
| 2022-02-28T13:37:06.230784
| 2022-02-20T16:45:25
| 2022-02-20T16:45:25
| 148,012,777
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,993
|
cpp
|
nop_join_test.cpp
|
//
// Benjamin Wagner 2018
//
#include "generators/uniform_generator.h"
#include "algorithms/nop_join.h"
#include "gtest/gtest.h"
#include <iostream>
#include <chrono>
using namespace generators; // NOLINT
using namespace algorithms; // NOLINT
// Ensure proper creation of object and no return before execution
TEST(NopTest, CreationTester) {
uniform_generator uni(0, 10000, 1000);
uni.build();
auto left = uni.get_vec_copy();
uni.build();
auto right = uni.get_vec_copy();
nop_join join(left.data(), right.data(), 1000, 1000, 1.5);
ASSERT_ANY_THROW(join.get());
}
// No result should be returned
TEST(NopTest, NoResTester) {
uint64_t min = 0;
uint64_t max = 10000;
uint64_t count = 1000;
uniform_generator gen(min, max, count);
gen.build();
auto left = gen.get_vec_copy();
min = 20000;
max = 30000;
gen = uniform_generator(min, max, count);
gen.build();
auto right = gen.get_vec_copy();
nop_join join(left.data(), right.data(), count, count, 1.5);
join.execute();
ASSERT_EQ(join.get().size(), 0);
}
// This is a simple cross product
TEST(NopTest, CrossTester1) {
uint64_t count = 1000;
uniform_generator uni(1, 1, count);
uni.build();
auto left = uni.get_vec_copy();
uni = uniform_generator(1,1,1);
uni.build();
auto right = uni.get_vec_copy();
nop_join join(left.data(), right.data(), count, 1, 1.5);
join.execute();
ASSERT_EQ(join.get().size(), count);
}
// This is a more complicated cross product
TEST(NopTest, CrossTester2) {
uint64_t count = 1000;
uniform_generator uni(1, 1, count);
uni.build();
auto left = uni.get_vec_copy();
uni.build();
auto right = uni.get_vec_copy();
nop_join join(left.data(), right.data(), count, count, 1.5);
join.execute();
ASSERT_EQ(join.get().size(), count*count);
}
// Statistical test, usually should not fail
TEST(NopTest, StatisticalTester){
uint64_t count = static_cast<uint64_t>(1) << static_cast<uint64_t>(17);
uint64_t min = 1;
uint64_t max = static_cast<uint64_t>(1) << static_cast<uint64_t>(12);
uniform_generator gen(min, max, count);
gen.build();
auto left = gen.get_vec_copy();
gen.build();
auto right = gen.get_vec_copy();
nop_join join(left.data(), right.data(), count, count);
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
join.execute();
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>( t2 - t1 ).count();
std::cout << "ST NOP Join Time: " << duration << " milliseconds.\n";
// Expected overall amount of join partners
auto expected = static_cast<uint64_t>(max * (static_cast<double>(count)/max) * static_cast<double>((count))/max);
ASSERT_LE(0.95 * expected, join.get().size());
ASSERT_GE(1.05 * expected, join.get().size());
}
|
3f59a0192f977f0c9e45407f5be9e9d6b906a5a5
|
1bbd1440effb236b247e6f0e710afaf924a324e2
|
/LambdaExpression/paramter.cpp
|
8768b2d511d4d261a6dadf8a4e6d1ac4ed07909b
|
[] |
no_license
|
theArcticOcean/CLib
|
25fbd159936913fd7f0ecdcb7737baf8b20d4459
|
9384eff20febd718f903cc1a86cad730043ce639
|
refs/heads/master
| 2023-06-24T06:19:37.560274
| 2023-06-15T01:22:07
| 2023-06-15T01:22:22
| 111,999,296
| 24
| 26
| null | 2022-01-17T03:11:49
| 2017-11-25T11:44:19
|
C++
|
UTF-8
|
C++
| false
| false
| 624
|
cpp
|
paramter.cpp
|
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
/*
Lambda Expression's Paramters:
1. 参数列表中不能有默认参数
2. 不支持可变参数
3. 所有参数必须有参数名
*/
int main()
{
vector<int> vec;
for( int i=0; i<10; ++i )
{
vec.push_back( i+1 );
}
auto fun = [](vector<int> &V) {
for( int i=0; i<V.size(); ++i )
{
V[i] += 10;
cout << V[i] << " ";
}
cout << endl;
};
fun( vec );
for( int i=0; i<vec.size(); ++i )
{
cout << vec[i] << " ";
}
cout << endl;
return 0;
}
/*
out:
11 12 13 14 15 16 17 18 19 20
11 12 13 14 15 16 17 18 19 20
*/
|
aafc5679f828cb47c2a5ca933cd61f698bab169c
|
c42ecbc5bb6bc33acc9833b738996e537d092041
|
/pothos-serialization/include/Pothos/serialization/impl/preprocessor/arithmetic/dec.hpp
|
5b3438fb657d504436686870c76d7133f6432f06
|
[
"BSL-1.0"
] |
permissive
|
lrmodesgh/pothos
|
abd652bc9b880139fa9fb2016b88cb21e0be1f0a
|
542c6cd19e1aa2ee1fda47fbc131431ed351ae31
|
refs/heads/master
| 2020-12-26T02:10:22.037019
| 2015-07-13T08:28:57
| 2015-07-13T08:28:57
| 39,064,513
| 1
| 0
| null | 2015-07-14T08:56:33
| 2015-07-14T08:56:33
| null |
UTF-8
|
C++
| false
| false
| 8,871
|
hpp
|
dec.hpp
|
# /* Copyright (C) 2001
# * Housemarque Oy
# * http://www.housemarque.com
# *
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# */
#
# /* Revised by Paul Mensonides (2002) */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef POTHOS_PREPROCESSOR_ARITHMETIC_DEC_HPP
# define POTHOS_PREPROCESSOR_ARITHMETIC_DEC_HPP
#
# include <Pothos/serialization/impl/preprocessor/config/config.hpp>
#
# /* POTHOS_PP_DEC */
#
# if ~POTHOS_PP_CONFIG_FLAGS() & POTHOS_PP_CONFIG_MWCC()
# define POTHOS_PP_DEC(x) POTHOS_PP_DEC_I(x)
# else
# define POTHOS_PP_DEC(x) POTHOS_PP_DEC_OO((x))
# define POTHOS_PP_DEC_OO(par) POTHOS_PP_DEC_I ## par
# endif
#
# define POTHOS_PP_DEC_I(x) POTHOS_PP_DEC_ ## x
#
# define POTHOS_PP_DEC_0 0
# define POTHOS_PP_DEC_1 0
# define POTHOS_PP_DEC_2 1
# define POTHOS_PP_DEC_3 2
# define POTHOS_PP_DEC_4 3
# define POTHOS_PP_DEC_5 4
# define POTHOS_PP_DEC_6 5
# define POTHOS_PP_DEC_7 6
# define POTHOS_PP_DEC_8 7
# define POTHOS_PP_DEC_9 8
# define POTHOS_PP_DEC_10 9
# define POTHOS_PP_DEC_11 10
# define POTHOS_PP_DEC_12 11
# define POTHOS_PP_DEC_13 12
# define POTHOS_PP_DEC_14 13
# define POTHOS_PP_DEC_15 14
# define POTHOS_PP_DEC_16 15
# define POTHOS_PP_DEC_17 16
# define POTHOS_PP_DEC_18 17
# define POTHOS_PP_DEC_19 18
# define POTHOS_PP_DEC_20 19
# define POTHOS_PP_DEC_21 20
# define POTHOS_PP_DEC_22 21
# define POTHOS_PP_DEC_23 22
# define POTHOS_PP_DEC_24 23
# define POTHOS_PP_DEC_25 24
# define POTHOS_PP_DEC_26 25
# define POTHOS_PP_DEC_27 26
# define POTHOS_PP_DEC_28 27
# define POTHOS_PP_DEC_29 28
# define POTHOS_PP_DEC_30 29
# define POTHOS_PP_DEC_31 30
# define POTHOS_PP_DEC_32 31
# define POTHOS_PP_DEC_33 32
# define POTHOS_PP_DEC_34 33
# define POTHOS_PP_DEC_35 34
# define POTHOS_PP_DEC_36 35
# define POTHOS_PP_DEC_37 36
# define POTHOS_PP_DEC_38 37
# define POTHOS_PP_DEC_39 38
# define POTHOS_PP_DEC_40 39
# define POTHOS_PP_DEC_41 40
# define POTHOS_PP_DEC_42 41
# define POTHOS_PP_DEC_43 42
# define POTHOS_PP_DEC_44 43
# define POTHOS_PP_DEC_45 44
# define POTHOS_PP_DEC_46 45
# define POTHOS_PP_DEC_47 46
# define POTHOS_PP_DEC_48 47
# define POTHOS_PP_DEC_49 48
# define POTHOS_PP_DEC_50 49
# define POTHOS_PP_DEC_51 50
# define POTHOS_PP_DEC_52 51
# define POTHOS_PP_DEC_53 52
# define POTHOS_PP_DEC_54 53
# define POTHOS_PP_DEC_55 54
# define POTHOS_PP_DEC_56 55
# define POTHOS_PP_DEC_57 56
# define POTHOS_PP_DEC_58 57
# define POTHOS_PP_DEC_59 58
# define POTHOS_PP_DEC_60 59
# define POTHOS_PP_DEC_61 60
# define POTHOS_PP_DEC_62 61
# define POTHOS_PP_DEC_63 62
# define POTHOS_PP_DEC_64 63
# define POTHOS_PP_DEC_65 64
# define POTHOS_PP_DEC_66 65
# define POTHOS_PP_DEC_67 66
# define POTHOS_PP_DEC_68 67
# define POTHOS_PP_DEC_69 68
# define POTHOS_PP_DEC_70 69
# define POTHOS_PP_DEC_71 70
# define POTHOS_PP_DEC_72 71
# define POTHOS_PP_DEC_73 72
# define POTHOS_PP_DEC_74 73
# define POTHOS_PP_DEC_75 74
# define POTHOS_PP_DEC_76 75
# define POTHOS_PP_DEC_77 76
# define POTHOS_PP_DEC_78 77
# define POTHOS_PP_DEC_79 78
# define POTHOS_PP_DEC_80 79
# define POTHOS_PP_DEC_81 80
# define POTHOS_PP_DEC_82 81
# define POTHOS_PP_DEC_83 82
# define POTHOS_PP_DEC_84 83
# define POTHOS_PP_DEC_85 84
# define POTHOS_PP_DEC_86 85
# define POTHOS_PP_DEC_87 86
# define POTHOS_PP_DEC_88 87
# define POTHOS_PP_DEC_89 88
# define POTHOS_PP_DEC_90 89
# define POTHOS_PP_DEC_91 90
# define POTHOS_PP_DEC_92 91
# define POTHOS_PP_DEC_93 92
# define POTHOS_PP_DEC_94 93
# define POTHOS_PP_DEC_95 94
# define POTHOS_PP_DEC_96 95
# define POTHOS_PP_DEC_97 96
# define POTHOS_PP_DEC_98 97
# define POTHOS_PP_DEC_99 98
# define POTHOS_PP_DEC_100 99
# define POTHOS_PP_DEC_101 100
# define POTHOS_PP_DEC_102 101
# define POTHOS_PP_DEC_103 102
# define POTHOS_PP_DEC_104 103
# define POTHOS_PP_DEC_105 104
# define POTHOS_PP_DEC_106 105
# define POTHOS_PP_DEC_107 106
# define POTHOS_PP_DEC_108 107
# define POTHOS_PP_DEC_109 108
# define POTHOS_PP_DEC_110 109
# define POTHOS_PP_DEC_111 110
# define POTHOS_PP_DEC_112 111
# define POTHOS_PP_DEC_113 112
# define POTHOS_PP_DEC_114 113
# define POTHOS_PP_DEC_115 114
# define POTHOS_PP_DEC_116 115
# define POTHOS_PP_DEC_117 116
# define POTHOS_PP_DEC_118 117
# define POTHOS_PP_DEC_119 118
# define POTHOS_PP_DEC_120 119
# define POTHOS_PP_DEC_121 120
# define POTHOS_PP_DEC_122 121
# define POTHOS_PP_DEC_123 122
# define POTHOS_PP_DEC_124 123
# define POTHOS_PP_DEC_125 124
# define POTHOS_PP_DEC_126 125
# define POTHOS_PP_DEC_127 126
# define POTHOS_PP_DEC_128 127
# define POTHOS_PP_DEC_129 128
# define POTHOS_PP_DEC_130 129
# define POTHOS_PP_DEC_131 130
# define POTHOS_PP_DEC_132 131
# define POTHOS_PP_DEC_133 132
# define POTHOS_PP_DEC_134 133
# define POTHOS_PP_DEC_135 134
# define POTHOS_PP_DEC_136 135
# define POTHOS_PP_DEC_137 136
# define POTHOS_PP_DEC_138 137
# define POTHOS_PP_DEC_139 138
# define POTHOS_PP_DEC_140 139
# define POTHOS_PP_DEC_141 140
# define POTHOS_PP_DEC_142 141
# define POTHOS_PP_DEC_143 142
# define POTHOS_PP_DEC_144 143
# define POTHOS_PP_DEC_145 144
# define POTHOS_PP_DEC_146 145
# define POTHOS_PP_DEC_147 146
# define POTHOS_PP_DEC_148 147
# define POTHOS_PP_DEC_149 148
# define POTHOS_PP_DEC_150 149
# define POTHOS_PP_DEC_151 150
# define POTHOS_PP_DEC_152 151
# define POTHOS_PP_DEC_153 152
# define POTHOS_PP_DEC_154 153
# define POTHOS_PP_DEC_155 154
# define POTHOS_PP_DEC_156 155
# define POTHOS_PP_DEC_157 156
# define POTHOS_PP_DEC_158 157
# define POTHOS_PP_DEC_159 158
# define POTHOS_PP_DEC_160 159
# define POTHOS_PP_DEC_161 160
# define POTHOS_PP_DEC_162 161
# define POTHOS_PP_DEC_163 162
# define POTHOS_PP_DEC_164 163
# define POTHOS_PP_DEC_165 164
# define POTHOS_PP_DEC_166 165
# define POTHOS_PP_DEC_167 166
# define POTHOS_PP_DEC_168 167
# define POTHOS_PP_DEC_169 168
# define POTHOS_PP_DEC_170 169
# define POTHOS_PP_DEC_171 170
# define POTHOS_PP_DEC_172 171
# define POTHOS_PP_DEC_173 172
# define POTHOS_PP_DEC_174 173
# define POTHOS_PP_DEC_175 174
# define POTHOS_PP_DEC_176 175
# define POTHOS_PP_DEC_177 176
# define POTHOS_PP_DEC_178 177
# define POTHOS_PP_DEC_179 178
# define POTHOS_PP_DEC_180 179
# define POTHOS_PP_DEC_181 180
# define POTHOS_PP_DEC_182 181
# define POTHOS_PP_DEC_183 182
# define POTHOS_PP_DEC_184 183
# define POTHOS_PP_DEC_185 184
# define POTHOS_PP_DEC_186 185
# define POTHOS_PP_DEC_187 186
# define POTHOS_PP_DEC_188 187
# define POTHOS_PP_DEC_189 188
# define POTHOS_PP_DEC_190 189
# define POTHOS_PP_DEC_191 190
# define POTHOS_PP_DEC_192 191
# define POTHOS_PP_DEC_193 192
# define POTHOS_PP_DEC_194 193
# define POTHOS_PP_DEC_195 194
# define POTHOS_PP_DEC_196 195
# define POTHOS_PP_DEC_197 196
# define POTHOS_PP_DEC_198 197
# define POTHOS_PP_DEC_199 198
# define POTHOS_PP_DEC_200 199
# define POTHOS_PP_DEC_201 200
# define POTHOS_PP_DEC_202 201
# define POTHOS_PP_DEC_203 202
# define POTHOS_PP_DEC_204 203
# define POTHOS_PP_DEC_205 204
# define POTHOS_PP_DEC_206 205
# define POTHOS_PP_DEC_207 206
# define POTHOS_PP_DEC_208 207
# define POTHOS_PP_DEC_209 208
# define POTHOS_PP_DEC_210 209
# define POTHOS_PP_DEC_211 210
# define POTHOS_PP_DEC_212 211
# define POTHOS_PP_DEC_213 212
# define POTHOS_PP_DEC_214 213
# define POTHOS_PP_DEC_215 214
# define POTHOS_PP_DEC_216 215
# define POTHOS_PP_DEC_217 216
# define POTHOS_PP_DEC_218 217
# define POTHOS_PP_DEC_219 218
# define POTHOS_PP_DEC_220 219
# define POTHOS_PP_DEC_221 220
# define POTHOS_PP_DEC_222 221
# define POTHOS_PP_DEC_223 222
# define POTHOS_PP_DEC_224 223
# define POTHOS_PP_DEC_225 224
# define POTHOS_PP_DEC_226 225
# define POTHOS_PP_DEC_227 226
# define POTHOS_PP_DEC_228 227
# define POTHOS_PP_DEC_229 228
# define POTHOS_PP_DEC_230 229
# define POTHOS_PP_DEC_231 230
# define POTHOS_PP_DEC_232 231
# define POTHOS_PP_DEC_233 232
# define POTHOS_PP_DEC_234 233
# define POTHOS_PP_DEC_235 234
# define POTHOS_PP_DEC_236 235
# define POTHOS_PP_DEC_237 236
# define POTHOS_PP_DEC_238 237
# define POTHOS_PP_DEC_239 238
# define POTHOS_PP_DEC_240 239
# define POTHOS_PP_DEC_241 240
# define POTHOS_PP_DEC_242 241
# define POTHOS_PP_DEC_243 242
# define POTHOS_PP_DEC_244 243
# define POTHOS_PP_DEC_245 244
# define POTHOS_PP_DEC_246 245
# define POTHOS_PP_DEC_247 246
# define POTHOS_PP_DEC_248 247
# define POTHOS_PP_DEC_249 248
# define POTHOS_PP_DEC_250 249
# define POTHOS_PP_DEC_251 250
# define POTHOS_PP_DEC_252 251
# define POTHOS_PP_DEC_253 252
# define POTHOS_PP_DEC_254 253
# define POTHOS_PP_DEC_255 254
# define POTHOS_PP_DEC_256 255
#
# endif
|
5c715b33ff5770aff1dcdd68b04ba9b6f2d798d8
|
2ed37eecee1472443d8b3ca6102f2b9e1bf63876
|
/leetcode/79.cpp
|
ddb6d2a5baa91811159fc0525b9c9a629ebb1725
|
[] |
no_license
|
chloejiwon/algorithm
|
441d9d3b007acb366370c1f5b59c73a804423ffc
|
2c6380959f2c998adf811940cff16099a669e1fd
|
refs/heads/master
| 2022-05-14T19:05:03.331467
| 2022-04-07T01:13:30
| 2022-04-07T01:13:30
| 114,375,453
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,002
|
cpp
|
79.cpp
|
// 이것은...디버깅의승리...?;;;
// 79. Minimum Window Substring
// Solution 1 - Sliding window --- Beat 20%
// need to work on simplifying methods..
// if s[start] is not substr in T, start++;
// if s[start~end] contains all chars in T
// if start-end+1 < min_len, min_len = start-end+1
// if not, start ++;
// if not, start ++;
class Solution {
public:
string minWindow(string s, string t) {
int window_end = 0;
int min_size = t.length();
if (min_size == 0)
return "";
vector<int> a(58);
for(int k=0; k<min_size; k++){
a[t[k]-65]++;
}
vector<int> b(58);
b[s[0]-65]++;
int i=0; int j=0; int minLen = 999999;
int start = 0; int end = 0;
int total = s.length();
while(j < total && i < total)
{
if(a[s[i]-65] == 0 )
{
b[s[i]-65]--;
i++;
continue;
}
if(a[s[j] - 65] > 0 )
{
bool everychar = true;
for(int k=0; k<58; k++)
{
if(a[k] >0 && b[k] < a[k])
{
everychar = false;
break;
}
}
if(everychar)
{
if(minLen > j - i +1)
{
minLen = j-i+1;
start = i; end = j;
}
b[s[i]-65]--;
i++;
}
else
{
j++;
if(j < total) b[s[j]-65]++;
}
}
else
{
j++;
if(j < total) b[s[j]-65]++;
}
}
if(minLen < 999999)
return s.substr(start,minLen);
else
return "";
}
};
|
6b5a616637a6da54765c33a6ad52c5a8352d66f3
|
236f41f385d697957dd2301e46fa1f4bdb926cf6
|
/URI/2871-TIMMY.cpp
|
19a190e46d5c03f1137540f642105c9ab1121df0
|
[] |
no_license
|
LeonardoFassini/Competitive-Programming
|
a2bcc9ae6aa015e70c4d5cae6091e3133765a69c
|
06bba6b4c2d10abc58e30f4ff8ea4d9ac1f535fc
|
refs/heads/master
| 2020-04-05T22:32:57.288103
| 2018-11-12T18:52:21
| 2018-11-12T18:52:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 371
|
cpp
|
2871-TIMMY.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main(void){
int n, m, num, count = 0;
while(cin >> n >> m){
count = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> num;
count += num;
}
}
int saca = count/60;
int litro = count%60;
cout << saca << " saca(s) e " << litro << " litro(s)\n";
}
return 0;
}
|
68fdf8770c044a7ce7a52531d0f5922842872d25
|
b76b2becfd8ac9feb76f014487f674dbb0110c8f
|
/matrix_impl/include/matrix_core/Matrix.h
|
bcbc87c0290a0d1ecb4747e329c0594edb55dd5c
|
[
"BSD-3-Clause"
] |
permissive
|
cyang019/matrix
|
2d141ad19d9b5b47f534534c7778f44bed82f746
|
aa303e870e7a0ba0048839589e1676861c78bcc0
|
refs/heads/main
| 2023-05-31T06:44:15.019838
| 2021-06-08T03:54:47
| 2021-06-08T03:54:47
| 366,855,653
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,363
|
h
|
Matrix.h
|
#ifndef _MATRIX_MATRIX_H
#define _MATRIX_MATRIX_H
#include <memory> // unique_ptr
#include <utility>
#include <exception>
#include <type_traits> // enable_if_t
#include <initializer_list>
#include <complex>
#include <random>
#include <cassert>
#include <cmath> // abs, max, min
#include <vector>
#include <unordered_set>
#include <algorithm> // sort
#include <functional> // less
#include <limits>
#include <iostream>
#include <sstream>
#include <cstdint> // uint32_t
#include <cstdlib> // rand, srand
#include "matrix_core/common.h"
#include "matrix_core/errors.h"
#include "blas_wrapper/cblas_functions.h"
namespace matrix {
inline namespace v1 {
template<typename T>
class Matrix;
//basic operations
template<typename T>
std::ostream& operator<<(std::ostream &os, const Matrix<T> &m);
template<typename T>
bool operator==(const Matrix<T> &, const Matrix<T> &);
template<typename T>
bool operator!=(const Matrix<T> &, const Matrix<T> &);
bool allclose(const Matrix<double> &, const Matrix<double> &,
double atol, double rtol=1.0e-5);
bool allclose(const Matrix<cxdbl> &, const Matrix<cxdbl> &,
double atol, double rtol=1.0e-5);
template<typename T>
Matrix<T> operator+(const Matrix<T> &, const Matrix<T> &);
template<typename T>
Matrix<T> operator+(const Matrix<T> &, const T &);
template<typename T>
Matrix<T> operator+(const T&, const Matrix<T> &);
template<typename T>
Matrix<T> operator-(const Matrix<T> &, const Matrix<T> &);
template<typename T>
Matrix<T> operator-(const Matrix<T> &, const T &);
template<typename T>
Matrix<T> operator-(const T&, const Matrix<T> &);
template<typename T>
Matrix<T> operator-(const Matrix<T> &);
template<typename T>
Matrix<T> operator*(const Matrix<T> &, const Matrix<T> &);
template<typename T>
Matrix<T> operator*(const Matrix<T> &, const T &);
template<typename T>
Matrix<T> operator*(const T&, const Matrix<T> &);
template<typename T>
Matrix<T> operator/(const Matrix<T> &, const T &);
/// @param mat: matrix
/// @param c: 'C' or 'R', column or row
template<typename T>
Matrix<T> flatten(const Matrix<T> &mat, char c);
// -------------------------
/// advanced operations
// -------------------------
template<typename T>
Matrix<T> abs(const Matrix<T> &);
template<typename T>
Matrix<T> exp(const Matrix<T> &);
/// solves for A * X = B
/// A is a square matrix
/// A & B will be destroyed after this function
template<typename T>
Matrix<T> linearSolveSq(Matrix<T> &, Matrix<T> &);
template<EigenMethod em=EigenMethod::zheevd>
std::tuple<Matrix<double>, Matrix<cxdbl>> eigenSys(const Matrix<cxdbl> &);
template<EigenMethod em=EigenMethod::zheevd>
Matrix<double> eigenVal(const Matrix<cxdbl> &);
template<typename T>
Matrix<T> kroneckerProduct(const Matrix<T> &, const Matrix<T> &);
template<typename T>
Matrix<T> kroneckerProduct(const std::vector<Matrix<T>> &);
/// trace of A^T. B or A^H . B
/// based on xdot & xdotc
template<typename T>
T projection(const Matrix<T> &, const Matrix<T> &);
template<typename T>
T projectionNorm(const Matrix<T> &, const Matrix<T> &);
template<typename T>
T trace(const Matrix<T> &);
template<typename T>
Matrix<T> pow(const Matrix<T> &, std::uint64_t);
// the maximum absolute column sum of a matrix
template<typename T>
double norm1(const Matrix<T> &);
// @brief: column major matrix type.
template<typename T>
class Matrix{
public:
friend std::ostream& operator<<<T>(std::ostream &os, const Matrix<T> &m);
friend bool operator==<T>(const Matrix<T> &, const Matrix<T> &);
friend bool operator!=<T>(const Matrix<T> &, const Matrix<T> &);
friend Matrix<T> operator+<T>(const Matrix<T> &t_m1, const Matrix<T> &t_m2);
friend Matrix<T> operator+<T>(const T &t_v1, const Matrix<T> &t_m2);
friend Matrix<T> operator+<T>(const Matrix<T> &t_m1, const T &t_v2);
friend Matrix<T> operator-<T>(const Matrix<T> &t_m1, const Matrix<T> &t_m2);
friend Matrix<T> operator-<T>(const T &t_v1, const Matrix<T> &t_m2);
friend Matrix<T> operator-<T>(const Matrix<T> &t_m1, const T &t_v2);
friend Matrix<T> operator*<T>(const Matrix<T> &t_m1, const Matrix<T> &t_m2);
friend Matrix<T> operator*<T>(const T &t_v1, const Matrix<T> &t_m2);
friend Matrix<T> operator*<T>(const Matrix<T> &t_m1, const T &t_v2);
friend Matrix<T> operator/<T>(const Matrix<T> &t_m1, const T &t_v2);
friend Matrix<T> flatten<T>(const Matrix<T> &mat, char c);
Matrix();
Matrix(size_t, size_t);
Matrix(size_t); ///< square matrix
Matrix(std::initializer_list<std::initializer_list<T>> il);
template<typename U=T,
std::enable_if_t<is_complex<U>::value, int> = 0>
Matrix(std::initializer_list<std::initializer_list<double>> il);
Matrix(size_t n_total, const T *raw_data);
// copy ctor
Matrix(const Matrix<T> &);
template<typename U = T,
std::enable_if_t<is_complex<U>::value, int> = 0>
Matrix(const Matrix<double> &);
// move ctor
Matrix(Matrix<T> &&) noexcept;
// copy ctor
Matrix<T>& operator=(const Matrix<T> &);
// move ctor
Matrix<T>& operator=(Matrix<T> &&) noexcept;
~Matrix();
Matrix<T>& swapCols(size_t, size_t);
Matrix<T>& swapRows(size_t, size_t);
Matrix<T>& operator+=(const Matrix<T> &);
Matrix<T>& operator+=(const T &);
Matrix<T>& operator-=(const Matrix<T> &);
Matrix<T>& operator-=(const T &);
Matrix<T>& operator*=(const T &);
Matrix<T>& operator*=(const Matrix<T> &);
Matrix<T>& operator/=(const T &);
Matrix<T>& setZero();
Matrix<T>& setOne();
Matrix<T>& setRandom();
Matrix<T>& row(size_t);
Matrix<T>& col(size_t);
T& operator()(size_t, size_t) const;
T& operator()(size_t, size_t);
// Transpose
Matrix<T> t() const;
Matrix<T>& tInplace();
// Adjoint
Matrix<T> adjoint() const;
Matrix<T>& adjointInplace();
// Inverse
Matrix<T> inverse() const;
Matrix<T>& inverseInplace();
// Print to format that is readily copied to python
void print() const;
T* data();
const T* data() const;
size_t nrows() const;
size_t ncols() const;
size_t nelements() const { return m_nrows * m_ncols; }
T trace() const;
std::tuple<size_t, size_t> shape() const;
private:
size_t m_nrows;
size_t m_ncols;
std::unique_ptr<T[]> m_data; ///< serialized matrix
};
template<typename T>
Matrix<T> diagonal(std::initializer_list<T> vals);
template<typename T,
std::enable_if_t<is_complex<T>::value, int> = 0>
Matrix<T> diagonal(std::initializer_list<double> vals);
template<typename T>
Matrix<T> identity(size_t n1, size_t n2);
template<typename T>
Matrix<T> identity(size_t n);
template<typename T>
Matrix<T> zeros(size_t nrows, size_t ncols);
template<typename T>
Matrix<T> ones(size_t nrows, size_t ncols);
/// for double mat, either 1 or -1
/// for complex<double> mat, a_ij/|a_ij|, sign(0) = 1
template<typename T>
Matrix<T> sign(const Matrix<T> &);
}
}
#include "matrix_core/MatrixImpl.hpp"
#include "matrix_core/OperatorsImpl.hpp"
#include "matrix_core/AdvancedFunctionsImpl.hpp"
#include "matrix_core/MatrixExponential.hpp"
#endif
|
3349a27c20199158a0564926742faf62ed028e48
|
f8083f1ac05ecb07b93c58af98eaf78e8eab9367
|
/samples/0_1_MST.cpp
|
b9019f1eacaf89ae8c1007eecf65831e4a38b37c
|
[] |
no_license
|
itohdak/AtCoder
|
4f42ccc7b2b7f71d0d51069bd86503ee0f4b3dbf
|
9ee89bac3ced919b94096ffd7b644d3716569762
|
refs/heads/master
| 2021-06-24T14:42:54.529474
| 2020-10-16T18:41:27
| 2020-10-16T18:41:27
| 134,136,836
| 2
| 1
| null | 2020-02-07T12:45:10
| 2018-05-20T09:26:13
|
C++
|
UTF-8
|
C++
| false
| false
| 1,075
|
cpp
|
0_1_MST.cpp
|
#include "header.hpp"
set<int> se;
vector<set<int> > G;
void dfs(int v) {
se.erase(v);
int tmp = 0;
while(!se.empty()) {
auto itr = se.upper_bound(tmp);
if(itr == se.end()) break;
tmp = *itr;
if(!G[v].count(tmp)) {
se.erase(tmp);
dfs(tmp);
}
}
}
int main() {
int N, M;
cin >> N >> M;
rep(i, N) se.insert(i);
G = vector<set<int> >(N);
rep(i, M) {
int a, b;
cin >> a >> b;
a--, b--;
G[a].insert(b);
G[b].insert(a);
}
int comp = 0;
rep(i, N) {
if(se.count(i)) {
comp++;
dfs(i);
}
}
cout << comp-1 << endl;
return 0;
}
// time complexity: O(N + M)
// https://codeforces.com/contest/920/problem/E
// 繋がっていない頂点ペアのリストが渡されて,逆に(繋がっている)連結グラフの個数を求める問題
// https://codeforces.com/contest/1243/problem/D
// コスト1で繋がっている頂点ペアのリストが渡されて(それ以外のペアもコスト0の辺で結ばれている),最小全域木のコストを求める問題
|
9fa95fac7c056517b17bc5cf6d48afd3b4c5c629
|
cb6092363d06df31d11cfc69fe073c0d5a1b4a89
|
/include/svip/svip_interface.h
|
d1fd66dcf6e4fd758c4ee78f8e1ea936d08f2c99
|
[] |
no_license
|
ljh9999/DetTrkPosRec
|
07f2fd91f2afe575c2475e0e2bb64c3e8e9f4bb9
|
f5522243927780ffc41524708c8771e2f9248b7f
|
refs/heads/main
| 2023-01-28T00:37:13.532222
| 2020-12-04T14:15:49
| 2020-12-04T14:15:49
| 318,535,466
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,738
|
h
|
svip_interface.h
|
//
// Created by ljh on 2020/10/23.
//
#ifndef FINAL_YOLOV5_SVIP_INTERFACE_H
#define FINAL_YOLOV5_SVIP_INTERFACE_H
#pragma once
#include <fstream>
#include "track.h"
#include <detect/detect.h>
#include "ActRecognize.h"
#include <detect/crop_util.h>
#include "md5/md5.h"
#include "svipAISDK_V3.h"
#include "opencv2/opencv.hpp"
#include "PoseEst.h"
#include <torch/script.h> // One-stop header.
#include <vector>
#include <iostream>
#include <memory>
#include <opencv2/opencv.hpp>
//#include "skeleton_seq_preprocess.h"
#include <fstream>
using namespace std;
using namespace cv;
using namespace std;
using namespace torch;
class BRIDGE
{
public:
long long mytime = 0;
ApplicationType applicationType{};
CameraType cameraType{};
svip_ai_result_cb mycallback{};
svip_ai_error_cb svip_ai_error_cb_ = nullptr;
void * svip_ai_error_cb_user_ = nullptr;
void *myuser = nullptr;
void *_params = nullptr;
DETECT *detector = nullptr;
TRACK *tracker = nullptr;
PoseEst *poseEst = nullptr;
int oriWidth, oriHeight;
// int setFrame(AstAIFrame *frameInfo);
//
// int checkMD5(FrameInfo *frameInfo, const char *md5_);
//
// int checkFMT(FrameInfo *frameInfo) const;
int setFrame(AstAIFrame *frameInfo);
int checkMD5(FrameInfo *frameInfo, const char *md5_);
int checkFMT(FrameInfo *frameInfo) const;
cv::Mat preprocessImg(cv::Mat &src, FrameInfo *frameInfo);
int runFrame(const char *md5_, FrameInfo *frame_info);
int parseDetRes(vector<DETECT::DET_BOX> &srcBoxes, vector<DETECT::DET_BOX> &dstBoxes) const;
int parse(FrameInfo *frameInfo);
int Deinit() const;
// 这个vector保存着一个视频帧里面的vector,如(50, 17, 2)
vector<vector<vector<int>>> _kps_seq;
// 这个vector保存着每一张图片的坐标或者是别的hourglass的输出,如(17, 2)
vector<vector<int>> _kps;
// 这个vector用于动态load,当图片解码之后,送入这个vector,然后deal_frame还要用到这个向量,用来得到坐标呢
vector<Mat> _pic_candidate;
//// block_left和block_right组成了所有的内存块
vector<vector<pair<int, Mat>>> block_left;
vector<vector<pair<int, Mat>>> block_right;
//// 同一个id下的block
vector<pair<int, Mat>> prev_block;
vector<pair<int, Mat>> curr_block;
int _index = 999;
vector<int> pre_IDs;
private:
float _rw, _rh;
int _re_w, _re_h, _re_x, _re_y;
// 将pose提取出来的关节点坐标,送入该vector
vector<float> coordinate_xy;
// std::unique_ptr<tflite::FlatBufferModel> model;
MD5_CTX md5{};
};
//class ACT_BRIDGE {
//public:
// ActRecognizer *actRecognizer = nullptr;
//
//
//};
//
//class DYNAMIC {
// int dynamic_save(vector<int> & pre_IDs, pair<int, Mat> & curr_pair);
// int dynamic_load(vector<vector<pair<int, Mat>>> block_left);
//
//// 这个vector保存着一个视频帧里面的vector,如(50, 17, 2)
// vector<vector<vector<int>>> _kps_seq;
//// 这个vector保存着每一张图片的坐标或者是别的hourglass的输出,如(17, 2)
// vector<vector<int>> _kps;
//// 这个vector用于动态load,当图片解码之后,送入这个vector,然后deal_frame还要用到这个向量,用来得到坐标呢
// vector<Mat> _pic_candidate;
//
////// block_left和block_right组成了所有的内存块
// vector<vector<pair<int, Mat>>> block_left;
// vector<vector<pair<int, Mat>>> block_right;
//
////// 同一个id下的block
// vector<pair<int, Mat>> prev_block;
// vector<pair<int, Mat>> curr_block;
//
// int _index = 999;
//
// vector<int> pre_IDs;
//};
#endif //FINAL_YOLOV5_SVIP_INTERFACE_H
|
4b16ab8d6918a9844e382196e9b5795f9fe4f2c1
|
70418d8faa76b41715c707c54a8b0cddfb393fb3
|
/758.cpp
|
69daf0de82b2fc2e9045acc58effb069dc7079ac
|
[] |
no_license
|
evandrix/UVa
|
ca79c25c8bf28e9e05cae8414f52236dc5ac1c68
|
17a902ece2457c8cb0ee70c320bf0583c0f9a4ce
|
refs/heads/master
| 2021-06-05T01:44:17.908960
| 2017-10-22T18:59:42
| 2017-10-22T18:59:42
| 107,893,680
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,957
|
cpp
|
758.cpp
|
#include <bits/stdc++.h>
using namespace std;
int wayx[4] = {0, 1, 0, -1};
int wayy[4] = {1, 0, -1, 0};
char map_[15][20];
int cnum, width, used[15][20], height[20];
int valid(int x, int y)
{
return y >= 0 && y < width && x >= 0 && x < height[y];
}
void counts(int x, int y, char c)
{
int i, tx, ty;
cnum++;
used[x][y] = 1;
for (i = 0; i < 4; i++)
{
tx = x + wayx[i];
ty = y + wayy[i];
if (valid(tx, ty) && !used[tx][ty] && map_[tx][ty] == c)
{
used[tx][ty] = 1;
counts(tx, ty, c);
}
}
}
void floodfill(int x, int y, char c)
{
int i, tx, ty;
map_[x][y] = 0;
for (i = 0; i < 4; i++)
{
tx = x + wayx[i];
ty = y + wayy[i];
if (valid(tx, ty) && map_[tx][ty] == c)
{
floodfill(tx, ty, c);
}
}
}
void adjust()
{
int i, j, k;
for (j = 0; j < 15; j++)
{
if (height[j])
{
for (i = 0, k = 0; i < height[j]; i++)
{
if (map_[i][j])
{
map_[k++][j] = map_[i][j];
}
}
height[j] = k;
}
else
{
break;
}
}
for (j = 0, k = 0; j < width; j++)
{
if (height[j])
{
for (i = 0; i < height[j]; i++)
{
map_[i][k] = map_[i][j];
}
height[k++] = height[j];
}
}
width = k;
/*for(; k<15; k++)
{
height[k] = 0;
}*/
}
int main()
{
int cas, count, i, j, k, l, tx, ty, max, remain, score, stemp;
cas = 0;
scanf("%d", &count);
while (count--)
{
for (i = 9; i >= 0; i--)
{
scanf("%s", map_[i]);
}
for (i = 0; i < 15; i++)
{
height[i] = 10;
}
width = 15;
printf("Game %d:\n\n", ++cas);
for (k = 1, remain = 150, score = 0;; k++)
{
memset(used, 0, sizeof(used));
/*printf("%d\n", width);
system("pause");*/
for (j = 0, max = 0; j < width; j++)
{
for (i = 0; i < height[j]; i++)
{
if (!used[i][j])
{
cnum = 0;
counts(i, j, map_[i][j]);
if (cnum > max)
{
max = cnum;
tx = i;
ty = j;
}
}
}
}
if (max <= 1)
{
break;
}
stemp = max - 2;
stemp *= stemp;
score += stemp;
printf("Move %d at (%d,%d): removed %d balls of color %c, got %d points.\n", k, tx + 1, ty + 1, max, map_[tx][ty], stemp);
floodfill(tx, ty, map_[tx][ty]);
/*for(i=9; i>=0; i--)
{
for(j=0; j<width; j++)
{
if(i < height[j] && map_[i][j])
{
printf("%c", map_[i][j]);
}
else
{
printf(" ");
}
}
printf("\n");
}
printf("\n");*/
remain -= max;
adjust();
/*for(i=9; i>=0; i--)
{
for(j=0; j<width; j++)
{
if(i < height[j] && map_[i][j])
{
printf("%c", map_[i][j]);
}
else
{
printf(" ");
}
}
printf("\n");
}*/
}
if (!remain)
{
score += 1000;
}
printf("Final score: %d, with %d balls remaining.\n", score, remain);
if (count)
{
printf("\n");
}
}
return 0;
}
|
73070236ea0599f5fc0a3c6dd1a3e5f3808519f5
|
c9cbdd19454ad19781435e1dd0fa1f1559042057
|
/Demo/FollowerDemo.cpp
|
b6b16f19b03f01e0ee490fbc7a2d95ef180f567f
|
[
"MIT"
] |
permissive
|
remicongee/Distributed-Lock
|
e15f185b1ff05bf3a270f7acb363900f62941946
|
0dabd63dbf81c43486d85a9438a54bec77c598fc
|
refs/heads/master
| 2020-04-08T23:15:29.627705
| 2018-11-30T12:04:18
| 2018-11-30T12:04:18
| 159,817,764
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 172
|
cpp
|
FollowerDemo.cpp
|
#include "../Headers/Follower.h"
using namespace std;
int main() {
// I'm blank
Follower* follower = new Follower();
follower->RunFollower();
return 0;
}
|
b8a04fa2c9aab2884b0298e0a75299b8d0d48707
|
fab3558facbc6d6f5f9ffba1d99d33963914027f
|
/include/fcppt/variant/not_equal.hpp
|
0dd213314e834ee6158691d482a99645f3f6409c
|
[] |
no_license
|
pmiddend/sgedoxy
|
315aa941979a26c6f840c6ce6b3765c78613593b
|
00b8a4aaf97c2c927a008929fb4892a1729853d7
|
refs/heads/master
| 2021-01-20T04:32:43.027585
| 2011-10-28T17:30:23
| 2011-10-28T17:30:23
| 2,666,694
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 565
|
hpp
|
not_equal.hpp
|
// Copyright Carl Philipp Reh 2009 - 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_VARIANT_NOT_EQUAL_HPP_INCLUDED
#define FCPPT_VARIANT_NOT_EQUAL_HPP_INCLUDED
#include <fcppt/variant/equal.hpp>
#include <fcppt/variant/object_fwd.hpp>
namespace fcppt
{
namespace variant
{
template<
typename Types
>
bool
operator!=(
object<Types> const &_a,
object<Types> const &_b
)
{
return !(_a == _b);
}
}
}
#endif
|
21ca94331349d4e13e48ebc96120374f56959270
|
b57585a9cadfeec84a22685e7f7f34c1e9d70009
|
/langdata.cpp
|
1bfd439f6d9152f467c617f451d49d2f9b4028ea
|
[] |
no_license
|
Erreke/TranslationProcessor
|
7cad5a36eea582faba1f2219cccef1a07e024c12
|
0f5d4395bf39924f2b8fc826928dbcfda479c000
|
refs/heads/master
| 2021-01-21T16:35:00.232392
| 2017-06-12T21:47:03
| 2017-06-12T21:47:03
| 91,896,248
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 136
|
cpp
|
langdata.cpp
|
#include "langdata.h"
LangData::LangData(QString _key, QString _value, int _id)
{
key = _key;
value = _value;
id = _id;
};
|
5acaca76c6f9f4f9c119ad8853a3c2935f103c00
|
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
|
/DP/629.cpp
|
e8aa9ced8891ef2e0a05dded7e8cc2138ab8a2cc
|
[] |
no_license
|
thegamer1907/Code_Analysis
|
0a2bb97a9fb5faf01d983c223d9715eb419b7519
|
48079e399321b585efc8a2c6a84c25e2e7a22a61
|
refs/heads/master
| 2020-05-27T01:20:55.921937
| 2019-11-20T11:15:11
| 2019-11-20T11:15:11
| 188,403,594
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 545
|
cpp
|
629.cpp
|
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
char c;
c=getchar();
int arr[100090]={0};
int k=1,count=0;
while(1)
{
char temp = c;
c=getchar();
if(c==10)break;
k++;
if(temp==c)
{
count++;
}
arr[k]=count;
}
///for(int i=0;i<=k;i++)cout<<arr[i]<<endl;
///return 0;
int m;
cin>>m;
for(int i=0;i<m;i++)
{
int l,r;
cin>>l>>r;
cout<<arr[r]-arr[l]<<endl;
}
}
|
045ade9d4e63304d9aee94c947e77d1d8020b544
|
48031a4b7a81c4b0bf01ee5532900059467600be
|
/SmallObjectAllocator/FixedAllocator.h
|
43f079f9dd64bc5c29deb8db98b414c559e60dea
|
[] |
no_license
|
pvmiseeffoC/Allocators
|
72f87fa4d864023b6b926941949d0fbb4c46c1a8
|
1edd21e20efef80e1dbe57f89fbc68ed3cc06d28
|
refs/heads/master
| 2023-03-06T01:45:22.375329
| 2021-02-07T16:21:31
| 2021-02-07T16:21:31
| 291,521,957
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,479
|
h
|
FixedAllocator.h
|
#pragma once
#include <limits>
#include <vector>
#include "Chunk.h"
namespace allocators
{
class FixedAllocator
{
public:
using ChunkType = DefaultChunk;
using Chunks = std::vector<ChunkType>;
private:
void deallocate( void* p );
bool makeChunk();
ChunkType* findChunk( void* p );
DataType _minObjectsPerChunk = 8;
DataType _maxObjectsPerChunk = std::numeric_limits<DataType>::max();
SizeType _blockSize;
DataType _numBlocks;
Chunks _chunks;
ChunkType* _allocChunk;
ChunkType* _deallocChunk;
ChunkType* _emptyChunk;
public:
FixedAllocator();
/// disable copying
FixedAllocator( FixedAllocator const& ) = delete;
FixedAllocator& operator=( FixedAllocator const& ) = delete;
/// Allow move sematincs
FixedAllocator( FixedAllocator && ) = default;
FixedAllocator& operator=( FixedAllocator && ) = default;
~FixedAllocator();
void init( SizeType blockSize, SizeType pageSize );
void* allocate();
bool deallocate( void* p, ChunkType* hint );
inline SizeType blockSize() const { return _blockSize; }
bool freeEmptyChunk();
bool tryToFreeUpSomeMemory();
SizeType emptyChunks( bool fast = true ) const;
bool isCorrupt() const;
const ChunkType* hasBlock( void* p ) const;
};
} // namespace allocators
|
c6a955ed8485629d6f72c85e92387b12c511a38c
|
80e17f421b3b1e11baa8c6860532b0803657789f
|
/demo/Chapter-11/033.Struct/VectorOperation.cpp
|
617e4102fb31dedc9a5dc2a2e2b728afdab08210
|
[] |
no_license
|
TakeOver5/My-C-Notes
|
be26f2243cd6f5eb31c3e85e4e70f5ee1643405e
|
8f5a8545288157ce4e5495d91738bbde1c306c94
|
refs/heads/master
| 2023-02-23T18:59:47.733031
| 2018-11-12T20:11:45
| 2018-11-12T20:11:45
| 126,676,278
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,850
|
cpp
|
VectorOperation.cpp
|
/*
* 時間:2018/10/07
* 功能:
* 向量的運算。
* 目的:
* 使用結構傳遞結構進入函式。
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct vector{
double x;
double y;
double z;
} V;
void enter(V*);
void vput(V*, V*, char);
V vadd(V*, V*);
double vdot(V*, V*);
V vcross(V*, V*);
int main(void){
double d;
V a,b,v;
// 輸入兩個向量
enter(&a);
enter(&b);
vput(&a, &b, '+');
v = vadd(&a, &b);
printf("(%.2lf, %.2lf, %.2lf)\n", v.x, v.y, v.z);
vput(&a, &b, '.');
d = vdot(&a, &b);
printf("%.2lf\n", d);
vput(&a, &b, 'x');
v = vcross(&a, &b);
printf("(%.2lf, %.2lf, %.2lf)\n", v.x, v.y, v.z);
system("pause");
return 0;
}
//輸出算式
void vput(V* a, V* b, char ch){
printf("(%.2lf, %.2lf, %.2lf) %c (%.2lf, %.2lf, %.2lf) = ",
a->x, a->y, a->z, ch, b->x, b->y, b->z);
}
//鍵入函式
void enter(V* v){
printf("輸入一個向量(x, y, z):");
scanf("%lf %lf %lf", &v->x, &v->y, &v->z);
}
//處理向量向加
V vadd(V* a, V* b){
V v;
v.x = a->x + b->x;
v.y = a->y + b->y;
v.z = a->z + b->z;
return v;
}
//處理向量內積
double vdot(V* a, V* b){
return a->x*b->x + a->y*b->y + a->z*b->z;
}
//處理向量外積
V vcross(V*a, V*b){
V v;
v.x = a->y*b->z - b->y*a->z;
v.y = a->z*b->x - b->z*a->x;
v.z = a->x*b->y - b->x*a->y;
return v;
}
/*
------------ 在 cmd 的輸出結果 ---------------
輸入一個向量(x, y, z):3 1 2
輸入一個向量(x, y, z):0 0 1
(3.00, 1.00, 2.00) + (0.00, 0.00, 1.00) = (3.00, 1.00, 3.00)
(3.00, 1.00, 2.00) . (0.00, 0.00, 1.00) = 2.00
(3.00, 1.00, 2.00) x (0.00, 0.00, 1.00) = (1.00, -3.00, 0.00)
----------------------------------------------
*/
|
394cb81cade9343dd551631ea9154283e50fb2bc
|
31c09851d83f56acbf86ecc4476a7a0a37b164cf
|
/include/classifier.hpp
|
6d6212d9cee0bbcece0785a275c3f01ec1802ccc
|
[] |
no_license
|
StephanXu/FireDetector
|
8f5cfde7e46fc03c5455503ba1f1cd475b424c1b
|
e77d951ff7c88b648a67e76e6289e195b5858cb1
|
refs/heads/master
| 2022-04-11T20:01:10.976180
| 2020-03-10T08:16:31
| 2020-03-10T08:16:31
| 164,626,981
| 8
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 728
|
hpp
|
classifier.hpp
|
#pragma once
#ifndef CLASSIFIER_HPP
#define CLASSIFIER_HPP
#include <string>
#include <vector>
#include <memory>
#include <opencv2/opencv.hpp>
#include <caffe/caffe.hpp>
class Cclassifier
{
public:
/*
Cclassifier:
*/
explicit Cclassifier(const std::string &deploy_file,
const std::string &caffemodel);
std::vector<float> Classify(const cv::Mat &img);
void SetMean(const std::string &mean_file);
std::tuple<int, float> GetResult(const std::vector<float> &classify_result);
private:
// network
std::shared_ptr<caffe::Net<float>> _net;
// input data size
cv::Size _input_geometry;
// num of channels
int _num_channels;
cv::Mat _mean;
};
#endif
|
56e7d2dd9403b2e7cd9cd15746756497f5b964ac
|
137e63892b98e84343b573415e0afa57a8188a6f
|
/src/OpenGLWindow.cpp
|
d9f97a01fb721778be9119ffdf4c845dab2c7186
|
[] |
no_license
|
Inamsorensen/Explosion
|
7e5f868e2708696c9097487355c3f5309f10d4a0
|
f77053c71ba33072d8e299148ac8ca254ab2db49
|
refs/heads/master
| 2021-01-17T10:19:01.893654
| 2016-06-13T08:58:56
| 2016-06-13T08:58:56
| 58,669,293
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,286
|
cpp
|
OpenGLWindow.cpp
|
#include <QMouseEvent>
#include <QGuiApplication>
#include <ngl/Camera.h>
#include <ngl/Light.h>
#include <ngl/Material.h>
#include <ngl/NGLInit.h>
#include <ngl/VAOPrimitives.h>
#include <ngl/ShaderLib.h>
#include <ngl/Transformation.h>
#include "OpenGLWindow.h"
//----------------------------------------------------------------------------------------------------------------------
/// @brief the increment for x/y translation with mouse movement
//----------------------------------------------------------------------------------------------------------------------
const static float INCREMENT=0.01;
//----------------------------------------------------------------------------------------------------------------------
/// @brief the increment for the wheel zoom
//----------------------------------------------------------------------------------------------------------------------
const static float ZOOM=0.1;
OpenGLWindow::OpenGLWindow()
{
//Set rotation of camera to zero for initialisation
m_rotate=false;
m_spinXFace=0;
m_spinYFace=0;
setTitle("Explosion");
}
OpenGLWindow::~OpenGLWindow()
{
if (m_explosionController!=nullptr)
{
// m_explosionController->~ExplosionController();
delete m_explosionController;
}
std::cout<<"Shutting down NGL, removing VAO's and Shaders\n";
}
void OpenGLWindow::resizeGL(QResizeEvent *_event )
{
m_width=_event->size().width()*devicePixelRatio();
m_height=_event->size().height()*devicePixelRatio();
// Reset camera with new width and height
m_camera.setShape(45.0f,(float)width()/height(),0.05f,350.0f);
}
void OpenGLWindow::resizeGL(int _w , int _h)
{
//Calculate new width and height
m_camera.setShape(45.0f,(float)_w/_h,0.05f,350.0f);
m_width=_w*devicePixelRatio();
m_height=_h*devicePixelRatio();
}
void OpenGLWindow::initializeGL()
{
ngl::NGLInit::instance();
// Grey Background
glClearColor(0.4f, 0.4f, 0.4f, 1.0f);
// enable depth testing for drawing
glEnable(GL_DEPTH_TEST);
// enable multisampling for smoother drawing
glEnable(GL_MULTISAMPLE);
//Camera setup
ngl::Vec3 from(0,0,1);
ngl::Vec3 to(0,0,0);
ngl::Vec3 up(0,1,0);
m_camera.set(from,to,up);
// set the shape using FOV 45 Aspect Ratio based on Width and Height
// The final two are near and far clipping planes of 0.5 and 10
m_camera.setShape(60,(float)720.0/576.0,0.5,150);
//Shader setup
//Setup Phong Gold shader - Used for burning particles
ngl::ShaderLib *shader=ngl::ShaderLib::instance();
shader->createShaderProgram("Phong");
shader->attachShader("PhongVertex",ngl::ShaderType::VERTEX);
shader->attachShader("PhongFragment",ngl::ShaderType::FRAGMENT);
shader->loadShaderSource("PhongVertex","shaders/Phong.vs");
shader->loadShaderSource("PhongFragment","shaders/Phong.fs");
shader->compileShader("PhongVertex");
shader->compileShader("PhongFragment");
shader->attachShaderToProgram("Phong","PhongVertex");
shader->attachShaderToProgram("Phong","PhongFragment");
shader->bindAttribute("Phong",0,"inVert");
shader->bindAttribute("Phong",1,"inUV");
shader->bindAttribute("Phong",2,"inNormal");
shader->linkProgramObject("Phong");
(*shader)["Phong"]->use();
shader->setShaderParam1i("Normalize",1);
// the shader will use the currently active material and light0 so set them
ngl::Material m(ngl::STDMAT::GOLD);
m.loadToShader("material");
ngl::Light light(ngl::Vec3(2,2,20),ngl::Colour(1,1,1,1),ngl::Colour(1,1,1,1),ngl::LightModes::POINTLIGHT);
//Create light
ngl::Mat4 iv=m_camera.getViewMatrix();
iv.transpose();
light.setTransform(iv);
light.setAttenuation(1,0,0);
light.enable();
light.loadToShader("light");
ngl::VAOPrimitives *prim=ngl::VAOPrimitives::instance();
prim->createSphere("sphere", 0.1,10);
//Setup Phong Silver shader - Used for soot
shader->createShaderProgram("PhongSilver");
shader->attachShader("PhongVertex",ngl::ShaderType::VERTEX);
shader->attachShader("PhongFragment",ngl::ShaderType::FRAGMENT);
shader->loadShaderSource("PhongVertex","shaders/Phong.vs");
shader->loadShaderSource("PhongFragment","shaders/Phong.fs");
shader->compileShader("PhongVertex");
shader->compileShader("PhongFragment");
shader->attachShaderToProgram("PhongSilver","PhongVertex");
shader->attachShaderToProgram("PhongSilver","PhongFragment");
shader->bindAttribute("PhongSilver",0,"inVert");
shader->bindAttribute("PhongSilver",1,"inUV");
shader->bindAttribute("PhongSilver",2,"inNormal");
shader->linkProgramObject("PhongSilver");
(*shader)["PhongSilver"]->use();
shader->setShaderParam1i("Normalize",1);
// the shader will use the currently active material and light0 so set them
ngl::Material mSilver(ngl::STDMAT::SILVER);
mSilver.loadToShader("material");
//Attach light
light.loadToShader("light");
//Setup Phong Copper shader - Used for unignited particles
shader->createShaderProgram("PhongCopper");
shader->attachShader("PhongVertex",ngl::ShaderType::VERTEX);
shader->attachShader("PhongFragment",ngl::ShaderType::FRAGMENT);
shader->loadShaderSource("PhongVertex","shaders/Phong.vs");
shader->loadShaderSource("PhongFragment","shaders/Phong.fs");
shader->compileShader("PhongVertex");
shader->compileShader("PhongFragment");
shader->attachShaderToProgram("PhongCopper","PhongVertex");
shader->attachShaderToProgram("PhongCopper","PhongFragment");
shader->bindAttribute("PhongCopper",0,"inVert");
shader->bindAttribute("PhongCopper",1,"inUV");
shader->bindAttribute("PhongCopper",2,"inNormal");
shader->linkProgramObject("PhongCopper");
(*shader)["PhongCopper"]->use();
shader->setShaderParam1i("Normalize",1);
// the shader will use the currently active material and light0 so set them
ngl::Material mCopper(ngl::STDMAT::COPPER);
mCopper.loadToShader("material");
//Attach light
light.loadToShader("light");
//Setup colour shader - Used to draw bounding box
shader->createShaderProgram("Colour");
shader->attachShader("ColourVertex", ngl::ShaderType::VERTEX);
shader->attachShader("ColourFragment", ngl::ShaderType::FRAGMENT);
shader->loadShaderSource("ColourVertex","shaders/colour.vs");
shader->loadShaderSource("ColourFragment","shaders/colour.fs");
shader->compileShader("ColourVertex");
shader->compileShader("ColourFragment");
shader->attachShaderToProgram("Colour","ColourVertex");
shader->attachShaderToProgram("Colour","ColourFragment");
shader->bindAttribute("Colour",0,"inVertex");
shader->bindAttribute("Colour",1,"inUV");
shader->bindAttribute("Colour",2,"inNormal");
shader->linkProgramObject("Colour");
(*shader)["Colour"]->use();
shader->setShaderParam1i("Normalize",1);
//Setup simulation
m_explosionController=ExplosionController::instance();
//Setup VAO for bounding box
buildVAO();
//Send render variables to explosion controller
m_explosionController->setRenderVariables(&m_camera, "Phong");
// as re-size is not explicitly called we need to do this.
glViewport(0,0,width(),height());
//Start timer.
startTimer(10);
}
void OpenGLWindow::buildVAO()
{
m_vao.reset( ngl::VertexArrayObject::createVOA(GL_LINES));
m_vao->bind();
//Line indices
const static GLubyte indices[]= {
0,1,1,2,2,3,3,0, //top
0,4,4,5,5,1,1,0, //back
0,4,4,7,7,3,3,0, //left
3,2,2,6,6,7,7,3, //front
7,6,6,5,5,4,4,7, //bottom
};
//Vertices of lines
GLfloat vertices[] = {0,1,0,
1,1,0,
1,1,1,
0,1,1,
0,0,0,
1,0,0,
1,0,1,
0,0,1
};
//Colour of each vertex
GLfloat colours[] = {1,0,0,
1,0,0,
1,0,0,
1,0,0,
1,0,0,
1,0,0,
1,0,0,
1,0,0
};
//Feed data into the VAO
m_vao->setIndexedData(24*sizeof(GLfloat),vertices[0],sizeof(indices),&indices[0],GL_UNSIGNED_BYTE,GL_STATIC_DRAW);
m_vao->setVertexAttributePointer(0,3,GL_FLOAT,0,0);
m_vao->setIndexedData(24*sizeof(GLfloat),colours[0],sizeof(indices),&indices[0],GL_UNSIGNED_BYTE,GL_STATIC_DRAW);
m_vao->setVertexAttributePointer(1,3,GL_FLOAT,0,0);
m_vao->setNumIndices(sizeof(indices));
m_vao->unbind();
}
void OpenGLWindow::paintGL()
{
// clear the screen and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0,0,m_width,m_height);
//Set ModelMatrix for camera orientation
ngl::Mat4 ModelMatrix_Camera;
//Create rotation matrices
ngl::Mat4 rotationX;
ngl::Mat4 rotationY;
rotationX.rotateX(m_spinXFace);
rotationY.rotateY(m_spinYFace);
//Multiply the rotation matrices and add translation
ModelMatrix_Camera=rotationX*rotationY;
ModelMatrix_Camera.m_30=m_modelPosition.m_x;
ModelMatrix_Camera.m_31=m_modelPosition.m_y;
ModelMatrix_Camera.m_32=m_modelPosition.m_z;
//Draw bounding box
ngl::ShaderLib *shader=ngl::ShaderLib::instance();
shader->use("Colour");
ngl::Mat4 MVP;
ngl::Transformation ModelMatrix_BBox;
ModelMatrix_BBox.setPosition(m_explosionController->getGridPosition());
float gridSize=m_explosionController->getGridSize();
ModelMatrix_BBox.setScale(gridSize,gridSize,gridSize);
//MVP calculated from multiplying ModelMatrix_BBox with ModelMatrix_Camera
ngl::Mat4 ModelMatrix;
ModelMatrix=ModelMatrix_BBox.getMatrix()*ModelMatrix_Camera;
MVP=ModelMatrix*m_camera.getVPMatrix();
shader->setShaderParamFromMat4("MVP",MVP);
m_vao->bind();
m_vao->draw();
m_vao->unbind();
//Draw particles
m_explosionController->render(ModelMatrix_Camera);
}
//----------------------------------------------------------------------------------------------------------------------
void OpenGLWindow::mouseMoveEvent (QMouseEvent * _event)
{
// note the method buttons() is the button state when event was called
// this is different from button() which is used to check which button was
// pressed when the mousePress/Release event is generated
if(m_rotate && _event->buttons() == Qt::LeftButton)
{
int diffx=_event->x()-m_origX;
int diffy=_event->y()-m_origY;
m_spinXFace += (float) 0.5f * diffy;
m_spinYFace += (float) 0.5f * diffx;
m_origX = _event->x();
m_origY = _event->y();
update();
}
// right mouse translate code
else if(m_translate && _event->buttons() == Qt::RightButton)
{
int diffX = (int)(_event->x() - m_origXPos);
int diffY = (int)(_event->y() - m_origYPos);
m_origXPos=_event->x();
m_origYPos=_event->y();
m_modelPosition.m_x += INCREMENT * diffX;
m_modelPosition.m_y -= INCREMENT * diffY;
update();
}
}
//----------------------------------------------------------------------------------------------------------------------
void OpenGLWindow::mousePressEvent ( QMouseEvent * _event)
{
// this method is called when the mouse button is pressed in this case we
// store the value where the maouse was clicked (x,y) and set the Rotate flag to true
if(_event->button() == Qt::LeftButton)
{
m_origX = _event->x();
m_origY = _event->y();
m_rotate =true;
}
// right mouse translate mode
else if(_event->button() == Qt::RightButton)
{
m_origXPos = _event->x();
m_origYPos = _event->y();
m_translate=true;
}
}
//----------------------------------------------------------------------------------------------------------------------
void OpenGLWindow::mouseReleaseEvent ( QMouseEvent * _event )
{
// this event is called when the mouse button is released
// we then set Rotate to false
if (_event->button() == Qt::LeftButton)
{
m_rotate=false;
}
// right mouse translate mode
if (_event->button() == Qt::RightButton)
{
m_translate=false;
}
}
//----------------------------------------------------------------------------------------------------------------------
void OpenGLWindow::wheelEvent(QWheelEvent *_event)
{
// check the diff of the wheel position (0 means no change)
if(_event->delta() > 0)
{
m_modelPosition.m_z+=ZOOM;
}
else if(_event->delta() <0 )
{
m_modelPosition.m_z-=ZOOM;
}
update();
}
//----------------------------------------------------------------------------------------------------------------------
void OpenGLWindow::keyPressEvent(QKeyEvent *_event)
{
// this method is called every time the main window recives a key event.
// we then switch on the key value and set the camera in the GLWindow
switch (_event->key())
{
// escape key to quite
case Qt::Key_Escape : QGuiApplication::exit(EXIT_SUCCESS); break;
case Qt::Key_F : showFullScreen(); break;
case Qt::Key_E : m_explosionController->toggleAlembicExport(); break;
default : break;
}
// update();
}
void OpenGLWindow::timerEvent(QTimerEvent *_event )
{
//Update explosion calculation
m_explosionController->update();
//Render new frame
update();
}
|
212aa394291958bc2d9bb48b76d6ae214c646a57
|
78cffeb33be19a2232c67f0eca6b39dd8e0c4976
|
/System.h
|
86e25babbe68822de54c2d9e94c3a24991a0a6a8
|
[] |
no_license
|
Alburgerto/ECS
|
d37092279e63ea6159430f41c9bd9a1f96492072
|
46b24af56be40bc0416de633a8217a2cb67040df
|
refs/heads/master
| 2020-04-09T05:33:06.459857
| 2019-01-21T16:38:35
| 2019-01-21T16:38:35
| 160,069,038
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 339
|
h
|
System.h
|
#pragma once
#include <memory>
#include "Entity.h"
class Shared;
class System {
public:
System(Shared* l_shared);
virtual ~System();
Shared* getShared() { return m_shared; }
// virtual void addEntity(std::pair<std::shared_ptr<Entity>, std::shared_ptr<Component>> l_entity) = 0;
protected:
Shared* m_shared;
};
|
6f4616237abdfcbccbb2f8e05b4dd05911779541
|
2b721d0e6d9ada23668d02ee14e83219a1ee0f48
|
/source/libguiex_core/guiutility.cpp
|
af5960ea072b24d894a4a17990e7c31092a0b23e
|
[] |
no_license
|
lougithub/libguiex
|
fef2165e06f3adb66295aac2cf5f0be24dd47d46
|
30cf061a40a4c113b58765dc3aeacddc4521a034
|
refs/heads/master
| 2016-09-10T10:20:48.122440
| 2014-06-11T14:17:56
| 2014-06-11T14:17:56
| 2,423,027
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,068
|
cpp
|
guiutility.cpp
|
/**
* @file guiutility.cpp
* @brief utility function for gui system
* @author ken
* @date 2006-06-01
*/
//============================================================================//
// include
//============================================================================//
#include "guiutility.h"
#include <string.h>
#if defined(GUIEX_PLATFORM_WIN32)
#include <windows.h>
#else
#include <ctype.h>
#endif
#include <stdio.h>
#include <locale.h>
//============================================================================//
// function
//============================================================================//
namespace guiex
{
//------------------------------------------------------------------------------
char * CGUIUtility::timestamp (char date_and_time[],int32 date_and_timelen,int32 return_pointer_to_first_digit)
{
if (date_and_timelen < 35)
{
return NULL;
}
#if defined(GUIEX_PLATFORM_WIN32)
// Emulate Unix. Win32 does NOT support all the UNIX versions
// below, so DO we need this ifdef.
static const char *day_of_week_name[] =
{
("Sun"),
("Mon"),
("Tue"),
("Wed"),
("Thu"),
("Fri"),
("Sat")
};
static const char *month_name[] =
{
("Jan"),
("Feb"),
("Mar"),
("Apr"),
("May"),
("Jun"),
("Jul"),
("Aug"),
("Sep"),
("Oct"),
("Nov"),
("Dec")
};
SYSTEMTIME local;
::GetLocalTime (&local);
sprintf (date_and_time,
("%3s %3s %2d %04d %02d:%02d:%02d.%06d"),
day_of_week_name[local.wDayOfWeek],
month_name[local.wMonth - 1],
(int32) local.wDay,
(int32) local.wYear,
(int32) local.wHour,
(int32) local.wMinute,
(int32) local.wSecond,
(int32) (local.wMilliseconds * 1000));
return &date_and_time[15 + (return_pointer_to_first_digit != 0)];
#elif defined(GUIEX_PLATFORM_LINUX)
long now;
char timebuf[40];
now=(long)time((time_t *)0);
ctime_r (&now,timebuf);
// date_and_timelen > sizeof timebuf!
strncpy (date_and_time,timebuf,date_and_timelen);
char yeartmp[5];
strncpy (yeartmp,&date_and_time[20],5);
char timetmp[9];
strncpy (timetmp,&date_and_time[11],9);
sprintf (&date_and_time[11], ("%s %s.%06ld"),yeartmp,timetmp,now );
date_and_time[33] = '\0';
return &date_and_time[15 + (return_pointer_to_first_digit != 0)];
#elif defined( GUIEX_PLATFORM_MAC)
long now;
char timebuf[40];
now=(long)time((time_t *)0);
ctime_r (&now,timebuf);
// date_and_timelen > sizeof timebuf!
strncpy (date_and_time,timebuf,date_and_timelen);
char yeartmp[5];
strncpy (yeartmp,&date_and_time[20],5);
char timetmp[9];
strncpy (timetmp,&date_and_time[11],9);
sprintf (&date_and_time[11], ("%s %s.%06ld"),yeartmp,timetmp,now );
date_and_time[33] = '\0';
return &date_and_time[15 + (return_pointer_to_first_digit != 0)];
#else
# error "unknown platform"
#endif /* WIN32 */
//------------------------------------------------------------------------------
}
//------------------------------------------------------------------------------
size_t CGUIUtility::format_hexdump (const char *buffer,size_t size,char *obuf,size_t obuf_sz)
{
unsigned char c;
char textver[16 + 1];
// We can fit 16 bytes output in text mode per line, 4 chars per byte.
size_t maxlen = (obuf_sz / 68) * 16;
if (size > maxlen)
{
size = maxlen;
}
size_t i;
size_t lines = size / 16;
for (i = 0; i < lines; i++)
{
size_t j;
for (j = 0 ; j < 16; j++)
{
c = (unsigned char) buffer[(i << 4) + j]; // or, buffer[i*16+j]
sprintf (obuf,"%02x ",c);
obuf += 3;
if (j == 7)
{
sprintf (obuf," ");
obuf++;
}
textver[j] = isprint (c) ? c : '.';
}
textver[j] = 0;
sprintf (obuf," %s\n",textver);
while (*obuf != '\0')
{
obuf++;
}
}
if (size % 16)
{
for (i = 0 ; i < size % 16; i++)
{
c = (unsigned char) buffer[size - size % 16 + i];
sprintf (obuf,"%02x ",c);
obuf += 3;
if (i == 7)
{
sprintf (obuf," ");
obuf++;
}
textver[i] = isprint (c) ? c : '.';
}
for (i = size % 16; i < 16; i++)
{
sprintf (obuf," ");
obuf += 3;
if (i == 7)
{
sprintf (obuf," ");
obuf++;
}
textver[i] = ' ';
}
textver[i] = 0;
sprintf (obuf," %s\n",textver);
}
return size;
}
//------------------------------------------------------------------------------
uint32 CGUIUtility::Log2 (uint32 num)
{
unsigned long log = 0;
for (; num > 0; ++log)
num >>= 1;
return log;
}
//------------------------------------------------------------------------------
CGUIString CGUIUtility::GenerateWidgetName()
{
static int nNameCount = 0;
char buf[32];
snprintf( buf,32, "widgetname_%d", nNameCount++ );
return buf;
}
//------------------------------------------------------------------------------
}//namespace guiex
|
23101ff74215818da99f13cac27bb275f7aa9054
|
3f3a42f429f8bcd769644148b24c3b0e6e2589ed
|
/GameProject/GameEngine/GameApp/Water/ocean_simulator.h
|
59ddb4ce2661c82362bcb6298965bb194a10f28a
|
[] |
no_license
|
DanielNeander/my-3d-engine
|
d10ad3e57a205f6148357f47467b550c7e0e0f33
|
7f0babbfdf0b719ea4b114a89997d3e52bcb2b6c
|
refs/heads/master
| 2021-01-10T17:58:25.691360
| 2013-04-24T07:37:31
| 2013-04-24T07:37:31
| 53,236,587
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,244
|
h
|
ocean_simulator.h
|
// Copyright (c) 2011 NVIDIA Corporation. All rights reserved.
//
// TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED
// *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS
// OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT,IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA
// OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, SPECIAL, INCIDENTAL, INDIRECT, OR
// CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS
// OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY
// OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
// EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
//
// Please direct any bugs or questions to SDKFeedback@nvidia.com
#ifndef _OCEAN_WAVE_H
#define _OCEAN_WAVE_H
#include "CSFFT/fft_512x512.h"
//#define CS_DEBUG_BUFFER
#define PAD16(n) (((n)+15)/16*16)
struct OceanParameter
{
// Must be power of 2.
int dmap_dim;
// Typical value is 1000 ~ 2000
float patch_length;
// Adjust the time interval for simulation.
float time_scale;
// Amplitude for transverse wave. Around 1.0
float wave_amplitude;
// Wind direction. Normalization not required.
D3DXVECTOR2 wind_dir;
// Around 100 ~ 1000
float wind_speed;
// This value damps out the waves against the wind direction.
// Smaller value means higher wind dependency.
float wind_dependency;
// The amplitude for longitudinal wave. Must be positive.
float choppy_scale;
};
class OceanSimulator
{
public:
OceanSimulator(OceanParameter& params, ID3D11Device* pd3dDevice);
~OceanSimulator();
// -------------------------- Initialization & simulation routines ------------------------
// Update ocean wave when tick arrives.
void updateDisplacementMap(float time);
// Texture access
ID3D11ShaderResourceView* getD3D11DisplacementMap();
ID3D11ShaderResourceView* getD3D11GradientMap();
const OceanParameter& getParameters();
protected:
OceanParameter m_param;
// ---------------------------------- GPU shading asset -----------------------------------
// D3D objects
ID3D11Device* m_pd3dDevice;
ID3D11DeviceContext* m_pd3dImmediateContext;
// Displacement map
ID3D11Texture2D* m_pDisplacementMap; // (RGBA32F)
ID3D11ShaderResourceView* m_pDisplacementSRV;
ID3D11RenderTargetView* m_pDisplacementRTV;
// Gradient field
ID3D11Texture2D* m_pGradientMap; // (RGBA16F)
ID3D11ShaderResourceView* m_pGradientSRV;
ID3D11RenderTargetView* m_pGradientRTV;
// Samplers
ID3D11SamplerState* m_pPointSamplerState;
// Initialize the vector field.
void initHeightMap(OceanParameter& params, D3DXVECTOR2* out_h0, float* out_omega);
// ----------------------------------- CS simulation data ---------------------------------
// Initial height field H(0) generated by Phillips spectrum & Gauss distribution.
ID3D11Buffer* m_pBuffer_Float2_H0;
ID3D11UnorderedAccessView* m_pUAV_H0;
ID3D11ShaderResourceView* m_pSRV_H0;
// Angular frequency
ID3D11Buffer* m_pBuffer_Float_Omega;
ID3D11UnorderedAccessView* m_pUAV_Omega;
ID3D11ShaderResourceView* m_pSRV_Omega;
// Height field H(t), choppy field Dx(t) and Dy(t) in frequency domain, updated each frame.
ID3D11Buffer* m_pBuffer_Float2_Ht;
ID3D11UnorderedAccessView* m_pUAV_Ht;
ID3D11ShaderResourceView* m_pSRV_Ht;
// Height & choppy buffer in the space domain, corresponding to H(t), Dx(t) and Dy(t)
ID3D11Buffer* m_pBuffer_Float_Dxyz;
ID3D11UnorderedAccessView* m_pUAV_Dxyz;
ID3D11ShaderResourceView* m_pSRV_Dxyz;
ID3D11Buffer* m_pQuadVB;
// Shaders, layouts and constants
ID3D11ComputeShader* m_pUpdateSpectrumCS;
ID3D11VertexShader* m_pQuadVS;
ID3D11PixelShader* m_pUpdateDisplacementPS;
ID3D11PixelShader* m_pGenGradientFoldingPS;
ID3D11InputLayout* m_pQuadLayout;
ID3D11Buffer* m_pImmutableCB;
ID3D11Buffer* m_pPerFrameCB;
// FFT wrap-up
CSFFT512x512_Plan m_fft_plan;
#ifdef CS_DEBUG_BUFFER
ID3D11Buffer* m_pDebugBuffer;
#endif
};
#endif // _OCEAN_WAVE_H
|
d9b5e005186f7818753b884c1d7ceb5c7cc762d6
|
44e09af91487023f303bafbef064276ec257ea94
|
/src/search.hpp
|
c521a3af1d14fb2f0ad3b3077580564651a3433e
|
[] |
no_license
|
wanmiles/puzzle-search
|
c104f49e4d64b07a1c2bdfdc60391aabeea448a8
|
d6d899d5fee4de3089f75a145e52fb33f620baf6
|
refs/heads/master
| 2020-05-17T22:34:38.933431
| 2012-07-02T17:25:00
| 2012-07-02T17:25:00
| 32,116,543
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,911
|
hpp
|
search.hpp
|
/**
* Copyright (c) 2010-2012, Ken Anderson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#include <time.h>
////////////////////////////////
// IDA star search /////////////
////////////////////////////////
inline int IDA::getHeuristic(const SearchState & state) const
{
int returnVal = 0;
#ifdef USE_HEURISTIC
returnVal = state.incHeuristic.value;
#endif
#ifdef USE_PERIMETER_DB
const int perimeterHeuristicVal = this->perimeterDb.getHeuristic(state.state, state.hash);
/* if( perimeterHeuristicVal > state.incHeuristic.value )
{
LOG("in perimeter: ");
state.print();
LOG(" md=%i perim=%i\n", state.incHeuristic.value, perimeterHeuristicVal );
}
*/
returnVal = std::max( returnVal, perimeterHeuristicVal );
#endif
#if defined USE_TRANS_TABLE && defined USE_TRANS_TABLE_HEUR_CACHING
const int cachedHeuristicVal = this->transTable.getCachedHeuristic(state.state, state.hash);
returnVal = std::max(returnVal, cachedHeuristicVal);
#endif
return returnVal;
}
inline void IDA::checkHeuristic(const SearchState & state, const int & heur)
{
#if defined USE_TRANS_TABLE && defined USE_TRANS_TABLE_HEUR_CACHING
//const int transTableCachedHeurVal = this->transTable.getCachedHeuristic(state.state, state.hash);
this->transTable.updateCachedHeuristic(state.state, state.hash, heur );
//transTableCachedHeurVal = std::max( heur, transTableCachedHeurVal, heur );
#endif
}
inline PruneStatus IDA::prune(
const SearchState & state,
const int & costLimit,
const int & heur
) //const
{
//const int heur = 0;
if( state.cost + heur > costLimit )
{
return NODE_PRUNED_BY_COST;
}
#ifdef USE_TRANS_TABLE
if( transTable.pruneState(state.state, state.hash, heur, state.cost, costLimit) )
{
return NODE_PRUNED_BY_TT;
}
else
{
return NODE_NEEDS_EXPANSION;
}
/* TransTableEntry * entry = NULL;
(entry) = transTable.LookupEntry( state.state, state.hash );
if( !(entry) )
{
return NODE_NEEDS_EXPANSION;
}
if( !(entry)->UpdateEntry( cost, costLimit ) )
{
return NODE_PRUNED_BY_TT;
}*/
#endif
return NODE_NEEDS_EXPANSION;
}
void indent(LogLevel level, int num)
{
for(int i=0; i<num; ++i)
_LOG(level," ");
}
NodeStatus IDA::idaRecursive( SearchState & state, const int & costLimit, int & prevHeuristic )
{
generationCount++;
// find heuristic
int heuristic = getHeuristic(state);
#ifdef USE_BPMX
heuristic = std::max(prevHeuristic-1,heuristic);
prevHeuristic = std::max(prevHeuristic, heuristic-1);
#endif
#if defined USE_TRANS_TABLE && defined USE_TRANS_TABLE_HEUR_CACHING
checkHeuristic(state, heuristic);
#endif
// Debugging
indent(DEBUG,state.cost);
state.print(DEBUG);
#ifdef USE_HEURISTIC
LOG_DEBUG(" heur=%i",heuristic);
#endif
LOG_DEBUG(" costLimit=%i \n",costLimit);
// Only continue if node needs expansion.
PruneStatus pruneStatus = prune(state,costLimit,heuristic);
if( pruneStatus == NODE_PRUNED_BY_TT )
{
return SEARCH_NODE_IN_TT;
}
else if( pruneStatus == NODE_PRUNED_BY_COST )
{
#ifdef USE_LOOKAHEAD
//int heur = heuristic;
lookaheadRecursive(state,costLimit+3,heuristic);
//if( heuristic > heur )
//{
// LOG("lookahead improved heuristic value\n");
//}
#endif
return SEARCH_SOME_CHILDREN_LEAF;
}
// Expanding node
if( state == m_goal )
{
//LOG(" |-- > solution! \n");
LOG("\n");
state.print(NORMAL);
LOG(" \n" );
return SEARCH_FOUND_SOLUTION; // Found the solution
}
NodeStatus childrenStatus = SEARCH_ALL_CHILDREN_IN_TT;
const OpList opList = state.findSuccessorOperators();
// Debug
indent(DEBUG,state.cost);
opList.print(DEBUG);
LOG_DEBUG("\n");
for( int i=0; i<opList.length; i++ )
{
// apply
state.apply( opList.ops[i] );
//recurse
NodeStatus status = idaRecursive( state, costLimit, heuristic );
// revert
state.unapply( opList.ops[i] );
if( status == SEARCH_FOUND_SOLUTION )
{
state.print(NORMAL);
LOG(" op=%i\n", opList.ops[i] );
return SEARCH_FOUND_SOLUTION;
} else if ( status == SEARCH_SOME_CHILDREN_LEAF )
{
childrenStatus = SEARCH_SOME_CHILDREN_LEAF;
}
#if defined USE_TRANS_TABLE && defined USE_TRANS_TABLE_HEUR_CACHING
checkHeuristic(state, heuristic);
#endif
#ifdef USE_BPMX
if( state.cost + heuristic > costLimit )
{ // heuristic propogated backwards and caused a parental cutoff
//LOG(".");
prevHeuristic = std::max(prevHeuristic, heuristic-1);
return SEARCH_SOME_CHILDREN_LEAF;
}
#endif
}
return childrenStatus;
}
#ifdef USE_LOOKAHEAD
NodeStatus IDA::lookaheadRecursive( SearchState & state, const int & costLimit, int & prevHeuristic )
{
generationCount++;
// Debugging
//print( state );
// find heuristic
int heuristic = getHeuristic(state);
#ifdef USE_BPMX
heuristic = std::max(prevHeuristic-1,heuristic);
prevHeuristic = std::max(prevHeuristic, heuristic-1);
#endif
// Only continue if node needs expansion.
PruneStatus pruneStatus = prune(state,costLimit,heuristic);
if( pruneStatus == NODE_PRUNED_BY_TT )
{
return SEARCH_NODE_IN_TT;
}
else if( pruneStatus == NODE_PRUNED_BY_COST )
{
return SEARCH_SOME_CHILDREN_LEAF;
}
/*
// Expanding node
if( state == m_goal )
{
return SEARCH_FOUND_SOLUTION; // Found the solution
}
*/
NodeStatus childrenStatus = SEARCH_ALL_CHILDREN_IN_TT;
int highestPriority = -1;
Operator highestPriorityOp = NO_OP;
const OpList opList = state.findSuccessorOperators();
for( int i=0; i<opList.length; i++ )
{
// apply
state.apply( opList.ops[i] );
generationCount++;
// get operation with highest state priority
int priority = getPriority(state.hash);
if( priority > highestPriority )
{
highestPriority = priority;
highestPriorityOp = opList.ops[i];
}
// revert
state.unapply( opList.ops[i] );
/*
if( status == SEARCH_FOUND_SOLUTION )
{
state.print(NORMAL);
LOG(" op=%i\n", opList.ops[i] );
return SEARCH_FOUND_SOLUTION;
} else if ( status == SEARCH_SOME_CHILDREN_LEAF )
{
childrenStatus = SEARCH_SOME_CHILDREN_LEAF;
}
*/
}
// Use best one
state.apply( highestPriorityOp );
/*NodeStatus status =*/ lookaheadRecursive( state, costLimit, heuristic );
state.unapply( highestPriorityOp );
#ifdef USE_BPMX
if( state.cost + heuristic > costLimit )
{ // heuristic propogated backwards and caused a parental cutoff
//LOG(".");
prevHeuristic = std::max(prevHeuristic, heuristic-1);
return SEARCH_SOME_CHILDREN_LEAF;
}
#endif
return childrenStatus;
}
#endif
inline int IDA::search(const SearchState & start, const SearchState & goal)
{
int depth = 0;
generationCount = 0;
clock_t totalClockTicks = 0;
int oldNodeCount = 0;
double time;
m_goal = goal;
//m_goal.print(NORMAL);
//LOG("\n");
NodeStatus status = SEARCH_SOME_CHILDREN_LEAF;
#ifdef USE_TRANS_TABLE
transTable.reset();
#endif
SearchState state;
while( status != SEARCH_FOUND_SOLUTION && depth < MAX_COST )
{
state = start;
depth++;
oldNodeCount = 0;
#ifdef USE_TRANS_TABLE
#ifndef USE_LAZY_TRANS_TABLE
//#ifndef USE_TT_SCAN_EXPANSION
transTable.resetTT();
//#endif
#endif
#endif
clock_t startClock = clock();
#ifndef USE_TT_SCAN_EXPANSION
int heur = 0;
status = idaRecursive(state, depth, heur);
#else
/*
// TODO: clean this up.
//int startingCost = depth-1;
if( depth <= 1 ) {
status = IdaRecursive(state, startingCost, depth);
} else {
for(int i=0; i<TT_SIZE; i++)
{
TransTableEntry & entry = transTable[i];
//LOG( "entry.cost=%i, startCost=%i\n", entry.cost, startingCost );
if( entry.cost != MAX_COST ) // valid node
{
copy( state, entry.state ); // Absolutely necessary!
status = IdaRecursive(state, entry.cost, depth);
}
else if( status == SEARCH_FOUND_SOLUTION ) {
LOG("Not implemented yet. exit(4)\n");
exit(4); // Not implemented.
}
}
}
*/
#endif
totalClockTicks += clock() - startClock;
time = (double)totalClockTicks/CLOCKS_PER_SEC;
LOG("depth=%2i genCnt=%13lld time=%6.2fsec nps=%9.f ",
depth, generationCount,
time, generationCount/time );
#ifdef USE_TRANS_TABLE
LOG("fill=%.3f", transTable.percentFull() );
//LOG("\n");
//printTT( transTable );
//printTTInfo( transTable );
#endif
LOG("\n");
}
// If didn't find solution, then we went up to our maximum depth. May want to increase MAX_DEPTH.
if( status != SEARCH_FOUND_SOLUTION)
depth = -1;
return depth;
}
///////////////////////////////
// DFS ////////////////////////
///////////////////////////////
DFS::DFS(PerimeterDb & _perimeterDb) : generationCount(0), perimeterDb(_perimeterDb)
{}
inline void DFS::search( const SearchState & goal, const int & depth)
{
SearchState state;
LOG("Populating PerimeterDb\n");
for( int d=0; d<depth; ++d )
{
state = goal;
dfsRecursive( state, d, d);
LOG("\n");
printTime(NORMAL);
LOG("depth=%3.i ", d);
perimeterDb.printInfo(NORMAL);
perimeterDb.printHistogram(DEBUG,d);
}
#ifdef USE_PERIMETER_SCAN_EXPANSION
// Error limited to 5
// This isn't the most efficient way to do this, but it the easiest
//double avgDepth;
//do
//{
// avgDepth = perimeterDb.getAvgDepth();
// TODO-- we're not storing the prevOp, so there's a big inefficiency there!
//for( int d=0; d<5; ++d )
const int ERROR = 5;
const int iteration = 2;
for( int it=0; it<iteration; ++it)
{
for( unsigned int i=0; i<PERIMETER_DB_SIZE; ++i)
{
PerimeterDbEntry* entry = perimeterDb.getState(i);
if( entry )
{
// reset entry so that search doesn't get cutoff at 1st node
//entry->iteration = 0;
// init
state.state = entry->state;
state.init();
state.cost = entry->cost;
// search
dfsRecursive( state, state.cost+ERROR*it, depth+it );
}
}
LOG("depth=%3.i ", depth+ERROR*it);
perimeterDb.printInfo(NORMAL);
//} while( avgDepth < perimeterDb.getAvgDepth() );
}
#endif
}
inline void DFS::dfsRecursive( SearchState & state, const int & costLimit, const int & iteration )
{
generationCount++;
// Debugging
state.print(DEBUG);
LOG_DEBUG(" costLimit=%i iteration=%i\n",costLimit,iteration);
// Only continue if node needs expansion.
if( prune(state,costLimit, iteration) )
{
return;
}
// Expanding node
/* if( state == m_start)
{
return SEARCH_FOUND_SOLUTION; // Found the solution
}
*/
//NodeStatus childrenStatus = SEARCH_ALL_CHILDREN_IN_TT;
const OpList opList = state.findPredecessorOperators();
for( int i=0; i<opList.length; i++ )
{
state.apply( opList.ops[i] );
/*NodeStatus status =*/ dfsRecursive( state, costLimit, iteration );
state.unapply( opList.ops[i] );
}
return;// childrenStatus;
}
// return true if pruned
// return false if needs expansion
inline bool DFS::prune(
const SearchState & state,
const int & costLimit,
const int & iteration
)
{
if( state.cost > costLimit )
{ // Pruned by cost
//LOG("pruning by cost=%i limit=%i iteration=%i\n",state.cost,costLimit,iteration);
return true;
}
#ifdef USE_PERIMETER_DB
if( perimeterDb.pruneState(state.state, state.hash, state.cost, iteration) )
{
//LOG("pruning by PerimeterDb=%i limit=%i iteration=%i\n",state.cost,costLimit,iteration);
return true;
}
#endif
//LOG("updating entry in DB\n");
return false;
}
|
7a08e125c041acb76b966a7f9bf21cb6d78de703
|
4d33c090428407d599a4c0a586e0341353bcf8d7
|
/trunk/tutorial/Model_11_terrain_chunk_painter/renderImp.cpp
|
b030c0bc15e0573ff98bb25470fbdfc18b6ab362
|
[] |
no_license
|
yty/bud
|
f2c46d689be5dfca74e239f90570617b3471ea81
|
a37348b77fb2722c73d972a77827056b0b2344f6
|
refs/heads/master
| 2020-12-11T06:07:55.915476
| 2012-07-22T21:48:05
| 2012-07-22T21:48:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 832
|
cpp
|
renderImp.cpp
|
#include "renderImp.h"
RenderEngineImp::RenderEngineImp( HWND h )
{
_hwnd = h;
_render = NULL;
_initialized = false;
_width = 600;
_height = 800;
}
bool RenderEngineImp::create()
{
_initialized = true;
_render = Zen::createRenderEngine();
//
if (NULL == _render)
{
return false;
}
_render->getCreationParameters()->hFocusWindow = _hwnd;
_render->getCreationParameters()->fWidth = _width;
_render->getCreationParameters()->fHeight = _height;
if (!_render->create())
{
return false;
}
return true;
}
Zen::IRenderEngine* RenderEngineImp::getRenderEngine()
{
return _render;
}
void RenderEngineImp::destroy()
{
if (_render)
{
_render->destroy();
delete _render;
_render = NULL;
}
}
bool RenderEngineImp::isInitialized()
{
return _initialized;
}
|
03f26fe08ca270bea4d759759423d361a6d28e0a
|
fe6f1821c2b2a775bfb969b5c98b36cea6d0fe68
|
/src/GameState.h
|
77a69b12ae9e7be5f9604a40b3c8718bf9633fbe
|
[] |
no_license
|
qxzcode/cpp-q-learning
|
01da3af22fbd0b3c06558628f7db4d163c4651ba
|
aeddfc516a610732483e78d63432233a2944d740
|
refs/heads/master
| 2021-04-27T00:05:02.847729
| 2018-03-04T02:42:15
| 2018-03-04T02:42:15
| 123,748,112
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 500
|
h
|
GameState.h
|
#pragma once
class GameState {
public:
double myPaddleY, yourPaddleY;
double ballX, ballY;
double ballVX, ballVY;
double normBallVX() const { return normV(ballVX); }
double normBallVY() const { return normV(ballVY); }
static constexpr double MAX_V = 1.0;
static constexpr double normV(double v) {
return v/(2*MAX_V) + 0.5;
}
static constexpr double unnormV(double norm) {
return (norm - 0.5) * (2*MAX_V);
}
};
|
42fc4ad4609545a025d31139bbba4cf05ce2e476
|
e24086db8ad3f89357b0c0dc480c9e723b3e4f5c
|
/알고리즘 스터디(C++)/여름방학 스터디/여름방학 스터디/사다리 조작.cpp
|
444e5f8c1b392f6946925b15e93857f0613d7774
|
[] |
no_license
|
ckgusdh10/Portfolio
|
5b381d6d361ee32ffbaed66acb1264e45db53852
|
fdfb181d173344eee9f7b0c22901be2c1df310ff
|
refs/heads/master
| 2023-02-10T05:39:56.212279
| 2021-01-05T08:47:34
| 2021-01-05T08:47:34
| 184,263,169
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,210
|
cpp
|
사다리 조작.cpp
|
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int N, M, H;
int base[50][50];
int answer = 99;
int Down()
{
int xpos;
int ypos;
for (int i = 1; i < N + 1; ++i)
{
xpos = i;
ypos = 0;
for (int j = 0; j < H + 1; ++j) // 세로로 내려가야 하는 횟수
{
if (base[j][xpos] == 1)
{
++xpos;
}
else if (base[j][xpos - 1] == 1)
{
--xpos;
}
ypos += 1;
}
//cout << xpos << " " << ypos << endl;
if (xpos != i)
{
return 0;
}
}
return 1;
}
void LadderAdd(int x, int y, int count)
{
if (count > 3)
{
//answer = -1;
return;
}
if (Down())
{
if (count < answer)
{
answer = count;
}
//cout << count << endl;
return;
}
for (int i = x; i < H + 1; ++i)
{
for (int j = 1; j < N + 1; ++j)
{
if (base[i][j] == 1 || base[i][j - 1] == 1 || base[i][j + 1] == 1)
continue;
base[i][j] = 1;
LadderAdd(i, y, count + 1);
base[i][j] = 0;
}
}
}
int main()
{
cin >> N >> M >> H;
if (M > 0)
{
for (int i = 0; i < M; ++i)
{
int a, b;
cin >> a >> b;
base[a][b] = 1;
}
}
LadderAdd(1, 1, 0);
if (answer > 3)
answer = -1;
cout << answer << endl;
}
|
8f6c6ecbc98a916ff3573a4d84cec52e0f0554c0
|
d6b4bdf418ae6ab89b721a79f198de812311c783
|
/mdp/include/tencentcloud/mdp/v20200527/model/UnbindCdnDomainWithChannelRequest.h
|
914d4ed8d0f051d67c6213f1fb25d0e1a546b0d0
|
[
"Apache-2.0"
] |
permissive
|
TencentCloud/tencentcloud-sdk-cpp-intl-en
|
d0781d461e84eb81775c2145bacae13084561c15
|
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
|
refs/heads/master
| 2023-08-21T12:29:54.125071
| 2023-08-21T01:12:39
| 2023-08-21T01:12:39
| 277,769,407
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,419
|
h
|
UnbindCdnDomainWithChannelRequest.h
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_MDP_V20200527_MODEL_UNBINDCDNDOMAINWITHCHANNELREQUEST_H_
#define TENCENTCLOUD_MDP_V20200527_MODEL_UNBINDCDNDOMAINWITHCHANNELREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Mdp
{
namespace V20200527
{
namespace Model
{
/**
* UnbindCdnDomainWithChannel request structure.
*/
class UnbindCdnDomainWithChannelRequest : public AbstractModel
{
public:
UnbindCdnDomainWithChannelRequest();
~UnbindCdnDomainWithChannelRequest() = default;
std::string ToJsonString() const;
/**
* 获取Channel ID
* @return ChannelId Channel ID
*
*/
std::string GetChannelId() const;
/**
* 设置Channel ID
* @param _channelId Channel ID
*
*/
void SetChannelId(const std::string& _channelId);
/**
* 判断参数 ChannelId 是否已赋值
* @return ChannelId 是否已赋值
*
*/
bool ChannelIdHasBeenSet() const;
/**
* 获取CDN playback domain name
* @return CdnDomain CDN playback domain name
*
*/
std::string GetCdnDomain() const;
/**
* 设置CDN playback domain name
* @param _cdnDomain CDN playback domain name
*
*/
void SetCdnDomain(const std::string& _cdnDomain);
/**
* 判断参数 CdnDomain 是否已赋值
* @return CdnDomain 是否已赋值
*
*/
bool CdnDomainHasBeenSet() const;
private:
/**
* Channel ID
*/
std::string m_channelId;
bool m_channelIdHasBeenSet;
/**
* CDN playback domain name
*/
std::string m_cdnDomain;
bool m_cdnDomainHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_MDP_V20200527_MODEL_UNBINDCDNDOMAINWITHCHANNELREQUEST_H_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.