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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
db0f6f1e29862ea7500867a2286f332cb985aad9
|
6a4bb1498d9cb21d9ef4b3cb0b325c7013cf3a13
|
/include/geometry/line3.h
|
54ef9acd074a95a37e861ae794c391a9f3dbb8aa
|
[] |
no_license
|
argontus/3S3K3D
|
663fea3b79a152d2ca26cd05242d931cbe9c402f
|
6d5fb09546e7f70d038e8cf89ff102088c03258a
|
refs/heads/master
| 2021-01-01T16:56:10.674766
| 2011-04-21T14:37:38
| 2011-04-21T14:37:38
| 1,295,720
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,826
|
h
|
line3.h
|
/**
* @file geometry/line3.h
* @author Mika Haarahiltunen
*/
#ifndef GEOMETRY_LINE3_H_INCLUDED
#define GEOMETRY_LINE3_H_INCLUDED
#include <geometry/vector3.h>
/**
* Represents an unbounded 3D line.
*/
class Line3
{
public:
// compiler-generated destructor, copy constructor and assignment operator
// are fine
/**
* Default constructor, constructs an uninitialized line.
*/
Line3();
/**
* Constructor.
*
* @param point Point on the line.
* @param direction Line direction, should be unit length.
*/
Line3(const Vector3& point, const Vector3& direction);
/**
* Exchanges the contents of <code>*this</code> and <code>other</code>.
*
* @param other The object to swap contents with.
*/
void swap(Line3& other);
Vector3 point; ///< Point on the line.
Vector3 direction; ///< Line direction, should be unit length.
};
/**
* Calculates the distance between line <code>x</code> and point
* <code>q</code>.
*
* @param x A line.
* @param q A point.
*
* @return The distance between line <code>x</code> and point <code>q</code>.
*/
float distance(const Line3& x, const Vector3& q);
/**
* Calculates the squared distance between line <code>x</code> and point
* <code>q</code>.
*
* @param x A line.
* @param q A point.
*
* @return The squared distance between line <code>x</code> and point
* <code>q</code>.
*/
float sqrDistance(const Line3& x, const Vector3& q);
/**
* Calculates the point on line <code>x</code> that is closest to point
* <code>q</code>.
*
* @param x A line.
* @param q A point.
*
* @return The point on line <code>x</code> that is closest to point
* <code>q</code>.
*/
const Vector3 closestPoint(const Line3& x, const Vector3& q);
#endif // #ifndef GEOMETRY_LINE3_H_INCLUDED
|
14d9cb6e62272dbaef742c63bfb53fc2c23ce6ed
|
92c43f9c66816e3b5424b93aa27f15b081905549
|
/Part7/CommonDataClasses/CDCs/CDCStatusInfo/StatusInfo.h
|
b349331b1f70d4f4ef668199e9d323dab172d7f5
|
[] |
no_license
|
adirkuhn/lib-iec61850
|
fd30b032b35d3184c3f01be4f0a11a3560c7954f
|
7a35d901a299c94e49fd4dcb468a9d0e993b0709
|
refs/heads/master
| 2020-05-21T12:11:30.042930
| 2014-10-27T17:51:18
| 2014-10-27T17:51:18
| 32,832,932
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,451
|
h
|
StatusInfo.h
|
///////////////////////////////////////////////////////////
// StatusInfo.h
// Implementation of the Class StatusInfo
// Created on: 15-Apr-2014 2:52:47 PM
// Original author: adirkuhn
///////////////////////////////////////////////////////////
#if !defined(EA_4A27DFE3_7CAA_401a_97AB_BCA717C69897__INCLUDED_)
#define EA_4A27DFE3_7CAA_401a_97AB_BCA717C69897__INCLUDED_
#include "TimeStamp_ST.h"
#include "VISIBLE_STRING255_DC.h"
#include "UNICODE_STRING255_DC.h"
#include "C_PrimitiveCDC.h"
/**
* <font color="#141414">Abstract supertype for all status information CDC.</font>
*/
class StatusInfo : public C_PrimitiveCDC
{
public:
StatusInfo();
virtual ~StatusInfo();
/**
* Timestamp of the last change in one of the attributes representing the data
* value or the data quality, i.e., those which have 'dchg' or 'qchg'.
* For SPS, DPS, INS (and all its specialisations), ACT and ACD, see the
* description for their quality attribute 'q' - timestamp 't' applies to same
* attributes to which 'q' applies, and to 'q' itself. For BCR, 't' applies to
* 'actVal' and 'q'. For SEC, 't' applies to 'cnt'.
*/
TimeStamp_ST t;
/**
* Textual description of the data.
*/
VISIBLE_STRING255_DC d;
private:
/**
* Textual description of the data using unicode characters
*/
UNICODE_STRING255_DC dU;
};
#endif // !defined(EA_4A27DFE3_7CAA_401a_97AB_BCA717C69897__INCLUDED_)
|
9a4c5a0d73db26ef80fb8959671d003031301b37
|
9367ff3cc1ad4128e8c7e3559185b5ad86ab562e
|
/util/affinity.h
|
324c8ccb04409a308505b6ceb70a21aafbd7b382
|
[
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
mitdbg/treeline
|
b829b2e4dd5b114c03e59235391fd048a5244047
|
6a7c35fb38f5de93026d451a0ed2d3199de8ad7a
|
refs/heads/master
| 2023-07-23T17:12:13.313496
| 2023-07-18T15:08:05
| 2023-07-18T15:08:05
| 373,646,092
| 94
| 8
|
MIT
| 2023-07-18T15:08:07
| 2021-06-03T21:30:18
|
C++
|
UTF-8
|
C++
| false
| false
| 1,045
|
h
|
affinity.h
|
#pragma once
#include <pthread.h>
#include <cstdint>
#include <stdexcept>
#include <string>
namespace tl {
namespace affinity {
// Pins the current thread to core `core_id`, returning true if the pin
// succeeded.
static bool PinToCore(uint32_t core_id) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);
pthread_t thread = pthread_self();
return pthread_setaffinity_np(thread, sizeof(cpuset), &cpuset) == 0;
}
// Unpins the current thread, returning true if the unpin succeeded.
static bool Unpin() {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
pthread_t thread = pthread_self();
return pthread_setaffinity_np(thread, sizeof(cpuset), &cpuset) == 0;
}
// RAII-helper that pins the current thread to `core_id`.
class PinInScope {
public:
PinInScope(uint32_t core_id) {
if (!PinToCore(core_id)) {
throw std::runtime_error("Failed to pin thread to core " +
std::to_string(core_id));
}
}
~PinInScope() { Unpin(); }
};
} // namespace affinity
} // namespace tl
|
d0a04a2cd25e1ae0975ccf556d966c83ab277e49
|
e7a1a974fe647574483af63e40cd33c092e4d011
|
/Tools/BugReporterV2/macx_collectors/lib/src/ShellSystemProfile.cpp
|
c838c19e08800e564d6453633fab41eab232b842
|
[] |
no_license
|
blockspacer/Unity2018ShaderCompiler
|
cddc3d1fdab0c18bfd563a30888bbc18f914a809
|
4a3517261506550a7d8325f0335792e634ce0ba4
|
refs/heads/main
| 2023-04-16T13:53:13.812665
| 2021-03-19T12:27:39
| 2021-03-19T12:27:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 711
|
cpp
|
ShellSystemProfile.cpp
|
#include "ShellSystemProfile.h"
#include "shims/logical/IsEmpty.h"
#include "system_interplay/Shell.h"
#include <sstream>
#include <algorithm>
namespace ureport
{
namespace macosx
{
ShellSystemProfile::ShellSystemProfile(std::shared_ptr<Shell> shell)
: m_Shell(shell)
{
}
std::string ShellSystemProfile::GetData(const std::vector<DataType>& types) const
{
if (IsEmpty(types))
return "";
std::stringstream command;
command << "system_profiler";
std::for_each(types.begin(), types.end(), [&] (const DataType& type)
{
command << " " << type;
});
return m_Shell->ExecuteCommand(command.str());
}
}
}
|
6ff5446996dfac8548f0889d18d6b5eab554bafb
|
0ef4f71c8ff2f233945ee4effdba893fed3b8fad
|
/misc_microsoft_gamedev_source_code/misc_microsoft_gamedev_source_code/extlib/wwise/source/SoundEngine/SoundEngineProxy/Common/SoundProxyLocal.h
|
07f9f23d44a81ac553d435853618d17032c44bc2
|
[] |
no_license
|
sgzwiz/misc_microsoft_gamedev_source_code
|
1f482b2259f413241392832effcbc64c4c3d79ca
|
39c200a1642102b484736b51892033cc575b341a
|
refs/heads/master
| 2022-12-22T11:03:53.930024
| 2020-09-28T20:39:56
| 2020-09-28T20:39:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,633
|
h
|
SoundProxyLocal.h
|
/***********************************************************************
The content of this file includes source code for the sound engine
portion of the AUDIOKINETIC Wwise Technology and constitutes "Level
Two Source Code" as defined in the Source Code Addendum attached
with this file. Any use of the Level Two Source Code shall be
subject to the terms and conditions outlined in the Source Code
Addendum and the End User License Agreement for Wwise(R).
Version: v2008.2.1 Build: 2821
Copyright (c) 2006-2008 Audiokinetic Inc.
***********************************************************************/
#pragma once
#include "ParameterNodeProxyLocal.h"
#include "ISoundProxy.h"
class CAkSound;
class SoundProxyLocal : public ParameterNodeProxyLocal
, virtual public ISoundProxy
{
public:
SoundProxyLocal( AkUniqueID in_id );
virtual ~SoundProxyLocal();
// ISoundProxy members
virtual void SetSource( AkUInt32 in_PluginID, AkLpCtstr in_szFileName, const AkAudioFormat& in_AudioFormat );
virtual void SetSource( AkPluginID in_ID, // Plug-in id.
void * in_vpParam, // Pointer to a setup param block.
AkUInt32 in_ulSize );
virtual void SetSrcParam( AkPluginID in_ID, // Plug-in id.
AkPluginParamID in_ParamID, // Parameter id.
void * in_vpParam, // Pointer to a setup param block.
AkUInt32 in_ulSize );
virtual void Loop( bool in_bIsLoopEnabled, bool in_bIsLoopInfinite, AkInt16 in_sLoopCount, AkInt16 in_sCountModMin, AkInt16 in_sCountModMax );
virtual void IsZeroLatency( bool in_bIsZeroLatency );
};
|
7dc468644b83aae41dc16b959fb2949e2a52c57d
|
c8cc1f23e0326aec71ebd0c90783a1831343da5b
|
/src/lexer.cc
|
308be3ac0c2cc7e7d4cf823347a9a1eb6becc07c
|
[] |
no_license
|
jabraham17/StackMachine
|
ec43a1dd73f9ea3bd9f0880962a3cd362b9d953e
|
ae851109a5e6d52ab9fdde85f12458ad406f574f
|
refs/heads/master
| 2022-12-31T05:17:44.066199
| 2020-10-15T23:38:18
| 2020-10-15T23:38:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,967
|
cc
|
lexer.cc
|
//
// Created by Jacob Abraham on 8/28/20.
//
#include "lexer.h"
const std::string Token::types[] = {
"END_OF_FILE",
#define TOKEN(t) #t,
LEXER_TOKENS(TOKEN)
#undef TOKEN
"ERROR"
};
Token Lexer::getToken() {
//if we have tokens, get them,
if(!tokens.empty()) {
Token t = tokens.back();
tokens.pop_back();
return t;
}
/*std::cout << &input << std::endl;
std::string s;
input >> s;
std::cout << s << std::endl;
std::cout << "finding token" << std::endl;*/
//skip all spaces
skipWhiteSpace();
//ignore comments
while(isComment()) {
ignoreComment();
//after we ignore a comment, skip all whitespace
skipWhiteSpace();
}
//check for each element
if(isIDStart()) return getID();
if(isNUM()) return getNUM();
if(isSymbol()) return getSymbol();
std::cout << "c: " << (unsigned int)peekChar() << "fail to find token" << line_number << std::endl;
//if at this point we have not returned, its either eof or error
Token t("", TokenType::ERROR, line_number);
if(endOfInput()) {
std::cout << "EOF" << std::endl;
std::cout << "c: " << (unsigned int)getChar() << "fail to find token" << line_number << std::endl;
std::cout << "c: " << (unsigned int)getChar() << "fail to find token" << line_number << std::endl;
std::cout << "c: " << (unsigned int)getChar() << "fail to find token" << line_number << std::endl;
t.token_type = TokenType::END_OF_FILE;
}
return t;
}
Token Lexer::peek() {
Token t = getToken();
ungetToken(t);
return t;
}
TokenType Lexer::ungetToken(Token t) {
tokens.push_back(t);
return t.token_type;
}
//returns ID
Token Lexer::getID() {
Token t("", TokenType::ERROR, line_number);
if(isIDStart()) {
//get the start token
t.lexeme += getChar();
//get the rest of the num
while(!endOfInput() && isIDBody()) t.lexeme += getChar();
//now we have a valid token
t.token_type = TokenType::ID;
}
return t;
}
bool Lexer::isIDStart() {
char c = peekChar();
return isalpha(c) || c == '_';
}
bool Lexer::isIDBody() {
char c = peekChar();
return isalnum(c) || c == '_';
}
//returns NUM
Token Lexer::getNUM() {
Token t("", TokenType::ERROR, line_number);
while(!endOfInput() && isNUM()) t.lexeme += getChar();
//now we have a valid token
t.token_type = TokenType::NUM;
return t;
}
bool Lexer::isNUM() {
char c = peekChar();
return isdigit(c);
}
Token Lexer::getSymbol() {
Token t("", TokenType::ERROR, line_number);
//get the char
if(isSymbol()) {
char c = getChar();
switch(c) {
case '.': {
t.token_type = TokenType::DOT;
break;
}
case '@': {
t.token_type = TokenType::AT;
break;
}
}
}
return t;
}
bool Lexer::isSymbol() {
char c = peekChar();
return c == '.' || c == '@';
}
void Lexer::skipWhiteSpace() {
//get a new char
char c = getChar();
//while not eof and c is whitespace
while(!endOfInput() && isspace(c)) c = getChar();
//if we got one too many, put it back
if(!endOfInput()) ungetChar(c);
}
bool Lexer::isComment() {
char c = peekChar();
return c == '#';
}
void Lexer::ignoreComment() {
//get a new char
char c = getChar();
//while not eof and not end of line
while(!endOfInput() && c != '\n') c = getChar();
}
bool Lexer::endOfInput() {
if(!input_buffer.empty()) {
//make sure input buffer isnt just holding eof
if(input_buffer.front() == '\0') return true;
else return false;
}
else return input.eof();
}
char Lexer::peekChar() {
char c = getChar();
ungetChar(c);
return c;
}
void Lexer::ungetChar(char c) {
if(c != EOF) input_buffer.push_back(c);
if(c == '\n') line_number--;
}
char Lexer::getChar() {
//check for end of input
if(endOfInput()) return '\0';
char c;
if(!input_buffer.empty()) {
c = input_buffer.back();
input_buffer.pop_back();
}
else input.get(c);
if(c == '\n') line_number++;
return c;
}
|
6932784cd194eb5b431ca6c528d7ec17c4cda441
|
c1ea86f1c551ac343e2d3a1e5d7e96c5d92d1dd5
|
/v0.05/TcpConnection.cc
|
2da4071f3cd5ca7608babe05fbbb774b6a3cf880
|
[] |
no_license
|
itherunder/tiny-muduo
|
93e0f490c8b73d7306fac4037716e3b5f32d0e5f
|
fd08bfe068c9a5fe612e1009160e61d1ead70453
|
refs/heads/main
| 2023-07-10T10:29:47.265407
| 2021-08-25T07:18:49
| 2021-08-25T07:18:49
| 395,884,378
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,135
|
cc
|
TcpConnection.cc
|
#include "TcpConnection.h"
TcpConnection::TcpConnection(EventLoop* loop, int sockFd)
: sockFd_(sockFd)
, channel_(nullptr) {
channel_ = new Channel(loop, sockFd);
channel_->SetCallBack(this);
channel_->EnableReading();
cout << "[CONS] TcpConnection ..." << endl;
}
TcpConnection::~TcpConnection() {
if (channel_) {
delete channel_;
channel_ = nullptr;
}
cout << "[DECO] ~TcpConnection ..." << endl;
}
void TcpConnection::OnIn(int sockFd) {
cout << "[INFO] OnIn: " << sockFd << endl;
if (sockFd < 0)
ERR_EXIT("[ERRO] EPOLLIN sockFd < 0 error");
char buf[MAX_BUFFER] = {0};
int ret = read(sockFd, buf, sizeof(buf));
if (ret == -1)
ERR_EXIT("[ERRO] read");
if (ret == 0) {
cout << "[INFO] client closed" << endl;
close(sockFd);//记得关闭
channel_->Close();
return;//记得返回
}
cout << buf << endl;
ret = write(sockFd, buf, strlen(buf));
if (ret == -1)
ERR_EXIT("[ERRO] write");
if (ret < static_cast<int>(strlen(buf)))
ERR_EXIT("[ERRO] write not finish one time");
}
|
4d9c701a46e3b3c2495f9a868dfd6305dd38168f
|
ccf5db110a77c37cf7880caf8bc0f98b97e6da9d
|
/Practicals/Practical 07/Practical 7/Part 4/Main.cpp
|
1c2da06c64d3ed7c02c383559b9512a0ed382ce7
|
[] |
no_license
|
deweiliu/c-plus-plus-practicals
|
fef27f717487c18bf82be31feb83eb149b877a0f
|
d2b5a4c2b4395441f02e8fe360170edd4eef9644
|
refs/heads/master
| 2021-02-06T00:53:32.319653
| 2020-02-28T23:08:29
| 2020-02-28T23:08:29
| 243,855,501
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 447
|
cpp
|
Main.cpp
|
#include<iostream>
#include"LinkedList.h"
using namespace std;
void main() {
// an empty char list
LinkedList<char> clist;
// add 10 chars one after another
for (int i = 0; i < 10; i++)
clist + ('a' + i);
// get chars at variable positions
char *f = clist / 3;
if (f)
cout << "char at " << 3 << " is: " << *f << endl;
f = clist / 7;
if (f)
cout << "char at " << 7 << " is: " << *f << endl;
system("pause");
}
|
d17e34a088ccc312902aad8fb0c9f6873b106d8a
|
8646d753247f7dddea6d73d81422b1ec742c9f5a
|
/WSGeometry/src/bary_sinkhorn_armadillo.cpp
|
521bd3f2b76f0b4b8af3d2e575e7df8f7f985cac
|
[] |
no_license
|
akhikolla/updatedatatype-list4
|
24f5271c9d2807aca7dc8620b56eb96e740cd3c4
|
0a2a0a46e9fb6e066f30899c4cb3c016ba3a1504
|
refs/heads/master
| 2023-04-01T20:11:05.484102
| 2021-04-02T01:19:34
| 2021-04-02T01:19:34
| 352,124,197
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,288
|
cpp
|
bary_sinkhorn_armadillo.cpp
|
#include <RcppArmadillo.h>
#include <ctime>
#ifdef _OPENMP
# include <omp.h>
#endif
using namespace Rcpp;
using namespace std;
//[[Rcpp::plugins(openmp)]]
// [[Rcpp::depends("RcppArmadillo")]]
//[[Rcpp::export]]
Rcpp::List bary_sinkhorn_arma(arma::mat weights,arma::mat frechet,int maxIter, double lambda,arma::mat C,double thresh, int threads) {
int N = weights.n_cols;
int M = weights.n_rows;
#ifdef _OPENMP
omp_set_num_threads(threads);
#endif
arma::mat K= exp((-1*C)/lambda);
arma::mat KT=trans(K);
arma::mat b=arma::ones(M,N);
arma::mat a=arma::ones(M,N);
arma::mat p=arma::ones(M,N);
arma::mat pvec=arma::ones(M,1);
arma::mat pOld=arma::ones(M,1)*1000;
int iter=0;
double p_change=1000;
while ((iter<maxIter) && (p_change>thresh)){
//Rcout << iter+1<< ",";
//a update loop
a=weights/(K*b);
a=KT*a;
//p update loop
p=a;
pvec=pow(p.col(0),frechet(0));
for (int i=1;i<N;i++){
pvec=pvec%pow(p.col(i),frechet(i));
}
//update b loop
#pragma omp parallel for
for (int i=0;i<N;i++){
b.col(i)=pvec/a.col(i);
}
p_change=arma::accu(abs((pvec-pOld)));
pOld=pvec;
iter+=1;
}
//Rcout << "\n";
return Rcpp::List::create(Rcpp::Named("bary") =pvec,Rcpp::Named("iterations")=iter);
}
|
873aec5ee54fb3db7c688cfde5fb358e2088898e
|
70261d2c3111d9b44478a6b007b25e01bfaee138
|
/Desktop/C.P/Sublime Text 3/programs/mew3.cpp
|
cb18e06740299f8b9c7961774861bc8641a4c542
|
[] |
no_license
|
AmarShukla1/Competitive-Programming
|
05a16ddb1cbc5b3c6223ca589608388957a754c0
|
782f0c9f1382581185bc497614ec09a5af846085
|
refs/heads/master
| 2023-06-05T09:19:45.428801
| 2021-06-26T08:49:20
| 2021-06-26T08:49:20
| 296,541,849
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,224
|
cpp
|
mew3.cpp
|
//Tonight's the night and it is going to happen again and again.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mp make_pair
#define pb push_back
#define T ll t; cin>>t; while(t--)
#define mod 1000000007
#define f(n) for(ll i = 0;i<n;i++)
ll gcd(ll a,ll b){if(b==0){return a;}return gcd(b,a%b);}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n,m;cin>>n>>m;if(n>m){cout<<n-m;exit(0);}
//try to build a graph that reaches m from n.
//n->n*2.,n-1
vector<int>adj[4*m+1];
int vis[4*m+1];memset(vis,0,sizeof(vis));
for(int i=1;i<=2*m;i++)
{
adj[i].pb(i*2);
adj[i].pb(i-1);
}
//basically shortest path from n to m in this graph.
//bfs can be used to find it in unweighted graph
queue<int>q;
q.push(n);int level[4*m+1];memset(level,0,sizeof(level));
vis[n]=1;int it=0;
while(!q.empty())
{
int x=q.front();
q.pop();
for(auto v:adj[x])
{
if(vis[v]==0)
{
q.push(v);
level[v]=level[x]+1;
vis[v]=1;
}
}
if(vis[m]==1){break;}
}
cout<<level[m];
}
|
45c1cce1d4b3d5e9dbca5a5d41bf8ee7dba5cbda
|
d7906e84bda2bd386e074eab9f05479205e7d2a9
|
/Development/Source/Renderers/Common/GLGPUSharing.cpp
|
ace818c9695de5a9070ef58f9bc964b199c7822c
|
[
"BSD-3-Clause"
] |
permissive
|
jwwalker/Quesa
|
6fedd297a5a4dd1c21686e71bba3c68228f61724
|
1816b0772409c2faacdb70b40d5c02a55d643793
|
refs/heads/master
| 2023-07-27T16:36:55.757833
| 2023-07-06T23:55:10
| 2023-07-06T23:55:10
| 204,233,833
| 33
| 7
|
BSD-3-Clause
| 2023-09-09T23:17:36
| 2019-08-25T01:59:21
|
C++
|
UTF-8
|
C++
| false
| false
| 12,507
|
cpp
|
GLGPUSharing.cpp
|
/* NAME:
GLGPUSharing.cpp
DESCRIPTION:
Source for GPU shared data cache manager.
COPYRIGHT:
Copyright (c) 2007-2019, Quesa Developers. All rights reserved.
For the current release of Quesa, please see:
<https://github.com/jwwalker/Quesa>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
o Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
o 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.
o Neither the name of Quesa nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
___________________________________________________________________________
*/
//=============================================================================
// Include files
//-----------------------------------------------------------------------------
#include "GLGPUSharing.h"
#include <algorithm>
#include <vector>
#include <map>
#include <list>
//=============================================================================
// Internal types
//-----------------------------------------------------------------------------
namespace
{
typedef std::vector< TQ3GLContext > GLContextVec;
typedef std::map< TQ3Uns32, CQ3GPSharedCache* > CacheMap;
/*!
@class GPUSharingGroup
@abstract A sharing group, which records GL contexts that share data
and caches that hold that data.
*/
struct GPUSharingGroup
{
GPUSharingGroup();
GPUSharingGroup(
const GPUSharingGroup& inOther );
~GPUSharingGroup();
GPUSharingGroup& operator=( const GPUSharingGroup& inOther );
GLContextVec mGLContexts;
CacheMap mCacheMap;
};
typedef std::list< GPUSharingGroup > GroupList;
}
//=============================================================================
// Static variables
//-----------------------------------------------------------------------------
static GroupList* sGroupList = nullptr;
//=============================================================================
// Internal functions
//-----------------------------------------------------------------------------
#if 0//Q3_DEBUG
static void LogGroups()
{
if (sGroupList != nullptr)
{
Q3_MESSAGE_FMT("Log of sharing groups" );
for (const auto& group : *sGroupList)
{
Q3_MESSAGE_FMT("Sharing group %p", &group);
for (const auto& context : group.mGLContexts )
{
Q3_MESSAGE_FMT(" Member context %p", context);
}
}
Q3_MESSAGE_FMT("End Log of sharing groups" );
}
}
#else
#define LogGroups()
#endif
/*!
@function InitGroups
@abstract Create the vector of sharing groups if it has not already been
created.
*/
static void InitGroups()
{
if (sGroupList == nullptr)
{
sGroupList = new(std::nothrow) GroupList;
if (sGroupList == nullptr)
{
E3ErrorManager_PostError( kQ3ErrorOutOfMemory, kQ3True );
}
}
}
/*!
@function FindGroupFromContext
@abstract Find the sharing group containing a specific CL context.
@param inContext A GL context.
@param outGroupIterator Receives an iterator into sGroupList,
possibly sGroupList->end().
@param outWhichContext Receives an iterator to the context.
May be omitted if you do not need this.
@result True if we found a group containing the context.
*/
static bool FindGroupFromContext( TQ3GLContext inContext,
GroupList::iterator& outGroupIterator,
GLContextVec::iterator* outWhichContext = nullptr )
{
bool didFind = false;
InitGroups();
if (sGroupList != nullptr)
{
GroupList::iterator endList = sGroupList->end();
outGroupIterator = endList;
for (GroupList::iterator i = sGroupList->begin(); i != endList; ++i)
{
GLContextVec::iterator foundContextIt = std::find(
i->mGLContexts.begin(), i->mGLContexts.end(), inContext );
if (foundContextIt != i->mGLContexts.end())
{
if (outWhichContext != nullptr)
*outWhichContext = foundContextIt;
outGroupIterator = i;
didFind = true;
break;
}
}
}
return didFind;
}
GPUSharingGroup::GPUSharingGroup()
{
}
GPUSharingGroup::GPUSharingGroup(
const GPUSharingGroup& inOther )
: mGLContexts( inOther.mGLContexts )
, mCacheMap( inOther.mCacheMap )
{
}
GPUSharingGroup::~GPUSharingGroup()
{
for (CacheMap::iterator i = mCacheMap.begin(); i != mCacheMap.end(); ++i)
{
std::pair<const TQ3Uns32, CQ3GPSharedCache*>& thePair( *i );
delete thePair.second;
}
}
GPUSharingGroup& GPUSharingGroup::operator=(
const GPUSharingGroup& inOther )
{
GPUSharingGroup temp( inOther );
mGLContexts.swap( temp.mGLContexts );
mCacheMap.swap( temp.mCacheMap );
return *this;
}
//=============================================================================
// Public functions
//-----------------------------------------------------------------------------
/*!
@function GLGPUSharing_GetNextSharingBase
@abstract Get the next GL sharing group base.
@discussion When a GL context is being created, we usually want to
make it share data with previously created GL contexts.
The texture manager maintains a list of existing GL contexts
grouped by sharing. This function can be used to find one
context in each sharing group.
@param glBase nullptr to begin iteration, or a value returned
by a previous call to this function.
@result Next GL sharing context, or nullptr when there are no more.
*/
TQ3GLContext GLGPUSharing_GetNextSharingBase( TQ3GLContext glBase )
{
TQ3GLContext nextContext = nullptr;
try
{
InitGroups();
if (sGroupList != nullptr)
{
if (glBase == nullptr)
{
if (! sGroupList->empty())
{
Q3_ASSERT( ! sGroupList->front().mGLContexts.empty() );
nextContext = sGroupList->front().mGLContexts[ 0 ];
}
}
else
{
GroupList::iterator theGroupIt;
if (FindGroupFromContext( glBase, theGroupIt ))
{
++theGroupIt;
if (theGroupIt != sGroupList->end())
{
nextContext = theGroupIt->mGLContexts[ 0 ];
}
}
}
}
}
catch (...)
{
E3ErrorManager_PostError( kQ3ErrorOutOfMemory, kQ3True );
}
return nextContext;
}
CQ3GPSharedCache::~CQ3GPSharedCache()
{
}
/*!
@function GLGPUSharing_AddContext
@abstract After successfully creating a new context, call this function
to inform the GPU sharing manager.
@param newGLContext The newly created context.
@param sharingBase The existing context with which the new one
shares data, or nullptr.
*/
void GLGPUSharing_AddContext( TQ3GLContext newGLContext,
TQ3GLContext sharingBase )
{
InitGroups();
if (sGroupList != nullptr)
{
try
{
GPUSharingGroup* theGroup = nullptr;
// If there is a sharing base, look for an existing group containing it.
if (sharingBase != nullptr)
{
GroupList::iterator groupIt;
if (FindGroupFromContext( sharingBase, groupIt ))
{
theGroup = &*groupIt;
}
}
// If we do not have an existing group to use, make a new one.
if (theGroup == nullptr)
{
sGroupList->push_back( GPUSharingGroup() );
theGroup = &sGroupList->back();
}
if (theGroup != nullptr)
{
theGroup->mGLContexts.push_back( newGLContext );
}
}
catch (...)
{
E3ErrorManager_PostError( kQ3ErrorOutOfMemory, kQ3True );
}
}
LogGroups();
}
/*!
@function GLGPUSharing_RemoveContext
@abstract Inform the GPU sharing manager that a GL context has been destroyed.
@discussion The given GL context will be forgotten from its sharing group.
If there are no more contexts associated with the sharing group,
then the sharing group will be disposed.
@param deadGLContext A former GL context.
*/
void GLGPUSharing_RemoveContext( TQ3GLContext deadGLContext )
{
GroupList::iterator groupIt;
GLContextVec::iterator contextIt;
if (FindGroupFromContext( deadGLContext, groupIt, &contextIt ))
{
groupIt->mGLContexts.erase( contextIt );
if (groupIt->mGLContexts.empty())
{
sGroupList->erase( groupIt );
}
}
LogGroups();
}
/*!
@function GLGPUSharing_IsContextKnown
@abstract Test whether the sharing manager knows about an OpenGL context.
@param inGLContext A GL context.
@result True if we find a sharing group for the context.
*/
bool GLGPUSharing_IsContextKnown( TQ3GLContext inGLContext )
{
GroupList::iterator groupIt;
return FindGroupFromContext( inGLContext, groupIt );
}
/*!
@function GLGPUSharing_GetAllContexts
@abstract Get all the context pointers.
@param outContexts Receives all the contexts.
*/
void GLGPUSharing_GetAllContexts( std::vector<TQ3GLContext>& outContexts )
{
outContexts.clear();
if (sGroupList != nullptr)
{
for (const auto& group : *sGroupList)
{
for (const auto& context : group.mGLContexts)
{
outContexts.push_back( context );
}
}
}
}
/*!
@function GLGPUSharing_GetCache
@abstract Locate a cache within a sharing group.
@param glContext A GL context.
@param inCacheType key code for type of cache.
@result A cache pointer, or nullptr.
*/
CQ3GPSharedCache* GLGPUSharing_GetCache( TQ3GLContext glContext,
TQ3Uns32 inCacheType )
{
CQ3GPSharedCache* theCache = nullptr;
GroupList::iterator groupIt;
if (FindGroupFromContext( glContext, groupIt ))
{
CacheMap::iterator foundIt = groupIt->mCacheMap.find( inCacheType );
if (foundIt != groupIt->mCacheMap.end())
{
theCache = foundIt->second;
}
}
else
{
Q3_ASSERT( !"unknown GL context" );
}
return theCache;
}
/*!
@function GLGPUSharing_AddCache
@abstract Add a cache to a sharing group.
@discussion This should only be called if GLGPUSharing_GetCache has
returned nullptr. After this call, the sharing group takes
ownership of the cache, so do not delete the cache. it will
be deleted when the sharing group is deleted.
@param glContext A GL context.
@param inCacheType key code for type of cache.
@param inCache A cache.
*/
void GLGPUSharing_AddCache( TQ3GLContext glContext,
TQ3Uns32 inCacheType,
CQ3GPSharedCache* inCache )
{
Q3_ASSERT( GLGPUSharing_GetCache( glContext, inCacheType ) == nullptr );
GroupList::iterator groupIt;
if (FindGroupFromContext( glContext, groupIt ))
{
try
{
groupIt->mCacheMap[ inCacheType ] = inCache;
}
catch (...)
{
E3ErrorManager_PostError( kQ3ErrorOutOfMemory, kQ3True );
}
}
}
#if Q3_DEBUG
/*!
@function GLGPUSharing_IsCacheValid
@abstract Test whether a cache exists, for debugging.
@param inCacheType key code for type of cache.
@param inCache A cache.
@result True if the cache is found.
*/
bool GLGPUSharing_IsCacheValid(
CQ3GPSharedCache* inCache,
TQ3Uns32 inCacheType )
{
bool didFind = false;
if (sGroupList != nullptr)
{
for (GroupList::iterator i = sGroupList->begin();
i != sGroupList->end(); ++i)
{
CacheMap::iterator foundIt = i->mCacheMap.find( inCacheType );
if ( (foundIt != i->mCacheMap.end()) &&
(foundIt->second == inCache) )
{
didFind = true;
break;
}
}
}
return didFind;
}
#endif
|
fa22eb967e07d0e622e5f3d57fcea59992c1155a
|
f5c5afb6e8c4afc8bad23333de836fb7d607d971
|
/client/src/user_interface/login_mode.cpp
|
81178ed33a7bbf3247bb3f8e1d2783928809df4e
|
[
"MIT"
] |
permissive
|
dima1997/PORTAL_2D_copy
|
471fa199c2886a9e1e3b53f7796b8f4cd922099d
|
7618d970feded3fc05fda0c422a5d76a1d3056c7
|
refs/heads/master
| 2020-09-05T14:36:04.176004
| 2019-06-26T01:03:51
| 2019-06-26T01:03:51
| 220,131,617
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,480
|
cpp
|
login_mode.cpp
|
#include "../../includes/user_interface/login_mode.h"
#include "ui_LoginMode.h"
#include "../../includes/user_interface/login_new.h"
#include "../../includes/user_interface/login_join.h"
#include "../../includes/user_interface/login.h"
#include <connector/connector.h>
#include <connector/socket_exception.h>
#include <QWidget>
#include <QMessageBox>
#include <sstream>
LoginMode::LoginMode(
LoginNew & loginNew,
LoginJoin & loginJoin,
QWidget *parent)
: QWidget(parent),
loginNew(loginNew),
loginJoin(loginJoin),
connector(),
isOpen(true)
{
Ui::LoginMode loginMode;
loginMode.setupUi(this);
this->hide();
this->connect_events();
}
LoginMode::~LoginMode() = default;
/*
PRE: Recibe un connector (Connector &).
POST: Toma posesion del connector por movimiento.
*/
void LoginMode::set_connector(Connector & connector){
this->connector = std::move(connector);
}
void LoginMode::config_new_game() {
this->connector << (uint8_t) new_game;
// Recibe ids de mapas a elegir
std::vector<uint8_t> mapIds;
uint8_t mapsNumber;
connector >> mapsNumber;
for (uint8_t i = 0; i < mapsNumber; ++i) {
uint8_t mapId;
connector >> mapId;
mapIds.push_back(mapId);
}
this->loginNew.set_connector(this->connector);
this->loginNew.set_map_ids(mapIds);
this->loginNew.show();
this->loginJoin.close();
this->close();
((Login*)this->parentWidget())->adjustSize();
return;
}
void LoginMode::config_join_game() {
this->connector << (uint8_t) join_game;
uint8_t gameCount;
this->connector >> gameCount;
if (gameCount == 0){
QMessageBox qMsg;
qMsg.setWindowTitle("PORTAL");
std::stringstream err;
err << "No games in stock.\n";
qMsg.setText(QString(err.str().c_str()));
qMsg.setIcon(QMessageBox::Warning);
qMsg.exec();
((Login*)this->parentWidget())->close();
this->close();
return;
}
std::map<uint8_t,std::string> stockGames;
for (uint8_t i = 0; i < gameCount; ++i) {
uint8_t gameId;
this->connector >> gameId;
std::string gameName;
this->connector >> gameName;
std::pair<uint8_t,std::string> oneGame(gameId, gameName);
stockGames.insert(oneGame);
}
this->loginJoin.set_connector(this->connector);
this->loginJoin.set_game_ids(stockGames);
this->loginJoin.show();
this->loginNew.close();
this->close();
((Login*)this->parentWidget())->adjustSize();
return;
}
void LoginMode::connect_events() {
QPushButton* buttonNew = findChild<QPushButton*>("buttonNew");
QObject::connect(buttonNew, &QPushButton::clicked,
this, &LoginMode::config_new_game);
QPushButton* buttonJoin = findChild<QPushButton*>("buttonJoin");
QObject::connect(buttonJoin, &QPushButton::clicked,
this, &LoginMode::config_join_game);
QPushButton* buttonQuit = findChild<QPushButton*>("buttonQuit");
QObject::connect(buttonQuit, &QPushButton::clicked,
this, &LoginMode::quit);
}
void LoginMode::closeEvent(QCloseEvent *event){
if (! this->isOpen){
return;
}
try {
this->connector.shutDownRD();
this->connector.shutDownWR();
} catch (SocketException &error){}
event->accept();
}
void LoginMode::quit(){
((Login*)this->parentWidget())->quit();
this->close();
}
|
9096aa4be5aa73624ec06c7d878515ac9a3d979c
|
642c101b5c2b4345f0b3aa59ede3feb531528647
|
/soap/cmxDeviceServicecdsObject.h
|
a63349981bc37add7cb549577fe9e884c300a66b
|
[] |
no_license
|
yanggihoon/new_ds_compact
|
cd24df6641c9290205750c856d8dc6e66af6d5fe
|
e5bbe2b167e7d7ee021912074cb0cbdc5e011e54
|
refs/heads/master
| 2020-05-18T14:08:05.932963
| 2010-10-05T02:02:20
| 2010-10-05T02:02:20
| 848,550
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 796
|
h
|
cmxDeviceServicecdsObject.h
|
/* cmxDeviceServicecdsObject.h
Generated by gSOAP 2.7.6e from ds_intf.h
Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc. All Rights Reserved.
This part of the software is released under one of the following licenses:
GPL, the gSOAP public license, or Genivia's license for commercial use.
*/
#ifndef cmxDeviceServicecds_H
#define cmxDeviceServicecds_H
#include "cmxDeviceServiceH.h"
extern SOAP_NMAC struct Namespace cmxDeviceService_namespaces[];
namespace cmxDeviceService {
class cds : public soap
{ public:
cds()
{ soap_init(this); this->namespaces = cmxDeviceService_namespaces; };
virtual ~cds() { soap_destroy(this); soap_end(this); soap_done(this); };
virtual int serve() { return cmxDeviceService_serve(this); };
};
} // namespace cmxDeviceService
#endif
|
53e50fe0f1e7c5738c0080128b5e7375d8aefed1
|
7bbcb00315b7c87032cfc0fb800e5a27f0f2882e
|
/benchmarks/allStru3Benchmarks.cpp
|
f688ad6ea8e6e999fe019b3da9dcc8bfa03984ce
|
[] |
no_license
|
drjod/heatOption
|
2e6b2463bd29894e13deac2344ce8b764a419283
|
d11b24739e19c772150554eada2401030e3247cd
|
refs/heads/master
| 2020-04-01T22:18:04.980143
| 2018-11-18T22:52:21
| 2018-11-18T22:52:21
| 153,699,038
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,348
|
cpp
|
allStru3Benchmarks.cpp
|
#include "dbench.h"
#include "benchmarking_stru3.cpp"
int main()
{
//benchmarking::collection.add_function(benchmarking::matrixAdditionSubtractionChain, "matrixAdditionSubtractionChain", 1);
benchmarking::collection.add_function(benchmarking::matrixDoubleMultiplication, "matrixDoubleMultiplication", 3);
benchmarking::collection.add_function(benchmarking::matrixVectorMultiplication, "matrixVectorMultiplication", 3);
//benchmarking::collection.add_function(benchmarking::matrixVectorMultiplication, "matrixMatrixMultiplication", 1);
//benchmarking::collection.add_function(benchmarking::matrixVectorMultiplication, "functionOnMatrices", 1);
benchmarking::collection.add_function(benchmarking::scaleAndAddVectors, "scaleAndAddVectors", 1);
benchmarking::collection.add_function(benchmarking::scaleAndAddRows, "scaleAndAddRows", 1);
benchmarking::collection.add_function(benchmarking::vectorAddition, "VectorAddition", 10);
//benchmarking::collection.add_function(benchmarking::matrixMultiplication, "matrixMultiplication", 1);
//benchmarking::collection.add_function(benchmarking::doubleMatrixMultiplication, "doubleMatrixMultiplication", 2);
benchmarking::collection.add_function(benchmarking::gauss, "gauss", 3);
benchmarking::collection.add_function(benchmarking::bcgs, "bcgs", 3);
benchmarking::collection.run();
return 0;
}
|
7d4e3bd398799d3297868f61ece1f7aca788149d
|
f63706944c5a45b011453b792bc25908fa355af5
|
/server/qcatalogserverworker.h
|
d22548f68f8bd4712b2ffe0f30f2db5c540f264a
|
[] |
no_license
|
172270/QElectricPartsCatalog
|
7332451f3c2b6f2769f5c3e398a6526c9dafeb3e
|
5e64ed85b4407cef3956dcaa8e00ce54b172e2ce
|
refs/heads/master
| 2020-12-26T20:30:38.073889
| 2014-11-05T16:54:55
| 2014-11-05T16:54:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 687
|
h
|
qcatalogserverworker.h
|
#ifndef QCATALOGSERVERWORKER_H
#define QCATALOGSERVERWORKER_H
#include <QObject>
#include <QDebug>
#include <QDateTime>
#include "workercache.h"
#include "messagehandlerinterface.h"
class QCatalogServerWorker : public QObject
{
Q_OBJECT
public:
explicit QCatalogServerWorker(QSqlDatabase db, QObject *parent = 0);
~QCatalogServerWorker();
signals:
void responseAvalible(QByteArray res);
void messageCorrupted();
void unknownMessageType( MsgType );
public slots:
void readyRead(const QByteArray &ba);
private:
QMap<MsgType, MessageHandlerInterface*> *handlers;
WorkerCache *workerCache;
QByteArray *buf;
};
#endif // QCATALOGSERVERWORKER_H
|
484a0c8712e2c536ded387f26abc5893a104cfa1
|
aa35ac84695af6132dc8f1e8de46bb6868f58ceb
|
/ZPH3D/H3DEngine/include/FunctionalTest/TestCase/ReloadTest/ReloadBPT测试用例/ReloadBptTest_Mat.cpp
|
740d9e57945313a3012370fa739f04d5f539be78
|
[] |
no_license
|
spawn66336/H3DEngine_Demo
|
0e93432b95d7de91492cac9b73bc5bd6e27151e7
|
fb1fc076e646e35fcad84c3cde5b1e33c2d19935
|
refs/heads/master
| 2021-03-19T13:29:46.254202
| 2013-09-17T06:02:27
| 2013-09-17T06:02:27
| 12,609,723
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 10,672
|
cpp
|
ReloadBptTest_Mat.cpp
|
#include "../../FunctionalTest/TestCase/ReloadTest/ReloadTestBase.h"
//#define RELOAD_BPT_TEST_MAT_TWO _TWO_MAT
//bpt测试基类 针对bpt索引的mat
class ReloadBPTTest_Mat :public ReloadTestBase
{
public:
ReloadBPTTest_Mat(const char* casename):ReloadTestBase(casename){}
H3DI::IActor* m_pActor;
#ifdef RELOAD_BPT_TEST_MAT_TWO
H3DI::IActor* m_pActor1;
#endif
public:
virtual void GetMatLodAndPath()
{
filePath=Make_HippoTestResource_Path("Reload测试用例资源/ReloadBPT/117002001/");
matLod = GetLod();
}
virtual int GetLod(){return 0;}
virtual void CreatModel()
{
m_pActor = m_pScene->CreateActor(false,matLod);
m_pActor->SetBodyPart(string(dirPath+"117002001.bpt").c_str());
#ifdef RELOAD_BPT_TEST_MAT_TWO
m_pActor1=m_pScene->CreateActor(false,matLod);
m_pActor->SetPosition(H3DVec3(-1.5f,0.f,0.f));
m_pActor1->SetBodyPart(string(dirPath+"117002001.bpt").c_str());
m_pActor1->SetPosition(H3DVec3(1.5f,0.f,0.f));
#endif
}
virtual void ReloadModel()
{
m_pActor->ReloadAll();
}
};
/*备注
断言没有通过,
可能原因:
*/
/*测试逻辑
测试目的:测试bpt索引的mat,mat索引的贴图在reload前后引用计数情况,只有袜子有mat
加载一个actor ,lod0
穿上袜子,记录引用计数s1
渲染5S
修改mat索引的2D贴图
reloadall()
记录引用计数,并比较
*/
class ReloadMatBPTTest_2DTex1:public ReloadBPTTest_Mat
{
public:
ReloadMatBPTTest_2DTex1(const char* casename):ReloadBPTTest_Mat(casename){}
virtual string GetDdsPath(bool bBack)
{
if (bBack)
return string(dirPath+"Texture/backTex/117002001_d.dds");
else
return string(dirPath+"Texture/117002001_d.dds");
}
virtual void CopyTestFileOrDel(bool bcopy)
{
if (bcopy)
{
CopyFile(GetDdsPath(true).c_str(),GetDdsPath(false).c_str(),TRUE);
CopyFile(string(dirPath+"Texture/backTex/changed_d.dds").c_str(),string(dirPath+"Texture/changed_d.dds").c_str(),TRUE);
}
else
{
DeleteFile(GetDdsPath(false).c_str());
DeleteFile(string(dirPath+"Texture/back_d.dds").c_str());
CopyFile(GetDdsPath(true).c_str(),GetDdsPath(false).c_str(),TRUE);
}
}
virtual void RenameTestFile()
{
rename(GetDdsPath(false).c_str(),string(dirPath+"Texture/back_d.dds").c_str());
rename(string(dirPath+"Texture/changed_d.dds").c_str(),GetDdsPath(false).c_str());
}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBPTTest_2DTex1);
/*测试逻辑
lod1 创建一个actor,其他逻辑同上
*/
class ReloadMatBPTTest_2DTex2:public ReloadMatBPTTest_2DTex1
{
public:
ReloadMatBPTTest_2DTex2(const char* casename):ReloadMatBPTTest_2DTex1(casename){}
virtual int GetLod(){return 1;}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBPTTest_2DTex2);
/*测试逻辑
lod2 创建一个actor,其他逻辑同上
*/
class ReloadMatBPTTest_2DTex3:public ReloadMatBPTTest_2DTex1
{
public:
ReloadMatBPTTest_2DTex3(const char* casename):ReloadMatBPTTest_2DTex1(casename){}
virtual int GetLod(){return 2;}
virtual string GetDdsPath(bool bBack)
{
if (bBack)
return dirPath+"Texture/backTex/117002001_d_LOD2.dds";
else
return dirPath+"Texture/117002001_d_LOD2.dds";
}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBPTTest_2DTex3);
/*测试逻辑
lod0 创建一个actor,这里修改mask贴图,其他逻辑同测试1
*/
class ReloadMatBPTTest_Mask4:public ReloadBPTTest_Mat
{
public:
ReloadMatBPTTest_Mask4(const char* casename):ReloadBPTTest_Mat(casename){}
virtual void CopyTestFileOrDel(bool bcopy)
{
if (bcopy)
{
CopyFile(string(dirPath+"Texture/backTex/117002001_m.dds").c_str(),string(dirPath+"Texture/117002001_m.dds").c_str(),TRUE);
CopyFile(string(dirPath+"Texture/backTex/changed_m.dds").c_str(),string(dirPath+"Texture/changed_m.dds").c_str(),TRUE);
}
else
{
DeleteFile(string(dirPath+"Texture/117002001_m.dds").c_str());
DeleteFile(string(dirPath+"Texture/back_m.dds").c_str());
CopyFile(string(dirPath+"Texture/backTex/117002001_m.dds").c_str(),string(dirPath+"Texture/117002001_m.dds").c_str(),TRUE);
}
}
virtual void RenameTestFile()
{
rename(string(dirPath+"Texture/117002001_m.dds").c_str(),string(dirPath+"Texture/back_m.dds").c_str());
rename(string(dirPath+"Texture/changed_m.dds").c_str(),string(dirPath+"Texture/117002001_m.dds").c_str());
}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBPTTest_Mask4);
/*测试逻辑
lod1 创建一个actor,其他逻辑同上
*/
class ReloadMatBPTTest_Mask5:public ReloadMatBPTTest_Mask4
{
public:
ReloadMatBPTTest_Mask5(const char* casename):ReloadMatBPTTest_Mask4(casename){}
virtual int GetLod(){return 1;}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBPTTest_Mask5);
/*测试逻辑
lod2创建一个人物,其他逻辑同上
*/
class ReloadMatBPTTest_Mask6:public ReloadMatBPTTest_Mask4
{
public:
ReloadMatBPTTest_Mask6(const char* casename):ReloadMatBPTTest_Mask4(casename){}
virtual int GetLod(){return 2;}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBPTTest_Mask6);
/*测试逻辑
lod0 创建一个actor,这里使用cube贴图替换,其他逻辑同测试1
*/
class ReloadMatBPTTest_Cube7:public ReloadBPTTest_Mat
{
public:
ReloadMatBPTTest_Cube7(const char* casename):ReloadBPTTest_Mat(casename){}
virtual void CopyTestFileOrDel(bool bcopy)
{
if (bcopy)
{
CopyFile(string(dirPath+"Texture/backTex/hdr.dds").c_str(),string(dirPath+"Texture/hdr.dds").c_str(),TRUE);
CopyFile(string(dirPath+"Texture/backTex/changed_hdr.dds").c_str(),string(dirPath+"Texture/changed_hdr.dds").c_str(),TRUE);
}
else
{
DeleteFile(string(dirPath+"Texture/hdr.dds").c_str());
DeleteFile(string(dirPath+"Texture/back_hdr.dds").c_str());
CopyFile(string(dirPath+"Texture/backTex/hdr.dds").c_str(),string(dirPath+"Texture/hdr.dds").c_str(),TRUE);
}
}
virtual void RenameTestFile()
{
rename(string(dirPath+"Texture/hdr.dds").c_str(),string(dirPath+"Texture/back_hdr.dds").c_str());
rename(string(dirPath+"Texture/changed_hdr.dds").c_str(),string(dirPath+"Texture/hdr.dds").c_str());
}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBPTTest_Cube7);
/*测试逻辑
lod1 加载一个actor,其他逻辑同上
*/
class ReloadMatBPTTest_Cube8:public ReloadMatBPTTest_Cube7
{
public:
ReloadMatBPTTest_Cube8(const char* casename):ReloadMatBPTTest_Cube7(casename){}
virtual int GetLod(){return 1;}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBPTTest_Cube8);
/*测试逻辑
lod2加载一个actor,其他逻辑同上
*/
class ReloadMatBPTTest_Cube9:public ReloadMatBPTTest_Cube7
{
public:
ReloadMatBPTTest_Cube9(const char* casename):ReloadMatBPTTest_Cube7(casename){}
virtual int GetLod(){return 2;}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBPTTest_Cube9);
/*测试逻辑
lod0 加载一个actor,同时修改三种贴图,比较前后引用计数
其他逻辑同测试1
*/
class ReloadMatBlendBPTTest10:public ReloadBPTTest_Mat
{
public:
ReloadMatBlendBPTTest10(const char* casename):ReloadBPTTest_Mat(casename){}
virtual string GetDdsPath(bool bBack)
{
if (bBack)
return string(dirPath+"Texture/backTex/117002001_d.dds");
else
return string(dirPath+"Texture/117002001_d.dds");
}
virtual void CopyTestFileOrDel(bool bcopy)
{
if (bcopy)
{
CopyFile(GetDdsPath(true).c_str(),GetDdsPath(false).c_str(),TRUE);
CopyFile(string(dirPath+"Texture/backTex/changed_d.dds").c_str(),string(dirPath+"Texture/changed_d.dds").c_str(),TRUE);
CopyFile(string(dirPath+"Texture/backTex/117002001_m.dds").c_str(),string(dirPath+"Texture/117002001_m.dds").c_str(),TRUE);
CopyFile(string(dirPath+"Texture/backTex/changed_m.dds").c_str(),string(dirPath+"Texture/changed_m.dds").c_str(),TRUE);
CopyFile(string(dirPath+"Texture/backTex/hdr.dds").c_str(),string(dirPath+"Texture/hdr.dds").c_str(),TRUE);
CopyFile(string(dirPath+"Texture/backTex/changed_hdr.dds").c_str(),string(dirPath+"Texture/changed_hdr.dds").c_str(),TRUE);
}
else
{
DeleteFile(GetDdsPath(false).c_str());
DeleteFile(string(dirPath+"Texture/back_d.dds").c_str());
CopyFile(GetDdsPath(true).c_str(),GetDdsPath(false).c_str(),TRUE);
DeleteFile(string(dirPath+"Texture/117002001_m.dds").c_str());
DeleteFile(string(dirPath+"Texture/back_m.dds").c_str());
CopyFile(string(dirPath+"Texture/backTex/117002001_m.dds").c_str(),string(dirPath+"Texture/117002001_m.dds").c_str(),TRUE);
DeleteFile(string(dirPath+"Texture/hdr.dds").c_str());
DeleteFile(string(dirPath+"Texture/back_hdr.dds").c_str());
CopyFile(string(dirPath+"Texture/backTex/hdr.dds").c_str(),string(dirPath+"Texture/hdr.dds").c_str(),TRUE);
}
}
virtual void RenameTestFile()
{
rename(GetDdsPath(false).c_str(),string(dirPath+"Texture/back_d.dds").c_str());
rename(string(dirPath+"Texture/changed_d.dds").c_str(),GetDdsPath(false).c_str());
rename(string(dirPath+"Texture/117002001_m.dds").c_str(),string(dirPath+"Texture/back_m.dds").c_str());
rename(string(dirPath+"Texture/changed_m.dds").c_str(),string(dirPath+"Texture/117002001_m.dds").c_str());
rename(string(dirPath+"Texture/hdr.dds").c_str(),string(dirPath+"Texture/back_hdr.dds").c_str());
rename(string(dirPath+"Texture/changed_hdr.dds").c_str(),string(dirPath+"Texture/hdr.dds").c_str());
}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBlendBPTTest10);
/*测试逻辑
lod1 加载一个actor,其他逻辑同测试1
*/
class ReloadMatBlendBPTTest11:public ReloadMatBlendBPTTest10
{
public:
ReloadMatBlendBPTTest11(const char* casename):ReloadMatBlendBPTTest10(casename){}
virtual int GetLod(){return 1;}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBlendBPTTest11);
/*测试逻辑
lod2 加载一个actor,其他逻辑同测试1
*/
class ReloadMatBlendBPTTest12:public ReloadMatBlendBPTTest10
{
public:
ReloadMatBlendBPTTest12(const char* casename):ReloadMatBlendBPTTest10(casename){}
virtual int GetLod(){return 2;}
virtual string GetDdsPath(bool bBack)
{
if (bBack)
return dirPath+"Texture/backTex/117002001_d_LOD2.dds";
else
return dirPath+"Texture/117002001_d_LOD2.dds";
}
private:
static HippoTestCaseBase* const testcase_;
};
ADD_TESTCASE("RELOAD_BPT_TEST_MAT",ReloadMatBlendBPTTest12);
|
6e86174b6b31e90d83547126dfacfcdda695d6be
|
439c92b465279d70c068548b197f0ea4a5f565fb
|
/sphere.cc
|
46a3d72852baea815759c2e6682a6d10eda0eb63
|
[] |
no_license
|
Li0nMo0se/ray_tracer
|
0cf1d0a96ca5c026d4d9987229e331efc3919f42
|
c4e5c23e1526a25bf1102451122d3561820db15d
|
refs/heads/main
| 2023-04-15T20:27:10.109468
| 2021-04-16T15:11:51
| 2021-04-16T15:11:51
| 342,230,768
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,123
|
cc
|
sphere.cc
|
#include "sphere.hh"
#include <cmath>
namespace scene
{
Sphere::Sphere(const space::Point3& origin,
const float radius,
const std::shared_ptr<TextureMaterial>& texture)
: Object(texture)
, origin_(origin)
, radius_(radius)
{
}
static std::optional<float>
solve_quadratic(const float a, const float b, const float c)
{
float delta = b * b - 4 * a * c;
if (delta < 0)
return std::nullopt;
if (delta == 0)
return (-b / (2 * a));
// else delta > 0
float t0 = (-b + std::sqrt(delta)) / (2 * a);
float t1 = (-b - std::sqrt(delta)) / (2 * a);
if (t0 < 0 && t1 < 0)
return std::nullopt;
else if (t0 < 0)
return t1;
else if (t1 < 0)
return t0;
else // t1 and t0 positive
return t0 < t1 ? t0 : t1;
}
std::optional<space::IntersectionInfo>
Sphere::intersect(const space::Ray& ray) const
{
// P = O + tD
// If sphere centered at (0, 0, 0)
// ||P|| = R
// R^2 = P^2
// P^2 - R^2 = 0
// (O + tD)^2 - R^2 = 0
// O^2 + 2ODt + D^2t^2 - R^2 = 0
// D^2t^2 + 2ODt + (O^2 - R^2) = 0
// a = D.D == ||D||^2
// b = 2* 0.D
// c = O^2 - R^2
// If sphere centered at C
// a = D.D == ||D||^2
// b = 2* (O - C).D
// c = (O - C)^2 - R^2
const space::Point3& ray_origin = ray.origin_get();
const space::Vector3& ray_direction = ray.direction_get();
const space::Vector3 L = ray_origin - this->origin_;
const float a = ray_direction.dot(ray_direction);
const float b = 2 * ray_direction.dot(L);
const float c = L.dot(L) - radius_ * radius_;
const std::optional<float> t_res = solve_quadratic(a, b, c);
if (!t_res.has_value() || t_res.value() < space::T_MIN)
return std::nullopt;
// Has intersected
return space::IntersectionInfo(t_res.value(), *this);
}
space::Vector3
Sphere::normal_get(const space::Ray&,
const space::IntersectionInfo& intersection) const
{
// p is the intersection point
return (intersection.intersection_get() - origin_).normalized();
}
} // namespace scene
|
422d42ff6c56adcccdd5b79282ac5af1b8d7f317
|
d278740afe97cf0b96e2083c237c0eadb8a24ee6
|
/Surface.cpp
|
b55105036f47203a28dd0c701d309ae3d4e204b3
|
[] |
no_license
|
jacobingalls1/SimplePlatformer
|
9ffe10c64e5299959e76d00ea3010405cfeef0b0
|
cbcdea5528d9f24199f5aa94c787e75ae6a58615
|
refs/heads/master
| 2020-12-24T03:20:30.430605
| 2020-01-31T05:00:51
| 2020-01-31T05:00:51
| 237,363,619
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,222
|
cpp
|
Surface.cpp
|
//
// Created by Ophiuchus on 6/28/2018.
//
#include "Surface.h"
#include <iostream>
using namespace std;
bool fComp(float a, float b) {
return abs(a - b) < .1;
}
bool ccw(Vector2f a, Vector2f b, Vector2f c) {
return (c.y-a.y)*(b.x-a.x) > (b.y-a.y)*(c.x-a.x);
}
bool betwixt(Vector2f a, Vector2f b, Vector2f c, Vector2f d) {
return ccw(a, c, d) != ccw(b, c, d) && ccw(a, b, c) != ccw(a, b, d);
}
float len(Vector2f a, Vector2f b) {
return (float)sqrt(pow((a.x - b.x), 2) + pow((a.y - b.y), 2));
}
Surface::Surface(Vector2f *vertIn, float friction, float bounce) {
for (int i = 0; i < 2; i++) {
vertices[i] = vertIn[i];
}
slope = (vertIn[0].x - vertIn[1].x) / (vertIn[0].y - vertIn[1].y);
this->friction = friction;
this->bounce = bounce;
}
Surface::Surface(Vector2f a, Vector2f b, float friction, float bounce) {
vertices[0] = a;
vertices[1] = b;
this->friction = friction;
this->bounce = bounce;
}
bool Surface::collision(Vector2f init, Vector2f target) {
return betwixt(init, target, vertices[0], vertices[1]);
}
float Surface::getSlope() {
return slope;
}
Vector2f Surface::getFirst() {
return vertices[0];
}
Vector2f Surface::getSecond() {
return vertices[1];
}
RectangleShape Surface::getRect() {
RectangleShape rect;
float len = length();
rect.setSize(Vector2f(len, 10));
// rect.rotate((float)asin(((-vertices[0].y + vertices[1].y) / len) / 3.141592 * 180));
return rect;
}
float Surface::getFrict() {
return friction;
}
float Surface::getBounce() {
return bounce;
}
Vector2f Surface::getPos() {
if (vertices[0].x < vertices[1].x or vertices[0].y < vertices[1].y) {
return vertices[0];
} else {
return vertices[1];
}
}
bool Surface::isOnSurface(Vector2f in) {
}
Vector2f Surface::onSurface(Vector2f a, Vector2f b) {
}
Vector2f Surface::lenVect() {
return Vector2f(abs(vertices[1].y - vertices[0].y), abs(vertices[1].x - vertices[0].x));
}
float Surface::length() {
return len(vertices[0], vertices[1]);
}
float Surface::xLen() {
return abs(vertices[0].x - vertices[1].x);
}
float Surface::yLen() {
return abs(vertices[0].y - vertices[1].y);
}
|
ee4f6c70634c46376f8475e08bb13bf4abc8f64b
|
1b9a32ea5f2492fd3512965f92e0f057b0528d33
|
/longest_arithematic_sequence.cpp
|
afd0b9544917928b0b248106eede6e853c67b6cb
|
[] |
no_license
|
shivangigoel1302/leetcode_solutions
|
a459a4279ffcfa889cf1fe0e8eb681e4e79186b6
|
3373f9710bd797bcda5cbd86958e8914ba9e2a15
|
refs/heads/master
| 2023-08-23T04:18:26.678630
| 2021-11-01T14:57:21
| 2021-11-01T14:57:21
| 274,206,300
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 457
|
cpp
|
longest_arithematic_sequence.cpp
|
class Solution {
public:
int longestArithSeqLength(vector<int>& A) {
int n = A.size();
vector<vector<int>>dp(n,vector<int>(2000,0));
int ans = INT_MIN;
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < i ; j++){
int diff = A[j] - A[i] + 1000;
dp[i][diff] = max(2,dp[j][diff] +1);
ans = max(ans,dp[i][diff]);
}
}
return ans;
}
};
|
d3a8a329563bfda368e276becca87a9dc4d9e65f
|
d86c053fed8395e313083f8b1f9a52ddabe29a1f
|
/class.cpp
|
377d39d68de0db3fb177e17fb191dcbb859e3867
|
[] |
no_license
|
foxxy777/manipulate-private-data-of-father-class
|
b85c17faeee6fa6632bcb358bdea23a8a2b23ee8
|
67f9f7d626d2016e4dad2297a685b896fddc6beb
|
refs/heads/master
| 2023-01-02T07:14:56.410615
| 2020-10-28T02:08:54
| 2020-10-28T02:08:54
| 307,882,229
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 793
|
cpp
|
class.cpp
|
#include "class.h"
Cat::Cat(int weight_value, int length_value)//默认参数写在h的声明里,而不是写在这
{
weight = weight_value;
length = length_value;
cout << "constructor of cat weight" << weight << endl;
cout << "constructor of cat length" << length << endl;
}
void Cat::setweight(int weight_value)//所以说父类的private参数实际上也被继承了,也在子类上开辟了空间,子类可以通过调用父类的public函数来调整的
{
weight = weight_value;
cout << "changed weight = "<< weight << endl;
}
WhiteCat::WhiteCat( string color_value)
{
color = color_value;
//weight = 10;//子类自己里面并没有weight这个变量,就只有一个父类空间里的weight,可以通过用父类的public函数来调整
}
|
9ad07217c87e31829d08a1995018adc9084abee3
|
bd2958b7c96cac4c330d4b703e8ea78c7868e8a3
|
/thread.cpp
|
ea84cc970c95df65e45a14f3b6f3c08ed84d498e
|
[] |
no_license
|
krajeshshau/CPP
|
bf0d3a001e466f1d50ffc3a8ca045783a522a1c0
|
99cdcfb7922d2f16ef57791b8b91a7b015d74f80
|
refs/heads/master
| 2022-12-16T03:43:01.768723
| 2020-09-19T14:44:39
| 2020-09-19T14:44:39
| 287,069,832
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,575
|
cpp
|
thread.cpp
|
#include <iostream>
#include <thread>
#include <algorithm>
#include<vector>
#include<mutex>
#include <condition_variable>
#include<future>
using namespace std;
class WorkerThread {
int data;
static std::mutex mut;
static condition_variable cv;
static int count;
static int flag;
public:
WorkerThread(/*int _data = 0*/)/*:data(_data)*/{ data = 0; count = 0;
}
void operator()()
{
std::cout<<"Worker Thread "<<std::this_thread::get_id()<<" is Executing"<<std::endl;
}
void display(int _i){
cout<<"Assigning pointer to member function of a class as thread function:"<<_i<<endl;
}
static void print(string const &str){
cout<<"Starting thread with static member function "<<str<<endl;
}
void set(int _data){
lock_guard<mutex> lg(mut);
data+= _data;
}
void get(){
lock_guard<mutex> lg(mut);
cout<<"data "<<data<<endl;
}
void increment_1(){
//while(count != 10){
do{
unique_lock<mutex> lg(mut);
++count;
cv.notify_one();
flag = true;
lg.unlock();
//cout<<this_thread::get_id()<<" "<<count<<endl;
cout<<"increment_1 "<<count<<endl;
//this_thread::sleep_for(chrono::milliseconds(2));
}while(count != 10);
}
void increment_2(){
//while(count != 10){
do{
unique_lock<mutex> lg(mut);
cv.wait(lg, [](){ return flag; });
++count;
flag = false;
lg.unlock();
//cout<<this_thread::get_id()<<" "<<count<<endl;
cout<<"increment_2 "<<count<<endl;
//this_thread::sleep_for(chrono::milliseconds(2));
}while(count != 10);
}
};
int WorkerThread::count = 0;
mutex WorkerThread::mut;
condition_variable WorkerThread:: cv;
int WorkerThread::flag = false;
void function_pointer ()
{
cout << "thread function_pointer" << endl;
}
void call_back(int _i, string _str){
++_i;
_str = "Rakesh";
cout<<"From thread "<<_i<<_str<<endl;
}
class threadRAII{
thread &th;
public:
threadRAII(thread &_th):th(_th){
}
~threadRAII(){
if(th.joinable()){
//th.detach();
th.join();
}
}
};
/*void future_promise_callback_fun(promise<int> * _promiseObj){
cout<<"inside thread setting value"<<endl;
_promiseObj->set_value(100);
}
*/
void future_promise_callback_fun(promise<int> * _promiseObj1,promise<int> * _promiseObj2){
cout<<"inside thread setting value"<<endl;
_promiseObj1->set_value(100);
_promiseObj2->set_value(200);
}
int main() {
/* thread thfp(function_pointer);
thfp.join();
*/
/* thread thObjectfun((WorkerThread()));
thObjectfun.join();
*/
/* thread thLambda([](){
cout<<"thread lambda"<<endl;
});
thLambda.join();
*/
/* vector<thread> threadList;
for(int i = 0; i < 5; i++){
threadList.push_back( thread( WorkerThread() ) );
}
for(auto it = threadList.begin(); it != threadList.end(); ++it){
it->join();
}
*/
/* int i{10};
string str{"Rajesh"};
thread th(call_back, i, str);
threadRAII raii(ref(th));
cout<<"From main "<<i<<str<<endl;
*/
//this_thread::sleep_for(chrono::milliseconds(10));
//Assigning pointer to member function of a class as thread function:
/* WorkerThread wth;
int i = 10;
thread th(&WorkerThread::display,&wth,i);
th.join();
*/
/* thread th(&WorkerThread::print,"Rajesh");
th.join();
*/
/* WorkerThread wt;
thread thget(&WorkerThread::get, &wt);
thread thset(&WorkerThread::set,&wt, 100);
thget.join();
thset.join();
*/
/* WorkerThread wt1;
WorkerThread wt2;
thread th1(&WorkerThread::increment_1, &wt1);
thread th2(&WorkerThread::increment_2, &wt2);
th1.join();
th2.join();
*/
/* promise<int> promiseObj;
future<int> futureObj = promiseObj.get_future();
thread th(future_promise_callback_fun, &promiseObj);
cout<<"value set through promise "<<futureObj.get();
th.join();
*/
/* promise<int> promiseObj1,promiseObj2;
future<int> futureObj1 = promiseObj1.get_future();
future<int> futureObj2 = promiseObj2.get_future();
thread th(future_promise_callback_fun, &promiseObj1, &promiseObj2);
cout<<"value set through promise "<<futureObj1.get()<<endl;
cout<<"value set through promise "<<futureObj2.get()<<endl;
th.join();
*/
return 0;
}
|
5dc0b39c1904f64317c4c8da4e35b21af8adce28
|
50486ebe8b4e6bd44eb70487d2725f5424504b71
|
/XCodeDemos/SingleThreadServer/SingleThreadServer/main.cpp
|
0813ee1af4fac1348e1e5fc3c8475b9b53a60428
|
[] |
no_license
|
Iann1978/Explore-to-Server
|
2c3d520ac13515d31201185766d1d1482a586eb8
|
c7cf30dcdd3d572e9b6a98caae90339461d28ed8
|
refs/heads/master
| 2020-05-17T22:39:34.881040
| 2019-04-30T02:08:57
| 2019-04-30T02:08:57
| 184,008,933
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 496
|
cpp
|
main.cpp
|
//
// main.cpp
// SingleThreadServer
//
// Created by iann on 2019/4/29.
// Copyright © 2019 iann. All rights reserved.
//
#include "Server.hpp"
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
int error = 0;
Server &server = Server::ins;
if (error = server.CreateSocket())
{
return -1;
}
if (error = server.Run())
{
return -1;
}
return error;
}
|
e49f2234cd2761fa6c4c0dc8e5b48fd3ca5e1ca4
|
71b91eb68d95fbeb48e32fa90db9fd0697f05bbb
|
/purepad/evalview.cpp
|
f8dfe1724d6505c0b5cac68512f2ede4835d2da0
|
[] |
no_license
|
agraef/pure-lang
|
2aaa3e08440b386d92f63b4da3e85450b7c5e81c
|
01603c49f8aab295989e2e239568373c3b016298
|
refs/heads/master
| 2022-10-01T05:05:21.484845
| 2022-08-07T22:24:27
| 2022-08-07T22:24:27
| 86,244,642
| 292
| 23
| null | 2022-09-20T03:35:21
| 2017-03-26T15:49:16
|
C++
|
UTF-8
|
C++
| false
| false
| 15,172
|
cpp
|
evalview.cpp
|
// EvalView.cpp : implementation of the CEvalView class
//
#include "stdafx.h"
#include "qpad.h"
#include "gotodlg.h"
#include "tabstopdlg.h"
#include "MainFrm.h"
#include "qpadDoc.h"
#include "EvalView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CEvalView
IMPLEMENT_DYNCREATE(CEvalView, CEditView)
BEGIN_MESSAGE_MAP(CEvalView, CEditView)
//{{AFX_MSG_MAP(CEvalView)
ON_CONTROL_REFLECT(EN_CHANGE, OnChange)
ON_WM_CHAR()
ON_UPDATE_COMMAND_UI(ID_EDIT_GOTO, OnUpdateEditGoto)
ON_COMMAND(ID_VIEW_FONT, OnViewFont)
ON_COMMAND(ID_VIEW_TABSTOPS, OnViewTabstops)
ON_WM_CREATE()
ON_COMMAND(ID_HIST_FIRST, OnHistFirst)
ON_COMMAND(ID_HIST_LAST, OnHistLast)
ON_COMMAND(ID_HIST_NEXT, OnHistNext)
ON_COMMAND(ID_HIST_PREV, OnHistPrev)
ON_COMMAND(ID_HIST_SEARCH_NEXT, OnHistSearchNext)
ON_COMMAND(ID_HIST_SEARCH_PREV, OnHistSearchPrev)
ON_COMMAND(ID_EDIT_GOTO, OnEditGoto)
//}}AFX_MSG_MAP
// update view when input from interpreter is available
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CEditView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CEditView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CEditView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CEvalView construction/destruction
CEvalView::CEvalView() : m_hist(CMainFrame::m_nHistSize)
{
// TODO: add construction code here
m_pGotoDialog = new CGotoDlg;
m_nTabStops = CMainFrame::m_nLogTabStops;
m_strPMark = "";
m_hist.Read(CMainFrame::m_strHistFile);
}
CEvalView::~CEvalView()
{
m_hist.Write(CMainFrame::m_strHistFile);
delete m_pGotoDialog;
}
BOOL CEvalView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CEditView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CEvalView drawing
void CEvalView::OnDraw(CDC* pDC)
{
CQpadDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
}
/////////////////////////////////////////////////////////////////////////////
// CEvalView printing
BOOL CEvalView::OnPreparePrinting(CPrintInfo* pInfo)
{
return DoPreparePrinting(pInfo);
}
void CEvalView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo)
{
CEditView::OnBeginPrinting(pDC, pInfo);
}
void CEvalView::OnEndPrinting(CDC* pDC, CPrintInfo* pInfo)
{
CEditView::OnEndPrinting(pDC, pInfo);
}
/////////////////////////////////////////////////////////////////////////////
// CEvalView diagnostics
#ifdef _DEBUG
void CEvalView::AssertValid() const
{
CEditView::AssertValid();
}
void CEvalView::Dump(CDumpContext& dc) const
{
CEditView::Dump(dc);
}
CQpadDoc* CEvalView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CQpadDoc)));
return (CQpadDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CEvalView message handlers
void CEvalView::OnActivateView(BOOL bActivate, CView *pActivateView, CView *pDeactiveView)
{
CEditView::OnActivateView(bActivate, pActivateView, pDeactiveView);
}
void CEvalView::OnChange()
{
}
void CEvalView::OnUpdateEditGoto(CCmdUI* pCmdUI)
{
pCmdUI->Enable(GetWindowTextLength());
}
void CEvalView::OnEditGoto()
{
if(m_pGotoDialog->DoModal() != IDOK)
return;
if(m_pGotoDialog->m_nLineNum < 1)
{
CString s1;
s1.LoadString(IDS_INVALID_LINENUM);
AfxMessageBox(s1);
return;
}
CEdit &edit = GetEditCtrl();
int i = edit.LineFromChar(); // this is the current line the cursor is on
int nLine = m_pGotoDialog->m_nLineNum; // line number to go to
if(nLine > (edit.GetLineCount()))
nLine = edit.GetLineCount();
// move window and caret
--nLine; // edit control is zero based
edit.LineScroll(nLine-i); // new line number - the current line
int idx;
idx = edit.LineIndex(nLine);
edit.SetSel(idx, idx);
}
void CEvalView::Reset()
{
CEvalView::SetWindowText(NULL);
m_strPMark = "";
}
static int count_lines(LPCTSTR s)
{
if (!s) return 0;
int n = 0;
for (; *s; s++) if (*s == 10) n++;
return n;
}
static void limit_buffer(CEdit& edit, int nlines)
{
int n = edit.GetLineCount() - nlines;
if (n <= 0) return;
int len = edit.GetWindowTextLength()+1;
LPTSTR buf = new TCHAR[len+1];
edit.GetWindowText(buf, len);
LPTSTR s;
for (s = buf; *s && n; s++)
if (*s == 10) n--;
edit.SetWindowText(s);
delete[] buf;
}
void CEvalView::Append(LPCTSTR lpszText, BOOL mark)
{
CEdit &edit = GetEditCtrl();
if (CMainFrame::m_nLogMaxLines > 0)
limit_buffer(edit, CMainFrame::m_nLogMaxLines -
count_lines(lpszText));
int len = edit.GetWindowTextLength();
edit.SetSel(len, len);
if (lpszText) {
edit.ReplaceSel(lpszText);
if (mark && lpszText) {
LPCTSTR p = strrchr(lpszText, '\n');
if (p)
m_strPMark = p+1;
else
m_strPMark += lpszText;
}
}
}
void CEvalView::AppendNewLine(LPCTSTR lpszText,
BOOL mark)
{
CEdit &edit = GetEditCtrl();
int len = edit.GetWindowTextLength();
int base = edit.LineIndex(edit.GetLineCount()-1);
if (base < len)
Append(_T("\r\n"), mark);
if (lpszText)
Append(lpszText, mark);
}
BOOL CEvalView::IsCmd()
{
CEdit& edit = GetEditCtrl();
return edit.LineIndex(edit.LineFromChar()+1) == -1;
}
void CEvalView::SetCmd(CString str)
{
CEdit& edit = GetEditCtrl();
int n1, n2 = GetWindowTextLength();
int l = edit.GetLineCount();
if (l <= 0) {
Append(str);
edit.SetSel(0, 0);
return;
} else if (m_strPMark.IsEmpty())
n1 = edit.LineIndex(l-1);
else {
n1 = edit.LineIndex(l-1);
CString line;
PeekLine(l-1, line);
l = strlen(m_strPMark);
if (strncmp(m_strPMark, line, l) == 0)
n1 += l;
}
int m1, m2;
edit.GetSel(m1, m2);
edit.SetSel(n1, n2);
edit.ReplaceSel(str);
// set cursor position
if (m2 >= n1) {
n2 = edit.GetWindowTextLength();
if (m2 > n2) m2 = n2;
else if (m2 < n1) m2 = n1;
edit.SetSel(m2, m2);
}
}
void CEvalView::PeekLine(int lineno, int len, CString& str,
BOOL remove_prompt)
{
CEdit& edit = GetEditCtrl();
if (edit.LineIndex(lineno) == -1) {
str = "";
return;
}
int ofs = 0;
LPTSTR line = new TCHAR[len+4];
ASSERT(line != NULL);
edit.GetLine(lineno, line, len);
line[len] = '\0';
if (remove_prompt) {
if (edit.LineIndex(lineno+1) < 0) {
int l = strlen(m_strPMark);
if (strncmp(m_strPMark, line, l) == 0)
ofs = l;
} else {
if (strncmp(CMainFrame::m_strQPSX, line,
strlen(CMainFrame::m_strQPSX)) == 0)
ofs = strlen(CMainFrame::m_strQPSX);
else if (strncmp(CMainFrame::m_strQPS2, line,
strlen(CMainFrame::m_strQPS2)) == 0)
ofs = strlen(CMainFrame::m_strQPS2);
else if (strncmp(CMainFrame::m_strDPS, line,
strlen(CMainFrame::m_strDPS)) == 0)
ofs = strlen(CMainFrame::m_strDPS);
}
}
str = line+ofs;
delete[] line;
}
void CEvalView::PeekLine(int lineno, CString& str,
BOOL remove_prompt)
{
CEdit& edit = GetEditCtrl();
int p = edit.LineIndex(lineno);
if (p != -1) {
int p2 = edit.LineIndex(lineno+1);
if (p2 == -1)
p2 = edit.GetWindowTextLength();
else
p2 -= 2; // CR/LF
PeekLine(lineno, p2-p, str, remove_prompt);
} else
str = "";
}
void CEvalView::GotoLine(int lineno)
{
CEdit& edit = GetEditCtrl();
int p = edit.LineIndex(lineno);
if (p != -1)
edit.SetSel(p, p);
}
void CEvalView::MarkLine(int lineno)
{
CEdit& edit = GetEditCtrl();
int p = edit.LineIndex(lineno);
if (p != -1) {
int p2 = edit.LineIndex(lineno+1);
if (p2 == -1)
p2 = edit.GetWindowTextLength();
else
p2 -= 2; // CR/LF
edit.SetSel(p2, p);
}
}
static BOOL match_ws(LPCTSTR& p)
{
while (*p && isspace(*p)) p++;
return TRUE;
}
static BOOL match_num(LPCTSTR& p, int& num)
{
LPCTSTR p1 = p;
while (*p1 && isdigit(*p1)) p1++;
if (p1 > p) {
LPTSTR numstr = new TCHAR[p1-p+1];
strncpy(numstr, p, p1-p);
numstr[p1-p] = '\0';
num = atoi(numstr);
p = p1;
delete[] numstr;
return TRUE;
} else
return FALSE;
}
static BOOL match_fname(LPCTSTR& p, LPTSTR fname)
{
LPCTSTR p1 = p;
while (*p1 && *p1 != ',') p1++;
if (p1 > p && fname) {
strncpy(fname, p, p1-p);
fname[p1-p] = '\0';
p = p1;
return TRUE;
} else
return FALSE;
}
static BOOL match(LPCTSTR s, LPCTSTR& p)
{
if (strncmp(s, p, strlen(s)) == 0) {
p += strlen(s);
return TRUE;
} else
return FALSE;
}
static BOOL match_error(LPCTSTR line, LPTSTR fname, LPCTSTR& msg,
int& lineno)
{
LPCTSTR p = line;
#if 0
LPCTSTR p1;
int stacknum;
match_ws(p); p1 = p;
if (!((match("Error", p) || match("Warning", p))
&& match_ws(p) ||
match_num(p, stacknum) && match(">", p) && match_ws(p)))
p = p1;
#endif
if (!(match_fname(p, fname) && match(", line ", p) &&
match_num(p, lineno) &&
match(":", p) && match_ws(p) &&
strcmp(fname, "<stdin>")))
return FALSE;
else {
msg = p;
return TRUE;
}
}
BOOL CEvalView::GetErr(CString& fname, int& lineno, int &ref,
CString& msg)
{
CString line;
PeekLine(ref, line);
LPCTSTR msgstr;
LPTSTR fnamestr = new TCHAR[line.GetLength()+1];
ASSERT(fnamestr != NULL);
if (match_error(line, fnamestr, msgstr, lineno)) {
msg = msgstr;
fname = fnamestr;
delete[] fnamestr;
return TRUE;
} else {
delete[] fnamestr;
return FALSE;
}
}
BOOL CEvalView::GetFirstErr(CString& fname, int& lineno, int &ref,
CString& msg, int ref0)
{
CString fname1, msg1;
int lineno1, ref1;
BOOL res = FALSE;;
CEdit& edit = GetEditCtrl();
if (ref0 < 0) ref0 = edit.LineFromChar();
for (ref1 = ref0; ref1 >= 0; ref1--)
if (GetErr(fname1, lineno1, ref1, msg1)) {
res = TRUE;
fname = fname1; lineno = lineno1;
ref = ref1; msg = msg1;
} else
return res;
return res;
}
BOOL CEvalView::GetLastErr(CString& fname, int& lineno, int &ref,
CString& msg, int ref0)
{
CString fname1, msg1;
int lineno1, ref1;
BOOL res = FALSE;;
CEdit& edit = GetEditCtrl();
if (ref0 < 0) ref0 = edit.LineFromChar();
for (ref1 = ref0; ref1 >= 0 &&
ref1 < edit.GetLineCount(); ref1++)
if (GetErr(fname1, lineno1, ref1, msg1)) {
res = TRUE;
fname = fname1; lineno = lineno1;
ref = ref1; msg = msg1;
} else
return res;
return res;
}
BOOL CEvalView::GetPrevErr(CString& fname, int& lineno, int &ref,
CString& msg, int ref0)
{
CEdit& edit = GetEditCtrl();
if (ref0 < 0) ref0 = edit.LineFromChar();
for (ref = ref0-1; ref >= 0; ref--)
if (GetErr(fname, lineno, ref, msg))
return TRUE;
return FALSE;
}
BOOL CEvalView::GetNextErr(CString& fname, int& lineno, int &ref,
CString& msg, int ref0)
{
CEdit& edit = GetEditCtrl();
if (ref0 < 0) ref0 = edit.LineFromChar();
for (ref = ref0+1; ref > 0 && ref < edit.GetLineCount(); ref++)
if (GetErr(fname, lineno, ref, msg))
return TRUE;
return FALSE;
}
void CEvalView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if (nChar == '\n' || nChar == '\r' && IsCmd()) {
CEdit& edit = GetEditCtrl();
// looks like we can assume this
ASSERT(nRepCnt == 1);
// get the current line
edit.ReplaceSel("");
int lineno = edit.LineFromChar();
CString line;
PeekLine(lineno, line, TRUE);
if (edit.LineIndex(lineno+1) != -1)
// copy the line down to the end of the buffer
SetCmd(line);
Append("\r\n");
CQpadDoc* pDoc = GetDocument();
// send the line to the interpreter process
if (IsRunning()) {
m_pipe.Write(line);
m_pipe.Write("\n");
}
// add the line to the command history
m_hist.Append(line);
// reset the process marker
m_strPMark = "";
} else
CEditView::OnChar(nChar, nRepCnt, nFlags);
}
// public attributes and operations
BOOL CEvalView::IsRunning()
{
return m_pipe.IsRunning();
}
BOOL CEvalView::Run(LPCTSTR name, LPCTSTR pname)
{
if (IsRunning())
AppendNewLine();
m_strPMark = "";
return m_pipe.Run(name, pname);
}
BOOL CEvalView::Debug(LPCTSTR name, LPCTSTR pname)
{
if (IsRunning())
AppendNewLine();
m_strPMark = "";
return m_pipe.Debug(name, pname);
}
void CEvalView::Break()
{
if (IsRunning()) {
AppendNewLine();
m_strPMark = "";
m_pipe.Break();
}
}
void CEvalView::Kill()
{
if (IsRunning()) {
AppendNewLine();
m_strPMark = "";
m_pipe.Kill();
}
}
void CEvalView::ProcessInput()
{
LPTSTR s = m_pipe.Read();
Append(s, TRUE);
delete[] s;
}
void CEvalView::OnViewFont()
{
CFont* pFont = GetFont();
LOGFONT lf;
if (pFont != NULL)
pFont->GetObject(sizeof(LOGFONT), &lf);
else
::GetObject(GetStockObject(SYSTEM_FONT), sizeof(LOGFONT), &lf);
CFontDialog dlg(&lf, CF_SCREENFONTS|CF_INITTOLOGFONTSTRUCT);
if (dlg.DoModal() == IDOK)
{
m_font.DeleteObject();
if (m_font.CreateFontIndirect(&lf))
{
CWaitCursor wait;
SetFont(&m_font);
CMainFrame::m_lfLogFont = lf;
}
}
}
void CEvalView::OnViewTabstops()
{
CTabStopDlg dlg;
dlg.m_nTabStops = m_nTabStops/4;
if (dlg.DoModal() == IDOK)
{
CWaitCursor wait;
SetTabStops(dlg.m_nTabStops*4);
CMainFrame::m_nLogTabStops = m_nTabStops;
}
}
int CEvalView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CEditView::OnCreate(lpCreateStruct) == -1)
return -1;
if (CMainFrame::m_lfLogFont.lfHeight != 0)
{
m_font.CreateFontIndirect(&CMainFrame::m_lfLogFont);
SetFont(&m_font);
}
return 0;
}
void CEvalView::OnHistFirst()
{
CString str;
if (IsCmd() && m_hist.GetFirst(str))
SetCmd(str);
else
MessageBeep(MB_OK);
}
void CEvalView::OnHistLast()
{
CString str;
if (IsCmd() && m_hist.GetLast(str))
SetCmd(str);
else
MessageBeep(MB_OK);
}
void CEvalView::OnHistNext()
{
CString str;
if (IsCmd() && m_hist.GetNext(str))
SetCmd(str);
else
MessageBeep(MB_OK);
}
void CEvalView::OnHistPrev()
{
CString str;
if (IsCmd() && m_hist.GetPrev(str))
SetCmd(str);
else
MessageBeep(MB_OK);
}
void CEvalView::GetSearchStr(CString& str)
{
CEdit& edit = GetEditCtrl();
int lineno = edit.LineFromChar(), n = edit.LineIndex();
int n1, n2;
edit.GetSel(n1, n2);
int len = n2-n;
PeekLine(lineno, len, str, TRUE);
}
void CEvalView::OnHistSearchNext()
{
if (IsCmd() && m_hist.HasNext()) {
CString str, search;
GetSearchStr(search);
if (m_hist.SearchNext(str, search))
SetCmd(str);
else
MessageBeep(MB_OK);
} else
MessageBeep(MB_OK);
}
void CEvalView::OnHistSearchPrev()
{
if (IsCmd() && m_hist.HasPrev()) {
CString str, search;
GetSearchStr(search);
if (m_hist.SearchPrev(str, search))
SetCmd(str);
else
MessageBeep(MB_OK);
} else
MessageBeep(MB_OK);
}
|
d5bd43ffec922467bd0f2e5938f56f3ecd8dae3f
|
c98d4eb235da3eebea22f1acc5a3e46edb10bdbc
|
/sourcecode/20191227study(structure,stringfunctions).cpp
|
f89daf8cdc8abc47a2964f8fd3441e7542006079
|
[
"MIT"
] |
permissive
|
tnstjd1212/TIL-Cpp
|
ed4a4147d2f87c9356b98aed8be54c84f84361f7
|
da659f6fb884c68835958959f5a1e6b0da949361
|
refs/heads/master
| 2020-11-29T05:42:50.514361
| 2020-01-19T11:54:01
| 2020-01-19T11:54:01
| 230,035,592
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,993
|
cpp
|
20191227study(structure,stringfunctions).cpp
|
#include <iostream>
using namespace std;
#define NAME_SIZE 32
/*
구조체 : 관련있는 변수들을 모아서 하나의 새로운 타입을 만들어주는 기능이다.
사용자정의 변수 타입이다.
struct 구조체명 {};
배열과 구조체의 공통점
1. 데이터 집합이다.
2. 연속된 메모리 블럭에 할당된다.
(구조체 멤버들은 연속된 메모리 블럭으로 잡히게 된다.)
*/
struct _tagStudent {
char strName[NAME_SIZE];
int iNum;
int iKorScore;
int iMathScore;
int iTotalScore;
float fAvg;
};
int main() {
_tagStudent tStudent = {}; //모든 멤버 0으로 초기화 가능
//구조체 배열도 선언이 가능하다
// _tagStudent tStudentArr[100] = {};
//구조체 멤버로 잡근할 때는 . 을 이용한다.
tStudent.iKorScore = 100;
//문자열을 배열에 넣어줄 때에는 단순 대입으로는 불가능하다.
//strcpy_s로 복사해 주어야 한다.
//이 함수는 오른쪽에 있는 문자열을 왼쪽으로 복사해준다.
strcpy_s(tStudent.strName, "박순성");
//문자열의 끝은 항상 0(NULL)로 끝나야한다.
//아니라면 출력할 때 문자열의 끝을 인식할 수 없기때문에 쓰레기 값으로 출력된다.
//strcat_s() 문자열을 붙여주는 함수
//오른쪽에 있는 문자열을 왼쪽 문자열뒤에 붙여준다,
strcat_s(tStudent.strName, " SoonSung");
//strlen() 문자열의 크기를 구해주는 함수
cout << "이름 길이 : " << strlen(tStudent.strName) << endl;
cout << "이름 : " << tStudent.strName << endl;
//strcmp 함수는 두 문자열을 비교하여 같을 경우 0을 반환 하고 다를경우
//0이 아닌 값을 반환한다.
strcpy_s(tStudent.strName, "Soonsung");
cout << "비교할 이름을 입력하세요 : ";
char strCmp[NAME_SIZE] = {};
cin >> strCmp;
if (strcmp(tStudent.strName, strCmp)) {
cout << "같지 않습니다" << endl;
}
else
cout << "같습니다" << endl;
return 0;
}
|
2814414173305461e3a95a6cd2156677cc1c857b
|
2b9e3c3a7cf48650157e9e860148f16597078ff3
|
/SelectCoordinary.cpp
|
9ecfd89ac2ae3224eea8b7a00e192e05c6fa8f32
|
[] |
no_license
|
zhaojidabao/MGCode
|
2a7fa089aaed9c2f99a2fd55cd4743fd1ae3d59e
|
c742915c8170869d5b2fbf791f339a1c28350334
|
refs/heads/master
| 2020-03-31T20:35:23.596990
| 2018-10-11T07:05:00
| 2018-10-11T07:05:00
| 152,546,612
| 0
| 6
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,760
|
cpp
|
SelectCoordinary.cpp
|
// SelectCoordinary.cpp : implementation file
//
#include "stdafx.h"
#include "hl.h"
#include "SelectCoordinary.h"
#include "HLDoc.h"
#include "HLView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// SelectCoordinary dialog
SelectCoordinary::SelectCoordinary(CWnd* pParent,double *pdbX,double *pdbY,double *pSizeX,double *pSizeY,CButton *pButt,int *pnIconType)
: CDialog(SelectCoordinary::IDD, pParent)
{
//{{AFX_DATA_INIT(SelectCoordinary)
m_nBaseType = *pnIconType;
//}}AFX_DATA_INIT
m_pView=pParent;
m_pdbX=pdbX;
m_pdbY=pdbY;
m_pSizeX=pSizeX;
m_pSizeY=pSizeY;
m_pButton=pButt;
m_pIconType=pnIconType;
}
void SelectCoordinary::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(SelectCoordinary)
DDX_Radio(pDX, IDC_RADIO_BASE_TL, m_nBaseType);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(SelectCoordinary, CDialog)
//{{AFX_MSG_MAP(SelectCoordinary)
ON_BN_CLICKED(IDC_RADIO_BASE_BL, OnRadioBaseBl)
ON_BN_CLICKED(IDC_RADIO_BASE_BM, OnRadioBaseBm)
ON_BN_CLICKED(IDC_RADIO_BASE_BR, OnRadioBaseBr)
ON_BN_CLICKED(IDC_RADIO_BASE_ML, OnRadioBaseMl)
ON_BN_CLICKED(IDC_RADIO_BASE_MM, OnRadioBaseMm)
ON_BN_CLICKED(IDC_RADIO_BASE_MR, OnRadioBaseMr)
ON_BN_CLICKED(IDC_RADIO_BASE_TL, OnRadioBaseTl)
ON_BN_CLICKED(IDC_RADIO_BASE_TM, OnRadioBaseTm)
ON_BN_CLICKED(IDC_RADIO_BASE_TR, OnRadioBaseTr)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// SelectCoordinary message handlers
void SelectCoordinary::OnOK()
{
// TODO: Add extra validation here
UpdateView();
SetSelectIcon();
CDialog::OnOK();
}
void SelectCoordinary::OnCancel()
{
// TODO: Add extra cleanup here
CDialog::OnCancel();
}
void SelectCoordinary::OnRadioBaseBl()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_nBaseType=6;
}
void SelectCoordinary::OnRadioBaseBm()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_nBaseType=7;
}
void SelectCoordinary::OnRadioBaseBr()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_nBaseType=8;
}
void SelectCoordinary::OnRadioBaseMl()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_nBaseType =3;
}
void SelectCoordinary::OnRadioBaseMm()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_nBaseType =4;
}
void SelectCoordinary::OnRadioBaseMr()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_nBaseType=5;
}
void SelectCoordinary::OnRadioBaseTl()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_nBaseType = 0;
}
void SelectCoordinary::OnRadioBaseTm()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_nBaseType=1;
}
void SelectCoordinary::OnRadioBaseTr()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_nBaseType = 2;
}
void SelectCoordinary::UpdateView()
{
//根据基本点位置确定XY坐标值
CHLView *pHLView=(CHLView*)m_pView;
CHLDoc *pDoc=(CHLDoc*)pHLView->GetDocument();
CQuad quad=pDoc->GetLimit();
CDot dot=quad.GetBaseDot(m_nBaseType);
pDoc->m_nPosType=m_nBaseType;
*m_pdbX=MyPrecision(dot.x);
*m_pdbY=MyPrecision(dot.y);
quad.Normal();
*m_pSizeX=MyPrecision(quad.right-quad.left);
*m_pSizeY=MyPrecision(quad.top-quad.bottom);
UpdateData(FALSE);
}
void SelectCoordinary::SetSelectIcon()
{
*m_pIconType=m_nBaseType;
switch(m_nBaseType)
{
case BASE_TL:
{
HICON hIcon=((CHLApp*)AfxGetApp())->LoadIcon(IDI_ICON10);
m_pButton->SetIcon(hIcon);
break;
}
case BASE_TM:
{
HICON hIcon=((CHLApp*)AfxGetApp())->LoadIcon(IDI_ICON11);
m_pButton->SetIcon(hIcon);
break;
}
case BASE_TR:
{
HICON hIcon=((CHLApp*)AfxGetApp())->LoadIcon(IDI_ICON12);
m_pButton->SetIcon(hIcon);
break;
}
case BASE_ML:
{
HICON hIcon=((CHLApp*)AfxGetApp())->LoadIcon(IDI_ICON13);
m_pButton->SetIcon(hIcon);
break;
}
case BASE_MM:
{
HICON hIcon=((CHLApp*)AfxGetApp())->LoadIcon(IDI_ICON14);
m_pButton->SetIcon(hIcon);
break;
}
case BASE_MR:
{
HICON hIcon=((CHLApp*)AfxGetApp())->LoadIcon(IDI_ICON15);
m_pButton->SetIcon(hIcon);
break;
}
case BASE_BL:
{
HICON hIcon=((CHLApp*)AfxGetApp())->LoadIcon(IDI_ICON16);
m_pButton->SetIcon(hIcon);
break;
}
case BASE_BM:
{
HICON hIcon=((CHLApp*)AfxGetApp())->LoadIcon(IDI_ICON17);
m_pButton->SetIcon(hIcon);
break;
}
case BASE_BR:
{
HICON hIcon=((CHLApp*)AfxGetApp())->LoadIcon(IDI_ICON18);
m_pButton->SetIcon(hIcon);
break;
}
}
}
|
ee25c5f7cb1b1da84e306dae82b2fe044f38f279
|
a4f955e84880c1a110e65484187d221c54b7c799
|
/ch02/const.cpp
|
d814b1c2b8d211e383ee71cee8a72c006d73dc44
|
[] |
no_license
|
kk4728/CppPrimer5th
|
5fe6a1997002ed8e8ef3c0c0a508666b403956af
|
7fa2d6d7957fe0a8b53a2cbfe71e63babb16cdee
|
refs/heads/master
| 2020-04-24T18:12:12.155711
| 2019-04-23T08:25:04
| 2019-04-23T08:25:04
| 172,173,131
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 461
|
cpp
|
const.cpp
|
#include <iostream>
void f2_4_1()
{
int i = 42;
int &r1 = i;
const int &r2 = i;
r1 = 0;
//r2 = 0;
}
void f2_4_2()
{
const int i = 42;
//int* ptr = &i;
const int* ptr = &i;
const int* const ptr2 = &i;
//*ptr = 5;
}
void f_constexpr()
{
const int max_files = 20;
const int limit = max_files + 1;
int staff_size = 27;
// const int sz = get_size();
constexpr int mf = 20;
constexpr int limit1 = mf + 1;
// constexpr int sz = size();
}
|
4bde30152eaf141d9222b21c84814b8402e72bea
|
2d0ca8ba54a59a12452898209d05c96302447f60
|
/VisibilityBufferTessellation/Buffer.cpp
|
1ed61aef96efd4a7b5581206e6965a4d46e98eb1
|
[] |
no_license
|
merpheus-dev/VisBufferTessellation
|
48916d09c8250a2212124143349c6a35db20398f
|
78ed62e05457a4145c98d357aef34f5062ffcbf6
|
refs/heads/master
| 2022-02-06T22:34:18.304998
| 2019-07-10T11:15:43
| 2019-07-10T11:15:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,418
|
cpp
|
Buffer.cpp
|
#include "Buffer.h"
#include <stdexcept>
namespace vbt
{
void Buffer::Create(VkDeviceSize size, VkBufferUsageFlags usage, VmaMemoryUsage allocUsage, VkMemoryPropertyFlags properties, VmaAllocator& allocator)
{
// Store info
bufferSize = size;
usageFlags = usage;
allocationUsage = allocUsage;
propertyFlags = properties;
// Fill buffer create info
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = bufferSize;
bufferInfo.usage = usageFlags;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
// Specify memory allocation Info
VmaAllocationCreateInfo allocInfo = {};
allocInfo.usage = allocationUsage;
allocInfo.requiredFlags = propertyFlags;
// Create buffer
if (vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &bufferMemory, nullptr) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create vertex buffer");
}
}
void Buffer::MapData(void* data, VmaAllocator& allocator)
{
// Map data to staging buffer memory allocation
void* mappedData;
vmaMapMemory(allocator, bufferMemory, &mappedData);
memcpy(mappedData, data, (size_t)bufferSize);
vmaUnmapMemory(allocator, bufferMemory);
}
void Buffer::Flush(VmaAllocator& allocator, VkDeviceSize size, VkDeviceSize offset)
{
vmaFlushAllocation(allocator, bufferMemory, offset, size);
}
void Buffer::Map(VmaAllocator& allocator)
{
vmaMapMemory(allocator, bufferMemory, &mappedRange);
}
void Buffer::Unmap(VmaAllocator& allocator)
{
if (mappedRange)
{
vmaUnmapMemory(allocator, bufferMemory);
mappedRange = nullptr;
}
}
void Buffer::SetupDescriptor(VkDeviceSize size, VkDeviceSize offset)
{
descriptor.offset = offset;
descriptor.buffer = buffer;
descriptor.range = size;
}
void Buffer::SetupDescriptorWriteSet(VkDescriptorSet dstSet, uint32_t binding, VkDescriptorType type, uint32_t count)
{
descriptorWriteSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWriteSet.dstSet = dstSet;
descriptorWriteSet.dstBinding = binding;
descriptorWriteSet.dstArrayElement = 0;
descriptorWriteSet.descriptorType = type;
descriptorWriteSet.descriptorCount = count;
descriptorWriteSet.pBufferInfo = &descriptor;
}
void Buffer::CleanUp(VmaAllocator& allocator)
{
// Free memory and destroy buffer object
Unmap(allocator);
vmaDestroyBuffer(allocator, buffer, bufferMemory);
}
}
|
e171c5b77f26b02ff31bf9578be8f20bbdd1663f
|
2bef21ebe475bae8754a8d24eea1920e0b462644
|
/Src/Neill3d_Archive/tool_blendPhase/blendPhase_tool.cxx
|
ff34eabf7ef224b77ebf7a7cfb0ef17699c858a8
|
[
"BSD-3-Clause"
] |
permissive
|
Neill3d/OpenMoBu
|
fd70392ba964fb0b65dc81adb04cc1dccc245af8
|
bce4dd9a0b46ea6d911f66e9115a58f99e0fda8a
|
refs/heads/master
| 2023-05-12T12:09:16.401574
| 2023-05-06T13:19:15
| 2023-05-06T13:19:15
| 24,093,493
| 77
| 14
|
NOASSERTION
| 2022-09-09T19:43:14
| 2014-09-16T09:31:25
|
C++
|
UTF-8
|
C++
| false
| false
| 7,293
|
cxx
|
blendPhase_tool.cxx
|
/***************************************************************************************
Autodesk(R) Open Reality(R) Samples
(C) 2006 Autodesk, Inc. and/or its licensors
All rights reserved.
AUTODESK SOFTWARE LICENSE AGREEMENT
Autodesk, Inc. licenses this Software to you only upon the condition that
you accept all of the terms contained in the Software License Agreement ("Agreement")
that is embedded in or that is delivered with this Software. By selecting
the "I ACCEPT" button at the end of the Agreement or by copying, installing,
uploading, accessing or using all or any portion of the Software you agree
to enter into the Agreement. A contract is then formed between Autodesk and
either you personally, if you acquire the Software for yourself, or the company
or other legal entity for which you are acquiring the software.
AUTODESK, INC., MAKES NO WARRANTY, EITHER EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR
PURPOSE REGARDING THESE MATERIALS, AND MAKES SUCH MATERIALS AVAILABLE SOLELY ON AN
"AS-IS" BASIS.
IN NO EVENT SHALL AUTODESK, INC., BE LIABLE TO ANYONE FOR SPECIAL, COLLATERAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES IN CONNECTION WITH OR ARISING OUT OF PURCHASE
OR USE OF THESE MATERIALS. THE SOLE AND EXCLUSIVE LIABILITY TO AUTODESK, INC.,
REGARDLESS OF THE FORM OF ACTION, SHALL NOT EXCEED THE PURCHASE PRICE OF THE
MATERIALS DESCRIBED HEREIN.
Autodesk, Inc., reserves the right to revise and improve its products as it sees fit.
Autodesk and Open Reality are registered trademarks or trademarks of Autodesk, Inc.,
in the U.S.A. and/or other countries. All other brand names, product names, or
trademarks belong to their respective holders.
GOVERNMENT USE
Use, duplication, or disclosure by the U.S. Government is subject to restrictions as
set forth in FAR 12.212 (Commercial Computer Software-Restricted Rights) and
DFAR 227.7202 (Rights in Technical Data and Computer Software), as applicable.
Manufacturer is Autodesk, Inc., 10 Duke Street, Montreal, Quebec, Canada, H3C 2L7.
***************************************************************************************/
/** \file blendPhase_tool.cxx
*/
//--- Class declaration
#include "blendPhase_Tool.h"
//--- Registration defines
#define BLENDPHASE__CLASS BLENDPHASE__CLASSNAME
#define BLENDPHASE__LABEL "blendPhase"
#define BLENDPHASE__DESC "test blend phases between two animations"
//--- FiLMBOX implementation and registration
FBToolImplementation( BLENDPHASE__CLASS );
FBRegisterTool ( BLENDPHASE__CLASS,
BLENDPHASE__LABEL,
BLENDPHASE__DESC,
FB_DEFAULT_SDK_ICON ); // Icon filename (default=Open Reality icon)
/************************************************
* FiLMBOX Constructor.
************************************************/
bool BlendPhase::FBCreate()
{
// Tool options
StartSize[0] = 400;
StartSize[1] = 160;
// Configure layout
int lB = 10;
// regions for label & edit visual elements
AddRegion( "LabelSrc", "LabelSrc",
lB, kFBAttachLeft, "", 1.0 ,
lB, kFBAttachTop, "", 1.0,
120,kFBAttachNone, "", 1.0,
30, kFBAttachNone, "", 1.0 );
AddRegion( "EditAnimSrc", "EditAnimSrc",
lB, kFBAttachRight, "LabelSrc", 1.0 ,
lB, kFBAttachTop, "", 1.0,
120,kFBAttachNone, "", 1.0,
30, kFBAttachNone, "", 1.0 );
AddRegion( "LabelDst", "LabelDst",
lB, kFBAttachLeft, "", 1.0 ,
lB, kFBAttachBottom,"LabelSrc", 1.0,
120,kFBAttachNone, "", 1.0,
30, kFBAttachNone, "", 1.0 );
AddRegion( "EditAnimDst", "EditAnimDst",
lB, kFBAttachRight, "LabelDst", 1.0 ,
lB, kFBAttachBottom,"EditAnimSrc", 1.0,
120,kFBAttachNone, "", 1.0,
30, kFBAttachNone, "", 1.0 );
AddRegion( "LabelBlend", "LabelBlend",
lB, kFBAttachLeft, "", 1.0 ,
lB, kFBAttachBottom,"LabelDst", 1.0,
120,kFBAttachNone, "", 1.0,
30, kFBAttachNone, "", 1.0 );
AddRegion( "EditBlendSize", "EditBlendSize",
lB, kFBAttachRight, "LabelBlend", 1.0 ,
lB, kFBAttachBottom,"EditAnimDst", 1.0,
120,kFBAttachNone, "", 1.0,
30, kFBAttachNone, "", 1.0 );
AddRegion( "ButtonBlend", "ButtonBlend",
lB, kFBAttachRight, "EditAnimDst", 1.0 ,
lB, kFBAttachBottom,"EditAnimSrc", 1.0,
120,kFBAttachNone, "", 1.0,
30, kFBAttachNone, "", 1.0 );
SetControl( "LabelSrc", mLabelSrc );
SetControl( "LabelDst", mLabelDst );
SetControl( "LabelBlend", mLabelBlend );
SetControl( "ButtonBlend", mButtonBlend );
SetControl( "EditAnimSrc", mEditAnimSrc );
SetControl( "EditAnimDst", mEditAnimDst );
SetControl( "EditBlendSize", mEditBlendSize );
// Configure button's
mLabelSrc.Caption = "1'st anim out [0;100]";
mLabelDst.Caption = "2'nd anim in [0;100]";
mLabelBlend.Caption = "blend len in frames";
mButtonBlend.Caption = "Blend";
mButtonBlend.PropertyList.Find( "Hint" )->SetString( "Make blend according current phase" );
mButtonBlend.OnClick.Add( this, (FBCallback) &BlendPhase::EventButtonBlendClick );
return true;
}
/************************************************
* Button click callback.
************************************************/
void BlendPhase::EventButtonBlendClick( HISender pSender, HKEvent pEvent )
{
FBStory lStory;
HFBStoryFolder lActionFolder = lStory.RootFolder;
HFBStoryTrack lCharTrack = lActionFolder->Tracks[0];
HFBStoryClip lClipSrc, lClipDst;
lClipSrc = lCharTrack->Clips[0];
lClipDst = lCharTrack->Clips[1];
float blendPos = mEditAnimSrc.Value;
float animDst = mEditAnimDst.Value;
float blendTime = mEditBlendSize.Value;
FBTime lInTimeSrc = lClipSrc->MarkIn;
FBTime lOutTimeSrc = lClipSrc->MarkOut;
FBTime lInTimeDst = lClipDst->MarkIn;
FBTime lOutTimeDst = lClipDst->MarkOut;
long lInTime = lInTimeSrc.GetFrame( true );
long lOutTime = lOutTimeSrc.GetFrame( true );
blendPos *= 0.01f;
blendPos = lInTime + (lOutTime - lInTime) * blendPos;
lInTime = lInTimeDst.GetFrame( true );
lOutTime = lOutTimeDst.GetFrame( true );
animDst *= 0.01f;
animDst = lInTime + (lOutTime - lInTime) * animDst;
FBTimeSpan lTimeSpanSrc( FBTime( 0, 0, 0, 0 ), 0 );
FBTimeSpan lTimeSpanDst( 0, FBTime( 0, 0, 0, 0 ) );
lClipSrc->PostBlend = lTimeSpanSrc;
lClipDst->PreBlend = lTimeSpanDst;
lClipDst->Offset = FBTime( 0, 0, 0, animDst );
lClipSrc->Stop = FBTime( 0, 0, 0, blendPos + blendTime );
lClipDst->MoveTo( FBTime( 0, 0, 0, blendPos ) );
}
/************************************************
* FiLMBOX Destruction function.
************************************************/
void BlendPhase::FBDestroy()
{
// Free user allocated memory
}
/************************************************
* FBX Storage.
************************************************/
bool BlendPhase::FbxStore ( HFBFbxObject pFbxObject, kFbxObjectStore pStoreWhat )
{
return true;
}
/************************************************
* FBX Retrieval.
************************************************/
bool BlendPhase::FbxRetrieve( HFBFbxObject pFbxObject, kFbxObjectStore pStoreWhat )
{
return true;
}
|
8aef705c34f4220984e3f89163dbc577e87e1081
|
4c05eb220a3ae5b1cd0197f2f4d33759f26d9451
|
/SaMod_V3/Shared/sdk/net/bitstream.h
|
e3d575c30621502ef2cd1d3bb9cfd4651eb214a6
|
[] |
no_license
|
grasmanek94/PAWN-4-SinglePlayer-GTA-SA
|
6276633ca3ad95d98d2d0302b160c3e68537c067
|
279569a3a5a257a36bcdc6ccb88a41ba76f62ae9
|
refs/heads/master
| 2020-12-24T20:52:25.112355
| 2016-04-25T23:48:14
| 2016-04-25T23:48:14
| 57,083,608
| 8
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,091
|
h
|
bitstream.h
|
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: Shared/sdk/net/bitstream.h
* PURPOSE: Network bitstream interface
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#pragma once
#include "Common.h"
#include "../Common.h"
#include <string>
#ifndef WIN32
#include <alloca.h>
#endif
struct ISyncStructure;
class NetBitStreamInterface;
class NetBitStreamInterfaceNoVersion : public CRefCountable
{
public:
virtual operator NetBitStreamInterface& ( void ) = 0;
virtual int GetReadOffsetAsBits ( void ) = 0;
virtual void SetReadOffsetAsBits ( int iOffset ) = 0;
virtual void Reset ( void ) = 0;
virtual void ResetReadPointer ( void ) = 0;
// Don't use this, it screws up randomly in certain conditions causing packet misalign
virtual void Write ( const unsigned char& input ) = 0;
virtual void Write ( const char& input ) = 0;
virtual void Write ( const unsigned short& input ) = 0;
virtual void Write ( const short& input ) = 0;
virtual void Write ( const unsigned int& input ) = 0;
virtual void Write ( const int& input ) = 0;
virtual void Write ( const float& input ) = 0;
virtual void Write ( const double& input ) = 0;
virtual void Write ( const char* input, int numberOfBytes ) = 0;
virtual void Write ( const ISyncStructure* syncStruct ) = 0;
public: // Use char functions only when they will be 0 most times
virtual void WriteCompressed ( const unsigned char& input ) = 0;
virtual void WriteCompressed ( const char& input ) = 0;
public:
virtual void WriteCompressed ( const unsigned short& input ) = 0;
virtual void WriteCompressed ( const short& input ) = 0;
virtual void WriteCompressed ( const unsigned int& input ) = 0;
virtual void WriteCompressed ( const int& input ) = 0;
private: // Float functions not used because they only cover -1 to +1 and are lossy
virtual void WriteCompressed ( const float& input ) = 0;
virtual void WriteCompressed ( const double& input ) = 0;
public:
virtual void WriteBits ( const char* input, unsigned int numbits ) = 0;
virtual void WriteBit ( bool input ) = 0;
// Write a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12 bytes. Will further compress y or z axis aligned vectors. Accurate to 1/32767.5.
virtual void WriteNormVector ( float x, float y, float z ) = 0;
// Write a vector, using 10 bytes instead of 12. Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important.
virtual void WriteVector ( float x, float y, float z ) = 0;
// Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy.
virtual void WriteNormQuat ( float w, float x, float y, float z) = 0;
// Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each for 6 bytes instead of 36
virtual void WriteOrthMatrix (
float m00, float m01, float m02,
float m10, float m11, float m12,
float m20, float m21, float m22
) = 0;
virtual bool Read ( unsigned char& output ) = 0;
virtual bool Read ( char& output ) = 0;
virtual bool Read ( unsigned short& output ) = 0;
virtual bool Read ( short& output ) = 0;
virtual bool Read ( unsigned int& output ) = 0;
virtual bool Read ( int& output ) = 0;
virtual bool Read ( float& output ) = 0;
virtual bool Read ( double& output ) = 0;
virtual bool Read ( char* output, int numberOfBytes ) = 0;
virtual bool Read ( ISyncStructure* syncStruct ) = 0;
public: // Use char functions only when they will be 0 most times
virtual bool ReadCompressed ( unsigned char& output ) = 0;
virtual bool ReadCompressed ( char& output ) = 0;
public:
virtual bool ReadCompressed ( unsigned short& output ) = 0;
virtual bool ReadCompressed ( short& output ) = 0;
virtual bool ReadCompressed ( unsigned int& output ) = 0;
virtual bool ReadCompressed ( int& output ) = 0;
private: // Float functions not used because they only cover -1 to +1 and are lossy
virtual bool ReadCompressed ( float& output ) = 0;
virtual bool ReadCompressed ( double& output ) = 0;
public:
virtual bool ReadBits ( char* output, unsigned int numbits ) = 0;
virtual bool ReadBit ( ) = 0;
virtual bool ReadNormVector ( float &x, float &y, float &z ) = 0;
virtual bool ReadVector ( float &x, float &y, float &z ) = 0;
virtual bool ReadNormQuat ( float &w, float &x, float &y, float &z) = 0;
virtual bool ReadOrthMatrix (
float &m00, float &m01, float &m02,
float &m10, float &m11, float &m12,
float &m20, float &m21, float &m22
) = 0;
// GetNumberOfBitsUsed appears to round up to the next byte boundary, when reading
virtual int GetNumberOfBitsUsed ( void ) const = 0;
virtual int GetNumberOfBytesUsed ( void ) const = 0;
// GetNumberOfUnreadBits appears to round up to the next byte boundary, when reading
virtual int GetNumberOfUnreadBits ( void ) const = 0;
virtual void AlignWriteToByteBoundary ( void ) const = 0;
virtual void AlignReadToByteBoundary ( void ) const = 0;
// Force long types to use 4 bytes
bool Read( unsigned long& e )
{
uint temp;
bool bResult = Read( temp );
e = temp;
return bResult;
}
bool Read( long& e )
{
int temp;
bool bResult = Read( temp );
e = temp;
return bResult;
}
bool ReadCompressed( unsigned long& e )
{
uint temp;
bool bResult = ReadCompressed( temp );
e = temp;
return bResult;
}
bool ReadCompressed( long& e )
{
int temp;
bool bResult = ReadCompressed( temp );
e = temp;
return bResult;
}
void Write( unsigned long e )
{
Write( (uint)e );
}
void Write( long e )
{
Write( (int)e );
}
void WriteCompressed( unsigned long e )
{
WriteCompressed( (uint)e );
}
void WriteCompressed( long e )
{
WriteCompressed( (int)e );
}
#ifdef WIN_x64
void Write ( const size_t& input );
void WriteCompressed ( const size_t& input );
bool Read ( size_t& output );
bool ReadCompressed ( size_t& output );
#endif
// Helper template methods that are not actually part
// of the interface but get inline compiled.
template < typename T >
inline void WriteBits ( T * input, unsigned int numbits )
{
WriteBits ( reinterpret_cast < const char * > ( input ), numbits );
}
template < typename T >
inline bool ReadBits ( T * output, unsigned int numbits )
{
return ReadBits ( reinterpret_cast < char * > ( output ), numbits );
}
// Read a single bit
bool ReadBit ( bool& output )
{
unsigned char ucTemp = 0;
if ( ReadBits ( &ucTemp, 1 ) )
{
output = ucTemp & 1;
return true;
}
return false;
}
// Return true if enough bytes left in the bitstream
bool CanReadNumberOfBytes( int iLength ) const
{
return iLength <= ( GetNumberOfUnreadBits() + 7 ) / 8;
}
// Write characters from a std::string
void WriteStringCharacters ( const std::string& value, uint uiLength )
{
dassert ( uiLength <= value.length () );
// Send the data
if ( uiLength )
Write ( &value.at ( 0 ), uiLength );
}
// Read characters into a std::string
bool ReadStringCharacters ( std::string& result, uint uiLength )
{
result = "";
if ( uiLength )
{
if ( !CanReadNumberOfBytes( uiLength ) )
return false;
// Read the data
std::vector < char > bufferArray;
bufferArray.resize( uiLength );
char* buffer = &bufferArray[0];
if ( !Read ( buffer, uiLength ) )
return false;
result = std::string ( buffer, uiLength );
}
return true;
}
// Write a string (incl. ushort size header)
void WriteString ( const std::string& value )
{
// Write the length
unsigned short usLength = value.length ();
Write ( usLength );
// Write the characters
return WriteStringCharacters ( value, usLength );
}
// Read a string (incl. ushort size header)
bool ReadString ( std::string& result )
{
result = "";
// Read the length
unsigned short usLength = 0;
if ( !Read ( usLength ) )
return false;
// Read the characters
return ReadStringCharacters ( result, usLength );
}
// Write variable size length
void WriteLength( uint uiLength )
{
if ( uiLength <= 0x7F ) // One byte for length up to 127
Write( (uchar)uiLength );
else
if ( uiLength <= 0x7FFF )
{ // Two bytes for length from 128 to 32767
Write( (uchar)( ( uiLength >> 8 ) + 128 ) );
Write( (uchar)( uiLength & 0xFF ) );
}
else
{ // Five bytes for length 32768 and up
Write( (uchar)255 );
Write( uiLength );
}
}
// Read variable size length
bool ReadLength( uint& uiOutLength )
{
uiOutLength = 0;
// Read the length
uchar ucValue = 0;
if ( !Read ( ucValue ) )
return false;
if ( ucValue <= 0x7F )
{ // One byte for length up to 127
uiOutLength = ucValue;
}
else
if ( ucValue != 255 )
{ // Two bytes for length from 128 to 32767
uchar ucValue2 = 0;
if ( !Read ( ucValue2 ) )
return false;
uiOutLength = ( ( ucValue - 128 ) << 8 ) + ucValue2;
}
else
{ // Five bytes for length 32768 and up
if ( !Read( uiOutLength ) )
return false;
}
return true;
}
// Write a string (incl. variable size header)
void WriteStr( const std::string& value )
{
WriteLength( value.length() );
return WriteStringCharacters( value, value.length() );
}
// Read a string (incl. variable size header)
bool ReadStr( std::string& result )
{
result = "";
uint uiLength = 0;
if ( !ReadLength ( uiLength ) )
return false;
return ReadStringCharacters ( result, uiLength );
}
#ifdef MTA_CLIENT
#define MAX_ELEMENTS MAX_CLIENT_ELEMENTS
#else
#define MAX_ELEMENTS MAX_SERVER_ELEMENTS
#endif
// Write an element ID
void Write(const ElementID& ID)
{
static const unsigned int bitcount = NumberOfSignificantBits < ( MAX_ELEMENTS - 1 ) >::COUNT;
const unsigned int& IDref = ID.Value ();
#ifdef MTA_CLIENT
if ( IDref != INVALID_ELEMENT_ID && IDref >= MAX_SERVER_ELEMENTS )
{
dassert ( "Sending client side element id to server" && 0 );
uint uiInvalidId = INVALID_ELEMENT_ID;
WriteBits ( reinterpret_cast < const unsigned char* > ( &uiInvalidId ), bitcount );
return;
}
#endif
WriteBits ( reinterpret_cast < const unsigned char* > ( &IDref ), bitcount );
}
// Read an element ID
bool Read(ElementID& ID)
{
static const unsigned int bitcount = NumberOfSignificantBits < ( MAX_ELEMENTS - 1 ) > ::COUNT;
unsigned int& IDref = ID.Value ();
IDref = 0;
bool bResult = ReadBits ( reinterpret_cast < unsigned char* > ( &IDref ), bitcount );
// If max value, change to INVALID_ELEMENT_ID
static const unsigned int maxValue = ( 1 << bitcount ) - 1;
if ( IDref == maxValue )
IDref = INVALID_ELEMENT_ID;
return bResult;
}
};
class NetBitStreamInterface : public NetBitStreamInterfaceNoVersion
{
NetBitStreamInterface ( const NetBitStreamInterface& );
const NetBitStreamInterface& operator= ( const NetBitStreamInterface& );
protected:
NetBitStreamInterface ( void ) { DEBUG_CREATE_COUNT( "NetBitStreamInterface" ); }
virtual ~NetBitStreamInterface ( void ) { DEBUG_DESTROY_COUNT( "NetBitStreamInterface" ); }
public:
virtual operator NetBitStreamInterface& ( void ) { return *this; }
virtual unsigned short Version ( void ) const = 0;
};
// Interface for all sync structures
struct ISyncStructure
{
virtual ~ISyncStructure () {}
virtual bool Read ( NetBitStreamInterface& bitStream ) = 0;
virtual void Write ( NetBitStreamInterface& bitStream ) const = 0;
};
|
aba51b5244b1293f4e2a0c221cf09a3e2fd5eda3
|
0712c7f5a75b9273ca01319007712fabc61af4b7
|
/Saideepthi180102062Assign5/assignment5/ques3/q3.cpp
|
da58afdf222398fbb40512b41e697d86878db2cd
|
[] |
no_license
|
Deepthi2001/DSA-EE390
|
9598736235673d5f18ef4fa1f5fcbb086391247b
|
494213b05d6b09fe670b918049a7e64b1865d096
|
refs/heads/main
| 2023-04-22T17:54:34.395282
| 2021-05-12T06:58:43
| 2021-05-12T06:58:43
| 366,619,775
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,873
|
cpp
|
q3.cpp
|
#include "global.h"
//depth first search
void DFS(int R, int V, vector<vector<int>> &Resistance, vector<vector<int>> &Voltage,int n) {
bool *visited = new bool[n];
for(int i=0;i<n;i++)
visited[i] = false;
stack<int>S;
int start = R;
S.push(start);
while(!S.empty()) {
start = S.top();
S.pop();
if(!visited[start])
visited[start] = true;
for(int i=0;i<n;i++) {
if(!visited[i] && Resistance[start][i]!=-1) {
visited[i] = true;
S.push(i);
}
}
}
for(int i=0;i<n;i++)
visited[i] = false;
start = V;
S.push(start);
while(!S.empty()) {
start = S.top();
S.pop();
if(!visited[start])
visited[start] = true;
for(int i=0;i<n;i++) {
if(!visited[i] && Voltage[start][i]!=-1) {
visited[i] = true;
S.push(i);
}
}
}
}
//breadth first search
void BFS(int R, int V, vector<vector<int>> &Resistance, vector<vector<int>> &Voltage,int n) {
bool *visited = new bool[n];
for(int i=0;i<n;i++)
visited[i] = false;
queue<int>Q;
int start = R;
Q.push(start);
while(!Q.empty()) {
start = Q.front();
Q.pop();
for(int i=0;i<n;i++) {
if(!visited[i] && Resistance[start][i]!=-1) {
visited[i] = true;
Q.push(i);
}
}
}
for(int i=0;i<n;i++)
visited[i] = false;
start = V;
Q.push(start);
while(!Q.empty()) {
start = Q.front();
Q.pop();
for(int i=0;i<n;i++) {
if(!visited[i] && Voltage[start][i]!=-1) {
visited[i] = true;
Q.push(i);
}
}
}
}
int main() {
int n=5;
std::ofstream myFile;
//opens the text file
myFile.open("compared_values.txt");
cout<<"DFS \t BFS"<<endl;
myFile << "size" << " " << "DFS" << " " << "BFS" << endl;
while(n<100000){
vector<vector<int>> Resistance(n,vector<int>(n));
vector<vector<int>> Voltage(n,vector<int>(n));
//initialise every element to -1(meaning no resistances)
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
Resistance[i][j] = -1;
Voltage[i][j] = -1;
}
}
fstream fin;
//takes input from text file provided
fin.open("input.txt", ios::in);
while(!fin.eof()) {
string data;
getline(fin,data);
string str;
stringstream iss(data);
iss >> str;
if(str[0]=='I')
continue;
else {
string n1, n2, value;
iss >> n1;
iss >> n2;
if(str[0]=='R') {
iss >> value;
Resistance[atoi(n1.c_str())][atoi(n2.c_str())] = atoi(value.c_str());
Resistance[atoi(n2.c_str())][atoi(n1.c_str())] = atoi(value.c_str());
}
else {
iss >> value;
Voltage[atoi(n1.c_str())][atoi(n2.c_str())] = atoi(value.c_str());
Voltage[atoi(n2.c_str())][atoi(n1.c_str())] = atoi(value.c_str());
}
}
}
fin.close();
clock_t start, end;
start = clock();
DFS(0,0,Resistance,Voltage,n);
end = clock();
double time1 = ((double)(end - start));
start = clock();
BFS(0,0,Resistance,Voltage,n);
end = clock();
double time2 = ((double)(end - start));
//stores the values in text file created
myFile << n << " " << time1 << " " << time2 << endl;
cout<<time1<<"\t "<<time2<<endl;
n+=100;
}
myFile.close();
//closes the text file after storing the values
}
|
553beae8dbbcd8c4c89fa6fecacfa997a1ee5c8f
|
96bc3dd8cfdb833a0e681b014cc4659df217ded0
|
/codechef/Outputs/abhishek_0097/codechef/CHEFSTLT/CHEFSTLT-9189327.cpp
|
a8083b76c970a2d8f114bfff7ab5d92bab5bb056
|
[] |
no_license
|
theabhishekmandal/Code
|
4d2f3b269fd150fa1ff443aebdee7522b089ece3
|
b28c85b1196faabbfc491a44be20b5b2c6022bbb
|
refs/heads/master
| 2022-04-13T11:43:15.274844
| 2020-04-10T08:54:58
| 2020-04-10T08:54:58
| 115,778,104
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 403
|
cpp
|
CHEFSTLT-9189327.cpp
|
#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
int t,i;
cin>>t;
while(t--)
{
char a[101],b[101]; int max=0,min=0;
scanf("%s%s",&a,&b);
for(i=0;a[i];i++)
{
if((a[i]=='?'&&b[i]!='?')||(b[i]=='?'&&a[i]!='?'))
{
max++;
}
else
if(a[i]=='?'&&b[i]=='?')
{
max++;
}
else
if(a[i]!='?'&&b[i]!='?')
{
if(a[i]!=b[i])
{
min++;
}
}
}
max=max+min;
cout<<min<<' '<<max<<endl;
}
return 0;
}
|
333f620492b6dbbcb975f6d7c8b3224b386434ce
|
e567681bca202d737995a9dde7ca646035d9d1d4
|
/Examples/gpucoder/gpucoder/api/cnnMain.hpp
|
c47b5cc33c5c1645c44c45caa26e31baa6e2af02
|
[] |
no_license
|
shackopu/ManavMantra
|
0b0bfad7ec9eacadae6d40dcc3e49ce3d7c0a6cf
|
72f0da766eddd93171d88359868c8ed9ad3b32a6
|
refs/heads/master
| 2020-04-15T20:07:21.655572
| 2018-04-29T08:35:42
| 2018-04-29T08:35:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 162
|
hpp
|
cnnMain.hpp
|
/* Copyright 2016 The MathWorks, Inc. */
// Main file functions
extern "C" {
void cnnMain_mex_setup();
void cnnMain_mex_run();
void cnnMain_mex_cleanup();
}
|
3b247537cd69e2f69b97e6eaec50fa764bd7ac1a
|
3ad20c303cfad42436888216fa3b2d19f4533ca0
|
/main/lib/math/fraction.cpp
|
1862dfe6aa074d9d20be4ba1583f075ca17df6dd
|
[] |
no_license
|
JasonBaby87/Eschatology-Prototype
|
b4dd8d15d276f8753d467aa8c521bbcf2f1214fc
|
45109fdd766fff8ec721e2700b83cef8b1bc341f
|
refs/heads/master
| 2021-06-20T01:37:34.661351
| 2017-06-26T15:57:03
| 2017-06-26T15:57:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,354
|
cpp
|
fraction.cpp
|
#ifndef FRACTION_CPP_INCLUDED
#define FRACTION_CPP_INCLUDED
#include <iostream>
#include <sstream>
#include "fraction.h"
#include "algorithm.h"
// ImproperFraction
template <typename N>
ImproperFraction<N>& ImproperFraction<N>::reduce()
{
N divisor = gcd(numerator, denominator);
numerator /= divisor;
denominator /= divisor;
if (denominator < 0)
{
numerator = -numerator;
denominator = -denominator;
}
return *this;
}
template <typename N>
ImproperFraction<N>::ImproperFraction(N n, N d): numerator(n), denominator(d)
{
reduce();
}
template <typename N>
N ImproperFraction<N>::getInteger() const
{
return numerator / denominator;
}
template <typename N>
N ImproperFraction<N>::getNumerator() const
{
return numerator;
}
template <typename N>
N ImproperFraction<N>::getDenominator() const
{
return denominator;
}
// Operator overloading when needed
template <typename N>
const ImproperFraction<N> ImproperFraction<N>::operator+(const ImproperFraction<N>& f) const
{
int n, d;
d = lcm(denominator, f.denominator);
n = numerator * (d / denominator);
n += f.numerator * (d / f.denominator);
return ImproperFraction<N>(n, d);
}
template <typename N>
const ImproperFraction<N> ImproperFraction<N>::operator-(const ImproperFraction<N>& f) const
{
return *this + -f;
}
template <typename N>
ImproperFraction<N>& ImproperFraction<N>::operator+=(const ImproperFraction<N>& n)
{
*this = *this + ImproperFraction<N>(n);
return *this;
}
template <typename N>
ImproperFraction<N>& ImproperFraction<N>::operator+=(N n)
{
*this += ImproperFraction<N>(n);
return *this;
}
template <typename N>
ImproperFraction<N>& ImproperFraction<N>::operator-=(const ImproperFraction<N>& n)
{
*this = *this - ImproperFraction<N>(n);
return *this;
}
template <typename N>
ImproperFraction<N>& ImproperFraction<N>::operator-=(N n)
{
*this -= ImproperFraction<N>(n);
return *this;
}
template <typename N>
bool ImproperFraction<N>::operator<(const ImproperFraction<N>& f) const
{
return static_cast<double>(*this) < static_cast<double>(f);
}
template <typename N>
bool ImproperFraction<N>::operator<(N n) const
{
return *this < ImproperFraction<N>(n);
}
template <typename N>
bool ImproperFraction<N>::operator>(const ImproperFraction<N>& f) const
{
return static_cast<double>(*this) > static_cast<double>(f);
}
template <typename N>
bool ImproperFraction<N>::operator>(N n) const
{
return *this > ImproperFraction<N>(n);
}
template <typename N>
const ImproperFraction<N> ImproperFraction<N>::operator-() const
{
return ImproperFraction(-numerator, denominator);
}
template <typename N>
const ImproperFraction<N> ImproperFraction<N>::operator++(int)
{
ImproperFraction<N> result = *this;
*this += 1;
return result;
}
template <typename N>
const ImproperFraction<N> ImproperFraction<N>::operator--(int)
{
ImproperFraction<N> result = *this;
*this -= 1;
return result;
}
template <typename N>
ImproperFraction<N>::operator N() const
{
return static_cast<N>(numerator / denominator);
}
template <typename N>
ImproperFraction<N>::operator double() const
{
return static_cast<double>(numerator) / denominator;
}
template <typename N>
ostream& operator<<(ostream& os, const ImproperFraction<N>& f)
{
os << f.getNumerator() << "/" << f.getDenominator();
return os;
}
template <typename N>
istream& operator>>(istream& is, ImproperFraction<N>& f)
{
string token;
stringstream input;
getline(is, token, '/');
input << token << " ";
is >> token;
input << token;
N numerator, denominator;
input >> numerator >> denominator;
f = ImproperFraction<N>(numerator, denominator);
return is;
}
// Fraction
template <typename N1, typename N2>
Fraction<N1,N2>& Fraction<N1,N2>::reduce()
{
int temp = fraction.getInteger();
integer += temp;
fraction -= temp;
if (integer > 0 && fraction < 0)
{
integer--;
fraction++;
}
else if (integer < 0 && fraction > 0)
{
integer++;
fraction--;
}
return *this;
}
template <typename N1, typename N2>
Fraction<N1,N2>::Fraction(N1 i, N2 n, N2 d): integer(i)
{
fraction = ImproperFraction<N2>(n, d);
reduce();
}
template <typename N1, typename N2>
N1 Fraction<N1,N2>::getInteger() const
{
return integer;
}
template <typename N1, typename N2>
const ImproperFraction<N2>& Fraction<N1,N2>::getFraction() const
{
return fraction;
}
template <typename N1, typename N2>
N2 Fraction<N1,N2>::getNumerator() const
{
return fraction.getNumerator();
}
template <typename N1, typename N2>
N2 Fraction<N1,N2>::getDenominator() const
{
return fraction.getDenominator();
}
template <typename N1, typename N2>
Fraction<N1, N2>::operator double() const
{
return integer + static_cast<double>(fraction);
}
template <typename N1, typename N2>
ostream& operator<<(ostream& os, const Fraction<N1,N2>& f)
{
os << f.getInteger() << " "
<< f.getFraction();
return os;
}
template <typename N1, typename N2>
istream& operator>>(istream& is, Fraction<N1,N2>& f)
{
N1 integer;
ImproperFraction<N2> fraction;
is >> integer >> fraction;
f = Fraction<N1,N2>(integer,
fraction.getNumerator(), fraction.getDenominator());
return is;
}
template <typename N1, typename N2>
const double operator*(double l, const Fraction<N1,N2>& r)
{
return l * static_cast<double>(r);
}
#endif // FRACTION_CPP_INCLUDED
|
b0aa155ac9541df23e21c8aa5f96369c143b4a24
|
e5422975481b1283b4a8a5207c2ff9a5e0d73ff1
|
/cl_dll/hud_icons/hud_turretI_icon.cpp
|
9ea66dbc4c4d564f76b97f8dc2a0259966aab7eb
|
[] |
no_license
|
mittorn/hlwe_src
|
ae6ebd30c3dc2965f501b7e5ee460a7c7de58892
|
7abbe2ab834d636af4224a0bd0c192c958242b49
|
refs/heads/master
| 2021-01-13T16:30:25.223519
| 2015-12-01T19:07:15
| 2015-12-01T19:07:15
| 47,205,047
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,283
|
cpp
|
hud_turretI_icon.cpp
|
#include "hud.h"
#include "cl_util.h"
#include "parsemsg.h"
#include <string.h>
#include <stdio.h>
int CHudTurretIon::Init(void)
{
gHUD.AddHudElem(this);
return 1;
};
int CHudTurretIon::VidInit(void)
{
m_TURRET_I = gHUD.GetSpriteIndex( "item_turret_ion" );
return 1;
};
int CHudTurretIon::MsgFunc_TurretI(const char *pszName, int iSize, void *pbuf )
{
TurretIon = READ_BYTE();
if (TurretIon)
m_iFlags |= HUD_ACTIVE;
else
m_iFlags &= ~HUD_ACTIVE;
return 1;
}
int CHudTurretIon::Draw(float flTime)
{
if (gHUD.m_iHideHUDDisplay & ( HIDEHUD_ALL ))
return 1;
if (!(gHUD.m_iWeaponBits & (1<<(WEAPON_SUIT)) ))
return 1;
int r, g, b, x, y;
int TurretWidth = gHUD.GetSpriteRect(m_TURRET_I).right - gHUD.GetSpriteRect(m_TURRET_I).left;
x = TurretWidth/3;
y = TurretWidth/0.6;
// Draw the icon
SPR_Set(gHUD.GetSprite(m_TURRET_I), 0, 120, 0);
SPR_DrawAdditive(0, x, y, &gHUD.GetSpriteRect(m_TURRET_I));
if (TurretIon <= 50)
UnpackRGB(r,g,b, RGB_REDISH);
if (TurretIon >= 49 && TurretIon <= 99)
UnpackRGB(r,g,b, RGB_YELLOWISH);
if (TurretIon >= 100)
UnpackRGB(r,g,b, RGB_GREENISH);
x += TurretWidth;
gHUD.DrawHudNumber(x, y+YRES(5), DHN_3DIGITS, TurretIon, r, g, b);
return 1;
}
|
d588b1a3d4da2d6917d1226cfe22cf3cea1d13ca
|
d53812fbdc773fc07d52c0b5c417bc399a753cf8
|
/虚析构.cpp
|
e33fddf45fe04553c0011320c022656050d9dbd3
|
[] |
no_license
|
599801489/c-
|
ca57d69d308c7418faaba4120ce9bf825131f16f
|
2b4d06ac9b86cde9a256a89fe22e274fafda2df2
|
refs/heads/master
| 2021-05-17T13:15:58.638298
| 2020-03-28T12:55:02
| 2020-03-28T12:55:02
| 250,793,673
| 0
| 0
| null | null | null | null |
TIS-620
|
C++
| false
| false
| 440
|
cpp
|
虚析构.cpp
|
//#include<iostream>
//using namespace std;
//class father
//{
//public:
// virtual ~father() //ะ้ฮ๖นน
// {
// cout << "father";
// }
// };
//
//class son:public father
//{
//public:
// ~son()
// {
// cout << "son";
// }
//};
//
//class xiaom
//{
//public:
// ~xiaom()
// {
// cout << "xiaom";
// }
//};
//int main()
//{
// father* fa = new son;
//
//
// delete (xiaom*)fa;
// return 0;
//}
|
f84bcad5aa2099cb8199658676d0ef6cfb323549
|
c77b7116439d6768a8d2e4b730af4ab784c89e94
|
/source/frontend/graphmlparser.cpp
|
bf598caabbc512e3175d7e2c63e5065643766c72
|
[
"BSD-2-Clause"
] |
permissive
|
forsyde/f2cc
|
ae77eca7a1c0ed8a13a905cdbc9f19c7a1076ed3
|
52a00c1c4f6d4f2786bf449f1a9a1269be97802d
|
refs/heads/master
| 2020-04-14T20:56:28.746729
| 2015-08-19T07:37:46
| 2015-08-19T07:37:46
| 40,982,034
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 43,422
|
cpp
|
graphmlparser.cpp
|
/*
* Copyright (c) 2011-2013
* Gabriel Hjort Blindell <ghb@kth.se>
* George Ungureanu <ugeorge@kth.se>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 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 AUTHORS OF THIS SOFTWARE NOR THE
* COPYRIGHT HOLDERS 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 "graphmlparser.h"
#include "../ticpp/ticpp.h"
#include "../ticpp/tinyxml.h"
#include "../tools/tools.h"
#include "../forsyde/SY/mapsy.h"
#include "../forsyde/SY/parallelmapsy.h"
#include "../forsyde/SY/zipxsy.h"
#include "../forsyde/SY/unzipxsy.h"
#include "../forsyde/SY/delaysy.h"
#include "../forsyde/SY/inport.h"
#include "../forsyde/SY/outport.h"
#include "../forsyde/SY/fanoutsy.h"
#include "../forsyde/SY/zipwithnsy.h"
#include "../language/cdatatype.h"
#include "../exceptions/invalidprocessexception.h"
#include "../exceptions/invalidformatexception.h"
#include "../exceptions/castexception.h"
#include <map>
#include <list>
#include <vector>
#include <stdexcept>
#include <new>
using namespace f2cc;
using namespace f2cc::Forsyde;
using namespace f2cc::Forsyde::SY;
using ticpp::Document;
using ticpp::Node;
using ticpp::Element;
using std::string;
using std::map;
using std::pair;
using std::list;
using std::vector;
using std::bad_alloc;
GraphmlParser::GraphmlParser(Logger& logger) throw() : Frontend(logger) {}
GraphmlParser::~GraphmlParser() throw() {}
ProcessNetwork* GraphmlParser::createProcessNetwork(const string& file)
throw(InvalidArgumentException, FileNotFoundException, IOException,
ParseException, InvalidModelException, RuntimeException) {
if (file.length() == 0) {
THROW_EXCEPTION(InvalidArgumentException, "\"file\" must not be empty "
"string");
}
file_ = file;
// Read file content
string xml_data;
logger_.logMessage(Logger::INFO, string("Reading xml data from file..."));
try {
tools::readFile(file_, xml_data);
} catch (FileNotFoundException& ex) {
logger_.logMessage(Logger::ERROR, string("No xml input file \"") + file_
+ "\" could be found");
throw;
} catch (IOException& ex) {
logger_.logMessage(Logger::ERROR, string("Failed to read xml file:\n")
+ ex.getMessage());
throw;
}
// Parse content
Document xml;
try {
logger_.logMessage(Logger::INFO, "Building xml structure...");
xml.Parse(xml_data);
} catch (ticpp::Exception& ex) {
// @todo throw more detailed ParseException (with line and column)
THROW_EXCEPTION(ParseException, file_, ex.what());
}
logger_.logMessage(Logger::INFO, "Checking xml structure...");
checkXmlDocument(&xml);
logger_.logMessage(Logger::INFO, "All checks passed");
logger_.logMessage(Logger::INFO, "Generating internal processnetwork...");
ProcessNetwork* processnetwork = generateProcessNetwork(findXmlGraphElement(&xml));
return processnetwork;
}
list<Element*> GraphmlParser::getElementsByName(Node* xml, const string& name)
throw(InvalidArgumentException, IOException, RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
if (name.length() == 0) {
THROW_EXCEPTION(InvalidArgumentException, "\"name\" must not be empty "
"string");
}
list<Element*> elements;
Node* child = NULL;
while ((child = xml->IterateChildren(name, child))) {
switch (child->Type()) {
case TiXmlNode::ELEMENT: {
try {
Element* e = dynamic_cast<Element*>(child);
if (!e) THROW_EXCEPTION(CastException);
elements.push_back(e);
} catch (bad_alloc&) {
THROW_EXCEPTION(OutOfMemoryException);
}
break;
}
case TiXmlNode::DECLARATION:
case TiXmlNode::DOCUMENT:
case TiXmlNode::UNKNOWN:
case TiXmlNode::TEXT:
case TiXmlNode::STYLESHEETREFERENCE:
case TiXmlNode::TYPECOUNT: {
// Found unknown XML data; warn and remove
logger_.logMessage(Logger::WARNING,
string("Unknown XML data at line ")
+ tools::toString(child->Row()) + ", column "
+ tools::toString(child->Column()) + ":\n"
+ child->Value());
Node* prev_child = child->PreviousSibling(name, false);
xml->RemoveChild(child);
child = prev_child;
break;
}
case TiXmlNode::COMMENT: {
// Found XML comment; ignore and remove
Node* prev_child = child->PreviousSibling(name, false);
xml->RemoveChild(child);
child = prev_child;
break;
}
}
}
return elements;
}
void GraphmlParser::checkXmlDocument(Document* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
// @todo implement
logger_.logMessage(Logger::WARNING, "XML document check not implemented");
}
Element* GraphmlParser::findXmlGraphElement(Document* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
Node* xml_graphml_node = xml->FirstChild("graphml", false);
if (!xml_graphml_node) {
THROW_EXCEPTION(ParseException, file_,
string("Could not find root element \"graphml\""));
}
if (xml_graphml_node->Type() != TiXmlNode::ELEMENT) {
THROW_EXCEPTION(ParseException, file_, xml_graphml_node->Row(),
xml_graphml_node->Column(),
string("Found \"graphml\" structure is not an "
"element"));
}
Element* xml_graphml = dynamic_cast<Element*>(
xml_graphml_node);
if (!xml_graphml) THROW_EXCEPTION(CastException);
Node* xml_graph_node = xml_graphml->FirstChild("graph", false);
if (!xml_graph_node) {
THROW_EXCEPTION(ParseException, file_,
string("Could not find element \"graph\""));
}
if (xml_graph_node->Type() != TiXmlNode::ELEMENT) {
THROW_EXCEPTION(ParseException, file_, xml_graphml_node->Row(),
xml_graphml_node->Column(),
string("Found \"graph\" structure is not an element"));
}
Element* xml_graph = dynamic_cast<Element*>(xml_graph_node);
if (!xml_graph) THROW_EXCEPTION(CastException);
return xml_graph;
}
ProcessNetwork* GraphmlParser::generateProcessNetwork(Element* xml)
throw(InvalidArgumentException, ParseException, InvalidModelException,
IOException, RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
ProcessNetwork* processnetwork = new (std::nothrow) ProcessNetwork();
if (!processnetwork) THROW_EXCEPTION(OutOfMemoryException);
logger_.logMessage(Logger::DEBUG, "Parsing \"node\" elements...");
parseXmlNodes(xml, processnetwork);
logger_.logMessage(Logger::DEBUG, "Parsing \"edge\" elements...");
map<Leaf::Port*, Leaf*> copy_processs;
parseXmlEdges(xml, processnetwork, copy_processs);
return processnetwork;
}
void GraphmlParser::parseXmlNodes(Element* xml, ProcessNetwork* processnetwork)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
if (!processnetwork) {
THROW_EXCEPTION(InvalidArgumentException, "\"processnetwork\" must not be NULL");
}
list<Element*> elements = getElementsByName(xml, "node");
list<Element*>::iterator it;
for (it = elements.begin(); it != elements.end(); ++it) {
logger_.logMessage(Logger::DEBUG, string("Analyzing line "
+ tools::toString((*it)->Row())
+ "..."));
Leaf* process = generateLeaf(*it);
try {
if (!processnetwork->addProcess(process)) {
THROW_EXCEPTION(ParseException, file_, (*it)->Row(),
(*it)->Column(),
string("Multiple processs with ID \"")
+ process->getId()->getString() + "\"");
}
} catch (bad_alloc&) {
THROW_EXCEPTION(OutOfMemoryException);
}
}
}
void GraphmlParser::parseXmlEdges(Element* xml, ProcessNetwork* processnetwork,
map<Leaf::Port*, Leaf*>& copy_processs)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
if (!processnetwork) {
THROW_EXCEPTION(InvalidArgumentException, "\"processnetwork\" must not be NULL");
}
list<Element*> elements = getElementsByName(xml, "edge");
list<Element*>::iterator it;
for (it = elements.begin(); it != elements.end(); ++it) {
logger_.logMessage(Logger::DEBUG, string("Analyzing line "
+ tools::toString((*it)->Row())
+ "..."));
generateConnection(*it, processnetwork, copy_processs);
}
}
void GraphmlParser::fixProcessNetworkInputsOutputs(ProcessNetwork* processnetwork)
throw(InvalidArgumentException, IOException, RuntimeException) {
if (!processnetwork) {
THROW_EXCEPTION(InvalidArgumentException, "\"processnetwork\" must not be NULL");
}
Leaf* inport_process = NULL;
Leaf* outport_process = NULL;
// Get InPort and OutPort processs from the processnetwork
list<Leaf*> processs = processnetwork->getProcesses();
list<Leaf*>::iterator process_it;
for (process_it = processs.begin(); process_it != processs.end();
++process_it) {
Leaf* process = *process_it;
if (dynamic_cast<InPort*>(process)) {
inport_process = process;
}
if (dynamic_cast<OutPort*>(process)) {
outport_process = process;
}
}
if (!inport_process) {
THROW_EXCEPTION(IllegalStateException, "Failed to locate InPort "
"process");
}
if (!outport_process) {
THROW_EXCEPTION(IllegalStateException, "Failed to locate OutPort "
"process");
}
// Set their in and out ports as outputs and inputs to the processnetwork
list<Leaf::Port*> ports = inport_process->getOutPorts();
list<Leaf::Port*>::iterator port_it;
for (port_it = ports.begin(); port_it != ports.end(); ++port_it) {
processnetwork->addInput((*port_it)->getConnectedPort());
}
ports = outport_process->getInPorts();
for (port_it = ports.begin(); port_it != ports.end(); ++port_it) {
processnetwork->addOutput((*port_it)->getConnectedPort());
}
// Delete the processs
if (!processnetwork->deleteProcess(*inport_process->getId())) {
THROW_EXCEPTION(IllegalStateException, "Failed to delete InPort "
"process");
}
if (!processnetwork->deleteProcess(*outport_process->getId())) {
THROW_EXCEPTION(IllegalStateException, "Failed to delete OutPort "
"process");
}
}
Leaf* GraphmlParser::generateLeaf(Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
Leaf* process;
// Create process of right type
string process_id = getId(xml);
string process_type = getProcessType(xml);
tools::toLowerCase(tools::trim(process_type));
if (process_type.length() == 0) {
THROW_EXCEPTION(ParseException, file_, xml->Row(), "No process type");
}
try {
if (process_type == "inport") {
process = new InPort(Id(process_id));
}
else if (process_type == "outport") {
process = new OutPort(Id(process_id));
}
else if (process_type == "mapsy") {
process = new Map(Id(process_id), generateLeafFunction(xml));
}
else if (process_type == "parallelmapsy") {
process = new ParallelMap(Id(process_id), getNumProcesses(xml),
generateLeafFunction(xml));
}
else if (process_type == "unzipxsy") {
process = new Unzipx(Id(process_id));
}
else if (process_type == "zipxsy") {
process = new Zipx(Id(process_id));
}
else if (process_type == "delaysy") {
process = new delay(Id(process_id), getInitialDelayValue(xml));
}
else if (process_type == "zipwithnsy") {
process = new ZipWithNSY(Id(process_id),
generateLeafFunction(xml));
}
else {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
string("Unknown process type \"")
+ process_type
+ "\"");
}
}
catch (bad_alloc&) {
THROW_EXCEPTION(OutOfMemoryException);
}
if (!process) THROW_EXCEPTION(OutOfMemoryException);
logger_.logMessage(Logger::DEBUG, string("Generated ") + process->type()
+ " from \"" + process->getId()->getString() + "\"");
// Get ports
list<Element*> elements = getElementsByName(xml, "port");
list<Element*>::iterator it;
for (it = elements.begin(); it != elements.end(); ++it) {
logger_.logMessage(Logger::DEBUG,
string("Analyzing line "
+ tools::toString((*it)->Row()) + "..."));
Leaf::Port* port = generatePort(*it);
bool is_in_port = isInPort(port->getId()->getString());
bool is_out_port = isOutPort(port->getId()->getString());
if (!is_in_port && !is_out_port) {
THROW_EXCEPTION(ParseException, file_, (*it)->Row(),
(*it)->Column(), "Invalid port ID format");
}
bool port_added;
if (is_in_port) port_added = process->addInPort(*port);
else port_added = process->addOutPort(*port);
if (!port_added) {
THROW_EXCEPTION(ParseException, file_, (*it)->Row(),
(*it)->Column(), string("Multiple ")
+ (is_in_port ? "in ports" : "out ports")
+ " with the same ID \""
+ port->getId()->getString() + "\"");
}
logger_.logMessage(Logger::DEBUG, string()
+ (is_in_port ? "In" : "Out")
+ " port \"" + port->getId()->getString()
+ "\" added to process \""
+ process->getId()->getString() + "\"");
delete port;
}
return process;
}
string GraphmlParser::getId(Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
string id = xml->GetAttribute("id");
if (id.length() == 0) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
string("Element is missing \"id\" attribute"));
}
return tools::trim(id);
}
string GraphmlParser::getName(Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
string name = xml->GetAttribute("name");
if (name.length() == 0) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
string("Element is missing \"name\" attribute"));
}
return tools::trim(name);
}
string GraphmlParser::getProcessType(Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
list<Element*> elements = getElementsByName(xml, "data");
list<Element*>::iterator it;
for (it = elements.begin(); it != elements.end(); ++it) {
logger_.logMessage(Logger::DEBUG,
string("Analyzing line "
+ tools::toString((*it)->Row()) + "..."));
string attr_name = (*it)->GetAttribute("key");
if (attr_name == "process_type") {
string type = (*it)->GetText(false);
return tools::trim(type);
}
}
// No such element found
THROW_EXCEPTION(ParseException, file_, xml->Row(), "No process type found");
}
CFunction GraphmlParser::generateLeafFunction(Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
list<Element*> elements = getElementsByName(xml, "data");
list<Element*>::iterator it;
for (it = elements.begin(); it != elements.end(); ++it) {
logger_.logMessage(Logger::DEBUG,
string("Analyzing line "
+ tools::toString((*it)->Row()) + "..."));
string attr_name = (*it)->GetAttribute("key");
if (attr_name == "procfun_arg") {
string function_str = (*it)->GetText(false);
try {
CFunction function(
generateLeafFunctionFromString(function_str));
findFunctionArraySizes(function, xml);
return function;
} catch (InvalidFormatException& ex) {
THROW_EXCEPTION(ParseException, file_, (*it)->Row(),
string("Invalid process function argument: ")
+ ex.getMessage());
}
}
}
// No such element found
THROW_EXCEPTION(ParseException, file_, xml->Row(),
"No process function argument found");
}
CFunction GraphmlParser::generateLeafFunctionFromString(
const std::string& str) throw(InvalidFormatException) {
// Find function prototype and body
size_t pos = str.find("{");
if (pos == string::npos) {
pos = str.find("(");
if (pos == string::npos) {
THROW_EXCEPTION(InvalidFormatException, "No '{' " "of ')' found");
}
++pos; // Include the ')' as we need it later
}
string prototype = str.substr(0, pos);
string function_body = str.substr(pos);
// Separate input parameters and function head
pos = prototype.find("(");
size_t pos2 = prototype.find(")");
if (pos == string::npos) {
THROW_EXCEPTION(InvalidFormatException, "No '(' found in the "
"prototype");
}
if (pos2 == string::npos) {
THROW_EXCEPTION(InvalidFormatException, "No ')' found in the "
"prototype");
}
string input_params_str = prototype.substr(pos + 1, pos2 - pos - 1);
string function_head = prototype.substr(0, pos);
try {
string function_name = getNameFromDeclaration(function_head);
CDataType function_return_data_type =
getDataTypeFromDeclaration(function_head);
// Find input parameters
list<CVariable> input_parameters;
vector<string> declarations = tools::split(input_params_str, ',');
for (vector<string>::iterator it = declarations.begin();
it != declarations.end(); ++it) {
CVariable parameter = CVariable(getNameFromDeclaration(*it),
getDataTypeFromDeclaration(*it));
input_parameters.push_back(parameter);
}
return CFunction(function_name, function_return_data_type,
input_parameters, function_body);
}
catch (InvalidArgumentException& ex) {
THROW_EXCEPTION(InvalidFormatException, ex.getMessage());
}
catch (bad_alloc&) {
THROW_EXCEPTION(OutOfMemoryException);
}
}
CDataType GraphmlParser::getDataTypeFromDeclaration(const string& str) const
throw(InvalidFormatException) {
size_t pos = str.find_last_of(" ");
if (pos == string::npos) {
THROW_EXCEPTION(InvalidFormatException, "No ' ' "
"found in the variable declaration");
}
string data_type_str = str.substr(0, pos);
tools::trim(data_type_str);
if (data_type_str.length() == 0) {
THROW_EXCEPTION(InvalidFormatException, "No data type in declaration");
}
bool is_const = false;
if (data_type_str.length() >= 6 && data_type_str.substr(0, 6) == "const ") {
is_const = true;
data_type_str.erase(0, 6);
}
tools::trim(data_type_str);
if (data_type_str.length() == 0) {
THROW_EXCEPTION(InvalidFormatException, "No data type in declaration");
}
if (data_type_str.find("&") != string::npos) {
THROW_EXCEPTION(InvalidFormatException, "References are not supported");
}
if (data_type_str.length() == 0) {
THROW_EXCEPTION(InvalidFormatException, "No data type in declaration");
}
bool is_array = false;
if (data_type_str[data_type_str.length() - 1] == '*') {
is_array = true;
data_type_str.erase(data_type_str.length() - 1, 1);
}
tools::trim(data_type_str);
if (data_type_str.find("*") != string::npos) {
THROW_EXCEPTION(InvalidFormatException, "Pointer-to-pointer data types "
"are not supported");
}
if (data_type_str.length() == 0) {
THROW_EXCEPTION(InvalidFormatException, "No data type in declaration");
}
try {
CDataType::Type type = CDataType::stringToType(data_type_str);
return CDataType(type, is_array, false, 0, false, is_const);
}
catch (InvalidArgumentException& ex) {
THROW_EXCEPTION(InvalidFormatException, ex.getMessage());
}
}
string GraphmlParser::getNameFromDeclaration(const string& str) const
throw(InvalidFormatException) {
size_t pos = str.find_last_of(" ");
if (pos == string::npos) {
THROW_EXCEPTION(InvalidFormatException, "No ' ' "
"found in the variable declaration");
}
string name = str.substr(pos + 1);
tools::trim(name);
return name;
}
int GraphmlParser::getNumProcesses(ticpp::Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
list<Element*> elements = getElementsByName(xml, "data");
list<Element*>::iterator it;
for (it = elements.begin(); it != elements.end(); ++it) {
logger_.logMessage(Logger::DEBUG,
string("Analyzing line "
+ tools::toString((*it)->Row()) + "..."));
string attr_name = (*it)->GetAttribute("key");
if (attr_name == "num_processes") {
string str = (*it)->GetText(false);
tools::trim(str);
try {
return tools::toInt(str);
}
catch (InvalidArgumentException&) {
THROW_EXCEPTION(ParseException, file_, xml->Row(), "Not a "
"number");
}
}
}
// No such element found
THROW_EXCEPTION(ParseException, file_, xml->Row(), "Number of processes "
"not found");
}
void GraphmlParser::findFunctionArraySizes(CFunction& function,
ticpp::Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
list<Element*> elements = getElementsByName(xml, "port");
// If return data type or last input parameter is an array, find the array
// size by analyzing the out port XML elements
CDataType* output_data_type = NULL;
if (function.getReturnDataType()->isArray()) {
output_data_type = function.getReturnDataType();
logger_.logMessage(Logger::DEBUG, "Searching array size for return "
"data type...");
} else if (function.getNumInputParameters() > 1) {
output_data_type = function.getInputParameters().back()->getDataType();
// Reset to NULL if the parameter is not what we are looking for
if (output_data_type->isArray()) {
logger_.logMessage(Logger::DEBUG, "Searching array size for second "
"input parameter data type...");
}
else {
output_data_type = NULL;
}
}
if (output_data_type) {
list<Element*>::iterator it;
for (it = elements.begin(); it != elements.end(); ++it) {
logger_.logMessage(Logger::DEBUG,
string("Analyzing line "
+ tools::toString((*it)->Row()) + "..."));
string port_name = getName(*it);
if (isOutPort(port_name)) {
size_t array_size = findArraySize(*it);
if (array_size > 0) {
logger_.logMessage(Logger::DEBUG,
string("Found array size ")
+ tools::toString(array_size));
output_data_type->setArraySize(array_size);
}
break;
}
}
}
// Find array sizes for the input parameters which are arrays by analyzing
// the in port XML elements
list<CVariable*> parameters = function.getInputParameters();
list<CVariable*>::iterator param_it = parameters.begin();
list<CVariable*>::iterator param_stop_point;
list<Element*>::iterator xml_it = elements.begin();
if (function.getNumInputParameters() > 1) {
param_stop_point = --parameters.end();
}
else {
param_stop_point = parameters.end();
}
while (param_it != param_stop_point && xml_it != elements.end()) {
if (param_it == parameters.begin()) {
logger_.logMessage(Logger::DEBUG, "Searching array size for "
"input parameter data type...");
}
logger_.logMessage(Logger::DEBUG,
string("Analyzing line "
+ tools::toString((*xml_it)->Row())
+ "..."));
if (!isInPort(getName(*xml_it))) {
logger_.logMessage(Logger::DEBUG, "Not an in port, moving to next");
++xml_it;
continue;
}
if ((*param_it)->getDataType()->isArray()) {
size_t array_size = findArraySize(*xml_it);
if (array_size > 0) {
logger_.logMessage(Logger::DEBUG,
string("Found array size ")
+ tools::toString(array_size));
(*param_it)->getDataType()->setArraySize(array_size);
}
else {
logger_.logMessage(Logger::DEBUG, "No array size key");
}
}
++param_it;
++xml_it;
}
}
size_t GraphmlParser::findArraySize(ticpp::Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
list<Element*> elements = getElementsByName(xml, "data");
list<Element*>::iterator it;
for (it = elements.begin(); it != elements.end(); ++it) {
logger_.logMessage(Logger::DEBUG,
string("Analyzing line "
+ tools::toString((*it)->Row()) + "..."));
string attr_name = (*it)->GetAttribute("key");
if (attr_name == "array_size") {
string array_size_str = (*it)->GetText(false);
if (!tools::isNumeric(array_size_str)) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
"Array size must be numeric");
}
int array_size = tools::toInt(array_size_str);
if (array_size < 1) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
"Array size must not be less than 1");
}
return (size_t) array_size;
}
}
// No such element found
return 0;
}
string GraphmlParser::getInitialDelayValue(Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
list<Element*> elements = getElementsByName(xml, "data");
list<Element*>::iterator it;
for (it = elements.begin(); it != elements.end(); ++it) {
logger_.logMessage(Logger::DEBUG,
string("Analyzing line "
+ tools::toString((*it)->Row()) + "..."));
string attr_name = (*it)->GetAttribute("key");
if (attr_name == "initial_value") {
string value = (*it)->GetText(false);
tools::trim(value);
if (value.length() == 0) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
"No initial delay value found");
}
return value;
}
}
// No such element found
THROW_EXCEPTION(ParseException, file_, xml->Row(),
"No initial delay value found");
}
Leaf::Port* GraphmlParser::generatePort(Element* xml)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
Leaf::Port* port = new (std::nothrow) Leaf::Port(getName(xml));
if (!port) THROW_EXCEPTION(OutOfMemoryException);
logger_.logMessage(Logger::DEBUG,
string("Generated port \"") + port->getId()->getString()
+ "\"");
return port;
}
bool GraphmlParser::isInPort(const std::string& id) const throw() {
return isValidPortId(id, "in");
}
bool GraphmlParser::isOutPort(const std::string& id) const throw() {
return isValidPortId(id, "out");
}
bool GraphmlParser::isValidPortId(const std::string& id,
const std::string direction) const throw() {
try {
size_t separator_pos = id.find_last_of("_");
size_t direction_pos =
separator_pos == string::npos ? 0 : separator_pos + 1;
// Check direction
if (id.substr(direction_pos, direction.length()) != direction) {
return false;
}
// Check that the part after the direction is numeric, if any
if (direction_pos + direction.length() < id.length()) {
string remaining(id.substr(direction_pos + direction.length()));
if (!tools::isNumeric(remaining)) return false;
// All tests passed
return true;
}
else {
// No trailing numeric part
return true;
}
} catch (std::out_of_range&) {
// Do nothing, but a check will fail because of this
}
return false;
}
void GraphmlParser::generateConnection(Element* xml, ProcessNetwork* processnetwork,
map<Leaf::Port*, Leaf*>&
copy_processs)
throw(InvalidArgumentException, ParseException, IOException,
RuntimeException) {
if (!xml) {
THROW_EXCEPTION(InvalidArgumentException, "\"xml\" must not be NULL");
}
if (!processnetwork) {
THROW_EXCEPTION(InvalidArgumentException, "\"processnetwork\" must not be NULL");
}
// Get source process ID
string source_process_id = xml->GetAttribute("source");
if (source_process_id.length() == 0) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
"\"edge\" element is missing \"source\" attribute");
}
// Get source process port ID
string source_process_port_id = xml->GetAttribute("sourceport");
if (source_process_port_id.length() == 0) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
"\"edge\" element is missing \"sourceport\" attribute");
}
// Get target process ID
string target_process_id = xml->GetAttribute("target");
if (target_process_id.length() == 0) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
"\"edge\" element is missing \"target\" attribute");
}
// Get target process port ID
string target_process_port_id = xml->GetAttribute("targetport");
if (target_process_port_id.length() == 0) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
"\"edge\" element is missing \"targetport\" attribute");
}
// Get source and target processs
Leaf* source_process = processnetwork->getProcess(source_process_id);
if (source_process == NULL) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
string("No source process \"")
+ source_process_id + "\" found");
}
Leaf* target_process = processnetwork->getProcess(target_process_id);
if (target_process == NULL) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
string("No target process \"")
+ target_process_id + "\" found");
}
// Get source and target ports
Leaf::Port* source_port =
source_process->getOutPort(source_process_port_id);
if (!source_port) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
string("No source process out port \"")
+ source_process_id + ":"
+ source_process_port_id + "\" ");
}
Leaf::Port* target_port =
target_process->getInPort(target_process_port_id);
if (!target_port) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
string("No target process in port \"")
+ target_process_id + ":"
+ target_process_port_id + "\" found");
}
// Check that the target port is not already connected to another port
if (target_port->isConnected()) {
THROW_EXCEPTION(ParseException, file_, xml->Row(),
string("Target port \"")
+ target_process_id + ":"
+ target_process_port_id
+ "\" is already connected to another port");
}
// Make port connections
if (!source_port->isConnected()) {
source_port->connect(target_port);
logger_.logMessage(Logger::DEBUG,
string("Connected port \"")
+ source_port->toString() + "\" with \""
+ target_port->toString() + "\"");
}
else {
// Source port already connected; use intermediate Fanout process
logger_.logMessage(Logger::DEBUG,
string("Source port \"")
+ source_port->toString() + "\" already connected "
+ "to \""
+ source_port->getConnectedPort()->toString()
+ "\". Using intermediate Fanout process.");
// Get Fanout process
Leaf* copy_process;
map<Leaf::Port*, Leaf*>::iterator it =
copy_processs.find(source_port);
if (it != copy_processs.end()) {
copy_process = it->second;
}
else {
// No such Fanout process; create a new one
copy_process = new (std::nothrow)
Fanout(processnetwork->getUniqueProcessId("_copySY_"));
if (copy_process == NULL) THROW_EXCEPTION(OutOfMemoryException);
copy_processs.insert(pair<Leaf::Port*, Leaf*>(source_port,
copy_process));
logger_.logMessage(Logger::DEBUG, string("New Fanout process \"")
+ copy_process->getId()->getString()
+ "\" created");
// Add to processnetwork
if (!processnetwork->addProcess(copy_process)) {
THROW_EXCEPTION(IllegalStateException, string("Failed to ")
+ "add new process: Leaf with ID \""
+ copy_process->getId()->getString()
+ "\" already existed");
}
logger_.logMessage(Logger::DEBUG, string("New process \"")
+ copy_process->getId()->getString()
+ "\" added to the processnetwork");
// Break the current connection and connect the source and previous
// target connection through the Fanout process
if(!copy_process->addInPort(Id("in"))) {
THROW_EXCEPTION(IllegalStateException, string("Failed to add ")
+ "in port to process \""
+ copy_process->getId()->getString() + "\"");
}
Leaf::Port* old_target_port = dynamic_cast<Leaf::Port*>(source_port->getConnectedPort());
source_port->unconnect();
logger_.logMessage(Logger::DEBUG,
string("Broke port connection \"")
+ source_port->toString() + "\"--\""
+ old_target_port->toString() + "\"");
source_port->connect(copy_process->getInPorts().front());
logger_.logMessage(Logger::DEBUG,
string("Connected port \"")
+ source_port->toString()
+ "\" with \""
+ copy_process->getInPorts().front()->toString()
+ "\"");
if(!copy_process->addOutPort(Id("out1"))) {
THROW_EXCEPTION(IllegalStateException, string("Failed to add ")
+ "out port to process \""
+ copy_process->getId()->getString() + "\"");
}
old_target_port->connect(copy_process->getOutPorts().front());
logger_.logMessage(Logger::DEBUG,
string("Connected port \"")
+ copy_process->getOutPorts().front()->toString()
+ "\" with \""
+ old_target_port->toString() + "\"");
}
string new_out_port_id = string("out")
+ tools::toString(copy_process->getOutPorts().size() + 1);
if(!copy_process->addOutPort(new_out_port_id)) {
THROW_EXCEPTION(IllegalStateException, string("Failed to add ")
+ "out port to process \""
+ copy_process->getId()->getString() + "\"");
}
target_port->connect(copy_process->getOutPorts().back());
logger_.logMessage(Logger::DEBUG,
string("Connected port \"")
+ copy_process->getOutPorts().back()->toString()
+ "\" with \""
+ target_port->toString() + "\"");
}
}
void GraphmlParser::checkProcessNetworkMore(ProcessNetwork* processnetwork)
throw(InvalidArgumentException, InvalidModelException, IOException,
RuntimeException) {
bool found_in_port_process = false;
bool found_out_port_process = false;
list<Leaf*> processs = processnetwork->getProcesses();
list<Leaf*>::iterator process_it;
for (process_it = processs.begin(); process_it != processs.end();
++process_it) {
Leaf* process = *process_it;
logger_.logMessage(Logger::DEBUG,
string("Checking process \"")
+ process->getId()->getString() + "\"");
// In- and OutPort presence check
if (dynamic_cast<InPort*>(process)) {
if (!found_in_port_process) {
found_in_port_process = true;
}
else {
THROW_EXCEPTION(InvalidModelException,
"Only one \"InPort\" process is allowed");
}
}
if (dynamic_cast<OutPort*>(process)) {
if (!found_out_port_process) {
found_out_port_process = true;
}
else {
THROW_EXCEPTION(InvalidModelException,
"Only one \"OutPort\" process is allowed");
}
}
}
if (!found_out_port_process) {
THROW_EXCEPTION(InvalidModelException,
"No \"OutPort\" process found");
}
}
void GraphmlParser::postCheckFixes(Forsyde::ProcessNetwork* processnetwork)
throw(InvalidArgumentException, IOException, RuntimeException) {
fixProcessNetworkInputsOutputs(processnetwork);
}
|
583707d7a15edd5ba049b1747399dd243df38464
|
42385b77d4fbbb4db6f8cd5b15a5f2cc02ba0e3c
|
/signals/discritsignals_filetransfer.h
|
5abd70d6f2432da246297527b14ba41b041c640f
|
[] |
no_license
|
jom-everest/poisk_technical-test
|
e2f98b9b0e2a4ca5dfd3a5ad2627f4480bfc3b6b
|
b7a9624e7e623c28d5951b9a47a0b86934f3e150
|
refs/heads/master
| 2021-08-24T07:49:16.792118
| 2017-12-08T18:21:09
| 2017-12-08T18:21:09
| 112,857,094
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,032
|
h
|
discritsignals_filetransfer.h
|
#ifndef discreTSIGNALS_FILETRANSFER_H
#define discreTSIGNALS_FILETRANSFER_H
#include <string>
#include "consts.h"
#include "struct_signals.h"
class DiscretSignals_FileTransfer
{
std::string fileName = DISCRET_DATA_TRANSFER_FILENAME;
public:
bool readFromFile(DiscretSignalsSet& set) {
char byte;
std::ifstream ifs(fileName, std::ifstream::in | std::ifstream::binary);
ifs.get(byte);
if (!ifs.good()) return false;
set.values[0] = byte & 0x01;
set.values[1] = (byte & 0x02) >> 1;
set.values[2] = (byte & 0x04) >> 2;
set.values[3] = (byte & 0x08) >> 3;
return true;
}
bool writeToFile(const DiscretSignalsSet& set) {
std::ofstream ofs (fileName, std::ofstream::trunc | std::ofstream::binary);
char byte = char((set.values[3]<<3) + (set.values[2]<<2) + (set.values[1]<<1) + set.values[0]);
ofs << byte;
if (!ofs.good()) return false;
return true;
}
};
#endif // discreTSIGNALS_FILETRANSFER_H
|
bd11fa96675aa48e5dfda059c2001667b4949340
|
ee7f198fffb71570ddaeb3225e04de48d8653633
|
/Cache_optimization/src/exec/main2.cpp
|
98826c15769284449249e2412e0058c51826167e
|
[] |
no_license
|
joeburg/side-projects
|
0cbece5a0c878e40734008f8f4252ddb65b2f3de
|
0400a511994ab51f3a2c6110f050c829c0528cdf
|
refs/heads/master
| 2021-01-25T11:03:25.999174
| 2017-06-22T08:16:30
| 2017-06-22T08:16:30
| 93,974,175
| 2
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,040
|
cpp
|
main2.cpp
|
#include <iomanip>
#include <iostream>
#include <memory>
#include "timer.h"
#include "utilities.hpp"
int main(void)
{
// initialize matrix size, padding and blocksize
int size = 4096;
int ldim = 4096+16;
int blocksize = 256;
double *a = new double[ldim*size];
initmatrix(a,size,ldim);
std::cout << "Running OptimizedTranspose()" << std::endl;
double t0 = timer();
int val = OptimizedTranspose(a,size,ldim,blocksize);
double elapsedtime = timer() - t0;
if (val == 1)
{
std::cout << "The transpose operation was unsuccessful!" << std::endl;
return 0;
}
else if (val == 2)
{
std::cout << "The block size must be a divisor of the matrix size." << std::endl;
return 0;
}
else
{
double bandwidth = 2*size*size*(double)sizeof(double)/1.e9/elapsedtime;
std::cout << "Effective bandwidth: " << std::fixed << std::setprecision(3) << bandwidth << " GB/sec" << std::endl;
}
delete[] a;
return 0;
}
|
4bd04cdc1365ef53da07fd557502a3a14163d869
|
89d113159b17f92e7ee245c0caa2ccccb2aed7c2
|
/include/i_subscriber.hpp
|
6cf2c622ddb564f9a340e4d7bbb17ca615565d4a
|
[] |
no_license
|
vell999/github-upload
|
be579d2fadf9ed5a6f56f4c06ce33489abb5cc6c
|
988eea89a860e231f7e29763333dcfbe2244c664
|
refs/heads/master
| 2023-05-12T03:47:29.255213
| 2021-06-02T12:14:38
| 2021-06-02T12:14:38
| 373,141,271
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 499
|
hpp
|
i_subscriber.hpp
|
#ifndef I_SUBSCRIBER_H
#define I_SUBSCRIBER_H
#include "i_event.hpp"
#include "shared_pointer.hpp"
using namespace advcpp;
namespace smarthome
{
class ISubscriber
{
public:
virtual ~ISubscriber() noexcept = 0;
virtual void Notify(SharedPointer<IEvent> a_event) = 0;
protected:
ISubscriber() = default;
ISubscriber(ISubscriber const& a_event) = default;
ISubscriber & operator = (const ISubscriber & a_event) = default;
};
} // namespace smarthome
#endif // I_SUBSCRIBER_H
|
d98c505dc73e5aedbf0f09353384b1217b2e0f88
|
73709039ac2b42e410c4d1d7b862e4e352a74599
|
/ipms_server_api/IPMS_config_so/ConfigTest.cpp
|
590877ef15d1b5be775599f561e395387d352e3d
|
[] |
no_license
|
GarfieldLinux/IPMS
|
a0743629325032b3319d0bb713ed624d0f5c19b7
|
21fab7a2513c402c0c3b3314c974ad7ab0e21a9c
|
refs/heads/master
| 2020-05-29T21:04:21.731270
| 2014-09-24T14:02:23
| 2014-09-24T14:02:23
| 19,529,124
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,412
|
cpp
|
ConfigTest.cpp
|
/*
* =====================================================================================
*
* Filename: ConfigTest.cpp
*
* Description:
*
* Version: 1.0
* Created: 2011年06月18日 23时11分07秒
* Revision: none
* Compiler: gcc
*
* Author: GarfieldLinux (zjf), garfieldlinux@gmail.com
* Company: 南通天联信息技术
*
* =====================================================================================
*/
#include "Config.h"
int main()
{
int port;
std::string ipAddress;
std::string username;
std::string password;
std::string dbname;
//const char ConfigFile[]= "ipms.conf";
const char ConfigFile[]= "IPMS.conf" ;
Config configSettings(ConfigFile);
port = configSettings.Read("port", 0);
ipAddress = configSettings.Read("ipAddress", ipAddress);
username = configSettings.Read("username", username);
password = configSettings.Read("password", password);
dbname = configSettings.Read("dbname",dbname);
std::cout<<"port:"<<port<<std::endl;
std::cout<<"ipAddress:"<<ipAddress<<std::endl;
std::cout<<"username:"<<username<<std::endl;
std::cout<<"password:"<<password<<std::endl;
std::cout<<"dbname:"<<dbname<<std::endl;
return 0;
}
|
09c6fe755f9ccc88a7427f5cf7fa1e552473f5d1
|
d093e5dbdf4fb08eacbe2ec3cfc070e4c58c0f3e
|
/Source/Modules/MMOEngine/SubSystem/RCMLogic.cpp
|
defc2c90739d65fb34382175221363c27bc03967
|
[
"MIT"
] |
permissive
|
RamilGauss/MMO-Framework
|
3bd57e800f20b6447b494009eb3d7a49dfeb1402
|
fa4ec6427a3a891954f97311af626f8753023ec2
|
refs/heads/master
| 2023-09-02T17:50:25.742920
| 2023-09-01T09:17:26
| 2023-09-01T09:17:26
| 15,496,543
| 32
| 20
|
MIT
| 2023-05-11T07:10:07
| 2013-12-28T17:54:28
|
C++
|
UTF-8
|
C++
| false
| false
| 928
|
cpp
|
RCMLogic.cpp
|
/*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information LICENSE.md.
*/
#include "RCMLogic.h"
using namespace nsMMOEngine;
TRCMLogic::TRCMLogic(TBase* p) : TBaseMasterLogic(p)
{
}
//-------------------------------------------------------------------------------------------
void TRCMLogic::EndRcm(IScenario* pSc)
{
}
//-------------------------------------------------------------------------
void TRCMLogic::NeedContextByClientKeyRcm(unsigned int clientKey)
{
}
//-------------------------------------------------------------------------
void TRCMLogic::NeedSlaveSessionDonorRcm(IScenario* pSc)
{
}
//-------------------------------------------------------------------------
void TRCMLogic::EventActivateRcm(IScenario* pSc)
{
}
//-------------------------------------------------------------------------
|
3b1e1eead59a6861d46878e18af685b8e287bcf6
|
e0a0d45181c1d0b0f0aa3d4dd977fc7bec4d21bb
|
/vision/run_map.cc
|
2b6621ae5f8a1ecd8709e1b99a483fcd61dcb424
|
[
"MIT"
] |
permissive
|
jpanikulam/experiments
|
71004ff701f4552c932eb6958a0bcd3de76ee383
|
be36319a89f8baee54d7fa7618b885edb7025478
|
refs/heads/master
| 2021-01-12T01:35:15.817397
| 2020-01-24T00:59:12
| 2020-01-24T00:59:17
| 78,386,199
| 1
| 1
|
MIT
| 2018-12-29T00:54:28
| 2017-01-09T02:24:16
|
C++
|
UTF-8
|
C++
| false
| false
| 3,795
|
cc
|
run_map.cc
|
#include "block_transform.hh"
#include "features.hh"
#include "histogram_equalize.hh"
#include "images.hh"
#include "io.hh"
#include "pyramid.hh"
#include "util/clamp.hh"
#include "eigen.hh"
#include <iostream>
#include <opencv2/opencv.hpp>
using Vec2 = Eigen::Vector2f;
struct MappingContext {
cv::Mat rgb_image;
std::vector<Vec2> points;
};
void visualize(const MappingContext &context) {
cv::Mat visualization_image = context.rgb_image;
for (const auto &point : context.points) {
constexpr int RADIUS = 1;
const cv::Scalar COLOR(0, 255, 0);
cv::circle(visualization_image, cv::Point(point.x(), point.y()), RADIUS, COLOR);
}
cv::imshow("Visualization", visualization_image);
}
cv::Mat normalize(const cv::Mat &grayscale_image) {
// Compute a block normalization of an grayscale_image
cv::Mat_<float> float_gs_image;
grayscale_image.convertTo(float_gs_image, CV_32FC1);
double min, max;
cv::minMaxLoc(float_gs_image, &min, &max);
return (float_gs_image - min) / (max - min);
}
std::vector<Vec2> extract_harris_features(const cv::Mat &image) {
constexpr double RELATIVE_SCALE = 1.0;
constexpr double INV_RELATIVE_SCALE = 1.0 / RELATIVE_SCALE;
cv::Mat scaled_image;
cv::resize(image, scaled_image, cv::Size(0, 0), RELATIVE_SCALE, RELATIVE_SCALE);
const cv::Mat normalized = normalize(scaled_image);
const float mean = cv::mean(normalized)[0];
cv::Mat mean_subtracted = normalized - mean;
cv::imshow("Gombo", normalized - mean);
float const *const pixel_ptr = (float *)mean_subtracted.data;
std::vector<Vec2> locations;
for (int col = 0; col < mean_subtracted.cols; ++col) {
for (int row = 0; row < mean_subtracted.rows; ++row) {
const int index = row * (mean_subtracted.cols) + col;
const float pixel_val = pixel_ptr[index];
constexpr float NORMALIZED_THRESHOLD = 0.05;
if (pixel_val > NORMALIZED_THRESHOLD) {
locations.emplace_back(col * INV_RELATIVE_SCALE, row * INV_RELATIVE_SCALE);
}
}
}
return locations;
}
int main() {
const auto image_and_depth_locations = slam::get_both();
for (const auto &location_pair : image_and_depth_locations) {
const cv::Mat image = cv::imread(location_pair.image);
const cv::Mat depth = cv::imread(location_pair.depth, CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat gray_image;
cv::cvtColor(image, gray_image, CV_BGR2GRAY);
const cv::Mat_<float> normalized_gray_image = normalize(gray_image);
constexpr int BLOCK_TRANSFORM_SIZE = 100;
const cv::Mat equalized = slam::block_transform<BLOCK_TRANSFORM_SIZE>(gray_image, slam::histogram_equalize);
cv::imshow("Equalized", equalized);
const auto get_harris = [&](const cv::Mat &sub_img) {
constexpr int HARRIS_BLOCK_SIZE = 2;
constexpr int HARRIS_K_SIZE = 5;
constexpr double HARRIS_FREE_PARAMETER = 0.0001;
cv::Mat temp_harris_image;
cornerHarris(sub_img, temp_harris_image, HARRIS_BLOCK_SIZE, HARRIS_K_SIZE, HARRIS_FREE_PARAMETER);
return temp_harris_image;
};
const cv::Mat harris_image = slam::block_transform<BLOCK_TRANSFORM_SIZE>(normalize(equalized), get_harris);
double min, max;
cv::minMaxLoc(harris_image, &min, &max);
std::cout << harris_image.size() << std::endl;
std::cout << "MIN: " << min << std::endl;
std::cout << "MAX: " << max << std::endl;
cv::imshow("Determinants", harris_image);
cv::imshow("Input", image);
// const auto pts = extract_harris_features(harris_image);
// MappingContext context;
// context.points = pts;
// context.rgb_image = image;
// visualize(context);
const int key = cv::waitKey(0);
if (key == 113 || key == 1048689) {
break;
}
}
}
|
7c7a2583d0a8097c103b8c98a44c71f070d7122c
|
74f8a44af74bd12951c5abc0fe4af82f5601aba1
|
/others/1931/main.cpp
|
6a6dac07d5feff5c36f3e2da76c07d58ec718cb4
|
[] |
no_license
|
skeleton625/BOJ
|
104060269a4a6996536558e65921c5302d58daee
|
936dbb405846de1b358aecfda1d0c0bb19b12d7b
|
refs/heads/master
| 2023-01-09T16:46:12.112568
| 2023-01-08T12:05:00
| 2023-01-08T12:05:00
| 176,702,443
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 378
|
cpp
|
main.cpp
|
#include <cstdio>
#include <algorithm>
typedef std::pair<int, int> meet;
meet *m;
int n;
int main() {
scanf_s("%d", &n);
m = new meet[n];
for (int i = 0; i < n; i++)
scanf_s("%d %d", &m[i].second, &m[i].first);
sort(m, m + n);
int p = 0, c = 1;
for (int i = 1; i < n; i++) {
if (m[i].second >= m[p].first) {
p = i;
c++;
}
}
printf("%d", c);
return 0;
}
|
6ef02e77926d3646efcbb064f9a29ebc95912397
|
b37d708f880ccd1b97eec929d603e860d0a202e2
|
/autogenerated/adverseevent-pskel.cxx
|
9c31493cbca30799e8ec277b5838b82990ffcf1b
|
[] |
no_license
|
lucatoldo/arduino-fhir
|
a19b03e0a194fd54b31036da504c21dd06929fd0
|
d591300758fb7e294265ccf974036fff706d9fcb
|
refs/heads/master
| 2021-05-17T12:19:47.518299
| 2020-03-28T11:05:15
| 2020-03-28T11:05:15
| 250,772,241
| 0
| 0
| null | 2020-03-28T11:03:27
| 2020-03-28T11:03:27
| null |
UTF-8
|
C++
| false
| false
| 53,786
|
cxx
|
adverseevent-pskel.cxx
|
// Copyright (c) 2005-2020 Code Synthesis Tools CC.
//
// This program was generated by CodeSynthesis XSD/e, an XML Schema
// to C++ data binding compiler for embedded systems.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
//
// Begin prologue.
//
//
// End prologue.
#include <xsde/cxx/pre.hxx>
#include "adverseevent-pskel.hxx"
namespace fhir
{
// AdverseEvent_pskel
//
void AdverseEvent_pskel::
identifier_parser (::fhir::Identifier_pskel& p)
{
this->identifier_parser_ = &p;
}
void AdverseEvent_pskel::
actuality_parser (::fhir::AdverseEventActuality_pskel& p)
{
this->actuality_parser_ = &p;
}
void AdverseEvent_pskel::
category_parser (::fhir::CodeableConcept_pskel& p)
{
this->category_parser_ = &p;
}
void AdverseEvent_pskel::
event_parser (::fhir::CodeableConcept_pskel& p)
{
this->event_parser_ = &p;
}
void AdverseEvent_pskel::
subject_parser (::fhir::Reference_pskel& p)
{
this->subject_parser_ = &p;
}
void AdverseEvent_pskel::
encounter_parser (::fhir::Reference_pskel& p)
{
this->encounter_parser_ = &p;
}
void AdverseEvent_pskel::
date_parser (::fhir::dateTime_pskel& p)
{
this->date_parser_ = &p;
}
void AdverseEvent_pskel::
detected_parser (::fhir::dateTime_pskel& p)
{
this->detected_parser_ = &p;
}
void AdverseEvent_pskel::
recordedDate_parser (::fhir::dateTime_pskel& p)
{
this->recordedDate_parser_ = &p;
}
void AdverseEvent_pskel::
resultingCondition_parser (::fhir::Reference_pskel& p)
{
this->resultingCondition_parser_ = &p;
}
void AdverseEvent_pskel::
location_parser (::fhir::Reference_pskel& p)
{
this->location_parser_ = &p;
}
void AdverseEvent_pskel::
seriousness_parser (::fhir::CodeableConcept_pskel& p)
{
this->seriousness_parser_ = &p;
}
void AdverseEvent_pskel::
severity_parser (::fhir::CodeableConcept_pskel& p)
{
this->severity_parser_ = &p;
}
void AdverseEvent_pskel::
outcome_parser (::fhir::CodeableConcept_pskel& p)
{
this->outcome_parser_ = &p;
}
void AdverseEvent_pskel::
recorder_parser (::fhir::Reference_pskel& p)
{
this->recorder_parser_ = &p;
}
void AdverseEvent_pskel::
contributor_parser (::fhir::Reference_pskel& p)
{
this->contributor_parser_ = &p;
}
void AdverseEvent_pskel::
suspectEntity_parser (::fhir::AdverseEvent_SuspectEntity_pskel& p)
{
this->suspectEntity_parser_ = &p;
}
void AdverseEvent_pskel::
subjectMedicalHistory_parser (::fhir::Reference_pskel& p)
{
this->subjectMedicalHistory_parser_ = &p;
}
void AdverseEvent_pskel::
referenceDocument_parser (::fhir::Reference_pskel& p)
{
this->referenceDocument_parser_ = &p;
}
void AdverseEvent_pskel::
study_parser (::fhir::Reference_pskel& p)
{
this->study_parser_ = &p;
}
void AdverseEvent_pskel::
parsers (::fhir::id_pskel& id,
::fhir::Meta_pskel& meta,
::fhir::uri_pskel& implicitRules,
::fhir::code_pskel& language,
::fhir::Narrative_pskel& text,
::fhir::ResourceContainer_pskel& contained,
::fhir::Extension_pskel& extension,
::fhir::Extension_pskel& modifierExtension,
::fhir::Identifier_pskel& identifier,
::fhir::AdverseEventActuality_pskel& actuality,
::fhir::CodeableConcept_pskel& category,
::fhir::CodeableConcept_pskel& event,
::fhir::Reference_pskel& subject,
::fhir::Reference_pskel& encounter,
::fhir::dateTime_pskel& date,
::fhir::dateTime_pskel& detected,
::fhir::dateTime_pskel& recordedDate,
::fhir::Reference_pskel& resultingCondition,
::fhir::Reference_pskel& location,
::fhir::CodeableConcept_pskel& seriousness,
::fhir::CodeableConcept_pskel& severity,
::fhir::CodeableConcept_pskel& outcome,
::fhir::Reference_pskel& recorder,
::fhir::Reference_pskel& contributor,
::fhir::AdverseEvent_SuspectEntity_pskel& suspectEntity,
::fhir::Reference_pskel& subjectMedicalHistory,
::fhir::Reference_pskel& referenceDocument,
::fhir::Reference_pskel& study)
{
this->id_parser_ = &id;
this->meta_parser_ = &meta;
this->implicitRules_parser_ = &implicitRules;
this->language_parser_ = &language;
this->text_parser_ = &text;
this->contained_parser_ = &contained;
this->extension_parser_ = &extension;
this->modifierExtension_parser_ = &modifierExtension;
this->identifier_parser_ = &identifier;
this->actuality_parser_ = &actuality;
this->category_parser_ = &category;
this->event_parser_ = &event;
this->subject_parser_ = &subject;
this->encounter_parser_ = &encounter;
this->date_parser_ = &date;
this->detected_parser_ = &detected;
this->recordedDate_parser_ = &recordedDate;
this->resultingCondition_parser_ = &resultingCondition;
this->location_parser_ = &location;
this->seriousness_parser_ = &seriousness;
this->severity_parser_ = &severity;
this->outcome_parser_ = &outcome;
this->recorder_parser_ = &recorder;
this->contributor_parser_ = &contributor;
this->suspectEntity_parser_ = &suspectEntity;
this->subjectMedicalHistory_parser_ = &subjectMedicalHistory;
this->referenceDocument_parser_ = &referenceDocument;
this->study_parser_ = &study;
}
AdverseEvent_pskel::
AdverseEvent_pskel (::fhir::DomainResource_pskel* tiein)
: ::fhir::DomainResource_pskel (tiein, 0),
AdverseEvent_impl_ (0),
identifier_parser_ (0),
actuality_parser_ (0),
category_parser_ (0),
event_parser_ (0),
subject_parser_ (0),
encounter_parser_ (0),
date_parser_ (0),
detected_parser_ (0),
recordedDate_parser_ (0),
resultingCondition_parser_ (0),
location_parser_ (0),
seriousness_parser_ (0),
severity_parser_ (0),
outcome_parser_ (0),
recorder_parser_ (0),
contributor_parser_ (0),
suspectEntity_parser_ (0),
subjectMedicalHistory_parser_ (0),
referenceDocument_parser_ (0),
study_parser_ (0),
v_state_stack_ (sizeof (v_state_), &v_state_first_)
{
}
AdverseEvent_pskel::
AdverseEvent_pskel (AdverseEvent_pskel* impl, void*)
: ::fhir::DomainResource_pskel (impl, 0),
AdverseEvent_impl_ (impl),
identifier_parser_ (0),
actuality_parser_ (0),
category_parser_ (0),
event_parser_ (0),
subject_parser_ (0),
encounter_parser_ (0),
date_parser_ (0),
detected_parser_ (0),
recordedDate_parser_ (0),
resultingCondition_parser_ (0),
location_parser_ (0),
seriousness_parser_ (0),
severity_parser_ (0),
outcome_parser_ (0),
recorder_parser_ (0),
contributor_parser_ (0),
suspectEntity_parser_ (0),
subjectMedicalHistory_parser_ (0),
referenceDocument_parser_ (0),
study_parser_ (0),
v_state_stack_ (sizeof (v_state_), &v_state_first_)
{
}
// AdverseEvent_SuspectEntity_pskel
//
void AdverseEvent_SuspectEntity_pskel::
instance_parser (::fhir::Reference_pskel& p)
{
this->instance_parser_ = &p;
}
void AdverseEvent_SuspectEntity_pskel::
causality_parser (::fhir::AdverseEvent_Causality_pskel& p)
{
this->causality_parser_ = &p;
}
void AdverseEvent_SuspectEntity_pskel::
parsers (::fhir::string_primitive_pskel& id,
::fhir::Extension_pskel& extension,
::fhir::Extension_pskel& modifierExtension,
::fhir::Reference_pskel& instance,
::fhir::AdverseEvent_Causality_pskel& causality)
{
this->id_parser_ = &id;
this->extension_parser_ = &extension;
this->modifierExtension_parser_ = &modifierExtension;
this->instance_parser_ = &instance;
this->causality_parser_ = &causality;
}
AdverseEvent_SuspectEntity_pskel::
AdverseEvent_SuspectEntity_pskel (::fhir::BackboneElement_pskel* tiein)
: ::fhir::BackboneElement_pskel (tiein, 0),
AdverseEvent_SuspectEntity_impl_ (0),
instance_parser_ (0),
causality_parser_ (0),
v_state_stack_ (sizeof (v_state_), &v_state_first_)
{
}
AdverseEvent_SuspectEntity_pskel::
AdverseEvent_SuspectEntity_pskel (AdverseEvent_SuspectEntity_pskel* impl, void*)
: ::fhir::BackboneElement_pskel (impl, 0),
AdverseEvent_SuspectEntity_impl_ (impl),
instance_parser_ (0),
causality_parser_ (0),
v_state_stack_ (sizeof (v_state_), &v_state_first_)
{
}
// AdverseEvent_Causality_pskel
//
void AdverseEvent_Causality_pskel::
assessment_parser (::fhir::CodeableConcept_pskel& p)
{
this->assessment_parser_ = &p;
}
void AdverseEvent_Causality_pskel::
productRelatedness_parser (::fhir::string_pskel& p)
{
this->productRelatedness_parser_ = &p;
}
void AdverseEvent_Causality_pskel::
author_parser (::fhir::Reference_pskel& p)
{
this->author_parser_ = &p;
}
void AdverseEvent_Causality_pskel::
method_parser (::fhir::CodeableConcept_pskel& p)
{
this->method_parser_ = &p;
}
void AdverseEvent_Causality_pskel::
parsers (::fhir::string_primitive_pskel& id,
::fhir::Extension_pskel& extension,
::fhir::Extension_pskel& modifierExtension,
::fhir::CodeableConcept_pskel& assessment,
::fhir::string_pskel& productRelatedness,
::fhir::Reference_pskel& author,
::fhir::CodeableConcept_pskel& method)
{
this->id_parser_ = &id;
this->extension_parser_ = &extension;
this->modifierExtension_parser_ = &modifierExtension;
this->assessment_parser_ = &assessment;
this->productRelatedness_parser_ = &productRelatedness;
this->author_parser_ = &author;
this->method_parser_ = &method;
}
AdverseEvent_Causality_pskel::
AdverseEvent_Causality_pskel (::fhir::BackboneElement_pskel* tiein)
: ::fhir::BackboneElement_pskel (tiein, 0),
AdverseEvent_Causality_impl_ (0),
assessment_parser_ (0),
productRelatedness_parser_ (0),
author_parser_ (0),
method_parser_ (0),
v_state_stack_ (sizeof (v_state_), &v_state_first_)
{
}
AdverseEvent_Causality_pskel::
AdverseEvent_Causality_pskel (AdverseEvent_Causality_pskel* impl, void*)
: ::fhir::BackboneElement_pskel (impl, 0),
AdverseEvent_Causality_impl_ (impl),
assessment_parser_ (0),
productRelatedness_parser_ (0),
author_parser_ (0),
method_parser_ (0),
v_state_stack_ (sizeof (v_state_), &v_state_first_)
{
}
// AdverseEventActuality_list_pskel
//
AdverseEventActuality_list_pskel::
AdverseEventActuality_list_pskel (::fhir::code_primitive_pskel* tiein)
: ::fhir::code_primitive_pskel (tiein, 0),
AdverseEventActuality_list_impl_ (0)
{
this->_enumeration_facet (_xsde_AdverseEventActuality_list_pskel_enums_, 2UL);
}
AdverseEventActuality_list_pskel::
AdverseEventActuality_list_pskel (AdverseEventActuality_list_pskel* impl, void*)
: ::fhir::code_primitive_pskel (impl, 0),
AdverseEventActuality_list_impl_ (impl)
{
this->_enumeration_facet (_xsde_AdverseEventActuality_list_pskel_enums_, 2UL);
}
// AdverseEventActuality_pskel
//
void AdverseEventActuality_pskel::
value_parser (::fhir::AdverseEventActuality_list_pskel& p)
{
this->value_parser_ = &p;
}
void AdverseEventActuality_pskel::
parsers (::fhir::string_primitive_pskel& id,
::fhir::Extension_pskel& extension,
::fhir::AdverseEventActuality_list_pskel& value)
{
this->id_parser_ = &id;
this->extension_parser_ = &extension;
this->value_parser_ = &value;
}
AdverseEventActuality_pskel::
AdverseEventActuality_pskel (::fhir::Element_pskel* tiein)
: ::fhir::Element_pskel (tiein, 0),
AdverseEventActuality_impl_ (0),
value_parser_ (0)
{
}
AdverseEventActuality_pskel::
AdverseEventActuality_pskel (AdverseEventActuality_pskel* impl, void*)
: ::fhir::Element_pskel (impl, 0),
AdverseEventActuality_impl_ (impl),
value_parser_ (0)
{
}
}
#include <assert.h>
namespace fhir
{
// AdverseEvent_pskel
//
void AdverseEvent_pskel::
identifier ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->identifier ();
}
void AdverseEvent_pskel::
actuality ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->actuality ();
}
void AdverseEvent_pskel::
category ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->category ();
}
void AdverseEvent_pskel::
event ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->event ();
}
void AdverseEvent_pskel::
subject ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->subject ();
}
void AdverseEvent_pskel::
encounter ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->encounter ();
}
void AdverseEvent_pskel::
date ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->date ();
}
void AdverseEvent_pskel::
detected ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->detected ();
}
void AdverseEvent_pskel::
recordedDate ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->recordedDate ();
}
void AdverseEvent_pskel::
resultingCondition ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->resultingCondition ();
}
void AdverseEvent_pskel::
location ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->location ();
}
void AdverseEvent_pskel::
seriousness ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->seriousness ();
}
void AdverseEvent_pskel::
severity ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->severity ();
}
void AdverseEvent_pskel::
outcome ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->outcome ();
}
void AdverseEvent_pskel::
recorder ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->recorder ();
}
void AdverseEvent_pskel::
contributor ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->contributor ();
}
void AdverseEvent_pskel::
suspectEntity ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->suspectEntity ();
}
void AdverseEvent_pskel::
subjectMedicalHistory ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->subjectMedicalHistory ();
}
void AdverseEvent_pskel::
referenceDocument ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->referenceDocument ();
}
void AdverseEvent_pskel::
study ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->study ();
}
void AdverseEvent_pskel::
post_AdverseEvent ()
{
if (this->AdverseEvent_impl_)
this->AdverseEvent_impl_->post_AdverseEvent ();
else
post_DomainResource ();
}
void AdverseEvent_pskel::
_reset ()
{
if (this->resetting_)
return;
typedef ::fhir::DomainResource_pskel base;
base::_reset ();
this->v_state_stack_.clear ();
this->resetting_ = true;
if (this->identifier_parser_)
this->identifier_parser_->_reset ();
if (this->actuality_parser_)
this->actuality_parser_->_reset ();
if (this->category_parser_)
this->category_parser_->_reset ();
if (this->event_parser_)
this->event_parser_->_reset ();
if (this->subject_parser_)
this->subject_parser_->_reset ();
if (this->encounter_parser_)
this->encounter_parser_->_reset ();
if (this->date_parser_)
this->date_parser_->_reset ();
if (this->detected_parser_)
this->detected_parser_->_reset ();
if (this->recordedDate_parser_)
this->recordedDate_parser_->_reset ();
if (this->resultingCondition_parser_)
this->resultingCondition_parser_->_reset ();
if (this->location_parser_)
this->location_parser_->_reset ();
if (this->seriousness_parser_)
this->seriousness_parser_->_reset ();
if (this->severity_parser_)
this->severity_parser_->_reset ();
if (this->outcome_parser_)
this->outcome_parser_->_reset ();
if (this->recorder_parser_)
this->recorder_parser_->_reset ();
if (this->contributor_parser_)
this->contributor_parser_->_reset ();
if (this->suspectEntity_parser_)
this->suspectEntity_parser_->_reset ();
if (this->subjectMedicalHistory_parser_)
this->subjectMedicalHistory_parser_->_reset ();
if (this->referenceDocument_parser_)
this->referenceDocument_parser_->_reset ();
if (this->study_parser_)
this->study_parser_->_reset ();
this->resetting_ = false;
}
// AdverseEvent_SuspectEntity_pskel
//
void AdverseEvent_SuspectEntity_pskel::
instance ()
{
if (this->AdverseEvent_SuspectEntity_impl_)
this->AdverseEvent_SuspectEntity_impl_->instance ();
}
void AdverseEvent_SuspectEntity_pskel::
causality ()
{
if (this->AdverseEvent_SuspectEntity_impl_)
this->AdverseEvent_SuspectEntity_impl_->causality ();
}
void AdverseEvent_SuspectEntity_pskel::
post_AdverseEvent_SuspectEntity ()
{
if (this->AdverseEvent_SuspectEntity_impl_)
this->AdverseEvent_SuspectEntity_impl_->post_AdverseEvent_SuspectEntity ();
else
post_BackboneElement ();
}
void AdverseEvent_SuspectEntity_pskel::
_reset ()
{
if (this->resetting_)
return;
typedef ::fhir::BackboneElement_pskel base;
base::_reset ();
this->v_state_stack_.clear ();
this->resetting_ = true;
if (this->instance_parser_)
this->instance_parser_->_reset ();
if (this->causality_parser_)
this->causality_parser_->_reset ();
this->resetting_ = false;
}
// AdverseEvent_Causality_pskel
//
void AdverseEvent_Causality_pskel::
assessment ()
{
if (this->AdverseEvent_Causality_impl_)
this->AdverseEvent_Causality_impl_->assessment ();
}
void AdverseEvent_Causality_pskel::
productRelatedness ()
{
if (this->AdverseEvent_Causality_impl_)
this->AdverseEvent_Causality_impl_->productRelatedness ();
}
void AdverseEvent_Causality_pskel::
author ()
{
if (this->AdverseEvent_Causality_impl_)
this->AdverseEvent_Causality_impl_->author ();
}
void AdverseEvent_Causality_pskel::
method ()
{
if (this->AdverseEvent_Causality_impl_)
this->AdverseEvent_Causality_impl_->method ();
}
void AdverseEvent_Causality_pskel::
post_AdverseEvent_Causality ()
{
if (this->AdverseEvent_Causality_impl_)
this->AdverseEvent_Causality_impl_->post_AdverseEvent_Causality ();
else
post_BackboneElement ();
}
void AdverseEvent_Causality_pskel::
_reset ()
{
if (this->resetting_)
return;
typedef ::fhir::BackboneElement_pskel base;
base::_reset ();
this->v_state_stack_.clear ();
this->resetting_ = true;
if (this->assessment_parser_)
this->assessment_parser_->_reset ();
if (this->productRelatedness_parser_)
this->productRelatedness_parser_->_reset ();
if (this->author_parser_)
this->author_parser_->_reset ();
if (this->method_parser_)
this->method_parser_->_reset ();
this->resetting_ = false;
}
// AdverseEventActuality_list_pskel
//
void AdverseEventActuality_list_pskel::
post_AdverseEventActuality_list ()
{
if (this->AdverseEventActuality_list_impl_)
this->AdverseEventActuality_list_impl_->post_AdverseEventActuality_list ();
else
post_code_primitive ();
}
const char* const AdverseEventActuality_list_pskel::_xsde_AdverseEventActuality_list_pskel_enums_[2UL] =
{
"actual",
"potential"
};
// AdverseEventActuality_pskel
//
void AdverseEventActuality_pskel::
value ()
{
if (this->AdverseEventActuality_impl_)
this->AdverseEventActuality_impl_->value ();
}
void AdverseEventActuality_pskel::
post_AdverseEventActuality ()
{
if (this->AdverseEventActuality_impl_)
this->AdverseEventActuality_impl_->post_AdverseEventActuality ();
else
post_Element ();
}
void AdverseEventActuality_pskel::
_reset ()
{
typedef ::fhir::Element_pskel base;
base::_reset ();
if (this->value_parser_)
this->value_parser_->_reset ();
}
}
#include <assert.h>
namespace fhir
{
// Element validation and dispatch functions for AdverseEvent_pskel.
//
bool AdverseEvent_pskel::
_start_element_impl (const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n)
{
::xsde::cxx::parser::context& ctx = this->_context ();
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_* vd = vs.data + (vs.size - 1);
if (vd->func == 0 && vd->state == 0)
{
typedef ::fhir::DomainResource_pskel base;
if (base::_start_element_impl (ns, n))
return true;
else
vd->state = 1;
}
while (vd->func != 0)
{
(this->*vd->func) (vd->state, vd->count, ns, n, true);
vd = vs.data + (vs.size - 1);
if (vd->state == ~0UL && !ctx.error_type ())
vd = vs.data + (--vs.size - 1);
else
break;
}
if (vd->func == 0)
{
if (vd->state != ~0UL)
{
unsigned long s = ~0UL;
if (n == "identifier" &&
ns == "http://hl7.org/fhir")
s = 0UL;
else if (n == "actuality" &&
ns == "http://hl7.org/fhir")
s = 1UL;
if (s != ~0UL)
{
vd->count++;
vd->state = ~0UL;
vd = vs.data + vs.size++;
vd->func = &AdverseEvent_pskel::sequence_0;
vd->state = s;
vd->count = 0;
this->sequence_0 (vd->state, vd->count, ns, n, true);
}
else
{
if (vd->count < 1UL)
{
this->_schema_error (::xsde::cxx::schema_error::expected_element);
return true;
}
return false;
}
}
else
return false;
}
return true;
}
bool AdverseEvent_pskel::
_end_element_impl (const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n)
{
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_& vd = vs.data[vs.size - 1];
if (vd.func == 0 && vd.state == 0)
{
typedef ::fhir::DomainResource_pskel base;
if (!base::_end_element_impl (ns, n))
assert (false);
return true;
}
assert (vd.func != 0);
(this->*vd.func) (vd.state, vd.count, ns, n, false);
if (vd.state == ~0UL)
vs.size--;
return true;
}
void AdverseEvent_pskel::
_pre_e_validate ()
{
this->v_state_stack_.push ();
static_cast< v_state_* > (this->v_state_stack_.top ())->size = 0;
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_& vd = vs.data[vs.size++];
vd.func = 0;
vd.state = 0;
vd.count = 0;
typedef ::fhir::DomainResource_pskel base;
base::_pre_e_validate ();
}
void AdverseEvent_pskel::
_post_e_validate ()
{
::xsde::cxx::parser::context& ctx = this->_context ();
typedef ::fhir::DomainResource_pskel base;
base::_post_e_validate ();
if (ctx.error_type ())
return;
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_* vd = vs.data + (vs.size - 1);
::xsde::cxx::ro_string empty;
while (vd->func != 0)
{
(this->*vd->func) (vd->state, vd->count, empty, empty, true);
if (ctx.error_type ())
return;
assert (vd->state == ~0UL);
vd = vs.data + (--vs.size - 1);
}
if (vd->count < 1UL)
this->_schema_error (::xsde::cxx::schema_error::expected_element);
this->v_state_stack_.pop ();
}
void AdverseEvent_pskel::
sequence_0 (unsigned long& state,
unsigned long& count,
const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n,
bool start)
{
::xsde::cxx::parser::context& ctx = this->_context ();
XSDE_UNUSED (ctx);
switch (state)
{
case 0UL:
{
if (n == "identifier" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->identifier_parser_)
{
this->identifier_parser_->pre ();
ctx.nested_parser (this->identifier_parser_);
}
}
else
{
if (this->identifier_parser_ != 0)
{
this->identifier_parser_->post_Identifier ();
this->identifier ();
}
count = 0;
state = 1UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 1UL;
// Fall through.
}
}
case 1UL:
{
if (n == "actuality" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->actuality_parser_)
{
this->actuality_parser_->pre ();
ctx.nested_parser (this->actuality_parser_);
}
}
else
{
if (this->actuality_parser_ != 0)
{
this->actuality_parser_->post_AdverseEventActuality ();
this->actuality ();
}
count = 0;
state = 2UL;
}
break;
}
else
{
assert (start);
if (count < 1UL)
{
this->_schema_error (::xsde::cxx::schema_error::expected_element);
break;
}
count = 0;
state = 2UL;
// Fall through.
}
}
case 2UL:
{
if (n == "category" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->category_parser_)
{
this->category_parser_->pre ();
ctx.nested_parser (this->category_parser_);
}
}
else
{
if (this->category_parser_ != 0)
{
this->category_parser_->post_CodeableConcept ();
this->category ();
}
count++;
}
break;
}
else
{
assert (start);
count = 0;
state = 3UL;
// Fall through.
}
}
case 3UL:
{
if (n == "event" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->event_parser_)
{
this->event_parser_->pre ();
ctx.nested_parser (this->event_parser_);
}
}
else
{
if (this->event_parser_ != 0)
{
this->event_parser_->post_CodeableConcept ();
this->event ();
}
count = 0;
state = 4UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 4UL;
// Fall through.
}
}
case 4UL:
{
if (n == "subject" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->subject_parser_)
{
this->subject_parser_->pre ();
ctx.nested_parser (this->subject_parser_);
}
}
else
{
if (this->subject_parser_ != 0)
{
this->subject_parser_->post_Reference ();
this->subject ();
}
count = 0;
state = 5UL;
}
break;
}
else
{
assert (start);
if (count < 1UL)
{
this->_schema_error (::xsde::cxx::schema_error::expected_element);
break;
}
count = 0;
state = 5UL;
// Fall through.
}
}
case 5UL:
{
if (n == "encounter" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->encounter_parser_)
{
this->encounter_parser_->pre ();
ctx.nested_parser (this->encounter_parser_);
}
}
else
{
if (this->encounter_parser_ != 0)
{
this->encounter_parser_->post_Reference ();
this->encounter ();
}
count = 0;
state = 6UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 6UL;
// Fall through.
}
}
case 6UL:
{
if (n == "date" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->date_parser_)
{
this->date_parser_->pre ();
ctx.nested_parser (this->date_parser_);
}
}
else
{
if (this->date_parser_ != 0)
{
this->date_parser_->post_dateTime ();
this->date ();
}
count = 0;
state = 7UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 7UL;
// Fall through.
}
}
case 7UL:
{
if (n == "detected" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->detected_parser_)
{
this->detected_parser_->pre ();
ctx.nested_parser (this->detected_parser_);
}
}
else
{
if (this->detected_parser_ != 0)
{
this->detected_parser_->post_dateTime ();
this->detected ();
}
count = 0;
state = 8UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 8UL;
// Fall through.
}
}
case 8UL:
{
if (n == "recordedDate" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->recordedDate_parser_)
{
this->recordedDate_parser_->pre ();
ctx.nested_parser (this->recordedDate_parser_);
}
}
else
{
if (this->recordedDate_parser_ != 0)
{
this->recordedDate_parser_->post_dateTime ();
this->recordedDate ();
}
count = 0;
state = 9UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 9UL;
// Fall through.
}
}
case 9UL:
{
if (n == "resultingCondition" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->resultingCondition_parser_)
{
this->resultingCondition_parser_->pre ();
ctx.nested_parser (this->resultingCondition_parser_);
}
}
else
{
if (this->resultingCondition_parser_ != 0)
{
this->resultingCondition_parser_->post_Reference ();
this->resultingCondition ();
}
count++;
}
break;
}
else
{
assert (start);
count = 0;
state = 10UL;
// Fall through.
}
}
case 10UL:
{
if (n == "location" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->location_parser_)
{
this->location_parser_->pre ();
ctx.nested_parser (this->location_parser_);
}
}
else
{
if (this->location_parser_ != 0)
{
this->location_parser_->post_Reference ();
this->location ();
}
count = 0;
state = 11UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 11UL;
// Fall through.
}
}
case 11UL:
{
if (n == "seriousness" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->seriousness_parser_)
{
this->seriousness_parser_->pre ();
ctx.nested_parser (this->seriousness_parser_);
}
}
else
{
if (this->seriousness_parser_ != 0)
{
this->seriousness_parser_->post_CodeableConcept ();
this->seriousness ();
}
count = 0;
state = 12UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 12UL;
// Fall through.
}
}
case 12UL:
{
if (n == "severity" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->severity_parser_)
{
this->severity_parser_->pre ();
ctx.nested_parser (this->severity_parser_);
}
}
else
{
if (this->severity_parser_ != 0)
{
this->severity_parser_->post_CodeableConcept ();
this->severity ();
}
count = 0;
state = 13UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 13UL;
// Fall through.
}
}
case 13UL:
{
if (n == "outcome" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->outcome_parser_)
{
this->outcome_parser_->pre ();
ctx.nested_parser (this->outcome_parser_);
}
}
else
{
if (this->outcome_parser_ != 0)
{
this->outcome_parser_->post_CodeableConcept ();
this->outcome ();
}
count = 0;
state = 14UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 14UL;
// Fall through.
}
}
case 14UL:
{
if (n == "recorder" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->recorder_parser_)
{
this->recorder_parser_->pre ();
ctx.nested_parser (this->recorder_parser_);
}
}
else
{
if (this->recorder_parser_ != 0)
{
this->recorder_parser_->post_Reference ();
this->recorder ();
}
count = 0;
state = 15UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 15UL;
// Fall through.
}
}
case 15UL:
{
if (n == "contributor" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->contributor_parser_)
{
this->contributor_parser_->pre ();
ctx.nested_parser (this->contributor_parser_);
}
}
else
{
if (this->contributor_parser_ != 0)
{
this->contributor_parser_->post_Reference ();
this->contributor ();
}
count++;
}
break;
}
else
{
assert (start);
count = 0;
state = 16UL;
// Fall through.
}
}
case 16UL:
{
if (n == "suspectEntity" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->suspectEntity_parser_)
{
this->suspectEntity_parser_->pre ();
ctx.nested_parser (this->suspectEntity_parser_);
}
}
else
{
if (this->suspectEntity_parser_ != 0)
{
this->suspectEntity_parser_->post_AdverseEvent_SuspectEntity ();
this->suspectEntity ();
}
count++;
}
break;
}
else
{
assert (start);
count = 0;
state = 17UL;
// Fall through.
}
}
case 17UL:
{
if (n == "subjectMedicalHistory" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->subjectMedicalHistory_parser_)
{
this->subjectMedicalHistory_parser_->pre ();
ctx.nested_parser (this->subjectMedicalHistory_parser_);
}
}
else
{
if (this->subjectMedicalHistory_parser_ != 0)
{
this->subjectMedicalHistory_parser_->post_Reference ();
this->subjectMedicalHistory ();
}
count++;
}
break;
}
else
{
assert (start);
count = 0;
state = 18UL;
// Fall through.
}
}
case 18UL:
{
if (n == "referenceDocument" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->referenceDocument_parser_)
{
this->referenceDocument_parser_->pre ();
ctx.nested_parser (this->referenceDocument_parser_);
}
}
else
{
if (this->referenceDocument_parser_ != 0)
{
this->referenceDocument_parser_->post_Reference ();
this->referenceDocument ();
}
count++;
}
break;
}
else
{
assert (start);
count = 0;
state = 19UL;
// Fall through.
}
}
case 19UL:
{
if (n == "study" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->study_parser_)
{
this->study_parser_->pre ();
ctx.nested_parser (this->study_parser_);
}
}
else
{
if (this->study_parser_ != 0)
{
this->study_parser_->post_Reference ();
this->study ();
}
count++;
}
break;
}
else
{
assert (start);
count = 0;
state = ~0UL;
// Fall through.
}
}
case ~0UL:
break;
}
}
// Element validation and dispatch functions for AdverseEvent_SuspectEntity_pskel.
//
bool AdverseEvent_SuspectEntity_pskel::
_start_element_impl (const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n)
{
::xsde::cxx::parser::context& ctx = this->_context ();
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_* vd = vs.data + (vs.size - 1);
if (vd->func == 0 && vd->state == 0)
{
typedef ::fhir::BackboneElement_pskel base;
if (base::_start_element_impl (ns, n))
return true;
else
vd->state = 1;
}
while (vd->func != 0)
{
(this->*vd->func) (vd->state, vd->count, ns, n, true);
vd = vs.data + (vs.size - 1);
if (vd->state == ~0UL && !ctx.error_type ())
vd = vs.data + (--vs.size - 1);
else
break;
}
if (vd->func == 0)
{
if (vd->state != ~0UL)
{
unsigned long s = ~0UL;
if (n == "instance" &&
ns == "http://hl7.org/fhir")
s = 0UL;
if (s != ~0UL)
{
vd->count++;
vd->state = ~0UL;
vd = vs.data + vs.size++;
vd->func = &AdverseEvent_SuspectEntity_pskel::sequence_0;
vd->state = s;
vd->count = 0;
this->sequence_0 (vd->state, vd->count, ns, n, true);
}
else
{
if (vd->count < 1UL)
{
this->_schema_error (::xsde::cxx::schema_error::expected_element);
return true;
}
return false;
}
}
else
return false;
}
return true;
}
bool AdverseEvent_SuspectEntity_pskel::
_end_element_impl (const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n)
{
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_& vd = vs.data[vs.size - 1];
if (vd.func == 0 && vd.state == 0)
{
typedef ::fhir::BackboneElement_pskel base;
if (!base::_end_element_impl (ns, n))
assert (false);
return true;
}
assert (vd.func != 0);
(this->*vd.func) (vd.state, vd.count, ns, n, false);
if (vd.state == ~0UL)
vs.size--;
return true;
}
void AdverseEvent_SuspectEntity_pskel::
_pre_e_validate ()
{
this->v_state_stack_.push ();
static_cast< v_state_* > (this->v_state_stack_.top ())->size = 0;
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_& vd = vs.data[vs.size++];
vd.func = 0;
vd.state = 0;
vd.count = 0;
typedef ::fhir::BackboneElement_pskel base;
base::_pre_e_validate ();
}
void AdverseEvent_SuspectEntity_pskel::
_post_e_validate ()
{
::xsde::cxx::parser::context& ctx = this->_context ();
typedef ::fhir::BackboneElement_pskel base;
base::_post_e_validate ();
if (ctx.error_type ())
return;
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_* vd = vs.data + (vs.size - 1);
::xsde::cxx::ro_string empty;
while (vd->func != 0)
{
(this->*vd->func) (vd->state, vd->count, empty, empty, true);
if (ctx.error_type ())
return;
assert (vd->state == ~0UL);
vd = vs.data + (--vs.size - 1);
}
if (vd->count < 1UL)
this->_schema_error (::xsde::cxx::schema_error::expected_element);
this->v_state_stack_.pop ();
}
void AdverseEvent_SuspectEntity_pskel::
sequence_0 (unsigned long& state,
unsigned long& count,
const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n,
bool start)
{
::xsde::cxx::parser::context& ctx = this->_context ();
XSDE_UNUSED (ctx);
switch (state)
{
case 0UL:
{
if (n == "instance" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->instance_parser_)
{
this->instance_parser_->pre ();
ctx.nested_parser (this->instance_parser_);
}
}
else
{
if (this->instance_parser_ != 0)
{
this->instance_parser_->post_Reference ();
this->instance ();
}
count = 0;
state = 1UL;
}
break;
}
else
{
assert (start);
if (count < 1UL)
{
this->_schema_error (::xsde::cxx::schema_error::expected_element);
break;
}
count = 0;
state = 1UL;
// Fall through.
}
}
case 1UL:
{
if (n == "causality" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->causality_parser_)
{
this->causality_parser_->pre ();
ctx.nested_parser (this->causality_parser_);
}
}
else
{
if (this->causality_parser_ != 0)
{
this->causality_parser_->post_AdverseEvent_Causality ();
this->causality ();
}
count++;
}
break;
}
else
{
assert (start);
count = 0;
state = ~0UL;
// Fall through.
}
}
case ~0UL:
break;
}
}
// Element validation and dispatch functions for AdverseEvent_Causality_pskel.
//
bool AdverseEvent_Causality_pskel::
_start_element_impl (const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n)
{
::xsde::cxx::parser::context& ctx = this->_context ();
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_* vd = vs.data + (vs.size - 1);
if (vd->func == 0 && vd->state == 0)
{
typedef ::fhir::BackboneElement_pskel base;
if (base::_start_element_impl (ns, n))
return true;
else
vd->state = 1;
}
while (vd->func != 0)
{
(this->*vd->func) (vd->state, vd->count, ns, n, true);
vd = vs.data + (vs.size - 1);
if (vd->state == ~0UL && !ctx.error_type ())
vd = vs.data + (--vs.size - 1);
else
break;
}
if (vd->func == 0)
{
if (vd->state != ~0UL)
{
unsigned long s = ~0UL;
if (n == "assessment" &&
ns == "http://hl7.org/fhir")
s = 0UL;
else if (n == "productRelatedness" &&
ns == "http://hl7.org/fhir")
s = 1UL;
else if (n == "author" &&
ns == "http://hl7.org/fhir")
s = 2UL;
else if (n == "method" &&
ns == "http://hl7.org/fhir")
s = 3UL;
if (s != ~0UL)
{
vd->count++;
vd->state = ~0UL;
vd = vs.data + vs.size++;
vd->func = &AdverseEvent_Causality_pskel::sequence_0;
vd->state = s;
vd->count = 0;
this->sequence_0 (vd->state, vd->count, ns, n, true);
}
else
{
return false;
}
}
else
return false;
}
return true;
}
bool AdverseEvent_Causality_pskel::
_end_element_impl (const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n)
{
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_& vd = vs.data[vs.size - 1];
if (vd.func == 0 && vd.state == 0)
{
typedef ::fhir::BackboneElement_pskel base;
if (!base::_end_element_impl (ns, n))
assert (false);
return true;
}
assert (vd.func != 0);
(this->*vd.func) (vd.state, vd.count, ns, n, false);
if (vd.state == ~0UL)
vs.size--;
return true;
}
void AdverseEvent_Causality_pskel::
_pre_e_validate ()
{
this->v_state_stack_.push ();
static_cast< v_state_* > (this->v_state_stack_.top ())->size = 0;
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_& vd = vs.data[vs.size++];
vd.func = 0;
vd.state = 0;
vd.count = 0;
typedef ::fhir::BackboneElement_pskel base;
base::_pre_e_validate ();
}
void AdverseEvent_Causality_pskel::
_post_e_validate ()
{
::xsde::cxx::parser::context& ctx = this->_context ();
typedef ::fhir::BackboneElement_pskel base;
base::_post_e_validate ();
if (ctx.error_type ())
return;
v_state_& vs = *static_cast< v_state_* > (this->v_state_stack_.top ());
v_state_descr_* vd = vs.data + (vs.size - 1);
::xsde::cxx::ro_string empty;
while (vd->func != 0)
{
(this->*vd->func) (vd->state, vd->count, empty, empty, true);
if (ctx.error_type ())
return;
assert (vd->state == ~0UL);
vd = vs.data + (--vs.size - 1);
}
this->v_state_stack_.pop ();
}
void AdverseEvent_Causality_pskel::
sequence_0 (unsigned long& state,
unsigned long& count,
const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n,
bool start)
{
::xsde::cxx::parser::context& ctx = this->_context ();
XSDE_UNUSED (ctx);
switch (state)
{
case 0UL:
{
if (n == "assessment" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->assessment_parser_)
{
this->assessment_parser_->pre ();
ctx.nested_parser (this->assessment_parser_);
}
}
else
{
if (this->assessment_parser_ != 0)
{
this->assessment_parser_->post_CodeableConcept ();
this->assessment ();
}
count = 0;
state = 1UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 1UL;
// Fall through.
}
}
case 1UL:
{
if (n == "productRelatedness" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->productRelatedness_parser_)
{
this->productRelatedness_parser_->pre ();
ctx.nested_parser (this->productRelatedness_parser_);
}
}
else
{
if (this->productRelatedness_parser_ != 0)
{
this->productRelatedness_parser_->post_string ();
this->productRelatedness ();
}
count = 0;
state = 2UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 2UL;
// Fall through.
}
}
case 2UL:
{
if (n == "author" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->author_parser_)
{
this->author_parser_->pre ();
ctx.nested_parser (this->author_parser_);
}
}
else
{
if (this->author_parser_ != 0)
{
this->author_parser_->post_Reference ();
this->author ();
}
count = 0;
state = 3UL;
}
break;
}
else
{
assert (start);
count = 0;
state = 3UL;
// Fall through.
}
}
case 3UL:
{
if (n == "method" &&
ns == "http://hl7.org/fhir")
{
if (start)
{
if (this->method_parser_)
{
this->method_parser_->pre ();
ctx.nested_parser (this->method_parser_);
}
}
else
{
if (this->method_parser_ != 0)
{
this->method_parser_->post_CodeableConcept ();
this->method ();
}
count = 0;
state = ~0UL;
}
break;
}
else
{
assert (start);
count = 0;
state = ~0UL;
// Fall through.
}
}
case ~0UL:
break;
}
}
}
namespace fhir
{
// Attribute validation and dispatch functions for AdverseEventActuality_pskel.
//
bool AdverseEventActuality_pskel::
_attribute_impl_phase_one (const ::xsde::cxx::ro_string& ns,
const ::xsde::cxx::ro_string& n,
const ::xsde::cxx::ro_string& s)
{
::xsde::cxx::parser::context& ctx = this->_context ();
if (n == "value" && ns.empty ())
{
if (this->value_parser_)
{
this->value_parser_->pre ();
this->value_parser_->_pre_impl (ctx);
if (!ctx.error_type ())
this->value_parser_->_characters (s);
if (!ctx.error_type ())
this->value_parser_->_post_impl ();
if (!ctx.error_type ())
this->value_parser_->post_AdverseEventActuality_list ();
this->value ();
}
return true;
}
typedef ::fhir::Element_pskel base;
return base::_attribute_impl_phase_one (ns, n, s);
}
}
namespace fhir
{
}
#include <xsde/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
|
bd7fb9a6e47391b1c46288ec17148dfb6bc808a2
|
04899c4620f640922cfddc6f12c3393043c4ff60
|
/AnKi/Scene/Components/GpuParticleEmitterComponent.cpp
|
359fbbea818302bf20b4ec4593daf759c8db3ce2
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
galek/anki-3d-engine-1
|
51c3d56b8aeaf6773216749d95e0326aa75978de
|
48f9806364d35a12a53508b248e26c597188b542
|
refs/heads/master
| 2021-11-25T06:47:32.120582
| 2021-10-24T19:33:05
| 2021-10-24T19:33:21
| 59,970,766
| 0
| 0
| null | 2016-05-30T00:57:00
| 2016-05-30T00:57:00
| null |
UTF-8
|
C++
| false
| false
| 10,212
|
cpp
|
GpuParticleEmitterComponent.cpp
|
// Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
// All rights reserved.
// Code licensed under the BSD License.
// http://www.anki3d.org/LICENSE
#include <AnKi/Scene/Components/GpuParticleEmitterComponent.h>
#include <AnKi/Scene/SceneNode.h>
#include <AnKi/Scene/SceneGraph.h>
#include <AnKi/Scene/Components/RenderComponent.h>
#include <AnKi/Resource/ResourceManager.h>
#include <AnKi/Shaders/Include/ParticleTypes.h>
namespace anki
{
ANKI_SCENE_COMPONENT_STATICS(GpuParticleEmitterComponent)
GpuParticleEmitterComponent::GpuParticleEmitterComponent(SceneNode* node)
: SceneComponent(node, getStaticClassId())
, m_node(node)
{
}
GpuParticleEmitterComponent::~GpuParticleEmitterComponent()
{
}
Error GpuParticleEmitterComponent::loadParticleEmitterResource(CString filename)
{
m_markedForUpdate = true;
// Create the debug drawer
if(!m_dbgImage.isCreated())
{
ANKI_CHECK(m_node->getSceneGraph().getResourceManager().loadResource("EngineAssets/ParticleEmitter.ankitex",
m_dbgImage));
}
// Load particle props
ANKI_CHECK(m_node->getSceneGraph().getResourceManager().loadResource(filename, m_particleEmitterResource));
const ParticleEmitterProperties& inProps = m_particleEmitterResource->getProperties();
m_maxParticleCount = inProps.m_maxNumOfParticles;
// Create program
ANKI_CHECK(
m_node->getSceneGraph().getResourceManager().loadResource("Shaders/GpuParticlesSimulation.ankiprog", m_prog));
const ShaderProgramResourceVariant* variant;
m_prog->getOrCreateVariant(variant);
m_grProg = variant->getProgram();
m_workgroupSizeX = variant->getWorkgroupSizes()[0];
// Create a UBO with the props
{
BufferInitInfo buffInit("GpuParticlesProps");
buffInit.m_mapAccess = BufferMapAccessBit::WRITE;
buffInit.m_usage = BufferUsageBit::UNIFORM_COMPUTE;
buffInit.m_size = sizeof(GpuParticleEmitterProperties);
m_propsBuff = m_node->getSceneGraph().getGrManager().newBuffer(buffInit);
GpuParticleEmitterProperties* props =
static_cast<GpuParticleEmitterProperties*>(m_propsBuff->map(0, MAX_PTR_SIZE, BufferMapAccessBit::WRITE));
props->m_minGravity = inProps.m_particle.m_minGravity;
props->m_minMass = inProps.m_particle.m_minMass;
props->m_maxGravity = inProps.m_particle.m_maxGravity;
props->m_maxMass = inProps.m_particle.m_maxMass;
props->m_minForce = inProps.m_particle.m_minForceDirection * inProps.m_particle.m_minForceMagnitude;
props->m_minLife = F32(inProps.m_particle.m_minLife);
props->m_maxForce = inProps.m_particle.m_maxForceDirection * inProps.m_particle.m_maxForceMagnitude;
props->m_maxLife = F32(inProps.m_particle.m_maxLife);
props->m_minStartingPosition = inProps.m_particle.m_minStartingPosition;
props->m_maxStartingPosition = inProps.m_particle.m_maxStartingPosition;
props->m_particleCount = inProps.m_maxNumOfParticles;
m_propsBuff->flush(0, MAX_PTR_SIZE);
m_propsBuff->unmap();
}
// Create the particle buffer
{
BufferInitInfo buffInit("GpuParticles");
buffInit.m_mapAccess = BufferMapAccessBit::WRITE;
buffInit.m_usage = BufferUsageBit::ALL_STORAGE;
buffInit.m_size = sizeof(GpuParticle) * m_maxParticleCount;
m_particlesBuff = m_node->getSceneGraph().getGrManager().newBuffer(buffInit);
GpuParticle* particle =
static_cast<GpuParticle*>(m_particlesBuff->map(0, MAX_PTR_SIZE, BufferMapAccessBit::WRITE));
const GpuParticle* end = particle + m_maxParticleCount;
for(; particle < end; ++particle)
{
particle->m_life = -1.0f; // Force GPU to init the particle
}
m_particlesBuff->flush(0, MAX_PTR_SIZE);
m_particlesBuff->unmap();
}
// Create the rand buffer
{
BufferInitInfo buffInit("GpuParticlesRand");
buffInit.m_mapAccess = BufferMapAccessBit::WRITE;
buffInit.m_usage = BufferUsageBit::ALL_STORAGE;
buffInit.m_size = sizeof(U32) + MAX_RAND_FACTORS * sizeof(F32);
m_randFactorsBuff = m_node->getSceneGraph().getGrManager().newBuffer(buffInit);
F32* randFactors = static_cast<F32*>(m_randFactorsBuff->map(0, MAX_PTR_SIZE, BufferMapAccessBit::WRITE));
*reinterpret_cast<U32*>(randFactors) = MAX_RAND_FACTORS;
++randFactors;
const F32* randFactorsEnd = randFactors + MAX_RAND_FACTORS;
for(; randFactors < randFactorsEnd; ++randFactors)
{
*randFactors = getRandomRange(0.0f, 1.0f);
}
m_randFactorsBuff->flush(0, MAX_PTR_SIZE);
m_randFactorsBuff->unmap();
}
// Create the sampler
{
SamplerInitInfo sinit("GpuParticles");
sinit.m_addressing = SamplingAddressing::CLAMP;
m_nearestAnyClampSampler = m_node->getSceneGraph().getGrManager().newSampler(sinit);
}
// Find the extend of the particles
if(inProps.m_emitterBoundingVolumeMin.x() >= inProps.m_emitterBoundingVolumeMax.x())
{
const Vec3 maxForce = inProps.m_particle.m_maxForceDirection * inProps.m_particle.m_maxForceMagnitude;
const Vec3& maxGravity = inProps.m_particle.m_maxGravity;
const F32 maxMass = inProps.m_particle.m_maxMass;
const F32 maxLife = F32(inProps.m_particle.m_maxLife);
const F32 dt = 1.0f / 30.0f;
const Vec3 initialForce = maxGravity * maxMass + maxForce;
const Vec3 initialAcceleration = initialForce / maxMass;
const Vec3 velocity = initialAcceleration * dt;
F32 life = maxLife;
Vec3 pos(0.0f);
while(life > dt)
{
pos = maxGravity * (dt * dt) + velocity * dt + pos;
life -= dt;
}
m_emitterBoundingBoxLocal = Aabb(-Vec3(pos.getLength()), Vec3(pos.getLength()));
}
else
{
m_emitterBoundingBoxLocal = Aabb(inProps.m_emitterBoundingVolumeMin, inProps.m_emitterBoundingVolumeMax);
}
return Error::NONE;
}
void GpuParticleEmitterComponent::simulate(GenericGpuComputeJobQueueElementContext& ctx) const
{
if(ANKI_UNLIKELY(!m_particleEmitterResource.isCreated()))
{
return;
}
CommandBufferPtr& cmdb = ctx.m_commandBuffer;
cmdb->bindShaderProgram(m_grProg);
// Bind resources
cmdb->bindStorageBuffer(1, 0, m_particlesBuff, 0, MAX_PTR_SIZE);
cmdb->bindUniformBuffer(1, 1, m_propsBuff, 0, MAX_PTR_SIZE);
cmdb->bindStorageBuffer(1, 2, m_randFactorsBuff, 0, MAX_PTR_SIZE);
cmdb->bindSampler(1, 3, m_nearestAnyClampSampler);
StagingGpuMemoryToken token;
GpuParticleSimulationState* unis =
static_cast<GpuParticleSimulationState*>(ctx.m_stagingGpuAllocator->allocateFrame(
sizeof(GpuParticleSimulationState), StagingGpuMemoryType::UNIFORM, token));
unis->m_viewProjMat = ctx.m_viewProjectionMatrix;
unis->m_unprojectionParams = ctx.m_projectionMatrix.extractPerspectiveUnprojectionParams();
unis->m_randomIndex = rand();
unis->m_dt = F32(m_dt);
unis->m_emitterPosition = m_worldPosition;
unis->m_emitterRotation = m_worldRotation;
unis->m_invViewRotation = Mat3x4(Vec3(0.0f), ctx.m_cameraTransform.getRotationPart());
cmdb->bindUniformBuffer(1, 4, token.m_buffer, token.m_offset, token.m_range);
// Dispatch
const U32 workgroupCount = (m_maxParticleCount + m_workgroupSizeX - 1) / m_workgroupSizeX;
cmdb->dispatchCompute(workgroupCount, 1, 1);
}
void GpuParticleEmitterComponent::draw(RenderQueueDrawContext& ctx) const
{
if(ANKI_UNLIKELY(!m_particleEmitterResource.isCreated()))
{
return;
}
CommandBufferPtr& cmdb = ctx.m_commandBuffer;
if(!ctx.m_debugDraw)
{
// Program
ShaderProgramPtr prog;
m_particleEmitterResource->getRenderingInfo(ctx.m_key, prog);
cmdb->bindShaderProgram(prog);
// Resources
static const Mat4 identity = Mat4::getIdentity();
RenderComponent::allocateAndSetupUniforms(m_particleEmitterResource->getMaterial(), ctx,
ConstWeakArray<Mat4>(&identity, 1),
ConstWeakArray<Mat4>(&identity, 1), *ctx.m_stagingGpuAllocator);
cmdb->bindStorageBuffer(0, 1, m_particlesBuff, 0, MAX_PTR_SIZE);
StagingGpuMemoryToken token;
Vec4* extraUniforms = static_cast<Vec4*>(
ctx.m_stagingGpuAllocator->allocateFrame(sizeof(Vec4), StagingGpuMemoryType::UNIFORM, token));
*extraUniforms = ctx.m_cameraTransform.getColumn(2);
cmdb->bindUniformBuffer(0, 2, token.m_buffer, token.m_offset, token.m_range);
// Draw
cmdb->setLineWidth(8.0f);
cmdb->drawArrays(PrimitiveTopology::LINES, m_maxParticleCount * 2);
}
else
{
const Vec4 tsl = (m_worldAabb.getMin() + m_worldAabb.getMax()) / 2.0f;
const Vec4 scale = (m_worldAabb.getMax() - m_worldAabb.getMin()) / 2.0f;
// Set non uniform scale. Add a margin to avoid flickering
Mat3 nonUniScale = Mat3::getZero();
nonUniScale(0, 0) = scale.x();
nonUniScale(1, 1) = scale.y();
nonUniScale(2, 2) = scale.z();
const Mat4 mvp = ctx.m_viewProjectionMatrix * Mat4(tsl.xyz1(), Mat3::getIdentity() * nonUniScale, 1.0f);
const Bool enableDepthTest = ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DEPTH_TEST_ON);
if(enableDepthTest)
{
cmdb->setDepthCompareOperation(CompareOperation::LESS);
}
else
{
cmdb->setDepthCompareOperation(CompareOperation::ALWAYS);
}
m_node->getSceneGraph().getDebugDrawer().drawCubes(
ConstWeakArray<Mat4>(&mvp, 1), Vec4(1.0f, 0.0f, 1.0f, 1.0f), 2.0f,
ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), 2.0f,
*ctx.m_stagingGpuAllocator, cmdb);
m_node->getSceneGraph().getDebugDrawer().drawBillboardTextures(
ctx.m_projectionMatrix, ctx.m_viewMatrix, ConstWeakArray<Vec3>(&m_worldPosition, 1), Vec4(1.0f),
ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), m_dbgImage->getTextureView(),
ctx.m_sampler, Vec2(0.75f), *ctx.m_stagingGpuAllocator, ctx.m_commandBuffer);
// Restore state
if(!enableDepthTest)
{
cmdb->setDepthCompareOperation(CompareOperation::LESS);
}
}
}
Error GpuParticleEmitterComponent::update(SceneNode& node, Second prevTime, Second crntTime, Bool& updated)
{
if(ANKI_UNLIKELY(!m_particleEmitterResource.isCreated()))
{
updated = false;
return Error::NONE;
}
updated = m_markedForUpdate;
m_markedForUpdate = false;
m_dt = crntTime - prevTime;
return Error::NONE;
}
void GpuParticleEmitterComponent::setWorldTransform(const Transform& trf)
{
m_worldPosition = trf.getOrigin().xyz();
m_worldRotation = trf.getRotation();
m_worldAabb.setMin(m_worldPosition + m_emitterBoundingBoxLocal.getMin().xyz());
m_worldAabb.setMax(m_worldPosition + m_emitterBoundingBoxLocal.getMax().xyz());
m_markedForUpdate = true;
}
} // end namespace anki
|
51aa99520a6ac4e9c265e1fdd1757162e24bfd2b
|
bd4db4919da1655f62388246c0b88011bae5ecb5
|
/icebridge_svn/trunk/gateway_server/sdk/PlayersManager.cpp
|
e1b057f00d0ce45892886e5b67588733a446f427
|
[] |
no_license
|
qxiong133/cpp_framework
|
0e567d914ea8e340ed6491b1837c9947a94b9308
|
076ecfed1ac71aa92d3c35394aab2fa064168cfe
|
refs/heads/master
| 2020-04-24T19:42:13.873427
| 2015-03-26T08:32:18
| 2015-03-26T08:32:18
| 31,106,660
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,145
|
cpp
|
PlayersManager.cpp
|
/*
* PlayersManager.cpp
*
* Created on: Aug 11, 2013
* Author: root
*/
#include "PlayersManager.h"
#include "sdk/tcp_session_handler.h"
#include "sdk/tcp_io_thread_manager.h"
#include <iostream>
using namespace eddy;
using namespace std;
using namespace boost;
extern TCPIOThreadManager manager;
PlayersManager::PlayersManager() {
// TODO Auto-generated constructor stub
activeClose = false;
}
PlayersManager::~PlayersManager() {
// TODO Auto-generated destructor stub
}
/*once the client logins,we register it into the two maps playerSessionMap_,sessionPlayerMap_. if the session has
exist before,then close it so the player can relate to the new session
*/
void PlayersManager::onLogin(PlayerID playerID, TCPSessionID sessionID) {
//TCPSessionID sessionID = handler.session_id();
LeftIterator it = playerSessionBiMap_.left.find(playerID);
/*std::cout << "playerID = " << playerID << " sessionID = " << sessionID
<< std::endl;*/
if (it != playerSessionBiMap_.left.end()) {
playerSessionBiMap_.erase(PlayerSession(playerID, sessionID));
playerIDDeletedSet.insert(playerID);
//this player is already login , so close the old one
manager.GetSessionHandler(it->second)->Close();
}
//now it is ok to add this new player
playerSessionBiMap_.insert(PlayerSession(playerID, sessionID));
}
// once the session out in whatever situation ,the function should always be invoked
void PlayersManager::onPlayerOut(TCPSessionID sessionID) {
//TCPSessionID sessionID = handler.session_id();
RightIterator it = playerSessionBiMap_.right.find(sessionID);
if (it != playerSessionBiMap_.right.end()) {
if (playerIDDeletedSet.find(it->second) == playerIDDeletedSet.end()) {
playerSessionBiMap_.erase(PlayerSession(it->second, sessionID));
} else {
playerIDDeletedSet.erase(it->second);
}
}
}
void PlayersManager::loginFailed(eddy::TCPSessionID sessionID) {
//handler.Close();
}
PlayersManager::PlayerID PlayersManager::getPlayerID(
eddy::TCPSessionID sessionID) {
PlayerID playerID;
RightIterator it = playerSessionBiMap_.right.find(sessionID);
if (it != playerSessionBiMap_.right.end()) {
playerID = it->second;
}
return playerID;
}
TCPSessionID PlayersManager::getSessionID(PlayerID playerID) {
LeftIterator it = playerSessionBiMap_.left.find(playerID);
if (it != playerSessionBiMap_.left.end()) {
return it->second;
}
return kInvalidTCPSessionID;
}
/*
PlayersManager::LeftIterator PlayersManager::getBeginSession(){
return playerSessionBiMap_.left.begin();
}
PlayersManager::LeftIterator PlayersManager::getNextSession(LeftIterator it){
return
}
*/
boost::optional<TCPSessionID> PlayersManager::getBeginSessionID() {
LeftIterator it = playerSessionBiMap_.left.begin();
//leftCurIterator = ++it;
if (it != playerSessionBiMap_.left.end()) {
TCPSessionID id = it->second;
leftCurIterator = ++it;
return optional<TCPSessionID>(id);
}
return optional<TCPSessionID>(boost::none);
}
//eddy::TCPSessionID getEndSession();
boost::optional<eddy::TCPSessionID> PlayersManager::getNextSessionID() {
return optional<TCPSessionID>(boost::none);
}
|
81dfb57e80fe9f530cea8ba3ec46ecb346fe08c3
|
7deb45a2b13b9b69d705e0750c9cf6c07ef08779
|
/sstable.h
|
f96bd473268c26679b28970430658f90e8d5f0ea
|
[] |
no_license
|
tao011110/LSM-Tree
|
0870c29221245b82989215e84e96ad9e7bb8937d
|
b7c6e348690ab4816cd99785d67756200f49ee04
|
refs/heads/master
| 2023-06-01T07:04:25.116770
| 2021-06-04T11:56:06
| 2021-06-04T11:56:06
| 368,061,318
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,387
|
h
|
sstable.h
|
#ifndef SSTABLE_H
#define SSTABLE_H
#include <string>
#include <vector>
#include <fstream>
#include "memtable.h"
#include "bloomfilter.h"
class sstable
{
private:
std::pair<uint64_t, uint32_t> *index;
std::string *data;
struct Header{
uint64_t time;
uint64_t num;
uint64_t min;
uint64_t max;
};
public:
explicit sstable(std::vector<memTable::dataNode> &vec);
~sstable();
uint32_t get(uint64_t key);
void reset();
bool check(uint64_t key);
void setTime(uint64_t time){
header.time = time;
}
void setNum(uint64_t num){
header.num = num;
}
void setMax(uint64_t max){
header.max = max;
}
void setMin(uint64_t min){
header.min = min;
}
uint64_t getTime(){
return header.time;
}
uint64_t getNum(){
return header.num;
}
uint64_t getMax(){
return header.max;
}
uint64_t getMin(){
return header.min;
}
void makeFileSST(std::string path);
void getIndex(std::pair<uint64_t, uint32_t> *newindex){
for(uint64_t i = 0; i < header.num; i++){
newindex[i].first = index[i].first;
newindex[i].second = index[i].second;
}
}
void getBf(BloomFilter *newbf){
bf.getBf(newbf);
}
Header header{};
BloomFilter bf;
};
#endif // SSTABLE_H
|
3eae434b4ecba8cce0994199dc1cd56b34c0dfbe
|
b09d9ac8d001123bb0aa9e862d898c102700080e
|
/arrays/threeNumberSort.cpp
|
8ba6aefe53d78392996f50b15aa68ee4de697f56
|
[] |
no_license
|
shobhanc/dcp
|
f1629bf3a23041e802a0f63f43b0d6dfd5d1b909
|
26c08f0a671562767d6d0378751fdad738c317a9
|
refs/heads/main
| 2023-03-10T12:45:36.215327
| 2021-02-28T08:15:26
| 2021-02-28T08:15:26
| 313,209,766
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,843
|
cpp
|
threeNumberSort.cpp
|
/*
* Three Number Sort
* Given an array [1,0,0,-1,-1,0,1,1]
* order of three distinct integers [0,1,-1]
*
* output in the same order as the order array:[0,0,0,1,1,1,-1,-1]
*
* Do in place sort without using auxillary data structure.
*/
//Bruteforce with auxillary array.
//O(k) space and O(Nk) time
vector<int> threeNumberSort(vector<int> array, vector<int> order) {
// Write your code here.
map<int,int> mp;
for(int v:order){
mp.insert({v,0});
}
for(int v:array){
mp[v]+=1;
}
int idx=0;
for(int v:order){
int t=mp[v];
for(int i=0; i<t; i++){
array[idx]=v;
idx++;
}
}
return array;
}
//O(1) space and O(NK) time
int vsort(vector<int>& array, int i, int val){
int j=i;
for(; i<array.size(); i++){
if(val==array[i]){
swap(array[j],array[i]);
j++;
}
}
return j;
}
vector<int> threeNumberSort(vector<int> array, vector<int> order) {
// Write your code here.
int start=0;
for(int i=0; i<order.size()-1 && start<array.size(); i++){
start= vsort(array, start, order[i]);
}
return array;
}
//time O(N) space O(1)
vector<int> threeNumberSort(vector<int> array, vector<int> order) {
// Write your code here.
int b=0, e=array.size()-1;
for(int i=0; i<array.size(); i++){
if(array[i]==order[0]){
swap(array[i],array[b]);
b++;
}
}
for(int i=array.size()-1; i>=0; i--){
if(array[i]==order[2]){
swap(array[i],array[e]);
e--;
}
}
return array;
}
//time O(N) and space(1)
vector<int> threeNumberSort(vector<int> array, vector<int> order) {
// Write your code here.
int start=0, end=array.size()-1;
int i=0;
while(i<=end){
if(array[i]==order[2]){
swap(array[i],array[end]);
end--;
}else if(array[i]==order[0]){
swap(array[i],array[start]);
start++;
i++;
}else{
i++;
}
}
return array;
}
|
255e0142d45954e046a3c75f09436ecd4858f2c6
|
be696f42628c9b2466fb46a710c866c0e336017a
|
/StudentProgram_C++/Compare.h
|
3b06c5fb84c4f643f7ef81514a64f8808e5820d8
|
[
"MIT"
] |
permissive
|
wjk0629/StudentManager
|
7c340ad372e7392cfde304a7b93f935b09c48b2e
|
1db0f62f0ffc0bedad189c56e047b928a5b85489
|
refs/heads/main
| 2023-05-04T10:27:59.859199
| 2021-05-24T11:12:22
| 2021-05-24T11:12:22
| 370,317,099
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 145
|
h
|
Compare.h
|
#pragma once
#include "CStudent.h"
class CompareByName
{
string name;
public:
CompareByName(string name)
:name(name)
{}
};
|
fc9341ffb4426536e6ad4999dc9c6a265539578f
|
83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1
|
/third_party/WebKit/Source/modules/permissions/PermissionQueryCallback.h
|
c5631582b2830013d8a202ab6087091da244a758
|
[
"Apache-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] |
permissive
|
cool2528/miniblink49
|
d909e39012f2c5d8ab658dc2a8b314ad0050d8ea
|
7f646289d8074f098cf1244adc87b95e34ab87a8
|
refs/heads/master
| 2020-06-05T03:18:43.211372
| 2019-06-01T08:57:37
| 2019-06-01T08:59:56
| 192,294,645
| 2
| 0
|
Apache-2.0
| 2019-06-17T07:16:28
| 2019-06-17T07:16:27
| null |
UTF-8
|
C++
| false
| false
| 1,368
|
h
|
PermissionQueryCallback.h
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PermissionQueryCallback_h
#define PermissionQueryCallback_h
#include "platform/heap/Handle.h"
#include "public/platform/WebCallbacks.h"
#include "public/platform/modules/permissions/WebPermissionStatus.h"
#include "public/platform/modules/permissions/WebPermissionType.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
class ScriptPromiseResolver;
// PermissionQueryCallback is an implementation of WebPermissionQueryCallbacks
// that will resolve the underlying promise depending on the result passed to
// the callback. It takes a WebPermissionType in its constructor and will pass
// it to the PermissionStatus.
class PermissionQueryCallback final
: public WebCallbacks<WebPermissionStatus, void> {
public:
explicit PermissionQueryCallback(PassRefPtr<ScriptPromiseResolver>, WebPermissionType);
~PermissionQueryCallback() override;
void onSuccess(WebPermissionStatus*) override;
void onError() override;
private:
RefPtr<ScriptPromiseResolver> m_resolver;
WebPermissionType m_permissionType;
WTF_MAKE_NONCOPYABLE(PermissionQueryCallback);
};
} // namespace blink
#endif // PermissionQueryCallback_h
|
972054dccd967a0b327f5bd50c7ce6d9958d4a49
|
14967a93424babfb3d8e80c6c0aa5fc54f857b9a
|
/FluxSol-Solver/FiniteVolume/Mesh/FvGrid.cpp
|
f878b4b5f3ab0be0ecc213dca6b789483adc2b9e
|
[] |
no_license
|
luchete80/fluxsol
|
aec0cdf118e0726d559916aba3f8d6e32d3cc609
|
a29af77858597d3fe77d3715d7c0fb65dba07736
|
refs/heads/master
| 2020-03-22T09:26:40.640514
| 2018-07-18T16:25:00
| 2018-07-18T16:25:00
| 42,241,640
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 50,721
|
cpp
|
FvGrid.cpp
|
/************************************************************************
Copyright 2012-2013 Luciano Buglioni
Contact: luciano.buglioni@gmail.com
This file is a part of FluxSol
FluxSol is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
FluxSol 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.
For a copy of the GNU General Public License,
see <http://www.gnu.org/licenses/>.
*************************************************************************/
#include "FvGrid.h"
#include <time.h>
#include "Modelo.h"
//To utils
//Redundance with vector c++ lib
template <class T> const T& max_int(const T& a, const T& b) {
return (a<b) ? b : a; // or: return comp(a,b)?b:a; for version (2)
}
using namespace std;
namespace FluxSol {
//TO MODIFY
Fv_CC_Grid::Fv_CC_Grid(const char *name){
fileName=name;
if(fileName.substr(fileName.find_last_of(".") + 1) == "cgns"){
cout << "[I] Mesh file format: CGNS"<<endl;
this->Read_CGNS();}
else if(fileName.substr(fileName.find_last_of(".") + 1) == "bdf")
this->Read_NASTRAN();}
Fv_CC_Grid::Fv_CC_Grid(string name){
fileName=name;
if(fileName.substr(fileName.find_last_of(".") + 1) == "cgns"){
cout << "[I] Mesh file format: CGNS"<<endl;
this->Read_CGNS();}
else if(fileName.substr(fileName.find_last_of(".") + 1) == "bdf"){
cout << "[I] Mesh file format: NASTRAN"<<endl;
this->Read_NASTRAN();}
}
Fv_CC_Grid::Fv_CC_Grid(const int &nex,const int &ney,const double &lx,const double &ly):
_Grid(nex,ney)
{
double elx,ely;
elx=lx/nex; ely=ly/ney;
//Hasta aca genero los vertices
GenerarMallaRectangular(elx,ely,(*this));
//Ahora debo generar los nodos
cout << "Creating Nodes..."<<endl;
CreateNodesFromCellVerts();
//Inicio las caras
cout << "Initializing faces..."<<endl;
Iniciar_Caras();
cout << "Assigning Neighbours..."<<endl;
AssignNeigboursCells();
CalcCellVolumes();
}
Fv_CC_Grid & Fv_CC_Grid::operator=(const Fv_CC_Grid & right)
{
this->num_verts=right.num_verts; //Este Numero no es constante por si modifico la malla
//Si voy a tener vertices tipo baffle no lo voy a tener en cuenta
this->num_cells_int=right.num_cells_int; //Numero de celdas efectivas
this->num_faces_int=right.num_faces_int; //Numero de faces efectivas (INTERIORES)
this->num_faces=right.num_faces;
this->num_cells=right.num_cells;
this->num_verts=right.num_verts;
//cout << "Equalling cells, "<< right.num_cells << endl;
for (int c=0;c<right.num_cells;c++)
{
this->cell.push_back(right.Cell(c));
this->node.push_back(right.Node_(c));
}
//cout << "Equalling verts "<< right.num_verts << endl;
for (int v=0;v<right.num_verts;v++) this->vert.push_back(right.Vertex(v));
//cout << "Equalling faces "<<endl;
for (int f=0;f<right.num_faces;f++) this->face.push_back(right.Face(f));
this->boundary=right.vBoundary();
//cout << "Setting up cell neigbours"<<endl;
this->SetFaceLocalCellNeighbours(); //New
this->Create_IntFaces();
return *this;
}
//Inserto una celda
void FluxSol::Fv_CC_Grid::PushCell(const std::vector <int> &vc)
{
Cell_CC c;
c.Conect(vc);
PushCell(c);
}
void FluxSol::Fv_CC_Grid::Log(string s)
{
//ESTO PUEDO COLOCARLO EN UN LOG APARTE PARA CLASE BASE
Log_Abrir(s.c_str()); //Abro archivo de log
meshlog << "Vertices Coordinates" << endl;
meshlog << endl;
Log_Verts(); //El Log de los vertices es el mismo
std::vector < Cell_CC >::iterator ccellit;
meshlog << endl;
meshlog<<"//////////////////////////////"<<endl;
meshlog << endl;
meshlog<<"Mesh Cells"<<endl;
meshlog << endl;
int i=0;
meshlog << "Cell Centers (Nodes)"<<endl;
for (ccellit=cell.begin();ccellit!=cell.end();ccellit++)
{
meshlog<< "["<<i<<"]"<<this->Node_(i).outstr()<<endl;
i++;
}
i=0;
for (ccellit=cell.begin();ccellit!=cell.end();ccellit++)
{
meshlog << "Cell " << i << endl;
meshlog<<"Vertices"<<endl;
meshlog<<(*ccellit).Imprimir_Conect()<<endl;
meshlog<<"Faces"<<endl;
for (int f=0;f<(*ccellit).Num_Faces();f++)
meshlog<<(*ccellit).Id_Face(f)<< " ";
meshlog <<endl;
meshlog << "Neighbours" << endl;
for (int n=0; n<(*ccellit).Num_Neighbours(); n++)
meshlog << (*ccellit).Neighbour(n) << endl;
meshlog << endl;
i++;
}
//Ahora viene la diferencia
//Busco las coordenadas de los nodos
meshlog<<"//////////////////////////////"<<endl;
meshlog << endl;
meshlog << "Nodes Coordinates" << endl;
meshlog << endl;
for (nodeit=node.begin();nodeit!=node.end();nodeit++)
meshlog<<nodeit->Imprimir_Coord()<<endl;
//Informacion de faces
int f=0;
meshlog << endl;
meshlog<<"//////////////////////////////"<<endl;
meshlog << endl;
meshlog<<"Face Conectivity"<<endl;
meshlog << endl;
for (faceit=this->face.begin();faceit!=face.end();faceit++)
{
meshlog<<"Face "<< f<<" cells"<<endl;
for (int i=0;i<faceit->NumCells();i++)
meshlog<<faceit->Cell(i)<<" ";
meshlog<<endl;
meshlog<<"Face "<< f<<" vertices"<<endl;
for (int i=0;i<faceit->NumVerts();i++)
meshlog<<faceit->Vert(i)<<" ";
meshlog<<endl;
meshlog<<"Face "<< f<<" fp"<<endl;
meshlog<<faceit->Fp().outstr()<<" ";
meshlog<<"fof: " << faceit->fof().outstr()<<endl;
meshlog << "PF: "<<faceit->Dist_pf_LR(0)<<endl;
meshlog << "e_PN: "<<faceit->e_PN().outstr()<<endl;
meshlog << "Baricenter (sm): "<<faceit->Baric()<<endl;
meshlog << "Af (Normal): "<<faceit->Af()<<endl;
meshlog << "Ad (Collineal to PN): "<<faceit->Ad()<<endl;
//faceit->ANorm()
meshlog<<endl;
f++;
}
f=0;
meshlog<<"//////////////////////////////"<<endl;
meshlog << endl;
meshlog<<"Face Geometry"<<endl;
meshlog << endl;
for (faceit=this->face.begin();faceit!=face.end();faceit++)
{
meshlog << "Face "<<f<<"Ad:"<<endl;
faceit->Ad().Log(meshlog);
meshlog<<endl;
meshlog << endl;
f++;
}
//ESTO ES NUEVO PARA LA CLASE DERIVADA
}
// VARIABLES DE NODOS
// Creo los nodos centrales
//La llamo muchas veces
Node & FluxSol::Fv_CC_Grid::CreateNodeFromCellVerts(const int &cellid)
{
vector <Vec3D> verts;
Cell_CC cell=this->Cell(cellid);
int globvert;
Node nod(0.);
//Recorro los vertices del cell
for (int n=0;n<cell.Num_Vertex();n++)
{
nod+=this->Vertex(cell.Id_Vert(n));
}
//Ahora divido por la cantidad de vertices
nod/=(double)cell.Num_Vertex();
return nod;
}
// Constructor que sirva para construir por ejemplo desde un archivo
Fv_CC_Grid::Fv_CC_Grid(vector <_Vertex> &vvert,vector <Cell_CC> &vcell, Boundary &bound)
{
num_verts=vvert.size();
num_cells=vcell.size();
//Agrego los vertices
for (int nv=0;nv<num_verts;nv++) vert.push_back(vvert[nv]);
for (int nc=0;nc<num_cells;nc++) cell.push_back(vcell[nc]);
for (int nc=0;nc<num_cells;nc++) CreateNodeFromCellVerts(nc);
boundary=bound;
inicie_cells=true;
//Creo los nodos
inicie_nodes=true;
//Chequeo si es 2D y agrego los vertices que corresponden para convertirlo en 3D
//(Recordar que para ensamblar se hace como 2D)
//Chequeo la cantidad de vertices
_Vertex vp;
for (cellit=cell.begin();cellit!=cell.end();cellit++)
{
if(cellit->Num_Vertex()<=4) //Es bidimensional
{
//Chequeo cual es la coordenada normal al plano bidimensional
//_Vertex vd1(vvert[cellit->Vert(1)-vvert[cellit->Vert(0)]);
//_Vertex vd2(vvert[cellit->Vert(1)-vvert[cellit->Vert(0)]);//prod=;
//vv[cellit->Vert(1)]
}
//Construyo las caras internas
//Recorro los vertices y hago grupos de 2 caras, en caso que no esten las agrego
this->Iniciar_Caras();
}
//Chequeo si no queda una parte libre del boundary
}
void Fv_CC_Grid::AssignNeigboursCells()
{
int c=0;
// cout <<"neigh assign" <<endl;
// cout << "Grid Num Faces" <<this->Num_Faces()<<endl;
// cout << "Grid Face Size" <<this->face.size()<<endl;
// cout << "Grid Cell Size" <<this->cell.size()<<endl;
bool end=false;
if (!this->Num_Faces() || this->face.size()==0 || this->cell.size()==0)
end=true;
if (!end)
{
for (cellit=cell.begin();cellit!=cell.end();cellit++)
{
// cout << "neigh assign cell "<<c<<endl;
// cout << "Num Faces" <<cellit->Num_Faces()<<endl;
for (int intface=0;intface<cellit->Num_Faces();intface++)
{
// cout << "Int face" << intface<<endl;
// cout << "Id Face"<<cellit->Id_Face(intface);
int idface=cellit->Id_Face(intface);
_FvFace fvface=this->Face(idface);
if (!fvface.Is_Null_Flux_Face() && !fvface.Boundaryface())
{
// cout << "Flux Internal Face"<<endl;
if (Face(idface).Cell(0)==c)
cellit->AddNeighbour(Face(idface).Cell(1));
else
cellit->AddNeighbour(Face(idface).Cell(0));
}
}
c++;
}
}
else
{
cout << "ERROR: Grid does not have any face..." << endl;
}
}
//Esto supone que el tipo de elementos ya esta definido
//Virtual function
void Fv_CC_Grid::Iniciar_Caras()
{
//Numero de faces dependiendo de los numeros de vertices
int numcellfaces [9]={0,0,0,0,4,5,5,0,6};
int v1,v2;
//
int numfaces=0;
int nfi=0; //Numero de caras interiores
int nfb=0; //Numero de caras en el borde
bool intfacefound;
int dc=0; //dummy cells
int c2;
// //Declaro otro iterador que no esta aca
//
// //Inicio las celdas
//cout << "Cell initialized "<<inicie_cells<<endl;
//cout << "Node initialized "<<inicie_nodes<<endl;
if (!inicie_cells || !inicie_nodes)
{
cout << "Nodes or cells not initiated. Grid initiation failed..."<<endl;
return;
}
vector <int> v(0);
//vector<vector<int> > vec(4, vector<int>(4))
//Para borde
int numdummycells=0;
vector < vector <bool> > cellfacefound;
//cout << "cell loop"<<endl;
//Control for
//Init cell face containers
for (cellit=cell.begin();cellit!=cell.end();cellit++)
{
//cout <<"cell loop"<<endl;
cellit->Init_Idface(numcellfaces[cellit->Num_Vertex()]);
cellit->Init_NumberofFaces(numcellfaces[cellit->Num_Vertex()]);
vector <bool> cellfaces;
cellfaces.assign(numcellfaces[cellit->Num_Vertex()],false);
cellfacefound.push_back(cellfaces);
}
//cout << "end cell loop"<<endl;
//Esto antes era sin iteradores
//Ahora recorro asi las celdas
int c1=0; //indice de la celda 1
//Celda primera
for (cellit=cell.begin();cellit!=cell.end();cellit++)
{
//cout <<"cell loop"<<endl;
// cout <<"Looking through cell "<<c1<<endl;
vector <int> intverts; //Los vertices interiores que voy encontrando
vector <Cell_CC>::iterator cellit2; //cellit 2 es a la segunda cara del elemento
int c2=c1+1;
//Recorro las caras
int numfaceverts;
vector <int> tempNodes; //Nodos de cada cara
for (int nf=0;nf<numcellfaces[cellit->Num_Vertex()];nf++)
{
tempNodes=cellit->GlobalVertFace(nf);
numfaceverts=tempNodes.size();
//Comienzo del 1 aumentado una posicion
//Busco la otra celda que comparta los vertices de la cara de cellit
cellit2=cellit+1;
c2=c1+1;
intfacefound=false; //enc refiere a que encontro una cara interna (sino es del borde)
//Si es la ultima celda solo quedan dummy cells
int nfenc2;
while (cellit2!=cell.end() && !intfacefound && !cellfacefound[c1][nf])//Recorrida por todos los elementos para ver quien comparte lado
{
vector <int> tempNodes2; //cell2 verts
int numfaceverts2;
for (int nf2=0;nf2<numcellfaces[cellit2->Num_Vertex()];nf2++)
{
tempNodes2=cellit2->GlobalVertFace(nf2);
numfaceverts2=tempNodes2.size();
//Compare tempNodes (vertices of cell1 face) with
int nvenc=NumVecElemFound(tempNodes,tempNodes2);
//if (NumVecElemFound(tempNodes,cellit2->Conect())==tempNodes.size())
//Si no lo coloco asi no anda
int maxfaces=max_int(numfaceverts,numfaceverts2);
//Found an internal face
//cout << "nf1 nf2 " << nf << " "<<nf2<<endl;
//cout << "c1 c2" << c1 << " " << c2<<endl;
//cout << "TempNodes"<<endl;
//for (int nn=0;nn<tempNodes.size();nn++)cout << tempNodes[nn]<<endl;
//cout << "TempNodes2"<<endl;
//for (int nn=0;nn<tempNodes2.size();nn++)cout << tempNodes2[nn]<<endl;
//cout << "nvenc maxfaces" <<nvenc<< maxfaces<<endl;
if (nvenc==maxfaces)
{
intfacefound=true;
//Los numeros de vertices encontrados tienen que ser mayores o iguales a 3
// ENCONTRE LA CARA INTERNA
//Ya tengo que tener iniciado el numero de cara
//Recorro las caras
//////Aca cambio esto y construyo la cara
vector <int> facecells(c1,c2); //aca el primer cell es el c
vector <_Vertex> facevertex;
vector <Node> facenodes;
facenodes.push_back(node[c1]);facenodes.push_back(node[c2]);
for (int fn=0;fn<numfaceverts;++fn) facevertex.push_back(this->vert[tempNodes[fn]]);
nfenc2=nf2;
//Busco que vertices encontro
//Falta ubicar los Cells, pero se corresponden con los nodos en las FvGrids
//Ojo adentro de la funcion f se ve para donde va la normal
_FvFace f(nf,tempNodes,facevertex,facenodes,false);
cellfacefound[c2][nf2]=true;
//Adding global face indexes for each cell
this->Cell(c1).Id_Face(nf,numfaces);
this->Cell(c2).Id_Face(nfenc2,numfaces);
//cout << "Found internal face"<<numfaces<<endl;
//cout << "Internal faces"<<nfi<<endl;
face.push_back(f);
nfi++;
numfaces++;
} //Fin del if found internal face
}//End of search faces
c2++;
cellit2++;
}//fin del while
//Tengo que agrupar los vertices del cell1 que no fueron encontrados
//Puede ser que haya mas de 2 faces, para esto puedo hacer lo siguiente
//1)tengo que ver las normales
//2) Puedo asociar las conectividades de acuerdo a Nastran
//Busco que
//De todos los vertices del cell1 no encontre 3 o mas comunes con otros cells
//Boundary faces
if (!intfacefound && !cellfacefound[c1][nf]) //Si tengo vertices que no son interiores
{
//Create Dummy Cells
vector <int> facecells(c1,this->Num_Cells()+numdummycells); //aca el primer cell es el c, el c2 es el dummy
vector <_Vertex> facevertex;
vector <Node> facenodes;
facenodes.push_back(node[c1]); //El otro nodo es ficticio, puedo ver que hago con esto
//Lo necesito para la distancia PN
for (int fn=0;fn<numfaceverts;++fn) facevertex.push_back(this->vert[tempNodes[fn]]);
this->Cell(c1).Id_Face(nf,numfaces);
//Busco que vertices encontro
//Falta ubicar los Cells, pero se corresponden con los nodos en las FvGrids
//Ojo adentro de la funcion f se ve para donde va la normal
//Si en esta funcion entra un vertice ya se que es una BoundaryFace
_FvFace f(nf,tempNodes,facevertex,facenodes,true);
face.push_back(f);
temp_boundfaces.push_back(numfaces);
nfb++;
numdummycells++;
numfaces++;
}
}//Fin del for de faces para cell c2
c1++;
}// Fin de for de cell c1
//Bidimensional case
//Only for regular mesh case
// if (this->bidim_mesh)
// {
// for(cellit=cell.begin();cellit!=cell.end();cellit++)
// {
// //In bidimensional cases face 0 and 1 are null_flux_faces
// this->Face(cellit->Id_Face(0)).Null_Flux_Face(true);
// this->Face(cellit->Id_Face(1)).Null_Flux_Face(true);
// }
// }
num_faces=numfaces;
num_boundary_faces=nfb;
//Init Face orientation
cout << "[I] Faces: " <<numfaces<<endl;
cout << "[I] Boundary Faces: " <<num_boundary_faces<<endl;
}
//
//If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:
//
//std::find(vec.begin(), vec.end(), x)
//
//runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - much more efficient with large numbers of elements.
//
//std::set also guarantees all the added elements are unique, which saves you from having to do anything like 'if not contained then push_back()...`.
////
void Fv_CC_Grid::Init_Faces()
{
//Numero de faces dependiendo de los numeros de vertices
int numcellfaces [9]={0,0,0,0,4,5,5,0,6};
int v1,v2;
//
int numfaces=0;
int nfi=0; //Numero de caras interiores
int nfb=0; //Numero de caras en el borde
bool intfacefound;
int dc=0; //dummy cells
int c2;
// //Declaro otro iterador que no esta aca
//
// //Inicio las celdas
//cout << "Cell initialized "<<inicie_cells<<endl;
//cout << "Node initialized "<<inicie_nodes<<endl;
if (!inicie_cells || !inicie_nodes)
{
cout << "Nodes or cells not initiated. Grid initiation failed..."<<endl;
return;
}
else
{
set < vector <int> > faceverts;
set < vector <int> > deffaceverts;
vector < vector <int> > faceverts2;
vector <int> cellsperface; //Indicates
set< vector <int> > ::iterator it;
vector<vector <int> > cellglobalfaces(this->Num_Cells()); //Index to global cell faces
vector<vector <int> > facecells; //Index to global cell faces
set <vector <int> >::iterator sit;
//map<vector <int>, int> mymap;
//map<vector <int>, int> ::iterator mymapit;
map<int, vector <int> > mymap;
map<int, vector <int> > ::iterator mymapit;
map<vector <int> , int > sortfacemap; //map to the sorted face vertex set
map<vector <int> , int >::iterator sortfacemapit;
for (cellit=cell.begin();cellit!=cell.end();cellit++)
{
//cout <<"cell loop"<<endl;
cellit->Init_Idface(numcellfaces[cellit->Num_Vertex()]);
cellit->Init_NumberofFaces(numcellfaces[cellit->Num_Vertex()]);
}
//vector<vector<int> > vec(4, vector<int>(4))
//Para borde
int numdummycells=0;
vector < vector <bool> > cellfacefound;
//cout << "cell loop"<<endl;
//Control for
//Init cell face containers
int c=0;
double tenperc=this->Num_Cells()/10.0;
int tennum=0;
bool foundten[10];for (int i=0;i<10;i++)foundten[i]=false;
double perc;
int k=0;
int numfaces=0;
int globalfaceid=0;
double ittime_spent;
clock_t ittime_begin, ittime_end, ittime_temp;
ittime_end = clock();
cout << "[I] Creating Faces..."<<endl;
cout << "[I] Completed: "<<endl;
for (cellit=cell.begin();cellit!=cell.end();cellit++)
{
vector<int> tempglobalfaces;
//cout <<"cell "<<c<<endl;
// cellit->Init_Idface(numcellfaces[cellit->Num_Vertex()]);
// cellit->Init_NumberofFaces(numcellfaces[cellit->Num_Vertex()]);
//cellfaces.assign(numcellfaces[cellit->Num_Vertex()],false);
//cellfacefound.push_back(cellfaces);
//cout << "Cell "<<c<<endl;
for (int nf=0;nf<numcellfaces[cellit->Num_Vertex()];nf++)
{
std::pair<std::set< vector <int> >::iterator,bool> ret; //To check if face are stored
//Pushing cell faces to set
int numfaceverts;
vector <int> tempNodes; //Nodos de cada cara
tempNodes=cellit->GlobalVertFace(nf);
numfaceverts=tempNodes.size();
vector <int> tempNodesSort(tempNodes);
std::sort (tempNodesSort.begin(), tempNodesSort.end(), myobject);
vector <int> tempv;
ret = faceverts.insert(tempNodesSort);
it=ret.first;
//if ((facepos)>cellsperface.size()) cout << "ERROR"<<endl;
if (ret.second==true) //Inserted, New faces
{
deffaceverts.insert(tempNodes);
mymap[globalfaceid]=tempNodes;
mymap.insert(std::pair<int, vector<int> > (globalfaceid, tempNodes) );
sortfacemap.insert(std::pair< vector <int> , int > (tempNodesSort, globalfaceid) );
//mymap[tempNodes]=globalfaceid; //this is long way faster than vector push_back
//mymap.insert(std::pair<vector<int>,int> (tempNodes,globalfaceid) );
cellglobalfaces[c].push_back(globalfaceid);
vector <int> vt; vt.push_back(c);
facecells.push_back(vt);
//cout << "Global Face Id "<< globalfaceid<<endl;
this->Cell(c).Id_Face(nf,globalfaceid);
globalfaceid++;
//*it=tempNodes;
//cout << "true"<<endl;
}
else
{
int faceid=sortfacemap[tempNodesSort];
// sortfacemapit=sortfacemap.find(tempNodesSort);
// int faceid=sortfacemapit->second;
// if (sortfacemapit!=sortfacemap.end())
// {
// cout << "face found " << sortfacemapit->second<<". facecells size"<< facecells.size()<<endl;
// }
//map find is equal to [] operator
//cout << "Face found" <<sortfacemap[tempNodesSort]<<endl;
//facecells[sortfacemapit->second].push_back(c);
cellglobalfaces[c].push_back(faceid);
facecells[faceid].push_back(c);
this->Cell(c).Id_Face(nf,faceid);
}
}//En cell faces
if (!foundten[tennum] && c>tennum*tenperc)
{
foundten[tennum]=true;
tennum++;
cout << tennum*10<< " % ";
}
c++;
}
cout << "\n";
ittime_spent = (double)(clock() - ittime_end) / CLOCKS_PER_SEC;
cout << "[I] Face Creation Time: " <<scientific <<ittime_spent <<" " <<endl;
//Inserting faces
cout << "[I] Inserting Faces ..." <<endl;
ittime_end = clock();
int nf=0;
int nfb=0;
for (it=deffaceverts.begin(); it!=deffaceverts.end(); ++it)
{
vector <int> tempNodes;
vector <_Vertex> facevertex;
vector <Node> facenodes;
tempNodes=mymap[nf];
facenodes.push_back(this->node[facecells[nf][0]]); //El otro nodo es ficticio, puedo ver que hago con esto
//Lo necesito para la distancia PN
for (int fn=0;fn<tempNodes.size();++fn) facevertex.push_back(this->vert[tempNodes[fn]]);
bool boundaryface=false;
//cout << "Face " << nf << "Cells "<<endl;
// for (int fc=0;fc<facecells[nf].size();fc++) cout << facecells[nf][fc]<<" ";
// cout <<endl;
//Adding global face indexes for each cell
//this->Cell(facecells[0]).Id_Face(nf,nf);
// Looking for boundary faces
if (facecells[nf].size()==1)
{
boundaryface=true;
//this->Cell(facecells[1]).Id_Face(nfenc2,nf); //Id_Face(nfenc2,Face Id);
temp_boundfaces.push_back(nf);
nfb++;
//NEW
vector <int> sortfacevertex(tempNodes);
std::sort (sortfacevertex.begin(), sortfacevertex.end(), myobject);
sortbfacemap.insert(std::pair< vector <int> , int > (sortfacevertex, nf) );
}
else
{
facenodes.push_back(this->node[facecells[nf][1]]);
}
_FvFace f(nf,mymap[nf],facevertex,facenodes,boundaryface);
this->face.push_back(f);
nf++;
}
this->num_faces=deffaceverts.size();
this->num_boundary_faces=nfb;
ittime_spent = (double)(clock() - ittime_end) / CLOCKS_PER_SEC;
cout << "[I] Face Insertion Time: " <<scientific <<ittime_spent <<" " <<endl;
}//If cells were initialized
}
const map<vector <int> , int > Fv_CC_Grid::FaceVertsMap()const
{
map<vector <int> , int > ret;
for (int f=0;f<this->Num_Faces();f++)
{
vector<int >faceverts=this->Face(f).Vert();
std::sort (faceverts.begin(), faceverts.end(), myobject);
ret.insert(std::pair< vector <int> , int > (faceverts, f) );
}
return ret;
}
////
////Adapted From freecfd
////void Fv_CC_Grid::Init_Faces()
////{
////
//// Set face connectivity lists
//// int hexaFaces[6][4]= {
//// {0,3,2,1},
//// {4,5,6,7},
//// {1,2,6,5},
//// {0,4,7,3},
//// {1,5,4,0},
//// {2,3,7,6}
//// };
//// int prismFaces[5][4]= {
//// {0,2,1,0},
//// {3,4,5,0},
//// {0,3,5,2},
//// {1,2,5,4},
//// {0,1,4,3}
//// };
//// int pyraFaces[5][4]= {
//// {0,3,2,1},
//// {0,1,4,0},
//// {1,2,4,0},
//// {3,4,2,0},
//// {0,4,3,0}
//// };
//// int tetraFaces[4][3]= {
//// {0,2,1},
//// {1,2,3},
//// {0,3,2},
//// {0,1,3}
//// };
////
//// // Search and construct faces
//// int faceCount=0;
////
//// // Time the face search
//// double timeRef, timeEnd;
//// if (Rank==0) timeRef=MPI_Wtime();
//// vector<int> unique_nodes;
//// set<int> repeated_node_cells;
////
//// Loop through all the cells
//// for (int c=0;c<this->Num_Cells();++c) {
//// int degenerate_face_count=0;
//// Loop through the faces of the current cell
//// for (int cf=0;cf<cell[c].Num_Faces();++cf) {
//// bool degenerate=false;
//// _FvFace tempFace;
//// int facenodeCount; //Is vertex count indeed
//// int *tempNodes;
//// switch (this->cell[c].Num_Vertex()) {
//// case 4: // Tetrahedra
//// facenodeCount=3;
//// tempNodes= new int[3];
//// break;
//// case 5: // Pyramid
//// if (cf<1) {
//// facenodeCount=4;
//// tempNodes= new int[4];
//// } else {
//// facenodeCount=3;
//// tempNodes= new int[3];
//// }
//// break;
//// case 6: // Prism
//// if (cf<2) {
//// facenodeCount=3;
//// tempNodes= new int[3];
//// } else {
//// facenodeCount=4;
//// tempNodes= new int[4];
//// }
//// break;
//// case 8: // Brick
//// facenodeCount=4;
//// tempNodes= new int[4];
//// break;
////
//// }//Cell Node Count
////
//// Face count is incremented everytime a new face is found
//// tempFace.id=faceCount;
//// // Assign current cell as the parent cell
//// tempFace.parent=c;
//// Assign boundary type as internal by default, will be overwritten later
//// tempFace.bc=INTERNAL_FACE;
//// Store the node local ids of the current face
//// for (int fn=0;fn<facenodeCount;++fn) {
//// switch (cell[c].Num_Vertex()) {
//// case 4: tempNodes[fn]=this->Cell(c).Vert(tetraFaces[cf][fn]); break; //Originally cellNode(c,tetraFaces[cf][fn]).id
//// case 5: tempNodes[fn]=this->Cell(c).Vert(pyraFaces[cf][fn]); break;
//// case 6: tempNodes[fn]=this->Cell(c).Vert(prismFaces[cf][fn]); break;
//// case 8: tempNodes[fn]=this->Cell(c).Vert(hexaFaces[cf][fn]); break;
//// }
//// }
//// Check if there is a repeated node
//// unique_nodes.clear();
//// bool skip;
//// for (int fn=0;fn<facenodeCount;++fn) {
//// skip=false;
//// for (int i=0;i<fn;++i) {
//// if (tempNodes[fn]==tempNodes[i]) {
//// skip=true;
//// break;
//// }
//// }
//// if (!skip) unique_nodes.push_back(tempNodes[fn]);
//// }
//// if (unique_nodes.size()!=facenodeCount) {
//// repeated_node_cells.insert(c); // mark the owner cell (it has repeated nodes)
//// if (unique_nodes.size()==2) { // If a face only has two unique nodes, mark as degenerate
//// degenerate=true;
//// degenerate_face_count++;
//// }
//// facenodeCount=unique_nodes.size();
//// for (int fn=0;fn<facenodeCount;++fn) tempNodes[fn]=unique_nodes[fn];
//// }
//// Find the neighbor cell
//// bool internal=false;
//// bool unique=true;
//// Loop cells neighboring the first node of the current face
//// for (int nc=0;nc<node[tempNodes[0]].cells.size();++nc) {
//// i is the neighbor cell index
//// int i=node[tempNodes[0]].cells[nc];
//// // If neighbor cell is not the current cell itself, and it has the same nodes as the face
//// if (i!=c && cell[i].HaveNodes(tempFace.nodeCount,tempNodes)) {
//// If the neighbor cell index is smaller then the current cell index,
//// it has already been processed so skip it
//// if (i>c) {
//// tempFace.neighbor=i;
//// internal=true;
//// } else {
//// unique=false;
//// }
//// }
//// } //Node cell nc
////
//// if (unique && !degenerate) { // If a new face
//// Insert the node list
//// for (int fn=0;fn<tempFace.nodeCount;++fn) tempFace.nodes.push_back(tempNodes[fn]);
//// if (!internal) { // If the face is either at inter-partition or boundary
//// tempFace.bc=UNASSIGNED_FACE; // yet
//// vector<int> face_matched_bcs;
//// int cell_matched_bc=-1;
//// bool match;
//// for (int nbc=0;nbc<raw.bocoNameMap.size();++nbc) { // For each boundary condition region
//// match=true;
//// for (int i=0;i<tempFace.nodeCount;++i) { // For each node of the current face
//// if (raw.bocoNodes[nbc].find(tempNodes[i])==raw.bocoNodes[nbc].end()) {
//// match=false;
//// break;
//// }
//// }
//// if (match) { // This means that all the face nodes are on the current bc node list
//// face_matched_bcs.push_back(nbc);
//// }
//// // There can be situations like back and front symmetry BC's in which
//// // face nodes will match more than one boundary condition
//// // Check if the owner cell has all its nodes on one of those bc's
//// // and eliminate those
//// if (cell_matched_bc==-1) {
//// match=true;
//// for (int i=0;i<cell[c].nodeCount;++i) {
//// if (raw.bocoNodes[nbc].find(cell[c].nodes[i])==raw.bocoNodes[nbc].end()) {
//// match=false;
//// break;
//// }
//// }
//// if (match) { // This means that all the cell nodes are on the current bc node list
//// cell_matched_bc=nbc;
//// }
//// }
//// }
//// if (face_matched_bcs.size()>1) {
//// for (int fbc=0;fbc<face_matched_bcs.size();++fbc) {
//// if(face_matched_bcs[fbc]!=cell_matched_bc) {
//// tempFace.bc=face_matched_bcs[fbc];
//// break;
//// }
//// }
//// } else if (face_matched_bcs.size()==1) {
//// tempFace.bc=face_matched_bcs[0];
//// }
//// // Some of these bc values will be overwritten later if the face is at a partition interface
////
//// } // if not internal
//// face.push_back(tempFace);
//// cell[c].faces.push_back(tempFace.id);
//// if (internal) cell[tempFace.neighbor].faces.push_back(tempFace.id);
//// ++faceCount;
//// } //New face
//// delete [] tempNodes;
//// } //for face cf
//// cell[c].faceCount-=degenerate_face_count;
//// } // for cells c
////
//// // Loop cells that has repeated nodes and fix the node list
//// set<int>::iterator sit;
//// vector<int> repeated_nodes;
//// for (sit=repeated_node_cells.begin();sit!=repeated_node_cells.end();sit++) {
//// // Find repeated nodes
//// repeated_nodes.clear();
//// for (int cn=0;cn<cell[(*sit)].nodeCount;++cn) {
//// for (int cn2=0;cn2<cn;++cn2) {
//// if (cell[(*sit)].nodes[cn]==cell[(*sit)].nodes[cn2]) repeated_nodes.push_back(cell[(*sit)].nodes[cn]);
//// }
//// }
//// if (cell[(*sit)].nodeCount==8 && repeated_nodes.size()==2) { // TODO Only Hexa to Penta mapping is handled for now
//// cell[(*sit)].nodes.clear();
//// // Loop triangular cell faces
//// int rindex=-1;
//// for (int cf=0;cf<cell[(*sit)].faceCount;++cf) {
//// if (cellFace((*sit),cf).nodeCount==3) {
//// // Loop the face nodes and see if the repeated node apears
//// int fn;
//// for (fn=0;fn<3;++fn) {
//// if (cellFace((*sit),cf).nodes[fn]==repeated_nodes[0]) { rindex=0; break; }
//// if (cellFace((*sit),cf).nodes[fn]==repeated_nodes[1]) { rindex=1; break; }
//// }
//// // Start from fn and fill the new cell node list
//// if (fn==0) {
//// cell[(*sit)].nodes.push_back(cellFace((*sit),cf).nodes[0]);
//// cell[(*sit)].nodes.push_back(cellFace((*sit),cf).nodes[1]);
//// cell[(*sit)].nodes.push_back(cellFace((*sit),cf).nodes[2]);
//// } else if (fn==1) {
//// cell[(*sit)].nodes.push_back(cellFace((*sit),cf).nodes[1]);
//// cell[(*sit)].nodes.push_back(cellFace((*sit),cf).nodes[2]);
//// cell[(*sit)].nodes.push_back(cellFace((*sit),cf).nodes[0]);
//// } else if (fn==2) {
//// cell[(*sit)].nodes.push_back(cellFace((*sit),cf).nodes[2]);
//// cell[(*sit)].nodes.push_back(cellFace((*sit),cf).nodes[0]);
//// cell[(*sit)].nodes.push_back(cellFace((*sit),cf).nodes[1]);
//// }
////
//// }
////
//// }
//// cell[(*sit)].nodeCount=6;
//// }
//// }
//// repeated_node_cells.clear();
////
//// for (int c=0; c<cellCount; ++c) {
//// if (Rank==0) if (cell[c].faceCount != cell[c].faces.size() ) cout << "no match" << "\t" << c << "\t" << cell[c].faceCount << "\t" << cell[c].faces.size() << "\t" << cell[c].nodeCount << endl;
//// }
////
//// if (Rank==0) {
//// timeEnd=MPI_Wtime();
//// cout << "[I Rank=" << Rank << "] Time spent on finding faces= " << timeEnd-timeRef << " sec" << endl;
//// }
////
//// for (int f=0;f<faceCount;++f) for (int n=0;n<face[f].nodes.size();++n) faceNode(f,n).faces.push_back(f);
////
////
////} // end Grid::create_faces
void Fv_CC_Grid::CalcCellVolumes()
{
for (int c=0;c<Num_Cells();c++)
{
Scalar vol=0.;
for (int cellface=0;cellface<this->cell[c].Num_Faces();cellface++)
{
_FvFace face = this->Face(Cell(c).Id_Face(cellface));
//vol+=face.Af()&face.Center();
//TO MODIFY
vol+=CellFaceAf_Slow(c,cellface)&face.Center();
}
vol=vol/3.;
this->Cell(c).Vp(vol);
}
}
//TO MODIFY, MUST RETURN A REFERENCE
const GeomSurfaceField<Vec3D> Fv_CC_Grid::Sf() const
{
GeomSurfaceField<Vec3D> ret(this->num_faces);
ret.AssignGrid(this);
for (int f = 0; f < this->num_faces; f++)
{
//THIS MUST NOT RETURN THE NORMAIZED VALUE
// ret.Val(f, this->face[f].Af().VecNorm());
ret.Val(f, this->face[f].Af());
}
return ret;
}
const std::string Fv_CC_Grid::Read_CGNS()
{
map<vector <int> , int >::iterator sortfacemapit; //for boundary creation
std::stringstream out;
//raw data - vertices
//base class function
out << "[I] Reading Initial CGNS ...\n"<<endl;
Read_InitialCGNS();
//Read boundary cells - Assuming boundary cell entry
vector<vector<int> > bpnode;
int boundnode =0;
cout << "[I] Creating boundary Elements ..."<<endl;
//--------------------------------
//IF INPUT IS WITH BOUNDARY CELLS
//--------------------------------
//raw->Cells
vector <Cell_CC> vboundcell; //For bidimensional cells
int boundelem =0;
//Read boundary cells - Assuming boundary cell entry
vector<vector<int> > bpelem;
//Boundary Patches bc
for (int bp=0;bp<this->raw.bc_elem_list.size();bp++)
{
//Associate face <-> 2d cell coinc
//bcfaces.push_back()
vector <int> temp;
//Search bc vertex in each 2D Cell
set <int> sbc = this->raw.bc_elem_list[bp];
set <int>::iterator sit=sbc.begin();
for (; sit!=sbc.end();sit++)
{
boundelem++;
temp.push_back(*sit);
}
bpelem.push_back(temp);
}
cout << "[I] Boundary Elements Count: "<<boundelem<<endl;
//vector<vector<int>> idbcellasoc(boundelem,vector<int>(2,-1)); //Id cells
vector<int> idbcell(boundelem,-1);
int bcell=0;
cout << "[I] Creating Cells ..."<<endl;
double ittime_spent;
clock_t ittime_begin, ittime_end, ittime_temp;
ittime_end = clock();
set <int> bcellids;
set <int>::iterator bcellidsit;
for (int bp=0;bp<bpelem.size();bp++)
for(int el=0;el<bpelem[bp].size();el++)
bcellids.insert(bpelem[bp][el]-1);
// vector<int> connect;
// Cell_CC scell;
for (int idcell =0 ; idcell<raw.cellConnIndex.size();idcell++)
{
int cellvertnum;
if (idcell<(raw.cellConnIndex.size()-1))
cellvertnum = raw.cellConnIndex [idcell+1] - raw.cellConnIndex [idcell];
else cellvertnum = raw.cellConnectivity.size()- raw.cellConnIndex [idcell] ;
bool found =false;
vector<int> connect;
for (int cv =0 ; cv<cellvertnum;cv++)
connect.push_back(raw.cellConnectivity[ raw.cellConnIndex [idcell] + cv]);
Cell_CC scell(idcell,connect);
//Check if this is a boundary element
//TO MODIFY, MUST CONSIDER TETRA CELLS
//if (connect.size()<=4) //All connectivity numbers are 3d
// for (int bp=0;bp<bpelem.size();bp++)
// for(int el=0;el<bpelem[bp].size();el++)
// if (idcell==(bpelem[bp][el]-1)) //Index of rawdata is counting from 1
// {
// vboundcell.push_back(scell);
// idbcell[bcell]=idcell;
// bcell++;
// found=true;
// }
//New form
bcellidsit=bcellids.find(idcell);
if (bcellidsit!=bcellids.end())
{
vboundcell.push_back(scell);
idbcell[bcell]=idcell;
bcell++;
found=true;
}
else
this->cell.push_back(scell);
}
ittime_spent = (double)(clock() - ittime_end) / CLOCKS_PER_SEC;
cout << "[I] Cell Creation Time: " <<scientific <<ittime_spent <<" " <<endl;
//vector<vector<int>> idbcellasoc(boundelem,vector<int>(2,-1)); //Id cells
bcell=0;
cout << "[I] Created " << this->cell.size() << " cells. "<<endl;
//Updating cell number
this->num_cells=cell.size();
// Nodes
cout << "[I] Creating Central Nodes ..."<<endl;
CreateNodesFromCellVerts();
this->inicie_nodes=true;
this->inicie_cells=true;
out << "[I] Assigning Faces ..."<<endl;
//Iniciar_Caras();
Init_Faces();
cout << "[I] Assigning Neighbours ..."<<endl;
AssignNeigboursCells();
cout << "[I] Calculating Volumes ..."<<endl;
CalcCellVolumes();
//CreateNodesFromCellVerts();
vector <Patch> vpatch;
cout << "[I] Boundary Faces count: " <<temp_boundfaces.size()<<endl;
std::vector<std::list <int> >bpfaces;
// cout << "Boundary zone nodes" << bpnode[0][node]<<endl;
out << "[I] Number of Patches: " << this->raw.bc_elem_list.size() <<endl;
int nBocos=raw.bocoNameMap.size(); //Extrcted from freecfd
out << "[I] Creating Patches ..."<<endl;
cout << "[I] Creating Boundary Patches..." <<endl;
ittime_end = clock();
vector <int> faceverts;
string pname;
int totalboundfaces=temp_boundfaces.size();
for (int bp=0;bp<this->raw.bc_elem_list.size();bp++) //Look Through patch
{
pname=this->imported_patchnames[bp];
list <int> temp;
list <int> tempnew;
out << "[I] Searching patch " << bp << ", named "<< pname<<", remaining boundary faces count: "<<temp_boundfaces.size()<<endl;
int nfoundfaces=0;
if (raw.bocoNodes[bp].size()>0)
{
cout << "[I] Patch defined via Nodes..."<<endl;
for (int bf=0;bf<temp_boundfaces.size();bf++) //Look through all boundary faces, coincidence with each boconodes patch
{
int idf=temp_boundfaces[bf];
//bool enc=FindAllVals(this->Face(idf).Vert(), bpnode[bp]);
bool enc=true;
for (int n=0;n<this->Face(idf).Vert().size();n++)
if (!(this->raw.bocoNodes[bp].find(this->Face(idf).Vert()[n])!=this->raw.bocoNodes[bp].end())) enc=false;
if (enc)
{
temp.push_back(idf);
temp_boundfaces.erase(temp_boundfaces.begin()+bf);
bf--;
}
}
}
else if (bpelem[bp].size()>0) //If bc are defined via 2D elements
{
//Looking through raw elements (faces in Grid)
cout << "[I] Patch defined via Elems..."<<endl;
for (int el=0;el<bpelem[bp].size();el++)
{
//Adding element vertices
//for (int iv=0;iv<this->Cell(bpelem[bp][el]).Num_Vertex();iv++)
for (int iv=0;iv<vboundcell[bcell].Num_Vertex();iv++) faceverts.push_back(vboundcell[bcell].Vert(iv));
vector <int> sortfaceverts(faceverts);
std::sort (sortfaceverts.begin(), sortfaceverts.end(), myobject);
//NEW FORM
//// /*COULD BE LIKE THIS:*/int faceid=sortbfacemap[sortfaceverts];
sortfacemapit=sortbfacemap.find(sortfaceverts);
int faceid=sortfacemapit->second;
if (sortfacemapit!=sortbfacemap.end()) //Found
temp.push_back(faceid);
faceverts.clear();
bcell++;
}//End element
}
else
out << "[I] WARNING: No Boundary defined. "<<endl;
bpfaces.push_back(temp);
cout << "[I] Created Patch "<<pname<<", Face Count: " <<temp.size()<<endl;
//cout << "[I] Created new Patch "<<pname<<", Face Count: " <<tempnew.size()<<endl;
Patch p(pname,bpfaces[bp]);
vpatch.push_back(p);
}
ittime_spent = (double)(clock() - ittime_end) / CLOCKS_PER_SEC;
cout << "[I] Boundary Patches Creation Time: " <<scientific <<ittime_spent <<" " <<endl;
this->SetFaceLocalCellNeighbours(); //New, 20150518
Boundary bound(vpatch);
this->AddBoundary(bound);
cout << "[I] Creating internal faces..." <<endl;
this->Create_IntFaces();
this->boundary.AddGridPtr(*this);
out << "[I] Mesh created ..." << endl;
slog << out;
return out.str();
}
//This function sets local ids of cell neighbours for each cell face
void Fv_CC_Grid::SetFaceLocalCellNeighbours()
{
int ln[2]; ln[0]=1; ln[1]=0;
int numnb=1; //Boundary faces
for (int f=0;f<this->Num_Faces();f++)
{
vector <int> temp;
_FvFace face=this->Face(f);
if (!this->Face(f).Boundaryface()) numnb=2;
//cout << "Not boundary face"<<endl;
//ap=-face.Norm_ad()/face.Dist_pn()*fi;
//an=-ap;
//nbr_eqn.push_back(VolField.Grid().Cell(c));
//eqnsys.Eqn(face.Cell(0)).Coeffs(ap,an);
//cout << "Look through neighbours"<<endl;
for (int nb=0;nb<numnb;nb++) //Face cells
{
//cout << "Neighbour" <<endl;
int localnid; //Id of local neigbour
localnid=ln[nb];
//p cell
int pcellid=face.Cell(nb);
int ncellid=face.Cell(localnid);
//cout << "Eqn size" << eqnsys.Num_Eqn()<<endl;
//cout << "Creating Eqn ... pcell id"<< pcellid<<endl;
//eqnsys.Eqn(pcellid).Ap()+=ap;
int neigbour_cell;
int localneighbourid; //local cell neigbour
//Neighbours are
//Find the global cell
Cell_CC cell=this->Cell(face.Cell(nb));
for (int localncell=0;localncell<cell.Num_Neighbours();localncell++)
if (cell.Neighbour(localncell)==ncellid)
{
localneighbourid=localncell;
temp.push_back(localncell);
}
//eqnsys.Eqn(pcellid).An(localneighbourid)+=an;
}//nb
this->face_local_cell_neighbour.push_back(temp);
}//Faces
}//Fv_CC_Grid::SetFaceLocalCellNeighbour()
const std::string Fv_CC_Grid::Read_NASTRAN() {
string cad;
FluxSol::Nastran::Modelo mod(this->fileName);
cout << "Nastran model created."<<endl;
cout << "[I] Creating vertices ..."<<endl;
this->vert.assign(mod.NumNodes(),_Vertex());
for (int nv=0;nv<mod.NumNodes();nv++)
this->vert[nv]=_Vertex(mod.Nodos[nv].VerId_Nastran(),
mod.Nodos[nv].Sc_int(),
mod.Nodos[nv].Coords());
this->num_verts=this->vert.size();
cout << "[I] " <<mod.NumNodes() << " vertices created. "<<endl;
// nodes=process_nodes(data);
// connectivity=process_cells(data);
//
cout << "[I] Creating cells..." << endl;
//this->cell.assign(mod.Elementos.size(),scell);
cout << "[I] Cell number "<<mod.Elementos.size()<<endl;
vector <int> v=mod.Elementos[140].Conect_int();
cout << "Element vector conect size: "<<v.size()<<endl;
// cout << "Element type: "<<mod.Elementos[0].Type()<<endl;
map < int , int> pidloc; //at left is id, right is position
map <int, int >::iterator pidloc_it;
vector < vector <int> > patchelem; //Element (position per patch
set<int> belem; //Element number per patch
int found_pids=0;
for (int idcell=0; idcell<mod.Elementos.size();idcell++)
{
if (mod.Elementos[idcell].Type()!="CQUAD4" && mod.Elementos[idcell].Type()!="CTRIA3")
{Cell_CC scell(idcell, mod.Elementos[idcell].Conect_int());
this->cell.push_back(scell);}
else { //Boundary element
int pid=mod.Elementos[idcell].Pid();
pidloc_it=pidloc.find(pid);
if (pidloc_it!=pidloc.end()) //pid already created
{
// cout << "Existent pid "<< pid << ", element" <<idcell<<endl;
patchelem[pidloc_it->second].push_back(idcell);
}
else
{
// cout << "Found new pid "<< pid << ", element" <<idcell<<endl;
pidloc.insert(std::pair <int,int> (pid,found_pids));
patchelem.push_back(vector<int>(1,idcell));
found_pids++;
}}
//belem.insert(idcell);
}
this->num_cells=cell.size();
//cout << "[I] Created " << mod.Elementos.size() - belem.size() << " internal cells." << endl;
cout << "[I] Creating Central Nodes..." << endl;
CreateNodesFromCellVerts();
this->inicie_nodes=true;
this->inicie_cells=true;
cout << "[I] Assigning Faces..." << endl;
Init_Faces();
cout << "[I] Assigning Neighbours..." << endl;
AssignNeigboursCells();
cout << "[I] Calculating Volumes..." << endl;
CalcCellVolumes();
cout << "[I] Creating Patches..." << endl;
myclass myobject;
//TO MODIFY: THIS MUST BE COMBINED WITH FvGrid::ReadCGNS AT FVGRID.CPP
map<vector <int> , int >::iterator sortfacemapit;
vector <Patch> vpatch;
std::vector<std::list <int> >bpfaces;
vector <int> faceverts;
//SAME OF FvGrid::ReadCGNS
//Looking through raw elements (faces in Grid)
//Looks faces in sortbfacemap defined in Init_Faces
for (int bp=0;bp<found_pids;bp++)
{
list <int> temp;
cout << "[I] Patch defined via Elems..."<<endl;
for (int el=0;el<patchelem[bp].size();el++)
{
//Adding element vertices
//for (int iv=0;iv<this->Cell(bpelem[bp][el]).Num_Vertex();iv++)
//for (int iv=0;iv<vboundcell[bcell].Num_Vertex();iv++) faceverts.push_back(vboundcell[bcell].Vert(iv));
int bcell=patchelem[bp][el];
faceverts=mod.Elementos[bcell].Conect_int();
//for (int iv=0;iv<mod.Elementos[bcell].NumNodes();iv++) faceverts.push_back(vboundcell[bcell].Vert(iv));
vector <int> sortfaceverts(faceverts);
std::sort (sortfaceverts.begin(), sortfaceverts.end(), myobject);
//NEW FORM
//// /*COULD BE LIKE THIS:*/int faceid=sortbfacemap[sortfaceverts];
//or sortfacemapit=sortbfacemap.find(sortfaceverts);
sortfacemapit=sortbfacemap.find(sortfaceverts);
int faceid=sortfacemapit->second;
if (sortfacemapit!=sortbfacemap.end()) //Found
temp.push_back(faceid);
faceverts.clear();
bcell++;
}//End element
bpfaces.push_back(temp);
stringstream convert;
int pid=mod.Elementos[patchelem[bp][0]].Pid();
convert <<pid;
cout << "[I] Created Patch id"<<convert.str() <<", Face Count: " <<temp.size()<<endl;
//cout << "[I] Created new Patch "<<pname<<", Face Count: " <<tempnew.size()<<endl;
Patch p(convert.str(),bpfaces[bp]);
vpatch.push_back(p);
}//End patch
// ittime_spent = (double)(clock() - ittime_end) / CLOCKS_PER_SEC;
// cout << "[I] Boundary Patches Creation Time: " <<scientific <<ittime_spent <<" " <<endl;
this->SetFaceLocalCellNeighbours(); //New, 20150518
Boundary bound(vpatch);
this->AddBoundary(bound);
cout << "[I] Creating internal faces..." <<endl;
this->Create_IntFaces();
this->boundary.AddGridPtr(*this);
cout << "[I] Mesh created ..." << endl;
return cad;
}
}// FluxSol
|
921c6b6111ea704af5c676c8ff7fd6670208d6b9
|
405098e2ebbe05337d290aa30ad038c5b882da1b
|
/Banco/include/bank.h
|
1b1a20029e6fde933eeb4d9d4d902b107b40f6e7
|
[] |
no_license
|
rodrigobardales/BankHW
|
90d5d8521565dddf57282ed228826d3562d321a8
|
8eb5003eb47ba55f1c983baa44964e446726e353
|
refs/heads/master
| 2022-01-22T03:15:59.538236
| 2019-07-20T21:10:24
| 2019-07-20T21:10:24
| 197,981,219
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 503
|
h
|
bank.h
|
#ifndef BANK_H
#define BANK_H
#include "structs.h"
#include <iostream>
#include <fstream>
using namespace std;
class bank
{
private:
bool find_account(int);
float check_balance(int);
bool change_balance(int, float);
void write_history(int, char, float);
public:
bank();
void create_account(int, char[], float);
bool transaction(int, char, float);
void read_history();
void view_account(int);
void assisst_create();
void assisst_transaction();
};
#endif
|
e33dfe9ab34d0befdd62d78400cf9d355062eb12
|
6158a30d3850867583f68d0073892424d4b3c996
|
/efw-engine/Source/System/SplashScreen.cpp
|
d51cf0fe60decc824550eecaac7dc1e8be90c3fe
|
[] |
no_license
|
zhaoterryy/efw-engine
|
b3d665ba607309f1223cbf42bf7a066b570db76a
|
bab8b4e7cfa13fdef6aee6d65edf36b41b808663
|
refs/heads/master
| 2021-09-13T03:01:16.504602
| 2018-03-04T01:11:37
| 2018-03-04T01:11:37
| 106,895,517
| 1
| 0
| null | 2018-03-01T08:01:30
| 2017-10-14T03:39:26
|
C++
|
UTF-8
|
C++
| false
| false
| 642
|
cpp
|
SplashScreen.cpp
|
#include "SplashScreen.h"
#include "Application.h"
void SplashScreen::Show(sf::RenderWindow& RenderWindow)
{
sf::Texture image;
sol::table splashTable = GEngine::GLua()["splash_screen"];
std::string imagePath = splashTable.get<std::string>("img_path");
if (image.loadFromFile(imagePath) != true)
return;
sf::Sprite Sprite(image);
RenderWindow.draw(Sprite);
RenderWindow.display();
sf::Event Event;
while (RenderWindow.pollEvent(Event))
{
if (Event.type == sf::Event::KeyPressed
|| Event.type == sf::Event::MouseButtonPressed
|| Event.type == sf::Event::Closed)
{
return;
}
}
}
|
9ca6590f110e0189f5081ecc57ff378ae9a74a57
|
4b192ec98a8105478800e78d17878b4a087f0c00
|
/INTEGRA/INTEGRA.CPP
|
4776dd50d680ca57768c67008b352a3c0e05fb85
|
[] |
no_license
|
Jhongesell/IntegraDOS
|
f4594909e9f67a2328b328e03a7cd40e6a436d10
|
d8a9128908d956398f6c153e245763f787859984
|
refs/heads/master
| 2020-04-25T02:23:26.586444
| 2017-04-13T07:26:56
| 2017-04-13T07:26:56
| null | 0
| 0
| null | null | null | null |
IBM852
|
C++
| false
| false
| 52,977
|
cpp
|
INTEGRA.CPP
|
//////////////////////////////////////////////////////////////
// //
// I N T E G R A V E R. 1.0 //
// (Analisador de sistemas dinámicos interativos) //
// //
// Desarrollado para ambiente DOS en modo de video //
// VGA y SVGA a 256 colores. //
// //
// Autores: //
// //
// Humberto Carrillo Calvet //
// Antonio Carrillo Ledesma //
// Luis A. Nava Fernandez //
// //
// Desarrollado en: //
// //
// Laboratorio de Dinamica no Lineal //
// Facultad de Ciencias, UNAM, México D.F. //
// Teléfono 6 22-48-70 //
// E-mail: dinamica@athena.fciencias.unam.mx //
// //
// Propiedad intelectual, todos los derechos reservados //
// conforme a la ley, registro en trámite. //
// Revisión 1.1-A //
// //
//////////////////////////////////////////////////////////////
#include "integra.hpp"
#include "nucleo.hpp"
#include "selecc.hpp"
#include "combo_b.hpp"
#include "version.hpp"
#include "\libreria\gen_rep.hpp"
extern "C" {
#include <graphics.h>
#include <stdio.h>
#include <math.h>
#include <dir.h>
}
// Definicion externa del objeto Nucleo
extern Nucleo *NCO;
// Indica si el programa esta o no activo
extern int Programa_activo;
// Tecla actual del bufer
extern int Tecla;
// Caracter actual del bufer
extern char Caracter;
// Dimenciones de la pantalla
extern int X_MAX;
extern int Y_MAX;
// Indica el archivo que se mostrara de ayuda
extern char *ARCHIVO_AYUDA;
// Indica cual texto explicativo a visualizar
extern unsigned int N_texto_explicativo;
// Metodos de Intebgracion numerica
extern const char *Metodos_integracion[];
// Nombre de los parametros de los metodos numericos
extern const char *Parametros_metodos_integracion[];
// Graba la imagen en formato GIF
void GIF_DumpEga10(char *filename);
// Nombre del archivo temporal para la ultima orbita
static const char *ARCH_TEMPORAL = "TMPVENT.$$$";
static const char *ARCH_CONFIG_TEMP = "TEMP.CFG";
// Nombre del directorio que contiene la descripcion del proyecto y sistemas
static const char *ARCH_DESCRIP = "C:\\INTEGRA\\DESCRIP\\";
#ifdef _IDIOMA_ESPANOL_
// Menu de ayuda
const char *M_AYUDA_MENU[] = {
"Que es INTEGRA",
"Manejo de INTEGRA",
"Funciones Genéricas",
"Funciones Validas",
"Acerca de...",
"0"
};
const char *M_AYUDA_MENU_TEC = "QMFUA";
// Archivos de ayuda
const char *M_AYUDA_ARCHIVO[] = {
"C:\\INTEGRA\\SYS\\HELP\\INTEGRA.HLP",
"C:\\INTEGRA\\SYS\\HELP\\FINTEGRA.HLP",
"C:\\INTEGRA\\SYS\\HELP\\AYUDAG.HLP",
"C:\\INTEGRA\\SYS\\HELP\\FUNCIONE.HLP",
"C:\\INTEGRA\\SYS\\HELP\\ACERCADE.HLP",
};
// Menu de archivos
static const char *M_archivos[] = {
"Reporte Especificaciones",
"Graba Especificaciones",
"Lee Especificaciones",
"Restaura Especificaciones",
"Descripción Proyecto",
"Graba Pantalla (GIF)",
"Visualiza Archivo",
"Crea / Edita Archivo",
"Acerca de ...",
"Termina Programa",
"0"
};
#define OPC03 "GLORDPEVAT"
// Menu de sistemas
static const char *M_sistemas[] = {
"Biblioteca de Sistemas",
"Descripción del Sistema",
"Reporte Especificaciones",
"0"
};
#define OPC04 "SDVR"
// Menu de parametros
static const char *M_parametros[] = {
"Modifica Parámetros",
"Parámetros Originales",
"0"
};
#define OPC05 "PO"
// Menu del cursor (condiciones iniciales)
static const char *M_cursor[] = {
"Mover a ...",
"Mover al Origen",
"Paso del Cursor",
"Incremento del Paso",
"",
"0"
};
#define OPC06 "MOPIC"
// Menu de la pantalla de trabajo
static const char *M_ventana[] = {
"Dimensiones",
"Limpiar Sin Consv. Posc.",
"Limpiar Consv. Posc.",
"Grabar (IMG)",
"Leer (IMG)",
"", // Una o dos ventanas
"", // Grafica en una o en ambas ventanas simultaneamente
"", // Invierte ventanas
"0"
};
#define OPC07 "DSCGLVTI"
// Menu del metodo grafico
static const char *M_grafico[] = {
"Escenario Gráfico",
"Mover Origen",
"Graduar Ejes",
"Acercar / Alejar",
"Rotaciones",
"",
"Ceroclinas",
"Isoclinas",
"Funciones Auxiliares",
"Colores del Sistema",
"0"
};
#define OPC08 "EMHARNCIFO"
// Menu del campo vectorial
static const char *M_campo_vectorial[] = {
"Configurar",
"Dibujar",
"0"
};
#define OPC09 "CD"
// Metodos numericos
static const char *M_Numerico[] = {
"Configurar",
"0"
};
#define OPC10 "C"
///////////////////////////////////////////
// Revisar los elementos del menu
///////////////////////////////////////////
// Menu de la ventana de visualizacion
static const char *M_ventana_mouse[] = {
"Maximizar",
"Minimizar",
"Grabar (IMG)",
"Leer (IMG)",
"Limpiar",
"0"
};
#define OPC01 "XNGLI" // Opciones
#define MSG01 "Terminar el programa y retornar al DOS"
#define MSG02 "Visualiza la ayuda sobre el sistema"
#define MSG03 "Selecciona un sistema de la biblioteca de sistemas"
#define MSG04 "Cambia el valor de los parámetros del sistema actual"
#define MSG05 "Activa la proyección XY"
#define MSG06 "Cambia dimensión de la ventana de trabajo"
#define MSG07 "Configura el método numérico de integración"
#define MSG08 "Selecciona el escenario gráfico"
#define MSG09 "Dibuja el campo vectorial"
#define MSG10 "Selecciona las condiciones iniciales (Cursor)"
#define MSG11 "Integra en tiempo positivo"
#define MSG12 "Integra en tiempo negativo"
#define MSG13 "Limpia la ventana de trabajo"
#define MSG14 "Cambia la gráfica de puntos a líneas y viceversa"
#define TXT2 "Escriba:"
#define TXT3 "Donde N es (3) SVGA 1024x768 256 colores (*)"
#define TXT4 " (2) SVGA 800x600 256 colores (*)"
#define TXT5 " (1) SVGA 640x480 256 colores (*)"
#define TXT6 " (0) VGA 640x480 16 colores"
#define TXT7 " (*) Corra primero el programa HGXMOUSE.EXE"
#define TXT01 "Acciones sobre la ventana de trabajo"
#define TXT04 "Menú de archivos"
#define TXT05 "Menú de Sistemas"
#define TXT06 "Menú de Parámetros"
#define TXT07 "Menu de Cursor"
#define TXT08 "Ver Coordenadas"
#define TXT09 "No ver Coordenadas"
#define TXT10 "Menú de la ventana de trabajo"
#define TXT11 "Menú de escenarios gráficos"
#define TXT12 "Ejes con Nombre"
#define TXT13 "Ejes sin Nombre"
#define TXT14 "Menú del campo vectorial"
#define TXT15 "Menú de los métodos númericos"
#define TXT16 "Archivo Sistemas Param. Cursor Ventana Escenarios C. Vect. M. Numer."
#define TXT17 "%s = %3.5f Paso = %3.5f %s = %3.5f Paso = %3.5f %s = %3.5f Paso = %3.5f"
#define TXT17A "%s = %3.5f Paso = %3.5f %s = %3.5f Paso = %3.5f"
#define TXT18 "Visualizando la descripción del proyecto"
#define TXT19 "DESCRIPCION DEL PROYECTO"
#define TXT20 "Nombre del archivo para grabar la pantalla en formato GIF"
#define TXT21 "GRABA PANTALLA"
#define TXT22 "Seleccione el archivo a editar"
#define TXT23 "EDITOR"
#define TXT24 "Seleccione el archivo a visualizar"
#define TXT25 "VISUALIZADOR"
#define TXT26 "Visualizando la descripción del sistema"
#define TXT27 "Nombre del archivo para grabar las especificaciones"
#define TXT28 "Nombre del archivo para leer las especificaciones"
#define TXT29 "Reporte del estado del sistema"
#define TXT30 "Capture la condición inicial"
#define TXT31 "MOVER A ..."
#define TXT32 "Eje Horizontal"
#define TXT33 "Eje Vertical"
#define TXT34 "Tercer Eje"
#define TXT35 "Capture el paso del cursor"
#define TXT36 "PASO DEL CURSOR"
#define TXT37 "Capture el incremento del paso del cursor"
#define TXT38 "INCREMENTO DEL PASO"
#define TXT39 "Capture las dimensiones de la ventana de trabajo"
#define TXT40 "Seleccione el escenario a gráficar"
#define TXT41 "Utilice las flechas para mover el origen, Esc para terminar"
#define TXT42 "Utilice [+,-] para acercar / alejar, Esc para terminar"
#define TXT43 "Utilice las flechas para rotar, Esc para terminar"
#define TXT44 "Seleccione los colores a usar en el sistema"
#define TXT45 "Configure el campo vectorial"
#define TXT46 "Seleccione y configure el método númerico de integración"
#define TXT48 "GRABA IMAGEN"
#define TXT49 "LEE IMAGEN"
#define TXT50 "Escriba la expresión a gráficar"
#define TXT51 "Grabando la ventana de trabajo ..."
#define TXT52 "Leyendo la ventana de trabajo ..."
#define TXT60 "Se encontro el archivo de estado del proyecto"
#define TXT61 "ĘDesea trabajar con esa configuración?"
#define TXT70 "Capture el número de puntos a graficar por la función auxiliar"
#define TXT71 "CAPTURA PUNTOS A GRAFICAR"
#define TXT72 "NUMERO DE PUNTOS"
#define TXT73 "Gráficando isoclinas presione [ESC] para cancelar"
#define TXT80 "Editando el archivo de notas del proyecto"
#define TXT81 "ARCHIVO DE NOTAS"
#define TXT90 "CURSO TEMPORAL"
#define TXT100 "ĘDesea activar graba calculo númerico?"
#define TXT101 "ĘDesea desactivar graba calculo númerico?"
#else
#endif
////////////////////////////////////////////////////////////////////////
// Proceso inicial del sistena integra //
////////////////////////////////////////////////////////////////////////
void Integra::Proceso_inicial(void)
{
// Indica que las ventanas no han sido invertidas
Inversion_ventanas = 0;
// Define los iconos de Integra
Niconos = 12;
Iconos = new Icono [Niconos];
Iconos[0].Define_icono("SISTEMA.ICO",10,43);
Iconos[1].Define_icono("PARAMET.ICO",55,43);
Iconos[2].Define_icono("EJE_XY.ICO",100,43);
Iconos[3].Define_icono("PANTALL.ICO",145,43);
Iconos[4].Define_icono("MET_INT.ICO",190,43);
Iconos[5].Define_icono("EJE_GRF.ICO",235,43);
Iconos[6].Define_icono("CAM_VEC.ICO",280,43);
Iconos[7].Define_icono("CURSOR.ICO",325,43);
Iconos[8].Define_icono("INT_POS.ICO",400,43);
Iconos[9].Define_icono("INT_NEG.ICO",445,43);
Iconos[10].Define_icono("LIMPIA.ICO",520,43);
Iconos[11].Define_icono("PUN_LIN.ICO",565,43);
Coordenadas = new char[200];
Texto_explicativo = new char *[16];
Texto_explicativo[0] = "";
Texto_explicativo[1] = MSG01;
Texto_explicativo[2] = MSG02;
Texto_explicativo[3] = MSG03;
Texto_explicativo[4] = MSG04;
Texto_explicativo[5] = MSG05;
Texto_explicativo[6] = MSG06;
Texto_explicativo[7] = MSG07;
Texto_explicativo[8] = MSG08;
Texto_explicativo[9] = MSG09;
Texto_explicativo[10] = MSG10;
Texto_explicativo[11] = MSG11;
Texto_explicativo[12] = MSG12;
Texto_explicativo[13] = MSG13;
Texto_explicativo[14] = MSG14;
Ipresionado = 0;
v_coord = 1;
// Inicializa las variables del sistema
Inicializa_variables();
Doble_ventana = 1; // Dos ventanas visibles
Estado_ventana = 2; // Ventana minimizadas
Ventana_activa = 0; // Primera ventana
Graficar_dos_ventanas = 4; // Grafica simultaneamente en las dos ventanas
// (1) Ventana uno solamente
// (2) Ventana dos solamente
// (3) Solo en la ventana activa
// (4) Simultaneamente en ambas ventanas
// Inicializa la clase de la ventana de graficacion
VT1 = new Ctrl_ventana_grafica;
VT1->Inicializa(Doble_ventana,Nombre_sistema[Sistema_actual],TXT90);
// Indica que la ventana principal no esta activa
Vt->Ventana_activa(NO);
// Dibuja la pantalla de trabajo
Dibuja_aplicacion();
// Carga la configuracion de la ventana de trabajo para cada sistema
for(unsigned int i = 0; i < Numero_sistemas; i++) {
VT1->VT1->Fija_dimenciones(Dim_maxima[0][i],Dim_minima[0][i]);
VT1->VT1->Retorna_configuracion(Escala[0][i],Centro[0][i],Angulos[0][i][0],Angulos[0][i][1]);
VT1->VT2->Fija_dimenciones(Dim_maxima[1][i],Dim_minima[1][i]);
VT1->VT2->Retorna_configuracion(Escala[1][i],Centro[1][i],Angulos[1][i][0],Angulos[1][i][1]);
}
// Graba la configuracion original del proyecto
Graba_estado(0,ARCH_CONFIG_TEMP);
// Lee el archivo de configuracion si existe
char arch[MAXPATH];
Manipulador_archivos ma;
ma.Cambia_ext_path(Proyecto,"CFG",arch);
if(n_archivos_directorios(arch,FA_ARCH)) {
if(NCO->Opcion(TXT60,TXT61) == 1) Lee_estado(arch,0);
}
// Actualiza los valores del la ventana al sistema actual
VT1->VT1->Fija_dimenciones(Dim_maxima[0][Sistema_actual],Dim_minima[0][Sistema_actual]);
VT1->VT1->Fija_configuracion(Escala[0][Sistema_actual],Centro[0][Sistema_actual],Angulos[0][Sistema_actual][0],Angulos[0][Sistema_actual][1]);
VT1->VT2->Fija_dimenciones(Dim_maxima[1][Sistema_actual],Dim_minima[1][Sistema_actual]);
VT1->VT2->Fija_configuracion(Escala[1][Sistema_actual],Centro[1][Sistema_actual],Angulos[1][Sistema_actual][0],Angulos[1][Sistema_actual][1]);
Dibuja_ventana_trabajo();
// Inicializa el reporte de integracion numerica
Rep_num = new Ctrl_reporte;
Rep_num->Parametros(0,66,300,REPORTE_GRABADO,LPT1,"REPINT.REP");
}
////////////////////////////////////////////////////////////////////////
// Proceso final de integra //
////////////////////////////////////////////////////////////////////////
void Integra::Proceso_final(void)
{
delete Rep_num;
unlink(ARCH_CONFIG_TEMP);
VT1->Destruye();
delete VT1;
delete []Iconos;
delete []Coordenadas;
}
////////////////////////////////////////////////////////////////////////
// Controlador del sistema integra //
////////////////////////////////////////////////////////////////////////
void Integra::Controlador()
{
// Revisa las acciones sobre la ventana de trabajo
selec = VT1->VT1->Itera();
// Cambia el tamano de la ventana de trabajo
if(selec == 1) Control_acciones(2000);
if(selec == 2) Control_acciones(2001);
// Checa procesos si esta activa la segunda ventana
if(VT1->Estado_ventana_doble()) {
// Activa a la segunda ventana y desactiva la primera (pero siguen visibles las dos)
if(VT1->VT2->Presionado(BR)) {
Ventana_activa = 1;
P_a = 1;
Guarda_posicion = NO;
v_coord = SI;
VT1->Fija_ventana_activa(1);
Actualiza_coordenadas();
}
selec = VT1->VT2->Itera();
// Cambia el tamano de la ventana de trabajo
if(selec == 1) {
Invierte_ventanas();
Inversion_ventanas = 1;
Control_acciones(2000);
}
// Activa el menu de la ventana numero 2
if(VT1->VT2->Presionado(BL)) {
if(Ventana_activa == 1) {
Visualiza_texto(TXT01);
vent.y = NCO->Retorna_estado_mouse().y;
vent.x = NCO->Retorna_estado_mouse().x;
if(Opcion_menu(M_ventana_mouse,OPC01,selec,vent)) Control_acciones(1999+selec);
}
}
}
// Activa el menu de la ventana numero 1
if(VT1->VT1->Presionado(BL)) {
if(Ventana_activa == 0) {
Visualiza_texto(TXT01);
vent.y = NCO->Retorna_estado_mouse().y;
vent.x = NCO->Retorna_estado_mouse().x;
if(Opcion_menu(M_ventana_mouse,OPC01,selec,vent)) Control_acciones(1999+selec);
}
}
// Activa a la primera ventana y desactiva la segunda (pero siguen visibles las dos)
if(VT1->VT1->Presionado(BR)) {
Ventana_activa = 0;
P_a = 0;
Guarda_posicion = NO;
v_coord = SI;
VT1->Fija_ventana_activa(0);
Actualiza_coordenadas();
}
// Revisa el comportamiento de los iconos del sistema
for(int i = 0; i < Niconos; i++) {
// Revisa si algun icono fue presionado
if(Iconos[i].Oprimido()) Ipresionado = i + 1;
// Revisa sobre que icono esta el mouse
if(Iconos[i].Mouse_dentro()) N_texto_explicativo = i + 3;
}
// Activacion del menu
if(Vt->Presionado(BR)) {
vent.y = NCO->Retorna_estado_mouse().y;
vent.x = NCO->Retorna_estado_mouse().x;
if(vent.y > 26 && vent.y < 40) {
delay(200);
if(vent.x > 10 && vent.x < 65 ) Tecla = ALT_A;
if(vent.x > 80 && vent.x < 145) Tecla = ALT_S;
if(vent.x > 160 && vent.x < 205) Tecla = ALT_P;
if(vent.x > 225 && vent.x < 273) Tecla = ALT_C;
if(vent.x > 288 && vent.x < 355) Tecla = ALT_T;
if(vent.x > 369 && vent.x < 450) Tecla = ALT_E;
if(vent.x > 465 && vent.x < 530) Tecla = ALT_V;
if(vent.x > 545 && vent.x < 615) Tecla = ALT_N;
}
}
// Controla los procesos seleccionador por los iconos
switch(Ipresionado) {
case 1: // Selecciona el sistema actual
Control_acciones(200);
break;
case 2: // Parametros del sistema
Control_acciones(300);
break;
case 3: // Selecciona proyeccion XY
// if(Ventana_activa) {
// Escenario[1][Sistema_actual].z = 0;
// VT1->VT2->Fija_dimenciones(Dim_maxima[1][Sistema_actual],Dim_minima[1][Sistema_actual]);
// } else {
// Escenario[0][Sistema_actual].z = 0;
// VT1->VT1->Fija_dimenciones(Dim_maxima[0][Sistema_actual],Dim_minima[0][Sistema_actual]);
// }
Escenario[Ventana_activa][Sistema_actual].z = 0;
Dibuja_ventana_trabajo();
VT1->Borra_archivo_ventana();
break;
case 4: // Cambia los parametros de la pantalla
Control_acciones(600);
break;
case 5: // Menu de metodos numericos
Control_acciones(1000);
break;
case 6: // Menu de graficos
Control_acciones(700);
break;
case 7: // Campo vectorial
Control_acciones(801);
break;
case 8: // Cursor
Control_acciones(500);
break;
case 9: // Integra en tiempo positivo
Caracter = 'F';
break;
case 10: // Integra en tiempo negativo
Caracter = 'B';
break;
case 11: // Limpia la ventana de trabajo
Aplicacion::Dibuja();
Redibuja_pantalla();
break;
case 12: // Cambia la grafica de puntos a lineas y viseversa
Caracter = 'P';
break;
}
Ipresionado = 0;
// Controla las tareas que utilizan solo un caracter para activar
switch(Caracter) {
///////////////////////////////////////////////////
// Estas teclas son de uso temporal
// if(Ventana_activa) VT1->VT2->Fija_tipo_ventana(!VT1->VT2->Retorna_tipo_ventana());
// else VT1->VT1->Fija_tipo_ventana(!VT1->VT1->Retorna_tipo_ventana());
// break;
// case 'o': // Visualiza en coordenadas polares
// case 'O':
// Coord_rectangulares = Coord_rectangulares ? 0 : 1;
///////////////////////////////////////////////////
case 'a':
case 'A':
if(NCO->Opcion(TXT100) == 1) Reporte_activo = 1; // Acvtiva la grabacion del reporte de integracion numerica
break;
case 'd':
case 'D':
if(NCO->Opcion(TXT101) == 1) Reporte_activo = 0; // Desactiva la grabacion del reporte de integracion numerica
break;
case 'c': // Limpia la ventana de trabajo
case 'C':
Control_acciones(2004);
break;
case 'p': // Grafica con punto o lineas
case 'P':
if(Grafica_puntos[Sistema_actual]) Grafica_puntos[Sistema_actual] = 0;
else Grafica_puntos[Sistema_actual] = 1;
break;
case 'f': // Integra en tiempo positivo
case 'F':
VT1->Visualiza_cursor(NO);
// Graba untima orbita de la ventana
if(!Guarda_posicion) VT1->Graba_archivo_ventana();
Visualiza_texto("");
Integra_numericamente(1);
Guarda_posicion = SI;
// Visualiza el cursor
VT1->Visualiza_cursor(SI);
break;
case 'b': // Integra en tiempo negativo
case 'B':
VT1->Visualiza_cursor(NO);
// Graba untima orbita de la ventana
if(!Guarda_posicion) VT1->Graba_archivo_ventana();
Visualiza_texto("");
Integra_numericamente(0);
Guarda_posicion = SI;
// Visualiza el cursor
VT1->Visualiza_cursor(SI);
break;
case 'l':
case 'L':
VT1->Visualiza_cursor(NO);
VT1->Lee_archivo_ventana();
Guarda_posicion = NO;
break;
case '+': // Incrementa el paso en el cursor
Controla_cursor(1);
v_coord = SI;
break;
case '-': // Decrementa el paso del cursor
Controla_cursor(2);
v_coord = SI;
break;
}
Numero_funcion = 0;
// Controla las tareas usando mas de una tecla para activar
switch(Tecla) {
case FLECHA_DERECHA: // Mueve el cursor positivamente en el eje X
case FLECHA_IZQUIERDA: // Mueve el cursor negativamente en el eje X
case FLECHA_ARRIBA: // Mueve el cursor positivamente en el eje Y
case FLECHA_ABAJO: // Mueve el cursor negativamente en el eje Y
case PGDN: // Mueve el cursor positivamente en el eje Z
case PGUP: // Mueve el cursor negativamente en el eje Z
Controla_cursor(Tecla);
v_coord = SI;
Guarda_posicion = NO;
break;
case CTRL_F1: // Graficacion de funciones definidas por la interfaz
Numero_funcion = 1;
break;
case CTRL_F2:
Numero_funcion = 2;
break;
case CTRL_F3:
Numero_funcion = 3;
break;
case CTRL_F4:
Numero_funcion = 4;
break;
case CTRL_F5:
Numero_funcion = 5;
break;
case CTRL_F6:
Numero_funcion = 6;
break;
case CTRL_F7:
Numero_funcion = 7;
break;
case CTRL_F8:
Numero_funcion = 8;
break;
case CTRL_F9:
Numero_funcion = 9;
break;
case CTRL_F10: // Funciones a graficar
Control_acciones(708);
break;
case ALT_F10: // Fija el numero de puntos para graficar las funciones auxiliares
Control_acciones(710);
break;
case ALT_F9: // Grafica ceroclinas
Control_acciones(706);
break;
case CTRL_N_O: // Editor del archivo de notas
{
char xarch[MAXPATH];
Manipulador_archivos ma;
sprintf(xarch,"C:\\INTEGRA\\EXES\\%s",Proyecto);
ma.Cambia_ext_path(xarch,"NOT");
Visualiza_texto(TXT80);
V_E_archivo(xarch,TXT81,EDITA,0);
}
break;
case ALT_A: // Menu de archivos
vent.x = 10,vent.y = 40;
Visualiza_texto(TXT04);
if(Opcion_menu(M_archivos,OPC03,selec,vent)) Control_acciones(99+selec);
break;
case ALT_S: // Menu de sistemas
Visualiza_texto(TXT05);
vent.x = 80,vent.y = 40;
if(Opcion_menu(M_sistemas,OPC04,selec,vent)) Control_acciones(199+selec);
break;
case ALT_P: // Menu de parametros
Visualiza_texto(TXT06);
vent.x = 160,vent.y = 40;
if(Opcion_menu(M_parametros,OPC05,selec,vent)) Control_acciones(299+selec);
break;
case ALT_C: // Menu del cursor
Visualiza_texto(TXT07);
vent.x = 225,vent.y = 40;
if(!Visualiza_coordenadas_sistema) M_cursor[4] = TXT08;
else M_cursor[4] = TXT09;
if(Opcion_menu(M_cursor,OPC06,selec,vent)) Control_acciones(499+selec);
break;
case ALT_T: // Menu de la ventana de trabajo
Visualiza_texto(TXT10);
vent.x = 288,vent.y = 40;
// Cambia los elementos del menu
M_ventana[6] = "0";
if(Doble_ventana) {
M_ventana[5] = "Una Ventana";
if(Graficar_dos_ventanas == 4) M_ventana[6] = "Gráfica en Una Ventana";
else M_ventana[6] = "Gráfica en Ambas Ventanas";
M_ventana[7] = "Invierte Ventanas";
} else M_ventana[5] = "Dos Ventanas";
if(Opcion_menu(M_ventana,OPC07,selec,vent)) Control_acciones(599+selec);
break;
case ALT_E: // Menu del escenario grafico
Visualiza_texto(TXT11);
vent.x = 369,vent.y = 40;
if(!VT1->Retorna_Visualiza_nombre_eje()) M_grafico[5] = TXT12;
else M_grafico[5] = TXT13;
if(Opcion_menu(M_grafico,OPC08,selec,vent,"G")) Control_acciones(699+selec);
break;
case ALT_V: // Menu del Campo vectorial
Visualiza_texto(TXT14);
vent.x = 465,vent.y = 40;
if(Opcion_menu(M_campo_vectorial,OPC09,selec,vent)) Control_acciones(799+selec);
break;
case ALT_N: // Menu de los metodos numericos
Visualiza_texto(TXT15);
vent.x = 545,vent.y = 40;
if(Opcion_menu(M_Numerico,OPC10,selec,vent)) Control_acciones(999+selec);
break;
case CTRL_C: // Limpia pantalla conservando la actual posición
Control_acciones(602);
break;
case CTRL_G: // Graba el contenido de la ventana de graficacion
Control_acciones(2100);
break;
case CTRL_L: // Lee el contenido de una ventana de graficacion
Control_acciones(2101);
break;
case CTRL_W: // Graba estado del proyecto
Control_acciones(100);
break;
case CTRL_R: // Lee estado del proyecto
Control_acciones(101);
break;
}
// Visualiza las coordenadas del sistema
if(v_coord || !N_texto_explicativo) Visualiza_coordenadas();
// Controla la visualizacion de las funciones auxiliares a graficar
if(Numero_funcion) {
if(Numero_funcion <= Numero_funciones_auxiliares[Sistema_actual]) {
// Oculta el cursor
VT1->Visualiza_cursor(NO);
Visualiza_texto("");
C_3D max, min;
// valores maximos y minimos de los ejes coordenados
if(Ventana_activa) VT1->VT2->Retorna_dimenciones_maximas(max,min);
else VT1->VT1->Retorna_dimenciones_maximas(max,min);
Grafica_funcion(Funciones_auxiliares[Sistema_actual][Numero_funcion-1], max, min);
// Muestra el cursor
VT1->Visualiza_cursor(SI);
}
}
/*
///////////////////////////////////
// Usada para seber posicion de raton.
///////////////////////////////////
if(Vt->Presionado(BR)) {
vent.y = NCO->Retorna_estado_mouse().y;
vent.x = NCO->Retorna_estado_mouse().x;
sprintf(Coordenadas,"X = %d Y = %d",vent.x,vent.y);
Visualiza_texto(Coordenadas);
}
*/
}
////////////////////////////////////////////////////////////////////////
// Pantalla de presentacion //
////////////////////////////////////////////////////////////////////////
void Integra::Pantalla_presentacion(void)
{
Visualiza_texto("Acerca de ...");
Ventana_iconos *Vpresent = new Ventana_iconos;
Vpresent->Activa_graba_ventana(1);
Vpresent->Ventana_centrada(VER_INTEGRA,480,300,0);
Vpresent->Dibuja();
Vpresent->Define_color_texto(Negro);
Vpresent->Limpia_recuadro(20,50,460,130,Gris1,Blanco,Gris9);
Vpresent->Define_tipo_letra(1,0,4,4,4,4);
Vpresent->Centra_texto(60,"SISTEMA INTEGRA");
Vpresent->Define_color_texto(Azul9);
Vpresent->Define_tipo_letra(0,0,-1,0,0,0);
Vpresent->Centra_texto(110,"ANALIZADOR DE SISTEMAS DINAMICOS");
Vpresent->Define_color_texto(Negro);
Vpresent->Centra_texto(140,VERSION);
Vpresent->Define_tipo_letra(2,0,-2,0,0,0);
Vpresent->Define_color_texto(Rojo1);
Vpresent->Centra_texto(155,FECHA_VERSION);
Vpresent->Define_tipo_letra(0,0,-1,0,0,0);
Vpresent->Define_color_texto(Negro);
Vpresent->Centra_texto(190,"Autores:");
Vpresent->Centra_texto(206,"Humberto Carrillo, Antonio Carrillo y Luis Nava");
Vpresent->Centra_texto(240,"Laboratorio de Dinámica no Lineal");
Vpresent->Centra_texto(250,"Facultad de Ciencias");
Vpresent->Centra_texto(260,"Universidad Nacional Autónoma de México");
Vpresent->Define_color_texto(Rojo1);
Vpresent->Centra_texto(280,REGISTRO);
while(!Vpresent->Itera() && Programa_activo && Tecla != ENTER && Tecla != ESC) NCO->Administrador();
delete Vpresent;
// Mensaje del sistema
NCO->Mensaje("ANALIZADOR DE SISTEMAS DINAMICOS",VERSION,"","Esta es una versión de prueba");
}
////////////////////////////////////////////////////////////////////////
// Pantalla de terminacion //
////////////////////////////////////////////////////////////////////////
void Integra::Pantalla_terminacion(void)
{
// Mensaje del sistema
NCO->Mensaje("Cualquier error o comentario","inicarlo por favor a:","","acl@hp.fciencias.unam.mx");
}
////////////////////////////////////////////////////////////////////////
// Dibuja la pantalla de trabajo //
////////////////////////////////////////////////////////////////////////
void Integra::Dibuja_aplicacion(void)
{
// Dibuja el area del menu vertical
Vt->Limpia_recuadro(1,25,X_MAX-1,39,Gris1,Gris9,Blanco);
Vt->Define_color_texto(Blanco);
Vt->Visualiza_texto(11,30,TXT16);
Vt->Define_color_texto(Negro);
Vt->Visualiza_texto(10,29,TXT16);
// Dibuja la area de iconos
Vt->Limpia_recuadro(1,40,X_MAX-1,82,Gris1,Gris9,Blanco);
// Dibuja a los iconos
for(i = 0; i < Niconos; i++) Iconos[i].Dibuja();
// Dibuja la ventana de graficacion
Dibuja_ventana_trabajo();
}
////////////////////////////////////////////////////////////////////////
// Visualiza coordenadas dentro de la ventana de trabajo //
////////////////////////////////////////////////////////////////////////
void Integra::Visualiza_coordenadas(void)
{
if(v_coord) {
if(Visualiza_coordenadas_sistema) {
aux[0] = 0;
if(Ventana_activa) {
aux[0] = 0;
for(i = 0; i < Numero_ecuaciones[Sistema_actual]; i++) aux[i+1] = Ac_Condicion[1][Sistema_actual][i];
aux[i+1] = Ac_Tiempo[1][Sistema_actual];
aux1.x = aux[Escenario[1][Sistema_actual].x];
aux1.y = aux[Escenario[1][Sistema_actual].y];
aux1.z = aux[Escenario[1][Sistema_actual].z];
} else {
aux[0] = 0;
for(i = 0; i < Numero_ecuaciones[Sistema_actual]; i++) aux[i+1] = Ac_Condicion[0][Sistema_actual][i];
aux[i+1] = Ac_Tiempo[0][Sistema_actual];
aux1.x = aux[Escenario[0][Sistema_actual].x];
aux1.y = aux[Escenario[0][Sistema_actual].y];
aux1.z = aux[Escenario[0][Sistema_actual].z];
}
// Cambia dependiendo del escenario ver que se visualizara
char xcad1[20], xcad2[20], xcad3[20];
Nombre_ecuacion_sistema_actual(Sistema_actual,Escenario[Ventana_activa][Sistema_actual].x-1,xcad1);
Nombre_ecuacion_sistema_actual(Sistema_actual,Escenario[Ventana_activa][Sistema_actual].y-1,xcad2);
Nombre_ecuacion_sistema_actual(Sistema_actual,Escenario[Ventana_activa][Sistema_actual].z-1,xcad3);
if(Escenario[Ventana_activa][Sistema_actual].z) sprintf(Coordenadas,TXT17,xcad1,aux1.x,Paso_cursor[Ventana_activa][Sistema_actual].x,xcad2,aux1.y,Paso_cursor[Ventana_activa][Sistema_actual].x,xcad3,aux1.z,Paso_cursor[Ventana_activa][Sistema_actual].z);
else sprintf(Coordenadas,TXT17A,xcad1,aux1.x,Paso_cursor[Ventana_activa][Sistema_actual].x,xcad2,aux1.y,Paso_cursor[Ventana_activa][Sistema_actual].y);
Texto_explicativo[15] = Coordenadas;
} else Texto_explicativo[15] = " ";
NCO->Visualiza_texto(Texto_explicativo[15]);
}
N_texto_explicativo = 15;
v_coord = 0;
}
///////////////////////////////////////////////////////////////////
// Control de acciones dentro del integra //
///////////////////////////////////////////////////////////////////
void Integra::Control_acciones(const unsigned int tp)
{
t_ceroclina = 1; // Indica que grafique isoclina
switch(tp) {
case 100: // Imprime estado del proyecto
Visualiza_texto(TXT29);
Imprime_estado(0,0);
break;
case 101: // Graba estado del proyecto
Visualiza_texto(TXT27);
VT1->VT1->Retorna_configuracion(Escala[0][Sistema_actual],Centro[0][Sistema_actual],Angulos[0][Sistema_actual][0],Angulos[0][Sistema_actual][1]);
VT1->VT2->Retorna_configuracion(Escala[1][Sistema_actual],Centro[1][Sistema_actual],Angulos[1][Sistema_actual][0],Angulos[1][Sistema_actual][1]);
Graba_estado(1,"");
break;
case 102: // Lee estado del proyecto
Visualiza_texto(TXT28);
if(Lee_estado("",1)) {
VT1->VT1->Fija_dimenciones(Dim_maxima[0][Sistema_actual],Dim_minima[0][Sistema_actual]);
VT1->VT1->Fija_configuracion(Escala[0][Sistema_actual],Centro[0][Sistema_actual],Angulos[0][Sistema_actual][0],Angulos[0][Sistema_actual][1]);
VT1->VT2->Fija_dimenciones(Dim_maxima[1][Sistema_actual],Dim_minima[1][Sistema_actual]);
VT1->VT2->Fija_configuracion(Escala[1][Sistema_actual],Centro[1][Sistema_actual],Angulos[1][Sistema_actual][0],Angulos[1][Sistema_actual][1]);
Dibuja_ventana_trabajo();
}
break;
case 103: // Restaura estado del proyecto
Visualiza_texto(TXT28);
if(Lee_estado(ARCH_CONFIG_TEMP,0)) {
VT1->VT1->Fija_dimenciones(Dim_maxima[0][Sistema_actual],Dim_minima[0][Sistema_actual]);
VT1->VT1->Fija_configuracion(Escala[0][Sistema_actual],Centro[0][Sistema_actual],Angulos[0][Sistema_actual][0],Angulos[0][Sistema_actual][1]);
VT1->VT2->Fija_dimenciones(Dim_maxima[1][Sistema_actual],Dim_minima[1][Sistema_actual]);
VT1->VT2->Fija_configuracion(Escala[1][Sistema_actual],Centro[1][Sistema_actual],Angulos[1][Sistema_actual][0],Angulos[1][Sistema_actual][1]);
Dibuja_ventana_trabajo();
}
break;
case 104: // Visualiza la descripcion del proyecto
Visualiza_texto(TXT18);
sprintf(cad,"%s%s0",ARCH_DESCRIP,Proyecto);
V_E_archivo(cad,TXT19,VISUALIZA,0);
break;
case 105: // Graba pantalla en formato GIF
Visualiza_texto(TXT20);
if(Retorna_archivo_seleccionado(cad,0,TXT21,"GIF","*.GIF")) GIF_DumpEga10(cad);
break;
case 106: // Visualiza Archivo
Visualiza_texto(TXT24);
V_E_archivo("*.TXT",TXT25,VISUALIZA,1);
break;
case 107: // Edita Archivo
Visualiza_texto(TXT21);
V_E_archivo("*.TXT",TXT23,EDITA,1);
break;
case 108: // Pantalla de presentacion
Pantalla_presentacion();
break;
case 109: // Termina el programa
NCO->Almacena_bufer_teclado(ALT_X);
break;
case 200: // Selecciona sistema
Control_acciones(2001);
VT1->VT1->Retorna_configuracion(Escala[0][Sistema_actual],Centro[0][Sistema_actual],Angulos[0][Sistema_actual][0],Angulos[0][Sistema_actual][1]);
VT1->VT2->Retorna_configuracion(Escala[1][Sistema_actual],Centro[1][Sistema_actual],Angulos[1][Sistema_actual][0],Angulos[1][Sistema_actual][1]);
if(Selecciona_sistema() == 1) {
VT1->VT1->Fija_dimenciones(Dim_maxima[0][Sistema_actual],Dim_minima[0][Sistema_actual]);
VT1->VT1->Fija_configuracion(Escala[0][Sistema_actual],Centro[0][Sistema_actual],Angulos[0][Sistema_actual][0],Angulos[0][Sistema_actual][1]);
VT1->VT2->Fija_dimenciones(Dim_maxima[1][Sistema_actual],Dim_minima[1][Sistema_actual]);
VT1->VT2->Fija_configuracion(Escala[1][Sistema_actual],Centro[1][Sistema_actual],Angulos[1][Sistema_actual][0],Angulos[1][Sistema_actual][1]);
Dibuja_ventana_trabajo();
// Borra archivo de ultima orbita
VT1->Borra_archivo_ventana();
}
break;
case 201: // Descripcion del sistema
{
Visualiza_texto(TXT26);
sprintf(cad,"%s%s%u",ARCH_DESCRIP,Proyecto,Sistema_actual+1);
V_E_archivo(cad,Nombre_sistema[Sistema_actual],VISUALIZA,0);
}
break;
case 202: // Reporte del estado del sistema
Visualiza_texto(TXT29);
Imprime_estado(1,0);
break;
case 300: // Parametros del sistema
Cambia_parametros_sistema();
break;
case 301: // Parametros originales del sistema actual
M_Definicion_usuario::Parametros(Sistema_actual,Ventana_activa);
break;
case 500: // Mover a ...
Visualiza_texto(TXT30);
Cambia_Condicion_inicial();
Actualiza_coordenadas();
Guarda_posicion = NO;
v_coord = SI;
break;
case 501: // Al Origen
for(i = 0; i < Numero_ecuaciones[Sistema_actual]; i++) Ac_Condicion[Ventana_activa][Sistema_actual][i] = 0.0;
Ac_Tiempo[Ventana_activa][Sistema_actual] = 0.0;
Actualiza_coordenadas();
Guarda_posicion = NO;
v_coord = SI;
break;
case 502: // Paso del cursor
Visualiza_texto(TXT35);
if(Captura_cadenas(TXT36,TXT32,Paso_cursor[Ventana_activa][Sistema_actual].x,TXT33,Paso_cursor[Ventana_activa][Sistema_actual].y,TXT34,Paso_cursor[Ventana_activa][Sistema_actual].z,1) == 1) {
if(Paso_cursor[Ventana_activa][Sistema_actual].x <= 0.0) Paso_cursor[Ventana_activa][Sistema_actual].x = 0.01;
if(Paso_cursor[Ventana_activa][Sistema_actual].y <= 0.0) Paso_cursor[Ventana_activa][Sistema_actual].y = 0.01;
if(Paso_cursor[Ventana_activa][Sistema_actual].z <= 0.0) Paso_cursor[Ventana_activa][Sistema_actual].z = 0.01;
v_coord = SI;
}
break;
case 503: // Incremento del paso del cursor
Visualiza_texto(TXT37);
if(Captura_cadenas(TXT38,TXT32,Incremento_paso[Ventana_activa][Sistema_actual].x,TXT33,Incremento_paso[Ventana_activa][Sistema_actual].y,TXT34,Incremento_paso[Ventana_activa][Sistema_actual].z,1) == 1) {
if(Incremento_paso[Ventana_activa][Sistema_actual].x <= 0.0) Incremento_paso[Ventana_activa][Sistema_actual].x = 0.01;
if(Incremento_paso[Ventana_activa][Sistema_actual].y <= 0.0) Incremento_paso[Ventana_activa][Sistema_actual].y = 0.01;
if(Incremento_paso[Ventana_activa][Sistema_actual].z <= 0.0) Incremento_paso[Ventana_activa][Sistema_actual].z = 0.01;
v_coord = SI;
}
break;
case 504: // Visualiza coordenadas
if(Visualiza_coordenadas_sistema) Visualiza_coordenadas_sistema = NO;
else Visualiza_coordenadas_sistema = SI;
v_coord = SI;
break;
case 600: // Dimenciones de los ejes coordenados de la ventana de trabajo
Visualiza_texto(TXT39);
if(Cambia_dimenciones_pantalla(Ventana_activa) == 1) {
VT1->VT1->Fija_dimenciones(Dim_maxima[0][Sistema_actual],Dim_minima[0][Sistema_actual]);
VT1->VT1->Retorna_configuracion(Escala[0][Sistema_actual],Centro[0][Sistema_actual],Angulos[0][Sistema_actual][0],Angulos[0][Sistema_actual][1]);
VT1->VT2->Fija_dimenciones(Dim_maxima[1][Sistema_actual],Dim_minima[1][Sistema_actual]);
VT1->VT2->Retorna_configuracion(Escala[1][Sistema_actual],Centro[1][Sistema_actual],Angulos[1][Sistema_actual][0],Angulos[1][Sistema_actual][1]);
Dibuja_ventana_trabajo();
}
break;
case 601: // Limpia pantalla sin conservar la actual posición
Control_acciones(2004);
break;
case 602: // Limpia pantalla conservando la actual posición
Control_acciones(2004);
Guarda_posicion = SI;
break;
case 603: // Graba imagen formato propio
Control_acciones(2002);
break;
case 604: // Lee imagen formato propio
Control_acciones(2003);
break;
case 605: // Activa una o dos ventanas
Doble_ventana = !Doble_ventana;
if(Doble_ventana) Control_acciones(2001);
else Control_acciones(2000);
break;
case 606: // Indica que grafique las orbitas en una o ambas ventanas de graficacion
VT1->Visualiza_cursor(NO);
Graficar_dos_ventanas = Graficar_dos_ventanas == 3 ? 4: 3;
if(Graficar_dos_ventanas == 4) {
for(i = 0; i < Numero_ecuaciones[Sistema_actual]; i++) Ac_Condicion[!Ventana_activa][Sistema_actual][i] = Ac_Condicion[Ventana_activa][Sistema_actual][i];
Ac_Tiempo[!Ventana_activa][Sistema_actual] = Ac_Tiempo[Ventana_activa][Sistema_actual];
v_coord = SI;
Guarda_posicion = NO;
}
Actualiza_coordenadas();
VT1->Visualiza_cursor(SI);
break;
case 607: // Invierte ventanas
if(Doble_ventana) {
Invierte_ventanas();
Estado_ventana = 3;
Control_acciones(2001);
}
break;
case 700: // Escenarios y curvas
Visualiza_texto(TXT40);
if(Escenarios(Ventana_activa) == 1) {
Dibuja_ventana_trabajo();
VT1->Borra_archivo_ventana();
}
break;
case 701: // Mover el origen
if(VT1->Retorna_tipo_ventana()) {
Visualiza_texto(TXT41);
Control_acciones(2004);
while(Tecla != ESC && Programa_activo) {
NCO->Administrador();
if(Tecla == -1) continue;
VT1->Mover_origen(Tecla);
}
}
break;
case 702: // Graduar ejes coordenados
// VT1->VT1->Gradua_ejes();
break;
case 703: // Acercar / alejar ejes
Visualiza_texto(TXT42);
Control_acciones(2004);
while(Tecla != ESC && Programa_activo) {
NCO->Administrador();
if(Tecla == -1) continue;
VT1->Acercar_alejar(Caracter);
}
break;
case 704: // Rotaciones
if(!VT1->Retorna_proyeccion_actual()) {
Visualiza_texto(TXT43);
Control_acciones(2004);
while(Tecla != ESC && Programa_activo) {
NCO->Administrador();
if(Tecla == -1) continue;
VT1->Rota_ejes(Tecla);
}
}
break;
case 705: // Visualiza nombre de ejes
VT1->Fija_Visualiza_nombre_eje();
Control_acciones(2004);
break;
case 706: // Ceroclinas
t_ceroclina = 0;
case 707: // Isoclinas
Visualiza_texto(TXT73);
VT1->Graba_archivo_ventana();
{
C_3D max, min;
// valores maximos y minimos de los ejes coordenados
if(Ventana_activa) VT1->VT2->Retorna_dimenciones_maximas(max,min);
else VT1->VT1->Retorna_dimenciones_maximas(max,min);
// Llama al controlador de funciones auxiliares
M_Definicion_usuario::Grafica_ceroclinas(t_ceroclina,0,max,min);
}
// Muestra el cursor
VT1->Visualiza_cursor(SI);
break;
case 708: // Funciones a graficar
// Oculta el cursor
VT1->Visualiza_cursor(NO);
Visualiza_texto(TXT50);
// Llama al controlador de funciones auxiliares
M_Definicion_usuario::Captura_funcion_auxiliar();
{
C_3D max, min;
// valores maximos y minimos de los ejes coordenados
if(Ventana_activa) VT1->VT2->Retorna_dimenciones_maximas(max,min);
else VT1->VT1->Retorna_dimenciones_maximas(max,min);
Grafica_funcion(Cadena_graficar, max, min);
}
// Muestra el cursor
VT1->Visualiza_cursor(SI);
break;
case 709: // Cambia los colores de ejes coordenados y graficos generados
Visualiza_texto(TXT44);
Selecciona_colores();
VT1->VT1->Revisualiza_ejes();
if(Ventana_activa) VT1->VT2->Revisualiza_ejes();
break;
case 710: // Fija el numero de puntos para graficar las funciones auxiliares
Visualiza_texto(TXT70);
if(Captura_cadena(TXT71,TXT72,NUMERO_PUNTOS,0) == 1) {
if(NUMERO_PUNTOS <= 10.0) NUMERO_PUNTOS = 10.0;
}
break;
case 800: // Configura el campo vectoria
Visualiza_texto(TXT45);
Configura_campo_vectorial();
break;
case 801: // Dibuja el campo vectorial
VT1->Visualiza_cursor(NO);
{
C_3D max,min;
// valores maximos y minimos de los ejes coordenados
if(Ventana_activa) VT1->VT2->Retorna_dimenciones_maximas(max,min);
else VT1->VT1->Retorna_dimenciones_maximas(max,min);
Dibuja_campo_vectorial(max,min);
}
VT1->Visualiza_cursor(SI);
break;
case 1000: // Configura a los Metodos numericos
Visualiza_texto(TXT46);
Selecciona_metodo_integracion();
break;
case 2000: // Maximiza la ventana
if(Estado_ventana != 3) {
VT1->Fija_ventana_activa(0);
VT1->Borra_archivo_ventana();
Guarda_posicion = NO;
v_coord = SI;
Doble_ventana = 0;
Estado_ventana = 3;
Ventana_activa = 0;
VT1->Fija_ventana_doble(0);
VT1->VT1->Cambiar_tamano(3,83,X_MAX-3,Y_MAX-31);
VT1->VT1->Fija_dimenciones(Dim_maxima[0][Sistema_actual],Dim_minima[0][Sistema_actual]);
Redibuja_pantalla();
}
break;
case 2001: // Minimiza la ventana
if(Estado_ventana != 2) {
// Si las ventanas fueron invertidas por maximizar la segunda ventana esta son de nuevo invertidas para estar como al principio
if (Inversion_ventanas) {
Inversion_ventanas = 0;
Invierte_ventanas();
}
Guarda_posicion = NO;
v_coord = SI;
Doble_ventana = 1;
Estado_ventana = 2;
VT1->Fija_ventana_doble(1);
VT1->VT1->Cambiar_tamano(3,83,X_MAX/2,Y_MAX-31);
VT1->VT1->Fija_dimenciones(Dim_maxima[0][Sistema_actual],Dim_minima[0][Sistema_actual]);
VT1->VT2->Fija_dimenciones(Dim_maxima[1][Sistema_actual],Dim_minima[1][Sistema_actual]);
VT1->Borra_archivo_ventana();
// Redibuja la ventana dos
VT1->Fija_ventana_activa(1);
Ventana_activa = 1;
Actualiza_coordenadas();
VT1->VT2->Dibuja();
// Redibuja la ventana uno
VT1->Fija_ventana_activa(0);
Ventana_activa = 0;
Actualiza_coordenadas();
VT1->VT1->Dibuja();
Redibuja_pantalla();
}
break;
case 2002: // Graba imagen formato propio
VT1->Visualiza_cursor(NO);
Visualiza_texto(TXT51);
if(Retorna_archivo_seleccionado(cad,0,TXT48,"IMG","*.IMG")) {
if(Ventana_activa) VT1->VT2->Graba_ventana(cad,SIN_FORMATO);
else VT1->VT1->Graba_ventana(cad,SIN_FORMATO);
}
VT1->Visualiza_cursor(SI);
break;
case 2003: // Lee imagen formato propio
VT1->Visualiza_cursor(NO);
Visualiza_texto(TXT52);
if(Retorna_archivo_seleccionado(cad,1,TXT49,"IMG","*.IMG")) {
if(Ventana_activa) VT1->VT2->Lee_ventana(cad,SIN_FORMATO);
else VT1->VT1->Lee_ventana(cad,SIN_FORMATO);
}
VT1->Visualiza_cursor(SI);
break;
case 2004: // Limpia la ventana activa sin conservar la posicion
VT1->Graba_archivo_ventana();
if(VT1->VT1->Retorna_ventana_activa()) VT1->VT1->Dibuja();
if(VT1->VT2->Retorna_ventana_activa()) VT1->VT2->Dibuja();
VT1->Visualiza_cursor(SI);
v_coord = SI;
Guarda_posicion = NO;
break;
case 2100: // Graba el contenido de la ventana de graficacion
VT1->Visualiza_cursor(NO);
if(Ventana_activa) {
unsigned int x1, x2, y1, y2;
VT1->VT2->Actual_pos_ventana(x1,y1,x2,y2);
graba_pantalla_grafica(x1,y1+21,x2,y2,ARCH_TEMPORAL);
} else {
unsigned int x1, x2, y1, y2;
VT1->VT1->Actual_pos_ventana(x1,y1,x2,y2);
graba_pantalla_grafica(x1,y1+21,x2,y2,ARCH_TEMPORAL);
}
VT1->Visualiza_cursor(SI);
break;
case 2101: // Lee el contenido de una ventana de graficacion
VT1->Visualiza_cursor(NO);
if(Ventana_activa) {
unsigned int x1, x2, y1, y2;
VT1->VT2->Actual_pos_ventana(x1,y1,x2,y2);
if(n_archivos_directorios(ARCH_TEMPORAL,FA_ARCH)) lee_pantalla_grafica(x1,y1+21,ARCH_TEMPORAL);
} else {
unsigned int x1, x2, y1, y2;
VT1->VT1->Actual_pos_ventana(x1,y1,x2,y2);
if(n_archivos_directorios(ARCH_TEMPORAL,FA_ARCH)) lee_pantalla_grafica(x1,y1+21,ARCH_TEMPORAL);
}
VT1->Visualiza_cursor(SI);
break;
}
}
//////////////////////////////////////////////////////////////////
// Pantalla de estado del sistema //
//////////////////////////////////////////////////////////////////
void Integra::Pantalla_estado_sistema(void)
{
// Visualiza estado del sistema
Imprime_estado(1,1);
}
// Redibuja pantalla
void Integra::Redibuja_pantalla(void)
{
Dibuja_aplicacion();
}
//////////////////////////////////////////////////////////////////
// RUTINA PRINCIPAL //
//////////////////////////////////////////////////////////////////
void main(int argc, char *argv[])
{
int svga = 0, st = 0;
// Revisa a que modo grafico iniciara la pantalla Grafica
if(argc == 2) {
svga = argv[1][0] - '0';
if(svga < 0 || svga > 3) st = 1;
} else st = 1;
if(st) printf("\n\n%s\n\n%s\n %s N\n\n%s\n%s\n%s\n%s\n%s\n",VER_INTEGRA,TXT2,argv[0],TXT3,TXT4,TXT5,TXT6,TXT7);
else {
Integra *If;
If = new Integra;
If->Ejecuta(VER_INTEGRA,svga);
delete If;
}
}
|
ad708b45362513e0da4f57c75e7cd2f84b3b349c
|
1dbf007249acad6038d2aaa1751cbde7e7842c53
|
/cfw/include/huaweicloud/cfw/v1/model/VPCProtectsVo.h
|
2e2c5b2d190b946287bbbef239dabbbbe68e7fc5
|
[] |
permissive
|
huaweicloud/huaweicloud-sdk-cpp-v3
|
24fc8d93c922598376bdb7d009e12378dff5dd20
|
71674f4afbb0cd5950f880ec516cfabcde71afe4
|
refs/heads/master
| 2023-08-04T19:37:47.187698
| 2023-08-03T08:25:43
| 2023-08-03T08:25:43
| 324,328,641
| 11
| 10
|
Apache-2.0
| 2021-06-24T07:25:26
| 2020-12-25T09:11:43
|
C++
|
UTF-8
|
C++
| false
| false
| 2,855
|
h
|
VPCProtectsVo.h
|
#ifndef HUAWEICLOUD_SDK_CFW_V1_MODEL_VPCProtectsVo_H_
#define HUAWEICLOUD_SDK_CFW_V1_MODEL_VPCProtectsVo_H_
#include <huaweicloud/cfw/v1/CfwExport.h>
#include <huaweicloud/core/utils/ModelBase.h>
#include <huaweicloud/core/http/HttpResponse.h>
#include <huaweicloud/cfw/v1/model/VpcAttachmentDetail.h>
#include <vector>
namespace HuaweiCloud {
namespace Sdk {
namespace Cfw {
namespace V1 {
namespace Model {
using namespace HuaweiCloud::Sdk::Core::Utils;
using namespace HuaweiCloud::Sdk::Core::Http;
/// <summary>
/// vpc protects vo
/// </summary>
class HUAWEICLOUD_CFW_V1_EXPORT VPCProtectsVo
: public ModelBase
{
public:
VPCProtectsVo();
virtual ~VPCProtectsVo();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
bool fromJson(const web::json::value& json) override;
/////////////////////////////////////////////
/// VPCProtectsVo members
/// <summary>
/// 总VPC数
/// </summary>
int32_t getTotal() const;
bool totalIsSet() const;
void unsettotal();
void setTotal(int32_t value);
/// <summary>
/// 本项目防护VPC数
/// </summary>
int32_t getSelfTotal() const;
bool selfTotalIsSet() const;
void unsetselfTotal();
void setSelfTotal(int32_t value);
/// <summary>
/// 其他项目防护VPC数
/// </summary>
int32_t getOtherTotal() const;
bool otherTotalIsSet() const;
void unsetotherTotal();
void setOtherTotal(int32_t value);
/// <summary>
/// 防护VPC
/// </summary>
std::vector<VpcAttachmentDetail>& getProtectVpcs();
bool protectVpcsIsSet() const;
void unsetprotectVpcs();
void setProtectVpcs(const std::vector<VpcAttachmentDetail>& value);
/// <summary>
/// 本项目防护VPC
/// </summary>
std::vector<VpcAttachmentDetail>& getSelfProtectVpcs();
bool selfProtectVpcsIsSet() const;
void unsetselfProtectVpcs();
void setSelfProtectVpcs(const std::vector<VpcAttachmentDetail>& value);
/// <summary>
/// 其他项目防护VPC
/// </summary>
std::vector<VpcAttachmentDetail>& getOtherProtectVpcs();
bool otherProtectVpcsIsSet() const;
void unsetotherProtectVpcs();
void setOtherProtectVpcs(const std::vector<VpcAttachmentDetail>& value);
protected:
int32_t total_;
bool totalIsSet_;
int32_t selfTotal_;
bool selfTotalIsSet_;
int32_t otherTotal_;
bool otherTotalIsSet_;
std::vector<VpcAttachmentDetail> protectVpcs_;
bool protectVpcsIsSet_;
std::vector<VpcAttachmentDetail> selfProtectVpcs_;
bool selfProtectVpcsIsSet_;
std::vector<VpcAttachmentDetail> otherProtectVpcs_;
bool otherProtectVpcsIsSet_;
};
}
}
}
}
}
#endif // HUAWEICLOUD_SDK_CFW_V1_MODEL_VPCProtectsVo_H_
|
b1c90edb18e235f335e1035ee1c7c599ff00de49
|
0c4a1194c0d4e567251382070323e0d805ec439b
|
/PS_BOJ/BOJ1991.cpp
|
ab91a73dfefcfce45a1de2cfa2e453ca3c769b15
|
[] |
no_license
|
webserver3315/Desktop_PS_BOJ
|
e49f3642cfb42a73f227248398b2d3bf6651ec3d
|
b778168e69997882de37eafa71b4fffbaeb9c6ee
|
refs/heads/master
| 2021-01-08T20:36:39.049238
| 2020-08-01T07:17:39
| 2020-08-01T07:17:39
| 242,135,976
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,674
|
cpp
|
BOJ1991.cpp
|
#include <iostream>
#include <vector>
#include <deque>
#include <utility>
#define pii pair<int,int>
#define ff first
#define ss second
#define mp(a,b) make_pair(a,b)
using namespace std;
char itoC(int i) {
return i + 'A';
}
int Ctoi(char c) {
return c - 'A';
}
class Tree {
public:
int nodeKazu;
vector<int> parent;
vector<pii> children;//ff:lc,ss:rc
Tree() :nodeKazu(0) {}
Tree(int n) :nodeKazu(n) {
parent.resize(nodeKazu, -1);
children.resize(nodeKazu);
}
void appendChild(char prnt, char lc, char rc) {
int curr = Ctoi(prnt);
if (lc == '.')
children[curr].ff = -1;
else
children[curr].ff = Ctoi(lc);
if (rc == '.')
children[curr].ss = -1;
else
children[curr].ss = Ctoi(rc);
}
void preorder(int root) {//전위순회: 루트 좌자 우자
cout << itoC(root);
if (children[root].ff != -1)
preorder(children[root].ff);
if (children[root].ss != -1)
preorder(children[root].ss);
}
void inorder(int root) {//중위: 좌자 루트 우자
if (children[root].ff != -1)
inorder(children[root].ff);
cout << itoC(root);
if (children[root].ss != -1)
inorder(children[root].ss);
}
void postorder(int root) {//후위: 좌자 우자 루트
if (children[root].ff != -1)
postorder(children[root].ff);
if (children[root].ss != -1)
postorder(children[root].ss);
cout << itoC(root);
}
};
int main() {
int n;
cin >> n;
Tree tree(n);
for (int i = 0; i < n; i++) {
string a, b, c;
cin >> a >> b >> c;
char ca, cb, cc;
ca = a[0]; cb = b[0]; cc = c[0];
tree.appendChild(ca, cb, cc);
}
tree.preorder(0);
cout << endl;
tree.inorder(0);
cout << endl;
tree.postorder(0);
cout << endl;
return 0;
}
|
870c8cf4379742ce41271d1b4b094fdce3275fce
|
4b0689713ceb26bda536077a73177a19a47726a9
|
/controller/controller_setpoint/src/controller_setpoint/controller_setpoint.cpp
|
76e5a06f08d053ec5a28cb3c4e8b0290e07a56ed
|
[] |
no_license
|
danielduberg/safe_flight
|
3f1227cfb295563b9f2c525709d182a53cd7b3b9
|
5c3be53454e4f8feeb6d6c06b43223894d52c073
|
refs/heads/master
| 2021-01-01T06:19:52.661467
| 2017-09-15T10:13:45
| 2017-09-15T10:13:45
| 97,410,250
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,567
|
cpp
|
controller_setpoint.cpp
|
#include <controller_setpoint/controller_setpoint.h>
#include <controller_msgs/Controller.h>
#include <tf2/utils.h>
namespace controller_setpoint
{
ControllerSetpoint::ControllerSetpoint(ros::NodeHandle nh, ros::NodeHandle nh_priv, ros::NodeHandle nh_controller)
: nh_(nh)
, nh_priv_(nh_priv_)
, nh_controller_(nh_controller)
, tf_listener_(tf_buffer_)
{
initParam(nh_);
controller_pub_ = nh_controller_.advertise<controller_msgs::Controller>("setpoint", 1);
setpoint_sub_ = nh_.subscribe<geometry_msgs::PoseStamped>("/nav_2d", 1, &ControllerSetpoint::setpointCallback, this);
current_setpoint_.pose.orientation.w = 1;
publish_timer_ = nh_.createTimer(ros::Duration(1.0 / frequency_), &ControllerSetpoint::publishCallback, this);
}
void ControllerSetpoint::initParam(ros::NodeHandle & nh)
{
nh.param<double>("frequency", frequency_, 60.0);
nh.param<std::string>("robot_base_frame", robot_base_frame_, "base_link");
}
void ControllerSetpoint::setpointCallback(const geometry_msgs::PoseStamped::ConstPtr & msg)
{
current_setpoint_ = *msg;
}
double ControllerSetpoint::getYaw(const geometry_msgs::Quaternion & orientation)
{
return tf2::getYaw(orientation);
}
geometry_msgs::PoseStamped ControllerSetpoint::transformPose(const geometry_msgs::PoseStamped & pose, const std::string & to_frame)
{
geometry_msgs::TransformStamped transform;
try
{
transform = tf_buffer_.lookupTransform(to_frame, pose.header.frame_id, ros::Time(0));
}
catch (tf2::TransformException & ex)
{
ROS_WARN_STREAM_THROTTLE_NAMED(1, "safe_flight/controller_setpoint", ex.what());
throw ex;
}
geometry_msgs::PoseStamped setpoint;
tf2::doTransform(pose, setpoint, transform);
return setpoint;
}
void ControllerSetpoint::publishCallback(const ros::TimerEvent & event)
{
geometry_msgs::PoseStamped setpoint;
try
{
current_setpoint_.header.stamp = ros::Time::now(); // So that we get the most recent transform
setpoint = transformPose(current_setpoint_, robot_base_frame_);
}
catch (tf2::TransformException & ex)
{
// Such that we just hold position
setpoint.pose.position.x = 0.0;
setpoint.pose.position.y = 0.0;
setpoint.pose.position.z = 0.0;
tf2::Quaternion q = tf2::Quaternion::getIdentity();
setpoint.pose.orientation.x = q.x();
setpoint.pose.orientation.y = q.y();
setpoint.pose.orientation.z = q.z();
setpoint.pose.orientation.w = q.w();
}
controller_msgs::Controller out;
out.header.stamp = ros::Time::now();
out.header.frame_id = robot_base_frame_;
out.twist_stamped.header.stamp = ros::Time::now();
out.twist_stamped.header.frame_id = robot_base_frame_;
out.twist_stamped.twist.linear.x = setpoint.pose.position.x * 0.5;
out.twist_stamped.twist.linear.y = setpoint.pose.position.y * 0.5;
out.twist_stamped.twist.linear.z = 0.0;
if (std::fabs(setpoint.pose.position.z) > 0.05)
{
out.twist_stamped.twist.linear.z = setpoint.pose.position.z;
}
out.twist_stamped.twist.angular.z = getYaw(setpoint.pose.orientation);
out.arm = true;
controller_pub_.publish(out);
}
}
|
cdccbd956632338a43f009d3d532a164ee4ba91e
|
4daf92779d11b71bc22b2cf61661b205ac7cc4e9
|
/kernel/irq.hpp
|
ef78e7bd5b1ebfda36c9e3edaa3cec08b18d06f7
|
[] |
no_license
|
Avidanborisov/Bug
|
22f9e392e7a2016c90970fa5e5c676429bcce6f9
|
25285184288c67117802efda113a39ea75c85e20
|
refs/heads/master
| 2020-05-29T18:49:17.018097
| 2016-10-15T21:53:09
| 2016-10-15T21:53:09
| 45,314,015
| 7
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 761
|
hpp
|
irq.hpp
|
#ifndef IRQ_HPP
#define IRQ_HPP
#include <stdint.h>
#include "context.hpp"
class IRQ {
public:
static void init();
using Handler = void(Context::Registers&);
static void handle(uint8_t num, Handler* handler);
static constexpr auto NUM_HANDLERS = 16;
private:
static void commonHandler(Context::Registers& regs) asm("IRQ_commonHandler");
static Handler* handlers[];
class PIC {
public:
PIC(uint16_t commandPort, uint16_t dataPort);
void sendCommand(uint8_t cmd) const;
void sendData(uint8_t data) const;
void sendEOI() const;
uint8_t readISR() const;
private:
uint16_t commandPort;
uint16_t dataPort;
};
static PIC master, slave;
};
#endif // IRQ_HPP
|
fa86dad4ef5ebd15bb1d0a42ab239d5b7a1cc0b2
|
42bdead94c0de0af015dfafefcf0391086c64ab1
|
/source/error.cpp
|
017bf8450bf630e93cf1c10dbc99721f0d5bbb79
|
[] |
no_license
|
csgardn2/eve_industry
|
d69c0eda5ee69c2ea7e053b9a605faf1e5182d0c
|
95028aa9cfb1549b3dc8ea67e7adc4220d02a754
|
refs/heads/master
| 2021-05-10T22:35:06.598736
| 2018-01-20T17:44:40
| 2018-01-20T17:44:40
| 118,259,985
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,380
|
cpp
|
error.cpp
|
/// @brief Implementation of @ref error_message_t class
///
/// * Contact conor.gardner@arm.com if you have questions about this code.
/// * Date Created = Saturday November 4 2017
/// * Documentation is generated by doxygen, see documentation/html_out/index.html
#include <string_view>
#include <vector>
#include "error.h"
const std::vector<std::string_view> error_message_t::error_names_ =
{
"FILE_SIZE_FAILED",
"FILE_READ_FAILED",
"FILE_WRITE_FAILED",
"JSON_SCHEMA_VIOLATION",
"YAML_SCHEMA_VIOLATION",
"YAML_MISSING_INVENTION_DEPENDENCY",
"MODE_MISSING",
"MODE_INVALID",
"ITEM_ATTRIBUTES_OUT_MISSING",
"ITEM_ATTRIBUTES_IN_MISSING",
"STATION_ATTRIBUTES_IN_MISSING",
"PRICES_OUT_MISSING",
"PRICES_IN_MISSING",
"BLUEPRINTS_IN_MISSING",
"PROFITS_OUT_MISSING",
"SORT_STRATEGY_INVALID",
"UNKNOWN_ORDER_TYPE",
"EVE_SUCKS",
"NO_ORDERS",
"HTTPS_GET_FAILED",
"MISSING_MARKET_PAGE",
"INVALID_MATERIAL_EFFICIENCY",
"INVALID_TIME_EFFICIENCY",
"INVALID_PROBABILITY",
"READ_INVALID_INVENT",
"READ_INVALID_COPY",
"UNKNOWN_DECRYPTOR_TYPE",
"UNKNOWN_MANUFACTURABILITY_STATUS",
"UNKNOWN_SORT_STRATEGY",
"ARG_MISSING_CCP_YAML_IN",
"ARG_WRONG_NUMBER_OF_PARAMETERS_CCP_YAML_IN",
"ARG_MISSING_CUSTOM_JSON_OUT",
"ARG_WRONG_NUMBER_OF_PARAMETERS_CUSTOM_JSON_OUT"
};
|
99226e05ba473afa319955cef73adc7ab28c96f3
|
720be6dce7bea45534313066104ca89c41a54c6f
|
/src/binarywriter.cpp
|
be852e0d9f8ead6a526a65ed1074c7e6d47073cc
|
[] |
no_license
|
vostreltsov/lisp-compiler
|
e2b4bba02531a93fdbe325942826b3c7b6297f48
|
badedb51b109dfedd1334c8428b931369e560fc7
|
refs/heads/master
| 2020-05-17T12:12:27.998929
| 2013-03-10T23:25:32
| 2013-03-10T23:25:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,200
|
cpp
|
binarywriter.cpp
|
#include "binarywriter.h"
BinaryWriter::BinaryWriter()
{
}
BinaryWriter::BinaryWriter(QString fileName)
{
QFile * file = new QFile(fileName);
if (file->open(QIODevice::WriteOnly)) {
stream.setDevice(file);
}
}
BinaryWriter::~BinaryWriter()
{
QIODevice * file = stream.device();
if (file != NULL) {
file->close();
delete file;
}
}
bool BinaryWriter::isAlive() const
{
return (stream.device() != NULL);
}
void BinaryWriter::writeU4(quint32 value)
{
if (isAlive()) {
stream << value;
}
}
void BinaryWriter::writeU2(quint16 value)
{
if (isAlive()) {
stream << value;
}
}
void BinaryWriter::writeU1(quint8 value)
{
if (isAlive()) {
stream << value;
}
}
void BinaryWriter::writeF4(float value)
{
if (isAlive()) {
char * data = (char*)&value;
stream.writeRawData(&data[3], 1);
stream.writeRawData(&data[2], 1);
stream.writeRawData(&data[1], 1);
stream.writeRawData(&data[0], 1);
}
}
void BinaryWriter::writeByteArray(QByteArray bytes)
{
if (isAlive()) {
foreach (unsigned char byte, bytes) {
stream << byte;
}
}
}
|
ac61a986fc2dec07f6b603c6b0e0374d0891a6c1
|
31928ab1235c4e25d3ea6d119c4231e501c72a59
|
/217_Contains_Duplicate/solution.cpp
|
e5fde3910c7b71da87b922d9f10900ed3149f903
|
[] |
no_license
|
yangzan0532/leetcode
|
7a4d3bc83640cec4eb8458805ab370ea73788b81
|
ec788d413e5687ef6eedfde65f030caa2d310d9e
|
refs/heads/master
| 2022-10-30T21:09:32.572141
| 2016-04-24T16:47:32
| 2016-04-24T16:47:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 352
|
cpp
|
solution.cpp
|
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
map<int,int>my_map;
for(vector<int>::iterator curr=nums.begin();
curr != nums.end();
++curr){
if((my_map.insert(make_pair(*curr, 1))).second== false){
return true;
}
}
return false;
}
};
|
dba3eb5e3cfca28191062806cce17a30b3f4fd2e
|
4f06b67cdd92724020d7a7bfd9428f631ceb986d
|
/app/components/scenegraph/Moveable.cpp
|
370e753cd760ce47530b15880302b7842b96ec12
|
[
"MIT"
] |
permissive
|
filipwasil/rearwing-glviewer
|
857e19dbd0abf7a6947628b236ad86ad201c6fa8
|
3d0289398367b6dc330eae18042497b8da2e77da
|
refs/heads/master
| 2020-08-30T12:36:59.968087
| 2020-01-24T10:06:01
| 2020-01-24T10:06:01
| 218,382,206
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,316
|
cpp
|
Moveable.cpp
|
#include <Moveable.hpp>
namespace rwc
{
Moveable::Moveable(const glm::vec3& translation, const glm::quat& rotation, const glm::vec3& scale)
: mTranslation{translation}
, mRotation{rotation}
, mScale{scale}
, mParentRotation{glm::quat(1.0, 0.0, 0.0, 0.0)}
, mMMC{1.0}
, mParentMMC{1.0}
, mRefresh{true}
, mAnimationChannelCustom{}
, mAnimationChannelTranslation{}
, mAnimationChannelRotation{}
, mAnimationChannelScale{}
{
// empty
}
Moveable::~Moveable() = default;
Moveable& Moveable::operator=(const Moveable&) = default;
Moveable::Moveable(const Moveable&) = default;
Moveable& Moveable::operator=(Moveable&&) = default;
Moveable::Moveable(Moveable&&) = default;
glm::vec3 Moveable::getTranslation() const
{
return mTranslation;
}
void Moveable::moveTo(const glm::vec3& coordinates)
{
mTranslation = coordinates;
mRefresh = true;
}
void Moveable::moveToX(float distance)
{
mTranslation.x = distance;
mRefresh = true;
}
void Moveable::moveToY(float distance)
{
mTranslation.y = distance;
mRefresh = true;
}
void Moveable::moveToZ(float distance)
{
mTranslation.z = distance;
mRefresh = true;
}
void Moveable::moveBy(const glm::vec3& coordinates)
{
mTranslation += coordinates;
mRefresh = true;
}
void Moveable::moveByX(float distance)
{
mTranslation.x += distance;
mRefresh = true;
}
void Moveable::moveByY(float distance)
{
mTranslation.y += distance;
mRefresh = true;
}
void Moveable::moveByZ(float distance)
{
mTranslation.z += distance;
mRefresh = true;
}
void Moveable::moveInDirection(const glm::vec3& direction)
{
mTranslation += glm::vec3(glm::mat4_cast(mRotation) * glm::vec4(direction, 1.0));
mRefresh = true;
}
glm::vec3 Moveable::getScale() const
{
return mScale;
}
void Moveable::scaleTo(float scale)
{
mScale = glm::vec3(scale, scale, scale);
mRefresh = true;
}
void Moveable::scaleTo(const glm::vec3& scale)
{
mScale = scale;
mRefresh = true;
}
void Moveable::scaleToX(float scale)
{
mScale = glm::vec3(scale, mScale.y, mScale.z);
mRefresh = true;
}
void Moveable::scaleToY(float scale)
{
mScale = glm::vec3(mScale.x, scale, mScale.z);
mRefresh = true;
}
void Moveable::scaleToZ(float scale)
{
mScale = glm::vec3(mScale.x, mScale.y, scale);
mRefresh = true;
}
glm::quat Moveable::getRotation() const
{
return mRotation;
}
void Moveable::rotateTo(const glm::quat& rotation)
{
mRotation = rotation;
mRefresh = true;
}
void Moveable::rotateTo(const glm::vec3& axis, float angle)
{
mRotation = glm::angleAxis(angle, glm::normalize(axis));
mRefresh = true;
}
void Moveable::rotateByX(float angle)
{
rotateBy(glm::vec3(1.0, 0.0, 0.0), angle);
mRefresh = true;
}
void Moveable::rotateByY(float angle)
{
rotateBy(glm::vec3(0.0, 1.0, 0.0), angle);
mRefresh = true;
}
void Moveable::rotateByZ(float angle)
{
rotateBy(glm::vec3(0.0, 0.0, 1.0), angle);
mRefresh = true;
}
void Moveable::rotateBy(const glm::vec3& axisLine, float angle)
{
const glm::vec3 axis(glm::mat4_cast(mRotation) * glm::vec4(glm::normalize(axisLine), 1.0) * sinf(angle / 2.0f));
const float scalar = cosf(angle / 2.0f);
const glm::quat offset(scalar, axis.x, axis.y, axis.z);
mRotation = glm::normalize(offset * mRotation);
mRefresh = true;
}
void Moveable::updateMatrixCache()
{
mMMC = glm::translate(glm::mat4(1.0), mTranslation) * glm::mat4_cast(mRotation) * glm::scale(glm::mat4(1.0), mScale);
}
bool Moveable::isRefresh() const
{
return mRefresh;
}
void Moveable::setRefresh(bool state)
{
mRefresh = state;
}
glm::mat4 Moveable::getParentMMC() const
{
return mParentMMC;
}
glm::quat Moveable::getParentRotation() const
{
return mParentRotation;
}
void Moveable::attachCustomCallback(float durationSeconds, std::function<void(float)> action)
{
std::get<CHANNEL_CURRENT_IDX>(mAnimationChannelCustom).push_back([this, durationSeconds, action](float deltaSeconds) {
auto& timePassed = std::get<CHANNEL_TIME_LENGTH_IDX>(mAnimationChannelCustom);
if (0.0f == durationSeconds) {
return durationSeconds;
}
if (0.0f == timePassed) {
action(0.0f);
}
timePassed += deltaSeconds;
action(getPercentageDone(timePassed, durationSeconds));
if (timePassed < durationSeconds) {
return 0.0f;
}
float timeLeft = timePassed - durationSeconds;
timePassed = 0;
return timeLeft;
});
}
void Moveable::waitInTime(float durationSeconds)
{
std::get<CHANNEL_CURRENT_IDX>(mAnimationChannelCustom).push_back([this, durationSeconds](float deltaSeconds) {
auto& timePassed = std::get<CHANNEL_TIME_LENGTH_IDX>(mAnimationChannelCustom);
timePassed += deltaSeconds;
if (timePassed <= durationSeconds) {
return 0.0f;
}
float timeLeft = timePassed - durationSeconds;
timePassed = 0;
return timeLeft;
});
}
void Moveable::moveBy(float durationSeconds, const glm::vec3& deltaMove, std::function<float(float)> ease)
{
clearChannel(mAnimationChannelTranslation);
std::get<CHANNEL_CURRENT_IDX>(mAnimationChannelTranslation).push_back(
[this, durationSeconds, deltaMove, ease](float deltaSeconds) {
auto& timePassed = std::get<CHANNEL_TIME_LENGTH_IDX>(mAnimationChannelTranslation);
if (0.0f == timePassed) {
std::get<CHANNEL_VALUE_IDX>(mAnimationChannelTranslation) = mTranslation;
}
timePassed += deltaSeconds;
const float percentageDone = ease(getPercentageDone(timePassed, durationSeconds));
moveTo(std::get<CHANNEL_VALUE_IDX>(mAnimationChannelTranslation) + percentageDone * deltaMove);
if (timePassed <= durationSeconds) {
return 0.0f;
}
float timeLeft = timePassed - durationSeconds;
timePassed = 0;
return timeLeft;
});
}
void Moveable::moveTo(float durationSeconds, const glm::vec3& endTranslation, std::function<float(float)> ease)
{
clearChannel(mAnimationChannelTranslation);
std::get<CHANNEL_CURRENT_IDX>(mAnimationChannelTranslation).push_back(
[this, durationSeconds, endTranslation, ease](float deltaSeconds) {
auto& timePassed = std::get<CHANNEL_TIME_LENGTH_IDX>(mAnimationChannelTranslation);
if (0.0f == timePassed) {
std::get<CHANNEL_VALUE_IDX>(mAnimationChannelTranslation) = mTranslation;
}
timePassed += deltaSeconds;
const glm::vec3 deltaMove = endTranslation - std::get<CHANNEL_VALUE_IDX>(mAnimationChannelTranslation);
const float percentageDone = ease(getPercentageDone(timePassed, durationSeconds));
moveTo(std::get<CHANNEL_VALUE_IDX>(mAnimationChannelTranslation) + percentageDone * deltaMove);
if (timePassed <= durationSeconds) {
return 0.0f;
}
float timeLeft = timePassed - durationSeconds;
timePassed = 0;
return timeLeft;
});
}
void Moveable::scaleBy(float durationSeconds, const glm::vec3& deltaScale, std::function<float(float)> ease)
{
clearChannel(mAnimationChannelScale);
std::get<CHANNEL_CURRENT_IDX>(mAnimationChannelScale).push_back(
[this, durationSeconds, deltaScale, ease](float deltaSeconds) {
auto& timePassed = std::get<CHANNEL_TIME_LENGTH_IDX>(mAnimationChannelScale);
auto& current = std::get<CHANNEL_VALUE_IDX>(mAnimationChannelScale);
if (0.0f == timePassed) {
current = mScale;
}
timePassed += deltaSeconds;
const float percentageDone = ease(getPercentageDone(timePassed, durationSeconds));
const glm::vec3 scale = current * ( deltaScale - glm::vec3(1.0) );
scaleTo(current + percentageDone * scale);
if (timePassed <= durationSeconds) {
return 0.0f;
}
const float timeLeft = timePassed - durationSeconds;
timePassed = 0;
return timeLeft;
});
}
void Moveable::scaleTo(float durationSeconds, const glm::vec3& endScale, std::function<float(float)> ease)
{
clearChannel(mAnimationChannelScale);
std::get<CHANNEL_CURRENT_IDX>(mAnimationChannelScale).push_back(
[this, durationSeconds, endScale, ease](float deltaSeconds) {
auto& timePassed = std::get<CHANNEL_TIME_LENGTH_IDX>(mAnimationChannelScale);
auto& current = std::get<CHANNEL_VALUE_IDX>(mAnimationChannelScale);
if (0.0f == timePassed) {
current = mScale;
}
timePassed += deltaSeconds;
const float percentageDone = ease(getPercentageDone(timePassed, durationSeconds));
scaleTo(current + percentageDone * (endScale - current));
if (timePassed <= durationSeconds) {
return 0.0f;
}
const float timeLeft = timePassed - durationSeconds;
timePassed = 0;
return timeLeft;
});
}
void Moveable::rotateBy(float durationSeconds, const glm::vec3& axis, const float endAngle, std::function<float(float)> ease)
{
clearChannel(mAnimationChannelRotation);
std::get<CHANNEL_CURRENT_IDX>(mAnimationChannelRotation).push_back(
[this, durationSeconds, endAngle, axis, ease](float deltaSeconds) {
auto& timePassed = std::get<CHANNEL_TIME_LENGTH_IDX>(mAnimationChannelRotation);
auto current = std::get<CHANNEL_VALUE_IDX>(mAnimationChannelRotation);
if (timePassed == 0.0f) {
current = mRotation;
}
timePassed += deltaSeconds;
const float percentageDone = ease(getPercentageDone(timePassed, durationSeconds));
rotateTo(current);
rotateTo(axis, percentageDone * endAngle);
if (timePassed < durationSeconds) {
return 0.0f;
}
float timeLeft = timePassed - durationSeconds;
timePassed = 0;
return timeLeft;
});
}
void Moveable::rotateTo(float durationSeconds, const glm::vec3& axis, const float endAngle, std::function<float(float)> ease)
{
clearChannel(mAnimationChannelRotation);
const auto endAngleQuat = glm::angleAxis(endAngle, glm::normalize(axis));
std::get<CHANNEL_CURRENT_IDX>(mAnimationChannelRotation).push_back(
[this, durationSeconds, endAngleQuat, ease](float deltaSeconds) {
auto& timePassed = std::get<CHANNEL_TIME_LENGTH_IDX>(mAnimationChannelRotation);
auto& current = std::get<CHANNEL_VALUE_IDX>(mAnimationChannelRotation);
if (timePassed == 0.0f) {
current = mRotation;
}
timePassed += deltaSeconds;
const float percentageDone = ease(getPercentageDone(timePassed, durationSeconds));
rotateTo(glm::mix(current, endAngleQuat, percentageDone));
if (timePassed < durationSeconds) {
return 0.0f;
}
const float timeLeft = timePassed - durationSeconds;
timePassed = 0;
return timeLeft;
});
}
template <class Container>
float Moveable::stepInTime(Container& container, float deltaTime) {
if (std::get<CHANNEL_CURRENT_IDX>(container).empty()
|| std::get<CHANNEL_HANDLERS_IDX>(container) == std::get<CHANNEL_CURRENT_IDX>(container).size()) {
return deltaTime;
}
float timeLeft = deltaTime;
do {
timeLeft = std::get<CHANNEL_CURRENT_IDX>(container)[std::get<CHANNEL_HANDLERS_IDX>(container)](timeLeft);
if (timeLeft == 0.0f) {
return 0.0f;
}
std::get<CHANNEL_TIME_LENGTH_IDX>(container) = 0.0f;
if (++std::get<CHANNEL_HANDLERS_IDX>(container) < std::get<CHANNEL_CURRENT_IDX>(container).size()) {
continue;
}
std::get<CHANNEL_HANDLERS_IDX>(container) = 0;
std::get<CHANNEL_CURRENT_IDX>(container).clear();
return timeLeft;
} while(1);
}
bool Moveable::onTimePassed(float secondsPassed)
{
const std::array <float, 4> timeLeft {
stepInTime(mAnimationChannelCustom, secondsPassed)
, stepInTime(mAnimationChannelTranslation, secondsPassed)
, stepInTime(mAnimationChannelRotation, secondsPassed)
, stepInTime(mAnimationChannelScale, secondsPassed)
};
return std::all_of(timeLeft.begin(), timeLeft.end(), [](float time) {
return time > 0.0f;
});
}
void Moveable::stop()
{
clearChannel(mAnimationChannelCustom);
clearChannel(mAnimationChannelTranslation);
clearChannel(mAnimationChannelScale);
clearChannel(mAnimationChannelRotation);
}
template float Moveable::stepInTime<Moveable::AnimationChannel<int>>(Moveable::AnimationChannel<int>& c, float deltaTime);
template float Moveable::stepInTime<Moveable::AnimationChannel<glm::vec3>>(Moveable::AnimationChannel<glm::vec3>& c, float deltaTime);
template float Moveable::stepInTime<Moveable::AnimationChannel<glm::quat>>(Moveable::AnimationChannel<glm::quat>& c, float deltaTime);
} // namespace rwc
|
9fc281b34b28e84b4551b405685a567efcccafcc
|
d7d6678b2c73f46ffe657f37169f8e17e2899984
|
/controllers/ros/include/services/differential_wheels_set_speed.h
|
35577c837eceb0c704d738e810617bbaaede6fd1
|
[] |
no_license
|
rggasoto/AdvRobotNav
|
ad8245618e1cc65aaf9a0d659c4bb1588f035f18
|
d562ba4fba896dc23ea917bc2ca2d3c9e839b037
|
refs/heads/master
| 2021-05-31T12:00:12.452249
| 2016-04-15T14:02:05
| 2016-04-15T14:02:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,503
|
h
|
differential_wheels_set_speed.h
|
#ifndef WEBOTS_ROS_MESSAGE_DIFFERENTIAL_WHEELS_SET_SPEED_H
#define WEBOTS_ROS_MESSAGE_DIFFERENTIAL_WHEELS_SET_SPEED_H
#include "ros/service_traits.h"
#include "differential_wheels_set_speedRequest.h"
#include "differential_wheels_set_speedResponse.h"
namespace webots_ros
{
struct differential_wheels_set_speed
{
typedef differential_wheels_set_speedRequest Request;
typedef differential_wheels_set_speedResponse Response;
Request request;
Response response;
typedef Request RequestType;
typedef Response ResponseType;
};
} // namespace webots_ros
namespace ros
{
namespace service_traits
{
template<>
struct MD5Sum< ::webots_ros::differential_wheels_set_speed > {
static const char* value()
{
return "a3f660fa6747eeaef7c7125d534eaa59";
}
static const char* value(const ::webots_ros::differential_wheels_set_speed&) { return value(); }
};
template<>
struct DataType< ::webots_ros::differential_wheels_set_speed > {
static const char* value()
{
return "webots_ros/differential_wheels_set_speed";
}
static const char* value(const ::webots_ros::differential_wheels_set_speed&) { return value(); }
};
template<>
struct MD5Sum< ::webots_ros::differential_wheels_set_speedRequest>
{
static const char* value()
{
return MD5Sum< ::webots_ros::differential_wheels_set_speed >::value();
}
static const char* value(const ::webots_ros::differential_wheels_set_speedRequest&)
{
return value();
}
};
template<>
struct DataType< ::webots_ros::differential_wheels_set_speedRequest>
{
static const char* value()
{
return DataType< ::webots_ros::differential_wheels_set_speed >::value();
}
static const char* value(const ::webots_ros::differential_wheels_set_speedRequest&)
{
return value();
}
};
template<>
struct MD5Sum< ::webots_ros::differential_wheels_set_speedResponse>
{
static const char* value()
{
return MD5Sum< ::webots_ros::differential_wheels_set_speed >::value();
}
static const char* value(const ::webots_ros::differential_wheels_set_speedResponse&)
{
return value();
}
};
template<>
struct DataType< ::webots_ros::differential_wheels_set_speedResponse>
{
static const char* value()
{
return DataType< ::webots_ros::differential_wheels_set_speed >::value();
}
static const char* value(const ::webots_ros::differential_wheels_set_speedResponse&)
{
return value();
}
};
} // namespace service_traits
} // namespace ros
#endif // WEBOTS_ROS_MESSAGE_DIFFERENTIAL_WHEELS_SET_SPEED_H
|
6e286db6d29c1b78b5daf3fee7e75450f91828d4
|
13933902f561dd3fa9bb0041838d38232170a95f
|
/Estructura/struct/Codigo vario/Codigo vario/Connect4/main.cpp
|
d49133ab722a23dc5519867166da7da4c72c8410
|
[
"MIT"
] |
permissive
|
dkmaster17/DKM
|
11eda0949275f05a105825e368865f065dd3515e
|
ef22411e57cb37f18b9ddd2305001050855cd137
|
refs/heads/master
| 2021-01-17T04:32:28.100338
| 2017-03-22T04:30:06
| 2017-03-22T04:30:06
| 82,981,267
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,720
|
cpp
|
main.cpp
|
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <gl\gl.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class Jugador {
private:
char *nombre;
int juego;
public :
Jugador() {
nombre=NULL;
juego=1;
}
void set_Nombre(char* a) {
nombre=a;
}
void set_jugando(int a) {
juego=a;
}
int get_jugando() {
return juego;
}
char* get_Nombre() {
return nombre;
}
void Imprimir() {
cout<<"Jugador :"<<nombre<<endl;
}
};
class Ficha {
private:
int valor;
public:
Ficha() {
valor=0;
}
int get_Valor() {
return valor; //Ayudan al manejo de las fichas su
}
void set_Valor(int a) {
valor=a;
}
void Imprimir() {
if(valor!=0)
cout<<"| "<<valor<<" |";
else cout<<"|"<<" "<<"|";
}
};
void Imprimir (Ficha** MapadeFichas,Ficha *Dondejuego) {
system("cls");
HANDLE hConsole;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
cout<<endl;
cout<<endl;
for(int j=0; j<7; j++) {
SetConsoleTextAttribute(hConsole,7);
cout<<"\t";
if(Dondejuego[j].get_Valor()==1) {
SetConsoleTextAttribute(hConsole,12);
}
if(Dondejuego[j].get_Valor()==2) {
SetConsoleTextAttribute(hConsole,25);
}
if(Dondejuego[j].get_Valor()==0) {
SetConsoleTextAttribute(hConsole,42);
}
Dondejuego[j].Imprimir();
}
SetConsoleTextAttribute(hConsole,7);
cout<<endl;
cout<<endl;
cout<<endl;
cout<<endl;
for(int i=0; i<6; i++) {
for(int j=0; j<7; j++) {
SetConsoleTextAttribute(hConsole,7);
cout<<"\t";
if(MapadeFichas[i][j].get_Valor()==1) {
SetConsoleTextAttribute(hConsole,12);
}
if(MapadeFichas[i][j].get_Valor()==2) {
SetConsoleTextAttribute(hConsole,25);
}
if(MapadeFichas[i][j].get_Valor()==0) {
SetConsoleTextAttribute(hConsole,42);
}
MapadeFichas[i][j].Imprimir();
}
SetConsoleTextAttribute(hConsole,7);
cout<<endl;
cout<<endl;
}
}
int Intercambio(int a,Ficha* Dondejuego,int quien,int direccion) {
if(direccion==1) {
Dondejuego[a].set_Valor(0);
Dondejuego[a+1].set_Valor(quien);
return 1;
}
if(direccion==2) {
Dondejuego[a].set_Valor(0);
Dondejuego[a-1].set_Valor(quien);
return -1;
}
}
int play(Ficha **MapadeFichas,int pos,int quienjuega) {
int count=0;
for(int i=0; i<7; i++) {
if(i+1<6) {
if (MapadeFichas[i+1][pos].get_Valor()==0) {
count++;
} else break;
}
}
if(MapadeFichas[count][pos].get_Valor()==0) {
MapadeFichas[count][pos].set_Valor(quienjuega);
}
return count;
}
bool validacionVictoria(Ficha** MapadeFichas,int i,int j,int quienjuega) {
int n=i,m=j,r=j,p=i;
int ConVer,ConHor,ConDigDer,ConDigIzq;
cout<< i<<" " << j <<endl;// 4, 3
if(MapadeFichas[n][m].get_Valor()==quienjuega)
{
ConVer=ConHor=ConDigIzq=ConDigDer=1;
for(int k=0; k<3; k++)
{
if(n+1<6&&MapadeFichas[n+1][j].get_Valor()==quienjuega) {
ConVer++;
}
if(m+1<7&&MapadeFichas[i][m+1].get_Valor()==quienjuega) {
ConHor++;
}
if(r-1>=0&&MapadeFichas[i][r-1].get_Valor()==quienjuega) {
ConHor++;
}
if((n+1<6&&m+1<7) &&MapadeFichas[n+1][m+1].get_Valor()==quienjuega) {
ConDigDer++;
}
if((n+1<6&&r-1>=0) &&MapadeFichas[n+1][r-1].get_Valor()==quienjuega) {
ConDigIzq++;
}
if((p-1>=0&&m+1<7) &&MapadeFichas[p-1][m+1].get_Valor()==quienjuega) {
ConDigIzq++;
}
if((p-1>=0&&r-1>=0)&&MapadeFichas[p-1][r-1].get_Valor()==quienjuega) {
ConDigDer++;
}
n++;
m++;
r--;
p--;
}
}
if(ConVer==4||ConHor==4||ConDigDer==4||ConDigIzq==4)return true;
return false;
}
void reinicio(Ficha**MapadeFichas,Ficha* Dondejuego,int quienjuega){
for(int i=0; i<6; i++) {
Dondejuego[i].set_Valor(0);
for(int j=0; j<7; j++) {
MapadeFichas[i][j].set_Valor(0);
}
}
Dondejuego[0].set_Valor(quienjuega);
}
void Movimientos(Ficha** MapadeFichas,Ficha *Dondejuego) {
char Move='a';
bool win=false;
int i=0,j=0,pos;
int cant;
Jugador quienjuega;
Dondejuego[i].set_Valor(quienjuega.get_jugando());
Imprimir(MapadeFichas,Dondejuego);
while(win!=true) {
if(quienjuega.get_jugando()==1)
{
Move=getche();
system("cls");
if(Move==82||Move==114)
{
reinicio(MapadeFichas,Dondejuego,quienjuega.get_jugando());
win=false;
i=0;
j=0;
}
if(Move==83||Move==115)
{
break;
}
if(Move==77&&i<6) {
if(i<6)
{
i=i+Intercambio(i,Dondejuego,quienjuega.get_jugando(),1);
}
}
if(Move==75&&i>=0) {
if(i-1>=0) {
i=i+Intercambio(i,Dondejuego,quienjuega.get_jugando(),2);
}
}
if(Move==' ') {
j=play(MapadeFichas,i, quienjuega.get_jugando());
if(j!=0) {
cant++;
if(cant>3) win=validacionVictoria(MapadeFichas,j,i,quienjuega.get_jugando());
quienjuega.set_jugando(2);
Dondejuego[i].set_Valor(quienjuega.get_jugando());
}
}
Imprimir(MapadeFichas,Dondejuego);
} else {
Move=getche();
system("cls");
if(Move==82||Move==114)
{
reinicio(MapadeFichas,Dondejuego,quienjuega.get_jugando());
i=0;
j=0;
win=false;
}
if(Move==83||Move==115)
{
break;
}
if(Move==77&&i<7) {
if(i<7) {
i=i+Intercambio(i,Dondejuego,quienjuega.get_jugando(),1);
}
}
if(Move==75&&i>=0) {
if(i-1>=0) {
i=i+Intercambio(i,Dondejuego,quienjuega.get_jugando(),2);
}
}
if(Move==' ') {
j=play(MapadeFichas,i, quienjuega.get_jugando());
cant++;
if(cant>3) win=validacionVictoria(MapadeFichas,j,i,quienjuega.get_jugando());
quienjuega.set_jugando(1);
Dondejuego[i].set_Valor(quienjuega.get_jugando());
}
Imprimir(MapadeFichas,Dondejuego);
}
}
}
void JugadorVrsPc()
{
}
void JugadorVrsJugador()
{
Ficha **MapadeFichas= new Ficha*[6];
Ficha *Dondejuego= new Ficha[7];
for(int i=0; i<7; i++) {
MapadeFichas[i]=new Ficha[7];
}
Movimientos(MapadeFichas,Dondejuego);
cout<<endl;
cout<<endl;
cout<<endl;
}
void Creditos()
{
}
void Menu()
{
char resp;
while(resp!='4')
{
cout<<endl;
cout<<endl;
cout<<endl;
cout<<endl;
cout<<"\t\t\t 1-->Jugador Vrs Pc."<<endl;
cout<<"jooodaseee"<<endl;
cout<<endl;
cout<<endl;
cout<<"\t\t 2-->Jugador Vrs Jugador."<<endl;
cout<<endl;
cout<<endl;
cout<<"\t\t\t 3-->Creditos."<<endl;
cout<<endl;
cout<<endl;
cout<<"\t\t\t 4-->Salir."<<endl;
cout<<endl;
cout<<endl;
cin>> resp;
cout<<endl;
cout<<endl;
switch (resp)
{
case '1':
JugadorVrsPc();
break;
case '2':
JugadorVrsJugador();
break;
case '3':
Creditos();
break;
case '4':
break;
}
}
}
int main(int argc, char** argv) {
Menu();
return 0;
}
|
29757e11503c8ef52ddb3e95fe843da6c37d8810
|
170c3bc0c94419269e8b461a2ac64230a73acea2
|
/MainMenuWindow.cpp
|
6c67ffa1087986536c1518f5cc54b3741d3cb135
|
[] |
no_license
|
meorules/StarWarsCardGame
|
cc0196b114a5e3db508a1e1a2210b5f682b9445a
|
7e109f04c9deee8ed4d9a7817d0c9ccd4cc2caa9
|
refs/heads/master
| 2023-04-13T18:13:54.938822
| 2021-04-17T16:03:48
| 2021-04-17T16:03:48
| 358,632,111
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,367
|
cpp
|
MainMenuWindow.cpp
|
#include "MainMenuWindow.h"
MainMenuWindow::MainMenuWindow(HINSTANCE hInsantce, int width, int height) : Window(hInsantce, width, height)
{
createWindow(hInstance, width, height);
currentState = browsing;
}
void MainMenuWindow::onDraw() {
drawBitmap(backgroundFile, 0, 0, 600, 400);
setTextColour(CYAN);
setFont(28, L"Univers Bold");
drawText(L"Main Menu", 300, 35);
//Output Text
setFont(12, L"Times New Roman Bold");
drawText(outputText.c_str(), 75, 300);
//Username Label & Box
setTextColour(YELLOW);
drawRectangle(125, 200, 200, 20, false);
drawText(L"Username:", 50, 200);
setTextColour(WHITE);
drawText(currentusernamefield.c_str(), 126, 201);
//Password Label & Box
setTextColour(YELLOW);
drawRectangle(125, 230, 200, 20, false);
drawText(L"Password:", 55, 230);
setTextColour(WHITE);
drawText(currentpasswordfield.c_str(), 126, 231);
//Sign Up Button
setFont(12, L"News Gothic Bold");
setBackColour(DARK_BLUE);
setTextColour(WHITE);
drawRectangle(370, 185, 60, 30, true);
drawText(L"Sign-up", 372, 190);
//Add Login logic
drawRectangle(370, 225, 60, 30, true);
drawText(L"Login", 380, 230);
//Add Card Library Logic
drawRectangle(450, 205, 100, 40, true);
drawText(L"Card Library", 455, 215);
//Basic onDraw()
Window::onDraw();
}
void MainMenuWindow::onCreate()
{
Window::onCreate();
outputText = "Please enter a username and password to create an account or login";
SetWindowText(getHWND(), L"Main Menu");
}
void MainMenuWindow::onLButtonDown(UINT nFlags, int x, int y)
{
//Collecting Username
if (x > 125 && x < 325 && y>200 && y < 220) {
currentState = collectingUsername;
}
//Collecting Password
else if (x > 125 && x < 325 && y>230 && y < 250) {
currentState = collectingPassword;
}
//Sign up Button drawRectangle(370, 185, 60, 30, true);
else if (x>370 && x<430 && y>185 && y<215) {
int found = Users::returnInstance()->findUser(User(currentusernamefield));
if (found == -1) {
Users::returnInstance()->addUser(User(currentusernamefield, currentpasswordfield,0,0));
currentusernamefield = "";
currentpasswordfield = "";
}
else {
outputText = "Username is already taken";
}
}
//Login Button drawRectangle(370, 225, 60, 30, true);
//NEEDS TO BE WORKED ON
else if (x > 370 && x < 430 && y>225 && y < 255) {
int found= Users::returnInstance()->findUser(User(currentusernamefield));
if (found!=-1) {
if (Users::returnInstance()->checkPassword(found, currentpasswordfield) == true) {
UserMenuWindow* main = new UserMenuWindow(hInstance, 600, 400, Users::returnInstance()->returnUser(found));
DestroyWindow(getHWND());
main->waitForClose();
delete main;
}
else {
outputText = "Password is incorrect";
}
}
else {
outputText = "Username not found";
}
}
// Card Library Button drawRectangle(450, 205, 100, 40, true);
else if (x > 450 && x < 550 && y>205 && y < 245) {
CardLibraryWindow* main = new CardLibraryWindow(hInstance, 1000, 600);
DestroyWindow(getHWND());
main->waitForClose();
delete main;
}
//Default
else{
currentState = browsing;
}
onDraw();
}
void MainMenuWindow::onChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
string character = string(1, char(nChar));
if (currentState == 1) {
if (nChar == 8) {
currentusernamefield = currentusernamefield.substr(0, currentusernamefield.length() - 1);
}
else {
if (currentusernamefield.length() < 25) {
currentusernamefield = currentusernamefield + character;
}
else {
outputText = "The username field has exceeded the limit of 24 characters";
}
}
}
else if (currentState == 2) {
if (nChar == 8) {
currentpasswordfield = currentpasswordfield.substr(0, currentpasswordfield.length() - 1);
}
else {
if (currentpasswordfield.length() < 25) {
currentpasswordfield = currentpasswordfield + character;
}
else {
outputText = "The password field has exceeded the limit of 24 characters";
}
}
}
if (currentusernamefield.length() < 25 && currentpasswordfield.length() < 25) {
outputText = "Please enter a username and password to create an account or login";
}
onDraw();
}
|
f348381a6a28e08f020600a41d6abe2bb06084b5
|
2e873074f8331537cf68f80d844cbe1d8f24f490
|
/Recipe.h
|
fd293e32dec42d4041b79f57d19923aae4b55400
|
[] |
no_license
|
SevenDeadlyCins/Recipe-Classes
|
be7737438b5c6087d702ef9f41176e3bbcd590ff
|
50e9e1cc9b3764c687df6921f92cc115aa3062ac
|
refs/heads/master
| 2020-08-17T12:21:39.759564
| 2019-11-15T17:24:17
| 2019-11-15T17:24:17
| 215,665,580
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 550
|
h
|
Recipe.h
|
/*
Abdulaziz Alamro
CS441 - Software Engineering
Group Project - Recipe Class
*/
#include <iostream>
#include <vector>
#include <fstream>
#include "Ingredient.h"
using namespace std;
class Recipe
{
public:
Recipe();
void readDrinkName();
void readRecipe();
void displayRecipe();
void readMaterials();
void displayMaterials();
Recipe addIngredient(Ingredient ingredient);
void displayIngredients();
void readDrinks();
vector<string> recipeList;
vector<string> reqMaterials;
vector<Ingredient> ingredientList;
friend class Read;
};
|
4e748951f8ffc0d3f3bd88eb829f1549c1d62f0a
|
f2e00ac569530a06f0f0b70dc342ad4681e480c2
|
/nxlib/nxsession.h
|
db1682a92cc25e4b30ad380250797218a3e2301a
|
[] |
no_license
|
BackupTheBerlios/freenx
|
b70e6ddba9e97723527bfdb2b328913e666adb29
|
67c8f84670651e561f3ebe77027c99bb61b82ce6
|
refs/heads/master
| 2020-05-27T07:37:47.954653
| 2006-07-26T11:40:08
| 2006-07-26T11:40:08
| 40,248,816
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,204
|
h
|
nxsession.h
|
/***************************************************************************
nxsession.h
-------------------
begin : Sat 22nd July 2006
copyright : (C) 2006 by George Wright
email : gwright@kde.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef _NXSESSION_H_
#define _NXSESSION_H_
// This class is used to parse the output from the nxssh session to the server
class NXSession
{
public:
NXSession();
~NXSession();
};
#endif
|
c13ccb52f5dacd1133b2231fce82a43a75919de8
|
03b39218d1990c99e9bf464f0e6f727373bef14f
|
/p31.cpp
|
83517d95dcef3cc8519f540ec5c2cb37d51a626d
|
[] |
no_license
|
RishiRajKhanna2001/Cpp-Code
|
1e052cd62066129a60a668e962600d2321d4a2f0
|
d5d7c41bfe51be0794f6255ac10fd1455473575f
|
refs/heads/master
| 2023-08-15T04:17:20.969616
| 2021-09-29T12:54:29
| 2021-09-29T12:54:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 772
|
cpp
|
p31.cpp
|
#include<iostream>
using namespace std;
//base class
class employee{
public:
int id;
float salary;
employee(int inpId){
id=inpId;
salary=34;
}
employee(){}
};
//derived class syntax
// class {{derived-class-name}} : {{ visibility-mode}} {{ base-class-name}}
// {
// class members/methods/etc..
// }
class programmer : public employee{
public:
programmer(int inpId)
{
id=inpId;
}
int languageCode=9;
void getdata()
{
cout<<id<<endl;
}
};
int main(){
employee harry(1),rishi(2);
cout<<harry.salary<<endl;
cout<<rishi.salary<<endl;
programmer skillf(10);
cout<<skillf.languageCode<<endl;
cout<<skillf.id<<endl;
skillf.getdata();
return 0;
}
|
42016954d5aced5a60b6f394355d6a4d5abf2c18
|
b41f5fc3c72b75f42419a16cffb145c59dedecab
|
/server/include/board.hpp
|
9723f24f49d7e89dbff3b777a8d6e1ad50f7fad2
|
[] |
no_license
|
MaxProfit/Snake-Server
|
cec5bcbe132880cfe7d7545ed764f4aa9b56222c
|
be32fc8186bd54e4db139a8c0c20feca4ada7a97
|
refs/heads/master
| 2020-04-11T20:45:06.985569
| 2018-12-17T06:44:42
| 2018-12-17T06:44:42
| 162,081,389
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,818
|
hpp
|
board.hpp
|
//
// Created by Matthew Williams on 2018-12-10.
//
#ifndef TEST_PROJECT_BOARD_HPP
#define TEST_PROJECT_BOARD_HPP
#include <array>
#include <vector>
#include <utility>
#include <unordered_map>
#include <random>
#include "../../lib/json.hpp"
#include "snake.hpp"
namespace snakegame {
class Snake;
}
namespace snakegameboard {
const uint16_t kMaxFood {5};
const uint16_t kHeight {27};
const uint16_t kWidth {48};
enum class Piece {
EMPTY,
FOOD,
SNAKE
};
class Board {
public:
// Get the positions of all the different snakes
// Get the positions of all of the food on the board
// Initializes the board, adding the food to the board
Board();
// Simply gets a random coordinate on the board that is unoccupied
std::pair<int, int> GetEmptyCoord();
// Uses the aggregate json data and passes that to the snake that deals with that data, or spawns new snake
void ConsumeJsonVec(std::vector<nlohmann::json> json_vec);
// Updates all the snakes on the board
void UpdateBoard();
// Checks if there is food at the location the snake is traveling to
bool IsFoodHere(std::pair<int, int> location);
// Checks if there is a snake at the location the snake is traveling to
bool IsSnakeHere(std::pair<int, int> location);
// Add food to the board and the serializable vector
void AddFood(std::pair<int, int> food_coord);
// Remove food from the board and the serializable vector
void RemoveFood(std::pair<int, int> food_coord);
// Add snake piece to the board
void AddSnakePiece(std::pair<int, int> snake_piece_coord);
// Remove snake piece from the board
void RemoveSnakePiece(std::pair<int, int> snake_piece_coord);
// Removes this snake from the board and the vector, used when the snake gets killed
void DeleteSnake(int id);
// Package into json for sending, serializes both snakes_loc_ and food_loc_
nlohmann::json PackageBoard();
// Sends snakes and food in a coordinate grid JSON
private:
// Used to represent the food and snakes, with access in order(1) time for quick lookup
std::array<std::array<Piece, kWidth>, kHeight> board_array_;
// Stores the food locations with easy parsing for JSON
std::vector<std::pair<int, int>> food_loc_;
// Stores the snakes in a map which refer to them by their ID
std::unordered_map<int, snakegame::Snake> id_snake_map_;
// Used to generate points on the board
std::mt19937 generator_;
std::uniform_int_distribution<> dist_x_;
std::uniform_int_distribution<> dist_y_;
};
}
#endif //TEST_PROJECT_BOARD_HPP
|
9c090538cfca438384bbd83dcf48fa6d0d9d94d9
|
88dcce19274d00eb1ad4970fb14242a98d214b8f
|
/Packages/java/nio/LongBuffer.hxx
|
1c548319d30426473eb29a1b00da8f26975b1d08
|
[
"MIT"
] |
permissive
|
Brandon-T/Aries
|
0802db9dac0fe6204c3c520bbfac9fbdbcd8a689
|
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
|
refs/heads/master
| 2021-09-07T16:02:21.520864
| 2018-02-25T18:25:24
| 2018-02-25T18:25:24
| 104,820,745
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,689
|
hxx
|
LongBuffer.hxx
|
//
// LongBuffer.hxx
// Aries
//
// Created by Brandon on 2018-02-24.
// Copyright © 2018 Brandon. All rights reserved.
//
#ifndef LongBuffer_hxx
#define LongBuffer_hxx
#include "Array.hxx"
#include "Buffer.hxx"
namespace java::nio
{
using java::lang::Object;
using java::lang::String;
using java::nio::Buffer;
using java::nio::ByteOrder;
class LongBuffer : public Buffer
{
public:
LongBuffer(JVM* vm, jobject instance);
static LongBuffer allocate(JVM* vm, std::int32_t capacity);
Array<std::int64_t> array();
std::int32_t arrayOffset();
LongBuffer asReadOnlyBuffer();
LongBuffer compact();
std::int32_t compareTo(LongBuffer that);
LongBuffer duplicate();
bool equals(Object ob);
std::int64_t get();
std::int64_t get(std::int32_t index);
LongBuffer get(Array<std::int64_t>& dst, std::int32_t offset, std::int32_t length);
LongBuffer get(Array<std::int64_t>& dst);
bool hasArray();
std::int32_t hashCode();
bool isDirect();
ByteOrder order();
LongBuffer put(std::int64_t l);
LongBuffer put(std::int32_t index, std::int64_t l);
LongBuffer put(LongBuffer src);
LongBuffer put(Array<std::int64_t>& src, std::int32_t offset, std::int32_t length);
LongBuffer put(Array<std::int64_t>& src);
LongBuffer slice();
String toString();
static LongBuffer wrap(JVM* vm, Array<std::int64_t>& array, std::int32_t offset, std::int32_t length);
static LongBuffer wrap(JVM* vm, Array<std::int64_t>& array);
};
}
#endif /* LongBuffer_hxx */
|
6474ee0eef9f05680555c0d1d34a2788858b0255
|
301ed54244fd41502fd6f23a2e016c6e0cfba2dd
|
/01 LIBRARY/009 MST.cpp
|
b91ece49fa02a1659766a1db2eab9a543545eeff
|
[] |
no_license
|
iCodeIN/Competitive-Programming-4
|
660607a74c4a846340b6fb08316668057f75a7ba
|
05b55d2736f6b22758cd57f3ed5093cf8a2f4e2f
|
refs/heads/master
| 2023-02-22T12:53:39.878593
| 2021-01-28T10:57:50
| 2021-01-28T10:57:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,546
|
cpp
|
009 MST.cpp
|
#include <bits/stdc++.h>
using namespace std;
struct Edge {
int u, v, weight;
bool operator<(Edge const& other) {
return weight < other.weight;
}
};
class WeightedUF {
private:
vector<int> arr;
vector<int> size;
int __root(int a) {
while (arr[a] != a) {
arr[a] = arr[arr[a]];
a = arr[a];
}
return a;
}
public:
WeightedUF(int v) {
arr = vector<int>(v + 1);
size = vector<int>(v + 1);
for (int i = 0; i <= v; i++) {
size[i] = 1;
arr[i] = i;
}
}
void _union(int a, int b) {
int rootA = __root(a);
int rootB = __root(b);
if (rootA == rootB) return;
if (size[rootA] < size[rootB]) {
arr[rootA] = rootB;
size[rootB] += size[rootA];
} else {
arr[rootB] = rootA;
size[rootA] += size[rootB];
}
}
bool _find(int a, int b) {
return __root(a) == __root(b);
}
};
int32_t main() {
int n;
vector<Edge> edges;
// initialize edges and n
vector<Edge> mst; int cost = 0;
WeightedUF uf(n);
sort(edges.begin(), edges.end());
for (auto e : edges) {
if (!uf._find(e.u, e.v)) {
cost += e.weight;
mst.push_back(e);
uf._union(e.u, e.v);
}
}
return 0;
}
|
bf45d417c935b075770581a0d458504aabb96f4b
|
4311f39735b2a3f61497a68dda212ad43b110ab2
|
/dmx_control/rgb_functions.ino
|
4a0ea807f90aac2e7810adc6eaaf5a8bb1926e19
|
[] |
no_license
|
cse-revue/arduino
|
e430c1376e7390a7ec101355fdbb0c28a9a3f292
|
c28b0c4132d283238be146f1f50c565bd983061e
|
refs/heads/master
| 2021-01-01T16:19:32.295375
| 2015-09-03T12:35:00
| 2015-09-03T12:35:00
| 24,551,207
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,001
|
ino
|
rgb_functions.ino
|
#include "defs.h"
void init_outputs(int pin_start, int r_offset, int g_offset, int b_offset) {
pinMode(pin_start + r_offset, OUTPUT);
pinMode(pin_start + g_offset, OUTPUT);
pinMode(pin_start + b_offset, OUTPUT);
}
void output_rgb_(int rgb[], int pin_start, int r_offset, int g_offset, int b_offset) {
for (byte i = 0; i != 3; ++i) {
if (rgb[i] < 0) rgb[i] = 0;
if (rgb[i] > 255) rgb[i] = 255;
}
analogWrite(pin_start + r_offset, rgb[INDEX_R]);
analogWrite(pin_start + g_offset, rgb[INDEX_G]);
analogWrite(pin_start + b_offset, rgb[INDEX_B]);
}
void zero_rgb_(int rgb[]) {
rgb[INDEX_R] = 0;
rgb[INDEX_G] = 0;
rgb[INDEX_B] = 0;
}
// Load random RGB Values
void setup_rgb_random(int rgb[]) {
rgb[0] = 7;
rgb[1] = 13;
rgb[2] = 19;
}
byte rgb_random(int rgb_1[], int index_r, int index_g, int index_b) {
rgb_1[index_r] = (rgb_1[index_r] * 7) % 255;
rgb_1[index_g] = (rgb_1[index_g] * 7) % 255;
rgb_1[index_b] = (rgb_1[index_b] * 7) % 255;
return true;
}
|
63e826813b70eb9530f861414b140111642537a2
|
0cd661abf98ce9000445ed3409fd4beebc0b50f0
|
/6/Carriage.h
|
d0dfaa4a8721c31bc65ffc0f3040408856c6f9fd
|
[] |
no_license
|
JeremyButt/3891Assignments
|
5069483623a258c79ab8bc1b3db1002c0e300f5e
|
45f5ce6d5a1c6beeaea0129b257560a080f96a97
|
refs/heads/master
| 2021-05-01T21:27:22.318354
| 2017-01-07T21:09:39
| 2017-01-07T21:09:39
| 69,761,756
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,476
|
h
|
Carriage.h
|
/*!
* @file Carriage.h
* @brief Declaration of the Carriage class.
*
* @author Jonathan Anderson <jonathan.anderson@mun.ca>
* @copyright (c) 2016 Jonathan Anderson. All rights reserved.
* @license Apache License, Version 2.0
*
* 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.
*/
#if !defined(CARRIAGE_H)
#define CARRIAGE_H
#include "date.h"
#include "Pumpkin.h"
//! A horse-and-carriage, as in the Cinderella story.
class Carriage
{
public:
/**
* Create a carriage of a given colour (pumpkin-coloured for reasons
* of circumstance).
*/
Carriage(Pumpkin::Colour);
//! What colour is this carriage?
Pumpkin::Colour colour() const;
/**
* Change this carriage into a pumpkin, if the day has changed since
* the carriage was created.
*
* @returns a Pumpkin if the date has changed, nullptr otherwise
*/
Pumpkin* change() const;
private:
Pumpkin::Colour colour_;
int dateCreated_;
};
#endif // !defined(CARRIAGE_H)
|
e4fe3ad141d73fab52e55f3509f0524cdef147f2
|
44e42f2f589fd18d68b8475a4265182f8d10264f
|
/smoothTxt/C3dPreview.cpp
|
2db85b4fe3814f7d600b5d3a0fea7e758c3c3b3f
|
[] |
no_license
|
clebail/m3d
|
d43fd0ed2fdcc20b7e27b881584a63bdd9d6d2c6
|
8e935b60cfa4213f6682c86c6d9dd4ce15856302
|
refs/heads/master
| 2020-02-26T16:22:41.445227
| 2019-04-01T15:31:56
| 2019-04-01T15:31:56
| 71,133,054
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,382
|
cpp
|
C3dPreview.cpp
|
//-----------------------------------------------------------------------------------------------
#include "C3dPreview.h"
//-----------------------------------------------------------------------------------------------
#define COEF (10.0f)
#define UNIT (1/COEF)
#define UNITY (UNIT*1.23f)
#define UNIT2 (UNIT/2.0f)
#define UNITY2 (UNITY/2.0f)
#define KNOBRADIUS (UNIT/3.25f)
#define KNOBHEIGHT (UNIT/4.6f)
//-----------------------------------------------------------------------------------------------
C3dPreview::C3dPreview(QWidget *parent, QHash<QString, QList<QList<SPoint *>*>*> *map) : QDialog(parent) {
setupUi(this);
lvMenu = new QMenu(this);
lvMenu->addAction(tr("Sélection tous"), this, SLOT(selectedAll()));
lvMenu->addAction(tr("Annuler la sélection"), this, SLOT(selectedNone()));
lvLayers->setSelectionMode(QAbstractItemView::MultiSelection);
connect(lvLayers, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(popupMenu(const QPoint &)));
connect(lvColors, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(popupMenu(const QPoint &)));
lvColors->setSelectionMode(QAbstractItemView::MultiSelection);
this->map = map;
if(map != nullptr) {
createList();
computeMap();
w3d->setMap(sfMap);
}
popupSender = nullptr;
}
//-----------------------------------------------------------------------------------------------
C3dPreview::~C3dPreview(void) {
clearMap();
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::createList(void) {
QHashIterator<QString, QList<QList<SPoint *>*>*> it(*map);
colors.clear();
lvLayers->clear();
lvColors->clear();
while (it.hasNext()) {
QList<QList<SPoint *>*> *list;
it.next();
list = it.value();
for(int i=0;i<list->size();i++) {
QList<SPoint *> *sl = list->at(i);
for(int j=0;j<sl->size();j++) {
QString color = sl->at(j)->coul;
if(!colors.contains(color)) {
colors << color;
lvColors->addItem(getColorNameFromIdx(color)+" ("+color+")");
}
}
}
lvLayers->addItem(it.key());
}
lvLayers->selectAll();
lvColors->selectAll();
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::computeMap(void) {
QHashIterator<QString, QList<QList<SPoint *>*>*> it(*map);
QList<QListWidgetItem *> selectedItems = lvLayers->selectedItems();
QList<QListWidgetItem *> selectedColorsItems = lvColors->selectedItems();
QStringList selectedText;
QStringList selectedColors;
clearMap();
for(int i=0;i<selectedItems.size();i++) {
selectedText << selectedItems.at(i)->text();
}
for(int i=0;i<lvColors->count();i++) {
if(lvColors->item(i)->isSelected()) {
selectedColors << colors.at(i);
}
}
while (it.hasNext()) {
QList<QList<SPoint *>*> *list;
it.next();
list = it.value();
if(selectedText.contains(it.key())) {
for(int i=0;i<list->size();i++) {
QList<SPoint *> *sl = list->at(i);
for(int j=0;j<sl->size();j++) {
if(selectedColors.contains(sl->at(j)->coul)) {
float x = (sl->at(j)->x / STEPX) / COEF;;
float y = (map->size() / 2 - it.key().toInt() - 1) * UNITY;
float z = (sl->at(j)->y / STEPY) / COEF;
QColor color = getColor(sl->at(j)->coul);
GLfloat coords[6][4][3] = {
{ { x+UNIT2, y-UNITY2, z+UNIT2 }, { x+UNIT2, y-UNITY2, z-UNIT2 }, { x+UNIT2, y+UNITY2, z-UNIT2 }, { x+UNIT2, y+UNITY2, z+UNIT2 } },
{ { x-UNIT2, y-UNITY2, z-UNIT2 }, { x-UNIT2, y-UNITY2, z+UNIT2 }, { x-UNIT2, y+UNITY2, z+UNIT2 }, { x-UNIT2, y+UNITY2, z-UNIT2 } },
{ { x+UNIT2, y-UNITY2, z-UNIT2 }, { x-UNIT2, y-UNITY2, z-UNIT2 }, { x-UNIT2, y+UNITY2, z-UNIT2 }, { x+UNIT2, y+UNITY2, z-UNIT2 } },
{ { x-UNIT2, y-UNITY2, z+UNIT2 }, { x+UNIT2, y-UNITY2, z+UNIT2 }, { x+UNIT2, y+UNITY2, z+UNIT2 }, { x-UNIT2, y+UNITY2, z+UNIT2 } },
{ { x-UNIT2, y-UNITY2, z-UNIT2 }, { x+UNIT2, y-UNITY2, z-UNIT2 }, { x+UNIT2, y-UNITY2, z+UNIT2 }, { x-UNIT2, y-UNITY2, z+UNIT2 } },
{ { x-UNIT2, y+UNITY2, z+UNIT2 }, { x+UNIT2, y+UNITY2, z+UNIT2 }, { x+UNIT2, y+UNITY2, z-UNIT2 }, { x-UNIT2, y+UNITY2, z-UNIT2 } }
};
for(int k=0;k<6;k++) {
SFace *face = new SFace();
memcpy(&face->coords, &coords[k], sizeof(GLfloat[4][3]));
face->color = color;
sfMap.append(face);
}
}
}
}
}
}
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::clearMap(void) {
for(int i=0;i<sfMap.size();i++) {
delete sfMap.at(i);
}
sfMap.clear();
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::on_hsX_valueChanged(int value) {
w3d->setRotate(static_cast<float>(hsX->value()), static_cast<float>(hsY->value()), static_cast<float>(hsZ->value()));
lbValueX->setText(QString::number(value));
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::on_hsY_valueChanged(int value) {
w3d->setRotate(static_cast<float>(hsX->value()), static_cast<float>(hsY->value()), static_cast<float>(hsZ->value()));
lbValueY->setText(QString::number(value));
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::on_hsZ_valueChanged(int value) {
w3d->setRotate(static_cast<float>(hsX->value()), static_cast<float>(hsY->value()), static_cast<float>(hsZ->value()));
lbValueZ->setText(QString::number(value));
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::on_lvLayers_itemSelectionChanged(void) {
computeMap();
w3d->setMap(sfMap);
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::on_lvColors_itemSelectionChanged(void) {
computeMap();
w3d->setMap(sfMap);
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::selectedAll(void) {
if(popupSender != nullptr) {
popupSender->selectAll();
}
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::selectedNone(void) {
if(popupSender != nullptr) {
popupSender->clearSelection();
}
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::popupMenu(const QPoint &pos) {
popupSender = dynamic_cast<QListWidget *>(sender());
if(popupSender != nullptr) {
lvMenu->exec(popupSender->mapToGlobal(pos));
}
}
//-----------------------------------------------------------------------------------------------
QColor C3dPreview::getColor(QString coul) {
QColor result = Qt::black;
if(coul == "15") {
result = Qt::white;
} else if(coul == "4") {
result = Qt::red;
} else if(coul == "1") {
result = Qt::blue;
} else if(coul == "78") {
result = QColor(246, 212, 179);
} else if(coul == "70") {
result = QColor(88, 42, 18);
} else if(coul == "14") {
result = Qt::yellow;
} else if(coul == "2") {
result = QColor(0, 140, 14);
}
return result;
}
//-----------------------------------------------------------------------------------------------
QString C3dPreview::getColorNameFromIdx(QString coul) {
QString result = "Noir";
if(coul == "15") {
result = "Blanc";
} else if(coul == "4") {
result = "Rouge";
} else if(coul == "1") {
result = "Bleu";
} else if(coul == "78") {
result = "Peau";
} else if(coul == "70") {
result = "Marron";
} else if(coul == "14") {
result = "Jaune";
} else if(coul == "2") {
result = "Vert";
}
return result;
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::on_hsLX_valueChanged(int) {
float xValue = static_cast<float>(hsLX->value()) / 10.0f;
float yValue = static_cast<float>(hsLY->value()) / 10.0f;
w3d->setTranslate(xValue, yValue);
}
//-----------------------------------------------------------------------------------------------
void C3dPreview::on_hsLY_valueChanged(int) {
float xValue = static_cast<float>(hsLX->value()) / 10.0f;
float yValue = static_cast<float>(hsLY->value()) / 10.0f;
w3d->setTranslate(xValue, yValue);
}
//-----------------------------------------------------------------------------------------------
|
ad628eb5982ef3a0fb8cc94cf2d9ba51f2158a27
|
750d46deec14147723a1b1e3f7ff3764c3415645
|
/IPA/src/PathImpl.cpp
|
b15f18fff599ffd0c390836707f205cb9e7b84ca
|
[] |
no_license
|
posjkh22/Code-Helper
|
37093cad16f0c2bc72236020dac6ed77ee517cf1
|
fd1ca8cf92e95506f737e085b6089541b4ac75db
|
refs/heads/master
| 2022-04-28T15:51:49.235273
| 2020-04-13T12:09:42
| 2020-04-13T12:09:42
| 155,648,176
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,062
|
cpp
|
PathImpl.cpp
|
#include "PathImpl.hpp"
bool setNameGPL(std::list<Path *> *inPathList){
static int number = 0;
std::list<Path *>::iterator iter;
for(iter = inPathList->begin();
iter != inPathList->end(); iter++){
Path *currentPath = (*iter);
currentPath->setName(std::string("[") + std::to_string(number++) + std::string("]"));
}
return true;
}
std::list<Path *> *PathImpl::insertPath(Path *TargetPath, wBasicBlock *CallBB, std::list<Path *> *InsertedPathList){
/* TargetPath & InsertedPathList should not be modified */
/* TargetPath must be copied (as many InsertedPathList Path Num) */
/* InsertedPathList must be inserted into TargetPath */
/* Calculated new CallBBLIST */
/* Return new newPathList (It shall be freed in the outer function) */
//static int insertPathRoutineNum = 0;
std::list<Path *> *newPathList = new std::list<Path *>;
//std::cout << "InsertPathRoutineNum: " << insertPathRoutineNum++ << std::endl;
int next_callBB_number = TargetPath->getdeleteNextNumberInCallBBList();
if(next_callBB_number == -1){
/* Impossible path */
std::cout << "ERROR!!" << std::endl;
}
std::list<Path *>::iterator iter1;
std::list<unsigned int>::iterator iter2;
std::list<unsigned int>::iterator iter3;
std::list<wBasicBlock *>::iterator iter4;
std::list<wBasicBlock *>::iterator iter5;
for(iter1 = InsertedPathList->begin(); \
iter1 != InsertedPathList->end(); iter1++){
/* Copy */
/* new_path should be stored in newPathList */
Path *new_path = new Path(TargetPath);
/* Insert InsertedPath into new_path */
Path *inserted_path = (*iter1);
std::list<wBasicBlock *> *wBBListIn_new_path = new_path->getPath();
std::list<wBasicBlock *> *wBBListIn_inserted_path \
= inserted_path->getPath();
unsigned int number = 0;
for(iter4 = wBBListIn_new_path->begin(), number = 0;\
(iter4 != wBBListIn_new_path->end()) \
&& (number < wBBListIn_new_path->size()); \
iter4++, number++){
if(number == (unsigned int)next_callBB_number && CallBB == *(iter4)){
iter4++;
break;
}
}
for(iter5 = wBBListIn_inserted_path->begin(); \
iter5 != wBBListIn_inserted_path->end(); \
iter5++){
wBasicBlock *inserted_bb = (*iter5);
wBBListIn_new_path->insert(iter4, inserted_bb);
}
/* new Path CallBBList Update */
std::list<unsigned int> *new_path_CallBBList = new_path->getCallBBList();
Path *currentInsertedPath = (*iter1);
std::list<unsigned int> *currentInsertedPathCallBBList \
= currentInsertedPath->getCallBBList();
unsigned int InsertedPathSize \
= currentInsertedPath->getPath()->size();
#ifdef DEBUG_IMPL
std::cout << "InsertedPath Size: " << InsertedPathSize << std::endl;
#endif
/* 1. Update: Inserting insertedPath results in existing CallBB change */
int tmp_size = new_path_CallBBList->size();
#ifdef DEBUG_IMPL
std::cout << "InsertedPath: " << std::endl;
for(iter2 = currentInsertedPathCallBBList->begin(); \
iter2 != currentInsertedPathCallBBList->end(); iter2++){
std::cout << (*iter2) << " ";
}
std::cout << std::endl;
std::cout << "ShowBB(Before): " << std::endl;
for(iter2 = new_path_CallBBList->begin();
iter2 != new_path_CallBBList->end(); iter2++){
std::cout << (*iter2) << " ";
}
std::cout << std::endl;
#endif
iter2 = new_path_CallBBList->begin();
for(int i = 0; i < tmp_size; i++){
unsigned int UpdateValue
= new_path_CallBBList->front() + InsertedPathSize;
new_path_CallBBList->pop_front();
new_path_CallBBList->push_back(UpdateValue);
}
#ifdef DEBUG_IMPL
std::cout << "ShowBB(pop): " << std::endl;
for(iter2 = new_path_CallBBList->begin();
iter2 != new_path_CallBBList->end(); iter2++){
std::cout << (*iter2) << " ";
}
std::cout << std::endl;
#endif
/* 2. Update: CallBBList in InsertedPath should be changed */
iter3 = new_path_CallBBList->begin();
if(currentInsertedPathCallBBList->empty() == false){
for(iter2 = currentInsertedPathCallBBList->begin(); \
iter2 != currentInsertedPathCallBBList->end(); iter2++){
unsigned int PassingValue \
= (*iter2) + next_callBB_number +1;
new_path_CallBBList->insert(iter3, PassingValue);
}
}
newPathList->push_back(new_path);
}
return newPathList;
}
std::list<Path *> *PathImpl::ProcessCallInInputPathOnce(std::list<Path *> *InputPath){
//static int processNum = 0;
std::list<Path *>::iterator iter1;
std::list<Path *>::iterator iter2;
std::list<Path *> *inserted_path_list;
std::list<Path *> *result_path_list;
wBasicBlock *target_block;
/* InputPath is from Entry function */
/* So No modifications to InputPath is allowed */
std::list<Path *> *new_return_path_list = new std::list<Path *>;
//std::cout << "ProcessNum(Once): " << processNum++ << std::endl;
for(iter1 = InputPath->begin(); iter1 != InputPath->end(); iter1++){
Path *current_path = (*iter1);
/* inserted_path_list is from wFunction Path: Not allowed to be freed */
inserted_path_list = current_path->SearchNextCallBBandReturnPath();
if(inserted_path_list == nullptr){
/*
for(iter2 = current_path_list->begin(); \
iter2 != inserted_path_list->end(); iter2++){
new_return_path_list->push_back((*iter2));
}
*/
new_return_path_list->push_back(current_path);
continue;
}
target_block = current_path->SearchCallBBListWithIterNumber(current_path->getjustNextNumberInCallBBList());
/* return_path_list is malloced in inserPath function: Need to be freed */
result_path_list = insertPath(current_path, target_block, inserted_path_list);
/*
unsigned int iter_cnt = current->getCallBBNextNumbering();
wBasicBlock *target_block = current->SearchNumberingBB(iter_cnt);
wFunction *target_func = target_block->getFuncCall();
inserted_path_list = target_func->getPATHSLIST();
*/
for(iter2 = result_path_list->begin(); \
iter2 != result_path_list->end(); iter2++){
new_return_path_list->push_back((*iter2));
}
//free(result_path_list);
}
return new_return_path_list;
}
std::list<Path *> *PathImpl::GenerateGPL(std::list<Path *> *EntryFuncPath){
#ifdef DEBUG_PATHIMPL
std::cout << std::endl << "[GPL creator]: Start! " << std::endl;
#endif
std::list<Path *> *GPL;
std::list<Path *> *InputPath = new std::list<Path *>(*EntryFuncPath);
std::list<Path *>::iterator iter;
#ifdef DEBUG_PATHIMPL
static int processNum = 0;
std::cout << "GPL input: " << std::endl;
for(iter = InputPath->begin(); iter != InputPath->end(); iter++){
(*iter)->ShowCallBBList();
(*iter)->ShowPath();
}
std::cout << std::endl;
std::cout << "First New for GPL" << std::endl;
#endif
while(!IsAllCallBBProcessed(InputPath)){
#ifdef DEBUG_PATHIMPL
std::cout << "Input Process GPL: " << std::endl;
for(iter = InputPath->begin(); iter != InputPath->end(); iter++){
(*iter)->ShowCallBBList();
(*iter)->ShowPath();
}
std::cout << std::endl;
#endif
GPL = ProcessCallInInputPathOnce(InputPath);
InputPath = GPL;
#ifdef DEBUG_PATHIMPL
std::cout << "Process GPL: " << processNum++ << std::endl;
for(iter = GPL->begin(); iter != GPL->end(); iter++){
(*iter)->ShowCallBBList();
(*iter)->ShowPath();
}
std::cout << std::endl;
#endif
}
#ifdef DEBUG_PATHIMPL
std::cout << "[GPL creator]: Successfully done! " << std::endl;
#endif
setNameGPL(GPL);
return GPL;
}
bool PathImpl::IsAllCallBBProcessed(std::list<Path *> *input){
//static int ProcessNum = 0;
//std::cout << "ProcessNum(Checker): " << ProcessNum++ << std::endl;
unsigned int sum = 0;
std::list<Path *>::iterator iter;
Path *current_path;
for(iter = input->begin(); iter != input->end(); iter++){
current_path = (*iter);
sum += current_path->getNumCallBBToBeProcessed();
}
if(sum == 0){
#ifdef DEBUG_PATHIMPL
std::cout << "[GPL creator]: All process is done" << std::endl;
#endif
return true;
}
else{
#ifdef DEBUG_PATHIMPL
std::cout << "[GPL creator]: The rest of process: " << sum << std::endl;
#endif
return false;
}
return false;
}
|
7dabd7e6a19bae13d39906456ab7e89c1d4c4909
|
cdf3b96d498b2dc2b72c9423968a57b5250c72f8
|
/gameoflife/backupcokoncesinoclass.cpp
|
c30cb7bf6b94a890d19d27584a98a3baf8eed1d9
|
[] |
no_license
|
ugurkanates/ProgrammingChallenges
|
7c80d28765ef4c375beab061a018d3575ad1f5eb
|
d297c3ccb8206c8239410b5aa7e58f2653241971
|
refs/heads/master
| 2021-01-02T22:53:45.567344
| 2019-03-04T21:16:00
| 2019-03-04T21:16:00
| 99,413,234
| 1
| 0
| null | 2017-08-05T09:47:54
| 2017-08-05T09:33:28
| null |
UTF-8
|
C++
| false
| false
| 3,633
|
cpp
|
backupcokoncesinoclass.cpp
|
#include <iostream>
#include <unistd.h>
#include "grid.h"
#define ROW 20
#define COLUMN 20 //those are for creating 20x20 arena serve as game table
#define WELCOME 39
using namespace std;
void printGame(bool table[][COLUMN]){
for(int i=0;i<ROW;i++) {
for (int j = 0; j < COLUMN; j++) {
if (table[i][j] == true)
cout << "*";
else
cout<< " " ;
}
cout<<endl;
}
}
void tableInitRandom(){
}
void printGameWelcome(){
int i,j,z;
for(i=0;i<ROW+1;i++)
cout<<"* ";
cout<<endl;
for(j=1;j<COLUMN;j++) {
cout << "*";
if(j==COLUMN/2) {
cout << " W E L C O M E T H E G A M E O F L I F E"; //39 word keep number
for (z = WELCOME; z < ROW; z++)
cout << " ";
cout << "*" << endl;
}
else{
for (z = 0; z < ROW; z++)
cout << " ";
cout << "*" << endl;
}
}
for(i=0;i<ROW+1;i++)
cout<<"* ";
cout << endl;
}
void init_choose(bool table[][COLUMN],int choose){
if(choose==0){ //glider tester
for(int i=0;i<ROW;i++)
for(int j=0;j<COLUMN;j++)
table[i][j]=false;
table[3][3]=true;
table[4][4]=true;
table[5][3]=true;
table[5][4]=true;
table[5][2]=true;
table[10][10]=true;
table[11][11]=true;
table[12][9]=true;
table[12][10]=true;
table[12][11]=true;
}
}
void copy_temp(bool table[][COLUMN],bool temp[][COLUMN]){
for(int i=0;i<ROW;i++){
for(int j=0;j<COLUMN;j++){
temp[i][j]=table[i][j];
}
}
}
void mainGame(){
//printGameWelcome();
bool table[ROW][COLUMN];
bool temp[ROW][COLUMN];
int choose=0;
init_choose(table,choose);
while(1) {
usleep(15*100000);
copy_temp(table, temp);
printGame(temp);
for(int i=0;i<ROW;i++){
for(int j=0;j<COLUMN;j++){
if(temp[i][j]==true){
int neigh=0;
if(temp[i][j + 1])
neigh++;
if(temp[i][j - 1])
neigh++;
if(temp[i- 1][j])
neigh++;
if(temp[i - 1][j + 1])
neigh++;
if(temp[i - 1][j - 1])
neigh++;
if(temp[i + 1][j + 1])
neigh++;
if(temp[i + 1][j])
neigh++;
if(temp[i+ 1 ][j - 1])
neigh++;
if(neigh<2 || neigh >3)
table[i][j]=false;
}
if(!temp[i][j]){
int neigh=0;
if(temp[i][j + 1])
neigh++;
if(temp[i][j - 1])
neigh++;
if(temp[i- 1][j])
neigh++;
if(temp[i - 1][j + 1])
neigh++;
if(temp[i - 1][j - 1])
neigh++;
if(temp[i + 1][j + 1])
neigh++;
if(temp[i + 1][j])
neigh++;
if(temp[i+ 1 ][j - 1])
neigh++;
if(neigh == 3)
table[i][j]=true;
}
}
}
}
}
int main() {
mainGame();
return 0;
}
|
c6c1c37adcb3b97ad5961a1a4926f415423a2198
|
2ef3a35a6f45ca6fb278027f6df1438b31a26b81
|
/Linked List/reversellist.cpp
|
9fd113c3d9784120951b676b2d73bd01f1e68102
|
[] |
no_license
|
imlishant/Data-Structures
|
7036485f5d473d295e4ed292870f0be227f79e33
|
2c7722a04f93ef1e1723a66021aea8876cea6683
|
refs/heads/master
| 2022-09-25T06:40:13.648698
| 2022-09-17T19:10:52
| 2022-09-17T19:10:52
| 167,225,421
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 361
|
cpp
|
reversellist.cpp
|
SinglyLinkedListNode* reverse(SinglyLinkedListNode* head) {
SinglyLinkedListNode *ptr = head;
vector<int> ll;
while(ptr != NULL){
ll.push_back(ptr->data);
ptr = ptr->next;
}
ptr = head;
int n = ll.size();
while(ptr != NULL){
ptr->data = ll[n-1];
n--;
ptr = ptr->next;
}
return head;
}
|
5ae63e652f440854033aad7a5a5bd8b016f4afa5
|
8717952bea2b5a7344a9db769a01f9d5ca0a40e5
|
/PiTempControl/lib/app/inc/core/TextColoring.h
|
2d2f482f9643af0a4a306f106440fe5ea41e0e42
|
[] |
no_license
|
Ethax/PiTempControl
|
3233ca36f83bf9a737d25df36b083e2048eed55c
|
31c5b8b2bdc809c7c80c269a5a00880c2c8424b9
|
refs/heads/master
| 2021-01-10T17:11:23.960378
| 2015-11-07T15:27:09
| 2015-11-07T15:27:09
| 45,565,894
| 0
| 0
| null | null | null | null |
ISO-8859-2
|
C++
| false
| false
| 1,618
|
h
|
TextColoring.h
|
#ifndef INC_TEXTCOLORING_H_
#define INC_TEXTCOLORING_H_
#include <ostream>
/**
* @namespace color
* @brief Az konzolon megjelenő szöveg színezéséhez szükséges
* elemeket magába foglaló névtér.
*/
namespace color {
/**
* Az adatfolyam módosítónak megadható színkódok felsorolása.
*/
enum ColorType {
FG_BLACK = 30, FG_RED = 31, FG_GREEN = 32, FG_YELLOW = 33, FG_BLUE = 34,
FG_MAGENTA = 35, FG_CYAN = 36, FG_WHITE = 37, FG_DEFAULT = 39,
BG_BLACK = 40, BG_RED = 41, BG_GREEN = 42, BG_YELLOW = 43, BG_BLUE = 44,
BG_MAGENTA = 45, BG_CYAN = 46, BG_WHITE = 47, BG_DEFAULT = 49
};
/**
* @class modifier
* @brief A kimenő adatfolyamot módosító osztály, aminek
* segítségével színezni lehet a konzolon megjelenő szöveget.
*/
class modifier {
/**
* A színkód tárolására szolgáló változó.
*/
ColorType code;
public:
/**
* @brief Az osztály konstruktora.
*
* @param _code A színkódot jelölő érték.
*/
modifier(ColorType _code) : code(_code) {}
/**
* @brief A kimenő adafolyam-operátor kiterjesztése, amivel
* a modifier típusú objektumokban tárolt színkódokat hozzá
* lehet írni az adatfolyamhoz.
*
* @param os Az adatfolyamra mutató referencia.
* @param mod Egy modifier típusú objektum, amiben a színkód
* található.
* @return Az első paraméterben fogadott referencia.
*/
friend std::ostream& operator<<(std::ostream& os, const modifier& mod) {
#ifdef _WIN32
return os;
#else
return os << "\033[" << mod.code << "m";
#endif
}
};
}
#endif /* INC_TEXTCOLORING_H_ */
|
94047c12d8d817933f08704c211bfd0fdbcb0cfd
|
866acbb0eed58ec6bbefa42b0e51c51de6c55d28
|
/Rocmop/External/mesquite_0_9_5/includeLinks/MeshImplData.hpp
|
563b9ae725baeaf29fdd7ca4b753802c3a0e54c8
|
[
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
metorm/Rocstar
|
0a96499fda3e14d073b365d9fa90d000839eabd3
|
5075e33131faa50919c15e08d2808bbeb576350e
|
refs/heads/master
| 2020-04-11T09:44:37.728497
| 2019-04-02T16:30:58
| 2019-04-02T16:30:58
| 59,928,027
| 0
| 0
|
NOASSERTION
| 2019-05-08T02:55:57
| 2016-05-29T05:32:35
|
FORTRAN
|
UTF-8
|
C++
| false
| false
| 28
|
hpp
|
MeshImplData.hpp
|
../src/Mesh/MeshImplData.hpp
|
6674e5d81e5fe19ba613b513d49d5be4f032647b
|
db6997aae88b4afb3e694587156040a18e4a6a93
|
/1-38-1 Arduino GPS Coordinate Distance Calculator in Node-RED/gps-mqtt-b/gps-mqtt-b.ino
|
4d7bc3e1a7b71ae25f650beb9820be9af12f978c
|
[] |
no_license
|
kdi6033/arduino
|
b9c8644425d4e3e78728b418bf94634e594a5f72
|
f86bb6ba8a1d3f762ca7df3946fcef2d60614af2
|
refs/heads/master
| 2023-03-15T17:43:28.325904
| 2023-03-02T06:07:45
| 2023-03-02T06:07:45
| 129,093,550
| 21
| 38
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,962
|
ino
|
gps-mqtt-b.ino
|
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <arduino-timer.h>
auto timer = timer_create_default(); // create a timer with default settings
// 아래의 6개설정은 사용자 환경에 맞게 수정하세요.
const char* mqtt_server = "broker.mqtt-dashboard.com"; //브로커 주소
const char* outTopic = "/kdi/outTopic"; // 이름이 중복되지 않게 설정 기록
const char* inTopic = "/kdi/inTopic"; // 이름이 중복되지 않게 설정 기록
const char* clientName = ""; // setup 함수에서 자동생성
String sChipId;
char cChipId[20];
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
long count=0;
//GPS 처리
double TargetLat = 37.816707; //GPS Data
double TargetLon = 126.801219;
double lat=0,lon=0;
void setup() {
Serial.begin(115200);
// 타이머 millis 마다 동작
timer.every(5000, pulse);
//이름 자동으로 생성
sChipId=String(ESP.getChipId(),HEX);
sChipId.toCharArray(cChipId,sChipId.length()+1);
clientName=&cChipId[0];
Serial.println(clientName);
//WiFiManager
WiFiManager wm;
//wm.startConfigPortal("");
//wm.resetSettings();
if (!wm.autoConnect(cChipId)) {
Serial.println("failed to connect and hit timeout");
//reset and try again, or maybe put it to deep sleep
ESP.restart();
delay(1000);
}
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// 통신에서 문자가 들어오면 이 함수의 payload 배열에 저장된다.
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
// mqtt 통신에 지속적으로 접속한다.
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientName)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish(outTopic, "Reconnected");
// ... and resubscribe
client.subscribe(inTopic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
bool pulse(void *) {
if(WiFi.status()==WL_CONNECTED) {
//가상데이타 보냄
count++;
lat=TargetLat+(float)count*0.001;
lon=TargetLon+(float)count*0.001;
snprintf(msg, 75, "{\"id\":\"%s\", \"lat\":%f, \"lon\":%f}",cChipId, lat,lon);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish(outTopic, msg);
}
return true;
}
void loop() {
timer.tick(); // tick the timer
if (!client.connected()) {
reconnect();
}
client.loop();
}
|
9e5a5a4c46ed5b0fadd69028d5eaf5c10de208d6
|
a10ae36164588675db630158fe882203449c8eac
|
/MonyFrame.h
|
e087a5afa2546e57ac3cb368e91e4a11e49a10ba
|
[] |
no_license
|
J1016/MonyBuilder
|
4ce83b124ca56bf2253b2d3294d49fa36667afa0
|
6c15fa0dfe7389b718b161397ff51b647f43e50c
|
refs/heads/master
| 2020-04-14T16:29:56.459943
| 2019-01-03T13:46:59
| 2019-01-03T13:46:59
| 163,953,456
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 714
|
h
|
MonyFrame.h
|
#ifndef MONYFRAME_H
#define MONYFRAME_H
#include "MonyTab.h"
#include <QLabel>
#include <QMainWindow>
class CMonyFrame : public QMainWindow
{
Q_OBJECT
private:
static CMonyFrame * sm_pMainFrame; //当前框架窗口
QWidget * m_pMainPanel; //基本面板
QTabWidget * m_pTabbedPanel; //分页面板标签
QLabel * m_pTipLabel; //提示信息面板
QVector<CMonyTab *> m_tabList; //面板集
public:
explicit CMonyFrame(QWidget * pParent = 0);
virtual ~CMonyFrame();
void InitTabs();
static void SetStatusText(QString text);
};
#endif // MONYFRAME_H
|
e7930ca827fbf4d97389c9ab9a4e442561b6df4c
|
0e367a56a1153aabbf3018274dfe2767d84df466
|
/missions/career/mun/surface/glonass/transfer.cpp
|
5b534ab16377a078194b77e0ad47c12509522b5a
|
[] |
no_license
|
mavaneerden/rocket-control-systems
|
4ca8b25fc611ca1121cf80e5898d3d4ea8a627bc
|
dbf5c26b76cdfbed89d59e21191f7ae3b9dc7379
|
refs/heads/master
| 2023-07-04T18:19:01.466721
| 2021-08-08T10:30:43
| 2021-08-08T10:30:43
| 390,065,750
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 566
|
cpp
|
transfer.cpp
|
#include "../../../../../lib/ksp.hpp"
int main(int argc, char const *argv[])
{
/* Automatically connects to the server with the given IP address. */
auto connection = KSP::Connection();
auto vessel = connection.space_center.active_vessel();
auto body = vessel.orbit().body();
auto mun = connection.get_body(KSP::bodies::MUN);
/* Create and execute circularisation maneuver node. */
auto maneuver = KSP::Maneuver(connection, vessel);
maneuver.change_inclination(mun);
KSP::sleep_seconds(3);
maneuver.transfer_to_body(mun);
}
|
24e1b1c55ab45e5f4b759dadec55ec39a1fc6aaa
|
a232b0adaf7a46d0c7cf032dd8f69abbff87c6cb
|
/AdvThreadPool/advthreadpool.cpp
|
b35029e5c077069a5f57113b143762c74f865df4
|
[] |
no_license
|
519984307/AdvThreadPool
|
f1acc75f3174806edd3494e0fa014a421bb30db0
|
1732dff2fbe95913361ef7d66822ba967804ebab
|
refs/heads/master
| 2023-03-15T16:29:36.873092
| 2014-06-14T18:34:25
| 2014-06-14T18:34:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,548
|
cpp
|
advthreadpool.cpp
|
//
/*
This file is part of project AdvThreadPool.
AdvThreadPool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License.
AdvThreadPool 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 pdb. If not, see <http://www.gnu.org/licenses/>.
*/
//
#include "advthread.h"
#include "advthreadpool.h"
//
#include <QTime>
#include <QCoreApplication>
#include <QMutexLocker>
//
#include <iostream> // only for debug
AdvThreadPool::AdvThreadPool(QObject *parent) :
QObject(parent)
{
m_uiMaxThreadNumber = 0;
m_uiUniquer = 0;
m_EnableWork = false;
//
setMode (en_FIFO);
}
AdvThreadPool::~AdvThreadPool()
{
ThreadMap::Iterator itr;
for (itr = m_Pool.begin(); itr != m_Pool.end(); ++itr)
{
delete itr.value();
};
//
m_Pool.clear();
}
AdvThreadPool& AdvThreadPool::getInstance()
{
static AdvThreadPool instance;
//
return instance;
}
void AdvThreadPool::init(unsigned int ui_threads_amount)
{
if (m_uiMaxThreadNumber > 0)
return;
//
if (ui_threads_amount > 0)
m_uiMaxThreadNumber = ui_threads_amount;
else
m_uiMaxThreadNumber = QThread::idealThreadCount();
//
m_EnableWork = true;
}
void AdvThreadPool::setMode (PoolMode en_mode)
{
QMutexLocker locker (&m_TaskLocker);
m_enPoolMode = en_mode;
}
bool AdvThreadPool::execute(AdvThreadJob* ptr_job)
{
if ( NULL == ptr_job )
return false;
//
if (false == m_EnableWork)
return false;
//
if (getTaskQueueSize() > 0)
{
addJobToQueue(ptr_job);
//std::cout<<"add job N 1, queuse size:"<<getTaskQueueSize()<<std::endl;
return true;
};
//
AdvThread* ptr_available_thread = getAvailableThread(); // scan threadpool, search available thread
//
if (NULL == ptr_available_thread) // available thread was not found, may be all existing threads are busy
{
ptr_available_thread = createReservedThread();
};
//
if (NULL != ptr_available_thread)
{
ptr_available_thread->setJob(ptr_job);
ptr_available_thread->start(ptr_job->getPriority());
}else
{
addJobToQueue(ptr_job);
//std::cout<<"add job N 2, queuse size:"<<getTaskQueueSize()<<std::endl;
};
//
return true;
}
void AdvThreadPool::stop ()
{
m_EnableWork = false;
//
int i_max_cycle_repeat = 1000;
int i_current_step = 0;
//
while ( true )
{
i_current_step++;
if (i_current_step >= i_max_cycle_repeat)
break;
//
if ( (isIdle() == false) || (getTaskQueueSize() > 0) )
{
sleep(1);
continue;
};
};
//
std::cout<<"final queue size:"<<getTaskQueueSize()<<std::endl;
//
return;
}
bool AdvThreadPool::isIdle ()
{
ThreadMap::Iterator itr;
{
QMutexLocker thread_locker (&m_PoolLocker);
//
for (itr = m_Pool.begin(); itr != m_Pool.end(); ++itr)
{
if ( itr.value()->isFinished() == false )
{
return false;
};
};
};
//
return true;
}
int AdvThreadPool::getTaskQueueSize() const
{
int i_queue_size = 0;
//
QMutexLocker locker (&m_TaskLocker);
i_queue_size = m_TaskQueue.size();
//
return i_queue_size;
}
void AdvThreadPool::addJobToQueue (AdvThreadJob* ptr_job)
{
QMutexLocker locker (&m_TaskLocker);
//
if (en_FIFO == m_enPoolMode)
{
m_TaskQueue.enqueue(ptr_job);
}else // in this case we are basing on the priority, not FIFO.
{
int i_insertion_position = -1;
for (int i = 0; i< m_TaskQueue.size(); i++)
{
AdvThreadJob* ptr_queue_job = m_TaskQueue.at(i);
//
const QThread::Priority queue_prio = ptr_queue_job->getPriority();
const QThread::Priority job_prio = ptr_job->getPriority();
//
if ( queue_prio < job_prio )
{
i_insertion_position = i;
break;
};
}
if (i_insertion_position != -1)
m_TaskQueue.insert(i_insertion_position, ptr_job);
else
m_TaskQueue.enqueue(ptr_job);
};
}
AdvThreadJob* AdvThreadPool::extractNextJob ()
{
QMutexLocker locker (&m_TaskLocker);
//
AdvThreadJob* ptr_job = NULL;
//
if (m_TaskQueue.size() > 0)
ptr_job = m_TaskQueue.dequeue();
//
return ptr_job;
}
AdvThread* AdvThreadPool::getAvailableThread ()
{
AdvThread* ptr_available_thread = NULL;
QMutexLocker thread_locker (&m_PoolLocker);
//
ThreadMap::Iterator itr;
for (itr = m_Pool.begin(); itr != m_Pool.end(); ++itr)
{
if ( itr.value()->isFinished() )
{
ptr_available_thread = itr.value();
break;
};
};
//
return ptr_available_thread;
}
/*
this is old version, but I will remove it later
*/
void AdvThreadPool::onStandardFinish ()
{
//QMutexLocker locker (&m_PoolLocker);
//
/*
QObject* ptr_sender = QObject::sender();
std::cout<<"finish triggered, queuse size:"<<getTaskQueueSize()<<std::endl;
AdvThreadJob* ptr_job = NULL;
//
if (getTaskQueueSize() > 0)
{
AdvThread* ptr_thread = AdvThreadPool::getAvailableThread ();
ptr_job = extractNextJob();
//
if (ptr_thread)
{
ptr_thread->setJob(ptr_job);
ptr_thread->start( ptr_job->getPriority() );
};
*/
/*
ThreadMap::const_iterator i = m_Pool.constBegin();
//
while (i != m_Pool.constEnd())
{
bool b_isfinished = i.value()->isFinished();
bool b_isrunning = i.value()->isRunning();
//
if ( i.value()->isFinished() )
{
ptr_job = extractNextJob();
i.value()->setJob(ptr_job);
i.value()->start( ptr_job->getPriority() );
};
++i;
};
};
*/
//
return;
}
void AdvThreadPool::onCheckFinish ()
{
QObject* ptr_sender = QObject::sender();
std::cout<<"finish triggered, queuse size:"<<getTaskQueueSize()<<std::endl;
AdvThreadJob* ptr_job = NULL;
//
if (getTaskQueueSize() > 0)
{
AdvThread* ptr_thread = AdvThreadPool::getAvailableThread ();
ptr_job = extractNextJob();
//
if (ptr_thread)
{
ptr_thread->setJob(ptr_job);
ptr_thread->start( ptr_job->getPriority() );
};
};
//
return;
}
AdvThread* AdvThreadPool::createReservedThread ()
{
QMutexLocker thread_locker (&m_PoolLocker);
//
AdvThread* ptr_thread = NULL;
if ((unsigned int) m_Pool.size() < m_uiMaxThreadNumber) // is it possible to create new one?
{
const unsigned int ui_id = ++m_uiUniquer;
ptr_thread = new AdvThread(ui_id);
QObject::connect(ptr_thread, SIGNAL(th_finished()), this, SLOT(onCheckFinish() ));
//
m_Pool[ui_id] = ptr_thread;
};
//
return ptr_thread;
}
|
16ac4105b5f87862b1c26d6ba14f1c80cc2fca28
|
600df3590cce1fe49b9a96e9ca5b5242884a2a70
|
/third_party/pdfium/xfa/fwl/lightwidget/cfwl_pushbutton.cpp
|
b1031692ddd058b3c6ec01e38e6696a314b63ccb
|
[
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
metux/chromium-suckless
|
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
|
72a05af97787001756bae2511b7985e61498c965
|
refs/heads/orig
| 2022-12-04T23:53:58.681218
| 2017-04-30T10:59:06
| 2017-04-30T23:35:58
| 89,884,931
| 5
| 3
|
BSD-3-Clause
| 2022-11-23T20:52:53
| 2017-05-01T00:09:08
| null |
UTF-8
|
C++
| false
| false
| 2,031
|
cpp
|
cfwl_pushbutton.cpp
|
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fwl/lightwidget/cfwl_pushbutton.h"
#include <memory>
IFWL_PushButton* CFWL_PushButton::GetWidget() {
return static_cast<IFWL_PushButton*>(m_pIface.get());
}
const IFWL_PushButton* CFWL_PushButton::GetWidget() const {
return static_cast<IFWL_PushButton*>(m_pIface.get());
}
CFWL_PushButton* CFWL_PushButton::Create() {
return new CFWL_PushButton;
}
FWL_Error CFWL_PushButton::Initialize(
const CFWL_WidgetProperties* pProperties) {
if (m_pIface)
return FWL_Error::Indefinite;
if (pProperties) {
*m_pProperties = *pProperties;
}
std::unique_ptr<IFWL_PushButton> pPushButton(IFWL_PushButton::Create(
m_pProperties->MakeWidgetImpProperties(&m_buttonData), nullptr));
FWL_Error ret = pPushButton->Initialize();
if (ret != FWL_Error::Succeeded) {
return ret;
}
m_pIface = std::move(pPushButton);
CFWL_Widget::Initialize();
return FWL_Error::Succeeded;
}
FWL_Error CFWL_PushButton::GetCaption(CFX_WideString& wsCaption) {
wsCaption = m_buttonData.m_wsCaption;
return FWL_Error::Succeeded;
}
FWL_Error CFWL_PushButton::SetCaption(const CFX_WideStringC& wsCaption) {
m_buttonData.m_wsCaption = wsCaption;
return FWL_Error::Succeeded;
}
CFX_DIBitmap* CFWL_PushButton::GetPicture() {
return m_buttonData.m_pBitmap;
}
FWL_Error CFWL_PushButton::SetPicture(CFX_DIBitmap* pBitmap) {
m_buttonData.m_pBitmap = pBitmap;
return FWL_Error::Succeeded;
}
CFWL_PushButton::CFWL_PushButton() {}
CFWL_PushButton::~CFWL_PushButton() {}
FWL_Error CFWL_PushButton::CFWL_PushButtonDP::GetCaption(
IFWL_Widget* pWidget,
CFX_WideString& wsCaption) {
wsCaption = m_wsCaption;
return FWL_Error::Succeeded;
}
CFX_DIBitmap* CFWL_PushButton::CFWL_PushButtonDP::GetPicture(
IFWL_Widget* pWidget) {
return m_pBitmap;
}
|
4bc5c157297d538b5e32aae218a892186649e172
|
d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3
|
/chromium/ui/aura/mus/gesture_synchronizer_unittest.cc
|
81b75132a55781c8094f7da03a87d407e99cefbe
|
[
"BSD-3-Clause"
] |
permissive
|
Csineneo/Vivaldi
|
4eaad20fc0ff306ca60b400cd5fad930a9082087
|
d92465f71fb8e4345e27bd889532339204b26f1e
|
refs/heads/master
| 2022-11-23T17:11:50.714160
| 2019-05-25T11:45:11
| 2019-05-25T11:45:11
| 144,489,531
| 5
| 4
|
BSD-3-Clause
| 2022-11-04T05:55:33
| 2018-08-12T18:04:37
| null |
UTF-8
|
C++
| false
| false
| 3,515
|
cc
|
gesture_synchronizer_unittest.cc
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/aura/mus/gesture_synchronizer.h"
#include <memory>
#include "ui/aura/env.h"
#include "ui/aura/mus/window_mus.h"
#include "ui/aura/mus/window_tree_host_mus.h"
#include "ui/aura/mus/window_tree_host_mus_init_params.h"
#include "ui/aura/test/aura_mus_test_base.h"
#include "ui/aura/test/mus/test_window_tree.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/test/test_windows.h"
#include "ui/events/test/event_generator.h"
namespace aura {
class GestureSynchronizerTest : public test::AuraMusClientTestBase {
public:
GestureSynchronizerTest() = default;
~GestureSynchronizerTest() override = default;
protected:
ui::GestureRecognizer* gesture_recognizer() {
return Env::GetInstance()->gesture_recognizer();
}
std::unique_ptr<Window> NewWindow(aura::WindowDelegate* delegate = nullptr) {
return std::unique_ptr<Window>(aura::test::CreateTestWindowWithDelegate(
delegate, 0, gfx::Rect(0, 0, 100, 100), root_window()));
}
private:
DISALLOW_COPY_AND_ASSIGN(GestureSynchronizerTest);
};
TEST_F(GestureSynchronizerTest, CancelActiveTouchesExcept) {
std::unique_ptr<Window> window = NewWindow();
gesture_recognizer()->CancelActiveTouchesExcept(window.get());
EXPECT_EQ(window_tree()->last_not_cancelled_window_id(),
WindowMus::Get(window.get())->server_id());
}
TEST_F(GestureSynchronizerTest, CancelActiveTouchesExceptForNullptr) {
gesture_recognizer()->CancelActiveTouchesExcept(nullptr);
EXPECT_EQ(window_tree()->last_not_cancelled_window_id(), kInvalidServerId);
}
TEST_F(GestureSynchronizerTest, CancelActiveTouches) {
aura::test::TestWindowDelegate delegate;
std::unique_ptr<Window> window = NewWindow(&delegate);
ui::test::EventGenerator event_generator(root_window());
event_generator.MoveTouch(window->GetBoundsInScreen().CenterPoint());
event_generator.PressTouch();
gesture_recognizer()->CancelActiveTouches(window.get());
EXPECT_EQ(window_tree()->last_cancelled_window_id(),
WindowMus::Get(window.get())->server_id());
}
TEST_F(GestureSynchronizerTest, CancelActiveTouchesNotSentWithoutTouches) {
aura::test::TestWindowDelegate delegate;
std::unique_ptr<Window> window = NewWindow(&delegate);
gesture_recognizer()->CancelActiveTouches(window.get());
EXPECT_EQ(window_tree()->last_cancelled_window_id(), 0u);
}
TEST_F(GestureSynchronizerTest, TransferGestureEventsTo) {
std::unique_ptr<Window> window1 = NewWindow();
std::unique_ptr<Window> window2 = NewWindow();
gesture_recognizer()->TransferEventsTo(window1.get(), window2.get(),
ui::TransferTouchesBehavior::kCancel);
EXPECT_EQ(window_tree()->last_transfer_current(),
WindowMus::Get(window1.get())->server_id());
EXPECT_EQ(window_tree()->last_transfer_new(),
WindowMus::Get(window2.get())->server_id());
EXPECT_TRUE(window_tree()->last_transfer_should_cancel());
gesture_recognizer()->TransferEventsTo(
window2.get(), window1.get(), ui::TransferTouchesBehavior::kDontCancel);
EXPECT_EQ(window_tree()->last_transfer_current(),
WindowMus::Get(window2.get())->server_id());
EXPECT_EQ(window_tree()->last_transfer_new(),
WindowMus::Get(window1.get())->server_id());
EXPECT_FALSE(window_tree()->last_transfer_should_cancel());
}
} // namespace aura
|
43fc51bc836a049929cb10ad870320382e764ca7
|
9fad4848e43f4487730185e4f50e05a044f865ab
|
/src/sync/internal_api/shared_model_type_processor_unittest.cc
|
b8da285f1545a56caba0042157ef6b5d3e29fe64
|
[
"BSD-3-Clause"
] |
permissive
|
dummas2008/chromium
|
d1b30da64f0630823cb97f58ec82825998dbb93e
|
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
|
refs/heads/master
| 2020-12-31T07:18:45.026190
| 2016-04-14T03:17:45
| 2016-04-14T03:17:45
| 56,194,439
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 48,547
|
cc
|
shared_model_type_processor_unittest.cc
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sync/internal_api/public/shared_model_type_processor.h"
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "sync/api/fake_model_type_service.h"
#include "sync/engine/commit_queue.h"
#include "sync/internal_api/public/activation_context.h"
#include "sync/internal_api/public/base/model_type.h"
#include "sync/internal_api/public/data_batch_impl.h"
#include "sync/internal_api/public/non_blocking_sync_common.h"
#include "sync/internal_api/public/simple_metadata_change_list.h"
#include "sync/protocol/data_type_state.pb.h"
#include "sync/protocol/sync.pb.h"
#include "sync/syncable/syncable_util.h"
#include "sync/test/engine/mock_commit_queue.h"
#include "sync/util/time.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace syncer_v2 {
static const syncer::ModelType kModelType = syncer::PREFERENCES;
namespace {
const std::string kTag1 = "tag1";
const std::string kTag2 = "tag2";
const std::string kTag3 = "tag3";
const std::string kValue1 = "value1";
const std::string kValue2 = "value2";
const std::string kValue3 = "value3";
std::string GenerateTagHash(const std::string& tag) {
return syncer::syncable::GenerateSyncableHash(kModelType, tag);
}
sync_pb::EntitySpecifics GenerateSpecifics(const std::string& tag,
const std::string& value) {
sync_pb::EntitySpecifics specifics;
specifics.mutable_preference()->set_name(tag);
specifics.mutable_preference()->set_value(value);
return specifics;
}
std::unique_ptr<EntityData> GenerateEntityData(const std::string& tag,
const std::string& value) {
std::unique_ptr<EntityData> entity_data = base::WrapUnique(new EntityData());
entity_data->client_tag_hash = GenerateTagHash(tag);
entity_data->specifics = GenerateSpecifics(tag, value);
entity_data->non_unique_name = tag;
return entity_data;
}
// It is intentionally very difficult to copy an EntityData, as in normal code
// we never want to. However, since we store the data as an EntityData for the
// test code here, this function is needed to manually copy it.
std::unique_ptr<EntityData> CopyEntityData(const EntityData& old_data) {
std::unique_ptr<EntityData> new_data(new EntityData());
new_data->id = old_data.id;
new_data->client_tag_hash = old_data.client_tag_hash;
new_data->non_unique_name = old_data.non_unique_name;
new_data->specifics = old_data.specifics;
new_data->creation_time = old_data.creation_time;
new_data->modification_time = old_data.modification_time;
return new_data;
}
// A basic in-memory storage mechanism for data and metadata. This makes it
// easier to test more complex behaviors involving when entities are written,
// committed, etc. Having a separate class helps keep the main one cleaner.
class SimpleStore {
public:
void PutData(const std::string& tag, const EntityData& data) {
data_change_count_++;
data_store_[tag] = CopyEntityData(data);
}
void PutMetadata(const std::string& tag,
const sync_pb::EntityMetadata& metadata) {
metadata_change_count_++;
metadata_store_[tag] = metadata;
}
void RemoveData(const std::string& tag) {
data_change_count_++;
data_store_.erase(tag);
}
void RemoveMetadata(const std::string& tag) {
metadata_change_count_++;
metadata_store_.erase(tag);
}
bool HasData(const std::string& tag) const {
return data_store_.find(tag) != data_store_.end();
}
bool HasMetadata(const std::string& tag) const {
return metadata_store_.find(tag) != metadata_store_.end();
}
const std::map<std::string, std::unique_ptr<EntityData>>& GetAllData() const {
return data_store_;
}
const EntityData& GetData(const std::string& tag) const {
return *data_store_.find(tag)->second;
}
const std::string& GetValue(const std::string& tag) const {
return GetData(tag).specifics.preference().value();
}
const sync_pb::EntityMetadata& GetMetadata(const std::string& tag) const {
return metadata_store_.find(tag)->second;
}
size_t DataCount() const { return data_store_.size(); }
size_t MetadataCount() const { return metadata_store_.size(); }
size_t DataChangeCount() const { return data_change_count_; }
size_t MetadataChangeCount() const { return metadata_change_count_; }
const sync_pb::DataTypeState& data_type_state() const {
return data_type_state_;
}
void set_data_type_state(const sync_pb::DataTypeState& data_type_state) {
data_type_state_ = data_type_state;
}
std::unique_ptr<MetadataBatch> CreateMetadataBatch() const {
std::unique_ptr<MetadataBatch> metadata_batch(new MetadataBatch());
metadata_batch->SetDataTypeState(data_type_state_);
for (auto it = metadata_store_.begin(); it != metadata_store_.end(); it++) {
metadata_batch->AddMetadata(it->first, it->second);
}
return metadata_batch;
}
void Reset() {
data_change_count_ = 0;
metadata_change_count_ = 0;
data_store_.clear();
metadata_store_.clear();
data_type_state_.Clear();
}
private:
size_t data_change_count_ = 0;
size_t metadata_change_count_ = 0;
std::map<std::string, std::unique_ptr<EntityData>> data_store_;
std::map<std::string, sync_pb::EntityMetadata> metadata_store_;
sync_pb::DataTypeState data_type_state_;
};
} // namespace
// Tests the various functionality of SharedModelTypeProcessor.
//
// The processor sits between the service (implemented by this test class) and
// the worker, which is represented as a commit queue (MockCommitQueue). This
// test suite exercises the initialization flows (whether initial sync is done,
// performing the initial merge, etc) as well as normal functionality:
//
// - Initialization before the initial sync and merge correctly performs a merge
// and initializes the metadata in storage.
// - Initialization after the initial sync correctly loads metadata and queues
// any pending commits.
// - Put and Delete calls from the service result in the correct metadata in
// storage and the correct commit requests on the worker side.
// - Updates and commit responses from the worker correctly affect data and
// metadata in storage on the service side.
class SharedModelTypeProcessorTest : public ::testing::Test,
public FakeModelTypeService {
public:
SharedModelTypeProcessorTest()
: FakeModelTypeService(
base::Bind(&SharedModelTypeProcessor::CreateAsChangeProcessor)) {}
~SharedModelTypeProcessorTest() override {}
void InitializeToMetadataLoaded() {
CreateChangeProcessor();
sync_pb::DataTypeState data_type_state(db_.data_type_state());
data_type_state.set_initial_sync_done(true);
db_.set_data_type_state(data_type_state);
OnMetadataLoaded();
}
// Initialize to a "ready-to-commit" state.
void InitializeToReadyState() {
InitializeToMetadataLoaded();
OnDataLoaded();
OnSyncStarting();
}
void OnMetadataLoaded() {
type_processor()->OnMetadataLoaded(db_.CreateMetadataBatch());
}
void OnDataLoaded() {
if (!data_callback_.is_null()) {
data_callback_.Run();
data_callback_.Reset();
}
}
void OnSyncStarting() {
type_processor()->OnSyncStarting(
base::Bind(&SharedModelTypeProcessorTest::OnReadyToConnect,
base::Unretained(this)));
}
void DisconnectSync() {
type_processor()->DisconnectSync();
mock_queue_ = nullptr;
}
// Local data modification. Emulates signals from the model thread.
void WriteItem(const std::string& tag, const std::string& value) {
WriteItem(tag, GenerateEntityData(tag, value));
}
// Overloaded form to allow passing of custom entity data.
void WriteItem(const std::string& tag,
std::unique_ptr<EntityData> entity_data) {
db_.PutData(tag, *entity_data);
if (type_processor()) {
std::unique_ptr<MetadataChangeList> change_list(
new SimpleMetadataChangeList());
type_processor()->Put(tag, std::move(entity_data), change_list.get());
ApplyMetadataChangeList(std::move(change_list));
}
}
// Writes data for |tag| and simulates a commit response for it.
void WriteItemAndAck(const std::string& tag, const std::string& value) {
WriteItem(tag, value);
ASSERT_TRUE(HasCommitRequestForTag(tag));
SuccessfulCommitResponse(GetLatestCommitRequestForTag(tag));
}
void DeleteItem(const std::string& tag) {
db_.RemoveData(tag);
if (type_processor()) {
std::unique_ptr<MetadataChangeList> change_list(
new SimpleMetadataChangeList());
type_processor()->Delete(tag, change_list.get());
ApplyMetadataChangeList(std::move(change_list));
}
}
// Wipes existing DB and simulates one commited item.
void ResetStateWriteAckedItem(const std::string& tag,
const std::string& value) {
clear_change_processor();
db_.Reset();
InitializeToReadyState();
EXPECT_EQ(0U, ProcessorEntityCount());
WriteItemAndAck(tag, "acked-value");
WriteItem(tag, value);
EXPECT_EQ(1U, ProcessorEntityCount());
clear_change_processor();
}
// Wipes existing DB and simulates one uncommited item.
void ResetStateWriteItem(const std::string& tag, const std::string& value) {
clear_change_processor();
db_.Reset();
InitializeToReadyState();
EXPECT_EQ(0U, ProcessorEntityCount());
WriteItem(tag, value);
EXPECT_EQ(1U, ProcessorEntityCount());
clear_change_processor();
}
// Wipes existing DB and simulates one uncommited deletion.
void ResetStateDeleteItem(const std::string& tag, const std::string& value) {
clear_change_processor();
db_.Reset();
InitializeToReadyState();
EXPECT_EQ(0U, ProcessorEntityCount());
WriteItemAndAck(tag, value);
EXPECT_EQ(1U, ProcessorEntityCount());
DeleteItem(tag);
EXPECT_EQ(1U, ProcessorEntityCount());
clear_change_processor();
}
// Simulates an initial GetUpdates response from the worker with |updates|.
void OnInitialSyncDone(UpdateResponseDataList updates) {
sync_pb::DataTypeState data_type_state(db_.data_type_state());
data_type_state.set_initial_sync_done(true);
type_processor()->OnUpdateReceived(data_type_state, updates);
}
// Overloaded form with no updates.
void OnInitialSyncDone() { OnInitialSyncDone(UpdateResponseDataList()); }
// Overloaded form that constructs an update for a single entity.
void OnInitialSyncDone(const std::string& tag, const std::string& value) {
UpdateResponseDataList updates;
UpdateResponseData update;
update.entity = GenerateEntityData(tag, value)->PassToPtr();
updates.push_back(update);
OnInitialSyncDone(updates);
}
// Emulate updates from the server.
// This harness has some functionality to help emulate server behavior.
void UpdateFromServer(int64_t version_offset,
const std::string& tag,
const std::string& value) {
const std::string tag_hash = GenerateTagHash(tag);
UpdateResponseData data = mock_queue_->UpdateFromServer(
version_offset, tag_hash, GenerateSpecifics(tag, value));
UpdateResponseDataList list;
list.push_back(data);
type_processor()->OnUpdateReceived(db_.data_type_state(), list);
}
void TombstoneFromServer(int64_t version_offset, const std::string& tag) {
// Overwrite the existing server version if this is the new highest version.
std::string tag_hash = GenerateTagHash(tag);
UpdateResponseData data =
mock_queue_->TombstoneFromServer(version_offset, tag_hash);
UpdateResponseDataList list;
list.push_back(data);
type_processor()->OnUpdateReceived(db_.data_type_state(), list);
}
// Read emitted commit requests as batches.
size_t GetNumCommitRequestLists() {
DCHECK(mock_queue_);
return mock_queue_->GetNumCommitRequestLists();
}
CommitRequestDataList GetNthCommitRequestList(size_t n) {
return mock_queue_->GetNthCommitRequestList(n);
}
// Read emitted commit requests by tag, most recent only.
bool HasCommitRequestForTag(const std::string& tag) {
const std::string tag_hash = GenerateTagHash(tag);
return mock_queue_->HasCommitRequestForTagHash(tag_hash);
}
CommitRequestData GetLatestCommitRequestForTag(const std::string& tag) {
const std::string tag_hash = GenerateTagHash(tag);
return mock_queue_->GetLatestCommitRequestForTagHash(tag_hash);
}
// Sends the type sync proxy a successful commit response.
void SuccessfulCommitResponse(const CommitRequestData& request_data) {
CommitResponseDataList list;
list.push_back(mock_queue_->SuccessfulCommitResponse(request_data));
type_processor()->OnCommitCompleted(db_.data_type_state(), list);
}
// Sends the type sync proxy an updated DataTypeState to let it know that
// the desired encryption key has changed.
void UpdateDesiredEncryptionKey(const std::string& key_name) {
sync_pb::DataTypeState data_type_state(db_.data_type_state());
data_type_state.set_encryption_key_name(key_name);
type_processor()->OnUpdateReceived(data_type_state,
UpdateResponseDataList());
}
// Sets the key_name that the mock CommitQueue will claim is in use
// when receiving items.
void SetServerEncryptionKey(const std::string& key_name) {
mock_queue_->SetServerEncryptionKey(key_name);
}
// Return the number of entities the processor has metadata for.
size_t ProcessorEntityCount() const {
DCHECK(type_processor());
return type_processor()->entities_.size();
}
// Expect that the |n|th commit request list has one commit request for |tag|
// with |value| set.
void ExpectNthCommitRequestList(size_t n,
const std::string& tag,
const std::string& value) {
const CommitRequestDataList& list = GetNthCommitRequestList(n);
ASSERT_EQ(1U, list.size());
const EntityData& data = list[0].entity.value();
EXPECT_EQ(GenerateTagHash(tag), data.client_tag_hash);
EXPECT_EQ(value, data.specifics.preference().value());
}
// For each tag in |tags|, expect a corresponding request list of length one.
void ExpectCommitRequests(const std::vector<std::string>& tags) {
EXPECT_EQ(tags.size(), GetNumCommitRequestLists());
for (size_t i = 0; i < tags.size(); i++) {
const CommitRequestDataList& commits = GetNthCommitRequestList(i);
EXPECT_EQ(1U, commits.size());
EXPECT_EQ(GenerateTagHash(tags[i]), commits[0].entity->client_tag_hash);
}
}
// Store a resolution for the next call to ResolveConflict. Note that if this
// is a USE_NEW resolution, the data will only exist for one resolve call.
void SetConflictResolution(ConflictResolution resolution) {
conflict_resolution_.reset(new ConflictResolution(std::move(resolution)));
}
const SimpleStore& db() const { return db_; }
MockCommitQueue* mock_queue() { return mock_queue_; }
SharedModelTypeProcessor* type_processor() const {
return static_cast<SharedModelTypeProcessor*>(change_processor());
}
private:
void OnReadyToConnect(syncer::SyncError error,
std::unique_ptr<ActivationContext> context) {
std::unique_ptr<MockCommitQueue> commit_queue(new MockCommitQueue());
// Keep an unsafe pointer to the commit queue the processor will use.
mock_queue_ = commit_queue.get();
context->type_processor->ConnectSync(std::move(commit_queue));
// The context's type processor is a proxy; run the task it posted.
sync_loop_.RunUntilIdle();
}
// FakeModelTypeService overrides.
std::string GetClientTag(const EntityData& entity_data) override {
// The tag is the preference name - see GenerateSpecifics.
return entity_data.specifics.preference().name();
}
std::unique_ptr<MetadataChangeList> CreateMetadataChangeList() override {
return std::unique_ptr<MetadataChangeList>(new SimpleMetadataChangeList());
}
syncer::SyncError MergeSyncData(
std::unique_ptr<MetadataChangeList> metadata_changes,
EntityDataMap data_map) override {
// Commit any local entities that aren't being overwritten by the server.
const auto& local_data = db_.GetAllData();
for (auto it = local_data.begin(); it != local_data.end(); it++) {
if (data_map.find(it->first) == data_map.end()) {
type_processor()->Put(it->first, CopyEntityData(*it->second),
metadata_changes.get());
}
}
// Store any new remote entities.
for (auto it = data_map.begin(); it != data_map.end(); it++) {
db_.PutData(it->first, it->second.value());
}
ApplyMetadataChangeList(std::move(metadata_changes));
return syncer::SyncError();
}
syncer::SyncError ApplySyncChanges(
std::unique_ptr<MetadataChangeList> metadata_changes,
EntityChangeList entity_changes) override {
for (const EntityChange& change : entity_changes) {
switch (change.type()) {
case EntityChange::ACTION_ADD:
EXPECT_FALSE(db_.HasData(change.client_tag()));
db_.PutData(change.client_tag(), change.data());
break;
case EntityChange::ACTION_UPDATE:
EXPECT_TRUE(db_.HasData(change.client_tag()));
db_.PutData(change.client_tag(), change.data());
break;
case EntityChange::ACTION_DELETE:
EXPECT_TRUE(db_.HasData(change.client_tag()));
db_.RemoveData(change.client_tag());
break;
}
}
ApplyMetadataChangeList(std::move(metadata_changes));
return syncer::SyncError();
}
void ApplyMetadataChangeList(
std::unique_ptr<MetadataChangeList> change_list) {
DCHECK(change_list);
SimpleMetadataChangeList* changes =
static_cast<SimpleMetadataChangeList*>(change_list.get());
const auto& metadata_changes = changes->GetMetadataChanges();
for (auto it = metadata_changes.begin(); it != metadata_changes.end();
it++) {
switch (it->second.type) {
case SimpleMetadataChangeList::UPDATE:
db_.PutMetadata(it->first, it->second.metadata);
break;
case SimpleMetadataChangeList::CLEAR:
EXPECT_TRUE(db_.HasMetadata(it->first));
db_.RemoveMetadata(it->first);
break;
}
}
if (changes->HasDataTypeStateChange()) {
const SimpleMetadataChangeList::DataTypeStateChange& state_change =
changes->GetDataTypeStateChange();
switch (state_change.type) {
case SimpleMetadataChangeList::UPDATE:
db_.set_data_type_state(state_change.state);
break;
case SimpleMetadataChangeList::CLEAR:
db_.set_data_type_state(sync_pb::DataTypeState());
break;
}
}
}
void GetData(ClientTagList tags, DataCallback callback) override {
std::unique_ptr<DataBatchImpl> batch(new DataBatchImpl());
for (const std::string& tag : tags) {
batch->Put(tag, CopyEntityData(db_.GetData(tag)));
}
data_callback_ =
base::Bind(callback, syncer::SyncError(), base::Passed(&batch));
}
ConflictResolution ResolveConflict(
const EntityData& local_data,
const EntityData& remote_data) const override {
DCHECK(conflict_resolution_);
return std::move(*conflict_resolution_);
}
std::unique_ptr<ConflictResolution> conflict_resolution_;
// This sets ThreadTaskRunnerHandle on the current thread, which the type
// processor will pick up as the sync task runner.
base::MessageLoop sync_loop_;
// The current mock queue, which is owned by |type_processor()|.
MockCommitQueue* mock_queue_;
// Stores the data callback between GetData() and OnDataLoaded().
base::Closure data_callback_;
// Contains all of the data and metadata state for these tests.
SimpleStore db_;
};
// Test that an initial sync handles local and remote items properly.
TEST_F(SharedModelTypeProcessorTest, InitialSync) {
CreateChangeProcessor();
OnMetadataLoaded();
OnSyncStarting();
// Local write before initial sync.
WriteItem(kTag1, kValue1);
// Has data, but no metadata, entity in the processor, or commit request.
EXPECT_EQ(1U, db().DataCount());
EXPECT_EQ(0U, db().MetadataCount());
EXPECT_EQ(0U, ProcessorEntityCount());
EXPECT_EQ(0U, GetNumCommitRequestLists());
// Initial sync with one server item.
OnInitialSyncDone(kTag2, kValue2);
// Now have data and metadata for both items, as well as a commit request for
// the local item.
EXPECT_EQ(2U, db().DataCount());
EXPECT_EQ(2U, db().MetadataCount());
EXPECT_EQ(2U, ProcessorEntityCount());
EXPECT_EQ(1, db().GetMetadata(kTag1).sequence_number());
EXPECT_EQ(0, db().GetMetadata(kTag2).sequence_number());
ExpectCommitRequests({kTag1});
}
// This test covers race conditions during loading pending data. All cases
// start with no processor and one acked (committed to the server) item with a
// pending commit. There are three different events that can occur in any order
// once metadata is loaded:
//
// - Pending commit data is loaded.
// - Sync gets connected.
// - Optionally, a put or delete happens to the item.
//
// This results in 2 + 12 = 14 orderings of the events.
TEST_F(SharedModelTypeProcessorTest, LoadPendingCommit) {
// Data, connect.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnDataLoaded();
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue1);
// Connect, data.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnSyncStarting();
EXPECT_EQ(0U, GetNumCommitRequestLists());
OnDataLoaded();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue1);
// Data, connect, put.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnDataLoaded();
OnSyncStarting();
WriteItem(kTag1, kValue2);
EXPECT_EQ(2U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue1);
ExpectNthCommitRequestList(1, kTag1, kValue2);
// Data, put, connect.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnDataLoaded();
WriteItem(kTag1, kValue2);
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue2);
// Connect, data, put.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnSyncStarting();
OnDataLoaded();
WriteItem(kTag1, kValue2);
EXPECT_EQ(2U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue1);
ExpectNthCommitRequestList(1, kTag1, kValue2);
// Connect, put, data.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnSyncStarting();
WriteItem(kTag1, kValue2);
EXPECT_EQ(0U, GetNumCommitRequestLists());
OnDataLoaded();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue2);
// Put, data, connect.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
WriteItem(kTag1, kValue2);
OnDataLoaded();
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue2);
// Put, connect, data.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
WriteItem(kTag1, kValue2);
OnSyncStarting();
EXPECT_EQ(0U, GetNumCommitRequestLists());
OnDataLoaded();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue2);
// Data, connect, delete.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnDataLoaded();
OnSyncStarting();
DeleteItem(kTag1);
EXPECT_EQ(2U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue1);
ExpectNthCommitRequestList(1, kTag1, "");
// Data, delete, connect.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnDataLoaded();
DeleteItem(kTag1);
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, "");
// Connect, data, delete.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnSyncStarting();
OnDataLoaded();
DeleteItem(kTag1);
EXPECT_EQ(2U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue1);
ExpectNthCommitRequestList(1, kTag1, "");
// Connect, delete, data.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnSyncStarting();
DeleteItem(kTag1);
EXPECT_EQ(0U, GetNumCommitRequestLists());
OnDataLoaded();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, "");
// Delete, data, connect.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
DeleteItem(kTag1);
OnDataLoaded();
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, "");
// Delete, connect, data.
ResetStateWriteAckedItem(kTag1, kValue1);
InitializeToMetadataLoaded();
DeleteItem(kTag1);
OnSyncStarting();
EXPECT_EQ(0U, GetNumCommitRequestLists());
OnDataLoaded();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, "");
}
// This test covers race conditions during loading a pending delete. All cases
// start with no processor and one item with a pending delete. There are two
// different events that can occur in any order once metadata is loaded, since
// for a deletion there is no data to load:
//
// - Sync gets connected.
// - Optionally, a put or delete happens to the item (repeated deletes should be
// handled properly).
//
// This results in 1 + 4 = 5 orderings of the events.
TEST_F(SharedModelTypeProcessorTest, LoadPendingDelete) {
// Connect.
ResetStateDeleteItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, "");
// Connect, put.
ResetStateDeleteItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
WriteItem(kTag1, kValue2);
EXPECT_EQ(2U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, "");
ExpectNthCommitRequestList(1, kTag1, kValue2);
// Put, connect.
ResetStateDeleteItem(kTag1, kValue1);
InitializeToMetadataLoaded();
WriteItem(kTag1, kValue2);
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, kValue2);
// Connect, delete.
ResetStateDeleteItem(kTag1, kValue1);
InitializeToMetadataLoaded();
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
DeleteItem(kTag1);
EXPECT_EQ(2U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, "");
ExpectNthCommitRequestList(1, kTag1, "");
// Delete, connect.
ResetStateDeleteItem(kTag1, kValue1);
InitializeToMetadataLoaded();
DeleteItem(kTag1);
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
ExpectNthCommitRequestList(0, kTag1, "");
}
// Test that loading a committed item does not queue another commit.
TEST_F(SharedModelTypeProcessorTest, LoadCommited) {
InitializeToReadyState();
WriteItemAndAck(kTag1, kValue1);
clear_change_processor();
// Test that a new processor loads the metadata without committing.
InitializeToReadyState();
EXPECT_EQ(1U, ProcessorEntityCount());
EXPECT_EQ(0U, GetNumCommitRequestLists());
}
// Creates a new item locally.
// Thoroughly tests the data generated by a local item creation.
TEST_F(SharedModelTypeProcessorTest, LocalCreateItem) {
InitializeToReadyState();
EXPECT_EQ(0U, GetNumCommitRequestLists());
WriteItem(kTag1, kValue1);
// Verify the commit request this operation has triggered.
ExpectCommitRequests({kTag1});
const CommitRequestData& tag1_request_data =
GetLatestCommitRequestForTag(kTag1);
const EntityData& tag1_data = tag1_request_data.entity.value();
EXPECT_EQ(kUncommittedVersion, tag1_request_data.base_version);
EXPECT_TRUE(tag1_data.id.empty());
EXPECT_FALSE(tag1_data.creation_time.is_null());
EXPECT_FALSE(tag1_data.modification_time.is_null());
EXPECT_EQ(kTag1, tag1_data.non_unique_name);
EXPECT_FALSE(tag1_data.is_deleted());
EXPECT_EQ(kTag1, tag1_data.specifics.preference().name());
EXPECT_EQ(kValue1, tag1_data.specifics.preference().value());
EXPECT_EQ(1U, db().MetadataCount());
const sync_pb::EntityMetadata metadata = db().GetMetadata(kTag1);
EXPECT_TRUE(metadata.has_client_tag_hash());
EXPECT_FALSE(metadata.has_server_id());
EXPECT_FALSE(metadata.is_deleted());
EXPECT_EQ(1, metadata.sequence_number());
EXPECT_EQ(0, metadata.acked_sequence_number());
EXPECT_EQ(kUncommittedVersion, metadata.server_version());
EXPECT_TRUE(metadata.has_creation_time());
EXPECT_TRUE(metadata.has_modification_time());
EXPECT_TRUE(metadata.has_specifics_hash());
}
// The purpose of this test case is to test setting |client_tag_hash| and |id|
// on the EntityData object as we pass it into the Put method of the processor.
TEST_F(SharedModelTypeProcessorTest, LocalUpdateItemWithOverrides) {
const std::string kId1 = "cid1";
const std::string kId2 = "cid2";
const std::string kName1 = "name1";
const std::string kName2 = "name2";
const std::string kHash = "hash";
InitializeToReadyState();
EXPECT_EQ(0U, GetNumCommitRequestLists());
std::unique_ptr<EntityData> entity_data = base::WrapUnique(new EntityData());
entity_data->specifics.mutable_preference()->set_name(kName1);
entity_data->specifics.mutable_preference()->set_value(kValue1);
entity_data->non_unique_name = kName1;
entity_data->client_tag_hash = kHash;
entity_data->id = kId1;
WriteItem(kTag1, std::move(entity_data));
EXPECT_EQ(1U, GetNumCommitRequestLists());
ASSERT_FALSE(mock_queue()->HasCommitRequestForTagHash(kHash));
ASSERT_TRUE(HasCommitRequestForTag(kTag1));
EXPECT_EQ(1U, db().MetadataCount());
const EntityData& out_entity1 =
GetLatestCommitRequestForTag(kTag1).entity.value();
const sync_pb::EntityMetadata metadata_v1 = db().GetMetadata(kTag1);
EXPECT_EQ(kId1, out_entity1.id);
EXPECT_NE(kHash, out_entity1.client_tag_hash);
EXPECT_EQ(kValue1, out_entity1.specifics.preference().value());
EXPECT_EQ(kId1, metadata_v1.server_id());
EXPECT_EQ(metadata_v1.client_tag_hash(), out_entity1.client_tag_hash);
entity_data.reset(new EntityData());
entity_data->specifics.mutable_preference()->set_name(kName2);
entity_data->specifics.mutable_preference()->set_value(kValue2);
entity_data->non_unique_name = kName2;
entity_data->client_tag_hash = kHash;
// Make sure ID isn't overwritten either.
entity_data->id = kId2;
WriteItem(kTag1, std::move(entity_data));
EXPECT_EQ(2U, GetNumCommitRequestLists());
ASSERT_FALSE(mock_queue()->HasCommitRequestForTagHash(kHash));
ASSERT_TRUE(HasCommitRequestForTag(kTag1));
EXPECT_EQ(1U, db().MetadataCount());
const EntityData& out_entity2 =
GetLatestCommitRequestForTag(kTag1).entity.value();
const sync_pb::EntityMetadata metadata_v2 = db().GetMetadata(kTag1);
EXPECT_EQ(kValue2, out_entity2.specifics.preference().value());
// Should still see old cid1 value, override is not respected on update.
EXPECT_EQ(kId1, out_entity2.id);
EXPECT_EQ(kId1, metadata_v2.server_id());
EXPECT_EQ(metadata_v2.client_tag_hash(), out_entity2.client_tag_hash);
// Specifics have changed so the hashes should not match.
EXPECT_NE(metadata_v1.specifics_hash(), metadata_v2.specifics_hash());
}
// Creates a new local item then modifies it.
// Thoroughly tests data generated by modification of server-unknown item.
TEST_F(SharedModelTypeProcessorTest, LocalUpdateItem) {
InitializeToReadyState();
WriteItem(kTag1, kValue1);
EXPECT_EQ(1U, db().MetadataCount());
ExpectCommitRequests({kTag1});
const CommitRequestData& request_data_v1 =
GetLatestCommitRequestForTag(kTag1);
const EntityData& data_v1 = request_data_v1.entity.value();
const sync_pb::EntityMetadata metadata_v1 = db().GetMetadata(kTag1);
WriteItem(kTag1, kValue2);
EXPECT_EQ(1U, db().MetadataCount());
ExpectCommitRequests({kTag1, kTag1});
const CommitRequestData& request_data_v2 =
GetLatestCommitRequestForTag(kTag1);
const EntityData& data_v2 = request_data_v2.entity.value();
const sync_pb::EntityMetadata metadata_v2 = db().GetMetadata(kTag1);
// Test some of the relations between old and new commit requests.
EXPECT_GT(request_data_v2.sequence_number, request_data_v1.sequence_number);
EXPECT_EQ(data_v1.specifics.preference().value(), kValue1);
// Perform a thorough examination of the update-generated request.
EXPECT_EQ(kUncommittedVersion, request_data_v2.base_version);
EXPECT_TRUE(data_v2.id.empty());
EXPECT_FALSE(data_v2.creation_time.is_null());
EXPECT_FALSE(data_v2.modification_time.is_null());
EXPECT_EQ(kTag1, data_v2.non_unique_name);
EXPECT_FALSE(data_v2.is_deleted());
EXPECT_EQ(kTag1, data_v2.specifics.preference().name());
EXPECT_EQ(kValue2, data_v2.specifics.preference().value());
EXPECT_FALSE(metadata_v1.has_server_id());
EXPECT_FALSE(metadata_v1.is_deleted());
EXPECT_EQ(1, metadata_v1.sequence_number());
EXPECT_EQ(0, metadata_v1.acked_sequence_number());
EXPECT_EQ(kUncommittedVersion, metadata_v1.server_version());
EXPECT_FALSE(metadata_v2.has_server_id());
EXPECT_FALSE(metadata_v2.is_deleted());
EXPECT_EQ(2, metadata_v2.sequence_number());
EXPECT_EQ(0, metadata_v2.acked_sequence_number());
EXPECT_EQ(kUncommittedVersion, metadata_v2.server_version());
EXPECT_EQ(metadata_v1.client_tag_hash(), metadata_v2.client_tag_hash());
EXPECT_NE(metadata_v1.specifics_hash(), metadata_v2.specifics_hash());
}
// Tests that a local update that doesn't change specifics doesn't generate a
// commit request.
TEST_F(SharedModelTypeProcessorTest, LocalUpdateItemRedundant) {
InitializeToReadyState();
WriteItem(kTag1, kValue1);
EXPECT_EQ(1U, db().MetadataCount());
ExpectCommitRequests({kTag1});
WriteItem(kTag1, kValue1);
ExpectCommitRequests({kTag1});
}
// Thoroughly tests the data generated by a server item creation.
TEST_F(SharedModelTypeProcessorTest, ServerCreateItem) {
InitializeToReadyState();
UpdateFromServer(5, kTag1, kValue1);
EXPECT_EQ(1U, db().DataCount());
EXPECT_EQ(1U, db().MetadataCount());
EXPECT_EQ(1U, ProcessorEntityCount());
EXPECT_EQ(0U, GetNumCommitRequestLists());
const EntityData& data = db().GetData(kTag1);
EXPECT_FALSE(data.id.empty());
EXPECT_EQ(kTag1, data.specifics.preference().name());
EXPECT_EQ(kValue1, data.specifics.preference().value());
EXPECT_FALSE(data.creation_time.is_null());
EXPECT_FALSE(data.modification_time.is_null());
EXPECT_EQ(kTag1, data.non_unique_name);
EXPECT_FALSE(data.is_deleted());
const sync_pb::EntityMetadata metadata = db().GetMetadata(kTag1);
EXPECT_TRUE(metadata.has_client_tag_hash());
EXPECT_TRUE(metadata.has_server_id());
EXPECT_FALSE(metadata.is_deleted());
EXPECT_EQ(0, metadata.sequence_number());
EXPECT_EQ(0, metadata.acked_sequence_number());
EXPECT_EQ(5, metadata.server_version());
EXPECT_TRUE(metadata.has_creation_time());
EXPECT_TRUE(metadata.has_modification_time());
EXPECT_TRUE(metadata.has_specifics_hash());
}
// Thoroughly tests the data generated by a server item creation.
TEST_F(SharedModelTypeProcessorTest, ServerUpdateItem) {
InitializeToReadyState();
// Local add writes data and metadata; ack writes metadata again.
WriteItemAndAck(kTag1, kValue1);
EXPECT_EQ(1U, db().DataChangeCount());
EXPECT_EQ(2U, db().MetadataChangeCount());
// Redundant update from server doesn't write data but updates metadata.
UpdateFromServer(5, kTag1, kValue1);
EXPECT_EQ(1U, db().DataChangeCount());
EXPECT_EQ(3U, db().MetadataChangeCount());
// A reflection (update already received) is ignored completely.
UpdateFromServer(0 /* version_offset */, kTag1, kValue1);
EXPECT_EQ(1U, db().DataChangeCount());
EXPECT_EQ(3U, db().MetadataChangeCount());
}
// Tests locally deleting an acknowledged item.
TEST_F(SharedModelTypeProcessorTest, LocalDeleteItem) {
InitializeToReadyState();
WriteItemAndAck(kTag1, kValue1);
ExpectCommitRequests({kTag1});
const sync_pb::EntityMetadata metadata_v1 = db().GetMetadata(kTag1);
EXPECT_FALSE(metadata_v1.is_deleted());
EXPECT_EQ(1, metadata_v1.sequence_number());
EXPECT_EQ(1, metadata_v1.acked_sequence_number());
EXPECT_EQ(1, metadata_v1.server_version());
DeleteItem(kTag1);
EXPECT_EQ(0U, db().DataCount());
// Metadata is not removed until the commit response comes back.
EXPECT_EQ(1U, db().MetadataCount());
EXPECT_EQ(1U, ProcessorEntityCount());
ExpectCommitRequests({kTag1, kTag1});
const sync_pb::EntityMetadata metadata_v2 = db().GetMetadata(kTag1);
EXPECT_TRUE(metadata_v2.is_deleted());
EXPECT_EQ(2, metadata_v2.sequence_number());
EXPECT_EQ(1, metadata_v2.acked_sequence_number());
EXPECT_EQ(1, metadata_v2.server_version());
// Ack the delete and check that the metadata is cleared.
SuccessfulCommitResponse(GetLatestCommitRequestForTag(kTag1));
EXPECT_EQ(0U, db().MetadataCount());
EXPECT_EQ(0U, ProcessorEntityCount());
}
// Tests creating and deleting an item locally before receiving a commit
// response, then getting the commit responses.
TEST_F(SharedModelTypeProcessorTest, LocalDeleteItemInterleaved) {
InitializeToReadyState();
WriteItem(kTag1, kValue1);
ExpectCommitRequests({kTag1});
const CommitRequestData& data_v1 = GetLatestCommitRequestForTag(kTag1);
const sync_pb::EntityMetadata metadata_v1 = db().GetMetadata(kTag1);
EXPECT_FALSE(metadata_v1.is_deleted());
EXPECT_EQ(1, metadata_v1.sequence_number());
EXPECT_EQ(0, metadata_v1.acked_sequence_number());
EXPECT_EQ(kUncommittedVersion, metadata_v1.server_version());
DeleteItem(kTag1);
EXPECT_EQ(0U, db().DataCount());
EXPECT_EQ(1U, db().MetadataCount());
EXPECT_EQ(1U, ProcessorEntityCount());
ExpectCommitRequests({kTag1, kTag1});
const CommitRequestData& data_v2 = GetLatestCommitRequestForTag(kTag1);
EXPECT_GT(data_v2.sequence_number, data_v1.sequence_number);
EXPECT_TRUE(data_v2.entity->id.empty());
EXPECT_EQ(kUncommittedVersion, data_v2.base_version);
EXPECT_TRUE(data_v2.entity->is_deleted());
const sync_pb::EntityMetadata metadata_v2 = db().GetMetadata(kTag1);
EXPECT_TRUE(metadata_v2.is_deleted());
EXPECT_EQ(2, metadata_v2.sequence_number());
EXPECT_EQ(0, metadata_v2.acked_sequence_number());
EXPECT_EQ(kUncommittedVersion, metadata_v2.server_version());
// A response for the first commit doesn't change much.
SuccessfulCommitResponse(data_v1);
EXPECT_EQ(0U, db().DataCount());
EXPECT_EQ(1U, db().MetadataCount());
EXPECT_EQ(1U, ProcessorEntityCount());
const sync_pb::EntityMetadata metadata_v3 = db().GetMetadata(kTag1);
EXPECT_TRUE(metadata_v3.is_deleted());
EXPECT_EQ(2, metadata_v3.sequence_number());
EXPECT_EQ(1, metadata_v3.acked_sequence_number());
EXPECT_EQ(1, metadata_v3.server_version());
SuccessfulCommitResponse(data_v2);
// The delete was acked so the metadata should now be cleared.
EXPECT_EQ(0U, db().MetadataCount());
EXPECT_EQ(0U, ProcessorEntityCount());
}
TEST_F(SharedModelTypeProcessorTest, ServerDeleteItem) {
InitializeToReadyState();
WriteItemAndAck(kTag1, kValue1);
EXPECT_EQ(1U, ProcessorEntityCount());
EXPECT_EQ(1U, db().MetadataCount());
EXPECT_EQ(1U, db().DataCount());
EXPECT_EQ(1U, GetNumCommitRequestLists());
TombstoneFromServer(5, kTag1);
// Delete from server should clear the data and all the metadata.
EXPECT_EQ(0U, db().DataCount());
EXPECT_EQ(0U, db().MetadataCount());
EXPECT_EQ(0U, ProcessorEntityCount());
EXPECT_EQ(1U, GetNumCommitRequestLists());
}
// Deletes an item we've never seen before.
// Should have no effect and not crash.
TEST_F(SharedModelTypeProcessorTest, LocalDeleteUnknown) {
InitializeToReadyState();
DeleteItem(kTag1);
EXPECT_EQ(0U, db().DataCount());
EXPECT_EQ(0U, db().MetadataCount());
EXPECT_EQ(0U, ProcessorEntityCount());
EXPECT_EQ(0U, GetNumCommitRequestLists());
}
// Deletes an item we've never seen before.
// Should have no effect and not crash.
TEST_F(SharedModelTypeProcessorTest, ServerDeleteUnknown) {
InitializeToReadyState();
TombstoneFromServer(5, kTag1);
EXPECT_EQ(0U, db().DataCount());
EXPECT_EQ(0U, db().MetadataCount());
EXPECT_EQ(0U, ProcessorEntityCount());
EXPECT_EQ(0U, GetNumCommitRequestLists());
}
// Creates two different sync items.
// Verifies that the second has no effect on the first.
TEST_F(SharedModelTypeProcessorTest, TwoIndependentItems) {
InitializeToReadyState();
EXPECT_EQ(0U, GetNumCommitRequestLists());
WriteItem(kTag1, kValue1);
EXPECT_EQ(1U, db().DataCount());
EXPECT_EQ(1U, db().MetadataCount());
const sync_pb::EntityMetadata metadata1 = db().GetMetadata(kTag1);
// There should be one commit request for this item only.
ExpectCommitRequests({kTag1});
WriteItem(kTag2, kValue2);
EXPECT_EQ(2U, db().DataCount());
EXPECT_EQ(2U, db().MetadataCount());
const sync_pb::EntityMetadata metadata2 = db().GetMetadata(kTag2);
// The second write should trigger another single-item commit request.
ExpectCommitRequests({kTag1, kTag2});
EXPECT_FALSE(metadata1.is_deleted());
EXPECT_EQ(1, metadata1.sequence_number());
EXPECT_EQ(0, metadata1.acked_sequence_number());
EXPECT_EQ(kUncommittedVersion, metadata1.server_version());
EXPECT_FALSE(metadata2.is_deleted());
EXPECT_EQ(1, metadata2.sequence_number());
EXPECT_EQ(0, metadata2.acked_sequence_number());
EXPECT_EQ(kUncommittedVersion, metadata2.server_version());
}
TEST_F(SharedModelTypeProcessorTest, ConflictResolutionChangesMatch) {
InitializeToReadyState();
WriteItem(kTag1, kValue1);
EXPECT_EQ(1U, db().DataChangeCount());
EXPECT_EQ(kValue1, db().GetValue(kTag1));
EXPECT_EQ(1U, db().MetadataChangeCount());
EXPECT_EQ(kUncommittedVersion, db().GetMetadata(kTag1).server_version());
ExpectCommitRequests({kTag1});
ExpectNthCommitRequestList(0, kTag1, kValue1);
// Changes match doesn't call ResolveConflict.
UpdateFromServer(5, kTag1, kValue1);
// Updated metadata but not data; no new commit request.
EXPECT_EQ(1U, db().DataChangeCount());
EXPECT_EQ(5, db().GetMetadata(kTag1).server_version());
ExpectCommitRequests({kTag1});
}
TEST_F(SharedModelTypeProcessorTest, ConflictResolutionUseLocal) {
InitializeToReadyState();
WriteItem(kTag1, kValue1);
SetConflictResolution(ConflictResolution::UseLocal());
UpdateFromServer(5, kTag1, kValue2);
// Updated metadata but not data; new commit request.
EXPECT_EQ(1U, db().DataChangeCount());
EXPECT_EQ(2U, db().MetadataChangeCount());
EXPECT_EQ(5, db().GetMetadata(kTag1).server_version());
ExpectCommitRequests({kTag1, kTag1});
ExpectNthCommitRequestList(1, kTag1, kValue1);
}
TEST_F(SharedModelTypeProcessorTest, ConflictResolutionUseRemote) {
InitializeToReadyState();
WriteItem(kTag1, kValue1);
SetConflictResolution(ConflictResolution::UseRemote());
UpdateFromServer(5, kTag1, kValue2);
// Updated client data and metadata; no new commit request.
EXPECT_EQ(2U, db().DataChangeCount());
EXPECT_EQ(kValue2, db().GetValue(kTag1));
EXPECT_EQ(2U, db().MetadataChangeCount());
EXPECT_EQ(5, db().GetMetadata(kTag1).server_version());
ExpectCommitRequests({kTag1});
}
TEST_F(SharedModelTypeProcessorTest, ConflictResolutionUseNew) {
InitializeToReadyState();
WriteItem(kTag1, kValue1);
SetConflictResolution(
ConflictResolution::UseNew(GenerateEntityData(kTag1, kValue3)));
UpdateFromServer(5, kTag1, kValue2);
EXPECT_EQ(2U, db().DataChangeCount());
EXPECT_EQ(kValue3, db().GetValue(kTag1));
EXPECT_EQ(2U, db().MetadataChangeCount());
EXPECT_EQ(5, db().GetMetadata(kTag1).server_version());
ExpectCommitRequests({kTag1, kTag1});
ExpectNthCommitRequestList(1, kTag1, kValue3);
}
// Test proper handling of disconnect and reconnect.
//
// Creates items in various states of commit and verifies they re-attempt to
// commit on reconnect.
TEST_F(SharedModelTypeProcessorTest, Disconnect) {
InitializeToReadyState();
// The first item is fully committed.
WriteItemAndAck(kTag1, kValue1);
// The second item has a commit request in progress.
WriteItem(kTag2, kValue2);
EXPECT_TRUE(HasCommitRequestForTag(kTag2));
DisconnectSync();
// The third item is added after stopping.
WriteItem(kTag3, kValue3);
// Reconnect.
OnSyncStarting();
EXPECT_EQ(1U, GetNumCommitRequestLists());
EXPECT_EQ(2U, GetNthCommitRequestList(0).size());
// The first item was already in sync.
EXPECT_FALSE(HasCommitRequestForTag(kTag1));
// The second item's commit was interrupted and should be retried.
EXPECT_TRUE(HasCommitRequestForTag(kTag2));
// The third item's commit was not started until the reconnect.
EXPECT_TRUE(HasCommitRequestForTag(kTag3));
}
// Test proper handling of disable and re-enable.
//
// Creates items in various states of commit and verifies they re-attempt to
// commit on re-enable.
TEST_F(SharedModelTypeProcessorTest, Disable) {
InitializeToReadyState();
// The first item is fully committed.
WriteItemAndAck(kTag1, kValue1);
// The second item has a commit request in progress.
WriteItem(kTag2, kValue2);
EXPECT_TRUE(HasCommitRequestForTag(kTag2));
DisableSync();
// The third item is added after disable.
WriteItem(kTag3, kValue3);
// Now we re-enable.
CreateChangeProcessor();
OnMetadataLoaded();
OnSyncStarting();
OnInitialSyncDone();
// Once we're ready to commit, all three local items should consider
// themselves uncommitted and pending for commit.
ExpectCommitRequests({kTag1, kTag2, kTag3});
}
// Test re-encrypt everything when desired encryption key changes.
TEST_F(SharedModelTypeProcessorTest, DISABLED_ReEncryptCommitsWithNewKey) {
InitializeToReadyState();
// Commit an item.
WriteItemAndAck(kTag1, kValue1);
// Create another item and don't wait for its commit response.
WriteItem(kTag2, kValue2);
ASSERT_EQ(2U, GetNumCommitRequestLists());
// Receive notice that the account's desired encryption key has changed.
UpdateDesiredEncryptionKey("k1");
// That should trigger a new commit request.
ASSERT_EQ(3U, GetNumCommitRequestLists());
EXPECT_EQ(2U, GetNthCommitRequestList(2).size());
const CommitRequestData& tag1_enc = GetLatestCommitRequestForTag(kTag1);
const CommitRequestData& tag2_enc = GetLatestCommitRequestForTag(kTag2);
SuccessfulCommitResponse(tag1_enc);
SuccessfulCommitResponse(tag2_enc);
// And that should be the end of it.
ASSERT_EQ(3U, GetNumCommitRequestLists());
}
// Test receipt of updates with new and old keys.
// TODO(stanisc): crbug/561814: Disabled due to data caching changes in
// ProcessorEntityTracker. Revisit the test once fetching of data is
// implemented.
TEST_F(SharedModelTypeProcessorTest, DISABLED_ReEncryptUpdatesWithNewKey) {
InitializeToReadyState();
// Receive an unencrypted update.
UpdateFromServer(5, "no_enc", kValue1);
ASSERT_EQ(0U, GetNumCommitRequestLists());
// Set desired encryption key to k2 to force updates to some items.
UpdateDesiredEncryptionKey("k2");
ASSERT_EQ(1U, GetNumCommitRequestLists());
EXPECT_EQ(1U, GetNthCommitRequestList(0).size());
EXPECT_TRUE(HasCommitRequestForTag("no_enc"));
// Receive an update that was encrypted with key k1.
SetServerEncryptionKey("k1");
UpdateFromServer(10, "enc_k1", kValue1);
// Receipt of updates encrypted with old key also forces a re-encrypt commit.
ASSERT_EQ(2U, GetNumCommitRequestLists());
EXPECT_EQ(1U, GetNthCommitRequestList(1).size());
EXPECT_TRUE(HasCommitRequestForTag("enc_k1"));
// Receive an update that was encrypted with key k2.
SetServerEncryptionKey("k2");
UpdateFromServer(15, "enc_k2", kValue1);
// That was the correct key, so no re-encryption is required.
EXPECT_EQ(2U, GetNumCommitRequestLists());
EXPECT_FALSE(HasCommitRequestForTag("enc_k2"));
}
} // namespace syncer_v2
|
1de0b23d522b1942531499179ed51289ff142db6
|
6a9c422f963e1fd79f6ceda23a6e147565b43624
|
/LEETCODE-238.ProductOfArrayExceptSelf.cpp
|
81a8ffaedcb112e03e078af26da16448095b6a47
|
[] |
no_license
|
sidhantchadha/LEETCODE
|
6605d07b30c06d47d81b0d6d84673c31ea0cc9e1
|
d67e210d396a015b2dd6980ffd2a82b9e0cf2d73
|
refs/heads/master
| 2020-03-07T01:37:28.592703
| 2018-06-22T20:32:11
| 2018-06-22T20:32:11
| 127,188,143
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 713
|
cpp
|
LEETCODE-238.ProductOfArrayExceptSelf.cpp
|
//============================================================================
// Name : ProductOfArrayExceptSelf.cpp
// Author : Sidhant Chadha
// Version :
// Copyright :
// Description : Product Of Array Except Self in C++, Ansi-style
//============================================================================
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int first=1;
int last=1;
int n=nums.size();
vector<int>V(n,1);
for(int i=0;i<n;i++) {
V[i]=first*V[i];
first=first*nums[i];
V[n-1-i]=last*V[n-1-i];
last=last*nums[n-1-i];
}
return V;
}
};
|
9fe93cab0bc9537e2087ed35a7c9b5a7a9bcadf1
|
9130dabd3ec3c9115c1d8f32f54e5817ce6a8401
|
/dynamic memory allocation-3types.cpp
|
fffb662e6c4c27142cf6fb4e8492ff266cb7cb5f
|
[] |
no_license
|
RaghavBansal31/cplusplus-programs
|
8713728dac1fc42d7a65850b499a36eff57b9410
|
1ceb73a38434adc084a38cd2679ba48f53d6fa8d
|
refs/heads/main
| 2023-04-18T00:59:21.854606
| 2021-04-28T07:02:40
| 2021-04-28T07:02:40
| 361,433,746
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 628
|
cpp
|
dynamic memory allocation-3types.cpp
|
#include<iostream>
using namespace std;
class product{
int price, qty;
public:
void input(int x, int y)
{
price = x;
qty = y;
}
void result()
{
cout<<"The total is: "<<price*qty<<endl;
}
};
int main()
{
//memory allocation to class object
product *a = new product();
(*a).input(5,6);
(*a).result();
a->input(4,4);
a->result();
delete a;
//memory allocation to array
int *p = new int[7];
for(int i = 0;i<5;i++)
{
cin>>p[i];
}
for(int i = 0;i<5;i++)
{
cout<<p[i]<<endl;
}
delete []p;
//memory allocation to variable
float *f = new float(8.6);
cout<<*f<<endl;
delete f;
}
|
ba3ea7b0d5e081825176e85aa9ad4944f8fa98b0
|
127fbc4b1325b6aeb622d9afe46976aaf2af4eef
|
/templatesone/templatesone/templatesone.cpp
|
733a5d677e5fcd30e981b270d6ef24c3c115fe80
|
[] |
no_license
|
Blackhatarcher/Templates
|
ac4c1340a5ffb123405f6181c96acb310126f5e5
|
ccc8f4c4033ab697215768ddfd4800680a109cea
|
refs/heads/master
| 2021-01-12T16:06:59.702600
| 2016-11-03T21:20:48
| 2016-11-03T21:20:48
| 71,940,317
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,483
|
cpp
|
templatesone.cpp
|
// templatesone.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <iomanip>
using namespace std;
template <typename T>
void Swap(T & v1, T & v2) {
T temp = v1;
v1 = v2;
v2 = temp;
}
template <typename T>
int* doubleCapacity(const T* list, int size) {
if (size > 0 && list != NULL) {
T* newlist = new T[size * 2];
for (int i = 0; i < size; i++) {
newlist[i] = list[i];
}
delete[] list;
return newlist;
}
else {
return NULL;
}
}
template <typename T>
class ExpandableArray {
private:
T* items;
int length;
int size;
void increaseSizeTo(int newSize) {
T* newList = new newSize[];
}
public:
ExpandableArray() {
size = 10;
length = 0;
items = new T[size];
}
int getLength() {
return length;
}
void append(T item) {
if (length >= size) {
doubleCapacity();
}
items[length] = item;
}
T getAtIndex(int index);
void setItemAtIndex(T item, int index);
void output();
};
int main()
{
bool playing = true;
while (playing) {
double x = 8.8;
double y = 90.0;
cout << x << endl;
cout << y << endl;
Swap(x, y);
cout << x << endl;
cout << y << endl;
ExpandableArray<int> sArray;
for (int i = 0; i < 200; i++) {
sArray.append(i);
}
sArray.output();
int finalanswer = 0;
cout << "Enter 1 to exit" << endl;
cin >> finalanswer;
if (finalanswer == 1) {
playing = false;
}
}
return 0;
}
|
b901c63d6f8f295e9cb6457cc3ef74f1b17c7b59
|
e0f08f13c8c716f3c2bbb314f7038a111d997615
|
/src/ChangeSeats.cpp
|
647b08ab345268910ce24af20ef6736aeed5b71e
|
[] |
no_license
|
byunghoonpark/OOAD
|
58ddd05cf0850b675055ac77c60892328e569a70
|
8792a95e5929fb26b9aea066b4d1c8c06ea5a16d
|
refs/heads/master
| 2020-05-27T05:56:59.022791
| 2019-06-25T17:44:37
| 2019-06-25T17:44:37
| 188,510,986
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,030
|
cpp
|
ChangeSeats.cpp
|
#include <iostream>
#include <string>
#include "ChangeSeats.h"
using namespace std;
// Seats seat[101];
ChangeSeats::ChangeSeats() {}
ChangeSeats::~ChangeSeats() {}
void ChangeSeats::changeCurPos(User &U) {
int wantSeats;
int curSeats = U.getSeatNumber();
cout << endl;
cout << U.getID() << "님의 좌석번호는 " << U.getSeatNumber() << " 입니다." << endl;
cout << "현재 빈 좌석: ";
for (int i = 1; i <= 100; i++) {
if (seat[i].getUserID() == "")
cout << i << ' ';
}
cout << endl;
cout << "위의 좌석들로 이동 가능합니다. 원하는 좌석번호를 입력하세요." << endl;
cin >> wantSeats;
cout << wantSeats << "번 좌석으로 이동합니다! " << endl;
U.setSeatNumber(wantSeats);
seat[wantSeats].setUserID(U.getID());
seat[curSeats].setUserID("");
cout << endl;
cout << U.getID() << "님의 좌석번호는 " << U.getSeatNumber() << " 입니다." << endl;
cout << wantSeats << "번 좌석번호의 " << "UserID: " << seat[wantSeats].getUserID() << endl;
cout << endl;
}
|
8dac55e031ae7ccdae5ddecd3de13dc2c25c0e97
|
e36906be9399685b0d03daffec9c33735eda8ba1
|
/src/mk/arch/lsf-d.cpp
|
60a0e12d2fd78986dc624094b24740204e989436
|
[] |
no_license
|
ybouret/yocto4
|
20deaa21c1ed4f52d5d6a7991450d90103a7fe8e
|
c02aa079d21cf9828f188153e5d65c1f0d62021c
|
refs/heads/master
| 2020-04-06T03:34:11.834637
| 2016-09-09T14:41:55
| 2016-09-09T14:41:55
| 33,724,799
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 43
|
cpp
|
lsf-d.cpp
|
#define YOCTO_ZTYPE 'd'
#include "lsf.cxx"
|
42327a64f2d00a4108ffc132c52b18094e4e2ce7
|
d223f4964f5a9a588453ce5fd75f894976132a37
|
/PluginFactory.h
|
f28dc09025cf6c2d31b23e239f5e77374bd58960
|
[] |
no_license
|
hexiangquan/tensorSSD
|
5d8ded7eb7cf93128559f4e057927ffade36542f
|
cf2e9cd2314e9cf4d7d42cd5141ca5d89cb9bdb3
|
refs/heads/master
| 2020-03-11T08:11:37.570763
| 2018-04-17T09:09:27
| 2018-04-17T09:09:27
| 129,877,290
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 28,937
|
h
|
PluginFactory.h
|
#ifndef __PLUGIN_FACTORY_H__
#define __PLUGIN_FACTORY_H__
#include <algorithm>
#include <cassert>
#include <iostream>
#include <cstring>
#include <sys/stat.h>
#include <map>
#include "NvCaffeParser.h"
#include "NvInferPlugin.h"
#include <cudnn.h>
#include <cuda_runtime.h>
#include <cublas_v2.h>
using namespace nvinfer1;
using namespace nvcaffeparser1;
using namespace plugin;
#if 0
//Concat layer . TensorRT Concat only support cross channel
class ConcatPlugin : public IPlugin
{
public:
ConcatPlugin(int axis){ _axis = axis; };
// ConcatPlugin(int axis, const void* buffer, size_t size);
ConcatPlugin::ConcatPlugin(int axis, const void* buffer, size_t size)
{
assert(size == (18*sizeof(int)));
const int* d = reinterpret_cast<const int*>(buffer);
dimsConv4_3 = DimsCHW{d[0], d[1], d[2]};
dimsFc7 = DimsCHW{d[3], d[4], d[5]};
dimsConv6 = DimsCHW{d[6], d[7], d[8]};
dimsConv7 = DimsCHW{d[9], d[10], d[11]};
dimsConv8 = DimsCHW{d[12], d[13], d[14]};
dimsConv9 = DimsCHW{d[15], d[16], d[17]};
_axis = axis;
}
inline int getNbOutputs() const override {return 1;};
// Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) override ;
Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims)
{
assert(nbInputDims == 6);
if(_axis == 1)
{
top_concat_axis = inputs[0].d[0] + inputs[1].d[0] + inputs[2].d[0] + inputs[3].d[0] + inputs[4].d[0] + inputs[5].d[0];
return DimsCHW(top_concat_axis, 1, 1);
}else if(_axis == 2){
top_concat_axis = inputs[0].d[1] + inputs[1].d[1] + inputs[2].d[1] + inputs[3].d[1] + inputs[4].d[1] + inputs[5].d[1];
return DimsCHW(2, top_concat_axis, 1);
}else{//_param.concat_axis == 3
return DimsCHW(0, 0, 0);
}
}
// int initialize()
int initialize()
{
inputs_size = 6;//6个bottom层
if(_axis == 1)//c
{
top_concat_axis = dimsConv4_3.c() + dimsFc7.c() + dimsConv6.c() + dimsConv7.c() + dimsConv8.c() + dimsConv9.c();
bottom_concat_axis[0] = dimsConv4_3.c(); bottom_concat_axis[1] = dimsFc7.c(); bottom_concat_axis[2] = dimsConv6.c();
bottom_concat_axis[3] = dimsConv7.c(); bottom_concat_axis[4] = dimsConv8.c(); bottom_concat_axis[5] = dimsConv9.c();
concat_input_size_[0] = dimsConv4_3.h() * dimsConv4_3.w(); concat_input_size_[1] = dimsFc7.h() * dimsFc7.w();
concat_input_size_[2] = dimsConv6.h() * dimsConv6.w(); concat_input_size_[3] = dimsConv7.h() * dimsConv7.w();
concat_input_size_[4] = dimsConv8.h() * dimsConv8.w(); concat_input_size_[5] = dimsConv9.h() * dimsConv9.w();
num_concats_[0] = dimsConv4_3.c(); num_concats_[1] = dimsFc7.c(); num_concats_[2] = dimsConv6.c();
num_concats_[3] = dimsConv7.c(); num_concats_[4] = dimsConv8.c(); num_concats_[5] = dimsConv9.c();
}else if(_axis == 2){//h
top_concat_axis = dimsConv4_3.h() + dimsFc7.h() + dimsConv6.h() + dimsConv7.h() + dimsConv8.h() + dimsConv9.h();
bottom_concat_axis[0] = dimsConv4_3.h(); bottom_concat_axis[1] = dimsFc7.h(); bottom_concat_axis[2] = dimsConv6.h();
bottom_concat_axis[3] = dimsConv7.h(); bottom_concat_axis[4] = dimsConv8.h(); bottom_concat_axis[5] = dimsConv9.h();
concat_input_size_[0] = dimsConv4_3.w(); concat_input_size_[1] = dimsFc7.w(); concat_input_size_[2] = dimsConv6.w();
concat_input_size_[3] = dimsConv7.w(); concat_input_size_[4] = dimsConv8.w(); concat_input_size_[5] = dimsConv9.w();
num_concats_[0] = dimsConv4_3.c() * dimsConv4_3.h(); num_concats_[1] = dimsFc7.c() * dimsFc7.h();
num_concats_[2] = dimsConv6.c() * dimsConv6.h(); num_concats_[3] = dimsConv7.c() * dimsConv7.h();
num_concats_[4] = dimsConv8.c() * dimsConv8.h(); num_concats_[5] = dimsConv9.c() * dimsConv9.h();
}else{//_param.concat_axis == 3 , w
top_concat_axis = dimsConv4_3.w() + dimsFc7.w() + dimsConv6.w() + dimsConv7.w() + dimsConv8.w() + dimsConv9.w();
bottom_concat_axis[0] = dimsConv4_3.w(); bottom_concat_axis[1] = dimsFc7.w(); bottom_concat_axis[2] = dimsConv6.w();
bottom_concat_axis[3] = dimsConv7.w(); bottom_concat_axis[4] = dimsConv8.w(); bottom_concat_axis[5] = dimsConv9.w();
concat_input_size_[0] = 1; concat_input_size_[1] = 1; concat_input_size_[2] = 1;
concat_input_size_[3] = 1; concat_input_size_[4] = 1; concat_input_size_[5] = 1;
return 0;
}
return 0;
}
// inline void terminate() override;
void terminate()
{
//CUDA_CHECK(cudaFree(scale_data));
delete[] bottom_concat_axis;
delete[] concat_input_size_;
delete[] num_concats_;
}
inline size_t getWorkspaceSize(int) const override { return 0; };
//int enqueue(int batchSize, const void*const *inputs, void** outputs, void*, cudaStream_t stream) override;
int enqueue(int batchSize, const void*const *inputs, void** outputs, void*, cudaStream_t stream)
{
float *top_data = reinterpret_cast<float*>(outputs[0]);
int offset_concat_axis = 0;
const bool kForward = true;
for (int i = 0; i < inputs_size; ++i) {
const float *bottom_data = reinterpret_cast<const float*>(inputs[i]);
const int nthreads = num_concats_[i] * concat_input_size_[i];
//const int nthreads = bottom_concat_size * num_concats_[i];
ConcatLayer(nthreads, bottom_data, kForward, num_concats_[i], concat_input_size_[i], top_concat_axis, bottom_concat_axis[i], offset_concat_axis, top_data, stream);
offset_concat_axis += bottom_concat_axis[i];
}
return 0;
}
// size_t getSerializationSize() override;
size_t getSerializationSize()
{
return 18*sizeof(int);
}
// void serialize(void* buffer) override;
void serialize(void* buffer)
{
int* d = reinterpret_cast<int*>(buffer);
d[0] = dimsConv4_3.c(); d[1] = dimsConv4_3.h(); d[2] = dimsConv4_3.w();
d[3] = dimsFc7.c(); d[4] = dimsFc7.h(); d[5] = dimsFc7.w();
d[6] = dimsConv6.c(); d[7] = dimsConv6.h(); d[8] = dimsConv6.w();
d[9] = dimsConv7.c(); d[10] = dimsConv7.h(); d[11] = dimsConv7.w();
d[12] = dimsConv8.c(); d[13] = dimsConv8.h(); d[14] = dimsConv8.w();
d[15] = dimsConv9.c(); d[16] = dimsConv9.h(); d[17] = dimsConv9.w();
}
// void configure(const Dims*inputs, int nbInputs, const Dims* outputs, int nbOutputs, int) override;
void configure(const Dims*inputs, int nbInputs, const Dims* outputs, int nbOutputs, int)
{
dimsConv4_3 = DimsCHW{inputs[0].d[0], inputs[0].d[1], inputs[0].d[2]};
dimsFc7 = DimsCHW{inputs[1].d[0], inputs[1].d[1], inputs[1].d[2]};
dimsConv6 = DimsCHW{inputs[2].d[0], inputs[2].d[1], inputs[2].d[2]};
dimsConv7 = DimsCHW{inputs[3].d[0], inputs[3].d[1], inputs[3].d[2]};
dimsConv8 = DimsCHW{inputs[4].d[0], inputs[4].d[1], inputs[4].d[2]};
dimsConv9 = DimsCHW{inputs[5].d[0], inputs[5].d[1], inputs[5].d[2]};
}
protected:
DimsCHW dimsConv4_3, dimsFc7, dimsConv6, dimsConv7, dimsConv8, dimsConv9;
int inputs_size;
int top_concat_axis;//top 层 concat后的维度
int* bottom_concat_axis = new int[9];//记录每个bottom层concat维度的shape
int* concat_input_size_ = new int[9];
int* num_concats_ = new int[9];
int _axis;
};
#endif
//SSD Reshape layer : shape{0,-1,21}
template<int OutC>
class Reshape : public IPlugin
{
public:
Reshape() {}
Reshape(const void* buffer, size_t size)
{
assert(size == sizeof(mCopySize));
mCopySize = *reinterpret_cast<const size_t*>(buffer);
}
int getNbOutputs() const override
{
return 1;
}
Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) override
{
assert(nbInputDims == 1);
assert(index == 0);
assert(inputs[index].nbDims == 3);
assert((inputs[0].d[0])*(inputs[0].d[1]) % OutC == 0);
return DimsCHW(OutC, inputs[0].d[0] * inputs[0].d[1] / OutC, inputs[0].d[2]);
}
int initialize() override
{
return 0;
}
void terminate() override
{
}
size_t getWorkspaceSize(int) const override
{
return 0;
}
// currently it is not possible for a plugin to execute "in place". Therefore we memcpy the data from the input to the output buffer
int enqueue(int batchSize, const void*const *inputs, void** outputs, void*, cudaStream_t stream) override
{
CHECK(cudaMemcpyAsync(outputs[0], inputs[0], mCopySize * batchSize, cudaMemcpyDeviceToDevice, stream));
return 0;
}
size_t getSerializationSize() override
{
return sizeof(mCopySize);
}
void serialize(void* buffer) override
{
*reinterpret_cast<size_t*>(buffer) = mCopySize;
}
void configure(const Dims*inputs, int nbInputs, const Dims* outputs, int nbOutputs, int) override
{
mCopySize = inputs[0].d[0] * inputs[0].d[1] * inputs[0].d[2] * sizeof(float);
}
protected:
size_t mCopySize;
};
//SSD Flatten layer
class FlattenLayer : public IPlugin
{
public:
FlattenLayer(){}
FlattenLayer(const void* buffer,size_t size)
{
assert(size == 3 * sizeof(int));
const int* d = reinterpret_cast<const int*>(buffer);
_size = d[0] * d[1] * d[2];
dimBottom = DimsCHW{d[0], d[1], d[2]};
}
inline int getNbOutputs() const override { return 1; };
Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) override
{
assert(1 == nbInputDims);
assert(0 == index);
assert(3 == inputs[index].nbDims);
_size = inputs[0].d[0] * inputs[0].d[1] * inputs[0].d[2];
return DimsCHW(_size, 1, 1);
}
int initialize() override
{
return 0;
}
inline void terminate() override
{
}
inline size_t getWorkspaceSize(int) const override { return 0; }
int enqueue(int batchSize, const void*const *inputs, void** outputs, void*, cudaStream_t stream) override
{
std::cout<<"flatten enqueue:"<<batchSize<<";"<<_size<<std::endl;
CHECK(cudaMemcpyAsync(outputs[0],inputs[0],batchSize*_size*sizeof(float),cudaMemcpyDeviceToDevice,stream));
return 0;
}
size_t getSerializationSize() override
{
return 3 * sizeof(int);
}
void serialize(void* buffer) override
{
int* d = reinterpret_cast<int*>(buffer);
d[0] = dimBottom.c(); d[1] = dimBottom.h(); d[2] = dimBottom.w();
}
void configure(const Dims*inputs, int nbInputs, const Dims* outputs, int nbOutputs, int) override
{
dimBottom = DimsCHW(inputs[0].d[0], inputs[0].d[1], inputs[0].d[2]);
}
protected:
DimsCHW dimBottom;
int _size;
};
struct Profiler : public IProfiler
{
typedef std::pair<std::string, float> Record;
std::vector<Record> mProfile;
virtual void reportLayerTime(const char* layerName, float ms)
{
auto record = std::find_if(mProfile.begin(), mProfile.end(), [&](const Record& r){ return r.first == layerName; });
if (record == mProfile.end()) mProfile.push_back(std::make_pair(layerName, ms));
else record->second += ms;
}
void printLayerTimes(const int TIMING_ITERATIONS)
{
float totalTime = 0;
for (size_t i = 0; i < mProfile.size(); i++)
{
printf("%-40.40s %4.3fms\n", mProfile[i].first.c_str(), mProfile[i].second / TIMING_ITERATIONS);
totalTime += mProfile[i].second;
}
printf("Time over all layers: %4.3f\n", totalTime / TIMING_ITERATIONS);
}
};
class PluginFactory : public nvinfer1::IPluginFactory, public nvcaffeparser1::IPluginFactory {
public:
// caffe parser plugin implementation
bool isPlugin(const char* name) override
{
return (!strcmp(name, "conv4_3_norm")
|| !strcmp(name, "conv4_3_norm_mbox_conf_perm")
|| !strcmp(name, "conv4_3_norm_mbox_conf_flat")
|| !strcmp(name, "conv4_3_norm_mbox_loc_perm")
|| !strcmp(name, "conv4_3_norm_mbox_loc_flat")
|| !strcmp(name, "fc7_mbox_conf_perm")
|| !strcmp(name, "fc7_mbox_conf_flat")
|| !strcmp(name, "fc7_mbox_loc_perm")
|| !strcmp(name, "fc7_mbox_loc_flat")
|| !strcmp(name, "conv6_2_mbox_conf_perm")
|| !strcmp(name, "conv6_2_mbox_conf_flat")
|| !strcmp(name, "conv6_2_mbox_loc_perm")
|| !strcmp(name, "conv6_2_mbox_loc_flat")
|| !strcmp(name, "conv7_2_mbox_conf_perm")
|| !strcmp(name, "conv7_2_mbox_conf_flat")
|| !strcmp(name, "conv7_2_mbox_loc_perm")
|| !strcmp(name, "conv7_2_mbox_loc_flat")
|| !strcmp(name, "conv8_2_mbox_conf_perm")
|| !strcmp(name, "conv8_2_mbox_conf_flat")
|| !strcmp(name, "conv8_2_mbox_loc_perm")
|| !strcmp(name, "conv8_2_mbox_loc_flat")
|| !strcmp(name, "conv9_2_mbox_conf_perm")
|| !strcmp(name, "conv9_2_mbox_conf_flat")
|| !strcmp(name, "conv9_2_mbox_loc_perm")
|| !strcmp(name, "conv9_2_mbox_loc_flat")
|| !strcmp(name, "conv4_3_norm_mbox_priorbox")
|| !strcmp(name, "fc7_mbox_priorbox")
|| !strcmp(name, "conv6_2_mbox_priorbox")
|| !strcmp(name, "conv7_2_mbox_priorbox")
|| !strcmp(name, "conv8_2_mbox_priorbox")
|| !strcmp(name, "conv9_2_mbox_priorbox")
|| !strcmp(name, "mbox_conf_reshape")
|| !strcmp(name, "mbox_conf_flatten")
|| !strcmp(name, "mbox_loc")
|| !strcmp(name, "mbox_conf")
|| !strcmp(name, "mbox_priorbox")
|| !strcmp(name, "detection_out")
|| !strcmp(name, "detection_out2")
);
}
virtual IPlugin* createPlugin(const char* layerName, const Weights* weights, int nbWeights) override
{
// there's no way to pass parameters through from the model definition, so we have to define it here explicitly
if(!strcmp(layerName, "conv4_3_norm")){
//INvPlugin * plugin::createSSDNormalizePlugin (const Weights *scales, bool acrossSpatial, bool channelShared, float eps)
_nvPlugins[layerName] = plugin::createSSDNormalizePlugin(weights,false,false,1e-10);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName, "conv4_3_norm_mbox_loc_perm")
|| !strcmp(layerName, "conv4_3_norm_mbox_conf_perm")
|| !strcmp(layerName,"fc7_mbox_loc_perm")
|| !strcmp(layerName,"fc7_mbox_conf_perm")
|| !strcmp(layerName,"conv6_2_mbox_loc_perm")
|| !strcmp(layerName,"conv6_2_mbox_conf_perm")
|| !strcmp(layerName,"conv7_2_mbox_loc_perm")
|| !strcmp(layerName,"conv7_2_mbox_conf_perm")
|| !strcmp(layerName,"conv8_2_mbox_loc_perm")
|| !strcmp(layerName,"conv8_2_mbox_conf_perm")
|| !strcmp(layerName,"conv9_2_mbox_loc_perm")
|| !strcmp(layerName,"conv9_2_mbox_conf_perm")
){
_nvPlugins[layerName] = plugin::createSSDPermutePlugin(Quadruple({0,2,3,1}));
return _nvPlugins.at(layerName);
} else if(!strcmp(layerName,"conv4_3_norm_mbox_priorbox")){
plugin::PriorBoxParameters params = {0};
float minSize[1] = {30.0f};
float maxSize[1] = {60.0f};
float aspectRatios[1] = {2.0f};
params.minSize = (float*)minSize;
params.maxSize = (float*)maxSize;
params.aspectRatios = (float*)aspectRatios;
params.numMinSize = 1;
params.numMaxSize = 1;
params.numAspectRatios = 1;
params.flip = true;
params.clip = false;
params.variance[0] = 0.10000000149;
params.variance[1] = 0.10000000149;
params.variance[2] = 0.20000000298;
params.variance[3] = 0.20000000298;
params.imgH = 0;
params.imgW = 0;
params.stepH = 8.0f;
params.stepW = 8.0f;
params.offset = 0.5f;
_nvPlugins[layerName] = plugin::createSSDPriorBoxPlugin(params);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"fc7_mbox_priorbox")){
plugin::PriorBoxParameters params = {0};
float minSize[1] = {60.0f};
float maxSize[1] = {111.0f};
float aspectRatios[2] = {2.0f, 3.0f};
params.minSize = (float*)minSize;
params.maxSize = (float*)maxSize;
params.aspectRatios = (float*)aspectRatios;
params.numMinSize = 1;
params.numMaxSize = 1;
params.numAspectRatios = 2;
params.flip = true;
params.clip = false;
params.variance[0] = 0.10000000149;
params.variance[1] = 0.10000000149;
params.variance[2] = 0.20000000298;
params.variance[3] = 0.20000000298;
params.imgH = 0;
params.imgW = 0;
params.stepH = 16.0f;
params.stepW = 16.0f;
params.offset = 0.5f;
_nvPlugins[layerName] = plugin::createSSDPriorBoxPlugin(params);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"conv6_2_mbox_priorbox")){
plugin::PriorBoxParameters params = {0};
float minSize[1] = {111.0f};
float maxSize[1] = {162.0f};
float aspectRatios[2] = {2.0f, 3.0f};
params.minSize = (float*)minSize;
params.maxSize = (float*)maxSize;
params.aspectRatios = (float*)aspectRatios;
params.numMinSize = 1;
params.numMaxSize = 1;
params.numAspectRatios = 2;
params.flip = true;
params.clip = false;
params.variance[0] = 0.10000000149;
params.variance[1] = 0.10000000149;
params.variance[2] = 0.20000000298;
params.variance[3] = 0.20000000298;
params.imgH = 0;
params.imgW = 0;
params.stepH = 32.0f;
params.stepW = 32.0f;
params.offset = 5.0f;
_nvPlugins[layerName] = plugin::createSSDPriorBoxPlugin(params);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"conv7_2_mbox_priorbox")){
plugin::PriorBoxParameters params = {0};
float minSize[1] = {162.0f};
float maxSize[1] = {213.0f};
float aspectRatios[2] = {2.0f, 3.0f};
params.minSize = (float*)minSize;
params.maxSize = (float*)maxSize;
params.aspectRatios = (float*)aspectRatios;
params.numMinSize = 1;
params.numMaxSize = 1;
params.numAspectRatios = 2;
params.flip = true;
params.clip = false;
params.variance[0] = 0.10000000149;
params.variance[1] = 0.10000000149;
params.variance[2] = 0.20000000298;
params.variance[3] = 0.20000000298;
params.imgH = 0;
params.imgW = 0;
params.stepH = 64.0f;
params.stepW = 64.0f;
params.offset = 0.5f;
_nvPlugins[layerName] = plugin::createSSDPriorBoxPlugin(params);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"conv8_2_mbox_priorbox")){
plugin::PriorBoxParameters params = {0};
float minSize[1] = {213.0f};
float maxSize[1] = {264.0f};
float aspectRatios[1] = {2.0f};
params.minSize = (float*)minSize;
params.maxSize = (float*)maxSize;
params.aspectRatios = (float*)aspectRatios;
params.numMinSize = 1;
params.numMaxSize = 1;
params.numAspectRatios = 1;
params.flip = true;
params.clip = false;
params.variance[0] = 0.10000000149;
params.variance[1] = 0.10000000149;
params.variance[2] = 0.20000000298;
params.variance[3] = 0.20000000298;
params.imgH = 0;
params.imgW = 0;
params.stepH = 100.0f;
params.stepW = 100.0f;
params.offset = 0.5f;
_nvPlugins[layerName] = plugin::createSSDPriorBoxPlugin(params);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"conv9_2_mbox_priorbox")){
plugin::PriorBoxParameters params = {0};
float minSize[1] = {264.0f};
float maxSize[1] = {315.0f};
float aspectRatios[1] = {2.0f};
params.minSize = (float*)minSize;
params.maxSize = (float*)maxSize;
params.aspectRatios = (float*)aspectRatios;
params.numMinSize = 1;
params.numMaxSize = 1;
params.numAspectRatios = 1;
params.flip = true;
params.clip = false;
params.variance[0] = 0.10000000149;
params.variance[1] = 0.10000000149;
params.variance[2] = 0.20000000298;
params.variance[3] = 0.20000000298;
params.imgH = 0;
params.imgW = 0;
params.stepH = 300.0f;
params.stepW = 300.0f;
params.offset = 0.5f;
_nvPlugins[layerName] = plugin::createSSDPriorBoxPlugin(params);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"detection_out")
||!strcmp(layerName,"detection_out2")
){
/*
bool shareLocation
bool varianceEncodedInTarget
int backgroundLabelId
int numClasses
int topK
int keepTopK
float confidenceThreshold
float nmsThreshold
CodeType_t codeType
*/
plugin::DetectionOutputParameters params = {0};
params.numClasses = 21;
params.shareLocation = true;
params.varianceEncodedInTarget = false;
params.backgroundLabelId = 0;
params.keepTopK = 200;
params.codeType = CENTER_SIZE;
params.nmsThreshold = 0.45;
params.topK = 400;
params.confidenceThreshold = 0.5;
_nvPlugins[layerName] = plugin::createSSDDetectionOutputPlugin (params);
return _nvPlugins.at(layerName);
}else if (
!strcmp(layerName, "conv4_3_norm_mbox_conf_flat")
||!strcmp(layerName,"conv4_3_norm_mbox_loc_flat")
||!strcmp(layerName,"fc7_mbox_loc_flat")
||!strcmp(layerName,"fc7_mbox_conf_flat")
||!strcmp(layerName,"conv6_2_mbox_conf_flat")
||!strcmp(layerName,"conv6_2_mbox_loc_flat")
||!strcmp(layerName,"conv7_2_mbox_conf_flat")
||!strcmp(layerName,"conv7_2_mbox_loc_flat")
||!strcmp(layerName,"conv8_2_mbox_conf_flat")
||!strcmp(layerName,"conv8_2_mbox_loc_flat")
||!strcmp(layerName,"conv9_2_mbox_conf_flat")
||!strcmp(layerName,"conv9_2_mbox_loc_flat")
||!strcmp(layerName,"mbox_conf_flatten")
){
_nvPlugins[layerName] = (plugin::INvPlugin*)(new FlattenLayer());
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"mbox_conf_reshape")){
_nvPlugins[layerName] = (plugin::INvPlugin*)new Reshape<21>();
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"mbox_loc")){
_nvPlugins[layerName] = plugin::createConcatPlugin (1,false);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"mbox_conf")){
_nvPlugins[layerName] = plugin::createConcatPlugin (1,false);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"mbox_priorbox")){
_nvPlugins[layerName] = plugin::createConcatPlugin (2,false);
return _nvPlugins.at(layerName);
}else {
assert(0);
return nullptr;
}
}
// deserialization plugin implementation
IPlugin* createPlugin(const char* layerName, const void* serialData, size_t serialLength) override {
if(!strcmp(layerName, "conv4_3_norm"))
{
_nvPlugins[layerName] = plugin::createSSDNormalizePlugin(serialData, serialLength);
return _nvPlugins.at(layerName);
}else if(
!strcmp(layerName, "conv4_3_norm_mbox_loc_perm")
|| !strcmp(layerName, "conv4_3_norm_mbox_conf_perm")
|| !strcmp(layerName,"fc7_mbox_loc_perm")
|| !strcmp(layerName,"fc7_mbox_conf_perm")
|| !strcmp(layerName,"conv6_2_mbox_loc_perm")
|| !strcmp(layerName,"conv6_2_mbox_conf_perm")
|| !strcmp(layerName,"conv7_2_mbox_loc_perm")
|| !strcmp(layerName,"conv7_2_mbox_conf_perm")
|| !strcmp(layerName,"conv8_2_mbox_loc_perm")
|| !strcmp(layerName,"conv8_2_mbox_conf_perm")
|| !strcmp(layerName,"conv9_2_mbox_loc_perm")
|| !strcmp(layerName,"conv9_2_mbox_conf_perm")
){
_nvPlugins[layerName] = plugin::createSSDPermutePlugin(serialData, serialLength);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"conv4_3_norm_mbox_priorbox")
|| !strcmp(layerName,"fc7_mbox_priorbox")
|| !strcmp(layerName,"conv6_2_mbox_priorbox")
|| !strcmp(layerName,"conv7_2_mbox_priorbox")
|| !strcmp(layerName,"conv8_2_mbox_priorbox")
|| !strcmp(layerName,"conv9_2_mbox_priorbox")
){
_nvPlugins[layerName] = plugin::createSSDPriorBoxPlugin (serialData, serialLength);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"detection_out")
|| !strcmp(layerName,"detection_out2")
){
_nvPlugins[layerName] = plugin::createSSDDetectionOutputPlugin (serialData, serialLength);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"mbox_conf_reshape")){
_nvPlugins[layerName] = (plugin::INvPlugin*)new Reshape<21>(serialData, serialLength);
return _nvPlugins.at(layerName);
}else if (
!strcmp(layerName, "conv4_3_norm_mbox_conf_flat")
||!strcmp(layerName,"conv4_3_norm_mbox_loc_flat")
||!strcmp(layerName,"fc7_mbox_loc_flat")
||!strcmp(layerName,"fc7_mbox_conf_flat")
||!strcmp(layerName,"conv6_2_mbox_conf_flat")
||!strcmp(layerName,"conv6_2_mbox_loc_flat")
||!strcmp(layerName,"conv7_2_mbox_conf_flat")
||!strcmp(layerName,"conv7_2_mbox_loc_flat")
||!strcmp(layerName,"conv8_2_mbox_conf_flat")
||!strcmp(layerName,"conv8_2_mbox_loc_flat")
||!strcmp(layerName,"conv9_2_mbox_conf_flat")
||!strcmp(layerName,"conv9_2_mbox_loc_flat")
||!strcmp(layerName,"mbox_conf_flatten")
){
_nvPlugins[layerName] = (plugin::INvPlugin*)(new FlattenLayer(serialData, serialLength));
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"mbox_loc")){
_nvPlugins[layerName] = plugin::createConcatPlugin (serialData, serialLength);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"mbox_conf")){
_nvPlugins[layerName] = plugin::createConcatPlugin (serialData, serialLength);
return _nvPlugins.at(layerName);
}else if(!strcmp(layerName,"mbox_priorbox")){
_nvPlugins[layerName] = plugin::createConcatPlugin (serialData, serialLength);
return _nvPlugins.at(layerName);
}else{
assert(0);
return nullptr;
}
}
void destroyPlugin()
{
for (auto it=_nvPlugins.begin(); it!=_nvPlugins.end(); ++it){
it->second->destroy();
_nvPlugins.erase(it);
}
}
private:
std::map<std::string, plugin::INvPlugin*> _nvPlugins;
};
#endif
|
e8025ba069c7ec056e23782fea81c17cf0207dba
|
1af7e974cd0aa50fe622af20a5fe0932a8500139
|
/ltr/predictions_aggregators/predictions_aggregator.h
|
f38755bac46dbfa87ef3f6ba70a809106cdf1e7a
|
[] |
no_license
|
fanfannothing/ltr
|
5db6b65720cdd1db3684a65454fc561778a279f5
|
793a49fa35669705205106770a3e539175e24c37
|
refs/heads/master
| 2021-01-20T16:17:53.626149
| 2013-10-10T12:05:08
| 2013-10-10T12:05:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 830
|
h
|
predictions_aggregator.h
|
// Copyright 2012 Yandex
#ifndef LTR_PREDICTIONS_AGGREGATORS_PREDICTIONS_AGGREGATOR_H_
#define LTR_PREDICTIONS_AGGREGATORS_PREDICTIONS_AGGREGATOR_H_
#include <vector>
#include "ltr/utility/boost/shared_ptr.h"
#include "ltr/interfaces/serializable.h"
#include "ltr/interfaces/parameterized.h"
using std::vector;
using ltr::Serializable;
using ltr::Parameterized;
namespace ltr {
/**
* Performs aggregation of objects weights and labels
*/
class PredictionsAggregator : public Serializable, public Parameterized {
public:
typedef ltr::utility::shared_ptr<PredictionsAggregator> Ptr;
virtual double aggregate(const vector<double>& labels,
const vector<double>& weights) const = 0;
virtual ~PredictionsAggregator() {}
};
};
#endif // LTR_PREDICTIONS_AGGREGATORS_PREDICTIONS_AGGREGATOR_H_
|
9258a8b005074e7ddd797f5d42da9537a5ea8490
|
624d7a0212847ec44579ac69d5902c82869829b8
|
/Source/Utility/UI/UIElement.h
|
71d81c7117d167669778e19183a925ddcbf86f5f
|
[] |
no_license
|
chillhammer/FedoraFrisbee
|
c0363205bccec5ba89158e83e33bd08f2e06de2d
|
8e7f9d920729fa82a45137dc080780499c8f0cdc
|
refs/heads/master
| 2020-04-14T01:14:16.883587
| 2019-10-15T01:48:46
| 2019-10-15T01:48:46
| 163,555,510
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 385
|
h
|
UIElement.h
|
#pragma once
#include <Transform/Transform.h>
#include <Utility/Graphics/Sprite/Sprite.h>
namespace Fed
{
class UIElement {
public:
UIElement(std::string textureName);
UIElement(Vector4 color);
Transform UITransform;
void Draw(const ShaderPtr& shader);
void Draw();
private:
UIElement() {};
UIElement(const UIElement& other) {};
protected:
Sprite m_Sprite;
};
}
|
dc0e2a8de8da9fb471fb954de1df805607e338d2
|
d6b4daf02ac3ed87efb47c6ba63e7f0489f289da
|
/ClusterDecoders/deprecated/ca_sim.hpp
|
61e4b1deb84394a15597ccc855713b816b020dff
|
[] |
no_license
|
Jonsm/ClusterDecoders
|
2188c52f2301bcd15ecf51fa5366b719934b4e30
|
ee44707f1711561b976b887ef3dfb30db956e862
|
refs/heads/main
| 2023-04-18T09:33:29.709623
| 2023-01-01T23:34:56
| 2023-01-01T23:34:56
| 399,565,271
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,401
|
hpp
|
ca_sim.hpp
|
//
// ca_sim.hpp
// ClusterDecoders
//
// Created by Jon San Miguel on 8/27/21.
//
#ifndef ca_sim_hpp
#define ca_sim_hpp
#include <vector>
#include <random>
#include "boost/multi_array.hpp"
#include "cluster_decoder.hpp"
#include "paulis.hpp"
class ca_sim {
public:
boost::multi_array<int, 2> syndromes_A;
boost::multi_array<int, 2> syndromes_B;
ca_sim(int w, int h, std::vector<float>& bias, int ca_freq);
void steps(int n_steps);
bool check();
void debug();
static void lifetime_sim(int avg, std::vector<std::pair<int,int>>& dims, std::vector<int>& strides, std::vector<float>& ps, std::vector<float>& normalized_bias, int freq, std::string filename);
static void distribution_sim(int avg, int t, std::vector<std::pair<int,int>>& dims, std::vector<float>& ps, std::vector<float>& normalized_bias, int freq, std::string filename);
protected:
const int w;
const int h;
const int ca_freq;
int total_steps = 0;
std::vector<float> bias_cumulative;
std::vector<std::pair<int, int>> syndrome_offsets_1;
std::vector<std::pair<int, int>> syndrome_offsets_2;
cluster_decoder decoder;
std::mt19937 engine;
std::uniform_real_distribution<float> dis;
void flip(int x, int y, int sublattice, Pauli p);
void add_errors();
virtual void ca_correction(int threshold, int sublattice);
};
#endif /* ca_sim_hpp */
|
5332de258f28b4480921361188ee09d8420ddf7e
|
786b47eb6dbbd8a0562eefeb157a01f0e24c33d6
|
/BallsCollisionCatchTest.cpp
|
738ec229d7be440608ed7c4a9c5a06519ff06f5b
|
[] |
no_license
|
Ollegio/Course_work
|
d757e3dc9c3dc8a6e2bc5ae96ac9af5927a858f8
|
33fd61dc226bddec34fa8a5f93eddb2e90db88f2
|
refs/heads/master
| 2020-03-08T00:41:33.444276
| 2018-04-22T15:34:03
| 2018-04-22T15:34:03
| 127,811,573
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 13,422
|
cpp
|
BallsCollisionCatchTest.cpp
|
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "BallsCollision.h"
#include "Particle.h"
#include "Event.h"
TEST_CASE("Reverse test") {
SECTION("Moving particles") {
test(5);
initVariables();
catchTest();
for (int i = 0; i < PARTICLES_COUNT; i++) {
REQUIRE(fabs(particles[i].getPos().x() - particlesTest[i].getPos().x()) < 1e-5);
REQUIRE(fabs(particles[i].getPos().y() - particlesTest[i].getPos().y()) < 1e-5);
REQUIRE(fabs(particles[i].getPos().z() - particlesTest[i].getPos().z()) < 1e-5);
}
}
}
GLvoid resizeGLScene(GLsizei width, GLsizei height) {
if (height == 0) // Предотвращение деления на ноль
height = 1;
glViewport(0, 0, width, height); // Сброс текущей области вывода
glMatrixMode(GL_PROJECTION); // Выбор матрицы проекций
glLoadIdentity(); // Сброс матрицы проекции
// Вычисление соотношения геометрических размеров для окна
gluPerspective(50.0f, (GLfloat)width / (GLfloat)height, 10.f, 1700.0f);
glMatrixMode(GL_MODELVIEW); // Выбор матрицы вида модели
glLoadIdentity(); // Сброс матрицы вида модели
}
GLboolean initGLScene(GLvoid) {
glClearDepth(1.0f); // Разрешить очистку буфера глубины
glEnable(GL_DEPTH_TEST); // Разрешить тест глубины
glDepthFunc(GL_LEQUAL); // Тип теста глубины
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Улучшение в вычислении перспективы
glClearColor(0, 0, 0, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glShadeModel(GL_SMOOTH);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_TEXTURE_2D);
if (!loadTexture(L"s.bmp", texture[0]))
return false;
return true;
}
GLint drawGLScene(GLvoid) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Очистить экран и буфер глубины
glLoadIdentity(); // Сбросить текущую матрицу
double a = 1000.0 * sin(0.017453 * (cameraTilt));
double b = 1000.0 * cos(0.017453 * (cameraTilt));
gluLookAt(camPosition.x(), camPosition.y() + a, camPosition.z() + b, camPosition.x() + camDirection.x(), camPosition.y() + camDirection.y(), camPosition.z() + camDirection.z(), 0, 1.0, 0.0);
glRotatef(cameraRotation, 0, 1, 0);
for (int i = 0; i < PARTICLES_COUNT; i++) {
if (velocityColor == true)
glColor3f(particles[i].getVel().length(), 0.0, 1.0 / particles[i].getVel().length());
else
glColor3fv(particles[i].getColor());
glPushMatrix();
glTranslated(particles[i].getPos().x(), particles[i].getPos().y(), particles[i].getPos().z());
gluSphere(cylinderObj, particles[i].getR(), 20, 20);
glPopMatrix();
}
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glColor3f(1, 1, 1);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(300, 300, 300);
glTexCoord2f(1.0f, 1.0f); glVertex3f(300, -300, 300);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-300, -300, 300);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-300, 300, 300);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-300, 300, -300);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-300, -300, -300);
glTexCoord2f(0.0f, 1.0f); glVertex3f(300, -300, -300);
glTexCoord2f(0.0f, 0.0f); glVertex3f(300, 300, -300);
glTexCoord2f(1.0f, 0.0f); glVertex3f(300, 300, -300);
glTexCoord2f(1.0f, 1.0f); glVertex3f(300, -300, -300);
glTexCoord2f(0.0f, 1.0f); glVertex3f(300, -300, 300);
glTexCoord2f(0.0f, 0.0f); glVertex3f(300, 300, 300);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-300, 300, 300);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-300, -300, 300);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-300, -300, -300);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-300, 300, -300);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-300, -300, 300);
glTexCoord2f(1.0f, 1.0f); glVertex3f(300, -300, 300);
glTexCoord2f(0.0f, 1.0f); glVertex3f(300, -300, -300);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-300, -300, -300);
glEnd();
glDisable(GL_TEXTURE_2D);
return true;
}
GLvoid createWin(char* title, GLfloat winWidth, GLfloat winHeight) {
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(winWidth, winHeight);
glutInitWindowPosition(200, 200);
wnd = glutCreateWindow(title);
}
GLvoid renderScene(GLvoid)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
drawGLScene();
glutPostRedisplay();
glutSwapBuffers();
}
GLvoid keyPressed(unsigned char key, int x, int y) {
if (key == VK_ESCAPE) {
glutDestroyWindow(wnd);
exit(0);
}
if (key == 'd')
cameraRotation -= 5;
if (key == 'a')
cameraRotation += 5;
if (key == 'w')
cameraTilt = cameraTilt == 90 ? 90 : cameraTilt + 5;
if (key == 's')
cameraTilt = cameraTilt == -20 ? -20 : cameraTilt - 5;
}
/*int main() {
setlocale(LC_ALL, "Russian");
printf("Введите количество шаров (0 - тестовый режим)\n");
int n;
scanf("%d", &n);
if (n == 0) {
printf("Тесты:\n0. Обычная симуляция, 27 частиц\n");
printf("1. Диффузия. 500 + 500 частиц\n");
printf("2. Броуновское движение, 63 частицы + 1 макрочастица\n");
printf("Введите номер теста: ");
scanf("%d", &n);
test(n);
initVariables();
}
else {
printf("Введите параметры каждого из N шаров через пробел:\n");
printf("Координаты X, Y, Z, Компоненты скорости по X, Y, Z, радиус, масса\n");
for (int i = 0; i < n; i++) {
double x, y, z, vx, vy, vz, r, m;
scanf("%lf %lf %lf %lf %lf %lf %lf %lf", &x, &y, &z, &vx, &vy, &vz, &r, &m);
particles[i] = Particle(x, y, z, vx, vy, vz, r, m);
}
}
currentTime = 0.0;
createWin("Balls Collision", 800, 600);
initGLScene();
glutDisplayFunc(renderScene);
glutIdleFunc(idle);
glutReshapeFunc(resizeGLScene);
glutKeyboardFunc(keyPressed);
glutMainLoop();
}*/
int main() {
currentTime = 0.0;
Catch::Session().run();
}
void catchTest() {
double targetTime;
for (;;) {
//glutDisplayFunc(renderScene);
static bool flag = true;
static bool cycle = true;
for (; cycle;) {
Event currentEvent = !ct.empty() ? ct.top() : dummy;
if (currentEvent.wasSuperveningEvent()) {
ct.pop();
continue;
}
for (int i = 0; i < PARTICLES_COUNT; i++) {
particles[i].move(currentEvent.getTime() - currentTime);
}
currentTime = currentEvent.getTime();
if (currentTime > 1000) {
if (flag) {
for (int i = 0; i < PARTICLES_COUNT; i++) {
particles[i].setVel(-particles[i].getVel());
}
targetTime = currentTime;
currentTime = 0.0;
ct = std::priority_queue<Event>();
initVariables();
flag = false;
}
}
if (!flag && fabs(currentTime - targetTime) < 1e-8)
return;
if (currentEvent.getType() == 4) {
currentEvent.getParticle1()->bounce(currentEvent.getParticle2());
currentEvent.getParticle1()->updateEvents();
currentEvent.getParticle2()->updateEvents();
}
if (currentEvent.getType() == 1) {
currentEvent.getParticle1()->bounceX();
currentEvent.getParticle1()->updateEvents();
}
if (currentEvent.getType() == 2) {
currentEvent.getParticle1()->bounceY();
currentEvent.getParticle1()->updateEvents();
}
if (currentEvent.getType() == 3) {
currentEvent.getParticle1()->bounceZ();
currentEvent.getParticle1()->updateEvents();
}
if (currentEvent.getType() == 0) {
ct.pop();
ct.push(Event(currentTime + timeStep, nullptr, nullptr, 0));
break;
}
continue;
}
//glutReshapeFunc(resizeGLScene);
//glutKeyboardFunc(keyPressed);
}
}
/*void idle() {
for (;cycle;) {
Event currentEvent = !ct.empty() ? ct.top() : dummy;
if (currentEvent.wasSuperveningEvent()) {
ct.pop();
continue;
}
for (int i = 0; i < PARTICLES_COUNT; i++) {
particles[i].move(currentEvent.getTime() - currentTime);
}
currentTime = currentEvent.getTime();
if (currentTime > 1000) {
if (flag) {
for (int i = 0; i < PARTICLES_COUNT; i++) {
particles[i].setVel(-particles[i].getVel());
}
currentTime = 0.0;
ct = std::priority_queue<Event>();
initVariables();
flag = false;
}
else
cycle = false;
}
if (currentEvent.getType() == 4) {
currentEvent.getParticle1()->bounce(currentEvent.getParticle2());
currentEvent.getParticle1()->updateEvents();
currentEvent.getParticle2()->updateEvents();
}
if (currentEvent.getType() == 1) {
currentEvent.getParticle1()->bounceX();
currentEvent.getParticle1()->updateEvents();
}
if (currentEvent.getType() == 2) {
currentEvent.getParticle1()->bounceY();
currentEvent.getParticle1()->updateEvents();
}
if (currentEvent.getType() == 3) {
currentEvent.getParticle1()->bounceZ();
currentEvent.getParticle1()->updateEvents();
}
if (currentEvent.getType() == 0) {
ct.pop();
ct.push(Event(currentTime + timeStep, nullptr, nullptr, 0));
break;
}
continue;
}
}*/
GLvoid initVariables() {
for (int i = 0; i < PARTICLES_COUNT; i++) {
particles[i].updateEvents();
}
ct.push(Event(currentTime + timeStep, nullptr, nullptr, 0));
cylinderObj = gluNewQuadric(); //объект для сферы
gluQuadricTexture(cylinderObj, GL_TRUE);
}
GLboolean loadTexture(LPTSTR szFileName, GLuint &texid) {
HBITMAP hBMP;
BITMAP BMP;
glGenTextures(1, &texid);
hBMP = (HBITMAP)LoadImage(GetModuleHandle(NULL), szFileName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE);
if (!hBMP)
return FALSE;
GetObject(hBMP, sizeof(BMP), &BMP);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glBindTexture(GL_TEXTURE_2D, texid);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 3, BMP.bmWidth, BMP.bmHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, BMP.bmBits);
DeleteObject(hBMP);
return true;
}
void test(int i) {
int lattice_x, lattice_y, lattice_z;
switch (i) {
case 0:
PARTICLES_COUNT = 27;
lattice_x = 3, lattice_y = 3, lattice_z = 3;
for (int z = 0; z < lattice_z; z++) {
for (int y = 0; y < lattice_y; y++) {
for (int x = 0; x < lattice_x; x++) {
particles[x + z * lattice_y * lattice_x + y * lattice_x] =
Particle(-250.0 + x * 100.0, y * 100.0 - 200.0, -250.0 + z * 100.0, 0.0, 0.0, 0.0, 1.0, 20.0);
}
}
}
particles[0] =
Particle(0.0, 0.0, 0.0, -7.0, -5.0, -2.0, 1.0, 20.0);
break;
case 1:
PARTICLES_COUNT = 1000;
velocityColor = false;
lattice_x = 10, lattice_y = 10, lattice_z = 10;
for (int z = 0; z < lattice_z; z++) {
for (int y = 0; y < lattice_y; y++) {
for (int x = 0; x < lattice_x; x++) {
Particle ball = Particle(-270.0 + x * 45, y * 45 - 270.0, -250.0 + z * 50,
((rand() % 50) - 5) / 10.0, ((rand() % 50) - 5) / 10.0, ((rand() % 50) - 5) / 10.0,
1.0, 15);
x < 5 ? ball.setColor(1, 1, 1) : ball.setColor(0, 0, 0);
particles[x + z * lattice_y * lattice_x + y * lattice_x] =
ball;
}
}
}
particles[0] =
Particle(-250.0, -200.0, -150.0,
10.0, 10.0, 10.0,
1.0, 15);
break;
case 2:
PARTICLES_COUNT = 64;
lattice_x = 8, lattice_y = 8, lattice_z = 1;
for (int z = 0; z < lattice_z; z++) {
for (int y = 0; y < lattice_y; y++) {
for (int x = 0; x < lattice_x; x++) {
particles[x + z * lattice_y * lattice_x + y * lattice_x] =
Particle(-250.0 + x * 50, y * 50 - 200.0, -250.0 + z * 100,
rand() % 10 / 2.0, rand() % 10 / 2.0, rand() % 10 / 2.0,
1.0, 10);
}
}
}
particles[0] =
Particle(0.0,0.0,0.0,
0.0,0.0,0.0,
100.0, 65);
break;
case 3:
velocityColor = false;
lattice_x = 2;
PARTICLES_COUNT = lattice_x * lattice_x * lattice_x;
for (int z = 0; z < lattice_z; z++) {
for (int y = 0; y < lattice_y; y++) {
for (int x = 0; x < lattice_x; x++) {
Particle ball = Particle(-270.0 + x * 45, y * 45 - 270.0, -250.0 + z * 50,
((rand() % 50) - 5) / 10.0, ((rand() % 50) - 5) / 10.0, ((rand() % 50) - 5) / 10.0,
1.0, 15);
x < 5 ? ball.setColor(1, 1, 1) : ball.setColor(0, 0, 0);
particles[x + z * lattice_y * lattice_x + y * lattice_x] =
ball;
}
}
}
break;
case 4:
PARTICLES_COUNT = 2;
particles[0] =
Particle(5.0, 0.0, 100.0,
0.0, 0.0, -1.0,
1.0, 20);
particles[1] =
Particle(-5.0, 0.0, -100.0,
0.0, 0.0, 1.0,
1.0, 20);
break;
case 5:
PARTICLES_COUNT = 27;
lattice_x = 3, lattice_y = 3, lattice_z = 3;
for (int z = 0; z < lattice_z; z++) {
for (int y = 0; y < lattice_y; y++) {
for (int x = 0; x < lattice_x; x++) {
particles[x + z * lattice_y * lattice_x + y * lattice_x] =
Particle(-250.0 + x * 100.0, y * 100.0 - 200.0, -250.0 + z * 100.0, 0.0, 0.0, 0.0, 1.0, 20.0);
particlesTest[x + z * lattice_y * lattice_x + y * lattice_x] =
Particle(-250.0 + x * 100.0, y * 100.0 - 200.0, -250.0 + z * 100.0, 0.0, 0.0, 0.0, 1.0, 20.0);
}
}
}
particles[0] =
Particle(0.0, 0.0, 0.0, -7.0, -5.0, -2.0, 1.0, 20.0);
particlesTest[0] =
Particle(0.0, 0.0, 0.0, -7.0, -5.0, -2.0, 1.0, 20.0);
break;
break;
}
}
|
e84941b4fc01f5a32cf905d7b79683443ebc3fa5
|
1f78692f10efe1b9d172869b34f16aaf3c14e1f0
|
/1114PrintInOrder.cpp
|
6e4ed8e265e0f7c52c47a18946592c63f968daa8
|
[] |
no_license
|
isVoid/Leet_codebase
|
5b2a77f87639f24dd81d9c2e23f24fffc2c1c179
|
e28685d84248f26462eede0513aa2853528b37c2
|
refs/heads/master
| 2022-01-22T17:06:56.399192
| 2019-07-20T03:19:01
| 2019-07-20T03:19:01
| 197,872,934
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,203
|
cpp
|
1114PrintInOrder.cpp
|
#include <iostream>
#include <vector>
#include <tuple>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include "dbg.hpp"
using namespace std;
struct ListNode;
struct TreeNode;
class Foo {
public:
void acquire(bool &mutex) {
while (mutex) {
//busy wait
}
mutex = true;
}
void release(bool &mutex) {
mutex = false;
}
bool mutex1, mutex2;
Foo() {
mutex1 = true;
mutex2 = true;
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
release(mutex1);
}
void second(function<void()> printSecond) {
acquire(mutex1);
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
release(mutex2);
}
void third(function<void()> printThird) {
acquire(mutex2);
// printThird() outputs "third". Do not change or remove this line.
printThird();
release(mutex2);
}
};
int main(int argc, char ** argv) {
return 0;
}
|
fcf82b365a7c9cecbe0fef1ce2181fcba127e4ef
|
1791461e6740f81c2dd6704ae6a899a6707ee6b1
|
/Codeforces/103D.cpp
|
4bff76a37cb78e1d842076d8f12f33fcb03aa461
|
[
"MIT"
] |
permissive
|
HeRaNO/OI-ICPC-Codes
|
b12569caa94828c4bedda99d88303eb6344f5d6e
|
4f542bb921914abd4e2ee7e17d8d93c1c91495e4
|
refs/heads/master
| 2023-08-06T10:46:32.714133
| 2023-07-26T08:10:44
| 2023-07-26T08:10:44
| 163,658,110
| 22
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 943
|
cpp
|
103D.cpp
|
#include <bits/stdc++.h>
#define MAXN 300005
using namespace std;
struct D
{
int a,b,c;
bool operator < (const D &a)const{
return b<a.b;
}
};
D b[MAXN];
int n,m,T,a[MAXN];
long long c[MAXN],ans[MAXN];
inline void calc(int x)
{
for (int i=n;i;i--)
{
c[i]=a[i];
if (i+x<=n) c[i]+=c[i+x];
}
return ;
}
inline void read(int &x)
{
x=0;char ch=getchar();
while (ch<'0'||ch>'9') ch=getchar();
while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return ;
}
int main()
{
read(n);for (int i=1;i<=n;i++) read(a[i]);m=(int)sqrt(n);
read(T);for (int i=1;i<=T;i++) read(b[i].a),read(b[i].b),b[i].c=i;
sort(b+1,b+T+1);int cur=1;
for (;b[cur].b<=m&&cur<=T;cur++)
{
if (b[cur].b!=b[cur-1].b) calc(b[cur].b);
ans[b[cur].c]=c[b[cur].a];
}
for (long long res=0;cur<=T;cur++,res=0)
{
for (int j=b[cur].a;j<=n;j+=b[cur].b) res+=a[j];
ans[b[cur].c]=res;
}
for (int i=1;i<=T;i++) printf("%lld\n",ans[i]);
return 0;
}
|
cad89e0b5c57089290fa91260640c16a419f0aad
|
ae9f6d6e4c7b569f4c216987cbcebb99be33bc91
|
/src/questionmark.cpp
|
5068f01ee06882c41468c38b120135dc08ace3d1
|
[] |
no_license
|
Azerrroth/CodeRio-Qt5
|
a2effcd94c97fd065229d05f4d66ef6142826890
|
7a9bce0a6721b463791010fb9bc6ed727648f07e
|
refs/heads/master
| 2022-06-23T21:18:30.658124
| 2019-05-14T14:10:39
| 2019-05-14T14:10:39
| 141,132,433
| 5
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 602
|
cpp
|
questionmark.cpp
|
#include "questionmark.h"
#include <QGraphicsObject>
#include <QPixmap>
#include <QPainter>
questionMark::questionMark()
{
m_pix_one.load("src/queblock.png");
isHitted = false;
}
QRectF questionMark::boundingRect() const {
double penwidth = 1;
return QRect(0 - penwidth / 2, 0 - penwidth / 2,
49 + penwidth, 49 + penwidth);
}
void questionMark::change()
{
m_pix_one.load("src/queblock1.png");
update();
}
void questionMark::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
Q_UNUSED(option);
Q_UNUSED(widget);
painter->drawPixmap(0, 0, m_pix_one);
}
|
44077ebb2d0a8665cbe9077a526143e92773002f
|
db3033246bb9edc514d19e0c604e5cc7c41ff6e3
|
/week3/袁娇/8-1 生化危机.cpp
|
34f1e27839839cb0fe03375d301e4ae54aa6c7cb
|
[] |
no_license
|
1525125249/NEUQ-ACM-Solution
|
2945a96659ccc5b5294a358564291c758feffce9
|
f651574880b6974b12e5dbc28f78d9bf4c1694b3
|
refs/heads/main
| 2023-08-27T17:56:56.052183
| 2021-11-07T05:14:30
| 2021-11-07T05:14:30
| 425,413,832
| 0
| 0
| null | 2021-11-07T04:40:57
| 2021-11-07T04:40:57
| null |
GB18030
|
C++
| false
| false
| 870
|
cpp
|
8-1 生化危机.cpp
|
#include <iostream>
using namespace std;
#define MAXN 111
typedef struct
{
int arcs[MAXN][MAXN];
int vex,arc;
}Graph;
int main()
{
int n;//n个安全城市
Graph G;
cin>>G.vex>>n>>G.arc;
int safecity[MAXN];
for(int i=0;i<n;i++)
{
cin>>safecity[i];
}
G.arcs[MAXN][MAXN] =0;
while(G.arc--)
{
int x,y;
scanf("%d %d",&x,&y);
G.arcs[x][y]=1;
G.arcs[y][x]=1;
}
int now,destination,flag=0;
scanf("%d %d",&now,&destination);
for(int i=0;i<n;i++)
{
if(destination==safecity[i])
{
flag=1;
break;
}
}
if(G.arcs[now][destination]==1)
{
if(flag)
printf("The city %d can arrive safely!\n",destination);
else
{
printf("The city %d is not safe!\n",destination);
}
}
else
{
if(flag)
printf("The city %d can not arrive safely!\n",destination);
else printf("The city %d is not safe!\n",destination);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.