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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b32aa846c0281581dfd5683d0e1453a2f874c010
|
55ba956a151844d92f784627543b46592c9c4313
|
/BCAL.cpp
|
1dbaac5e038663defc5deec60acaad414cbfbca7
|
[] |
no_license
|
sheenxavi004/Coding-Ninjas
|
9303574b4ee025ee05bb996783c0dc7ed3062eb6
|
6a38663bb5f179ea884e6369c75746e2004c3a89
|
refs/heads/master
| 2022-11-08T22:35:34.181417
| 2020-06-26T07:50:39
| 2020-06-26T07:50:39
| 275,101,177
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 746
|
cpp
|
BCAL.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int m;
cin >> m;
vector<int> ans;
int n;
cin >> n;
while(n--)
{
string a;
cin >> a;
int carry = 0;
if(ans.empty())
{
for(int i = m - 1 ; i >= 0 ; i--)
{
int a_bit = a[i] - 48;
ans.push_back(a_bit);
}
}
else
{
int size = ans.size();
for(int i = size - 1 ; i >= 0 ; i--)
{
int a_bit = 0 ;
if(i >= size - m)
a_bit = a[i - (size - m)] - 48;
int sum = a_bit + ans[size - i - 1] + carry;
ans[size - i + 1] = sum % 2;
carry = sum / 2;
}
while(carry > 0)
{
ans.push_back(carry % 2);
carry /= 2;
}
}
}
int size = ans.size();
for(int i = size - 1; i >= 0 ; i--)
{
cout << ans[i];
}
return 0;
}
|
09385c0f743f570e9b0798f31276b296bccbd087
|
6517df3e19322929cb7d6de28d75b6a58fb129f8
|
/classes/implementation/userCode_test_soilwat_simulate.cpp
|
b02bfaea41c2efaca81a576b1a604b4be4000ca1
|
[
"MIT"
] |
permissive
|
tpilz/echse_engines
|
81ebd77cc0480ad49d96e8291f00b11ed5fa187b
|
96de4b8af730f439d759aaaeb8958dfeebf884e5
|
refs/heads/master
| 2023-02-08T10:21:06.155226
| 2023-02-02T17:32:28
| 2023-02-02T17:32:28
| 39,507,604
| 1
| 1
| null | 2015-07-22T13:29:13
| 2015-07-22T13:29:12
| null |
UTF-8
|
C++
| false
| false
| 4,694
|
cpp
|
userCode_test_soilwat_simulate.cpp
|
// save initial values of runoff components
double surf_sat_init = stateScal(runst_surf_sat);
double surf_inf_init = stateScal(runst_surf_inf);
double sub_init = stateScal(runst_sub);
double gw_init = stateScal(runst_gw);
// scaling of ksat
vector<double> ksat_scale(stateVect(wc).size());
for (unsigned int i=0; i<stateVect(wc).size(); i++)
ksat_scale[i] = paramFun(ksat,i+1) / sharedParamNum(scale_ks);
// compute initial states of hydraulic properties at very first time step (-9999. given as initial value; no need to compute within pre-processing)
// vector<double> mat_pot_t(stateVect(wc).size());
// vector<double> ku_t(stateVect(wc).size());
// vector<double> wc_a(stateVect(wc).size());
// if( abs(stateVect(mat_pot)[0] + 9999.) < 0.01 ){
// // get actual soil moisture states
// wc_a = stateVect(wc);
//
// // calculate matric potential
// for (unsigned int i=0; i<stateVect(wc).size(); i++)
// mat_pot_t[i] = matric_pot(sharedParamNum(ch_soilmod), wc_a[i], paramFun(wc_sat,i+1), paramFun(wc_res,i+1), paramFun(pores_ind,i+1), paramFun(bubble,i+1), sharedParamNum(na_val));
//
// set_stateVect(mat_pot) = mat_pot_t;
//
// // calculate conductivity
// for (unsigned int i=0; i<stateVect(wc).size(); i++)
// ku_t[i] = k_unsat(sharedParamNum(ch_soilmod), wc_a[i], paramFun(wc_sat,i+1), paramFun(wc_res,i+1), paramFun(pores_ind,i+1), paramFun(ksat,i+1), sharedParamNum(na_val));
//
// set_stateVect(k_u) = ku_t;
// }
// vector with all state variables
vector<double> states_all;
states_all.insert(states_all.end(), stateScal_all().begin(), stateScal_all().end());
// Put wc and hydraulic properties at the end to access the other variables via their pre-defined index in derivsScal()
states_all.insert(states_all.end(), stateVect(wc).begin(), stateVect(wc).end());
// states_all.insert(states_all.end(), stateVect(mat_pot).begin(), stateVect(mat_pot).end());
// states_all.insert(states_all.end(), stateVect(k_u).begin(), stateVect(k_u).end());
// update soil water storage by Numerical ODE integration (see *serivsScal.cpp)
odesolve_nonstiff(
states_all, // Initial value(s) of state variable(s)
delta_t, // Length of time step
sharedParamNum(ode_accuracy),// Accuracy (in case of soil moisture 1e-3 is equivalent to 1 mm for a horizon of 1 m thickness)
sharedParamNum(ode_max_iter),// Maximum number of sub-steps
this, // Pointer to this object
states_all,// New value(s) of state variable(s)
sharedParamNum(ch_odesolve) // choice flag of method for numerical integration
);
// UPDATE STORAGES
vector<double> wc_a(stateVect(wc).size());
vector<double> state_t(stateScal_all().size());
for (unsigned int i=0; i<stateScal_all().size(); i++)
state_t[i] = states_all[i];
set_stateScal_all() = state_t;
for (unsigned int i=0; i<stateVect(wc).size(); i++)
wc_a[i] = states_all[stateScal_all().size()+i];
set_stateVect(wc) = wc_a;
// soil hydraulic head / matric potential / capillary suction (m of water)/(100 hPa)
vector<double> mat_pot_t(stateVect(wc).size());
for (unsigned int i=0; i<stateVect(wc).size(); i++)
mat_pot_t[i] = matric_pot(sharedParamNum(ch_soilmod), wc_a[i], paramFun(wc_sat,i+1), paramFun(wc_res,i+1), paramFun(pores_ind,i+1), paramFun(bubble,i+1), sharedParamNum(na_val));
set_stateVect(mat_pot) = mat_pot_t;
// hydraulic conductivity (m/s)
vector<double> ku_t(stateVect(wc).size());
for (unsigned int i=0; i<stateVect(wc).size(); i++)
ku_t[i] = k_unsat(sharedParamNum(ch_soilmod), wc_a[i], paramFun(wc_sat,i+1), paramFun(wc_res,i+1), paramFun(pores_ind,i+1), ksat_scale[i], sharedParamNum(na_val));
set_stateVect(k_u) = ku_t;
// OUTPUT (m/s)
// calculate averages of wc and wc_sat
double w = -9999.;
double wc_sat_av = 0.;
double wc_a_av = 0.;
for (unsigned int i=0; i<wc_a.size(); i++) {
w = paramFun(hor_depth,i+1)/paramNum(soil_depth);
wc_sat_av += paramFun(wc_sat,i+1) * w;
wc_a_av += wc_a[i] * w;
}
// calculate saturation of soil (-)
double f_sat = f_saturation(
wc_a_av,
wc_sat_av,
sharedParamNum(var1),
sharedParamNum(var2),
sharedParamNum(var3),
sharedParamNum(var4),
sharedParamNum(var5),
sharedParamNum(frac1),
sharedParamNum(frac2),
sharedParamNum(frac3),
sharedParamNum(frac4),
sharedParamNum(frac5)
);
set_output(saturation) = f_sat;
set_output(run_surf_sat) = (stateScal(runst_surf_sat) - surf_sat_init) / delta_t;
set_output(run_surf_inf) = (stateScal(runst_surf_inf) - surf_inf_init) / delta_t;
set_output(run_surf) = ( (stateScal(runst_surf_sat)+stateScal(runst_surf_inf)) - (surf_sat_init+surf_inf_init) ) / delta_t;
set_output(run_sub) = (stateScal(runst_sub) - sub_init) / delta_t ;
set_output(run_gw) = (stateScal(runst_gw) - gw_init) / delta_t ;
|
76db75daa3296ddc5396dfabcb9018451f7499f5
|
511e5a4dca0455a7309f05e514eda244170d5eaa
|
/src/utilities/wrappers/mpi_wrapper.hpp
|
99f31da2703e6d68eac64d4860c238c55e26f57f
|
[] |
no_license
|
SimonDavenport/quantum_state_neural_network
|
278ac2a95c647aad03108b979d641ba39d278a11
|
9935d42b3f5350414ce6ab82b438507187b1ea4b
|
refs/heads/master
| 2021-01-17T10:12:47.868856
| 2017-06-05T12:19:44
| 2017-06-05T12:19:44
| 84,007,660
| 4
| 1
| null | 2017-06-05T12:14:24
| 2017-03-05T22:40:09
|
Roff
|
UTF-8
|
C++
| false
| false
| 17,878
|
hpp
|
mpi_wrapper.hpp
|
////////////////////////////////////////////////////////////////////////////////
//!
//! \author Simon C. Davenport
//!
//! \file
//! This file contains a bunch of functions used for MPI programming
//! Examples at https://computing.llnl.gov/tutorials/mpi/
//!
//! Copyright (C) Simon C Davenport
//!
//! 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 3 of the License,
//! or (at your option) any later version.
//!
//! This program is distributed in the hope that it will be useful, but
//! WITHOUT ANY WARRANTY; without even the implied warranty of
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//! General Public License for more details.
//!
//! You should have received a copy of the GNU General Public License
//! along with this program. If not, see <http://www.gnu.org/licenses/>.
//!
////////////////////////////////////////////////////////////////////////////////
#ifndef _MPI_WRAPPED_HPP_INCLUDED_
#define _MPI_WRAPPED_HPP_INCLUDED_
/////// LIBRARY INCLUSIONS /////////////////////////////////////////////
#include "../general/dcmplx_type_def.hpp"
#include "../general/cout_tools.hpp"
#include "../general/template_tools.hpp"
#include <mpi.h>
#include <iomanip>
#include <string.h>
#include <vector>
#include <chrono>
#include <cstdint>
namespace utilities
{
////////////////////////////////////////////////////////////////////////////////
//! \brief A struct of variables and functions that can be used
//! to pass MPI interface between functions
//!
//! These functions use the mpi/h library.
//! Examples at https://computing.llnl.gov/tutorials/mpi/
////////////////////////////////////////////////////////////////////////////////
struct MpiWrapper
{
std::chrono::high_resolution_clock::time_point m_wallTime;
//!< Keep track of the time taken during the program run
//!
int m_nbrProcs; //!< Number of processor cores available
//!
int m_id; //!< Processor core identification number
//!
std::vector<std::string> m_hosts;
//!< Array to store host names of all process on
//!
int m_firstTask;
//!< Lowest task index for a parallelized task
//!
int m_lastTask;
//!< Highest task index for a parallelized task
//!
bool m_exitFlag;//!< Flag to exit MPI process on all cores
//!
MPI_Comm m_comm;//!< MPI communicator
//!
Cout* m_cout; //!< a Cout object pointer, to control output
//! verbosity levels
bool m_coutExternal;
//!< Flag to keep track of whether to delete the
//! Cout object or not when the class destructor is
//! called (avoiding multiple deletions of the object)
////////////////////////////////////////////////////////////////////////////////
//! \brief Default constructor
//!
//! (default to using the global interface COMM_WORLD)
////////////////////////////////////////////////////////////////////////////////
MpiWrapper()
:
m_comm(MPI_COMM_WORLD),
m_coutExternal(false)
{
m_cout = new Cout; // Construct a default version of the object
// and set it to that all output will be displayed
m_cout->SetVerbosity(0);
}
////////////////////////////////////////////////////////////////////////////////
//! \brief Constructor to redirect the class internal verbosity object
//! (m_cout) to an external instance.
////////////////////////////////////////////////////////////////////////////////
MpiWrapper(Cout& cout)
:
m_comm(MPI_COMM_WORLD),
m_coutExternal(true)
{
m_cout = &cout;
}
////////////////////////////////////////////////////////////////////////////////
//! \brief Destructor. This function is designed to be executed when
//! the program terminates (which you can do by implementing this class
//! globally)
////////////////////////////////////////////////////////////////////////////////
~MpiWrapper()
{
if(m_id==0) // FOR THE MASTER NODE //
{
m_cout->MainOutput()<<"\n\t\tPROGRAM TERMINATED ";
TimeStamp();
auto duration = std::chrono::high_resolution_clock::now() - m_wallTime;
auto hours = std::chrono::duration_cast<std::chrono::hours>(duration);
auto minutes = std::chrono::duration_cast<std::chrono::minutes>(duration-hours);
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration-hours-minutes);
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration-hours-minutes-seconds);
m_cout->MainOutput()<<"\t\tTIME ELAPSED "<<hours.count()<<" HOURS "<<minutes.count()<<" MINUTES "<<seconds.count()<<"."<<millis.count()<<" SECONDS.\n"<<std::endl;
m_cout->MainOutput()<<"------------------------------------------------------------------------------------------"<<std::endl;
m_cout->MainOutput()<<"------------------------------------------------------------------------------------------"<<std::endl;
}
if(!m_coutExternal)
{
delete m_cout;
}
MPI_Finalize();
return;
}
// Define MPI utility functions
void TimeStamp() const;
void DivideTasks(const int id, const int nbrTasks, int nbrProcs,
int* firstTask, int* lastTask, const bool display) const;
void TriangularDivideTasks(const int id, const int nbrTasks, int nbrProcs,
int* firstTask, int* lastTask, const bool display) const;
void Init(int argc, char *argv[]);
void Init(int argc, char *argv[],bool);
void ExitFlagTest();
void GenerateHostNameList();
void Sync(std::string& buffer, int syncNode) const;
////////////////////////////////////////////////////////////////////////////////
//! \brief A function to implement MPI Gather, but with different sizes of
//! buffer on each node (the standard MPI_Gather assumes the buffer sizes are
//! identical on all nodes).
////////////////////////////////////////////////////////////////////////////////
template<typename T>
void Gather(
T* sendBuffer, //!< Send buffer
int sendCount, //!< Size of send buffer (can be different for each node)
T* recvBuffer, //!< Receive buffer: MUST BE OF TOTAL sendCount dimension
//! on the node where the data are sent to. Not addressed
//! on other nodes.
int recvCount, //!< Size of the recvBuffer
int gatherId, //!< id of the processor where the data are to be gathered
MPI_Comm comm, //!< mpi communicator
MPI_Status status) //!< mpi status
const
{
int nbrProcs;
int id;
MPI_Comm_size(comm, &nbrProcs);
MPI_Comm_rank(comm, &id);
if(id == gatherId)
{
int cumulativeSize = 0;
for(int i=0; i<nbrProcs; ++i)
{
if(i != gatherId)
{
int recv;
// Receive the buffer size first
MPI_Recv(&recv, 1, MPI_INT, i, 40+2*i, comm, &status);
// Receive the buffer contents
MPI_Recv(recvBuffer+cumulativeSize, recv, this->GetType<T>(), i, 40+2*i+1, comm, &status);
cumulativeSize += recv;
}
else
{
memcpy(recvBuffer+cumulativeSize, sendBuffer, sizeof(T)*sendCount);
cumulativeSize += sendCount;
}
}
}
else
{
// Send the buffer size first
MPI_Send(&sendCount, 1, MPI_INT, gatherId, 40+2*id, comm);
// Send the buffer contents
MPI_Send(sendBuffer, sendCount, this->GetType<T>(), gatherId, 40+2*id+1, comm);
}
MPI_Barrier(comm);
return;
}
////////////////////////////////////////////////////////////////////////////////
//! \brief A function to implement MPI Scatter, but with different sizes of
//! buffer on each node (the standard MPI_Scatter assumes the buffer sizes are
//! identical on all nodes).
////////////////////////////////////////////////////////////////////////////////
template<typename T>
void Scatter(
T* sendBuffer, //!< Send buffer MUST BE OF TOTAL recvCount dimension
//! on the node where the data are sent from. Not addressed
//! on other nodes.
int sendCount, //!< Size of send buffer
T* recvBuffer, //!< Receive buffer
int recvCount, //!< Size of the recvBuffer (can be different for each node)
int scatterId, //!< id of the processor where the data are to be scattered
MPI_Comm comm, //!< mpi communicator
MPI_Status status) //!< mpi status
const
{
int nbrProcs;
int id;
MPI_Comm_size(comm, &nbrProcs);
MPI_Comm_rank(comm, &id);
if(id == scatterId)
{
int cumulativeSize = 0;
for(int i=0; i<nbrProcs; ++i)
{
if(i != scatterId)
{
int send;
// Receive the buffer size first
MPI_Recv(&send, 1, MPI_INT, i, 40+2*i, comm, &status);
// Send the buffer contents
MPI_Send(sendBuffer+cumulativeSize, send, this->GetType<T>(), i, 40+2*i+1, comm);
cumulativeSize += send;
}
else
{
memcpy(recvBuffer, sendBuffer+cumulativeSize, sizeof(T)*recvCount);
cumulativeSize += recvCount;
}
}
}
else
{
// Send the buffer size first
MPI_Send(&recvCount, 1, MPI_INT, scatterId, 40+2*id, comm);
// Receive the buffer contents
MPI_Recv(recvBuffer, recvCount, this->GetType<T>(), scatterId, 40+2*id+1, comm, &status);
}
MPI_Barrier(comm);
return;
}
////////////////////////////////////////////////////////////////////////////////
//! \brief A function to implement MPI Reduce, but with different sizes of
//! buffer on each node (the standard MPI_Reduce assumes the buffer sizes are
//! identical on all nodes).
//!
//! Note: if the send and recieve buffers are the same on the reduce node
//! then copying the reduce node allocation is ignored.
//!
//! The function is currently set up to sum the array values sent back to the
//! reduce node
////////////////////////////////////////////////////////////////////////////////
template<typename T>
void Reduce(
T* reduceBuffer, //!< Buffer containing the input/output
T* recvBuffer, //!< Buffer to received mpi messages from other nodes
int bufferCount, //!< Size of both the recvBuffer and the sendBuffer
int reduceId, //!< id of the processor where the data are to be reduced
MPI_Comm comm, //!< mpi communicator
MPI_Status status) //!< mpi status
const
{
int nbrProcs;
int id;
MPI_Comm_size(comm, &nbrProcs);
MPI_Comm_rank(comm, &id);
if(reduceBuffer == recvBuffer)
{
std::cerr<<"ERROR WITH mpi.Reduce - reduce and recv buffers must have different addresses!"<<std::endl;
exit(EXIT_FAILURE);
}
if(id == reduceId)
{
// Recieve all other data
for(int i=0; i<nbrProcs; ++i)
{
if(i != reduceId)
{
// Receive the buffer contents
MPI_Recv(recvBuffer, bufferCount, this->GetType<T>(), i, 40+2*i+1, comm, &status);
// Add to the reduce buffer
for(int j=0; j<bufferCount; ++j)
{
reduceBuffer[j] += recvBuffer[j];
}
}
}
}
else
{
// Send the buffer contents
MPI_Send(reduceBuffer, bufferCount, this->GetType<T>(), reduceId, 40+2*id+1, comm);
}
MPI_Barrier(comm);
return;
}
////////////////////////////////////////////////////////////////////////////////
//! \brief A template function to convert a given c variable type
//! into an appropriate MPI type.
//!
//! \return An MPI type determined by the template argument T.
//! Default return is MPI_CHAR.
////////////////////////////////////////////////////////////////////////////////
template<typename T>
MPI_Datatype GetType() const
{
// Integer types
if(is_same<T, uint64_t>::value) return MPI_UINT64_T;
if(is_same<T, unsigned long int>::value) return MPI_UNSIGNED_LONG;
if(is_same<T, uint32_t>::value) return MPI_UINT32_T;
if(is_same<T, unsigned int>::value) return MPI_UNSIGNED;
if(is_same<T, uint16_t>::value) return MPI_UINT16_T;
if(is_same<T, unsigned short int>::value)return MPI_UNSIGNED_SHORT;
if(is_same<T, uint8_t>::value) return MPI_UINT8_T;
if(is_same<T, int64_t>::value) return MPI_INT64_T;
if(is_same<T, long int>::value) return MPI_LONG;
if(is_same<T, int32_t>::value) return MPI_INT32_T;
if(is_same<T, int>::value) return MPI_INT;
if(is_same<T, int16_t>::value) return MPI_INT16_T;
if(is_same<T, short int>::value) return MPI_SHORT;
if(is_same<T, int8_t>::value) return MPI_INT8_T;
// Real types
if(is_same<T, double>::value) return MPI_DOUBLE;
if(is_same<T, float>::value) return MPI_FLOAT;
// Complex types
if(is_same<T, dcmplx>::value) return MPI_DOUBLE_COMPLEX;
// Bool types
if(is_same<T, bool>::value) return MPI_C_BOOL;
// Char types
if(is_same<T, unsigned char>::value) return MPI_UNSIGNED_CHAR;
if(is_same<T, char>::value) return MPI_CHAR;
// Default return
return MPI_CHAR;
}
////////////////////////////////////////////////////////////////////////////////
//! \brief A template function to synchronize a given buffer, using the GetType
//! function to automatically set the correct type
////////////////////////////////////////////////////////////////////////////////
template<typename T>
void Sync(
T* buffer, //!< Pointer to the broadcast buffer
int bufferSize, //!< Size of the buffer
int syncNode) //!< Node to synchronize the buffer with
const
{
MPI_Bcast(buffer, bufferSize, this->GetType<T>(), syncNode, m_comm);
}
////////////////////////////////////////////////////////////////////////////////
//! \brief A function to MPI synchronize a std::vector
////////////////////////////////////////////////////////////////////////////////
template <typename T>
void Sync(
std::vector<T>* buffer, //!< Broadcast buffer
int syncNode) //!< Node to synchronize the buffer with
const
{
unsigned long int bufferSize = 0;
if(syncNode == m_id)
{
bufferSize = buffer->size();
}
MPI_Bcast(&bufferSize, 1, this->GetType<unsigned long int>(), syncNode, m_comm);
buffer->resize(bufferSize);
this->Sync<T>(buffer->data(),bufferSize,syncNode);
}
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\//
};
} // End namespace utilities
#endif
|
9e523406d302bdb1d56987e8ea71f8d5c1eb5b2a
|
fbe68d84e97262d6d26dd65c704a7b50af2b3943
|
/third_party/virtualbox/src/VBox/Runtime/r3/linux/mp-linux.cpp
|
7ba407875c43ff4ab944671c484e5149f89b3a8f
|
[
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"CDDL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"GPL-2.0-or-later",
"MPL-1.0",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"OpenSSL",
"MIT"
] |
permissive
|
thalium/icebox
|
c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb
|
6f78952d58da52ea4f0e55b2ab297f28e80c1160
|
refs/heads/master
| 2022-08-14T00:19:36.984579
| 2022-02-22T13:10:31
| 2022-02-22T13:10:31
| 190,019,914
| 585
| 109
|
MIT
| 2022-01-13T20:58:15
| 2019-06-03T14:18:12
|
C++
|
UTF-8
|
C++
| false
| false
| 9,424
|
cpp
|
mp-linux.cpp
|
/* $Id: mp-linux.cpp $ */
/** @file
* IPRT - Multiprocessor, Linux.
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#define LOG_GROUP RTLOGGROUP_SYSTEM
#include <stdio.h>
#include <errno.h>
#include <iprt/mp.h>
#include "internal/iprt.h"
#include <iprt/alloca.h>
#include <iprt/cpuset.h>
#include <iprt/assert.h>
#include <iprt/string.h>
#include <iprt/linux/sysfs.h>
/**
* Internal worker that determines the max possible CPU count.
*
* @returns Max cpus.
*/
static RTCPUID rtMpLinuxMaxCpus(void)
{
#if 0 /* this doesn't do the right thing :-/ */
int cMax = sysconf(_SC_NPROCESSORS_CONF);
Assert(cMax >= 1);
return cMax;
#else
static uint32_t s_cMax = 0;
if (!s_cMax)
{
int cMax = 1;
for (unsigned iCpu = 0; iCpu < RTCPUSET_MAX_CPUS; iCpu++)
if (RTLinuxSysFsExists("devices/system/cpu/cpu%d", iCpu))
cMax = iCpu + 1;
ASMAtomicUoWriteU32((uint32_t volatile *)&s_cMax, cMax);
return cMax;
}
return s_cMax;
#endif
}
/**
* Internal worker that picks the processor speed in MHz from /proc/cpuinfo.
*
* @returns CPU frequency.
*/
static uint32_t rtMpLinuxGetFrequency(RTCPUID idCpu)
{
FILE *pFile = fopen("/proc/cpuinfo", "r");
if (!pFile)
return 0;
char sz[256];
RTCPUID idCpuFound = NIL_RTCPUID;
uint32_t Frequency = 0;
while (fgets(sz, sizeof(sz), pFile))
{
char *psz;
if ( !strncmp(sz, RT_STR_TUPLE("processor"))
&& (sz[10] == ' ' || sz[10] == '\t' || sz[10] == ':')
&& (psz = strchr(sz, ':')))
{
psz += 2;
int64_t iCpu;
int rc = RTStrToInt64Ex(psz, NULL, 0, &iCpu);
if (RT_SUCCESS(rc))
idCpuFound = iCpu;
}
else if ( idCpu == idCpuFound
&& !strncmp(sz, RT_STR_TUPLE("cpu MHz"))
&& (sz[10] == ' ' || sz[10] == '\t' || sz[10] == ':')
&& (psz = strchr(sz, ':')))
{
psz += 2;
int64_t v;
int rc = RTStrToInt64Ex(psz, &psz, 0, &v);
if (RT_SUCCESS(rc))
{
Frequency = v;
break;
}
}
}
fclose(pFile);
return Frequency;
}
/** @todo RTmpCpuId(). */
RTDECL(int) RTMpCpuIdToSetIndex(RTCPUID idCpu)
{
return idCpu < rtMpLinuxMaxCpus() ? (int)idCpu : -1;
}
RTDECL(RTCPUID) RTMpCpuIdFromSetIndex(int iCpu)
{
return (unsigned)iCpu < rtMpLinuxMaxCpus() ? iCpu : NIL_RTCPUID;
}
RTDECL(RTCPUID) RTMpGetMaxCpuId(void)
{
return rtMpLinuxMaxCpus() - 1;
}
RTDECL(bool) RTMpIsCpuOnline(RTCPUID idCpu)
{
/** @todo check if there is a simpler interface than this... */
int64_t i = 0;
int rc = RTLinuxSysFsReadIntFile(0, &i, "devices/system/cpu/cpu%d/online", (int)idCpu);
if ( RT_FAILURE(rc)
&& RTLinuxSysFsExists("devices/system/cpu/cpu%d", (int)idCpu))
{
/** @todo Assert(!RTLinuxSysFsExists("devices/system/cpu/cpu%d/online",
* (int)idCpu));
* Unfortunately, the online file wasn't always world readable (centos
* 2.6.18-164). */
i = 1;
rc = VINF_SUCCESS;
}
AssertMsg(i == 0 || i == -1 || i == 1, ("i=%d\n", i));
return RT_SUCCESS(rc) && i != 0;
}
RTDECL(bool) RTMpIsCpuPossible(RTCPUID idCpu)
{
/** @todo check this up with hotplugging! */
return RTLinuxSysFsExists("devices/system/cpu/cpu%d", (int)idCpu);
}
RTDECL(PRTCPUSET) RTMpGetSet(PRTCPUSET pSet)
{
RTCpuSetEmpty(pSet);
RTCPUID cMax = rtMpLinuxMaxCpus();
for (RTCPUID idCpu = 0; idCpu < cMax; idCpu++)
if (RTMpIsCpuPossible(idCpu))
RTCpuSetAdd(pSet, idCpu);
return pSet;
}
RTDECL(RTCPUID) RTMpGetCount(void)
{
RTCPUSET Set;
RTMpGetSet(&Set);
return RTCpuSetCount(&Set);
}
RTDECL(RTCPUID) RTMpGetCoreCount(void)
{
RTCPUID cMax = rtMpLinuxMaxCpus();
uint32_t *paidCores = (uint32_t *)alloca(sizeof(paidCores[0]) * (cMax + 1));
uint32_t *paidPckgs = (uint32_t *)alloca(sizeof(paidPckgs[0]) * (cMax + 1));
uint32_t cCores = 0;
for (RTCPUID idCpu = 0; idCpu < cMax; idCpu++)
{
if (RTMpIsCpuPossible(idCpu))
{
int64_t idCore = 0;
int64_t idPckg = 0;
int rc = RTLinuxSysFsReadIntFile(0, &idCore, "devices/system/cpu/cpu%d/topology/core_id", (int)idCpu);
if (RT_SUCCESS(rc))
rc = RTLinuxSysFsReadIntFile(0, &idPckg, "devices/system/cpu/cpu%d/topology/physical_package_id", (int)idCpu);
if (RT_SUCCESS(rc))
{
uint32_t i;
for (i = 0; i < cCores; i++)
if ( paidCores[i] == (uint32_t)idCore
&& paidPckgs[i] == (uint32_t)idPckg)
break;
if (i >= cCores)
{
paidCores[cCores] = (uint32_t)idCore;
paidPckgs[cCores] = (uint32_t)idPckg;
cCores++;
}
}
}
}
Assert(cCores > 0);
return cCores;
}
RTDECL(PRTCPUSET) RTMpGetOnlineSet(PRTCPUSET pSet)
{
RTCpuSetEmpty(pSet);
RTCPUID cMax = rtMpLinuxMaxCpus();
for (RTCPUID idCpu = 0; idCpu < cMax; idCpu++)
if (RTMpIsCpuOnline(idCpu))
RTCpuSetAdd(pSet, idCpu);
return pSet;
}
RTDECL(RTCPUID) RTMpGetOnlineCount(void)
{
RTCPUSET Set;
RTMpGetOnlineSet(&Set);
return RTCpuSetCount(&Set);
}
RTDECL(RTCPUID) RTMpGetOnlineCoreCount(void)
{
RTCPUID cMax = rtMpLinuxMaxCpus();
uint32_t *paidCores = (uint32_t *)alloca(sizeof(paidCores[0]) * (cMax + 1));
uint32_t *paidPckgs = (uint32_t *)alloca(sizeof(paidPckgs[0]) * (cMax + 1));
uint32_t cCores = 0;
for (RTCPUID idCpu = 0; idCpu < cMax; idCpu++)
{
if (RTMpIsCpuOnline(idCpu))
{
int64_t idCore = 0;
int64_t idPckg = 0;
int rc = RTLinuxSysFsReadIntFile(0, &idCore, "devices/system/cpu/cpu%d/topology/core_id", (int)idCpu);
if (RT_SUCCESS(rc))
rc = RTLinuxSysFsReadIntFile(0, &idPckg, "devices/system/cpu/cpu%d/topology/physical_package_id", (int)idCpu);
if (RT_SUCCESS(rc))
{
uint32_t i;
for (i = 0; i < cCores; i++)
if ( paidCores[i] == idCore
&& paidPckgs[i] == idPckg)
break;
if (i >= cCores)
{
paidCores[cCores] = idCore;
paidPckgs[cCores] = idPckg;
cCores++;
}
}
}
}
Assert(cCores > 0);
return cCores;
}
RTDECL(uint32_t) RTMpGetCurFrequency(RTCPUID idCpu)
{
int64_t kHz = 0;
int rc = RTLinuxSysFsReadIntFile(0, &kHz, "devices/system/cpu/cpu%d/cpufreq/cpuinfo_cur_freq", (int)idCpu);
if (RT_FAILURE(rc))
{
/*
* The file may be just unreadable - in that case use plan B, i.e.
* /proc/cpuinfo to get the data we want. The assumption is that if
* cpuinfo_cur_freq doesn't exist then the speed won't change, and
* thus cur == max. If it does exist then cpuinfo contains the
* current frequency.
*/
kHz = rtMpLinuxGetFrequency(idCpu) * 1000;
}
return (kHz + 999) / 1000;
}
RTDECL(uint32_t) RTMpGetMaxFrequency(RTCPUID idCpu)
{
int64_t kHz = 0;
int rc = RTLinuxSysFsReadIntFile(0, &kHz, "devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", (int)idCpu);
if (RT_FAILURE(rc))
{
/*
* Check if the file isn't there - if it is there, then /proc/cpuinfo
* would provide current frequency information, which is wrong.
*/
if (!RTLinuxSysFsExists("devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", (int)idCpu))
kHz = rtMpLinuxGetFrequency(idCpu) * 1000;
else
kHz = 0;
}
return (kHz + 999) / 1000;
}
|
147a4e89076ecf6efcb5910f45949005bea421f1
|
89f30a997d0ae6d634e0f8c861b7a101f8a7b57e
|
/10square/Source.cpp
|
076c28c14d6b56d2c4070e4894818bc4da695fd5
|
[] |
no_license
|
Napassawan/10square
|
178be62d8da0614d22d8c07bf73fab72e69e220c
|
78ae3a00c1e3f4166ad2580f095e02a0df8845d4
|
refs/heads/master
| 2022-12-28T02:49:25.546993
| 2020-10-14T17:06:49
| 2020-10-14T17:06:49
| 304,080,558
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 334
|
cpp
|
Source.cpp
|
#include <stdio.h>
int a, r, star;
void square(int);
int main()
{
printf("Enter number of rows : ");
scanf_s("%d", &a);
square(a);
}
void square(int a)
{
for (r = 1; r <= a; r++)
{
for (star = 1; star <= a; star++)
{
if (r % 2 == 0)
{
printf("1");
}
else
{
printf("0");
}
}
printf("\n");
}
}
|
2a9726dac441421f049974ac8e727bdee4704590
|
c66541f5cf90e75933a85851c38ea1a03e8dc233
|
/Chapter9/Inserting a Range of Elements.cpp
|
fe9a552ab8b2cd52f0f3cb8190148801e93fb296
|
[] |
no_license
|
Chase07/Cpp-Primer-Exercise
|
ce89266d54f41ace27ce8fbb54281757b291fb34
|
bd33cba4b7213ecaa23c8437080dbc6289cd9d80
|
refs/heads/master
| 2021-08-22T06:21:21.902266
| 2017-11-29T13:51:53
| 2017-11-29T13:51:53
| 112,478,205
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 428
|
cpp
|
Inserting a Range of Elements.cpp
|
#include<iostream>
#include<vector>
#include<list>
#include<string>
using namespace::std;
int main()
{
vector<string> svec{"Hello!"};
list<string> slist;
slist.insert(slist.begin(), "over!");
svec.insert(svec.begin(), 9, "Hi!");
slist.insert(slist.begin(), svec.end() - 1, svec.end());
slist.insert(slist.end(), { "Let", "it", "go", "~~~" });
for (auto& i : slist)
{
cout << i << " ";
}
cout << endl;
return 0;
}
|
9bf7416e5009517d98429acb9ba3a6d3d57d81bc
|
314ddc4c5d39c5670ce31f094e9983ff838f95a5
|
/HugCoffe/HugCoffe/MenuModifyDlg.cpp
|
dd07de400849be053a208b74270464d10e91b837
|
[] |
no_license
|
sc545/DB-Project
|
24d2534e2d8598bb915e5157bc8adbfac5380472
|
38681815e372f0306a0d95707e82ba3e109d3670
|
refs/heads/master
| 2021-01-18T23:55:21.701797
| 2015-12-16T20:52:27
| 2015-12-16T20:52:27
| 47,829,197
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 3,564
|
cpp
|
MenuModifyDlg.cpp
|
// MenuModifyDlg.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "HugCoffe.h"
#include "MenuModifyDlg.h"
#include "afxdialogex.h"
#include "tblBeverage.h"
#include "tblSide.h"
// CMenuModifyDlg 대화 상자입니다.
IMPLEMENT_DYNAMIC(CMenuModifyDlg, CDialogEx)
CMenuModifyDlg::CMenuModifyDlg(CWnd* pParent /*=NULL*/, CString name, LONG price, LONG id, int selectedMenu)
: CDialogEx(CMenuModifyDlg::IDD, pParent)
, m_strMenuName(name)
, m_lMenuPrice(price)
, m_lMenuId(id)
, m_iSelectedMenu(selectedMenu)
{
}
CMenuModifyDlg::~CMenuModifyDlg()
{
}
BOOL CMenuModifyDlg::OnInitDialog(){
CDialog::OnInitDialog();
// 다이얼로그 초기화 코드 작성
m_editMenuName.SetWindowTextW(m_strMenuName.Trim());
CString str;
str.Format(_T("%ld"), m_lMenuPrice);
m_editMenuPrice.SetWindowTextW(str);
return TRUE;
}
void CMenuModifyDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT_MENU_NAME, m_editMenuName);
DDX_Control(pDX, IDC_EDIT_MENU_PRICE, m_editMenuPrice);
}
BEGIN_MESSAGE_MAP(CMenuModifyDlg, CDialogEx)
ON_BN_CLICKED(ID_BUTTON_MENU_OK, &CMenuModifyDlg::OnClickedButtonMenuOk)
ON_BN_CLICKED(ID_BUTTON_MENU_CANCEL, &CMenuModifyDlg::OnClickedButtonMenuCancel)
END_MESSAGE_MAP()
// CMenuModifyDlg 메시지 처리기입니다.
void CMenuModifyDlg::OnClickedButtonMenuOk()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
CtblBeverage<CtblBeverageUpdateAccessor> updateBeverage;
CtblSide<CtblSideUpdateAccessor> updateSide;
m_editMenuName.GetWindowTextW(m_strMenuName);
CString str;
m_editMenuPrice.GetWindowTextW(str);
m_lMenuPrice = _wtol(str);
if(m_iSelectedMenu == 0){
if(m_strMenuName.GetLength()<1){
AfxMessageBox(_T("메뉴이름을 입력해주세요!!"));
}else if(str.GetLength()<1){
AfxMessageBox(_T("메뉴가격을 입력해주세요!!"));
}else{
wcscpy_s((wchar_t*)updateBeverage.m_bev_name, 20, (const wchar_t*)m_strMenuName.GetBuffer(m_strMenuName.GetLength()));
updateBeverage.m_dwbev_nameLength = wcslen((const wchar_t*)m_strMenuName.GetBuffer(m_strMenuName.GetLength()))*2;
updateBeverage.m_dwbev_nameStatus = DBSTATUS_S_OK;
updateBeverage.m_bev_price = m_lMenuPrice;
updateBeverage.m_dwbev_priceStatus = DBSTATUS_S_OK;
updateBeverage.m_bev_id = m_lMenuId;
updateBeverage.m_dwbev_idStatus = DBSTATUS_S_OK;
if(updateBeverage.OpenAll() == S_OK){
EndDialog(1);
}else{
AfxMessageBox(_T("데이터베이스 접속 실패!!"));
}
}
}
if(m_iSelectedMenu == 1){
if(m_strMenuName.GetLength()<1){
AfxMessageBox(_T("메뉴이름을 입력해주세요!!"));
}else if(str.GetLength()<1){
AfxMessageBox(_T("메뉴가격을 입력해주세요!!"));
}else{
wcscpy_s((wchar_t*)updateSide.m_side_name, 20, (const wchar_t*)m_strMenuName.GetBuffer(m_strMenuName.GetLength()));
updateSide.m_dwside_nameLength = wcslen((const wchar_t*)m_strMenuName.GetBuffer(m_strMenuName.GetLength()))*2;
updateSide.m_dwside_nameStatus = DBSTATUS_S_OK;
updateSide.m_side_price = m_lMenuPrice;
updateSide.m_dwside_priceStatus = DBSTATUS_S_OK;
updateSide.m_side_id = m_lMenuId;
updateSide.m_dwside_idStatus = DBSTATUS_S_OK;
if(updateSide.OpenAll() == S_OK){
EndDialog(1);
}else{
AfxMessageBox(_T("데이터베이스 접속 실패!!"));
}
}
}
updateBeverage.CloseAll();
updateSide.CloseAll();
}
void CMenuModifyDlg::OnClickedButtonMenuCancel()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
EndDialog(0);
}
|
6238b9b987a3ac87344fb1a65e9070c362f3212c
|
7fd64b86c7e8f63d6238fe93ccf6e62a4b8ebc66
|
/codeforces/1349/B.cpp
|
d58d4fe67c7c3626fef35eec30917e4a38aa3c01
|
[] |
no_license
|
Mohammad-Yasser/harwest
|
775ba71303cc2849f71e82652263f31e79bd8e04
|
d01834a9a41c828c8c548a115ecefd77ff2d6adc
|
refs/heads/master
| 2023-02-02T23:37:54.186079
| 2013-09-19T19:28:00
| 2020-12-21T14:30:32
| 323,233,072
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,606
|
cpp
|
B.cpp
|
#ifndef Local
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,sse4.2,popcnt,abm,mmx,avx")
#endif
#include <bits/stdc++.h>
#include <ext/numeric>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace __gnu_cxx;
using namespace std;
#define popCnt(x) (__builtin_popcountll(x))
#define sz(x) ((int)(x.size()))
#define all(v) begin(v), end(v)
typedef long long Long;
typedef double Double;
const int N = 2e5 + 5;
int arr[N];
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
#ifdef Local
freopen("test.in", "r", stdin);
#else
#define endl '\n'
#endif
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
bool k_appeared = false;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (x == k) {
x = 1;
k_appeared = true;
} else if (x < k) {
x = 0;
} else if (x > k) {
x = 2;
}
arr[i] = x;
}
if (!k_appeared) {
cout << "no" << endl;
continue;
}
if (n == 1) {
cout << "yes" << endl;
continue;
}
bool valid = false;
for (int i = 0; i + 1 < n; ++i) {
int tmp = (!arr[i] + !arr[i + 1]);
if (tmp == 0) {
valid = true;
break;
}
if (i + 2 < n) {
tmp += !arr[i + 2];
if (tmp == 1) {
valid = true;
break;
}
}
}
cout << (valid ? "yes" : "no") << endl;
}
return 0;
}
|
2bb70ea45d19e07931e55f6e359cb7d56cba2838
|
1958153475715dfc266cbc469a8d5ccaa6241c8b
|
/mc/semantics.hpp
|
4a8bf84b8509c9cc45e016690a718aba99ae0709
|
[] |
no_license
|
tdotdev/mcc
|
6b64416ece570af8c5f2cbe0fc1b70ad04172174
|
1594efdd040ac9b4ae6b2748bb4a438ab17d9179
|
refs/heads/master
| 2021-09-14T07:43:09.956575
| 2018-05-10T03:25:19
| 2018-05-10T03:25:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,259
|
hpp
|
semantics.hpp
|
#pragma once
#include <vector>
#include <unordered_map>
#include "expression.hpp"
#include "statement.hpp"
#include "declaration.hpp"
#include "type.hpp"
#include "token.hpp"
#include "scope.hpp"
struct Semantics {
Semantics()
{
sem_scope = new scope(global);
}
scope* sem_scope;
decl* new_program(std::vector<decl*> dec_seq);
decl* new_var_decl(token* tok, type* t);
decl* new_var_def(decl* var_decl, expr* e);
decl* new_const_decl(token* tok, type* t);
decl* new_const_def(decl* var_decl, expr* e);
decl* new_val_decl(token* tok, type* t);
decl* new_val_def(decl* var_decl, expr* e);
decl* new_func_decl(token* tok, std::vector<decl*> params, type* t);
decl* new_func_def(decl* func_decl, stmt* func_body);
decl* new_param(token* param, type* t);
stmt* new_block_stmt(std::vector<stmt*> stmt_seq);
stmt* new_if_stmt(expr* condition, stmt* if_true, stmt* if_false);
stmt* new_while_stmt(expr* condition, stmt* statement);
stmt* new_break_stmt();
stmt* new_continue_stmt();
stmt* new_return_stmt(expr* expression);
stmt* new_decl_stmt(decl* declaration);
stmt* new_expr_stmt(expr* expression);
expr* new_boolean_literal(token* tok);
expr* new_integer_literal(token* tok);
expr* new_float_literal(token* tok);
expr* new_char_literal(token* tok);
expr* new_string_literal(token* tok);
expr* new_identifier(token* tok);
expr* new_postfix_expr(expr* expression, std::vector<expr*> args);
expr* new_unary_expr(token_name unary_op, expr* expression);
expr* new_cast_expr(expr* cast_expr, type* ts);
expr* new_mul_expr(token_name mul_op, expr* lhs, expr* rhs);
expr* new_add_expr(token_name add_op, expr* lhs, expr* rhs);
expr* new_shift_expr(token_name shift_op, expr* lhs, expr* rhs);
expr* new_rel_expr(token_name rel_op, expr* lhs, expr* rhs);
expr* new_eq_expr(token_name eq_op, expr* lhs, expr* rhs);
expr* new_bw_and_expr(expr* lhs, expr* rhs);
expr* new_bw_xor_expr(expr* lhs, expr* rhs);
expr* new_bw_or_expr(expr* lhs, expr* rhs);
expr* new_log_and_expr(expr* lhs, expr* rhs);
expr* new_log_or_expr(expr* lhs, expr* rhs);
expr* new_cond_expr(expr* expr1, expr* expr2, expr* expr3);
expr* new_assign_expr(expr* lhs, expr* rhs);
type* new_void_type();
type* new_bool_type();
type* new_int_type();
type* new_float_type();
type* new_char_type();
type* new_string_type();
type* new_func_type(std::vector<type*> params, type_t ret_type);
type* new_ptr_type(type* ptr_to);
type* new_ref_type(type* ref_to);
void new_global_scope();;
void new_param_scope();
void new_block_scope();
void exit_current_scope();
// Semantic helper functions
decl* lookup(std::string id);
type* common_type_of(expr* e1, expr* e2);
type* verify_conversion(expr* e, type* t);
type* val_conv(expr* e);
expr* basic_to_bool(expr* e);
expr* to_int(expr* e);
expr* to_float(expr*e);
void assert_type(expr* e, type_t t);
void assert_reference(expr* e);
void assert_same_type(expr* e1, expr* e2);
void assert_arithmetic(expr* e);
void assert_int(expr* e);
void assert_scalar(expr* e);
bool is_scalar(expr* e);
bool is_reference(expr* e);
bool is_same_type(expr* e1, expr* e2);
bool is_type(expr* e, type* t);
bool is_arithmetic(expr* e);
bool is_int(expr* e);
bool val_conv_is(expr* e, type* t);
};
|
222a9e96603d4689766859a41c1c6a4961a460d3
|
c3de57676ebc2c4f6d0849347798534f85ab9a72
|
/GUILib/include/GUILib/Plot.h
|
a21432341dbc6fe0ed4e14b2137c992b190e6fb8
|
[] |
no_license
|
plusminus34/Interactive_thin_shells_Bachelor_thesis
|
0662f6d88d76d8d49b2b6066bf1d2b0fc258f01e
|
85f034a476eeab8d485f19a6ea3208498061a4da
|
refs/heads/main
| 2023-03-10T15:15:53.666726
| 2021-02-24T08:01:25
| 2021-02-24T08:01:25
| 341,820,202
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,867
|
h
|
Plot.h
|
/*
Plot.h -- Plot widget, based off nanogui/graph.h
*/
#pragma once
#include <nanogui/widget.h>
#include <Eigen/Eigen>
struct PlotData
{
public:
PlotData() {}
PlotData(const Eigen::VectorXf &xValues, const Eigen::VectorXf &yValues)
: mXValues(xValues), mYValues(yValues){
updateMinMax();
}
PlotData(const Eigen::VectorXf &xValues, const Eigen::VectorXf &yValues, const nanogui::Color &color, float width = 1)
: mXValues(xValues), mYValues(yValues), mColor(color), mWidth(width){
updateMinMax();
}
int getClosestDataPointIndex(float x) const;
void updateMinMax();
Eigen::VectorXf mXValues;
Eigen::VectorXf mYValues;
Eigen::Vector2f mMinVal;
Eigen::Vector2f mMaxVal;
nanogui::Color mColor = nanogui::Color(1.f, 1.f, 1.f, 1.f);
float mWidth = 1;
};
class Plot : public nanogui::Widget {
public:
Plot(nanogui::Widget *parent, const std::string &caption = "Untitled");
const std::string &caption() const { return mCaption; }
void setCaption(const std::string &caption) { mCaption = caption; }
const std::string &header() const { return mHeader; }
void setHeader(const std::string &header) { mHeader = header; }
const std::string &footer() const { return mFooter; }
void setFooter(const std::string &footer) { mFooter = footer; }
const nanogui::Color &backgroundColor() const { return mBackgroundColor; }
void setBackgroundColor(const nanogui::Color &backgroundColor) { mBackgroundColor = backgroundColor; }
const nanogui::Color &foregroundColor() const { return mForegroundColor; }
void setForegroundColor(const nanogui::Color &foregroundColor) { mForegroundColor = foregroundColor; }
const nanogui::Color &textColor() const { return mTextColor; }
void setTextColor(const nanogui::Color &textColor) { mTextColor = textColor; }
bool showLegend() const { return mShowLegend; }
void setShowLegend(bool showLegend) { mShowLegend = showLegend; }
const PlotData &plotData(const std::string &name) const { return mDataColl.at(name); }
PlotData &plotData(const std::string &name) { return mDataColl[name]; }
void setPlotData(const std::string &name, const PlotData &data);
void clearPlotData();
const std::map<std::string, PlotData> &dataColl() { return mDataColl; }
// TODO: come up with better names
void updateMinMax();
const Eigen::Vector2f &dataMin() const { return mDataMin; }
void setDataMin(const Eigen::Vector2f &dataMin) { mDataMin = dataMin; }
const Eigen::Vector2f &dataMax() const { return mDataMax; }
void setDataMax(const Eigen::Vector2f &dataMax) { mDataMax = dataMax; }
bool showTicks() const { return mShowTicks; }
void setShowTicks(bool showTicks) { mShowTicks = showTicks; }
const Eigen::Vector2i &numTicks() const { return mNumTicks; }
void setNumTicks(const Eigen::Vector2i &numTicks) { mNumTicks = numTicks; }
virtual bool mouseMotionEvent(const Eigen::Vector2i &p, const Eigen::Vector2i &rel, int button, int modifiers);
// TODO: should we rather override `preferredSize` or use `setSize` from `Widget`?
// virtual Eigen::Vector2i preferredSize(NVGcontext *ctx) const override;
virtual void draw(NVGcontext *ctx) override;
virtual void save(nanogui::Serializer &s) const override;
virtual bool load(nanogui::Serializer &s) override;
private:
float scaledXValue(float value) { return (value-mDataMin(0))/(mDataMax(0)-mDataMin(0)); }
float scaledYValue(float value) { return (value-mDataMin(1))/(mDataMax(1)-mDataMin(1)); }
float computeTickStep(int dim) const;
static float computeMagnitude(float x);
protected:
std::string mCaption, mHeader, mFooter;
nanogui::Color mBackgroundColor, mForegroundColor, mTextColor;
bool mShowLegend, mShowTicks;
Eigen::Vector2i mNumTicks;
int mTickHeight;
std::map<std::string, PlotData> mDataColl;
Eigen::Vector2f mDataMin, mDataMax;
std::map<std::string, int> mDataHighlight;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
|
dac5511481d27aecc350492c230a734e28e20ffe
|
3f277f9f4e034d6d47984bdc70a24ba8952e5a1d
|
/src/RcppExports.cpp
|
79ffa89401c9ee0a800001bcf694472faa8af9e0
|
[] |
no_license
|
kkholst/mets
|
42c1827c8ab939b38e68d965c27ffe849bcd6350
|
c1b37b8885d5a9b34688cb4019170a424b7bec70
|
refs/heads/master
| 2023-08-11T17:09:18.762625
| 2023-06-16T07:54:16
| 2023-06-16T07:54:16
| 28,029,335
| 16
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 22,584
|
cpp
|
RcppExports.cpp
|
// Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include "../inst/include/mets.h"
#include <RcppArmadillo.h>
#include <Rcpp.h>
#include <string>
#include <set>
using namespace Rcpp;
#ifdef RCPP_USE_GLOBAL_ROSTREAM
Rcpp::Rostream<true>& Rcpp::Rcout = Rcpp::Rcpp_cout_get();
Rcpp::Rostream<false>& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get();
#endif
// ApplyBy2
NumericMatrix ApplyBy2(NumericMatrix idata, NumericVector icluster, SEXP F, Environment Env, std::string Argument, int Columnwise, int Reduce, double epsilon);
RcppExport SEXP _mets_ApplyBy2(SEXP idataSEXP, SEXP iclusterSEXP, SEXP FSEXP, SEXP EnvSEXP, SEXP ArgumentSEXP, SEXP ColumnwiseSEXP, SEXP ReduceSEXP, SEXP epsilonSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericMatrix >::type idata(idataSEXP);
Rcpp::traits::input_parameter< NumericVector >::type icluster(iclusterSEXP);
Rcpp::traits::input_parameter< SEXP >::type F(FSEXP);
Rcpp::traits::input_parameter< Environment >::type Env(EnvSEXP);
Rcpp::traits::input_parameter< std::string >::type Argument(ArgumentSEXP);
Rcpp::traits::input_parameter< int >::type Columnwise(ColumnwiseSEXP);
Rcpp::traits::input_parameter< int >::type Reduce(ReduceSEXP);
Rcpp::traits::input_parameter< double >::type epsilon(epsilonSEXP);
rcpp_result_gen = Rcpp::wrap(ApplyBy2(idata, icluster, F, Env, Argument, Columnwise, Reduce, epsilon));
return rcpp_result_gen;
END_RCPP
}
// ApplyBy
NumericMatrix ApplyBy(NumericMatrix idata, IntegerVector icluster, Function f);
RcppExport SEXP _mets_ApplyBy(SEXP idataSEXP, SEXP iclusterSEXP, SEXP fSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericMatrix >::type idata(idataSEXP);
Rcpp::traits::input_parameter< IntegerVector >::type icluster(iclusterSEXP);
Rcpp::traits::input_parameter< Function >::type f(fSEXP);
rcpp_result_gen = Rcpp::wrap(ApplyBy(idata, icluster, f));
return rcpp_result_gen;
END_RCPP
}
// loglikMVN
arma::mat loglikMVN(arma::mat Yl, SEXP yu, SEXP status, arma::mat Mu, SEXP dmu, arma::mat S, SEXP ds, SEXP z, SEXP su, SEXP dsu, SEXP threshold, SEXP dthreshold, bool Score, double itol);
static SEXP _mets_loglikMVN_try(SEXP YlSEXP, SEXP yuSEXP, SEXP statusSEXP, SEXP MuSEXP, SEXP dmuSEXP, SEXP SSEXP, SEXP dsSEXP, SEXP zSEXP, SEXP suSEXP, SEXP dsuSEXP, SEXP thresholdSEXP, SEXP dthresholdSEXP, SEXP ScoreSEXP, SEXP itolSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< arma::mat >::type Yl(YlSEXP);
Rcpp::traits::input_parameter< SEXP >::type yu(yuSEXP);
Rcpp::traits::input_parameter< SEXP >::type status(statusSEXP);
Rcpp::traits::input_parameter< arma::mat >::type Mu(MuSEXP);
Rcpp::traits::input_parameter< SEXP >::type dmu(dmuSEXP);
Rcpp::traits::input_parameter< arma::mat >::type S(SSEXP);
Rcpp::traits::input_parameter< SEXP >::type ds(dsSEXP);
Rcpp::traits::input_parameter< SEXP >::type z(zSEXP);
Rcpp::traits::input_parameter< SEXP >::type su(suSEXP);
Rcpp::traits::input_parameter< SEXP >::type dsu(dsuSEXP);
Rcpp::traits::input_parameter< SEXP >::type threshold(thresholdSEXP);
Rcpp::traits::input_parameter< SEXP >::type dthreshold(dthresholdSEXP);
Rcpp::traits::input_parameter< bool >::type Score(ScoreSEXP);
Rcpp::traits::input_parameter< double >::type itol(itolSEXP);
rcpp_result_gen = Rcpp::wrap(loglikMVN(Yl, yu, status, Mu, dmu, S, ds, z, su, dsu, threshold, dthreshold, Score, itol));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_loglikMVN(SEXP YlSEXP, SEXP yuSEXP, SEXP statusSEXP, SEXP MuSEXP, SEXP dmuSEXP, SEXP SSEXP, SEXP dsSEXP, SEXP zSEXP, SEXP suSEXP, SEXP dsuSEXP, SEXP thresholdSEXP, SEXP dthresholdSEXP, SEXP ScoreSEXP, SEXP itolSEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_loglikMVN_try(YlSEXP, yuSEXP, statusSEXP, MuSEXP, dmuSEXP, SSEXP, dsSEXP, zSEXP, suSEXP, dsuSEXP, thresholdSEXP, dthresholdSEXP, ScoreSEXP, itolSEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// dmvn
NumericVector dmvn(arma::mat u, arma::mat mu, arma::mat rho);
static SEXP _mets_dmvn_try(SEXP uSEXP, SEXP muSEXP, SEXP rhoSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< arma::mat >::type u(uSEXP);
Rcpp::traits::input_parameter< arma::mat >::type mu(muSEXP);
Rcpp::traits::input_parameter< arma::mat >::type rho(rhoSEXP);
rcpp_result_gen = Rcpp::wrap(dmvn(u, mu, rho));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_dmvn(SEXP uSEXP, SEXP muSEXP, SEXP rhoSEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_dmvn_try(uSEXP, muSEXP, rhoSEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// rmvn
arma::mat rmvn(unsigned n, arma::mat mu, arma::mat rho);
static SEXP _mets_rmvn_try(SEXP nSEXP, SEXP muSEXP, SEXP rhoSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< unsigned >::type n(nSEXP);
Rcpp::traits::input_parameter< arma::mat >::type mu(muSEXP);
Rcpp::traits::input_parameter< arma::mat >::type rho(rhoSEXP);
rcpp_result_gen = Rcpp::wrap(rmvn(n, mu, rho));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_rmvn(SEXP nSEXP, SEXP muSEXP, SEXP rhoSEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_rmvn_try(nSEXP, muSEXP, rhoSEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// rpch
arma::vec rpch(unsigned n, std::vector<double> lambda, std::vector<double> time);
static SEXP _mets_rpch_try(SEXP nSEXP, SEXP lambdaSEXP, SEXP timeSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< unsigned >::type n(nSEXP);
Rcpp::traits::input_parameter< std::vector<double> >::type lambda(lambdaSEXP);
Rcpp::traits::input_parameter< std::vector<double> >::type time(timeSEXP);
rcpp_result_gen = Rcpp::wrap(rpch(n, lambda, time));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_rpch(SEXP nSEXP, SEXP lambdaSEXP, SEXP timeSEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_rpch_try(nSEXP, lambdaSEXP, timeSEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// cpch
arma::vec cpch(arma::vec& x, std::vector<double> lambda, std::vector<double> time);
static SEXP _mets_cpch_try(SEXP xSEXP, SEXP lambdaSEXP, SEXP timeSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< arma::vec& >::type x(xSEXP);
Rcpp::traits::input_parameter< std::vector<double> >::type lambda(lambdaSEXP);
Rcpp::traits::input_parameter< std::vector<double> >::type time(timeSEXP);
rcpp_result_gen = Rcpp::wrap(cpch(x, lambda, time));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_cpch(SEXP xSEXP, SEXP lambdaSEXP, SEXP timeSEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_cpch_try(xSEXP, lambdaSEXP, timeSEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// rchazC
arma::colvec rchazC(const arma::mat& cum, const arma::colvec rr, const arma::colvec entry);
static SEXP _mets_rchazC_try(SEXP cumSEXP, SEXP rrSEXP, SEXP entrySEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< const arma::mat& >::type cum(cumSEXP);
Rcpp::traits::input_parameter< const arma::colvec >::type rr(rrSEXP);
Rcpp::traits::input_parameter< const arma::colvec >::type entry(entrySEXP);
rcpp_result_gen = Rcpp::wrap(rchazC(cum, rr, entry));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_rchazC(SEXP cumSEXP, SEXP rrSEXP, SEXP entrySEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_rchazC_try(cumSEXP, rrSEXP, entrySEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// simGL
arma::mat simGL(const arma::mat& dcum, const arma::colvec& St, const arma::colvec& rr, const arma::colvec& rd, const arma::colvec& z, const arma::colvec& fz, const arma::colvec& tc, const int type, const double theta, const int maxit, const double share);
static SEXP _mets_simGL_try(SEXP dcumSEXP, SEXP StSEXP, SEXP rrSEXP, SEXP rdSEXP, SEXP zSEXP, SEXP fzSEXP, SEXP tcSEXP, SEXP typeSEXP, SEXP thetaSEXP, SEXP maxitSEXP, SEXP shareSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< const arma::mat& >::type dcum(dcumSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type St(StSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type rr(rrSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type rd(rdSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type z(zSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type fz(fzSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type tc(tcSEXP);
Rcpp::traits::input_parameter< const int >::type type(typeSEXP);
Rcpp::traits::input_parameter< const double >::type theta(thetaSEXP);
Rcpp::traits::input_parameter< const int >::type maxit(maxitSEXP);
Rcpp::traits::input_parameter< const double >::type share(shareSEXP);
rcpp_result_gen = Rcpp::wrap(simGL(dcum, St, rr, rd, z, fz, tc, type, theta, maxit, share));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_simGL(SEXP dcumSEXP, SEXP StSEXP, SEXP rrSEXP, SEXP rdSEXP, SEXP zSEXP, SEXP fzSEXP, SEXP tcSEXP, SEXP typeSEXP, SEXP thetaSEXP, SEXP maxitSEXP, SEXP shareSEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_simGL_try(dcumSEXP, StSEXP, rrSEXP, rdSEXP, zSEXP, fzSEXP, tcSEXP, typeSEXP, thetaSEXP, maxitSEXP, shareSEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// simSurvZ
arma::mat simSurvZ(const arma::mat& St, const arma::colvec& rd, const arma::colvec& z, const double theta, const int type);
static SEXP _mets_simSurvZ_try(SEXP StSEXP, SEXP rdSEXP, SEXP zSEXP, SEXP thetaSEXP, SEXP typeSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< const arma::mat& >::type St(StSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type rd(rdSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type z(zSEXP);
Rcpp::traits::input_parameter< const double >::type theta(thetaSEXP);
Rcpp::traits::input_parameter< const int >::type type(typeSEXP);
rcpp_result_gen = Rcpp::wrap(simSurvZ(St, rd, z, theta, type));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_simSurvZ(SEXP StSEXP, SEXP rdSEXP, SEXP zSEXP, SEXP thetaSEXP, SEXP typeSEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_simSurvZ_try(StSEXP, rdSEXP, zSEXP, thetaSEXP, typeSEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// tildeLambda1
arma::mat tildeLambda1(const arma::colvec& dLambda1, const arma::colvec& LambdaD, const arma::colvec& r1, const arma::colvec& rd, const arma::colvec& theta, const IntegerVector id);
static SEXP _mets_tildeLambda1_try(SEXP dLambda1SEXP, SEXP LambdaDSEXP, SEXP r1SEXP, SEXP rdSEXP, SEXP thetaSEXP, SEXP idSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< const arma::colvec& >::type dLambda1(dLambda1SEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type LambdaD(LambdaDSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type r1(r1SEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type rd(rdSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type theta(thetaSEXP);
Rcpp::traits::input_parameter< const IntegerVector >::type id(idSEXP);
rcpp_result_gen = Rcpp::wrap(tildeLambda1(dLambda1, LambdaD, r1, rd, theta, id));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_tildeLambda1(SEXP dLambda1SEXP, SEXP LambdaDSEXP, SEXP r1SEXP, SEXP rdSEXP, SEXP thetaSEXP, SEXP idSEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_tildeLambda1_try(dLambda1SEXP, LambdaDSEXP, r1SEXP, rdSEXP, thetaSEXP, idSEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// tildeLambda1R
arma::mat tildeLambda1R(const arma::colvec& dLambda1, const arma::colvec& LambdaD, const arma::colvec& r1, const arma::colvec& rd, const arma::colvec& theta, const IntegerVector id, const arma::colvec& sign);
static SEXP _mets_tildeLambda1R_try(SEXP dLambda1SEXP, SEXP LambdaDSEXP, SEXP r1SEXP, SEXP rdSEXP, SEXP thetaSEXP, SEXP idSEXP, SEXP signSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::traits::input_parameter< const arma::colvec& >::type dLambda1(dLambda1SEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type LambdaD(LambdaDSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type r1(r1SEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type rd(rdSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type theta(thetaSEXP);
Rcpp::traits::input_parameter< const IntegerVector >::type id(idSEXP);
Rcpp::traits::input_parameter< const arma::colvec& >::type sign(signSEXP);
rcpp_result_gen = Rcpp::wrap(tildeLambda1R(dLambda1, LambdaD, r1, rd, theta, id, sign));
return rcpp_result_gen;
END_RCPP_RETURN_ERROR
}
RcppExport SEXP _mets_tildeLambda1R(SEXP dLambda1SEXP, SEXP LambdaDSEXP, SEXP r1SEXP, SEXP rdSEXP, SEXP thetaSEXP, SEXP idSEXP, SEXP signSEXP) {
SEXP rcpp_result_gen;
{
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = PROTECT(_mets_tildeLambda1R_try(dLambda1SEXP, LambdaDSEXP, r1SEXP, rdSEXP, thetaSEXP, idSEXP, signSEXP));
}
Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error");
if (rcpp_isInterrupt_gen) {
UNPROTECT(1);
Rf_onintr();
}
bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen);
if (rcpp_isLongjump_gen) {
Rcpp::internal::resumeJump(rcpp_result_gen);
}
Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error");
if (rcpp_isError_gen) {
SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen);
UNPROTECT(1);
Rf_error(CHAR(rcpp_msgSEXP_gen));
}
UNPROTECT(1);
return rcpp_result_gen;
}
// validate (ensure exported C++ functions exist before calling them)
static int _mets_RcppExport_validate(const char* sig) {
static std::set<std::string> signatures;
if (signatures.empty()) {
signatures.insert("arma::mat(*.loglikMVN)(arma::mat,SEXP,SEXP,arma::mat,SEXP,arma::mat,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,bool,double)");
signatures.insert("NumericVector(*.dmvn)(arma::mat,arma::mat,arma::mat)");
signatures.insert("arma::mat(*.rmvn)(unsigned,arma::mat,arma::mat)");
signatures.insert("arma::vec(*.rpch)(unsigned,std::vector<double>,std::vector<double>)");
signatures.insert("arma::vec(*.cpch)(arma::vec&,std::vector<double>,std::vector<double>)");
signatures.insert("arma::colvec(*.rchazC)(const arma::mat&,const arma::colvec,const arma::colvec)");
signatures.insert("arma::mat(*.simGL)(const arma::mat&,const arma::colvec&,const arma::colvec&,const arma::colvec&,const arma::colvec&,const arma::colvec&,const arma::colvec&,const int,const double,const int,const double)");
signatures.insert("arma::mat(*.simSurvZ)(const arma::mat&,const arma::colvec&,const arma::colvec&,const double,const int)");
signatures.insert("arma::mat(*.tildeLambda1)(const arma::colvec&,const arma::colvec&,const arma::colvec&,const arma::colvec&,const arma::colvec&,const IntegerVector)");
signatures.insert("arma::mat(*.tildeLambda1R)(const arma::colvec&,const arma::colvec&,const arma::colvec&,const arma::colvec&,const arma::colvec&,const IntegerVector,const arma::colvec&)");
}
return signatures.find(sig) != signatures.end();
}
// registerCCallable (register entry points for exported C++ functions)
RcppExport SEXP _mets_RcppExport_registerCCallable() {
R_RegisterCCallable("mets", "_mets_.loglikMVN", (DL_FUNC)_mets_loglikMVN_try);
R_RegisterCCallable("mets", "_mets_.dmvn", (DL_FUNC)_mets_dmvn_try);
R_RegisterCCallable("mets", "_mets_.rmvn", (DL_FUNC)_mets_rmvn_try);
R_RegisterCCallable("mets", "_mets_.rpch", (DL_FUNC)_mets_rpch_try);
R_RegisterCCallable("mets", "_mets_.cpch", (DL_FUNC)_mets_cpch_try);
R_RegisterCCallable("mets", "_mets_.rchazC", (DL_FUNC)_mets_rchazC_try);
R_RegisterCCallable("mets", "_mets_.simGL", (DL_FUNC)_mets_simGL_try);
R_RegisterCCallable("mets", "_mets_.simSurvZ", (DL_FUNC)_mets_simSurvZ_try);
R_RegisterCCallable("mets", "_mets_.tildeLambda1", (DL_FUNC)_mets_tildeLambda1_try);
R_RegisterCCallable("mets", "_mets_.tildeLambda1R", (DL_FUNC)_mets_tildeLambda1R_try);
R_RegisterCCallable("mets", "_mets_RcppExport_validate", (DL_FUNC)_mets_RcppExport_validate);
return R_NilValue;
}
|
7f136a78480672511ee0a7bbed785d36bc462b57
|
f681c4cd4bec5ec0a724960b89b5ea38318c6168
|
/open.gl/textures/units.cpp
|
a8cdaeb5c9a3d34fdfdfcd89507077ebd214ee4d
|
[] |
no_license
|
bbguimaraes/books
|
3da5948a7c075de2e6b52802266fa358abf80049
|
379107bdc4a89065e07113d581ebc26a50bb603a
|
refs/heads/master
| 2022-06-26T10:59:48.539652
| 2022-06-19T08:39:51
| 2022-06-21T17:06:47
| 182,409,569
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,576
|
cpp
|
units.cpp
|
#include "common.h"
#include <SOIL/SOIL.h>
float vertices[] = {
// pos texcoords
-0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, 0.0f, 1.0f,
};
GLuint elements[] = {
0, 1, 2,
2, 3, 0,
};
const GLchar * vertex_shader_src =
"#version 150 core\n"
"\n"
"in vec2 position;\n"
"in vec2 texcoord;\n"
"\n"
"out vec2 Texcoord;\n"
"\n"
"void main() {\n"
" Texcoord = texcoord;\n"
" gl_Position = vec4(position, 0.0, 1.0);\n"
"}\n";
const GLchar * frag_shader_src =
"#version 150 core\n"
"\n"
"in vec2 Texcoord;\n"
"\n"
"out vec4 outColor;\n"
"\n"
"uniform sampler2D texKitten;\n"
"uniform sampler2D texPuppy;\n"
"\n"
"void main() {\n"
" vec4 colKitten = texture(texKitten, Texcoord);\n"
" vec4 colPuppy = texture(texPuppy, Texcoord);\n"
" outColor = mix(colKitten, colPuppy, 0.5)\n"
" * vec4(1.0, 1.0, 1.0, 1.0);\n"
"}\n";
int main() {
GLFWwindow * window = init();
create_vao();
create_vbo(sizeof(vertices), vertices);
create_ebo(sizeof(elements), elements);
GLuint vertex_shader = create_shader_or_exit(
vertex_shader_src, GL_VERTEX_SHADER);
GLuint frag_shader = create_shader_or_exit(
frag_shader_src, GL_FRAGMENT_SHADER);
GLuint program = create_program(vertex_shader, frag_shader);
GLint pos_attr = glGetAttribLocation(program, "position");
glEnableVertexAttribArray(pos_attr);
glVertexAttribPointer(
pos_attr, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0);
GLint tex_attr = glGetAttribLocation(program, "texcoord");
glEnableVertexAttribArray(tex_attr);
glVertexAttribPointer(
tex_attr, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
reinterpret_cast<void *>(2 * sizeof(float)));
GLint tex = create_texture_from_image("../sample.png", GL_TEXTURE0);
glUniform1i(glGetUniformLocation(program, "texKitten"), 0);
tex = create_texture_from_image("../sample2.png", GL_TEXTURE1);
glUniform1i(glGetUniformLocation(program, "texPuppy"), 1);
while(!glfwWindowShouldClose(window)) {
glfwSwapBuffers(window);
glfwPollEvents();
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
exit_on_gl_error();
}
glfwTerminate();
return 0;
}
|
30853a140c724fd5f7f897e43fb4412ecf8fc59a
|
b50bc7c8a3ee966b05de80a318c94a8c2f616399
|
/old/MPBStreamingSoundWhiteNoise.cpp
|
806de115c88721c6cc09503bf15938ccb039280e
|
[] |
no_license
|
mpb-cal/MPB-Game-Library
|
8420e4c5613f985b9a6d4851ecb0ab0f84b9e69a
|
8d1ead5288f84eb139139b8eb5ffaf52ab4442c8
|
refs/heads/master
| 2020-12-04T10:05:13.961280
| 2020-01-04T06:48:58
| 2020-01-04T06:48:58
| 231,721,364
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 192
|
cpp
|
MPBStreamingSoundWhiteNoise.cpp
|
#include "MPBStreamingSoundWhiteNoise.h"
GGSynthFloat* MPBStreamingSoundWhiteNoise::process()
{
m_umb.clear();
m_uwn.gen( .1f );
m_umb.gen( m_uwn.outputs );
return m_umb.outputs;
}
|
02076a9c1bab7b6ff210de4ed08d1dc78d52633a
|
56c558f4bbcd79447cf072cce75b01f4dc76eb43
|
/Lab 2/StateMachine/StateMachine.ino
|
2d62ca5fa72cada94b7ee4713f759009cb1a7bfb
|
[] |
no_license
|
parzival111/Mobile-Robotics
|
c4f7846ea96618aa9aed1fc84f45e10f41e44d2f
|
bb6a0760126f344b488bc0445d423c3730de37c2
|
refs/heads/master
| 2020-09-26T07:55:45.993869
| 2020-02-19T16:07:15
| 2020-02-19T16:07:15
| 226,208,558
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,296
|
ino
|
StateMachine.ino
|
/*&StateMachine.ino
Author: Carlotta. A. Berry
Date: December 3, 2016
This program will provide a template for an example of implementing a behavior-based control architecture
for a mobile robot to implement obstacle avoidance and random wander. There are many ways to create a state machine
and this is just one. It is to help get you started and brainstorm ideas, you are not required to use it.
Feel free to create your own version of state machine.
The flag byte (8 bits) variable will hold the IR and sonar data [X X snrRight snrLeft irLeft irRight irRear irFront]
The state byte (8 bits) variable will hold the state information as well as motor motion [X X X wander runAway collide rev fwd]
Use the following functions to read, clear and set bits in the byte
bitRead(state, wander)) { // check if the wander state is active
bitClear(state, wander);//clear the the wander state
bitSet(state, wander);//set the wander state
Hardware Connections:
Stepper Enable Pin 48
Right Stepper Step Pin 46
Right Stepper Direction Pin 53
Left Stepper Step Pin 44
Left Stepper Direction Pin 49
Front IR A8
Back IR A9
Right IR A10
Left IR A11
Left Sonar A12
Right Sonar A13
Button A15
*/
#include <AccelStepper.h>//include the stepper motor library
#include <MultiStepper.h>//include multiple stepper motor library
#include <NewPing.h> //include sonar library
#include <TimerOne.h>
//define stepper motor pin numbers
const int rtStepPin = 46; //right stepper motor step pin
const int rtDirPin = 53; // right stepper motor direction pin
const int ltStepPin = 44; //left stepper motor step pin
const int ltDirPin = 49; //left stepper motor direction pin
AccelStepper stepperRight(AccelStepper::DRIVER, rtStepPin, rtDirPin);//create instance of right stepper motor object (2 driver pins, low to high transition step pin 52, direction input pin 53 (high means forward)
AccelStepper stepperLeft(AccelStepper::DRIVER, ltStepPin, ltDirPin);//create instance of left stepper motor object (2 driver pins, step pin 50, direction input pin 51)
MultiStepper steppers;//create instance to control multiple steppers at the same time
//define stepper motor constants
#define stepperEnable 48 //stepper enable pin on stepStick
#define enableLED 13 //stepper enabled LED
#define stepperEnTrue false //variable for enabling stepper motor
#define stepperEnFalse true //variable for disabling stepper motor
#define test_led 13 //test led to test interrupt heartbeat
#define robot_spd 1500 //set robot speed
#define max_accel 10000//maximum robot acceleration
#define max_spd 2500//maximum robot speed
#define quarter_rotation 200 //stepper quarter rotation
#define half_rotation 400 //stepper half rotation
#define one_rotation 800 //stepper motor runs in 1/4 steps so 800 steps is one full rotation
#define two_rotation 1600 //stepper motor 2 rotations
#define three_rotation 2400 //stepper rotation 3 rotations
#define four_rotation 3200 //stepper rotation 3 rotations
#define five_rotation 4000 //stepper rotation 3 rotations
#define irFront A8 //front IR analog pin
#define irRear A9 //back IR analog pin
#define irRight A10 //right IR analog pin
#define irLeft A11 //left IR analog pin
#define snrLeft A12 //front left sonar
#define snrRight A13 //front right sonar
#define button A15 //pushbutton
NewPing sonarLt(snrLeft, snrLeft); //create an instance of the left sonar
NewPing sonarRt(snrRight, snrRight); //create an instance of the right sonar
#define irThresh 400 // The IR threshold for presence of an obstacle
#define snrThresh 5 // The sonar threshold for presence of an obstacle
#define minThresh 0 // The sonar minimum threshold to filter out noise
#define stopThresh 150 // If the robot has been stopped for this threshold move
#define baud_rate 9600//set serial communication baud rate
int irFrontArray[5] = {0, 0, 0, 0, 0}; //array to hold 5 front IR readings
int irRearArray[5] = {0, 0, 0, 0, 0}; //array to hold 5 back IR readings
int irRightArray[5] = {0, 0, 0, 0, 0}; //array to hold 5 right IR readings
int irLeftArray[5] = {0, 0, 0, 0, 0}; //array to hold 5 left IR readings
int irFrontAvg; //variable to hold average of current front IR reading
int irLeftAvg; //variable to hold average of current left IR reading
int irRearAvg; //variable to hold average of current rear IR reading
int irRightAvg; //variable to hold average of current right IR reading
int irIdx = 0;//index for 5 IR readings to take the average
int srLeftArray[5] = {0, 0, 0, 0, 0}; //array to hold 5 left sonar readings
int srRightArray[5] = {0, 0, 0, 0, 0}; //array to hold 5 right sonar readings
int srIdx = 0;//index for 5 sonar readings to take the average
int srLeft; //variable to hold average of left sonar current reading
int srRight; //variable to hold average or right sonar current reading
int srLeftAvg; //variable to holde left sonar data
int srRightAvg; //variable to hold right sonar data
volatile boolean test_state; //variable to hold test led state for timer interrupt
//flag byte to hold sensor data
volatile byte flag = 0; // Flag to hold IR & Sonar data - used to create the state machine
//bit definitions for sensor data flag byte
#define obFront 0 // Front IR trip
#define obRear 1 // Rear IR trip
#define obRight 2 // Right IR trip
#define obLeft 3 // Left IR trip
#define obFLeft 4 // Left Sonar trip
#define obFRight 5 // Right Sonar trip
int count; //count number of times collide has tripped
#define max_collide 250 //maximum number of collides before robot reverses
//state byte to hold robot motion and state data
volatile byte state = 0; //state to hold robot states and motor motion
//bit definitions for robot motion and state byte
#define fwd 0
#define rev 1
#define collide 2
#define runAway 3
#define wander 4
//define layers of subsumption architecture that are active
byte layers = 2; //[wander runAway collide]
//bit definitions for layers
#define cLayer 0
#define rLayer 1
#define wLayer 2
#define timer_int 250000 // 1/2 second (500000 us) period for timer interrupt
void setup()
{
//stepper Motor set up
pinMode(rtStepPin, OUTPUT);//sets pin as output
pinMode(rtDirPin, OUTPUT);//sets pin as output
pinMode(ltStepPin, OUTPUT);//sets pin as output
pinMode(ltDirPin, OUTPUT);//sets pin as output
pinMode(stepperEnable, OUTPUT);//sets pin as output
digitalWrite(stepperEnable, stepperEnFalse);//turns off the stepper motor driver
pinMode(enableLED, OUTPUT);//set LED as output
digitalWrite(enableLED, LOW);//turn off enable LED
stepperRight.setMaxSpeed(max_spd);//set the maximum permitted speed limited by processor and clock speed, no greater than 4000 steps/sec on Arduino
stepperRight.setAcceleration(max_accel);//set desired acceleration in steps/s^2
stepperLeft.setMaxSpeed(max_spd);//set the maximum permitted speed limited by processor and clock speed, no greater than 4000 steps/sec on Arduino
stepperLeft.setAcceleration(max_accel);//set desired acceleration in steps/s^2
stepperRight.setSpeed(robot_spd);//set right motor speed
stepperLeft.setSpeed(robot_spd);//set left motor speed
steppers.addStepper(stepperRight);//add right motor to MultiStepper
steppers.addStepper(stepperLeft);//add left motor to MultiStepper
digitalWrite(stepperEnable, stepperEnTrue);//turns on the stepper motor driver
digitalWrite(enableLED, HIGH);//turn on enable LED
//Timer Interrupt Set Up
Timer1.initialize(timer_int); // initialize timer1, and set a period in microseconds
Timer1.attachInterrupt(updateSensors); // attaches updateSensors() as a timer overflow interrupt
Serial.begin(baud_rate);//start serial communication in order to debug the software while coding
delay(3000);//wait 3 seconds before robot moves
}
void loop()
{
robotMotion(); //execute robot motions based upon sensor data and current state
}
/*
This is a sample updateSensors() function and it should be updated along with the description to reflect what you actually implemented
to meet the lab requirements.
*/
void updateSensors() {
// Serial.print("updateSensors\t");
// Serial.println(test_state);
//test_state = !test_state;//LED to test the heartbeat of the timer interrupt routine
//digitalWrite(enableLED, test_state); // Toggles the LED to let you know the timer is working
test_state = !test_state;
digitalWrite(test_led, test_state);
flag = 0; //clear all sensor flags
state = 0; //clear all state flags
updateIR(); //update IR readings and update flag variable and state machine
//updateSonar(); //update Sonar readings and update flag variable and state machine
//updateSonar2(); //there are 2 ways to read sonar data, this is the 2nd option, use whichever one works best for your hardware
updateState(); //update State Machine based upon sensor readings
//delay(1000); //added so that you can read the data on the serial monitor
}
/*
This is a sample updateIR() function, the description and code should be updated to take an average, consider all sensor and reflect
the necesary changes for the lab requirements.
*/
void updateIR() {
int front, back, left, right;
front = analogRead(irFront);
back = analogRead(irRear);
left = analogRead(irLeft);
right = analogRead(irRight);
// print IR data
// Serial.println("frontIR\tbackIR\tleftIR\trightIR");
// Serial.print(front); Serial.print("\t");
// Serial.print(back); Serial.print("\t");
// Serial.print(left); Serial.print("\t");
// Serial.println(right);
if (right > irThresh)
bitSet(flag, obRight);//set the right obstacle
else
bitClear(flag, obRight);//clear the right obstacle
if (left > irThresh)
bitSet(flag, obLeft);//set the left obstacle
else
bitClear(flag, obLeft);//clear the left obstacle
if (front > irThresh) {
Serial.println("set front obstacle bit");
bitSet(flag, obFront);//set the front obstacle
}
else
bitClear(flag, obFront);//clear the front obstacle
if (back > irThresh)
bitSet(flag, obRear);//set the back obstacle
else
bitClear(flag, obRear);//clear the back obstacle
}
/*
This is a sample updateSonar() function, the description and code should be updated to take an average, consider all sensors and reflect
the necesary changes for the lab requirements.
*/
void updateSonar() {
long left, right;
//read right sonar
pinMode(snrRight, OUTPUT);//set the PING pin as an output
digitalWrite(snrRight, LOW);//set the PING pin low first
delayMicroseconds(2);//wait 2 us
digitalWrite(snrRight, HIGH);//trigger sonar by a 2 us HIGH PULSE
delayMicroseconds(5);//wait 5 us
digitalWrite(snrRight, LOW);//set pin low first again
pinMode(snrRight, INPUT);//set pin as input with duration as reception
right = pulseIn(snrRight, HIGH);//measures how long the pin is high
//read left sonar
pinMode(snrLeft, OUTPUT);//set the PING pin as an output
digitalWrite(snrLeft, LOW);//set the PING pin low first
delayMicroseconds(2);//wait 2 us
digitalWrite(snrLeft, HIGH);//trigger sonar by a 2 us HIGH PULSE
delayMicroseconds(5);//wait 5 us
digitalWrite(snrLeft, LOW);//set pin low first again
pinMode(snrLeft, INPUT);//set pin as input with duration as reception
left = pulseIn(snrLeft, HIGH);//measures how long the pin is high
// print sonar data
// Serial.println("leftSNR\trightSNR");
// Serial.print(left); Serial.print("\t");
// Serial.println(right);
if (right < snrThresh)
bitSet(flag, obFRight);//set the front right obstacle
else
bitClear(flag, obFRight);//clear the front right obstacle
if (left < snrThresh)
bitSet(flag, obFLeft);//set the front left obstacle
else
bitClear(flag, obFLeft);//clear the front left obstacle
}
/*
This is a sample updateSonar2() function, the description and code should be updated to take an average, consider all sensors and reflect
the necesary changes for the lab requirements.
*/
void updateSonar2() {
srRightAvg = sonarRt.ping_in(); //right sonara in inches
delay(50);
srLeftAvg = sonarLt.ping_in(); //left sonar in inches
// Serial.print("lt snr:\t");
// Serial.print(srLeftAvg);
// Serial.print("rt snr:\t");
// Serial.println(srRightAvg);
if (srRightAvg < snrThresh && srRightAvg > minThresh)
bitSet(flag, obFRight);//set the front right obstacle
else
bitClear(flag, obFRight);//clear the front right obstacle
if (srLeftAvg < snrThresh && srLeftAvg > minThresh)
bitSet(flag, obFLeft);//set the front left obstacle
else
bitClear(flag, obFLeft);//clear the front left obstacle
}
/*
This is a sample updateState() function, the description and code should be updated to reflect the actual state machine that you will implement
based upon the the lab requirements.
*/
void updateState() {
if (!(flag)) { //no sensors triggered
bitSet(state, fwd); //set forward motion
bitClear(state, collide);//clear collide state
count--;//decrement collide counter
}
else if (flag & 0b1) { //front sensors triggered
bitClear(state, fwd); //clear reverse motion
bitSet(state, collide);//set collide state
}
//print flag byte
// Serial.println("\trtSNR\tltSNR\tltIR\trtIR\trearIR\tftIR");
// Serial.print("flag byte: ");
// Serial.println(flag, BIN);
//print state byte
// Serial.println("\twander\trunAway\tcollide\treverse\tforward");
// Serial.print("state byte: ");
// Serial.println(state, BIN);
}
/*
This is a sample robotMotion() function, the description and code should be updated to reflect the actual robot motion function that you will implement
based upon the the lab requirements. Some things to consider, you cannot use a blocking motor function because you need to use sensor data to update
movement. You also need to continue to poll the sensors during the motion and update flags and state because this will serve as your interrupt to
stop or change movement.
*/
void robotMotion() {
if ((flag & 0b1) || bitRead(state, collide)) { //check for a collide state
stop();
Serial.println("robot stop");
}
else{
Serial.println("robot forward");
forward(one_rotation);//move forward as long as all sensors are clear
}
}
void forward(int rot) {
long positions[2]; // Array of desired stepper positions
stepperRight.setCurrentPosition(0);
stepperLeft.setCurrentPosition(0);
positions[0] = stepperRight.currentPosition() + rot; //right motor absolute position
positions[1] = stepperLeft.currentPosition() + rot; //left motor absolute position
stepperRight.move(positions[0]); //move right motor to position
stepperLeft.move(positions[1]); //move left motor to position
runToStop();//run until the robot reaches the target
}
void stop() {
stepperRight.stop();
stepperLeft.stop();
}
/*This function, runToStop(), will run the robot until the target is achieved and
then stop it
*/
void runToStop ( void ) {
int runNow = 1;
while (runNow) {
if (!stepperRight.run() ) {
runNow = 0;
stop();
}
if (!stepperLeft.run()) {
runNow = 0;
stop();
}
}
}
|
6b0fccec183dde2c8bb7be96e02091e5df552d87
|
e2da41aefbd0d5b82a4471830b0e03b173229c95
|
/final_v2.ino
|
f8bc0cc3952efee04a2b16639d8d9eddc0ff5340
|
[] |
no_license
|
ocneves/Glute-O-Licious
|
f3fd80454b92d7778358f8a23274dd67f1036924
|
e050dafe12343a69d84d50dfae2362ffa0c98cf5
|
refs/heads/master
| 2021-01-24T04:29:51.428439
| 2012-04-06T15:48:58
| 2012-04-06T15:48:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,699
|
ino
|
final_v2.ino
|
/*------------------------------------------------------------------------------------------
FINAL PROJECT - VIRTUAL BIKE RIDE
------------------------------------------------------------------------------------------*/
const int sensor1 = 2; //reed switch is attached to pin 2 is wheel sensor
const int sensor2 = 3; //reed switch attached to pin 3 is pedal sensor
int switchState; //current state of switch
int lastSwitchState = LOW; //last state of wheel switch
int pedalState;
int lastPedalState = LOW; //last state of pedal switch
int currentTime;
int pedalTime;
int threshold = 2000;
long lastTime = 0;
long lastPedalTime = 0;
//-------------------------------SETUP IS HERE-------------------------------------------------//
void setup() {
pinMode(sensor1, INPUT); //initialize sensor1 as an input
pinMode(sensor2, INPUT); //initialize sensor2 as input
Serial.begin(9600); //initialize serial communication
}
//-------------------------------LOOP IS HERE-------------------------------------------------//
void loop() {
//read switch
switchState = digitalRead(sensor1);
pedalState = digitalRead(sensor2);
//check to see if rider stopped pedaling
if((millis() - lastTime) > threshold) {
//if current time - most recent reading is greater than threshold
//rider has stopped pedaling. set currentTime == 0
//currentTime = 0;
Serial.print("0");
Serial.print(",");
//delay(50);
lastTime = millis(); //update lastTime
}
//testing only when switch changes states (high to low or low to high)
else {
if(switchState != lastSwitchState) {
//delay(50);
//if the state is HIGH, then the switch is on.
if(switchState == HIGH) {
//calculate time since last time switch was HIGH
currentTime = millis() - lastTime;
Serial.print(currentTime);
Serial.print(",");
//Serial.println(pedalState);
} else {
//if the current state is LOW, do nothing
}
//update lastTime
lastTime = millis();
}
}
//save switch state
lastSwitchState = switchState;
if(millis() - lastPedalTime > threshold) {
Serial.println("0");
lastPedalTime = millis();
}
else {
if(pedalState != lastPedalState) {
if(pedalState == HIGH) {
pedalTime = millis() - lastPedalTime;
Serial.println(pedalTime);
}
else {
//if current state is LOW, do nothing
}
//update last pedal time
lastPedalTime = millis();
}
}
lastPedalState = pedalState;
}
|
5bdc104e3ed501a4cbae8416b6b983dbbc6bb54c
|
007837c3ecfdea6af17368dc0bb705cf9db54b40
|
/hackathon_final.ino
|
cbc645847f1c2c377cfd324b828069aa725734a1
|
[] |
no_license
|
Rudra-banerjee/Drip-irrigation
|
9ae5163b90e12f6886cd061cb654569825470a49
|
04cb689d243c52c2ed81cc8bffc816f4c62330b7
|
refs/heads/master
| 2021-09-06T06:24:48.119120
| 2018-02-03T05:22:09
| 2018-02-03T05:22:09
| 113,135,826
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,216
|
ino
|
hackathon_final.ino
|
//GSM communication sms
#include <SoftwareSerial.h>
SoftwareSerial GPRS(8,9); //Pins 8 and 9 to Rx Tx
int c;
#include <dht.h> //DHT11 library
dht DHT; //DHT object
#include<LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
#define motor 4
#define acidvalve 5
#define basevalve 6
#define mainvalve 13
//Water level sensor Ultrasonic sensor
#define trigger 11
#define echo 10
int duration, cm;
int ch; //For crop type
int reset = LOW; //Initially no reset
void setup() {
Serial.begin(9600);
GPRS.begin(9600);
lcd.begin(16, 2);
lcd.clear();
lcd.print("WELCOME");
pinMode(A0, INPUT); //Moisture sensor
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT); //Water level US sensor
pinMode(7, INPUT); //DHT-Humidity Temp
pinMode(A3, INPUT); //pH sensor
pinMode(1, INPUT); // Button for Rice
pinMode(2, INPUT); //Button for Tea
pinMode(3, INPUT); //Reset button
pinMode(4, OUTPUT); // Motor output
pinMode(5, OUTPUT); //Acid valve
pinMode(6, OUTPUT); //Base valve
pinMode(12,OUTPUT); //Fertilizer valve
pinMode(13,OUTPUT); //Main release valve
GPRS.println("AT");
delay(1000);
init();
}
void init()
{
lcd.setCursor(0, 0);
lcd.print("Select crop");
lcd.setCursor(1, 0);
lcd.print("1:Cotton 2:Tea");
if (digitalRead(1) == HIGH) {
ch = 1;
digitalWrite(1, LOW);
}
else if (digitalWrite(2) == HIGH) {
ch = 2;
digitalWrite(2, LOW);
}
}
void loop() {
reset = digitalRead(3);
if (reset == HIGH) {
init();
digitalWrite(3, LOW);
}
wl = Level(); //Returns 0 if LOW, 1 if Medium and 2 if HIGH
switch (ch) {
case 1: if (wl == 0)
digitalWrite(motor, LOW);
else if (wl == 1) //Water level is medium
{
switch(env()){ //env() is environment function that returns values ranging from 1-3 as per temperature and humidity(high or low). 1: Case when most water is req
case 1:
if (moisture() == 0) { //moisture() function returns 1 if high, 0 if low
motorOn(90000,450000); //motorOn(t1, t2) switches the motor on for t1 ms (filling time of treatment chamber)and off for t2 ms(emptying time of chamber)... Let the best case be 1.5 mins and 7.5 mins
delay(1350000); //Wait 22.5 mins for entire dripping
}
else {
digitalWrite(motor, LOW);
}
break;
case 2:
if (moisture() == 0) {
motorOn(60000,300000); //1min , 5 mins
delay(900000); //Wait 15 mins for entire dripping
}
else {
digitalWrite(motor, LOW);
}
break;
case 3:
if (moisture() == 0) {
motorOn(30000,150000); //0.5min, 2.5 mins
delay(450000); //Wait 7.5 mins for entire dripping
}
else {
digitalWrite(motor, LOW);
}
break;
}
}
else { //Water level is maximum
switch(env()){ //env() is environment function that returns values ranging from 1-3 as per temperature and humidity(high or low). 1: Case when most water is req
case 1:
if (moisture() == 0) { //moisture() function returns 1 if high, 0 if low
motorOn(120000,600000); //motorOn(t1, t2) switches the motor on for t1 ms (filling time of Treatment chamber)and off for t2 ms(emptying time)... Let the best case be 2 mins and 10 mins
delay(1800000); //Wait 30 mins for entire dripping
}
else {
digitalWrite(motor, LOW);
}
break;
case 2:
if (moisture() == 0) {
motorOn(90000,450000); //1.5mins , 7.5 mins
delay(1350000); //Wait 22.5 mins for entire dripping
}
else {
digitalWrite(motor, LOW);
}
break;
case 3:
if (moisture() == 0) {
motorOn(60000,300000); //1 min, 5 mins
delay(900000); //Wait 15 mins for entire dripping
}
else {
digitalWrite(motor, LOW);
}
break;
}
break; //Break from cotton case
//Tea case
case 2:
if(wl==0)
digitalWrite(motor, LOW);
else if (wl == 1) //Water level is medium
{
switch(env())
{ //env() is environment function that returns values ranging from 1-3 as per temperature and humidity(high or low). 1: Case when most water is req
case 1:
if (moisture() == 0)
{ //moisture() function returns 1 if high, 0 if low
motorOn(70000,350000); //motorOn(t1, t2) switches the motor on for t1 ms (filling time of treatment chamber)and off for t2 ms(emptying time of chamber)... Let the best case be 1.5 mins and 7.5 mins
delay(850000); //Wait 22.5 mins for entire dripping
}
if(moisture()==1)
{
motorOn(60000,250000);
delay(750000);
}
if(moisture()==2)
{
digitalWrite(motor, LOW);
}
break;
case 2:
if (moisture() == 0)
{
motorOn(40000,250000); //1min , 5 mins
delay(650000); //Wait 15 mins for entire dripping
}
if(moisture()==1)
{
motorOn(30000,150000);
delay(550000);
}
if(moisture()==2)
{
digitalWrite(motor, LOW);
}
break;
case 3:
if (moisture() == 0)
{
motorOn(20000,100000); //0.5min, 2.5 mins
delay(300000); //Wait 7.5 mins for entire dripping
}
if(moisture()==1)
{
motorOn(15000,50000)
delay(150000);
}
if(moisture()==2)
{
digitalWrite(motor, LOW);
}
break;
}
}
else { //Water level is maximum
switch(env())
{ //env() is environment function that returns values ranging from 1-3 as per temperature and humidity(high or low). 1: Case when most water is req
case 1:
if (moisture() == 0)
{ //moisture() function returns 1 if high, 0 if low
motorOn(90000,400000); //motorOn(t1, t2) switches the motor on for t1 ms (filling time of Treatment chamber)and off for t2 ms(emptying time)... Let the best case be 2 mins and 10 mins
delay(1300000); //Wait 30 mins for entire dripping
}
if(moisture()==1)
{
motorOn(70000,300000);
delay(1100000);
}
if(moisture()==2)
{
digitalWrite(motor, LOW);
}
break;
case 2:
if (moisture() == 0)
{
motorOn(70000,300000); //1.5mins , 7.5 mins
delay(1000000); //Wait 22.5 mins for entire dripping
}
if(moisture()==1)
{
motorOn(50000,200000);
delay(650000);
}
if(moisture()==2)
{
digitalWrite(motor, LOW);
}
break;
case 3:
if (moisture() == 0)
{
motorOn(40000,350000); //1 min, 5 mins
delay(650000); //Wait 15 mins for entire dripping
}
if(moisture()==1)
{
motorOn(30000,200000);
delay(450000);
}
if(moisture()==2)
{
digitalWrite(motor, LOW);
}
break;
}
break;// break from tea case
}
}
motorOn(int t1, int t2) {
digitalWrite(motor, HIGH);
delay(t1);
digitalWrite(motor, LOW);
digitalWrite(12,HIGH); //12 is connected to fertilizer tank
Tf= 0.1*t1;
delay(Tf); //Fertilizer valve opens for 10% of t1 time.
digitalWrite(12,LOW);
if (ph() > 7) { //ph() returns ph value of sample
digitalWrite(acidvalve, HIGH);
int T=(int((ph() - 7) * 600);
delay(T); // Acid valve opens for (ph()-7)*10 seconds... For 8 it opens for 10s, for 9 for 20s etc
digitalWrite(acidvalve, LOW);
}
else {
digitalWrite(basevalve, HIGH);
int T=(int(7 - ph()) * 600);
delay(T); // Base valve opens for (7-ph())*10 seconds... For 6 it opens for 10s, for 5 for 20s etc
digitalWrite(basevalve, LOW);
}
delay(3600); //wait 1 min for mixing of componenents.
digitalWrite(mainvalve,HIGH);
delay(t2+Tf+T);
digitalWrite(mainvalve,LOW);
}
int Level() {
int wl;
digitalWrite(trigger, LOW);
delayMicroseconds(2);
digitalWrite(trigger, HIGH);
delayMicroseconds(5);
digitalWrite(trigger, LOW);
duration = pulseIn(echo, HIGH); //pulseIn gives time value after which echo pin becomes high ie sound signal reaches back
cm = (duration / 2) / 29; //Here cm gives the depth of the tank upto which water is available, so water level is inversely prop to cm
if (cm < 10){
wl= 2; c=1;
}
else if (cm >= 10 && cm < 50){
wl= 1; c=1;
}
else{
wl= 0;
if(c==1&&wl==0){ //global variable c ensures that for one cycle only one sms is sent to the farmer, otherwise SMS will be sent infinitely.
sendSMS();
c=0;
}
return wl;
}
}
sendSMS(){
Serial.println("Alert: Water Level is Low");
GPRS.println("AT+CMGF=1");
delay(500);
GPRS.println("AT+CMGS=\"+919531711838\"");
delay(500);
GPRS.println("Alert: Water Level is Low.");
GPRS.write(0x1a); //hexadecimal for Ctrl+Z sequence to denote end of message.
delay(500);
}
int env() {
float T, H; //T:in deg C, H:in %
T = temp();
H = hum();
if(T>25 && H<50)
return 1;
else if(T>25 && H>50|| T<25 && H<50)
return 2;
else
return 3;
}
float temp(){
int chk = DHT.read11(7); //DHT connected to pin 7
return DHT.temperature; //in deg C
}
float hum(){
int chk = DHT.read11(7); //DHT connected to pin 7
return DHT.humidity; //in %
}
int moisture(){
int mois= analogRead(A0);
if(mois>700)
return 1;
else
return 0;
}
float ph(){
const int analogInPin = A3; //pH probe connected to pin A3
int sensorValue = 0;
unsigned long int avgValue;
float b;
int buf[10],temp;
for(int i=0;i<10;i++)
{
buf[i]=analogRead(analogInPin);
delay(10);
}
for(int i=0;i<9;i++)
{
for(int j=i+1;j<10;j++)
{
if(buf[i]>buf[j])
{
temp=buf[i];
buf[i]=buf[j];
buf[j]=temp;
}
}
}
avgValue=0;
for(int i=2;i<8;i++)
avgValue+=buf[i];
float pHVol=(float)avgValue*5.0/1024/6;
float phValue = -5.70 * pHVol + 21.34;
return phValue;
}
|
f4c41866ae1c42eb052343fa493e6e1d7ee33089
|
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
|
/Engine/Source/Runtime/AnimGraphRuntime/Private/AnimNotify_PlayMontageNotify.cpp
|
bfb46a8c8e66e610509c1cea8ec72346611a4f88
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
refs/heads/4.18-GameWorks
| 2023-03-11T02:50:08.471040
| 2022-01-13T20:50:29
| 2022-01-13T20:50:29
| 124,100,479
| 262
| 179
|
MIT
| 2022-12-16T05:36:38
| 2018-03-06T15:44:09
|
C++
|
UTF-8
|
C++
| false
| false
| 2,546
|
cpp
|
AnimNotify_PlayMontageNotify.cpp
|
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "AnimNotify_PlayMontageNotify.h"
#include "Animation/AnimInstance.h"
//////////////////////////////////////////////////////////////////////////
// UAnimNotify_PlayMontageNotify
//////////////////////////////////////////////////////////////////////////
UAnimNotify_PlayMontageNotify::UAnimNotify_PlayMontageNotify(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
bIsNativeBranchingPoint = true;
}
void UAnimNotify_PlayMontageNotify::BranchingPointNotify(FBranchingPointNotifyPayload& BranchingPointPayload)
{
Super::BranchingPointNotify(BranchingPointPayload);
if (USkeletalMeshComponent* MeshComp = BranchingPointPayload.SkelMeshComponent)
{
if (UAnimInstance* AnimInstance = MeshComp->GetAnimInstance())
{
AnimInstance->OnPlayMontageNotifyBegin.Broadcast(NotifyName, BranchingPointPayload);
}
}
}
#if WITH_EDITOR
bool UAnimNotify_PlayMontageNotify::CanBePlaced(UAnimSequenceBase* Animation) const
{
return (Animation && Animation->IsA(UAnimMontage::StaticClass()));
}
#endif // WITH_EDITOR
//////////////////////////////////////////////////////////////////////////
// UAnimNotify_PlayMontageNotifyWindow
//////////////////////////////////////////////////////////////////////////
UAnimNotify_PlayMontageNotifyWindow::UAnimNotify_PlayMontageNotifyWindow(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
bIsNativeBranchingPoint = true;
}
void UAnimNotify_PlayMontageNotifyWindow::BranchingPointNotifyBegin(FBranchingPointNotifyPayload& BranchingPointPayload)
{
Super::BranchingPointNotifyBegin(BranchingPointPayload);
if (USkeletalMeshComponent* MeshComp = BranchingPointPayload.SkelMeshComponent)
{
if (UAnimInstance* AnimInstance = MeshComp->GetAnimInstance())
{
AnimInstance->OnPlayMontageNotifyBegin.Broadcast(NotifyName, BranchingPointPayload);
}
}
}
void UAnimNotify_PlayMontageNotifyWindow::BranchingPointNotifyEnd(FBranchingPointNotifyPayload& BranchingPointPayload)
{
Super::BranchingPointNotifyEnd(BranchingPointPayload);
if (USkeletalMeshComponent* MeshComp = BranchingPointPayload.SkelMeshComponent)
{
if (UAnimInstance* AnimInstance = MeshComp->GetAnimInstance())
{
AnimInstance->OnPlayMontageNotifyEnd.Broadcast(NotifyName, BranchingPointPayload);
}
}
}
#if WITH_EDITOR
bool UAnimNotify_PlayMontageNotifyWindow::CanBePlaced(UAnimSequenceBase* Animation) const
{
return (Animation && Animation->IsA(UAnimMontage::StaticClass()));
}
#endif // WITH_EDITOR
|
829820d20a0b3af845b26c8a3758d4d23ce8ca0b
|
7766b4e12fbd6b6e8b9dab3e631aa745af0b3d1c
|
/FreeCompose/branches/devel/SharedInclude/KeyIsXAlnum.h
|
0e3364b8eeb11a541736db417c582905eb67f20f
|
[] |
no_license
|
TReKiE/freecompose
|
8634ee9bb3c44856be373700e887500a1216adba
|
a03775c2f1a6ff8bac272b74038fde1782d6c995
|
refs/heads/master
| 2020-04-08T07:32:44.006087
| 2015-04-15T15:57:47
| 2015-04-15T15:57:47
| 33,805,024
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 230
|
h
|
KeyIsXAlnum.h
|
#pragma once
#include "FCShared.h"
class FCSHARED_API KeyIsXAlnum {
public:
static bool Test( const DWORD dwVK );
private:
static void _Initialize( void );
static bool _map[256];
static bool _initialized;
};
|
7ee62398f416be5fa78e505fe7c8baeaa5cd806a
|
311da5b17c18be34422ae55a12c4d6e8ec3a0767
|
/src/grid/grid_general.h
|
4a8a25e0c66d936b467528eb6b7ce48c08aee3de
|
[] |
no_license
|
Knights-Templars/pubsed
|
f3d17df709f5e0d4c556a59fd80d38c4370b0979
|
f124d000b0d8eedae86a6cee4253a1eb4c202665
|
refs/heads/main
| 2023-05-09T19:26:17.747010
| 2020-07-20T22:29:53
| 2020-07-20T22:29:53
| 445,101,129
| 1
| 0
| null | 2022-01-06T08:47:19
| 2022-01-06T08:47:19
| null |
UTF-8
|
C++
| false
| false
| 4,339
|
h
|
grid_general.h
|
//------------------------------------------------------------------
//*****************************************************************
//************************* GRID ********************************
//*****************************************************************
// The grid class is a construct whose main purpose is to handle
// the geometry of the model. It does two main things: (1) Reads
// in the input density,temperature,composition files (that of
// course must have a specific geometry). (2) Given a set of
// 3-d coordinates, it will give the corosponding zone index (or
// note that the coords are off the grid).
//
// The grid holds an array of zones, where key fluid data is stored
//
// The grid class is an abstract class that will be used to
// create subclasses (e.g. grid_1D_sphere, grid_3D_cart, etc...
//*****************************************************************
#ifndef _GRID_GENERAL_H
#define _GRID_GENERAL_H 1
#include <string>
#include <iostream>
#include <mpi.h>
#include "sedona.h"
#include "zone.h"
#include "ParameterReader.h"
#include "h5utils.h"
#include "hdf5.h"
#include "hdf5_hl.h"
class grid_general
{
protected:
int use_homologous_velocities_;
int my_rank;
int nproc;
int do_restart_;
// fill the grid with data from a model file
virtual void read_model_file(ParameterReader*) = 0;
void writeCheckpointGeneralGrid(std::string fname);
void readCheckpointGeneralGrid(std::string fname, bool test=false);
void testCheckpointGeneralGrid(std::string fname);
public:
// set everything up
void init(ParameterReader* params);
virtual ~grid_general() {}
// descrption of grid type
std::string grid_type;
// vector of zones
std::vector<zone> z;
std::vector<zone> z_new; // For restart debugging
int n_zones;
int n_zones_new;
double t_now;
double t_now_new;
// vector of isotopes to use
std::vector<int> elems_Z;
std::vector<int> elems_Z_new;
std::vector<int> elems_A;
std::vector<int> elems_A_new;
int n_elems;
int n_elems_new;
// mpi reduce quantities
void reduce_radiation();
void reduce_radiation_block(int, int);
void reduce_T_gas();
void reduce_n_elec();
// output functions
void write_integrated_quantities(int iw, double tt);
void write_hdf5_plotfile_zones(hid_t file_id, hsize_t *dims_g, int ndims, double);
void writeCheckpointZones(std::string fname);
void writeScalarZoneProp(std::string fname, std::string fieldname);
void writeVectorZoneProp(std::string fname, std::string fieldname);
void readCheckpointZones(std::string fname, bool test=false);
void readScalarZoneProp(std::string fname, std::string fieldname);
void readVectorZoneProp(std::string fname, std::string fieldname);
void testCheckpointZones(std::string fname);
//****** virtual functions (geometry specific)
// get zone index from x,y,z position
virtual int get_zone(const double *) const = 0;
// get zone index from x,y,z position
virtual int get_next_zone(const double *, const double *, int, double, double *) const = 0;
// return volume of zone i
virtual double zone_volume(const int i) const = 0;
// randomly sample a position within the zone i
virtual void sample_in_zone(int,std::vector<double>,double[3]) = 0;
// give the velocity vector at this point in zone i
virtual void get_velocity(int i, double[3], double[3], double[3], double*) = 0;
// get the coordinates at the center of the zone i
virtual void coordinates(int i,double r[3]) = 0;
// write out the grid state
virtual void write_plotfile(int,double,int) = 0;
// expand the grid by a factor of e
virtual void expand(double) = 0;
//****** empty functions to overide
virtual void get_radial_edges
(std::vector<double>&, double&, std::vector<double>&, double&) const
{ }
virtual void set_radial_edges
(const std::vector<double>, double, const std::vector<double>, double)
{ }
virtual void get_zone_size(int, double*)
{
}
virtual void get_r_out_min(double*)
{}
/* TODO: MAKE PURE VIRTUAL EVENTUALLY */
virtual void writeCheckpointGrid(std::string fname) {};
virtual void readCheckpointGrid(std::string fname, bool test=false) {};
virtual void testCheckpointGrid(std::string fname) {};
virtual void restartGrid(ParameterReader* params) {};
};
#endif
|
6537433d870d6cef4d6ed2c2e442d9cf47c097ab
|
d6ac474dd403e7c0302dfa0f94a7efbb98e89a13
|
/Intro3D/Polygon3D.cpp
|
b03865057dbfae5a1ddff459fa196b6d2cb82c01
|
[] |
no_license
|
HampsterEater/DirectXFramework
|
25a52b2cecb6880f5085dfd9f7afd038f49114fb
|
f99f350ec7b28e20b9d7882432e0e02dc07a3c9a
|
refs/heads/master
| 2021-01-01T15:55:18.902444
| 2013-03-16T03:41:44
| 2013-03-16T03:41:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,224
|
cpp
|
Polygon3D.cpp
|
// =========================================================================================
// Polygon3D.cpp
// =========================================================================================
// Written by Timothy Leonard
// For Introduction to 3D Graphics Programming (5CC068)
// =========================================================================================
#include "StdAfx.h"
#include "Polygon3D.h"
// Contructors.
Polygon3D::Polygon3D(void)
{
_avgDepth = 0.0f;
}
Polygon3D::Polygon3D(int i1, int i2, int i3)
{
_vertexIndexes[0] = i1;
_vertexIndexes[1] = i2;
_vertexIndexes[2] = i3;
_avgDepth = 0.0f;
}
// Copy constructor.
Polygon3D::Polygon3D(const Polygon3D& poly)
{
_avgDepth = 0.0f;
Copy(poly);
}
// Destructor.
Polygon3D::~Polygon3D()
{
}
// Assignment operator. Copys the value of one polygon to another.
Polygon3D& Polygon3D::operator= (const Polygon3D &rhs)
{
if (this != &rhs)
{
// Only copy if we are not assigning to ourselves.
// (remember that a = b is the same as a.operator=(b))
Copy(rhs);
}
return *this;
}
// Accessor methods. Simple get/set code.
int Polygon3D::GetVertexIndex(int index)
{
return _vertexIndexes[index];
}
void Polygon3D::SetVertexIndex(int index, int value)
{
_vertexIndexes[index] = value;
}
int Polygon3D::GetUVIndex(int index)
{
return _uvIndexes[index];
}
void Polygon3D::SetUVIndex(int index, int value)
{
_uvIndexes[index] = value;
}
void Polygon3D::SetBackfacing(bool value)
{
_backfacing = value;
}
bool Polygon3D::GetBackfacing()
{
return _backfacing;
}
void Polygon3D::SetAvgDepth(float value)
{
_avgDepth = value;
}
float Polygon3D::GetAvgDepth() const
{
return _avgDepth;
}
void Polygon3D::SetColor(Color value)
{
_color = value;
}
Color Polygon3D::GetColor()
{
return _color;
}
// Copys the value of this polygon to another polygon.
void Polygon3D::Copy(const Polygon3D& poly)
{
_vertexIndexes[0] = poly._vertexIndexes[0];
_vertexIndexes[1] = poly._vertexIndexes[1];
_vertexIndexes[2] = poly._vertexIndexes[2];
_uvIndexes[0] = poly._uvIndexes[0];
_uvIndexes[1] = poly._uvIndexes[1];
_uvIndexes[2] = poly._uvIndexes[2];
_backfacing = poly._backfacing;
_avgDepth = poly._avgDepth;
_color = poly._color;
}
|
d6a7213b55ea721a46d6d414180f7d9e15aa2ffd
|
98e657765290c2bbbd12f51788e2880a0b0d16d8
|
/bobcat/datetime/setyear.cc
|
408c7f7ab84340502bfe1935a0bff20172029eee
|
[] |
no_license
|
RoseySoft/bobcat
|
70f7394ebfa752a04aeaafa043c2a26f2ab09bd7
|
ec358733b07fb1a8018602a46e92e7511ba5a97f
|
refs/heads/master
| 2018-02-24T06:07:50.699146
| 2016-08-17T08:32:41
| 2016-08-17T08:32:41
| 67,193,814
| 1
| 0
| null | 2016-09-02T05:46:56
| 2016-09-02T05:46:55
| null |
UTF-8
|
C++
| false
| false
| 148
|
cc
|
setyear.cc
|
#include "datetime.ih"
bool DateTime::setYear(size_t year)
{
TimeStruct ts = d_tm;
ts.tm_year = year - 1900;
return updateTime(ts);
}
|
08ad9d261b0a3b1c7823eaa4cfab73f1f7718ba4
|
17da3571af4a82f8a7b70c5701987cdc455f055a
|
/src/VMFoundation/mappingfile.h
|
403aaf3e7f6f5c125e788ea4ffbe9023453c61b1
|
[] |
no_license
|
cad420/VMCore
|
32566c245cc6ac34ddad4075f1f974309f14da74
|
ef97966c03320663f342673ded49d8ab6b5a6e62
|
refs/heads/master
| 2023-06-22T13:13:03.533705
| 2023-06-19T13:04:03
| 2023-06-19T13:04:03
| 210,555,836
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,155
|
h
|
mappingfile.h
|
#pragma once
/*
* Only for internal use
*/
#include <VMCoreExtension/ifilemappingplugininterface.h>
#include <VMCoreExtension/plugin.h>
#include <VMUtils/common.h>
#ifdef _WIN32
namespace vm
{
class WindowsFileMapping__pImpl;
class WindowsFileMapping : public EverythingBase<IMappingFile>
{
VM_DECL_IMPL( WindowsFileMapping )
public:
WindowsFileMapping( ::vm::IRefCnt *cnt );
bool Open( const std::string &fileName, size_t fileSize, FileAccess fileFlags, MapAccess mapFlags ) override;
unsigned char *MemoryMap( unsigned long long offset, std::size_t size ) override;
void MemoryUnmap( unsigned char *addr ) override;
bool Flush() override;
bool Flush( void *ptr, size_t len, int flags ) override;
bool Close() override;
~WindowsFileMapping();
};
} // namespace vm
class WindowsFileMappingFactory : public vm::IPluginFactory
{
DECLARE_PLUGIN_FACTORY( "vmcore.imappingfile" )
public:
int Keys( const char **keys ) const override;
::vm::IEverything *Create( const char *key ) override;
};
VM_REGISTER_PLUGIN_FACTORY_DECL( WindowsFileMappingFactory )
// EXPORT_PLUGIN_FACTORY( WindowsFileMappingFactory )
#else
#include <set>
namespace vm
{
class LinuxFileMapping : public ::vm::EverythingBase<IMappingFile>
{
std::unordered_map<unsigned char *, size_t> mappedPointers;
int fd = -1;
FileAccess fileAccess;
MapAccess mapAccess;
size_t fileSize = 0;
public:
LinuxFileMapping( ::vm::IRefCnt *cnt ) :
::vm::EverythingBase<IMappingFile>( cnt ) {}
bool Open( const std::string &fileName, size_t fileSize, FileAccess fileFlags, MapAccess mapFlags ) override;
unsigned char *MemoryMap( unsigned long long offset, size_t size ) override;
void MemoryUnmap( unsigned char *addr ) override;
bool Flush() override;
bool Flush( void *ptr, size_t len, int flags ) override;
bool Close() override;
~LinuxFileMapping();
};
} // namespace vm
class LinuxFileMappingFactory : public vm::IPluginFactory
{
DECLARE_PLUGIN_FACTORY( "vmcore.imappingfile" )
public:
int Keys( const char **keys ) const override;
::vm::IEverything *Create( const char *key ) override;
};
VM_REGISTER_PLUGIN_FACTORY_DECL( LinuxFileMappingFactory )
#endif
|
0c2ecad22305ff62c13d12a3323eae289430eb79
|
8c0aa69b4a148f96bcdf4637329262d5227ddf08
|
/include/goetia/sketches/sketch/vec/blaze/blaze/math/views/column/Column.h
|
0b2901f9a30b8f1ebf02296ae9c578d5980792b3
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
camillescott/goetia
|
edd42c80451a13d4d0ced2f6ddb4ed9cb9ac7c80
|
db75dc0d87126c5ad20c35405699d89153f109a8
|
refs/heads/main
| 2023-04-12T15:30:48.253961
| 2022-03-25T00:23:39
| 2022-03-25T00:23:39
| 81,270,193
| 6
| 0
|
MIT
| 2022-04-01T21:40:58
| 2017-02-08T00:40:08
|
C++
|
UTF-8
|
C++
| false
| false
| 15,387
|
h
|
Column.h
|
//=================================================================================================
/*!
// \file blaze/math/views/column/Column.h
// \brief Column documentation
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZE_MATH_VIEWS_COLUMN_COLUMN_H_
#define _BLAZE_MATH_VIEWS_COLUMN_COLUMN_H_
//=================================================================================================
//
// DOXYGEN DOCUMENTATION
//
//=================================================================================================
//*************************************************************************************************
/*!\defgroup column Column
// \ingroup views
//
// Just as rows provide a view on a specific row of a matrix, columns provide views on a specific
// column of a dense or sparse matrix. As such, columns act as a reference to a specific column.
// This reference is valid and can be used in every way any other column vector can be used as
// long as the matrix containing the column is not resized or entirely destroyed. Changes made to
// the elements (e.g. modifying values, inserting or erasing elements) are immediately visible in
// the matrix and changes made via the matrix are immediately visible in the column.
//
//
// \n \section column_setup Setup of Columns
//
// \image html column.png
// \image latex column.eps "Column view" width=250pt
//
// A reference to a dense or sparse column can be created very conveniently via the \c column()
// function. It can be included via the header file
\code
#include <blaze/math/Column.h>
\endcode
// The column index must be in the range from \f$[0..N-1]\f$, where \c N is the total number of
// columns of the matrix, and can be specified both at compile time or at runtime:
\code
blaze::DynamicMatrix<double,blaze::columnMajor> A;
// ... Resizing and initialization
// Creating a reference to the 1st column of matrix A (compile time index)
auto col1 = column<1UL>( A );
// Creating a reference to the 2nd column of matrix A (runtime index)
auto col2 = column( A, 2UL );
\endcode
// The \c column() function returns an expression representing the column view. The type of this
// expression depends on the given column arguments, primarily the type of the matrix and the
// compile time arguments. If the type is required, it can be determined via \c decltype specifier:
\code
using MatrixType = blaze::DynamicMatrix<int>;
using ColumnType = decltype( blaze::column<1UL>( std::declval<MatrixType>() ) );
\endcode
// The resulting view can be treated as any other column vector, i.e. it can be assigned to, it
// can be copied from, and it can be used in arithmetic operations. The reference can also be used
// on both sides of an assignment: The column can either be used as an alias to grant write access
// to a specific column of a matrix primitive on the left-hand side of an assignment or to grant
// read-access to a specific column of a matrix primitive or expression on the right-hand side
// of an assignment. The following example demonstrates this in detail:
\code
blaze::DynamicVector<double,blaze::columnVector> x;
blaze::CompressedVector<double,blaze::columnVector> y;
blaze::DynamicMatrix<double,blaze::columnMajor> A, B;
blaze::CompressedMatrix<double,blaze::columnMajor> C, D;
// ... Resizing and initialization
// Setting the 1st column of matrix A to x
auto col1 = column( A, 1UL );
col1 = x;
// Setting the 4th column of matrix B to y
column( B, 4UL ) = y;
// Setting x to the 2nd column of the result of the matrix multiplication
x = column( A * B, 2UL );
// Setting y to the 2nd column of the result of the sparse matrix multiplication
y = column( C * D, 2UL );
\endcode
// \n \section column_element_access Element access
//
// The elements of the dense column can be directly accessed with the subscript operator.
\code
blaze::DynamicMatrix<double,blaze::columnMajor> A;
// ... Resizing and initialization
// Creating a view on the 4th column of matrix A
auto col4 = column( A, 4UL );
// Setting the 1st element of the dense column, which corresponds
// to the 1st element in the 4th column of matrix A
col4[1] = 2.0;
\endcode
// The numbering of the column elements is
\f[\left(\begin{array}{*{5}{c}}
0 & 1 & 2 & \cdots & N-1 \\
\end{array}\right),\f]
// where N is the number of rows of the referenced matrix. Alternatively, the elements of a column
// can be traversed via iterators. Just as with vectors, in case of non-const columns, \c begin()
// and \c end() return an iterator, which allows to manipulate the elements, in case of constant
// columns an iterator to immutable elements is returned:
\code
blaze::DynamicMatrix<int,blaze::columnMajor> A( 128UL, 256UL );
// ... Resizing and initialization
// Creating a reference to the 31st column of matrix A
auto col31 = column( A, 31UL );
// Traversing the elements via iterators to non-const elements
for( auto it=col31.begin(); it!=col31.end(); ++it ) {
*it = ...; // OK; Write access to the dense column value
... = *it; // OK: Read access to the dense column value.
}
// Traversing the elements via iterators to const elements
for( auto it=col31.cbegin(); it!=col31.cend(); ++it ) {
*it = ...; // Compilation error: Assignment to the value via iterator-to-const is invalid.
... = *it; // OK: Read access to the dense column value.
}
\endcode
\code
blaze::CompressedMatrix<int,blaze::columnMajor> A( 128UL, 256UL );
// ... Resizing and initialization
// Creating a reference to the 31st column of matrix A
auto col31 = column( A, 31UL );
// Traversing the elements via iterators to non-const elements
for( auto it=col31.begin(); it!=col31.end(); ++it ) {
it->value() = ...; // OK: Write access to the value of the non-zero element.
... = it->value(); // OK: Read access to the value of the non-zero element.
it->index() = ...; // Compilation error: The index of a non-zero element cannot be changed.
... = it->index(); // OK: Read access to the index of the sparse element.
}
// Traversing the elements via iterators to const elements
for( auto it=col31.cbegin(); it!=col31.cend(); ++it ) {
it->value() = ...; // Compilation error: Assignment to the value via iterator-to-const is invalid.
... = it->value(); // OK: Read access to the value of the non-zero element.
it->index() = ...; // Compilation error: The index of a non-zero element cannot be changed.
... = it->index(); // OK: Read access to the index of the sparse element.
}
\endcode
// \n \section sparse_column_element_insertion Element Insertion
//
// Inserting/accessing elements in a sparse column can be done by several alternative functions.
// The following example demonstrates all options:
\code
blaze::CompressedMatrix<double,blaze::columnMajor> A( 100UL, 10UL ); // Non-initialized 100x10 matrix
auto col0( column( A, 0UL ) ); // Reference to the 0th column of A
// The subscript operator provides access to all possible elements of the sparse column,
// including the zero elements. In case the subscript operator is used to access an element
// that is currently not stored in the sparse column, the element is inserted into the column.
col0[42] = 2.0;
// The second operation for inserting elements is the set() function. In case the element
// is not contained in the column it is inserted into the column, if it is already contained
// in the column its value is modified.
col0.set( 45UL, -1.2 );
// An alternative for inserting elements into the column is the insert() function. However,
// it inserts the element only in case the element is not already contained in the column.
col0.insert( 50UL, 3.7 );
// A very efficient way to add new elements to a sparse column is the append() function.
// Note that append() requires that the appended element's index is strictly larger than
// the currently largest non-zero index of the column and that the column's capacity is
// large enough to hold the new element.
col0.reserve( 10UL );
col0.append( 51UL, -2.1 );
\endcode
// \n \section column_common_operations Common Operations
//
// A column view can be used like any other column vector. For instance, the current number of
// column elements can be obtained via the \c size() function, the current capacity via the
// \c capacity() function, and the number of non-zero elements via the \c nonZeros() function.
// However, since columns are references to specific columns of a matrix, several operations
// are not possible, such as resizing and swapping:
\code
blaze::DynamicMatrix<int,blaze::columnMajor> A( 42UL, 42UL );
// ... Resizing and initialization
// Creating a reference to the 2nd column of matrix A
auto col2 = column( A, 2UL );
col2.size(); // Returns the number of elements in the column
col2.capacity(); // Returns the capacity of the column
col2.nonZeros(); // Returns the number of non-zero elements contained in the column
col2.resize( 84UL ); // Compilation error: Cannot resize a single column of a matrix
auto col3 = column( A, 3UL );
swap( col2, col3 ); // Compilation error: Swap operation not allowed
\endcode
// \n \section column_arithmetic_operations Arithmetic Operations
//
// Both dense and sparse columns can be used in all arithmetic operations that any other dense or
// sparse column vector can be used in. The following example gives an impression of the use of
// dense columns within arithmetic operations. All operations (addition, subtraction, multiplication,
// scaling, ...) can be performed on all possible combinations of dense and sparse columns with
// fitting element types:
\code
blaze::DynamicVector<double,blaze::columnVector> a( 2UL, 2.0 ), b;
blaze::CompressedVector<double,blaze::columnVector> c( 2UL );
c[1] = 3.0;
blaze::DynamicMatrix<double,blaze::columnMajor> A( 2UL, 4UL ); // Non-initialized 2x4 matrix
auto col0( column( A, 0UL ) ); // Reference to the 0th column of A
col0[0] = 0.0; // Manual initialization of the 0th column of A
col0[1] = 0.0;
column( A, 1UL ) = 1.0; // Homogeneous initialization of the 1st column of A
column( A, 2UL ) = a; // Dense vector initialization of the 2nd column of A
column( A, 3UL ) = c; // Sparse vector initialization of the 3rd column of A
b = col0 + a; // Dense vector/dense vector addition
b = c + column( A, 1UL ); // Sparse vector/dense vector addition
b = col0 * column( A, 2UL ); // Component-wise vector multiplication
column( A, 1UL ) *= 2.0; // In-place scaling of the 1st column
b = column( A, 1UL ) * 2.0; // Scaling of the 1st column
b = 2.0 * column( A, 1UL ); // Scaling of the 1st column
column( A, 2UL ) += a; // Addition assignment
column( A, 2UL ) -= c; // Subtraction assignment
column( A, 2UL ) *= column( A, 0UL ); // Multiplication assignment
double scalar = trans( c ) * column( A, 1UL ); // Scalar/dot/inner product between two vectors
A = column( A, 1UL ) * trans( c ); // Outer product between two vectors
\endcode
// \n \section column_on_row_major_matrix Columns on a Row-Major Matrix
//
// Especially noteworthy is that column views can be created for both row-major and column-major
// matrices. Whereas the interface of a row-major matrix only allows to traverse a row directly
// and the interface of a column-major matrix only allows to traverse a column, via views it is
// possible to traverse a row of a column-major matrix or a column of a row-major matrix. For
// instance:
\code
blaze::DynamicMatrix<int,blaze::rowMajor> A( 64UL, 32UL );
// ... Resizing and initialization
// Creating a reference to the 1st column of a column-major matrix A
auto col1 = column( A, 1UL );
for( auto it=col1.begin(); it!=col1.end(); ++it ) {
// ...
}
\endcode
// However, please note that creating a column view on a matrix stored in a row-major fashion
// can result in a considerable performance decrease in comparison to a column view on a matrix
// with column-major storage format. This is due to the non-contiguous storage of the matrix
// elements. Therefore care has to be taken in the choice of the most suitable storage order:
\code
// Setup of two row-major matrices
blaze::DynamicMatrix<double,blaze::rowMajor> A( 128UL, 128UL );
blaze::DynamicMatrix<double,blaze::rowMajor> B( 128UL, 128UL );
// ... Resizing and initialization
// The computation of the 15th column of the multiplication between A and B ...
blaze::DynamicVector<double,blaze::columnVector> x = column( A * B, 15UL );
// ... is essentially the same as the following computation, which multiplies
// A with the 15th column of the row-major matrix B.
blaze::DynamicVector<double,blaze::columnVector> x = A * column( B, 15UL );
\endcode
// Although Blaze performs the resulting matrix/vector multiplication as efficiently as possible
// using a column-major storage order for matrix \c A would result in a more efficient evaluation.
*/
//*************************************************************************************************
} // namespace blaze
#endif
|
b953b0f815638b04d9a8d00646d6b8db6e9a0601
|
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
|
/TeCom/src/TdkLayout/Source Files/TdkViewUserProperty.cpp
|
e9dab57c3bfe5963ce2174226a2f4a40daa6d0db
|
[] |
no_license
|
radtek/terra-printer
|
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
|
959241e52562128d196ccb806b51fda17d7342ae
|
refs/heads/master
| 2020-06-11T01:49:15.043478
| 2011-12-12T13:31:19
| 2011-12-12T13:31:19
| null | 0
| 0
| null | null | null | null |
ISO-8859-2
|
C++
| false
| false
| 2,462
|
cpp
|
TdkViewUserProperty.cpp
|
#include<TdkLayoutTypes.h>
#include <TdkViewUserProperty.h>
///////////////////////////////////////////////////////////////////////////////
// Constructor
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
TdkViewUserProperty::TdkViewUserProperty(const std::string &value)
{
_propertyName="ViewUser_Property";
_type=PText;
_userName=value;
}
///////////////////////////////////////////////////////////////////////////////
// Destructor
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
TdkViewUserProperty::~TdkViewUserProperty()
{
}
///////////////////////////////////////////////////////////////////////////////
// setValue
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkViewUserProperty::setValue(const std::string &newVal)
{
_userName=newVal;
}
///////////////////////////////////////////////////////////////////////////////
// getValue
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
std::string TdkViewUserProperty::getValue()
{
return _userName;
}
///////////////////////////////////////////////////////////////////////////////
// getValue by reference
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkViewUserProperty::getValue(std::string &value)
{
value=_userName;
}
///////////////////////////////////////////////////////////////////////////////
// Equal operator
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
TdkViewUserProperty& TdkViewUserProperty::operator=(const TdkViewUserProperty &other)
{
this->_userName=other._userName;
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// Equal operator
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
TdkViewUserProperty& TdkViewUserProperty::operator=(const TdkAbstractProperty &other)
{
this->_userName=((TdkViewUserProperty&)other)._userName;
return *this;
}
|
6b212e4675ed54a659ec47267c08bf12d7fa4595
|
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
|
/CodesNew/4666.cpp
|
83389e57efea1ed5d0b44006bd336b1598f34802
|
[] |
no_license
|
thegamer1907/Code_Analysis
|
0a2bb97a9fb5faf01d983c223d9715eb419b7519
|
48079e399321b585efc8a2c6a84c25e2e7a22a61
|
refs/heads/master
| 2020-05-27T01:20:55.921937
| 2019-11-20T11:15:11
| 2019-11-20T11:15:11
| 188,403,594
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 321
|
cpp
|
4666.cpp
|
#include<bits/stdc++.h>
using namespace std;
int n,m[500001],j,k,i,a;
main()
{
cin>>n;
for(i=0; i<n; i++)
cin>>m[i];
sort(m,m+n);
for(j=0; j<n; j++)
{
if(m[j]>=2*m[k])
k++;
}
a = n/2;
a = min(a,k);
n = n-a;
cout<<n;
}
|
e60486a9b85119e5d3af185c59ac0f2152f88426
|
d14b5d78b72711e4614808051c0364b7bd5d6d98
|
/third_party/llvm-16.0/llvm/lib/Target/DirectX/DirectXSubtarget.cpp
|
526b7d29fb13ed5d91e98a96b6c2c2c218709768
|
[
"Apache-2.0"
] |
permissive
|
google/swiftshader
|
76659addb1c12eb1477050fded1e7d067f2ed25b
|
5be49d4aef266ae6dcc95085e1e3011dad0e7eb7
|
refs/heads/master
| 2023-07-21T23:19:29.415159
| 2023-07-21T19:58:29
| 2023-07-21T20:50:19
| 62,297,898
| 1,981
| 306
|
Apache-2.0
| 2023-07-05T21:29:34
| 2016-06-30T09:25:24
|
C++
|
UTF-8
|
C++
| false
| false
| 1,044
|
cpp
|
DirectXSubtarget.cpp
|
//===-- DirectXSubtarget.cpp - DirectX Subtarget Information --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the DirectX-specific subclass of TargetSubtarget.
///
//===----------------------------------------------------------------------===//
#include "DirectXSubtarget.h"
#include "DirectXTargetLowering.h"
using namespace llvm;
#define DEBUG_TYPE "directx-subtarget"
#define GET_SUBTARGETINFO_CTOR
#define GET_SUBTARGETINFO_TARGET_DESC
#include "DirectXGenSubtargetInfo.inc"
DirectXSubtarget::DirectXSubtarget(const Triple &TT, StringRef CPU,
StringRef FS, const DirectXTargetMachine &TM)
: DirectXGenSubtargetInfo(TT, CPU, CPU, FS), FL(*this), TL(TM, *this) {}
void DirectXSubtarget::anchor() {}
|
ea001868aa0e77ec31db9839c25d332d18f514cc
|
9da63bc07c1b71ecc34db52f16e762cf5dfa9d6f
|
/dlls/IVI Foundation/IVI/Drivers/wx218x/Source/IWX218xASK.cpp
|
664b377765702c54d7ec95d64972ea21469076f9
|
[] |
no_license
|
tomdbar/cold-control
|
bd9f64a583793aa9ddefc8a1624948c3290d61bc
|
4ed8aa46915aa9adf1eada1c6cebfd4778b6f42e
|
refs/heads/master
| 2020-03-27T23:32:09.914576
| 2018-09-07T09:32:09
| 2018-09-07T09:32:09
| 147,326,156
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 21,153
|
cpp
|
IWX218xASK.cpp
|
/******************************************************************************
*
* Copyright 2010-2012 Tabor Electronics Ltd.
* All rights reserved.
*
*****************************************************************************/
#include "stdafx.h"
#include "CoWX218x.h"
#pragma warning(disable : 4996)
/* Start Amplitude */
HRESULT WX218x::IWX218xASK_StartAmplitude_RangeCheck(LPCTSTR pszPropertyName, BSTR Channel, double val)
{
HRESULT hr = S_OK;
double valMin, valMax;
valMin = ASK_START_AMPL_MIN;
valMax = ASK_START_AMPL_MAX;
if (val < valMin || val > valMax)
hr = err.InvalidValue(_T("val"), val);
return hr;
}
HRESULT WX218x::IWX218xASK_get_StartAmplitude(BSTR Channel, double* val)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
CString strChanSend, strCommandSend;
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
strCommandSend = WX218x::MakeSCPIString(strChanSend, _T(":ASK:AMPL:STAR?"));
io.Queryf(strCommandSend, _T("%Lf"), val);
return hr;
}
HRESULT WX218x::IWX218xASK_put_StartAmplitude(BSTR Channel, double val)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
CString strChanSend, strCommandSend;
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
strCommandSend.Format(WX218x::MakeSCPIString(strChanSend, _T(":ASK:AMPL:STAR %Lf")), val);
hr = io.Printf(strCommandSend);
return hr;
}
/* Shift Amplitude */
HRESULT WX218x::IWX218xASK_ShiftAmplitude_RangeCheck(LPCTSTR pszPropertyName, BSTR Channel, double val)
{
HRESULT hr = S_OK;
double valMin, valMax;
valMin = ASK_SHIFT_AMPL_MIN;
valMax = ASK_SHIFT_AMPL_MAX;
if (val < valMin || val > valMax)
hr = err.InvalidValue(_T("val"), val);
return hr;
}
HRESULT WX218x::IWX218xASK_get_ShiftAmplitude(BSTR Channel, double* val)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
CString strChanSend, strCommandSend;
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
strCommandSend = WX218x::MakeSCPIString(strChanSend, _T(":ASK:AMPL:SHIF?"));
io.Queryf(strCommandSend, _T("%Lf"), val);
return hr;
}
HRESULT WX218x::IWX218xASK_put_ShiftAmplitude(BSTR Channel, double val)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
CString strChanSend, strCommandSend;
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
strCommandSend.Format(WX218x::MakeSCPIString(strChanSend, _T(":ASK:AMPL:SHIF %Lf")), val);
hr = io.Printf(strCommandSend);
return hr;
}
/* Baud */
HRESULT WX218x::IWX218xASK_Baud_RangeCheck(LPCTSTR pszPropertyName, BSTR Channel, double val)
{
HRESULT hr = S_OK;
double valMin, valMax;
int modelNumber;
modelNumber = FuncReturnModelNumber();
switch (modelNumber)
{
case MNM_WX2181B:
case MNM_WX2182B:
case MNM_WX2181BD:
case MNM_WX2182BD:
valMin = ASK_BAUD_MIN;
valMax = ASK_BAUD_MAX;
break;
case MNM_WX2182C:
case MNM_WX2181C:
case MNM_WX1281C:
case MNM_WX1282C:
valMin = ASK_BAUD_MIN;
valMax = ASK_BAUD_MAX;
break;
case MNM_WX1281B:
case MNM_WX1282B:
case MNM_WX1281BD:
case MNM_WX1282BD:
valMin = ASK_BAUD_MIN;
valMax = ASK_BAUD_MAX_WX128XB;
break;
case MNM_WS8351:
case MNM_WS8352:
valMin = ASK_BAUD_MIN;
valMax = ASK_BAUD_MAX_WS835X;
break;
case MNM_WX2184:
valMin = ASK_BAUD_MIN;
valMax = ASK_BAUD_MAX_WX2184;
break;
case MNM_WX2184C:
case MNM_WX1284C:
valMin = ASK_BAUD_MIN;
valMax = ASK_BAUD_MAX_WX2184C;
break;
case MNM_WX1284:
valMin = ASK_BAUD_MIN;
valMax = ASK_BAUD_MAX_WX1284;
break;
default:
valMin = ASK_BAUD_MIN;
valMax = ASK_BAUD_MAX;
}
if (val < valMin || val > valMax)
hr = err.InvalidValue(_T("val"), val);
return hr;
}
HRESULT WX218x::IWX218xASK_get_Baud(BSTR Channel, double* val)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
CString strChanSend, strCommandSend;
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
strCommandSend = WX218x::MakeSCPIString(strChanSend, _T(":ASK:BAUD?"));
io.Queryf(strCommandSend, _T("%Lf"), val);
return hr;
}
HRESULT WX218x::IWX218xASK_put_Baud(BSTR Channel, double val)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
CString strChanSend, strCommandSend;
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
strCommandSend.Format(WX218x::MakeSCPIString(strChanSend, _T(":ASK:BAUD %Lf")), val);
hr = io.Printf(strCommandSend);
return hr;
}
/* Marker */
HRESULT WX218x::IWX218xASK_Marker_RangeCheck(LPCTSTR pszPropertyName, BSTR Channel, long val)
{
HRESULT hr = S_OK;
long valMin, valMax;
int modelNumber;
modelNumber = FuncReturnModelNumber();
switch (modelNumber)
{
case MNM_WX2184:
case MNM_WX1284:
case MNM_WX2184C:
case MNM_WX1284C:
valMin = ASK_MARKER_MIN;
valMax = ASK_MARKER_MAX_WX2184;
break;
default:
valMin = ASK_MARKER_MIN;
valMax = ASK_MARKER_MAX;
}
if (val < valMin || val > valMax)
hr = err.InvalidValue(_T("val"), val);
return hr;
}
HRESULT WX218x::IWX218xASK_get_Marker(BSTR Channel, long* val)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
CString strChanSend, strCommandSend;
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
strCommandSend = WX218x::MakeSCPIString(strChanSend, _T(":ASK:MARK?"));
io.Queryf(strCommandSend, _T("%d"), val);
return hr;
}
HRESULT WX218x::IWX218xASK_put_Marker(BSTR Channel, long val)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
CString strChanSend, strCommandSend;
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
strCommandSend.Format(WX218x::MakeSCPIString(strChanSend, _T(":ASK:MARK %d")), val);
hr = io.Printf(strCommandSend);
return hr;
}
//================================= ASK Enabled =========================================
HRESULT WX218x::IWX218xASK_get_Enabled(BSTR Channel, VARIANT_BOOL* val)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
CString strChanSend, strCommandSend, strResponse;
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
strCommandSend = WX218x::MakeSCPIString(strChanSend, _T(":MOD:TYPE?"));
io.Queryf(strCommandSend, _T("%$Cs"), &strResponse);
if (!strResponse.CompareNoCase(_T("ASK")))
*val = VARIANT_TRUE;
else
*val = VARIANT_FALSE;
return hr;
}
HRESULT WX218x::IWX218xASK_put_Enabled(BSTR Channel, VARIANT_BOOL val)
{
HRESULT hr = S_OK;
CString strEnabled, strChanSend, strCommandSend;
CString strChanCheck = COLE2T(Channel);
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
strChanSend = WX218x::ReturnChannelSend(strChanCheck);
if (val == VARIANT_TRUE)
strEnabled = _T("ASK");
else
strEnabled = _T("OFF");
strCommandSend.Format(WX218x::MakeSCPIString(strChanSend, _T(":MOD:TYPE %s")), strEnabled);
hr = io.Printf(strCommandSend);
return hr;
}
//=================================================================================================
// - ConfigureASKStartAmplitude -
HRESULT WX218x::IWX218xASK_ConfigureASKStartAmplitude(BSTR Channel, double StartAmpl)
{
HRESULT hr = S_OK;
hr = _IWX218xASK::put_StartAmplitude(Channel, StartAmpl);
return hr;
}
//==================================================================================================
// - ConfigureASKShiftAmplitude -
HRESULT WX218x::IWX218xASK_ConfigureASKShiftAmplitude(BSTR Channel, double ShiftAmpl)
{
HRESULT hr = S_OK;
hr = _IWX218xASK::put_ShiftAmplitude(Channel, ShiftAmpl);
return hr;
}
//================================================================================================
// - ConfigureASKMarker -
HRESULT WX218x::IWX218xASK_ConfigureASKMarker(BSTR Channel, long Marker)
{
HRESULT hr = S_OK;
hr = _IWX218xASK::put_Marker(Channel, Marker);
return hr;
}
//====================================================================================================
// - ConfigureASKEnabled -
HRESULT WX218x::IWX218xASK_ConfigureASKEnabled(BSTR Channel, VARIANT_BOOL Enabled)
{
HRESULT hr = S_OK;
hr = _IWX218xASK::put_Enabled(Channel, Enabled);
return hr;
}
//======================================================================================================
// - ConfigureASKBaud -
HRESULT WX218x::IWX218xASK_ConfigureASKBaud(BSTR Channel, double Baud)
{
HRESULT hr = S_OK;
hr = _IWX218xASK::put_Baud(Channel, Baud);
return hr;
}
//============================== CreateASKDataAdv ===========================================================
HRESULT WX218x::IWX218xASK_CreateASKDataAdv(BSTR Channel, SAFEARRAY** Data)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
long sizeArray;
long lBoundArray, indexArray;
long uBoundArray;
SAFEARRAY* psaData = *Data;
CString strChanSend, strFormatValue, strFormatElement, strFormatParameter;
long askDataLengthByte, totalBytes = 0;
long valueArray;
unsigned char* binData = VI_NULL;
unsigned char* p0 = VI_NULL; //we need this pointer at the end of the loop for know total bytes
long lengthMin, lengthMax;
int modelNumber;
modelNumber = FuncReturnModelNumber();
switch (modelNumber)
{
case MNM_WX2184:
case MNM_WX1284:
case MNM_WX2184C:
case MNM_WX1284C:
lengthMin = ASK_DATA_LENGTH_MIN;
lengthMax = ASK_DATA_LENGTH_MAX_WX2184;
break;
default:
lengthMin = ASK_DATA_LENGTH_MIN;
lengthMax = ASK_DATA_LENGTH_MAX;
}
//Checking parameter Active channel
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
if (GetSimulate()) //temporary close for offline
{
return hr;
}
//Getting size of array
sizeArray = psaData->rgsabound->cElements;
if ((sizeArray< lengthMin) || (sizeArray > lengthMax))
{
hr = ReportInvalidValueError(_T("CreateASKData"), _T("Data"), _T("Size of Data array"));
return hr;
}
//Checking the lower bound of the dimension
lBoundArray = psaData->rgsabound->lLbound;
//Checking if lower bound of array AmplLevel is zero
if (lBoundArray != 0)
{
hr = err.LboundArrayZero(_T("Data Array"));
return hr;
}
//Checking the upper bound of the dimension
hr = ::SafeArrayGetUBound(psaData, 1, &uBoundArray);
//Checking if upper bound of arrays is not zero
if ((uBoundArray == 0))
{
hr = err.UpperBoundZero(_T("Data Array"));
return hr;
}
askDataLengthByte = sizeof(BYTE) * sizeArray;
binData = new unsigned char[askDataLengthByte];
memset(binData, '\0', askDataLengthByte);
//We must save the start of this pointer
p0 = binData;
for (indexArray = lBoundArray; indexArray < sizeArray; indexArray++) //access elements in all arrays
{
hr = SafeArrayGetElement(psaData, &indexArray, &valueArray);
//Checking Data range
if (valueArray < ASK_DATA_MIN || valueArray > ASK_DATA_MAX)
{
strFormatValue.Format(_T("(%d)"), valueArray);
strFormatElement.Format(_T("(%d)"), indexArray);
strFormatParameter.Format(_T("(%s)"), _T("Data"));
hr = err.ElementArrayNotValid(strFormatValue, strFormatElement, strFormatParameter);
if (binData)
delete [] binData;
return hr;
}
//Putting in binData value from array
//*((unsigned char*)p0) = (unsigned char)('0' + valueArray); //temporary for check
*((unsigned char*)p0) = (unsigned char)(valueArray); //temporary for check
p0 += sizeof(unsigned char);
totalBytes = p0 - binData;
}//end for,access elements in all arrays
//Now we need calculate total bytes
totalBytes = p0 - binData;
//Setting Active Channel
hr = _IWX218x::put_ActiveChannel(Channel);
hr = WX218x::LoadGeneralData(totalBytes, binData, TYPE_ASK);
if (binData)
delete [] binData;
return hr;
}
//=================================== LoadASKDataFile =========================================================
HRESULT WX218x::IWX218xASK_LoadASKDataFile(BSTR Channel, BSTR FileName)
{
HRESULT hr = S_OK;
FILE *wfmFile = VI_NULL;
CString strChannel, strFileName, strExtension, strFormatValue;
long lengthFile, lengthString, numBytes, wfmSize, file_count;
unsigned char* binData = VI_NULL;
int data;
long lengthMin, lengthMax;
int modelNumber;
modelNumber = FuncReturnModelNumber();
switch (modelNumber)
{
case MNM_WX2184:
case MNM_WX1284:
case MNM_WX2184C:
case MNM_WX1284C:
lengthMin = ASK_DATA_LENGTH_MIN;
lengthMax = ASK_DATA_LENGTH_MAX_WX2184;
break;
default:
lengthMin = ASK_DATA_LENGTH_MIN;
lengthMax = ASK_DATA_LENGTH_MAX;
}
//Checking parameter Active channel
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
if (GetSimulate()) //temporary close for offline
{
return hr;
}
strFileName = COLE2T(FileName);
lengthFile = strFileName.GetLength();
lengthString = strFileName.GetLength() + 1;
if (!lengthFile)
{
hr = err.InvalidValue(_T("FileName"), FileName);
return hr;
}
//Converting CString to char*/TCHAR
char *tmpChar = new char [lengthString];
TCHAR *tmpStr = new TCHAR [lengthString];
_tcscpy_s(tmpStr, lengthString, strFileName);
numBytes = wcstombs(tmpChar, tmpStr, lengthString);
//Open Asccii File for reading
wfmFile = fopen(tmpChar, "rt");
delete [] tmpChar;
delete [] tmpStr;
if (!wfmFile) //Can not open file
{
hr = err.CannotOpenFile(strFileName);
return hr;
}//end if,Can not open file
wfmSize = 0;
//Getting file size
hr = WX218x::GetAsciiFileSize(strFileName, wfmSize);
if (!SUCCEEDED(hr))
return hr;
binData = new unsigned char [wfmSize];
file_count = 0;
while (file_count < wfmSize && !feof(wfmFile))
{
fscanf(wfmFile, "%d", &data);
//Checking if data in file are correct
if (data < ASK_DATA_MIN || data > ASK_DATA_MAX)
{
strFormatValue.Format(_T("(%Lf)"), data);
hr = err.InvalidFileData(strFormatValue);
if (binData)
delete [] binData;
return hr;
}
//binData[file_count] = (ViByte)('0'+data); //27.07.2013 close becouse Nadav did it in binary way
binData[file_count] = (ViByte)(data); //binary way
file_count ++;
}
fclose(wfmFile);
//Checking if file_count is in correct range
if ((file_count< lengthMin) || (file_count > lengthMax))
{
strFormatValue.Format(_T("(%d)"), file_count);
hr = err.InvalidFileLength(strFormatValue);
if (binData)
delete [] binData;
return hr;
}
//Setting Active Channel
hr = _IWX218x::put_ActiveChannel(Channel);
hr = WX218x::LoadGeneralData(file_count, binData, TYPE_ASK);
if (binData)
delete [] binData;
return hr;
}
//===================================== Create ASK Data ===============================================
HRESULT WX218x::IWX218xASK_CreateASKData(BSTR Channel, SAFEARRAY** Data)
{
HRESULT hr = S_OK;
CString strChanCheck = COLE2T(Channel);
long sizeArray;
long lBoundArray, indexArray;
long uBoundArray;
SAFEARRAY* psaData = *Data;
CString strChanSend, strFormatValue, strFormatElement, strFormatParameter;
long askDataLengthByte, totalBytes = 0;
BYTE valueArray;
unsigned char* binData = VI_NULL;
unsigned char* p0 = VI_NULL; //we need this pointer at the end of the loop for know total bytes
long lengthMin, lengthMax;
int modelNumber;
modelNumber = FuncReturnModelNumber();
switch (modelNumber)
{
case MNM_WX2184:
case MNM_WX1284:
case MNM_WX2184C:
case MNM_WX1284C:
lengthMin = ASK_DATA_LENGTH_MIN;
lengthMax = ASK_DATA_LENGTH_MAX_WX2184;
break;
default:
lengthMin = ASK_DATA_LENGTH_MIN;
lengthMax = ASK_DATA_LENGTH_MAX;
}
//Checking parameter Active channel
hr = WX218x::ActiveChannel_RangeCheck(_T("Channel"), Channel);
if(!SUCCEEDED(hr))
{
hr = err.InvalidValue(_T("Channel"), Channel);
return hr;
}
if (GetSimulate()) //temporary close for offline
{
return hr;
}
//Getting size of array
sizeArray = psaData->rgsabound->cElements;
if ((sizeArray< lengthMin) || (sizeArray > lengthMax))
{
hr = ReportInvalidValueError(_T("CreateASKData"), _T("Data"), _T("Size of Data array"));
return hr;
}
//Checking the lower bound of the dimension
lBoundArray = psaData->rgsabound->lLbound;
//Checking if lower bound of array AmplLevel is zero
if (lBoundArray != 0)
{
hr = err.LboundArrayZero(_T("Data Array"));
return hr;
}
//Checking the upper bound of the dimension
hr = ::SafeArrayGetUBound(psaData, 1, &uBoundArray);
//Checking if upper bound of arrays is not zero
if ((uBoundArray == 0))
{
hr = err.UpperBoundZero(_T("Data Array"));
return hr;
}
askDataLengthByte = sizeof(BYTE) * sizeArray;
binData = new unsigned char[askDataLengthByte];
memset(binData, '\0', askDataLengthByte);
//We must save the start of this pointer
p0 = binData;
for (indexArray = lBoundArray; indexArray < sizeArray; indexArray++) //access elements in all arrays
{
hr = SafeArrayGetElement(psaData, &indexArray, &valueArray);
//Checking Data range
if (valueArray < ASK_DATA_MIN || valueArray > ASK_DATA_MAX)
{
//NEW 27.11.2013 add by Ira
//Doing this for LabView Wrapper
if (valueArray == 49)
valueArray = 1;
else if (valueArray == 48)
valueArray = 0;
else //the data was wrong
{
strFormatValue.Format(_T("(%d)"), valueArray);
strFormatElement.Format(_T("(%d)"), indexArray);
strFormatParameter.Format(_T("(%s)"), _T("Data"));
hr = err.ElementArrayNotValid(strFormatValue, strFormatElement, strFormatParameter);
if (binData)
delete [] binData;
return hr;
}//end else the data was wrong
}
//Putting in binData value from array
//*((unsigned char*)p0) = (unsigned char)('0' + valueArray); //temporary for check
*((unsigned char*)p0) = (unsigned char)(valueArray); //temporary for check
p0 += sizeof(unsigned char);
totalBytes = p0 - binData;
}//end for,access elements in all arrays
//Now we need calculate total bytes
totalBytes = p0 - binData;
//Setting Active Channel
hr = _IWX218x::put_ActiveChannel(Channel);
hr = WX218x::LoadGeneralData(totalBytes, binData, TYPE_ASK);
if (binData)
delete [] binData;
return hr;
}
|
8923f5f424030c183927064371514fc9994a03ec
|
98e575d2911f291ec152e32721468a0ccb9b7dd0
|
/sockets/Archive/findLocalIp.h
|
b4af7bba6322ef6e41469c81a44f3c0bfab567df
|
[] |
no_license
|
BenjaminKnol/domotica
|
3f54840e9271450d9ac766b4aeae0d8ecf4b96e5
|
ed8a280bd39edc90409b031d09f50109a85df1e5
|
refs/heads/master
| 2023-03-01T04:25:40.684365
| 2021-01-28T08:32:41
| 2021-01-28T08:32:41
| 315,907,622
| 1
| 1
| null | 2021-02-03T22:44:29
| 2020-11-25T10:41:39
|
PHP
|
UTF-8
|
C++
| false
| false
| 360
|
h
|
findLocalIp.h
|
//
// Created by benja on 08/01/2021.
//
#ifndef SOCKETS_FINDLOCALIP_H
#define SOCKETS_FINDLOCALIP_H
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
class findLocalIp {
public:
string findIp();
};
#endif //SOCKETS_FINDLOCALIP_H
|
ad4f9f4fdba4e4b575ab26307ad6a1035acd5e41
|
725aabdfb0a30083357a72f989eefa9b2d710aad
|
/strutture/Location.cpp
|
e49e9c352c566d3c6e1170912b745f530faeeaaa
|
[] |
no_license
|
luigimassagallerano/posix-file-sharing
|
aa7c38ae7928d455071fad2dd5061e9a16454814
|
09053fd15782feeb6b68236cbb72b548594614ba
|
refs/heads/master
| 2021-01-02T08:33:29.798419
| 2013-02-10T11:22:42
| 2013-02-10T11:22:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 967
|
cpp
|
Location.cpp
|
#include "../include/Location.h"
Location::Location(const string& ip, const string& porta, int mc)
{
ip_FS = ip;
porta_FS = porta;
if(sem_init(&maxClient, 0, mc) == -1) sys_err("Inizializzazione maxClient Fallita!\n");
}
Location::Location(const string& ip, const string& porta)
{
ip_FS = ip;
porta_FS = porta;
}
string Location::getLocation()
{
//prima di poter ottenere la Location bisogna acquisire maxClient
sem_wait(&maxClient);
//solo se ci sono slot liberi il thread otterrà la Location
return ip_FS+":"+porta_FS;
}
bool Location::equals(Location& l)
{
if( (ip_FS+":"+porta_FS).compare(l.getLocation()) == 0) return true;
return false;
}
void Location::liberaSlot()
{
sem_post(&maxClient); //sarà il DFR a risvegliare i thread client che aspettano uno slot
}
bool Location::haveSlot()
{
int value;
sem_getvalue(&maxClient, &value);
if(value > 0) return true;
return false;
}
string Location::stampa()
{
return ip_FS+":"+porta_FS;
}
|
dc13e719b2eef41a33b9318c20f68f781ae6a3f9
|
1b28e004adc4d365eb70165719c08e59cc1d8b10
|
/ci22.cpp
|
7521f44ab0741f271f551b6578a47b97255630a3
|
[] |
no_license
|
weirme/leetme
|
e5a98abdc0816dbe87292172c41c328513640898
|
0e3d4c40c8e122cde8f50ab541b182041c53078d
|
refs/heads/master
| 2022-06-08T15:21:26.554825
| 2022-02-19T11:23:51
| 2022-02-19T11:23:51
| 203,276,581
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 686
|
cpp
|
ci22.cpp
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include "types.h"
using namespace std;
const int INF = 0x3f3f3f3f;
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
if (head == nullptr)
return head;
ListNode * p = head;
ListNode * q = head;
while (k-- && p != nullptr) {
p = p->next;
}
if (k > 0) return nullptr;
while (p != nullptr) {
p = p->next;
q = q->next;
}
return q;
}
};
|
10a3299eb32d81f65fcd6c17d976ad63be3040e5
|
312463a0ad42b933cce6a851004ab5e56e5b4fb4
|
/src/neb/gfx/core/actor/plugin.cpp
|
51a9d788fcd252c6c833fe226b7e488a35c902c4
|
[] |
no_license
|
Luddw/Nebula-Graphics
|
bfeeedafc18f18728fb9b5adc8198f12a56891af
|
8d787f4fed27e9d0130f69a4473d5bfe48e02794
|
refs/heads/master
| 2021-05-29T17:42:09.056540
| 2015-03-11T03:17:14
| 2015-03-11T03:17:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 349
|
cpp
|
plugin.cpp
|
#include <neb/fnd/plug/gfx/core/actor/util/decl.hpp>
#include <neb/gfx/core/actor/base.hpp>
namespace NS0 = neb::fnd::plug::gfx::core::actor;
namespace NS1 = neb::gfx::core::actor;
typedef NS0::Base T0;
typedef NS1::base T;
extern "C" T0* actor_create(int i)
{
return new T;
return 0;
}
extern "C" void actor_destroy(T0* t)
{
delete t;
}
|
b5130155719f4105854212c5a2f1bbb3a3707677
|
10ec02d50efe300575da214023bb8f93801f5882
|
/Kursovaya/Site.h
|
16a4e3c6b0250c05b33d40332817df9b396dec6d
|
[] |
no_license
|
Pavelpro-art/Kurs
|
07b15f32116c2e0e567fd586e5d32796f2eca872
|
212dda625746532202f6d6d3d26e9f7018b658d4
|
refs/heads/master
| 2022-09-25T01:52:40.219548
| 2020-06-07T21:56:46
| 2020-06-07T21:56:46
| 269,346,562
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 186
|
h
|
Site.h
|
#pragma once
#include "Chain.h"
class Site : public Сhain {
protected:
string filename;
void result(Game* game);
public:
Site(); //конструктор
string get_filename();
};
|
4f71e19d8845d5e235beb1635bb5ce48668a52b5
|
e83fd6a92810c746415a0648306ba2549d2df6ce
|
/src/Entity/Mesh.cpp
|
662721a217dd82130f37dff59411f66420f11374
|
[] |
no_license
|
Craigspaz/Axle
|
e59906af68a9d9b7e3fc7902cb4b70d630b09811
|
9a37162e393dba9f1a5b5769a6d88cd59a3e4a37
|
refs/heads/master
| 2023-06-05T15:08:47.044512
| 2021-06-23T01:38:12
| 2021-06-23T01:38:12
| 114,414,532
| 0
| 0
| null | 2020-10-12T18:05:57
| 2017-12-15T21:59:07
|
C
|
UTF-8
|
C++
| false
| false
| 61
|
cpp
|
Mesh.cpp
|
#include "Entity/Mesh.h"
Mesh::Mesh()
{
}
Mesh::~Mesh()
{
}
|
9aff91d8ab74f3a0edbd0b96b53e448375e6357f
|
b3588eb9c3747e2e95881f88c2a2c522ce784dc3
|
/inc/camera.h
|
314fe50887fe237e5ce7ca95f82d89ac2544c2cc
|
[] |
no_license
|
knightlyj/renderer
|
90a819420ac9da4c5dadb8784f4b2e4c25c0f085
|
628397228b12c9aeea46d353eb39f48afb9230eb
|
refs/heads/master
| 2021-01-20T13:46:00.285606
| 2018-08-26T15:05:32
| 2018-08-26T15:05:32
| 90,527,317
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,881
|
h
|
camera.h
|
#pragma once
#include <vector>
#include "transform.h"
#include "math3d.h"
#include "matrix.h"
#include "RenderTexture.h"
#include "vertex.h"
#include "FbxModel.h"
class Camera
{
public:
Camera() {
Setup(-1, -1000, 1, 90);
}
Camera(float n, float f, float aspect, float fov) {
Setup(n, f, aspect, fov);
}
void Setup(float n, float f, float aspect, float fov)
{
this->fov = fov;
this->aspect = aspect;
this->n = n;
this->f = f;
this->b = n * tan(fov * PI / 360);
this->t = -this->b;
this->l = this->b * aspect;
this->r = this->t * aspect;
SetupFrumstum();
}
~Camera() {}
Transform transform;
void SetFov(float newFov) {
if (newFov > 120)
newFov = 120;
else if (newFov < 50)
newFov = 50;
Setup(n, f, aspect, newFov);
}
float GetFov() {
return this->fov;
}
void LookAt(MyMath::Vector3 point) {
//没有做
}
MyMath::HomoVector4 PerspectiveProj(MyMath::HomoVector4 point) {
MyMath::HomoVector4 newPoint = this->perspect * point;
return newPoint;
}
//z为向前,y为向上,x为向左
void Move(MyMath::Vector3 dist) {
MyMath::Vector3 mov(-dist.x, dist.y, -dist.z);
mov = transform.rotation * mov;
transform.position += mov;
}
//渲染模型
void RenderModel(RenderTexture* pRenderTexture, FbxModel *pModel);
//画三角形
void DrawTriangle(RenderTexture* pRenderTexture, Vertex v0, Vertex v1, Vertex v2);
MyMath::MyMat4 perspect;
private:
void SetupFrumstum() {
perspect.data[0][0] = 2 * n / (r - l);
perspect.data[0][1] = 0;
perspect.data[0][2] = -(r + l) / (r - l);
perspect.data[0][3] = 0;
perspect.data[1][0] = 0;
perspect.data[1][1] = 2 * n / (t - b);
perspect.data[1][2] = -(t + b) / (t - b);
perspect.data[1][3] = 0;
perspect.data[2][0] = 0;
perspect.data[2][1] = 0;
perspect.data[2][2] = (f + n) / (f - n);
perspect.data[2][3] = -2 * f * n / (f - n);
perspect.data[3][0] = 0;
perspect.data[3][1] = 0;
perspect.data[3][2] = 1;
perspect.data[3][3] = 0;
leftBd = l / n;
rightBd = r / n;
bottomBd = b / n;
topBd = t / n;
}
MyMath::HomoVector4 WorldToCamera(MyMath::HomoVector4 point);
bool FrustumCull(Vertex *v0, Vertex *v1, Vertex *v2);
bool BackFaceCull(Vertex *v0, Vertex *v1, Vertex *v2);
void HomoClip(vector<Vertex> *in, vector<Vertex> *out);
void Triangulate(vector<Vertex> *in, vector<int> *out);
typedef bool(*VertexInternalFunc)(Vertex *pV, Camera *pCamera); //判断是否在内部
typedef void(*IntersectionFunc)(Vertex *v1, Vertex *v2, Vertex *out, Camera *pCamera); //计算交点
//齐次裁减,传入不同的函数,裁减不同的平面
void Clip(vector<Vertex> *in, vector<Vertex> *out, VertexInternalFunc isInternal, IntersectionFunc getIntersection);
//近平面裁剪
static bool VertexInNear(Vertex *pV, Camera *pCamera);
static void IntersectionOnNear(Vertex *pV1, Vertex *pV2, Vertex *pOut, Camera *pCamera);
//远平面裁剪
static bool VertexInFar(Vertex *pV, Camera *pCamera);
static void IntersectionOnFar(Vertex *pV1, Vertex *pV2, Vertex *pOut, Camera *pCamera);
//左右算法可能反了,但不影响结果
//左平面裁剪
static bool VertexInLeft(Vertex *pV, Camera *pCamera);
static void IntersectionOnLeft(Vertex *pV1, Vertex *pV2, Vertex *pOut, Camera *pCamera);
//右平面裁剪
static bool VertexInRight(Vertex *pV, Camera *pCamera);
static void IntersectionOnRight(Vertex *pV1, Vertex *pV2, Vertex *pOut, Camera *pCamera);
//上平面裁剪
static bool VertexInTop(Vertex *pV, Camera *pCamera);
static void IntersectionOnTop(Vertex *pV1, Vertex *pV2, Vertex *pOut, Camera *pCamera);
//下平面裁剪
static bool VertexInBottom(Vertex *pV, Camera *pCamera);
static void IntersectionOnBottom(Vertex *pV1, Vertex *pV2, Vertex *pOut, Camera *pCamera);
double l, r, t, b, n, f; //frustum参数
double leftBd, rightBd, topBd, bottomBd;
float fov, aspect;
};
|
90e4cb34ff4a84552abc7846e5e0761d670020d4
|
c937d29654550947de0354fcd330ca4a642458be
|
/ExportPart.h
|
2312c9bf97e6b020b97a767f7ccfa5f85d11f3a3
|
[] |
no_license
|
EricFonk/Database
|
5ba76415b2957eab5c2566055160970d63d4fdce
|
169a9c53649f4800c0c54b26e4532af4f111be09
|
refs/heads/master
| 2021-01-12T04:01:19.611722
| 2016-09-10T07:28:34
| 2016-09-10T07:28:34
| 77,472,015
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,054
|
h
|
ExportPart.h
|
//
// ExportPart.hpp
//
// Created by Eric on 16/8/21.
//
//
#ifndef EXPORTPART_H
#define EXPORTPART_H
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QListView>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QTableView>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QWidget>
#include <QtWidgets/QGroupBox>
#include <QtGui>
#include <qboxlayout.h>
#pragma pack(push,1)
typedef struct database
{
QString databasename;
QStringList table;
bool SelectStatus = false;
}database;
#pragma pack(pop)
class ExportPart :public QWidget
{
Q_OBJECT
public:
ExportPart();
void TableWidgetShowDatabasesInit();
void FileCopy(QString TempFile, QString FinalFile);
QString GetType();
public:
QVBoxLayout *WholeWindow;
QWidget *WholeExport;
//显示数据库部分
QGroupBox *GroupBox_TablesToExport;
QHBoxLayout *TopLayout_1;
QHBoxLayout *TopLayout_2;
QVBoxLayout *TopLayout;
QTableWidget *TableWidget_ShowDatabases;
QTableWidget *TableWidget_ShowTables;
QPushButton *PushBtn_Refresh;
QComboBox *ComboBox_ExportType;
QPushButton *PushBtn_SelectTable;
QPushButton *PushBtn_UnselectAll;
//导出对象部分
QGroupBox *GroupBox_ObjectToExport;
QHBoxLayout *MidLayout;
QCheckBox *CheckBox_ExportSet1;//Dump Stored procedures and Functions
QCheckBox *CheckBox_ExportSet2;// Dump Events
QCheckBox *CheckBox_ExportSet3;//Dump Trigger
//导出设置部分
QGroupBox *GroupBox_ExportOption;
QHBoxLayout *BottomLayout;
QLabel *Label_ExportFolder;
QLineEdit *LineEdit_ExportPath;
QPushButton *PushBtn_FileOpen;
//导出按钮部分
QHBoxLayout *OtherLayout;
QLabel *Label_PromptStatement;
QPushButton *PushBtn_StartExport;
private slots:
bool ExportConnectSQL();
void Refresh();
void SavePath();
void GetTable(int row, int col);
void GetSelectTable(int row, int col);
void Export();
void Select_AllTable();
void UnSelect_AllTable();
};
#endif
|
90d91b6897f8cc27e3c90a689aafd4396b65b2d5
|
bc965d59d05962a911d2aeffe419d86e076a71b6
|
/exercises/lab6/task3.cpp
|
6a4b9fc03e57afe1fe277cae8415483784026299
|
[] |
no_license
|
AGalabov/up-2019-2020
|
c8449dc7b6efa0bef4be8df3aba9833a5b9539c0
|
96eff071fa8efc9e3e1ef206b8d2311c4dcafe86
|
refs/heads/master
| 2020-08-13T19:19:20.231489
| 2020-01-13T12:54:33
| 2020-01-13T12:54:33
| 215,024,194
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,120
|
cpp
|
task3.cpp
|
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[1001];
cin.getline(str, 1001);
int histogram['z' - 'a' + 1]; // 26 letters
/*
'z' and 'a' are constant, there will be no error. So you don't have to remember how many letters there
are in the alphabet z = 'a' + 25, so we need 1 more for a!
*/
for (int i = 0; i <= ('z' - 'a'); i++)
{
histogram[i] = 0; // ALWAYS SET THE MEMORY BEFORE USING IT
}
for (int i = 0; i < strlen(str); i++)
{
if ('a' <= str[i] && str[i] <= 'z')
{
int indexOfLetter = str[i] - 'a'; // This ensures 'a' to be at index 0, b -> 1, ... , z -> 25
histogram[indexOfLetter]++; // We add 1 to the index of the letter, thus counting the letter;
}
}
for (int i = 0; i <= ('z' - 'a'); i++)
{
if (histogram[i] != 0) // We onlu want to print existing symbols
{
cout << char(i + 'a') << ":" << histogram[i] << endl;
// Prints the i-th symbol after 'a' = corresponding letter
}
}
return 0;
}
|
f6ba9b53edf768af717409581a0fcae1a488984e
|
1d4204c6766449214544a6511e138782712c0806
|
/Src/Simulation/DockWidget.h
|
950833dc3c0a831ca785812190cd44941d12a9bc
|
[] |
no_license
|
spyfree/tjNaoBackup
|
2d0291a83f8473346546567ae7856634f6c5a292
|
0c7dd47f65e23be6e9d82a31f15ef69a3ce386cb
|
refs/heads/master
| 2016-09-06T08:20:52.068351
| 2014-01-31T03:33:19
| 2014-01-31T03:33:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,334
|
h
|
DockWidget.h
|
#ifndef DOCKWIDGET_H
#define DOCKWIDGET_H
#include <QDockWidget>
#include <QAbstractItemModel>
#include <QTreeView>
#include <QModelIndex>
#include <QStringListModel>
#include <QVariant>
#include "MotionWindow.h"
class DockWidget :public QDockWidget
{
Q_OBJECT
public:
DockWidget(QWidget *parent=0);
DockWidget(const QString & title, QWidget *parent=0);
};
//TreeItem is like a dir
class TreeItem
{
public:
TreeItem(const QVector<QVariant> &data, TreeItem *parent = 0);
~TreeItem();
bool AddChildren(int position ,int rowcount,int columnscount );
bool RemoveChildren(int posion,int rowcount);
int RowCount();
int columnCount() const;
QVariant GetData(int columnscount);
TreeItem *parent();
TreeItem *children(int row);
bool SetData(int columns,const QVariant &value);
QList<TreeItem*>childItems;
private:
QVector<QVariant>itemData;
TreeItem *parentItem;
};
class TreeModel:public QAbstractItemModel
{
Q_OBJECT
public:
TreeModel(const QStringList&header,const QString &data,
QObject *parent = 0);
~TreeModel();
int rowCount ( const QModelIndex & parent = QModelIndex() ) const;
int columnCount ( const QModelIndex & parent = QModelIndex() ) const;
QVariant data(const QModelIndex&index,int role= Qt::DisplayRole)const;
private:
bool setData(const QModelIndex &index, const QVariant &value,int role = Qt::EditRole);
QModelIndex index ( int row, int column, const QModelIndex & parent = QModelIndex() ) const;
TreeItem* itemFromIndex(const QModelIndex &index)const ;
QModelIndex parent ( const QModelIndex & index ) const ;
TreeItem *rootItem;
void setupModelData(const QStringList &lines, TreeItem *parent);
QVariant headerData ( int section, Qt::Orientation orientation,
int role = Qt::DisplayRole ) const ;
Qt::ItemFlags flags(const QModelIndex &index) const;
bool insertRows(int position, int rows,
const QModelIndex &parent = QModelIndex());
};
class Tree:public DockWidget
{
Q_OBJECT
public:
Tree(QWidget*parent=0);
void SetModel(TreeModel &model);
signals:
void MotionSeen(QString str );
void ParentNodeStr(QString str);
private slots:
void itemActivatedSlot(const QModelIndex& index);
private:
void CreatConnect();
QTreeView *treeView;
TreeModel *treeModel;
QStringListModel *model;
};
#endif
|
710d1939a454c1b884f5cf1b4f756b94a2eef01a
|
06861f9da5c7ef4764ba2b739c7b8028160d59e4
|
/MyLittleGame/source/Application.h
|
714cc39f3a098fc4413165cad9b6192ae7298bd4
|
[] |
no_license
|
archfedorov/tryGithub
|
17161edfe22112c152f58a5e307139f5b917b378
|
4d05e7b57d0b52163d896c204aa11e39c3f95d72
|
refs/heads/master
| 2023-01-06T05:13:29.354220
| 2020-11-07T05:16:53
| 2020-11-07T05:16:53
| 240,283,151
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 274
|
h
|
Application.h
|
#pragma once
#include "SFMLForward.h"
namespace mlg {
class Application {
private:
sf::RenderWindow* window;
void processInput();
void update(const sf::Time&);
void render();
void initialize();
public:
Application();
~Application();
void run();
};
}
|
3dbd3ad0a2c93ed87a3da5323e74a5590b1ef896
|
8351df6733abc3d833a19cbc10ae2942521af003
|
/src/infra/MessageException.h
|
2372f0a91a88e7f823fe6d4ae06c54a1ae2e6de4
|
[] |
no_license
|
eklavya1983/datom
|
4d569adbecfa908d2829015dcfd13b5be639cd62
|
29800008a40040a958c57571c4b9abd42420e75e
|
refs/heads/master
| 2021-01-12T16:08:23.374707
| 2017-03-29T02:12:57
| 2017-03-29T02:12:57
| 71,948,107
| 1
| 1
| null | 2017-04-07T19:41:34
| 2016-10-25T23:40:06
|
C++
|
UTF-8
|
C++
| false
| false
| 549
|
h
|
MessageException.h
|
#pragma once
#include <infra/StatusException.h>
namespace infra {
struct MessageException : StatusException {
MessageException(Status status, const std::string &message)
: StatusException(status),
message_(message)
{
}
void setMessage(const std::string &message)
{
message_ = message;
}
const std::string& getMessage() const
{
return message_;
}
const char* what() const noexcept override
{
return message_.c_str();
}
protected:
std::string message_;
};
}
|
4fcb6750afb1e82c5172a2ded87da396def7c04d
|
42bfe89e7d24abf27d8c1e047ada75cccc9cd850
|
/Arduino/submodule/submodule.ino
|
6b219124bc8ee495c21fc9148ae40cba05e5ec85
|
[] |
no_license
|
ayware/smart_home
|
e1ff4bb34661446273ea93b0e8cee52de9240607
|
3066eaab136d4ab08c1862d23079458d773a517c
|
refs/heads/master
| 2022-10-21T14:54:15.250805
| 2020-06-15T12:42:12
| 2020-06-15T12:42:12
| 270,732,384
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,008
|
ino
|
submodule.ino
|
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#define CSN_PIN 10
#define CE_PIN 9
#define NRF_DATA_LED 6
#define RELAY_PIN 7
#define POT_PIN A0
#define BLINK_DELAY 50
RF24 alici(CE_PIN, CSN_PIN);
const byte address[6] = {"00001"};
struct Data {
int socketValue;
int ledValue;
int potValue;
};
void initNrf();
struct Data dataGet;
void setup() {
Serial.begin(9600);
pinMode(NRF_DATA_LED, OUTPUT);
pinMode(RELAY_PIN, OUTPUT);
initNrf();
}
void loop() {
if (alici.available()) {
Serial.println("available");
alici.read(&dataGet, sizeof(dataGet));
Serial.println("socket: " + String(dataGet.socketValue));
blinkLed(NRF_DATA_LED, BLINK_DELAY);
if (dataGet.socketValue == 1)
digitalWrite(RELAY_PIN, HIGH);
else
digitalWrite(RELAY_PIN, LOW);
} else {
digitalWrite(NRF_DATA_LED, LOW);
}
}
void blinkLed(int ledPin, long t) {
digitalWrite(ledPin, HIGH);
delay(t);
digitalWrite(ledPin, LOW);
delay(t);
}
|
0dcfba81c005d176d8e760b261c9f6959d79f26d
|
ddf9da2d740d24ebf786d9fe9df3ba49e648e53c
|
/bridge/abstraction.cpp
|
fc8f06d7f8aae188adae52075b540cb20199e9a9
|
[] |
no_license
|
archdoor/DesignPatterns
|
3ed1259bbb9cc5ee6fc0f308525fa63fbf3d20c5
|
5e4ce6913504929228f891c80e2f5bd59d12df4d
|
refs/heads/master
| 2020-04-25T03:20:10.542138
| 2019-02-25T09:17:40
| 2019-02-25T09:17:40
| 172,472,627
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 322
|
cpp
|
abstraction.cpp
|
#include "abstraction.h"
Abstraction::Abstraction()
{
}
Abstraction::~Abstraction()
{
}
DefinedAbstraction::DefinedAbstraction(AbstractionImplement* absImp)
{
this->absImp = absImp;
}
DefinedAbstraction::~DefinedAbstraction()
{
}
void DefinedAbstraction::operation()
{
absImp->operation();
}
|
8ee86758207fe778a5bf362efc750ad6a8b82d70
|
8c4c0e3a496f74d955a299dc9dfad2ceefbcf82f
|
/Bitwise_Operators/ShreyasheeS2.cpp
|
3e366757d3689a2c8efe794e567aa35fa40586d6
|
[
"MIT"
] |
permissive
|
shwethabm/Hacktoberfest-2k17
|
002e9a97ebfcae001e199155e4c904d28573bd94
|
87383df4bf705358866a5a4120dd678a3f2acd3e
|
refs/heads/master
| 2020-03-31T04:31:42.151588
| 2017-11-03T11:18:25
| 2017-11-03T11:18:25
| 151,909,308
| 0
| 1
|
MIT
| 2018-10-08T15:20:35
| 2018-10-07T05:33:08
|
C
|
UTF-8
|
C++
| false
| false
| 401
|
cpp
|
ShreyasheeS2.cpp
|
//This code in C++ swaps the even and odd bits in a binary number and prints the resultant decimal number.
#include<iostream>
using namespace std;
int main()
{
//code
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
unsigned int even=n&(0x5555);
unsigned int odd=n&(0xAAAA);
even=even<<1;
odd=odd>>1;
unsigned int num=even|odd;
cout<<num<<endl;
}
return 0;
}
|
92294b9bfb2df20e7465dfb366c699820655c771
|
1be66b32b55baeef9dff49bafc04a26dce301192
|
/RTS_Prototype/BSRTSCamera.h
|
2707f2f16ea20ac914af37c041fa63118058e680
|
[] |
no_license
|
LarssonSv/HordeHavoc
|
d66c622814d0794ad08c076af9d441ac311aa407
|
a2435f09ef0018995497b9cf1def7f573f7fd491
|
refs/heads/master
| 2020-08-05T00:36:29.716542
| 2019-10-23T07:34:50
| 2019-10-23T07:34:50
| 212,334,305
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,883
|
h
|
BSRTSCamera.h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "Components/BSElementComponentSystem.h"
#include "BSRTSCamera.generated.h"
UCLASS()
class TEAM2_PROJECT2_API ABSRTSCamera : public APawn
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Components)
class USceneComponent* CameraAttachmentPoint;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Components)
class USpringArmComponent* CameraArm;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Components)
class UCameraComponent* Camera;
UPROPERTY(EditDefaultsOnly, Category = Movement)
float HeightBuffer = 15.0f;
UPROPERTY(EditDefaultsOnly, Category = Movement)
float WidthBuffer = 15.0f;
UPROPERTY(EditDefaultsOnly, Category = Movement)
float Speed = 1000;
UPROPERTY(EditDefaultsOnly, Category = Movement)
float Acceleration = 100;
UPROPERTY(EditDefaultsOnly, Category = Movement)
float Deceleration = 100;
UPROPERTY(EditDefaultsOnly, Category = Movement)
float FollowCameraSmoothing = 1000;
UPROPERTY(EditDefaultsOnly, Category = Movement)
float RotationSpeed = 1000;
UPROPERTY(EditDefaultsOnly, Category = Zoom)
float ZoomSpeed = 1000;
UPROPERTY(EditDefaultsOnly, Category = Zoom)
float MinDistance = 300.0f;
UPROPERTY(EditDefaultsOnly, Category = Zoom)
float MaxDistance = 1000.0f;
UPROPERTY(EditDefaultsOnly, Category = Zoom)
float ClampAngle = 35.0f;
UPROPERTY(EditDefaultsOnly)
float LerpSpeed = 40.f;
UPROPERTY(EditDefaultsOnly, Category = Bounding)
FString BoundingBoxName = "BoundingBox";
UPROPERTY(EditDefaultsOnly, Category = CameraShake)
TSubclassOf<UCameraShake> ExplosionShake;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
bool Activated = true;
private:
class ABSPlayerController* PlayerController;
float RotationInput;
float HorizontalInput;
float VerticalInput;
float ZoomInput;
float CurrentSpeed;
FVector MovementDirection;
float TargetHeight;
class ATriggerBox* BoundingBox = nullptr;
bool FocusOnUnits;
const float MINIMUM_ACCEPTED_INPUT = 0.1f;
FRotator StartRotation;
public:
ABSRTSCamera();
virtual void BeginPlay() override;
virtual void Tick(float DeltaTime) override;
virtual void SetupPlayerInputComponent(UInputComponent* InputComponent) override;
void ExplodeShake();
private:
void UpdateRotation(const float DeltaTime);
void UpdateZoom(const float DeltaTime);
void UpdateMovement(const float DeltaTime);
void FollowUnits(const float DeltaTime);
void SetRotationInput(float rotation);
void SetHorizontalInput(float horizontal);
void SetVerticalInput(float vertical);
void SetZoomInput(float zoom);
void FollowGroundLevel(float DeltaTime);
UFUNCTION()
void SetFocusInput();
};
|
41f042425ee2884ce0c39cc01afe2043d64e0221
|
9eab75ac8109b4cd6968718252cf949dd54ff8f4
|
/codeforces/cf_ringRoad.cpp
|
991fccf5cdf5e9316a16286f42eab023430a7468
|
[] |
no_license
|
tymefighter/CompetitiveProg
|
48131feca6498672c9d64787a27bea20597e5810
|
f867d53c6f1b307d8f2d323a315974b418abd48d
|
refs/heads/master
| 2021-06-09T14:09:16.186246
| 2021-05-17T14:17:14
| 2021-05-17T14:17:14
| 186,087,058
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,741
|
cpp
|
cf_ringRoad.cpp
|
#include<iostream>
#include<cstdio>
#include<vector>
#include<map>
#include<utility>
using namespace std;
bool check_edge(vector<pair<int, int> > &a, int u)
{
for(auto x : a)
{
if(x.first == u)
return true;
}
return false;
}
int find_wt(vector<pair<int, int> > &a, int u)
{
for(auto x : a)
{
if(x.first == u)
{
//printf("%d %d\n", x.first, x.second);
return x.second;
}
}
return -100000;
}
int main()
{
int i, n, cost1, cost2, count, x, w, start, end;
vector<vector<int> >a;
vector<vector<pair<int, int> > > adjList;
vector<bool> visited;
map<int, int> m;
cin>>n;
//cout<<n<<'\n';/////
adjList.resize(n);
a.resize(n);
visited.assign(n, false);
for(i = 0;i < n;i++)
{
cin>>start>>end>>w;
start--;
end--;
//printf("%d %d %d\n", n, start, end);
a[start].push_back(end);
a[end].push_back(start);
adjList[start].push_back(make_pair(end, w));
}
x = count = 0;
while(visited[x] == false)
{
visited[x] = true;
m[count] = x;
//printf("%d %d\n", count, x);
count++;
if(visited[a[x][0]] == false)
x = a[x][0];
else
x = a[x][1];
}
//cout<<count<<'\n';
cost1 = 0;
for(i = 0;i < count-1;i++)
{
//printf("%d %d\n", m[i]+1, m[i+1]+1);
if(check_edge(adjList[m[i]], m[i+1]) == false)
cost1 += find_wt(adjList[m[i+1]], m[i]);
}
if(check_edge(adjList[m[count-1]], m[0]) == false)
cost1 += find_wt(adjList[m[0]], m[count-1]);
cost2 = 0;
for(i = count - 1;i >= 1;i--)
{
if(check_edge(adjList[m[i]], m[i-1]) == false)
cost2 += find_wt(adjList[m[i-1]], m[i]);
}
if(check_edge(adjList[m[0]], m[count-1]) == false)
cost2 += find_wt(adjList[m[count-1]], m[0]);
//printf("%d %d\n",cost1, cost2);
cout<<min(cost1, cost2)<<'\n';
return 0;
}
|
22472a9d4f5e418cbbbfdd6703cdd2889b012cc1
|
96aacfe8ce2922cad8d4b8bd0f341b0297f70323
|
/LineEditor.cpp
|
5f1a1a69ca96854db5aa43569220d51c5df63127
|
[] |
no_license
|
andrewfsanchez/DataStructure-Project-1
|
52f134882982ce2858f6cd33a144986454aee0c2
|
75710c29e02592cac464ae14bc01bc63257cb1f0
|
refs/heads/master
| 2020-03-28T16:22:51.612396
| 2018-09-26T22:11:00
| 2018-09-26T22:11:00
| 148,688,666
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,847
|
cpp
|
LineEditor.cpp
|
#include "stdafx.h"
#include "LineEditor.h"
LineEditor::LineEditor()
{
LinkedList document;
}
void LineEditor::start() {
bool t = true;
while (t)
{
std::string input = "";
getline(std::cin, input);
std::string temp = input.substr(0, input.find(" "));
if (temp.compare("insertEnd") == 0)
{
int start = input.find("\"") + 1;
int length = input.rfind("\"") - 1 - input.find("\"");
temp = input.substr(start, length);
document.addNode(temp);
}
else if (temp.compare("insert") == 0)
{
temp = input.substr(input.find(" ") + 1);
std::string temp2 = temp.substr(0, temp.find(" "));
int index = stoi(temp2); //converts string to int.
int start = input.find("\"") + 1;
int length = input.rfind("\"") - 1 - input.find("\"");
temp = input.substr(start, length);
document.addNode(index - 1, temp);
}
else if (temp.compare("edit") == 0)
{
temp = input.substr(input.find(" ") + 1);
std::string temp2 = temp.substr(0, temp.find(" "));
int index = stoi(temp2); //converts string to int.
int start = input.find("\"") + 1;
int length = input.rfind("\"") - 1 - input.find("\"");
temp = input.substr(start, length);
document.editNode(index - 1, temp);
}
else if (temp.compare("print") == 0)
{
document.printList();
}
else if (temp.compare("search") == 0)
{
int start = input.find("\"") + 1;
int length = input.rfind("\"") - 1 - input.find("\"");
temp = input.substr(start, length);
document.search(temp);
}
else if (temp.compare("delete") == 0)
{
temp = input.substr(input.find(" ") + 1);
int index = stoi(temp); //converts string to int.
document.deleteNode(index - 1);
}
else if (temp.compare("quit") == 0)
{
t = false;
}
else
std::cout << "Invalid command.\n\n";
}
}
|
d979498bc80a019ff3d02ef54866e9044a195aaf
|
076fea580fcdd2bdf815fc901a3874ce412073fb
|
/src/core/interfaces/IEngine.h
|
ba540e564e9e698eb360655c0a2aed4a9f08ec31
|
[
"MIT"
] |
permissive
|
varunamachi/tanyatu
|
b67fb7340f37aac8c64cb43ef537edae2dfc9296
|
ce055e0fb0b688054fe19ef39b09a6ca655e2457
|
refs/heads/master
| 2021-01-10T19:39:17.131012
| 2017-03-08T01:14:29
| 2017-03-08T01:14:29
| 28,555,687
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,132
|
h
|
IEngine.h
|
/*******************************************************************************
* Copyright (c) 2014 Varuna L Amachi. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
#pragma once
#include <QObject>
#include <QSet>
#include <QStringList>
#include "../data/MediaItem.h"
#include "../TanyatuCoreGlobal.h"
namespace Tanyatu
{
/**
* \class IEngine serves as the base class for all the media engines
* responsible for playback of media content. AudioEngines and VideoEngines
* inherit from this class
*/
class TANYATU_CORE_EXPORT IEngine : public QObject
{
Q_OBJECT
public:
enum class Type
{
Audio,
Video
};
enum class State
{
Playing,
Loading,
Buffering,
Paused,
Stopped,
Error,
Unknown
};
/**
* Gives the type/identity of the engine
*/
virtual Type type() const = 0;
/**
* Gives the short description about the engine.
* \returns short description of the engine
*/
virtual QString engineDesc() const = 0;
/**
* Gives the total duration of the currently loaded item in milliseconds
* \returns total time of the current item.
*/
virtual qint64 currentItemTotalTime() const = 0;
/**
* Gives the remaining time of the playback of current item.
* \returns remaining play back time for current item
*/
virtual qint64 currentItemRemainingTime() const = 0;
/**
* Tells whether the current item that is being played is seekable or not
* \returns true if the current item is seekable
*/
virtual bool isCurrentSeekable() const = 0;
/**
* Gives the file extentions of files of supported audio formats.
* \returns set of file extentions of supported file types
*/
virtual QStringList supportedFileExtentions() = 0;
/**
* @brief state Returns the state of the engine
* @return state of the engine
*/
virtual State state() = 0;
virtual int volume() = 0;
virtual Data::MediaItem* currentItem() = 0;
/**
* Normal QObject constructor
*/
explicit IEngine(QObject *parent = 0) :
QObject(parent) {
}
virtual ~IEngine()
{
}
signals:
/**
* @brief sourceChanged Emitted when a media source is set as current source
* @param item Item which is set.
*/
void sourceChanged( Tanyatu::Data::MediaItem *item );
/**
* Signals the start of playback
* \param pointer to the item for which the signal is emitted.
*/
void playStarted( Tanyatu::Data::MediaItem *item );
/**
* Signals the pause action for the engine
* \param item [out] pointer to the item for which the signal is emitted.
*/
void paused( Tanyatu::Data::MediaItem *item );
/**
* Signals the end / manual stop of playback
* \param [out] the media item whose playback has been stopped
*/
void stopped( Tanyatu::Data::MediaItem *item );
/**
* This signal is emitted just before the track finishes playing
* \param [out] item which is going to finish soon
*/
void aboutToFinish( Tanyatu::Data::MediaItem *item);
/**
* signals a time tick idealy 1ms
* \param [out] time tick in milli seconds
*/
void tick( qint64 tick );
/**
* Notifies the change in volume of the player
* \param [out] newValue value to after change
*/
void volumeChanged( int newValue );
/** Notifies change in the mute state
* \param [out] newValue value after change
*/
void muteStateChanged( bool newValue );
/**
* In case of error this signal is fired with the error message
* \param [out] error message
*/
void error( QString message );
/**
* Notifies when the current position in the media playback is changed
* \param value [out] the new time corresponding to new position in milli
* seconds
*/
void positionSeeked( quint64 newMs );
/**
* Signals the change of player/engine state
* \param newState the new state of the engine
* \param oldState the old state of the engine
*/
void stateChanged( Tanyatu::IEngine::State newState,
Tanyatu::IEngine::State oldState);
/**
* signals the playback finish of the item
* \param item which has finished playback
*/
void finished( Tanyatu::Data::MediaItem *item );
public slots:
/**
* Sets the source for the engine. Playback may be delayed for short time
* till the player loads the item
* \param media item for playing
*/
virtual void setSource( Tanyatu::Data::MediaItem *item ) = 0;
/**
* Pauses the playback
*/
virtual void pause() = 0;
/**
* Initiate the play action. Actual playback can be delayed based on the
* engine state.
*/
virtual void play() = 0;
/**
* Stops playback
*/
virtual void stop() = 0;
/**
* Sets the current time in the playback
*/
virtual void seek( qint64 millis ) = 0;
/**
* sets the volume for the player
* \param value value for the volume from 0 to 100 any other value will
* be neglected
*/
virtual void setVolume( int value ) = 0;
/**
* Sets the volume to 0 i.e muts the player.
* \param value if true mutes the volume if not already muted, if false
* unmutes the volume if it is already muted.
*/
virtual void mute( bool value ) = 0;
/**
* @brief clear Stops playback and clears the current playing item
*/
virtual void clear() = 0;
};
}
|
abe8791f9809b158515e74be9f5aaaf15e23d808
|
2dc607eda5957c91cddf2a040eeb2c5ae9db416f
|
/kernel/ddstring.cpp
|
c47c292766067e1e9272ed731bbeba820d3de3c0
|
[
"Apache-2.0"
] |
permissive
|
ddjohn/mordana
|
42c87465077dabb064ce0ec5917cfd1f52ac6be6
|
bb9bdc9406c46933e1e428644dd2a4abc40574c9
|
refs/heads/master
| 2021-07-09T04:49:27.090246
| 2021-03-08T21:14:33
| 2021-03-08T21:14:33
| 230,494,282
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 649
|
cpp
|
ddstring.cpp
|
#include "ddstring.h"
String::String() {
data[0] = '\0';
len = 0;
}
String::String(const char* message) {
for(unsigned int i = 0; i < MAX_STRING_LENGTH + 1; i++) {
data[i] = message[i];
if(message[i] == '\0') {
len = i;
break;
}
}
data[MAX_STRING_LENGTH + 1] != '\0';
}
String::~String() {
}
String& String::operator+(String& other) {
const char* message = other.getChars();
for(unsigned int i = len; i < MAX_STRING_LENGTH + 1; i++) {
data[i] = message[i-len];
if(message[i-len] == '\0') {
len = i;
break;
}
}
data[MAX_STRING_LENGTH + 1] != '\0';
}
const char* String::getChars() {
return data;
}
|
42ef25b1528baa56ec288f3830349277fc0e5752
|
5a63bd6870346aa6593233b990303e743cdb8861
|
/SDK/UI_StopServerDisclaimer_parameters.h
|
d2d0176309ab033341f767f17f784b1422acbe6e
|
[] |
no_license
|
zH4x-SDK/zBlazingSails-SDK
|
dc486c4893a8aa14f760bdeff51cea11ff1838b5
|
5e6d42df14ac57fb934ec0dabbca88d495db46dd
|
refs/heads/main
| 2023-07-10T12:34:06.824910
| 2021-08-27T13:42:23
| 2021-08-27T13:42:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,446
|
h
|
UI_StopServerDisclaimer_parameters.h
|
#pragma once
#include "../SDK.h"
// Name: BS, Version: 1.536.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function UI_StopServerDisclaimer.UI_StopServerDisclaimer_C.BndEvt__AcceptButton_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature
struct UUI_StopServerDisclaimer_C_BndEvt__AcceptButton_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature_Params
{
};
// Function UI_StopServerDisclaimer.UI_StopServerDisclaimer_C.BndEvt__CancelButton_K2Node_ComponentBoundEvent_1_OnButtonClickedEvent__DelegateSignature
struct UUI_StopServerDisclaimer_C_BndEvt__CancelButton_K2Node_ComponentBoundEvent_1_OnButtonClickedEvent__DelegateSignature_Params
{
};
// Function UI_StopServerDisclaimer.UI_StopServerDisclaimer_C.BndEvt__AcceptButton_K2Node_ComponentBoundEvent_2_OnButtonHoverEvent__DelegateSignature
struct UUI_StopServerDisclaimer_C_BndEvt__AcceptButton_K2Node_ComponentBoundEvent_2_OnButtonHoverEvent__DelegateSignature_Params
{
};
// Function UI_StopServerDisclaimer.UI_StopServerDisclaimer_C.BndEvt__AcceptButton_K2Node_ComponentBoundEvent_3_OnButtonHoverEvent__DelegateSignature
struct UUI_StopServerDisclaimer_C_BndEvt__AcceptButton_K2Node_ComponentBoundEvent_3_OnButtonHoverEvent__DelegateSignature_Params
{
};
// Function UI_StopServerDisclaimer.UI_StopServerDisclaimer_C.BndEvt__CancelButton_K2Node_ComponentBoundEvent_4_OnButtonHoverEvent__DelegateSignature
struct UUI_StopServerDisclaimer_C_BndEvt__CancelButton_K2Node_ComponentBoundEvent_4_OnButtonHoverEvent__DelegateSignature_Params
{
};
// Function UI_StopServerDisclaimer.UI_StopServerDisclaimer_C.BndEvt__CancelButton_K2Node_ComponentBoundEvent_5_OnButtonHoverEvent__DelegateSignature
struct UUI_StopServerDisclaimer_C_BndEvt__CancelButton_K2Node_ComponentBoundEvent_5_OnButtonHoverEvent__DelegateSignature_Params
{
};
// Function UI_StopServerDisclaimer.UI_StopServerDisclaimer_C.ExecuteUbergraph_UI_StopServerDisclaimer
struct UUI_StopServerDisclaimer_C_ExecuteUbergraph_UI_StopServerDisclaimer_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
df2d1677a523e348b48df35be518d621f89fc721
|
bfa1718b94d3f991c90509b5d50712f1e1c5388e
|
/src/He3DetectorConstruction.cc
|
700c414ba04bbdd38c44cfa80bf9aaeba276f1af
|
[] |
no_license
|
madantimalsina/G4_He3YBeNsim_UCB
|
4862db3470ee4d3cf84e5b1f890e1cecd9a69eb5
|
60a0e6ccdd1943df5e4ebd314e3c7f3857363aa2
|
refs/heads/main
| 2023-08-12T10:59:48.606681
| 2021-09-29T16:32:38
| 2021-09-29T16:32:38
| 411,417,986
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 39,941
|
cc
|
He3DetectorConstruction.cc
|
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
/// \file He3DetectorConstruction.cc
/// \brief Implementation of the He3DetectorConstruction class
#include "He3DetectorConstruction.hh"
#include "G4Material.hh"
#include "G4RunManager.hh"
#include "G4NistManager.hh"
#include "G4Box.hh"
#include "G4Cons.hh"
#include "G4Polycone.hh"
#include "G4Tubs.hh"
#include "G4Orb.hh"
#include "G4Sphere.hh"
#include "G4Trd.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4SystemOfUnits.hh"
#include "G4PVReplica.hh"
#include "G4GlobalMagFieldMessenger.hh"
#include "G4AutoDelete.hh"
#include "G4GeometryManager.hh"
#include "G4PhysicalVolumeStore.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4SolidStore.hh"
#include "G4VisAttributes.hh"
#include "G4Colour.hh"
#include "G4PhysicalConstants.hh"
#include "G4SystemOfUnits.hh"
#include "G4SubtractionSolid.hh"
#include "G4BooleanSolid.hh"
#include "G4VSolid.hh"
#include "G4RotationMatrix.hh"
#include "G4ThreeVector.hh"
#include "G4Transform3D.hh"
#include "G4AffineTransform.hh"
#include "G4MultiUnion.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4ThreadLocal
G4GlobalMagFieldMessenger* He3DetectorConstruction::fMagFieldMessenger = nullptr;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
He3DetectorConstruction::He3DetectorConstruction()
: G4VUserDetectorConstruction(),
fAbsorberPV(nullptr),
fGapPV(nullptr),
fCheckOverlaps(true)
{
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
He3DetectorConstruction::~He3DetectorConstruction()
{
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4VPhysicalVolume* He3DetectorConstruction::Construct()
{
// Define materials
DefineMaterials();
// Define volumes
return DefineVolumes();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void He3DetectorConstruction::DefineMaterials()
{
// Define materials
G4double A; // atomic mass (mass of a mole)
G4double Z; // atomic number (mean number of protons)
G4double d; // density
G4double fractionMass; // Fraction by Mass (Weight %)
G4double abundance;
// Lead material defined using NIST Manager
auto nistManager = G4NistManager::Instance();
nistManager->FindOrBuildMaterial("G4_Pb");
//nistManager->FindOrBuildMaterial("G4_TEFLON");
nistManager->FindOrBuildMaterial("G4_POLYETHYLENE");
nistManager->FindOrBuildMaterial("G4_POLYPROPYLENE");
nistManager->FindOrBuildMaterial("G4_AIR");
nistManager->FindOrBuildMaterial("G4_Al");
nistManager->FindOrBuildMaterial("G4_W");
//*******************************************************************
//General Material defination
G4Element* elH = new G4Element ("Hydrogen","H",Z = 1.,A = 1.01*g/mole);
G4Element* elBe = new G4Element("Beryllium","Be", Z=4, A=9.1218*g/mole);
G4Element* elC = new G4Element("Carbon","C",Z = 6.,A = 12.011*g/mole);
G4Element* elO = new G4Element("Oxygen","O",Z = 8.,A = 16.00*g/mole);
G4Element* elCr = new G4Element("Chromium","Cr",Z = 24.,A = 52.00*g/mole);
G4Element* elFe = new G4Element("Iron","Fe", Z=26., A = 55.845*g/mole);
G4Element* elNi = new G4Element("Nickel","Ni", Z=28., A = 58.69*g/mole);
G4Element* elW = new G4Element("Tungsten","W", Z=74., A = 183.84*g/mole);
G4Element* elAl = new G4Element("Aluminum","Al", Z = 13.0, A = 26.982*g/mole);
G4Element* elMg = new G4Element("Magnesium","Mg", Z = 12.0, A = 24.305*g/mole);
G4Element* elS = new G4Element("Sulfur","S", Z = 16.0, A = 32.06*g/mole);
//Molybdenum definition
G4Isotope* Mo92 = new G4Isotope("Mo92", 42, 92, 91.906809 * g / mole);
G4Isotope* Mo94 = new G4Isotope("Mo94", 42, 94, 93.9050853 * g / mole);
G4Isotope* Mo95 = new G4Isotope("Mo95", 42, 95, 94.9058411 * g / mole);
G4Isotope* Mo96 = new G4Isotope("Mo96", 42, 96, 95.9046785 * g / mole);
G4Isotope* Mo97 = new G4Isotope("Mo97", 42, 97, 96.9060205 * g / mole);
G4Isotope* Mo98 = new G4Isotope("Mo98", 42, 98, 97.9054073 * g / mole);
G4Isotope* Mo100 = new G4Isotope("Mo100", 42, 100, 99.907477 * g / mole);
G4Element* elMo = new G4Element("Natural Mo", "elMo", 7);
elMo->AddIsotope(Mo92, abundance=14.84*perCent);
elMo->AddIsotope(Mo94, abundance=9.25*perCent);
elMo->AddIsotope(Mo95, abundance=15.92*perCent);
elMo->AddIsotope(Mo96, abundance=16.68*perCent);
elMo->AddIsotope(Mo97, abundance=9.55*perCent);
elMo->AddIsotope(Mo98, abundance=24.13*perCent);
elMo->AddIsotope(Mo100, abundance=9.63*perCent);
//YBe Source Assembly Materials
//MT-185 alloys of Tungsten used to make YBe Pig (LZYBePig)
// Midwest Tungsten Service -> 97.0% (W), 2.1% (Ni), 0.9% (Fe)
// Mi Tech Tungsten Metals -> 97.05% (W), 2.04% (Ni), 0.91% (Fe)
d = 18.52*g/cm3;
G4Material* YBeTungsten_MT185 = new G4Material("Tungsten_MT185",d,3);
YBeTungsten_MT185->AddElement(elW, fractionMass=97.05*perCent);
YBeTungsten_MT185->AddElement(elNi, fractionMass=2.04*perCent);
YBeTungsten_MT185->AddElement(elFe, fractionMass=0.91*perCent);
//YBeTungsten_MT185->AddElement(elW,fractionMass=0.97);
//YBeTungsten_MT185->AddElement(elNi,fractionMass=0.021);
//YBeTungsten_MT185->AddElement(elFe,fractionMass=0.009);
/*
// LZYBeSource (Beryllium metal)
d = 1.85*g/cm3;
G4Material* Beryllium = new G4Material("Beryllium", d, 1);
Beryllium->AddElement(elBe, fractionMass=100.0*perCent);
*/
// Beryllium metal
G4Material* Beryllium = new G4Material("Beryllium", d = 1.85*g/cm3, 7);
Beryllium->AddElement(elBe, fractionMass=99.0892*perCent);
Beryllium->AddElement(elO, fractionMass= 0.6378*perCent);
Beryllium->AddElement(elC, fractionMass= 0.06*perCent);
Beryllium->AddElement(elFe, fractionMass= 0.11*perCent);
Beryllium->AddElement(elAl, fractionMass= 0.05*perCent);
Beryllium->AddElement(elMg, fractionMass= 0.02*perCent);
Beryllium->AddElement(elS, fractionMass= 0.03*perCent);
// LZYBeDisk (Made up of SS-316)
d = 7.99*g/cm3;
G4Material* SS316 = new G4Material("SS316",d,4);
SS316->AddElement(elFe, fractionMass=68.5*perCent);
SS316->AddElement(elCr, fractionMass=17.0*perCent);
SS316->AddElement(elNi, fractionMass=12.0*perCent);
SS316->AddElement(elMo, fractionMass=2.5*perCent);
//************************************************************************
// plexiglass, lucite
d = 1.19*g/cm3;
G4Material* matplexiglass = new G4Material("Plexiglass",d,3);
matplexiglass->AddElement(elH, fractionMass=8.0*perCent);
matplexiglass->AddElement(elC, fractionMass=60.0*perCent);
matplexiglass->AddElement(elO, fractionMass=32.0*perCent);
//*****************************************************************************
// He3 gas for UCB/LBNL He3 tube
//Volume of the He3 tubes
G4double volume_He3 = (8.0*2.54*pi*1.18872*1.18872);
// Build He3 gas
//(From Junsong's email) LND replies
// The gas mix for the LND 252 is 91.2 Torr CO2, 2948.8 Torr He-3.
// Total fill pressure is 3040 Torr
G4int protons=2, neutrons=1, nucleons=protons+neutrons;
G4double elements;
G4double atomicMass_He3 = 3.016*g/mole; //molar mass
G4Isotope* isoHe3 = new G4Isotope("He3", protons, nucleons, atomicMass_He3);
G4Element* elHe3 = new G4Element("Helium3", "He3", 1);
elHe3->AddIsotope(isoHe3, 100*perCent);
G4double pressure_He3 = 2948.8/760.0*atmosphere; // 2948.8 Torr He-3
G4double temperature = 293.15*kelvin;
G4double molar_constant = Avogadro*k_Boltzmann;
//G4double density = (atomicMass*pressure)/(temperature*molar_constant);
// PV = nRT --> PV= (m/M)RT --> P/RT = D/M --> D = MP/RT
G4double density_He3 = (atomicMass_He3*pressure_He3)/(temperature*molar_constant);
G4Material* Helium3 = new G4Material("Helium3", density_He3, elements=1, kStateGas, temperature, pressure_He3);
Helium3->AddElement(elHe3, fractionMass=100*perCent);
// carbon dioxide (Co2) gas in non STP conditions
G4int ncomponents, natoms;
G4double atomicMass_Co2 = 44.01*g/mole; //molar mass (12.01 + 2*16.0)
G4double pressure_Co2 = (91.2/760.0)*atmosphere; //91.2 Torr CO2
G4double temperature_Co2 = 293.15*kelvin;
// PV = nRT --> PV= (m/M)RT --> P/RT = D/M --> D = MP/RT
G4double density_Co2 = (atomicMass_Co2*pressure_Co2)/(temperature_Co2*molar_constant);
G4Material* CO2 = new G4Material("carbon dioxide", density_Co2, ncomponents=2, kStateGas, temperature_Co2, pressure_Co2);
CO2->AddElement(elC, natoms=1);
CO2->AddElement(elO, natoms=2);
// Now mixture He3 + Co2
//Amount of He3 with respect to total = 2948.8/3040*100 = 97.0%
//Amount of Co2 with respect to total = 91.2/3040*100 = 3.0%
//G4double atomicMass_He3Co2 = ((2948.8/3040.0)*3.016 + (91.2/3040.0)*44.01)*g/mole;
G4double atomicMass_He3Co2 = ((0.97*3.016) + (0.03*44.01))*g/mole;
G4double pressure_He3Co2 = (3040.0/760.0)*atmosphere;
G4double density_He3Co2 = (atomicMass_He3Co2*pressure_He3Co2)/(temperature*molar_constant);
G4Material* He3Co2 = new G4Material("He3Co2" , density_He3Co2, 2, kStateGas, temperature, pressure_He3Co2);
He3Co2->AddMaterial( Helium3, (0.97 *3.016) / ((0.97 *3.016) + (0.03* 44.01)) );
He3Co2->AddMaterial( CO2, (0.03* 44.01) / ((0.97 *3.016) + (0.03* 44.01)) );
/*
//Volume of the He3 tubes
G4double volume_He3 = (13*2.54*pi*1.18872*1.18872);
// Build He3 gas
G4int protons=2, neutrons=1, nucleons=protons+neutrons;
G4double elements;
G4double atomicMass_He3 = 3.016*g/mole; //molar mass
G4Isotope* isoHe3 = new G4Isotope("He3", protons, nucleons, atomicMass_He3);
G4Element* elHe3 = new G4Element("Helium3", "He3", 1);
elHe3->AddIsotope(isoHe3, 100*perCent);
G4double pressure_He3 = 11.02*atmosphere;
G4double temperature = 293.15*kelvin;
G4double molar_constant = Avogadro*k_Boltzmann;
//G4double density = (atomicMass*pressure)/(temperature*molar_constant);
G4double density_He3 = (atomicMass_He3*pressure_He3)/(temperature*molar_constant);
G4Material* Helium3 = new G4Material("Helium3", density_He3, elements=1, kStateGas, temperature, pressure_He3);
Helium3->AddElement(elHe3, fractionMass=100*perCent);
// Argon
G4double atomicMass_Ar = 39.948*g/mole;
G4double pressure_Ar = 0.58*atmosphere;
G4double density_Ar = (atomicMass_Ar*pressure_Ar)/(temperature*molar_constant);
G4Element* elAr = new G4Element("Argon", "Ar", Z=18., atomicMass_Ar);
G4Material* Argon = new G4Material("Argon" , density_Ar, 1, kStateGas, temperature, pressure_Ar);
Argon->AddElement(elAr, 1);
// 95% He3 + 4.95% Ar + 0.05% CH4,
G4double atomicMass_He3Ar = ((0.95 *3.016) + (0.05* 39.948))*g/mole;
G4double pressure_He3Ar = 11.60*atmosphere;
G4double density_He3Ar = (atomicMass_He3Ar*pressure_He3Ar)/(temperature*molar_constant);
G4Material* He3Ar = new G4Material("He3Ar" , density_He3Ar, 2, kStateGas, temperature, pressure_He3Ar);
He3Ar->AddMaterial( Helium3, (0.95 *3.016) / ((0.95 *3.016) + (0.05* 39.948)) );
He3Ar->AddMaterial( Argon, (0.05* 39.948) / ((0.95 *3.016) + (0.05* 39.948)) );
*/
// UHMW (Ultra High Molecular Weight Polyethylene)
d = 0.93*g/cm3;
nistManager->BuildMaterialWithNewDensity("UHMWPE","G4_POLYETHYLENE",d);
// UHMW for Thermal Scattering of neutron
// For containt (http://www.apc.univ-paris7.fr/~franco/g4doxy/html/G4NistMaterialBuilder_8cc-source.html)
G4Element *H = new G4Element("TS_H_of_Polyethylene", "H", 1., 1.0079*g/mole);
G4Material *TS_of_Polyethylene = new G4Material("TS_of_Polyethylene", 0.94*g/cm3, 2, kStateSolid, 293.15*kelvin);
TS_of_Polyethylene->AddElement(H, fractionMass=14.3711*perCent);
TS_of_Polyethylene->AddElement(elC, fractionMass=85.6289*perCent);
// POLYPROPYLENE
d = 913.43685*mg/cm3; // Geant4 density: 900.000 mg/cm3
nistManager->BuildMaterialWithNewDensity("POLYPROPYLENE","G4_POLYPROPYLENE",d);
// POLYPROPYLENE for Thermal Scattering of neutron
// For containt (http://www.apc.univ-paris7.fr/~franco/g4doxy/html/G4NistMaterialBuilder_8cc-source.html)
G4Material *TS_of_Polypropylene = new G4Material("TS_of_Polypropylene", 913.43685*mg/cm3, 2, kStateSolid, 293.15*kelvin);
TS_of_Polypropylene->AddElement(H, fractionMass=14.3711*perCent);
TS_of_Polypropylene->AddElement(elC, fractionMass=85.6289*perCent);
G4cout<< G4endl;
G4cout << "**************************************************************************"<< G4endl;
G4cout << "**************************************************************************"<< G4endl;
G4cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<G4endl;
G4cout << "MY CHECK....!!!! " << "pressure_He3 = " << pressure_He3/atmosphere << " atmosphere"<< G4endl;
G4cout << "MY CHECK....!!!! " << "pressure_Co2 = " << pressure_Co2/atmosphere<< " atmosphere" << G4endl;
G4cout << "MY CHECK....!!!! " << "pressure_He3Co2 = " << pressure_He3Co2/atmosphere<< " atmosphere" << G4endl;
G4cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<G4endl;
G4cout << "MY CHECK....!!!! " << "density_He3 = " << density_He3/(mg/cm3)<< " kg/m3" << G4endl;
G4cout << "MY CHECK....!!!! " << "density_Co2 = " << density_Co2/(mg/cm3)<< " kg/m3" << G4endl;
G4cout << "MY CHECK....!!!! " << "density_He3Co2 = " << density_He3Co2/(mg/cm3)<< " kg/m3" << G4endl;
G4cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<G4endl;
G4cout << "MY CHECK....!!!! " << "volume of the tube = " << volume_He3 << " cm3"<< G4endl;
G4cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<G4endl;
G4cout << "MY CHECK....!!!! " << "Mass_He3 = " << (density_He3/(mg/cm3))*volume_He3 << " mg" << G4endl;
G4cout << "MY CHECK....!!!! " << "Mass_Co2 = " << (density_Co2/(mg/cm3))*volume_He3 << " mg"<<G4endl;
G4cout << "MY CHECK....!!!! " << "mass_He3Co2 = " << (density_He3Co2/(mg/cm3))*volume_He3 << " mg"<< G4endl;
G4cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<G4endl;
G4cout << "**************************************************************************"<< G4endl;
G4cout << "**************************************************************************"<< G4endl;
// Print materials
G4cout << *(G4Material::GetMaterialTable()) << G4endl;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4VPhysicalVolume* He3DetectorConstruction::DefineVolumes()
{
// Geometry parameters
G4double startAngle = 0.*deg;
G4double spanningAngle = 360.*deg;
// Outer layer of He3 tube
G4double outerRadius_He3Tubes = 25.4/2*mm;
G4double thickness_AlTube = (0.032*25.4)*mm;
// Parameters: Inner layer of He3
// Tubes filled with He3 gas + ...
G4double outerRadius_He3Gass = outerRadius_He3Tubes - thickness_AlTube;
G4double inerrRadius_He3Gass = 0.*mm;
// This is the effective length (13") of He-3 tubes
// divide by 2 because of to match G4 simulation style (-33.02/2 to +33.02/2)
G4double zHalfHeight_He3Tube = (11.20*2.54)/2*cm;
G4double zHalfHeight_He3Gass = (8.0*2.54)/2*cm;
// Rotation of the Tubes
// (both outer and inner filled with He3 gas)
G4RotationMatrix* rotD1 = new G4RotationMatrix();
G4RotationMatrix* rotD2 = new G4RotationMatrix();
G4RotationMatrix* rotD3 = new G4RotationMatrix();
rotD1->rotateZ(90.*deg);
rotD2->rotateX(90.*deg);
rotD3->rotateY(90.*deg);
//G4double moderatorThickness = 2.5*2.540*cm; // Thickness of moderator (Varies: 1", 2", 2.5", 5" etc)
// (From Junsong email) The round-tube-shape UHMW PE are all 12 inch long.
//I attach the Xometry order for the UHMW PE tubes.
//There is a 1-inch dimaeter, 1 inch long UHMW PE plug on the far side of the He-3 tube.
G4double innerRadius_PE = (1.02/2.0)*25.4*mm; // 1.02" internal diameter
// (UCB measurement for 0.5", 1.0", 1.5", 2.0", 2.5", 3" thickness (radius))
G4double outerRadius_PE = 2.50*25.4*mm; // You change thickness each time here
G4double zHalfHeight_PE = 6.0*25.4*mm;
// 1" PE plug
G4double innerRadius_PE2 = 0.0*mm;
G4double outerRadius_PE2 = 0.5*25.4*mm;
G4double zHalfHeight_PE2 = 0.5*25.4*mm;
//G4double boxSizeX = 30.48*cm; // 12"
G4double boxSizeX = 31.115*cm; // 12.25"
//G4double boxSizeY = 30.48*cm; // 12"
G4double boxSizeXY = 100.0*cm;
auto boxSizeZ = 100.0*cm;
auto worldSizeXY = 5.0 * boxSizeX;
auto worldSizeZ = 5.0 * boxSizeZ;
// Parameters: source holder YBe source
G4double innerRadius_sourceHolder = 0.*cm;
G4double outerRadius_sourceHolder = 10.*cm;
G4double zHalfHeight_YBeSourceHolder = (20./2.)*cm;
G4double outerRadius_YBeSourceHolderCap = (10.52/2.0)*cm;
G4double zHalfHeight_YBeSourceHolderCap = (4./2.)*cm;
//G4double Position_YBeSourceHolder = moderatorThickness/2 + zHalfHeight_YBeSourceHolder; // just add thickness here for table height etc.
// (From Junsong email) The He-3 tube was horizontally orientated, and its center was 4.875" (12.3825*cm) below the bottom of the tungsten.
//The middle of the 12-inch long UHMW PE tube is center to the Tungsten Shielding.
//We keep the He-3 tube positions relative to the tungsten shielding the same in the different scenarios of PE thicknesses.
G4double Position_YBeSourceHolder = 12.3825*cm + zHalfHeight_YBeSourceHolder; // just add thickness here for table height etc.
G4double Position_YBeSourceHolderCap = Position_YBeSourceHolder+ zHalfHeight_YBeSourceHolder + zHalfHeight_YBeSourceHolderCap;
G4double outerRadius_YBeBeO = (2.54/2.)*cm;
//G4double zHalfHeight_YBeBeO = (6.46/2.)*cm; //My old value
G4double zHalfHeight_YBeBeO = (6.858/2.)*cm; // new value from Andy
//Bottom of BeO start at 12.31646 (4.894 in CAd Drawing) cm from base of YBe Pig
//Centre of Be at total 15.74546 (6.199") from bottom of the W pig
G4double Position_YBeBeO = Position_YBeSourceHolder + 2.31646*cm + (6.858/2.)*cm; //Centre of Be at total 15.74546 (6.199") from bottom of the W pig
G4double outerRadius_YDisk = (2.35)*mm;
G4double zHalfHeight_YDisk = (4.6/2.)*mm;
//From CAD drawing distance from bottom of the pig to bottom of Y88 disk 6.349"
G4double Position_YDisk = Position_YBeSourceHolder + 6.12646*cm; //directly from CAD drawing
//G4double Position_YDisk = Position_YBeBeO + 0.635*cm;
// Get materials
auto defaultMaterial = G4Material::GetMaterial("G4_AIR");
//auto absorberMaterial = G4Material::GetMaterial("Helium3");
auto absorberMaterial = G4Material::GetMaterial("He3Co2");
//auto absorberMaterial = G4Material::GetMaterial("He3Ar");
//auto moderatorMaterial = G4Material::GetMaterial("G4_POLYETHYLENE");
//auto moderatorMaterial = G4Material::GetMaterial("UHMWPE");
auto moderatorMaterial = G4Material::GetMaterial("TS_of_Polyethylene");
//auto moderatorMaterial2 = G4Material::GetMaterial("POLYPROPYLENE");
//auto moderatorMaterial2 = G4Material::GetMaterial("TS_of_Polypropylene");
//auto holdMaterial = G4Material::GetMaterial("Plexiglass");
auto moderatorMaterialT = G4Material::GetMaterial("G4_Al");
//auto holdMaterial_Tungsten = G4Material::GetMaterial("G4_W");
auto holdMaterial_Tungsten_MT185 = G4Material::GetMaterial("Tungsten_MT185");
auto BeMaterial = G4Material::GetMaterial("Beryllium");
auto YMaterial = G4Material::GetMaterial("SS316");
if ( ! defaultMaterial || ! absorberMaterial || ! moderatorMaterial ) {
G4ExceptionDescription msg;
msg << "Cannot retrieve materials already defined.";
G4Exception("He3DetectorConstruction::DefineVolumes()",
"MyCode0001", FatalException, msg);
}
// Volume defination:
//
// World
//
auto worldS
= new G4Box("World", // its name
worldSizeXY/2, worldSizeXY/2, worldSizeZ/2); // its size
auto worldLV
= new G4LogicalVolume(
worldS, // its solid
defaultMaterial, // its material
"World"); // its name
auto worldPV
= new G4PVPlacement(
0, // no rotation
G4ThreeVector(), // at (0,0,0)
worldLV, // its logical volume
"World", // its name
0, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
//
// Layer (This is a Box to put every little geometry on it !!!)
//
auto layerS
= new G4Box("Layer", // its name
boxSizeXY/2, boxSizeXY/2, boxSizeZ/2.); // its size
auto layerLV
= new G4LogicalVolume(
layerS, // its solid
defaultMaterial, // its material
"Layer"); // its name
/* new G4PVReplica(
"Layer", // its name
layerLV, // its logical volume
worldLV, // its mother
kZAxis, // axis of replication
1, // number of replica
boxSizeZ); // witdth of replica*/
new G4PVPlacement(
0, // no rotation
G4ThreeVector(), // at (0,0,0)
layerLV, // its logical volume
"Layer", // its name
worldLV, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
//***************************************************************************************************//
//
// Source holder for YBe neutron source
//YBe source Pig Cap
//
G4Tubs* sourceTubeYBeCap =
new G4Tubs("YBeSourceCap", innerRadius_sourceHolder, outerRadius_YBeSourceHolderCap, zHalfHeight_YBeSourceHolderCap, startAngle, spanningAngle);
G4LogicalVolume* YBeCap =
new G4LogicalVolume(sourceTubeYBeCap, //its solid
holdMaterial_Tungsten_MT185, //its material
"YBeSourceCap");
fHoldPV
= new G4PVPlacement(
0, // no rotation
G4ThreeVector(0., 0., -Position_YBeSourceHolderCap), // its position (moderatorThickness/2 + zHalfHeight_YBeSourceHolder)
YBeCap, // its logical volume
"YBeSourceCap", // its name
layerLV, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
//
//YBe Pig
//
G4Tubs* sourceTube =
new G4Tubs("YBeSourcePig", innerRadius_sourceHolder, outerRadius_sourceHolder, zHalfHeight_YBeSourceHolder, startAngle, spanningAngle);
/*
// substracting the voulume if we do not on different logic volume!!!
// outerRadius_YBeBeO+0.3937*mm, 0.7874/2 added because of 1.03 inch of source inner can diameter
// zHalfHeight_YBeBeO+2.63*mm, 5.25/2 added because of 2.75 inch of source inner can height
G4Tubs* sourceTube_BeOVol = new G4Tubs("Source_BeoVol", innerRadius_sourceHolder, outerRadius_YBeBeO+0.3937*mm, zHalfHeight_YBeBeO+2.63*mm, startAngle, spanningAngle);
// substraction of Beo overlap volume from Tungsten Pig
G4VSolid* subtract_BeoVol = new G4SubtractionSolid("SourcePig-Source_BeoVol", sourceTube, sourceTube_BeOVol, 0, G4ThreeVector(0., 0., -5.18*cm));
G4LogicalVolume* YBePig = new G4LogicalVolume(subtract_BeoVol,holdMaterial_Tungsten_MT185,"SourcePig");
G4LogicalVolume* YBePig = new G4LogicalVolume(sourceTube, holdMaterial_Tungsten_MT185,"SourcePig"); */
G4LogicalVolume* YBePig = new G4LogicalVolume(sourceTube,holdMaterial_Tungsten_MT185,"YBeSourcePig");
fHoldPV
= new G4PVPlacement(
0, // no rotation
G4ThreeVector(0., 0., -Position_YBeSourceHolder), // its position (moderatorThickness/2 + zHalfHeight_YBeSourceHolder)
YBePig, // its logical volume
"YBeSourcePig", // its name
layerLV, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
//
// Source BeO
/* // YBe source position is based on the Andy's BACCARAT simulation
// https://luxzeplin.gitlab.io/docs/softwaredocs/simulations/baccarat/event_generator/generators_details/YBe.html
//3.23*cm --> z-offset of the center of the BeO volume relative to the center of the total tungsten volume (main cylinder + cap)
// 5.23*cm --> (3.23 + 2.0)*cm, I added 2.0*cmm because Andy's values based on the (main cylinder + cap)
// which is opposite then I assumed but in both cases base of the Ybe source start at 12 cm from bottom of the YBe Pig
//So distance from the bottom of the tungston pig to center of Beo volume is 12 + 3.23 = 15.23 cm
*/
// New math based on the CAD drawing
//(and also match with Andy new simulation https://gitlab.com/biekerta/photoneutron-safety-sims/-/blob/main/YBe_pig/src/YBeSafeDetectorConstruction.cc)
//Bottom of BeO start at 12.31646 (4.894 in CAd Drawing) cm from base of YBe Pig
// length of Be metal 2.7" --> 6.858 cm
//Centre of Be at total 12.31646 + (6.858/2) = 15.74546 (6.199") from bottom of the W pig
// base of Be start at 12.31646 (4.894 in CAd Drawing) cm from base of YBe Pig
// so z -position for z with respect to ventre of the 20 cm height w pig is 2.31646 cm + 6.858/2 cm (length of Be metal 2.7") = 5.74546
//
G4Tubs* sourceTubeBeO =
new G4Tubs("YBeSource_Be", innerRadius_sourceHolder, outerRadius_YBeBeO, zHalfHeight_YBeBeO, startAngle, spanningAngle);
/*
// substracting the voulume if we do not on different logic volume!!!
G4Tubs* sourceTube_YDiskVol = new G4Tubs("Source_YDiskVol", innerRadius_sourceHolder, outerRadius_YDisk+0.01*mm, zHalfHeight_YDisk+0.04*mm, startAngle, spanningAngle);
// substraction of overlap Y-88 Disk volume from BeO
G4VSolid* subtract_YDiskVol = new G4SubtractionSolid("SourceBeo-Source_YDiskVol", sourceTubeBeO, sourceTube_YDiskVol, 0, G4ThreeVector(0., 0., -1.23357*cm));
G4LogicalVolume* BeVolume = new G4LogicalVolume(subtract_YDiskVol,BeMaterial,"SourceBeo");
*/
G4LogicalVolume* BeVolume = new G4LogicalVolume(sourceTubeBeO,BeMaterial,"YBeSource_Be");
fHoldPV_Beo
= new G4PVPlacement(
0, // no rotation
G4ThreeVector(0., 0., -(5.74546*cm)), // its position (moderatorThickness/2 + zHalfHeight_YBeSourceHolder)
BeVolume, // its logical volume
"YBeSource_Be", // its name
YBePig, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
//
// source YDisk
// New math based on the CAD drawing
//(and also match with Andy new simulation https://gitlab.com/biekerta/photoneutron-safety-sims/-/blob/main/YBe_pig/src/YBeSafeDetectorConstruction.cc)
//Bottom of Be start at 12.31646 (4.894 in CAd Drawing) cm from base of W Pig
//Centre of Be at total 15.74546 (6.199") from bottom of the W pig
// bottom of the Y88 start at 16.12646 cm (6.349") from the bottom of the W pig
// and centre at 16.12646 cm + zHalfHeight_YDisk (4.6 mm/2.) = 16.35646
// so the off set is 16.35646-15.74546 = 0.611 cm (check with Andy code and he has same value)
G4Tubs* sourceTubeYDisk =
new G4Tubs("YBeSource_YDisk", innerRadius_sourceHolder, outerRadius_YDisk, zHalfHeight_YDisk, startAngle, spanningAngle);
G4LogicalVolume* YDisk =
new G4LogicalVolume(sourceTubeYDisk, //its solid
YMaterial, //its material
"YBeSource_YDisk");
fHoldPV_YDisk
= new G4PVPlacement(
0, // no rotation
//G4ThreeVector(0., 0., -(1.23*cm)),
G4ThreeVector(0., 0., (-0.611*cm)),
YDisk, // its logical volume
"YBeSource_YDisk", // its name
BeVolume, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
/*
// if we substract the voulume for the different logic volume!!! here e.g layerLV
fHoldPV
= new G4PVPlacement(
0, // no rotation
G4ThreeVector(0., 0., -(Position_YDisk)), // its position (moderatorThickness/2 + zHalfHeight_YBeSourceHolder)
YDisk, // its logical volume
"SourceYDisk", // its name
layerLV, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps */
//***************************************************************************************************//
// Neutron Moderator
// Here neutron moderator material is UHMWPE (Ultra High Molecular Weight Polyethylene)
//
//G4double innerRadius_PE = 25.6*mm;
//G4double outerRadius_PE = 3*25.4*mm;
//G4double zHalfHeight_PE = 6*25.4*mm;
auto gapS = new G4Tubs("Moderator", innerRadius_PE, outerRadius_PE, zHalfHeight_PE, startAngle, spanningAngle);
//auto gapS = new G4Box("Moderator", boxSizeX/2, boxSizeY/2, moderatorThickness/2);
auto gapLV = new G4LogicalVolume(gapS, moderatorMaterial,"Moderator");
fGapPV
= new G4PVPlacement(
rotD3, // no rotation
G4ThreeVector(0., 0., 0.), // its position
gapLV, // its logical volume
"Moderator", // its name
layerLV, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
// For 1 inch PE cap at far end
auto gapS2 = new G4Tubs("Moderator2", innerRadius_PE2, outerRadius_PE2, zHalfHeight_PE2, startAngle, spanningAngle);
//auto gapS = new G4Box("Moderator", boxSizeX/2, boxSizeY/2, moderatorThickness/2);
auto gapLV2 = new G4LogicalVolume(gapS2, moderatorMaterial,"Moderator2");
fGapPV
= new G4PVPlacement(
rotD3, // no rotation
G4ThreeVector(-5.5*25.4, 0., 0.), // its position
gapLV2, // its logical volume
"PE_Plug_1in", // its name
layerLV, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
//
// For He3 tube outerlayer
// Tube 1 (center tube) outerlayer
// centre tube is off by 0.635cm(0.25")
// Length of the tube (not symmetric)
// 1.6"-1.25" = 0.35" active length extending out of moderator at NEAR END
// 1.6"-0.95" = 0.65" active length extending out of moderator at FAR END
// So the X-center is pushed by the 0.15"
//
//G4double zPosition_He3Tubes = (moderatorThickness/2.) + outerRadius_He3Tubes + 3.6*mm;
//G4double zPosition_He3Gass = (moderatorThickness/2.) + outerRadius_He3Tubes + 3.6*mm;
// Almunium Outer layer
auto gapsT1
= new G4Tubs("AlmuniumOuterLayer_centralTube", outerRadius_He3Gass, outerRadius_He3Tubes, zHalfHeight_He3Tube, startAngle, spanningAngle);
auto gapLVT1
= new G4LogicalVolume(
gapsT1, // its solid
moderatorMaterialT, // its material
"AlmuniumOuterLayer_centralTube"); // its name
fGapPV
= new G4PVPlacement(
rotD3, // no rotation
G4ThreeVector(0.6*25.4, 0., 0.),
//G4ThreeVector((0.15 * 2.54)*cm, 0, zPosition_He3Tubes),
gapLVT1, // its logical volume
"AlmuniumOuterLayer_centralTube", // its name
layerLV, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
//
// Absorber
// Absorber is 95% He3 + 4.95% Ar + 0.05% CH4,
// For He3 gas Tube 1 (Center tube)
// Centre tube is off by 0.635cm (0.25")
// Length of the tube (not symmetric)
// 1.6"-1.25" = 0.35" active length extending out of moderator at NEAR END
// 1.6"-0.95" = 0.65" active length extending out of moderator at FAR END
// So the X-center is pushed by the 0.15"
auto absorberS
= new G4Tubs("Absorber_centralTube", inerrRadius_He3Gass, outerRadius_He3Gass, zHalfHeight_He3Gass, startAngle, spanningAngle);
auto absorberLV
= new G4LogicalVolume(
absorberS, // its solid
absorberMaterial, // its material
"Absorber_centralTube"); // its name
fAbsorberPV
= new G4PVPlacement(
rotD3, // no rotation
G4ThreeVector(0., 0., 0.),
//G4ThreeVector((0.15 * 2.54)*cm, 0, zPosition_He3Gass), // its position Centre tube is off by 0.635cm (0.25")
absorberLV, // its logical volume
"Absorber_centralTube", // its name
layerLV, // its mother volume
false, // no boolean operation
0, // copy number
fCheckOverlaps); // checking overlaps
// print parameters
///////
G4cout<< G4endl;
G4cout << "**************************************************************************"<< G4endl;
G4cout << "**************************************************************************"<< G4endl;
G4cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<G4endl;
G4cout << "MY CHECK....!!!! " << "Gap Thickness (Moderator Radius) = " << outerRadius_PE << " mm"<< G4endl;
G4cout << "MY CHECK....!!!! " << "Position of Y-88 source disk = " << Position_YDisk << " mm"<< G4endl;
G4cout << "MY CHECK....!!!! " << "Position of center of BeO volume = " << Position_YBeBeO << " mm"<< G4endl;
G4cout << "MY CHECK....!!!! " << "Position of YBe Source Holder = " << Position_YBeSourceHolder << " mm"<< G4endl;
G4cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<G4endl;
//G4cout << "MY CHECK....!!!! " << "X-position of all He3 tubes (const. /w M.T.) = " << 0.15*2.54 << " mm "<< G4endl;
//G4cout << "MY CHECK....!!!! " << "Y-position of 2 side He3 tubes (const. /w M.T.) = +/-" << 5.0*25.4 << " mm "<< G4endl;
//G4cout << "MY CHECK....!!!! " << "Y-position of central He3 tube (const. /w M.T.) = " << 0.0*25.4 << " mm "<< G4endl;
//G4cout << "MY CHECK....!!!! " << "Z-position of all He3 tubes (change /w M.T.) = " << zPosition_He3Tubes << " mm "<< G4endl;
//G4cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<G4endl;
G4cout << "**************************************************************************"<< G4endl;
G4cout << "**************************************************************************"<< G4endl;
//
// Visualization attributes
//
G4VisAttributes* blue_clear = new G4VisAttributes(G4Colour(0.0, 0.0, 1.0, 0.4));
G4VisAttributes* aqua_clear = new G4VisAttributes(G4Colour(0.0, 0.5, 1.0, 0.7));
G4VisAttributes* brown_clear = new G4VisAttributes(G4Colour(0.45, 0.25, 0.0, 0.7));
G4VisAttributes* yellow_clear = new G4VisAttributes(G4Colour(1.0, 1.0, 0.0, 0.5));
G4VisAttributes* red_clear = new G4VisAttributes(G4Colour(1.0, 0.0, 0.0, 0.5));
G4VisAttributes* red_clear2 = new G4VisAttributes(G4Colour(1.0, 0.0, 0.0, 0.2));
worldLV->SetVisAttributes (G4VisAttributes::GetInvisible());
layerLV->SetVisAttributes (G4VisAttributes::GetInvisible());
YBePig->SetVisAttributes(brown_clear);
BeVolume->SetVisAttributes(yellow_clear);
YDisk->SetVisAttributes(red_clear2);
YBeCap->SetVisAttributes(brown_clear);
absorberLV->SetVisAttributes(red_clear);
gapLVT1->SetVisAttributes(blue_clear);
gapLV->SetVisAttributes(aqua_clear);
//
// Always return the physical World
//
return worldPV;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void He3DetectorConstruction::ConstructSDandField()
{
// Create global magnetic field messenger.
// Uniform magnetic field is then created automatically if
// the field value is not zero.
G4ThreeVector fieldValue;
fMagFieldMessenger = new G4GlobalMagFieldMessenger(fieldValue);
fMagFieldMessenger->SetVerboseLevel(1);
// Register the field messenger for deleting
G4AutoDelete::Register(fMagFieldMessenger);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
|
d4fd77c257111aaac57d1a46e9390484cb1a7315
|
dbe1d5035800c829b2137ffda2259dee17ea1169
|
/cppcache_server/src/encrypt/include/encrypt_crack.h
|
b3ff163587d6a729e630d4c89f237fa4bac6f9bf
|
[] |
no_license
|
chwangbjtu/urlcracker
|
d6fbf911b6026f705ac926e0a6c5dccc1a211902
|
51d6b99d837db45d831f3a2f10a682d42d36e85a
|
refs/heads/master
| 2021-01-24T10:59:23.587133
| 2016-09-27T09:56:53
| 2016-09-27T09:56:53
| 69,342,847
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 922
|
h
|
encrypt_crack.h
|
#ifndef __ENCRYPT_CRACK_H__
#define __ENCRYPT_CRACK_H__
#include "encrypt_base.h"
namespace ftsps {
//class encryption;
class encrypt_crack : public encrypt_base{
public:
virtual ~encrypt_crack(){}
static encrypt_crack* instance(void);
private:
encrypt_crack();
static encrypt_crack* _instance;
};
//class arithmetic;
class arithmetic_crack1 : public arithmetic_base{
public:
friend class encrypt_crack;
arithmetic_crack1();
virtual ~arithmetic_crack1();
protected:
virtual int decrypt(int k_index, unsigned int random, unsigned char* pkt, int len);
virtual int encrypt(int k_index, unsigned int random, unsigned char* pkt, int len);
private:
inline int xxcrypt(int k_index, unsigned int random, unsigned char* pkt, int len);
};
//class register;
class register_encrypt_crack {
public:
register_encrypt_crack(){encrypt_crack::instance();}
};
};
using namespace ftsps;
#endif//__ENCRYPT_CRACK_H__:~~
|
6745df9c16e49bb34fb4c2f4e3ca413ff3be2e8c
|
de58c954b511189b5b60ce3bd073764ccfd7032d
|
/Práctica 1/TPV2/GameCtrl.h
|
58ad2a2bf1b0de071a3e1b7f16e4fae586cee761
|
[] |
no_license
|
jorgmo02/TPV2
|
6871e1bef77661c9904d8a8636b76c3a53774299
|
e7560074093a14e69d12d953896c88f283a07c75
|
refs/heads/master
| 2022-11-13T21:51:37.707142
| 2020-07-06T16:05:45
| 2020-07-06T16:05:45
| 239,794,279
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 470
|
h
|
GameCtrl.h
|
#pragma once
#include "Component.h"
#include "ScoreManager.h"
#include "Transform.h"
#include "AsteroidPool.h"
#include "Health.h"
class GameCtrl: public Component {
public:
GameCtrl();
GameCtrl(AsteroidPool* a, Health* h, int asteroidsGenerated);
virtual ~GameCtrl();
void init() override;
void update() override;
void draw() override;
private:
int iniLifes_;
int asteroidsGenerated_;
AsteroidPool* pool_;
Health* health_;
ScoreManager *scoreManager_;
};
|
6aff055face02b7b0cd4ea6d15bcb5bb96569fcb
|
3a90df4655a9bfcc01df3fbf0e8ef5081794736c
|
/PRACTICE/stack.cpp
|
9e80aa4ba8ba1308a322a2d3774d541e38752575
|
[
"MIT"
] |
permissive
|
prasantmahato/CP-Practice
|
0442434665603496b3e79741476c0a30855be214
|
54ca79117fcb0e2722bfbd1007b972a3874bef03
|
refs/heads/master
| 2023-01-03T04:41:22.672625
| 2020-10-26T16:52:37
| 2020-10-26T16:52:37
| 300,133,429
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 986
|
cpp
|
stack.cpp
|
#include <iostream>
using namespace std;
#define MAX 1000
class Stack
{
int top;
public:
int arr[MAX];
Stack(){ top=-1; }
bool push(int x);
int pop();
int peek();
bool isEmpty();
};
bool Stack::push(int x)
{
if(top >= (MAX-1))
{
cout<<"\nStack Overflow.";
return false;
}
else
{
arr[++top]=x;
cout<<x<<" pushed in Stack."<<endl;
return true;
}
}
int Stack::pop()
{
if(top<0)
{
cout<<"\nStack Underflow.";
return 0;
}
else
{
int x=arr[top--];
return x;
}
}
int Stack::peek()
{
if(top<0)
{
cout<<"\nStack is Empty.";
return 0;
}
else
{
int x=arr[top];
return x;
}
}
bool Stack::isEmpty()
{
return (top<0);
}
int main()
{
Stack s;
s.push(20);
s.push(2120);
s.push(10);
s.push(20123);
cout<<s.pop()<<"\nPopped from Stack. ";
return 0;
}
|
5617065e1ba6c5f03868a9066a075226d52e3e00
|
1477fb73b101a32d111f0a5a13354ead9fffff33
|
/src/libkmc/calculators/node.h
|
141c8abca3e38c5305748af59bdb4d580b74905c
|
[
"Apache-2.0"
] |
permissive
|
razziel89/kmc
|
f7a4946759cee795792ab8faaef6c6db2b7afcd6
|
22b1d67991a60533266bceffb41057aa70c475bf
|
refs/heads/master
| 2021-01-19T22:05:00.776253
| 2017-01-25T22:22:58
| 2017-01-25T22:22:58
| 88,747,752
| 0
| 0
| null | 2017-04-19T13:21:27
| 2017-04-19T13:21:27
| null |
UTF-8
|
C++
| false
| false
| 2,181
|
h
|
node.h
|
/*
* author: Kordt
*/
#ifndef NODE_H
#define NODE_H
#include <votca/tools/vec.h>
using namespace std;
using namespace votca::kmc;
// KMCMULTIPLE PART //
typedef votca::tools::vec myvec;
struct Event
{
int destination;
double rate;
votca::tools::vec dr;
// stuff for Coulomb interaction
double Jeff2;
double reorg_out;
double initialrate;
};
class Node
{
public:
int id;
int occupied;
int injectable;
double escaperate;
double occupationtime;
myvec position;
vector<Event> event;
// stuff for Coulomb interaction:
double siteenergy;
double reorg_intorig; // UnCnN
double reorg_intdest; // UcNcC
double EscapeRate();
void AddEvent(int seg2, double rate12, myvec dr, double Jeff2, double reorg_out);
void InitEscapeRate();
};
void Node::AddEvent(int seg2, double rate12, myvec dr, double Jeff2, double reorg_out)
{
Event newEvent;
newEvent.destination = seg2;
newEvent.rate = rate12;
newEvent.initialrate = rate12;
newEvent.dr = dr;
newEvent.Jeff2 = Jeff2;
newEvent.reorg_out = reorg_out;
this->event.push_back(newEvent);
}
void Node::InitEscapeRate()
{
double newEscapeRate = 0;
for(unsigned int i=0; i<this->event.size();i++)
{
newEscapeRate += this->event[i].rate;
}
this->escaperate = newEscapeRate;
// cout << "Escape rate for segment " << this->id << " was set to " << newEscapeRate << endl;
}
double Node::EscapeRate()
{
return escaperate;
}
// END KMCMULTIPLE PART //
// KMCSINGLE PART //
/*
struct link_t;
class node_t : public VSSMGroup<link_t> {
public:
node_t(int id)
: _id(id), _occ(0) {}
double _occ;
int _id;
void onExecute() {
_occ+=WaitingTime();
VSSMGroup<link_t>::onExecute();
}
};
node_t *current;
vec r(0,0,0);
struct link_t {
link_t(node_t *dest, double rate, vec r)
: _dest(dest), _rate(rate), _r(r) {}
double Rate() {
return _rate;
}
void onExecute() {
r+=_r;
current = _dest;
}
double _rate;
node_t *_dest;
vec _r;
};
// END KMCSINGLE PART //
*/
#endif /* NODE_H */
|
c2a4e53cba45f7d1cf160526959bf45a0eab7c0e
|
f0306eb78280dbf5de894c247a2545738298ce39
|
/PatriciaTrie/Patricia.cpp
|
537e33ca6ea2971dda743ca65de33c13c84f5b05
|
[] |
no_license
|
trol53/DA
|
18d086a2cd72a757e891d48538bf2f86b41bcd92
|
f6909374ded5ff0a89b3a5c9d55eeff75f6ae892
|
refs/heads/master
| 2021-04-02T23:53:09.921672
| 2020-12-04T09:29:32
| 2020-12-04T09:29:32
| 248,337,802
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,294
|
cpp
|
Patricia.cpp
|
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <fstream>
const int MAX_SIZE = 257;
using namespace std;
void ToLower(char *str){
int size = strlen(str);
for (int i = 0; i < size; i++){
char tmp = str[i];
str[i] = (char)tolower(tmp);
}
}
bool CompareChar (char *s1, char *s2){
int size1 = strlen(s1);
int size2 = strlen(s2);
if (size1 != size2)
return false;
for (int i = 0; i < size1; i++){
if (s1[i] != s2[i])
return false;
}
return true;
}
struct TNode {
char *key;
unsigned long long value;
int bit;
TNode *left;
TNode *right;
int index;
int size;
int str_size;
};
TNode* CreateNode (char *keys, unsigned long long values){
TNode *tmp = new TNode();
int length = strlen(keys);
tmp->key = new char[length + 1];
int i;
ToLower(keys);
for (i = 0; i < length; i++){
tmp->key[i] = keys[i];
}
tmp->key[i] = '\0';
tmp->value = values;
tmp->bit = 0;
tmp->left = nullptr;
tmp->right = nullptr;
tmp->size = 1;
tmp->index = 0;
tmp->str_size = length;
return tmp;
}
bool Digit (char *s, int bit, int size){
int index = bit / 8;
if (size <= index){
return false;
}
char temp = s[index];
return (temp >> (7 - bit % 8)) & 1;
}
int DifferentBit (char *s1, char *s2){
int i;
int size1 = strlen(s1);
int size2 = strlen(s2);
for (i = 0; Digit(s1,i,size1) == Digit(s2, i, size2); i++);
return i;
}
TNode * Find(TNode *&root, char *key, int pred_bit){
if (root->bit <= pred_bit){
return root;
}
int size = strlen(key);
if (Digit(key, root->bit, size)){
return Find (root->right, key, root->bit);
} else {
return Find (root->left, key, root->bit);
}
}
TNode* InsertR (TNode *&root, char *keys, unsigned long long values, int bits, int pred_bit){
if (root->bit >= bits || root->bit <= pred_bit){
TNode *tmp = CreateNode(keys, values);
tmp->bit = bits;
if (Digit(tmp->key, bits, tmp->str_size)){
tmp->left = root;
tmp->right = tmp;
} else {
tmp->left = tmp;
tmp->right = root;
}
return tmp;
}
if (Digit(keys, root->bit, strlen(keys))){
root->right = InsertR(root->right, keys, values, bits, root->bit);
} else {
root->left = InsertR(root->left, keys, values, bits, root->bit);
}
return root;
}
TNode* Insert (TNode *root, char *keys, unsigned long long values){
if (root == nullptr){
root = CreateNode(keys, values);
root->left = root;
cout << "OK\n";
return root;
}
ToLower(keys);
TNode *tmp = Find(root->left, keys, 0);
if (CompareChar(keys, tmp->key)){
cout << "Exist\n";
return root;
}
root->left = InsertR(root->left, keys, values, DifferentBit(keys, tmp->key), 0);
root->size++;
cout << "OK\n";
return root;
}
TNode* Parent (TNode *root, TNode *search, char &flag){
TNode *prev = root;
TNode *now = root->left;
flag = 'l';
while (now != search){
if (Digit(search->key, now->bit, search->str_size)){
prev = now;
now = now->right;
flag = 'r';
} else {
prev = now;
now = now->left;
flag = 'l';
}
}
return prev;
}
TNode* CicleNode (TNode *root, TNode *search, char &flag, int pred_bit, TNode *pred){
if (root->bit <= pred_bit){
return pred;
}
if (Digit(search->key, root->bit, search->str_size)){
flag = 'r';
return CicleNode (root->right, search, flag, root->bit, root);
} else {
flag = 'l';
return CicleNode (root->left, search, flag, root->bit, root);
}
}
void Delete(TNode *&root, char *keys){
if (root == nullptr){
cout << "NoSuchWord\n";
return;
}
TNode *delete_node = Find (root->left, keys, 0);
if (!CompareChar(delete_node->key, keys)){
cout << "NoSuchWord\n";
return;
}
if (root->bit == root->left->bit){
delete[] root->key;
delete root;
root = nullptr;
cout << "OK\n";
return;
}
char flag_p, flag_c1, flag_c2;
if (delete_node->bit != root->bit){
if (delete_node->bit == delete_node->left->bit){
TNode *p = Parent(root, delete_node, flag_p);
if (flag_p == 'l'){
p->left = delete_node->right;
delete_node->left = nullptr;
delete[] delete_node->key;
delete delete_node;
delete_node = nullptr;
cout << "OK\n";
root->size--;
return;
} else {
p->right = delete_node->right;
delete_node->left = nullptr;
delete[] delete_node->key;
delete delete_node;
delete_node = nullptr;
cout << "OK\n";
root->size--;
return;
}
}
if (delete_node->bit == delete_node->right->bit){
TNode *p = Parent(root, delete_node, flag_p);
if (flag_p == 'l'){
p->left = delete_node->left;
delete_node->right = nullptr;
delete[] delete_node->key;
delete delete_node;
delete_node = nullptr;
cout << "OK\n";
root->size--;
return;
} else {
p->right = delete_node->left;
delete_node->right = nullptr;
delete[] delete_node->key;
delete delete_node;
delete_node = nullptr;
cout << "OK\n";
root->size--;
return;
}
}
}
TNode *swap_node = CicleNode(root->left, delete_node, flag_c1, 0, root);
delete[] delete_node->key;
delete_node->str_size = swap_node->str_size;
int i;
delete_node->key = new char[delete_node->str_size + 1];
for (i = 0; i < delete_node->str_size; i++){
delete_node->key[i] = swap_node->key[i];
}
delete_node->key[i] = '\0';
delete_node->value = swap_node->value;
TNode *p = Parent(root, swap_node, flag_p);
TNode *swap_cicle = CicleNode(root->left, swap_node, flag_c2, 0, root);
if (flag_c2 == 'l'){
if (flag_c1 == 'l'){
swap_cicle->left = swap_node->left;
} else {
swap_cicle->left = swap_node->right;
}
} else {
if (flag_c1 == 'l'){
swap_cicle->right = swap_node->left;
} else {
swap_cicle->right = swap_node->right;
}
}
if (flag_p == 'l'){
if (flag_c1 == 'l'){
p->left = swap_node->right;
} else {
p->left = swap_node->left;
}
} else {
if (flag_c1 == 'l'){
p->right = swap_node->right;
} else {
p->right = swap_node->left;
}
}
delete[] swap_node->key;
delete swap_node;
swap_node = nullptr;
cout << "OK\n";
root->size--;
return;
}
void Read (TNode *&tree, char *read){
unsigned long long val;
cin >> read >> val;
tree = Insert(tree, read, val);
return;
}
void Remove (TNode *&root, char *read){
cin >> read;
ToLower(read);
Delete(root, read);
return;
}
void Search (TNode *root, char *read){
if (root == nullptr){
cout << "NoSuchWord\n";
return;
}
ToLower(read);
TNode *f = Find(root->left, read, 0);
if (CompareChar(f->key, read)){
cout << "OK: " << f->value << '\n';
} else {
cout << "NoSuchWord\n";
}
return;
}
void DelTree (TNode *&node){
if (node == nullptr)
return;
if (node->bit == 0){
delete[] node->key;
delete node;
node = nullptr;
return;
}
if (node->right->bit > node->bit) {
DelTree(node->right);
}
if (node->left->bit > node->bit) {
DelTree(node->left);
}
delete[] node->key;
delete node;
node = nullptr;
}
void SetIndex (TNode *&tree, int &ind){
if (tree->bit == 0){
tree->index = ind;
return;
}
tree->index = ind;
ind++;
if (tree->left->bit > tree->bit){
SetIndex(tree->left, ind);
}
if (tree->right->bit > tree->bit){
SetIndex(tree->right, ind);
}
}
void SaveR (TNode *node, ofstream &file){
file << node->key << ' ' << node->value << ' ' << node->bit << ' ' << node->index << ' ';
if (node->left->bit > node->bit){
file << -1 << ' ';
} else {
file << node->left->index << ' ';
}
if (node->right->bit > node->bit){
file << -1;
} else {
file << node->right->index;
}
file << '\n';
if (node->left->bit > node->bit){
SaveR(node->left, file);
}
if (node->right->bit > node->bit){
SaveR(node->right, file);
}
}
void Save (TNode *tree, ofstream &file){
if (tree == nullptr){
file << "Header" << '\0' << ' ' << 0 << '\n';
return;
}
file << "Header" << '\0' << ' ' << tree->size << '\n';
if (tree->left->bit <= tree->bit){
file << tree->key << ' ' << tree->value << ' ' << tree->bit << ' ' << tree->index << ' ' << 0 << '\n';
} else {
file << tree->key << ' ' << tree->value << ' ' << tree->bit << ' ' << tree->index << ' ' << -1 << '\n';
int ind = 1;
SetIndex(tree->left, ind);
SaveR (tree->left, file);
}
}
TNode* Load (TNode **mass, ifstream &file, char *read){
unsigned long long val;
int bits, indexs, checkl, checkr;
file >> read >> val >> bits >> indexs >> checkl >> checkr;
mass[indexs] = CreateNode(read, val);
mass[indexs]->bit = bits;
mass[indexs]->index = indexs;
if (checkl == -1){
mass[indexs]->left = Load(mass, file, read);
} else {
mass[indexs]->left = mass[checkl];
}
if (checkr == -1){
mass[indexs]->right = Load(mass, file, read);
} else {
mass[indexs]->right = mass[checkr];
}
return mass[indexs];
}
void SaveLoad (TNode *&tree, char *read){
cin >> read;
if (read[0] == 'S'){
cin >> read;
ofstream file;
file.open(read, ios::binary);
if (!file.is_open()) {
cout << "ERROR: error create file\n";
return;
}
Save(tree, file);
file.close();
cout << "OK\n";
} else{
cin >> read;
ifstream file;
file.open(read, ios::binary);
if (!file.is_open()) {
cout << "ERROR: error create file\n";
return;
}
file >> read;
char check[] = {'H', 'e', 'a', 'd', 'e', 'r', '\0'};
if (!CompareChar(read, check)){
cout << "ERROR: wrong file\n";
file.close();
return;
}
if (tree != nullptr){
if (tree->left->bit != tree->bit){
DelTree(tree->left);
delete[] tree->key;
delete tree;
tree = nullptr;
} else {
delete[] tree->key;
delete tree;
tree = nullptr;
}
}
int size;
file >> size;
if (size == 0){
cout << "OK\n";
return;
}
TNode **mass = (TNode **)malloc(size * sizeof(TNode *));
unsigned long long val;
int bits, indexs, checkl;
file >> read >> val >> bits >> indexs >> checkl;
mass[0] = CreateNode(read, val);
mass[0]->bit = bits;
mass[0]->index = indexs;
if (checkl == 0){
mass[0]->left = mass[0];
tree = mass[0];
free(mass);
file.close();
return;
}
mass[0]->left = Load (mass, file, read);
tree = mass[0];
free(mass);
file.close();
cout << "OK\n";
}
}
void Show(TNode *node, int i) {
if (node == nullptr)
return;
if (node->bit == 0){
return;
}
if (node->right->bit > node->bit) {
Show(node->right, i + 1);
}
for (int j = 0; j < i*6; ++j) {
cout << ' ';
}
cout << node->key << " " << node->index << " ";
std::cout << '\n';
if (node->left->bit > node->bit) {
Show(node->left, i + 1);
}
}
int main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
TNode *tree = nullptr;
char read[MAX_SIZE];
while (cin >> read){
switch (read[0])
{
case '+':
Read(tree, read);
break;
case '-':
Remove(tree, read);
break;
case '!':
SaveLoad(tree, read);
break;
default:
Search(tree, read);
break;
}
}
if (tree == nullptr){
return 0;
}
if (tree->left->bit != tree->bit){
DelTree(tree->left);
delete[] tree->key;
delete tree;
} else {
delete[] tree->key;
delete tree;
}
}
|
b8e14552c704683643e1aee506c999782b8f995d
|
0a699f115a1e4d3045ed3da528d088b30b6f5b1b
|
/serial_lcd_write.ino
|
ebe759b7a486c1760d7078c1f33858591c9d0704
|
[
"MIT"
] |
permissive
|
ckuzma/arduino-weather-lcd-shield
|
0aa5b39f6c49a5aa5dfe0713fcd2bfd9d3261f09
|
3a2986f503e5d6ad11f4bae2c40a37172d38c88a
|
refs/heads/master
| 2020-05-20T06:03:07.751075
| 2016-02-14T21:35:44
| 2016-02-14T21:35:44
| 51,715,225
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 720
|
ino
|
serial_lcd_write.ino
|
#include <Wire.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
Serial.begin(9600);
}
void loop() {
String content = "";
char character;
while(Serial.available()) {
delay(10);
character = Serial.read();
content.concat(character);
}
if(content != "") {
Serial.println(content);
// Clear out the LCD...
lcd.setCursor(0, 0);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(" ");
// Print the stuff!
lcd.setCursor(0, 0);
lcd.print(content.substring(0,16));
lcd.setCursor(0, 1);
lcd.print(content.substring(16));
}
}
|
61ebb8fecb7b8cbb40ea3ee29166dc3c9cd07f1e
|
293af45d1722f0b059028f8d06f2a3151c3858bd
|
/DevilTitan-LIBPRO-64/DataProcessingTechnician.h
|
d759c1e97854ad6a4eb761c2bb2087360ca093bc
|
[] |
no_license
|
DevilTitan/DevilTitan-LIBPRO
|
912c24b6d242e7c8076d7aabee5bc4aa28ab8fff
|
1cb5562faab818973ebaced588abc07707b91e08
|
refs/heads/master
| 2020-12-30T16:28:19.449946
| 2017-06-23T04:44:03
| 2017-06-23T04:44:03
| 90,991,599
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,602
|
h
|
DataProcessingTechnician.h
|
#pragma once
#include <QWidget>
#include "ui_DataProcessingTechnician.h"
#include "user.h"
#include "global.h"
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QDebug>
#include "QSqlError"
#include <QSqlQueryModel>
#include "switchrole.h"
#include "loginform.h"
#include "changepassword.h"
#include "changetheme.h"
#include "notification.h"
#include <QTime>
#include <QDateTime>
class DataProcessingTechnician : public QWidget
{
Q_OBJECT
public:
DataProcessingTechnician(QWidget *parent = Q_NULLPTR,User * curUser = NULL);
~DataProcessingTechnician();
void displaybook();
void clear();
void displayNotify();
void updateTime();
private slots:
void on_waitTable_clicked(const QModelIndex &index);
void on_bookTable_clicked(const QModelIndex &index);
void on_isbnsearch_textChanged(const QString &arg1);
void on_booknamesearch_textChanged(const QString &arg1);
void on_requestTable_clicked(const QModelIndex &index);
void on_insertButton_2_clicked();
void on_isbn_editingFinished();
void on_searchButton_clicked();
void on_insertButton_clicked();
void on_searchButton_3_clicked();
void on_book_name_textChanged(const QString &arg1);
void on_username_textChanged(const QString &arg1);
void on_logout_clicked();
void on_publicChat_3_clicked();
void on_theme_clicked();
void on_publicChat_6_clicked();
void on_publicChat_2_clicked();
private:
Ui::DataProcessingTechnician ui;
QString curISBN;
int curidx;
User* curUser;
QTimer *count;
QTime now;
QDateTime date;
};
|
b8aa67d73f915f0e6f60877bfefa47b114d9eb31
|
e27ba04dcd5a60cd74ff8ba27db5edabd2810687
|
/library_rsa/Source.cpp
|
5ac43ad20c8da668e7a584352624891674f0c84a
|
[] |
no_license
|
pavelllm/RSALibrary
|
62b13c04ef182662c58e9d0c5a8cd2e606aff828
|
5242bbf135d0c75d7f5684d60cb4a590d6c0998f
|
refs/heads/master
| 2021-07-10T17:27:24.584827
| 2017-10-10T18:47:37
| 2017-10-10T18:47:37
| 105,371,441
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,103
|
cpp
|
Source.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Library.h"
//Подпрограмма сложеие двух длинных чисел
//a и b - слагаемые размером size слов
//с - сумма размером size слов
//возвращаемое значение - бит переноса
unsigned short add(unsigned short * a, unsigned short * b, unsigned short size, unsigned short * c)
{
//бит переноса старшего разряда при сложении
unsigned short d = 0;
//промежутчный результат сложения слов
unsigned int T;
for (int i = 0; i < size; ++i)
{
T = unsigned int(a[i]) + unsigned int(b[i]) + unsigned int(d);
c[i] = LOWORD(T);
d = HIWORD(T);
}
c[size] = d;
return d;
}
//Подпрограмма вычитания двух длинных беззнаковых чисел
// a, b - числа, разность которых нужно посчитать, длинной size слов
//c - разность a и b размером size слов
//возвращаемое значение - бит переноса
unsigned short sub(unsigned short * a, unsigned short * b, unsigned short size, unsigned short * c)
{
//бит переноса разряда при вычитании
unsigned short d = 0;
//промежуточный результат вычитания слов
unsigned int T;
for (int i = 0; i< size; ++i)
{
T = (unsigned int)(a[i]) - (unsigned int)(b[i]) - (unsigned int)(d);
c[i] = LOWORD(T);
d = (HIWORD(T) == 0) ? 0 : 1;
}
c[size] = d;
return d;
}
//Подпрограмма сравнения двух длинных беззнаковых чисел
// a, b - сравниваемые числа длинной size слов
//возвращаемые значения:
//0: a == b
//1: a > b
//-1: b > a
int cmp(unsigned short * a, unsigned short * b, unsigned short size)
{
for (int i = size - 1; i >= 0; --i)
{
//a > b
if (a[i] > b[i]) return 1;
//a < b
if (a[i] < b[i]) return -1;
}
return 0;
}
//Подпрограмма генерации случайного длинного беззнакового числа
//a - массив для записи числа размером size слов
unsigned short * generate(unsigned short * a, unsigned short size)
{
for (int i = 0; i < size; i++)
{
//8 бит + 8 бит = 16 бит => профит, иначе
//(a[i] == rand()) <= (RAND_MAX == 32767)
a[i] = MAKEWORD(LOBYTE(rand()), LOBYTE(rand()));
}
return a;
}
//Подпрограмма вывода длинного беззнакового числа в шестандцатиричном формате (начиная со старших разрядов)
//а - число размером size слов
void print_result(unsigned short * a, unsigned short size)
{
for (int i = size - 1; i >= 0; --i)
{
printf("%04x", a[i]);
}
printf("\n");
}
//Подпрограмма обнуления длинного беззнакового числа number размером size_number
void zeroing(unsigned short * number, unsigned short size_number)
{
for (int i = 0; i < size_number; ++i) number[i] = 0;
}
//Подпрограмма присвоения одного длинного числа другому
void assign(unsigned short * a, unsigned short * b, unsigned short size)
{
for (int i = 0; i < size; ++i)
{
a[i] = b[i];
}
}
//Подпрограмма умножения двух длинных беззнаковых чисел
//a, b - умножаемые числа длинной size_a и size_b слов соответственно
//c - произведение a и b, размером size_a + size_b слов
unsigned short * mul(unsigned short * a, unsigned short size_a, unsigned short * b, unsigned short size_b, unsigned short * c)
{
unsigned short d = 0, size_c;
unsigned long T;
size_c = size_a + size_b;
zeroing(c, size_c);
for (unsigned long i = 0; i < size_a; i++)
{
for (unsigned long j = 0; j < size_b; j++)
{
T = (unsigned long)c[i + j] + (unsigned long)a[i] * (unsigned long)b[j] + (unsigned long)d;
c[i + j] = LOWORD(T);
d = HIWORD(T);
}
c[i + size_b] = d;
}
return c;
}
//Подпрограмма умножения длинного беззнакового числа на слово
//a - умножаемое число длинной size слов
//b - множитель длинной в 1 слово
//c - произведение a и b, размером size слов
//возвращаемое значение - слово переноса
unsigned short mul_word(unsigned short * a, unsigned short size_a, unsigned short b, unsigned short * c)
{
unsigned long T;
unsigned short d = 0;
for (int i = 0; i < size_a; i++)
{
T = (unsigned long)a[i] * (unsigned long)b + (unsigned long)d;
c[i] = LOWORD(T);
d = HIWORD(T);
}
return d;
}
//Подпрограмма деления длинного беззнакового числа на слово
//a - делимое число длинной size слов
//b - делитель длинной в 1 слово
//c [Nullable] - частное a и b, размером size слов
//r [Nullable] - остаток от деления a на b, размером 1 слово
//возвращаемое значение - остаток от деления
unsigned short div_word(unsigned short * a, unsigned short size, unsigned short b, unsigned short * c, unsigned short * r)
{
unsigned long T = 0;
if (b == 0) exit(0);
for (int i = size; i > 0; i--)
{
T <<= sizeof(unsigned short) * 8;
T |= a[i - 1];
if (c != NULL) c[i - 1] = LOWORD(T / (unsigned long)b);
T %= b;
}
if (r != NULL) *r = LOWORD(T);
return LOWORD(T);
}
//Подпрограмма деления двух длинных беззнаковых чисел
// U - делимое, размером sizeU слов
// V - делитель, размером sizeV слов
// Q [Nullable] - частное, размером sizeU слов
// R [Nullable] - остаток, размером sizeV слов
void div(unsigned short * U, unsigned short * V, unsigned short * Q, unsigned short * const R, unsigned short sizeU, unsigned short sizeV)
{
unsigned short q, buf1, buf2;
unsigned short U2[33], V2[33], R2[33];
unsigned long inter;
int i, j, k;
unsigned short d;
//Проверки, подготовка
if (R != NULL) zeroing(R, sizeV);
if (Q != NULL) zeroing(Q, sizeU);
for (i = sizeV; (i > 0)&(!V[i - 1]); i--);
sizeV = i;
if (sizeV == 0) return; // исключение "Деление на ноль" (просто уходим)
for (k = sizeU; (k > 0)&(!U[k - 1]); k--);
sizeU = k;
if (sizeV > sizeU)
{
if (R != NULL) assign(R, U, sizeU);
return;
}
if (sizeV == 1)
{
div_word(U, sizeU, V[0], Q, R);
return;
}
//Нормализация
d = (unsigned short)(((unsigned long)65535 + 1) / ((unsigned long)V[sizeV - 1] + 1));
if (d != 1)
{
V2[sizeV] = mul_word(V, sizeV, d, V2);
U2[sizeU] = mul_word(U, sizeU, d, U2);
}
else
{
assign(V2, V, sizeV);
V2[sizeV] = 0;
assign(U2, U, sizeU);
U2[sizeU] = 0;
}
//Основной цикл
for (j = sizeU; j >= sizeV; j--)
{
//Очередное слово частного
inter = MAKEDWORD(U2[j], U2[j - 1]);
if (U2[j] == V2[sizeV - 1])
q = 65535;
else {
q = (unsigned short)(inter / V2[sizeV - 1]);//j-е слово частного q находим делением
//Коррекция слова частного
if (((unsigned long)V2[sizeV - 2] * q) > (MAKEDWORD((unsigned short)(inter%V2[sizeV - 1]), U2[j - 2])))
{
q--; //коррекция слова частного уменьшением q на 1
}
}
//Вычитание кратного делителя
buf1 = mul_word(V2, sizeV, q, R2);
buf2 = sub(U2 + j - sizeV, R2, sizeV, U2 + j - sizeV);
inter = (unsigned long)U2[j] - buf1 - buf2;
//Коррекция остатка и частного
if (HIWORD(inter))
{
add(U2 + j - sizeV, V2, sizeV, U2 + j - sizeV);
q--;
}
if (Q != NULL)
Q[j - sizeV] = q;
}
//Завершение
if (R != NULL)
{
div_word(U2, sizeV, d, R, NULL);
}
}
//Подпрограмма вычисления произведения двух длинных беззнаковых чисел по модулю длинного беззнакового числа
//a - первый сомножитель размером size слов
//b - второй сомножитель размером size слов
//n - модуль размером size слов
//c - a * b mod n размеров size слов
void mod_mul(unsigned short * a, unsigned short * b, unsigned short * n, unsigned short * c, unsigned long size)
{
unsigned short d[32 * 2];
mul(a, size, b, size, d);
div(d, n, NULL, c, 2 * size, size);
}
//Подпрограмма возведения длинного беззнакового числа в степень длинного беззнакового числа по модулю длинного беззнакового числа
//a - основание размером size_a слов
//b - показатель размером size_b слов
//n - модуль размером size_a слов
//c - a ^ b mod n размеров size_a слов
void mod_pow(unsigned short * a, unsigned long size_a, unsigned short * b, unsigned long size_b, unsigned short * n, unsigned short * c)
{
zeroing(c, size_a);
c[0] = 1;
for (int i = 16 * size_b; i > 0; i--)
{
mod_mul(c, c, n, c, size_a);
if ((b[(i - 1) / 16] >> ((i - 1) % 16)) & 1)
{
mod_mul(c, a, n, c, size_a);
}
}
}
void rsa_encrypt(unsigned short * M, unsigned long s, unsigned short * e, unsigned short * n, unsigned short * C, unsigned long k)
{
mod_pow(M, s / 2, e, s / 2, n, C);
}
void rsa_decrypt(unsigned short * C, unsigned short * d, unsigned short * n, unsigned short * M, unsigned long k)
{
mod_pow(C, k / 16, d, k / 16, n, M);
}
|
5ec42f8aa28169826c33346b8fe465814481e683
|
d444e796a9543b7b855fad46be1ffcd83a5b3941
|
/farsight/cpp/2-day/Vector.cpp
|
bfa484bc60749affdedf3e24d2fd1c22fea1bdb1
|
[] |
no_license
|
xianjimli/misc
|
7e1f8e02f30e0cb0700e9751d5336b329a97880f
|
90cc886b2ce882eec2513b654d7c04920be0d028
|
refs/heads/master
| 2021-06-05T23:04:42.242138
| 2018-09-19T06:40:06
| 2018-09-19T06:40:06
| 20,082,914
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 509
|
cpp
|
Vector.cpp
|
#include "Vector.h"
#include <cstring>
#include <cstdlib>
#ifdef VECTOR_TEST
#include <cassert>
int main(int argc, char* argv[])
{
int i = 0;
int data = 0;
CVector<int>* dvector = new CVector<int>(10);
for(i = 0; i < 20; i++)
{
dvector->append(i);
assert(dvector->get(i, data) && data == i);
}
CVector<int> svector(*dvector);
CVector<int> avector = *dvector;
for(i = 0; i < 20; i++)
{
assert(svector.get(i, data) && data == i);
}
delete dvector;
return 0;
}
#endif/*VECTOR_TEST*/
|
973ca1f7e8adf843ac1d16a80cb82f02366782fe
|
1a8b0d48e3cb78803aee22fcd676dcb17d3b5340
|
/Protocol/headers/NewEntity.hpp
|
d59b446c9641d327b66d200b7cbcd680f1bacd46
|
[
"WTFPL"
] |
permissive
|
jurelou/R-type
|
e62a17ab4c35fe951a3c9b82b23f505944724caf
|
0982f0a6fa49456abca3c3471094a8f5332e9f7a
|
refs/heads/master
| 2021-05-02T13:18:20.821238
| 2018-02-08T13:17:55
| 2018-02-08T13:17:55
| 120,756,725
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 601
|
hpp
|
NewEntity.hpp
|
//
// Created by marmus_a on 18/01/18.
//
#ifndef R_TYPE_NEWENTITY_HPP
#define R_TYPE_NEWENTITY_HPP
#include <ARequest.hpp>
#include "Vertex.hpp"
namespace Protocol {
class NewEntity : public ARequest {
public:
NewEntity();
NewEntity(EntityType type, int id, const Vertex& pos);
virtual ~NewEntity();
EntityType type;
int id;
Vertex pos;
virtual std::string* stringify();
#ifdef SERVER
virtual bool run(Server *s, ISocket* userSockets);
#else
virtual bool run(Client *c);
#endif
};
}
#endif //R_TYPE_NEWENTITY_HPP
|
90ee50bb3b0795f84194eb9004ed9c4e558ddb6d
|
af74ee386a16d0445e18d0ed25999d493092e3f1
|
/TankWars/Tank.cpp
|
e5a7e7c6ddb29a2fae3b91c6b852bac2925fbe72
|
[] |
no_license
|
LonelyCpp/TankWars
|
54a979c9452df8467b4aeccc3c89996ca8b74d0e
|
edaf209bd35173c478270a239917dd7808f2575b
|
refs/heads/master
| 2022-07-20T07:09:06.717676
| 2020-05-19T05:26:52
| 2020-05-19T05:26:52
| 86,409,532
| 5
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,839
|
cpp
|
Tank.cpp
|
#include "Tank.h"
#include <vector>
void Tank::drawCircle(float x, float y, float r)
{
glBegin(GL_POINTS);
glPointSize(1);
for(float i = 0; i < 2 * 3.14159; i += 0.5)
{
glVertex2f(x + r * cos(i), y + r * sin(i));
}
glEnd();
}
Tank::Tank(int x, int y)
:healthBar(x + 30, y + 100)
{
this->x = x;
this->y = y;
health = 100;
hitBox = { 0 + x, 100 + y, 135 + x, 0 + y };
healthBar.setDim(50, 5);
healthBar.setFill(health);
}
void Tank::drawHitBox()
{
glBegin(GL_LINE_LOOP);
glVertex2f(hitBox.botx, hitBox.boty);
glVertex2f(hitBox.topx, hitBox.boty);
glVertex2f(hitBox.topx, hitBox.topy);
glVertex2f(hitBox.botx, hitBox.topy);
glEnd();
}
void Tank::draw(bool draw)
{
//drawHitBox();
//<base>
healthBar.draw();
glColor3ub(66, 74, 59);
glBegin(GL_POLYGON);
glVertex2f(5 + x, 42 + y);
glVertex2f(120 + x, 42 + y);
glVertex2f(115 + x, 51 + y);
glVertex2f(8 + x, 51 + y);
glEnd();
glBegin(GL_POLYGON);
glVertex2f(115 + x, 51 + y);
glVertex2f(107 + x, 64 + y);
glVertex2f(18 + x, 64 + y);
glVertex2f(8 + x, 51 + y);
glEnd();
glColor3ub(120, 134, 107);
glBegin(GL_POLYGON);
glVertex2f(5 + x, 42 + y);
glVertex2f(120 + x, 42 + y);
glVertex2f(115 + x, 51 + y);
glVertex2f(8 + x, 51 + y);
glEnd();
glBegin(GL_POLYGON);
glVertex2d(94 + x, 31 + y);
glVertex2d(14 + x, 31 + y);
glVertex2d(14 + x, 41 + y);
glVertex2d(94 + x, 41 + y);
glEnd();
glColor3ub(0, 0, 0);
glBegin(GL_LINES);
for (int i = 0; i <= 8; i++)
{
glVertex2d(14 + x + i * 10, 31 + y);
glVertex2d(14 + x + i * 10, 41 + y);
}
glEnd();
glPointSize(8);
glBegin(GL_POINTS);
for(int i = 0; i<7; i++)
glVertex2f(26 + i*12 + x, 58 + y);
glEnd();
glPointSize(2);
glBegin(GL_POINTS);
for (int i = 0; i<9; i++)
glVertex2f(13 + i * 12 + x, 45 + y);
glEnd();
glBegin(GL_LINE_LOOP);
glVertex2f(5 + x, 42 + y);
glVertex2f(120 + x, 42 + y);
glVertex2f(115 + x, 51 + y);
glVertex2f(8 + x, 51 + y);
glEnd();
//<cannon>
glColor3ub(color.r, color.b, color.g);
glLineWidth(5);
glBegin(GL_LINES);
glVertex2f(54 + x, 25 + y);
if (armAngle < 0)
glVertex2f(ARM_LENGTH*cos(armAngle) + (54 + x), ARM_LENGTH*sin(armAngle) + 25 + y);
else
glVertex2f(-1 * ARM_LENGTH*cos(armAngle) + (54 + x) , -1 * ARM_LENGTH*sin(armAngle) + 25 + y);
glEnd();
glLineWidth(1);
//</cannon>
glColor3ub(120, 134, 107);
glBegin(GL_POLYGON);
glVertex2d(84 + x, 31 + y);
glVertex2d(94 + x, 25 + y);
glVertex2d(14 + x, 25 + y);
glVertex2d(24 + x, 31 + y);
glEnd();
glColor3ub(0, 0, 0);
glBegin(GL_LINE_LOOP);
glVertex2d(84 + x, 31 + y);
glVertex2d(84 + x, 25 + y);
glVertex2d(24 + x, 25 + y);
glVertex2d(24 + x, 31 + y);
glEnd();
//</base>
}
void Tank::setColor(Color c)
{
color = c;
}
void Tank::erase()
{
glColor3ub(gameGlobals::backColor.r, gameGlobals::backColor.g, gameGlobals::backColor.b);
glBegin(GL_POLYGON);
glVertex2d(hitBox.botx - 30, hitBox.boty);
glVertex2d(hitBox.botx - 30, hitBox.topy - 65);
glVertex2d(hitBox.topx, hitBox.topy - 65);
glVertex2d(hitBox.topx, hitBox.boty);
glEnd();
}
bool Tank::didHit(int checkX, int checkY)
{
if (checkX > hitBox.botx && checkX < hitBox.topx)
if (checkY < hitBox.boty && checkY > hitBox.topy)
{
health -= 60;
healthBar.setFill(health);
return true;
}
return false;
}
void Tank::updatePos(int x, int y)
{
this->x = x;
this->y = y;
}
void Tank::updateAngle(int mouseX, int mouseY)
{
if (mouseY < (15 + y))
armAngle = atan(((15 + y) - mouseY) / (float)((54 + x) - mouseX));
}
Weapon* Tank::createWeapon(int power)
{
Weapon *w;
if (armAngle < 0)
w = new Weapon(ARM_LENGTH*cos(armAngle) + 54 + x, ARM_LENGTH*sin(armAngle) + 15 + y, power, armAngle);
else
w = new Weapon(-1 * ARM_LENGTH*cos(armAngle) + 54 + x, -1 * ARM_LENGTH*sin(armAngle) + 15 + y, power, armAngle);
w->setColor(color);
return w;
}
|
83d1d4e381957fe06727aa02a995fb6bf938e533
|
fc718d08bd934266fce33896d42d0a8641af37b8
|
/LL_Anim.hpp
|
0547efb3fdbb58eef4b15ded036c84d041b9368c
|
[] |
no_license
|
ixchow/Preshack
|
de690b1c500e9389f54db524a82ac920e028e6fd
|
d8aa0f8ef8cca8d5b1aed759a92202de8355934e
|
refs/heads/master
| 2021-06-08T12:05:10.338455
| 2017-08-25T03:36:42
| 2017-08-25T03:36:42
| 4,300,347
| 15
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 456
|
hpp
|
LL_Anim.hpp
|
#ifndef LL_ANIM_HPP
#define LL_ANIM_HPP
#include "Module.hpp"
enum {
BARS,
BALL,
EDGES,
STACKING
};
class LayerAnim : public Module {
public:
LayerAnim();
virtual ~LayerAnim();
virtual Vector2f size();
virtual void draw(Box2f viewport, Box2f screen_viewport, float scale, unsigned int recurse = 0);
virtual void update(float elapsed_time);
virtual bool handle_event(SDL_Event const &event, Vector2f mouse);
int mode;
};
#endif //LL_ANIM_HPP
|
60117d52d63e2cd066211aed3a3c753c3281f212
|
058238f45c98e0d4a7ed9883594489780f6ebe7d
|
/QTProject/QTopObjectDisplay.h
|
be20a24b560829484d9fe4c7f67a3d6d6a6537b9
|
[] |
no_license
|
xiangliu/QSceneEdit
|
18283970032208ef6c395c200cea3bd56978f982
|
f9215782fa7896322556e20b74df1ccbe187f7b2
|
refs/heads/master
| 2020-05-04T15:32:25.091948
| 2013-06-03T01:53:44
| 2013-06-03T01:53:44
| 7,065,363
| 0
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 659
|
h
|
QTopObjectDisplay.h
|
#ifndef QTOPOBJECTDISPLAY_H
#define QTOPOBJECTDISPLAY_H
namespace Ui {
class QTopObjectDisplay;
}
class QTopObjectDisplay : public QWidget
{
Q_OBJECT
//method
public:
explicit QTopObjectDisplay(QWidget *parent = 0);
~QTopObjectDisplay();
void paintEvent(QPaintEvent *e); //继承自基类的虚绘制函数
protected:
//attribute:
public:
QImage *topImage; //用于显示的Image
signals:
//void PickupObject(QImage *grayImage); //这个signal由QSegPictureDisplay 来接受,用来显示pickup的object
public slots:
//void GetSegObjectList(vector<CSegObject*> &objects); // 从mainwindow获取相关的数据
private:
};
#endif
|
a25a80bb8ab089fcc3db353ecde68060aca881a2
|
427f48b76d1b312cff7af2d9b535ea333e8d154e
|
/cpp/utility_rel_ops_operator_cmp.cpp
|
0719429e09d576670c86c7abc76841ac3d73eddd
|
[
"MIT"
] |
permissive
|
rpuntaie/c-examples
|
8925146dd1a59edb137c6240363e2794eccce004
|
385b3c792e5b39f81a187870100ed6401520a404
|
refs/heads/main
| 2023-05-31T15:29:38.919736
| 2021-06-28T16:53:07
| 2021-06-28T16:53:07
| 381,098,552
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 821
|
cpp
|
utility_rel_ops_operator_cmp.cpp
|
/*
g++ --std=c++20 -pthread -o ../_build/cpp/utility_rel_ops_operator_cmp.exe ./cpp/utility_rel_ops_operator_cmp.cpp && (cd ../_build/cpp/;./utility_rel_ops_operator_cmp.exe)
https://en.cppreference.com/w/cpp/utility/rel_ops/operator_cmp
*/
#include <iostream>
#include <utility>
struct Foo {
int n;
};
bool operator==(const Foo& lhs, const Foo& rhs)
{
return lhs.n == rhs.n;
}
bool operator<(const Foo& lhs, const Foo& rhs)
{
return lhs.n < rhs.n;
}
int main()
{
Foo f1 = {1};
Foo f2 = {2};
using namespace std::rel_ops;
std::cout << std::boolalpha;
std::cout << "not equal? : " << (f1 != f2) << '\n';
std::cout << "greater? : " << (f1 > f2) << '\n';
std::cout << "less equal? : " << (f1 <= f2) << '\n';
std::cout << "greater equal? : " << (f1 >= f2) << '\n';
}
|
0f61756e2035c07e435b58a38cac6f6f213540ec
|
2743ed11026e2fba43799799b04d0df55af30365
|
/abserv/abserv/IOModel.h
|
4079f7de036d828fdf789e3811efeaf2cbe2b123
|
[] |
no_license
|
lineCode/ABx
|
bb792946429bf60fee38da609b0c36c89ec34990
|
b726a2ada8815e8d4c8a838f823ffd3ab2e2b81b
|
refs/heads/master
| 2022-01-22T06:13:49.170390
| 2019-07-19T20:03:31
| 2019-07-19T20:03:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 268
|
h
|
IOModel.h
|
#pragma once
#include "Model.h"
#include "IOAsset.h"
namespace IO {
class IOModel : public IOAssetImpl<Game::Model>
{
public:
/// Import 3D Model file exported with the import program
bool Import(Game::Model* asset, const std::string& name) override;
};
}
|
12966fb09458102c161bd225ed06454aae662aa3
|
9e96debaf9c430056586e0dc3c9ac363f1eb3810
|
/compendium/tools/SCRCodeGen/test/TestCodeGenerator.cpp
|
3ada67304e75a44361ae28b2f148e058b9bec5ef
|
[
"Apache-2.0"
] |
permissive
|
sunfirefox/CppMicroServices
|
b2f73be5c75efb5ffcedeed0deb82e37bac66272
|
55dda3b59ce471b3b7baaa6bf449bc0efe930956
|
refs/heads/master
| 2023-05-24T20:28:38.076412
| 2023-04-28T15:09:27
| 2023-04-28T15:09:27
| 14,852,197
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 29,231
|
cpp
|
TestCodeGenerator.cpp
|
/*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include <regex>
#include "../ComponentCallbackGenerator.hpp"
#include "../ManifestParser.hpp"
#include "../ManifestParserFactory.hpp"
#include "ReferenceAutogenFiles.hpp"
#include "Util.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "json/json.h"
namespace codegen
{
const std::string manifest_json = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"activate" : "Activate",
"deactivate" : "Deactivate",
"configuration-policy" : "require",
"configuration-pid" : ["DSSpellCheck::SpellCheckImpl"],
"factory" : "factory id",
"factory-properties" : {
"abc" : "123"
},
"service": {
"scope": "singleton",
"interfaces": ["SpellCheck::ISpellCheckService"]
},
"references": [{
"name": "dictionary",
"interface": "DictionaryService::IDictionaryService"
}]
}]
}
}
)manifest";
const std::string manifest_dyn = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"activate" : "Activate",
"deactivate" : "Deactivate",
"inject-references" : true,
"service": {
"scope": "SINGLETON", //case-insensitive
"interfaces": ["SpellCheck::ISpellCheckService"]
},
"references": [{
"name": "dictionary",
"interface": "DictionaryService::IDictionaryService",
"policy": "dynamic"
}]
}]
}
}
)manifest";
const std::string manifest_mult_comp = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo::Impl1",
"service": {
"interfaces": ["Foo::Interface"]
}
},
{"implementation-class": "Foo::Impl2",
"service": {
"interfaces": ["Foo::Interface"]
}
}]
}
}
)manifest";
const std::string manifest_mult_comp_same_impl = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo::Impl1",
"name": "FooImpl1",
"service": {
"interfaces": ["Foo::Interface"]
}
},
{"implementation-class": "Foo::Impl1",
"name": "FooImpl2",
"service": {
"interfaces": ["Foo::Interface"]
}
}]
}
}
)manifest";
const std::string manifest_no_scr = R"manifest(
{
}
)manifest";
const std::string manifest_empty_scr = R"manifest(
{
"scr" : ""
}
)manifest";
const std::string manifest_illegal_scr = R"manifest(
{
"scr" : 911
}
)manifest";
const std::string manifest_illegal_ver = R"manifest(
{
"scr" : { "version" : 0,
"components": [{
}]
}
}
)manifest";
const std::string manifest_missing_ver = R"manifest(
{
"scr" : {"components": [{
"implementation-class": "Foo::Impl1",
"service": {
"interfaces": ["Foo::Interface"]
}
}]
}
}
)manifest";
const std::string manifest_illegal_ver2 = R"manifest(
{
"scr" : { "version" : "",
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl"
}]
}
}
)manifest";
const std::string manifest_illegal_ver3 = R"manifest(
{
"scr" : { "version" : "one",
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl"
}]
}
}
)manifest";
const std::string manifest_illegal_ver4 = R"manifest(
{
"scr" : { "version" : ,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl"
}]
}
}
)manifest";
const std::string manifest_dup_keys = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl"
}]
},
"scr" : "duplicated"
}
)manifest";
const std::string manifest_no_comp = R"manifest(
{
"scr" : { "version" : 1
}
}
)manifest";
const std::string manifest_no_impl_class = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"activate" : "Activate",
"deactivate" : "Deactivate",
"service": {
"scope": "singleton",
"interfaces": ["SpellCheck::ISpellCheckService"]
},
"references": [{
"name": "dictionary",
"interface": "DictionaryService::IDictionaryService"
}]
}]
}
}
)manifest";
const std::string manifest_no_ref_name = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"activate" : "Activate",
"deactivate" : "Deactivate",
"service": {
"scope": "singleton",
"interfaces": ["SpellCheck::ISpellCheckService"]
},
"references": [{
"interface": "DictionaryService::IDictionaryService"
}]
}]
}
}
)manifest";
const std::string manifest_no_ref_interface = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"activate" : "Activate",
"deactivate" : "Deactivate",
"service": {
"scope": "singleton",
"interfaces": ["SpellCheck::ISpellCheckService"]
},
"references": [{
"name": "dictionary"
}]
}]
}
}
)manifest";
const std::string manifest_illegal_service = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"activate" : "Activate",
"deactivate" : "Deactivate",
"service": 911
}]
}
}
)manifest";
const std::string manifest_no_interfaces = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"activate" : "Activate",
"deactivate" : "Deactivate",
"service": {
"scope": "singleton"
},
"references": [{
"name": "dictionary",
"interface": "DictionaryService::IDictionaryService"
}]
}]
}
}
)manifest";
const std::string manifest_empty_interfaces_arr = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"service": {
"scope": "singleton",
"interfaces": []
}
}]
}
}
)manifest";
const std::string manifest_empty_impl_class = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": ""
}]
}
}
)manifest";
const std::string manifest_illegal_inject_refs = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo",
"inject-references": "true"
}]
}
}
)manifest";
const std::string manifest_illegal_inject_refs2 = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo",
"inject-references": {}
}]
}
}
)manifest";
const std::string manifest_empty_ref_name = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"references": [{
"name": "",
"interface": "Bar"
}]
}]
}
}
)manifest";
const std::string manifest_illegal_ref_name = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"references": [{
"name": 729,
"interface": "Bar"
}]
}]
}
}
)manifest";
const std::string manifest_duplicate_ref_name = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"references": [{
"name": "foo",
"interface": "Bar"
},
{
"name": "foo",
"interface": "Bar"
}]
}]
}
}
)manifest";
const std::string manifest_illegal_comp = R"manifest(
{
"scr" : { "version" : 1,
"components": []
}
}
)manifest";
const std::string manifest_empty_ref_interface = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"references": [{
"name": "Foo",
"interface": ""
}]
}]
}
}
)manifest";
const std::string manifest_illegal_ref_interface = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"references": [{
"name": "Foo",
"interface": 911
}]
}]
}
}
)manifest";
const std::string manifest_dup_ref_interface = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"references": [{
"name": "Foo",
"interface": "Foo::Bar",
"interface": "Foo::Baz"
}]
}]
}
}
)manifest";
const std::string manifest_illegal_scope = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"service": {
"scope": "global",
"interfaces": ["SpellCheck::ISpellCheckService"]
}
}]
}
}
)manifest";
const std::string manifest_illegal_ref = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "DSSpellCheck::SpellCheckImpl",
"references": "illegal"
}]
}
}
)manifest";
const std::string manifest_illegal_interfaces = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo::Impl1",
"service": {
"interfaces": [1, 2]
}
}
]
}
}
)manifest";
const std::string manifest_empty_interfaces_string = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo::Impl1",
"service": {
"interfaces": ["", "valid", ""]
}
}
]
}
}
)manifest";
const std::string manifest_illegal_configuration_policy = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo",
"configuration-policy": "default",
"configuration-pid" : ["Foo"]
}]
}
}
)manifest";
const std::string manifest_illegal_configuration_pid = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo",
"configuration-policy": "ignore",
"configuration-pid": [""]
}]
}
}
)manifest";
const std::string manifest_duplicate_configuration_pid = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo",
"configuration-policy": "require",
"configuration-pid": ["Foo", "Foo"]
}]
}
}
)manifest";
const std::string manifest_illegal_factory = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo",
"factory": true
}]
}
}
)manifest";
const std::string manifest_configuration_policy_but_no_pid = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo",
"configuration-policy": "optional"
}]
}
}
)manifest";
const std::string manifest_configuration_pid_but_no_policy = R"manifest(
{
"scr" : { "version" : 1,
"components": [{
"implementation-class": "Foo",
"configuration-pid": ["Foo"]
}]
}
}
)manifest";
auto
GetManifestSCRData(std::string const& content)
{
std::istringstream istrstream(content);
auto root = util::ParseManifestOrThrow(istrstream);
return util::JsonValueValidator(root, "scr", Json::ValueType::objectValue)();
};
// For the manifest specified in the member manifest and headers specified in headers,
// we expect the output generated by the code-generator to be exactly referenceOutput.
struct CodegenValidManifestState
{
CodegenValidManifestState(std::string _manifest,
std::vector<std::string> _headers,
std::string _referenceOutput)
: manifest(std::move(_manifest))
, headers(std::move(_headers))
, referenceOutput(std::move(_referenceOutput))
{
}
std::string manifest;
std::vector<std::string> headers;
std::string referenceOutput;
friend std::ostream&
operator<<(std::ostream& os, CodegenValidManifestState const& obj)
{
os << "Manifest: " << obj.manifest << "\nHeaders: ";
std::for_each(obj.headers.begin(),
obj.headers.end(),
[&os](std::string const& header) { os << header << "\n "; });
return os << "\nReference Output: " << obj.referenceOutput << "\n";
}
};
class ValidCodegenTest : public ::testing::TestWithParam<CodegenValidManifestState>
{
};
TEST_P(ValidCodegenTest, TestCodegenFunctionality)
{
CodegenValidManifestState vcs = GetParam();
auto scr = GetManifestSCRData(vcs.manifest);
auto version = util::JsonValueValidator(scr, "version", Json::ValueType::intValue)();
auto manifestParser = ManifestParserFactory::Create(version.asInt());
auto componentInfos = manifestParser->ParseAndGetComponentInfos(scr);
ComponentCallbackGenerator compGen(vcs.headers, componentInfos);
EXPECT_EQ(compGen.GetString(), vcs.referenceOutput);
}
INSTANTIATE_TEST_SUITE_P(
SuccessModes,
ValidCodegenTest,
testing::Values(
// valid manifest
CodegenValidManifestState(manifest_json, { "SpellCheckerImpl.hpp" }, REF_SRC),
// valid manifest with dynamic policy
CodegenValidManifestState(manifest_dyn, { "SpellCheckerImpl.hpp" }, REF_SRC_DYN),
// valid manifest with multiple components
CodegenValidManifestState(manifest_mult_comp, { "A.hpp", "B.hpp", "C.hpp" }, REF_MULT_COMPS),
// valid manifest with multiple components of the same implementation class
CodegenValidManifestState(manifest_mult_comp_same_impl,
{ "A.hpp", "B.hpp", "C.hpp" },
REF_MULT_COMPS_SAME_IMPL)));
// For the manifest specified in the member manifest, we expect the exception message
// output by the code-generator to be exactly errorOutput.
// Instead, if we expect the errorOutput to be contained in the generated error message,
// we set isPartial = true. (This is useful when we don't want to specify really long error messages)
struct CodegenInvalidManifestState
{
CodegenInvalidManifestState(std::string _manifest, std::string _errorOutput, bool _isPartial = false)
: manifest(std::move(_manifest))
, errorOutput(std::move(_errorOutput))
, isPartial(_isPartial)
{
}
std::string manifest;
std::string errorOutput;
bool isPartial;
friend std::ostream&
operator<<(std::ostream& os, CodegenInvalidManifestState const& obj)
{
return os << "Manifest: " << obj.manifest << " Error output: " << obj.errorOutput
<< " Perform partial match: " << (obj.isPartial ? "Yes" : "No") << "\n";
}
};
class InvalidCodegenTest : public ::testing::TestWithParam<CodegenInvalidManifestState>
{
};
// Test failure modes where mandatory manifest names are missing or empty
TEST_P(InvalidCodegenTest, TestCodegenFailureModes)
{
CodegenInvalidManifestState ics = GetParam();
try
{
auto scr = GetManifestSCRData(ics.manifest);
auto version = util::JsonValueValidator(scr, "version", Json::ValueType::intValue)();
auto manifestParser = ManifestParserFactory::Create(version.asInt());
manifestParser->ParseAndGetComponentInfos(scr);
FAIL() << "This failure suggests that parsing has succeeded. "
"Shouldn't happen for failure mode tests";
}
catch (std::exception const& err)
{
if (!ics.isPartial)
{
ASSERT_STREQ(ics.errorOutput.c_str(), err.what());
}
else
{
const std::string regex = "(" + ics.errorOutput + ")";
ASSERT_TRUE(std::regex_search(err.what(), std::regex(regex)));
}
}
}
INSTANTIATE_TEST_SUITE_P(
FailureModes,
InvalidCodegenTest,
testing::Values(
CodegenInvalidManifestState(manifest_no_scr, "Mandatory name 'scr' missing from the manifest"),
CodegenInvalidManifestState(manifest_empty_scr,
"Invalid value for the name 'scr'. Expected non-empty JSON object i.e. "
"collection of name/value pairs"),
CodegenInvalidManifestState(manifest_illegal_scr,
"Invalid value for the name 'scr'. Expected non-empty JSON object i.e. "
"collection of name/value pairs"),
// We test the duplicate names only twice because the check is done by the JSON parser
// and we trust its validation.
// We have a test point for a duplicate name at the root and in the interior
CodegenInvalidManifestState(manifest_dup_keys,
"Duplicate key: 'scr'",
/*isPartial=*/true),
CodegenInvalidManifestState(manifest_illegal_ver, "Unsupported manifest file version '0'"),
CodegenInvalidManifestState(manifest_illegal_ver2, "Invalid value for the name 'version'. Expected int"),
CodegenInvalidManifestState(manifest_illegal_ver3, "Invalid value for the name 'version'. Expected int"),
CodegenInvalidManifestState(manifest_illegal_ver4,
"Syntax error: value, object or array expected",
/*isPartial=*/true),
CodegenInvalidManifestState(manifest_missing_ver, "Mandatory name 'version' missing from the manifest"),
CodegenInvalidManifestState(manifest_no_comp, "Mandatory name 'components' missing from the manifest"),
CodegenInvalidManifestState(manifest_illegal_comp,
"Invalid value for the name 'components'. Expected non-empty array"),
CodegenInvalidManifestState(manifest_no_impl_class,
"Mandatory name 'implementation-class' missing from the manifest"),
CodegenInvalidManifestState(manifest_empty_impl_class,
"Invalid value for the name 'implementation-class'. Expected non-empty "
"string"),
CodegenInvalidManifestState(manifest_no_ref_name, "Mandatory name 'name' missing from the manifest"),
CodegenInvalidManifestState(manifest_empty_ref_name,
"Invalid value for the name 'name'. Expected non-empty string"),
CodegenInvalidManifestState(manifest_illegal_ref_name,
"Invalid value for the name 'name'. Expected non-empty string"),
CodegenInvalidManifestState(manifest_duplicate_ref_name,
"Duplicate service reference names found. Reference names must be "
"unique. Duplicate names: foo "),
CodegenInvalidManifestState(manifest_no_ref_interface,
"Mandatory name 'interface' missing from the manifest"),
CodegenInvalidManifestState(manifest_empty_ref_interface,
"Invalid value for the name 'interface'. Expected non-empty string"),
CodegenInvalidManifestState(manifest_illegal_ref_interface,
"Invalid value for the name 'interface'. Expected non-empty string"),
CodegenInvalidManifestState(manifest_dup_ref_interface,
"Duplicate key: 'interface'",
/*isPartial=*/true),
CodegenInvalidManifestState(manifest_illegal_service,
"Invalid value for the name 'service'. Expected non-empty JSON object "
"i.e. collection of name/value pairs"),
CodegenInvalidManifestState(manifest_no_interfaces,
"Mandatory name 'interfaces' missing from the manifest"),
CodegenInvalidManifestState(manifest_empty_interfaces_arr,
"Invalid value for the name 'interfaces'. Expected non-empty array"),
CodegenInvalidManifestState(manifest_illegal_interfaces,
"Invalid array value for the name "
"'interfaces'. Expected non-empty string"),
CodegenInvalidManifestState(manifest_empty_interfaces_string,
"Invalid array value for the name "
"'interfaces'. Expected non-empty string"),
CodegenInvalidManifestState(manifest_illegal_inject_refs,
"Invalid value for the name 'inject-references'. Expected boolean"),
CodegenInvalidManifestState(manifest_illegal_inject_refs2,
"Invalid value for the name 'inject-references'. Expected boolean"),
CodegenInvalidManifestState(manifest_illegal_scope,
"Invalid value 'global' for the name 'scope'. The valid choices are : "
"[singleton, bundle, prototype]"),
CodegenInvalidManifestState(manifest_illegal_ref,
"Invalid value for the name 'references'. Expected non-empty array"),
CodegenInvalidManifestState(manifest_illegal_configuration_policy,
"Invalid value 'default' for the name 'configuration-policy'. The valid "
"choices are : [require, optional, ignore]"),
CodegenInvalidManifestState(manifest_duplicate_configuration_pid,
"configuration-pid error in the manifest. Duplicate pid detected.",
true),
CodegenInvalidManifestState(manifest_illegal_factory,
"Invalid value for the name 'factory'. Expected non-empty string"),
CodegenInvalidManifestState(manifest_configuration_policy_but_no_pid,
"Error: Both configuration-policy and configuration-pid must be "
"present in the manifest.json file to participate in Configuration "
"Admin.",
true),
CodegenInvalidManifestState(manifest_configuration_pid_but_no_policy,
"Error: Both configuration-policy and configuration-pid must be "
"present in the manifest.json file to participate in Configuration "
"Admin.",
true)));
} // namespace codegen
|
355e63b95c19c5fcd8591e569a10b80888cf3097
|
d25e80c4469f2e7f4bafc23bc49cfc6a8c1e13c5
|
/dfslib-clientnode-p2.cpp
|
09b50578195e7b251b19d7c8e3d2f2967dd19460
|
[] |
no_license
|
GJGao/Distributed-File-System-gRPC
|
58394a055cbcdc57c9e1da6096678109b3c7fd8f
|
aa508995f25f94a6828dac7ab9a76bd3dbef68cc
|
refs/heads/master
| 2022-12-06T08:44:16.388262
| 2020-09-02T04:09:43
| 2020-09-02T04:09:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 41,607
|
cpp
|
dfslib-clientnode-p2.cpp
|
#include <regex>
#include <mutex>
#include <vector>
#include <string>
#include <thread>
#include <cstdio>
#include <chrono>
#include <errno.h>
#include <csignal>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <getopt.h>
#include <unistd.h>
#include <limits.h>
#include <sys/inotify.h>
#include <grpcpp/grpcpp.h>
#include <utime.h>
#include "src/dfs-utils.h"
#include "src/dfslibx-clientnode-p2.h"
#include "dfslib-shared-p2.h"
#include "dfslib-clientnode-p2.h"
#include "proto-src/dfs-service.grpc.pb.h"
using grpc::Status;
using grpc::Channel;
using grpc::StatusCode;
using grpc::ClientWriter;
using grpc::ClientReader;
using grpc::ClientContext;
using namespace std;
extern dfs_log_level_e DFS_LOG_LEVEL;
//
// STUDENT INSTRUCTION:
//
// Change these "using" aliases to the specific
// message types you are using to indicate
// a file request and a listing of files from the server.
//
//using FileRequestType = FileRequest;
//using FileListResponseType = FileList;
using FileRequestType = dfs_service::FileRequest;
using FileListResponseType = dfs_service::FileMap;
DFSClientNodeP2::DFSClientNodeP2() : DFSClientNode() {}
DFSClientNodeP2::~DFSClientNodeP2() {}
void DFSClientNodeP2::loadMountFiles()
{
std::lock_guard<std::mutex> lock(Function2);
//make a table of all files in hte mount dir.
//load all files in mount_dir
if (DEBUG) cout<<"loading files from mount dir "<<mount_path<<endl;
cout<<"wrapped path"<<WrapPath("mypath")<<endl;
cout<<"some more text"<<endl;
struct dirent *fileInfo;
struct stat fileStatus;
int fdes;
DIR *folder;
if((folder = opendir(mount_path.c_str())) != NULL)
{
while((fileInfo = readdir(folder)) != NULL)
{
if(fileInfo->d_type == DT_REG)
{
//found a file. add to fileTable.
char buffer[100];
memset(buffer,0,100);
strcpy(buffer, mount_path.c_str());
strcat(buffer, fileInfo->d_name);
fdes = open(buffer,O_RDWR,0644);
if(fdes<0)
{
cout<<"Couldn't open files"<<endl;
cout<<strerror(errno)<<endl;
closedir(folder);
return;
}
fstat(fdes, &fileStatus);
//add to map.
if(DEBUG) cout<<"loading "<<fileInfo->d_name<<" size: "<<fileStatus.st_size<<endl;
dfs_service::FileStatus thisStatus;
thisStatus.set_fdes(fdes);
thisStatus.set_mtime((fileStatus.st_mtim).tv_sec);
thisStatus.set_ctime((fileStatus.st_ctim).tv_sec);
thisStatus.set_crc(dfs_file_checksum(buffer, &crc_table));
thisStatus.set_todelete(true);
thisStatus.set_filename(fileInfo->d_name);
thisStatus.set_ownerclientid(ClientId());
thisStatus.set_size(fileStatus.st_size);
// fileTable.mutable_mapval()->insert(pair<string, dfs_service::FileStatus>(fileInfo->d_name, thisStatus));
// {
// std::lock_guard<std::mutex> lock(writeAccessMutex);
// writeAccessMutex.lock();
(*fileTable.mutable_mapval())[fileInfo->d_name].CopyFrom(thisStatus);
// writeAccessMutex.unlock();
// }
// fileTable[fileInfo->d_name] = thisStatus;
// fileTable[fileInfo->d_name] = FileAttr(fdes, fileStatus.st_size, (fileStatus.st_mtim).tv_sec, (fileStatus.st_ctim).tv_sec);
}
}
closedir(folder);
}
}
bool DFSClientNodeP2::isServerDelete(const string & filename)
{
dfs_service::FileRequest request;
request.set_name(filename);
dfs_service::FileStatus response;
::grpc::ClientContext context;
//create deadline
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(deadline_timeout);
context.set_deadline(deadline);
::grpc::Status resultStatus = service_stub->getServerStatus(&context,request,&response);
if (resultStatus.error_code() == StatusCode::OK)
{
return(response.todelete());
}
return false;
}
grpc::StatusCode DFSClientNodeP2::RequestWriteAccess(const std::string &filename) {
std::lock_guard<std::mutex> lock(Function2);
// RequestWriteLockMutex.lock();
//
// STUDENT INSTRUCTION:
//
// Add your request to obtain a write lock here when trying to store a file.
// This method should request a write lock for the given file at the server,
// so that the current client becomes the sole creator/writer. If the server
// responds with a RESOURCE_EXHAUSTED response, the client should cancel
// the current file storage
//
// The StatusCode response should be:
//
// OK - if all went well
// StatusCode::DEADLINE_EXCEEDED - if the deadline timeout occurs
// StatusCode::RESOURCE_EXHAUSTED - if a write lock cannot be obtained
// StatusCode::CANCELLED otherwise
//
//
/*
1. if the entry is not in client, create a new one with filname.
*/
// string shortClientID = ClientId().substr(24,3);
string shortClientID = ClientId();
if (DEBUG) cout<<std::this_thread::get_id()<<" request Write Access "<<filename<<" id "<<shortClientID<<endl;
::grpc::ClientContext context;
//create deadline
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(deadline_timeout);
context.set_deadline(deadline);
::dfs_service::AccessRequest request;
::dfs_service::Access response;
::dfs_service::FileStatus requestStatus;
request.set_clientid(ClientId());
// std::lock_guard<std::mutex> lock(writeAccessMutex);
// writeAccessMutex.lock();
auto itr = fileTable.mutable_mapval()->find(filename);
if(itr == fileTable.mutable_mapval()->end())
{
//not with client
::dfs_service::FileStatus newFileStatus;
newFileStatus.set_ownerclientid(ClientId());
newFileStatus.set_filename(filename);
newFileStatus.set_todelete(true);
newFileStatus.set_crc(0);
newFileStatus.set_mtime(0);
newFileStatus.set_fdes(0);
requestStatus.CopyFrom(newFileStatus);
}
else
{
//entry already exists.
requestStatus.CopyFrom(itr->second);
}
// request.set_allocated_fstatval(&requestStatus);
request.mutable_fstatval()->CopyFrom(requestStatus);
::grpc::Status resultStatus = service_stub->RequestWriteLock(&context,request,&response);
// writeAccessMutex.unlock();
// RequestWriteLockMutex.unlock();
return resultStatus.error_code();
}
bool DFSClientNodeP2::ExistsInServer(const string &filename)
{
std::lock_guard<std::mutex> lock(Function2);
// ExistsinServerMutex.lock();
::grpc::ClientContext context;
//create deadline
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(deadline_timeout);
context.set_deadline(deadline);
::dfs_service::FileStatus request;
// {
// std::lock_guard<std::mutex> lock(writeAccessMutex);
// request = (*fileTable.mutable_mapval())[filename];
// writeAccessMutex.lock();
request.CopyFrom((*fileTable.mutable_mapval())[filename]);
// writeAccessMutex.unlock();
// }
::dfs_service::Access response;
auto result = service_stub->alreadyExists(&context,request, &response);
// ExistsinServerMutex.unlock();
return response.accessval();
}
grpc::StatusCode DFSClientNodeP2::Store(const std::string &filename) {
std::lock_guard<std::mutex> lock(Function1);
//
// STUDENT INSTRUCTION:
//
// Add your request to store a file here. Refer to the Part 1
// student instruction for details on the basics.
//
// You can start with your Part 1 implementation. However, you will
// need to adjust this method to recognize when a file trying to be
// stored is the same on the server (i.e. the ALREADY_EXISTS gRPC response).
//
// You will also need to add a request for a write lock before attempting to store.
//
// If the write lock request fails, you should return a status of RESOURCE_EXHAUSTED
// and cancel the current operation.
//
// The StatusCode response should be:
//
// StatusCode::OK - if all went well
// StatusCode::DEADLINE_EXCEEDED - if the deadline timeout occurs
// StatusCode::ALREADY_EXISTS - if the local cached file has not changed from the server version
// StatusCode::RESOURCE_EXHAUSTED - if a write lock cannot be obtained
// StatusCode::CANCELLED otherwise
//
//
if (!loadedFromMountStatus)
{
loadMountFiles();
loadedFromMountStatus = true;
}
cout<<std::this_thread::get_id()<<" 1 store "<<filename<<endl;
/*
1. create Context and response message pointer.
2. set teh deadline
3. obtain the client writer.
4. open the file
5. send the file size.
6. successively use the writer to send the values out.
7. once done, observe the status of the return value without concerning about the response.
*/
::grpc::ClientContext context;
//create deadline
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(deadline_timeout);
context.set_deadline(deadline);
//create response msg
dfs_service::Msg response;
dfs_service::Data fileData;
//open the file
string fullPath = WrapPath(filename);
// cout<<"1 file "<<filename<<" path "<<fullPath<<endl;
int fdes = open(fullPath.c_str(),O_RDONLY,0664);
//handline file not found.
if (fdes < 0)
{
if (DEBUG) cout<<std::this_thread::get_id()<<" 1 file not found"<<endl;
return StatusCode::NOT_FOUND;
}
struct stat fileStat;
fstat(fdes, &fileStat);
size_t fileSize = fileStat.st_size;
//check if file is on the filetable.
{
// std::lock_guard<std::mutex> lock(writeAccessMutex);
// writeAccessMutex.lock();
auto itr = fileTable.mutable_mapval()->find(filename);
if (itr == fileTable.mutable_mapval()->end())
{
if (DEBUG) cout<<std::this_thread::get_id()<<" 1 creating new entry in fileTable for "<<filename<<endl;
dfs_service::FileStatus thisStatus;
thisStatus.set_fdes(fdes);
thisStatus.set_mtime((fileStat.st_mtim).tv_sec);
thisStatus.set_ctime((fileStat.st_ctim).tv_sec);
thisStatus.set_filename(filename);
thisStatus.set_crc(dfs_file_checksum(fullPath, &crc_table));
thisStatus.set_size(fileStat.st_size);
thisStatus.set_todelete(true);
thisStatus.set_ownerclientid(ClientId());
(*fileTable.mutable_mapval())[filename].CopyFrom(thisStatus);
}
else
{
if (DEBUG) cout<<std::this_thread::get_id()<<" 1 previously existed filename "<<filename<<endl;
dfs_service::FileStatus thisStatus;
thisStatus.CopyFrom((*fileTable.mutable_mapval())[filename]);
thisStatus.set_crc(dfs_file_checksum(fullPath, &crc_table));
thisStatus.set_mtime((fileStat.st_mtim).tv_sec);
thisStatus.set_ctime((fileStat.st_ctim).tv_sec);
thisStatus.set_fdes(fdes);
thisStatus.set_size(fileStat.st_size);
thisStatus.set_todelete(true);
thisStatus.set_ownerclientid(ClientId());
(*fileTable.mutable_mapval())[filename].CopyFrom(thisStatus);
}
// writeAccessMutex.unlock();
}
//check if already exists
if (ExistsInServer(filename))
{
if (DEBUG) cout<<std::this_thread::get_id()<<" 1 same file as exists "<<filename<<endl;
return StatusCode::ALREADY_EXISTS;
}
if (DEBUG) cout<<std::this_thread::get_id()<<" 1 waiting to get the lock "<<filename<<endl;
//get file lock
::grpc::StatusCode fileAccessStatus = RequestWriteAccess(filename);
(*fileTable.mutable_mapval())[filename].set_todelete(true);
if(fileAccessStatus == StatusCode::DEADLINE_EXCEEDED)
{
cout<<"1 Store "<<filename<<" deadline exceeded"<<endl;
return StatusCode::DEADLINE_EXCEEDED;
}
if(fileAccessStatus == StatusCode::RESOURCE_EXHAUSTED)
{
cout<<"1 Store "<<filename<<" recource exhausted"<<endl;
return StatusCode::RESOURCE_EXHAUSTED;
}
if(fileAccessStatus == StatusCode::CANCELLED)
{
cout<<"1 Store "<<filename<<" cancelled"<<endl;
return StatusCode::CANCELLED;
}
cout<<std::this_thread::get_id()<<" 1 got the lock "<<filename<<endl;
//create clinet writer.
std::unique_ptr< ::grpc::ClientWriter< ::dfs_service::Data>> writer = service_stub->storeFile(&context,&response);
//send the filename to the server
fileData.set_dataval(filename);
writer->Write(fileData);
//send the mtime.
// {
// writeAccessMutex.lock();
// std::lock_guard<std::mutex> lock(writeAccessMutex);
//send mtime
fileData.set_dataval(to_string((*fileTable.mutable_mapval())[filename].mtime()));
// writeAccessMutex.unlock();
// }
writer->Write(fileData);
//get filesize and send to server
fileData.set_dataval(to_string(fileSize));
writer->Write(fileData);
//start sending file in chunks
size_t leftBytes = fileSize;
size_t sentTotal = 0;
size_t thisChunk = BUFF_SIZE;
size_t sentNow = 0;
char buffer[BUFF_SIZE];
memset(buffer, 0, BUFF_SIZE);
cout<<"1 starting to store "<<filename<<endl;
while(leftBytes > 0)
{
thisChunk = BUFF_SIZE;
if (leftBytes < BUFF_SIZE)
{
thisChunk = leftBytes;
}
sentNow = pread(fdes, buffer, thisChunk, sentTotal);
fileData.set_dataval(buffer, sentNow);
writer->Write(fileData);
//update counters
leftBytes -= sentNow;
sentTotal += sentNow;
memset(buffer, 0, BUFF_SIZE);
// cout<<"1 "<<filename<<" write left "<<leftBytes<<endl;
}
cout<<"1 done storing "<<filename<<endl;
Status serverStatus = writer->Finish();
if(serverStatus.error_code() == StatusCode::OK)
{
// if(ExistsInServer(filename))
// {
// if (DEBUG) cout<<std::this_thread::get_id()<<" 1 verified with server"<<endl;
// }
// writeAccessMutex.lock();
// (*fileTable.mutable_mapval())[filename].set_todelete(true);
// writeAccessMutex.unlock();
if (DEBUG) cout<<std::this_thread::get_id()<<" 1 finished storing "<<filename<<endl;
return StatusCode::OK;
}
else if(serverStatus.error_code() == StatusCode::DEADLINE_EXCEEDED)
{
if (DEBUG) cout<<"1 Deadline exceeded "<<filename<<endl;
return StatusCode::DEADLINE_EXCEEDED;
}
else if(serverStatus.error_code() == StatusCode::CANCELLED)
{
cout<<"1 server already has a later version "<<filename<<endl;
}
if (DEBUG) cout<<std::this_thread::get_id()<<" 1 Cancelled "<<filename<<endl;
return StatusCode::CANCELLED;
}
grpc::StatusCode DFSClientNodeP2::Fetch(const std::string &filename) {
std::lock_guard<std::mutex> lock(Function1);
if (!loadedFromMountStatus)
{
loadMountFiles();
loadedFromMountStatus = true;
}
//
// STUDENT INSTRUCTION:
//
// Add your request to fetch a file here. Refer to the Part 1
// student instruction for details on the basics.
//
// You can start with your Part 1 implementation. However, you will
// need to adjust this method to recognize when a file trying to be
// fetched is the same on the client (i.e. the files do not differ
// between the client and server and a fetch would be unnecessary.
//
// The StatusCode response should be:
//
// OK - if all went well
// DEADLINE_EXCEEDED - if the deadline timeout occurs
// NOT_FOUND - if the file cannot be found on the server
// ALREADY_EXISTS - if the local cached file has not changed from the server version
// CANCELLED otherwise
//
// Hint: You may want to match the mtime on local files to the server's mtime
//
/*
1. check if the file is with the clinet.
1.2. if so, check if its CRC matches with that of the Servers using an rpc call. if so, return already exists.
2. if not, create a temp entry. don't add to the filetable.
3. set the filename and send it over with the clientid variable.
4.
*/
cout<<"2 fetch "<<filename<<endl;
// {
// std::lock_guard<std::mutex> lock(writeAccessMutex);
// writeAccessMutex.lock();
auto itr = (fileTable.mutable_mapval())->find(filename);
bool exists = true;
if(isServerDelete(filename))
{
if (DEBUG) cout<<"2 deleted file in fetch"<<filename<<endl;
return StatusCode::CANCELLED;
}
if(itr == (fileTable.mutable_mapval())->end())
{
//check if it is due to inotify or callback. if inotify, the file already exists, jsut need to add it to teh table.
if ( FILE * clientFile = fopen(WrapPath(filename).c_str(), "r"))
{
exists = true;
fclose(clientFile);
int fdes = open(WrapPath(filename).c_str(),O_WRONLY|O_CREAT,0644);
dfs_service::FileStatus thisStatus;
cout<<"2 already exists "<<filename<<endl;
struct stat fileStat;
fstat(fdes,&fileStat);
thisStatus.set_filename(filename);
thisStatus.set_ctime((fileStat.st_ctim).tv_sec);
thisStatus.set_mtime((fileStat.st_mtim).tv_sec);
thisStatus.set_size(fileStat.st_size);
thisStatus.set_fdes(fdes);
thisStatus.set_ownerclientid(ClientId());
thisStatus.set_todelete(true);
close(fdes);
thisStatus.set_crc(dfs_file_checksum(WrapPath(filename), &crc_table));
(*fileTable.mutable_mapval())[filename].CopyFrom(thisStatus);
cout<<"2 loading existing file "<<filename<<endl;
}
else
{
exists = false;
dfs_service::FileStatus thisStatus;
thisStatus.set_todelete(true);
thisStatus.set_crc(0);
thisStatus.set_ownerclientid(ClientId());
thisStatus.set_size(0);
thisStatus.set_filename(filename);
(*fileTable.mutable_mapval())[filename].CopyFrom(thisStatus);
}
}
else
{
(itr->second).set_todelete(true);
exists = true;
}
// writeAccessMutex.unlock();
//entry in the client
//check that its not hte same.
if(ExistsInServer(filename))
{
if (DEBUG) cout<<"2 existing unmodified file "<<filename<<endl;
return StatusCode::ALREADY_EXISTS;
}
else{
if (DEBUG) cout<<"2 existing modified file "<<filename<<endl;
}
//get file lock
::grpc::StatusCode fileAccessStatus = RequestWriteAccess(filename);
(*fileTable.mutable_mapval())[filename].set_todelete(true);
if(fileAccessStatus == StatusCode::DEADLINE_EXCEEDED)
{
cout<<"2 Store "<<filename<<" deadline exceeded"<<endl;
return StatusCode::DEADLINE_EXCEEDED;
}
if(fileAccessStatus == StatusCode::RESOURCE_EXHAUSTED)
{
cout<<"2 Store "<<filename<<" recource exhausted"<<endl;
return StatusCode::RESOURCE_EXHAUSTED;
}
if(fileAccessStatus == StatusCode::CANCELLED)
{
cout<<"2 Store "<<filename<<" cancelled"<<endl;
return StatusCode::CANCELLED;
}
cout<<std::this_thread::get_id()<<"2 got the lock "<<filename<<endl;
// }
/*
1. use the stub to call the server and get the clientReader.
2. Check if the writer is still present to see if the file is found. if not, return.
3. create a file and start receiving the message and storing in the file.
*/
//create reader
unique_ptr<::grpc::ClientReader<::dfs_service::Data>> reader;
//create context and return request.
::grpc::ClientContext clientContext;
//create deadline
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(deadline_timeout);
clientContext.set_deadline(deadline);
//message to request file
::dfs_service::Msg request;
//fill in the file name into the request
request.set_msgval(filename);
//send request to server by calling the stub and get the reader.
reader = service_stub->fetchFile(&clientContext,request);
//use the reader to read into a local data variable
::dfs_service::Data fileData;
// Read the file size. if -1, didn't find.
reader->Read(&fileData);
long long int fileSize = stoi(fileData.dataval());
if (fileSize == -1)
{
if (DEBUG) cout<<"2 file not found"<<endl;
// writeAccessMutex.lock();
(*fileTable.mutable_mapval()).erase(filename);
// writeAccessMutex.unlock();
return StatusCode::NOT_FOUND;
}
else if(fileSize == -2)
{
if (DEBUG) cout<<"2 deleted file "<<filename<<endl;
// writeAccessMutex.lock();
(*fileTable.mutable_mapval()).erase(filename);
// writeAccessMutex.unlock();
return StatusCode::CANCELLED;
}
//receive the data into a buffer and write it into a file.
//create a complete file path with the mount
string wholeName = WrapPath(filename);
char buffer[BUFF_SIZE];
if (exists)
remove(wholeName.c_str());
int fdes = open(wholeName.c_str(),O_WRONLY|O_CREAT,0644);
cout<<"2 file path "<<wholeName<<endl;
//transfer to file
size_t bytesLeft = fileSize;
size_t bytesTransferred = 0;
size_t chunkSize = BUFF_SIZE;
while(reader->Read(&fileData))
{
//set chunk size
chunkSize = BUFF_SIZE;
if (bytesLeft < BUFF_SIZE)
{
chunkSize = bytesLeft;
}
memset(buffer, 0, BUFF_SIZE);
memcpy(buffer, fileData.dataval().c_str(), BUFF_SIZE);
//write it into the file
size_t thisTransferBytes = pwrite(fdes, buffer, chunkSize, bytesTransferred);
//update counters
bytesTransferred += thisTransferBytes;
bytesLeft -= thisTransferBytes;
}
reader->Read(&fileData);
long long int thisMtime = stoi(fileData.dataval());
Status serverStatus = reader->Finish();
if (serverStatus.error_code() == StatusCode::OK)
{
//its all ok.
//add it to the map
struct stat fileStat;
fstat(fdes, &fileStat);
::dfs_service::FileStatus newFileStatus;
newFileStatus.set_filename(filename);
newFileStatus.set_ctime((fileStat.st_ctim).tv_sec);
newFileStatus.set_mtime(thisMtime);
uint32_t crcRes = dfs_file_checksum(wholeName, &crc_table);
newFileStatus.set_crc(crcRes);
newFileStatus.set_size(fileStat.st_size);
newFileStatus.set_fdes(fdes);
newFileStatus.set_ownerclientid(ClientId());
newFileStatus.set_todelete(true);
{
// std::lock_guard<std::mutex> lock(writeAccessMutex);
// writeAccessMutex.lock();
(*fileTable.mutable_mapval())[filename].CopyFrom(newFileStatus);
// writeAccessMutex.unlock();
}
//close the reader.
close(fdes);
cout<<"2 done reading "<<filename<<endl;
return StatusCode::OK;
}
else if(serverStatus.error_code() == StatusCode::DEADLINE_EXCEEDED)
{
if(DEBUG) cout<<"2 Deadline exceeded"<<filename<<endl;
//close the reader.
close(fdes);
return StatusCode::DEADLINE_EXCEEDED;
}
//close the reader.
close(fdes);
return StatusCode::CANCELLED;
}
grpc::StatusCode DFSClientNodeP2::Delete(const std::string &filename) {
std::lock_guard<std::mutex> lock(Function1);
//
// STUDENT INSTRUCTION:
//
// Add your request to delete a file here. Refer to the Part 1
// student instruction for details on the basics.
//
// You will also need to add a request for a write lock before attempting to delete.
//
// If the write lock request fails, you should return a status of RESOURCE_EXHAUSTED
// and cancel the current operation.
//
// The StatusCode response should be:
//
// StatusCode::OK - if all went well
// StatusCode::DEADLINE_EXCEEDED - if the deadline timeout occurs
// StatusCode::RESOURCE_EXHAUSTED - if a write lock cannot be obtained
// StatusCode::CANCELLED otherwise
//
//
if (!loadedFromMountStatus)
{
loadMountFiles();
loadedFromMountStatus = true;
}
cout<<"3 Delete "<<filename<<endl;
bool exists = false;
auto temp_itr = fileTable.mutable_mapval()->find(filename);
if(temp_itr == fileTable.mutable_mapval()->end())
{
cout<<"3 no file to be deleted "<<filename<<endl;
return StatusCode::CANCELLED;
}
else if( FILE * clientFile = fopen(WrapPath(filename).c_str(), "r"))
{
cout<<"3 file exists "<<endl;
exists = true;
fclose(clientFile);
if((temp_itr->second).todelete())
{
// (temp_itr->second).set_todelete(false);
cout<<"3 no file to be deleted "<<filename<<endl;
return StatusCode::CANCELLED;
}
}
//acquire lock
//get file lock
if (DEBUG) cout<<"3 requesting lock "<<filename<<endl;
::grpc::StatusCode fileAccessStatus = RequestWriteAccess(filename);
if(fileAccessStatus == StatusCode::DEADLINE_EXCEEDED)
{
if (DEBUG) cout<<"3 deadline exceeded "<<filename<<endl;
return StatusCode::DEADLINE_EXCEEDED;
}
if(fileAccessStatus == StatusCode::RESOURCE_EXHAUSTED)
{
if (DEBUG) cout<<"3 resource exhausted "<<filename<<endl;
return StatusCode::RESOURCE_EXHAUSTED;
}
if(fileAccessStatus == StatusCode::CANCELLED)
{
if (DEBUG) cout<<"3 cancelled "<<filename<<endl;
return StatusCode::CANCELLED;
}
if (DEBUG) cout<<"3 acquired lock "<<filename<<endl;
/*
send the file to be deleted.
1. create stub which returns the status. look at the status. thats. it.
*/
//create context.
::grpc::ClientContext clientContext;
//create deadline
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(deadline_timeout);
clientContext.set_deadline(deadline);
//Create request
dfs_service::Msg request;
request.set_msgval(filename);
//response
dfs_service::Msg response;
//call method
Status serverStatus = service_stub->deleteFile(&clientContext,request,&response);
//delete if exists
if (exists)
remove(WrapPath(filename).c_str());
//delete from fileTable
// writeAccessMutex.lock();
auto itr = fileTable.mutable_mapval()->find(filename);
if(itr != fileTable.mutable_mapval()->end())
(*fileTable.mutable_mapval()).erase(filename);
// writeAccessMutex.unlock();
//OK, NOTFOund, deadline and other
if (serverStatus.error_code() == StatusCode::OK)
{
if(DEBUG) cout<<"3 status ok "<<filename<<endl;
return StatusCode::OK;
}
else if (serverStatus.error_code() == StatusCode::NOT_FOUND)
{
if(DEBUG) cout<<"3 status not found"<<filename<<endl;
return StatusCode::NOT_FOUND;
}
else if (serverStatus.error_code() == StatusCode::DEADLINE_EXCEEDED)
{
if(DEBUG) cout<<"3 status deadline exceeded"<<filename<<endl;
return StatusCode::DEADLINE_EXCEEDED;
}
cout<<"3 delete done "<<filename<<endl;
return StatusCode::CANCELLED;
}
grpc::StatusCode DFSClientNodeP2::List(std::map<std::string,int>* file_map, bool display) {
//
// STUDENT INSTRUCTION:
//
// Add your request to list files here. Refer to the Part 1
// student instruction for details on the basics.
//
// You can start with your Part 1 implementation and add any additional
// listing details that would be useful to your solution to the list response.
//
// The StatusCode response should be:
//
// StatusCode::OK - if all went well
// StatusCode::DEADLINE_EXCEEDED - if the deadline timeout occurs
// StatusCode::CANCELLED otherwise
//
//
if (DEBUG) cout<<"List "<<endl;
return StatusCode::OK;
}
grpc::StatusCode DFSClientNodeP2::Stat(const std::string &filename, void* file_status) {
//
// STUDENT INSTRUCTION:
//
// Add your request to get the status of a file here. Refer to the Part 1
// student instruction for details on the basics.
//
// You can start with your Part 1 implementation and add any additional
// status details that would be useful to your solution.
//
// The StatusCode response should be:
//
// StatusCode::OK - if all went well
// StatusCode::DEADLINE_EXCEEDED - if the deadline timeout occurs
// StatusCode::NOT_FOUND - if the file cannot be found on the server
// StatusCode::CANCELLED otherwise
//
//
if (DEBUG) cout<<"Stat "<<endl;
return StatusCode::OK;
}
void DFSClientNodeP2::InotifyWatcherCallback(std::function<void()> callback) {
//
// STUDENT INSTRUCTION:
//
// This method gets called each time inotify signals a change
// to a file on the file system. That is every time a file is
// modified or created.
//
// You may want to consider how this section will affect
// concurrent actions between the inotify watcher and the
// asynchronous callbacks associated with the server.
//
// The callback method shown must be called here, but you may surround it with
// whatever structures you feel are necessary to ensure proper coordination
// between the async and watcher threads.
//
// Hint: how can you prevent race conditions between this thread and
// the async thread when a file event has been signaled?
//
{
std::lock_guard<std::mutex> lock(Function3);
// std::lock_guard<std::mutex> lock(functionMutex);
if (!loadedFromMountStatus)
{
loadMountFiles();
loadedFromMountStatus = true;
}
// std::lock_guard<std::mutex> lock(writeAccessMutex);
// functionMutex.lock();
if (DEBUG) cout<<"Inotify callback"<<endl;
callback();
// functionMutex.unlock();
}
}
//
// STUDENT INSTRUCTION:
//
// This method handles the gRPC asynchronous callbacks from the server.
// We've provided the base structure for you, but you should review
// the hints provided in the STUDENT INSTRUCTION sections below
// in order to complete this method.
//
void DFSClientNodeP2::HandleCallbackList() {
if (!loadedFromMountStatus)
{
loadMountFiles();
loadedFromMountStatus = true;
}
if(DEBUG) cout<<"Handle Callback List"<<endl;
void* tag;
bool ok = false;
//
// STUDENT INSTRUCTION:
//
// Add your file list synchronization code here.
//
// When the server responds to an asynchronous request for the CallbackList,
// this method is called. You should then synchronize the
// files between the server and the client based on the goals
// described in the readme.
//
// In addition to synchronizing the files, you'll also need to ensure
// that the async thread and the file watcher thread are cooperating. These
// two threads could easily get into a race condition where both are trying
// to write or fetch over top of each other. So, you'll need to determine
// what type of locking/guarding is necessary to ensure the threads are
// properly coordinated.
//
// Block until the next result is available in the completion queue.
while (completion_queue.Next(&tag, &ok)) {
{
//
// STUDENT INSTRUCTION:
//
// Consider adding a critical section or RAII style lock here
//
std::lock_guard<std::mutex> lock(Function3);
// std::lock_guard<std::mutex> lock(writeAccessMutex);
// functionMutex.lock();
// if(DEBUG) cout<<"Handle Callback List returned"<<endl;
// The tag is the memory location of the call_data object
AsyncClientData<FileListResponseType> *call_data = static_cast<AsyncClientData<FileListResponseType> *>(tag);
dfs_log(LL_DEBUG2) << "Received completion queue callback";
// Verify that the request was completed successfully. Note that "ok"
// corresponds solely to the request for updates introduced by Finish().
// GPR_ASSERT(ok);
if (!ok) {
dfs_log(LL_ERROR) << "Completion queue callback not ok.";
}
if (ok && call_data->status.ok()) {
dfs_log(LL_DEBUG3) << "Handling async callback ";
//
// STUDENT INSTRUCTION:
//
// Add your handling of the asynchronous event calls here.
// For example, based on the file listing returned from the server,
// how should the client respond to this updated information?
// Should it retrieve an updated version of the file?
// Send an update to the server?
// Do nothing?
//
auto itr = ((call_data->reply).mutable_mapval())->begin();
// dfs_service::FileMap thisMap = (*call_data);
/*
check the received map against clients.
if client didn't have an entry or if mtime of client is older than that in the received map, issue fetch.
if server didn't have an entry or if mtime of server is older than that of client, issue store.
if server wanted the clinet to delete a file, it should keep a table entry with a unique state.
*/
//for each element in server map, if there is no element or if mtime is less, fetch.
int i = 1;
while(itr != ((call_data->reply).mutable_mapval())->end())
{
// auto findInClient = (fileTable.mutable_mapval())->find(*(*itr).mutable_name()));
// cout<<i++<<" server entry "<<(itr->first)<<" deleted "<<(itr->second).todelete() << endl;
// writeAccessMutex.lock();
auto findInClient = (fileTable.mutable_mapval())->find(itr->first);
//not found
if(findInClient == (fileTable.mutable_mapval())->end() )
{
// writeAccessMutex.unlock();
if( !(itr->second).todelete())
{
cout<<itr->first<<" async not found in client, need to fetch"<<endl;
Fetch(itr->first);
}
}
else{
//found
//need to update server
int clientCRC = (findInClient->second).crc();
int serverCRC = (itr->second).crc();
//check for files to be deleted
if( (itr->second).todelete())
{
//remove file from local dir
if(isServerDelete(itr->first))
{
(findInClient->second).set_todelete(false);
string wholePath = WrapPath(itr->first);
cout<<"async removing file "<<(itr->first)<<" "<<wholePath<<endl;
// remove(wholePath.c_str());
// (*fileTable.mutable_mapval()).erase(itr->first);
// writeAccessMutex.unlock();
Delete(itr->first);
}
}
else if(clientCRC != serverCRC)
{
if ( (findInClient->second).mtime() > ((itr->second).mtime()))
{
cout<<" file "<<itr->first<<"async updating server with mtime "<< (itr->second).mtime() <<" clinet "<<(findInClient->second).mtime()<<endl;
// writeAccessMutex.unlock();
Store(itr->first);
}else if ((findInClient->second).mtime() < ((itr->second).mtime()))
{
cout<<" file "<<itr->first<<"async updating client, server with mtime "<< (itr->second).mtime() <<" clinet "<<(findInClient->second).mtime()<<endl;
// writeAccessMutex.unlock();
Fetch(itr->first);
}
else if ((findInClient->second).mtime() == ((itr->second).mtime()))
{
//do nothing
// writeAccessMutex.unlock();
}
}
else if(clientCRC == serverCRC)
{
// cout<<"the file "<<itr->first<<" is same in both"<<endl;
// writeAccessMutex.unlock();
}
}
itr++;
}
//need to look for entries in client which are not in the server
// writeAccessMutex.lock();
auto citr = (fileTable.mutable_mapval())->begin();
// writeAccessMutex.unlock();
if(citr != (fileTable.mutable_mapval())->end()){
while(citr != (fileTable.mutable_mapval()->end()))
{
//for the entries not present in server.
auto sitr = (call_data->reply).mutable_mapval()->find(citr->first);
if (sitr == ((call_data->reply).mutable_mapval()->end()))
{
cout<<"file "<<citr->first<<"async not found in server "<<endl;
Store(citr->first);
}
citr++;
}
}
} else {
dfs_log(LL_ERROR) << "Status was not ok. Will try again in " << DFS_RESET_TIMEOUT << " milliseconds.";
dfs_log(LL_ERROR) << call_data->status.error_message();
std::this_thread::sleep_for(std::chrono::milliseconds(DFS_RESET_TIMEOUT));
}
// Once we're complete, deallocate the call_data object.
delete call_data;
//
// STUDENT INSTRUCTION:
//
// Add any additional syncing/locking mechanisms you may need here
// functionMutex.unlock();
}
// Start the process over and wait for the next callback response
dfs_log(LL_DEBUG3) << "Calling InitCallbackList";
InitCallbackList();
}
}
/**
* This method will start the callback request to the server, requesting
* an update whenever the server sees that files have been modified.
*
* We're making use of a template function here, so that we can keep some
* of the more intricate workings of the async process out of the way, and
* give you a chance to focus more on the project's requirements.
*/
void DFSClientNodeP2::InitCallbackList() {
// if(DEBUG) cout<<"call back list "<<endl;
CallbackList<FileRequestType, FileListResponseType>();
}
//
// STUDENT INSTRUCTION:
//
// Add any additional code you need to here
//
|
ecb4648191216678dd7ce8d6d2e8b7197adc1fe5
|
c9426c0b6919f2aeee9f7ed43771d531b6d8ca59
|
/DiabloUI/selhero.cpp
|
2250407a11311b888e89095bb40f0aa0f809a9d7
|
[
"Unlicense",
"LicenseRef-scancode-public-domain"
] |
permissive
|
seritools/devil-nightly
|
d90902ae3983aa9e4bbde619d9a1f5e7e0dd3758
|
78e0cd3e49029fd9f05c9431b26a6fcb3b2693ae
|
refs/heads/master
| 2020-03-26T22:02:06.902318
| 2018-09-17T20:50:13
| 2018-09-17T20:50:13
| 145,426,445
| 1
| 0
|
Unlicense
| 2018-08-20T14:10:33
| 2018-08-20T14:10:33
| null |
UTF-8
|
C++
| false
| false
| 24,088
|
cpp
|
selhero.cpp
|
// ref: 0x1000B7A0
int SelHero_1000B7A0() { return 0; }
/* {
return dword_1002A458;
} */
// 1002A458: using guessed type int dword_1002A458;
// ref: 0x1000B7A6
int SelHero_1000B7A6() { return 0; }
/* {
return dword_1002A428;
} */
// 1002A428: using guessed type int dword_1002A428;
// ref: 0x1000B7AC
void UNKCALL SelHero_1000B7AC(void *arg) { return; }
/* {
dword_1002A420 = (int)arg;
} */
// 1002A420: using guessed type int dword_1002A420;
// ref: 0x1000B7B3
char *SelHero_1000B7B3() { return 0; }
/* {
return &byte_1002A440;
} */
// ref: 0x1000B7B9
void *SelHero_1000B7B9() { return 0; }
/* {
return SMemAlloc(44, "C:\\Src\\Diablo\\DiabloUI\\SelHero.cpp", 123, 0);
} */
// 10010364: using guessed type int __stdcall SMemAlloc(_DWORD, _DWORD, _DWORD, _DWORD);
// ref: 0x1000B7CA
int SelHero_1000B7CA() { return 0; }
/* {
return dword_1002A48C;
} */
// 1002A48C: using guessed type int dword_1002A48C;
// ref: 0x1000B7D0
int __fastcall SelHero_1000B7D0(int a1, int a2) { return 0; }
/* {
return dword_1002A410(a1, a2);
} */
// 1002A410: using guessed type int (__stdcall *dword_1002A410)(_DWORD, _DWORD);
// ref: 0x1000B7DE
signed int SelHero_1000B7DE() { return 0; }
/* {
signed int result; // eax
result = 2139095040;
dword_1002A414 = 2139095040;
return result;
} */
// 1002A414: using guessed type int dword_1002A414;
// ref: 0x1000B899
int __fastcall SelHero_1000B899(HWND hDlg, int a2) { return 0; }
/* {
int v2; // ebx
HWND v3; // esi
struct tagRECT Rect; // [esp+8h] [ebp-10h]
v2 = a2;
v3 = GetDlgItem(hDlg, 1040);
InvalidateRect(v3, 0, 0);
GetClientRect(v3, &Rect);
local_10007A68(&Rect, 0, v2 * Rect.bottom);
return SDlgSetBitmapI(v3, 0, "Static", -1, 1, dword_1002A498, &Rect, dword_1002A418, dword_1002A41C, -1);
} */
// 10010400: using guessed type int __stdcall SDlgSetBitmapI(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
// 1002A418: using guessed type int dword_1002A418;
// 1002A41C: using guessed type int dword_1002A41C;
// 1002A498: using guessed type int dword_1002A498;
// ref: 0x1000B905
int __fastcall SelHero_1000B905(HWND hDlg, int a2) { return 0; }
/* {
HWND v2; // ebp
HWND v3; // eax
int v4; // eax
HWND v5; // eax
int v6; // eax
HWND v7; // eax
int v8; // eax
HWND v9; // eax
int v10; // eax
HWND v11; // eax
int v12; // eax
int result; // eax
int v14; // esi
HWND v15; // edi
HWND v16; // ebp
int v17; // eax
HWND hWnd; // ST1C_4
int v19; // eax
HWND v20; // ST1C_4
int v21; // eax
HWND v22; // ST1C_4
int v23; // eax
HWND v24; // ST1C_4
int v25; // eax
HWND hDlga; // [esp+Ch] [ebp-4h]
v14 = a2;
v15 = hDlg;
hDlga = hDlg;
if ( *(_WORD *)(a2 + 20) )
{
dword_1002A424 = *(_DWORD *)(a2 + 36);
strcpy(&byte_1002A440, (const char *)(a2 + 4));
v16 = GetDlgItem(v15, 1014);
wsprintfA(byte_1002A42C, "%d", *(unsigned short *)(v14 + 20));
v17 = GetWindowLongA(v16, -21);
local_10007FA4(v17, byte_1002A42C);
hWnd = GetDlgItem(hDlga, 1018);
wsprintfA(byte_1002A490, "%d", *(unsigned short *)(v14 + 24));
v19 = GetWindowLongA(hWnd, -21);
local_10007FA4(v19, byte_1002A490);
v20 = GetDlgItem(hDlga, 1017);
wsprintfA(byte_1002A43C, "%d", *(unsigned short *)(v14 + 26));
v21 = GetWindowLongA(v20, -21);
local_10007FA4(v21, byte_1002A43C);
v22 = GetDlgItem(hDlga, 1016);
wsprintfA(byte_1002A454, "%d", *(unsigned short *)(v14 + 28));
v23 = GetWindowLongA(v22, -21);
local_10007FA4(v23, byte_1002A454);
v24 = GetDlgItem(hDlga, 1015);
wsprintfA(byte_1002A494, "%d", *(unsigned short *)(v14 + 30));
v25 = GetWindowLongA(v24, -21);
local_10007FA4(v25, byte_1002A494);
SelHero_1000B899(hDlga, *(unsigned char *)(v14 + 22));
result = Doom_10006A13(hDlga, (int *)&unk_10023020, 1);
}
else
{
dword_1002A424 = 0;
byte_1002A440 = 0;
v2 = hDlg;
v3 = GetDlgItem(hDlg, 1014);
v4 = GetWindowLongA(v3, -21);
local_10007FA4(v4, "--");
v5 = GetDlgItem(v2, 1018);
v6 = GetWindowLongA(v5, -21);
local_10007FA4(v6, "--");
v7 = GetDlgItem(v2, 1017);
v8 = GetWindowLongA(v7, -21);
local_10007FA4(v8, "--");
v9 = GetDlgItem(v2, 1016);
v10 = GetWindowLongA(v9, -21);
local_10007FA4(v10, "--");
v11 = GetDlgItem(v2, 1015);
v12 = GetWindowLongA(v11, -21);
local_10007FA4(v12, "--");
SelHero_1000B899(v2, 3);
result = Doom_10006A13(v2, (int *)&unk_10023020, 1);
}
return result;
} */
// 1002A424: using guessed type int dword_1002A424;
// ref: 0x1000BA7B
HWND __fastcall SelHero_1000BA7B(HWND hDlg, const char *a2) { return 0; }
/* {
HWND v2; // esi
const char *v3; // edi
HWND result; // eax
int v5; // eax
v2 = hDlg;
v3 = a2;
result = GetDlgItem(hDlg, 1038);
if ( result )
{
v5 = GetWindowLongA(result, -21);
local_10007FA4(v5, v3);
result = (HWND)Doom_10006A13(v2, (int *)&unk_10023000, 5);
}
return result;
} */
// ref: 0x1000BAB4
char *UNKCALL SelHero_1000BAB4(char *arg) { return 0; }
/* {
UINT v1; // esi
char *result; // eax
CHAR SrcStr; // [esp+4h] [ebp-90h]
CHAR Buffer; // [esp+84h] [ebp-10h]
strcpy(&SrcStr, arg);
_strlwr(&SrcStr);
v1 = 19;
while ( 1 )
{
LoadStringA(hInstance, v1, &Buffer, 15);
SelHero_1000BB26(&Buffer);
_strlwr(&Buffer);
result = strstr(&SrcStr, &Buffer);
if ( result )
break;
if ( (signed int)++v1 > 26 )
return result;
}
return (char *)1;
} */
// ref: 0x1000BB26
char __fastcall SelHero_1000BB26(char *a1) { return 0; }
/* {
char result; // al
while ( 1 )
{
result = *a1;
if ( !*a1 )
break;
*a1++ = result - 1;
}
return result;
} */
// ref: 0x1000BB34
int __fastcall SelHero_1000BB34(char *a1, char *a2) { return 0; }
/* {
char *v2; // esi
char *v3; // edi
char v5; // al
v2 = a1;
v3 = a2;
if ( strpbrk(a1, ",<>%&\\\"?*#/:") || strpbrk(v2, v3) )
return 1;
while ( 1 )
{
v5 = *v2;
if ( !*v2 )
break;
if ( (unsigned char)v5 < 0x20u || (unsigned char)v5 > 0x7Eu && (unsigned char)v5 < 0xC0u )
return 1;
++v2;
}
return 0;
} */
// ref: 0x1000BB75
int __stdcall UiValidPlayerName(char *arg) { return 0; }
/* {
char *v1; // esi
signed int v2; // edi
v1 = arg;
v2 = 1;
if ( !strlen(arg) )
v2 = 0;
if ( dword_1002A48C == 1 && (SelHero_1000BAB4(v1) || SelHero_1000BB34(v1, " ")) )
v2 = 0;
return v2;
} */
// 1002A48C: using guessed type int dword_1002A48C;
// ref: 0x1000BBB4
int __stdcall UiSelHeroMultDialog(void *fninfo, void *fncreate, void *fnremove, void *fnstats, int *a5, int *a6, char *name) { return 0; }
/* {
int v7; // eax
int v8; // eax
artfont_10001159();
dword_1002A438 = (int (__stdcall *)(_DWORD))a1;
dword_1002A450 = (int (UNKCALL *)(_DWORD, _DWORD))a2;
dword_1002A434 = (int (__stdcall *)(_DWORD))a3;
dword_1002A410 = (int (__stdcall *)(_DWORD, _DWORD))a4;
dword_1002A458 = 0;
dword_1002A48C = 1;
dword_1002A45C = 0;
v7 = SDrawGetFrameWindow();
v8 = SDlgDialogBoxParam(hInstance, "SELHERO_DIALOG", v7, SelHero_1000BC46, 0);
if ( a5 )
*(_DWORD *)a5 = v8;
if ( a7 )
strcpy(a7, &byte_1002A440);
if ( a6 )
*(_DWORD *)a6 = dword_1002A45C;
return 1;
} */
// 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
// 10010382: using guessed type _DWORD __stdcall SDrawGetFrameWindow();
// 1002A410: using guessed type int (__stdcall *dword_1002A410)(_DWORD, _DWORD);
// 1002A434: using guessed type int (__stdcall *dword_1002A434)(_DWORD);
// 1002A438: using guessed type int (__stdcall *dword_1002A438)(_DWORD);
// 1002A450: using guessed type int (UNKCALL *dword_1002A450)(_DWORD, _DWORD);
// 1002A458: using guessed type int dword_1002A458;
// 1002A45C: using guessed type int dword_1002A45C;
// 1002A48C: using guessed type int dword_1002A48C;
// ref: 0x1000BC46
int __stdcall SelHero_1000BC46(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { return 0; }
/* {
HWND v4; // eax
int v6; // edx
HWND v7; // ecx
signed int v8; // [esp-4h] [ebp-8h]
int v9; // [esp+0h] [ebp-4h]
if ( Msg > 0xBD2 )
{
switch ( Msg )
{
case 0xBD3u:
SelHero_1000C21A(hWnd);
return 0;
case 0xBD4u:
SelHero_1000C269(hWnd);
return 0;
case 0xBD5u:
v7 = hWnd;
if ( dword_1002A48C != 1 )
{
v8 = 2;
goto LABEL_30;
}
break;
case 0xBD6u:
strcpy(&byte_1002A440, byte_1002A464);
v6 = 1;
v7 = hWnd;
if ( dword_1002A48C != 1 )
{
dword_1002A420 = 0;
LABEL_31:
SelHero_1000C3E2((int)v7, v6);
return 0;
}
break;
case 0xBD7u:
SelHero_1000BDAD(hWnd);
return 0;
default:
return SDlgDefDialogProc(hWnd, Msg, wParam, lParam);
}
v8 = 3;
LABEL_30:
v6 = v8;
goto LABEL_31;
}
if ( Msg == 3026 )
{
SelHero_1000C09B(hWnd);
return 0;
}
if ( Msg == 2 )
{
SelHero_1000C364(hWnd);
return SDlgDefDialogProc(hWnd, Msg, wParam, lParam);
}
if ( Msg <= 0x103 )
return SDlgDefDialogProc(hWnd, Msg, wParam, lParam);
if ( Msg <= 0x105 )
{
v4 = (HWND)SDrawGetFrameWindow();
SendMessageA(v4, Msg, wParam, lParam);
return SDlgDefDialogProc(hWnd, Msg, wParam, lParam);
}
switch ( Msg )
{
case 0x110u:
SelHero_1000C3FF(hWnd);
PostMessageA(hWnd, 0x7E8u, 0, 0);
return 0;
case 0x7E8u:
if ( !Fade_1000739F() )
Fade_100073FD(hWnd, v9);
return 0;
case 0xBD0u:
SelHero_1000BF6D(hWnd);
return 0;
}
if ( Msg != 3025 )
return SDlgDefDialogProc(hWnd, Msg, wParam, lParam);
SelHero_1000BFF9(hWnd);
return 0;
} */
// 1001037C: using guessed type int __stdcall SDlgDefDialogProc(_DWORD, _DWORD, _DWORD, _DWORD);
// 10010382: using guessed type _DWORD __stdcall SDrawGetFrameWindow();
// 1002A420: using guessed type int dword_1002A420;
// 1002A48C: using guessed type int dword_1002A48C;
// ref: 0x1000BDAD
BOOL UNKCALL SelHero_1000BDAD(HWND arg) { return 0; }
/* {
const char *v1; // eax
CHAR v3; // [esp+Ch] [ebp-B4h]
CHAR v4; // [esp+5Ch] [ebp-64h]
CHAR Buffer; // [esp+9Ch] [ebp-24h]
HWND hWnd; // [esp+BCh] [ebp-4h]
hWnd = arg;
if ( SelHero_1000B7CA() == 1 )
LoadStringA(hInstance, 0x23u, &Buffer, 31);
else
LoadStringA(hInstance, 0x22u, &Buffer, 31);
LoadStringA(hInstance, 7u, &v4, 63);
wsprintfA(&v3, &v4, &byte_1002A440);
if ( SelYesNo_1000FA49((int)hWnd, &v3, (int)&Buffer, 1) != 2 )
{
v1 = SelHero_1000BF4A((const char *)dword_1002A458, &byte_1002A440);
if ( v1 )
{
if ( dword_1002A434(v1) )
{
dword_1002A458 = (int)SelHero_1000BEDB((int *)dword_1002A458, &byte_1002A440);
--dword_1002A428;
LoadStringA(hInstance, 0x1Eu, &v4, 15);
if ( !strcmp(&v4, (const char *)(dword_1002A458 + 4)) )
return PostMessageA(hWnd, 0xBD1u, 0, 0);
SelHero_1000B905(hWnd, dword_1002A458);
}
else
{
LoadStringA(hInstance, 0x11u, &v4, 63);
SelYesNo_1000FD39((int)hWnd, &v4, (int)&Buffer, 1);
}
}
}
return PostMessageA(hWnd, 0xBD0u, 0, 0);
} */
// 1002A428: using guessed type int dword_1002A428;
// 1002A434: using guessed type int (__stdcall *dword_1002A434)(_DWORD);
// 1002A458: using guessed type int dword_1002A458;
// ref: 0x1000BEDB
int *__fastcall SelHero_1000BEDB(int *a1, char *a2) { return 0; }
/* {
int *v2; // ebx
_DWORD *v3; // ebp
_DWORD *v4; // edi
int *v5; // esi
char *v7; // [esp+10h] [ebp-4h]
v2 = a1;
v3 = 0;
v4 = 0;
v7 = a2;
v5 = a1;
if ( a1 )
{
while ( !v4 )
{
if ( !strcmp((const char *)v5 + 4, v7) )
{
v4 = v5;
}
else
{
v3 = v5;
v5 = (int *)*v5;
}
if ( !v5 )
{
if ( !v4 )
return v2;
break;
}
}
if ( v3 )
*v3 = *v4;
else
v2 = (int *)*v4;
SelHero_1000BF33(v4);
}
return v2;
} */
// ref: 0x1000BF33
int UNKCALL SelHero_1000BF33(void *arg) { return 0; }
/* {
int result; // eax
if ( arg )
result = SMemFree(arg, "C:\\Src\\Diablo\\DiabloUI\\SelHero.cpp", 131, 0);
return result;
} */
// 10010340: using guessed type int __stdcall SMemFree(_DWORD, _DWORD, _DWORD, _DWORD);
// ref: 0x1000BF4A
const char *__fastcall SelHero_1000BF4A(const char *a1, const char *a2) { return 0; }
/* {
const char *v2; // edi
const char *i; // esi
v2 = a2;
for ( i = a1; i && _strcmpi(i + 4, v2); i = *(const char **)i )
;
return i;
} */
// ref: 0x1000BF6D
int UNKCALL SelHero_1000BF6D(HWND hWnd) { return 0; }
/* {
HWND v1; // esi
int v2; // eax
int v4; // edx
v1 = hWnd;
v2 = SDlgDialogBoxParam(hInstance, "SELLIST_DIALOG", hWnd, SelList_1000D774, 0);
if ( v2 == 1 )
{
if ( !strlen(&byte_1002A440) )
return PostMessageA(v1, 0xBD1u, 0, 0);
if ( dword_1002A48C == 1 )
return PostMessageA(v1, 0xBD5u, 0, 0);
if ( dword_1002A424 )
return PostMessageA(v1, 0xBD3u, 0, 0);
dword_1002A420 = 0;
v4 = 1;
return SelHero_1000C3E2((int)v1, v4);
}
if ( v2 != 1006 )
{
v4 = 4;
return SelHero_1000C3E2((int)v1, v4);
}
return PostMessageA(v1, 0xBD7u, 0, 0);
} */
// 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
// 1002A420: using guessed type int dword_1002A420;
// 1002A424: using guessed type int dword_1002A424;
// 1002A48C: using guessed type int dword_1002A48C;
// ref: 0x1000BFF9
int UNKCALL SelHero_1000BFF9(HWND hWnd) { return 0; }
/* {
HWND v1; // esi
int v2; // eax
int v3; // eax
int result; // eax
CHAR Buffer; // [esp+8h] [ebp-20h]
v1 = hWnd;
v2 = SDlgDialogBoxParam(hInstance, "SELCLASS_DIALOG", hWnd, SelClass_10009D66, 0);
if ( v2 == -1 || v2 == 2 )
{
LoadStringA(hInstance, 0x1Eu, &Buffer, 31);
if ( !strcmp(&Buffer, (const char *)(dword_1002A458 + 4)) )
result = SelHero_1000C3E2((int)v1, 4);
else
result = PostMessageA(v1, 0xBD0u, 0, 0);
}
else
{
v3 = v2 - 1063;
if ( v3 )
{
if ( v3 == 1 )
byte_1002A476 = 2;
else
byte_1002A476 = 0;
}
else
{
byte_1002A476 = 1;
}
result = PostMessageA(v1, 0xBD2u, 0, 0);
}
return result;
} */
// 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
// 1002A458: using guessed type int dword_1002A458;
// 1002A476: using guessed type char byte_1002A476;
// ref: 0x1000C09B
int UNKCALL SelHero_1000C09B(HWND hWnd) { return 0; }
/* {
HWND v1; // esi
int result; // eax
char v3; // [esp+8h] [ebp-10h]
char v4; // [esp+17h] [ebp-1h]
v1 = hWnd;
if ( SDlgDialogBoxParam(hInstance, "ENTERNAME_DIALOG", hWnd, EntName_10006F7C, &v3) != 1 )
return PostMessageA(v1, 0xBD1u, 0, 0);
v4 = 0;
if ( SelHero_1000C0F9((int)v1, &v3) )
result = PostMessageA(v1, 0xBD6u, 0, 0);
else
result = PostMessageA(v1, 0xBD2u, 0, 0);
return result;
} */
// 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
// ref: 0x1000C0F9
signed int __fastcall SelHero_1000C0F9(int a1, char *a2) { return 0; }
/* {
const char *v2; // edi
int v3; // ST0C_4
CHAR v5; // [esp+Ch] [ebp-138h]
CHAR v6; // [esp+9Ch] [ebp-A8h]
CHAR Buffer; // [esp+11Ch] [ebp-28h]
int v8; // [esp+13Ch] [ebp-8h]
char *v9; // [esp+140h] [ebp-4h]
v9 = a2;
v8 = a1;
if ( SelHero_1000B7CA() == 1 )
LoadStringA(hInstance, 0x20u, &Buffer, 31);
else
LoadStringA(hInstance, 0x1Fu, &Buffer, 31);
if ( !UiValidPlayerName(v9) )
{
LoadStringA(hInstance, 0xFu, &v6, 127);
SelYesNo_1000FD39(v8, &v6, (int)&Buffer, 1);
return 0;
}
v2 = SelHero_1000BF4A((const char *)dword_1002A458, v9);
if ( v2 )
{
LoadStringA(hInstance, 8u, &v6, 127);
wsprintfA(&v5, &v6, v2 + 4);
if ( SelYesNo_1000FA49(v8, &v5, (int)&Buffer, 1) == 2 )
return 0;
}
strcpy(byte_1002A464, v9);
dword_1002A484 = 0;
if ( !dword_1002A450(v3, &unk_1002A460) )
{
LoadStringA(hInstance, 0x10u, &v6, 127);
OkCancel_1000930A(v8, (int)&v6, 1);
return 0;
}
dword_1002A45C = 1;
return 1;
} */
// 1002A450: using guessed type int (UNKCALL *dword_1002A450)(_DWORD, _DWORD);
// 1002A458: using guessed type int dword_1002A458;
// 1002A45C: using guessed type int dword_1002A45C;
// 1002A484: using guessed type int dword_1002A484;
// ref: 0x1000C21A
BOOL UNKCALL SelHero_1000C21A(HWND hWnd) { return 0; }
/* {
HWND v1; // esi
int v2; // eax
v1 = hWnd;
v2 = SDlgDialogBoxParam(hInstance, "SELLOAD_DIALOG", hWnd, SelLoad_1000E1C2, 0);
if ( v2 == -1 || v2 == 2 )
return PostMessageA(v1, 0xBD0u, 0, 0);
if ( v2 == 1106 )
return PostMessageA(v1, 0xBD5u, 0, 0);
return PostMessageA(v1, 0xBD4u, 0, 0);
} */
// 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
// ref: 0x1000C269
int UNKCALL SelHero_1000C269(HWND hWnd) { return 0; }
/* {
HWND v1; // ebx
int v2; // ecx
const char *v4; // eax
int v5; // eax
CHAR Buffer; // [esp+4h] [ebp-208h]
char v7; // [esp+104h] [ebp-108h]
char v8; // [esp+184h] [ebp-88h]
char v9; // [esp+204h] [ebp-8h]
char v10; // [esp+208h] [ebp-4h]
v1 = hWnd;
if ( !SelHero_1000B7CA() )
{
SelHero_1000B7AC(0);
v2 = (int)v1;
return SelHero_1000C3E2(v2, 1);
}
CreaDung_10004C33((void *)1);
if ( SDlgDialogBoxParam(hInstance, "SELDIFF_DIALOG", v1, CreaDung_10004C4A, dword_1002A48C) != 1 )
return PostMessageA(v1, 0xBD3u, 0, 0);
v4 = SelHero_1000BF4A((const char *)dword_1002A458, &byte_1002A440);
UiCreatePlayerDescription((int)v4, 1145195599, (int)&v8);
v10 = dword_1002A420;
Connect_10003E0C((int)&v9, &byte_1002A440, &v8, &v7, 128);
v5 = UiAuthCallback(2, (int)&byte_1002A440, &v8, 0, &v7, &Buffer, 256);
v2 = (int)v1;
if ( v5 )
return SelHero_1000C3E2(v2, 1);
SelYesNo_1000FD39((int)v1, &Buffer, 0, 1);
return PostMessageA(v1, 0xBD4u, 0, 0);
} */
// 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
// 1002A420: using guessed type int dword_1002A420;
// 1002A458: using guessed type int dword_1002A458;
// 1002A48C: using guessed type int dword_1002A48C;
// ref: 0x1000C364
void UNKCALL SelHero_1000C364(HWND hDlg) { return; }
/* {
HWND v1; // esi
_DWORD *v2; // eax
v1 = hDlg;
Doom_10006C53(hDlg, (int *)&unk_10023020);
Doom_10006C53(v1, (int *)&unk_10023008);
Doom_10006C53(v1, (int *)&unk_10023000);
Title_100100E7(v1);
SelHero_1000C3CE((_DWORD *)dword_1002A458);
if ( dword_1002A498 )
{
SMemFree(dword_1002A498, "C:\\Src\\Diablo\\DiabloUI\\SelHero.cpp", 744, 0);
dword_1002A498 = 0;
}
v2 = (_DWORD *)GetWindowLongA(v1, -21);
local_10007F72(v2);
} */
// 10010340: using guessed type int __stdcall SMemFree(_DWORD, _DWORD, _DWORD, _DWORD);
// 1002A458: using guessed type int dword_1002A458;
// 1002A498: using guessed type int dword_1002A498;
// ref: 0x1000C3CE
int __fastcall SelHero_1000C3CE(_DWORD *a1) { return 0; }
/* {
_DWORD *v1; // esi
int result; // eax
if ( a1 )
{
do
{
v1 = (_DWORD *)*a1;
result = SelHero_1000BF33(a1);
a1 = v1;
}
while ( v1 );
}
return result;
} */
// ref: 0x1000C3E2
int __fastcall SelHero_1000C3E2(int a1, int a2) { return 0; }
/* {
int v2; // edi
int v3; // esi
v2 = a2;
v3 = a1;
Fade_100073B4();
Fade_100072BE(10);
return SDlgEndDialog(v3, v2);
} */
// 10010376: using guessed type int __stdcall SDlgEndDialog(_DWORD, _DWORD);
// ref: 0x1000C3FF
int UNKCALL SelHero_1000C3FF(HWND hWnd) { return 0; }
/* {
HWND v1; // eax
int v2; // eax
HWND v3; // eax
int v4; // eax
HWND v5; // eax
int v6; // eax
HWND v7; // eax
int v8; // eax
HWND v9; // eax
int v10; // eax
HWND v12; // esi
int v13; // eax
int *v14; // edi
void *v15; // [esp+0h] [ebp-8h]
HWND v16; // [esp+0h] [ebp-8h]
v12 = hWnd;
SelHero_1000C49F(hWnd, v15);
v13 = local_10007F46();
v14 = (int *)v13;
if ( v13 )
{
SetWindowLongA(v12, -21, v13);
local_10007944((int)v12, 0, &byte_10029448, -1, 1, (int)"ui_art\\selhero.pcx", v14, v14 + 1, 0);
Fade_100073C5(v12, 1);
}
local_100078BE((int)"ui_art\\heros.pcx", &dword_1002A498, &dword_1002A418);
SetActiveWindow(v12);
Title_1001009E(v12, (int)"ui_art\\smlogo.pcx", v16);
Doom_100068AB(v12, (int *)&unk_10023000, 5);
Doom_100068AB(v12, (int *)&unk_10023008, 1);
Doom_100068AB(v12, (int *)&unk_10023020, 1);
dword_1002A424 = 0;
byte_1002A440 = 0;
v1 = GetDlgItem(v12, 1014);
v2 = GetWindowLongA(v1, -21);
local_10007FA4(v2, "--");
v3 = GetDlgItem(v12, 1018);
v4 = GetWindowLongA(v3, -21);
local_10007FA4(v4, "--");
v5 = GetDlgItem(v12, 1017);
v6 = GetWindowLongA(v5, -21);
local_10007FA4(v6, "--");
v7 = GetDlgItem(v12, 1016);
v8 = GetWindowLongA(v7, -21);
local_10007FA4(v8, "--");
v9 = GetDlgItem(v12, 1015);
v10 = GetWindowLongA(v9, -21);
local_10007FA4(v10, "--");
SelHero_1000B899(v12, 3);
return Doom_10006A13(v12, (int *)&unk_10023020, 1);
} */
// 1002A418: using guessed type int dword_1002A418;
// 1002A424: using guessed type int dword_1002A424;
// 1002A498: using guessed type int dword_1002A498;
// ref: 0x1000C49F
BOOL UNKCALL SelHero_1000C49F(HWND hWnd, void *a2) { return 0; }
/* {
HWND v2; // ebx
int v3; // esi
BOOL result; // eax
int v5; // [esp+10h] [ebp-44h]
CHAR Buffer; // [esp+14h] [ebp-40h]
v2 = hWnd;
v3 = SelHero_1000B7B9();
*(_DWORD *)v3 = 0;
LoadStringA(hInstance, 0x1Eu, (LPSTR)(v3 + 4), 15);
*(_WORD *)(v3 + 20) = 0;
dword_1002A458 = (int)SelRegn_1000EF56(dword_1002A458, (_DWORD *)v3);
v5 = dword_1002A458;
dword_1002A428 = 1;
if ( !dword_1002A438(SelHero_1000C541) )
{
LoadStringA(hInstance, 0x12u, &Buffer, 64);
OkCancel_1000930A((int)v2, (int)&Buffer, 1);
}
if ( v5 == dword_1002A458 )
result = PostMessageA(v2, 0xBD1u, 0, 0);
else
result = PostMessageA(v2, 0xBD0u, 0, 0);
return result;
} */
// 1002A428: using guessed type int dword_1002A428;
// 1002A438: using guessed type int (__stdcall *dword_1002A438)(_DWORD);
// 1002A458: using guessed type int dword_1002A458;
// ref: 0x1000C541
signed int __stdcall SelHero_1000C541(void *a1) { return 0; }
/* {
_DWORD *v1; // esi
_DWORD *v2; // eax
v1 = (_DWORD *)SelHero_1000B7B9();
memcpy(v1, a1, 0x2Cu);
*v1 = 0;
v2 = SelRegn_1000EF56(dword_1002A458, v1);
++dword_1002A428;
dword_1002A458 = (int)v2;
return 1;
} */
// 1002A428: using guessed type int dword_1002A428;
// 1002A458: using guessed type int dword_1002A458;
// ref: 0x1000C57A
int __stdcall UiSelHeroSingDialog(void *fninfo, void *fncreate, void *fnremove, void *fnstats, int *a5, char *name, int *difficulty) { return 0; }
/* {
int v7; // eax
int v8; // edi
artfont_10001159();
dword_1002A438 = (int (__stdcall *)(_DWORD))a1;
dword_1002A450 = (int (UNKCALL *)(_DWORD, _DWORD))a2;
dword_1002A434 = (int (__stdcall *)(_DWORD))a3;
dword_1002A410 = (int (__stdcall *)(_DWORD, _DWORD))a4;
dword_1002A458 = 0;
dword_1002A48C = 0;
v7 = SDrawGetFrameWindow();
v8 = SDlgDialogBoxParam(hInstance, "SELHERO_DIALOG", v7, SelHero_1000BC46, 0);
if ( a5 )
*(_DWORD *)a5 = v8;
if ( a6 )
strcpy(a6, &byte_1002A440);
if ( a7 )
*(_DWORD *)a7 = dword_1002A420;
if ( v8 != 4 )
artfont_100010C8();
return 1;
} */
// 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
// 10010382: using guessed type _DWORD __stdcall SDrawGetFrameWindow();
// 1002A410: using guessed type int (__stdcall *dword_1002A410)(_DWORD, _DWORD);
// 1002A420: using guessed type int dword_1002A420;
// 1002A434: using guessed type int (__stdcall *dword_1002A434)(_DWORD);
// 1002A438: using guessed type int (__stdcall *dword_1002A438)(_DWORD);
// 1002A450: using guessed type int (UNKCALL *dword_1002A450)(_DWORD, _DWORD);
// 1002A458: using guessed type int dword_1002A458;
// 1002A48C: using guessed type int dword_1002A48C;
|
ca38b0e54fd169688106c8a9dcfb550d628d7a2d
|
08ec40c60e13fffa6d8289c4f5e5aae0c02de983
|
/hcc_ws/devel/include/tutorial/my_service.h
|
1fb46fddab2b7f9b4e0c83f72093a325140c7513
|
[] |
no_license
|
samuel95207/ROS-Projects
|
335b31ba00ce14e0c02f70bf6ffe9f2581718bb1
|
f3fa05c3650873600c52e9b8921cb3e360cda8bc
|
refs/heads/master
| 2022-12-14T08:04:45.844776
| 2020-08-31T06:45:52
| 2020-08-31T06:45:52
| 283,133,719
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,607
|
h
|
my_service.h
|
// Generated by gencpp from file tutorial/my_service.msg
// DO NOT EDIT!
#ifndef TUTORIAL_MESSAGE_MY_SERVICE_H
#define TUTORIAL_MESSAGE_MY_SERVICE_H
#include <ros/service_traits.h>
#include <tutorial/my_serviceRequest.h>
#include <tutorial/my_serviceResponse.h>
namespace tutorial
{
struct my_service
{
typedef my_serviceRequest Request;
typedef my_serviceResponse Response;
Request request;
Response response;
typedef Request RequestType;
typedef Response ResponseType;
}; // struct my_service
} // namespace tutorial
namespace ros
{
namespace service_traits
{
template<>
struct MD5Sum< ::tutorial::my_service > {
static const char* value()
{
return "6961c189baed6807930789f82dc9e445";
}
static const char* value(const ::tutorial::my_service&) { return value(); }
};
template<>
struct DataType< ::tutorial::my_service > {
static const char* value()
{
return "tutorial/my_service";
}
static const char* value(const ::tutorial::my_service&) { return value(); }
};
// service_traits::MD5Sum< ::tutorial::my_serviceRequest> should match
// service_traits::MD5Sum< ::tutorial::my_service >
template<>
struct MD5Sum< ::tutorial::my_serviceRequest>
{
static const char* value()
{
return MD5Sum< ::tutorial::my_service >::value();
}
static const char* value(const ::tutorial::my_serviceRequest&)
{
return value();
}
};
// service_traits::DataType< ::tutorial::my_serviceRequest> should match
// service_traits::DataType< ::tutorial::my_service >
template<>
struct DataType< ::tutorial::my_serviceRequest>
{
static const char* value()
{
return DataType< ::tutorial::my_service >::value();
}
static const char* value(const ::tutorial::my_serviceRequest&)
{
return value();
}
};
// service_traits::MD5Sum< ::tutorial::my_serviceResponse> should match
// service_traits::MD5Sum< ::tutorial::my_service >
template<>
struct MD5Sum< ::tutorial::my_serviceResponse>
{
static const char* value()
{
return MD5Sum< ::tutorial::my_service >::value();
}
static const char* value(const ::tutorial::my_serviceResponse&)
{
return value();
}
};
// service_traits::DataType< ::tutorial::my_serviceResponse> should match
// service_traits::DataType< ::tutorial::my_service >
template<>
struct DataType< ::tutorial::my_serviceResponse>
{
static const char* value()
{
return DataType< ::tutorial::my_service >::value();
}
static const char* value(const ::tutorial::my_serviceResponse&)
{
return value();
}
};
} // namespace service_traits
} // namespace ros
#endif // TUTORIAL_MESSAGE_MY_SERVICE_H
|
69cc4fe91fdce5d87c23d48e754d6e01f55facd1
|
2ac71c7f3fe414113216bc42c27de916de250eb6
|
/src/render/ChunkRenderer.cpp
|
a863fdf1407335ea916ae9ff637512f9366bf4a8
|
[] |
no_license
|
thebigcx/cubeworld
|
db00562a3950f3559f71f0fc7904fc5159cf9d8d
|
5edbc48b6fc057fe796021bf1355a5713a24318d
|
refs/heads/master
| 2022-12-27T18:44:57.039618
| 2020-10-07T23:09:13
| 2020-10-07T23:09:13
| 299,471,443
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 521
|
cpp
|
ChunkRenderer.cpp
|
#include "ChunkRenderer.h"
ChunkRenderer::ChunkRenderer()
{
}
void ChunkRenderer::render(Chunk& p_chunk)
{
ResourceManager::shaders.get("block").use();
ResourceManager::shaders.get("block").setUniform("model", p_chunk.m_mesh.model);
ResourceManager::textures.get("terrainAtlas").bind();
glBindVertexArray(p_chunk.m_mesh.getVertexArray());
glDrawElements(GL_TRIANGLES, p_chunk.m_mesh.vertexCount, GL_UNSIGNED_INT, 0);
}
void ChunkRenderer::add(Mesh& mesh)
{
m_pMeshes.push_back(&mesh);
}
|
df92a8a25da84a5367a781ebcf8623d11ba2a642
|
335f7102c0a5d8d1dc3d9f94d653a51469489254
|
/src/include/error_handling/detail/Ret/RetValErrors.hpp
|
b90f74f8f87bb5d4309567d00387f60df7771d2e
|
[
"BSL-1.0"
] |
permissive
|
mdraven/error_handling
|
f4b23c535741573fab09e47ca61b6f67ec91f27f
|
eb81346d0089fb97331b9f46f2771c2b9b14d4d4
|
refs/heads/master
| 2020-05-20T14:02:14.489072
| 2014-07-20T13:25:35
| 2014-07-20T13:25:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,879
|
hpp
|
RetValErrors.hpp
|
/*
* Copyright (C) 2014 Ramil Iljasov
*
* Distributed under the Boost Software License, Version 1.0.
*
*/
#ifndef RETVALERRORS_HPP_
#define RETVALERRORS_HPP_
#include <error_handling/detail/Ret/Ret.hpp>
#include <error_handling/detail/Set/Set.hpp>
#include <error_handling/detail/EnableIfNotUniversalRef.hpp>
#include <error_handling/detail/unsafe_access_to_internal_data.hpp>
#include <error_handling/detail/Any.hpp>
#include <error_handling/detail/config.hpp>
namespace error_handling {
namespace detail {
template <class Val, class Errors>
class Ret final {
static_assert(IsSet<Errors>::value, "Second template argument must be `Set` type.");
Any<Val, Errors> any;
template <class OVal, class OErrors>
friend Any<OVal, OErrors>& unsafe_access_to_internal_data(Ret<OVal, OErrors>&) noexcept;
template <class OVal, class OErrors>
friend const Any<OVal, OErrors>& unsafe_access_to_internal_data(const Ret<OVal, OErrors>& v) noexcept;
struct Constraints {
template <class Err>
static void err(const Err&) {
static const bool is_known_error = IsContains<Errors, Err>::value;
static_assert(is_known_error, "Unknown error type");
}
template <class OVal, class OErrors>
static void retValErr(const Ret<OVal, OErrors>&) {
static const bool is_convertible_val = std::is_convertible<OVal, Val>::value;
static_assert(is_convertible_val, "Cannot convert `Val` type.");
static const bool is_more_weak = IsDifferenceEmpty<OErrors, Errors>::value;
static_assert(is_more_weak, "Assign to more strong type.");
}
template <class OVal>
static void retVal(const Ret<OVal, Set<>>&) {
static const bool is_convertible_val = std::is_convertible<OVal, Val>::value;
static_assert(is_convertible_val, "Cannot convert `Val` type.");
}
template <class OErrors>
static void retNErr(const Ret<N, OErrors>&) {
static const bool is_more_weak = IsDifferenceEmpty<OErrors, Errors>::value;
static_assert(is_more_weak, "Assign to more strong type.");
}
};
public:
Ret() noexcept(noexcept(Any<Val, Errors>())) :
any() {
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "default constructor");
}
Ret(const Val& v) noexcept(noexcept(Any<Val, Errors>(v))) :
any(v) {
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "copy constructor Val");
}
Ret(Val&& v) noexcept(noexcept(Any<Val, Errors>(std::move(v)))) :
any(std::move(v)) {
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move constructor Val");
}
template <class OErr>
Ret(const OErr& v) noexcept(noexcept(Any<Val, Errors>(v))) :
any(v) {
Constraints::err(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "copy constructor Err");
}
template <class OErr,
class = typename EnableIfNotUniversalRef<OErr>::type::type>
Ret(OErr&& v) noexcept(noexcept(Any<Val, Errors>(std::move(v)))) :
any(std::move(v)) {
Constraints::err(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move constructor Err");
}
template <class OVal, class OErrors>
Ret(const Ret<OVal, OErrors>& v) noexcept(noexcept(Any<Val, Errors>(unsafe_access_to_internal_data(v)))) :
any(unsafe_access_to_internal_data(v)) {
Constraints::retValErr(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "copy constructor Ret");
#ifdef ERROR_HANDLING_CHECK_EMPTY_RET
if(unsafe_access_to_internal_data(v).empty()) {
ERROR_HANDLING_CRITICAL_ERROR("Copying an empty `Ret`.");
}
#endif
}
template <class OVal>
Ret(const Ret<OVal, Set<>>& v) noexcept(noexcept(Any<Val, Errors>(unsafe_access_to_internal_data(v)))) :
any(unsafe_access_to_internal_data(v)) {
Constraints::retVal(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "copy constructor Ret");
}
template <class OVal, class OErrors>
Ret(Ret<OVal, OErrors>&& v) noexcept(noexcept(Any<Val, Errors>(std::move(unsafe_access_to_internal_data(v))))) :
any() {
Constraints::retValErr(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move constructor Ret");
#ifdef ERROR_HANDLING_CHECK_EMPTY_RET
if(unsafe_access_to_internal_data(v).empty()) {
ERROR_HANDLING_CRITICAL_ERROR("Moving an empty `Ret`.");
}
#endif
any = std::move(unsafe_access_to_internal_data(v));
}
template <class OErrors>
Ret(Ret<N, OErrors>&& v) noexcept(noexcept(Any<Val, Errors>(std::move(unsafe_access_to_internal_data(v))))) :
any() {
Constraints::retNErr(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move constructor Ret");
#ifdef ERROR_HANDLING_CHECK_EMPTY_RET
if(unsafe_access_to_internal_data(v).empty()) {
ERROR_HANDLING_CRITICAL_ERROR("Moving an empty `Ret`.");
}
#endif
any = std::move(unsafe_access_to_internal_data(v));
}
template <class OVal>
Ret(Ret<OVal, Set<>>&& v) noexcept(noexcept(Any<Val, Errors>(std::move(unsafe_access_to_internal_data(v))))) :
any(std::move(unsafe_access_to_internal_data(v))) {
Constraints::retVal(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move constructor Ret");
}
Ret<Val, Errors>& operator=(const Val& v) noexcept(noexcept(any = v)) {
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "copy assign Val");
this->any = v;
return *this;
}
Ret<Val, Errors>& operator=(Val&& v) noexcept(noexcept(any = std::move(v))) {
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move assign Val");
this->any = std::move(v);
return *this;
}
template <class OErr>
Ret<Val, Errors>& operator=(const OErr& v) noexcept(noexcept(any = v)) {
Constraints::err(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "copy assign Err");
this->any = v;
return *this;
}
template <class OErr,
class = typename EnableIfNotUniversalRef<OErr>::type::type>
Ret<Val, Errors>& operator=(OErr&& v) noexcept(noexcept(any = std::move(v))) {
Constraints::err(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move assign Err");
this->any = std::move(v);
return *this;
}
template <class OVal, class OErrors>
Ret<Val, Errors>& operator=(const Ret<OVal, OErrors>& v) noexcept(noexcept(any = unsafe_access_to_internal_data(v))) {
Constraints::retValErr(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "copy assign Ret");
#ifdef ERROR_HANDLING_CHECK_EMPTY_RET
if(unsafe_access_to_internal_data(v).empty()) {
ERROR_HANDLING_CRITICAL_ERROR("Copying an empty `Ret`.");
}
#endif
this->any = unsafe_access_to_internal_data(v);
return *this;
}
template <class OVal>
Ret<Val, Errors>& operator=(const Ret<OVal, Set<>>& v) noexcept(noexcept(any = unsafe_access_to_internal_data(v))) {
Constraints::retVal(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "copy assign Ret");
this->any = unsafe_access_to_internal_data(v);
return *this;
}
template <class OVal, class OErrors>
Ret<Val, Errors>& operator=(Ret<OVal, OErrors>&& v) noexcept(noexcept(any = std::move(unsafe_access_to_internal_data(v)))) {
Constraints::retValErr(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move assign Ret");
#ifdef ERROR_HANDLING_CHECK_EMPTY_RET
if(unsafe_access_to_internal_data(v).empty()) {
ERROR_HANDLING_CRITICAL_ERROR("Moving an empty `Ret`.");
}
#endif
this->any = std::move(unsafe_access_to_internal_data(v));
return *this;
}
template <class OErrors>
Ret<Val, Errors>& operator=(Ret<N, OErrors>&& v) noexcept(noexcept(any = std::move(unsafe_access_to_internal_data(v)))) {
Constraints::retNErr(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move assign Ret");
#ifdef ERROR_HANDLING_CHECK_EMPTY_RET
if(unsafe_access_to_internal_data(v).empty()) {
ERROR_HANDLING_CRITICAL_ERROR("Moving an empty `Ret`.");
}
#endif
this->any = std::move(unsafe_access_to_internal_data(v));
return *this;
}
template <class OVal>
Ret<Val, Errors>& operator=(Ret<OVal, Set<>>&& v) noexcept(noexcept(any = std::move(unsafe_access_to_internal_data(v)))) {
Constraints::retVal(v);
ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "move assign Ret");
this->any = std::move(unsafe_access_to_internal_data(v));
return *this;
}
/* операторов приведения типа(например к Val или ErrN) -- нет: если тип в any не совпал, то
мы можем только бросить исключение, но эта библиотека не кидает >своих< исключений(возможно только в
деструкторе этого класса) */
/* набор операторов сравнения отсутствует, так как всё что они могут при
any != Val -- кинуть исключение, а кидать исключения нельзя(в этом суть идеи) */
~Ret() {
#ifdef ERROR_HANDLING_CHECK_EMPTY_RET
if(!any.empty()) {
ERROR_HANDLING_CRITICAL_ERROR("Unchecked Ret.");
// ERROR_HANDLING_DEBUG_MSG((Ret<Val, Errors>), "Unchecked Ret");
}
#endif
}
};
} /* namespace detail */
} /* namespace error_handling */
#endif /* RETVALERRORS_HPP_ */
|
0471d7303e49daf94038444bb3a1f27582eb516a
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5706278382862336_0/C++/Omelianenko/a.cpp
|
149d539a703a98184b0cbdf88fff826826d6520e
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,418
|
cpp
|
a.cpp
|
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<vector>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define x first
#define y second
#define pow hi1
#define mp make_pair
#define ll long long
#define pb push_back
#define bro pair<int, int>
#define all(a) (a).begin(), (a).end()
const int N=45;
int t, ans, i, n=41;
long long g, p, q, pow[N];
long long gcd(long long x, long long y)
{
while(x>0&&y>0)
if(x>y)x%=y; else y%=x;
return x+y;
}
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
freopen("A-small-attempt4.in","r",stdin);
freopen("1.txt","w",stdout);
pow[0]=1;
for(i=1; i<n; i++)
pow[i]=pow[i-1]+pow[i-1];
cin>>t;
char c;
int k=0;
while(t--)
{
k++;
ans=-1;
cin>>p>>c>>q;
g=gcd(p, q);
p/=g;
q/=g;
for(i=0; i<=n; i++)
if(pow[i]>q)break; else
if(q%pow[i]==0&&(q/pow[i])<=p)
{
ans=i;
break;
}
int f=0;
for(i=0; i<=n; i++)
if(pow[i]==q)
{
f=1;
break;
}
if(!f)ans=-1;
cout<<"Case #"<<k<<": ";
if(ans<0)cout<<"impossible"<<endl;
else cout<<ans<<endl;
}
}
|
dc4ac596b563be26c6025f5ed066e1255ebfb1bd
|
ee0943757123a5c01348588928203ca8a53f3a99
|
/headers/Level.h
|
70ecc609da78747c415bcade6a8c7319509798cc
|
[] |
no_license
|
igormlk/CaveStoryRemake
|
ba3020a70fac27e965151c0489224704a6c3fe6b
|
b759f5e833c28f216c8a451bdf5d63ccde7e21e6
|
refs/heads/master
| 2020-03-28T20:09:37.233184
| 2019-07-21T18:33:08
| 2019-07-21T18:33:08
| 149,045,407
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,307
|
h
|
Level.h
|
//
// Created by igor on 16/09/18.
//
#ifndef LEVEL_H
#define LEVEL_H
#include <string>
#include <vector>
#include <tinyxml2.h>
#include "Vector2.h"
#include "Tile.h"
#include "Tileset.h"
#include "Rectangle.h"
class Graphics;
struct SDL_Texture;
class Level
{
public:
Level();
Level(std::string mapName, Vector2 spawnPoint, Graphics &graphics);
~Level();
void update(int elapsedTime);
void draw(Graphics &graphics);
std::vector<Rectangle> checkTileCollisions(const Rectangle &other);
const Vector2 getPlayerSpawnPoint() const;
private:
std::string _mapName;
Vector2 _spawnPoint;
Vector2 _size;
Vector2 _tileSize;
SDL_Texture * _backgroundTexture;
std::vector<Tile> _tileList;
std::vector<Tileset> _tileSets;
std::vector<Rectangle> _collisionRects;
void loadMap(std::string name, Graphics & graphics);
void splitTiles(std::string &stringT, std::vector<std::string> &tilesArray) const;
void parseCollisions(tinyxml2::XMLElement *pObjectGroup, const std::stringstream &ss, std::vector<Rectangle> & list) const;
void parseSpawnPoints(tinyxml2::XMLElement *pElement, std::stringstream &stringstream);
void setPlayerSpawnPoint(float x, float y, const std::stringstream &strName);
};
#endif //CAVESTORYREMAKE_LEVEL_H
|
2b9eafa53d40664bd84770a378a097a42a63d69d
|
06bc755b00127f5c6ed72aa9e959d4464a1f9949
|
/Software/lib/SpeedMeter/SpeedMeter.cpp
|
6e028f6a69c456e3e97d52e8d5fade23226f99b5
|
[] |
no_license
|
TheMadHatt3r/RT-E
|
214d8d811231ec50317968a451246c2744fd7bbc
|
0041f7e8c9583f1d68e2c29ca6a88e27f588d23d
|
refs/heads/master
| 2021-07-23T17:21:23.250764
| 2017-10-30T00:49:13
| 2017-10-30T00:49:13
| 108,783,610
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,558
|
cpp
|
SpeedMeter.cpp
|
/*
Collin Matthews - 2014
library to measure fuel flow and temperature.
Just call IncPulseCnt in the edge interrupt, feed it a temperature every now and then,
and then call FlowUpdate.
Lib version 1.1
1.0 - did not self contain temperature
*/
#include "Arduino.h"
#include "SpeedMeter.h"
SpeedMeter::SpeedMeter(long pulses_per_mile)
{
ppm=pulses_per_mile;
pulse_count_session=0;
pulse_count_cnt=0;
speed_mph=0;
speed_kmh=0;
}
void SpeedMeter::incPulseCnt()
{
pulse_count_session++;
pulse_count_cnt++;
}
void SpeedMeter::clearSessionCnt()
{
pulse_count_session=0;
pulse_count_cnt=0;
}
void SpeedMeter::speedUpdate()
{
unsigned int time_delta;
unsigned long mills_holder;
//Approximately the interval since last update, this makes it more accurate
mills_holder = millis();
time_delta = mills_holder - time_last_call; //time since last pulse
time_last_call = mills_holder;
//Shift all readings back 1 spot
for (byte i=(POINTS_AVERAGED-1);i>0; i--)
{
rate_avg[i]=rate_avg[i-1];
}
cli(); //ATOMIC operation
//Calculate real moving rate!
//best case for floating point precision is ~6 digits, double is = float in Arduino
//always do math in mph, later convert to kmh
rate_avg[0] = (float(pulse_count_cnt)/ppm)*MS_TO_HR;
pulse_count_cnt=0;
sei();//END ATOMIC operation
//avg
speed_mph=0;
for (byte i=0;i<POINTS_AVERAGED; i++)
{
speed_mph = speed_mph + rate_avg[i];
}
speed_mph=float(speed_mph)/POINTS_AVERAGED;
//also convert for Km/hr
speed_kmh = speed_mph*MPH_TO_KMPH;
}
|
2d836ce458130d976aa93ff584c4ca4070bef5d5
|
84a3adb95d4c3340c266fd9ec0d19000f362e11f
|
/infoarena/ratina/main.cpp
|
0bec182b9c9674b2da91c9831abd6a8483d00503
|
[] |
no_license
|
lavandalia/work
|
50b4b3eb4a63a5a0d0ab8ab4670d14ecb3d71293
|
a591adfd2fd2ff0fa8c65dc5829a15bc8cc60245
|
refs/heads/master
| 2020-05-01T02:25:31.229379
| 2017-12-17T08:39:32
| 2017-12-17T08:39:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,746
|
cpp
|
main.cpp
|
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ifstream cin("ratina.in");
ofstream cout("ratina.out");
int N, M; cin >> N >> M;
vector<string> S(N);
for (int i = 0; i < N; ++i)
cin >> S[i];
vector<int> P(N);
for (int i = 0; i < N; ++i)
P[i] = i;
sort(P.begin(), P.end(), [&](int x, int y) {
return S[x] < S[y];
});
vector<int> pos(N);
for (int i = 0; i < N; ++i)
pos[P[i]] = i;
vector<int> diff(N - 1);
for (int i = 0; i + 1 < N; ++i)
for (diff[i] = 0; diff[i] < int(S[P[i]].size()) && diff[i] < int(S[P[i + 1]].size()) && S[P[i]][diff[i]] == S[P[i + 1]][diff[i]]; ++diff[i]);
int log;
for (log = 1; (1 << log) < N; ++log);
vector< vector<int> > rmq(log, vector<int>(N - 1, 0));
rmq[0] = diff;
for (int i = 1; i < log; ++i)
for (int j = 0; j + (1 << (i - 1)) < N - 1; ++j)
rmq[i][j] = min(rmq[i - 1][j], rmq[i - 1][j + (1 << (i - 1))]);
vector<int> logv(N);
logv[1] = 0;
for (int i = 2; i < N; ++i)
logv[i] = 1 + logv[i / 2];
auto query = [&](int x, int y) {
int diff = y - x + 1;
int log = logv[diff];
return min(rmq[log][x], rmq[log][y - (1 << log) + 1]);
};
for (int i = 0; i < M; ++i) {
int K; cin >> K;
int mint = N, maxt = 0;
for (int j = 0; j < K; ++j) {
int x; cin >> x;
--x;
mint = min(mint, pos[x]);
maxt = max(maxt, pos[x]);
}
if (mint == maxt) {
cout << S[P[mint]].size() << "\n";
continue;
}
cout << query(mint, maxt - 1) << "\n";
}
}
|
e4adac8334de620c9a657b39c1bf175b10b1aaef
|
bdc67ddec677652859d5af62fb9be76e232064b8
|
/c++ learning/Others/Prime_factorization(11653번).cpp
|
53be903ae6849579993ebae3d2863cc751e3737d
|
[] |
no_license
|
vvonth/Algorithm
|
e1491bf95740fb6037ae4834c7bd05d38db11c88
|
7847ffd9ae32410507b93226e424b6a3886c38ae
|
refs/heads/master
| 2023-02-16T18:31:36.631210
| 2021-01-10T03:35:25
| 2021-01-10T03:35:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,312
|
cpp
|
Prime_factorization(11653번).cpp
|
//
// Prime factorization.cpp
// c++ learning
//
// Created by 원태희 on 04/04/2019.
// Copyright © 2019 원태희. All rights reserved.
//
/*#include <iostream>
using namespace std;
int main(void)
{
int n,i;
scanf("%d",&n);
for(i=2;i*i<=n;i++)
{ while(n%i==0)
{
cout<<i<<'\n';
n/=i;
}
}
if(n>1)
cout<<n<<'\n';
return 0;
}*/
/*#include <iostream>
using namespace std;
int main(void)
{
int n,i;
scanf("%d",&n);
while(n!=1)
{
for(i=2;i<=n;i++)
{ if(n%i==0)
{
cout<<i<<'\n';
n/=i;
break;
}
}
}
return 0;
}*/
#include<iostream>
#include<algorithm>
using namespace std;
int main(void)
{
int n,m;
int count1=0;
int count2=0;
int count3=0;
int count4=0;
cin>>n>>m;
for(long long i=2,j=5;i<=n;i*=2,j*=5)
{
count1+=n/i;
if(j<=n)
count2+=n/j;
}
for(long long i=2,j=5;i<=m;i*=2,j*=5)
{
count3+=m/i;
if(j<=m)
count4+=m/j;
}
for(long long i=2,j=5;i<=n-m;i*=2,j*=5)
{
count3+=(n-m)/i;
if(j<=n-m)
count4+=(n-m)/j;
}
cout<<min(count1-count3,count2-count4);
}
|
25b7433ec75b7b1dcf811d08a2bb05e1959ba086
|
4ca4e2ab20b67a36ca7dc7b8401e5e01c8b4b4d2
|
/Public/ShopApi.h
|
27b4b0cdf4770a442e16c89aea294c3606dd6922
|
[] |
no_license
|
admin4eg/survivalshop-api
|
faf68a077cb4ba9b2e9d59b092d085b35d26fea0
|
8d97d4c010d86edb6c0abc50660ee6ecc60e279a
|
refs/heads/master
| 2023-05-25T15:53:26.015174
| 2023-05-18T19:06:46
| 2023-05-18T19:06:46
| 148,482,243
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,560
|
h
|
ShopApi.h
|
#pragma once
#include "Plugin.h"
#define SURVIVALSHOP_API __declspec(dllimport)
namespace SurvivalShopApi
{
typedef bool(*EquipmentFunction)(const unsigned long long steamId, const web::json::value *customItem, std::wstring *logMessage);
typedef void(*TimerFunction)(const unsigned long long id, unsigned long long steamId, const std::wstring *data, const std::wstring *auxData, const std::wstring *comment, std::wstring *playerMessage);
// RegisterCustom
// get shop api version
SURVIVALSHOP_API float Version();
// GetLastError
// get last error
SURVIVALSHOP_API std::wstring GetLastError();
// RegisterEquipmentType
// register a custom goods type
SURVIVALSHOP_API bool RegisterEquipmentType(const std::wstring pluginName, const std::wstring typeName, EquipmentFunction func);
// UnregisterEquipmentType
// register a custom goods type
SURVIVALSHOP_API void UnregisterEquipmentType(const std::wstring typeName);
// RegisterTimerType
// register a timer function, the function is called when timer ends
SURVIVALSHOP_API bool RegisterTimerType(const std::wstring pluginName, const std::wstring timerType, TimerFunction func);
// UnregisterTimerType
// register a timer function, the function is called when timer ends
SURVIVALSHOP_API void UnregisterTimerType(const std::wstring timerType);
// SetTimer
// set a timer for a player
SURVIVALSHOP_API bool SetTimer(const std::wstring timerName, const unsigned long long steamId, const std::wstring data, const std::wstring auxData, const std::wstring comment, long minutes);
}
|
6001272778641310dabd4cf79b5eb169cd306345
|
6aff867d1ca170085987cc0a007c6aad6050e255
|
/Source/Tutorial/AnimInstance/CEnemyAnimInstance.cpp
|
09713c0b8aa5afc9b3442ac70a21b2de709af8cc
|
[] |
no_license
|
tjrdud004/Ue4Tutorial
|
d9f8d85cf4f72c30fedebc67138e4bbecf55cbf9
|
133755f2ed57b9d397d4e3136bac6ea329c6b9d6
|
refs/heads/master
| 2022-10-09T15:18:55.121380
| 2020-06-09T12:57:13
| 2020-06-09T12:57:13
| 267,015,916
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 873
|
cpp
|
CEnemyAnimInstance.cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "CEnemyAnimInstance.h"
#include "GameFramework/Character.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Enemy/CEnemy.h"
UCEnemyAnimInstance::UCEnemyAnimInstance()
{
}
void UCEnemyAnimInstance::NativeBeginPlay()
{
Super::NativeBeginPlay();
}
void UCEnemyAnimInstance::NativeUpdateAnimation(float DeltaSeconds)
{
Super::NativeUpdateAnimation(DeltaSeconds);
ACharacter* character = Cast<ACharacter>(TryGetPawnOwner());
if (character == NULL)
return;
Speed = character->GetVelocity().Size();
Direction = CalculateDirection(character->GetVelocity(),character->GetActorRotation());
bInAir = character->GetCharacterMovement()->IsFalling();
ACEnemy* enemy = Cast<ACEnemy>(character);
if (enemy == NULL)
return;
bTarget = enemy->IsTarget();
}
|
e83f9770e057f451178e4438a6a0a9ec53512926
|
c81a95338c75978747468f933cba4dfc581bddbc
|
/eminence/dynamicProg2/subsetSumExtended.cpp
|
cb9a7ddc4938eee1d876036c12797f2ad8bc2c74
|
[] |
no_license
|
swardhan/competetive
|
f775a8fc8f95a9ce12f61b5f6871ae77ea7e1d5c
|
997e6369e8e9aeebad3034163bc1a6065185cd77
|
refs/heads/master
| 2018-12-24T18:03:49.693987
| 2018-10-17T14:09:34
| 2018-10-17T14:09:34
| 107,956,151
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 702
|
cpp
|
subsetSumExtended.cpp
|
#include<bits/stdc++.h>
using namespace std;
bool subsetSum(int* val, int n, int sum){
bool** dp = new bool*2;
for(int i=0;i<=1;i++){
dp[i] = new bool[sum+1];
}
for(int i=0;i<=sum;i++){
dp[0][1] = false;
}
dp[0][0] = true;
int flag = 1;
for(int i=1; i<=n; i++){
for(int j=1; j<=sum;j++){
dp[flag][j] = dp[flag^1][j];
if(j>=val[i-1]){
dp[flag][j]= dp[flag][j] || dp[flag^1][j-val[i-1]];
}
}
flag = flag^1;
}
bool ans = dp[flag^1][sum];
for (int i=0; i<=2; i++) {
delete [] dp[i];
}
delete [] dp;
return ans;
}
int main(){
int val[] = {1,3,5,7,9};
int sum = 12;
cout << subsetSum(val,5,sum) << endl;
return 0;
}
|
eeb41b918f48d97f1fed847181ad0fa172d3f0f7
|
2e270b8d6ab03c5a2566c91817f5d611f9741f78
|
/C++/119.cpp
|
11956151690d884497d81eccf6c0b91cb02b5842
|
[] |
no_license
|
zjjyh96/LeetCode
|
9b4a3171d88936268bf59a8c33b477b177715ae6
|
e9bb86f21fa88298072b1b2718bfcba22fe8df5f
|
refs/heads/master
| 2021-05-26T07:02:34.165999
| 2019-10-15T20:13:41
| 2019-10-15T20:13:41
| 127,827,519
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 412
|
cpp
|
119.cpp
|
//
// Created by Yinhao Jiang on 2018/8/13.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> ans(rowIndex+1,0);
ans[0]=1;
for(int i=1;i<rowIndex+1;i++)
{
for(int j=i;j>0;j--)
{
ans[j]+=ans[j-1];
}
}
return ans;
}
};
|
783cd339a13b60c5d0815574ea074f8faffcb142
|
f157a231879833ac4dfa054d9f8e5a9aa9042725
|
/mtk/gui_ext/test/test-service.cpp
|
7b21f3286f492f4b762dd7be0bf48fafb941d557
|
[] |
no_license
|
xen0n/android_device_meizu_arale
|
3f0812dbd6f6d900ceaf05e1f8822fb6762b735b
|
e11e0c3611d375fdfbc2e51e26f9ef2c645b30fa
|
refs/heads/cm-13.0
| 2020-04-04T03:12:08.790366
| 2016-12-02T15:59:06
| 2016-12-02T15:59:06
| 41,228,374
| 51
| 55
| null | 2016-08-19T05:56:32
| 2015-08-22T23:38:47
|
C
|
UTF-8
|
C++
| false
| false
| 1,311
|
cpp
|
test-service.cpp
|
#define LOG_TAG "GuiExt-Test"
#define MTK_LOG_ENABLE 1
#include <cutils/log.h>
#ifdef USE_PTHREAD
#include <pthread.h>
#else
#include <utils/AndroidThreads.h>
#endif
#include <binder/BinderService.h>
#include <AALService.h>
void printids(const char *s)
{
#ifdef USE_PTHREAD
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid,(unsigned int)tid,(unsigned int)tid);
#else
printf("%s pid %u tid %u \n",s,(unsigned int)getpid(),(unsigned int)android::getThreadId());
#endif
}
int aal_service_fun(void *arg)
{
printids("new thread:");
android::AALService::publishAndJoinThreadPool();
return 0;
}
int main(int argc, char** argv)
{
ALOGD("AAL service start...");
#ifdef USE_PTHREAD
pthread_t aal_tid;
int err;
err = pthread_create(&aal_tid, NULL, aal_service_fun, NULL);
if(err != 0){
printf("can't create thread: %s\n", strerror(err));
return -1;
}
#else
if (!android::createThreadEtc(aal_service_fun, NULL, "AALService")) {
printf("can't create thread\n");
return -1;
}
#endif
printids("main thread:");
sleep(10000);
ALOGD("AAL service finish...");
return 0;
}
|
41e7627ffaebb3c84c9212744cfdd2935de4a396
|
a3effdcf4d0546743118897a2508f3f4a3fadded
|
/cs165/asteroids/source_code/imageSet.cpp
|
292dda0bfe8eb48a1508c67bc0c65d871941b227
|
[] |
no_license
|
wheelerkeith/cs165
|
70a35fbd6f6ac6cad0a325240f894489e1f8e12a
|
e65f0fdaee1fc2757d02c7033085c7722e68852b
|
refs/heads/master
| 2020-04-04T18:22:36.611594
| 2019-10-25T15:50:03
| 2019-10-25T15:50:03
| 156,161,184
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,252
|
cpp
|
imageSet.cpp
|
#include "imageSet.h"
sf::RenderWindow* imageSet::pWndw = NULL;
sf::Color imageSet::tColor = sf::Color(0,0,0);// transparency mask color
imageSet::imageSet(void)
{
}
imageSet::~imageSet(void)
{
DLT();
}
bool imageSet::INIT( std::string fileName, int NumSets, int NumCols, int cellSzx, int cellSzy )
{
bool OK = FALSE;
if( !img.LoadFromFile(fileName.c_str()) )
return false;
img.CreateMaskFromColor(tColor);
sprite.SetImage(img);
wImage = img.GetWidth();
hImage = img.GetHeight();
nSets = NumSets;
cols = NumCols;
wCell = cellSzx;
hCell = cellSzy;
if( (pRowSet = new int[nSets]) )
if( (pfrCntSet = new int[nSets]) )
if( (pSzx = new int[nSets]) )
if( (pSzy = new int[nSets]) )
OK = TRUE;// all allocations good
return OK;
}// end of INIT()
bool imageSet::INIT( std::string fileName )// a text file has been passed
{
bool OK = FALSE;
std::ifstream fin( fileName.c_str() );
if( fin )
{
std::string imgFilename;
std::getline( fin, imgFilename );
if( !img.LoadFromFile(imgFilename.c_str()) )
return false;
img.CreateMaskFromColor(tColor);
sprite.SetImage(img);
wImage = img.GetWidth();
hImage = img.GetHeight();
fin >> nSets >> cols >> wCell >> hCell;
}
if( (pRowSet = new int[nSets]) )
if( (pfrCntSet = new int[nSets]) )
if( (pSzx = new int[nSets]) )
if( (pSzy = new int[nSets]) )
OK = TRUE;// all allocations good
if( OK )
{
for( int i = 0; i < nSets; ++i )
fin >> pRowSet[i] >> pfrCntSet[i] >> pSzx[i] >> pSzy[i];
}
return OK;
}// end of INIT()
void imageSet::INITset( const int& setNum, const int& setRowNum, const int& setFrCount, const int& szx, const int& szy )// setNum from zero
{
*(pRowSet + setNum) = setRowNum;
*(pfrCntSet + setNum) = setFrCount;
*(pSzx + setNum) = szx;
*(pSzy + setNum) = szy;
return;
}// end of INITset()
void imageSet::DLT(void)
{
delete [] fileName;
if( nSets == 1 )
{
if( pRowSet != NULL )
delete pRowSet;
if( pfrCntSet != NULL )
delete pfrCntSet;
if( pSzx != NULL )
delete pSzx;
if( pSzy != NULL )
delete pSzy;
}
if( nSets > 1 )
{
if( pRowSet != NULL )
delete []pRowSet;
if( pfrCntSet != NULL )
delete []pfrCntSet;
if( pSzx != NULL )
delete []pSzx;
if( pSzy != NULL )
delete []pSzy;
}
return;
}// end of DLT()
void imageSet::draw( const bool& frAdvance, const int& setNum, int* pfrIndex, const float& posx, const float& posy )
{
sf::IntRect srcRect;
srcRect.Top = (( *pfrIndex / cols ) + pRowSet[setNum])*(hCell+1);
srcRect.Left = ( *pfrIndex % cols ) * (wCell+1);
srcRect.Bottom = srcRect.Top + pSzy[setNum];
srcRect.Right = srcRect.Left + pSzx[setNum];
sprite.SetSubRect(srcRect);
sprite.SetPosition(posx, posy);
if( pWndw )
pWndw->Draw( sprite );
if( frAdvance )
{
*pfrIndex += 1;
if( *pfrIndex >= pfrCntSet[setNum] )
*pfrIndex = 0;
}
return;
}// end of draw()
void imageSet::drawRotate( sf::Sprite* pSprite, const float& angle, const bool& frAdvance, const int& setNum, int* pfrIndex, const float& posx, const float& posy )
{
sf::IntRect srcRect;
srcRect.Top = (( *pfrIndex / cols ) + pRowSet[setNum])*(hCell+1);
srcRect.Left = ( *pfrIndex % cols ) * (wCell+1);
srcRect.Bottom = srcRect.Top + pSzy[setNum];
srcRect.Right = srcRect.Left + pSzx[setNum];
pSprite->SetSubRect(srcRect);
pSprite->SetPosition(posx, posy);
pSprite->SetRotation( angle );
if( pWndw )
pWndw->Draw( *pSprite );
if( frAdvance )
{
*pfrIndex += 1;
if( *pfrIndex >= pfrCntSet[setNum] )
*pfrIndex = 0;
}
return;
}// end of drawRotate()
void imageSet::drawCell( const int& setNum, const int& frIndex, const float& posx, const float& posy )
{
sf::IntRect srcRect;
srcRect.Top = (( frIndex / cols ) + pRowSet[setNum])*(hCell+1);
srcRect.Left = ( frIndex % cols ) * (wCell+1);
srcRect.Bottom = srcRect.Top + pSzy[setNum];
srcRect.Right = srcRect.Left + pSzx[setNum];
sprite.SetSubRect(srcRect);
sprite.SetPosition(posx, posy);
if( pWndw )
pWndw->Draw( sprite );
return;
}// end of drawCell()
|
8518eee680f8e5c8230c508bc218ab583d02bbc8
|
5a49b5da44fa9c3a585febcf3d975197d872efc9
|
/SGPLibraryCode/modules/sgp_particle/core/sgp_SPARK_Interpolator.h
|
40e327cf4ad4c9de769634d914c71f2a58cb77af
|
[
"MIT"
] |
permissive
|
phoenixzz/SGPEngine
|
1ab3de99fdf6dd791baaf57e029a09e8db3580f7
|
593b4313abdb881d60e82750b36ddda2d7c73c49
|
refs/heads/master
| 2021-01-24T03:42:44.683083
| 2017-01-24T04:39:43
| 2017-01-24T04:39:43
| 53,315,434
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,784
|
h
|
sgp_SPARK_Interpolator.h
|
#ifndef __SGP_SPARKINTERPOLATOR_HEADER__
#define __SGP_SPARKINTERPOLATOR_HEADER__
class Particle;
// Constants defining which type of value is used for interpolation
enum InterpolationType
{
INTERPOLATOR_LIFETIME, /**< Constant defining the life time as the value used to interpolate */
INTERPOLATOR_AGE, /**< Constant defining the age as the value used to interpolate */
INTERPOLATOR_PARAM, /**< Constant defining a parameter as the value used to interpolate */
INTERPOLATOR_VELOCITY, /**< Constant defining the square norm of the velocity as the value used to interpolate */
};
/**
* An entry in the interpolator graph
*/
struct InterpolatorEntry
{
float x; /**< x value of this entry */
float y0; /**< y first value of this entry */
float y1; /**< y second value of this entry */
/**Default constructor of interpolator entry. All values are set to 0 */
InterpolatorEntry() : x(0.0f), y0(0.0f), y1(0.0f) {}
/**
* Constructs an interpolator entry with y0 and y1 having the same value
*/
InterpolatorEntry(float x, float y) : x(x), y0(y), y1(y) {}
InterpolatorEntry(float x, float y0, float y1) : x(x), y0(y0), y1(y1) {}
// used internally
InterpolatorEntry(float x) : x(x) {}
};
// forward declaration to allow the set of entries in interpolator to be constructed
bool operator<(const InterpolatorEntry& entry0, const InterpolatorEntry& entry1);
/**
* An interpolator that offers flexible control over particle parameters
*
* An interpolator is created for each parameter of a model which is set as interpolated.
* The user can get the interpolator of a parameter for a given model by calling Model::getInterpolator(ModelParam).
* An interpolator can use several types of value to interpolate a given parameter :
* the lifetime of a particle : it is defined in a range between 0 and 1, 0 being the birth of the particle and 1 being its death
* the age of a particle
* the value of another parameter of a particle (which can be any of the parameters)
* the square norm of the velocity of a particle
*
* Here is a description of how an interpolator works :
* Internally an interpolator holds a list of entries which defines a 2D graph. The entries are sorted internally along the x axis.
* Each entry have a unique x value and 2 y values (although both y can have the same value).
* The x defines the value that will be used to interpolate the parameter value. This value depends on the type set of the interpolator.
* For instance, if the type is INTERPOLATOR_AGE, the current x value will be the age of the particle.
* Knowing the current x value, the interpolator interpolates the y value in function of the entries y values.
* An interpolator holds 2 curves : the y0 one and the y1 one.
* Each particle is given a random value between 0 and 1 which defines where between the y0 and the y1 curve the interpolated y value will be.
* The final interpolated y value will be the value of the interpolated particle parameter for this frame.
* Moreover the graph can loop or not :
* If the graph does not loop, the current x value is clamped between the minimum x and the maximum x of the graph.
* If the graph loops, the current x is recomputed to fit in the range between the minimum x and the maximum x of the graph.
* Finally, it is possible to set a variation in the offset and the scale of the current x computed :
* Each particle is given an offset and a scale to compute its current x depending on the variations set. The formula to compute the final current x is the following :
* final current x = (current x + offset) * scale
* offset being randomly generated per particle in [-offsetXVariation, +offsetXVariation]
* scale being randomly generated per particle in 1.0 + [-scaleXVariation, +scaleXVariation]
* The default values of the interpolator are the following :
type : INTERPOLATOR_LIFETIME
offset x variation : 0.0
scale x variation : 0.0
*/
class SGP_API Interpolator
{
friend class Particle;
friend class Model;
public:
/**
* Sets the value used to interpolate
*
* See the class description for more information.
* Note that the argument param is only used when the type is INTERPOLATOR_PARAM.
*
* @param type : the type of value used to interpolate
* @param param : the parameter used to interpolate when the type is INTERPOLATOR_PARAM.
*/
void setType(InterpolationType type, ModelParam param = PARAM_SIZE);
/**
* Enables or disables the looping of the graph
*
* The range of the graph is defined between the entry with the minimum x and the entry with the maximum y.
* If the looping is disabled, the x are clamped to the range.
* If the looping is enabled, the value of x is reported in the range. It is better that the xmin and xmax have
* the same y values so that the graph tiles perfectly.
*
*/
void enableLooping(bool loop);
/**
* Sets the scale variation in x
*/
void setScaleXVariation(float scaleXVariation);
float getScaleXVariation() const;
/**
* Sets the offset variation in x
*/
void setOffsetXVariation(float offsetXVariation);
float getOffsetXVariation() const;
/**
* Gets the type of value used to interpolate
*/
InterpolationType getType() const;
/**
* Gets the parameter used to interpolate
* Note that the parameter is only used if the type is INTERPOLATOR_PARAM
*/
ModelParam getInterpolatorParam() const;
/**
* Tells whether the looping is enabled or not
*/
bool isLoopingEnabled() const;
SortedSet<InterpolatorEntry>& getGraph();
const SortedSet<InterpolatorEntry>& getGraph() const;
/**
* Adds an entry to the graph
* return true if the entry has been added to the graph, false if not (the graph already contains an entry with the same x)
*/
bool addEntry(const InterpolatorEntry& entry);
/**
* Adds an entry to the graph
* return true if the entry has been added to the graph, false if not (the graph already contains an entry with the same x)
*/
bool addEntry(float x, float y);
/**
* Adds an entry to the graph
* return true if the entry has been added to the graph, false if not (the graph already contains an entry with the same x)
*/
bool addEntry(float x, float y0, float y1);
/** Clears the graph (removes all the entries) */
void clearGraph();
/** Generates a sinusoidal curve
* Note that the graph is previously cleared from all its entries
*/
void generateSinCurve(float period, float amplitudeMin, float amplitudeMax, float offsetX, float offsetY, float startX, uint32 length, uint32 nbSamples);
/** Generates a polynomial curve
* Note that the graph is previously cleared from all its entries
*/
void generatePolyCurve(float constant, float linear, float quadratic, float cubic, float startX, float endX, uint32 nbSamples);
private:
SortedSet<InterpolatorEntry> graph;
InterpolationType type;
ModelParam param;
bool loopingEnabled;
float scaleXVariation;
float offsetXVariation;
float interpolate(const Particle& particle, ModelParam interpolatedParam, float ratioY, float offsetX, float scaleX);
float interpolateY(const InterpolatorEntry& entry, float ratio);
// methods to compute X
typedef float (Interpolator::*computeXFn)(const Particle&) const;
static computeXFn COMPUTE_X_FN[4];
float computeXLifeTime(const Particle& particle) const;
float computeXAge(const Particle& particle) const;
float computeXParam(const Particle& particle) const;
float computeXVelocity(const Particle& particle) const;
// Only a model can create and destroy an interpolator
Interpolator();
~Interpolator() {};
};
inline void Interpolator::setType(InterpolationType type, ModelParam param)
{
this->type = type;
this->param = param;
}
inline void Interpolator::enableLooping(bool loop)
{
loopingEnabled = loop;
}
inline void Interpolator::setScaleXVariation(float scaleXVariation)
{
this->scaleXVariation = scaleXVariation;
}
inline void Interpolator::setOffsetXVariation(float offsetXVariation)
{
this->offsetXVariation = offsetXVariation;
}
inline InterpolationType Interpolator::getType() const
{
return type;
}
inline ModelParam Interpolator::getInterpolatorParam() const
{
return param;
}
inline bool Interpolator::isLoopingEnabled() const
{
return loopingEnabled;
}
inline float Interpolator::getScaleXVariation() const
{
return scaleXVariation;
}
inline float Interpolator::getOffsetXVariation() const
{
return offsetXVariation;
}
inline SortedSet<InterpolatorEntry>& Interpolator::getGraph()
{
return graph;
}
inline const SortedSet<InterpolatorEntry>& Interpolator::getGraph() const
{
return graph;
}
inline bool Interpolator::addEntry(const InterpolatorEntry& entry)
{
return graph.add(entry);
}
inline bool Interpolator::addEntry(float x,float y)
{
return addEntry(InterpolatorEntry(x,y));
}
inline bool Interpolator::addEntry(float x, float y0, float y1)
{
return addEntry(InterpolatorEntry(x, y0, y1));
}
inline void Interpolator::clearGraph()
{
graph.clear();
}
inline float Interpolator::interpolateY(const InterpolatorEntry& entry, float ratio)
{
return entry.y0 + (entry.y1 - entry.y0) * ratio;
}
/////////////////////////////////////////////////////////////
// Functions to sort the entries on the interpolator graph //
/////////////////////////////////////////////////////////////
inline bool operator<(const InterpolatorEntry& entry0, const InterpolatorEntry& entry1)
{
return entry0.x < entry1.x;
}
inline bool operator<=(const InterpolatorEntry& entry0, const InterpolatorEntry& entry1)
{
return entry0.x <= entry1.x;
}
inline bool operator>=(const InterpolatorEntry& entry0, const InterpolatorEntry& entry1)
{
return entry0.x >= entry1.x;
}
inline bool operator==(const InterpolatorEntry& entry0, const InterpolatorEntry& entry1)
{
return entry0.x == entry1.x;
}
#endif // __SGP_SPARKINTERPOLATOR_HEADER__
|
d33947cf1b97df01e1d8638c3b52892e5a39dc39
|
70418d8faa76b41715c707c54a8b0cddfb393fb3
|
/10022.cpp
|
41697ab1cb65a9648d2742e7b7fe9f16825de3c8
|
[] |
no_license
|
evandrix/UVa
|
ca79c25c8bf28e9e05cae8414f52236dc5ac1c68
|
17a902ece2457c8cb0ee70c320bf0583c0f9a4ce
|
refs/heads/master
| 2021-06-05T01:44:17.908960
| 2017-10-22T18:59:42
| 2017-10-22T18:59:42
| 107,893,680
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,419
|
cpp
|
10022.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define MAXI(a, b) (a > b ? a : b)
#define MINI(a, b) (a > b ? b : a)
int N, M, N_row, M_row, N_left, M_left, N_right, M_right, MAX;
int Find_R(int n)
{
int k;
k = sqrt((double)n);
if (k * k < n)
{
return k + 1;
}
return k;
}
int Find_L_R(int n, int row)
{
int m, d, k;
m = (row - 1) * (row - 1) + 1;
d = n - m + 1;
k = ceil((double)d / 2);
return k;
}
int Find_R_R(int n, int row)
{
int m, d, k;
m = row * row;
d = m - n + 1;
k = ceil((double)d / 2);
return k;
}
int Dis()
{
if (M_left >= N_left && M_right >= N_right)
{
return 1;
}
return 0;
}
int Distance(int m, int m_r, int n, int n_r)
{
int d = 0, k, dis;
if ((m % 2 && m_r % 2) || (!(m % 2) && !(m_r % 2)))
{
d++;
}
if ((n % 2 && n_r % 2 == 0) || (n % 2 == 0 && n_r % 2 != 0))
{
d++;
}
k = m_r - n_r - 1;
dis = k * 2 + d + 1;
return dis;
}
int LEFT_inside()
{
int d, val, dis, meet_row;
int meet_point;
d = M_left - N_left - 1;
meet_row = M_row - d;
dis = d * 2 + 1;
if ((M_row % 2 == 0 && M % 2 != 0) || (M_row % 2 != 0 && M % 2 == 0))
{
dis++;
meet_row--;
}
meet_point = (meet_row - 1) * (meet_row - 1) + N_left * 2;
val = dis + Distance(meet_point, meet_row, N, N_row);
return val;
}
void Out_side()
{
int meet_point, val;
int d = (M_row - 1) * (M_row - 1);
meet_point = d + N_left * 2;
val = Distance(meet_point, M_row, N, N_row);
val += abs(M - meet_point);
if (val < MAX)
{
MAX = val;
}
d = (M_row) * (M_row);
meet_point = d - N_right * 2 + 1;
val = Distance(meet_point, M_row, N, N_row);
val += abs(M - meet_point);
if (val < MAX)
{
MAX = val;
}
}
void Cal()
{
int temp;
N_row = Find_R(N);
M_row = Find_R(M);
if (N_row == M_row)
{
printf("%d\n", abs(M - N));
return;
}
N_left = Find_L_R(N, N_row);
M_left = Find_L_R(M, M_row);
if (N_left == M_left)
{
printf("%d\n", Distance(M, M_row, N, N_row));
return;
}
N_right = Find_R_R(N, N_row);
M_right = Find_R_R(M, M_row);
if (N_right == M_right)
{
printf("%d\n", Distance(M, M_row, N, N_row));
return;
}
if (Dis() == 1)
{
temp = LEFT_inside();
if (temp < MAX)
{
MAX = temp;
}
}
else
{
Out_side();
}
printf("%d\n", MAX);
}
int main()
{
int a, b;
int kase;
scanf("%d", &kase);
while (kase--)
{
scanf("%d%d", &a, &b);
MAX = 2147483647;
N = MINI(a, b);
M = MAXI(a, b);
Cal();
if (kase)
{
printf("\n");
}
}
return 0;
}
|
0d81568c9a436a4be9e303aabf3d02f1b809d365
|
c464c4b4ed4527d5f6f2f53b82815a8ec6b5e4fc
|
/test/spec/section/list_spec.cpp
|
49611d0c1c8218b64e33c232fc0b16e736314849
|
[
"MIT"
] |
permissive
|
mrk21/bitfield
|
210e6186c0192091ba80ca8805818f8de84c4d59
|
01dae50464ee568e0c9dc9143048cd7e348eed18
|
refs/heads/master
| 2020-05-05T01:35:07.902928
| 2014-06-10T04:11:22
| 2014-06-10T04:11:22
| 18,355,150
| 4
| 2
| null | 2014-06-02T12:28:08
| 2014-04-02T05:00:48
|
C++
|
UTF-8
|
C++
| false
| false
| 4,457
|
cpp
|
list_spec.cpp
|
#include <bandit/bandit.h>
#include <bitfield/field.hpp>
#include <bitfield/section/list.hpp>
#include <bitfield/iostream.hpp>
#include <array>
namespace bitfield { namespace section {
union list_test {
using container_type = container::array<96>;
using sections_length_type = field< 8>;
using v1_type = sections_length_type::next_field<24>;
union section_type {
using section_length_type = field<8>;
using v1_type = section_length_type::next_field<8>;
section_length_type section_length;
v1_type v1;
std::size_t length() const {
return this->section_length;
}
};
struct section_container_type: public list<section_container_type, section_type, list_test> {
const uint8_t * base_addr() const {
return bit_type(v1_type::NEXT_OFFSET).addr(this);
}
std::size_t length() const {
return this->parent()->sections_length;
}
};
container_type container;
sections_length_type sections_length;
section_container_type sections;
};
go_bandit([]{
using namespace bandit;
describe("section::list", [&]{
list_test * packet;
before_each([&]{
// 1 packet = 96 byte
packet = new list_test{{{
0x18, 0x01, 0xE0, 0xA5, // sections_length = 24 byte, v1 = 123045
0x04, 0x10, 0xFF, 0xFF, // section 1: section_length = 4 byte, v1 = 16
0x0C, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // section 2: section_length = 12 byte, v1 = 240
0x08, 0x15, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // section 3: section_length = 8 byte, v1 = 21
// padding = 68 byte
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF
}}};
});
describe("#size()", [&]{
it("should be the number of fieldsets in the list.", [&]{
AssertThat(packet->sections.size(), Equals(3));
});
});
describe("iterator", [&]{
it("should iterate each fieldset in the list", [&]{
auto it = packet->sections.begin();
auto end = packet->sections.end();
AssertThat(it, not Equals(end));
AssertThat(it->v1, Equals(16));
++it;
AssertThat(it, not Equals(end));
AssertThat(it->v1, Equals(240));
++it;
AssertThat(it, not Equals(end));
AssertThat(it->v1, Equals(21));
++it;
AssertThat(it, Equals(end));
});
describe("inner iterator", [&]{
it("should iterate each byte of the fieldset", [&]{
auto it = packet->sections.begin();
auto it_it = it.begin();
auto it_end = it.end();
AssertThat(it_it, not Equals(it_end));
AssertThat(uint32_t(*it_it), Equals(0x04));
++it_it;
AssertThat(it_it, not Equals(it_end));
AssertThat(uint32_t(*it_it), Equals(0x10));
++it_it;
AssertThat(it_it, not Equals(it_end));
AssertThat(uint32_t(*it_it), Equals(0xFF));
++it_it;
AssertThat(it_it, not Equals(it_end));
AssertThat(uint32_t(*it_it), Equals(0xFF));
++it_it;
AssertThat(it_it, Equals(it_end));
});
});
});
});
});
}}
|
eb60bc033f3c3ad1a6d0c244478fb62d4f0988bb
|
10cd18311300d8684bd057a09a0fc088cf5c2668
|
/Try some Algorithms/Fast Dijkstra/FastDijkstra.cpp
|
e69d3a2560a69f74bdccfc19e324923dfaf77179
|
[] |
no_license
|
jam-xd/Competitive-Programing
|
a2a17835bdb114740b7f8c4d478492aad075cb38
|
6e897affd33655938aa3d83e75cf4b1ee05bb017
|
refs/heads/master
| 2023-03-11T20:35:29.466393
| 2021-03-02T22:41:22
| 2021-03-02T22:41:22
| 336,113,893
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,891
|
cpp
|
FastDijkstra.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double dbl;
#define QuieroComer ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define FileIn freopen("input.txt", "r", stdin)
#define FileOut freopen("output.txt", "w", stdout)
#define endl "\n"
#define debug(x) cout<<"--> "<<x<<endl
int const MOD = 10e9+7;
deque<deque<pair<int,int> > >graph;
deque<int>distFromInit;
void dijkstra(int init){
distFromInit.resize(graph.size());
set<pair<int,int> >taskList;
for(int i=0;i<graph.size();i++)distFromInit[i] = INT_MAX;
distFromInit[init] = 0;
taskList.insert(pair<int,int>(init, distFromInit[init]));
while(taskList.empty() == false){
pair<int,int>current = *taskList.begin();
taskList.erase(taskList.begin());
int currNode = current.first;
int currDist = current.second;
deque<pair<int,int> >::iterator it;
for(it = graph[currNode].begin(); it != graph[currNode].end(); it++){
int adjNode = it->first;
int adjDist = it->second;
if(distFromInit[currNode] + adjDist < distFromInit[adjNode]){
if(distFromInit[adjNode] != INT_MAX){
taskList.erase(taskList.find(pair<int,int>(adjNode, distFromInit[adjNode])));
}
distFromInit[adjNode] = distFromInit[currNode] + adjDist;
taskList.insert(pair<int,int>(adjNode, distFromInit[adjNode]));
}
}
}
}
int main()
{
int casos; cin>>casos;
while(casos--){
int nodos, arcos; cin>>nodos>>arcos;
graph.resize(nodos);
for(int i=0;i<arcos;i++){
int u,v,peso;
cin>>u>>v>>peso;
graph[u].push_back(pair<int,int>(v,peso));
graph[v].push_back(pair<int,int>(u,peso));
}
cout<<"---------------------------"<<endl;
for(int i=0;i<nodos;i++){
cout<<"Curren node: "<<i<<" { ";
for(int j=0;j<graph[i].size();j++){
cout<<graph[i][j].first<<",";
}cout<<"}"; cout<<endl;
}
cout<<"---------------------------"<<endl;
cout<<"Calculate Dijkstra from node: ";
int init; cin>>init;
dijkstra(init);
for(int i=0;i<distFromInit.size();i++){
cout<<"Distance from origin ["<<init<<"] to node ["<<i<<"] is "<<distFromInit[i]<<endl;
}
cout<<"Furulaaaa :DD"<<endl;
}
return 0;
}
/*--------------------------------------------/
* overflow?
* Corner cases (n=1? || n=n-1?)
* n=n+1 (!=) n+=1;
(copy n) ~ (don't make a copy of n)
* if(use vector, string, deque in function) use "&"before.
(to rewrite, instead of make a copy)
* DON'T GET STUCK ON ONE APPROACH
//Animo, sales de gris :'v, haz upsolving cuando termine >:v
//Despues comes :3
----------------------------------------------/
*/
|
79db841a1c08abf6182d2edcbc6f718abe359112
|
7a6f95fe320efd1fbf91b8deef2591ce470c4a69
|
/ex2/param_par_defaut.cpp
|
23ddc0131865587b9a8d84504d497a4428712b00
|
[] |
no_license
|
AnodeGrindYo/cpp_exercices
|
8cd84a2fc4b8ce0aab6129e86237d729b52bd1b1
|
2cc9221a293f137bc746552ac8bebbb0170a2f37
|
refs/heads/master
| 2022-01-08T04:17:18.013617
| 2017-06-26T10:59:57
| 2017-06-26T10:59:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,326
|
cpp
|
param_par_defaut.cpp
|
#include <iostream>
#include <cmath>
using namespace std;
struct cercle
{
string nom;
double rayon;
double perimetre;
double aire;
};
double Aire(string nomducercle = "Defaut_A", double rayon = 1)
{
double aire = rayon*rayon*M_PI;
cout << "\nFonction Aire\n-------------" << endl;
cout << nomducercle << " a un rayon de " << rayon << " et une aire de " << aire << endl;
cout << "-------------\n" << endl;
return aire;
}
double Perimetre(string nomducercle = "Defaut_P", double rayon = 1)
{
double perimetre = 2*rayon*M_PI;
cout << "\nFonction Permimetre\n------------------" << endl;
cout << nomducercle << " a un rayon de " << rayon << " et un perimetre de " << perimetre << endl;
cout << "-------------\n" << endl;
return perimetre;
}
int main(int argc, char *argv[])
{
/* code */
cercle patatoide;
cout << "Nom du cercle : " << endl;
cin >> patatoide.nom;
cout << "Rayon : ";
cin >> patatoide.rayon;
patatoide.aire = Aire(patatoide.nom, patatoide.rayon);
patatoide.perimetre = Perimetre(patatoide.nom, patatoide.rayon);
cout << "\nTest des appels avec les parametres par defaut : " << endl;
cout << "--------------------------------------------------" << endl;
cout << "Test de la fonction Aire :" << endl;
Aire();
cout << "Test de la fonction Perimetre" << endl;
Perimetre();
return 0;
}
|
920e1854783991bf43b7342dbdac5b006cc5535f
|
64bd24b4f52af6594fb63d467276168288680d69
|
/src/payload.cpp
|
0ec111e5a47162c2f8db744a0af1dcd73c216815
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
simoncl2/snowplow-cpp-tracker
|
395658c358afc1b96e6746712cf0547f04dbc3e7
|
88623326345450a74dcd0722b47e9d15b05f7bfd
|
refs/heads/master
| 2021-01-16T20:14:06.125098
| 2016-06-09T21:49:13
| 2016-06-09T21:49:13
| 60,808,832
| 0
| 0
| null | 2016-06-09T21:38:28
| 2016-06-09T21:38:27
| null |
UTF-8
|
C++
| false
| false
| 1,518
|
cpp
|
payload.cpp
|
/*
Copyright (c) 2016 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License Version 2.0.
You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
#include "payload.hpp"
Payload::~Payload() {
this->m_pairs.clear();
}
void Payload::add(const string & key, const string & value) {
if (!key.empty() && !value.empty()) {
this->m_pairs[key] = value;
}
}
void Payload::add_map(map<string, string> pairs) {
map<string, string>::iterator it;
for (it = pairs.begin(); it != pairs.end(); it++) {
this->add(it->first, it->second);
}
}
void Payload::add_payload(Payload p) {
this->add_map(p.get());
}
void Payload::add_json(json j, bool base64Encode, const string & encoded, const string & not_encoded) {
if (base64Encode) {
string json_str = j.dump();
this->add(encoded, base64_encode((const unsigned char *) json_str.c_str(), json_str.length()));
} else {
this->add(not_encoded, j.dump());
}
}
map<string, string> Payload::get() {
return this->m_pairs;
}
|
fd89f41fc3ecf4616f0ebf3e62c65b0eb4003269
|
6ea50d800eaf5690de87eea3f99839f07c662c8b
|
/ver.0.15.0.1/DefaultMobSpawner.h
|
a0a590c2807a20960164e8932709e41a07ad3229
|
[] |
no_license
|
Toku555/MCPE-Headers
|
73eefeab8754a9ce9db2545fb0ea437328cade9e
|
b0806aebd8c3f4638a1972199623d1bf686e6497
|
refs/heads/master
| 2021-01-15T20:53:23.115576
| 2016-09-01T15:38:27
| 2016-09-01T15:38:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 254
|
h
|
DefaultMobSpawner.h
|
#pragma once
class DefaultMobSpawner{
public:
DefaultMobSpawner(MobSpawnerBlockEntity *);
void getPos(void);
void getPos(void);
void ~DefaultMobSpawner();
void ~DefaultMobSpawner();
void ~DefaultMobSpawner();
void ~DefaultMobSpawner();
};
|
9e04d9e6422d86bbc4ad471c1b756e094035658b
|
c3f715589f5d83e3ba92baaa309414eb253ca962
|
/C++/round-5/1401-1500/1421-1440/1431.h
|
05184922ff3a3e3de897420aeae6fa22708370ac
|
[] |
no_license
|
kophy/Leetcode
|
4b22272de78c213c4ad42c488df6cffa3b8ba785
|
7763dc71fd2f34b28d5e006a1824ca7157cec224
|
refs/heads/master
| 2021-06-11T05:06:41.144210
| 2021-03-09T08:25:15
| 2021-03-09T08:25:15
| 62,117,739
| 13
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 346
|
h
|
1431.h
|
class Solution {
public:
vector<bool> kidsWithCandies(vector<int> &candies, int extraCandies) {
int max_candies = *max_element(candies.begin(), candies.end());
vector<bool> result(candies.size());
for (int i = 0; i < result.size(); ++i) {
result[i] = (candies[i] + extraCandies) >= max_candies;
}
return result;
}
};
|
b09d7055d3a975a2773623703dc6c0260a66df92
|
b125a380034af850935172318cb553e7e97a0cc8
|
/u_assert.cpp
|
b01a4f1f9edf2071fd8321414504261c6e112667
|
[
"MIT"
] |
permissive
|
graphitemaster/neothyne
|
375a3f6835edeb525d2aa97f6f65d444bd1d2395
|
101dd7f96e5c62e32e797105d9fb23f975986626
|
refs/heads/master
| 2021-01-24T06:41:32.453686
| 2017-01-08T21:28:41
| 2017-01-08T21:28:41
| 22,590,787
| 82
| 21
| null | 2016-12-27T22:02:14
| 2014-08-04T03:27:46
|
C++
|
UTF-8
|
C++
| false
| false
| 297
|
cpp
|
u_assert.cpp
|
#include "engine.h"
namespace u {
[[noreturn]] void assert(const char *expression,
const char *file,
const char *func,
size_t line)
{
neoFatal("Assertion failed: %s (%s: %s: %d)", expression, file, func, line);
}
}
|
26d4565fe52d125bf0cd05219cdc38ec6d743e3f
|
eb3b6e912c3fca7991717d645a09d9a47a59eeb6
|
/main.cpp
|
3fa26ba6685a48d7045347d4c3f885465318f1f7
|
[] |
no_license
|
Vespemeon/AlgLabSem4_1
|
c493d09a4b042943601ac307e259364d58c56728
|
193c91f8dc339361aa4ef3bbf724c239fee31a81
|
refs/heads/master
| 2020-05-29T11:31:08.994156
| 2019-05-29T00:12:33
| 2019-05-29T00:12:33
| 189,119,925
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 183
|
cpp
|
main.cpp
|
#include "linkedList.h"
int main() {
List<int> *list = new List<int>({ 13, 19, 16, 8 });
list->insert(15, 3);
std::cout << *list << std::endl;
system("PAUSE");
return 0;
}
|
15e1d17a7569a22b86d4745aefb2affd0d746f25
|
9d6ddd684d04e13713111c2a6cc8456f0d5dde19
|
/Main_Arduino/Main_Arduino.ino
|
826f8b8c8dcdb31e7dc91e8fa8d478d929afac70
|
[
"MIT"
] |
permissive
|
AndresBercovich/Motorghino
|
3778f6506a4ecacae62e9c111b57d3fe7fc4498c
|
8740f385d67750cf51d5417292aa4df3828a6090
|
refs/heads/main
| 2023-01-21T18:04:52.880547
| 2023-01-09T20:21:24
| 2023-01-09T20:21:24
| 240,085,927
| 2
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 248
|
ino
|
Main_Arduino.ino
|
#include <SPI.h>
#define CS_Motorghino_L 7
#define CS_Motorghino_R 8
int a, b;
int l_a, l_b;
long s_L, l_s_L, rev_L = 0;
int d_wheel = 32;
void setup() {
Serial.begin(115200);
motorghino_begin();
}
void loop() {
systick();
}
|
39ca1e3e5590f4492f508f1f232e50bfccbecd97
|
fcdce5a6f6e75f28a8998a08f54fd452a3c91f0f
|
/02_VECTORES/vectores_9.cpp
|
21be196ef0aebd3ba89e98263ff089d4e8cf230b
|
[] |
no_license
|
pablolizardo/TSP
|
a118a7db552f7b406ab4298bc47f97e3e9a2f452
|
9ff001231664887cd4b607f5d934406a7f983328
|
refs/heads/master
| 2021-01-20T18:28:17.123932
| 2016-06-24T21:32:13
| 2016-06-24T21:32:13
| 61,912,727
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 802
|
cpp
|
vectores_9.cpp
|
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int n = 0;
cout << "Ingrese la cantidad de alumnos -> ";
cin >> n;
int trim1[n], trim2[n], trim3[n], prom[n] ;
for (int i = 0; i < n; ++i)
{
trim1[i]=0;
trim2[i]=0;
trim3[i]=0;
prom[i]=0;
}
for (int i = 0; i < n; ++i)
{
cout << "Ingrese las notas del alumno " << i+1 <<"\n";
cout << "Primer Cuatrimestre -> \t";
cin >> trim1[i];
cout << "Primer Cuatrimestre -> \t";
cin >> trim2[i];
cout << "Primer Cuatrimestre -> \t";
cin >> trim3[i];
prom[i]= (trim1[i]+trim2[i]+trim3[i])/3;
}
cout << "Alumno\t1er\t2do\t3er\tProm\n";
for (int i = 0; i < n; ++i)
{
cout << i+1 << "\t" << trim1[i]<< "\t" <<trim2[i]<< "\t" <<trim3[i] << "\t" << prom[i] << "\n";
}
return 0;
}
|
dd74b1e003ac949cc6708b30e2db8a3508371c7e
|
b794490c0e89db4a3a4daabe91b2f057a32878f0
|
/PE/Debugger/EasyDbg/src/ExportTable.cpp
|
c2f9bcc53bb564f9d78c9607b7325e03fa14b251
|
[] |
no_license
|
FusixGit/hf-2011
|
8ad747ee208183a194d0ce818f07d312899a44d2
|
e0f1d9743238d75ea81f1c8d0a3ea1b5a2320a16
|
refs/heads/master
| 2021-01-10T17:31:14.137939
| 2012-11-05T12:43:24
| 2012-11-05T12:43:24
| 50,957,230
| 3
| 8
| null | null | null | null |
GB18030
|
C++
| false
| false
| 5,573
|
cpp
|
ExportTable.cpp
|
// ExportTable.cpp : implementation file
//
#include "stdafx.h"
#include "EasyDbg.h"
#include "ExportTable.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CExportTable dialog
extern DWORD g_dwExportRva;
extern PIMAGE_SECTION_HEADER g_SecHeader;
extern DWORD g_SecNum;
extern char* g_pFile;
CExportTable::CExportTable(CWnd* pParent /*=NULL*/)
: CDialog(CExportTable::IDD, pParent)
{
//{{AFX_DATA_INIT(CExportTable)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CExportTable::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CExportTable)
DDX_Control(pDX, IDC_LIST1, m_expList);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CExportTable, CDialog)
//{{AFX_MSG_MAP(CExportTable)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CExportTable message handlers
void CExportTable::OnOK()
{
// TODO: Add extra validation here
//CDialog::OnOK();
}
BOOL CExportTable::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
UIinit();
GetExportInfo();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
//界面初始化
void CExportTable::UIinit()
{
m_expList.InsertColumn(0,TEXT("序号"),LVCFMT_LEFT,80);
m_expList.InsertColumn(1,TEXT("RVA"),LVCFMT_LEFT,80);
m_expList.InsertColumn(2,TEXT("文件偏移"),LVCFMT_LEFT,100);
m_expList.InsertColumn(3,TEXT("名称"),LVCFMT_LEFT,260);
m_expList.SetExtendedStyle(m_expList.GetExtendedStyle()|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
}
//获得导出表信息
void CExportTable::GetExportInfo()
{
m_expList.DeleteAllItems();
DWORD dwExportOffset=0;
//获得导入表的文件偏移
dwExportOffset=RvaToFileOffset(g_dwExportRva,g_SecNum,g_SecHeader);
PIMAGE_EXPORT_DIRECTORY pExp=NULL;
pExp=(PIMAGE_EXPORT_DIRECTORY)(g_pFile+dwExportOffset);
CString szText;
szText.Format("%08X",pExp->Characteristics);
SetDlgItemText(IDC_Characteristics,szText);
szText.Format("%08X",pExp->TimeDateStamp);
SetDlgItemText(IDC_TimeDateStamp,szText);
szText.Format("%08X",pExp->Name);
SetDlgItemText(IDC_NAMERVA,szText);
szText.Format("%08X",pExp->Base);
SetDlgItemText(IDC_BASE,szText);
szText.Format("%08X",pExp->NumberOfFunctions);
SetDlgItemText(IDC_NumberOfFunctions,szText);
szText.Format("%08X",pExp->NumberOfNames);
SetDlgItemText(IDC_NumberOfNames,szText);
szText.Format("%08X",pExp->AddressOfFunctions);
SetDlgItemText(IDC_AddressOfFunctions,szText);
szText.Format("%08X",pExp->AddressOfNameOrdinals);
SetDlgItemText(IDC_AddressOfNameOrdinals,szText);
szText.Format("%08X",pExp->AddressOfNames);
SetDlgItemText(IDC_AddressOfNames,szText);
DWORD dwNameOffset=0;
dwNameOffset=RvaToFileOffset(pExp->Name,g_SecNum,g_SecHeader);
char*pName=NULL;
pName=(char*)(g_pFile+dwNameOffset);
szText.Format("%s",pName);
SetDlgItemText(IDC_NAME,szText);
DWORD dwBase=0;
dwBase=pExp->Base;
for (DWORD j=0;j<pExp->NumberOfFunctions;j++)
{
//先遍历函数地址数组
PDWORD pAddr=(PDWORD)(g_pFile+RvaToFileOffset(pExp->AddressOfFunctions,g_SecNum,g_SecHeader));
//地址有效
if (pAddr[j]!=0)
{
szText.Format("%04X",dwBase+j);
m_expList.InsertItem(j,szText);
szText.Format("%08X",pAddr[j]);
m_expList.SetItemText(j,1,szText);
szText.Format("%08X",RvaToFileOffset(pAddr[j],g_SecNum,g_SecHeader));
m_expList.SetItemText(j,2,szText);
//通过序号得到相应函数名数组下标
//序号数组
PWORD pNum=(PWORD)(g_pFile+RvaToFileOffset(pExp->AddressOfNameOrdinals,g_SecNum,g_SecHeader));
for (WORD k=0;k<pExp->NumberOfNames;k++ )
{
//在序号数组里找序号相同的 找到下标然后读函数名
if (j==pNum[k])
{
//导出函数名(或变量名数组) 得到的是RVA
PDWORD pName=(PDWORD)(g_pFile+RvaToFileOffset(pExp->AddressOfNames,g_SecNum,g_SecHeader));
//注意要转换为文件偏移在读取名字
char *pszName=(char*)(g_pFile+RvaToFileOffset(pName[k],g_SecNum,g_SecHeader));
szText.Format("%s",pszName);
m_expList.SetItemText(j,3,szText);
break;
}
}
}
}
}
//参数一 导入表的RVA 参数2区块表的数目 参数3区块表的首地址
DWORD CExportTable::RvaToFileOffset(DWORD dwRva,DWORD dwSecNum,PIMAGE_SECTION_HEADER pSec)
{
if (dwSecNum==0)
{
return 0;
}
for (DWORD i=0;i<dwSecNum;i++)
{
if (dwRva>=pSec[i].VirtualAddress&&dwRva<pSec[i].VirtualAddress+pSec[i].SizeOfRawData)
{
return dwRva-pSec[i].VirtualAddress+pSec[i].PointerToRawData;
}
}
return 0;
}
|
f72841897cbf33322ca7cf68c5abe29637f4e7b2
|
cb3d8088e0894d9fadaeb3313af850660dff29de
|
/src/Vulkan/VulkanObjectCreation/InstanceCreation.cpp
|
3c041961a2ab2076812b395240cf986c1d5e5df4
|
[
"MIT"
] |
permissive
|
GJHap/VkPong
|
851c900152636ffaa3f957974cb47db6e57962d4
|
bedb9bce32fb3be98a283df02b803d230e5c0176
|
refs/heads/master
| 2022-04-10T03:59:42.790289
| 2020-03-23T02:02:39
| 2020-03-23T02:02:39
| 242,434,854
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,647
|
cpp
|
InstanceCreation.cpp
|
#include "InstanceCreation.hpp"
#include "GLFW/glfw3.h"
namespace vkPong
{
const static std::vector<const char*> INSTANCE_EXTENSIONS
{
"VK_EXT_debug_report"
};
const static std::vector<const char*> INSTANCE_VALIDATION_LAYERS
{
"VK_LAYER_LUNARG_standard_validation"
};
static std::vector<const char*> getVulkanInstanceExtensions()
{
uint32_t extensionCount;
const char** ppExtensions = glfwGetRequiredInstanceExtensions(&extensionCount);
std::vector<const char*> extensions(extensionCount);
std::copy(ppExtensions, ppExtensions + extensionCount, extensions.begin());
return extensions;
}
vk::Instance createInstance()
{
std::vector<const char*> instanceExtensions = getVulkanInstanceExtensions();
std::vector<const char*> enabledLayers;
#ifndef NDEBUG
enabledLayers = INSTANCE_VALIDATION_LAYERS;
std::copy(INSTANCE_EXTENSIONS.begin(), INSTANCE_EXTENSIONS.end(), std::back_inserter(instanceExtensions));
#endif
vk::ApplicationInfo applicationInfo;
applicationInfo.setPApplicationName("VkPong");
applicationInfo.setApplicationVersion(VK_MAKE_VERSION(1, 0, 0));
applicationInfo.setApiVersion(VK_API_VERSION_1_1);
vk::InstanceCreateInfo instanceCreateInfo;
instanceCreateInfo.setPApplicationInfo(&applicationInfo);
instanceCreateInfo.setEnabledLayerCount(static_cast<uint32_t>(enabledLayers.size()));
instanceCreateInfo.setPpEnabledLayerNames(enabledLayers.data());
instanceCreateInfo.setEnabledExtensionCount(static_cast<uint32_t>(instanceExtensions.size()));
instanceCreateInfo.setPpEnabledExtensionNames(instanceExtensions.data());
return vk::createInstance(instanceCreateInfo);
}
}
|
0b5479e757138b827f3b44f95aebf4efd3154b91
|
363ff47ec32297c25c43840d12dae4497b5f0b32
|
/include/Utils/Matrix.h
|
b05cf912193187f30a9c168b9137e023f276bb0d
|
[
"MIT"
] |
permissive
|
pyomeca/biorbd
|
0fd76f36a01bce2e259ddea476d712c60fb79364
|
70265cb1931c463a24f27013350e363134ce6801
|
refs/heads/master
| 2023-06-25T21:07:37.358851
| 2023-06-22T13:38:47
| 2023-06-22T13:38:47
| 124,423,173
| 63
| 43
|
MIT
| 2023-09-14T14:40:58
| 2018-03-08T17:08:37
|
C++
|
UTF-8
|
C++
| false
| false
| 2,238
|
h
|
Matrix.h
|
#ifndef BIORBD_UTILS_MATRIX_H
#define BIORBD_UTILS_MATRIX_H
#include "biorbdConfig.h"
#include "rbdl/rbdl_math.h"
namespace BIORBD_NAMESPACE
{
namespace utils
{
///
/// \brief A wrapper for the Eigen::MatrixXd
///
#ifdef SWIG
class BIORBD_API Matrix
#else
class BIORBD_API Matrix : public RigidBodyDynamics::Math::MatrixNd
#endif
{
public:
///
/// \brief Construct matrix
///
Matrix();
#ifdef BIORBD_USE_EIGEN3_MATH
///
/// \brief Construct matrix from another Eigen matrix
/// \param other The other Eigen matrix
///
template<typename OtherDerived> Matrix(const Eigen::MatrixBase<OtherDerived>&
other) :
Eigen::MatrixXd(other) {}
#endif
#ifdef BIORBD_USE_CASADI_MATH
///
/// \brief Construct matrix from Casadi matrix
/// \param other The matrix to copy
///
Matrix(
const Matrix& other);
///
/// \brief Construct matrix from Casadi matrix
/// \param other The matrix to copy
///
Matrix(
const RigidBodyDynamics::Math::MatrixNd& other);
///
/// \brief Construct matrix from Casadi matrix
/// \param other The matrix to copy
///
Matrix(
const RBDLCasadiMath::MX_Xd_SubMatrix& other);
#endif
///
/// \brief Construct matrix of size nbRows,nbCols
/// \param nbRows Number of rows
/// \param nbCols Number of columns
///
Matrix(
unsigned int nbRows,
unsigned int nbCols);
#ifndef SWIG
#ifdef BIORBD_USE_EIGEN3_MATH
///
/// \brief To use operator= with matrix
/// \param other The other Eigen matrix
///
template<typename OtherDerived>
Matrix& operator=(const Eigen::MatrixBase <OtherDerived>& other)
{
this->Eigen::MatrixXd::operator=(other);
return *this;
}
#endif
#ifdef BIORBD_USE_CASADI_MATH
///
/// \brief operator= For submatrices
/// \param other The matrix to copy
///
void operator=(
const Matrix& other);
///
/// \brief operator= For submatrices
/// \param other The matrix to copy
///
void operator=(
const RBDLCasadiMath::MX_Xd_SubMatrix& other);
#endif
#endif
};
}
}
#endif // BIORBD_UTILS_MATRIX_H
|
ce48d695d58a2a3f966561f1278a63ce2203ef65
|
b57d616af751914298914d94cb42fde311e48cf2
|
/Going_Quackers_Framework/Code/EngineBase/Game Systems/Components/GrapplingHook.h
|
48ac99c51be037cb8a82d8346a1ac8b57279b015
|
[] |
no_license
|
JennyBeanTheSkelepun/GGD-GoingQuackersFramework
|
b2ef18de2926ac589e727f8872f9c4f6a4b0844f
|
a324237b7a34b015511088b6f8c5976dc50a87fd
|
refs/heads/main
| 2023-05-30T12:50:56.385037
| 2021-06-08T09:30:45
| 2021-06-08T09:30:45
| 333,702,828
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,948
|
h
|
GrapplingHook.h
|
#ifndef _GRAPPINGHOOK_H_
#define _GRAPPINGHOOK_H_
#include "Component.h"
#include "../../Data Structures/Vectors.h"
class GrapplingHook : public Component
{
public:
GrapplingHook(GameObject* owner);
~GrapplingHook();
//- Basic Loops -//
void OnDestroy() override;
void Update() override;
//- ImGui UpdateLoop -//
void ImGUIUpdate() override;
//- Scene Save and Load -//
json* SceneSave() override;
void SceneLoad(json* componentJSON) override;
///<summary>Fires the Grappling Hook towards Target Position, Taking in the GameObject firing the Hook as well</summary>
void Fire(Vector2 targetPos, GameObject* handler);
///<summary>Retracts the Grappling Hook to pull the Player Closer. Must of been Fired first</summary>
void Retract();
///<summary>Returns the Grappling Hook to the Player</summary>
void Return();
///<summary>Resets the Hooks Propoties to allow it to be Re-Fired</summary>
void ResetHook();
///<summary> Returns the Distance between the Hook and the Player firing it</summary>
float GetHookDistance();
float GetFiringSpeed() { return m_fireSpeed; }
float GetHookRange() { return m_hookRange; }
///<summary>Returns if the Grappling Hook has hooked onto a object</summary>
bool IsHooked() { return m_hit; }
private:
bool CheckForWallCollision();
void HitWall();
private:
GameObject* mp_handler;
Vector2 m_fireDirection; //The Direction the Grappling Hook is fired
float m_fireSpeed; //The Firing Speed of the Grappling Hook
float m_hookRange; //The Max range of the Grappling Hook
bool m_hit; //Has the Grappling Hook hit a Wall?
bool m_fired; //Has the Grappling Hook fired?
float m_retractSpeed; //The Speed that the Player is pulled towards the Grappling Hook
float m_retractMinimum; //The Minimum Range the Grappling Hook should retract before it is fully retracted
float m_returnSpeed; //The Speed that the Grappling Hook returns to the Player
};
#endif // !_GRAPPINGHOOK_H_
|
1e06bc68dd1ee257759ba3321c59538575659b88
|
6666e7a941745462a00855aafa61a97f8a58ee47
|
/Test/include/EventAction.h
|
1804ea64ab165ac0acfe84b1053e347d035da8db
|
[] |
no_license
|
IvyHong/2nd-SchoolPC
|
572c61ea8e13bad06259d2f04d112286f0ee9b22
|
462a377ad64b83f327f44c060d7e56d95c4df602
|
refs/heads/master
| 2020-04-08T12:27:04.453896
| 2014-02-01T15:54:15
| 2014-02-01T15:54:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 609
|
h
|
EventAction.h
|
#ifndef EVENTACTION_H
#define EVENTACTION_H
#include "G4UserEventAction.hh"
#include "globals.hh"
#include "RunAction.h"
#include "G4ThreeVector.hh"
class RunAction;
class HistoManager;
class G4HCofThisEvent;
class EventAction : public G4UserEventAction
{
public:
// Constructor
EventAction();
// Destructor
virtual ~EventAction();
// Methods
virtual void BeginOfEventAction(const G4Event*);
virtual void EndOfEventAction(const G4Event*);
private:
G4int fHitsCollectionID;
G4int fHitsCollectionID_monitor;
G4int fPrintModulo;
};
#endif // EVENTACTION_H
|
35f5c499970304752f604a39f825c78e19660350
|
fbf0b22759588eafab029b7c1253eccbae0068c3
|
/Sources/Utils/Bounds.hpp
|
8a45b80f889f73816f3641bc416c05a7ab4aacad
|
[
"MIT"
] |
permissive
|
facybenbook/LightweightGraphicCore
|
a835230f91aa1cc04cf6d58bb60b78b50359b1e5
|
655ed35350206401e20bc2fe6063574e1ede603f
|
refs/heads/master
| 2022-01-15T04:08:39.888594
| 2019-06-22T15:15:14
| 2019-06-22T15:15:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 942
|
hpp
|
Bounds.hpp
|
#pragma once
#include <iostream>
#include <string>
#include "IncludeDeps.hpp"
#include GLM_INCLUDE
namespace LWGC
{
class Bounds
{
private:
glm::vec3 _min;
glm::vec3 _max;
public:
Bounds(void);
Bounds(const glm::vec3 & min, const glm::vec3 & max);
Bounds(const float x1, const float y1, const float z1, const float x2, const float y2, const float z2);
Bounds(const Bounds & rhs);
Bounds & operator=(const Bounds & rhs);
float GetMaxX(void) const;
float GetMaxY(void) const;
float GetMaxZ(void) const;
float GetMinX(void) const;
float GetMinY(void) const;
float GetMinZ(void) const;
glm::vec3 GetSize(void) const;
glm::vec3 GetMin(void) const;
glm::vec3 GetMax(void) const;
void Encapsulate(const glm::vec3 & p);
bool Intersects(const glm::vec3 & origin, const glm::vec3 direction);
//...
};
std::ostream & operator<<(std::ostream & o, Bounds const & r);
}
|
3af998c0862232e3dba0944cf551f296b8ad3d14
|
ac7fffccaf78a6496dd7211866b7e0b6118a83d0
|
/Information.h
|
2c905ac14234414a7f274d5ab230c151d33b07a7
|
[] |
no_license
|
mohammadalikhasi/AP_SEC_PRO
|
f8426a1c34427821b7832e14f32e344212229b5d
|
01ff887924dd2ac612f2e1003b01c56e7ad1974e
|
refs/heads/main
| 2023-06-17T02:06:46.092600
| 2021-07-22T02:43:40
| 2021-07-22T02:43:40
| 387,844,398
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 974
|
h
|
Information.h
|
#ifndef INFORMATION_H
#define INFORMATION_H
#include <QDialog>
#include <QPushButton>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
namespace Ui {
class information;
}
class information : public QDialog
{
Q_OBJECT
QPushButton *cls;
QLabel*user1,*user2,*user3,*col1,*col2,*col3;
QLineEdit *line1,*line2,*line3;
QComboBox *bx1,*bx2,*bx3;
public:
QString user11(){
return line1->text();
}
QString color1(){
return bx1->currentText();
}
QString user12(){
return line2->text();
}
QString color2(){
return bx2->currentText();
}
QString user13(){
return line3->text();
}
QString color3(){
return bx3->currentText();
}
public slots:
void CLS();
signals:
void infoadded();
public:
explicit information(QWidget *parent = nullptr);
~information();
private:
Ui::information *ui;
};
#endif // INFORMATION_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.