hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fa0916f810206180426544fdf9db4310b2e390a0 | 12,292 | cxx | C++ | xp_comm_proj/rd_shape/shprdpnt.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 3 | 2020-08-03T08:52:20.000Z | 2021-04-10T11:55:49.000Z | xp_comm_proj/rd_shape/shprdpnt.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | null | null | null | xp_comm_proj/rd_shape/shprdpnt.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 1 | 2021-06-08T18:16:45.000Z | 2021-06-08T18:16:45.000Z | #include "pnt_gen.h"
#include "gsshape.h"
#include "gsesri.h"
int
ReadShape_ReadShapeMods_ReadShapePoint::ReadShapePoint(OMevent_mask event_mask, int seq_num)
{
// ShapeFileName (OMXstr read req notify)
// FeatureNumber (OMXint read notify)
// Coordinates (OMXdouble_array write)
double *Coordinates_arr;
// FeatureID (OMXint_array write)
int *FeatureID_arr;
XP_GIS_ESRI_Shape_c ShapeFile; // shape file reader object
unsigned long ReturnValue; // return from read method
unsigned long LocalNumberOfPoints; // local version of express value
unsigned long LocalFeatureNumber; // local version of express value
unsigned long LocalNumberOfFeatures; // local version of express value
unsigned long LocalShapeType; // local version of express value
unsigned long TotalNumberOfPoints; // total # of points output
//unsigned long TotalNumberOfPointsInFeature; // # of features in 1 feature
unsigned long FeatureStart; // first feature to process
unsigned long FeatureEnd; // last feature to process
long NumberOfPointsInFeature; // # of points in 1 feature
long RecordNumber; // record number read
double *CoordinatesPtr; // ptr to coordinate list
int *FeatureIDPtr; // ptr to feature id list
/***********************/
/* Function's Body */
/***********************/
#ifdef DEBUG
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"I'm in method: ReadShapePoint::ReadShapePoint\n");
#endif
//
// Tell the shape file object what the shape file name is.
//
if (ShapeFile.FileName(ShapeFileName) == NULL)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error opening shape file.\n");
return 0;
}
//
// Print out the header to see what we've got.
//
#ifdef DEBUG
if (ShapeFile.ShapeHeader().PrintFileHeader(cout) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error printing shape file header\n");
return 0;
}
#endif
//
// Validate the header to make sure we have a good shape file.
//
if (ShapeFile.ShapeHeader().ValidateFileHeader() != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error validating shape file header\n");
return 0;
}
//
// Get the shape type.
//
LocalShapeType = ShapeFile.ShapeHeader().ShapeType();
if ((LocalShapeType != XP_GIS_POINT_SHAPE) &&
(LocalShapeType != XP_GIS_MULTIPOINT_SHAPE))
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"The shape type is not point or multipoint.\n");
return 0;
}
//
// Get the number of features in the shape file.
//
if (ShapeFile.NumberOfDataRecords(&LocalNumberOfFeatures) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error getting number of data records\n");
return 0;
}
//
// If the feature number was provided, we want to read only that
// feature. Otherwise, we want to read all the features. FeatureStart
// and FeatureEnd are loop start and end control variables that
// tell us which feature(s) to process.
//
FeatureStart = 1;
FeatureEnd = LocalNumberOfFeatures;
LocalFeatureNumber = (int) FeatureNumber;
if (FeatureNumber.valid_obj())
{
//
// Check to see if the feature number requested is valid.
//
if ((LocalFeatureNumber <= 0) ||
(LocalFeatureNumber > LocalNumberOfFeatures))
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"The feature number is not valid.\n");
return 0;
}
FeatureStart = (unsigned long) (LocalFeatureNumber);
FeatureEnd = FeatureStart;
//
// We are only reading one feature. We need to figure out the
// number of parts and points for the requested feature so we
// can allocate the correct amount of space for the arrays.
//
LocalNumberOfFeatures = 1;
if (LocalShapeType == XP_GIS_POINT_SHAPE)
{
TotalNumberOfPoints = 1;
}
else if (LocalShapeType == XP_GIS_MULTIPOINT_SHAPE)
{
if (ShapeFile.SeekToDataRecord((long) LocalFeatureNumber) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error seeking to the feature.\n");
return 0;
}
if (ShapeFile.GetMultiPointShapeInfo(&RecordNumber,
&NumberOfPointsInFeature) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error getting information for feature.\n");
return 0;
}
else if (RecordNumber != LocalFeatureNumber)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Unexpected record number found.\n");
return 0;
}
TotalNumberOfPoints = NumberOfPointsInFeature;
}
}
else
{
//
// We are going to read all the features in the file. We need to
// figure out the total number of points for all features
// in the file so we can allocate the correct amount of space
// for the arrays.
//
if (ShapeFile.NumberOfPoints(&TotalNumberOfPoints) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error getting number of parts in file.\n");
return 0;
}
}
LocalNumberOfPoints = TotalNumberOfPoints;
//
// Allocate space for the coordinates array.
//
Coordinates_arr = (double *) malloc(sizeof(double) *
(LocalNumberOfPoints * 2));
if (Coordinates_arr == NULL)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error allocating space for coordinate array.\n");
return 0;
}
//
// Allocate space for the feature id array.
//
FeatureID_arr = (int *) malloc(sizeof(int) * LocalNumberOfFeatures);
if (FeatureID_arr == NULL)
{
if (Coordinates_arr != NULL) free(Coordinates_arr);
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error allocating space for FeatureID array.\n");
return 0;
}
//
// Seek to the start of the requested feature.
//
if (ShapeFile.SeekToDataRecord((long) FeatureStart) != XP_GIS_OK)
{
if (Coordinates_arr != NULL) free(Coordinates_arr);
if (FeatureID_arr != NULL) free(FeatureID_arr);
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error seeking to the feature.\n");
return 0;
}
//
// Assign temporary pointers to allow more convenient increment.
//
CoordinatesPtr = Coordinates_arr;
FeatureIDPtr = FeatureID_arr;
//
// This module handles point feature types. It handles both
// shape points and multipoints. Switch based on the shape
// type.
//
switch (LocalShapeType)
{
case XP_GIS_POINT_SHAPE: // point shape type
{
double XPoint; // x point for the feature
double YPoint; // y point for the feature
//
// Loop for each feature.
//
for (LocalFeatureNumber = FeatureStart;
LocalFeatureNumber <= FeatureEnd;
LocalFeatureNumber++)
{
//
// Read the feature.
//
ReturnValue = ShapeFile.ReadPointShape(&RecordNumber,
&XPoint,
&YPoint);
if (ReturnValue != XP_GIS_OK)
{
if (ReturnValue == XP_GIS_EOF)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Reached unexpected end of file.\n");
break;
}
else
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error reading point feature.\n");
continue;
}
}
else if (RecordNumber != LocalFeatureNumber)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Unexpected record number found.\n");
break;
}
else
{
*CoordinatesPtr++ = XPoint; // assign the X coordinate
*CoordinatesPtr++ = YPoint; // assign the Y coordinate
*FeatureIDPtr++ = LocalFeatureNumber; // assign the feature #
}
}
break;
}
case XP_GIS_MULTIPOINT_SHAPE: // multipoint shape type
{
double XMin; // feature X min
double YMin; // feature Y min
double XMax; // feature X max
double YMax; // feature Y max
double *XPoints; // array of feature X coords
double *YPoints; // array of feature Y coords
unsigned long PointNumber; // point # we are working with
long MaximumNumberOfPoints; // max # of pts we can handle
MaximumNumberOfPoints = 0; // init to 0...will be reassigned
XPoints = NULL; // init to NULL...will be allocated
YPoints = NULL; // init to NULL...will be allocated
//
// For each feature in the file
//
for (LocalFeatureNumber = FeatureStart;
LocalFeatureNumber < FeatureEnd;
LocalFeatureNumber++)
{
//
// Read the feature.
//
ReturnValue = ShapeFile.ReadMultiPointShape(&RecordNumber,
&XMin,
&YMin,
&XMax,
&YMax,
&NumberOfPointsInFeature,
&MaximumNumberOfPoints,
&XPoints,
&YPoints);
if (ReturnValue != XP_GIS_OK)
{
if (ReturnValue == XP_GIS_EOF)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Reached unexpected end of file.\n");
break;
}
else
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error reading multipoint feature.\n");
continue;
}
}
else if (RecordNumber != LocalFeatureNumber)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Unexpected record number found.\n");
break;
}
else
{
//
// For each point in the feature.
//
for (PointNumber = 0;
PointNumber < NumberOfPointsInFeature;
PointNumber++)
{
*CoordinatesPtr++ = XPoints[PointNumber]; // assign X coord
*CoordinatesPtr++ = YPoints[PointNumber]; // assign Y coord
*FeatureIDPtr++ = LocalFeatureNumber; // assign feature #
}
}
}
//
// Free the arrays that were allocated by the read method.
//
if (XPoints != NULL) free(XPoints);
if (YPoints != NULL) free(YPoints);
}
default: // Invalid shape type
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"The shape type is not point or multipoint.\n");
return 0;
}
}
//
// Now, set the values that belong to express.
//
NumberOfPoints = (int) LocalNumberOfPoints;
NumberOfFeatures = (int) LocalNumberOfFeatures;
ShapeType = (int) LocalShapeType;
Coordinates.set_array(OM_TYPE_DOUBLE,
(char *) Coordinates_arr,
(int) (LocalNumberOfPoints * 2),
OM_SET_ARRAY_FREE);
FeatureID.set_array(OM_TYPE_INT,
(char *) FeatureID_arr,
(int) LocalNumberOfFeatures,
OM_SET_ARRAY_FREE);
// return 1 for success
return(1);
}
| 30.501241 | 92 | 0.537179 | avs |
fa0cc8fd0f23c1f4fa9ba5bd8faf9bdf174fc2fa | 1,205 | cpp | C++ | codebook/code/Matching/Blossom.cpp | NCTU-PCCA/NCTU_Yggdrasill | 4f086c9737502f69044f574514cf191d536aaf22 | [
"MIT"
] | null | null | null | codebook/code/Matching/Blossom.cpp | NCTU-PCCA/NCTU_Yggdrasill | 4f086c9737502f69044f574514cf191d536aaf22 | [
"MIT"
] | null | null | null | codebook/code/Matching/Blossom.cpp | NCTU-PCCA/NCTU_Yggdrasill | 4f086c9737502f69044f574514cf191d536aaf22 | [
"MIT"
] | null | null | null | #define MAXN 505
vector<int>g[MAXN];//用vector存圖
int pa[MAXN],match[MAXN],st[MAXN],S[MAXN],vis[MAXN];
int t,n;
inline int lca(int u,int v){//找花的花托
for(++t;;swap(u,v)){
if(u==0)continue;
if(vis[u]==t)return u;
vis[u]=t;//這種方法可以不用清空vis陣列
u=st[pa[match[u]]];
}
}
#define qpush(u) q.push(u),S[u]=0
inline void flower(int u,int v,int l,queue<int> &q){
while(st[u]!=l){
pa[u]=v;//所有未匹配邊的pa都是雙向的
if(S[v=match[u]]==1)qpush(v);//所有奇點變偶點
st[u]=st[v]=l,u=pa[v];
}
}
inline bool bfs(int u){
for(int i=1;i<=n;++i)st[i]=i;//st[i]表示第i個點的集合
memset(S+1,-1,sizeof(int)*n);//-1:沒走過 0:偶點 1:奇點
queue<int>q;qpush(u);
while(q.size()){
u=q.front(),q.pop();
for(size_t i=0;i<g[u].size();++i){
int v=g[u][i];
if(S[v]==-1){
pa[v]=u,S[v]=1;
if(!match[v]){//有增廣路直接擴充
for(int lst;u;v=lst,u=pa[v])
lst=match[u],match[u]=v,match[v]=u;
return 1;
}
qpush(match[v]);
}else if(!S[v]&&st[v]!=st[u]){
int l=lca(st[v],st[u]);//遇到花,做花的處理
flower(v,u,l,q),flower(u,v,l,q);
}
}
}
return 0;
}
inline int blossom(){
memset(pa+1,0,sizeof(int)*n);
memset(match+1,0,sizeof(int)*n);
int ans=0;
for(int i=1;i<=n;++i)
if(!match[i]&&bfs(i))++ans;
return ans;
} | 23.173077 | 52 | 0.559336 | NCTU-PCCA |
fa0d99ae5c5f24a96a0bd0f127c0cedd118144ff | 1,214 | cpp | C++ | Problem201-250/p222_2.cpp | dingqunfei/LeetCode | c74a21ea56ee7b35308d2f387ef24ab29b031e24 | [
"Apache-2.0"
] | null | null | null | Problem201-250/p222_2.cpp | dingqunfei/LeetCode | c74a21ea56ee7b35308d2f387ef24ab29b031e24 | [
"Apache-2.0"
] | null | null | null | Problem201-250/p222_2.cpp | dingqunfei/LeetCode | c74a21ea56ee7b35308d2f387ef24ab29b031e24 | [
"Apache-2.0"
] | null | null | null | /**
* @file p222_2.cpp
* @brief
* @author dingqunfei ([email protected])
* @version 1.0
* @date 2021-04-11
*
* @copyright Copyright (c) 2021 DQFLYING
*
* @par :
*
*
* Date : 2021-04-11
* Version : 1.0
* Author : dqflying
* Lisence :
* Description :
*
*
*
*
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root)
{
return 0;
}
int lh = 0, rh = 0;
TreeNode *left = root;
TreeNode *right = root;
while(left)
{
++lh;
left = left->left;
}
while(right)
{
++rh;
right = right->right;
}
if(rh == lh)
{
return pow(2, rh)-1;
}
return 1+countNodes(root->left)+countNodes(root->right);
}
}; | 19.580645 | 93 | 0.474465 | dingqunfei |
fa0e0437ec04fa419d4d14000c86ed654c7fe6b8 | 1,002 | cpp | C++ | CLASSES/inheritance/practice_question2(absract class).cpp | shauryauppal/Algo-DS-StudyMaterial | 1c481f066d21b33ec2533156e75f45fa9b6a7606 | [
"Apache-2.0"
] | 3 | 2020-12-03T14:52:23.000Z | 2021-12-19T09:26:50.000Z | CLASSES/inheritance/practice_question2(absract class).cpp | shauryauppal/Algo-DS-StudyMaterial | 1c481f066d21b33ec2533156e75f45fa9b6a7606 | [
"Apache-2.0"
] | null | null | null | CLASSES/inheritance/practice_question2(absract class).cpp | shauryauppal/Algo-DS-StudyMaterial | 1c481f066d21b33ec2533156e75f45fa9b6a7606 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdio>
using namespace std;
//give act as a virtual class
class give
{
//protected members
protected:
int width,height;
public:
//pure virtual function used
virtual int getarea()=0;
//use to get data
void getheight()
{
cout<<"\nEnter height->";
cin>>height;
}
//used to get data
void getwidth()
{
cout<<"\nEnter width->";
cin>>width;
}
};
//derived class visibility public
class rectangle:public give
{
public:
int getarea()
{
return (height*width);
}
};
//derived class
class triangle:public give
{
public:
int getarea()
{
return ((height*width)/2);
}
};
int main()
{
rectangle r;
r.getheight();
r.getwidth();
cout<<"\nRectange area->"<<r.getarea();
triangle t;
t.getheight();
t.getwidth();
cout<<"\nTriangle area->"<<t.getarea();
return 0;
}
| 17.892857 | 44 | 0.533932 | shauryauppal |
fa116ab2dba71367016ae32a0d280ef1ceac0c7a | 11,082 | cxx | C++ | src/escape.cxx | jktjkt/replxx | 12f2adee7f9123880db1f870c360a88c1f7ba182 | [
"Apache-2.0"
] | 1 | 2019-06-11T06:49:15.000Z | 2019-06-11T06:49:15.000Z | src/escape.cxx | jktjkt/replxx | 12f2adee7f9123880db1f870c360a88c1f7ba182 | [
"Apache-2.0"
] | null | null | null | src/escape.cxx | jktjkt/replxx | 12f2adee7f9123880db1f870c360a88c1f7ba182 | [
"Apache-2.0"
] | 1 | 2019-06-10T16:48:55.000Z | 2019-06-10T16:48:55.000Z | #include "escape.hxx"
#include "io.hxx"
#include "keycodes.hxx"
#ifndef _WIN32
namespace replxx {
namespace EscapeSequenceProcessing { // move these out of global namespace
// This chunk of code does parsing of the escape sequences sent by various Linux
// terminals.
//
// It handles arrow keys, Home, End and Delete keys by interpreting the
// sequences sent by
// gnome terminal, xterm, rxvt, konsole, aterm and yakuake including the Alt and
// Ctrl key
// combinations that are understood by replxx.
//
// The parsing uses tables, a bunch of intermediate dispatch routines and a
// doDispatch
// loop that reads the tables and sends control to "deeper" routines to continue
// the
// parsing. The starting call to doDispatch( c, initialDispatch ) will
// eventually return
// either a character (with optional CTRL and META bits set), or -1 if parsing
// fails, or
// zero if an attempt to read from the keyboard fails.
//
// This is rather sloppy escape sequence processing, since we're not paying
// attention to what the
// actual TERM is set to and are processing all key sequences for all terminals,
// but it works with
// the most common keystrokes on the most common terminals. It's intricate, but
// the nested 'if'
// statements required to do it directly would be worse. This way has the
// advantage of allowing
// changes and extensions without having to touch a lot of code.
static char32_t thisKeyMetaCtrl = 0; // holds pre-set Meta and/or Ctrl modifiers
// This dispatch routine is given a dispatch table and then farms work out to
// routines
// listed in the table based on the character it is called with. The dispatch
// routines can
// read more input characters to decide what should eventually be returned.
// Eventually,
// a called routine returns either a character or -1 to indicate parsing
// failure.
//
char32_t doDispatch(char32_t c, CharacterDispatch& dispatchTable) {
for (unsigned int i = 0; i < dispatchTable.len; ++i) {
if (static_cast<unsigned char>(dispatchTable.chars[i]) == c) {
return dispatchTable.dispatch[i](c);
}
}
return dispatchTable.dispatch[dispatchTable.len](c);
}
// Final dispatch routines -- return something
//
static char32_t normalKeyRoutine(char32_t c) { return thisKeyMetaCtrl | c; }
static char32_t upArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | UP_ARROW_KEY;
}
static char32_t downArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | DOWN_ARROW_KEY;
}
static char32_t rightArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | RIGHT_ARROW_KEY;
}
static char32_t leftArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | LEFT_ARROW_KEY;
}
static char32_t homeKeyRoutine(char32_t) { return thisKeyMetaCtrl | HOME_KEY; }
static char32_t endKeyRoutine(char32_t) { return thisKeyMetaCtrl | END_KEY; }
static char32_t pageUpKeyRoutine(char32_t) {
return thisKeyMetaCtrl | PAGE_UP_KEY;
}
static char32_t pageDownKeyRoutine(char32_t) {
return thisKeyMetaCtrl | PAGE_DOWN_KEY;
}
static char32_t deleteCharRoutine(char32_t) {
return thisKeyMetaCtrl | ctrlChar('H');
} // key labeled Backspace
static char32_t deleteKeyRoutine(char32_t) {
return thisKeyMetaCtrl | DELETE_KEY;
} // key labeled Delete
static char32_t ctrlUpArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | UP_ARROW_KEY;
}
static char32_t ctrlDownArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | DOWN_ARROW_KEY;
}
static char32_t ctrlRightArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | RIGHT_ARROW_KEY;
}
static char32_t ctrlLeftArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | LEFT_ARROW_KEY;
}
static char32_t escFailureRoutine(char32_t) {
beep();
return -1;
}
// Handle ESC [ 1 ; 3 (or 5) <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket1Semicolon3or5Routines[] = {
upArrowKeyRoutine, downArrowKeyRoutine, rightArrowKeyRoutine,
leftArrowKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket1Semicolon3or5Dispatch = {
4, "ABCD", escLeftBracket1Semicolon3or5Routines};
// Handle ESC [ 1 ; <more stuff> escape sequences
//
static char32_t escLeftBracket1Semicolon3Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
thisKeyMetaCtrl |= META;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static char32_t escLeftBracket1Semicolon5Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
thisKeyMetaCtrl |= CTRL;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static CharacterDispatchRoutine escLeftBracket1SemicolonRoutines[] = {
escLeftBracket1Semicolon3Routine, escLeftBracket1Semicolon5Routine,
escFailureRoutine};
static CharacterDispatch escLeftBracket1SemicolonDispatch = {
2, "35", escLeftBracket1SemicolonRoutines};
// Handle ESC [ 1 <more stuff> escape sequences
//
static char32_t escLeftBracket1SemicolonRoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket1SemicolonDispatch);
}
static CharacterDispatchRoutine escLeftBracket1Routines[] = {
homeKeyRoutine, escLeftBracket1SemicolonRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket1Dispatch = {2, "~;",
escLeftBracket1Routines};
// Handle ESC [ 3 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket3Routines[] = {deleteKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket3Dispatch = {1, "~",
escLeftBracket3Routines};
// Handle ESC [ 4 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket4Routines[] = {endKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket4Dispatch = {1, "~",
escLeftBracket4Routines};
// Handle ESC [ 5 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket5Routines[] = {pageUpKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket5Dispatch = {1, "~",
escLeftBracket5Routines};
// Handle ESC [ 6 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket6Routines[] = {pageDownKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket6Dispatch = {1, "~",
escLeftBracket6Routines};
// Handle ESC [ 7 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket7Routines[] = {homeKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket7Dispatch = {1, "~",
escLeftBracket7Routines};
// Handle ESC [ 8 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket8Routines[] = {endKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket8Dispatch = {1, "~",
escLeftBracket8Routines};
// Handle ESC [ <digit> escape sequences
//
static char32_t escLeftBracket0Routine(char32_t c) {
return escFailureRoutine(c);
}
static char32_t escLeftBracket1Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket1Dispatch);
}
static char32_t escLeftBracket2Routine(char32_t c) {
return escFailureRoutine(c); // Insert key, unused
}
static char32_t escLeftBracket3Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket3Dispatch);
}
static char32_t escLeftBracket4Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket4Dispatch);
}
static char32_t escLeftBracket5Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket5Dispatch);
}
static char32_t escLeftBracket6Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket6Dispatch);
}
static char32_t escLeftBracket7Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket7Dispatch);
}
static char32_t escLeftBracket8Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket8Dispatch);
}
static char32_t escLeftBracket9Routine(char32_t c) {
return escFailureRoutine(c);
}
// Handle ESC [ <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracketRoutines[] = {
upArrowKeyRoutine, downArrowKeyRoutine, rightArrowKeyRoutine,
leftArrowKeyRoutine, homeKeyRoutine, endKeyRoutine,
escLeftBracket0Routine, escLeftBracket1Routine, escLeftBracket2Routine,
escLeftBracket3Routine, escLeftBracket4Routine, escLeftBracket5Routine,
escLeftBracket6Routine, escLeftBracket7Routine, escLeftBracket8Routine,
escLeftBracket9Routine, escFailureRoutine};
static CharacterDispatch escLeftBracketDispatch = {16, "ABCDHF0123456789",
escLeftBracketRoutines};
// Handle ESC O <char> escape sequences
//
static CharacterDispatchRoutine escORoutines[] = {
upArrowKeyRoutine, downArrowKeyRoutine, rightArrowKeyRoutine,
leftArrowKeyRoutine, homeKeyRoutine, endKeyRoutine,
ctrlUpArrowKeyRoutine, ctrlDownArrowKeyRoutine, ctrlRightArrowKeyRoutine,
ctrlLeftArrowKeyRoutine, escFailureRoutine};
static CharacterDispatch escODispatch = {10, "ABCDHFabcd", escORoutines};
// Initial ESC dispatch -- could be a Meta prefix or the start of an escape
// sequence
//
static char32_t escLeftBracketRoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracketDispatch);
}
static char32_t escORoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escODispatch);
}
static char32_t setMetaRoutine(char32_t c); // need forward reference
static CharacterDispatchRoutine escRoutines[] = {escLeftBracketRoutine,
escORoutine, setMetaRoutine};
static CharacterDispatch escDispatch = {2, "[O", escRoutines};
// Initial dispatch -- we are not in the middle of anything yet
//
static char32_t escRoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escDispatch);
}
static CharacterDispatchRoutine initialRoutines[] = {
escRoutine, deleteCharRoutine, normalKeyRoutine};
static CharacterDispatch initialDispatch = {2, "\x1B\x7F", initialRoutines};
// Special handling for the ESC key because it does double duty
//
static char32_t setMetaRoutine(char32_t c) {
thisKeyMetaCtrl = META;
if (c == 0x1B) { // another ESC, stay in ESC processing mode
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escDispatch);
}
return doDispatch(c, initialDispatch);
}
char32_t doDispatch(char32_t c) {
EscapeSequenceProcessing::thisKeyMetaCtrl = 0; // no modifiers yet at initialDispatch
return doDispatch(c, initialDispatch);
}
} // namespace EscapeSequenceProcessing // move these out of global namespace
}
#endif /* #ifndef _WIN32 */
| 35.748387 | 86 | 0.750135 | jktjkt |
fa145534ed2ca5a09dd724073d7b787b656e1cc4 | 816 | cpp | C++ | Notebook/codes/estruturas/map.cpp | rodrigoAMF7/Notebook---Maratonas | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | 4 | 2019-01-25T21:22:55.000Z | 2019-03-20T18:04:01.000Z | Notebook/codes/estruturas/map.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | Notebook/codes/estruturas/map.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | // Map é uma variação da estrutura set e sua implementação também é feita utilizando Red- Black Trees. A principal diferença entre um set e um map é o segundo armazena os conjuntos chave, valor e o primeiro apenas chave.
map<string, int> M; // Declaração
M.insert(make_pair("Alana", 10)); //Inserimos uma variável do tipo pair diretamente no map
M["Alana"] = 10; // Relacionando o valor 10 à chave "Alana"
if(M.find("Alana") != M.end()) //Se a chave "Alana" foi inserida no map
cout<<M["Alana"]<<"\n"; //Imprime o valor da chave "Alana", no caso, o valor 10.
M.erase("Alana"); //Apaga o elemento que possui a chave "Alana" do map
// clear(): Apaga todos os elementos.
// size(): Retorna a quantidade de elementos.
// begin(): Retorna um ponteiro para o inicio do map
// end(): Retorna um ponteiro para o final do map | 74.181818 | 220 | 0.714461 | rodrigoAMF7 |
fa1acb3ec000410176148209f2e3ef08501890b6 | 511 | cpp | C++ | Luogu/P3912.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | Luogu/P3912.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | Luogu/P3912.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | // P3912 素数个数
// WzhDnwzWzh
#include <cstring>
#include <cstdio>
const int MAXN = 100000000;
int main() {
int n;
scanf("%d", &n);
static bool a[MAXN + 1];
memset(a, true, sizeof(a));
for (int i = 2; i * i <= n; i++) {
if (a[i]) {
for (int j = i * i; j <= n; j += i) {
if (a[j]) a[j] = false;
}
}
}
int ans = 0;
for (int i = 2; i <= n; i++) {
if (a[i]) ans++;
}
printf("%d\n", ans);
return 0;
} | 15.484848 | 49 | 0.395303 | XenonWZH |
fa1d427f4907498834b2f85ae3fa22c683432fd1 | 7,916 | cpp | C++ | CodeSnippets/rotateMatrix.cpp | Teabeans/CPP_Learn | a767dd323d67fab5c2baffb5aa6dd3f1e6baa35a | [
"MIT"
] | 1 | 2019-01-31T23:42:59.000Z | 2019-01-31T23:42:59.000Z | CodeSnippets/rotateMatrix.cpp | Teabeans/CPP_Learn | a767dd323d67fab5c2baffb5aa6dd3f1e6baa35a | [
"MIT"
] | null | null | null | CodeSnippets/rotateMatrix.cpp | Teabeans/CPP_Learn | a767dd323d67fab5c2baffb5aa6dd3f1e6baa35a | [
"MIT"
] | 1 | 2020-03-04T18:09:15.000Z | 2020-03-04T18:09:15.000Z | //-----------------------------------------------------------------------------|
// Authorship
//-----------------------------------------------------------------------------|
//
// Tim Lum
// [email protected]
// Created: 2018.07.15
// Modified: 2018.08.22
//
/*
1.7 - RotateMatrix() - P.91
Given an image represented by an NxN matrix, where each pixel in the image is 4
bytes, write a method to rotate the image by 90 degrees.
Can you do this in place?
//-----------------------------------------------------------------------------|
// PROBLEM SETUP AND ASSUMPTIONS
//-----------------------------------------------------------------------------|
A left rotation may be performed by calling a right rotation 3 times.
Only the right (clockwise) rotation shall be handled
The nature of the pixel is immaterial; we may handle the pixel as a 32-bit int
Since the problem specifies an N x N matrix, we address a square aspect ratio
To move a pixel
0 1 X 0 1 X
+---+---+ +---+---+ ([0][0] becomes [1][0])
0 | 1 | 2 | 0 | 4 | 1 | ([1][0] becomes [1][1])
+---+---+ +---+---+
1 | 4 | 3 | 1 | 3 | 2 |
+---+---+ +---+---+
Y Y
Output format is ambiguous, though it is implied that the data itself should be
rotated. However, displaying the "image" and its rotated result may also be
acceptable.
//-----------------------------------------------------------------------------|
// NAIVE APPROACH
//-----------------------------------------------------------------------------|
Iterate across every pixel within a quadrant and for (4) times
Identify the 4 sister-pixels
And swap them in turn
0 1 2 X [X][Y] is sister to
+---+---+---+ [XMax - X][Y] which is sister to
0 | 1 | 2 | 3 | [XMax - X][YMax - Y] which is sister to
+---+---+---+ [X][YMax-Y]
1 | 8 | 9 | 4 |
+---+---+---+
2 | 7 | 6 | 5 |
+---+---+---+
The global behavioral rule may be defined as:
The 90 degree rotational position of any pixel in a square matrix with coordinates:
X, Y
Is
(XMax - Y), X
0 1 2 X
+---+---+---+
0 | X | O | X | 0, 0 rotates 90 degrees to
+---+---+---+ 2, 0 which rotates 90 degrees to
1 | O | O | O | 2, 2 which rotates 90 degrees to
+---+---+---+ 0, 2
2 | X | O | X |
+---+---+---+
//-----------------------------------------------------------------------------|
// OPTIMIZATIONS
//-----------------------------------------------------------------------------|
1) The orientation of the image may be stored as a separate value from 0 to 3.
This may then be used to interpret the N, E, S, W orientation of the image
without modifying the image itself.
Effectively, we may interject an orientation filter which appropriately redirects
array access based upon the rotational state of the image.
This has the added benefit of functioning on non-square arrays, and also facilitates
easy addition of -90 and 180 degree rotations.
From an image editing standpoint, interpretation rather than alteration of the base
data will also better preserve image information.
//-----------------------------------------------------------------------------|
// TIME COMPLEXITY
//-----------------------------------------------------------------------------|
Any solution which modifies the original body of data may not complete faster
than in a time complexity of:
O( n^2 )
A filter solution, however, only adds a constant time alteration to the random
access lookup of the parent data. As a "rotation" is merely the toggling of a
rotation byte, the filter may complete in a time complexity of:
O( 1 )
//-----------------------------------------------------------------------------|
// PSEUDOLOGIC
//-----------------------------------------------------------------------------|
Compare string lengths for equality
Declare alphabet table charCounts
For each character in string1
Add 1 to the appropriate table in charCounts
For each character in string2
Subtract 1 from the appropriate table in charCounts
If the result is <0
Return false
//-----------------------------------------------------------------------------|
// CODE (C++)
//-----------------------------------------------------------------------------|
*/
// Compile with:
// $ g++ --std=c++11 01_07_RotateMatrix.cpp -o RotateMatrix
// Run with:
// $ ./RotateMatrix
#include <string>
#include <iostream>
#include <iomanip>
#define WIDTH 3
#define HEIGHT 7
// Rotation control:
// 0 == Base image
// 1 == 90 degree clockwise rotation
// 2 == 180 degree rotation
// 3 == 270 degree rotation
int ROTATION = 0;
int IMAGE[ WIDTH ][ HEIGHT ];
// (+) --------------------------------|
// #printMatrix( )
// ------------------------------------|
// Desc: Print a matrix
// Params: None
// PreCons: None
// PosCons: None
// RetVal: None
void printMatrix( ) {
int xDim = WIDTH;
int yDim = HEIGHT;
if( ROTATION == 0 ) {
// For rows 0 to MAX...
for( int row = 0 ; row < yDim ; row++ ) {
// Print column 0 to MAX
for( int col = 0 ; col < xDim; col++ ) {
std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " ";
}
std::cout << std::endl << std::endl;
}
}
else if( ROTATION == 1 ) {
for( int col = 0 ; col < xDim ; col++ ) {
for( int row = ( yDim - 1 ) ; row >= 0; row-- ) {
std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " ";
}
std::cout << std::endl << std::endl;
}
}
else if ( ROTATION == 2 ) {
for( int row = yDim-1 ; row >= 0 ; row-- ) {
for( int col = ( xDim - 1 ) ; col >= 0 ; col-- ) {
std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " ";
}
std::cout << std::endl << std::endl;
}
}
else if ( ROTATION == 3 ) {
for( int col = ( xDim - 1 ) ; col >= 0 ; col-- ) {
for( int row = 0 ; row < yDim ; row++ ) {
std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " ";
}
std::cout << std::endl << std::endl;
}
}
}
// (+) --------------------------------|
// #rotateMatrix( )
// ------------------------------------|
// Desc: Rotates a matrix
// Params: None
// PreCons: None
// PosCons: None
// RetVal: None
void rotateMatrix( ) {
ROTATION = ( ROTATION + 1 ) % 4;
}
//-----------------------------------------------------------------------------|
// DRIVER
//-----------------------------------------------------------------------------|
// (+) --------------------------------|
// #main( int, char* )
// ------------------------------------|
// Desc: Code driver
// Params: int arg1 - The number of command line arguments passed in
// char* arg2 - The content of the command line arguments
// PreCons: None
// PosCons: None
// RetVal: int - The exit code (0 for normal, -1 for error)
int main( int argc, char* argv[ ] ) {
std::cout << "Test of rotateMatrix( )" << std::endl;
int xDim = WIDTH;
int yDim = HEIGHT;
// For row 0 to MAX
for( int row = 0 ; row < yDim ; row++ ) {
for( int col = 0 ; col < xDim ; col++ ) {
IMAGE[ col ][ row ] = ( xDim * row ) + col;
}
}
printMatrix( );
std::cout << std::endl;
std::cout << "Rotating..." << std::endl << std::endl;
rotateMatrix( );
printMatrix( );
std::cout << std::endl;
std::cout << "Rotating..." << std::endl << std::endl;
rotateMatrix( );
printMatrix( );
std::cout << std::endl;
std::cout << "Rotating..." << std::endl << std::endl;
rotateMatrix( );
printMatrix( );
std::cout << std::endl;
std::cout << "Rotating..." << std::endl << std::endl;
rotateMatrix( );
printMatrix( );
return( 0 );
} // Closing main( int, char* )
// End of file 01_07_RotateMatrix.cpp
| 28.681159 | 84 | 0.457302 | Teabeans |
fa2773883101d19fb4a9236d013891fd8d8796f5 | 2,172 | cpp | C++ | src/e101_200/q1414.cpp | extremedeckguru/leetcode | e45923ccbca7ae1c5f85d8c996392e8b492c1306 | [
"MIT"
] | 9 | 2020-04-09T12:37:50.000Z | 2021-04-01T14:01:14.000Z | src/e101_200/q1414.cpp | extremedeckguru/leetcode | e45923ccbca7ae1c5f85d8c996392e8b492c1306 | [
"MIT"
] | 3 | 2020-05-05T02:43:54.000Z | 2020-05-20T11:12:16.000Z | src/e101_200/q1414.cpp | extremedeckguru/leetcode | e45923ccbca7ae1c5f85d8c996392e8b492c1306 | [
"MIT"
] | 5 | 2020-04-17T02:32:10.000Z | 2020-05-20T10:12:26.000Z | /*
#面试刷题# 第0101期
#Leetcode# Q1414 找出和为K的斐波那契数的最小个数
难度:中
给定一个数k,返回其总和等于k的斐波那契数的最小值,一个斐波那契数是否可以多次使用。
斐波那契数的定义为。
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 ,对于 n > 2。
可以保证,对于给定的约束,我们总是可以找到这样的斐波那契数和k。
约束条件:
1 <= k <= 10^9
示例1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
示例2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
示例3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
*/
#include "leetcode.h"
namespace q1414 {
template<typename T>
bool run_testcases() {
T slt;
CHECK_RET(2 == slt.findMinFibonacciNumbers(7));
CHECK_RET(2 == slt.findMinFibonacciNumbers(10));
CHECK_RET(3 == slt.findMinFibonacciNumbers(19));
return true;
}
// Runtime: 4 ms, faster than 79.64%
// Memory Usage: 6.5 MB, less than 100.00%
class Solution {
public:
int findMinFibonacciNumbers(int k) {
// compute fibonacci
vector<int> fib{1,1};
for (int i=0; fib[i] + fib[i+1] <= k; ++i) {
fib.push_back(fib[i] + fib[i+1]);
}
// search answer starting from the bigger
int ret = 0;
for (auto iter = fib.rbegin(); iter != fib.rend(); ++iter) {
if (*iter > k) {continue;}
k -= *iter;
++ret;
if(0 == k) {break;}
}
return ret;
}
};
TEST(Q1414, Solution) {EXPECT_TRUE(run_testcases<Solution>());}
// @Tiabeanie2
class Solution02 {
public:
int findMinFibonacciNumbers(int k) {
vector<int> fibos = {1, 1};
while (fibos.back() < 1e9)
{
fibos.push_back(fibos.back() + fibos[fibos.size() - 2]);
}
int ans = 0;
while (k > 1)
{
auto it = std::lower_bound(fibos.begin(), fibos.end(), k);
if (*it == k)
{
ans ++;
break;
}
--it;
ans ++;
k -= *it;
}
if (k == 1) ans ++;
return ans;
}
};
TEST(Q1414, Solution02) {EXPECT_TRUE(run_testcases<Solution02>());}
}; // nam;espace q1414
| 21.939394 | 70 | 0.521179 | extremedeckguru |
fa33c7e062e7c5ed1374704d895628d0627ec2a1 | 2,474 | hpp | C++ | include/rcppmath/clamp.hpp | shumov-ag/rcpputils | a7898d98ab684bb5d0cb2c20c823a1b4014fa0dc | [
"Apache-2.0"
] | 14 | 2019-05-05T06:36:41.000Z | 2022-02-11T06:43:37.000Z | include/rcppmath/clamp.hpp | shumov-ag/rcpputils | a7898d98ab684bb5d0cb2c20c823a1b4014fa0dc | [
"Apache-2.0"
] | 125 | 2019-02-26T18:38:18.000Z | 2022-01-21T20:18:59.000Z | include/rcppmath/clamp.hpp | shumov-ag/rcpputils | a7898d98ab684bb5d0cb2c20c823a1b4014fa0dc | [
"Apache-2.0"
] | 39 | 2019-02-26T18:12:29.000Z | 2022-03-11T15:23:01.000Z | // Copyright 2020 PAL Robotics S.L.
//
// 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.
/*! \file clamp.hpp
* \brief Restrict a value between two bounds.
*/
#ifndef RCPPMATH__CLAMP_HPP_
#define RCPPMATH__CLAMP_HPP_
#include <cassert>
namespace rcppmath
{
/**
* If v compares less than lo, returns lo; otherwise if hi compares less
* than v, returns hi; otherwise returns v. Uses operator< to compare the values.
*
* \param[in] v The value to clamp.
* \param[in] lo The lower boundary.
* \param[in] hi The higher boundary.
* \return Reference to lo if v is less than lo, reference to hi if hi is less than v, otherwise
* reference to v.
* \note Implementation from https://en.cppreference.com/w/cpp/algorithm/clamp.
* \warning Capturing the result of clamp by reference if one of the parameters is rvalue produces
* a dangling reference if that parameter is returned.
*/
template<class T>
constexpr const T & clamp(const T & v, const T & lo, const T & hi)
{
assert(!(hi < lo) );
return (v < lo) ? lo : (hi < v) ? hi : v;
}
/**
* Performs clamping with a provided Comparison object (comp).
*
* \param[in] v The value to clamp.
* \param[in] lo The lower boundary.
* \param[in] hi The higher boundary.
* \param[in] comp Comparison object that returns true if the first argument is
* less than the second.
* \return Reference to lo if v is less than lo, reference to hi if hi is less than v, otherwise
* reference to v. "Less than" semantics determined by Comparison object.
* \warning Capturing the result of clamp by reference if one of the parameters is rvalue produces
* a dangling reference if that parameter is returned.
* \sa rcppmath::clamp(const T&, const T&, const T&)
*/
template<class T, class Compare>
constexpr const T & clamp(const T & v, const T & lo, const T & hi, Compare comp)
{
assert(!comp(hi, lo) );
return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
}
} // namespace rcppmath
#endif // RCPPMATH__CLAMP_HPP_
| 35.342857 | 98 | 0.710994 | shumov-ag |
fa35dd16f796e2efc6d61495c26e22b135919be9 | 406 | cpp | C++ | src/techniques/lrel.cpp | shibii/nn | 2022ec423c3bfe179997630d6ba705aeaabdd918 | [
"MIT"
] | 1 | 2020-11-17T14:25:28.000Z | 2020-11-17T14:25:28.000Z | src/techniques/lrel.cpp | shibii/nn | 2022ec423c3bfe179997630d6ba705aeaabdd918 | [
"MIT"
] | null | null | null | src/techniques/lrel.cpp | shibii/nn | 2022ec423c3bfe179997630d6ba705aeaabdd918 | [
"MIT"
] | null | null | null | #include "lrel.hpp"
namespace nn {
LReL::LReL(float leak) : leak_(leak) {}
void LReL::forward(Feed &f) {
input_ = f.signal;
f.signal = (input_ > 0.f) * input_ + (input_ <= 0.f) * input_ * leak_;
}
void LReL::backward(Feed &f) {
f.signal = (input_ > 0.f) * f.signal + (input_ <= 0.f) * f.signal * leak_;
}
template <class Archive>
void LReL::serialize(Archive &ar) {
ar(leak_);
}
} // namespace nn | 25.375 | 76 | 0.618227 | shibii |
fa3601c6cb60c9c0200636a17693bc5d3438e55b | 471 | cpp | C++ | BASIC c++/pointer-and-referencers/pointer1.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/pointer-and-referencers/pointer1.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/pointer-and-referencers/pointer1.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | //
// Created by Rahul on 6/5/2019.
//
#include <iostream>
#include<math.h>
using namespace std;
int var,*ptr;
int main()
{
var=100;
ptr=&var;
cout<<"value of var "<<var<<"address of ptr"<<&var<<endl;
cout<<"value pf ptr "<<ptr<<"address od ptr "<<&ptr<<endl;
long a=10,b;
long *ptr;
ptr=&a;
b=*ptr;
cout<<ptr<<endl<<b<<endl;
double x,y,*px;
px=&x;
*px=12;
*px+=4.5;
cout<<sin(*px)<<endl<<x<<endl;
return 0;
}
| 17.444444 | 62 | 0.532909 | jattramesh |
fa3685a95830cfa707379fe292adfeb218693d7e | 76,936 | hpp | C++ | snark-logic/libs-source/marshalling/include/nil/marshalling/options.hpp | idealatom/podlodkin-freeton-year-control | 6aa96e855fe065c9a75c76da976a87fe2d1668e6 | [
"MIT"
] | null | null | null | snark-logic/libs-source/marshalling/include/nil/marshalling/options.hpp | idealatom/podlodkin-freeton-year-control | 6aa96e855fe065c9a75c76da976a87fe2d1668e6 | [
"MIT"
] | null | null | null | snark-logic/libs-source/marshalling/include/nil/marshalling/options.hpp | idealatom/podlodkin-freeton-year-control | 6aa96e855fe065c9a75c76da976a87fe2d1668e6 | [
"MIT"
] | 1 | 2021-09-15T20:27:27.000Z | 2021-09-15T20:27:27.000Z | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2021 Mikhail Komarov <[email protected]>
// Copyright (c) 2020-2021 Nikita Kaskov <[email protected]>
//
// MIT License
//
// 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.
//---------------------------------------------------------------------------//
/// @file
/// Contains definition of all the options used by the @b Marshalling library
#ifndef MARSHALLING_OPTIONS_HPP
#define MARSHALLING_OPTIONS_HPP
#include <tuple>
#include <type_traits>
#include <limits>
#include <ratio>
#include <cstdint>
#include <cstddef>
#include <nil/marshalling/endianness.hpp>
#include <nil/marshalling/units_types.hpp>
#include <nil/marshalling/status_type.hpp>
#include <nil/marshalling/types/optional_mode.hpp>
namespace nil {
namespace marshalling {
namespace option {
namespace detail {
template<typename T>
struct is_ratio_t {
static const bool value = false;
};
template<std::intmax_t TNum, std::intmax_t TDen>
struct is_ratio_t<std::ratio<TNum, TDen>> {
static const bool value = true;
};
template<typename T>
constexpr bool is_ratio() {
return is_ratio_t<T>::value;
}
} // namespace detail
// message/field_t common options
/// @brief options to specify endian.
/// @tparam TEndian endian_type type. Must be either nil::marshalling::endian::big_endian or
/// nil::marshalling::endian::little_endian.
/// @headerfile nil/marshalling/options.hpp
template<typename TEndian>
struct endian { };
/// @brief Alias option to endian_type specifying big endian.
/// @headerfile nil/marshalling/options.hpp
using big_endian = endian<nil::marshalling::endian::big_endian>;
/// @brief Alias option to endian_type specifying little endian.
/// @headerfile nil/marshalling/options.hpp
using little_endian = endian<nil::marshalling::endian::little_endian>;
/// @brief No-op option, doesn't have any effect.
/// @headerfile nil/marshalling/options.hpp
struct empty_option { };
/// @brief Option used to specify type of the ID.
/// @tparam T Type of the message ID.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct msg_id_type { };
/// @brief Option used to specify type of iterator used for reading.
/// @tparam TIter Type of the iterator.
/// @headerfile nil/marshalling/options.hpp
template<typename TIter>
struct read_iterator { };
/// @brief Option used to specify type of iterator used for writing.
/// @tparam TIter Type of the iterator.
/// @headerfile nil/marshalling/options.hpp
template<typename TIter>
struct write_iterator { };
/// @brief Option used to add @b get_id() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct id_info_interface { };
/// @brief Option used to add @b valid() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct valid_check_interface { };
/// @brief Option used to add @b length() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct length_info_interface { };
/// @brief Option used to add @b refresh() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct refresh_interface { };
/// @brief Option used to add @b name() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct name_interface { };
/// @brief Option used to specify type of the message handler.
/// @tparam T Type of the handler.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct handler { };
/// @brief Option used to specify numeric ID of the message.
/// @tparam TId Numeric ID value.
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TId>
struct static_num_id_impl { };
/// @brief Option used to specify that message doesn't have valid ID.
/// @headerfile nil/marshalling/options.hpp
struct no_id_impl { };
/// @brief Option used to specify actual type of the message.
/// @headerfile nil/marshalling/options.hpp
template<typename TMsg>
struct msg_type { };
/// @brief Option used to inhibit default implementation of @b dispatch_impl()
/// in nil::marshalling::message_base.
/// @headerfile nil/marshalling/options.hpp
struct no_dispatch_impl { };
/// @brief Option used to specify some extra fields from transport framing.
/// @details Some fields from transport framing may influence the way on how
/// message fields get read or written. It may also have an influence on
/// how message is handled. This option is intended to provide a list
/// of such fields, bundled in @b std::tuple, to @ref nil::marshalling::message interface
/// class.
/// @tparam TFields The fields of the message bundled in std::tuple.
/// @headerfile nil/marshalling/options.hpp
template<typename TFields>
struct extra_transport_fields { };
/// @brief Option used to specify index of the version field inside
/// extra transport fields tuple provided with @ref
/// nil::marshalling::option::extra_transport_fields_type option.
/// @tparam TIdx Index of the field inside the tuple.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TIdx>
struct version_in_extra_transport_fields { };
/// @brief Option used to specify fields of the message and force implementation
/// of default read, write, validity check, and length retrieval information
/// of the message.
/// @tparam TFields The fields of the message bundled in std::tuple.
/// @headerfile nil/marshalling/options.hpp
template<typename TFields>
struct fields_impl;
/// @cond SKIP_DOC
template<typename... TFields>
struct fields_impl<std::tuple<TFields...>> { };
/// @endcond
/// @brief Alias to FieldsImpl<std::tuple<> >
/// @headerfile nil/marshalling/options.hpp
using zero_fields_impl = fields_impl<std::tuple<>>;
/// @brief Option that inhibits implementation of nil::marshalling::message_base::read_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_read_impl { };
/// @brief Option that inhibits implementation of nil::marshalling::message_base::write_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_write_impl { };
/// @brief Option that inhibits implementation of nil::marshalling::message_base::valid_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_valid_impl { };
/// @brief Option that inhibits implementation of nil::marshalling::message_base::length_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_length_impl { };
/// @brief Option that inhibits implementation of nil::marshalling::message_base::refresh_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_refresh_impl { };
/// @brief Option that notifies nil::marshalling::message_base about existence of
/// @b eval_get_id() member function in derived class.
/// @headerfile nil/marshalling/options.hpp
struct has_do_get_id { };
/// @brief Option that notifies nil::marshalling::message_base about existence of
/// access to fields.
/// @details Can be useful when there is a chain of inheritances from
/// nil::marshalling::message_base.
/// @headerfile nil/marshalling/options.hpp
struct assume_fields_existence { };
/// @brief Option that forces "in place" allocation with placement "new" for
/// initialisation, instead of usage of dynamic memory allocation.
/// @headerfile nil/marshalling/options.hpp
struct in_place_allocation { };
/// @brief Option used to allow @ref nil::marshalling::generic_message generation inside
/// @ref nil::marshalling::msg_factory and/or @ref nil::marshalling::protocol::MsgIdLayer classes.
/// @tparam TGenericMessage Type of message, expected to be a variant of
/// @ref nil::marshalling::generic_message.
template<typename TGenericMessage>
struct support_generic_message { };
/// @brief Option used to specify number of bytes that is used for field serialization.
/// @details Applicable only to numeric fields, such as nil::marshalling::types::integral or
/// nil::marshalling::types::enumeration.
///
/// For example, protocol specifies that some field is serialized using
/// only 3 bytes. There is no basic integral type that takes 3 bytes
/// of space exactly. The closest alternative is std::int32_t or
/// std::uint32_t. Such field may be defined as:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint32_t,
/// nil::marshalling::option::fixed_length<3>
/// >;
/// @endcode
/// @tparam TLen length of the serialized value.
/// @tparam TSignExtend Perform sign extension, relevant only to signed types.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TLen, bool TSignExtend = true>
struct fixed_length { };
/// @brief Option used to specify number of bits that is used for field serialization
/// when a field is a member of nil::marshalling::types::bitfield.
/// @details For example, the protocol specifies that two independent integer
/// values of 6 and 10 bits respectively packed into two bytes to save space.
/// Such combined field may be defined as:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::bitfield<
/// MyFieldBase,
/// std::tuple<
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint8_t,
/// nil::marshalling::option::fixed_bit_length<6>
/// >,
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint16_t,
/// nil::marshalling::option::fixed_bit_length<10>
/// >
/// >
/// >;
/// @endcode
/// @tparam TLen length of the serialized value in bits.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TLen>
struct fixed_bit_length { };
/// @brief Option used to specify that field may have variable serialization length
/// @details Applicable only to numeric fields, such as nil::marshalling::types::integral
/// or nil::marshalling::types::enumeration.
/// Use this option to specify that serialized value has
/// <a href="https://en.wikipedia.org/wiki/Variable-length_quantity">Base-128</a>
/// encoding, i.e. the most significant bit in the byte indicates whether
/// the encoding of the value is complete or the next byte in
/// sequence still encodes the current integer value. For example field
/// which value can be serialized using between 1 and 4 bytes can be
/// defined as:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint32_t,
/// nil::marshalling::option::var_length<1, 4>
/// >;
/// @endcode
/// @tparam TMin Minimal length the field may consume.
/// @tparam TMax Maximal length the field may consume.
/// @pre TMin <= TMax
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TMin, std::size_t TMax>
struct var_length {
static_assert(TMin <= TMax, "TMin must not be greater that TMax.");
};
/// @brief Option to specify numeric value serialization offset.
/// @details Applicable only to numeric fields such as nil::marshalling::types::integral or
/// nil::marshalling::types::enumeration.
/// The provided value will be added to the field's value and the
/// result will be written to the buffer when serialising. Good example
/// for such option would be serialising a "current year" value. Most protocols
/// now specify it as an offset from year 2000 or later and written as a
/// single byte, i.e. to specify year 2015 is to write value 15.
/// However it may be inconvenient to manually adjust serialized/deserialized
/// value by predefined offset 2000. To help with such case option
/// nil::marshalling::option::num_value_ser_offset can be used. For example:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint16_t,
/// nil::marshalling::option::fixed_length<1>,
/// nil::marshalling::option::num_value_ser_offset<-2000>
/// >;
/// @endcode
/// Note that in the example above the field value (accessible by @b value() member
/// function of the field) will have type std::uint16_t and will be equal to
/// say 2015, while when serialized it consumes only 1 byte (thanks to
/// nil::marshalling::option::fixed_length option) and reduced value of 15 is written.
/// @tparam TOffset Offset value to be added when serialising field.
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TOffset>
struct num_value_ser_offset { };
/// @brief Option that forces usage of embedded uninitialised data area instead
/// of dynamic memory allocation.
/// @details Applicable to fields that represent collection of raw data or other
/// fields, such as nil::marshalling::types::array_list or nil::marshalling::types::string. By
/// default, these fields will use
/// <a href="http://en.cppreference.com/w/cpp/container/vector">std::vector</a> or
/// <a href="http://en.cppreference.com/w/cpp/string/basic_string">std::string</a>
/// for their internal data storage. If this option is used, it will force
/// such fields to use @ref nil::marshalling::container::static_vector or @ref
/// nil::marshalling::container::static_string with the capacity provided by this option.
/// @tparam TSize Size of the storage area in number of elements, for strings it does @b NOT include
/// the '\0' terminating character.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TSize>
struct fixed_size_storage { };
/// @brief Set custom storage type for fields like nil::marshalling::types::string or
/// nil::marshalling::types::array_list.
/// @details By default nil::marshalling::types::string uses
/// <a href="http://en.cppreference.com/w/cpp/string/basic_string">std::string</a>
/// and nil::marshalling::types::array_list uses
/// <a href="http://en.cppreference.com/w/cpp/container/vector">std::vector</a> as
/// their internal storage types. The @ref fixed_size_storage option forces
/// them to use nil::marshalling::container::static_string and
/// nil::marshalling::container::static_vector instead. This option can be used to provide any other
/// third party type. Such type must define the same public interface as @b std::string (when used with
/// nil::marshalling::types::string) or @b std::vector (when used with
/// nil::marshalling::types::array_list).
/// @tparam TType Custom storage type
/// @headerfile nil/marshalling/options.hpp
template<typename TType>
struct custom_storage_type { };
/// @brief Option to specify scaling ratio.
/// @details Applicable only to nil::marshalling::types::integral.
/// Sometimes the protocol specifies values being transmitted in
/// one units while when handling the message they are better to be handled
/// in another. For example, some distance information is transmitted as
/// integer value of millimetres, but while processing it should be handled as floating
/// point value of meters. Such field is defined as:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::int32_t,
/// nil::marshalling::option::scaling_ratio<1, 100>
/// >;
/// @endcode
/// Then, to accessed the scaled value of the field use @b scale_as() or
/// @b set_scaled() methods of nil::marshalling::types::integral field:
/// @code
/// void processField(const MyField& field)
/// {
/// auto distInMillimetres = field.value();
/// auto distInMeters = field.scale_as<double>();
/// }
/// @endcode
/// @tparam TNum Numerator of the scaling ratio.
/// @tparam TDenom Denominator of the scaling ratio.
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TNum, std::intmax_t TDenom>
struct scaling_ratio {
static_assert(TNum != 0, "Wrong scaling ratio");
static_assert(TDenom != 0, "Wrong scaling ratio");
};
/// @brief Option that modifies the default behaviour of collection fields to
/// prepend the serialized data with number of @b elements information.
/// @details Quite often when collection of fields is serialized it must be
/// prepended with one or more bytes indicating number of elements that will
/// follow.
/// Applicable to fields that represent collection of raw data or other
/// fields, such as nil::marshalling::types::array_list or nil::marshalling::types::string.@n
/// For example sequence of raw bytes must be prefixed with 2 bytes stating
/// the size of the sequence:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::array_list<
/// MyFieldBase,
/// std::uint8_t,
/// nil::marshalling::option::sequence_size_field_prefix_type<
/// nil::marshalling::types::integral<MyFieldBase, std::uint16_t>
/// >
/// >;
/// @endcode
/// @tparam TField Type of the field that represents size
/// @headerfile nil/marshalling/options.hpp
template<typename TField>
struct sequence_size_field_prefix { };
/// @brief Option that modifies the default behaviour of collection fields to
/// prepend the serialized data with number of @b bytes information.
/// @details Similar to @ref sequence_size_field_prefix_type, but instead of
/// number of @b elements to follow, the prefix field contains number of
/// @b bytes that will follow.
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::array_list<
/// MyFieldBase,
/// nil::marshalling::types::bundle<
/// std::tuple<
/// nil::marshalling::types::integral<MyFieldBase, std::uint32_t>,
/// nil::marshalling::types::string<MyFieldBase>
/// >
/// >,
/// nil::marshalling::option::sequence_ser_length_field_prefix_type<
/// nil::marshalling::types::integral<MyFieldBase, std::uint16_t>
/// >
/// >;
/// @endcode
/// @tparam TField Type of the field that represents serialization length
/// @tparam TReadErrorStatus Error status to return in case read operation fails when should not
/// @headerfile nil/marshalling/options.hpp
template<typename TField,
status_type TReadErrorStatus = status_type::invalid_msg_data>
struct sequence_ser_length_field_prefix { };
/// @brief Option that forces <b>every element</b> of @ref nil::marshalling::types::array_list to
/// be prefixed with its serialization length.
/// @details Similar to @ref sequence_ser_length_field_prefix_type but instead of the whole
/// list, every element is prepended with its serialization length.
/// @tparam TField Type of the field that represents serialization length
/// @tparam TReadErrorStatus Error status to return in case read operation fails when should not
/// @headerfile nil/marshalling/options.hpp
template<typename TField,
status_type TReadErrorStatus = status_type::invalid_msg_data>
struct sequence_elem_ser_length_field_prefix { };
/// @brief Option that forces @b first element only of @ref nil::marshalling::types::array_list to
/// be prefixed with its serialization length.
/// @details Similar to @ref sequence_elem_ser_length_field_prefix_type, but
/// applicable only to the lists where elements are of the same
/// fixed size, where there is no need to prefix @b every element
/// with its size.
/// @tparam TField Type of the field that represents serialization length
/// @tparam TReadErrorStatus Error status to return in case read operation fails when should not
/// @headerfile nil/marshalling/options.hpp
template<typename TField,
status_type TReadErrorStatus = status_type::invalid_msg_data>
struct sequence_elem_fixed_ser_length_field_prefix { };
/// @brief Option that forces termination of the sequence when predefined value
/// is encountered.
/// @details Sometimes protocols use zero-termination for strings instead of
/// prefixing them with their size. Below is an example of how to achieve
/// such termination using sequence_termination_field_suffix option.
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::string<
/// MyFieldBase,
/// nil::marshalling::option::sequence_termination_field_suffix<
/// nil::marshalling::types::integral<MyFieldBase, char,
/// nil::marshalling::option::default_num_value<0> >
/// >
/// >;
/// @endcode
/// @tparam TField Type of the field that represents suffix
/// @headerfile nil/marshalling/options.hpp
template<typename TField>
struct sequence_termination_field_suffix { };
/// @brief Option that forces collection fields to append provides suffix every
/// time it is serialized.
/// @details It is a bit looser version than sequence_termination_field_suffix.
/// Encountering the expected termination value doesn't terminate the
/// read operation on the sequence. The size of the sequence should
/// be defined by other means. For example, zero termination string that
/// occupies exactly 6 bytes when serialized (padded with zeroes at the end)
/// will be defined like this:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::string<
/// MyFieldBase,
/// nil::marshalling::option::sequence_fixed_size<5>,
/// nil::marshalling::option::sequence_trailing_field_suffix<
/// nil::marshalling::types::integral<MyFieldBase, char,
/// nil::marshalling::option::default_num_value<0> >
/// >
/// >;
/// @endcode
/// @tparam TField Type of the field that represents suffix
/// @headerfile nil/marshalling/options.hpp
template<typename TField>
struct sequence_trailing_field_suffix { };
/// @brief Option to enable external forcing of the collection's elements count.
/// @details Sometimes the size information is detached from the data sequence
/// itself, i.e. there may be one or more independent fields between the
/// size field and the first byte of the collection. In such case it becomes
/// impossible to use @ref sequence_size_field_prefix_type option. Instead, the size
/// information must be provided by external calls. Usage of this option
/// enables @b force_read_elem_count() and @b clear_read_elem_count() functions in
/// the collection fields, such as nil::marshalling::types::array_list or
/// nil::marshalling::types::string which can be used to specify the size information after it was read
/// independently.
/// @headerfile nil/marshalling/options.hpp
struct sequence_size_forcing_enabled { };
/// @brief Option to enable external forcing of the collection's serialization length
/// duting "read" operation.
/// @details Sometimes the length information is detached from the data sequence
/// itself, i.e. there may be one or more independent fields between the
/// length field and the first byte of the collection. In such case it becomes
/// impossible to use @ref sequence_ser_length_field_prefix_type option. Instead, the length
/// information must be provided by external calls. Usage of this option
/// enables @b force_read_length() and @b clear_read_length_forcing() functions in
/// the collection fields, such as nil::marshalling::types::array_list or
/// nil::marshalling::types::string which can be used to specify the size information after it was read
/// independently.
/// @headerfile nil/marshalling/options.hpp
struct sequence_length_forcing_enabled { };
/// @brief Option to enable external forcing of the collection element
/// serialization length.
/// @details Some protocols may prefix the variable length lists with serialization
/// length of a <b>single element</b> in addition to the number of elements
/// in the list. Usage of this option
/// enables @b force_read_elem_length() and @b clear_read_elem_length_forcing() functions in
/// the nil::marshalling::types::array_list
/// which can be used to specify the element serialization length after it was read
/// independently. @n
/// @headerfile nil/marshalling/options.hpp
struct sequence_elem_length_forcing_enabled { };
/// @brief Option used to define exact number of elements in the collection field.
/// @details Protocol specification may define that there is exact number of
/// elements in the sequence. Use sequence_fixed_size option to convey
/// this information to the field definition, which will force @b read() and
/// @b write() member functions of the collection field to behave as expected.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TSize>
struct sequence_fixed_size { };
/// @brief Option that forces usage of fixed size storage for sequences with fixed
/// size.
/// @details Equivalent to @ref fixed_size_storage option, but applicable only
/// to sequence types @ref nil::marshalling::types::array_list or @ref nil::marshalling::types::string,
/// that alrady use @ref sequence_fixed_size option. Usage of this option do not require knowledge of
/// the storage area size.
/// @headerfile nil/marshalling/options.hpp
struct sequence_fixed_size_use_fixed_size_storage { };
/// @brief Option that specifies default initialisation class.
/// @details Use this option when default constructor of the field must assign
/// some special value. The initialiser class provided as template argument
/// must define the following member function:
/// @code
/// struct MyInitialiser
/// {
/// template <typename TField>
/// void operator()(TField& field) {...}
/// };
/// @endcode
/// For example, we want string field that will have "hello" as its default
/// value. The provided initialiser class with the option will be instantiated
/// and its operator() is invoked which is responsible to assign proper
/// value to the field.
/// @code
/// struct MyStringInitialiser
/// {
/// template <typename TField>
/// void operator()(TField& field) const
/// {
/// field.value() = hello;
/// }
/// };
///
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::string<
/// MyFieldBase,
/// nil::marshalling::option::default_value_initializer<MyStringInitialiser>
/// >;
/// @endcode
/// @tparam T Type of the initialiser class.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct default_value_initialiser { };
/// @brief Option that specifies custom validation class.
/// @details By default, value of every field is considered to be valid
/// (@b valid() member function of the field returns @b true). If there is a need
/// to validate the value of the function, use this option to define
/// custom validation logic for the field. The validation class provided as
/// a template argument to this option must define the following member function:
/// @code
/// struct MyValidator
/// {
/// template <typename TField>
/// bool operator()(const TField& field) {...}
/// };
/// @endcode
/// For example, value of the string field considered to be valid if it's
/// not empty and starts with '$' character.
/// The provided validator class with the option will be instantiated
/// and its operator() will be invoked.
/// @code
/// struct MyStringValidator
/// {
/// template <typename TField>
/// bool operator()(TField& field) const
/// {
/// auto& str = field.value();
/// return (!str.empty()) && (str[0] == '$');
/// }
/// };
///
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::string<
/// MyFieldBase,
/// nil::marshalling::option::contents_validator<MyStringValidator>
/// >;
/// @endcode
/// Note that in the example above the default constructed MyField will
/// have invalid value. To fix that you must also use
/// nil::marshalling::option::default_value_initializer option to specify proper default
/// value.
/// @tparam T Type of the validator class.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct contents_validator { };
/// @brief Option that specifies custom refreshing class.
/// @details The "refreshing" functionality is there to allow bringing field's
/// contents into a consistent state if it's not. The default "refreshing"
/// functionality does nothing and returns @b false (meaning nothing has
/// been changed). If there is a need to provide custom refreshing functionality
/// use this option and provide custom refresher class. It must
/// define the following member function:
/// @code
/// struct MyRefresher
/// {
/// template <typename TField>
/// bool operator()(TField& field) {
/// ... // return true if field's contents changed
/// }
/// };
/// @endcode
/// @tparam T Type of the refresher class.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct contents_refresher { };
/// @brief Option that specifies custom value reader class.
/// @details It may be useful to override default reading functionality for complex
/// fields, such as nil::marshalling::types::bundle, where the way members are read is
/// defined by the values of other members. For example, bundle of two integer
/// fields, the first one is normal, and the second one is optional.
/// The optional mode of the latter is determined by
/// the value of the first field. If its value is 0, than the second
/// member exists, otherwise it's missing.
/// @code
/// typedef nil::marshalling::types::bundle<
/// nil::marshalling::field_type<BigEndianOpt>,
/// std::tuple<
/// nil::marshalling::types::integral<
/// nil::marshalling::field_type<BigEndianOpt>,
/// std::uint8_t
/// >,
/// nil::marshalling::types::optional<
/// nil::marshalling::types::integral<
/// nil::marshalling::field_type<BigEndianOpt>,
/// std::uint16_t
/// >
/// >
/// >,
/// nil::marshalling::option::custom_value_reader<MyCustomReader>
/// > field_type;
/// @endcode
/// The @b MyCustomReader custom reading class may implement required
/// functionality of reading the first member, analysing its value, setting
/// appropriate mode for the second one and read the second member.
///
/// The custom value reader class provided as template argument
/// must define the following member function:
/// @code
/// struct MyCustomReader
/// {
/// template <typename TField, typename TIter>
/// nil::marshalling::ErrorStatus operator()(TField& field, TIter& iter, std::size_t len) {...}
/// };
/// @endcode
///
/// The custom reader for the example above may be implemented as:
/// @code
/// struct MyCustomReader
/// {
/// template <typename TField, typename TIter>
/// nil::marshalling::ErrorStatus operator()(TField& field, TIter& iter, std::size_t len) const
/// {
/// auto& members = field.value();
/// auto& first = std::get<0>(members);
/// auto& second = std::get<1>(members);
///
/// auto es = first.read(iter, len);
/// if (es != nil::marshalling::ErrorStatus::Success) {
/// return es;
/// }
///
/// if (first.value() != 0) {
/// second.set_mode(nil::marshalling::types::optional_mode::missing);
/// }
/// else {
/// second.set_mode(nil::marshalling::types::optional_mode::exists);
/// }
///
/// return second.read(iter, len - first.length());
/// }
/// };
/// @endcode
/// @tparam T Type of the custom reader class.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct custom_value_reader { };
/// @brief Option that forces field's read operation to fail if invalid value
/// is received.
/// @details Sometimes protocol is very strict about what field's values are
/// allowed and forces to abandon a message if invalid value is received.
/// If nil::marshalling::option::fail_on_invalid is provided as an option to a field,
/// the validity is going to checked automatically after the read. If invalid
/// value is identified, error will be returned from the @b read() operation.
/// @tparam TStatus Error status to return when the content of the read field is invalid.
/// @headerfile nil/marshalling/options.hpp
template<status_type TStatus = status_type::invalid_msg_data>
struct fail_on_invalid { };
/// @brief Option that forces field's read operation to ignore read data if invalid value
/// is received.
/// @details If this option is provided to the field, the read operation will
/// check the validity of the read value. If it is identified as invalid,
/// the read value is not assigned to the field, i.e. the field's value
/// remains unchanged, although no error is reported.
/// @headerfile nil/marshalling/options.hpp
struct ignore_invalid { };
/// @brief Force the destructor of nil::marshalling::message class to be @b non-virtual,
/// even if there are other virtual functions defined.
/// @headerfile nil/marshalling/options.hpp
struct no_virtual_destructor { };
/// @brief options to specify units of the field.
/// @tparam TType Type of the unints, can be any type from nil::marshalling::traits::units
/// namespace.
/// @tparam TRatio Ratio within the units type, must be a variant of
/// @b std::ratio type.
/// @headerfile nil/marshalling/options.hpp
template<typename TType, typename TRatio>
struct units {
static_assert(detail::is_ratio_t<TRatio>(), "TRatio parameter must be a variant of std::ratio");
static_assert(TRatio::num != 0, "Wrong ratio value");
static_assert(TRatio::den != 0, "Wrong ratio value");
};
/// @brief Alias option, specifying field value units are "nanoseconds".
/// @headerfile nil/marshalling/options.hpp
using units_nanoseconds
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::nanoseconds_ratio>;
/// @brief Alias option, specifying field value units are "microseconds".
/// @headerfile nil/marshalling/options.hpp
using units_microseconds
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::microseconds_ratio>;
/// @brief Alias option, specifying field value units are "milliseconds".
/// @headerfile nil/marshalling/options.hpp
using units_milliseconds
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::milliseconds_ratio>;
/// @brief Alias option, specifying field value units are "seconds".
/// @headerfile nil/marshalling/options.hpp
using units_seconds
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::seconds_ratio>;
/// @brief Alias option, specifying field value units are "minutes".
/// @headerfile nil/marshalling/options.hpp
using units_minutes
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::minutes_ratio>;
/// @brief Alias option, specifying field value units are "hours".
/// @headerfile nil/marshalling/options.hpp
using units_hours
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::hours_ratio>;
/// @brief Alias option, specifying field value units are "days".
/// @headerfile nil/marshalling/options.hpp
using units_days
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::days_ratio>;
/// @brief Alias option, specifying field value units are "weeks".
/// @headerfile nil/marshalling/options.hpp
using units_weeks
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::weeks_ratio>;
/// @brief Alias option, specifying field value units are "nanometers".
/// @headerfile nil/marshalling/options.hpp
using units_nanometers
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::nanometers_ratio>;
/// @brief Alias option, specifying field value units are "micrometers".
/// @headerfile nil/marshalling/options.hpp
using units_micrometers
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::micrometers_ratio>;
/// @brief Alias option, specifying field value units are "millimeters".
/// @headerfile nil/marshalling/options.hpp
using units_millimeters
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::millimeters_ratio>;
/// @brief Alias option, specifying field value units are "centimeters".
/// @headerfile nil/marshalling/options.hpp
using units_centimeters
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::centimeters_ratio>;
/// @brief Alias option, specifying field value units are "meters".
/// @headerfile nil/marshalling/options.hpp
using units_meters
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::meters_ratio>;
/// @brief Alias option, specifying field value units are "kilometers".
/// @headerfile nil/marshalling/options.hpp
using units_kilometers
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::kilometers_ratio>;
/// @brief Alias option, specifying field value units are "nanometers per second".
/// @headerfile nil/marshalling/options.hpp
using units_nanometers_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::nanometers_per_second_ratio>;
/// @brief Alias option, specifying field value units are "micrometers per second".
/// @headerfile nil/marshalling/options.hpp
using units_micrometers_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::micrometers_per_second_ratio>;
/// @brief Alias option, specifying field value units are "millimeters per second".
/// @headerfile nil/marshalling/options.hpp
using units_millimeters_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::millimeters_per_second_ratio>;
/// @brief Alias option, specifying field value units are "centimeters per second".
/// @headerfile nil/marshalling/options.hpp
using units_centimeters_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::centimeters_per_second_ratio>;
/// @brief Alias option, specifying field value units are "meters per second".
/// @headerfile nil/marshalling/options.hpp
using units_meters_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::meters_per_second_ratio>;
/// @brief Alias option, specifying field value units are "kilometers per second".
/// @headerfile nil/marshalling/options.hpp
using units_kilometers_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::kilometers_per_second_ratio>;
/// @brief Alias option, specifying field value units are "kilometers per hour".
/// @headerfile nil/marshalling/options.hpp
using units_kilometers_per_hour = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::kilometers_per_hour_ratio>;
/// @brief Alias option, specifying field value units are "hertz".
/// @headerfile nil/marshalling/options.hpp
using units_hertz
= units<nil::marshalling::traits::units::frequency, nil::marshalling::traits::units::hz_ratio>;
/// @brief Alias option, specifying field value units are "kilohertz".
/// @headerfile nil/marshalling/options.hpp
using units_kilohertz
= units<nil::marshalling::traits::units::frequency, nil::marshalling::traits::units::kilo_hz_ratio>;
/// @brief Alias option, specifying field value units are "megahertz".
/// @headerfile nil/marshalling/options.hpp
using units_megahertz
= units<nil::marshalling::traits::units::frequency, nil::marshalling::traits::units::mega_hz_ratio>;
/// @brief Alias option, specifying field value units are "gigahertz".
/// @headerfile nil/marshalling/options.hpp
using units_gigahertz
= units<nil::marshalling::traits::units::frequency, nil::marshalling::traits::units::giga_hz_ratio>;
/// @brief Alias option, specifying field value units are "degrees".
/// @headerfile nil/marshalling/options.hpp
using units_degrees
= units<nil::marshalling::traits::units::angle, nil::marshalling::traits::units::degrees_ratio>;
/// @brief Alias option, specifying field value units are "radians".
/// @headerfile nil/marshalling/options.hpp
using units_radians
= units<nil::marshalling::traits::units::angle, nil::marshalling::traits::units::radians_ratio>;
/// @brief Alias option, specifying field value units are "nanoamps".
/// @headerfile nil/marshalling/options.hpp
using units_nanoamps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::nanoamps_ratio>;
/// @brief Alias option, specifying field value units are "microamps".
/// @headerfile nil/marshalling/options.hpp
using units_microamps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::microamps_ratio>;
/// @brief Alias option, specifying field value units are "milliamps".
/// @headerfile nil/marshalling/options.hpp
using units_milliamps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::milliamps_ratio>;
/// @brief Alias option, specifying field value units are "amps".
/// @headerfile nil/marshalling/options.hpp
using units_amps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::amps_ratio>;
/// @brief Alias option, specifying field value units are "kiloamps".
/// @headerfile nil/marshalling/options.hpp
using units_kiloamps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::kiloamps_ratio>;
/// @brief Alias option, specifying field value units are "nanovolts".
/// @headerfile nil/marshalling/options.hpp
using units_nanovolts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::nanovolts_ratio>;
/// @brief Alias option, specifying field value units are "microvolts".
/// @headerfile nil/marshalling/options.hpp
using units_microvolts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::microvolts_ratio>;
/// @brief Alias option, specifying field value units are "millivolts".
/// @headerfile nil/marshalling/options.hpp
using units_millivolts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::millivolts_ratio>;
/// @brief Alias option, specifying field value units are "volts".
/// @headerfile nil/marshalling/options.hpp
using units_volts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::volts_ratio>;
/// @brief Alias option, specifying field value units are "kilovolts".
/// @headerfile nil/marshalling/options.hpp
using units_kilovolts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::kilovolts_ratio>;
namespace detail {
template<typename T, T TVal>
struct default_num_value_initialiser {
template<typename TField>
void operator()(TField &&field) {
using field_type = typename std::decay<TField>::type;
using value_type = typename field_type::value_type;
field.value() = static_cast<value_type>(TVal);
}
};
template<std::intmax_t TMinValue, std::intmax_t TMaxValue>
struct num_value_range_validator {
static_assert(TMinValue <= TMaxValue, "Min value must be not greater than Max value");
template<typename TField>
constexpr bool operator()(const TField &field) const {
using MinTag =
typename std::conditional<(std::numeric_limits<decltype(MinValue)>::min() < MinValue),
compare_tag, return_true_tag>::type;
using MaxTag =
typename std::conditional<(MaxValue < std::numeric_limits<decltype(MaxValue)>::max()),
compare_tag, return_true_tag>::type;
return above_min(field.value(), MinTag()) && below_max(field.value(), MaxTag());
}
private:
struct return_true_tag { };
struct compare_tag { };
template<typename TValue>
static constexpr bool above_min(const TValue &value, compare_tag) {
using value_type = typename std::decay<decltype(value)>::type;
return (static_cast<value_type>(MinValue) <= static_cast<value_type>(value));
}
template<typename TValue>
static constexpr bool above_min(const TValue &, return_true_tag) {
return true;
}
template<typename TValue>
static constexpr bool below_max(const TValue &value, compare_tag) {
using value_type = typename std::decay<decltype(value)>::type;
return (value <= static_cast<value_type>(MaxValue));
}
template<typename TValue>
static constexpr bool below_max(const TValue &, return_true_tag) {
return true;
}
static const auto MinValue = TMinValue;
static const auto MaxValue = TMaxValue;
};
template<std::uintmax_t TMask, std::uintmax_t TValue>
struct bitmask_reserved_bits_validator {
template<typename TField>
constexpr bool operator()(TField &&field) const {
using field_type = typename std::decay<TField>::type;
using value_type = typename field_type::value_type;
return (field.value() & static_cast<value_type>(TMask)) == static_cast<value_type>(TValue);
}
};
template<nil::marshalling::types::optional_mode TVal>
struct default_opt_mode_initialiser {
template<typename TField>
void operator()(TField &field) const {
field.set_mode(TVal);
}
};
template<std::size_t TIdx>
struct default_variant_index_initialiser {
template<typename TField>
void operator()(TField &field) {
field.template init_field<TIdx>();
}
};
} // namespace detail
/// @brief Alias to default_value_initializer, it defines initialiser class that
/// assigns numeric value provided as the template argument to this option.
/// @details If the required numeric value is too big (doesn't fit into @b
/// std::intmax_t type), please use @ref DefaultBigUnsignedNumValue option
/// class instead.
/// @tparam TVal Numeric value is to be assigned to the field in default constructor.
/// @see @ref DefaultBigUnsignedNumValue
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TVal>
using default_num_value
= default_value_initialiser<detail::default_num_value_initialiser<std::intmax_t, TVal>>;
/// @brief Alias to default_value_initializer, it defines initialiser class that
/// assigns big unsigned numeric value provided as the template argument to this option.
/// @details If the required numeric value is small enough to fit into @b
/// std::intmax_t type, it is recommended to use @ref default_num_value option
/// class instead.
/// @tparam TVal Numeric value is to be assigned to the field in default constructor.
/// @see @ref DefaultBigUnsignedNumValue
/// @headerfile nil/marshalling/options.hpp
template<std::uintmax_t TVal>
using default_big_unsigned_num_value
= default_value_initialiser<detail::default_num_value_initialiser<std::uintmax_t, TVal>>;
/// @brief Provide range of valid numeric values.
/// @details Quite often numeric fields such as nil::marshalling::types::integral or
/// nil::marshalling::types::enumeration have limited number of valid values ranges.
/// This option can be used multiple times to provide several valid ranges.@n
/// If values are too big to fit into @b std::intmax_t type, please use
/// @ref ValidBigUnsignedNumValueRange option instead.
/// @tparam TMinValue Minimal valid numeric value
/// @tparam TMaxValue Maximal valid numeric value
/// @note The intersection of the provided multiple ranges is @b NOT checked.
/// @warning Some older compilers (@b gcc-4.7) fail to compile valid C++11 code
/// that allows usage of multiple @ref valid_num_value_range options. If this is
/// the case, please don't pass more than one @ref valid_num_value_range option.
/// @see @ref ValidNumValue
/// @see @ref ValidBigUnsignedNumValueRange
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TMinValue, std::intmax_t TMaxValue>
struct valid_num_value_range {
static_assert(TMinValue <= TMaxValue, "Invalid range");
};
/// @brief Clear accumulated ranges of valid values.
struct valid_ranges_clear { };
/// @brief Similar to @ref valid_num_value_range, but overrides (nullifies)
/// all previously set valid values ranges.
/// @see @ref ValidNumValueOverride
/// @see @ref ValidBigUnsignedNumValueRangeOverride
/// @deprecated Use @ref valid_ranges_clear instead.
template<std::intmax_t TMinValue, std::intmax_t TMaxValue>
using valid_num_value_range_override
= std::tuple<valid_num_value_range<TMinValue, TMaxValue>, valid_ranges_clear>;
/// @brief Alias to @ref valid_num_value_range.
/// @details Equivalent to @b valid_num_value_range<TValue, TValue>
template<std::intmax_t TValue>
using valid_num_value = valid_num_value_range<TValue, TValue>;
/// @brief Alias to @ref valid_num_value_rangeOverride.
/// @details Equivalent to @b valid_num_value_rangeOverride<TValue, TValue>
/// @deprecated Use @ref valid_ranges_clear instead.
template<std::intmax_t TValue>
using valid_num_value_override = valid_num_value_range_override<TValue, TValue>;
/// @brief Provide range of valid unsigned numeric values.
/// @details Similar to @ref valid_num_value_range, but dedicated to
/// big unsigned numbers, which don't fit into @b std::intmax_t type.
/// @tparam TMinValue Minimal valid numeric value
/// @tparam TMaxValue Maximal valid numeric value
/// @note The intersection of the provided multiple ranges is @b NOT checked.
/// @warning Some older compilers (@b gcc-4.7) fail to compile valid C++11 code
/// that allows usage of multiple @ref valid_num_value_range options. If this is
/// the case, please don't pass more than one
/// @ref valid_num_value_range or @ref ValidBigUnsignedNumValueRange option.
/// @see @ref valid_num_value_range
/// @see @ref ValidBigUnsignedNumValue
/// @headerfile nil/marshalling/options.hpp
template<std::uintmax_t TMinValue, std::uintmax_t TMaxValue>
struct valid_big_unsigned_num_value_range {
static_assert(TMinValue <= TMaxValue, "Invalid range");
};
/// @brief Similar to @ref ValidBigUnsignedNumValueRange, but overrides (nullifies)
/// all previously set valid values ranges.
/// @see @ref ValidNumValueOverride
/// @see @ref ValidBigUnsignedNumValueOverride
/// @deprecated Use @ref valid_ranges_clear instead.
template<std::uintmax_t TMinValue, std::uintmax_t TMaxValue>
using valid_big_unsigned_num_value_range_override
= std::tuple<valid_big_unsigned_num_value_range<TMinValue, TMaxValue>, valid_ranges_clear>;
/// @brief Alias to @ref ValidBigUnsignedNumValueRange.
/// @details Equivalent to @b ValidBigUnsignedNumValueRange<TValue, TValue>
template<std::uintmax_t TValue>
using valid_big_unsigned_num_value = valid_big_unsigned_num_value_range<TValue, TValue>;
/// @brief Alias to @ref ValidBigUnsignedNumValueRangeOverride.
/// @details Equivalent to @b ValidBigUnsignedNumValueRangeOverride<TValue, TValue>
/// @deprecated Use @ref valid_ranges_clear instead.
template<std::uintmax_t TValue>
using valid_big_unsigned_num_value_override = valid_big_unsigned_num_value_range_override<TValue, TValue>;
/// @brief Alias to contents_validator, it defines validator class that checks
/// that reserved bits of the field have expected values.
/// @details It is usually used with nil::marshalling::types::BitmaskValue field to
/// specify values of the unused/reserved bits.
/// The custom validator will return true if
/// @code
/// (field.value() & TMask) == TValue
/// @endcode
/// @tparam TMask Mask that specifies reserved bits.
/// @tparam TValue Expected value of the reserved bits. Defaults to 0.
/// @headerfile nil/marshalling/options.hpp
template<std::uintmax_t TMask, std::uintmax_t TValue = 0U>
using bitmask_reserved_bits = contents_validator<detail::bitmask_reserved_bits_validator<TMask, TValue>>;
/// @brief Alias to default_value_initializer, it sets default mode
/// to types::optional field.
/// @tparam TVal optional mode value is to be assigned to the field in default constructor.
/// @see @ref MissingByDefault
/// @see @ref ExistsByDefault
/// @headerfile nil/marshalling/options.hpp
template<nil::marshalling::types::optional_mode TVal>
using default_optional_mode = default_value_initialiser<detail::default_opt_mode_initialiser<TVal>>;
/// @brief Alias to @ref DefaultOptionalMode.
/// @details Equivalent to
/// @code
/// DefaultOptionalMode<nil::marshalling::types::optional_mode::missing>
/// @endcode
using missing_by_default = default_optional_mode<nil::marshalling::types::optional_mode::missing>;
/// @brief Alias to @ref DefaultOptionalMode.
/// @details Equivalent to
/// @code
/// DefaultOptionalMode<nil::marshalling::types::optional_mode::exists>
/// @endcode
using exists_by_default = default_optional_mode<nil::marshalling::types::optional_mode::exists>;
/// @brief Alias to DefaultOptionalMode<nil::marshalling::types::OptinalMode::missing>
using optional_missing_by_default = missing_by_default;
/// @brief Alias to DefaultOptionalMode<nil::marshalling::types::OptinalMode::exists>
using optional_exists_by_default = exists_by_default;
/// @brief Alias to default_value_initializer, it initalises nil::marshalling::types::variant field
/// to contain valid default value of the specified member.
/// @tparam TIdx Index of the default member.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TIdx>
using default_variant_index = default_value_initialiser<detail::default_variant_index_initialiser<TIdx>>;
/// @brief Force nil::marshalling::protocol::ChecksumLayer and
/// nil::marshalling::protocol::ChecksumPrefixLayer, to verify checksum prior to
/// forwarding read to the wrapped layer(s).
/// @headerfile nil/marshalling/options.hpp
struct checksum_layer_verify_before_read { };
/// @brief Use "view" on original raw data instead of copying it.
/// @details Can be used with @ref nil::marshalling::types::string and raw data @ref
/// nil::marshalling::types::array_list,
/// will force usage of @ref nil::marshalling::container::string_view and
/// nil::marshalling::container::array_view respectively as data storage type.
/// @note The original data must be preserved until destruction of the field
/// that uses the "view".
/// @note Incompatible with other options that contol data storage type,
/// such as @ref nil::marshalling::option::custom_storage_type or @ref
/// nil::marshalling::option::fixed_size_storage
/// @headerfile nil/marshalling/options.hpp
struct orig_data_view { };
/// @brief Force field not to be serialized during read/write operations
/// @details Some protocols may define some constant values that are predefined
/// and are not present on I/O link when serialized. Sometimes it is convenient
/// to have such values abstracted away as fields, which are not actually
/// serialized. Using this option will have such effect: read/write operaitons
/// will not change the value of iterators and will report immediate success.
/// The serialization length is always reported as 0.
/// @headerfile nil/marshalling/options.hpp
struct empty_serialization { };
/// @brief Option to force @ref nil::marshalling::protocol::ProtocolLayerBase class to
/// split read operation "until" and "from" data (payload) layer.
/// @details Can be used by some layers which require its read operation to be
/// fully complete before read is forwared to data layer, i.e. until message
/// contents being read.
/// @headerfile nil/marshalling/options.hpp
struct protocol_layer_force_read_until_data_split { };
/// @brief Disallow usage of @ref ProtocolLayerForceReadUntilDataSplit option in
/// earlier (outer wrapping) layers.
/// @details Some layers, such as @ref nil::marshalling::protocol::ChecksumLayer cannot
/// split their "read" operation to "until" and "from" data layer. They can
/// use this option to prevent outer layers from using
/// @ref ProtocolLayerForceReadUntilDataSplit one.
/// @headerfile nil/marshalling/options.hpp
struct protocol_layer_disallow_read_until_data_split { };
/// @brief Mark this class to have custom
/// implementation of @b read functionality.
/// @headerfile nil/marshalling/options.hpp
struct has_custom_read { };
/// @brief Mark this class to have custom
/// implementation of @b refresh functionality.
/// @headerfile nil/marshalling/options.hpp
struct has_custom_refresh { };
/// @brief Mark this class as providing its name information
/// @headerfile nil/marshalling/options.hpp
struct has_name { };
/// @brief Option that notifies nil::marshalling::message_base about existence of
/// custom refresh functionality in derived class.
/// @details Alias to @ref has_custom_refresh for backward compatibility.
/// @deprecated Use @ref has_custom_refresh instead.
/// @headerfile nil/marshalling/options.hpp
using has_do_refresh = has_custom_refresh;
/// @brief Option for @ref nil::marshalling::protocol::TransportValueLayer to
/// mark that the handled field is a "pseudo" one, i.e. is not serialized.
struct pseudo_value { };
/// @brief Provide type to be used for versioning
/// @tparam T Type of the version value. Expected to be unsigned integral one.
template<typename T>
struct version_type {
static_assert(std::is_integral<T>::value, "Only unsigned integral types are supported for versions");
static_assert(std::is_unsigned<T>::value, "Only unsigned integral types are supported for versions");
};
/// @brief Mark this class to have custom
/// implementation of version update functionality.
/// @headerfile nil/marshalling/options.hpp
struct has_custom_version_update { };
/// @brief Mark an @ref nil::marshalling::types::optional field as existing
/// between specified versions.
/// @tparam TFrom First version when field has been added
/// @tparam TUntil Last version when field still hasn't been removed.
/// @pre @b TFrom <= @b TUntil
template<std::uintmax_t TFrom, std::uintmax_t TUntil>
struct exists_between_versions {
static_assert(TFrom <= TUntil, "Invalid version parameters");
};
/// @brief Mark an @ref nil::marshalling::types::optional field as existing
/// starting from specified version.
/// @details Alias to @ref ExistsBetweenVersions
/// @tparam TVer First version when field has been added
template<std::uintmax_t TVer>
using exists_since_version = exists_between_versions<TVer, std::numeric_limits<std::uintmax_t>::max()>;
/// @brief Mark an @ref nil::marshalling::types::optional field as existing
/// only until specified version.
/// @details Alias to @ref ExistsBetweenVersions
/// @tparam TVer Last version when field still hasn't been removed.
template<std::uintmax_t TVer>
using exists_until_version = exists_between_versions<0, TVer>;
/// @brief Make the field's contents to be invalid by default.
struct invalid_by_default { };
/// @brief Add storage of version information inside private data members.
/// @details The version information can be accessed using @b get_version() member function.
struct version_storage { };
} // namespace option
} // namespace marshalling
} // namespace nil
#endif // MARSHALLING_OPTIONS_HPP
| 56.82127 | 119 | 0.578312 | idealatom |
fa3b963e8bff7662eee819b9d93b379986e5926b | 3,241 | cpp | C++ | tests/utils_test.cpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 7 | 2015-01-28T09:17:08.000Z | 2020-04-21T13:51:16.000Z | tests/utils_test.cpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | null | null | null | tests/utils_test.cpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 1 | 2020-07-11T09:20:25.000Z | 2020-07-11T09:20:25.000Z | #include <utils/base64.hpp>
#include <utils/string.hpp>
#include <utils/scopeguard.hpp>
#include <utils/zlib.hpp>
#include <utils/time.hpp>
#include "catch.hpp"
TEST_CASE("Both", "[base64]")
{
std::string hello = "Coucou ici";
CHECK(base64_decode(base64_encode(reinterpret_cast<const unsigned char*>(hello.c_str()), hello.size())) ==
"Coucou ici");
}
TEST_CASE("encode", "[base64]")
{
std::string encoded("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=");
CHECK(base64_decode(encoded) == "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.");
}
TEST_CASE("decompressAndCompress", "[zlib]")
{
std::string original("coucou coucou");
CHECK(zlib_decompress(zlib_compress(original)) == "coucou coucou");
}
TEST_CASE("trim", "[strings]")
{
std::string original(" coucou\n");
utils::trim(original);
CHECK(original == "coucou");
original = " coucou";
utils::trim(original);
CHECK(original == "coucou");
original = "coucou ";
utils::trim(original);
CHECK(original == "coucou");
original = "coucou";
utils::trim(original);
CHECK(original == "coucou");
original = "\n\ncoucou \r\n ";
utils::trim(original);
CHECK(original == "coucou");
}
TEST_CASE("Scopeguard")
{
int i = 5;
{
CHECK(i == 5);
utils::ScopeGuard guard([&i]() {--i;});
CHECK(i == 5);
}
CHECK(i == 4);
{
CHECK(i == 4);
utils::ScopeGuard guard;
guard.add_callback([&i]() {--i;});
guard.add_callback([&i]() {--i;});
CHECK(i == 4);
}
CHECK(i == 2);
{
CHECK(i == 2);
utils::ScopeGuard guard;
guard.add_callback([&i]() {--i;});
CHECK(i == 2);
guard.disable();
}
CHECK(i == 2);
}
TEST_CASE("BasicTick", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 1s;
auto ticks = utils::get_number_of_ticks(dt);
CHECK(ticks == 50);
CHECK(dt == 0s);
}
TEST_CASE("BasicTick2", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 500000us;
auto ticks = utils::get_number_of_ticks(dt);
CHECK(ticks == 25);
CHECK(dt == 0s);
}
TEST_CASE("Ticks", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 420000us;
auto ticks = utils::get_number_of_ticks(dt);
CHECK(ticks == 21);
CHECK(dt == 0us);
}
TEST_CASE("ConvertToFloatingSeconds", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 8420000us;
auto secs = utils::sec(dt);
CHECK(secs == 8.42s);
dt = -8420000us;
secs = utils::sec(dt);
CHECK(secs == -8.42s);
}
TEST_CASE("NullTime", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 0h;
auto ticks = utils::get_number_of_ticks(dt);
CHECK(ticks == 0);
CHECK(dt == 0us);
}
| 24.930769 | 386 | 0.676026 | louiz |
fa3e9a0bc2dd0bcba79d797ef2269824617ff5b6 | 3,440 | cpp | C++ | genome/genome.cpp | nicodex/lianzifu | 67c08abf0636e85512bfc91ac9ebe43dc2255186 | [
"MIT"
] | 2 | 2018-02-01T04:08:48.000Z | 2018-02-03T16:33:38.000Z | genome/genome.cpp | nicodex/lianzifu | 67c08abf0636e85512bfc91ac9ebe43dc2255186 | [
"MIT"
] | 1 | 2018-02-02T12:28:32.000Z | 2018-02-09T13:13:53.000Z | genome/genome.cpp | nicodex/lianzifu | 67c08abf0636e85512bfc91ac9ebe43dc2255186 | [
"MIT"
] | 1 | 2020-05-20T15:52:21.000Z | 2020-05-20T15:52:21.000Z | //
// Copyright (c) 2018 Nico Bendlin <[email protected]>
//
// 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.
//
#include <genome/genome.hpp>
#include <genome/locale.hpp>
#include <genome/filesystem.hpp>
void
init_genome(void)
{
genome::locale::init();
genome::filesystem::init();
}
namespace genome {
namespace /*{anonymous}*/ {
char const*
skip_space(char const*& s)
{
if (!s) {
s = "";
} else {
while (('\t' == *s) || (' ' == *s)) {
++s;
}
}
return (s);
}
bool
is_end(char const*& s)
{
return ('\0' == *skip_space(s));
}
} // namespace genome::{anonymous}
//
// platforms
//
char const*
platform_name(platform target)
{
switch (target) {
default:
case platform_unknown:
return ("<invalid>");
case platform_pc:
return ("pc");
case platform_x64:
return ("x64");
case platform_ps3:
return ("ps3");
case platform_ps4:
return ("ps4");
case platform_x360:
return ("x360");
case platform_xone:
return ("xone");
}
}
char const*
platform_desc(platform target)
{
switch (target) {
default:
case platform_unknown:
return ("<invalid>");
case platform_pc:
return ("Windows (32-bit)");
case platform_x64:
return ("Windows (64-bit)");
case platform_ps3:
return ("PlayStation 3");
case platform_ps4:
return ("PlayStation 4");
case platform_x360:
return ("Xbox 360");
case platform_xone:
return ("Xbox One");
}
}
platform
platform_from_name(char const* name)
{
switch (*skip_space(name)) {
case 'p': case 'P':
switch (*++name) {
case 'c': case 'C':
if (is_end(++name)) {
return (platform_pc);
}
break;
case 's': case 'S':
switch (*++name) {
case '3':
if (is_end(++name)) {
return (platform_ps3);
}
break;
case '4':
if (is_end(++name)) {
return (platform_ps4);
}
break;
}
break;
}
break;
case 'x': case 'X':
switch (*++name) {
case '3':
if ('6' == *++name) {
if ('0' == *++name) {
if (is_end(++name)) {
return (platform_x360);
}
}
}
break;
case '6':
if ('4' == *++name) {
if (is_end(++name)) {
return (platform_x64);
}
}
break;
case 'o': case 'O':
if (++name, ('n' == *name) || ('N' == *name)) {
if (++name, ('e' == *name) || ('E' == *name)) {
if (is_end(++name)) {
return (platform_xone);
}
}
}
break;
}
break;
}
return (platform_unknown);
}
} // namespace genome
| 20.598802 | 80 | 0.623256 | nicodex |
fa41bd932a3d0556d52ae51a1763aa49055ceffe | 2,106 | cc | C++ | kernel/src/arch/x86_64/hal/task/context.cc | igarfieldi/Danaos64 | f4a2df8de5f214af7a4d18e14790740d2c481c48 | [
"Apache-2.0"
] | 2 | 2017-09-16T19:41:14.000Z | 2017-11-04T10:41:38.000Z | kernel/src/arch/x86_64/hal/task/context.cc | igarfieldi/Danaos64 | f4a2df8de5f214af7a4d18e14790740d2c481c48 | [
"Apache-2.0"
] | null | null | null | kernel/src/arch/x86_64/hal/task/context.cc | igarfieldi/Danaos64 | f4a2df8de5f214af7a4d18e14790740d2c481c48 | [
"Apache-2.0"
] | null | null | null | #include "context.h"
#include "hal/interrupts/gdt.h"
#include "main/task/task.h"
namespace hal {
task_context create_context(volatile uint64_t *stack, task::task &task) {
task_context context(&stack[-21]);
// New state
stack[-21] = reinterpret_cast<uint64_t>(&stack[0]); // RBP
stack[-20] = 0xAAAAAAAAAAAAAAAA; // RAX
stack[-19] = 0xBBBBBBBBBBBBBBBB; // RBX
stack[-18] = 0xCCCCCCCCCCCCCCCC; // RCX
stack[-17] = 0xDDDDDDDDDDDDDDDD; // RDX
stack[-16] = 0x8888888888888888; // R8
stack[-15] = 0x9999999999999999; // R9
stack[-14] = 0x0000000000000000; // R10
stack[-13] = 0x1111111111111111; // R11
stack[-12] = 0x2222222222222222; // R12
stack[-11] = 0x3333333333333333; // R13
stack[-10] = 0x4444444444444444; // R14
stack[-9] = 0x5555555555555555; // R15
stack[-8] = 0x5151515151515151; // RSI
stack[-7] = reinterpret_cast<uint64_t>(&task); // RDI
stack[-6] = 0x0; // Interrupt number
stack[-5] = 0x0; // Error code
stack[-4] = reinterpret_cast<uint64_t>(&task::task::start); // Return RIP
stack[-3] = 0x8; // Return CS
stack[-2] = 0x200; // RFLAGS (enable interrupts)
stack[-1] = reinterpret_cast<uint64_t>(&stack[0]); // Return RSP
stack[0] = 0x10; // Return SS
return context;
}
} // namespace hal
| 55.421053 | 101 | 0.395537 | igarfieldi |
fa425c1f643a874587973399f192364a916e82ae | 139,538 | cxx | C++ | SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowPlant_ElectricalGenerator_Photovoltaic.cxx | EnEff-BIM/EnEffBIM-Framework | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | [
"MIT"
] | 3 | 2016-05-30T15:12:16.000Z | 2022-03-22T08:11:13.000Z | SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowPlant_ElectricalGenerator_Photovoltaic.cxx | EnEff-BIM/EnEffBIM-Framework | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | [
"MIT"
] | 21 | 2016-06-13T11:33:45.000Z | 2017-05-23T09:46:52.000Z | SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowPlant_ElectricalGenerator_Photovoltaic.cxx | EnEff-BIM/EnEffBIM-Framework | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | [
"MIT"
] | null | null | null | // Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "SimFlowPlant_ElectricalGenerator_Photovoltaic.hxx"
#include "doublelist.hxx"
namespace schema
{
namespace simxml
{
namespace MepModel
{
// SimFlowPlant_ElectricalGenerator_Photovoltaic
//
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name () const
{
return this->SimFlowPlant_Name_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name ()
{
return this->SimFlowPlant_Name_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name (const SimFlowPlant_Name_type& x)
{
this->SimFlowPlant_Name_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name (const SimFlowPlant_Name_optional& x)
{
this->SimFlowPlant_Name_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name (::std::auto_ptr< SimFlowPlant_Name_type > x)
{
this->SimFlowPlant_Name_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_SurfName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName () const
{
return this->SimFlowPlant_SurfName_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_SurfName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName ()
{
return this->SimFlowPlant_SurfName_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName (const SimFlowPlant_SurfName_type& x)
{
this->SimFlowPlant_SurfName_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName (const SimFlowPlant_SurfName_optional& x)
{
this->SimFlowPlant_SurfName_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName (::std::auto_ptr< SimFlowPlant_SurfName_type > x)
{
this->SimFlowPlant_SurfName_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_PhotovoltaicPerfObjType_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType () const
{
return this->SimFlowPlant_PhotovoltaicPerfObjType_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_PhotovoltaicPerfObjType_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType ()
{
return this->SimFlowPlant_PhotovoltaicPerfObjType_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType (const SimFlowPlant_PhotovoltaicPerfObjType_type& x)
{
this->SimFlowPlant_PhotovoltaicPerfObjType_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType (const SimFlowPlant_PhotovoltaicPerfObjType_optional& x)
{
this->SimFlowPlant_PhotovoltaicPerfObjType_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType (::std::auto_ptr< SimFlowPlant_PhotovoltaicPerfObjType_type > x)
{
this->SimFlowPlant_PhotovoltaicPerfObjType_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_ModulePerfName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName () const
{
return this->SimFlowPlant_ModulePerfName_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_ModulePerfName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName ()
{
return this->SimFlowPlant_ModulePerfName_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName (const SimFlowPlant_ModulePerfName_type& x)
{
this->SimFlowPlant_ModulePerfName_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName (const SimFlowPlant_ModulePerfName_optional& x)
{
this->SimFlowPlant_ModulePerfName_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName (::std::auto_ptr< SimFlowPlant_ModulePerfName_type > x)
{
this->SimFlowPlant_ModulePerfName_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_HeatTranstegrationMode_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode () const
{
return this->SimFlowPlant_HeatTranstegrationMode_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_HeatTranstegrationMode_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode ()
{
return this->SimFlowPlant_HeatTranstegrationMode_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode (const SimFlowPlant_HeatTranstegrationMode_type& x)
{
this->SimFlowPlant_HeatTranstegrationMode_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode (const SimFlowPlant_HeatTranstegrationMode_optional& x)
{
this->SimFlowPlant_HeatTranstegrationMode_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode (::std::auto_ptr< SimFlowPlant_HeatTranstegrationMode_type > x)
{
this->SimFlowPlant_HeatTranstegrationMode_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_NumberofSeriesStringsinParallel_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumberofSeriesStringsinParallel () const
{
return this->SimFlowPlant_NumberofSeriesStringsinParallel_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_NumberofSeriesStringsinParallel_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumberofSeriesStringsinParallel ()
{
return this->SimFlowPlant_NumberofSeriesStringsinParallel_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumberofSeriesStringsinParallel (const SimFlowPlant_NumberofSeriesStringsinParallel_type& x)
{
this->SimFlowPlant_NumberofSeriesStringsinParallel_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumberofSeriesStringsinParallel (const SimFlowPlant_NumberofSeriesStringsinParallel_optional& x)
{
this->SimFlowPlant_NumberofSeriesStringsinParallel_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_NumModulesSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumModulesSeries () const
{
return this->SimFlowPlant_NumModulesSeries_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_NumModulesSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumModulesSeries ()
{
return this->SimFlowPlant_NumModulesSeries_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumModulesSeries (const SimFlowPlant_NumModulesSeries_type& x)
{
this->SimFlowPlant_NumModulesSeries_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumModulesSeries (const SimFlowPlant_NumModulesSeries_optional& x)
{
this->SimFlowPlant_NumModulesSeries_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name () const
{
return this->PhotovoltaicPerformance_Simple_Name_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name ()
{
return this->PhotovoltaicPerformance_Simple_Name_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name (const PhotovoltaicPerformance_Simple_Name_type& x)
{
this->PhotovoltaicPerformance_Simple_Name_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name (const PhotovoltaicPerformance_Simple_Name_optional& x)
{
this->PhotovoltaicPerformance_Simple_Name_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name (::std::auto_ptr< PhotovoltaicPerformance_Simple_Name_type > x)
{
this->PhotovoltaicPerformance_Simple_Name_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells () const
{
return this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells ()
{
return this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells (const PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_type& x)
{
this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells (const PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_optional& x)
{
this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode () const
{
return this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode ()
{
return this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode (const PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_type& x)
{
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode (const PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_optional& x)
{
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode (::std::auto_ptr< PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_type > x)
{
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed () const
{
return this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed ()
{
return this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed (const PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_type& x)
{
this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed (const PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_optional& x)
{
this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_EfficiencyScheduleName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName () const
{
return this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_EfficiencyScheduleName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName ()
{
return this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName (const PhotovoltaicPerformance_Simple_EfficiencyScheduleName_type& x)
{
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName (const PhotovoltaicPerformance_Simple_EfficiencyScheduleName_optional& x)
{
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName (::std::auto_ptr< PhotovoltaicPerformance_Simple_EfficiencyScheduleName_type > x)
{
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name () const
{
return this->PVPerf_EquivOne_Diode_Name_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name ()
{
return this->PVPerf_EquivOne_Diode_Name_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name (const PVPerf_EquivOne_Diode_Name_type& x)
{
this->PVPerf_EquivOne_Diode_Name_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name (const PVPerf_EquivOne_Diode_Name_optional& x)
{
this->PVPerf_EquivOne_Diode_Name_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name (::std::auto_ptr< PVPerf_EquivOne_Diode_Name_type > x)
{
this->PVPerf_EquivOne_Diode_Name_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_CellType_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType () const
{
return this->PVPerf_EquivOne_Diode_CellType_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_CellType_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType ()
{
return this->PVPerf_EquivOne_Diode_CellType_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType (const PVPerf_EquivOne_Diode_CellType_type& x)
{
this->PVPerf_EquivOne_Diode_CellType_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType (const PVPerf_EquivOne_Diode_CellType_optional& x)
{
this->PVPerf_EquivOne_Diode_CellType_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType (::std::auto_ptr< PVPerf_EquivOne_Diode_CellType_type > x)
{
this->PVPerf_EquivOne_Diode_CellType_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NumCellsSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NumCellsSeries () const
{
return this->PVPerf_EquivOne_Diode_NumCellsSeries_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NumCellsSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NumCellsSeries ()
{
return this->PVPerf_EquivOne_Diode_NumCellsSeries_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NumCellsSeries (const PVPerf_EquivOne_Diode_NumCellsSeries_type& x)
{
this->PVPerf_EquivOne_Diode_NumCellsSeries_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NumCellsSeries (const PVPerf_EquivOne_Diode_NumCellsSeries_optional& x)
{
this->PVPerf_EquivOne_Diode_NumCellsSeries_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ActiveArea_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ActiveArea () const
{
return this->PVPerf_EquivOne_Diode_ActiveArea_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ActiveArea_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ActiveArea ()
{
return this->PVPerf_EquivOne_Diode_ActiveArea_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ActiveArea (const PVPerf_EquivOne_Diode_ActiveArea_type& x)
{
this->PVPerf_EquivOne_Diode_ActiveArea_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ActiveArea (const PVPerf_EquivOne_Diode_ActiveArea_optional& x)
{
this->PVPerf_EquivOne_Diode_ActiveArea_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TransAbsorptanceProduct_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TransAbsorptanceProduct () const
{
return this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TransAbsorptanceProduct_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TransAbsorptanceProduct ()
{
return this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TransAbsorptanceProduct (const PVPerf_EquivOne_Diode_TransAbsorptanceProduct_type& x)
{
this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TransAbsorptanceProduct (const PVPerf_EquivOne_Diode_TransAbsorptanceProduct_optional& x)
{
this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_SemiconductorBandgap_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_SemiconductorBandgap () const
{
return this->PVPerf_EquivOne_Diode_SemiconductorBandgap_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_SemiconductorBandgap_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_SemiconductorBandgap ()
{
return this->PVPerf_EquivOne_Diode_SemiconductorBandgap_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_SemiconductorBandgap (const PVPerf_EquivOne_Diode_SemiconductorBandgap_type& x)
{
this->PVPerf_EquivOne_Diode_SemiconductorBandgap_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_SemiconductorBandgap (const PVPerf_EquivOne_Diode_SemiconductorBandgap_optional& x)
{
this->PVPerf_EquivOne_Diode_SemiconductorBandgap_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ShuntResist_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShuntResist () const
{
return this->PVPerf_EquivOne_Diode_ShuntResist_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ShuntResist_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShuntResist ()
{
return this->PVPerf_EquivOne_Diode_ShuntResist_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShuntResist (const PVPerf_EquivOne_Diode_ShuntResist_type& x)
{
this->PVPerf_EquivOne_Diode_ShuntResist_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShuntResist (const PVPerf_EquivOne_Diode_ShuntResist_optional& x)
{
this->PVPerf_EquivOne_Diode_ShuntResist_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShortCircuitCurrent () const
{
return this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShortCircuitCurrent ()
{
return this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShortCircuitCurrent (const PVPerf_EquivOne_Diode_ShortCircuitCurrent_type& x)
{
this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShortCircuitCurrent (const PVPerf_EquivOne_Diode_ShortCircuitCurrent_optional& x)
{
this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_OpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_OpenCircuitVolt () const
{
return this->PVPerf_EquivOne_Diode_OpenCircuitVolt_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_OpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_OpenCircuitVolt ()
{
return this->PVPerf_EquivOne_Diode_OpenCircuitVolt_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_OpenCircuitVolt (const PVPerf_EquivOne_Diode_OpenCircuitVolt_type& x)
{
this->PVPerf_EquivOne_Diode_OpenCircuitVolt_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_OpenCircuitVolt (const PVPerf_EquivOne_Diode_OpenCircuitVolt_optional& x)
{
this->PVPerf_EquivOne_Diode_OpenCircuitVolt_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_RefTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefTemp () const
{
return this->PVPerf_EquivOne_Diode_RefTemp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_RefTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefTemp ()
{
return this->PVPerf_EquivOne_Diode_RefTemp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefTemp (const PVPerf_EquivOne_Diode_RefTemp_type& x)
{
this->PVPerf_EquivOne_Diode_RefTemp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefTemp (const PVPerf_EquivOne_Diode_RefTemp_optional& x)
{
this->PVPerf_EquivOne_Diode_RefTemp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_RefInsol_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefInsol () const
{
return this->PVPerf_EquivOne_Diode_RefInsol_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_RefInsol_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefInsol ()
{
return this->PVPerf_EquivOne_Diode_RefInsol_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefInsol (const PVPerf_EquivOne_Diode_RefInsol_type& x)
{
this->PVPerf_EquivOne_Diode_RefInsol_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefInsol (const PVPerf_EquivOne_Diode_RefInsol_optional& x)
{
this->PVPerf_EquivOne_Diode_RefInsol_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr () const
{
return this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr ()
{
return this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr (const PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_type& x)
{
this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr (const PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_optional& x)
{
this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr () const
{
return this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr ()
{
return this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr (const PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_type& x)
{
this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr (const PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_optional& x)
{
this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent () const
{
return this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent ()
{
return this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent (const PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_type& x)
{
this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent (const PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_optional& x)
{
this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt () const
{
return this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt ()
{
return this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt (const PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_type& x)
{
this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt (const PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_optional& x)
{
this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp () const
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp ()
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp (const PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_type& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp (const PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_optional& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp () const
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp ()
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp (const PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_type& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp (const PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_optional& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol () const
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol ()
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol (const PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_type& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol (const PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_optional& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleHeatLossCoef_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleHeatLossCoef () const
{
return this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleHeatLossCoef_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleHeatLossCoef ()
{
return this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleHeatLossCoef (const PVPerf_EquivOne_Diode_ModuleHeatLossCoef_type& x)
{
this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleHeatLossCoef (const PVPerf_EquivOne_Diode_ModuleHeatLossCoef_optional& x)
{
this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TotalHeatCap_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TotalHeatCap () const
{
return this->PVPerf_EquivOne_Diode_TotalHeatCap_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TotalHeatCap_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TotalHeatCap ()
{
return this->PVPerf_EquivOne_Diode_TotalHeatCap_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TotalHeatCap (const PVPerf_EquivOne_Diode_TotalHeatCap_type& x)
{
this->PVPerf_EquivOne_Diode_TotalHeatCap_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TotalHeatCap (const PVPerf_EquivOne_Diode_TotalHeatCap_optional& x)
{
this->PVPerf_EquivOne_Diode_TotalHeatCap_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name () const
{
return this->PVPerf_Sandia_Name_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name ()
{
return this->PVPerf_Sandia_Name_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name (const PVPerf_Sandia_Name_type& x)
{
this->PVPerf_Sandia_Name_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name (const PVPerf_Sandia_Name_optional& x)
{
this->PVPerf_Sandia_Name_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name (::std::auto_ptr< PVPerf_Sandia_Name_type > x)
{
this->PVPerf_Sandia_Name_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_ActiveArea_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ActiveArea () const
{
return this->PVPerf_Sandia_ActiveArea_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_ActiveArea_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ActiveArea ()
{
return this->PVPerf_Sandia_ActiveArea_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ActiveArea (const PVPerf_Sandia_ActiveArea_type& x)
{
this->PVPerf_Sandia_ActiveArea_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ActiveArea (const PVPerf_Sandia_ActiveArea_optional& x)
{
this->PVPerf_Sandia_ActiveArea_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_NumCellsSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsSeries () const
{
return this->PVPerf_Sandia_NumCellsSeries_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_NumCellsSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsSeries ()
{
return this->PVPerf_Sandia_NumCellsSeries_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsSeries (const PVPerf_Sandia_NumCellsSeries_type& x)
{
this->PVPerf_Sandia_NumCellsSeries_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsSeries (const PVPerf_Sandia_NumCellsSeries_optional& x)
{
this->PVPerf_Sandia_NumCellsSeries_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_NumCellsParallel_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsParallel () const
{
return this->PVPerf_Sandia_NumCellsParallel_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_NumCellsParallel_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsParallel ()
{
return this->PVPerf_Sandia_NumCellsParallel_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsParallel (const PVPerf_Sandia_NumCellsParallel_type& x)
{
this->PVPerf_Sandia_NumCellsParallel_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsParallel (const PVPerf_Sandia_NumCellsParallel_optional& x)
{
this->PVPerf_Sandia_NumCellsParallel_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_ShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ShortCircuitCurrent () const
{
return this->PVPerf_Sandia_ShortCircuitCurrent_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_ShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ShortCircuitCurrent ()
{
return this->PVPerf_Sandia_ShortCircuitCurrent_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ShortCircuitCurrent (const PVPerf_Sandia_ShortCircuitCurrent_type& x)
{
this->PVPerf_Sandia_ShortCircuitCurrent_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ShortCircuitCurrent (const PVPerf_Sandia_ShortCircuitCurrent_optional& x)
{
this->PVPerf_Sandia_ShortCircuitCurrent_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_OpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_OpenCircuitVolt () const
{
return this->PVPerf_Sandia_OpenCircuitVolt_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_OpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_OpenCircuitVolt ()
{
return this->PVPerf_Sandia_OpenCircuitVolt_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_OpenCircuitVolt (const PVPerf_Sandia_OpenCircuitVolt_type& x)
{
this->PVPerf_Sandia_OpenCircuitVolt_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_OpenCircuitVolt (const PVPerf_Sandia_OpenCircuitVolt_optional& x)
{
this->PVPerf_Sandia_OpenCircuitVolt_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_CurrentAtMaxPwrPoint_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_CurrentAtMaxPwrPoint () const
{
return this->PVPerf_Sandia_CurrentAtMaxPwrPoint_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_CurrentAtMaxPwrPoint_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_CurrentAtMaxPwrPoint ()
{
return this->PVPerf_Sandia_CurrentAtMaxPwrPoint_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_CurrentAtMaxPwrPoint (const PVPerf_Sandia_CurrentAtMaxPwrPoint_type& x)
{
this->PVPerf_Sandia_CurrentAtMaxPwrPoint_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_CurrentAtMaxPwrPoint (const PVPerf_Sandia_CurrentAtMaxPwrPoint_optional& x)
{
this->PVPerf_Sandia_CurrentAtMaxPwrPoint_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_VoltAtMaxPwrPoint_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_VoltAtMaxPwrPoint () const
{
return this->PVPerf_Sandia_VoltAtMaxPwrPoint_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_VoltAtMaxPwrPoint_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_VoltAtMaxPwrPoint ()
{
return this->PVPerf_Sandia_VoltAtMaxPwrPoint_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_VoltAtMaxPwrPoint (const PVPerf_Sandia_VoltAtMaxPwrPoint_type& x)
{
this->PVPerf_Sandia_VoltAtMaxPwrPoint_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_VoltAtMaxPwrPoint (const PVPerf_Sandia_VoltAtMaxPwrPoint_optional& x)
{
this->PVPerf_Sandia_VoltAtMaxPwrPoint_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamAc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAc () const
{
return this->PVPerf_Sandia_SandiaDbParamAc_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamAc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAc ()
{
return this->PVPerf_Sandia_SandiaDbParamAc_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAc (const PVPerf_Sandia_SandiaDbParamAc_type& x)
{
this->PVPerf_Sandia_SandiaDbParamAc_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAc (const PVPerf_Sandia_SandiaDbParamAc_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamAc_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamAImp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAImp () const
{
return this->PVPerf_Sandia_SandiaDbParamAImp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamAImp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAImp ()
{
return this->PVPerf_Sandia_SandiaDbParamAImp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAImp (const PVPerf_Sandia_SandiaDbParamAImp_type& x)
{
this->PVPerf_Sandia_SandiaDbParamAImp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAImp (const PVPerf_Sandia_SandiaDbParamAImp_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamAImp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc0 () const
{
return this->PVPerf_Sandia_SandiaDBParamc0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc0 ()
{
return this->PVPerf_Sandia_SandiaDBParamc0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc0 (const PVPerf_Sandia_SandiaDBParamc0_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc0 (const PVPerf_Sandia_SandiaDBParamc0_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc1 () const
{
return this->PVPerf_Sandia_SandiaDBParamc1_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc1 ()
{
return this->PVPerf_Sandia_SandiaDBParamc1_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc1 (const PVPerf_Sandia_SandiaDBParamc1_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc1_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc1 (const PVPerf_Sandia_SandiaDBParamc1_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc1_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamBVoc0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVoc0 () const
{
return this->PVPerf_Sandia_SandiaDbParamBVoc0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamBVoc0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVoc0 ()
{
return this->PVPerf_Sandia_SandiaDbParamBVoc0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVoc0 (const PVPerf_Sandia_SandiaDbParamBVoc0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamBVoc0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVoc0 (const PVPerf_Sandia_SandiaDbParamBVoc0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamBVoc0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamMBVoc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVoc () const
{
return this->PVPerf_Sandia_SandiaDbParamMBVoc_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamMBVoc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVoc ()
{
return this->PVPerf_Sandia_SandiaDbParamMBVoc_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVoc (const PVPerf_Sandia_SandiaDbParamMBVoc_type& x)
{
this->PVPerf_Sandia_SandiaDbParamMBVoc_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVoc (const PVPerf_Sandia_SandiaDbParamMBVoc_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamMBVoc_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamBVmp0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVmp0 () const
{
return this->PVPerf_Sandia_SandiaDbParamBVmp0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamBVmp0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVmp0 ()
{
return this->PVPerf_Sandia_SandiaDbParamBVmp0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVmp0 (const PVPerf_Sandia_SandiaDbParamBVmp0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamBVmp0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVmp0 (const PVPerf_Sandia_SandiaDbParamBVmp0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamBVmp0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamMBVmp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVmp () const
{
return this->PVPerf_Sandia_SandiaDbParamMBVmp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamMBVmp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVmp ()
{
return this->PVPerf_Sandia_SandiaDbParamMBVmp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVmp (const PVPerf_Sandia_SandiaDbParamMBVmp_type& x)
{
this->PVPerf_Sandia_SandiaDbParamMBVmp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVmp (const PVPerf_Sandia_SandiaDbParamMBVmp_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamMBVmp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_DiodeFactor_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_DiodeFactor () const
{
return this->PVPerf_Sandia_DiodeFactor_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_DiodeFactor_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_DiodeFactor ()
{
return this->PVPerf_Sandia_DiodeFactor_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_DiodeFactor (const PVPerf_Sandia_DiodeFactor_type& x)
{
this->PVPerf_Sandia_DiodeFactor_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_DiodeFactor (const PVPerf_Sandia_DiodeFactor_optional& x)
{
this->PVPerf_Sandia_DiodeFactor_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc2 () const
{
return this->PVPerf_Sandia_SandiaDBParamc2_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc2 ()
{
return this->PVPerf_Sandia_SandiaDBParamc2_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc2 (const PVPerf_Sandia_SandiaDBParamc2_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc2_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc2 (const PVPerf_Sandia_SandiaDBParamc2_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc2_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc3 () const
{
return this->PVPerf_Sandia_SandiaDBParamc3_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc3 ()
{
return this->PVPerf_Sandia_SandiaDBParamc3_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc3 (const PVPerf_Sandia_SandiaDBParamc3_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc3_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc3 (const PVPerf_Sandia_SandiaDBParamc3_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc3_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParama_0_0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 () const
{
return this->PVPerf_Sandia_SandiaDbParama_0_0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParama_0_0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 ()
{
return this->PVPerf_Sandia_SandiaDbParama_0_0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 (const PVPerf_Sandia_SandiaDbParama_0_0_type& x)
{
this->PVPerf_Sandia_SandiaDbParama_0_0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 (const PVPerf_Sandia_SandiaDbParama_0_0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParama_0_0_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 (::std::auto_ptr< PVPerf_Sandia_SandiaDbParama_0_0_type > x)
{
this->PVPerf_Sandia_SandiaDbParama_0_0_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParama_1_1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 () const
{
return this->PVPerf_Sandia_SandiaDbParama_1_1_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParama_1_1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 ()
{
return this->PVPerf_Sandia_SandiaDbParama_1_1_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 (const PVPerf_Sandia_SandiaDbParama_1_1_type& x)
{
this->PVPerf_Sandia_SandiaDbParama_1_1_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 (const PVPerf_Sandia_SandiaDbParama_1_1_optional& x)
{
this->PVPerf_Sandia_SandiaDbParama_1_1_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 (::std::auto_ptr< PVPerf_Sandia_SandiaDbParama_1_1_type > x)
{
this->PVPerf_Sandia_SandiaDbParama_1_1_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama2 () const
{
return this->PVPerf_Sandia_SandiaDBParama2_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama2 ()
{
return this->PVPerf_Sandia_SandiaDBParama2_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama2 (const PVPerf_Sandia_SandiaDBParama2_type& x)
{
this->PVPerf_Sandia_SandiaDBParama2_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama2 (const PVPerf_Sandia_SandiaDBParama2_optional& x)
{
this->PVPerf_Sandia_SandiaDBParama2_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama3 () const
{
return this->PVPerf_Sandia_SandiaDBParama3_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama3 ()
{
return this->PVPerf_Sandia_SandiaDBParama3_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama3 (const PVPerf_Sandia_SandiaDBParama3_type& x)
{
this->PVPerf_Sandia_SandiaDBParama3_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama3 (const PVPerf_Sandia_SandiaDBParama3_optional& x)
{
this->PVPerf_Sandia_SandiaDBParama3_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama4 () const
{
return this->PVPerf_Sandia_SandiaDBParama4_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama4 ()
{
return this->PVPerf_Sandia_SandiaDBParama4_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama4 (const PVPerf_Sandia_SandiaDBParama4_type& x)
{
this->PVPerf_Sandia_SandiaDBParama4_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama4 (const PVPerf_Sandia_SandiaDBParama4_optional& x)
{
this->PVPerf_Sandia_SandiaDBParama4_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamb_0_0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 () const
{
return this->PVPerf_Sandia_SandiaDbParamb_0_0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamb_0_0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 ()
{
return this->PVPerf_Sandia_SandiaDbParamb_0_0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 (const PVPerf_Sandia_SandiaDbParamb_0_0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamb_0_0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 (const PVPerf_Sandia_SandiaDbParamb_0_0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamb_0_0_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 (::std::auto_ptr< PVPerf_Sandia_SandiaDbParamb_0_0_type > x)
{
this->PVPerf_Sandia_SandiaDbParamb_0_0_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamb_1_1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 () const
{
return this->PVPerf_Sandia_SandiaDbParamb_1_1_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamb_1_1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 ()
{
return this->PVPerf_Sandia_SandiaDbParamb_1_1_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 (const PVPerf_Sandia_SandiaDbParamb_1_1_type& x)
{
this->PVPerf_Sandia_SandiaDbParamb_1_1_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 (const PVPerf_Sandia_SandiaDbParamb_1_1_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamb_1_1_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 (::std::auto_ptr< PVPerf_Sandia_SandiaDbParamb_1_1_type > x)
{
this->PVPerf_Sandia_SandiaDbParamb_1_1_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb2 () const
{
return this->PVPerf_Sandia_SandiaDBParamb2_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb2 ()
{
return this->PVPerf_Sandia_SandiaDBParamb2_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb2 (const PVPerf_Sandia_SandiaDBParamb2_type& x)
{
this->PVPerf_Sandia_SandiaDBParamb2_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb2 (const PVPerf_Sandia_SandiaDBParamb2_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamb2_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb3 () const
{
return this->PVPerf_Sandia_SandiaDBParamb3_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb3 ()
{
return this->PVPerf_Sandia_SandiaDBParamb3_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb3 (const PVPerf_Sandia_SandiaDBParamb3_type& x)
{
this->PVPerf_Sandia_SandiaDBParamb3_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb3 (const PVPerf_Sandia_SandiaDBParamb3_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamb3_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb4 () const
{
return this->PVPerf_Sandia_SandiaDBParamb4_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb4 ()
{
return this->PVPerf_Sandia_SandiaDBParamb4_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb4 (const PVPerf_Sandia_SandiaDBParamb4_type& x)
{
this->PVPerf_Sandia_SandiaDBParamb4_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb4 (const PVPerf_Sandia_SandiaDBParamb4_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamb4_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb5_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb5 () const
{
return this->PVPerf_Sandia_SandiaDBParamb5_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb5_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb5 ()
{
return this->PVPerf_Sandia_SandiaDBParamb5_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb5 (const PVPerf_Sandia_SandiaDBParamb5_type& x)
{
this->PVPerf_Sandia_SandiaDBParamb5_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb5 (const PVPerf_Sandia_SandiaDBParamb5_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamb5_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamDeltaTc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamDeltaTc () const
{
return this->PVPerf_Sandia_SandiaDbParamDeltaTc_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamDeltaTc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamDeltaTc ()
{
return this->PVPerf_Sandia_SandiaDbParamDeltaTc_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamDeltaTc (const PVPerf_Sandia_SandiaDbParamDeltaTc_type& x)
{
this->PVPerf_Sandia_SandiaDbParamDeltaTc_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamDeltaTc (const PVPerf_Sandia_SandiaDbParamDeltaTc_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamDeltaTc_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamFd_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamFd () const
{
return this->PVPerf_Sandia_SandiaDbParamFd_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamFd_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamFd ()
{
return this->PVPerf_Sandia_SandiaDbParamFd_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamFd (const PVPerf_Sandia_SandiaDbParamFd_type& x)
{
this->PVPerf_Sandia_SandiaDbParamFd_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamFd (const PVPerf_Sandia_SandiaDbParamFd_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamFd_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamA_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamA () const
{
return this->PVPerf_Sandia_SandiaDbParamA_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamA_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamA ()
{
return this->PVPerf_Sandia_SandiaDbParamA_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamA (const PVPerf_Sandia_SandiaDbParamA_type& x)
{
this->PVPerf_Sandia_SandiaDbParamA_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamA (const PVPerf_Sandia_SandiaDbParamA_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamA_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamB_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamB () const
{
return this->PVPerf_Sandia_SandiaDbParamB_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamB_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamB ()
{
return this->PVPerf_Sandia_SandiaDbParamB_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamB (const PVPerf_Sandia_SandiaDbParamB_type& x)
{
this->PVPerf_Sandia_SandiaDbParamB_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamB (const PVPerf_Sandia_SandiaDbParamB_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamB_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc4 () const
{
return this->PVPerf_Sandia_SandiaDBParamc4_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc4 ()
{
return this->PVPerf_Sandia_SandiaDBParamc4_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc4 (const PVPerf_Sandia_SandiaDBParamc4_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc4_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc4 (const PVPerf_Sandia_SandiaDBParamc4_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc4_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc5_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc5 () const
{
return this->PVPerf_Sandia_SandiaDBParamc5_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc5_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc5 ()
{
return this->PVPerf_Sandia_SandiaDBParamc5_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc5 (const PVPerf_Sandia_SandiaDBParamc5_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc5_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc5 (const PVPerf_Sandia_SandiaDBParamc5_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc5_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamIx0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIx0 () const
{
return this->PVPerf_Sandia_SandiaDbParamIx0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamIx0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIx0 ()
{
return this->PVPerf_Sandia_SandiaDbParamIx0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIx0 (const PVPerf_Sandia_SandiaDbParamIx0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamIx0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIx0 (const PVPerf_Sandia_SandiaDbParamIx0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamIx0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamIxx0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIxx0 () const
{
return this->PVPerf_Sandia_SandiaDbParamIxx0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamIxx0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIxx0 ()
{
return this->PVPerf_Sandia_SandiaDbParamIxx0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIxx0 (const PVPerf_Sandia_SandiaDbParamIxx0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamIxx0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIxx0 (const PVPerf_Sandia_SandiaDbParamIxx0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamIxx0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc6_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc6 () const
{
return this->PVPerf_Sandia_SandiaDBParamc6_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc6_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc6 ()
{
return this->PVPerf_Sandia_SandiaDBParamc6_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc6 (const PVPerf_Sandia_SandiaDBParamc6_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc6_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc6 (const PVPerf_Sandia_SandiaDBParamc6_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc6_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc7_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc7 () const
{
return this->PVPerf_Sandia_SandiaDBParamc7_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc7_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc7 ()
{
return this->PVPerf_Sandia_SandiaDBParamc7_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc7 (const PVPerf_Sandia_SandiaDBParamc7_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc7_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc7 (const PVPerf_Sandia_SandiaDBParamc7_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc7_ = x;
}
}
}
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
}
namespace schema
{
namespace simxml
{
namespace MepModel
{
// SimFlowPlant_ElectricalGenerator_Photovoltaic
//
SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ElectricalGenerator_Photovoltaic ()
: ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator (),
SimFlowPlant_Name_ (this),
SimFlowPlant_SurfName_ (this),
SimFlowPlant_PhotovoltaicPerfObjType_ (this),
SimFlowPlant_ModulePerfName_ (this),
SimFlowPlant_HeatTranstegrationMode_ (this),
SimFlowPlant_NumberofSeriesStringsinParallel_ (this),
SimFlowPlant_NumModulesSeries_ (this),
PhotovoltaicPerformance_Simple_Name_ (this),
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ (this),
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ (this),
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ (this),
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ (this),
PVPerf_EquivOne_Diode_Name_ (this),
PVPerf_EquivOne_Diode_CellType_ (this),
PVPerf_EquivOne_Diode_NumCellsSeries_ (this),
PVPerf_EquivOne_Diode_ActiveArea_ (this),
PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ (this),
PVPerf_EquivOne_Diode_SemiconductorBandgap_ (this),
PVPerf_EquivOne_Diode_ShuntResist_ (this),
PVPerf_EquivOne_Diode_ShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_OpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_RefTemp_ (this),
PVPerf_EquivOne_Diode_RefInsol_ (this),
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ (this),
PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ (this),
PVPerf_EquivOne_Diode_TotalHeatCap_ (this),
PVPerf_Sandia_Name_ (this),
PVPerf_Sandia_ActiveArea_ (this),
PVPerf_Sandia_NumCellsSeries_ (this),
PVPerf_Sandia_NumCellsParallel_ (this),
PVPerf_Sandia_ShortCircuitCurrent_ (this),
PVPerf_Sandia_OpenCircuitVolt_ (this),
PVPerf_Sandia_CurrentAtMaxPwrPoint_ (this),
PVPerf_Sandia_VoltAtMaxPwrPoint_ (this),
PVPerf_Sandia_SandiaDbParamAc_ (this),
PVPerf_Sandia_SandiaDbParamAImp_ (this),
PVPerf_Sandia_SandiaDBParamc0_ (this),
PVPerf_Sandia_SandiaDBParamc1_ (this),
PVPerf_Sandia_SandiaDbParamBVoc0_ (this),
PVPerf_Sandia_SandiaDbParamMBVoc_ (this),
PVPerf_Sandia_SandiaDbParamBVmp0_ (this),
PVPerf_Sandia_SandiaDbParamMBVmp_ (this),
PVPerf_Sandia_DiodeFactor_ (this),
PVPerf_Sandia_SandiaDBParamc2_ (this),
PVPerf_Sandia_SandiaDBParamc3_ (this),
PVPerf_Sandia_SandiaDbParama_0_0_ (this),
PVPerf_Sandia_SandiaDbParama_1_1_ (this),
PVPerf_Sandia_SandiaDBParama2_ (this),
PVPerf_Sandia_SandiaDBParama3_ (this),
PVPerf_Sandia_SandiaDBParama4_ (this),
PVPerf_Sandia_SandiaDbParamb_0_0_ (this),
PVPerf_Sandia_SandiaDbParamb_1_1_ (this),
PVPerf_Sandia_SandiaDBParamb2_ (this),
PVPerf_Sandia_SandiaDBParamb3_ (this),
PVPerf_Sandia_SandiaDBParamb4_ (this),
PVPerf_Sandia_SandiaDBParamb5_ (this),
PVPerf_Sandia_SandiaDbParamDeltaTc_ (this),
PVPerf_Sandia_SandiaDbParamFd_ (this),
PVPerf_Sandia_SandiaDbParamA_ (this),
PVPerf_Sandia_SandiaDbParamB_ (this),
PVPerf_Sandia_SandiaDBParamc4_ (this),
PVPerf_Sandia_SandiaDBParamc5_ (this),
PVPerf_Sandia_SandiaDbParamIx0_ (this),
PVPerf_Sandia_SandiaDbParamIxx0_ (this),
PVPerf_Sandia_SandiaDBParamc6_ (this),
PVPerf_Sandia_SandiaDBParamc7_ (this)
{
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ElectricalGenerator_Photovoltaic (const RefId_type& RefId)
: ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator (RefId),
SimFlowPlant_Name_ (this),
SimFlowPlant_SurfName_ (this),
SimFlowPlant_PhotovoltaicPerfObjType_ (this),
SimFlowPlant_ModulePerfName_ (this),
SimFlowPlant_HeatTranstegrationMode_ (this),
SimFlowPlant_NumberofSeriesStringsinParallel_ (this),
SimFlowPlant_NumModulesSeries_ (this),
PhotovoltaicPerformance_Simple_Name_ (this),
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ (this),
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ (this),
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ (this),
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ (this),
PVPerf_EquivOne_Diode_Name_ (this),
PVPerf_EquivOne_Diode_CellType_ (this),
PVPerf_EquivOne_Diode_NumCellsSeries_ (this),
PVPerf_EquivOne_Diode_ActiveArea_ (this),
PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ (this),
PVPerf_EquivOne_Diode_SemiconductorBandgap_ (this),
PVPerf_EquivOne_Diode_ShuntResist_ (this),
PVPerf_EquivOne_Diode_ShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_OpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_RefTemp_ (this),
PVPerf_EquivOne_Diode_RefInsol_ (this),
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ (this),
PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ (this),
PVPerf_EquivOne_Diode_TotalHeatCap_ (this),
PVPerf_Sandia_Name_ (this),
PVPerf_Sandia_ActiveArea_ (this),
PVPerf_Sandia_NumCellsSeries_ (this),
PVPerf_Sandia_NumCellsParallel_ (this),
PVPerf_Sandia_ShortCircuitCurrent_ (this),
PVPerf_Sandia_OpenCircuitVolt_ (this),
PVPerf_Sandia_CurrentAtMaxPwrPoint_ (this),
PVPerf_Sandia_VoltAtMaxPwrPoint_ (this),
PVPerf_Sandia_SandiaDbParamAc_ (this),
PVPerf_Sandia_SandiaDbParamAImp_ (this),
PVPerf_Sandia_SandiaDBParamc0_ (this),
PVPerf_Sandia_SandiaDBParamc1_ (this),
PVPerf_Sandia_SandiaDbParamBVoc0_ (this),
PVPerf_Sandia_SandiaDbParamMBVoc_ (this),
PVPerf_Sandia_SandiaDbParamBVmp0_ (this),
PVPerf_Sandia_SandiaDbParamMBVmp_ (this),
PVPerf_Sandia_DiodeFactor_ (this),
PVPerf_Sandia_SandiaDBParamc2_ (this),
PVPerf_Sandia_SandiaDBParamc3_ (this),
PVPerf_Sandia_SandiaDbParama_0_0_ (this),
PVPerf_Sandia_SandiaDbParama_1_1_ (this),
PVPerf_Sandia_SandiaDBParama2_ (this),
PVPerf_Sandia_SandiaDBParama3_ (this),
PVPerf_Sandia_SandiaDBParama4_ (this),
PVPerf_Sandia_SandiaDbParamb_0_0_ (this),
PVPerf_Sandia_SandiaDbParamb_1_1_ (this),
PVPerf_Sandia_SandiaDBParamb2_ (this),
PVPerf_Sandia_SandiaDBParamb3_ (this),
PVPerf_Sandia_SandiaDBParamb4_ (this),
PVPerf_Sandia_SandiaDBParamb5_ (this),
PVPerf_Sandia_SandiaDbParamDeltaTc_ (this),
PVPerf_Sandia_SandiaDbParamFd_ (this),
PVPerf_Sandia_SandiaDbParamA_ (this),
PVPerf_Sandia_SandiaDbParamB_ (this),
PVPerf_Sandia_SandiaDBParamc4_ (this),
PVPerf_Sandia_SandiaDBParamc5_ (this),
PVPerf_Sandia_SandiaDbParamIx0_ (this),
PVPerf_Sandia_SandiaDbParamIxx0_ (this),
PVPerf_Sandia_SandiaDBParamc6_ (this),
PVPerf_Sandia_SandiaDBParamc7_ (this)
{
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ElectricalGenerator_Photovoltaic (const SimFlowPlant_ElectricalGenerator_Photovoltaic& x,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator (x, f, c),
SimFlowPlant_Name_ (x.SimFlowPlant_Name_, f, this),
SimFlowPlant_SurfName_ (x.SimFlowPlant_SurfName_, f, this),
SimFlowPlant_PhotovoltaicPerfObjType_ (x.SimFlowPlant_PhotovoltaicPerfObjType_, f, this),
SimFlowPlant_ModulePerfName_ (x.SimFlowPlant_ModulePerfName_, f, this),
SimFlowPlant_HeatTranstegrationMode_ (x.SimFlowPlant_HeatTranstegrationMode_, f, this),
SimFlowPlant_NumberofSeriesStringsinParallel_ (x.SimFlowPlant_NumberofSeriesStringsinParallel_, f, this),
SimFlowPlant_NumModulesSeries_ (x.SimFlowPlant_NumModulesSeries_, f, this),
PhotovoltaicPerformance_Simple_Name_ (x.PhotovoltaicPerformance_Simple_Name_, f, this),
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ (x.PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_, f, this),
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ (x.PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_, f, this),
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ (x.PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_, f, this),
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ (x.PhotovoltaicPerformance_Simple_EfficiencyScheduleName_, f, this),
PVPerf_EquivOne_Diode_Name_ (x.PVPerf_EquivOne_Diode_Name_, f, this),
PVPerf_EquivOne_Diode_CellType_ (x.PVPerf_EquivOne_Diode_CellType_, f, this),
PVPerf_EquivOne_Diode_NumCellsSeries_ (x.PVPerf_EquivOne_Diode_NumCellsSeries_, f, this),
PVPerf_EquivOne_Diode_ActiveArea_ (x.PVPerf_EquivOne_Diode_ActiveArea_, f, this),
PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ (x.PVPerf_EquivOne_Diode_TransAbsorptanceProduct_, f, this),
PVPerf_EquivOne_Diode_SemiconductorBandgap_ (x.PVPerf_EquivOne_Diode_SemiconductorBandgap_, f, this),
PVPerf_EquivOne_Diode_ShuntResist_ (x.PVPerf_EquivOne_Diode_ShuntResist_, f, this),
PVPerf_EquivOne_Diode_ShortCircuitCurrent_ (x.PVPerf_EquivOne_Diode_ShortCircuitCurrent_, f, this),
PVPerf_EquivOne_Diode_OpenCircuitVolt_ (x.PVPerf_EquivOne_Diode_OpenCircuitVolt_, f, this),
PVPerf_EquivOne_Diode_RefTemp_ (x.PVPerf_EquivOne_Diode_RefTemp_, f, this),
PVPerf_EquivOne_Diode_RefInsol_ (x.PVPerf_EquivOne_Diode_RefInsol_, f, this),
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ (x.PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_, f, this),
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ (x.PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_, f, this),
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ (x.PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_, f, this),
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ (x.PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_, f, this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ (x.PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_, f, this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ (x.PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_, f, this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ (x.PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_, f, this),
PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ (x.PVPerf_EquivOne_Diode_ModuleHeatLossCoef_, f, this),
PVPerf_EquivOne_Diode_TotalHeatCap_ (x.PVPerf_EquivOne_Diode_TotalHeatCap_, f, this),
PVPerf_Sandia_Name_ (x.PVPerf_Sandia_Name_, f, this),
PVPerf_Sandia_ActiveArea_ (x.PVPerf_Sandia_ActiveArea_, f, this),
PVPerf_Sandia_NumCellsSeries_ (x.PVPerf_Sandia_NumCellsSeries_, f, this),
PVPerf_Sandia_NumCellsParallel_ (x.PVPerf_Sandia_NumCellsParallel_, f, this),
PVPerf_Sandia_ShortCircuitCurrent_ (x.PVPerf_Sandia_ShortCircuitCurrent_, f, this),
PVPerf_Sandia_OpenCircuitVolt_ (x.PVPerf_Sandia_OpenCircuitVolt_, f, this),
PVPerf_Sandia_CurrentAtMaxPwrPoint_ (x.PVPerf_Sandia_CurrentAtMaxPwrPoint_, f, this),
PVPerf_Sandia_VoltAtMaxPwrPoint_ (x.PVPerf_Sandia_VoltAtMaxPwrPoint_, f, this),
PVPerf_Sandia_SandiaDbParamAc_ (x.PVPerf_Sandia_SandiaDbParamAc_, f, this),
PVPerf_Sandia_SandiaDbParamAImp_ (x.PVPerf_Sandia_SandiaDbParamAImp_, f, this),
PVPerf_Sandia_SandiaDBParamc0_ (x.PVPerf_Sandia_SandiaDBParamc0_, f, this),
PVPerf_Sandia_SandiaDBParamc1_ (x.PVPerf_Sandia_SandiaDBParamc1_, f, this),
PVPerf_Sandia_SandiaDbParamBVoc0_ (x.PVPerf_Sandia_SandiaDbParamBVoc0_, f, this),
PVPerf_Sandia_SandiaDbParamMBVoc_ (x.PVPerf_Sandia_SandiaDbParamMBVoc_, f, this),
PVPerf_Sandia_SandiaDbParamBVmp0_ (x.PVPerf_Sandia_SandiaDbParamBVmp0_, f, this),
PVPerf_Sandia_SandiaDbParamMBVmp_ (x.PVPerf_Sandia_SandiaDbParamMBVmp_, f, this),
PVPerf_Sandia_DiodeFactor_ (x.PVPerf_Sandia_DiodeFactor_, f, this),
PVPerf_Sandia_SandiaDBParamc2_ (x.PVPerf_Sandia_SandiaDBParamc2_, f, this),
PVPerf_Sandia_SandiaDBParamc3_ (x.PVPerf_Sandia_SandiaDBParamc3_, f, this),
PVPerf_Sandia_SandiaDbParama_0_0_ (x.PVPerf_Sandia_SandiaDbParama_0_0_, f, this),
PVPerf_Sandia_SandiaDbParama_1_1_ (x.PVPerf_Sandia_SandiaDbParama_1_1_, f, this),
PVPerf_Sandia_SandiaDBParama2_ (x.PVPerf_Sandia_SandiaDBParama2_, f, this),
PVPerf_Sandia_SandiaDBParama3_ (x.PVPerf_Sandia_SandiaDBParama3_, f, this),
PVPerf_Sandia_SandiaDBParama4_ (x.PVPerf_Sandia_SandiaDBParama4_, f, this),
PVPerf_Sandia_SandiaDbParamb_0_0_ (x.PVPerf_Sandia_SandiaDbParamb_0_0_, f, this),
PVPerf_Sandia_SandiaDbParamb_1_1_ (x.PVPerf_Sandia_SandiaDbParamb_1_1_, f, this),
PVPerf_Sandia_SandiaDBParamb2_ (x.PVPerf_Sandia_SandiaDBParamb2_, f, this),
PVPerf_Sandia_SandiaDBParamb3_ (x.PVPerf_Sandia_SandiaDBParamb3_, f, this),
PVPerf_Sandia_SandiaDBParamb4_ (x.PVPerf_Sandia_SandiaDBParamb4_, f, this),
PVPerf_Sandia_SandiaDBParamb5_ (x.PVPerf_Sandia_SandiaDBParamb5_, f, this),
PVPerf_Sandia_SandiaDbParamDeltaTc_ (x.PVPerf_Sandia_SandiaDbParamDeltaTc_, f, this),
PVPerf_Sandia_SandiaDbParamFd_ (x.PVPerf_Sandia_SandiaDbParamFd_, f, this),
PVPerf_Sandia_SandiaDbParamA_ (x.PVPerf_Sandia_SandiaDbParamA_, f, this),
PVPerf_Sandia_SandiaDbParamB_ (x.PVPerf_Sandia_SandiaDbParamB_, f, this),
PVPerf_Sandia_SandiaDBParamc4_ (x.PVPerf_Sandia_SandiaDBParamc4_, f, this),
PVPerf_Sandia_SandiaDBParamc5_ (x.PVPerf_Sandia_SandiaDBParamc5_, f, this),
PVPerf_Sandia_SandiaDbParamIx0_ (x.PVPerf_Sandia_SandiaDbParamIx0_, f, this),
PVPerf_Sandia_SandiaDbParamIxx0_ (x.PVPerf_Sandia_SandiaDbParamIxx0_, f, this),
PVPerf_Sandia_SandiaDBParamc6_ (x.PVPerf_Sandia_SandiaDBParamc6_, f, this),
PVPerf_Sandia_SandiaDBParamc7_ (x.PVPerf_Sandia_SandiaDBParamc7_, f, this)
{
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ElectricalGenerator_Photovoltaic (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator (e, f | ::xml_schema::flags::base, c),
SimFlowPlant_Name_ (this),
SimFlowPlant_SurfName_ (this),
SimFlowPlant_PhotovoltaicPerfObjType_ (this),
SimFlowPlant_ModulePerfName_ (this),
SimFlowPlant_HeatTranstegrationMode_ (this),
SimFlowPlant_NumberofSeriesStringsinParallel_ (this),
SimFlowPlant_NumModulesSeries_ (this),
PhotovoltaicPerformance_Simple_Name_ (this),
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ (this),
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ (this),
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ (this),
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ (this),
PVPerf_EquivOne_Diode_Name_ (this),
PVPerf_EquivOne_Diode_CellType_ (this),
PVPerf_EquivOne_Diode_NumCellsSeries_ (this),
PVPerf_EquivOne_Diode_ActiveArea_ (this),
PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ (this),
PVPerf_EquivOne_Diode_SemiconductorBandgap_ (this),
PVPerf_EquivOne_Diode_ShuntResist_ (this),
PVPerf_EquivOne_Diode_ShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_OpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_RefTemp_ (this),
PVPerf_EquivOne_Diode_RefInsol_ (this),
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ (this),
PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ (this),
PVPerf_EquivOne_Diode_TotalHeatCap_ (this),
PVPerf_Sandia_Name_ (this),
PVPerf_Sandia_ActiveArea_ (this),
PVPerf_Sandia_NumCellsSeries_ (this),
PVPerf_Sandia_NumCellsParallel_ (this),
PVPerf_Sandia_ShortCircuitCurrent_ (this),
PVPerf_Sandia_OpenCircuitVolt_ (this),
PVPerf_Sandia_CurrentAtMaxPwrPoint_ (this),
PVPerf_Sandia_VoltAtMaxPwrPoint_ (this),
PVPerf_Sandia_SandiaDbParamAc_ (this),
PVPerf_Sandia_SandiaDbParamAImp_ (this),
PVPerf_Sandia_SandiaDBParamc0_ (this),
PVPerf_Sandia_SandiaDBParamc1_ (this),
PVPerf_Sandia_SandiaDbParamBVoc0_ (this),
PVPerf_Sandia_SandiaDbParamMBVoc_ (this),
PVPerf_Sandia_SandiaDbParamBVmp0_ (this),
PVPerf_Sandia_SandiaDbParamMBVmp_ (this),
PVPerf_Sandia_DiodeFactor_ (this),
PVPerf_Sandia_SandiaDBParamc2_ (this),
PVPerf_Sandia_SandiaDBParamc3_ (this),
PVPerf_Sandia_SandiaDbParama_0_0_ (this),
PVPerf_Sandia_SandiaDbParama_1_1_ (this),
PVPerf_Sandia_SandiaDBParama2_ (this),
PVPerf_Sandia_SandiaDBParama3_ (this),
PVPerf_Sandia_SandiaDBParama4_ (this),
PVPerf_Sandia_SandiaDbParamb_0_0_ (this),
PVPerf_Sandia_SandiaDbParamb_1_1_ (this),
PVPerf_Sandia_SandiaDBParamb2_ (this),
PVPerf_Sandia_SandiaDBParamb3_ (this),
PVPerf_Sandia_SandiaDBParamb4_ (this),
PVPerf_Sandia_SandiaDBParamb5_ (this),
PVPerf_Sandia_SandiaDbParamDeltaTc_ (this),
PVPerf_Sandia_SandiaDbParamFd_ (this),
PVPerf_Sandia_SandiaDbParamA_ (this),
PVPerf_Sandia_SandiaDbParamB_ (this),
PVPerf_Sandia_SandiaDBParamc4_ (this),
PVPerf_Sandia_SandiaDBParamc5_ (this),
PVPerf_Sandia_SandiaDbParamIx0_ (this),
PVPerf_Sandia_SandiaDbParamIxx0_ (this),
PVPerf_Sandia_SandiaDBParamc6_ (this),
PVPerf_Sandia_SandiaDBParamc7_ (this)
{
if ((f & ::xml_schema::flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, true, false, true);
this->parse (p, f);
}
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::flags f)
{
this->::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator::parse (p, f);
for (; p.more_content (); p.next_content (false))
{
const ::xercesc::DOMElement& i (p.cur_element ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
// SimFlowPlant_Name
//
if (n.name () == "SimFlowPlant_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_Name_type > r (
SimFlowPlant_Name_traits::create (i, f, this));
if (!this->SimFlowPlant_Name_)
{
this->SimFlowPlant_Name_.set (r);
continue;
}
}
// SimFlowPlant_SurfName
//
if (n.name () == "SimFlowPlant_SurfName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_SurfName_type > r (
SimFlowPlant_SurfName_traits::create (i, f, this));
if (!this->SimFlowPlant_SurfName_)
{
this->SimFlowPlant_SurfName_.set (r);
continue;
}
}
// SimFlowPlant_PhotovoltaicPerfObjType
//
if (n.name () == "SimFlowPlant_PhotovoltaicPerfObjType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_PhotovoltaicPerfObjType_type > r (
SimFlowPlant_PhotovoltaicPerfObjType_traits::create (i, f, this));
if (!this->SimFlowPlant_PhotovoltaicPerfObjType_)
{
this->SimFlowPlant_PhotovoltaicPerfObjType_.set (r);
continue;
}
}
// SimFlowPlant_ModulePerfName
//
if (n.name () == "SimFlowPlant_ModulePerfName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_ModulePerfName_type > r (
SimFlowPlant_ModulePerfName_traits::create (i, f, this));
if (!this->SimFlowPlant_ModulePerfName_)
{
this->SimFlowPlant_ModulePerfName_.set (r);
continue;
}
}
// SimFlowPlant_HeatTranstegrationMode
//
if (n.name () == "SimFlowPlant_HeatTranstegrationMode" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_HeatTranstegrationMode_type > r (
SimFlowPlant_HeatTranstegrationMode_traits::create (i, f, this));
if (!this->SimFlowPlant_HeatTranstegrationMode_)
{
this->SimFlowPlant_HeatTranstegrationMode_.set (r);
continue;
}
}
// SimFlowPlant_NumberofSeriesStringsinParallel
//
if (n.name () == "SimFlowPlant_NumberofSeriesStringsinParallel" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->SimFlowPlant_NumberofSeriesStringsinParallel_)
{
this->SimFlowPlant_NumberofSeriesStringsinParallel_.set (SimFlowPlant_NumberofSeriesStringsinParallel_traits::create (i, f, this));
continue;
}
}
// SimFlowPlant_NumModulesSeries
//
if (n.name () == "SimFlowPlant_NumModulesSeries" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->SimFlowPlant_NumModulesSeries_)
{
this->SimFlowPlant_NumModulesSeries_.set (SimFlowPlant_NumModulesSeries_traits::create (i, f, this));
continue;
}
}
// PhotovoltaicPerformance_Simple_Name
//
if (n.name () == "PhotovoltaicPerformance_Simple_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PhotovoltaicPerformance_Simple_Name_type > r (
PhotovoltaicPerformance_Simple_Name_traits::create (i, f, this));
if (!this->PhotovoltaicPerformance_Simple_Name_)
{
this->PhotovoltaicPerformance_Simple_Name_.set (r);
continue;
}
}
// PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells
//
if (n.name () == "PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_)
{
this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_.set (PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_traits::create (i, f, this));
continue;
}
}
// PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode
//
if (n.name () == "PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_type > r (
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_traits::create (i, f, this));
if (!this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_)
{
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_.set (r);
continue;
}
}
// PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed
//
if (n.name () == "PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_)
{
this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_.set (PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_traits::create (i, f, this));
continue;
}
}
// PhotovoltaicPerformance_Simple_EfficiencyScheduleName
//
if (n.name () == "PhotovoltaicPerformance_Simple_EfficiencyScheduleName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PhotovoltaicPerformance_Simple_EfficiencyScheduleName_type > r (
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_traits::create (i, f, this));
if (!this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_)
{
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_.set (r);
continue;
}
}
// PVPerf_EquivOne_Diode_Name
//
if (n.name () == "PVPerf_EquivOne_Diode_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_EquivOne_Diode_Name_type > r (
PVPerf_EquivOne_Diode_Name_traits::create (i, f, this));
if (!this->PVPerf_EquivOne_Diode_Name_)
{
this->PVPerf_EquivOne_Diode_Name_.set (r);
continue;
}
}
// PVPerf_EquivOne_Diode_CellType
//
if (n.name () == "PVPerf_EquivOne_Diode_CellType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_EquivOne_Diode_CellType_type > r (
PVPerf_EquivOne_Diode_CellType_traits::create (i, f, this));
if (!this->PVPerf_EquivOne_Diode_CellType_)
{
this->PVPerf_EquivOne_Diode_CellType_.set (r);
continue;
}
}
// PVPerf_EquivOne_Diode_NumCellsSeries
//
if (n.name () == "PVPerf_EquivOne_Diode_NumCellsSeries" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_NumCellsSeries_)
{
this->PVPerf_EquivOne_Diode_NumCellsSeries_.set (PVPerf_EquivOne_Diode_NumCellsSeries_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ActiveArea
//
if (n.name () == "PVPerf_EquivOne_Diode_ActiveArea" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ActiveArea_)
{
this->PVPerf_EquivOne_Diode_ActiveArea_.set (PVPerf_EquivOne_Diode_ActiveArea_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_TransAbsorptanceProduct
//
if (n.name () == "PVPerf_EquivOne_Diode_TransAbsorptanceProduct" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_)
{
this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_.set (PVPerf_EquivOne_Diode_TransAbsorptanceProduct_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_SemiconductorBandgap
//
if (n.name () == "PVPerf_EquivOne_Diode_SemiconductorBandgap" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_SemiconductorBandgap_)
{
this->PVPerf_EquivOne_Diode_SemiconductorBandgap_.set (PVPerf_EquivOne_Diode_SemiconductorBandgap_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ShuntResist
//
if (n.name () == "PVPerf_EquivOne_Diode_ShuntResist" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ShuntResist_)
{
this->PVPerf_EquivOne_Diode_ShuntResist_.set (PVPerf_EquivOne_Diode_ShuntResist_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ShortCircuitCurrent
//
if (n.name () == "PVPerf_EquivOne_Diode_ShortCircuitCurrent" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_)
{
this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_.set (PVPerf_EquivOne_Diode_ShortCircuitCurrent_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_OpenCircuitVolt
//
if (n.name () == "PVPerf_EquivOne_Diode_OpenCircuitVolt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_OpenCircuitVolt_)
{
this->PVPerf_EquivOne_Diode_OpenCircuitVolt_.set (PVPerf_EquivOne_Diode_OpenCircuitVolt_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_RefTemp
//
if (n.name () == "PVPerf_EquivOne_Diode_RefTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_RefTemp_)
{
this->PVPerf_EquivOne_Diode_RefTemp_.set (PVPerf_EquivOne_Diode_RefTemp_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_RefInsol
//
if (n.name () == "PVPerf_EquivOne_Diode_RefInsol" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_RefInsol_)
{
this->PVPerf_EquivOne_Diode_RefInsol_.set (PVPerf_EquivOne_Diode_RefInsol_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr
//
if (n.name () == "PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_)
{
this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_.set (PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr
//
if (n.name () == "PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_)
{
this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_.set (PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent
//
if (n.name () == "PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_)
{
this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_.set (PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt
//
if (n.name () == "PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_)
{
this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_.set (PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp
//
if (n.name () == "PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_.set (PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp
//
if (n.name () == "PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_.set (PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol
//
if (n.name () == "PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_.set (PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ModuleHeatLossCoef
//
if (n.name () == "PVPerf_EquivOne_Diode_ModuleHeatLossCoef" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_)
{
this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_.set (PVPerf_EquivOne_Diode_ModuleHeatLossCoef_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_TotalHeatCap
//
if (n.name () == "PVPerf_EquivOne_Diode_TotalHeatCap" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_TotalHeatCap_)
{
this->PVPerf_EquivOne_Diode_TotalHeatCap_.set (PVPerf_EquivOne_Diode_TotalHeatCap_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_Name
//
if (n.name () == "PVPerf_Sandia_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_Name_type > r (
PVPerf_Sandia_Name_traits::create (i, f, this));
if (!this->PVPerf_Sandia_Name_)
{
this->PVPerf_Sandia_Name_.set (r);
continue;
}
}
// PVPerf_Sandia_ActiveArea
//
if (n.name () == "PVPerf_Sandia_ActiveArea" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_ActiveArea_)
{
this->PVPerf_Sandia_ActiveArea_.set (PVPerf_Sandia_ActiveArea_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_NumCellsSeries
//
if (n.name () == "PVPerf_Sandia_NumCellsSeries" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_NumCellsSeries_)
{
this->PVPerf_Sandia_NumCellsSeries_.set (PVPerf_Sandia_NumCellsSeries_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_NumCellsParallel
//
if (n.name () == "PVPerf_Sandia_NumCellsParallel" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_NumCellsParallel_)
{
this->PVPerf_Sandia_NumCellsParallel_.set (PVPerf_Sandia_NumCellsParallel_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_ShortCircuitCurrent
//
if (n.name () == "PVPerf_Sandia_ShortCircuitCurrent" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_ShortCircuitCurrent_)
{
this->PVPerf_Sandia_ShortCircuitCurrent_.set (PVPerf_Sandia_ShortCircuitCurrent_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_OpenCircuitVolt
//
if (n.name () == "PVPerf_Sandia_OpenCircuitVolt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_OpenCircuitVolt_)
{
this->PVPerf_Sandia_OpenCircuitVolt_.set (PVPerf_Sandia_OpenCircuitVolt_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_CurrentAtMaxPwrPoint
//
if (n.name () == "PVPerf_Sandia_CurrentAtMaxPwrPoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_CurrentAtMaxPwrPoint_)
{
this->PVPerf_Sandia_CurrentAtMaxPwrPoint_.set (PVPerf_Sandia_CurrentAtMaxPwrPoint_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_VoltAtMaxPwrPoint
//
if (n.name () == "PVPerf_Sandia_VoltAtMaxPwrPoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_VoltAtMaxPwrPoint_)
{
this->PVPerf_Sandia_VoltAtMaxPwrPoint_.set (PVPerf_Sandia_VoltAtMaxPwrPoint_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamAc
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamAc" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamAc_)
{
this->PVPerf_Sandia_SandiaDbParamAc_.set (PVPerf_Sandia_SandiaDbParamAc_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamAImp
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamAImp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamAImp_)
{
this->PVPerf_Sandia_SandiaDbParamAImp_.set (PVPerf_Sandia_SandiaDbParamAImp_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc0
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc0_)
{
this->PVPerf_Sandia_SandiaDBParamc0_.set (PVPerf_Sandia_SandiaDBParamc0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc1
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc1_)
{
this->PVPerf_Sandia_SandiaDBParamc1_.set (PVPerf_Sandia_SandiaDBParamc1_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamBVoc0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamBVoc0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamBVoc0_)
{
this->PVPerf_Sandia_SandiaDbParamBVoc0_.set (PVPerf_Sandia_SandiaDbParamBVoc0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamMBVoc
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamMBVoc" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamMBVoc_)
{
this->PVPerf_Sandia_SandiaDbParamMBVoc_.set (PVPerf_Sandia_SandiaDbParamMBVoc_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamBVmp0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamBVmp0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamBVmp0_)
{
this->PVPerf_Sandia_SandiaDbParamBVmp0_.set (PVPerf_Sandia_SandiaDbParamBVmp0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamMBVmp
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamMBVmp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamMBVmp_)
{
this->PVPerf_Sandia_SandiaDbParamMBVmp_.set (PVPerf_Sandia_SandiaDbParamMBVmp_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_DiodeFactor
//
if (n.name () == "PVPerf_Sandia_DiodeFactor" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_DiodeFactor_)
{
this->PVPerf_Sandia_DiodeFactor_.set (PVPerf_Sandia_DiodeFactor_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc2
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc2_)
{
this->PVPerf_Sandia_SandiaDBParamc2_.set (PVPerf_Sandia_SandiaDBParamc2_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc3
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc3_)
{
this->PVPerf_Sandia_SandiaDBParamc3_.set (PVPerf_Sandia_SandiaDBParamc3_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParama_0_0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParama_0_0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_SandiaDbParama_0_0_type > r (
PVPerf_Sandia_SandiaDbParama_0_0_traits::create (i, f, this));
if (!this->PVPerf_Sandia_SandiaDbParama_0_0_)
{
this->PVPerf_Sandia_SandiaDbParama_0_0_.set (r);
continue;
}
}
// PVPerf_Sandia_SandiaDbParama_1_1
//
if (n.name () == "PVPerf_Sandia_SandiaDbParama_1_1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_SandiaDbParama_1_1_type > r (
PVPerf_Sandia_SandiaDbParama_1_1_traits::create (i, f, this));
if (!this->PVPerf_Sandia_SandiaDbParama_1_1_)
{
this->PVPerf_Sandia_SandiaDbParama_1_1_.set (r);
continue;
}
}
// PVPerf_Sandia_SandiaDBParama2
//
if (n.name () == "PVPerf_Sandia_SandiaDBParama2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParama2_)
{
this->PVPerf_Sandia_SandiaDBParama2_.set (PVPerf_Sandia_SandiaDBParama2_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParama3
//
if (n.name () == "PVPerf_Sandia_SandiaDBParama3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParama3_)
{
this->PVPerf_Sandia_SandiaDBParama3_.set (PVPerf_Sandia_SandiaDBParama3_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParama4
//
if (n.name () == "PVPerf_Sandia_SandiaDBParama4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParama4_)
{
this->PVPerf_Sandia_SandiaDBParama4_.set (PVPerf_Sandia_SandiaDBParama4_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamb_0_0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamb_0_0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_SandiaDbParamb_0_0_type > r (
PVPerf_Sandia_SandiaDbParamb_0_0_traits::create (i, f, this));
if (!this->PVPerf_Sandia_SandiaDbParamb_0_0_)
{
this->PVPerf_Sandia_SandiaDbParamb_0_0_.set (r);
continue;
}
}
// PVPerf_Sandia_SandiaDbParamb_1_1
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamb_1_1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_SandiaDbParamb_1_1_type > r (
PVPerf_Sandia_SandiaDbParamb_1_1_traits::create (i, f, this));
if (!this->PVPerf_Sandia_SandiaDbParamb_1_1_)
{
this->PVPerf_Sandia_SandiaDbParamb_1_1_.set (r);
continue;
}
}
// PVPerf_Sandia_SandiaDBParamb2
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamb2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamb2_)
{
this->PVPerf_Sandia_SandiaDBParamb2_.set (PVPerf_Sandia_SandiaDBParamb2_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamb3
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamb3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamb3_)
{
this->PVPerf_Sandia_SandiaDBParamb3_.set (PVPerf_Sandia_SandiaDBParamb3_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamb4
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamb4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamb4_)
{
this->PVPerf_Sandia_SandiaDBParamb4_.set (PVPerf_Sandia_SandiaDBParamb4_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamb5
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamb5" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamb5_)
{
this->PVPerf_Sandia_SandiaDBParamb5_.set (PVPerf_Sandia_SandiaDBParamb5_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamDeltaTc
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamDeltaTc" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamDeltaTc_)
{
this->PVPerf_Sandia_SandiaDbParamDeltaTc_.set (PVPerf_Sandia_SandiaDbParamDeltaTc_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamFd
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamFd" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamFd_)
{
this->PVPerf_Sandia_SandiaDbParamFd_.set (PVPerf_Sandia_SandiaDbParamFd_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamA
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamA" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamA_)
{
this->PVPerf_Sandia_SandiaDbParamA_.set (PVPerf_Sandia_SandiaDbParamA_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamB
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamB" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamB_)
{
this->PVPerf_Sandia_SandiaDbParamB_.set (PVPerf_Sandia_SandiaDbParamB_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc4
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc4_)
{
this->PVPerf_Sandia_SandiaDBParamc4_.set (PVPerf_Sandia_SandiaDBParamc4_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc5
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc5" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc5_)
{
this->PVPerf_Sandia_SandiaDBParamc5_.set (PVPerf_Sandia_SandiaDBParamc5_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamIx0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamIx0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamIx0_)
{
this->PVPerf_Sandia_SandiaDbParamIx0_.set (PVPerf_Sandia_SandiaDbParamIx0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamIxx0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamIxx0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamIxx0_)
{
this->PVPerf_Sandia_SandiaDbParamIxx0_.set (PVPerf_Sandia_SandiaDbParamIxx0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc6
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc6" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc6_)
{
this->PVPerf_Sandia_SandiaDBParamc6_.set (PVPerf_Sandia_SandiaDBParamc6_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc7
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc7" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc7_)
{
this->PVPerf_Sandia_SandiaDBParamc7_.set (PVPerf_Sandia_SandiaDBParamc7_traits::create (i, f, this));
continue;
}
}
break;
}
}
SimFlowPlant_ElectricalGenerator_Photovoltaic* SimFlowPlant_ElectricalGenerator_Photovoltaic::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class SimFlowPlant_ElectricalGenerator_Photovoltaic (*this, f, c);
}
SimFlowPlant_ElectricalGenerator_Photovoltaic& SimFlowPlant_ElectricalGenerator_Photovoltaic::
operator= (const SimFlowPlant_ElectricalGenerator_Photovoltaic& x)
{
if (this != &x)
{
static_cast< ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator& > (*this) = x;
this->SimFlowPlant_Name_ = x.SimFlowPlant_Name_;
this->SimFlowPlant_SurfName_ = x.SimFlowPlant_SurfName_;
this->SimFlowPlant_PhotovoltaicPerfObjType_ = x.SimFlowPlant_PhotovoltaicPerfObjType_;
this->SimFlowPlant_ModulePerfName_ = x.SimFlowPlant_ModulePerfName_;
this->SimFlowPlant_HeatTranstegrationMode_ = x.SimFlowPlant_HeatTranstegrationMode_;
this->SimFlowPlant_NumberofSeriesStringsinParallel_ = x.SimFlowPlant_NumberofSeriesStringsinParallel_;
this->SimFlowPlant_NumModulesSeries_ = x.SimFlowPlant_NumModulesSeries_;
this->PhotovoltaicPerformance_Simple_Name_ = x.PhotovoltaicPerformance_Simple_Name_;
this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ = x.PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_;
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ = x.PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_;
this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ = x.PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_;
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ = x.PhotovoltaicPerformance_Simple_EfficiencyScheduleName_;
this->PVPerf_EquivOne_Diode_Name_ = x.PVPerf_EquivOne_Diode_Name_;
this->PVPerf_EquivOne_Diode_CellType_ = x.PVPerf_EquivOne_Diode_CellType_;
this->PVPerf_EquivOne_Diode_NumCellsSeries_ = x.PVPerf_EquivOne_Diode_NumCellsSeries_;
this->PVPerf_EquivOne_Diode_ActiveArea_ = x.PVPerf_EquivOne_Diode_ActiveArea_;
this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ = x.PVPerf_EquivOne_Diode_TransAbsorptanceProduct_;
this->PVPerf_EquivOne_Diode_SemiconductorBandgap_ = x.PVPerf_EquivOne_Diode_SemiconductorBandgap_;
this->PVPerf_EquivOne_Diode_ShuntResist_ = x.PVPerf_EquivOne_Diode_ShuntResist_;
this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_ = x.PVPerf_EquivOne_Diode_ShortCircuitCurrent_;
this->PVPerf_EquivOne_Diode_OpenCircuitVolt_ = x.PVPerf_EquivOne_Diode_OpenCircuitVolt_;
this->PVPerf_EquivOne_Diode_RefTemp_ = x.PVPerf_EquivOne_Diode_RefTemp_;
this->PVPerf_EquivOne_Diode_RefInsol_ = x.PVPerf_EquivOne_Diode_RefInsol_;
this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ = x.PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_;
this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ = x.PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_;
this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ = x.PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_;
this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ = x.PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_;
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ = x.PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_;
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ = x.PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_;
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ = x.PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_;
this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ = x.PVPerf_EquivOne_Diode_ModuleHeatLossCoef_;
this->PVPerf_EquivOne_Diode_TotalHeatCap_ = x.PVPerf_EquivOne_Diode_TotalHeatCap_;
this->PVPerf_Sandia_Name_ = x.PVPerf_Sandia_Name_;
this->PVPerf_Sandia_ActiveArea_ = x.PVPerf_Sandia_ActiveArea_;
this->PVPerf_Sandia_NumCellsSeries_ = x.PVPerf_Sandia_NumCellsSeries_;
this->PVPerf_Sandia_NumCellsParallel_ = x.PVPerf_Sandia_NumCellsParallel_;
this->PVPerf_Sandia_ShortCircuitCurrent_ = x.PVPerf_Sandia_ShortCircuitCurrent_;
this->PVPerf_Sandia_OpenCircuitVolt_ = x.PVPerf_Sandia_OpenCircuitVolt_;
this->PVPerf_Sandia_CurrentAtMaxPwrPoint_ = x.PVPerf_Sandia_CurrentAtMaxPwrPoint_;
this->PVPerf_Sandia_VoltAtMaxPwrPoint_ = x.PVPerf_Sandia_VoltAtMaxPwrPoint_;
this->PVPerf_Sandia_SandiaDbParamAc_ = x.PVPerf_Sandia_SandiaDbParamAc_;
this->PVPerf_Sandia_SandiaDbParamAImp_ = x.PVPerf_Sandia_SandiaDbParamAImp_;
this->PVPerf_Sandia_SandiaDBParamc0_ = x.PVPerf_Sandia_SandiaDBParamc0_;
this->PVPerf_Sandia_SandiaDBParamc1_ = x.PVPerf_Sandia_SandiaDBParamc1_;
this->PVPerf_Sandia_SandiaDbParamBVoc0_ = x.PVPerf_Sandia_SandiaDbParamBVoc0_;
this->PVPerf_Sandia_SandiaDbParamMBVoc_ = x.PVPerf_Sandia_SandiaDbParamMBVoc_;
this->PVPerf_Sandia_SandiaDbParamBVmp0_ = x.PVPerf_Sandia_SandiaDbParamBVmp0_;
this->PVPerf_Sandia_SandiaDbParamMBVmp_ = x.PVPerf_Sandia_SandiaDbParamMBVmp_;
this->PVPerf_Sandia_DiodeFactor_ = x.PVPerf_Sandia_DiodeFactor_;
this->PVPerf_Sandia_SandiaDBParamc2_ = x.PVPerf_Sandia_SandiaDBParamc2_;
this->PVPerf_Sandia_SandiaDBParamc3_ = x.PVPerf_Sandia_SandiaDBParamc3_;
this->PVPerf_Sandia_SandiaDbParama_0_0_ = x.PVPerf_Sandia_SandiaDbParama_0_0_;
this->PVPerf_Sandia_SandiaDbParama_1_1_ = x.PVPerf_Sandia_SandiaDbParama_1_1_;
this->PVPerf_Sandia_SandiaDBParama2_ = x.PVPerf_Sandia_SandiaDBParama2_;
this->PVPerf_Sandia_SandiaDBParama3_ = x.PVPerf_Sandia_SandiaDBParama3_;
this->PVPerf_Sandia_SandiaDBParama4_ = x.PVPerf_Sandia_SandiaDBParama4_;
this->PVPerf_Sandia_SandiaDbParamb_0_0_ = x.PVPerf_Sandia_SandiaDbParamb_0_0_;
this->PVPerf_Sandia_SandiaDbParamb_1_1_ = x.PVPerf_Sandia_SandiaDbParamb_1_1_;
this->PVPerf_Sandia_SandiaDBParamb2_ = x.PVPerf_Sandia_SandiaDBParamb2_;
this->PVPerf_Sandia_SandiaDBParamb3_ = x.PVPerf_Sandia_SandiaDBParamb3_;
this->PVPerf_Sandia_SandiaDBParamb4_ = x.PVPerf_Sandia_SandiaDBParamb4_;
this->PVPerf_Sandia_SandiaDBParamb5_ = x.PVPerf_Sandia_SandiaDBParamb5_;
this->PVPerf_Sandia_SandiaDbParamDeltaTc_ = x.PVPerf_Sandia_SandiaDbParamDeltaTc_;
this->PVPerf_Sandia_SandiaDbParamFd_ = x.PVPerf_Sandia_SandiaDbParamFd_;
this->PVPerf_Sandia_SandiaDbParamA_ = x.PVPerf_Sandia_SandiaDbParamA_;
this->PVPerf_Sandia_SandiaDbParamB_ = x.PVPerf_Sandia_SandiaDbParamB_;
this->PVPerf_Sandia_SandiaDBParamc4_ = x.PVPerf_Sandia_SandiaDBParamc4_;
this->PVPerf_Sandia_SandiaDBParamc5_ = x.PVPerf_Sandia_SandiaDBParamc5_;
this->PVPerf_Sandia_SandiaDbParamIx0_ = x.PVPerf_Sandia_SandiaDbParamIx0_;
this->PVPerf_Sandia_SandiaDbParamIxx0_ = x.PVPerf_Sandia_SandiaDbParamIxx0_;
this->PVPerf_Sandia_SandiaDBParamc6_ = x.PVPerf_Sandia_SandiaDBParamc6_;
this->PVPerf_Sandia_SandiaDBParamc7_ = x.PVPerf_Sandia_SandiaDBParamc7_;
}
return *this;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::
~SimFlowPlant_ElectricalGenerator_Photovoltaic ()
{
}
}
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace schema
{
namespace simxml
{
namespace MepModel
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| 43.769762 | 195 | 0.725179 | EnEff-BIM |
fa436636d8dac56b1c2ef14b9a1b811fc6eae866 | 10,898 | hpp | C++ | include/algebra/array/multi_array.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/algebra/array/multi_array.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/algebra/array/multi_array.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | /************************
// \file multi_array.hpp
// \brief
//
// \author czhou
// \date 20 janv. 2018
***********************/
#ifndef MULTI_ARRAY_HPP_
#define MULTI_ARRAY_HPP_
#include <iostream>
#include <assert.h>
#include "algebra/algebra_define.hpp"
#include <array>
#include "array_list.hpp"
namespace carpio {
template<typename T, St DIM>
class MultiArray_ {
public:
static const St Dim = DIM;
// type definitions===================
typedef T value_t;
typedef MultiArray_<value_t, Dim> Self;
typedef MultiArray_<value_t, Dim>* pSelf;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef St size_type;
typedef St difference_type;
typedef typename ArrayListT_<value_t>::iterator iterator;
typedef typename ArrayListT_<value_t>::const_iterator const_iterator;
private:
std::array<St, Dim> m_len;
ArrayListT_<value_t> m_mp;
public:
//constructor==========================
MultiArray_(){
m_len.fill(0);
}
MultiArray_(const Self& a){
this->m_len = a.m_len;
this->m_mp = a.m_mp;
}
MultiArray_(St iLen, St jLen= 0, St kLen= 0){
St len = iLen;
this->m_len[0] = iLen;
if (Dim >= 2) {
ASSERT(iLen > 0 && jLen > 0);
this->m_len[1] = jLen;
len *= jLen;
}
if (Dim == 3) {
ASSERT(iLen > 0 && jLen > 0 && kLen > 0);
this->m_len[2] = kLen;
len *= kLen;
}
this->m_mp.reconstruct(len);
}
void reconstruct(St iLen, St jLen = 0, St kLen= 0){
St len = iLen;
this->m_len[0] = iLen;
if (Dim >= 2) {
ASSERT(iLen > 0 && jLen > 0);
this->m_len[1] = jLen;
len *= jLen;
}
if (Dim == 3) {
ASSERT(iLen > 0 && jLen > 0 && kLen > 0);
this->m_len[2] = kLen;
len *= kLen;
}
this->m_mp.reconstruct(len);
}
//=============================================
MultiArray_<T, DIM>& operator=(const MultiArray_<T, DIM>& a){
if (this == &a) {
return *this;
}
this->m_len = a.m_len;
this->m_mp = a.m_mp;
return *this;
}
//=============================================
~MultiArray_() {
}
//Capacity=====================================
St size() const {
return m_mp.size();
}
St size_i() const {
return m_len[0];
}
St size_j() const {
return Dim >= 2 ? m_len[1] : 0;
}
St size_k() const {
return Dim >= 3 ? m_len[2] : 0;
}
bool empty() const {
return m_mp.empty();
}
/*
* iterator
*/
iterator begin() {
return m_mp.begin();
}
const_iterator begin() const {
return m_mp.begin();
}
iterator end() {
return m_mp.end();
}
const_iterator end() const {
return m_mp.end();
}
//Element access===============================
St to_1d_idx(St i, St j = 0, St k = 0) const{
ASSERT(i < this->m_len[0]);
if (Dim >= 2)
ASSERT(j < this->m_len[1]);
if (Dim >= 3)
ASSERT(k < this->m_len[2]);
std::array<St, Dim> inp;
inp[0] = i;
if (Dim >= 2) {
inp[1] = j;
}
if (Dim >= 3) {
inp[2] = k;
}
St idx = 0;
for (St ii = 0; ii < Dim; ii++) {
St b = 1;
for (St jj = ii + 1; jj < Dim; jj++) {
b *= m_len[jj];
}
idx += b * inp[ii];
}
return idx;
}
reference at(St i, St j= 0, St k= 0){
St idx = to_1d_idx(i, j, k);
return m_mp[idx];
}
const_reference at(St i, St j = 0, St k = 0) const{
St idx = to_1d_idx(i, j, k);
return m_mp[idx];
}
reference operator()(St i, St j = 0, St k = 0){
return at(i, j, k);
}
const_reference operator()(St i, St j = 0, St k = 0) const{
return at(i, j, k);
}
reference at_1d(St i){ return m_mp[i];}
const_reference at_1d(St i) const{ return m_mp[i];}
T get(St i, St j = 0, St k = 0){
return at(i, j, k);
}
void set(const T& value, St i, St j = 0, St k = 0){
this->at(i, j, k) = value;
}
void assign(const T& value){
m_mp.assign(value);
}
//element access===============================
// T* getpValue(St i, St = 0, St = 0); //not good
inline bool check_idx(St dim, St idx) const {
ASSERT(dim < Dim);
if (idx >= 0 && idx < m_len[dim]) {
return true;
} else {
return false;
}
}
inline bool check_idx_ijk(St i, St j, St k) const {
return check_idx(0, i) && ((Dim >= 2) ? check_idx(1, j) : true)
&& ((Dim >= 3) ? check_idx(2, k) : true);
}
inline St count_equal(const T& nd) const { //overload ==
return m_mp.count_equal(nd);
}
};
template<typename T, St DIM>
class MultiArrayV_ {
public:
static const St Dim = DIM;
// type definitions===================
typedef T value_t;
typedef MultiArrayV_<value_t, Dim> Self;
typedef MultiArrayV_<value_t, Dim>& ref_Self;
typedef const MultiArrayV_<value_t, Dim>& const_ref_Self;
typedef MultiArrayV_<value_t, Dim>* pSelf;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef St size_type;
typedef St difference_type;
typedef typename ArrayListT_<value_t>::iterator iterator;
typedef typename ArrayListT_<value_t>::const_iterator const_iterator;
private:
std::array<St, Dim> m_len;
ArrayListV_<value_t> m_mp;
public:
//constructor==========================
MultiArrayV_(){
m_len.fill(0);
}
MultiArrayV_(const Self& a):
m_len(a.m_len), m_mp(a.m_mp){
}
MultiArrayV_(St iLen, St jLen= 0, St kLen= 0){
St len = iLen;
this->m_len[0] = iLen;
if (Dim >= 2) {
ASSERT(iLen > 0 && jLen > 0);
this->m_len[1] = jLen;
len *= jLen;
}
if (Dim >= 3) {
ASSERT(iLen > 0 && jLen > 0 && kLen > 0);
this->m_len[2] = kLen;
len *= kLen;
}
this->m_mp.reconstruct(len);
}
void reconstruct(St iLen, St jLen = 0, St kLen= 0){
St Len = 0;
this->m_len[0] = iLen;
if (Dim == 1) {
Len = iLen;
}
if (Dim >= 2) {
ASSERT(iLen > 0 && jLen > 0);
this->m_len[1] = jLen;
Len = iLen * jLen;
}
if (Dim >= 3) {
ASSERT(iLen > 0 && jLen > 0 && kLen > 0);
this->m_len[2] = kLen;
Len = iLen * jLen * kLen;
}
this->m_mp.reconstruct(Len);
}
//=============================================
ref_Self operator=(const Self& a){
if (this == &a) {
return *this;
}
this->m_len = a.m_len;
this->m_mp = a.m_mp;
return *this;
}
//=============================================
~MultiArrayV_() {
}
//Capacity=====================================
St size() const {
return m_mp.size();
}
St size_i() const {
return m_len[0];
}
St size_j() const {
return Dim >= 2 ? m_len[1] : 0;
}
St size_k() const {
return Dim >= 3 ? m_len[2] : 0;
}
bool empty() const {
return m_mp.empty();
}
bool is_compatible(const Self& other) const{
for(St i = 0; i< Dim;++i){
if(m_len[i] != other.m_len[i]){
return false;
}
}
return true;
}
/*
* iterator
*/
iterator begin() {
return m_mp.begin();
}
const_iterator begin() const {
return m_mp.begin();
}
iterator end() {
return m_mp.end();
}
const_iterator end() const {
return m_mp.end();
}
//Element access===============================
St to_1d_idx(St i, St j = 0, St k = 0) const{
ASSERT(i < this->m_len[0]);
if (Dim >= 2)
ASSERT(j < this->m_len[1]);
if (Dim >= 3)
ASSERT(k < this->m_len[2]);
std::array<St, Dim> inp;
inp[0] = i;
if (Dim >= 2) {
inp[1] = j;
}
if (Dim >= 3) {
inp[2] = k;
}
St idx = 0;
for (St ii = 0; ii < Dim; ii++) {
St b = 1;
for (St jj = ii + 1; jj < Dim; jj++) {
b *= m_len[jj];
}
idx += b * inp[ii];
}
return idx;
}
reference at(const St& i,
const St& j= 0,
const St& k= 0){
St idx = to_1d_idx(i, j, k);
return m_mp[idx];
}
const_reference at(const St& i,
const St& j = 0,
const St& k = 0) const{
St idx = to_1d_idx(i, j, k);
return m_mp[idx];
}
reference operator()(const St& i,
const St& j = 0,
const St& k = 0){
return at(i, j, k);
}
const_reference operator()(const St i,
const St j = 0,
const St k = 0) const{
return at(i, j, k);
}
reference at_1d(St i){ return m_mp[i];}
const_reference at_1d(St i) const{ return m_mp[i];}
T get(St i, St j = 0, St k = 0){
return at(i, j, k);
}
void set(const T& value, St i, St j = 0, St k = 0){
this->at(i, j, k) = value;
}
void assign(const T& value){
m_mp.assign(value);
}
T max() const {
return this->m_mp.max();
}
T min() const {
return this->m_mp.min();
}
void abs(){
this->m_mp.abs();
}
T norm1() const{
return this->m_mp.norm1();
}
T norm2() const{
return this->m_mp.norm2();
}
T norminf() const{
return this->m_mp.norminf();
}
//element access===============================
inline bool check_idx(St dim, St idx) const {
ASSERT(dim < Dim);
if (idx >= 0 && idx < m_len[dim]) {
return true;
} else {
return false;
}
}
inline bool check_idx_ijk(St i, St j, St k) const {
return check_idx(0, i) && ((Dim >= 2) ? check_idx(1, j) : true)
&& ((Dim >= 3) ? check_idx(2, k) : true);
}
inline St count_equal(const T& nd) const { //overload ==
return m_mp.count_equal(nd);
}
// operator ====================================
Self operator-(){
Self res(*this);
res.m_mp = -res.m_mp;
return res;
}
ref_Self operator+=(const Self& a) {
ASSERT(this->is_compatible(a));
m_mp += a.m_mp;
return *this;
}
ref_Self operator-=(const Self& a) {
ASSERT(this->is_compatible(a));
m_mp -= a.m_mp;
return *this;
}
ref_Self operator*=(const Self& a) {
ASSERT(this->is_compatible(a));
m_mp *= a.m_mp;
return *this;
}
ref_Self operator/=(const Self& a) {
ASSERT(this->is_compatible(a));
m_mp /= a.m_mp;
return *this;
}
ref_Self operator+=(const Vt& a) {
m_mp += a;
return *this;
}
ref_Self operator-=(const Vt& a) {
m_mp -= a;
return *this;
}
ref_Self operator*=(const Vt& a) {
m_mp *= a;
return *this;
}
ref_Self operator/=(const Vt& a) {
m_mp /= a;
return *this;
}
};
template<typename T, St DIM>
MultiArrayV_<T, DIM> Abs(const MultiArrayV_<T, DIM> a){
MultiArrayV_<T, DIM> res(a);
}
}
#endif /* MULTI_ARRAY_HPP */
| 22.751566 | 73 | 0.497706 | hyperpower |
fa490073c133f6add5e423d69c2ba6046a6935e4 | 1,636 | cpp | C++ | cpp/subprojects/common/src/common/sampling/weight_vector_dense.cpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | null | null | null | cpp/subprojects/common/src/common/sampling/weight_vector_dense.cpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | null | null | null | cpp/subprojects/common/src/common/sampling/weight_vector_dense.cpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | 1 | 2022-03-08T22:06:56.000Z | 2022-03-08T22:06:56.000Z | #include "common/sampling/weight_vector_dense.hpp"
template<class T>
DenseWeightVector<T>::DenseWeightVector(uint32 numElements)
: DenseWeightVector<T>(numElements, false) {
}
template<class T>
DenseWeightVector<T>::DenseWeightVector(uint32 numElements, bool init)
: vector_(DenseVector<T>(numElements, init)), numNonZeroWeights_(0) {
}
template<class T>
typename DenseWeightVector<T>::iterator DenseWeightVector<T>::begin() {
return vector_.begin();
}
template<class T>
typename DenseWeightVector<T>::iterator DenseWeightVector<T>::end() {
return vector_.end();
}
template<class T>
typename DenseWeightVector<T>::const_iterator DenseWeightVector<T>::cbegin() const {
return vector_.cbegin();
}
template<class T>
typename DenseWeightVector<T>::const_iterator DenseWeightVector<T>::cend() const {
return vector_.cend();
}
template<class T>
uint32 DenseWeightVector<T>::getNumElements() const {
return vector_.getNumElements();
}
template<class T>
uint32 DenseWeightVector<T>::getNumNonZeroWeights() const {
return numNonZeroWeights_;
}
template<class T>
void DenseWeightVector<T>::setNumNonZeroWeights(uint32 numNonZeroWeights) {
numNonZeroWeights_ = numNonZeroWeights;
}
template<class T>
bool DenseWeightVector<T>::hasZeroWeights() const {
return numNonZeroWeights_ < vector_.getNumElements();
}
template<class T>
float64 DenseWeightVector<T>::getWeight(uint32 pos) const {
return (float64) vector_[pos];
}
template class DenseWeightVector<uint8>;
template class DenseWeightVector<uint32>;
template class DenseWeightVector<float32>;
template class DenseWeightVector<float64>;
| 25.169231 | 84 | 0.76956 | mrapp-ke |
fa492905fb125ca0c75a842e3ef0c326fc54635d | 395 | cpp | C++ | taint/src/riscv/targetcontext.cpp | ClasSun9/riscv-dynamic-taint-analysis | 8a96f5ea8d07580315253dc074f60955fc633da9 | [
"MIT"
] | null | null | null | taint/src/riscv/targetcontext.cpp | ClasSun9/riscv-dynamic-taint-analysis | 8a96f5ea8d07580315253dc074f60955fc633da9 | [
"MIT"
] | null | null | null | taint/src/riscv/targetcontext.cpp | ClasSun9/riscv-dynamic-taint-analysis | 8a96f5ea8d07580315253dc074f60955fc633da9 | [
"MIT"
] | null | null | null | #include "./targetcontext.hpp"
namespace riscv {
addr_t targetcontext::pc() {
return _pc;
}
const instruction& targetcontext::insn() {
return _insn;
}
const registerset& targetcontext::regs() {
return _regs;
}
targetcontext::targetcontext() { }
targetcontext::targetcontext(addr_t pc, instruction insn, registerset regs)
: _pc(pc)
, _insn(insn)
, _regs(regs) { }
} | 17.173913 | 76 | 0.678481 | ClasSun9 |
fa4ad8c3c50f540ea9be50d2aababf37cee4df09 | 1,216 | cpp | C++ | Sources/AGEngine/Utils/RWLock.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 47 | 2015-03-29T09:44:25.000Z | 2020-11-30T10:05:56.000Z | Sources/AGEngine/Utils/RWLock.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 313 | 2015-01-01T18:16:30.000Z | 2015-11-30T07:54:07.000Z | Sources/AGEngine/Utils/RWLock.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 9 | 2015-06-07T13:21:54.000Z | 2020-08-25T09:50:07.000Z | #include "RWLock.hpp"
#include "Debug.hpp"
#include <thread>
namespace AGE
{
RWLock::RWLock()
{
_sharedLock.store(0, std::memory_order_relaxed);
_uniqueLock.store(false, std::memory_order_relaxed);
}
void RWLock::ReadLock()
{
while (_uniqueLock.exchange(true, std::memory_order_relaxed))
{
std::this_thread::yield();
}
_sharedLock.fetch_add(1, std::memory_order_relaxed);
_uniqueLock.store(false, std::memory_order_relaxed);
}
void RWLock::ReadUnlock()
{
_sharedLock.fetch_sub(1, std::memory_order_relaxed);
}
void RWLock::WriteLock()
{
while (_uniqueLock.exchange(true, std::memory_order_relaxed))
{
std::this_thread::yield();
}
while (_sharedLock.load(std::memory_order_relaxed) > 0)
{
std::this_thread::yield();
}
}
void RWLock::WriteUnlock()
{
_uniqueLock.store(false, std::memory_order_relaxed);
}
// RWLockGuard
RWLockGuard::RWLockGuard(RWLock &lock, bool exclusive)
: _lock(lock)
, _exclusive(exclusive)
{
if (_exclusive)
{
_lock.WriteLock();
}
else
{
_lock.ReadLock();
}
}
RWLockGuard::~RWLockGuard()
{
if (_exclusive)
{
_lock.WriteUnlock();
}
else
{
_lock.ReadUnlock();
}
}
// End RWLockGuard
} | 16 | 63 | 0.67352 | Another-Game-Engine |
fa51378664eecd4a1bb9ef10d04f177fb4fe41a2 | 2,335 | cpp | C++ | cmfe/compute_sdk/examples/sample/kernel.cpp | dmitryryintel/cm-compiler | 1ef7651dc1c33d3e4853f8779d6a720e45e20e19 | [
"Intel",
"MIT"
] | 115 | 2018-02-01T18:56:44.000Z | 2022-03-21T13:23:00.000Z | cmfe/compute_sdk/examples/sample/kernel.cpp | dmitryryintel/cm-compiler | 1ef7651dc1c33d3e4853f8779d6a720e45e20e19 | [
"Intel",
"MIT"
] | 27 | 2018-09-17T17:49:49.000Z | 2021-11-03T04:31:51.000Z | cmfe/compute_sdk/examples/sample/kernel.cpp | dmitryryintel/cm-compiler | 1ef7651dc1c33d3e4853f8779d6a720e45e20e19 | [
"Intel",
"MIT"
] | 55 | 2018-02-01T07:11:49.000Z | 2022-03-04T01:20:23.000Z | /*===================== begin_copyright_notice ==================================
Copyright (c) 2021, Intel Corporation
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.
======================= end_copyright_notice ==================================*/
#include <cm/cm.h>
#ifdef SHIM
#include "shim_support.h"
#else
#define SHIM_API_EXPORT
#endif
extern "C" SHIM_API_EXPORT void vector_add(SurfaceIndex, SurfaceIndex, SurfaceIndex);
// shim layer (CM kernel, OpenCL runtime, GPU)
#ifdef SHIM
EXPORT_SIGNATURE(vector_add);
#endif
#define SURFACE_TYPE [[type("buffer_t")]]
#if defined(SHIM) || defined(CMRT_EMU)
#undef SURFACE_TYPE
#define SURFACE_TYPE
#endif
#define SZ 16
_GENX_MAIN_ void vector_add(
SurfaceIndex isurface1 SURFACE_TYPE,
SurfaceIndex isurface2 SURFACE_TYPE,
SurfaceIndex osurface SURFACE_TYPE
)
{
vector<int, SZ> ivector1;
vector<int, SZ> ivector2;
vector<int, SZ> ovector;
//printf("gid(0)=%d, gid(1)=%d, lid(0)=%d, lid(1)=%d\n", cm_group_id(0), cm_group_id(1), cm_local_id(0), cm_local_id(1));
unsigned offset = sizeof(unsigned) * SZ * cm_group_id(0);
//
// read-in the arguments
read(isurface1, offset, ivector1);
read(isurface2, offset, ivector2);
// perform addition
ovector = ivector1 + ivector2;
// write-out the results
write (osurface, offset, ovector);
}
| 34.850746 | 125 | 0.71606 | dmitryryintel |
fa54286fcc62fa3538bbf968e29a5b4093dfce47 | 8,310 | cpp | C++ | examples/fast_fourier_transform/test.cpp | drichmond/HOPS | 9684c0c9ebe5511fe0c202219a0bcd51fbf61079 | [
"BSD-3-Clause"
] | 10 | 2018-10-03T09:19:48.000Z | 2021-09-15T14:46:32.000Z | examples/fast_fourier_transform/test.cpp | drichmond/HOPS | 9684c0c9ebe5511fe0c202219a0bcd51fbf61079 | [
"BSD-3-Clause"
] | 1 | 2019-09-24T17:38:25.000Z | 2019-09-24T17:38:25.000Z | examples/fast_fourier_transform/test.cpp | drichmond/HOPS | 9684c0c9ebe5511fe0c202219a0bcd51fbf61079 | [
"BSD-3-Clause"
] | null | null | null | // ----------------------------------------------------------------------
// Copyright (c) 2018, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// 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 REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
#include <iostream>
#include <complex>
#include "utility.hpp"
#include "fft.hpp"
#ifdef BIT_ACCURATE
#include "hls_math.h"
#include "ap_fixed.h"
#include "ap_int.h"
#define DTYPE ap_fixed<32, 16, AP_RND>
#else
#define DTYPE float
#endif
#define LOG_LIST_LENGTH 4
#define LIST_LENGTH (1<<LOG_LIST_LENGTH)
std::array<std::complex<DTYPE>, LIST_LENGTH> fft_loop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> const& IN){
#pragma HLS PIPELINE
#pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE
return loop::fft(IN);
}
std::array<std::complex<DTYPE>, LIST_LENGTH> bitreverse_loop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> const& IN){
#pragma HLS PIPELINE
#pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE
return loop::bitreverse(IN);
}
std::array<std::complex<DTYPE>, LIST_LENGTH> nptfft_loop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH/2> const& L,
std::array<std::complex<DTYPE>, LIST_LENGTH/2> const& R){
return loop::nPtFFT(L, R);
}
std::array<std::complex<DTYPE>, LIST_LENGTH> fft_hop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> IN){
#pragma HLS PIPELINE
#pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE
#pragma HLS_INLINE
return fft(IN);
}
std::array<std::complex<DTYPE>, LIST_LENGTH> bitreverse_hop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> const& IN){
#pragma HLS PIPELINE
#pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE
return bitreverse(IN);
}
std::array<std::complex<DTYPE>, LIST_LENGTH> nptfft_hop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH/2> L, std::array<std::complex<DTYPE>, LIST_LENGTH/2> R){
#pragma HLS PIPELINE
#pragma HLS ARRAY_PARTITION variable=L._M_instance COMPLETE
#pragma HLS ARRAY_PARTITION variable=R._M_instance COMPLETE
return nPtFFT(L, R);
}
void bit_reverse(DTYPE X_R[LIST_LENGTH], DTYPE X_I[LIST_LENGTH]){
for(unsigned int t = 0; t < LIST_LENGTH; t++){
DTYPE temp;
unsigned int b = 0;
for(int j = 0; j < LOG_LIST_LENGTH; j++){
b = b << 1;
b |= ((t >> j) &1);
}
if(t > b){
temp = X_R[t];
X_R[t] = X_R[b];
X_R[b] = temp;
temp = X_I[t];
X_I[t] = X_I[b];
X_I[b] = temp;
}
}
}
void fft(DTYPE X_R[LIST_LENGTH], DTYPE X_I[LIST_LENGTH])
{
DTYPE temp_R; /*temporary storage complex variable*/
DTYPE temp_I; /*temporary storage complex variable*/
int i,j,k; /* loop indexes */
int i_lower; /* Index of lower point in butterfly */
int step;
int stage;
int DFTpts;
int BFSkip; /*Butterfly Width*/
int N2 = LIST_LENGTH>>1; /* N2=N>>1 */
/*=====================BEGIN BIT REVERSAL===========================*/
unsigned int t, b;
DTYPE temp;
bit_reverse(X_R, X_I);
/*++++++++++++++++++++++END OF BIT REVERSAL++++++++++++++++++++++++++*/
/*=======================BEGIN: FFT=========================*/
// Do M stages of butterflies
step=N2;
DTYPE a, e, c, s;
int counter;
stages:
for(stage=1; stage<= LOG_LIST_LENGTH; ++stage){
DFTpts = 1 << stage; // DFT = 2^stage = points in sub DFT
BFSkip = DFTpts/2; // Butterfly WIDTHS in sub-DFT
k=0;
e = -2*M_PI/DFTpts;
a = 0.0;
counter = 0;
// Perform butterflies for j-th stage
butterfly:
for(j=0; j<BFSkip; ++j){
c = cos((double)a);
s = sin((double)a);
// Compute butterflies that use same W**k
DFTpts:
for(i=j; i<LIST_LENGTH; i += DFTpts){
counter ++;
i_lower = i + BFSkip; //index of lower point in butterfly
//printf("%d %d %d a:%4f \tr:%4f \ti:%4f \trl:%4f \til:%4f\n", stage, i, i_lower, a, X_R[i], X_I[i], X_R[i_lower], X_I[i_lower]);
temp_R = X_R[i_lower]*c+ X_I[i_lower]*s;
temp_I = X_I[i_lower]*c- X_R[i_lower]*s;
X_R[i_lower] = X_R[i] - temp_R;
X_I[i_lower] = X_I[i] - temp_I;
X_R[i] = X_R[i] + temp_R;
X_I[i] = X_I[i] + temp_I;
}
a = a + e;
k+=step;
}
step=step/2;
}
}
int fft_test(){
std::array<std::complex<DTYPE>, LIST_LENGTH> in, out;
DTYPE gold_real[LIST_LENGTH];
DTYPE gold_imag[LIST_LENGTH];
for(int i = 0; i < LIST_LENGTH; i ++){
in[i] = {(DTYPE)(i + 1), (DTYPE)0};
gold_real[i] = i + 1;
gold_imag[i] = 0;
}
fft(gold_real, gold_imag);
out = fft_hop_synth(in);
for(int i = 0; i < LIST_LENGTH; i ++){
if(std::abs(float(gold_real[i] - out[i].real())) > .25){
std::cout << "Error! Recursive Real FFT Values at index "
<< i << "did not match" << std::endl;
return -1;
}
if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){
std::cout << "Error! Recursive Imaginary FFT Values at index "
<< i << "did not match" << std::endl;
return -1;
}
}
out = fft_loop_synth(in);
for(int i = 0; i < LIST_LENGTH; i ++){
if(std::abs(float(gold_real[i] - out[i].real())) > .25){
std::cout << "Error! Loop Real FFT Values at index "
<< i << "did not match" << std::endl;
return -1;
}
if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){
std::cout << "Error! Loop Imaginary FFT Values at index "
<< i << "did not match" << std::endl;
return -1;
}
}
std::cout << "Passed FFT tests!" << std::endl;
return 0;
}
int bitreverse_test(){
std::array<std::complex<DTYPE>, LIST_LENGTH> in, out;
DTYPE gold_real[LIST_LENGTH];
DTYPE gold_imag[LIST_LENGTH];
for(int i = 0; i < LIST_LENGTH; i ++){
in[i] = {(DTYPE)(i + 1), (DTYPE)0};
gold_real[i] = i + 1;
gold_imag[i] = 0;
}
bit_reverse(gold_real, gold_imag);
out = bitreverse_hop_synth(in);
for(int i = 0; i < LIST_LENGTH; i ++){
if(std::abs(float(gold_real[i] - out[i].real())) > .25){
std::cout << "Error! Loop Real Bitreverse Values at index "
<< i << "did not match" << std::endl;
return -1;
}
if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){
std::cout << "Error! Loop Imaginary Bitreverse Values at index "
<< i << "did not match" << std::endl;
return -1;
}
}
out = bitreverse_loop_synth(in);
for(int i = 0; i < LIST_LENGTH; i ++){
if(std::abs(float(gold_real[i] - out[i].real())) > .25){
std::cout << "Error! Loop Real Bitreverse Values at index "
<< i << "did not match" << std::endl;
return -1;
}
if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){
std::cout << "Error! Loop Imaginary Bitreverse Values at index "
<< i << "did not match" << std::endl;
return -1;
}
}
std::cout << "Passed Bitreverse tests!" << std::endl;
return 0;
}
int main(){
int err;
if((err = bitreverse_test())){
return err;
}
if((err = fft_test())){
return err;
}
std::cout << "FFT Tests Passed!" << std::endl;
return 0;
}
| 30.43956 | 162 | 0.633213 | drichmond |
fa594fe597bfb13624c70b7b714310278eecc85b | 776 | hpp | C++ | android-28/javax/security/auth/SubjectDomainCombiner.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/javax/security/auth/SubjectDomainCombiner.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/javax/security/auth/SubjectDomainCombiner.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "../../../JObject.hpp"
class JArray;
class JArray;
class JString;
namespace java::security
{
class ProtectionDomain;
}
namespace javax::security::auth
{
class Subject;
}
namespace javax::security::auth
{
class SubjectDomainCombiner : public JObject
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit SubjectDomainCombiner(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
SubjectDomainCombiner(QJniObject obj);
// Constructors
SubjectDomainCombiner(javax::security::auth::Subject arg0);
// Methods
JArray combine(JArray arg0, JArray arg1) const;
javax::security::auth::Subject getSubject() const;
};
} // namespace javax::security::auth
| 20.972973 | 162 | 0.716495 | YJBeetle |
fa60e041eac01f3fb44db8322fce99f975a32b55 | 926 | cpp | C++ | OOP - Laborator 9/Problema 1/Problema 1/main.cpp | alexrobert02/oop-2022 | 277655132fb8618b1ce1bd4bb53edc147a53028b | [
"MIT"
] | null | null | null | OOP - Laborator 9/Problema 1/Problema 1/main.cpp | alexrobert02/oop-2022 | 277655132fb8618b1ce1bd4bb53edc147a53028b | [
"MIT"
] | null | null | null | OOP - Laborator 9/Problema 1/Problema 1/main.cpp | alexrobert02/oop-2022 | 277655132fb8618b1ce1bd4bb53edc147a53028b | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include <vector>
#include <map>
#include "map.h"
int main()
{
Map<int, const char*> m;
m[10] = "C++";
m[20] = "test";
m[30] = "Poo";
for (auto [key, value, index] : m) {
printf("Index:%d, Key=%d, Value=%s\n", index, key, value);
}
m[20] = "result";
for (auto [key, value, index] : m) {
printf("Index:%d, Key=%d, Value=%s\n", index, key, value);
}
Map<int, const char*> n;
n[20] = "examen";
printf("%d\n", m.Includes(n));
m.Set(10, "licenta");
for (auto [key, value, index] : m) {
printf("Index:%d, Key=%d, Value=%s\n", index, key, value);
}
m.Delete(20);
for (auto [key, value, index] : m) {
printf("Index:%d, Key=%d, Value=%s\n", index, key, value);
}
printf("%d\n", m.Count());
const char* value;
m.Get(10, value);
printf("%s\n", value);
return 0;
} | 19.702128 | 66 | 0.5 | alexrobert02 |
fa61a1793e2b57b94e64326851a048b2a43f300f | 1,172 | hpp | C++ | source/NanairoCore/Data/intersection_test_result.hpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 30 | 2015-09-06T03:14:29.000Z | 2021-06-18T11:00:19.000Z | source/NanairoCore/Data/intersection_test_result.hpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 31 | 2016-01-14T14:50:34.000Z | 2018-06-25T13:21:48.000Z | source/NanairoCore/Data/intersection_test_result.hpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 6 | 2017-04-09T13:07:47.000Z | 2021-05-29T21:17:34.000Z | /*!
\file intersection_test_result.hpp
\author Sho Ikeda
Copyright (c) 2015-2018 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#ifndef NANAIRO_INTERSECTION_TEST_RESULT_HPP
#define NANAIRO_INTERSECTION_TEST_RESULT_HPP
// Nanairo
#include "NanairoCore/nanairo_core_config.hpp"
namespace nanairo {
/*!
*/
class IntersectionTestResult
{
public:
//! Create a failure result
IntersectionTestResult() noexcept;
//! Create a success result with the distance
IntersectionTestResult(const Float d) noexcept;
//! Check if the result is success
explicit operator bool() const noexcept;
//! Return the failure distance
static constexpr Float failureDistance() noexcept;
//! Check if the result is success
bool isSuccess() const noexcept;
//! Return the distance of the intersection point
Float rayDistance() const noexcept;
//! Set the distance of the intersection point
void setRayDistance(const Float d) noexcept;
private:
Float distance_;
};
} // namespace nanairo
#include "intersection_test_result-inl.hpp"
#endif // NANAIRO_INTERSECTION_TEST_RESULT_HPP
| 21.309091 | 52 | 0.756826 | byzin |
fa63f29fe52e415cd068788f3ad21da08e907982 | 17,604 | cpp | C++ | src/GenCVisitor.cpp | jkolek/cparser | 13a18cdfdd1e3fc4104b7def1dc7d81bdd8a8164 | [
"MIT"
] | 10 | 2017-12-16T14:40:30.000Z | 2022-02-20T09:09:02.000Z | src/GenCVisitor.cpp | jkolek/cparser | 13a18cdfdd1e3fc4104b7def1dc7d81bdd8a8164 | [
"MIT"
] | 3 | 2018-04-27T08:16:02.000Z | 2018-09-01T16:01:41.000Z | src/GenCVisitor.cpp | jkolek/cparser | 13a18cdfdd1e3fc4104b7def1dc7d81bdd8a8164 | [
"MIT"
] | 2 | 2019-02-06T14:02:31.000Z | 2021-11-02T02:34:21.000Z | // Generate C visitor - implementation file.
// Copyright (C) 2017, 2018 Jozef Kolek <[email protected]>
//
// All rights reserved.
//
// See the LICENSE file for more details.
#include "../include/GenCVisitor.h"
#include "../include/ASTNode.h"
#include "../include/TreeVisitor.h"
#include <iostream>
#define TAB_SIZE 4
namespace cparser
{
static void printTab(int n)
{
int i, x;
x = n * TAB_SIZE;
for (i = 0; i < x; i++)
std::cout << " ";
}
void GenCVisitor::visit(IdentASTNode *n)
{
std::cout << n->getValue();
}
void GenCVisitor::visit(IntegerConstASTNode *n)
{
std::cout << n->getValue();
}
void GenCVisitor::visit(StringConstASTNode *n)
{
std::cout << "\"" << n->getValue() << "\"";
}
void GenCVisitor::visit(CharConstASTNode *n)
{
if (n->getValue() == '\n')
std::cout << "'\\n'";
else
std::cout << "'" << (char) n->getValue() << "'";
}
void GenCVisitor::visit(SizeOfExprASTNode *n)
{
std::cout << "sizeof(";
if (n->getExpr() != NULL_AST_NODE)
n->getExpr()->accept(this);
std::cout << ")";
}
void GenCVisitor::visit(AlignOfExprASTNode *n)
{
std::cout << "_Alignof(";
if (n->getExpr() != NULL_AST_NODE)
n->getExpr()->accept(this);
std::cout << ")";
}
void GenCVisitor::visit(TypeDeclASTNode *n)
{
std::cout << "typedef ";
n->getBody()->accept(this);
std::cout << " ";
n->getName()->accept(this);
}
void GenCVisitor::visit(FunctionDeclASTNode *n)
{
n->getType()->accept(this);
std::cout << " ";
n->getName()->accept(this);
std::cout << "(";
_inList++;
n->getPrms()->accept(this);
_inList--;
std::cout << ")" << std::endl;
n->getBody()->accept(this);
}
void GenCVisitor::visit(VarDeclASTNode *n)
{
// if (n->getType()->getKind() == NK_FUNCTION_TYPE)
// {
// static_cast<FunctionTypeASTNode *>(n->getType())->getType()->accept(this);
// std::cout << "(*";
// n->getName()->accept(this);
// std::cout << ")";
// std::cout << "(";
// _inList++;
// static_cast<FunctionTypeASTNode *>(n->getType())->getPrms()->accept(this);
// _inList--;
// std::cout << ")";
// }
// else
// {
n->getType()->accept(this);
std::cout << " ";
// if (n->getType()->getKind() == NK_POINTER_TYPE)
// std::cout << "*";
n->getName()->accept(this);
if (n->getType()->getKind() == NK_ARRAY_TYPE)
{
std::cout << "[";
// Print out type expression
static_cast<ArrayTypeASTNode *>(n->getType())->getExpr()->accept(this);
std::cout << "]";
}
if (n->getInit() != NULL_AST_NODE)
{
std::cout << " = ";
n->getInit()->accept(this);
}
// }
}
void GenCVisitor::visit(ParmDeclASTNode *n)
{
if (n->getType() != NULL_AST_NODE)
n->getType()->accept(this);
std::cout << " ";
// if (n->getType()->getKind() == NK_POINTER_TYPE)
// std::cout << "*";
if (n->getName() != NULL_AST_NODE)
n->getName()->accept(this);
}
void GenCVisitor::visit(FieldDeclASTNode *n)
{
// _level++;
// printTab(_level);
// std::cout << "NK_FIELD_DECL" << std::endl;
// if (n->getName() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Name:" << std::endl;
// n->getName()->accept(this);
// }
// if (n->getType() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Type:" << std::endl;
// n->getType()->accept(this);
// }
// _level--;
if (n->getType() != NULL_AST_NODE)
n->getType()->accept(this);
std::cout << " ";
if (n->getName() != NULL_AST_NODE)
n->getName()->accept(this);
}
void GenCVisitor::visit(AsmStmtASTNode *n)
{
printTab(_level + 1);
std::cout << "NK_ASM_STMT" << std::endl;
printTab(_level + 1);
std::cout << "Data:" << std::endl;
printTab(_level + 2);
std::cout << n->getData() << std::endl;
}
void GenCVisitor::visit(BreakStmtASTNode *n)
{
std::cout << "break";
}
void GenCVisitor::visit(CaseLabelASTNode *n)
{
_level++;
printTab(_level);
std::cout << "CASE_LABEL" << std::endl;
if (n->getExpr() != NULL_AST_NODE)
{
printTab(_level);
std::cout << "Expression:" << std::endl;
n->getExpr()->accept(this);
}
if (n->getStmt() != NULL_AST_NODE)
{
printTab(_level);
std::cout << "Statement:" << std::endl;
n->getStmt()->accept(this);
}
_level--;
}
void GenCVisitor::visit(CompoundStmtASTNode *n)
{
printTab(_level);
std::cout << "{" << std::endl;
_level++;
if (n->getDecls() != NULL_AST_NODE)
{
n->getDecls()->accept(this);
}
if (n->getStmts() != NULL_AST_NODE)
{
n->getStmts()->accept(this);
}
_level--;
printTab(_level);
std::cout << "}" << std::endl;
}
void GenCVisitor::visit(ContinueStmtASTNode *n)
{
std::cout << "continue";
}
void GenCVisitor::visit(DoStmtASTNode *n)
{
std::cout << "do" << std::endl;
n->getBody()->accept(this);
printTab(_level);
std::cout << "while (";
n->getCondition()->accept(this);
std::cout << ");" << std::endl;
}
void GenCVisitor::visit(ForStmtASTNode *n)
{
std::cout << "for (";
if (n->getInit() != NULL_AST_NODE)
n->getInit()->accept(this);
std::cout << ";";
if (n->getCondition() != NULL_AST_NODE)
{
std::cout << " ";
n->getCondition()->accept(this);
}
std::cout << ";";
if (n->getStep() != NULL_AST_NODE)
{
std::cout << " ";
n->getStep()->accept(this);
}
std::cout << ")" << std::endl;
n->getBody()->accept(this);
}
void GenCVisitor::visit(GotoStmtASTNode *n)
{
std::cout << "goto ";
n->getLabel()->accept(this);
}
void GenCVisitor::visit(IfStmtASTNode *n)
{
std::cout << "if (";
if (n->getCondition() != NULL_AST_NODE)
n->getCondition()->accept(this);
std::cout << ")" << std::endl;
if (n->getThenClause() != NULL_AST_NODE)
{
if (n->getThenClause()->getKind() != NK_COMPOUND_STMT)
printTab(_level+1);
n->getThenClause()->accept(this);
}
if (n->getElseClause() != NULL_AST_NODE)
{
printTab(_level);
std::cout << "else";
if (n->getElseClause()->getKind() == NK_IF_STMT)
std::cout << " ";
else
std::cout << std::endl;
if (n->getElseClause()->getKind() != NK_COMPOUND_STMT &&
n->getElseClause()->getKind() != NK_IF_STMT)
printTab(_level+1);
n->getElseClause()->accept(this);
}
std::cout << std::endl;
}
void GenCVisitor::visit(LabelStmtASTNode *n)
{
int prevLevel = _level;
_level = 0;
n->getLabel()->accept(this);
_level = prevLevel;
std::cout << ":" << std::endl;
printTab(_level);
n->getStmt()->accept(this);
}
void GenCVisitor::visit(ReturnStmtASTNode *n)
{
std::cout << "return";
if (n->getExpr() != NULL_AST_NODE)
{
std::cout << " ";
n->getExpr()->accept(this);
}
}
void GenCVisitor::visit(SwitchStmtASTNode *n)
{
_level++;
printTab(_level);
std::cout << "SWITCH_STMT" << std::endl;
if (n->getExpr() != NULL_AST_NODE)
{
printTab(_level);
std::cout << "Expression:" << std::endl;
n->getExpr()->accept(this);
}
if (n->getStmt() != NULL_AST_NODE)
{
printTab(_level);
std::cout << "Statement:" << std::endl;
n->getStmt()->accept(this);
}
_level--;
}
void GenCVisitor::visit(WhileStmtASTNode *n)
{
std::cout << "while (";
if (n->getCondition() != NULL_AST_NODE)
n->getCondition()->accept(this);
std::cout << ")" << std::endl;
if (n->getBody() != NULL_AST_NODE)
n->getBody()->accept(this);
}
void GenCVisitor::visit(CastExprASTNode *n)
{
// _level++;
// printTab(_level);
// std::cout << "NK_CAST_EXPR" << std::endl;
// if (n->getExpr() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Expression:" << std::endl;
// n->getExpr()->accept(this);
// }
// if (n->getType() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Type:" << std::endl;
// n->getType()->accept(this);
// }
// _level--;
std::cout << "(";
n->getType()->accept(this);
std::cout << ") ";
n->getExpr()->accept(this);
}
void GenCVisitor::visit(BitNotExprASTNode *n)
{
std::cout << "~";
n->getExpr()->accept(this);
}
void GenCVisitor::visit(LogNotExprASTNode *n)
{
std::cout << "!";
n->getExpr()->accept(this);
}
void GenCVisitor::visit(PredecrementExprASTNode *n)
{
std::cout << "--";
n->getExpr()->accept(this);
}
void GenCVisitor::visit(PreincrementExprASTNode *n)
{
std::cout << "++";
n->getExpr()->accept(this);
}
void GenCVisitor::visit(PostdecrementExprASTNode *n)
{
n->getExpr()->accept(this);
std::cout << "--";
}
void GenCVisitor::visit(PostincrementExprASTNode *n)
{
n->getExpr()->accept(this);
std::cout << "++";
}
void GenCVisitor::visit(AddrExprASTNode *n)
{
std::cout << "&";
n->getExpr()->accept(this);
}
void GenCVisitor::visit(IndirectRefASTNode *n)
{
if (n->getField() == NULL_AST_NODE)
std::cout << "*";
if (n->getExpr() != NULL_AST_NODE)
n->getExpr()->accept(this);
if (n->getField() != NULL_AST_NODE)
{
std::cout << "->";
n->getField()->accept(this);
}
// if (n->getType() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Type:" << std::endl;
// n->getType()->accept(this);
// }
// _level--;
}
void GenCVisitor::visit(NopExprASTNode *n)
{
_level++;
printTab(_level);
std::cout << "NK_NOP_EXPR" << std::endl;
_level--;
}
void GenCVisitor::visit(LShiftExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " << ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(RShiftExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " >> ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(BitIorExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " | ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(BitXorExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " ^ ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(BitAndExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " & ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(LogAndExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " && ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(LogOrExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " || ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(PlusExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " + ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(MinusExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " - ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(MultExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " * ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(TruncDivExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " / ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(TruncModExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " % ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(ArrayRefASTNode *n)
{
// _level++;
// printTab(_level);
// std::cout << "ARRAY_REF" << std::endl;
// if (n->getExpr() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Expression:" << std::endl;
// n->getExpr()->accept(this);
// }
// if (n->getIndex() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Index:" << std::endl;
// n->getIndex()->accept(this);
// }
// if (n->getType() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Element type:" << std::endl;
// n->getType()->accept(this);
// }
// _level--;
if (n->getExpr() != NULL_AST_NODE)
n->getExpr()->accept(this);
std::cout << "[";
if (n->getIndex() != NULL_AST_NODE)
n->getIndex()->accept(this);
std::cout << "]";
}
void GenCVisitor::visit(StructRefASTNode *n)
{
// _level++;
// printTab(_level);
// std::cout << "STRUCT_REF" << std::endl;
// if (n->getName() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Name:" << std::endl;
// n->getName()->accept(this);
// }
// if (n->getMember() != NULL_AST_NODE)
// {
// printTab(_level);
// std::cout << "Member:" << std::endl;
// n->getMember()->accept(this);
// }
// _level--;
if (n->getName() != NULL_AST_NODE)
n->getName()->accept(this);
std::cout << ".";
if (n->getMember() != NULL_AST_NODE)
n->getMember()->accept(this);
}
void GenCVisitor::visit(LtExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " < ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(LeExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " <= ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(GtExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " > ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(GeExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " >= ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(EqExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " == ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(NeExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " != ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(AssignExprASTNode *n)
{
n->getLhs()->accept(this);
std::cout << " = ";
n->getRhs()->accept(this);
}
void GenCVisitor::visit(CondExprASTNode *n)
{
n->getCondition()->accept(this);
std::cout << " ? ";
n->getThenClause()->accept(this);
std::cout << " : ";
n->getElseClause()->accept(this);
}
void GenCVisitor::visit(CallExprASTNode *n)
{
n->getExpr()->accept(this);
std::cout << "(";
_inList++;
n->getArgs()->accept(this);
_inList--;
std::cout << ")";
}
void GenCVisitor::visit(VoidTypeASTNode *n)
{
std::cout << "void";
}
void GenCVisitor::visit(IntegralTypeASTNode *n)
{
if (!n->getIsSigned())
std::cout << "unsigned ";
switch (n->getAlignment())
{
case 1:
std::cout << "char";
break;
case 2:
std::cout << "short";
break;
case 4:
std::cout << "int";
break;
case 8:
std::cout << "long";
break;
default:
std::cout << "int";
break;
}
}
void GenCVisitor::visit(RealTypeASTNode *n)
{
if (n->getIsDouble())
std::cout << "double";
else
std::cout << "float";
}
void GenCVisitor::visit(EnumeralTypeASTNode *n)
{
std::cout << "enum ";
n->getName()->accept(this);
printTab(_level);
std::cout << std::endl << "{" << std::endl;
_level++;
_inList++;
n->getBody()->accept(this);
_inList--;
_level--;
printTab(_level);
std::cout << "}";
}
void GenCVisitor::visit(PointerTypeASTNode *n)
{
// std::cout << "* ";
n->getBaseType()->accept(this);
std::cout << "*";
}
void GenCVisitor::visit(FunctionTypeASTNode *n)
{
// n->getType()->accept(this);
// std::cout << "(*";
// // Name
// std::cout << ")";
std::cout << "(";
_inList++;
n->getPrms()->accept(this);
_inList--;
std::cout << ")";
}
void GenCVisitor::visit(ArrayTypeASTNode *n)
{
// std::cout << "[";
// n->getExpr()->accept(this);
// std::cout << "]" << std::endl;
n->getElementType()->accept(this);
}
void GenCVisitor::visit(StructTypeASTNode *n)
{
std::cout << "struct ";
if (n->getName() != NULL_AST_NODE)
n->getName()->accept(this);
if (n->getBody() != NULL_AST_NODE)
{
std::cout << std::endl;
printTab(_level);
std::cout << "{" << std::endl;
_level++;
n->getBody()->accept(this);
_level--;
printTab(_level);
std::cout << "}";
}
}
void GenCVisitor::visit(UnionTypeASTNode *n)
{
// TODO: Implement
}
void GenCVisitor::visit(NullASTNode *n)
{
// Print nothing
}
static bool isNonSemi(ASTNodeKind n)
{
return n == NK_IF_STMT || n == NK_WHILE_STMT || n == NK_DO_STMT ||
n == NK_FUNCTION_DECL || n == NK_COMPOUND_STMT ||
n == NK_INTEGRAL_TYPE;
}
void GenCVisitor::visit(SequenceASTNode *n)
{
std::vector<ASTNode *> &elements = n->getElements();
if (elements.size() > 0)
{
if (!_inList)
printTab(_level);
elements[0]->accept(this);
if (!_inList)
{
if (!isNonSemi(elements[0]->getKind()))
std::cout << ";" << std::endl;
}
}
for (unsigned i = 1; i < elements.size(); i++)
{
if (elements[i] == NULL_AST_NODE)
continue;
if (!_inList)
printTab(_level);
else
std::cout << ", ";
elements[i]->accept(this);
if (!_inList)
{
if (!isNonSemi(elements[i]->getKind()))
std::cout << ";" << std::endl;
}
}
}
} // namespace cparser
| 21.057416 | 85 | 0.526869 | jkolek |
fa6acb14331e9c56515c39ac495c021bfdd368d6 | 661 | cpp | C++ | queue/circular.cpp | sans712/SDE-Interview-Questions | 44f5bda60b9ed301b93a944e1c333d833c9b054b | [
"MIT"
] | null | null | null | queue/circular.cpp | sans712/SDE-Interview-Questions | 44f5bda60b9ed301b93a944e1c333d833c9b054b | [
"MIT"
] | null | null | null | queue/circular.cpp | sans712/SDE-Interview-Questions | 44f5bda60b9ed301b93a944e1c333d833c9b054b | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
#include<bits/stdc++.h>
class queues{
int *arr;
int f,r,cs,ms;
public:
queues(int ds=5){
arr=new int [ds];
cs=0;
ms=ds;
f=0;
r=ms-1;
}
bool full(){
return cs==ms;
}
bool empty(){
return cs==0;
}
void push(int x){
if(!full()){
r=(r+1)%ms;
arr[r]=x;
cs++;
}
}
void pop(){
if(!empty()){
f=(f+1)%ms;
cs--;
}
}
int front(){
return arr[f];
}
~queues(){
if(arr!=nullptr){
delete [] arr;
arr=nullptr;
}
}
};
int main(){
queues q;
for(int i=1;i<=5;i++){
q.push(i);
}
q.pop();
q.pop();
q.push(11);
while(!q.empty()){
cout<<q.front()<<" ";
q.pop();
}
} | 11.596491 | 23 | 0.497731 | sans712 |
fa6bc6d07b389ee5b05c8ce9109b5bbbb258565e | 969 | cpp | C++ | codes/UVA/10001-19999/uva11014.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/UVA/10001-19999/uva11014.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/UVA/10001-19999/uva11014.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 200000;
int np, pri[maxn+5], vis[maxn+5];
void priTable (int n) {
np = 0;
memset(vis, 0, sizeof(vis));
for (int i = 2; i <= n; i++) {
if (vis[i])
continue;
pri[np++] = i;
for (int j = 2*i; j <= n; j += i)
vis[j] = 1;
}
}
ll N;
inline ll count (ll n) {
return n * n * n - 1;
}
inline ll fcount (ll n) {
int ans = 0;
for (int i = 0; i < np && pri[i] <= n; i++) {
if (n < maxn && !vis[n]) {
ans++;
break;
}
if (n%pri[i] == 0) {
ans++;
n /= pri[i];
if (n%pri[i] == 0)
return 0;
}
}
return ans&1 ? -1 : 1;
}
ll solve () {
ll ans = count(N+1);
for (ll i = 2; i <= N; i++) {
ll t = fcount(i);
ans += count(N/(2*i) * 2 + 1) * t;
}
return ans;
}
int main () {
int cas = 1;
priTable(maxn);
while (scanf("%lld", &N) == 1 && N) {
printf("Crystal %d: %lld\n", cas++, solve());
}
return 0;
}
| 14.907692 | 47 | 0.4871 | JeraKrs |
fa6e6425724669d527e75115990d1f7fe9b20ced | 73 | hpp | C++ | benchmarks/benchmark.hpp | stdml/stdnn-ops | 0e6132bd65319e318f918094e482482698482e9e | [
"MIT"
] | 3 | 2018-10-23T18:46:39.000Z | 2019-06-24T00:46:10.000Z | benchmarks/benchmark.hpp | stdml/stdnn-ops | 0e6132bd65319e318f918094e482482698482e9e | [
"MIT"
] | 27 | 2018-11-10T14:19:16.000Z | 2020-03-08T23:33:01.000Z | benchmarks/benchmark.hpp | stdml/stdnn-ops | 0e6132bd65319e318f918094e482482698482e9e | [
"MIT"
] | 1 | 2018-11-05T06:17:12.000Z | 2018-11-05T06:17:12.000Z | #pragma once
#include <benchmark/benchmark.h>
#include "build_info.hpp"
| 14.6 | 32 | 0.767123 | stdml |
fa75e9117e534ec6e8c6b5dae4c83b9277ed8ae6 | 338 | cpp | C++ | Codeforces Online Judge Solve/68A - Irrational problem.cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | Codeforces Online Judge Solve/68A - Irrational problem.cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | Codeforces Online Judge Solve/68A - Irrational problem.cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | // Remon Hasan
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int p[4], a, b;
cin >> p[0] >> p[1] >> p[2] >> p[3] >> a >> b;
int m = *min_element(p, p + 4);
if (a < m)
{
cout << min(b, m - 1) - a + 1 << endl;
}
else
{
cout << 0 << endl;
}
return 0;
}
| 14.695652 | 50 | 0.423077 | Remonhasan |
fa7877aae48974b80d2d09d051de5f5d06ce8bc7 | 1,761 | cpp | C++ | src/astro/basic_astro/bodyShapeModel.cpp | kimonito98/tudat | c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092 | [
"BSD-3-Clause"
] | null | null | null | src/astro/basic_astro/bodyShapeModel.cpp | kimonito98/tudat | c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092 | [
"BSD-3-Clause"
] | null | null | null | src/astro/basic_astro/bodyShapeModel.cpp | kimonito98/tudat | c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*
* References
* Montebruck O, Gill E. Satellite Orbits, Springer, 2000.
*
*/
#include "tudat/astro/basic_astro/bodyShapeModel.h"
namespace tudat
{
namespace basic_astrodynamics
{
//! Function to calculate the altitude of a point over a central body
//! from positions of both the point and the body (in any frame)
double getAltitudeFromNonBodyFixedPosition(
const std::shared_ptr< BodyShapeModel > bodyShapeModel, const Eigen::Vector3d& position,
const Eigen::Vector3d& bodyPosition, const Eigen::Quaterniond& toBodyFixedFrame )
{
return bodyShapeModel->getAltitude( toBodyFixedFrame * ( position - bodyPosition ) );
}
//! Function to calculate the altitude of a point over a central body
//! from positions of both the point and the body (in any frame)
double getAltitudeFromNonBodyFixedPositionFunctions(
const std::shared_ptr< BodyShapeModel > bodyShapeModel, const Eigen::Vector3d& position,
const std::function< Eigen::Vector3d( ) > bodyPositionFunction,
const std::function< Eigen::Quaterniond( ) > toBodyFixedFrameFunction )
{
return getAltitudeFromNonBodyFixedPosition( bodyShapeModel, position, bodyPositionFunction( ),
toBodyFixedFrameFunction( ) );
}
} // namespace basic_astrodynamics
} // namespace tudat
| 39.133333 | 99 | 0.720045 | kimonito98 |
fa7ba8a28c1e8de79e5ff218c649b797b3e8b818 | 4,748 | cpp | C++ | src/zenoh_flow_local_planner.cpp | autocore-ai/zenoh_flow_autoware | 8b5320fe95cfeb3d0573d7f520a6bab925ff6208 | [
"Apache-2.0"
] | 1 | 2022-03-31T08:53:16.000Z | 2022-03-31T08:53:16.000Z | src/zenoh_flow_local_planner.cpp | autocore-ai/zenoh_flow_autoware | 8b5320fe95cfeb3d0573d7f520a6bab925ff6208 | [
"Apache-2.0"
] | 2 | 2022-01-03T20:36:57.000Z | 2022-01-19T03:55:51.000Z | src/zenoh_flow_local_planner.cpp | autocore-ai/zenoh_flow_autoware | 8b5320fe95cfeb3d0573d7f520a6bab925ff6208 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The AutoCore.AI.
//
// 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 <zenoh_flow_local_planner/zenoh_flow_local_planner.hpp>
#include <zenoh_flow_msg_convert/zenoh_flow_msg_convert.hpp>
#include <iostream>
namespace zenoh_flow
{
namespace autoware_auto
{
namespace ffi
{
NativeNode_local_planner::NativeNode_local_planner(const NativeConfig &cfg)
{
if (!rclcpp::ok())
{
rclcpp::init(0, nullptr);
}
rclcpp::NodeOptions options;
std::vector<rclcpp::Parameter> paramters = std::vector<rclcpp::Parameter>();
paramters.push_back(rclcpp::Parameter("enable_object_collision_estimator", cfg.enable_object_collision_estimator));
paramters.push_back(rclcpp::Parameter("heading_weight", cfg.heading_weight));
paramters.push_back(rclcpp::Parameter("goal_distance_thresh", cfg.goal_distance_thresh));
paramters.push_back(rclcpp::Parameter("stop_velocity_thresh", cfg.stop_velocity_thresh));
paramters.push_back(rclcpp::Parameter("subroute_goal_offset_lane2parking", cfg.subroute_goal_offset_lane2parking));
paramters.push_back(rclcpp::Parameter("subroute_goal_offset_parking2lane", cfg.subroute_goal_offset_parking2lane));
paramters.push_back(rclcpp::Parameter("vehicle.cg_to_front_m", cfg.vehicle.cg_to_front_m));
paramters.push_back(rclcpp::Parameter("vehicle.cg_to_rear_m", cfg.vehicle.cg_to_rear_m));
paramters.push_back(rclcpp::Parameter("vehicle.front_overhang_m", cfg.vehicle.front_overhang_m));
paramters.push_back(rclcpp::Parameter("vehicle.rear_overhang_m", cfg.vehicle.rear_overhang_m));
options.parameter_overrides(paramters);
std::cout << "BehaviorPlannerNode" << std::endl;
ptr = std::make_shared<autoware::behavior_planner_nodes::BehaviorPlannerNode>(options, autocore::NodeType::ZenohFlow);
}
void NativeNode_local_planner::SetRoute(const AutowareAutoMsgsHadmapRoute &msg)
{
ptr->SetRoute(Convert(msg));
}
void NativeNode_local_planner::SetKinematicState(const AutowareAutoMsgsVehicleKinematicState &msg)
{
if (rclcpp::ok())
{
rclcpp::spin_some(ptr);
}
ptr->SetKinematicState(Convert(msg));
}
void NativeNode_local_planner::SetStateReport(const AutowareAutoMsgsVehicleStateReport &msg)
{
ptr->SetStateReport(Convert(msg));
}
AutowareAutoMsgsTrajectory NativeNode_local_planner::GetTrajectory() { return Convert(ptr->GetTrajectory()); }
AutowareAutoMsgsVehicleStateCommand NativeNode_local_planner::GetStateCmd()
{
return Convert(ptr->GetStateCmd());
}
std::unique_ptr<NativeNode_local_planner> init_local_planner(const NativeConfig &cfg)
{
return std::make_unique<NativeNode_local_planner>(cfg);
}
AutowareAutoMsgsTrajectory get_trajectory(std::unique_ptr<NativeNode_local_planner> &node)
{
return node->GetTrajectory();
}
AutowareAutoMsgsVehicleStateCommand get_state_cmd(std::unique_ptr<NativeNode_local_planner> &node)
{
return node->GetStateCmd();
}
void set_route(std::unique_ptr<NativeNode_local_planner> &node, const AutowareAutoMsgsHadmapRoute &msg)
{
node->SetRoute(msg);
}
void set_kinematic_state(
std::unique_ptr<NativeNode_local_planner> &node, const AutowareAutoMsgsVehicleKinematicState &msg)
{
node->SetKinematicState(msg);
}
void set_state_report(
std::unique_ptr<NativeNode_local_planner> &node, const AutowareAutoMsgsVehicleStateReport &msg)
{
node->SetStateReport(msg);
}
}
}
}
| 48.948454 | 134 | 0.639427 | autocore-ai |
fa7d3d4044a2f033f206ade8d5558b3ed03c9040 | 2,098 | cpp | C++ | classnote/Midexam/DB_Conversion.cpp | Alex-Lin5/cpp_practice | c249362d6bbe932dc1eb4a4b8c51728d58db2aa7 | [
"MIT"
] | null | null | null | classnote/Midexam/DB_Conversion.cpp | Alex-Lin5/cpp_practice | c249362d6bbe932dc1eb4a4b8c51728d58db2aa7 | [
"MIT"
] | null | null | null | classnote/Midexam/DB_Conversion.cpp | Alex-Lin5/cpp_practice | c249362d6bbe932dc1eb4a4b8c51728d58db2aa7 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <list>
#include <map>
using namespace std;
//Implement the following function
void DB1_to_DB2(list<vector<list<int>*>* >& DB1, vector<list<list<int*> >*>* pDB2);
template <typename T> ostream& operator<<(ostream& str, const vector<T>& V);
template <typename T> ostream& operator<<(ostream& str, const vector<T *>& V);
template <typename T> ostream& operator<<(ostream& str, const list<T>& L);
template <typename T> ostream& operator<<(ostream& str, const list<T*>& L);
int main() {
list<vector<list<int>*>* > DB1{ new vector<list<int>*> { new list<int> {1,2,3}, new list<int>{4,5,6,7}, new list<int>{8, 9}},
new vector<list<int>*> { new list<int> {11,12,13}, new list<int>{14,15,16,17}, new list<int>{18, 19}},
new vector<list<int>*> { new list<int> {21,22,23}, new list<int>{24,25,26,27}, new list<int>{28, 29}}
};
cout << DB1 << endl;
vector<list<list<int*> >*>* pDB2{ new vector<list<list<int*> >*> {} };
DB1_to_DB2(DB1, pDB2);
cout << *pDB2 << endl;
return 0;
}
void DB1_to_DB2(list<vector<list<int>*>* >& DB1, vector<list<list<int*> >*>* pDB2) {
for (auto& i : *pDB2) {
for (auto& j : *i) {
for (auto& k : j) {
delete k;
}
}
delete i;
}
pDB2->clear();
for (auto& i : DB1) {
list<list<int*>>* p1{ new list<list<int*>> };
for (auto& j : *i) {
list<int*> L1;
for (auto& k : *j) {
L1.push_back(new int{ k });
}
p1->push_back(L1);
}
pDB2->push_back(p1);
}
}
template <typename T> ostream& operator<<(ostream& str, const vector<T>& V) {
str << "[ ";
for (auto& i : V) str << i << " ";
str << "]";
return str;
}
template <typename T> ostream& operator<<(ostream& str, const vector<T *>& V) {
str << "[ ";
for (auto& i : V) str << *i << " ";
str << "]";
return str;
}
template <typename T> ostream& operator<<(ostream& str, const list<T>& L) {
str << "< ";
for (auto& i : L) str << i << " ";
str << ">";
return str;
}
template <typename T> ostream& operator<<(ostream& str, const list<T*>& L) {
str << "< ";
for (auto& i : L) str << *i << " ";
str << ">";
return str;
} | 25.901235 | 126 | 0.577216 | Alex-Lin5 |
fa7dba3908b35bf14a87cfe638101b39a1dd2dce | 6,743 | cpp | C++ | src/make_detect.cpp | cschreib/qdeblend | dceee75f3ff475995dbbb8660a6665ece205494f | [
"MIT"
] | null | null | null | src/make_detect.cpp | cschreib/qdeblend | dceee75f3ff475995dbbb8660a6665ece205494f | [
"MIT"
] | null | null | null | src/make_detect.cpp | cschreib/qdeblend | dceee75f3ff475995dbbb8660a6665ece205494f | [
"MIT"
] | null | null | null | #include <vif.hpp>
#include <vif/astro/ds9.hpp>
using namespace vif;
using namespace vif::astro;
int vif_main(int argc, char* argv[]) {
vec1s files = {"acs-f435w", "acs-f606w", "acs-f775w", "acs-f814w", "acs-f850lp",
"wfc3-f105w", "wfc3-f125w", "wfc3-f140w", "wfc3-f160w"};
files += ".fits";
std::string flux_image = "wfc3-f160w.fits";
double deblend_threshold = 0.4;
double detect_threshold = 1.0;
double conv_fwhm = 0.2;
double min_snr = 10.0;
uint_t min_area = 10;
read_args(argc, argv, arg_list(files, flux_image,
deblend_threshold, detect_threshold, conv_fwhm, min_area, min_snr
));
vec3f imgs;
vec1f rms;
double stack_rms = 0;
vec2f stack;
vec2f wstack;
fits::header ghdr;
double aspix = 0.06;
for (std::string& f : files) {
if (!file::exists(f)) continue;
vec2d img;
fits::header hdr;
fits::read(f, img, hdr);
astro::wcs w(hdr);
if (ghdr.empty()) ghdr = hdr;
// From DS9 region files
std::string base = file::remove_extension(f);
std::string bad_file = base+"-bad.reg";
if (!file::exists(bad_file)) {
bad_file = base+"_bad.reg";
}
if (!file::exists(bad_file)) {
bad_file = "";
}
if (!bad_file.empty()) {
vec2b bad_mask(img.dims);
ds9::mask_regions(bad_file, w, bad_mask);
img[where(bad_mask)] = dnan;
}
if (fraction_of(is_finite(img) || abs(img) > 0) < 0.6) continue;
rms.push_back(1.48*mad(img));
vec2d wei = replicate(1.0/sqr(rms.back()), img.dims);
vec1u idb = where(!is_finite(img));
img[idb] = 0; wei[idb] = 0;
if (stack.empty()) {
stack = img*wei;
wstack = wei;
} else {
stack += img*wei;
wstack += wei;
}
stack_rms += sqr(rms.back()/sqr(rms.back()));
append<0>(imgs, reform(img/rms.back(), 1, img.dims));
}
astro::wcs gw(ghdr);
double tw = total(1/sqr(rms));
stack_rms = sqrt(stack_rms)/tw;
stack /= wstack;
fits::write("det_stack.fits", stack, ghdr);
append<0>(imgs, reform(stack/stack_rms, 1, stack.dims));
// Build detection image
vec2f det = partial_max(0, imgs);
double conv = conv_fwhm/aspix/2.335; {
vec1u idb = where(!is_finite(det));
det[idb] = 0;
uint_t hpix = 5*conv;
vec2d kernel = gaussian_profile({{2*hpix+1, 2*hpix+1}}, conv, hpix, hpix);
det = convolve2d(det, kernel);
det[idb] = fnan;
}
fits::write("det_snr.fits", det, ghdr);
// Perform segmentation
segment_deblend_params sdp;
sdp.detect_threshold = detect_threshold + median(det);
sdp.deblend_threshold = deblend_threshold/aspix;
sdp.min_area = min_area;
segment_deblend_output segments;
vec2u seg = segment_deblend(det, segments, sdp);
// Read fluxes on image
vec2d himg;
fits::read(flux_image, himg);
vec1u idbg = where(seg == 0);
himg -= median(himg[idbg]);
double hrms = 1.48*mad(himg[idbg]);
vec1f hflx(segments.id.size());
vec1f hflx_err(segments.id.size());
foreach_segment(seg, segments.origin, [&](uint_t s, vec1u ids) {
hflx[s] = total(himg[ids]);
hflx_err[s] = sqrt(ids.size())*hrms;
});
// Remove too low S/N objects.
vec1u idls = where(hflx/hflx_err < min_snr);
foreach_segment(seg, segments.origin[idls], [&](uint_t s, vec1u ids) {
seg[ids] = 0;
});
inplace_remove(segments.id, idls);
inplace_remove(segments.area, idls);
inplace_remove(segments.px, idls);
inplace_remove(segments.py, idls);
inplace_remove(hflx, idls);
inplace_remove(hflx_err, idls);
// Merge segments (if any).
std::string manual_file = "merged_segments.reg";
if (file::exists(manual_file)) {
vec<1,ds9::region> reg;
ds9::read_regions_physical(manual_file, gw, reg);
for (uint_t i : range(reg)) {
vec2b mask(seg.dims);
ds9::mask_region(reg[i], mask);
vec1u idm = where(mask);
vec1u idu = unique_values(seg[idm]);
idu = idu[where(idu != 0)];
if (idu.size() > 1) {
print("merged ", idu.size(), " segments");
for (uint_t u : range(1, idu.size())) {
vec1u ids = where(seg == idu[u]);
seg[ids] = idu[0];
idu[u] = where_first(segments.id == idu[u]);
}
uint_t im = where_first(segments.id == idu[0]);
idu[0] = im;
segments.px[im] = total(segments.px[idu]*segments.area[idu])/total(segments.area[idu]);
segments.py[im] = total(segments.py[idu]*segments.area[idu])/total(segments.area[idu]);
segments.area[im] = total(segments.area[idu]);
hflx[im] = total(hflx[idu]);
hflx_err[im] = sqrt(total(sqr(hflx_err[idu])));
idu = idu[1-_];
inplace_remove(segments.id, idu);
inplace_remove(segments.px, idu);
inplace_remove(segments.py, idu);
inplace_remove(segments.area, idu);
inplace_remove(hflx, idu);
inplace_remove(hflx_err, idu);
}
}
}
// Add manual detections (if any).
manual_file = "det_manual.reg";
if (file::exists(manual_file)) {
vec<1,ds9::region> reg;
ds9::read_regions_physical(manual_file, gw, reg);
vec1s sid(reg.size());
for (uint_t i : range(reg)) sid[i] = reg[i].text;
vec1s uid = unique_values(sid);
for (std::string s : uid) {
vec1u idl = where(sid == s);
vec2b mask(seg.dims);
for (uint_t i : idl) {
ds9::mask_region(reg[i], mask);
}
vec1u ids = where(mask);
uint_t seg_id = max(segments.id)+1;
seg[ids] = seg_id;
segments.id.push_back(seg_id);
segments.px.push_back(reg[idl[0]].params[0]);
segments.py.push_back(reg[idl[0]].params[1]);
segments.area.push_back(ids.size());
hflx.push_back(total(himg[ids]));
hflx_err.push_back(sqrt(ids.size())*hrms);
}
}
fits::write("det_seg.fits", seg, ghdr);
vec1d ra, dec;
astro::xy2ad(gw, segments.px+1, segments.py+1, ra, dec);
fits::write_table("det_cat.fits",
"id", segments.id, "area", segments.area, "x", segments.px, "y", segments.py,
"ra", ra, "dec", dec, "flux", hflx, "flux_err", hflx_err
);
return 0;
}
| 30.102679 | 103 | 0.547976 | cschreib |
fa82b6e764767ec297ffd9060a087f242751acf1 | 8,957 | cpp | C++ | src/XspfDateTime.cpp | ezdev128/libxspf | ba71431e24293510c44d6581e2c05b901a372880 | [
"BSD-3-Clause"
] | null | null | null | src/XspfDateTime.cpp | ezdev128/libxspf | ba71431e24293510c44d6581e2c05b901a372880 | [
"BSD-3-Clause"
] | null | null | null | src/XspfDateTime.cpp | ezdev128/libxspf | ba71431e24293510c44d6581e2c05b901a372880 | [
"BSD-3-Clause"
] | null | null | null | /*
* libxspf - XSPF playlist handling library
*
* Copyright (C) 2006-2008, Sebastian Pipping / Xiph.Org Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of the Xiph.Org Foundation nor the names of
* its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Sebastian Pipping, [email protected]
*/
/**
* @file XspfDateTime.cpp
* Implementation of XspfDateTime.
*/
#include <xspf/XspfDateTime.h>
#include <cstring>
#if defined(sun) || defined(__sun)
# include <strings.h> // for strncmp()
#endif
namespace Xspf {
/// @cond DOXYGEN_NON_API
/**
* D object for XspfDateTime.
*/
class XspfDateTimePrivate {
friend class XspfDateTime;
int year; ///< Year [-9999..+9999] but not zero
int month; ///< Month [1..12]
int day; ///< Day [1..31]
int hour; ///< Hour [0..23]
int minutes; ///< Minutes [0..59]
int seconds; ///< Seconds [0..59]
int distHours; ///< Time shift hours [-14..+14]
int distMinutes; ///< Time shift minutes [-59..+59]
/**
* Creates a new D object.
*
* @param year Year [-9999..+9999] but not zero
* @param month Month [1..12]
* @param day Day [1..31]
* @param hour Hour [0..23]
* @param minutes Minutes [0..59]
* @param seconds Seconds [0..59]
* @param distHours Time shift hours [-14..+14]
* @param distMinutes Time shift minutes [-59..+59]
*/
XspfDateTimePrivate(int year, int month, int day, int hour,
int minutes, int seconds, int distHours, int distMinutes)
: year(year),
month(month),
day(day),
hour(hour),
minutes(minutes),
seconds(seconds),
distHours(distHours),
distMinutes(distMinutes) {
}
/**
* Destroys this D object.
*/
~XspfDateTimePrivate() {
}
};
/// @endcond
XspfDateTime::XspfDateTime(int year, int month, int day,
int hour, int minutes, int seconds, int distHours,
int distMinutes)
: d(new XspfDateTimePrivate(year, month, day, hour,
minutes, seconds, distHours, distMinutes)) {
}
XspfDateTime::XspfDateTime()
: d(new XspfDateTimePrivate(0, 0, 0, -1, -1, -1, 0, 0)) {
}
XspfDateTime::XspfDateTime(XspfDateTime const & source)
: d(new XspfDateTimePrivate(*(source.d))) {
}
XspfDateTime & XspfDateTime::operator=(XspfDateTime const & source) {
if (this != &source) {
*(this->d) = *(source.d);
}
return *this;
}
XspfDateTime::~XspfDateTime() {
delete this->d;
}
XspfDateTime * XspfDateTime::clone() const {
return new XspfDateTime(this->d->year, this->d->month, this->d->day,
this->d->hour, this->d->minutes, this->d->seconds, this->d->distHours,
this->d->distMinutes);
}
int XspfDateTime::getYear() const {
return this->d->year;
}
int XspfDateTime::getMonth() const {
return this->d->month;
}
int XspfDateTime::getDay() const {
return this->d->day;
}
int XspfDateTime::getHour() const {
return this->d->hour;
}
int XspfDateTime::getMinutes() const {
return this->d->minutes;
}
int XspfDateTime::getSeconds() const {
return this->d->seconds;
}
int XspfDateTime::getDistHours() const {
return this->d->distHours;
}
int XspfDateTime::getDistMinutes() const {
return this->d->distMinutes;
}
void XspfDateTime::setYear(int year) {
this->d->year = year;
}
void XspfDateTime::setMonth(int month) {
this->d->month = month;
}
void XspfDateTime::setDay(int day) {
this->d->day = day;
}
void XspfDateTime::setHour(int hour) {
this->d->hour = hour;
}
void XspfDateTime::setMinutes(int minutes) {
this->d->minutes = minutes;
}
void XspfDateTime::setSeconds(int seconds) {
this->d->seconds = seconds;
}
void XspfDateTime::setDistHours(int distHours) {
this->d->distHours = distHours;
}
void XspfDateTime::setDistMinutes(int distMinutes) {
this->d->distMinutes = distMinutes;
}
namespace {
/**
* Calls atoi() on a limited number of characters.
*
* @param text Text
* @param len Number of characters to read
* @return Result of atoi()
* @since 1.0.0rc1
*/
int PORT_ANTOI(XML_Char const * text, int len) {
XML_Char * final = new XML_Char[len + 1];
::PORT_STRNCPY(final, text, len);
final[len] = _PT('\0');
int const res = ::PORT_ATOI(final);
delete [] final;
return res;
}
} // anon namespace
/*static*/ bool
XspfDateTime::extractDateTime(XML_Char const * text,
XspfDateTime * output) {
// http://www.w3.org/TR/xmlschema-2/#dateTime-lexical-representation
// '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?
// '-'?
bool const leadingMinus = (*text == _PT('-'));
if (leadingMinus) {
text++;
}
// yyyy
if ((::PORT_STRNCMP(text, _PT("0001"), 4) < 0) || (::PORT_STRNCMP(_PT("9999"), text, 4) < 0)) {
return false;
}
int const year = PORT_ANTOI(text, 4);
output->setYear(year);
text += 4;
// '-' mm
if ((::PORT_STRNCMP(text, _PT("-01"), 3) < 0) || (::PORT_STRNCMP(_PT("-12"), text, 3) < 0)) {
return false;
}
int const month = PORT_ANTOI(text + 1, 2);
output->setMonth(month);
text += 3;
// '-' dd
if ((::PORT_STRNCMP(text, _PT("-01"), 3) < 0) || (::PORT_STRNCMP(_PT("-31"), text, 3) < 0)) {
return false;
}
int const day = PORT_ANTOI(text + 1, 2);
output->setDay(day);
text += 3;
// Month specific day check
switch (month) {
case 2:
switch (day) {
case 31:
case 30:
return false;
case 29:
if (((year % 400) != 0) && (((year % 4) != 0)
|| ((year % 100) == 0))) {
// Not a leap year
return false;
}
break;
case 28:
break;
}
break;
case 4:
case 6:
case 9:
case 11:
if (day > 30) {
return false;
}
break;
}
// 'T' hh
if ((::PORT_STRNCMP(text, _PT("T00"), 3) < 0) || (::PORT_STRNCMP(_PT("T23"), text, 3) < 0)) {
return false;
}
output->setHour(PORT_ANTOI(text + 1, 2));
text += 3;
// ':' mm
if ((::PORT_STRNCMP(text, _PT(":00"), 3) < 0) || (::PORT_STRNCMP(_PT(":59"), text, 3) < 0)) {
return false;
}
output->setMinutes(PORT_ANTOI(text + 1, 2));
text += 3;
// ':' ss
if ((::PORT_STRNCMP(text, _PT(":00"), 2) < 0) || (::PORT_STRNCMP(_PT(":59"), text, 2) < 0)) {
return false;
}
output->setSeconds(PORT_ANTOI(text + 1, 2));
text += 3;
// ('.' s+)?
if (*text == _PT('.')) {
text++;
int counter = 0;
while ((*text >= _PT('0')) && (*text <= _PT('9'))) {
text++;
counter++;
}
if (counter == 0) {
return false;
} else {
// The fractional second string, if present, must not end in '0'
if (*(text - 1) == _PT('0')) {
return false;
}
}
}
// (zzzzzz)? := (('+' | '-') hh ':' mm) | 'Z'
XML_Char const * const timeZoneStart = text;
switch (*text) {
case _PT('+'):
case _PT('-'):
{
text++;
if ((::PORT_STRNCMP(text, _PT("00"), 2) < 0) || (::PORT_STRNCMP(_PT("14"), text, 2) < 0)) {
return false;
}
int const distHours = PORT_ANTOI(text, 2);
output->setDistHours(distHours);
text += 2;
if ((::PORT_STRNCMP(text, _PT(":00"), 3) < 0) || (::PORT_STRNCMP(_PT(":59"), text, 3) < 0)) {
return false;
}
int const distMinutes = PORT_ANTOI(text + 1, 2);
output->setDistMinutes(distMinutes);
if ((distHours == 14) && (distMinutes != 0)) {
return false;
}
text += 3;
if (*text != _PT('\0')) {
return false;
}
if (*timeZoneStart == _PT('-')) {
output->setDistHours(-distHours);
output->setDistMinutes(-distMinutes);
}
}
break;
case _PT('Z'):
text++;
if (*text != _PT('\0')) {
return false;
}
// NO BREAK
case _PT('\0'):
output->setDistHours(0);
output->setDistMinutes(0);
break;
default:
return false;
}
return true;
}
} // namespace Xspf
| 21.275534 | 96 | 0.620744 | ezdev128 |
fa8625618391b436b5d3793376c4526443b27842 | 3,821 | cpp | C++ | scripts/da_shotgun.cpp | mpforums/RenSharp | 5b3fb8bff2a1772a82a4148bcf3e1265a11aa097 | [
"Apache-2.0"
] | 1 | 2021-10-04T02:34:33.000Z | 2021-10-04T02:34:33.000Z | scripts/da_shotgun.cpp | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 9 | 2019-07-03T19:19:59.000Z | 2020-03-02T22:00:21.000Z | scripts/da_shotgun.cpp | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 2 | 2019-08-14T08:37:36.000Z | 2020-09-29T06:44:26.000Z | /* Renegade Scripts.dll
Dragonade Shotgun Wars Game Mode
Copyright 2017 Whitedragon, Tiberian Technologies
This file is part of the Renegade scripts.dll
The Renegade scripts.dll is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version. See the file COPYING for more details.
In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence.
Only the source code to the module(s) containing the licenced code has to be released.
*/
#include "general.h"
#include "scripts.h"
#include "engine.h"
#include "engine_DA.h"
#include "da.h"
#include "da_shotgun.h"
void DAShotgunGameModeClass::Init() {
Register_Event(DAEvent::ADDWEAPONREQUEST,INT_MAX);
Register_Object_Event(DAObjectEvent::CREATED,DAObjectEvent::POWERUP | DAObjectEvent::BUILDING | DAObjectEvent::ARMED,INT_MAX);
WeaponDefinitionClass *Shotgun = (WeaponDefinitionClass*)Find_Named_Definition("Weapon_Shotgun_Player");
WeaponDefinitionClass *Repair = (WeaponDefinitionClass*)Find_Named_Definition("Weapon_RepairGun_Player");
int ShotgunID = Shotgun->Get_ID();
Shotgun->MaxInventoryRounds = -1;
int RepairID = Repair->Get_ID();
ArmorType LightArmor = ArmorWarheadManager::Get_Armor_Type("CNCVehicleLight");
for (SoldierGameObjDef *Def = (SoldierGameObjDef*)DefinitionMgrClass::Get_First(CID_Soldier);Def;Def = (SoldierGameObjDef*)DefinitionMgrClass::Get_Next(Def,CID_Soldier)) {
Def->WeaponDefID = ShotgunID;
Def->SecondaryWeaponDefID = RepairID;
Def->WeaponRounds = -1;
}
for (VehicleGameObjDef *Def = (VehicleGameObjDef*)DefinitionMgrClass::Get_First(CID_Vehicle); Def; Def = (VehicleGameObjDef*)DefinitionMgrClass::Get_Next(Def, CID_Vehicle)) {
if (Def->Get_Type() != VehicleType::VEHICLE_TYPE_TURRET) {
Def->WeaponDefID = ShotgunID;
Def->WeaponRounds = -1;
}
if (Def->DefenseObjectDef.ShieldType != ArmorType(1)) {
Def->DefenseObjectDef.ShieldType = LightArmor;
Def->DefenseObjectDef.Skin = LightArmor;
}
}
}
bool DAShotgunGameModeClass::Add_Weapon_Request_Event(cPlayer *Player,const WeaponDefinitionClass *Weapon) {
if (_stricmp(Weapon->Get_Name(),"Weapon_Shotgun_Player") && _stricmp(Weapon->Get_Name(), "Weapon_RepairGun_Player")) {
return false;
}
return true;
}
void DAShotgunGameModeClass::Object_Created_Event(GameObject *obj) {
if (BuildingGameObj *Building = obj->As_BuildingGameObj()) {
Building->Get_Defense_Object()->Set_Skin(ArmorWarheadManager::Get_Armor_Type("CNCVehicleMedium"));
Building->Get_Defense_Object()->Set_Shield_Type(ArmorWarheadManager::Get_Armor_Type("CNCVehicleMedium"));
const_cast<BuildingGameObjDef&>(Building->Get_Definition()).MCTSkin = ArmorWarheadManager::Get_Armor_Type("CNCVehicleLight");
}
else if (VehicleGameObj *Vehicle = obj->As_VehicleGameObj()) {
if (!_stricmp(Vehicle->Get_Weapon()->Get_Name(),"Weapon_Shotgun_Player")) {
Update_Network_Object(Vehicle);
Set_Position_Clip_Bullets(Vehicle,1,-1);
}
if (Vehicle->Get_Defense_Object()->Get_Shield_Type() != ArmorType(1)) {
ArmorType LightArmor = ArmorWarheadManager::Get_Armor_Type("CNCVehicleLight");
Vehicle->Get_Defense_Object()->Set_Shield_Type(LightArmor);
Vehicle->Get_Defense_Object()->Set_Skin(LightArmor);
}
}
else if (SoldierGameObj *Soldier = obj->As_SoldierGameObj()) {
if (Soldier->Get_Player()) {
Update_Network_Object(Soldier->Get_Player());
}
Update_Network_Object(Soldier);
Set_Position_Clip_Bullets(Soldier,1,-1);
}
else if (((PowerUpGameObj*)obj)->Get_Definition().GrantWeapon) {
obj->Set_Delete_Pending();
}
}
Register_Game_Mode(DAShotgunGameModeClass,"Shotgun","Shotgun Wars",0); | 44.430233 | 175 | 0.772311 | mpforums |
fa8cab7d2db90b6c1d432127901d174625e5eb3e | 362 | hh | C++ | fields/versionchecker.hh | 45G/libsocks6msg | 73b778bfe8efb2c311520617debdfbadf10b6d88 | [
"MIT"
] | 2 | 2020-08-18T11:20:21.000Z | 2022-03-08T23:49:02.000Z | fields/versionchecker.hh | 45G/libsocks6msg | 73b778bfe8efb2c311520617debdfbadf10b6d88 | [
"MIT"
] | null | null | null | fields/versionchecker.hh | 45G/libsocks6msg | 73b778bfe8efb2c311520617debdfbadf10b6d88 | [
"MIT"
] | null | null | null | #ifndef SOCKS6MSG_VERSIONCHECKER_HH
#define SOCKS6MSG_VERSIONCHECKER_HH
#include "bytebuffer.hh"
namespace S6M
{
template <uint8_t VER>
struct VersionChecker
{
VersionChecker() {}
VersionChecker(ByteBuffer *bb)
{
uint8_t *ver = bb->peek<uint8_t>();
if (*ver != VER)
throw BadVersionException(*ver);
}
};
}
#endif // SOCKS6MSG_VERSIONCHECKER_HH
| 14.48 | 37 | 0.732044 | 45G |
fa90467c310331ed5de2fbe188d6fa0e46e86225 | 9,392 | hh | C++ | wersja szablonowa/include/macierz.hh | KPO-2020-2021/zad3-AdamStypczyc | 68c9b63d1b9b0176536ae46cc6863127d608433c | [
"Unlicense"
] | null | null | null | wersja szablonowa/include/macierz.hh | KPO-2020-2021/zad3-AdamStypczyc | 68c9b63d1b9b0176536ae46cc6863127d608433c | [
"Unlicense"
] | null | null | null | wersja szablonowa/include/macierz.hh | KPO-2020-2021/zad3-AdamStypczyc | 68c9b63d1b9b0176536ae46cc6863127d608433c | [
"Unlicense"
] | null | null | null | #ifndef MACIERZ_HH
#define MACIERZ_HH
#include <iostream>
#include <cstdlib>
#include <cmath>
#include "wektor.hh"
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
class Macierz
{
private:
Templ_Typ value[Templ_Rozmiar][Templ_Rozmiar]; // Wartosci macierzy
double kat_stopnie;
double kat_radian;
double kat_stopnieX;
double kat_radianX;
double kat_stopnieY;
double kat_radianY;
double kat_stopnieZ;
double kat_radianZ;
public:
Macierz(Templ_Typ tmp[Templ_Rozmiar][Templ_Rozmiar]); // Konstruktor klasy
Macierz(); // Konstruktor klasy
// Wektor operator*(Wektor tmp); // Operator mnożenia przez wektor
Macierz operator+(Macierz tmp);
Macierz operator-(Macierz tmp);
Macierz operator*(Macierz tmp);
Templ_Typ &operator()(unsigned int row, unsigned int column);
const Templ_Typ &operator()(unsigned int row, unsigned int column) const;
void StopienNaRadian();
void StopienNaRadianX();
void StopienNaRadianY();
void StopienNaRadianZ();
void Oblicz_Macierz_Obrotu();
void Oblicz_Macierz_ObrotuX();
void Oblicz_Macierz_ObrotuY();
void Oblicz_Macierz_ObrotuZ();
void przypisz_stopnie(double stopnie);
void przypisz_stopnieX(double stopnie);
void przypisz_stopnieY(double stopnie);
void przypisz_stopnieZ(double stopnie);
bool operator==(const Macierz tmp) const;
};
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
Macierz<Templ_Typ, Templ_Rozmiar>::Macierz(Templ_Typ tmp[Templ_Rozmiar][Templ_Rozmiar])
{
for (unsigned int index = 0; index < Templ_Rozmiar; ++index)
{
for (unsigned int j = 0; j < Templ_Rozmiar; ++j)
{
value[index][j] = tmp[index][j];
}
}
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
Macierz<Templ_Typ, Templ_Rozmiar>::Macierz()
{
for (unsigned int i = 0; i < Templ_Rozmiar; ++i)
{
for (unsigned int j = 0; j < Templ_Rozmiar; ++j)
{
value[i][j] = 0;
}
}
}
// template <typename Templ_Typ, unsigned int Templ_Rozmiar>
// Wektor<Templ_Typ, Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::operator*(Wektor<Templ_Typ, Templ_Rozmiar> tmp)
// {
// Wektor<Templ_Typ, Templ_Rozmiar> result;
// for (unsigned int i = 0; i < Templ_Rozmiar; ++i)
// {
// for (unsigned int j = 0; j < Templ_Rozmiar; ++j)
// {
// result[i] += value[i][j] * tmp[j];
// }
// }
// return result;
// }
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
Macierz<Templ_Typ, Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::operator+(Macierz<Templ_Typ, Templ_Rozmiar> tmp)
{
Macierz result = Macierz();
for (unsigned int i = 0; i < Templ_Rozmiar; ++i)
{
for (unsigned int j = 0; j < Templ_Rozmiar; ++j)
{
result(i, j) = this->value[i][j] + tmp(i, j);
}
}
return result;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
Macierz<Templ_Typ, Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::operator-(Macierz<Templ_Typ, Templ_Rozmiar> tmp)
{
Macierz result = Macierz();
for (unsigned int i = 0; i < Templ_Rozmiar; ++i)
{
for (unsigned int j = 0; j < Templ_Rozmiar; ++j)
{
result(i, j) = this->value[i][j] - tmp(i, j);
}
}
return result;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
Macierz<Templ_Typ, Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::operator*(Macierz<Templ_Typ, Templ_Rozmiar> tmp)
{
Macierz result = Macierz();
for (unsigned int i = 0; i < Templ_Rozmiar; ++i)
{
for (unsigned int j = 0; j < Templ_Rozmiar; ++j)
{
for (unsigned int k = 0; k < Templ_Rozmiar; ++k)
{
result(i, j) += this->value[i][k] * tmp(k, j);
}
}
}
return result;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
Templ_Typ &Macierz<Templ_Typ, Templ_Rozmiar>::operator()(unsigned int row, unsigned int column)
{
if (row >= Templ_Rozmiar)
{
std::cout << "Error: Macierz jest poza zasiegiem";
exit(0);
}
if (column >= Templ_Rozmiar)
{
std::cout << "Error: Macierz jest poza zasiegiem";
exit(0);
}
return value[row][column];
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
const Templ_Typ &Macierz<Templ_Typ, Templ_Rozmiar>::operator()(unsigned int row, unsigned int column) const
{
if (row >= Templ_Rozmiar)
{
std::cout << "Error: Macierz jest poza zasiegiem";
exit(0); // lepiej byłoby rzucić wyjątkiem stdexcept
}
if (column >= Templ_Rozmiar)
{
std::cout << "Error: Macierz jest poza zasiegiem";
exit(0); // lepiej byłoby rzucić wyjątkiem stdexcept
}
return value[row][column];
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::StopienNaRadian()
{
kat_radian = kat_stopnie * M_PI / 180;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::StopienNaRadianX()
{
kat_radianX = kat_stopnieX * M_PI / 180;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::StopienNaRadianY()
{
kat_radianY = kat_stopnieY * M_PI / 180;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::StopienNaRadianZ()
{
kat_radianZ = kat_stopnieZ * M_PI / 180;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::Oblicz_Macierz_Obrotu()
{
if (Templ_Rozmiar == 2)
{
value[0][0] = cos(kat_radian);
value[0][1] = -sin(kat_radian);
value[1][0] = sin(kat_radian);
value[1][1] = cos(kat_radian);
}
else
{
std::cerr << "Błąd!!!" << std::endl;
}
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::Oblicz_Macierz_ObrotuX()
{
if (Templ_Rozmiar == 3)
{
value[0][0] = 1;
value[0][1] = 0;
value[0][2] = 0;
value[1][0] = 0;
value[1][1] = cos(kat_radianX);
value[1][2] = -sin(kat_radianX);
value[2][0] = 0;
value[2][1] = sin(kat_radianX);
value[2][2] = cos(kat_radianX);
}
else
{
std::cerr << "Błąd!!!" << std::endl;
}
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::Oblicz_Macierz_ObrotuY()
{
if (Templ_Rozmiar == 3)
{
value[0][0] = cos(kat_radianY);
value[0][1] = 0;
value[0][2] = sin(kat_radianY);
value[1][0] = 0;
value[1][1] = 1;
value[1][2] = 0;
value[2][0] = -sin(kat_radianY);
value[2][1] = 0;
value[2][2] = cos(kat_radianY);
}
else
{
std::cerr << "Błąd!!!" << std::endl;
}
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::Oblicz_Macierz_ObrotuZ()
{
if (Templ_Rozmiar == 3)
{
value[0][0] = cos(kat_radianZ);
value[0][1] = -sin(kat_radianZ);
value[0][2] = 0;
value[1][0] = sin(kat_radianZ);
value[1][1] = cos(kat_radianZ);
value[1][2] = 0;
value[2][0] = 0;
value[2][1] = 0;
value[2][2] = 1;
}
else
{
std::cerr << "Błąd!!!" << std::endl;
}
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::przypisz_stopnie(double stopnie)
{
kat_stopnie = stopnie;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::przypisz_stopnieX(double stopnie)
{
kat_stopnieX = stopnie;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::przypisz_stopnieY(double stopnie)
{
kat_stopnieY = stopnie;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
void Macierz<Templ_Typ, Templ_Rozmiar>::przypisz_stopnieZ(double stopnie)
{
kat_stopnieZ = stopnie;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
bool Macierz<Templ_Typ, Templ_Rozmiar>::operator==(const Macierz<Templ_Typ, Templ_Rozmiar> tmp) const
{
int liczenie = 0;
for (unsigned int i = 0; i < Templ_Rozmiar; ++i)
{
for (unsigned int j = 0; j < Templ_Rozmiar; ++j)
{
if (std::abs(value[i][j] - tmp(i, j)) <= MIN_DIFF)
{
++liczenie;
}
}
}
if (liczenie == pow(Templ_Rozmiar, 2))
{
return true;
}
return false;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
std::istream &operator>>(std::istream &in, Macierz<Templ_Typ, Templ_Rozmiar> &mat)
{
for (unsigned int i = 0; i < Templ_Rozmiar; ++i)
{
for (unsigned int j = 0; j < Templ_Rozmiar; ++j)
{
in >> mat(i, j);
}
}
return in;
}
template <typename Templ_Typ, unsigned int Templ_Rozmiar>
std::ostream &operator<<(std::ostream &out, Macierz<Templ_Typ, Templ_Rozmiar> const &mat)
{
for (unsigned int i = 0; i < Templ_Rozmiar; ++i)
{
for (unsigned int j = 0; j < Templ_Rozmiar; ++j)
{
out << "| " << mat(i, j) << " | ";
}
std::cout << std::endl;
}
return out;
}
#endif | 27.144509 | 118 | 0.622658 | KPO-2020-2021 |
fa94f3a3046e6cbd35b7f1ec92771ba7927d1907 | 913 | hpp | C++ | Applications/ZilchShadersTests/Helpers.hpp | jodavis42/ZilchShaders | a161323165c54d2824fe184f5d540e0a008b4d59 | [
"MIT"
] | 1 | 2019-08-31T00:45:45.000Z | 2019-08-31T00:45:45.000Z | Applications/ZilchShadersTests/Helpers.hpp | jodavis42/ZilchShaders | a161323165c54d2824fe184f5d540e0a008b4d59 | [
"MIT"
] | 5 | 2020-04-13T00:17:11.000Z | 2021-04-20T23:11:42.000Z | Applications/ZilchShadersTests/Helpers.hpp | jodavis42/ZilchShaders | a161323165c54d2824fe184f5d540e0a008b4d59 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
///
/// Authors: Joshua Davis
/// Copyright 2015, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
void LoadSettingsOrDefault(ZilchShaderSpirVSettings& settings, StringParam defFilePath);
void LoadDirectorySettingsOrDefault(ZilchShaderSpirVSettings& settings, StringParam directoryPath);
void LoadFragmentCodeDirectory(SimpleZilchShaderIRGenerator& shaderGenerator, StringParam directory);
// Simple function to display a diff error in notepad++ (ideally use a better text editor or something later)
void DisplayError(StringParam filePath, StringParam lineNumber, StringParam errMsg);
void FileToStream(File& file, TextStreamBuffer& stream);
void RunProcess(StringParam applicationPath, StringParam args, String* stdOutResult, String* stdErrResult);
| 50.722222 | 109 | 0.684556 | jodavis42 |
fa965d14c8328527988ae1edb2011efab9fa57a5 | 404 | hpp | C++ | server/world.hpp | irl-game/irl | ba507a93371ab172b705c1ede8cd062123fc96f5 | [
"MIT"
] | null | null | null | server/world.hpp | irl-game/irl | ba507a93371ab172b705c1ede8cd062123fc96f5 | [
"MIT"
] | null | null | null | server/world.hpp | irl-game/irl | ba507a93371ab172b705c1ede8cd062123fc96f5 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <unordered_map>
#include <unordered_set>
class Entity;
class Client;
class World
{
public:
World();
~World();
auto tick() noexcept -> void;
std::unordered_map<Client *, std::unique_ptr<Client>> clients;
private:
std::unordered_map<const Entity *, std::unique_ptr<Entity>> entities;
std::unordered_map<uint32_t, std::unordered_set<Entity *>> grid;
}; | 20.2 | 71 | 0.717822 | irl-game |
b71232d372e0f2221c02359b6f2eb745778fe0b7 | 634 | cpp | C++ | Lista_2/mike_new.cpp | Thulio-Carvalho/Advanced-Algorithms-Problems | 724bfb765d056ddab414df7dd640914aa0c665ae | [
"MIT"
] | null | null | null | Lista_2/mike_new.cpp | Thulio-Carvalho/Advanced-Algorithms-Problems | 724bfb765d056ddab414df7dd640914aa0c665ae | [
"MIT"
] | null | null | null | Lista_2/mike_new.cpp | Thulio-Carvalho/Advanced-Algorithms-Problems | 724bfb765d056ddab414df7dd640914aa0c665ae | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define MAXN 200014
using namespace std;
int N, arr[MAXN], l[MAXN], r[MAXN];
stack<int> s;
int main(){
cin >> N;
for (int i = 0; i < N; i++) {
cin >> arr[i];
}
fill(l, l + MAXN, -1);
fill(r, r + MAXN, N);
for (int i = 0; i < N; i++) {
while(!s.empty() && arr[s.top()] >= arr[i])
s.pop();
if (!s.empty())
l[i] = s.top();
s.push(i);
}
for (int i = 0; i < N; i++) {
cout << arr[i] << " ";
} cout << endl;
for (int i = 0; i < N; i++) {
cout << l[i] << " ";
} cout << endl;
return 0;
} | 17.611111 | 51 | 0.388013 | Thulio-Carvalho |
b71300420aeed2ab23a6a8af5412a20fed020f3c | 4,213 | cpp | C++ | test/lib/Dialect/VectorExt/TestVectorMaskingUtils.cpp | giuseros/iree-llvm-sandbox | d47050d04d299dab799f8a1c6eb7e5d85bda535f | [
"Apache-2.0"
] | null | null | null | test/lib/Dialect/VectorExt/TestVectorMaskingUtils.cpp | giuseros/iree-llvm-sandbox | d47050d04d299dab799f8a1c6eb7e5d85bda535f | [
"Apache-2.0"
] | null | null | null | test/lib/Dialect/VectorExt/TestVectorMaskingUtils.cpp | giuseros/iree-llvm-sandbox | d47050d04d299dab799f8a1c6eb7e5d85bda535f | [
"Apache-2.0"
] | null | null | null | //===- TestMaskingUtils.cpp - Utilities for vector masking ----------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements logic for testing Vector masking utilities.
//
//===----------------------------------------------------------------------===//
#include "Dialects/VectorExt/VectorExtOps.h"
#include "Dialects/VectorExt/VectorMaskingUtils.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/Vector/IR/VectorOps.h"
#include "mlir/IR/Visitors.h"
#include "mlir/Pass/Pass.h"
using namespace mlir;
using namespace mlir::linalg;
using namespace mlir::vector;
using namespace mlir::vector_ext;
namespace {
struct TestVectorMaskingUtils
: public PassWrapper<TestVectorMaskingUtils, OperationPass<FuncOp>> {
TestVectorMaskingUtils() = default;
TestVectorMaskingUtils(const TestVectorMaskingUtils &pass) {}
StringRef getArgument() const final { return "test-vector-masking-utils"; }
StringRef getDescription() const final {
return "Test vector masking utilities";
}
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<LinalgDialect, VectorDialect, VectorExtDialect>();
}
Option<bool> predicationEnabled{*this, "predication",
llvm::cl::desc("Test vector predication"),
llvm::cl::init(false)};
Option<bool> maskingEnabled{*this, "masking",
llvm::cl::desc("Test vector masking"),
llvm::cl::init(false)};
void testPredication() {
// Try different testing approaches until one triggers the predication
// transformation for that particular function.
bool predicationSucceeded = false;
// Test tiled loop body predication.
if (!predicationSucceeded) {
getOperation().walk([&](TiledLoopOp loopOp) {
predicationSucceeded = true;
OpBuilder builder(loopOp);
if (failed(predicateTiledLoop(builder, loopOp,
/*incomingMask=*/llvm::None)))
loopOp.emitError("Predication of tiled loop failed");
});
}
// Test function body predication.
if (!predicationSucceeded) {
FuncOp funcOp = getOperation();
ValueRange funcArgs = funcOp.body().getArguments();
if (funcArgs.size() >= 3) {
predicationSucceeded = true;
// Return the mask from the third argument position starting from the
// end, if found. Otherwise, return a null value.
auto createPredicateMaskForFuncOp = [&](OpBuilder &builder) -> Value {
if (funcArgs.size() < 3)
return Value();
// Predicate mask is the third argument starting from the end.
Value mask = *std::prev(funcArgs.end(), 3);
if (auto vecType = mask.getType().dyn_cast<VectorType>()) {
Type elemType = vecType.getElementType();
if (elemType.isInteger(1))
return mask;
}
return Value();
};
OpBuilder builder(funcOp);
Value idx = *std::prev(funcArgs.end(), 2);
Value incoming = funcArgs.back();
if (!predicateOp(builder, funcOp, &funcOp.body(),
createPredicateMaskForFuncOp, idx, incoming))
funcOp.emitRemark("Predication of function failed");
}
}
}
void testMasking() {
FuncOp funcOp = getOperation();
OpBuilder builder(funcOp);
if (failed(maskVectorPredicateOps(builder, funcOp,
maskGenericOpWithSideEffects)))
funcOp.emitError("Masking of function failed");
}
void runOnOperation() override {
if (predicationEnabled)
testPredication();
if (maskingEnabled)
testMasking();
}
};
} // namespace
namespace mlir {
namespace test_ext {
void registerTestVectorMaskingUtils() {
PassRegistration<TestVectorMaskingUtils>();
}
} // namespace test_ext
} // namespace mlir
| 33.704 | 80 | 0.61785 | giuseros |
b71353bd1158764cddf2d9e45be1599d3d6c7708 | 12,774 | hpp | C++ | src/codegen/bytecode.hpp | Zoxc/mirb | 14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6 | [
"BSD-3-Clause"
] | 10 | 2016-10-06T06:22:20.000Z | 2022-02-28T05:33:09.000Z | src/codegen/bytecode.hpp | Zoxc/mirb | 14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6 | [
"BSD-3-Clause"
] | null | null | null | src/codegen/bytecode.hpp | Zoxc/mirb | 14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6 | [
"BSD-3-Clause"
] | 3 | 2018-01-08T03:34:34.000Z | 2021-09-12T12:12:22.000Z | #pragma once
#include "../common.hpp"
#include "opcodes.hpp"
#include "../tree/nodes.hpp"
#include "../tree/tree.hpp"
#include <Prelude/JoiningBuffer.hpp>
namespace Mirb
{
namespace Tree
{
class Scope;
};
namespace CodeGen
{
class ByteCodeGenerator;
class VariableGroup
{
private:
size_t address;
ByteCodeGenerator *bcg;
var_t var;
public:
VariableGroup(ByteCodeGenerator *bcg, size_t size);
var_t operator[](size_t index);
var_t use();
size_t size;
};
class Label
{
public:
#ifdef MIRB_DEBUG_COMPILER
size_t id;
Label(size_t id) : id(id) {}
#endif
size_t pos;
};
class ByteCodeGenerator
{
private:
void convert_data(Tree::Node *basic_node, var_t var);
void convert_heredoc(Tree::Node *basic_node, var_t var);
void convert_interpolate(Tree::Node *basic_node, var_t var);
void convert_integer(Tree::Node *basic_node, var_t var);
void convert_float(Tree::Node *basic_node, var_t var);
void convert_variable(Tree::Node *basic_node, var_t var);
void convert_cvar(Tree::Node *basic_node, var_t var);
void convert_ivar(Tree::Node *basic_node, var_t var);
void convert_global(Tree::Node *basic_node, var_t var);
void convert_constant(Tree::Node *basic_node, var_t var);
void convert_unary_op(Tree::Node *basic_node, var_t var);
void convert_boolean_not(Tree::Node *basic_node, var_t var);
void convert_binary_op(Tree::Node *basic_node, var_t var);
void convert_boolean_op(Tree::Node *basic_node, var_t var);
void convert_assignment(Tree::Node *basic_node, var_t var);
void convert_self(Tree::Node *basic_node, var_t var);
void convert_nil(Tree::Node *basic_node, var_t var);
void convert_true(Tree::Node *basic_node, var_t var);
void convert_false(Tree::Node *basic_node, var_t var);
void convert_symbol(Tree::Node *basic_node, var_t var);
void convert_range(Tree::Node *basic_node, var_t var);
void convert_array(Tree::Node *basic_node, var_t var);
void convert_hash(Tree::Node *basic_node, var_t var);
void convert_block(Tree::Node *basic_node, var_t var);
void convert_call(Tree::Node *basic_node, var_t var);
void convert_super(Tree::Node *basic_node, var_t var);
void convert_if(Tree::Node *basic_node, var_t var);
void convert_case(Tree::Node *basic_node, var_t var);
void convert_loop(Tree::Node *basic_node, var_t var);
void convert_group(Tree::Node *basic_node, var_t var);
void convert_return(Tree::Node *basic_node, var_t var);
void convert_break(Tree::Node *basic_node, var_t var);
void convert_next(Tree::Node *basic_node, var_t var);
void convert_redo(Tree::Node *basic_node, var_t var);
void convert_class(Tree::Node *basic_node, var_t var);
void convert_module(Tree::Node *basic_node, var_t var);
void convert_method(Tree::Node *basic_node, var_t var);
void convert_alias(Tree::Node *basic_node, var_t var);
void convert_undef(Tree::Node *basic_node, var_t var);
void convert_handler(Tree::Node *basic_node, var_t var);
void convert_multiple_expressions(Tree::Node *basic_node, var_t var);
static void (ByteCodeGenerator::*jump_table[Tree::SimpleNode::Types])(Tree::Node *basic_node, var_t var);
void convert_multiple_assignment(Tree::MultipleExpressionsNode *node, var_t rhs);
// Members
Label *body; // The point after the prolog of the block.
Tree::Scope *const scope;
Label *epilog; // The end of the block
var_t return_var;
Mirb::Block *final;
/*
* Exception related fields
*/
ExceptionBlock *current_exception_block;
Vector<ExceptionBlock *, MemoryPool> exception_blocks;
Vector<const char_t *, MemoryPool> strings;
JoiningBuffer<sizeof(MoveOp) * 32, MemoryPool> opcode;
typedef std::pair<size_t, Label *> BranchInfo;
typedef std::pair<size_t, const SourceLoc *> SourceInfo;
Vector<BranchInfo, MemoryPool> branches;
Vector<SourceInfo, MemoryPool> source_locs;
var_t heap_var;
void finalize();
size_t var_count; // The total variable count.
#ifdef MIRB_DEBUG_COMPILER
size_t label_count; // Nicer label labeling...
#endif
size_t loc;
Mirb::Block *compile(Tree::Scope *scope);
Mirb::Block *defer(Tree::Scope *scope);
void to_bytecode(Tree::Node *node, var_t var)
{
mirb_debug_assert(node);
mirb_debug_assert(node->type() < Tree::Node::Types);
auto func = jump_table[node->type()];
mirb_debug_assert(func);
(this->*func)(node, var);
}
var_t reuse(var_t var)
{
// TODO: Make sure no code stores results in the returned variable
return var == no_var ? create_var() : var;
}
var_t ref(Tree::Variable *var)
{
if(var)
return var->loc;
else
return no_var;
}
void gen_string(var_t var, const DataEntry &data)
{
auto str = data.copy<Prelude::Allocator::Standard>();
strings.push(str.data);
gen<StringOp>(var, str.data, str.length);
}
void gen_regexp(var_t var, const DataEntry &data, const SourceLoc &range)
{
auto str = data.copy<Prelude::Allocator::Standard>();
strings.push(str.data);
gen<RegexpOp>(var, str.data, str.length);
location(&range);
}
void gen_if(Label *ltrue, var_t var)
{
branches.push(BranchInfo(gen<BranchIfOp>(var), ltrue));
}
void gen_unwind_redo(Label *body)
{
branches.push(BranchInfo(gen<UnwindRedoOp>(), body));
}
void gen_unless(Label *lfalse, var_t var)
{
branches.push(BranchInfo(gen<BranchUnlessOp>(var), lfalse));
}
void location(const SourceLoc *range)
{
source_locs.push(SourceInfo(opcode.size(), range));
}
void gen_branch(Label *block)
{
branches.push(BranchInfo(gen<BranchOp>(), block));
}
void branch(Label *block)
{
gen_branch(block);
//TODO: Eliminate code generation from this point. The block will never be reached
gen(create_label());
}
template<typename F> var_t write_node(Tree::Node *lhs, F func, var_t temp)
{
switch(lhs->type())
{
case Tree::SimpleNode::MultipleExpressions:
{
var_t var = reuse(temp);
var_t rhs = create_var();
func(var);
gen<ArrayOp>(rhs, 0, 0); // TODO: Add an opcode to convert into an array to avoid copying data
gen<PushArrayOp>(rhs, var);
convert_multiple_assignment((Tree::MultipleExpressionsNode *)lhs, rhs);
return var;
}
case Tree::SimpleNode::Call:
{
auto node = (Tree::CallNode *)lhs;
var_t var = reuse(temp);
func(var);
size_t argc = node->arguments.size + 1;
VariableGroup group(this, argc);
size_t param = 0;
for(auto arg: node->arguments)
to_bytecode(arg, group[param++]);
gen<MoveOp>(group[param++], var);
var_t obj = create_var();
to_bytecode(node->object, obj);
gen<CallOp>(var, obj, node->method, no_var, argc, group.use());
location(node->range);
return var;
}
case Tree::SimpleNode::Variable:
{
auto variable = (Tree::VariableNode *)lhs;
return write_variable(variable->var, func, temp);
}
case Tree::SimpleNode::CVar:
{
auto variable = (Tree::CVarNode *)lhs;
var_t var = reuse(temp);
func(var);
gen<SetIVarOp>(variable->name, var); // TODO: Fix cvars
return var;
}
case Tree::SimpleNode::IVar:
{
auto variable = (Tree::IVarNode *)lhs;
var_t var = reuse(temp);
func(var);
gen<SetIVarOp>(variable->name, var);
return var;
}
case Tree::SimpleNode::Global:
{
auto variable = (Tree::GlobalNode *)lhs;
var_t var = reuse(temp);
func(var);
gen<SetGlobalOp>(variable->name, var);
location(&variable->range);
return var;
}
case Tree::SimpleNode::Constant:
{
auto variable = (Tree::ConstantNode *)lhs;
var_t var = reuse(temp);
func(var);
var_t obj = no_var;
if(variable->obj)
{
obj = create_var();
to_bytecode(variable->obj, obj);
}
else if(variable->top_scope)
{
obj = create_var();
gen<LoadObjectOp>(obj);
}
if(obj == no_var)
gen<SetConstOp>(variable->name, var);
else
gen<SetScopedConstOp>(obj, variable->name, var);
location(variable->range);
return var;
}
default:
mirb_debug_abort("Unknown left hand expression");
}
}
template<typename F> var_t write_variable(Tree::Variable *var, F func, var_t temp)
{
if(var->heap)
{
var_t heap;
if(var->owner != scope)
{
heap = create_var();
gen<LookupOp>(heap, scope->referenced_scopes.index_of(var->owner));
}
else
heap = heap_var;
var_t store = reuse(temp);
func(store);
gen<SetHeapVarOp>(heap, var->loc, store);
return store;
}
else
{
var_t store = reuse(temp);
func(store);
gen<MoveOp>(ref(var), store);
return store;
}
}
var_t block_arg(Tree::Scope *scope, var_t break_dst);
var_t call_args(Tree::InvokeNode *node, Tree::Scope *scope, size_t &argc, var_t &argv, var_t break_dst);
void early_finalize(Block *block, Tree::Scope *scope);
friend class VariableGroup;
friend class ByteCodePrinter;
public:
ByteCodeGenerator(MemoryPool memory_pool, Tree::Scope *scope);
MemoryPool memory_pool;
Label *gen(Label *block)
{
block->pos = opcode.size();
return block;
}
bool is_var(var_t var)
{
return var != no_var;
}
template<class T, typename F> size_t alloc(F func)
{
size_t result = opcode.size();
func(opcode.allocate(sizeof(T)));
return result;
}
template<class T> size_t gen()
{
return alloc<T>([&](void *p) { new (p) T(); });
}
template<class T, typename Arg1> size_t gen(Arg1 arg1)
{
return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1)); });
}
template<class T, typename Arg1, typename Arg2> size_t gen(Arg1&& arg1, Arg2&& arg2)
{
return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)); });
}
template<class T, typename Arg1, typename Arg2, typename Arg3> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3)
{
return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)); });
}
template<class T, typename Arg1, typename Arg2, typename Arg3, typename Arg4> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4)
{
return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)); });
}
template<class T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4, Arg5&& arg5)
{
return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4), std::forward<Arg5>(arg5)); });
}
template<class T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4, Arg5&& arg5, Arg6&& arg6)
{
return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4), std::forward<Arg5>(arg5), std::forward<Arg6>(arg6)); });
}
template<class T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4, Arg5&& arg5, Arg6&& arg6, Arg7&& arg7)
{
return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4), std::forward<Arg5>(arg5), std::forward<Arg6>(arg6), std::forward<Arg7>(arg7)); });
}
var_t create_var();
Label *create_label();
var_t read_variable(Tree::Variable *var);
void write_variable(Tree::Variable *var, var_t value);
Block *generate();
};
};
};
| 27.95186 | 232 | 0.617739 | Zoxc |
b7176c107b4c4c326de6c7ac47392a995897d323 | 9,801 | hpp | C++ | include/mflib/waveformTemplate.hpp | uofuseismo/mflib | 14695f62082d28d4cc5603bb6edcaf1efe9dd980 | [
"MIT"
] | 5 | 2019-12-06T21:14:17.000Z | 2021-09-21T03:36:58.000Z | include/mflib/waveformTemplate.hpp | uofuseismo/mflib | 14695f62082d28d4cc5603bb6edcaf1efe9dd980 | [
"MIT"
] | 5 | 2019-11-27T19:06:06.000Z | 2020-04-24T19:07:44.000Z | include/mflib/waveformTemplate.hpp | uofuseismo/mflib | 14695f62082d28d4cc5603bb6edcaf1efe9dd980 | [
"MIT"
] | 2 | 2021-09-09T11:15:50.000Z | 2021-12-04T00:50:53.000Z | #ifndef MFLIB_WAVEFORMTEMPLATE_HPP
#define MFLIB_WAVEFORMTEMPLATE_HPP
#include <memory>
#include "mflib/enums.hpp"
namespace MFLib
{
class NetworkStationPhase;
/*!
* @brief Defines a waveform template.
* @copyright Ben Baker (University of Utah) distributed under the MIT license.
*/
class WaveformTemplate
{
public:
/*! @name Constructors
* @{
*/
/*!
* @brief Constructor.
*/
WaveformTemplate();
/*!
* @brief Copy constructor.
* @param[in] tplate The template class from which to initialize this
* template.
*/
WaveformTemplate(const WaveformTemplate &tplate);
/*!
* @brief Move constructor.
* @param[in,out] tplate The template class whose memory will be moved
* to this. On exit, tplate's behavior is undefined.
*/
WaveformTemplate(WaveformTemplate &&tplate) noexcept;
/*! } */
/*!
* @brief Copy assignment operator.
* @param[in] tplate The waveform template class to copy.
* @result A deep copy of the inupt waveform template.
*/
WaveformTemplate& operator=(const WaveformTemplate &tplate);
/*!
* @brief Move assignment operator.
* @param[in,out] tplate The waveform template class whose memory will be
* moved to this class. On exit, tplate's behavior
* is undefined.
* @result The memory from tplate moved to this.
*/
WaveformTemplate& operator=(WaveformTemplate &&tplate) noexcept;
/*! @name Destructors
* @{
*/
/*!
* @brief Destructor.
*/
~WaveformTemplate();
/*!
* @brief Clears and resets the memory of the class.
*/
void clear() noexcept;
/*! @} */
/*! @name Signal (Required)
* @{
*/
/*!
* @brief Sets the template waveform signal.
* @param[in] npts The number of samples in the template.
* @param[in] x The template waveform signal. This is an array whose
* dimension is [npts].
* @throws std::invalid_argument if npts is not positive or x is NULL.
* @note This will invalidate the onset time.
*/
void setSignal(int npts, const double x[]);
/*! @coypdoc setSignal */
void setSignal(int npts, const float x[]);
/*!
* @brief Gets the template waveform signal.
* @param[in] maxx The maximum number of samples that x can hold. This
* must be at least \c getSignalLength().
* @param[out] x The waveform template. This is an array whose dimension
* is [maxx] however only the first \c getSignalLength()
* samples are accessed.
* @throws std::invalid_argument if x is NULL or maxx is too small.
* @throws std::runtime_error if the signal was not set.
*/
void getSignal(int maxx, double *x[]) const;
/*! @copydoc getSignal */
void getSignal(int maxx, float *x[]) const;
/*!
* @result The length of the template waveform signal.
* @throws std::runtime_error if the template waveform was not set.
* @sa \c haveSignal()
*/
int getSignalLength() const;
/*!
* @brief Determines if the template waveform signal was set.
* @result True indicates that the template was set.
*/
bool haveSignal() const noexcept;
/*! @} */
/*! @name Sampling Rate (Required)
* @{
*/
/*!
* @brief Sets the sampling rate.
* @param[in] samplingRate The sampling rate in Hz of the template waveform
* signal.
* @throws std::invalid_argument if this is not positive.
* @note This will invalidate the onset time.
*/
void setSamplingRate(double samplingRate);
/*!
* @brief Gets the sampling rate.
* @result The template's sampling rate.
* @throws std::runtime_error if the sampling rate was not set.
*/
double getSamplingRate() const;
/*!
* @brief Determines if the sampling rate was set.
* @result True indicates that the sampling rate was set.
*/
bool haveSamplingRate() const noexcept;
/*! @} */
/*! @name Shift and Sum Weight
* @{
*/
/*!
* @brief Defines the template's weight in the shift and stack operation.
* @param[in] weight The weight of this template during the shift and sum
* operation.
* @throws std::invalid_argument if weight is not in the range [0,1].
*/
void setShiftAndStackWeight(double weight);
/*!
* @brief Gets the template's weight during the shift and stack operation.
* @result The template's weight during the shift and sum operation.
* @note If \c setShiftStackAndWeight() was not called then this will
* be unity.
*/
double getShiftAndStackWeight() const noexcept;
/*! @} */
/*! @name Onset Time (Required for Shifting)
* @{
*/
/*!
* @brief Sets the time in seconds relative to the trace where the
* phase onset occurs.
* @param[in] onsetTime The onset time in seconds where the pick occurs.
* For example, if the pick is 2 seconds into the
* the trace, i.e., there is `noise' 2 seconds prior
* to the pick, then this should be 2.
* @throws std::runtime_error if the waveform template signal was not set
* or the sampling rate was not set.
* @throws std::invalid_argument if the onset time is not in the trace.
* @sa \c haveSignal(), \c haveSamplingRate().
* @note This is invalidated whenever the sampling period or signal is set.
*/
void setPhaseOnsetTime(double onsetTime);
/*!
* @brief Gets the phase onset time.
* @result The time, relative to the trace start, where the pick occurs.
* For example, if 2, then 2 seconds into the trace is where the
* pick was made.
* @throws std::runtime_error if the onset time was not set.
* @sa \c havePhaseOnsetTime()
*/
double getPhaseOnsetTime() const;
/*!
* @brief Determines if the onset time was set.
* @result True indicates that the onset time was set.
*/
bool havePhaseOnsetTime() const noexcept;
/*!@ } */
/*! @brief Travel Time (Required for Shifting)
* @{
*/
/*!
* @brief Sets the observed travel time for the pick.
* @param[in] travelTime The observed travel time in seconds for the pick.
* For example, if this is 7, then it took 7 seconds
* for the wave to travel from the source to the
* receiver.
* @throws std::invalid_argument if travelTime is negative
* @note The trace commences travelTime - onsetTime seconds after the origin
* time.
*/
void setTravelTime(double travelTime);
/*!
* @brief Gets the observed travel time for the pick.
* @result The observed travel time for this pick in seconds.
* For example, if this is 7, then it took 7 seconds for the
* wave to travel from the source to the receiver.
* @throws std::runtime_error if the travel time was not set.
* @sa \c haveTravelTime()
*/
double getTravelTime() const;
/*!
* @brief Determines if the travel time was set set.
* @result True indicates that the travel time was set.
*/
bool haveTravelTime() const noexcept;
/*! @} */
/*! @brief Identifier
* @{
*/
/*!
* @brief This is used to give the waveform template an identifier.
* The identifier defines the network, station, and phase
* as well as the event identifier to which the phase was associated
* in the catalog.
* @param[in] id The waveform identifier.
*/
void setIdentifier(const std::pair<NetworkStationPhase, uint64_t> &id) noexcept;
/*!
* @brief Gets the waveform template identifier.
* @result The waveform identifier where result.first is the network,
* station, and phase while result.second is the event identifier.
* @throws std::runtime_error if the waveform identifier was not set.
* @sa \c haveIdentifier()
*/
std::pair<NetworkStationPhase, uint64_t> getIdentifier() const;
/*!
* @brief Determines whether or not the waveform identifier was set.
* @result True indicates that the waveform identifier was set.
*/
bool haveIdentifier() const noexcept;
/*! @} */
/*! @brief Magnitude
* @{
*/
/*!
* @brief Sets the event magnitude associated with this template.
* @param[in] magnitude The magnitude.
*/
void setMagnitude(double magnitude) noexcept;
/*!
* @brief Gets the magnitude associated with this template.
* @result The magnitude associated with this template.
* @throws std::runtime_error if the magnitude was not set.
* @sa \c haveMagnitude()
*/
double getMagnitude() const;
/*!
* @brief Determines whether or not the magnitude was set.
* @result True indicates that the magnitude was set.
*/
bool haveMagnitude() const noexcept;
/*! @} */
/*! @brief Polarity
* @{
*/
/*!
* @brief Sets the onset's polarity.
* @param[in] polarity The arrival's polarity.
*/
void setPolarity(MFLib::Polarity polarity) noexcept;
/*!
* @brief Gets the onset's polarity.
* @result The onset's polarity. By default this is unknown.
*/
MFLib::Polarity getPolarity() const noexcept;
/*! @} */
private:
class WaveformTemplateImpl;
std::unique_ptr<WaveformTemplateImpl> pImpl;
};
}
#endif
| 35.255396 | 84 | 0.605755 | uofuseismo |
b7195e0b4a7870d5eb1e153904e59c4b42652bbe | 2,773 | cpp | C++ | systems/polyvox/PolyVoxShader.cpp | phisko/kengine | c30f98cc8e79cce6574b5f61088b511f29bbe8eb | [
"MIT"
] | 259 | 2018-11-01T05:12:37.000Z | 2022-03-28T11:15:27.000Z | systems/polyvox/PolyVoxShader.cpp | raptoravis/kengine | 619151c20e9db86584faf04937bed3d084e3bc21 | [
"MIT"
] | 2 | 2018-11-30T13:58:44.000Z | 2018-12-17T11:58:42.000Z | systems/polyvox/PolyVoxShader.cpp | raptoravis/kengine | 619151c20e9db86584faf04937bed3d084e3bc21 | [
"MIT"
] | 16 | 2018-12-01T13:38:18.000Z | 2021-12-04T21:31:55.000Z | #include "PolyVoxShader.hpp"
#include "EntityManager.hpp"
#include "data/TransformComponent.hpp"
#include "data/PolyVoxComponent.hpp"
#include "data/GraphicsComponent.hpp"
#include "data/ModelComponent.hpp"
#include "data/OpenGLModelComponent.hpp"
#include "systems/opengl/shaders/ApplyTransparencySrc.hpp"
#include "systems/opengl/ShaderHelper.hpp"
static inline const char * vert = R"(
#version 330
layout (location = 0) in vec3 position;
layout (location = 2) in vec3 color;
uniform mat4 proj;
uniform mat4 view;
uniform mat4 model;
uniform vec3 viewPos;
out vec4 WorldPosition;
out vec3 EyeRelativePos;
out vec3 Color;
void main() {
WorldPosition = model * vec4(position, 1.0);
EyeRelativePos = WorldPosition.xyz - viewPos;
Color = color;
//Color = vec3(1.0); // This is pretty
gl_Position = proj * view * WorldPosition;
}
)";
static inline const char * frag = R"(
#version 330
in vec4 WorldPosition;
in vec3 EyeRelativePos;
in vec3 Color;
uniform vec4 color;
uniform float entityID;
layout (location = 0) out vec4 gposition;
layout (location = 1) out vec3 gnormal;
layout (location = 2) out vec4 gcolor;
layout (location = 3) out float gentityID;
void applyTransparency(float a);
void main() {
applyTransparency(color.a);
gposition = WorldPosition;
gnormal = -normalize(cross(dFdy(EyeRelativePos), dFdx(EyeRelativePos)));
gcolor = vec4(Color * color.rgb, 0.0);
gentityID = entityID;
}
)";
namespace kengine {
static glm::vec3 toVec(const putils::Point3f & p) { return { p.x, p.y, p.z }; }
PolyVoxShader::PolyVoxShader(EntityManager & em)
: Program(false, putils_nameof(PolyVoxShader)),
_em(em)
{}
void PolyVoxShader::init(size_t firstTextureID) {
initWithShaders<PolyVoxShader>(putils::make_vector(
ShaderDescription{ vert, GL_VERTEX_SHADER },
ShaderDescription{ frag, GL_FRAGMENT_SHADER },
ShaderDescription{ Shaders::src::ApplyTransparency::Frag::glsl, GL_FRAGMENT_SHADER }
));
}
void PolyVoxShader::run(const Parameters & params) {
use();
_view = params.view;
_proj = params.proj;
_viewPos = params.camPos;
for (const auto &[e, poly, graphics, transform] : _em.getEntities<PolyVoxObjectComponent, GraphicsComponent, TransformComponent>()) {
if (graphics.model == Entity::INVALID_ID)
continue;
const auto & modelInfoEntity = _em.getEntity(graphics.model);
if (!modelInfoEntity.has<OpenGLModelComponent>() || !modelInfoEntity.has<ModelComponent>())
continue;
const auto & modelInfo = modelInfoEntity.get<ModelComponent>();
const auto & openGL = modelInfoEntity.get<OpenGLModelComponent>();
_model = ShaderHelper::getModelMatrix(modelInfo, transform);
_entityID = (float)e.id;
_color = graphics.color;
ShaderHelper::drawModel(openGL);
}
}
}
| 25.440367 | 135 | 0.728814 | phisko |
b726b6a2a934148784791d29bdc232ba711d26fe | 942 | hpp | C++ | sdk/keyvault/azure-security-keyvault-keys/inc/azure/keyvault/keys/key_create_options.hpp | sjoubert/azure-sdk-for-cpp | 5e2e84cdbcf49497ac67b77f642c2c7d0f2f0278 | [
"MIT"
] | null | null | null | sdk/keyvault/azure-security-keyvault-keys/inc/azure/keyvault/keys/key_create_options.hpp | sjoubert/azure-sdk-for-cpp | 5e2e84cdbcf49497ac67b77f642c2c7d0f2f0278 | [
"MIT"
] | null | null | null | sdk/keyvault/azure-security-keyvault-keys/inc/azure/keyvault/keys/key_create_options.hpp | sjoubert/azure-sdk-for-cpp | 5e2e84cdbcf49497ac67b77f642c2c7d0f2f0278 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
/**
* @brief Defines the supported options to create a Key Vault Key.
*
*/
#pragma once
#include <azure/core/context.hpp>
#include <azure/core/datetime.hpp>
#include <azure/core/nullable.hpp>
#include "azure/keyvault/keys/key_operation.hpp"
#include <list>
#include <string>
#include <unordered_map>
namespace Azure { namespace Security { namespace KeyVault { namespace Keys {
struct CreateKeyOptions
{
/**
* @brief Context for cancelling long running operations.
*/
Azure::Core::Context Context;
std::list<KeyOperation> KeyOperations;
Azure::Core::Nullable<Azure::Core::DateTime> NotBefore;
Azure::Core::Nullable<Azure::Core::DateTime> ExpiresOn;
Azure::Core::Nullable<bool> Enabled;
std::unordered_map<std::string, std::string> Tags;
};
}}}} // namespace Azure::Security::KeyVault::Keys
| 22.428571 | 76 | 0.707006 | sjoubert |
b727edd6f6e528c256e2dc56b9a9c2e0379019bf | 1,531 | cpp | C++ | tests/test_cpu.cpp | Ma-Dan/ncnn | 8e94566ffb6b676b05a3d2875eaa9463acc4a176 | [
"BSD-3-Clause"
] | 59 | 2020-12-28T02:46:58.000Z | 2022-02-10T14:50:48.000Z | tests/test_cpu.cpp | Ma-Dan/ncnn | 8e94566ffb6b676b05a3d2875eaa9463acc4a176 | [
"BSD-3-Clause"
] | 2 | 2020-11-05T05:39:31.000Z | 2020-11-27T06:08:23.000Z | tests/test_cpu.cpp | Ma-Dan/ncnn | 8e94566ffb6b676b05a3d2875eaa9463acc4a176 | [
"BSD-3-Clause"
] | 13 | 2020-12-28T02:49:01.000Z | 2022-03-12T11:58:33.000Z | #include <stdio.h>
#include "cpu.h"
#if defined __ANDROID__ || defined __linux__
static int test_cpu_set()
{
ncnn::CpuSet set;
if (set.num_enabled() != 0)
{
fprintf(stderr, "By default all cpus should be disabled\n");
return 1;
}
set.enable(0);
if (!set.is_enabled(0))
{
fprintf(stderr, "CpuSet enable doesn't work\n");
return 1;
}
if (set.num_enabled() != 1)
{
fprintf(stderr, "Only one cpu should be enabled\n");
return 1;
}
set.disable(0);
if (set.is_enabled(0))
{
fprintf(stderr, "CpuSet disable doesn't work\n");
return 1;
}
return 0;
}
static int test_cpu_info()
{
if (ncnn::get_cpu_count() >= 0 && ncnn::get_little_cpu_count() >= 0 && ncnn::get_big_cpu_count() >= 0)
{
return 0;
}
else
{
fprintf(stderr, "The system cannot have a negative number of processors\n");
return 1;
}
}
static int test_cpu_omp()
{
if (ncnn::get_omp_num_threads() >= 0 && ncnn::get_omp_thread_num() >= 0 && ncnn::get_omp_dynamic() >= 0)
{
return 0;
}
else
{
fprintf(stderr, "The OMP cannot have a negative number of processors\n");
return 1;
}
}
#else
static int test_cpu_set()
{
return 0;
}
static int test_cpu_info()
{
return 0;
}
static int test_cpu_omp()
{
return 0;
}
#endif
int main()
{
return 0
|| test_cpu_set()
|| test_cpu_info()
|| test_cpu_omp();
}
| 16.641304 | 108 | 0.555846 | Ma-Dan |
b728245881598bd173e019180fb2863faf68151d | 1,845 | cpp | C++ | 1135/main.cpp | Heliovic/PAT_Solutions | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | 2 | 2019-03-18T12:55:38.000Z | 2019-09-07T10:11:26.000Z | 1135/main.cpp | Heliovic/My_PAT_Answer | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | null | null | null | 1135/main.cpp | Heliovic/My_PAT_Answer | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | null | null | null | #include <cstdio>
//#include <cstdlib>
#define MAX_N 64
#define RED -1
#define BLACK 1
using namespace std;
struct node
{
int type, data;
node* lc;
node* rc;
node() {lc = rc = NULL;}
};
int K, N;
node* root = NULL;
int black_cnt = -1;
bool is_rbtree = true;
void insert_bst(int data, node* & r, int type)
{
if (r == NULL)
{
r = new node;
r->data = data;
r->type = type;
return;
}
if (data < r->data)
insert_bst(data, r->lc, type);
else
insert_bst(data, r->rc, type);
}
int dfs(node* r)
{
if (!is_rbtree)
return -1;
if (r == NULL)
{
return 1;
}
/*system("pause");
printf("%d\n", r->data);*/
if (r->type == RED)
{
if ((r->lc != NULL && r->lc->type == RED) || (r->rc != NULL && r->rc->type == RED))
{
is_rbtree = false;
return -1;
}
}
int lcnt = dfs(r->lc);
int rcnt = dfs(r->rc);
if (lcnt != rcnt)
is_rbtree = false;
return r->type == BLACK ? lcnt + 1 : lcnt;
}
void pre(node* r)
{
if (r == NULL)
return;
printf("%d ", r->data);
pre(r->lc);
pre(r->rc);
}
int main()
{
scanf("%d", &K);
while (K--)
{
root = NULL;
black_cnt = -1;
is_rbtree = true;
scanf("%d", &N);
for (int i = 0; i < N; i++)
{
int t;
scanf("%d", &t);
if (t < 0)
insert_bst(-t, root, RED);
else
insert_bst(t, root, BLACK);
}
if (root->type == RED)
{
printf("No\n");
continue;
}
//pre(root);
dfs(root);
if (is_rbtree)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
| 15.769231 | 91 | 0.416802 | Heliovic |
b72addd0b84922e8ce3620fd8c1a1584a73f03d6 | 2,562 | cpp | C++ | Samples/RadialController/cpp/RadialController.cpp | windows-development/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 8 | 2017-04-30T17:38:27.000Z | 2021-11-29T00:59:03.000Z | Samples/RadialController/cpp/RadialController.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | null | null | null | Samples/RadialController/cpp/RadialController.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 1 | 2020-01-18T09:12:02.000Z | 2020-01-18T09:12:02.000Z | #include "stdafx.h"
#include <tchar.h>
#include <StrSafe.h>
#include <wrl\implements.h>
#include <wrl\module.h>
#include <wrl\event.h>
#include <roapi.h>
#include <wrl.h>
#include "DeviceListener.h"
#include <ShellScalingApi.h>
#define CLASSNAME L"Radial Device Controller"
#define BUFFER_SIZE 2000
LRESULT CALLBACK WindowProc(
__in HWND hWindow,
__in UINT uMsg,
__in WPARAM wParam,
__in LPARAM lParam);
HANDLE console;
WCHAR windowClass[MAX_PATH];
void PrintMsg(WCHAR *msg)
{
size_t textLength;
DWORD charsWritten;
StringCchLength(msg, BUFFER_SIZE, &textLength);
WriteConsole(console, msg, (DWORD)textLength, &charsWritten, NULL);
}
void PrintStartupMessage()
{
wchar_t message[2000];
swprintf_s(message, 2000, L"Press F10 to begin...\n");
PrintMsg(message);
}
int _cdecl _tmain(
int argc,
TCHAR *argv[])
{
// Register Window Class
WNDCLASS wndClass = {
CS_DBLCLKS, (WNDPROC)WindowProc,
0,0,0,0,0,0,0, CLASSNAME
};
RegisterClass(&wndClass);
HWND hwnd = CreateWindow(
CLASSNAME,
L"Message Listener Window",
WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_VSCROLL,
CW_USEDEFAULT, // default horizontal position
CW_USEDEFAULT, // default vertical position
CW_USEDEFAULT, // default width
CW_USEDEFAULT, // default height
NULL, NULL, NULL, NULL);
console = GetStdHandle(STD_OUTPUT_HANDLE);
PrintStartupMessage();
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg); // Dispatch message to WindowProc
if (msg.message == WM_QUIT)
{
Windows::Foundation::Uninitialize();
break;
}
}
SetConsoleTextAttribute(console, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
}
DeviceListener *listener = nullptr;
LRESULT CALLBACK WindowProc(
__in HWND hWindow,
__in UINT uMsg,
__in WPARAM wParam,
__in LPARAM lParam)
{
switch (uMsg)
{
case WM_CLOSE:
DestroyWindow(hWindow);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_SYSKEYUP: //Press F10
if (!listener)
{
listener = new DeviceListener(console);
listener->Init(hWindow);
}
default:
return DefWindowProc(hWindow, uMsg, wParam, lParam);
}
return 0;
}
| 23.943925 | 91 | 0.607728 | windows-development |
b72bcdc1cba305dc1b857157a455e1a46417bce8 | 2,902 | hpp | C++ | src/xalanc/XPath/XNumber.hpp | kidaa/xalan-c | bb666d0ab3d0a192410823e6857c203d83c27b16 | [
"Apache-2.0"
] | null | null | null | src/xalanc/XPath/XNumber.hpp | kidaa/xalan-c | bb666d0ab3d0a192410823e6857c203d83c27b16 | [
"Apache-2.0"
] | 1 | 2021-08-18T12:32:31.000Z | 2021-08-18T12:32:31.000Z | src/xalanc/XPath/XNumber.hpp | AaronNGray/xalan | 6741bbdcb64a9d33df8bd7e21b558d66bb4292ec | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XNUMBER_HEADER_GUARD_1357924680)
#define XNUMBER_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <xalanc/XPath/XPathDefinitions.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
// Base class header file.
#include <xalanc/XPath/XNumberBase.hpp>
XALAN_CPP_NAMESPACE_BEGIN
class XALAN_XPATH_EXPORT XNumber : public XNumberBase
{
public:
/**
* Create an XNumber from a number.
*
* @param val numeric value to use
*/
XNumber(
double val,
MemoryManager& theMemoryManager);
XNumber(
const XNumber& source,
MemoryManager& theMemoryManager);
virtual
~XNumber();
// These methods are inherited from XObject ...
virtual double
num(XPathExecutionContext& executionContext) const;
virtual double
num() const;
virtual const XalanDOMString&
str(XPathExecutionContext& executionContext) const;
virtual const XalanDOMString&
str() const;
virtual void
str(
XPathExecutionContext& executionContext,
FormatterListener& formatterListener,
MemberFunctionPtr function) const;
virtual void
str(
FormatterListener& formatterListener,
MemberFunctionPtr function) const;
virtual void
str(
XPathExecutionContext& executionContext,
XalanDOMString& theBuffer) const;
virtual void
str(XalanDOMString& theBuffer) const;
virtual double
stringLength(XPathExecutionContext& executionContext) const;
// These methods are new to XNumber...
/**
* Change the value of an XNumber
*
* @param theValue The new value.
*/
void
set(double theValue);
private:
// not implemented
XNumber();
XNumber(const XNumber&);
// Value of the number being represented.
double m_value;
mutable XalanDOMString m_cachedStringValue;
};
XALAN_CPP_NAMESPACE_END
#endif // XNUMBER_HEADER_GUARD_1357924680
| 23.216 | 75 | 0.677119 | kidaa |
b734f0cd3f3cc7fa7d4671f172f94cf7d4a471b7 | 2,361 | cpp | C++ | Examples/CPP/WorkingWithResourceAssignments/GetResourceAssignmentOvertimes.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2022-03-16T14:31:36.000Z | 2022-03-16T14:31:36.000Z | Examples/CPP/WorkingWithResourceAssignments/GetResourceAssignmentOvertimes.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | null | null | null | Examples/CPP/WorkingWithResourceAssignments/GetResourceAssignmentOvertimes.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2020-07-01T01:26:17.000Z | 2020-07-01T01:26:17.000Z | #include "GetResourceAssignmentOvertimes.h"
#include <system/type_info.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/reflection/method_base.h>
#include <system/object_ext.h>
#include <system/object.h>
#include <system/decimal.h>
#include <system/console.h>
#include <system/collections/ienumerator.h>
#include <ResourceAssignmentCollection.h>
#include <ResourceAssignment.h>
#include <Project.h>
#include <Key.h>
#include <enums/AsnKey.h>
#include <Duration.h>
#include <Asn.h>
#include "RunExamples.h"
namespace Aspose {
namespace Tasks {
namespace Examples {
namespace CPP {
namespace WorkingWithResourceAssignments {
RTTI_INFO_IMPL_HASH(3423715729u, ::Aspose::Tasks::Examples::CPP::WorkingWithResourceAssignments::GetResourceAssignmentOvertimes, ThisTypeBaseTypesInfo);
void GetResourceAssignmentOvertimes::Run()
{
// The path to the documents directory.
System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
// ExStart:GetResourceAssignmentOvertimes
// Create project instance
System::SharedPtr<Project> project1 = System::MakeObject<Project>(dataDir + u"ResourceAssignmentOvertimes.mpp");
// Print assignment overtimes
{
auto ra_enumerator = (project1->get_ResourceAssignments())->GetEnumerator();
decltype(ra_enumerator->get_Current()) ra;
while (ra_enumerator->MoveNext() && (ra = ra_enumerator->get_Current(), true))
{
System::Console::WriteLine(ra->Get<System::Decimal>(Asn::OvertimeCost()));
System::Console::WriteLine(System::ObjectExt::ToString(ra->Get<Duration>(Asn::OvertimeWork())));
System::Console::WriteLine(ra->Get<System::Decimal>(Asn::RemainingCost()));
System::Console::WriteLine(ra->Get<System::Decimal>(Asn::RemainingOvertimeCost()));
System::Console::WriteLine(System::ObjectExt::ToString(ra->Get<Duration>(Asn::RemainingOvertimeWork())));
System::Console::WriteLine(System::ObjectExt::ToString(ra->Get<Duration>(Asn::RemainingOvertimeWork())));
}
}
// ExEnd:GetResourceAssignmentOvertimes
}
} // namespace WorkingWithResourceAssignments
} // namespace CPP
} // namespace Examples
} // namespace Tasks
} // namespace Aspose
| 35.772727 | 164 | 0.725964 | aspose-tasks |
b73b91877c6c37a97da62a77dd2023b25fd36147 | 1,310 | cpp | C++ | week 4/Linked List/10. Minimum Platforms .cpp | arpit456jain/gfg-11-Weeks-Workshop-on-DSA-in-CPP | ed7fd8bc0a581f54ba3a3588dd01013776c4ece6 | [
"MIT"
] | 6 | 2021-08-06T14:36:41.000Z | 2022-03-22T11:22:07.000Z | week 4/Linked List/10. Minimum Platforms .cpp | arpit456jain/11-Weeks-Workshop-on-DSA-in-CPP | ed7fd8bc0a581f54ba3a3588dd01013776c4ece6 | [
"MIT"
] | 1 | 2021-08-09T05:09:48.000Z | 2021-08-09T05:09:48.000Z | week 4/Linked List/10. Minimum Platforms .cpp | arpit456jain/11-Weeks-Workshop-on-DSA-in-CPP | ed7fd8bc0a581f54ba3a3588dd01013776c4ece6 | [
"MIT"
] | 1 | 2021-08-09T14:25:17.000Z | 2021-08-09T14:25:17.000Z | // { Driver Code Starts
// Program to find minimum number of platforms
// required on a railway station
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
//Function to find the minimum number of platforms required at the
//railway station such that no train waits.
int findPlatform(int arr[], int dep[], int n)
{
// Your code here
sort(arr,arr+n);
sort(dep,dep+n);
int i=1; // we are considring the 1 train is arived
int j=0; // its not dept
int max_plat = 1;
int plat = 1;
while(i<n && j<n)
{
if(arr[i]<=dep[j])
{
plat++;
i++;
}
else if(arr[i]>dep[j])
{
plat--;
j++;
}
max_plat = max(max_plat,plat);
}
return max_plat;
}
};
// { Driver Code Starts.
// Driver code
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n];
int dep[n];
for(int i=0;i<n;i++)
cin>>arr[i];
for(int j=0;j<n;j++){
cin>>dep[j];
}
Solution ob;
cout <<ob.findPlatform(arr, dep, n)<<endl;
}
return 0;
} // } Driver Code Ends | 19.264706 | 70 | 0.468702 | arpit456jain |
b73fce49595bcb5c50d37701f3db5ffd4bff29e6 | 2,052 | cpp | C++ | src/VisumScriptMain.cpp | Mokon/visum | 53f602fcf22eadd60f446d04a26b4a6e7217c052 | [
"RSA-MD"
] | null | null | null | src/VisumScriptMain.cpp | Mokon/visum | 53f602fcf22eadd60f446d04a26b4a6e7217c052 | [
"RSA-MD"
] | null | null | null | src/VisumScriptMain.cpp | Mokon/visum | 53f602fcf22eadd60f446d04a26b4a6e7217c052 | [
"RSA-MD"
] | null | null | null | /* Copyright (C) 2013-2016 David 'Mokon' Bond, All Rights Reserved */
#include <config.h>
#include <glog/logging.h>
#include <visum/entities/common/Bank.hpp>
#include <visum/entities/common/CreditCard.hpp>
#include <visum/entities/common/Person.hpp>
#include <visum/entities/Entity.hpp>
#include <visum/entities/EntityGraph.hpp>
#include <visum/events/actions/BankDepositFunds.hpp>
#include <visum/events/Event.hpp>
#include <visum/events/repeats/Once.hpp>
#include <visum/types/positions/Account.hpp>
namespace visum {
// TODO (005) remove this exe once we load from a text script
inline void printStaticGraph()
{
auto eg = std::make_shared<EntityGraph>(localTime());
auto person = std::make_shared<Person>("person");
auto bank = std::make_shared<Bank>("bank");
auto creditcard = std::make_shared<CreditCard>("creditcard");
eg->graph::Graph::add(person);
eg->graph::Graph::add(bank);
eg->graph::Graph::add(creditcard);
auto checking = bank->createAccount(person);
auto cc = creditcard->createAccount(person);
auto once = std::make_shared<Once>(eg->getSimulationTime());
auto event = std::make_shared<BankDepositFunds>(checking, bank,
person, Currency(100, Currency::Code::USD));
auto initialBalance = std::make_shared<Event>("initial balance",
once, event);
eg->add(initialBalance);
cereal::JSONOutputArchive ar(std::cout);
ar(cereal::make_nvp("entityGraph", eg));
}
}
int main(int argc, char* argv[])
{
int ret = EXIT_SUCCESS;
try {
assert(argc);
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
google::SetStderrLogging(google::INFO);
visum::printStaticGraph();
} catch(const std::exception& ex) {
LOG(ERROR) << ex.what() << std::endl;
ret = EXIT_FAILURE;
} catch (...) {
LOG(ERROR) << "Caught thrown" << std::endl;
ret = EXIT_FAILURE;
}
return ret;
}
| 30.626866 | 96 | 0.640838 | Mokon |
b7415fabb9cac20eba8cc19edb1a7fa026a177f7 | 1,139 | cpp | C++ | gpu_lib/external_gpu_algorithm.cpp | ARGO-group/Argo_CUDA | 7a15252906860f4a725e37b6add211f625b91869 | [
"MIT"
] | null | null | null | gpu_lib/external_gpu_algorithm.cpp | ARGO-group/Argo_CUDA | 7a15252906860f4a725e37b6add211f625b91869 | [
"MIT"
] | null | null | null | gpu_lib/external_gpu_algorithm.cpp | ARGO-group/Argo_CUDA | 7a15252906860f4a725e37b6add211f625b91869 | [
"MIT"
] | 1 | 2021-07-10T09:59:52.000Z | 2021-07-10T09:59:52.000Z | #include "external_gpu_algorithm.h"
#include <thread>
#include <config.h>
#include <hash_conversions.h>
#include <run_parallel.h>
#include <safe_counter.h>
#include <gpu_info.h>
#include "finder_kernel.cuh"
void external_gpu_algorithm(const std::vector<uint32_t> &motif_hashes,
const SequenceHashes &sequence_hashes,
std::vector<uint16_t> &out_motif_weights,
const GpuCudaParams ¶ms)
{
out_motif_weights.resize(motif_hashes.size(), 0);
uint32_t threads = (params.gpu_count > 0) ? params.gpu_count : 1;
SafeCounter motifs_counter(motif_hashes.size());
run_parallel(threads, [&](uint32_t thread_id) {
GpuExternalMemory gpu_memory(params, sequence_hashes);
while (true) {
const auto range = motifs_counter.get_and_increment_range_info(params.motif_range_size);
if (range.count() == 0) {
break;
}
motif_finder_gpu_external(
motif_hashes, gpu_memory, params, out_motif_weights, range.start, range.count(), thread_id);
}
});
} | 32.542857 | 108 | 0.639157 | ARGO-group |
b74bf15f46745c90202343ea77a3026b857f93c9 | 784 | cpp | C++ | Software/app/nixie_state.cpp | gotlaufs/rtu-nixie-clock | 7fe43f13deb8f5314ce19d00fe6623337c0d0df7 | [
"MIT"
] | null | null | null | Software/app/nixie_state.cpp | gotlaufs/rtu-nixie-clock | 7fe43f13deb8f5314ce19d00fe6623337c0d0df7 | [
"MIT"
] | 5 | 2019-02-19T22:23:19.000Z | 2019-02-19T22:27:27.000Z | Software/app/nixie_state.cpp | gotlaufs/rtu-nixie-clock | 7fe43f13deb8f5314ce19d00fe6623337c0d0df7 | [
"MIT"
] | null | null | null | // Nixie state class implementation
#include "nixie_state.h"
NixieState::NixieState(NixieClock & app_) : app(app_)
{
memset(&nixie_data, 0, sizeof(nixie_data_type));
}
void NixieState::writeTimeToNixie()
{
if (sec > 99)
{
// Blank tubes if too big digit
nixie_data.N6 = 10;
nixie_data.N5 = 10;
}
else
{
nixie_data.N6 = sec % 10;
nixie_data.N5 = sec / 10;
}
if (min > 99)
{
nixie_data.N4 = 10;
nixie_data.N3 = 10;
}
else
{
nixie_data.N4 = min % 10;
nixie_data.N3 = min / 10;
}
if (hour > 99)
{
nixie_data.N2 = 10;
nixie_data.N1 = 10;
}
else
{
nixie_data.N2 = hour % 10;
nixie_data.N1 = hour / 10;
}
}
| 17.422222 | 53 | 0.512755 | gotlaufs |
b74c2f463fe2ec1f3eab79af4dbebde53df4d597 | 90 | cpp | C++ | core/src/backend/task/FunctionDataTemplate.cpp | ExaBerries/spruce | 85845244f7d6cd5a662f0dbc9b4079a1230d9a4b | [
"MIT"
] | null | null | null | core/src/backend/task/FunctionDataTemplate.cpp | ExaBerries/spruce | 85845244f7d6cd5a662f0dbc9b4079a1230d9a4b | [
"MIT"
] | null | null | null | core/src/backend/task/FunctionDataTemplate.cpp | ExaBerries/spruce | 85845244f7d6cd5a662f0dbc9b4079a1230d9a4b | [
"MIT"
] | null | null | null | #include <backend/task/FunctionDataTemplate.h>
namespace spruce {
namespace task {
}
}
| 12.857143 | 46 | 0.744444 | ExaBerries |
b753e58ff00bc994c8dc9e157fe23b35e3166aa9 | 8,811 | hpp | C++ | include/mockturtle/algorithms/aqfp/detail/dag_util.hpp | shi27feng/mockturtle | 032dcd590b57040c5ff10d80b515353ffe822671 | [
"MIT"
] | null | null | null | include/mockturtle/algorithms/aqfp/detail/dag_util.hpp | shi27feng/mockturtle | 032dcd590b57040c5ff10d80b515353ffe822671 | [
"MIT"
] | null | null | null | include/mockturtle/algorithms/aqfp/detail/dag_util.hpp | shi27feng/mockturtle | 032dcd590b57040c5ff10d80b515353ffe822671 | [
"MIT"
] | null | null | null | /* mockturtle: C++ logic network library
* Copyright (C) 2018-2021 EPFL
*
* 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.
*/
/*!
\file dag_util.hpp
\brief Utilities for DAG generation
\author Dewmini Marakkalage
*/
#pragma once
#include <map>
#include <set>
#include <unordered_map>
#include <vector>
#include <mockturtle/utils/hash_functions.hpp>
namespace mockturtle
{
namespace detail
{
/*! \brief Computes and returns the frequency map for a given collection of elements.
* Use std::map instead of std::unordered_map because we use it as a key in a hash-table so the order is important to compute the hash
*/
template<typename ElemT>
inline std::map<ElemT, uint32_t> get_frequencies( const std::vector<ElemT>& elems )
{
std::map<ElemT, uint32_t> elem_counts;
std::for_each( elems.begin(), elems.end(), [&elem_counts]( auto e ) { elem_counts[e]++; } );
return elem_counts;
}
template<typename ElemT>
class partition_generator
{
using part = std::multiset<ElemT>;
using partition = std::multiset<part>;
using partition_set = std::set<partition>;
using inner_cache_key_t = std::vector<ElemT>;
using inner_cache_t = std::unordered_map<inner_cache_key_t, partition_set, hash<inner_cache_key_t>>;
using outer_cache_key_t = std::tuple<std::vector<uint32_t>, uint32_t, uint32_t>;
using outer_cache_t = std::unordered_map<outer_cache_key_t, inner_cache_t, hash<outer_cache_key_t>>;
public:
/*! \brief Computes and returns a set of partitions for a given list of elements
* such that no part contains any element `e` more than `max_counts[e]` times.
*/
partition_set operator()(
std::vector<int> elems,
const std::vector<uint32_t>& max_counts = {},
uint32_t max_parts = 0,
uint32_t max_part_size = 0 )
{
_elems = elems;
_max_counts = max_counts;
_max_parts = max_parts;
_max_part_size = max_part_size;
const outer_cache_key_t key = { _max_counts, _max_parts, _max_part_size };
partition_cache = outer_cache.insert( { key, inner_cache_t() } ).first;
return get_all_partitions();
}
private:
outer_cache_t outer_cache;
typename outer_cache_t::iterator partition_cache;
std::vector<ElemT> _elems;
std::vector<uint32_t> _max_counts;
uint32_t _max_parts;
uint32_t _max_part_size;
partition_set get_all_partitions()
{
if ( _elems.size() == 0 )
{
return { {} }; // return the empty partition.
}
inner_cache_key_t key = _elems;
if ( partition_cache->second.count( key ) )
{
return partition_cache->second.at( key );
}
partition_set result;
auto last = _elems.back();
_elems.pop_back();
auto temp = get_all_partitions();
for ( auto&& t : temp )
{
partition cpy;
// take 'last' in its own partition
cpy = t;
if ( _max_parts == 0u || _max_parts > cpy.size() )
{
cpy.insert( { last } );
result.insert( cpy );
}
// add 'last' to one of the existing partitions
for ( auto it = t.begin(); it != t.end(); )
{
if ( _max_counts.empty() || it->count( last ) < _max_counts[last] )
{
if ( _max_part_size == 0 || _max_part_size > it->size() )
{
cpy = t;
auto elem_it = cpy.find( *it );
auto cpy_elem = *elem_it;
cpy_elem.insert( last );
cpy.erase( elem_it );
cpy.insert( cpy_elem );
result.insert( cpy );
}
}
std::advance( it, t.count( *it ) );
}
}
return ( partition_cache->second[key] = result );
}
};
template<typename ElemT>
class partition_extender
{
using part = std::multiset<ElemT>;
using partition = std::multiset<part>;
using partition_set = std::set<partition>;
using inner_cache_key_t = std::vector<ElemT>;
using inner_cache_t = std::unordered_map<inner_cache_key_t, partition_set, hash<inner_cache_key_t>>;
using outer_cache_key_t = std::tuple<partition, std::vector<uint32_t>, uint32_t>;
using outer_cache_t = std::map<outer_cache_key_t, inner_cache_t>;
public:
/*! \brief Compute a list of different partitions that can be obtained by adding elements
* in `elems` to the parts of `base` such that no part contains any element `e` more than
* `max_counts[e]` times
*/
partition_set operator()( std::vector<ElemT> elems, partition base, const std::vector<uint32_t>& max_counts, uint32_t max_part_size = 0 )
{
_elems = elems;
_base = base;
_max_counts = max_counts;
_max_part_size = max_part_size;
const outer_cache_key_t key = { _base, _max_counts, _max_part_size };
partition_cache = outer_cache.insert( { key, inner_cache_t() } ).first;
return extend_partitions();
}
private:
outer_cache_t outer_cache;
typename outer_cache_t::iterator partition_cache;
std::vector<ElemT> _elems;
partition _base;
std::vector<uint32_t> _max_counts;
uint32_t _max_part_size;
partition_set extend_partitions()
{
if ( _elems.size() == 0 )
{
return { _base };
}
inner_cache_key_t key = _elems;
if ( partition_cache->second.count( key ) )
{
return partition_cache->second.at( key );
}
partition_set result;
auto last = _elems.back();
_elems.pop_back();
auto temp = extend_partitions();
for ( auto&& t : temp )
{
partition cpy;
for ( auto it = t.begin(); it != t.end(); )
{
if ( it->count( last ) < _max_counts.at( last ) )
{
if ( _max_part_size == 0 || _max_part_size > it->size() )
{
cpy = t;
auto elem_it = cpy.find( *it );
auto cpy_elem = *elem_it;
cpy_elem.insert( last );
cpy.erase( elem_it );
cpy.insert( cpy_elem );
result.insert( cpy );
}
}
std::advance( it, t.count( *it ) );
}
}
return ( partition_cache->second[key] = result );
}
};
template<typename ElemT>
struct sublist_generator
{
using sub_list_cache_key_t = std::map<ElemT, uint32_t>;
public:
/**
* \brief Given a list of elements `elems`, generate all sub lists of those elements.
* Ex: if `elems` = [1, 2, 2, 3], this will generate the following lists:
* [0], [1], [1, 2], [1, 2, 2], [1, 2, 2, 3], [1, 2, 3], [1, 3], [2], [2, 2], [2, 2, 3], [2, 3], and [3].
*/
std::set<std::vector<ElemT>> operator()( std::vector<ElemT> elems )
{
elem_counts = get_frequencies( elems );
return get_sub_lists_recur();
}
private:
std::unordered_map<sub_list_cache_key_t, std::set<std::vector<ElemT>>, hash<sub_list_cache_key_t>> sub_list_cache;
std::map<ElemT, uint32_t> elem_counts;
std::set<std::vector<ElemT>> get_sub_lists_recur()
{
if ( elem_counts.size() == 0u )
{
return { {} };
}
sub_list_cache_key_t key = elem_counts;
if ( !sub_list_cache.count( key ) )
{
auto last = std::prev( elem_counts.end() );
auto last_elem = last->first;
auto last_count = last->second;
elem_counts.erase( last );
std::set<std::vector<int>> result;
std::vector<int> t;
for ( auto i = last_count; i > 0; --i )
{
t.push_back( last_elem );
result.insert( t ); // insert a copy of t, and note that t is already sorted.
}
auto temp = get_sub_lists_recur();
for ( std::vector<int> t : temp )
{
result.insert( t );
for ( auto i = last_count; i > 0; --i )
{
t.push_back( last_elem );
std::sort( t.begin(), t.end() );
result.insert( t );
}
}
sub_list_cache[key] = result;
}
return sub_list_cache[key];
}
};
} // namespace detail
} // namespace mockturtle
| 27.794953 | 139 | 0.637726 | shi27feng |
b75582d23033bd9636bd190462cb22da89e5bd0b | 61,137 | cpp | C++ | vphysics_bullet/Physics_Environment.cpp | SwagSoftware/Kisak-Strike | 7498c886b5199b37cbd156ceac9377ecac73b982 | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | vphysics_bullet/Physics_Environment.cpp | SwagSoftware/Kisak-Strike | 7498c886b5199b37cbd156ceac9377ecac73b982 | [
"Unlicense"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | vphysics_bullet/Physics_Environment.cpp | SwagSoftware/Kisak-Strike | 7498c886b5199b37cbd156ceac9377ecac73b982 | [
"Unlicense"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z | #include "StdAfx.h"
#include <cmodel.h>
#include <cstring>
#include "Physics_Environment.h"
#include "Physics.h"
#include "Physics_Object.h"
#include "Physics_ShadowController.h"
#include "Physics_PlayerController.h"
#include "Physics_FluidController.h"
#include "Physics_DragController.h"
#include "Physics_MotionController.h"
#include "Physics_Constraint.h"
#include "Physics_Collision.h"
#include "Physics_VehicleController.h"
#include "miscmath.h"
#include "convert.h"
#if DEBUG_DRAW
#include "DebugDrawer.h"
#endif
#include "BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h"
#include "BulletDynamics/MLCPSolvers/btMLCPSolver.h"
#include "BulletDynamics/MLCPSolvers/btLemkeSolver.h"
#include "BulletDynamics/MLCPSolvers/btDantzigSolver.h"
#include "BulletDynamics/MLCPSolvers/btSolveProjectedGaussSeidel.h"
#include "BulletDynamics/ConstraintSolver/btNNCGConstraintSolver.h"
#include "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolverMt.h"
#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorldMt.h"
#include "BulletCollision/CollisionDispatch/btCollisionDispatcherMt.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
/*****************************
* MISC. CLASSES
*****************************/
class IDeleteQueueItem {
public:
virtual void Delete() = 0;
};
template <typename T>
class CDeleteProxy : public IDeleteQueueItem {
public:
CDeleteProxy(T *pItem) : m_pItem(pItem) {}
virtual void Delete() override { delete m_pItem; }
private:
T *m_pItem;
};
class CDeleteQueue {
public:
void Add(IDeleteQueueItem *pItem) {
m_list.AddToTail(pItem);
}
template <typename T>
void QueueForDelete(T *pItem) {
Add(new CDeleteProxy<T>(pItem));
}
void DeleteAll() {
for (int i = m_list.Count()-1; i >= 0; --i) {
m_list[i]->Delete();
delete m_list[i];
}
m_list.RemoveAll();
}
private:
CUtlVector<IDeleteQueueItem *> m_list;
};
bool CCollisionSolver::needBroadphaseCollision(btBroadphaseProxy *proxy0, btBroadphaseProxy *proxy1) const {
btRigidBody *body0 = btRigidBody::upcast(static_cast<btCollisionObject*>(proxy0->m_clientObject));
btRigidBody *body1 = btRigidBody::upcast(static_cast<btCollisionObject*>(proxy1->m_clientObject));
if(!body0 || !body1)
{
// Check if one of them is a soft body
// btCollisionObject *colObj0 = static_cast<btCollisionObject*>(proxy0->m_clientObject);
// btCollisionObject *colObj1 = static_cast<btCollisionObject*>(proxy1->m_clientObject);
// if (colObj0->getInternalType() & btCollisionObject::CO_SOFT_BODY || colObj1->getInternalType() & btCollisionObject::CO_SOFT_BODY) {
// return true;
// }
return (body0 != nullptr && !body0->isStaticObject()) || (body1 != nullptr && !body1->isStaticObject());
}
CPhysicsObject *pObject0 = static_cast<CPhysicsObject*>(body0->getUserPointer());
CPhysicsObject *pObject1 = static_cast<CPhysicsObject*>(body1->getUserPointer());
bool collides = NeedsCollision(pObject0, pObject1) &&
(proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
if (!collides) {
// Clean this pair from the cache
m_pEnv->GetBulletEnvironment()->getBroadphase()->getOverlappingPairCache()->removeOverlappingPair(proxy0, proxy1, m_pEnv->GetBulletEnvironment()->getDispatcher());
}
return collides;
}
bool CCollisionSolver::NeedsCollision(CPhysicsObject *pObject0, CPhysicsObject *pObject1) const {
if (pObject0 && pObject1) {
// No static->static collisions
if (pObject0->IsStatic() && pObject1->IsStatic())
{
return false;
}
// No shadow->shadow collisions
if (pObject0->GetShadowController() && pObject1->GetShadowController())
{
return false;
}
if (!pObject0->IsCollisionEnabled() || !pObject1->IsCollisionEnabled())
{
return false;
}
if ((pObject0->GetCallbackFlags() & CALLBACK_ENABLING_COLLISION) || (pObject1->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE))
{
return false;
}
// No kinematic->static collisions
if ((pObject0->GetObject()->getCollisionFlags() & btCollisionObject::CF_KINEMATIC_OBJECT && pObject1->IsStatic())
|| (pObject1->GetObject()->getCollisionFlags() & btCollisionObject::CF_KINEMATIC_OBJECT && pObject0->IsStatic()))
{
return false;
}
if ((pObject1->GetCallbackFlags() & CALLBACK_ENABLING_COLLISION) || (pObject0->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE))
{
return false;
}
// Most expensive call, do this check last
if (m_pSolver && !m_pSolver->ShouldCollide(pObject0, pObject1, pObject0->GetGameData(), pObject1->GetGameData()))
{
return false;
}
}
else
{
// One of the objects has no phys object...
if (pObject0 && !pObject0->IsCollisionEnabled())
return false;
if (pObject1 && !pObject1->IsCollisionEnabled())
return false;
}
return true;
}
void SerializeWorld_f(const CCommand &args) {
if (args.ArgC() != 3) {
Msg("Usage: bt_serialize <index> <name>\n");
return;
}
CPhysicsEnvironment *pEnv = (CPhysicsEnvironment *)g_Physics.GetActiveEnvironmentByIndex(atoi(args.Arg(2)));
if (pEnv) {
btDiscreteDynamicsWorld *pWorld = static_cast<btDiscreteDynamicsWorld*>(pEnv->GetBulletEnvironment());
Assert(pWorld);
btSerializer *pSerializer = new btDefaultSerializer;
pWorld->serialize(pSerializer);
// FIXME: We shouldn't be using this. Find the appropiate method from valve interfaces.
const char *pName = args.Arg(2);
FILE *pFile = fopen(pName, "wb");
if (pFile) {
fwrite(pSerializer->getBufferPointer(), pSerializer->getCurrentBufferSize(), 1, pFile);
fclose(pFile);
} else {
Warning("Couldn't open \"%s\" for writing!\n", pName);
}
} else {
Warning("Invalid environment index supplied!\n");
}
}
static ConCommand cmd_serializeworld("bt_serialize", SerializeWorld_f, "Serialize environment by index (usually 0=server, 1=client)\n\tDumps the file out to the exe directory.");
/*******************************
* CLASS CObjectTracker
*******************************/
class CObjectTracker {
public:
CObjectTracker(CPhysicsEnvironment *pEnv, IPhysicsObjectEvent *pObjectEvents) {
m_pEnv = pEnv;
m_pObjEvents = pObjectEvents;
}
int GetActiveObjectCount() const {
return m_activeObjects.Count();
}
void GetActiveObjects(IPhysicsObject **pOutputObjectList) const {
if (!pOutputObjectList) return;
const int size = m_activeObjects.Count();
for (int i = 0; i < size; i++) {
pOutputObjectList[i] = m_activeObjects[i];
}
}
void SetObjectEventHandler(IPhysicsObjectEvent *pEvents) {
m_pObjEvents = pEvents;
}
void ObjectRemoved(CPhysicsObject *pObject) {
m_activeObjects.FindAndRemove(pObject);
}
void Tick() {
btDiscreteDynamicsWorld *pBulletEnv = m_pEnv->GetBulletEnvironment();
btCollisionObjectArray &colObjArray = pBulletEnv->getCollisionObjectArray();
for (int i = 0; i < colObjArray.size(); i++) {
CPhysicsObject *pObj = static_cast<CPhysicsObject*>(colObjArray[i]->getUserPointer());
if (!pObj) continue; // Internal object that the game doesn't need to know about
Assert(*(char *)pObj != 0xDD); // Make sure the object isn't deleted (only works in debug builds) TODO: This can be removed, result is always true
// Don't add objects marked for delete
if (pObj->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) {
continue;
}
if (colObjArray[i]->getActivationState() != pObj->GetLastActivationState()) {
const int newState = colObjArray[i]->getActivationState();
// Not a state we want to track.
if (newState == WANTS_DEACTIVATION)
continue;
if (m_pObjEvents) {
switch (newState) {
// FIXME: Objects may call objectwake twice if they go from disable_deactivation -> active_tag
case DISABLE_DEACTIVATION:
case ACTIVE_TAG:
m_pObjEvents->ObjectWake(pObj);
break;
case ISLAND_SLEEPING:
m_pObjEvents->ObjectSleep(pObj);
break;
case DISABLE_SIMULATION:
// Don't call ObjectSleep on DISABLE_SIMULATION on purpose.
break;
default:
NOT_IMPLEMENTED;
assert(false);
}
}
switch (newState) {
case DISABLE_DEACTIVATION:
case ACTIVE_TAG:
// Don't add the object twice!
if (m_activeObjects.Find(pObj) == -1)
m_activeObjects.AddToTail(pObj);
break;
case DISABLE_SIMULATION:
case ISLAND_SLEEPING:
m_activeObjects.FindAndRemove(pObj);
break;
default:
NOT_IMPLEMENTED;
assert(false);
}
pObj->SetLastActivationState(newState);
}
}
}
private:
CPhysicsEnvironment *m_pEnv;
IPhysicsObjectEvent *m_pObjEvents;
CUtlVector<IPhysicsObject *> m_activeObjects;
};
/*******************************
* CLASS CPhysicsCollisionData
*******************************/
class CPhysicsCollisionData : public IPhysicsCollisionData {
public:
CPhysicsCollisionData(btManifoldPoint *manPoint) {
ConvertDirectionToHL(manPoint->m_normalWorldOnB, m_surfaceNormal);
ConvertPosToHL(manPoint->getPositionWorldOnA(), m_contactPoint);
ConvertPosToHL(manPoint->m_lateralFrictionDir1, m_contactSpeed); // FIXME: Need the correct variable from the manifold point
}
// normal points toward second object (object index 1)
void GetSurfaceNormal(Vector &out) override
{
out = m_surfaceNormal;
}
// contact point of collision (in world space)
void GetContactPoint(Vector &out) override
{
out = m_contactPoint;
}
// speed of surface 1 relative to surface 0 (in world space)
void GetContactSpeed(Vector &out) override
{
out = m_contactSpeed;
}
private:
Vector m_surfaceNormal;
Vector m_contactPoint;
Vector m_contactSpeed;
};
/*********************************
* CLASS CCollisionEventListener
*********************************/
class CCollisionEventListener : public btSolveCallback {
public:
CCollisionEventListener(CPhysicsEnvironment *pEnv) {
m_pEnv = pEnv;
m_pCallback = NULL;
}
// TODO: Optimize this, heavily!
void preSolveContact(btSolverBody *body0, btSolverBody *body1, btManifoldPoint *cp) override
{
CPhysicsObject *pObj0 = static_cast<CPhysicsObject*>(body0->m_originalColObj->getUserPointer());
CPhysicsObject *pObj1 = static_cast<CPhysicsObject*>(body1->m_originalColObj->getUserPointer());
if (pObj0->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE || pObj1->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE)
return;
const unsigned int flags0 = pObj0->GetCallbackFlags();
const unsigned int flags1 = pObj1->GetCallbackFlags();
// Clear it
memset(&m_tmpEvent, 0, sizeof(m_tmpEvent));
m_tmpEvent.collisionSpeed = 0.f; // Invalid pre-collision
m_tmpEvent.deltaCollisionTime = 10.f; // FIXME: Find a way to track the real delta time
m_tmpEvent.isCollision = (flags0 & flags1 & CALLBACK_GLOBAL_COLLISION); // False when either one of the objects don't have CALLBACK_GLOBAL_COLLISION
m_tmpEvent.isShadowCollision = ((flags0 ^ flags1) & CALLBACK_SHADOW_COLLISION) != 0; // True when only one of the objects is a shadow (if both are shadow, it's handled by the game)
m_tmpEvent.pObjects[0] = pObj0;
m_tmpEvent.pObjects[1] = pObj1;
m_tmpEvent.surfaceProps[0] = pObj0->GetMaterialIndex();
m_tmpEvent.surfaceProps[1] = pObj1->GetMaterialIndex();
if ((pObj0->IsStatic() && !(flags1 & CALLBACK_GLOBAL_COLLIDE_STATIC)) || (pObj1->IsStatic() && !(flags0 & CALLBACK_GLOBAL_COLLIDE_STATIC))) {
m_tmpEvent.isCollision = false;
}
if (!m_tmpEvent.isCollision && !m_tmpEvent.isShadowCollision) return;
CPhysicsCollisionData data(cp);
m_tmpEvent.pInternalData = &data;
// Give the game its stupid velocities
if (body0->m_originalBody) {
m_tmpVelocities[0] = body0->m_originalBody->getLinearVelocity();
m_tmpAngVelocities[0] = body0->m_originalBody->getAngularVelocity();
body0->m_originalBody->setLinearVelocity(m_tmpVelocities[0] + body0->internalGetDeltaLinearVelocity());
body0->m_originalBody->setAngularVelocity(m_tmpAngVelocities[0] + body0->internalGetDeltaAngularVelocity());
}
if (body1->m_originalBody) {
m_tmpVelocities[1] = body1->m_originalBody->getLinearVelocity();
m_tmpAngVelocities[1] = body1->m_originalBody->getAngularVelocity();
body1->m_originalBody->setLinearVelocity(m_tmpVelocities[1] + body1->internalGetDeltaLinearVelocity());
body1->m_originalBody->setAngularVelocity(m_tmpAngVelocities[1] + body1->internalGetDeltaAngularVelocity());
}
if (m_pCallback)
m_pCallback->PreCollision(&m_tmpEvent);
// Restore the velocities
// UNDONE: No need, postSolveContact will do this.
/*
if (body0->m_originalBody) {
body0->m_originalBody->setLinearVelocity(m_tmpVelocities[0]);
body0->m_originalBody->setAngularVelocity(m_tmpAngVelocities[0]);
}
if (body1->m_originalBody) {
body1->m_originalBody->setLinearVelocity(m_tmpVelocities[1]);
body1->m_originalBody->setAngularVelocity(m_tmpAngVelocities[1]);
}
*/
}
// TODO: Optimize this, heavily!
void postSolveContact(btSolverBody *body0, btSolverBody *body1, btManifoldPoint *cp) override
{
btRigidBody *rb0 = btRigidBody::upcast(body0->m_originalColObj);
btRigidBody *rb1 = btRigidBody::upcast(body1->m_originalColObj);
// FIXME: Problem with bullet code, only one solver body created for static objects!
// There could be more than one static object created by us!
CPhysicsObject *pObj0 = static_cast<CPhysicsObject*>(body0->m_originalColObj->getUserPointer());
CPhysicsObject *pObj1 = static_cast<CPhysicsObject*>(body1->m_originalColObj->getUserPointer());
if (pObj0->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE || pObj1->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE)
return;
//unsigned int flags0 = pObj0->GetCallbackFlags();
//unsigned int flags1 = pObj1->GetCallbackFlags();
const btScalar combinedInvMass = rb0->getInvMass() + rb1->getInvMass();
m_tmpEvent.collisionSpeed = BULL2HL(cp->m_appliedImpulse * combinedInvMass); // Speed of body 1 rel to body 2 on axis of constraint normal
// FIXME: Find a way to track the real delta time
// IVP tracks this delta time between object pairs
// lwss: I had a method in here to track the delta times between the pairs.
// I wondered what it was for, turns out it's all 95% for a sound hack
// in which they don't play sounds too often on 2 colliding objects.
// so for now, I'll just leave this as is and play all physics sounds
m_tmpEvent.deltaCollisionTime = 10.f;
//lwss hack - ragdoll sounds are a bit too loud
if( pObj0->GetCollisionHints() & COLLISION_HINT_RAGDOLL || pObj1->GetCollisionHints() & COLLISION_HINT_RAGDOLL )
{
// value determined from testing :))
m_tmpEvent.collisionSpeed *= 0.4f;
}
//lwss end
/*
m_tmpEvent.isCollision = (flags0 & flags1 & CALLBACK_GLOBAL_COLLISION); // False when either one of the objects don't have CALLBACK_GLOBAL_COLLISION
m_tmpEvent.isShadowCollision = (flags0 ^ flags1) & CALLBACK_SHADOW_COLLISION; // True when only one of the objects is a shadow
m_tmpEvent.pObjects[0] = pObj0;
m_tmpEvent.pObjects[1] = pObj1;
m_tmpEvent.surfaceProps[0] = pObj0 ? pObj0->GetMaterialIndex() : 0;
m_tmpEvent.surfaceProps[1] = pObj1 ? pObj1->GetMaterialIndex() : 0;
*/
if (!m_tmpEvent.isCollision && !m_tmpEvent.isShadowCollision) return;
CPhysicsCollisionData data(cp);
m_tmpEvent.pInternalData = &data;
// Give the game its stupid velocities
if (body0->m_originalBody) {
body0->m_originalBody->setLinearVelocity(m_tmpVelocities[0] + body0->internalGetDeltaLinearVelocity());
body0->m_originalBody->setAngularVelocity(m_tmpAngVelocities[0] + body0->internalGetDeltaAngularVelocity());
}
if (body1->m_originalBody) {
body1->m_originalBody->setLinearVelocity(m_tmpVelocities[1] + body1->internalGetDeltaLinearVelocity());
body1->m_originalBody->setAngularVelocity(m_tmpAngVelocities[1] + body1->internalGetDeltaAngularVelocity());
}
if (m_pCallback)
m_pCallback->PostCollision(&m_tmpEvent);
// Restore the velocities
if (body0->m_originalBody) {
body0->m_originalBody->setLinearVelocity(m_tmpVelocities[0]);
body0->m_originalBody->setAngularVelocity(m_tmpAngVelocities[0]);
}
if (body1->m_originalBody) {
body1->m_originalBody->setLinearVelocity(m_tmpVelocities[1]);
body1->m_originalBody->setAngularVelocity(m_tmpAngVelocities[1]);
}
}
void friction(btSolverBody *body0, btSolverBody *body1, btSolverConstraint *constraint) override
{
/*
btRigidBody *rb0 = btRigidBody::upcast(body0->m_originalColObj);
btRigidBody *rb1 = btRigidBody::upcast(body1->m_originalColObj);
// FIXME: Problem with bullet code, only one solver body created for static objects!
// There could be more than one static object created by us!
CPhysicsObject *pObj0 = (CPhysicsObject *)body0->m_originalColObj->getUserPointer();
CPhysicsObject *pObj1 = (CPhysicsObject *)body1->m_originalColObj->getUserPointer();
unsigned int flags0 = pObj0->GetCallbackFlags();
unsigned int flags1 = pObj1->GetCallbackFlags();
// Don't do the callback if it's disabled on either object
if (!(flags0 & flags1 & CALLBACK_GLOBAL_FRICTION)) return;
// If the solver uses 2 friction directions
btSolverConstraint *constraint2 = NULL;
if (m_pEnv->GetBulletEnvironment()->getSolverInfo().m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS) {
constraint2 = constraint + 1; // Always stored after the first one
}
// Calculate the energy consumed
float totalImpulse = constraint->m_appliedImpulse + (constraint2 ? constraint2->m_appliedImpulse : 0);
totalImpulse *= rb0->getInvMass(); // Get just the velocity
totalImpulse *= totalImpulse; // Square it
totalImpulse *= SAFE_DIVIDE(.5, rb0->getInvMass()); // Add back the mass (1/2*mv^2)
if (m_pCallback)
m_pCallback->Friction(pObj0)
*/
}
void SetCollisionEventCallback(IPhysicsCollisionEvent *pCallback) {
m_pCallback = pCallback;
}
private:
CPhysicsEnvironment *m_pEnv;
IPhysicsCollisionEvent *m_pCallback;
// Temp. variables saved between Pre/PostCollision
btVector3 m_tmpVelocities[2];
btVector3 m_tmpAngVelocities[2];
vcollisionevent_t m_tmpEvent{};
};
/*******************************
* Bullet Dynamics World Static References
*******************************/
// TODO: See if this dynamics world pointer is right, it's assigned twice
static bool gBulletDynamicsWorldGuard = false;
static btDynamicsWorld* gBulletDynamicsWorld = NULL;
#ifdef BT_THREADSAFE
static bool gMultithreadedWorld = true;
static SolverType gSolverType = SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT;
#else
static bool gMultithreadedWorld = false;
static SolverType gSolverType = SOLVER_TYPE_SEQUENTIAL_IMPULSE;
#endif
static int gSolverMode = SOLVER_SIMD | SOLVER_USE_WARMSTARTING |
/* SOLVER_RANDMIZE_ORDER | SOLVER_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS | SOLVER_USE_2_FRICTION_DIRECTIONS |*/ 0;
/*******************************
* Bullet Dynamics World ConVars
*******************************/
// bt_solveriterations
static void cvar_solver_iterations_Change(IConVar *var, const char *pOldValue, float flOldValue);
static ConVar cvar_solver_iterations("bt_solver_iterations", "4", FCVAR_REPLICATED, "Number of collision solver iterations", true, 1, true, 32, cvar_solver_iterations_Change);
static void cvar_solver_iterations_Change(IConVar *var, const char *pOldValue, float flOldValue)
{
if(gBulletDynamicsWorld)
{
gBulletDynamicsWorld->getSolverInfo().m_numIterations = cvar_solver_iterations.GetInt();
Msg("Solver iteration count is changed from %i to %i\n", static_cast<int>(flOldValue), cvar_solver_iterations.GetInt());
}
}
// bt_solver_residualthreshold
static void cvar_solver_residualthreshold_Change(IConVar *var, const char *pOldValue, float flOldValue);
static ConVar cvar_solver_residualthreshold("bt_solver_residualthreshold", "0.0", FCVAR_REPLICATED, "Solver leastSquaresResidualThreshold (used to run fewer solver iterations when convergence is good)", true, 0.0f, true, 0.25f, cvar_solver_residualthreshold_Change);
static void cvar_solver_residualthreshold_Change(IConVar *var, const char *pOldValue, float flOldValue)
{
if (gBulletDynamicsWorld)
{
gBulletDynamicsWorld->getSolverInfo().m_leastSquaresResidualThreshold = cvar_solver_residualthreshold.GetFloat();
Msg("Solver residual threshold is changed from %f to %f\n", flOldValue, cvar_solver_residualthreshold.GetFloat());
}
}
// bt_substeps
static ConVar bt_max_world_substeps("bt_max_world_substeps", "5", FCVAR_REPLICATED, "Maximum amount of catchup simulation-steps BulletPhysics is allowed to do per Simulation()", true, 1, true, 12);
// Threadsafe specific console variables
#ifdef BT_THREADSAFE
// bt_threadcount
static void cvar_threadcount_Change(IConVar *var, const char *pOldValue, float flOldValue);
static ConVar cvar_threadcount("bt_threadcount", "1", FCVAR_REPLICATED, "Number of cores utilized by bullet task scheduler. By default, TBB sets this to optimal value", true, 1, true, static_cast<float>(BT_MAX_THREAD_COUNT), cvar_threadcount_Change);
static void cvar_threadcount_Change(IConVar *var, const char *pOldValue, float flOldValue)
{
const int newNumThreads = MIN(cvar_threadcount.GetInt(), int(BT_MAX_THREAD_COUNT));
const int oldNumThreads = btGetTaskScheduler()->getNumThreads();
// only call when the thread count is different
if (newNumThreads != oldNumThreads)
{
btGetTaskScheduler()->setNumThreads(newNumThreads);
Msg("Changed %s task scheduler thread count from %i to %i\n", btGetTaskScheduler()->getName(), oldNumThreads, newNumThreads);
}
}
// bt_island_batchingthreshold
static void cvar_island_batchingthreshold_Change(IConVar *var, const char *pOldValue, float flOldValue);
static ConVar cvar_island_batchingthreshold("bt_solver_islandbatchingthreshold", std::to_string(btSequentialImpulseConstraintSolverMt::s_minimumContactManifoldsForBatching).c_str(), FCVAR_REPLICATED, "If the number of manifolds that an island have reaches to that value, they will get batched", true, 1, true, 2000, cvar_island_batchingthreshold_Change);
static void cvar_island_batchingthreshold_Change(IConVar *var, const char *pOldValue, float flOldValue)
{
btSequentialImpulseConstraintSolverMt::s_minimumContactManifoldsForBatching = cvar_island_batchingthreshold.GetInt();
Msg("Island batching threshold is changed from %i to %i\n", static_cast<int>(flOldValue), cvar_island_batchingthreshold.GetInt());
}
// bt_solver_minbatchsize
static void cvar_solver_minbatchsize_Change(IConVar *var, const char *pOldValue, float flOldValue);
static ConVar cvar_solver_minbatchsize("bt_solver_minbatchsize", std::to_string(btSequentialImpulseConstraintSolverMt::s_minBatchSize).c_str(), FCVAR_REPLICATED, "Minimum size of batches for solver", true, 1, true, 1000, cvar_solver_minbatchsize_Change);
// bt_solver_maxbatchsize
static void cvar_solver_maxbatchsize_Change(IConVar *var, const char *pOldValue, float flOldValue);
static ConVar cvar_solver_maxbatchsize("bt_solver_maxbatchsize", std::to_string(btSequentialImpulseConstraintSolverMt::s_maxBatchSize).c_str(), FCVAR_REPLICATED, "Maximum size of batches for solver", true, 1, true, 1000, cvar_solver_maxbatchsize_Change);
static void cvar_solver_minbatchsize_Change(IConVar *var, const char *pOldValue, float flOldValue)
{
cvar_solver_maxbatchsize.SetValue(MAX(cvar_solver_maxbatchsize.GetInt(), cvar_solver_minbatchsize.GetInt()));
btSequentialImpulseConstraintSolverMt::s_minBatchSize = cvar_solver_minbatchsize.GetInt();
btSequentialImpulseConstraintSolverMt::s_maxBatchSize = cvar_solver_maxbatchsize.GetInt();
Msg("Min batch size for solver is changed from %i to %i\n", flOldValue, cvar_solver_minbatchsize.GetFloat());
}
static void cvar_solver_maxbatchsize_Change(IConVar *var, const char *pOldValue, float flOldValue)
{
cvar_solver_minbatchsize.SetValue(MIN(cvar_solver_maxbatchsize.GetInt(), cvar_solver_minbatchsize.GetInt()));
btSequentialImpulseConstraintSolverMt::s_minBatchSize = cvar_solver_minbatchsize.GetInt();
btSequentialImpulseConstraintSolverMt::s_maxBatchSize = cvar_solver_maxbatchsize.GetInt();
Msg("Max batch size for solver is changed from %i to %i\n", flOldValue, cvar_solver_maxbatchsize.GetFloat());
}
#endif
/*******************************
* CLASS CPhysicsEnvironment
*******************************/
CPhysicsEnvironment::CPhysicsEnvironment() {
m_multithreadedWorld = false;
m_multithreadCapable = false;
m_deleteQuick = false;
m_bUseDeleteQueue = false;
m_inSimulation = false;
m_bConstraintNotify = false;
m_pDebugOverlay = NULL;
m_pConstraintEvent = NULL;
m_pObjectEvent = NULL;
m_pObjectTracker = NULL;
m_pCollisionEvent = NULL;
m_pThreadManager = NULL;
m_pBulletBroadphase = NULL;
m_pBulletConfiguration = NULL;
m_pBulletDispatcher = NULL;
m_pBulletDynamicsWorld = NULL;
m_pBulletGhostCallback = NULL;
m_pBulletSolver = NULL;
m_timestep = 0.f;
m_invPSIScale = 0.f;
m_simPSICurrent = 0;
m_simPSI = 0;
m_simTime = 0.0f;
#ifdef BT_THREADSAFE
// Initilize task scheduler, we will be using TBB
// btSetTaskScheduler(btGetSequentialTaskScheduler()); // Can be used for debugging purposes
//btSetTaskScheduler(btGetTBBTaskScheduler());
//const int maxNumThreads = btGetTBBTaskScheduler()->getMaxNumThreads();
//btGetTBBTaskScheduler()->setNumThreads(maxNumThreads);
btSetTaskScheduler(btGetOpenMPTaskScheduler());
//lwss: this is silly to use all cpu threads, how about just 2
btGetOpenMPTaskScheduler()->setNumThreads(2);
cvar_threadcount.SetValue(2);
#endif
// Create a fresh new dynamics world
CreateEmptyDynamicsWorld();
}
CPhysicsEnvironment::~CPhysicsEnvironment() {
#if DEBUG_DRAW
delete m_debugdraw;
#endif
CPhysicsEnvironment::SetQuickDelete(true);
for (int i = m_objects.Count() - 1; i >= 0; --i) {
delete m_objects[i];
}
m_objects.RemoveAll();
CPhysicsEnvironment::CleanupDeleteList();
delete m_pDeleteQueue;
delete m_pPhysicsDragController;
delete m_pBulletDynamicsWorld;
delete m_pBulletSolver;
delete m_pBulletBroadphase;
delete m_pBulletDispatcher;
delete m_pBulletConfiguration;
delete m_pBulletGhostCallback;
// delete m_pCollisionListener;
delete m_pCollisionSolver;
delete m_pObjectTracker;
}
btConstraintSolver* createSolverByType(SolverType t)
{
btMLCPSolverInterface* mlcpSolver = NULL;
switch (t)
{
case SOLVER_TYPE_SEQUENTIAL_IMPULSE:
return new btSequentialImpulseConstraintSolver();
case SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT:
return new btSequentialImpulseConstraintSolverMt();
case SOLVER_TYPE_NNCG:
return new btNNCGConstraintSolver();
case SOLVER_TYPE_MLCP_PGS:
mlcpSolver = new btSolveProjectedGaussSeidel();
break;
case SOLVER_TYPE_MLCP_DANTZIG:
mlcpSolver = new btDantzigSolver();
break;
case SOLVER_TYPE_MLCP_LEMKE:
mlcpSolver = new btLemkeSolver();
break;
default:
assert(false);
break;
}
if (mlcpSolver)
{
return new btMLCPSolver(mlcpSolver);
}
return NULL;
}
IVPhysicsDebugOverlay *g_pDebugOverlay = NULL;
void CPhysicsEnvironment::CreateEmptyDynamicsWorld()
{
if(gBulletDynamicsWorldGuard)
{
gBulletDynamicsWorld = m_pBulletDynamicsWorld;
}
else
{
gBulletDynamicsWorldGuard = true;
}
m_pCollisionListener = new CCollisionEventListener(this);
m_solverType = gSolverType;
#ifdef BT_THREADSAFE
btAssert(btGetTaskScheduler() != NULL);
if (btGetTaskScheduler() != NULL && btGetTaskScheduler()->getNumThreads() > 1)
{
m_multithreadCapable = true;
}
#endif
if (gMultithreadedWorld)
{
#ifdef BT_THREADSAFE
btAssert(btGetTaskScheduler() != NULL);
m_pBulletDispatcher = NULL;
btDefaultCollisionConstructionInfo cci;
cci.m_defaultMaxPersistentManifoldPoolSize = 80000;
cci.m_defaultMaxCollisionAlgorithmPoolSize = 80000;
m_pBulletConfiguration = new btDefaultCollisionConfiguration(cci);
// Dispatcher generates around 360 pair objects on average. Maximize thread usage by using this value
m_pBulletDispatcher = new btCollisionDispatcherMt(m_pBulletConfiguration, 360 / cvar_threadcount.GetInt() + 1);
m_pBulletBroadphase = new btDbvtBroadphase();
// Enable deferred collide, increases performance with many collisions calculations going on at the same time
static_cast<btDbvtBroadphase*>(m_pBulletBroadphase)->m_deferedcollide = true;
btConstraintSolverPoolMt* solverPool;
{
SolverType poolSolverType = m_solverType;
if (poolSolverType == SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT)
{
// pool solvers shouldn't be parallel solvers, we don't allow that kind of
// nested parallelism because of performance issues
poolSolverType = SOLVER_TYPE_SEQUENTIAL_IMPULSE;
}
CUtlVector<btConstraintSolver*> solvers;
const int threadCount = cvar_threadcount.GetInt();
for (int i = 0; i < threadCount; ++i)
{
auto solver = createSolverByType(poolSolverType);
solver->setSolveCallback(m_pCollisionListener);
solvers.AddToTail(solver);
}
solverPool = new btConstraintSolverPoolMt(solvers.Base(), threadCount);
m_pBulletSolver = solverPool;
m_pBulletSolver->setSolveCallback(m_pCollisionListener);
}
btSequentialImpulseConstraintSolverMt* solverMt = NULL;
if (m_solverType == SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT)
{
solverMt = new btSequentialImpulseConstraintSolverMt();
}
btDiscreteDynamicsWorld* world = new btDiscreteDynamicsWorldMt(m_pBulletDispatcher, m_pBulletBroadphase, solverPool, solverMt, m_pBulletConfiguration);
m_pBulletDynamicsWorld = world;
m_pBulletDynamicsWorld->setForceUpdateAllAabbs(false);
gBulletDynamicsWorld = world; // Also keep a static ref for ConVar callbacks
m_multithreadedWorld = true;
#endif // #if BT_THREADSAFE
}
else
{
// single threaded world
m_multithreadedWorld = false;
///collision configuration contains default setup for memory, collision setup
m_pBulletConfiguration = new btDefaultCollisionConfiguration();
// Use the default collision dispatcher. For parallel processing you can use a different dispatcher (see Extras/BulletMultiThreaded)
m_pBulletDispatcher = new btCollisionDispatcher(m_pBulletConfiguration);
m_pBulletBroadphase = new btDbvtBroadphase();
SolverType solverType = m_solverType;
if (solverType == SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT)
{
// using the parallel solver with the single-threaded world works, but is
// disabled here to avoid confusion
solverType = SOLVER_TYPE_SEQUENTIAL_IMPULSE;
}
m_pBulletSolver = createSolverByType(solverType);
m_pBulletSolver->setSolveCallback(m_pCollisionListener);
m_pBulletDynamicsWorld = new btDiscreteDynamicsWorld(m_pBulletDispatcher, m_pBulletBroadphase, m_pBulletSolver, m_pBulletConfiguration);
}
m_pBulletDynamicsWorld->getSolverInfo().m_solverMode = gSolverMode;
m_pBulletDynamicsWorld->getSolverInfo().m_numIterations = cvar_solver_iterations.GetInt();
m_pBulletGhostCallback = new btGhostPairCallback;
m_pCollisionSolver = new CCollisionSolver(this);
m_pBulletDynamicsWorld->getPairCache()->setOverlapFilterCallback(m_pCollisionSolver);
m_pBulletBroadphase->getOverlappingPairCache()->setInternalGhostPairCallback(m_pBulletGhostCallback);
m_pDeleteQueue = new CDeleteQueue;
m_pPhysicsDragController = new CPhysicsDragController;
m_pObjectTracker = new CObjectTracker(this, NULL);
m_perfparams.Defaults();
memset(&m_stats, 0, sizeof(m_stats));
// TODO: Threads solve any oversized batches (>32?), otherwise solving done on main thread.
m_pBulletDynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = 128; // Combine islands up to this many constraints
m_pBulletDynamicsWorld->getDispatchInfo().m_allowedCcdPenetration = 0.0001f;
m_pBulletDynamicsWorld->setApplySpeculativeContactRestitution(true);
m_pBulletDynamicsWorld->setInternalTickCallback(TickCallback, (void *)this);
// HACK: Get ourselves a debug overlay on the client
// CreateInterfaceFn engine = Sys_GetFactory("engine");
// CPhysicsEnvironment::SetDebugOverlay(engine);
m_pDebugOverlay = g_Physics.GetPhysicsDebugOverlay();
g_pDebugOverlay = m_pDebugOverlay;
#if DEBUG_DRAW
m_debugdraw = new CDebugDrawer(m_pBulletDynamicsWorld);
m_debugdraw->SetDebugOverlay( m_pDebugOverlay );
#endif
}
// Don't call this directly
void CPhysicsEnvironment::TickCallback(btDynamicsWorld *world, btScalar timeStep) {
if (!world) return;
CPhysicsEnvironment *pEnv = static_cast<CPhysicsEnvironment*>(world->getWorldUserInfo());
if (pEnv)
pEnv->BulletTick(timeStep);
}
//void CPhysicsEnvironment::SetDebugOverlay(CreateInterfaceFn debugOverlayFactory) {
// if (debugOverlayFactory && !g_pDebugOverlay)
// g_pDebugOverlay = static_cast<IVPhysicsDebugOverlay*>(debugOverlayFactory(VPHYSICS_DEBUG_OVERLAY_INTERFACE_VERSION, NULL));
//
//#if DEBUG_DRAW
// if (g_pDebugOverlay)
// m_debugdraw->SetDebugOverlay(g_pDebugOverlay);
//#endif
//}
IVPhysicsDebugOverlay *CPhysicsEnvironment::GetDebugOverlay() {
return g_pDebugOverlay;
}
btIDebugDraw *CPhysicsEnvironment::GetDebugDrawer() const
{
return reinterpret_cast<btIDebugDraw*>(m_debugdraw);
}
void CPhysicsEnvironment::SetGravity(const Vector &gravityVector) {
btVector3 temp;
ConvertPosToBull(gravityVector, temp);
m_pBulletDynamicsWorld->setGravity(temp);
}
void CPhysicsEnvironment::GetGravity(Vector *pGravityVector) const {
if (!pGravityVector) return;
const btVector3 temp = m_pBulletDynamicsWorld->getGravity();
ConvertPosToHL(temp, *pGravityVector);
}
void CPhysicsEnvironment::SetAirDensity(float density) {
m_pPhysicsDragController->SetAirDensity(density);
}
float CPhysicsEnvironment::GetAirDensity() const {
return m_pPhysicsDragController->GetAirDensity();
}
IPhysicsObject *CPhysicsEnvironment::CreatePolyObject(const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams) {
IPhysicsObject *pObject = CreatePhysicsObject(this, pCollisionModel, materialIndex, position, angles, pParams, false);
m_objects.AddToTail(pObject);
return pObject;
}
IPhysicsObject *CPhysicsEnvironment::CreatePolyObjectStatic(const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams) {
IPhysicsObject *pObject = CreatePhysicsObject(this, pCollisionModel, materialIndex, position, angles, pParams, true);
m_objects.AddToTail(pObject);
return pObject;
}
// Deprecated. Create a sphere model using collision interface.
IPhysicsObject *CPhysicsEnvironment::CreateSphereObject(float radius, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams, bool isStatic) {
IPhysicsObject *pObject = CreatePhysicsSphere(this, radius, materialIndex, position, angles, pParams, isStatic);
m_objects.AddToTail(pObject);
return pObject;
}
void CPhysicsEnvironment::DestroyObject(IPhysicsObject *pObject) {
if (!pObject) return;
Assert(m_deadObjects.Find(pObject) == -1); // If you hit this assert, the object is already on the list!
m_objects.FindAndRemove(pObject);
m_pObjectTracker->ObjectRemoved(dynamic_cast<CPhysicsObject*>(pObject));
if (m_inSimulation || m_bUseDeleteQueue) {
// We're still in the simulation, so deleting an object would be disastrous here. Queue it!
dynamic_cast<CPhysicsObject*>(pObject)->AddCallbackFlags(CALLBACK_MARKED_FOR_DELETE);
m_deadObjects.AddToTail(pObject);
} else {
delete pObject;
}
}
IPhysicsFluidController *CPhysicsEnvironment::CreateFluidController(IPhysicsObject *pFluidObject, fluidparams_t *pParams) {
CPhysicsFluidController *pFluid = ::CreateFluidController(this, static_cast<CPhysicsObject*>(pFluidObject), pParams);
if (pFluid)
m_fluids.AddToTail(pFluid);
return pFluid;
}
void CPhysicsEnvironment::DestroyFluidController(IPhysicsFluidController *pController) {
m_fluids.FindAndRemove(dynamic_cast<CPhysicsFluidController*>(pController));
delete pController;
}
IPhysicsSpring *CPhysicsEnvironment::CreateSpring(IPhysicsObject *pObjectStart, IPhysicsObject *pObjectEnd, springparams_t *pParams) {
return ::CreateSpringConstraint(this, pObjectStart, pObjectEnd, pParams);
}
void CPhysicsEnvironment::DestroySpring(IPhysicsSpring *pSpring) {
if (!pSpring) return;
CPhysicsConstraint* pConstraint = reinterpret_cast<CPhysicsConstraint*>(pSpring);
if (m_deleteQuick) {
IPhysicsObject *pObj0 = pConstraint->GetReferenceObject();
if (pObj0 && !pObj0->IsStatic())
pObj0->Wake();
IPhysicsObject *pObj1 = pConstraint->GetAttachedObject();
if (pObj1 && !pObj0->IsStatic())
pObj1->Wake();
}
if (m_inSimulation) {
pConstraint->Deactivate();
m_pDeleteQueue->QueueForDelete(pSpring);
} else {
delete pSpring;
}
}
IPhysicsConstraint *CPhysicsEnvironment::CreateRagdollConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ragdollparams_t &ragdoll) {
return ::CreateRagdollConstraint(this, pReferenceObject, pAttachedObject, pGroup, ragdoll);
}
IPhysicsConstraint *CPhysicsEnvironment::CreateHingeConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_hingeparams_t &hinge) {
return ::CreateHingeConstraint(this, pReferenceObject, pAttachedObject, pGroup, hinge);
}
IPhysicsConstraint *CPhysicsEnvironment::CreateFixedConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_fixedparams_t &fixed) {
return ::CreateFixedConstraint(this, pReferenceObject, pAttachedObject, pGroup, fixed);
}
IPhysicsConstraint *CPhysicsEnvironment::CreateSlidingConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_slidingparams_t &sliding) {
return ::CreateSlidingConstraint(this, pReferenceObject, pAttachedObject, pGroup, sliding);
}
IPhysicsConstraint *CPhysicsEnvironment::CreateBallsocketConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ballsocketparams_t &ballsocket) {
return ::CreateBallsocketConstraint(this, pReferenceObject, pAttachedObject, pGroup, ballsocket);
}
IPhysicsConstraint *CPhysicsEnvironment::CreatePulleyConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_pulleyparams_t &pulley) {
return ::CreatePulleyConstraint(this, pReferenceObject, pAttachedObject, pGroup, pulley);
}
IPhysicsConstraint *CPhysicsEnvironment::CreateLengthConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_lengthparams_t &length) {
return ::CreateLengthConstraint(this, pReferenceObject, pAttachedObject, pGroup, length);
}
IPhysicsConstraint *CPhysicsEnvironment::CreateGearConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_gearparams_t &gear) {
return ::CreateGearConstraint(this, pReferenceObject, pAttachedObject, pGroup, gear);
}
IPhysicsConstraint *CPhysicsEnvironment::CreateUserConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, IPhysicsUserConstraint *pConstraint) {
return ::CreateUserConstraint(this, pReferenceObject, pAttachedObject, pGroup, pConstraint);
}
void CPhysicsEnvironment::DestroyConstraint(IPhysicsConstraint *pConstraint) {
if (!pConstraint) return;
if (m_deleteQuick) {
IPhysicsObject *pObj0 = pConstraint->GetReferenceObject();
if (pObj0 && !pObj0->IsStatic())
pObj0->Wake();
IPhysicsObject *pObj1 = pConstraint->GetAttachedObject();
if (pObj1 && !pObj1->IsStatic())
pObj1->Wake();
}
if (m_inSimulation) {
pConstraint->Deactivate();
m_pDeleteQueue->QueueForDelete(pConstraint);
} else {
delete pConstraint;
}
}
IPhysicsConstraintGroup *CPhysicsEnvironment::CreateConstraintGroup(const constraint_groupparams_t &groupParams) {
return ::CreateConstraintGroup(this, groupParams);
}
void CPhysicsEnvironment::DestroyConstraintGroup(IPhysicsConstraintGroup *pGroup) {
delete pGroup;
}
IPhysicsShadowController *CPhysicsEnvironment::CreateShadowController(IPhysicsObject *pObject, bool allowTranslation, bool allowRotation) {
CShadowController *pController = ::CreateShadowController(pObject, allowTranslation, allowRotation);
if (pController)
m_controllers.AddToTail(pController);
return pController;
}
void CPhysicsEnvironment::DestroyShadowController(IPhysicsShadowController *pController) {
if (!pController) return;
m_controllers.FindAndRemove(static_cast<CShadowController*>(pController));
delete pController;
}
IPhysicsPlayerController *CPhysicsEnvironment::CreatePlayerController(IPhysicsObject *pObject) {
CPlayerController *pController = ::CreatePlayerController(this, pObject);
if (pController)
m_controllers.AddToTail(pController);
return pController;
}
void CPhysicsEnvironment::DestroyPlayerController(IPhysicsPlayerController *pController) {
if (!pController) return;
m_controllers.FindAndRemove(dynamic_cast<CPlayerController*>(pController));
delete pController;
}
IPhysicsMotionController *CPhysicsEnvironment::CreateMotionController(IMotionEvent *pHandler) {
CPhysicsMotionController *pController = dynamic_cast<CPhysicsMotionController*>(::CreateMotionController(this, pHandler));
if (pController)
m_controllers.AddToTail(pController);
return pController;
}
void CPhysicsEnvironment::DestroyMotionController(IPhysicsMotionController *pController) {
if (!pController) return;
m_controllers.FindAndRemove(static_cast<CPhysicsMotionController*>(pController));
delete pController;
}
IPhysicsVehicleController *CPhysicsEnvironment::CreateVehicleController(IPhysicsObject *pVehicleBodyObject, const vehicleparams_t ¶ms, unsigned int nVehicleType, IPhysicsGameTrace *pGameTrace) {
return ::CreateVehicleController(this, static_cast<CPhysicsObject*>(pVehicleBodyObject), params, nVehicleType, pGameTrace);
}
void CPhysicsEnvironment::DestroyVehicleController(IPhysicsVehicleController *pController) {
delete pController;
}
void CPhysicsEnvironment::SetCollisionSolver(IPhysicsCollisionSolver *pSolver) {
m_pCollisionSolver->SetHandler(pSolver);
}
void CPhysicsEnvironment::Simulate(float deltaTime) {
Assert(m_pBulletDynamicsWorld);
// Input deltaTime is how many seconds have elapsed since the previous frame
// phys_timescale can scale this parameter however...
// Can cause physics to slow down on the client environment when the game's window is not in focus
// Also is affected by the tickrate as well
if (deltaTime > 1.0 || deltaTime < 0.0) {
deltaTime = 0;
} else if (deltaTime > 0.1) {
deltaTime = 0.1f;
}
// sim PSI: How many substeps are done in a single simulation step
m_simPSI = bt_max_world_substeps.GetInt() != 0 ? bt_max_world_substeps.GetInt() : 1;
m_simPSICurrent = m_simPSI; // Substeps left in this step
m_numSubSteps = m_simPSI;
m_curSubStep = 0;
// Simulate no less than 1 ms
if (deltaTime > 0.001) {
// Now mark us as being in simulation. This is used for callbacks from bullet mid-simulation
// so we don't end up doing stupid things like deleting objects still in use
m_inSimulation = true;
m_subStepTime = m_timestep;
// Okay, how this fixed timestep shit works:
// The game sends in deltaTime which is the amount of time that has passed since the last frame
// Bullet will add the deltaTime to its internal counter
// When this internal counter exceeds m_timestep (param 3 to the below), the simulation will run for fixedTimeStep seconds
// If the internal counter does not exceed fixedTimeStep, bullet will just interpolate objects so the game can render them nice and happy
//if( deltaTime > (bt_max_world_substeps.GetInt() * m_timestep) )
//{
// Msg("Warning! We are losing physics-time! - deltaTime(%f) - maxTime(%f)\n", deltaTime, (bt_max_world_substeps.GetInt() * m_timestep));
//}
int stepsTaken = m_pBulletDynamicsWorld->stepSimulation(deltaTime, bt_max_world_substeps.GetInt(), m_timestep, m_simPSICurrent);
//lwss: stepSimulation returns the number of steps taken in the simulation this go-around.
// We can simply multiply this by the timestep(60hz client - 64hz server) to get the time simulated.
// and add it to our simtime.
m_simTime += ( stepsTaken * m_timestep );
// No longer in simulation!
m_inSimulation = false;
}
#if DEBUG_DRAW
m_debugdraw->DrawWorld();
#endif
}
bool CPhysicsEnvironment::IsInSimulation() const {
return m_inSimulation;
}
float CPhysicsEnvironment::GetSimulationTimestep() const {
return m_timestep;
}
void CPhysicsEnvironment::SetSimulationTimestep(float timestep) {
m_timestep = timestep;
}
float CPhysicsEnvironment::GetSimulationTime() const {
//lwss - add simulation time. (mainly used for forced ragdoll sleeping hack in csgo)
return m_simTime;
}
void CPhysicsEnvironment::ResetSimulationClock() {
m_simTime = 0.0f;
}
float CPhysicsEnvironment::GetNextFrameTime() const {
NOT_IMPLEMENTED
return 0;
}
void CPhysicsEnvironment::SetCollisionEventHandler(IPhysicsCollisionEvent *pCollisionEvents) {
//lwss: This enables the CCollisionEvent::PreCollision() and CCollisionEvent::PostCollision()
// in client/physics.cpp and server/physics.cpp
// Used for: Physics hit sounds, dust particles, and screen shake(unused?)
// The accuracy of the physics highly depends on the stepSimulation() maxSteps and resolution.
//
// There is another section that calls m_pCollisionEvent->Friction().
// That section is somewhat similar, But deals with friction Scrapes instead of impacts.
// It is ran on the server, which sends the particle/sound commands to the client
// TODO
m_pCollisionListener->SetCollisionEventCallback(pCollisionEvents);
m_pCollisionEvent = pCollisionEvents;
}
void CPhysicsEnvironment::SetObjectEventHandler(IPhysicsObjectEvent *pObjectEvents) {
m_pObjectEvent = pObjectEvents;
m_pObjectTracker->SetObjectEventHandler(pObjectEvents);
}
void CPhysicsEnvironment::SetConstraintEventHandler(IPhysicsConstraintEvent *pConstraintEvents) {
m_pConstraintEvent = pConstraintEvents;
}
void CPhysicsEnvironment::SetQuickDelete(bool bQuick) {
m_deleteQuick = bQuick;
}
int CPhysicsEnvironment::GetActiveObjectCount() const {
return m_pObjectTracker->GetActiveObjectCount();
}
void CPhysicsEnvironment::GetActiveObjects(IPhysicsObject **pOutputObjectList) const {
return m_pObjectTracker->GetActiveObjects(pOutputObjectList);
}
int CPhysicsEnvironment::GetObjectCount() const {
return m_objects.Count();
}
const IPhysicsObject **CPhysicsEnvironment::GetObjectList(int *pOutputObjectCount) const {
if (pOutputObjectCount) {
*pOutputObjectCount = m_objects.Count();
}
return const_cast<const IPhysicsObject**>(m_objects.Base());
}
bool CPhysicsEnvironment::TransferObject(IPhysicsObject *pObject, IPhysicsEnvironment *pDestinationEnvironment) {
if (!pObject || !pDestinationEnvironment) return false;
if (pDestinationEnvironment == this) {
dynamic_cast<CPhysicsObject*>(pObject)->TransferToEnvironment(this);
m_objects.AddToTail(pObject);
if (pObject->IsFluid())
m_fluids.AddToTail(dynamic_cast<CPhysicsObject*>(pObject)->GetFluidController());
return true;
} else {
m_objects.FindAndRemove(pObject);
if (pObject->IsFluid())
m_fluids.FindAndRemove(dynamic_cast<CPhysicsObject*>(pObject)->GetFluidController());
return pDestinationEnvironment->TransferObject(pObject, pDestinationEnvironment);
}
}
void CPhysicsEnvironment::CleanupDeleteList() {
for (int i = 0; i < m_deadObjects.Count(); i++) {
delete m_deadObjects.Element(i);
}
m_deadObjects.Purge();
m_pDeleteQueue->DeleteAll();
}
void CPhysicsEnvironment::EnableDeleteQueue(bool enable) {
m_bUseDeleteQueue = enable;
}
bool CPhysicsEnvironment::Save(const physsaveparams_t ¶ms) {
NOT_IMPLEMENTED
return false;
}
void CPhysicsEnvironment::PreRestore(const physprerestoreparams_t ¶ms) {
NOT_IMPLEMENTED
}
bool CPhysicsEnvironment::Restore(const physrestoreparams_t ¶ms) {
NOT_IMPLEMENTED
return false;
}
void CPhysicsEnvironment::PostRestore() {
NOT_IMPLEMENTED
}
//lwss add
void CPhysicsEnvironment::SetAlternateGravity(const Vector &gravityVector)
{
ConvertPosToBull(gravityVector, m_vecRagdollGravity);
}
void CPhysicsEnvironment::GetAlternateGravity(Vector *pGravityVector) const
{
ConvertPosToHL( m_vecRagdollGravity, *pGravityVector );
}
float CPhysicsEnvironment::GetDeltaFrameTime(int maxTicks) const
{
//TODO - implement this for bullet
// this is fully accurate, the IDA king has spoken.
//double timeDiff = m_pPhysEnv->time_of_next_psi.get_time() - m_pPhysEnv->current_time.get_time();
//return float( (float(maxTicks) * m_pPhysEnv->delta_PSI_time) + timeDiff );
// HACK ALERT!!
return 1.0f;
}
void CPhysicsEnvironment::ForceObjectsToSleep(IPhysicsObject **pList, int listCount)
{
//lwss: Technically this does not force the objects to sleep, but works OK.
for( int i = 0; i < listCount; i++ )
{
pList[i]->Sleep();
}
}
void CPhysicsEnvironment::SetPredicted(bool bPredicted)
{
// This check is a little different from retail
if( m_objects.Count() > 0 || m_deadObjects.Count() > 0 )
{
Error( "Predicted physics are not designed to change once objects have been made.\n");
/* Exit */
}
if( bPredicted )
Warning("WARNING: Kisak physics does NOT have prediction!\n");
//m_predictionEnabled = bPredicted;
}
bool CPhysicsEnvironment::IsPredicted()
{
//lwss hack - I didn't redo the whole physics prediction.
// return false so it doesn't try to use it.
return false;
//return m_predictionEnabled;
}
void CPhysicsEnvironment::SetPredictionCommandNum(int iCommandNum)
{
if( !m_predictionEnabled )
return;
//lwss hack - didn't reimplement the entire physics prediction system.
m_predictionCmdNum = iCommandNum;
Warning("LWSS didn't implement SetPredictionCommandNum\n");
}
int CPhysicsEnvironment::GetPredictionCommandNum()
{
return m_predictionCmdNum;
}
void CPhysicsEnvironment::DoneReferencingPreviousCommands(int iCommandNum)
{
//lwss hack
//Warning("LWSS didn't implement DoneReferencingPreviousCommands\n");
}
void CPhysicsEnvironment::RestorePredictedSimulation()
{
//lwss hack
Warning("LWSS didn't implement RestorePredictedSimulation\n");
}
void CPhysicsEnvironment::DestroyCollideOnDeadObjectFlush(CPhysCollide *)
{
//lwss hack
Warning("LWSS didn't implement DestroyCollideOnDeadObjectFlush\n");
// m_lastObjectThisTick // +20 bytes
}
//lwss end
bool CPhysicsEnvironment::IsCollisionModelUsed(CPhysCollide *pCollide) const {
for (int i = 0; i < m_objects.Count(); i++) {
if (dynamic_cast<CPhysicsObject*>(m_objects[i])->GetObject()->getCollisionShape() == pCollide->GetCollisionShape())
return true;
}
// Also scan the to-be-deleted objects list
for (int i = 0; i < m_deadObjects.Count(); i++) {
if (dynamic_cast<CPhysicsObject*>(m_deadObjects[i])->GetObject()->getCollisionShape() == pCollide->GetCollisionShape())
return true;
}
return false;
}
void CPhysicsEnvironment::TraceRay(const Ray_t &ray, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace) {
if (!ray.m_IsRay || !pTrace) return;
btVector3 vecStart, vecEnd;
ConvertPosToBull(ray.m_Start + ray.m_StartOffset, vecStart);
ConvertPosToBull(ray.m_Start + ray.m_StartOffset + ray.m_Delta, vecEnd);
// TODO: Override this class to use the mask and trace filter.
btCollisionWorld::ClosestRayResultCallback cb(vecStart, vecEnd);
m_pBulletDynamicsWorld->rayTest(vecStart, vecEnd, cb);
pTrace->fraction = cb.m_closestHitFraction;
ConvertPosToHL(cb.m_hitPointWorld, pTrace->endpos);
ConvertDirectionToHL(cb.m_hitNormalWorld, pTrace->plane.normal);
}
// Is this function ever called?
// TODO: This is a bit more complex, bullet doesn't support compound sweep tests.
void CPhysicsEnvironment::SweepCollideable(const CPhysCollide *pCollide, const Vector &vecAbsStart, const Vector &vecAbsEnd, const QAngle &vecAngles, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace) {
NOT_IMPLEMENTED
}
class CFilteredConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback {
public:
CFilteredConvexResultCallback(IPhysicsTraceFilter *pFilter, unsigned int mask, const btVector3 &convexFromWorld, const btVector3 &convexToWorld):
btCollisionWorld::ClosestConvexResultCallback(convexFromWorld, convexToWorld) {
m_pTraceFilter = pFilter;
m_mask = mask;
}
virtual bool needsCollision(btBroadphaseProxy *proxy0) const {
btCollisionObject *pColObj = (btCollisionObject *)proxy0->m_clientObject;
CPhysicsObject *pObj = (CPhysicsObject *)pColObj->getUserPointer();
if (pObj && !m_pTraceFilter->ShouldHitObject(pObj, m_mask)) {
return false;
}
bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0;
collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
private:
IPhysicsTraceFilter *m_pTraceFilter;
unsigned int m_mask;
};
void CPhysicsEnvironment::SweepConvex(const CPhysConvex *pConvex, const Vector &vecAbsStart, const Vector &vecAbsEnd, const QAngle &vecAngles, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace) {
if (!pConvex || !pTrace) return;
btVector3 vecStart, vecEnd;
ConvertPosToBull(vecAbsStart, vecStart);
ConvertPosToBull(vecAbsEnd, vecEnd);
btMatrix3x3 matAng;
ConvertRotationToBull(vecAngles, matAng);
btTransform transStart, transEnd;
transStart.setOrigin(vecStart);
transStart.setBasis(matAng);
transEnd.setOrigin(vecEnd);
transEnd.setBasis(matAng);
btConvexShape *pShape = (btConvexShape *)pConvex;
CFilteredConvexResultCallback cb(pTraceFilter, fMask, vecStart, vecEnd);
m_pBulletDynamicsWorld->convexSweepTest(pShape, transStart, transEnd, cb, 0.0001f);
pTrace->fraction = cb.m_closestHitFraction;
ConvertPosToHL(cb.m_hitPointWorld, pTrace->endpos);
ConvertDirectionToHL(cb.m_hitNormalWorld, pTrace->plane.normal);
}
void CPhysicsEnvironment::GetPerformanceSettings(physics_performanceparams_t *pOutput) const {
if (!pOutput) return;
*pOutput = m_perfparams;
}
void CPhysicsEnvironment::SetPerformanceSettings(const physics_performanceparams_t *pSettings) {
if (!pSettings) return;
m_perfparams = *pSettings;
}
void CPhysicsEnvironment::ReadStats(physics_stats_t *pOutput) {
if (!pOutput) return;
*pOutput = m_stats;
}
void CPhysicsEnvironment::ClearStats() {
memset(&m_stats, 0, sizeof(m_stats));
}
unsigned int CPhysicsEnvironment::GetObjectSerializeSize(IPhysicsObject *pObject) const {
NOT_IMPLEMENTED
return 0;
}
void CPhysicsEnvironment::SerializeObjectToBuffer(IPhysicsObject *pObject, unsigned char *pBuffer, unsigned int bufferSize) {
NOT_IMPLEMENTED
}
IPhysicsObject *CPhysicsEnvironment::UnserializeObjectFromBuffer(void *pGameData, unsigned char *pBuffer, unsigned int bufferSize, bool enableCollisions) {
NOT_IMPLEMENTED
return NULL;
}
void CPhysicsEnvironment::EnableConstraintNotify(bool bEnable) {
// Notify game about broken constraints?
m_bConstraintNotify = bEnable;
}
// FIXME: What do? Source SDK mods call this every frame in debug builds.
void CPhysicsEnvironment::DebugCheckContacts() {
}
// UNEXPOSED
btDiscreteDynamicsWorld *CPhysicsEnvironment::GetBulletEnvironment() const
{
return m_pBulletDynamicsWorld;
}
// UNEXPOSED
float CPhysicsEnvironment::GetInvPSIScale() const
{
return m_invPSIScale;
}
// UNEXPOSED
void CPhysicsEnvironment::BulletTick(btScalar dt) {
// Dirty hack to spread the controllers throughout the current simulation step
if (m_simPSICurrent) {
m_invPSIScale = 1.0f / static_cast<float>(m_simPSICurrent);
m_simPSICurrent--;
} else {
m_invPSIScale = 0;
}
m_pPhysicsDragController->Tick(dt);
for (int i = 0; i < m_controllers.Count(); i++)
m_controllers[i]->Tick(dt);
for (int i = 0; i < m_fluids.Count(); i++)
m_fluids[i]->Tick(dt);
m_inSimulation = false;
// Update object sleep states
m_pObjectTracker->Tick();
if (!m_bUseDeleteQueue) {
CleanupDeleteList();
}
//lwss: This part of the code is used by the server to send FRICTION sounds/dust
// these are separate from collisions.
DoCollisionEvents(dt);
//lwss end.
if (m_pCollisionEvent)
m_pCollisionEvent->PostSimulationFrame();
m_inSimulation = true;
m_curSubStep++;
}
// UNEXPOSED
CPhysicsDragController *CPhysicsEnvironment::GetDragController() const
{
return m_pPhysicsDragController;
}
CCollisionSolver *CPhysicsEnvironment::GetCollisionSolver() const
{
return m_pCollisionSolver;
}
btVector3 CPhysicsEnvironment::GetMaxLinearVelocity() const {
return btVector3(HL2BULL(m_perfparams.maxVelocity), HL2BULL(m_perfparams.maxVelocity), HL2BULL(m_perfparams.maxVelocity));
}
btVector3 CPhysicsEnvironment::GetMaxAngularVelocity() const {
return btVector3(HL2BULL(m_perfparams.maxAngularVelocity), HL2BULL(m_perfparams.maxAngularVelocity), HL2BULL(m_perfparams.maxAngularVelocity));
}
// UNEXPOSED
// Purpose: To be the biggest eyesore ever
// Bullet doesn't provide many callbacks such as the ones we're looking for, so
// we have to iterate through all the contact manifolds and generate the callbacks ourselves.
// FIXME: Remove this function and implement callbacks in bullet code
void CPhysicsEnvironment::DoCollisionEvents(float dt) {
if (m_pCollisionEvent) {
const int numManifolds = m_pBulletDynamicsWorld->getDispatcher()->getNumManifolds();
for (int i = 0; i < numManifolds; i++) {
btPersistentManifold *contactManifold = m_pBulletDynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
if (contactManifold->getNumContacts() <= 0)
continue;
const btCollisionObject *obA = contactManifold->getBody0();
const btCollisionObject *obB = contactManifold->getBody1();
if (!obA || !obB) continue;
CPhysicsObject *physObA = static_cast<CPhysicsObject*>(obA->getUserPointer());
CPhysicsObject *physObB = static_cast<CPhysicsObject*>(obB->getUserPointer());
// These are our own internal objects, don't do callbacks on them.
if (obA->getInternalType() == btCollisionObject::CO_GHOST_OBJECT || obB->getInternalType() == btCollisionObject::CO_GHOST_OBJECT)
continue;
if (!(physObA->GetCallbackFlags() & CALLBACK_GLOBAL_FRICTION) || !(physObB->GetCallbackFlags() & CALLBACK_GLOBAL_FRICTION))
continue;
for (int j = 0; j < contactManifold->getNumContacts(); j++) {
btManifoldPoint manPoint = contactManifold->getContactPoint(j);
// FRICTION CALLBACK
// FIXME: We need to find the energy used by the friction! Bullet doesn't provide this in the manifold point.
// This may not be the proper variable but whatever, as of now it works.
const float energy = abs(manPoint.m_appliedImpulseLateral1);
if (energy > 0.05f) {
CPhysicsCollisionData data(&manPoint);
m_pCollisionEvent->Friction(static_cast<CPhysicsObject*>(obA->getUserPointer()),
ConvertEnergyToHL(energy),
static_cast<CPhysicsObject*>(obA->getUserPointer())->GetMaterialIndex(),
static_cast<CPhysicsObject*>(obB->getUserPointer())->GetMaterialIndex(),
&data);
}
// TODO: Collision callback
// Source wants precollision and postcollision callbacks (pre velocity and post velocity, etc.)
// How do we generate a callback before the collision happens?
}
}
}
}
// ==================
// EVENTS
// ==================
// UNEXPOSED
void CPhysicsEnvironment::HandleConstraintBroken(CPhysicsConstraint *pConstraint) const
{
if (m_bConstraintNotify && m_pConstraintEvent)
m_pConstraintEvent->ConstraintBroken(pConstraint);
}
// UNEXPOSED
void CPhysicsEnvironment::HandleFluidStartTouch(CPhysicsFluidController *pController, CPhysicsObject *pObject) const
{
if (pObject->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return;
if (m_pCollisionEvent)
m_pCollisionEvent->FluidStartTouch(pObject, pController);
}
// UNEXPOSED
void CPhysicsEnvironment::HandleFluidEndTouch(CPhysicsFluidController *pController, CPhysicsObject *pObject) const
{
if (pObject->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return;
if (m_pCollisionEvent)
m_pCollisionEvent->FluidEndTouch(pObject, pController);
}
// UNEXPOSED
void CPhysicsEnvironment::HandleObjectEnteredTrigger(CPhysicsObject *pTrigger, CPhysicsObject *pObject) const
{
if (pObject->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return;
if (m_pCollisionEvent)
m_pCollisionEvent->ObjectEnterTrigger(pTrigger, pObject);
}
// UNEXPOSED
void CPhysicsEnvironment::HandleObjectExitedTrigger(CPhysicsObject *pTrigger, CPhysicsObject *pObject) const
{
if (pObject->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return;
if (m_pCollisionEvent)
m_pCollisionEvent->ObjectLeaveTrigger(pTrigger, pObject);
}
| 36.0053 | 354 | 0.762828 | SwagSoftware |
b755fae74c436939a563f178a7d1bb9e6675d203 | 1,106 | cpp | C++ | Source/src/Json Parser/DataTypeHandlers/JsonObject.cpp | codenameone-akshat/LittleJsonReader | 2a28219ef494d4d3a02961d74fb90fa4829a14c5 | [
"MIT"
] | null | null | null | Source/src/Json Parser/DataTypeHandlers/JsonObject.cpp | codenameone-akshat/LittleJsonReader | 2a28219ef494d4d3a02961d74fb90fa4829a14c5 | [
"MIT"
] | null | null | null | Source/src/Json Parser/DataTypeHandlers/JsonObject.cpp | codenameone-akshat/LittleJsonReader | 2a28219ef494d4d3a02961d74fb90fa4829a14c5 | [
"MIT"
] | null | null | null | #include "JsonObjectItem.h"
JsonReader::JsonItem * JsonReader::JsonObjectItem::GetValue()
{
return this;
}
JsonReader::JsonItem * JsonReader::JsonObjectItem::GetFirstChild()
{
it = m_value.begin();
return *it;
}
JsonReader::JsonItem * JsonReader::JsonObjectItem::GetNextChild()
{
std::vector<JsonItem*>::iterator end = m_value.end()-1;
if (it != end)
{
++it;
return *it;
}
else
return *it;
}
JsonReader::JsonItem * JsonReader::JsonObjectItem::AddChild(JsonItem* jsonItem)
{
m_value.push_back(jsonItem);
return jsonItem;
}
JsonReader::JsonItem * JsonReader::JsonObjectItem::GetChildAt(int index)
{
if (index <= m_value.size() - 1)
{
return m_value.at(index);
}
else
return nullptr;
}
int JsonReader::JsonObjectItem::asInt()
{
return 0;
}
double JsonReader::JsonObjectItem::asDouble()
{
return 0.0;
}
bool JsonReader::JsonObjectItem::asBool()
{
return false;
}
std::string JsonReader::JsonObjectItem::asString()
{
return std::string();
}
int JsonReader::JsonObjectItem::size()
{
return m_value.size();
}
| 16.757576 | 80 | 0.664557 | codenameone-akshat |
b758578b94442795754abc3bccdd5a85647c9325 | 677 | cpp | C++ | sources codes/tute30b.cpp | darkrabel/c-personal-reference-code- | 0ea62666a6f8b7ea876e96498e3c0b6b4e773a7f | [
"MIT"
] | 2 | 2021-06-17T11:05:01.000Z | 2021-11-15T11:39:46.000Z | sources codes/tute30b.cpp | darkrabel/c-personal-reference-code- | 0ea62666a6f8b7ea876e96498e3c0b6b4e773a7f | [
"MIT"
] | null | null | null | sources codes/tute30b.cpp | darkrabel/c-personal-reference-code- | 0ea62666a6f8b7ea876e96498e3c0b6b4e773a7f | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
class Point{
int x, y;
public:
Point(int a, int b){
x = a;
y = b;
}
void displayPoint(){
cout<<"The point is ("<<x<<", "<<y<<")"<<endl;
}
};
// Create a function (Hint: Make it a friend function) which takes 2 point objects and computes the distance between those 2 points
// Use these examples to check your code:
// Distance between (1, 1) and (1, 1) is 0
// Distance between (0, 1) and (0, 6) is 5
// Distance between (1, 0) and (70, 0) is 69
int main(){
Point p(1, 1);
p.displayPoint();
Point q(4, 6);
q.displayPoint();
return 0;
}
| 21.83871 | 131 | 0.552437 | darkrabel |
b75b6cd1faa782a6f70b5eddbb1aacaba1f7d65b | 860 | hpp | C++ | src/Camera.hpp | Philipp-M/CG_Project1 | 19e6b96c8c6d6fe4323af50f247ed07120c74f9c | [
"MIT"
] | null | null | null | src/Camera.hpp | Philipp-M/CG_Project1 | 19e6b96c8c6d6fe4323af50f247ed07120c74f9c | [
"MIT"
] | null | null | null | src/Camera.hpp | Philipp-M/CG_Project1 | 19e6b96c8c6d6fe4323af50f247ed07120c74f9c | [
"MIT"
] | null | null | null | #pragma once
#include <GL/gl.h>
#include <glm/glm.hpp>
#include <glm/gtc/constants.hpp>
const GLfloat PI_4 = 0.78539816339744830962;
class Camera
{
private:
GLfloat fieldOfView;
GLfloat width;
GLfloat height;
GLfloat nearPlane;
GLfloat farPlane;
glm::mat4 viewMat;
public:
Camera(GLfloat width = 1920, GLfloat height = 1080, GLfloat nearPlane = 1, GLfloat farPlane = 50, GLfloat fieldOfView = PI_4);
GLfloat getWidth() const;
void setWidth(GLfloat width);
GLfloat getHeight() const;
void setHeight(GLfloat height);
/*** implemented from the interface Entity ***/
void move(glm::vec3 delta);
void rotate(glm::vec3 delta);
void rotateAroundAxis(glm::vec3 a, float w);
void scale(glm::vec3 factor);
void scale(GLfloat factor);
void resetViewMatrix();
glm::mat4 getViewMatrix() const;
glm::mat4 getProjectionMatrix() const;
};
| 17.916667 | 127 | 0.727907 | Philipp-M |
b75cfe6dbda9e66acdf42f4480e39184ba41ea21 | 449 | cpp | C++ | code/data-structures/segment_tree_node.cpp | viswamy/CompetitiveProgramming | 497d58adce25cfe4fc327301d977da275ad80201 | [
"MIT"
] | null | null | null | code/data-structures/segment_tree_node.cpp | viswamy/CompetitiveProgramming | 497d58adce25cfe4fc327301d977da275ad80201 | [
"MIT"
] | null | null | null | code/data-structures/segment_tree_node.cpp | viswamy/CompetitiveProgramming | 497d58adce25cfe4fc327301d977da275ad80201 | [
"MIT"
] | 1 | 2019-07-28T03:12:29.000Z | 2019-07-28T03:12:29.000Z | #ifndef STNODE
#define STNODE
struct node {
int l, r;
ll x, lazy;
node() {}
node(int _l, int _r) : l(_l), r(_r), x(0), lazy(0) { }
node(int _l, int _r, ll _x) : node(_l,_r) { x = _x; }
node(node a, node b) : node(a.l,b.r) { x = a.x + b.x; }
void update(ll v) { x = v; }
void range_update(ll v) { lazy = v; }
void apply() { x += lazy * (r - l + 1); lazy = 0; }
void push(node &u) { u.lazy += lazy; } };
#endif
| 29.933333 | 59 | 0.492205 | viswamy |
b75e80dfc6b4645d842b4b4bce139b667dddd272 | 1,416 | cpp | C++ | VIIL/src/renderer/interface/Shader.cpp | Vixnil/VIIL | 0057464a1bc6e938825cfdf59a977cbe53c03a00 | [
"Apache-2.0"
] | null | null | null | VIIL/src/renderer/interface/Shader.cpp | Vixnil/VIIL | 0057464a1bc6e938825cfdf59a977cbe53c03a00 | [
"Apache-2.0"
] | null | null | null | VIIL/src/renderer/interface/Shader.cpp | Vixnil/VIIL | 0057464a1bc6e938825cfdf59a977cbe53c03a00 | [
"Apache-2.0"
] | null | null | null | #include "core/standardUse.h"
#include "renderer/interface/Shader.h"
#include "renderer//interface/RendererLibrary.h"
#include "renderer/OpenGL/OpenGLShader.h"
namespace VIIL
{
std::shared_ptr<Shader> Shader::Create(const std::shared_ptr<File>& shaderSrc)
{
switch (RendererLibrary::getType())
{
case RendererLibrary::Type::OpenGL:
return std::shared_ptr<Shader>(new OpenGLShader(shaderSrc));
break;
default:
VL_ENGINE_FATAL("Unimplemented renderer type selected. Shader creation failed.");
}
return nullptr;
}
std::shared_ptr<Shader> Shader::Create(const std::string& name, const std::shared_ptr<File>& vertexFile, const std::shared_ptr<File>& fragmentFile)
{
switch (RendererLibrary::getType())
{
case RendererLibrary::Type::OpenGL:
return std::shared_ptr<Shader>(new OpenGLShader(name, vertexFile, fragmentFile));
break;
default:
VL_ENGINE_FATAL("Unimplemented renderer type selected. Shader creation failed.");
}
return nullptr;
}
std::shared_ptr<Shader> Shader::Create(const std::string& name, const std::string& vertexSrc, const std::string& fragmentSrc)
{
switch (RendererLibrary::getType())
{
case RendererLibrary::Type::OpenGL:
return std::shared_ptr<Shader>(new OpenGLShader(name, vertexSrc, fragmentSrc));
break;
default:
VL_ENGINE_FATAL("Unimplemented renderer type selected. Shader creation failed.");
}
return nullptr;
}
} | 27.764706 | 148 | 0.737288 | Vixnil |
b767de3fcf18ad1ff838a3b3ee458af38573a642 | 5,173 | cpp | C++ | test/System/Session.cpp | ntoskrnl7/win32api-ex | e91521b53745655fd8fb7d6532770f4888420814 | [
"MIT"
] | 18 | 2022-01-12T23:01:55.000Z | 2022-03-28T01:50:56.000Z | test/System/Session.cpp | ntoskrnl7/win32api-ex | e91521b53745655fd8fb7d6532770f4888420814 | [
"MIT"
] | null | null | null | test/System/Session.cpp | ntoskrnl7/win32api-ex | e91521b53745655fd8fb7d6532770f4888420814 | [
"MIT"
] | 3 | 2022-02-25T10:55:41.000Z | 2022-02-25T13:06:21.000Z | #include <Win32Ex/System/Session.hpp>
#include <gtest/gtest.h>
TEST(SessionTest, ThisSession)
{
EXPECT_EQ(Win32Ex::ThisSession::Id(), WTSGetActiveConsoleSessionId());
EXPECT_STREQ(Win32Ex::ThisSession::Name().c_str(),
Win32Ex::System::Session(Win32Ex::ThisSession::Id()).Name().c_str());
EXPECT_STREQ(Win32Ex::ThisSession::UserName().c_str(),
Win32Ex::System::Session(Win32Ex::ThisSession::Id()).UserName().c_str());
}
TEST(SessionTest, ThisSessionNewProcessT)
{
#if defined(WIN32EX_USE_TEMPLATE_FUNCTION_DEFAULT_ARGUMENT_STRING_T)
auto process = Win32Ex::ThisSession::NewProcessT(Win32Ex::System::UserAccount, TEXT("notepad"));
#else
Win32Ex::Result<Win32Ex::System::SessionT<>::RunnableProcessPtr> process =
Win32Ex::ThisSession::NewProcessT<Win32Ex::StringT>(Win32Ex::System::UserAccount, TEXT("notepad"));
#endif
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
process = Win32Ex::ThisSession::NewProcessT<Win32Ex::StringT>(Win32Ex::System::SystemAccount, TEXT("notepad"));
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
}
TEST(SessionTest, ThisSessionNewProcess)
{
#if defined(WIN32EX_USE_TEMPLATE_FUNCTION_DEFAULT_ARGUMENT_STRING_T)
auto process = Win32Ex::ThisSession::NewProcess(Win32Ex::System::UserAccount, "notepad");
#else
Win32Ex::Result<Win32Ex::System::Session::RunnableProcessPtr> process =
Win32Ex::ThisSession::NewProcess(Win32Ex::System::UserAccount, "notepad");
#endif
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
process = Win32Ex::ThisSession::NewProcess(Win32Ex::System::SystemAccount, "notepad");
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
}
TEST(SessionTest, ThisSessionNewProcessW)
{
#if defined(WIN32EX_USE_TEMPLATE_FUNCTION_DEFAULT_ARGUMENT_STRING_T)
auto process = Win32Ex::ThisSession::NewProcessW(Win32Ex::System::UserAccount, L"notepad");
#else
Win32Ex::Result<Win32Ex::System::SessionW::RunnableProcessPtr> process =
Win32Ex::ThisSession::NewProcessW(Win32Ex::System::UserAccount, L"notepad");
#endif
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
process = Win32Ex::ThisSession::NewProcessW(Win32Ex::System::SystemAccount, L"notepad");
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
}
TEST(SessionTest, SessionNewProcess)
{
#if defined(__cpp_range_based_for)
for (auto session : Win32Ex::System::Session::All())
{
auto process = session.NewProcess(Win32Ex::System::UserAccount, "notepad");
#else
// clang-format off
for each (Win32Ex::System::Session session in Win32Ex::System::Session::All())
{
Win32Ex::Result<Win32Ex::System::Session::RunnableProcessPtr> process =
session.NewProcess(Win32Ex::System::UserAccount, "notepad");
// clang-format on
#endif
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
process = session.NewProcess(Win32Ex::System::SystemAccount, "notepad");
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
}
}
TEST(SessionTest, SessionWNewProcess)
{
#if defined(__cpp_range_based_for)
for (auto session : Win32Ex::System::SessionW::All())
{
auto process = session.NewProcess(Win32Ex::System::UserAccount, L"notepad");
#else
// clang-format off
for each (Win32Ex::System::SessionW session in Win32Ex::System::SessionW::All())
{
Win32Ex::Result<Win32Ex::System::SessionW::RunnableProcessPtr> process =
session.NewProcess(Win32Ex::System::UserAccount, L"notepad");
// clang-format on
#endif
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
process = session.NewProcess(Win32Ex::System::SystemAccount, L"notepad");
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
}
}
TEST(SessionTest, SessionTNewProcess)
{
#if defined(__cpp_range_based_for)
for (auto session : Win32Ex::System::SessionT<>::All())
{
auto process = session.NewProcess(Win32Ex::System::UserAccount, TEXT("notepad"));
#else
// clang-format off
for each (Win32Ex::System::SessionT<> session in Win32Ex::System::SessionT<>::All())
{
Win32Ex::Result<Win32Ex::System::SessionT<>::RunnableProcessPtr> process =
session.NewProcess(Win32Ex::System::UserAccount, TEXT("notepad"));
// clang-format on
#endif
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
process = session.NewProcess(Win32Ex::System::SystemAccount, TEXT("notepad"));
if (process.IsOk())
{
process->RunAsync().Wait(500);
process->Exit();
}
}
}
| 32.534591 | 115 | 0.635028 | ntoskrnl7 |
b76d9160b34a21db97aa8eac8705d37d6e0abf72 | 13,690 | cpp | C++ | cppLib/code/dep/G3D/source/ConvexPolyhedron.cpp | DrYaling/ProcedureContentGenerationForUnity | 3c4f1e70b01e4fe2b9f847324b60b15016b9a740 | [
"MIT"
] | 3 | 2019-05-14T07:19:59.000Z | 2019-05-14T08:08:25.000Z | cppLib/code/dep/G3D/source/ConvexPolyhedron.cpp | DrYaling/ProcedureContentGenerationForUnity | 3c4f1e70b01e4fe2b9f847324b60b15016b9a740 | [
"MIT"
] | null | null | null | cppLib/code/dep/G3D/source/ConvexPolyhedron.cpp | DrYaling/ProcedureContentGenerationForUnity | 3c4f1e70b01e4fe2b9f847324b60b15016b9a740 | [
"MIT"
] | 1 | 2018-08-08T07:39:16.000Z | 2018-08-08T07:39:16.000Z | /**
@file ConvexPolyhedron.cpp
@author Morgan McGuire, http://graphics.cs.williams.edu
@created 2001-11-11
@edited 2009-08-10
Copyright 2000-2009, Morgan McGuire.
All rights reserved.
*/
#include "G3D/platform.h"
#include "G3D/ConvexPolyhedron.h"
#include "G3D/debug.h"
namespace G3D {
ConvexPolygon::ConvexPolygon(const Array<Vector3>& __vertex) : _vertex(__vertex) {
// Intentionally empty
}
ConvexPolygon::ConvexPolygon(const Vector3& v0, const Vector3& v1, const Vector3& v2) {
_vertex.append(v0, v1, v2);
}
bool ConvexPolygon::isEmpty() const {
return (_vertex.length() == 0) || (getArea() <= fuzzyEpsilon32);
}
float ConvexPolygon::getArea() const {
if (_vertex.length() < 3) {
return 0;
}
float sum = 0;
int length = _vertex.length();
// Split into triangle fan, compute individual area
for (int v = 2; v < length; ++v) {
int i0 = 0;
int i1 = v - 1;
int i2 = v;
sum += (_vertex[i1] - _vertex[i0]).cross(_vertex[i2] - _vertex[i0]).magnitude() / 2;
}
return sum;
}
void ConvexPolygon::cut(const Plane& plane, ConvexPolygon &above, ConvexPolygon &below) {
DirectedEdge edge;
cut(plane, above, below, edge);
}
void ConvexPolygon::cut(const Plane& plane, ConvexPolygon &above, ConvexPolygon &below, DirectedEdge &newEdge) {
above._vertex.resize(0);
below._vertex.resize(0);
if (isEmpty()) {
//debugPrintf("Empty\n");
return;
}
int v = 0;
int length = _vertex.length();
Vector3 polyNormal = normal();
Vector3 planeNormal= plane.normal();
// See if the polygon is *in* the plane.
if (planeNormal.fuzzyEq(polyNormal) || planeNormal.fuzzyEq(-polyNormal)) {
// Polygon is parallel to the plane. It must be either above,
// below, or in the plane.
double a, b, c, d;
Vector3 pt = _vertex[0];
plane.getEquation(a,b,c,d);
float r = (float)(a * pt.x + b * pt.y + c * pt.z + d);
if (fuzzyGe(r, 0)) {
// The polygon is entirely in the plane.
//debugPrintf("Entirely above\n");
above = *this;
return;
} else {
//debugPrintf("Entirely below (1)\n");
below = *this;
return;
}
}
// Number of edges crossing the plane. Used for
// debug assertions.
int count = 0;
// True when the last _vertex we looked at was above the plane
bool lastAbove = plane.halfSpaceContains(_vertex[v]);
if (lastAbove) {
above._vertex.append(_vertex[v]);
} else {
below._vertex.append(_vertex[v]);
}
for (v = 1; v < length; ++v) {
bool isAbove = plane.halfSpaceContains(_vertex[v]);
if (lastAbove ^ isAbove) {
// Switched sides.
// Create an interpolated point that lies
// in the plane, between the two points.
Line line = Line::fromTwoPoints(_vertex[v - 1], _vertex[v]);
Vector3 interp = line.intersection(plane);
if (! interp.isFinite()) {
// Since the polygon is not in the plane (we checked above),
// it must be the case that this edge (and only this edge)
// is in the plane. This only happens when the polygon is
// entirely below the plane except for one edge. This edge
// forms a degenerate polygon, so just treat the whole polygon
// as below the plane.
below = *this;
above._vertex.resize(0);
//debugPrintf("Entirely below\n");
return;
}
above._vertex.append(interp);
below._vertex.append(interp);
if (lastAbove) {
newEdge.stop = interp;
} else {
newEdge.start = interp;
}
++count;
}
lastAbove = isAbove;
if (lastAbove) {
above._vertex.append(_vertex[v]);
} else {
below._vertex.append(_vertex[v]);
}
}
// Loop back to the first point, seeing if an interpolated point is
// needed.
bool isAbove = plane.halfSpaceContains(_vertex[0]);
if (lastAbove ^ isAbove) {
Line line = Line::fromTwoPoints(_vertex[length - 1], _vertex[0]);
Vector3 interp = line.intersection(plane);
if (! interp.isFinite()) {
// Since the polygon is not in the plane (we checked above),
// it must be the case that this edge (and only this edge)
// is in the plane. This only happens when the polygon is
// entirely below the plane except for one edge. This edge
// forms a degenerate polygon, so just treat the whole polygon
// as below the plane.
below = *this;
above._vertex.resize(0);
//debugPrintf("Entirely below\n");
return;
}
above._vertex.append(interp);
below._vertex.append(interp);
debugAssertM(count < 2, "Convex polygons may only intersect planes at two edges.");
if (lastAbove) {
newEdge.stop = interp;
} else {
newEdge.start = interp;
}
++count;
}
debugAssertM((count == 2) || (count == 0), "Convex polygons may only intersect planes at two edges.");
}
ConvexPolygon ConvexPolygon::inverse() const {
ConvexPolygon result;
int length = _vertex.length();
result._vertex.resize(length);
for (int v = 0; v < length; ++v) {
result._vertex[v] = _vertex[length - v - 1];
}
return result;
}
void ConvexPolygon::removeDuplicateVertices(){
// Any valid polygon should have 3 or more vertices, but why take chances?
if (_vertex.size() >= 2){
// Remove duplicate vertices.
for (int i=0;i<_vertex.size()-1;++i){
if (_vertex[i].fuzzyEq(_vertex[i+1])){
_vertex.remove(i+1);
--i; // Don't move forward.
}
}
// Check the last vertex against the first.
if (_vertex[_vertex.size()-1].fuzzyEq(_vertex[0])){
_vertex.pop();
}
}
}
//////////////////////////////////////////////////////////////////////////////
ConvexPolyhedron::ConvexPolyhedron(const Array<ConvexPolygon>& _face) : face(_face) {
// Intentionally empty
}
float ConvexPolyhedron::getVolume() const {
if (face.length() < 4) {
return 0;
}
// The volume of any pyramid is 1/3 * h * base area.
// Discussion at: http://nrich.maths.org/mathsf/journalf/oct01/art1/
float sum = 0;
// Choose the first _vertex of the first face as the origin.
// This lets us skip one face, too, and avoids negative heights.
Vector3 v0 = face[0]._vertex[0];
for (int f = 1; f < face.length(); ++f) {
const ConvexPolygon& poly = face[f];
float height = (poly._vertex[0] - v0).dot(poly.normal());
float base = poly.getArea();
sum += height * base;
}
return sum / 3;
}
bool ConvexPolyhedron::isEmpty() const {
return (face.length() == 0) || (getVolume() <= fuzzyEpsilon32);
}
void ConvexPolyhedron::cut(const Plane& plane, ConvexPolyhedron &above, ConvexPolyhedron &below) {
above.face.resize(0);
below.face.resize(0);
Array<DirectedEdge> edge;
int f;
// See if the plane cuts this polyhedron at all. Detect when
// the polyhedron is entirely to one side or the other.
//{
int numAbove = 0, numIn = 0, numBelow = 0;
bool ruledOut = false;
double d;
Vector3 abc;
plane.getEquation(abc, d);
// This number has to be fairly large to prevent precision problems down
// the road.
const float eps = 0.005f;
for (f = face.length() - 1; (f >= 0) && (!ruledOut); f--) {
const ConvexPolygon& poly = face[f];
for (int v = poly._vertex.length() - 1; (v >= 0) && (!ruledOut); v--) {
double r = abc.dot(poly._vertex[v]) + d;
if (r > eps) {
++numAbove;
} else if (r < -eps) {
++numBelow;
} else {
++numIn;
}
ruledOut = (numAbove != 0) && (numBelow !=0);
}
}
if (numBelow == 0) {
above = *this;
return;
} else if (numAbove == 0) {
below = *this;
return;
}
//}
// Clip each polygon, collecting split edges.
for (f = face.length() - 1; f >= 0; f--) {
ConvexPolygon a, b;
DirectedEdge e;
face[f].cut(plane, a, b, e);
bool aEmpty = a.isEmpty();
bool bEmpty = b.isEmpty();
//debugPrintf("\n");
if (! aEmpty) {
//debugPrintf(" Above %f\n", a.getArea());
above.face.append(a);
}
if (! bEmpty) {
//debugPrintf(" Below %f\n", b.getArea());
below.face.append(b);
}
if (! aEmpty && ! bEmpty) {
//debugPrintf(" == Split\n");
edge.append(e);
} else {
// Might be the case that the polygon is entirely on
// one side of the plane yet there is an edge we need
// because it touches the plane.
//
// Extract the non-empty _vertex list and examine it.
// If we find exactly one edge in the plane, add that edge.
const Array<Vector3>& _vertex = (aEmpty ? b._vertex : a._vertex);
int L = _vertex.length();
int count = 0;
for (int v = 0; v < L; ++v) {
if (plane.fuzzyContains(_vertex[v]) && plane.fuzzyContains(_vertex[(v + 1) % L])) {
e.start = _vertex[v];
e.stop = _vertex[(v + 1) % L];
++count;
}
}
if (count == 1) {
edge.append(e);
}
}
}
if (above.face.length() == 1) {
// Only one face above means that this entire
// polyhedron is below the plane. Move that face over.
below.face.append(above.face[0]);
above.face.resize(0);
} else if (below.face.length() == 1) {
// This shouldn't happen, but it arises in practice
// from numerical imprecision.
above.face.append(below.face[0]);
below.face.resize(0);
}
if ((above.face.length() > 0) && (below.face.length() > 0)) {
// The polyhedron was actually cut; create a cap polygon
ConvexPolygon cap;
// Collect the final polgyon by sorting the edges
int numVertices = edge.length();
/*debugPrintf("\n");
for (int xx=0; xx < numVertices; ++xx) {
std::string s1 = edge[xx].start.toString();
std::string s2 = edge[xx].stop.toString();
debugPrintf("%s -> %s\n", s1.c_str(), s2.c_str());
}
*/
// Need at least three points to make a polygon
debugAssert(numVertices >= 3);
Vector3 last_vertex = edge.last().stop;
cap._vertex.append(last_vertex);
// Search for the next _vertex. Because of accumulating
// numerical error, we have to find the closest match, not
// just the one we expect.
for (int v = numVertices - 1; v >= 0; v--) {
// matching edge index
int index = 0;
int num = edge.length();
double distance = (edge[index].start - last_vertex).squaredMagnitude();
for (int e = 1; e < num; ++e) {
double d = (edge[e].start - last_vertex).squaredMagnitude();
if (d < distance) {
// This is the new closest one
index = e;
distance = d;
}
}
// Don't tolerate ridiculous error.
debugAssertM(distance < 0.02, "Edge missing while closing polygon.");
last_vertex = edge[index].stop;
cap._vertex.append(last_vertex);
}
//debugPrintf("\n");
//debugPrintf("Cap (both) %f\n", cap.getArea());
above.face.append(cap);
below.face.append(cap.inverse());
}
// Make sure we put enough faces on each polyhedra
debugAssert((above.face.length() == 0) || (above.face.length() >= 4));
debugAssert((below.face.length() == 0) || (below.face.length() >= 4));
}
///////////////////////////////////////////////
ConvexPolygon2D::ConvexPolygon2D(const Array<Vector2>& pts, bool reverse) : m_vertex(pts) {
if (reverse) {
m_vertex.reverse();
}
}
bool ConvexPolygon2D::contains(const Vector2& p, bool reverse) const {
// Compute the signed area of each polygon from p to an edge.
// If the area is non-negative for all polygons then p is inside
// the polygon. (To adapt this algorithm for a concave polygon,
// the *sum* of the areas must be non-negative).
float r = reverse ? -1.0f : 1.0f;
for (int i0 = 0; i0 < m_vertex.size(); ++i0) {
int i1 = (i0 + 1) % m_vertex.size();
const Vector2& v0 = m_vertex[i0];
const Vector2& v1 = m_vertex[i1];
Vector2 e0 = v0 - p;
Vector2 e1 = v1 - p;
// Area = (1/2) cross product, negated to be ccw in
// a 2D space; we neglect the 1/2
float area = -(e0.x * e1.y - e0.y * e1.x);
if (area * r < 0) {
return false;
}
}
return true;
}
}
| 29.89083 | 112 | 0.530533 | DrYaling |
b7726f6aa53071e6a333dd5784e55ebad81a0659 | 2,367 | cpp | C++ | src/red4ext.dll/Utils.cpp | gammaparticle/RED4ext | 1d5ad2745cc806acf1111cde7e46d3f250d42474 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/red4ext.dll/Utils.cpp | gammaparticle/RED4ext | 1d5ad2745cc806acf1111cde7e46d3f250d42474 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/red4ext.dll/Utils.cpp | gammaparticle/RED4ext | 1d5ad2745cc806acf1111cde7e46d3f250d42474 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #include "stdafx.hpp"
#include "Utils.hpp"
#include "App.hpp"
std::wstring Utils::FormatErrorMessage(uint32_t aErrorCode)
{
wchar_t* buffer = nullptr;
auto errorCode = GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
errorCode, LANG_USER_DEFAULT, reinterpret_cast<LPWSTR>(&buffer), 0, nullptr);
std::wstring result = buffer;
LocalFree(buffer);
buffer = nullptr;
return result;
}
const RED4ext::VersionInfo Utils::GetRuntimeVersion()
{
auto app = App::Get();
auto filename = app->GetExecutablePath();
auto size = GetFileVersionInfoSize(filename.c_str(), nullptr);
if (!size)
{
auto err = GetLastError();
auto errMsg = Utils::FormatErrorMessage(err);
spdlog::error(L"Could not retrive game's version size, error: 0x{:X}, description: {}", err, errMsg);
return RED4EXT_SEMVER(0, 0, 0);
}
auto data = new char[size];
if (!data)
{
spdlog::error(L"Could not allocate {} bytes on stack or heap", size);
return RED4EXT_SEMVER(0, 0, 0);
}
if (!GetFileVersionInfo(filename.c_str(), 0, size, data))
{
auto err = GetLastError();
auto errMsg = Utils::FormatErrorMessage(err);
spdlog::error(L"Could not retrive game's version info, error: 0x{:X}, description: {}", err, errMsg);
delete[] data;
return RED4EXT_SEMVER(0, 0, 0);
}
VS_FIXEDFILEINFO* buffer = nullptr;
uint32_t length = 0;
if (!VerQueryValue(data, L"\\", reinterpret_cast<LPVOID*>(&buffer), &length) || !length)
{
auto err = GetLastError();
auto errMsg = Utils::FormatErrorMessage(err);
spdlog::error(L"Could not query version info, error: 0x{:X}, description: {}", err, errMsg);
delete[] data;
return RED4EXT_SEMVER(0, 0, 0);
}
if (buffer->dwSignature != 0xFEEF04BD)
{
spdlog::error(L"Retrived version signature does not match");
delete[] data;
return RED4EXT_SEMVER(0, 0, 0);
}
uint8_t major = (buffer->dwProductVersionMS >> 16) & 0xFF;
uint16_t minor = buffer->dwProductVersionMS & 0xFFFF;
uint32_t patch = (buffer->dwProductVersionLS >> 16) & 0xFFFF;
delete[] data;
return RED4EXT_SEMVER(major, minor, patch);
}
| 29.222222 | 119 | 0.635403 | gammaparticle |
b77cfa1b68cff6fbd2eca0a1d11220cf9d3b33ec | 1,158 | cpp | C++ | common/gui/win32/WinFileUtil.cpp | lesit/NeuroStudio | f505065d694a8614587e7cc243ede72c141bd80b | [
"W3C"
] | 21 | 2018-11-15T08:23:14.000Z | 2022-03-30T15:44:59.000Z | common/gui/win32/WinFileUtil.cpp | lesit/NeuroStudio | f505065d694a8614587e7cc243ede72c141bd80b | [
"W3C"
] | null | null | null | common/gui/win32/WinFileUtil.cpp | lesit/NeuroStudio | f505065d694a8614587e7cc243ede72c141bd80b | [
"W3C"
] | 1 | 2021-12-08T01:17:27.000Z | 2021-12-08T01:17:27.000Z | #include "stdafx.h"
#include "WinFileUtil.h"
using namespace np::gui::win32;
bool WinFileUtil::IsDirectory(const wchar_t* strFilePath)
{
DWORD dwAttr = GetFileAttributes(strFilePath);
if (dwAttr == INVALID_FILE_ATTRIBUTES)
return false;
return (dwAttr & FILE_ATTRIBUTE_DIRECTORY)>0;
}
bool WinFileUtil::GetNormalFileType(const wchar_t* strFilePath, bool& bDirectory)
{
DWORD dwAttr = GetFileAttributes(strFilePath);
if (dwAttr == INVALID_FILE_ATTRIBUTES)
return false;
if (dwAttr & (FILE_ATTRIBUTE_TEMPORARY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN))
return false;
bDirectory = (dwAttr & FILE_ATTRIBUTE_DIRECTORY)>0;
return true;
}
void WinFileUtil::GetSubFiles(const wchar_t* dir_path, std_wstring_vector& path_vector)
{
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile(dir_path, &findFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
DEBUG_OUTPUT(L"FindFirstFile failed (%d)", GetLastError());
return;
}
do
{
if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
continue;
path_vector.push_back(findFileData.cFileName);
} while (FindNextFile(hFind, &findFileData));
FindClose(hFind);
}
| 22.705882 | 89 | 0.765976 | lesit |
b77eb22e05e8b69ed2c7767aa7a8eab4bed43f85 | 10,700 | cpp | C++ | src/openpose/utilities/fileSystem.cpp | meiwanlanjun/openpose | 71078eb1b7571789c7589cf6c8de1786c3227a90 | [
"DOC",
"MIT-CMU"
] | null | null | null | src/openpose/utilities/fileSystem.cpp | meiwanlanjun/openpose | 71078eb1b7571789c7589cf6c8de1786c3227a90 | [
"DOC",
"MIT-CMU"
] | null | null | null | src/openpose/utilities/fileSystem.cpp | meiwanlanjun/openpose | 71078eb1b7571789c7589cf6c8de1786c3227a90 | [
"DOC",
"MIT-CMU"
] | null | null | null | #include <cstdio> // fopen
#ifdef _WIN32
#include <direct.h> // _mkdir
#include <windows.h> // DWORD, GetFileAttributesA
#elif defined __unix__
#include <dirent.h> // opendir
#include <sys/stat.h> // mkdir
#else
#error Unknown environment!
#endif
#include <openpose/utilities/string.hpp>
#include <openpose/utilities/fileSystem.hpp>
namespace op
{
void makeDirectory(const std::string& directoryPath)
{
try
{
if (!directoryPath.empty())
{
// Format the path first
const auto formatedPath = formatAsDirectory(directoryPath);
// Create dir if it doesn't exist yet
if (!existDirectory(formatedPath))
{
#ifdef _WIN32
const auto status = _mkdir(formatedPath.c_str());
#elif defined __unix__
// Create folder
// Access permission - 775 (7, 7, 4+1)
// https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html
const auto status = mkdir(formatedPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#endif
// Error if folder cannot be created
if (status != 0)
error("Could not create directory: " + formatedPath + ". Status error = "
+ std::to_string(status) + ". Does the parent folder exist and/or do you have writting"
" access to that path?", __LINE__, __FUNCTION__, __FILE__);
}
}
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
bool existDirectory(const std::string& directoryPath)
{
try
{
// Format the path first
const auto formatedPath = formatAsDirectory(directoryPath);
#ifdef _WIN32
DWORD status = GetFileAttributesA(formatedPath.c_str());
// It is not a directory
if (status == INVALID_FILE_ATTRIBUTES)
return false;
// It is a directory
else if (status & FILE_ATTRIBUTE_DIRECTORY)
return true;
// It is not a directory
return false; // this is not a directory!
#elif defined __unix__
// It is a directory
if (auto* directory = opendir(formatedPath.c_str()))
{
closedir(directory);
return true;
}
// It is not a directory
else
return false;
#else
#error Unknown environment!
#endif
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return false;
}
}
bool existFile(const std::string& filePath)
{
try
{
if (auto* file = fopen(filePath.c_str(), "r"))
{
fclose(file);
return true;
}
else
return false;
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return false;
}
}
std::string formatAsDirectory(const std::string& directoryPathString)
{
try
{
std::string directoryPath = directoryPathString;
if (!directoryPath.empty())
{
// Replace all '\\' to '/'
std::replace(directoryPath.begin(), directoryPath.end(), '\\', '/');
if (directoryPath.back() != '/')
directoryPath = directoryPath + "/";
// Windows - Replace all '/' to '\\'
#ifdef _WIN32
std::replace(directoryPath.begin(), directoryPath.end(), '/', '\\');
#endif
}
return directoryPath;
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return "";
}
}
std::string getFileNameAndExtension(const std::string& fullPath)
{
try
{
size_t lastSlashPos = fullPath.find_last_of("\\/");
if (lastSlashPos != std::string::npos)
return fullPath.substr(lastSlashPos+1, fullPath.size() - lastSlashPos - 1);
else
return fullPath;
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return "";
}
}
std::string getFileNameNoExtension(const std::string& fullPath)
{
try
{
// Name + extension
std::string nameExt = getFileNameAndExtension(fullPath);
// Name
size_t dotPos = nameExt.find_last_of(".");
if (dotPos != std::string::npos)
return nameExt.substr(0, dotPos);
else
return nameExt;
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return "";
}
}
std::string getFileExtension(const std::string& fullPath)
{
try
{
// Name + extension
std::string nameExt = getFileNameAndExtension(fullPath);
// Extension
size_t dotPos = nameExt.find_last_of(".");
if (dotPos != std::string::npos)
return nameExt.substr(dotPos + 1, nameExt.size() - dotPos - 1);
else
return "";
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return "";
}
}
// This function just removes the initial '.' in the std::string (if any)
// To avoid errors for not finding extensions because of comparing ".jpg" vs "jpg"
std::string removeExtensionDot(const std::string& extension)
{
try
{
// Extension is empty
if (extension.empty())
return "";
// Return string without initial character
else if (*extension.cbegin() == '.')
return extension.substr(1, extension.size() - 1);
// Return string itself
else
return extension;
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return "";
}
}
bool extensionIsDesired(const std::string& extension, const std::vector<std::string>& extensions)
{
try
{
const auto cleanedExtension = toLower(removeExtensionDot(extension));
for (auto& extensionI : extensions)
if (cleanedExtension == toLower(removeExtensionDot(extensionI)))
return true;
return false;
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return false;
}
}
std::vector<std::string> getFilesOnDirectory(const std::string& directoryPath,
const std::vector<std::string>& extensions)
{
try
{
// Format the path first
const auto formatedPath = formatAsDirectory(directoryPath);
// Check folder exits
if (!existDirectory(formatedPath))
error("Folder " + formatedPath + " does not exist.", __LINE__, __FUNCTION__, __FILE__);
// Read all files in folder
std::vector<std::string> filePaths;
#ifdef _WIN32
auto formatedPathWindows = formatedPath;
formatedPathWindows.append("\\*");
WIN32_FIND_DATA data;
HANDLE hFind;
if ((hFind = FindFirstFile(formatedPathWindows.c_str(), &data)) != INVALID_HANDLE_VALUE)
{
do
filePaths.emplace_back(formatedPath + data.cFileName);
while (FindNextFile(hFind, &data) != 0);
FindClose(hFind);
}
#elif defined __unix__
std::shared_ptr<DIR> directoryPtr(
opendir(formatedPath.c_str()),
[](DIR* formatedPath){ formatedPath && closedir(formatedPath); }
);
struct dirent* direntPtr;
while ((direntPtr = readdir(directoryPtr.get())) != nullptr)
{
std::string currentPath = formatedPath + direntPtr->d_name;
if ((strncmp(direntPtr->d_name, ".", 1) == 0) || existDirectory(currentPath))
continue;
filePaths.emplace_back(currentPath);
}
#else
#error Unknown environment!
#endif
// Check #files > 0
if (filePaths.empty())
error("No files were found on " + formatedPath, __LINE__, __FUNCTION__, __FILE__);
// If specific extensions specified
if (!extensions.empty())
{
// Read images
std::vector<std::string> specificExtensionPaths;
specificExtensionPaths.reserve(filePaths.size());
for (const auto& filePath : filePaths)
if (extensionIsDesired(getFileExtension(filePath), extensions))
specificExtensionPaths.emplace_back(filePath);
std::swap(filePaths, specificExtensionPaths);
}
// Sort alphabetically
std::sort(filePaths.begin(), filePaths.end());
// Return result
return filePaths;
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return {};
}
}
std::vector<std::string> getFilesOnDirectory(const std::string& directoryPath, const std::string& extension)
{
try
{
return getFilesOnDirectory(directoryPath, std::vector<std::string>{extension});
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return {};
}
}
}
| 34.96732 | 117 | 0.497383 | meiwanlanjun |
b7828e490770598d7cbe06bfad2e50233ce92d64 | 1,838 | hpp | C++ | src/backnocles/utils/disablewarnings.hpp | dsiroky/backnocles | 889ab5f65fc1beb27f6dfff36d5fcda8544a9be2 | [
"MIT"
] | 3 | 2017-10-22T17:57:10.000Z | 2017-11-06T12:33:31.000Z | src/backnocles/utils/disablewarnings.hpp | dsiroky/backnocles | 889ab5f65fc1beb27f6dfff36d5fcda8544a9be2 | [
"MIT"
] | null | null | null | src/backnocles/utils/disablewarnings.hpp | dsiroky/backnocles | 889ab5f65fc1beb27f6dfff36d5fcda8544a9be2 | [
"MIT"
] | null | null | null | /// Place this include above thirdparty includes. Pair with enablewarnings.hpp.
///
/// Project has very restrictive warnings and lots of libraries does not
/// conform to that. MSVC++ does not have "-isystem" equivalent.
///
/// @file
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4244)
#pragma warning(disable: 4245)
#pragma warning(disable: 4251)
#pragma warning(disable: 4290)
#pragma warning(disable: 4913)
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-align"
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
#pragma GCC diagnostic ignored "-Wdeprecated"
#pragma GCC diagnostic ignored "-Wfloat-equal"
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wsign-promo"
#pragma GCC diagnostic ignored "-Wswitch-default"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#ifndef __APPLE__
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#ifdef __clang__
#ifndef __APPLE__
#pragma GCC diagnostic ignored "-Winconsistent-missing-override"
#endif
#pragma GCC diagnostic ignored "-Wfloat-conversion"
#pragma GCC diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#pragma GCC diagnostic ignored "-Wparentheses-equality"
#if __clang_major__ * 100 + __clang_minor__ >= 309
#ifndef __APPLE__
#pragma GCC diagnostic ignored "-Wexpansion-to-defined"
#endif
#pragma GCC diagnostic ignored "-Wnull-dereference"
#endif
#endif
#endif
| 37.510204 | 79 | 0.73667 | dsiroky |
b783c70fbc58bdd7d14e497c5f0d07c4cb71122b | 320 | cpp | C++ | DwarfDash/src/Geometry.cpp | Zai-shen/DwarfDash | 2a991a33dc4550bdf89a665a092b0b8db6a03724 | [
"MIT"
] | null | null | null | DwarfDash/src/Geometry.cpp | Zai-shen/DwarfDash | 2a991a33dc4550bdf89a665a092b0b8db6a03724 | [
"MIT"
] | null | null | null | DwarfDash/src/Geometry.cpp | Zai-shen/DwarfDash | 2a991a33dc4550bdf89a665a092b0b8db6a03724 | [
"MIT"
] | null | null | null | #include "Geometry.h"
glm::mat4 Geometry::getModelMatrix() {
return _modelMatrix;
}
void Geometry::setTransformMatrix(glm::mat4 transformationMatrix) {
_transformMatrix = transformationMatrix;
}
//void Geometry::transform(glm::mat4 transformationMatrix) {
// _modelMatrix = _modelMatrix * transformationMatrix;
//} | 22.857143 | 67 | 0.775 | Zai-shen |
b785a7ba88c2fcb13ae1a182ee56c29a5e6721f2 | 8,966 | cpp | C++ | game/graphics/texture/jak1_tpage_dir.cpp | Hat-Kid/jak-project | 0e2320ca9584118316313e41e646b179a1083feb | [
"ISC"
] | 54 | 2022-02-08T13:07:50.000Z | 2022-03-31T14:18:42.000Z | game/graphics/texture/jak1_tpage_dir.cpp | Hat-Kid/jak-project | 0e2320ca9584118316313e41e646b179a1083feb | [
"ISC"
] | 120 | 2022-02-08T05:19:11.000Z | 2022-03-30T22:26:52.000Z | game/graphics/texture/jak1_tpage_dir.cpp | Hat-Kid/jak-project | 0e2320ca9584118316313e41e646b179a1083feb | [
"ISC"
] | 8 | 2022-02-13T22:39:55.000Z | 2022-03-30T02:17:57.000Z | #include <vector>
#include "common/common_types.h"
#include "jak1_tpage_dir.h"
namespace {
std::vector<u32> tpage_dir = {
0x0, 0x2, 0x37, 0x1, 0x1, 0x10, 0x2, 0x4, 0x3, 0x2, 0x1, 0x5, 0x7, 0x8, 0x1, 0x1, 0x1, 0xb, 0xe,
0x8, 0x1, 0x6, 0x4, 0x6, 0x3, 0x3, 0x6, 0x6, 0x4, 0x4, 0x4, 0xd, 0x1, 0x4, 0x9, 0xc, 0x1, 0x1,
0x6, 0x3, 0x2, 0x14, 0x1, 0x1, 0x2, 0x2, 0x34, 0x34, 0x4, 0x15, 0x1, 0x1, 0x1, 0x8, 0x6, 0xb,
0xb, 0x7, 0x17, 0x1, 0x7, 0x20, 0xd, 0xa, 0x1, 0x1, 0xb, 0x11, 0x2, 0x9, 0xb, 0xa, 0xe, 0x1,
0x6, 0x6, 0x1, 0x2, 0x2, 0x33, 0x33, 0xd, 0x2, 0x9, 0x4, 0x68, 0x1, 0x9, 0x1, 0x2, 0x1, 0x5,
0x9, 0x7, 0x14, 0xa, 0x1, 0x1, 0x1, 0x2, 0x10, 0x4, 0x2, 0x17, 0x2, 0x1, 0x13, 0x6, 0x1, 0x1,
0x1, 0x2, 0x1, 0x16, 0x1, 0x5, 0x1, 0xe, 0x3, 0x2, 0x1, 0x9, 0x15, 0x3, 0x1, 0x2, 0x40, 0x6,
0xb, 0x9, 0x2, 0x8, 0xf, 0x2, 0x2, 0x7, 0x11, 0x5, 0x7, 0x13, 0x9, 0x1, 0x1, 0x1, 0x8, 0x1, 0x1,
0x1, 0x1, 0x1, 0x2, 0x2, 0x9, 0x2, 0xb, 0x5, 0x1, 0xa, 0x15, 0x2e, 0x4, 0x22, 0xb, 0x2e, 0x1e,
0x6, 0x4, 0x6, 0x3, 0x3, 0x6, 0x6, 0x2, 0x19, 0x5, 0x5, 0x8, 0x37, 0x15, 0x2, 0x1, 0x1, 0x4,
0x4, 0x8, 0x9, 0x9, 0x9, 0x9, 0x8, 0x6, 0x1e, 0x7, 0x1, 0x5, 0x9, 0x72, 0xc, 0x5, 0x16, 0x5,
0x4, 0x1, 0x6, 0x3, 0x3, 0x3, 0x3, 0x1, 0x1, 0x1c, 0xa3, 0x47, 0x1b, 0xc9, 0xa, 0x1, 0x16, 0x1,
0x4, 0x4, 0x4, 0x4, 0x4, 0xd, 0x4, 0xc, 0x2d, 0x4, 0x1, 0x1, 0xf, 0x2, 0x2, 0x10, 0x3, 0x3, 0x1,
0x1, 0x1, 0x1, 0x1, 0x4, 0x4, 0x9, 0x9, 0x5, 0x6, 0xa, 0x4, 0x1, 0x5, 0x4, 0x9, 0x2, 0x1, 0x4,
0x2, 0x2, 0x3, 0x12, 0xa, 0x8, 0x4, 0x5, 0x1, 0x1, 0x6, 0x6, 0x7, 0xf, 0x1d, 0x4, 0x4, 0x93,
0x1, 0x2, 0x15, 0x1, 0xc, 0x1, 0xb, 0x1, 0x5, 0x1e, 0x1, 0x3c, 0x10, 0x5, 0x4, 0x5, 0x3, 0xb,
0x4, 0x8, 0x4, 0x4, 0x9, 0x6, 0x3, 0x1d, 0x2e, 0x1, 0x3, 0x15, 0xb, 0x1, 0x1, 0x1, 0x2, 0x1,
0x1, 0x1, 0x1, 0x9, 0x8, 0x1a, 0x5, 0xe, 0x1, 0x1e, 0xc, 0x57, 0x71, 0x1, 0x4, 0x8, 0x5, 0x15,
0x7, 0xa, 0x1f, 0xc, 0x6, 0x12, 0x1, 0x2, 0x9, 0x4c, 0xa, 0xc9, 0x1, 0x8, 0x8, 0x1b, 0x8, 0x1d,
0x15, 0x1, 0x19, 0x97, 0x6c, 0xd, 0x3, 0x4, 0x4, 0x2, 0x2, 0x3d, 0xa, 0x36, 0x4, 0x8, 0x21,
0x15, 0x1, 0x1, 0x2, 0x6, 0x2, 0xb, 0x6, 0xb, 0xc, 0x5, 0x4, 0x15, 0x14, 0x1, 0x21, 0x5, 0x6,
0xb, 0x1, 0x1b, 0x57, 0x1e, 0x2, 0xc, 0x16, 0x9, 0x5, 0x9, 0x1, 0x1, 0x2f, 0x1a, 0x9, 0x80,
0x19, 0x97, 0xd, 0x26, 0x8, 0xb, 0x8, 0x1, 0x6, 0x4, 0x1, 0x2, 0x1c, 0x9, 0x13, 0xe, 0x8, 0x1,
0x1, 0x8, 0x4, 0x6, 0x1, 0xd, 0x6, 0x1c, 0x8, 0x1, 0x1d, 0x1, 0x3, 0x4, 0x2, 0x2, 0x1, 0x1,
0x12, 0x3d, 0x13, 0x5, 0x1, 0x25, 0x1, 0x1, 0xb, 0xa, 0x1, 0xe, 0x1, 0xb, 0xa, 0xb, 0x1, 0x38,
0x5, 0x8, 0x1, 0x2, 0x51, 0xc, 0x2, 0x1, 0x5, 0x2, 0x7a, 0x5, 0x5, 0x1, 0x1, 0x2, 0x1, 0x1, 0x7,
0xe, 0xd, 0x2, 0x4, 0x1, 0x1, 0xc, 0x5, 0x3, 0x1, 0x2, 0x24, 0x15, 0x24, 0x8, 0x11, 0x1, 0x1,
0x1, 0x5, 0x1, 0x1, 0x8, 0x2, 0x2, 0x1, 0x1, 0xb, 0xa, 0xa, 0x5, 0x1, 0x1d, 0x4, 0x6, 0x2, 0x4,
0x9, 0x15, 0x4, 0x4, 0x1, 0x6, 0x2, 0x5c, 0x70, 0x9, 0x1, 0xc, 0x74, 0x5, 0x2, 0x7, 0x2, 0x4,
0x2, 0x5, 0x19, 0x1, 0x71, 0x4, 0x8, 0x6, 0x2, 0x2, 0x2, 0x11, 0x11, 0x2, 0x6, 0x5, 0xa, 0x2,
0x1, 0x2, 0x4, 0xf, 0x3b, 0x2, 0x5, 0x5, 0x4, 0x5, 0x4, 0xf, 0xd, 0x2, 0x2, 0x2, 0x7, 0x3f, 0xc,
0x9, 0x3a, 0xa, 0x15, 0x14, 0x4, 0x4, 0x1, 0xa, 0x9, 0x8, 0x1, 0x7, 0x5b, 0x9, 0x13, 0x1c, 0x18,
0x5, 0x5, 0x6, 0x18, 0x4, 0x8, 0x14, 0x3a, 0x13, 0x1, 0x43, 0x4, 0x3, 0x17, 0x1, 0x16, 0x15,
0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x8a, 0x1, 0x4, 0x1, 0x1, 0x8, 0x1, 0x1, 0x1, 0x1, 0x9, 0x6, 0x6,
0x1, 0x13, 0xa, 0x10, 0x5, 0x3, 0x6, 0x6, 0x3, 0x3, 0x4, 0xf, 0x13, 0xb, 0x3, 0x1, 0x1, 0x3,
0x3, 0x3, 0x14, 0x13, 0x6, 0x15, 0xa, 0x1, 0x5, 0x4, 0x1, 0x2, 0x5, 0x2, 0xd, 0x9, 0xf, 0x5d,
0x9, 0x47, 0xd, 0x6, 0x5, 0x5d, 0xa, 0x47, 0x15, 0x42, 0x9, 0x6, 0x3, 0x5, 0x2, 0xe, 0xd, 0x11,
0x4, 0x5, 0x2, 0x1, 0x15, 0x1, 0x1, 0x4, 0x2, 0x13, 0xf, 0x11, 0x11, 0x2, 0xa, 0x9, 0x5, 0x5,
0x7, 0x5, 0x4, 0x3, 0x4, 0x13, 0x5, 0xb, 0x1, 0x12, 0x12, 0x4, 0x13, 0x1, 0x1, 0x1, 0x1, 0xc,
0x11, 0x9, 0x5b, 0xa, 0x13, 0xd, 0xa, 0x8, 0x1, 0x1, 0x2, 0x9, 0x6, 0x1, 0x1, 0x1, 0x2, 0x1,
0x1, 0xa, 0x9, 0x2, 0xf, 0x1, 0x8, 0x3, 0x9, 0x3, 0x1, 0x9, 0x6, 0x6, 0x5, 0x2, 0x5, 0x2, 0x5,
0x3, 0x1, 0x57, 0x3, 0x1, 0x1, 0x7, 0x3, 0x1, 0x9, 0x7, 0x3, 0x3, 0x3, 0xb1, 0x2, 0x1, 0x12,
0x2b, 0x3, 0x1, 0x3, 0x2, 0x4, 0x1, 0x2, 0x5, 0x6, 0xd, 0x1, 0x1, 0x1, 0x2, 0x2, 0x6, 0x5, 0x2,
0x2, 0x2, 0x10, 0x1, 0x1, 0x24, 0x1, 0x1, 0x1, 0x1, 0x6, 0x4, 0x7, 0x21, 0x2, 0x9, 0xa, 0xa,
0x16, 0xb, 0x34, 0x5, 0x3, 0x10, 0x1, 0x1, 0x2e, 0x13, 0x2, 0x13, 0x1, 0x1, 0x1, 0x25, 0x13,
0x4, 0x47, 0x8, 0x7, 0x4, 0x35, 0x1, 0xb, 0x19, 0x2, 0x2, 0x8, 0x8, 0x7, 0x10, 0xd, 0x6, 0x6,
0xa, 0x3, 0x6a, 0x13, 0x18, 0x12, 0x3, 0x57, 0x1d, 0x1, 0xb, 0x5, 0x4, 0x7, 0x1, 0x1, 0x2, 0x2,
0x2, 0x7, 0x15, 0x2f, 0x1, 0x2, 0xb, 0x4, 0x4, 0x3, 0x5, 0xb, 0xa, 0x9, 0x1, 0x4, 0x5, 0x3, 0x3,
0x3, 0xb, 0x1b, 0x32, 0x9, 0x4, 0x4, 0x1, 0x1, 0x15, 0x1d, 0x13, 0x12, 0x6, 0xe, 0x4, 0x2, 0x7,
0x2, 0xc, 0x6, 0x2, 0x5, 0x3, 0x3, 0x9, 0x7, 0xe, 0x9, 0x2, 0x1, 0x3, 0x5, 0x3, 0x3, 0x4, 0x4,
0x3, 0x6, 0x5, 0x5, 0x19, 0x6, 0x3, 0x1, 0x11, 0x12, 0x84, 0x1c, 0x19, 0xa3, 0x2e, 0xe, 0x13,
0x47, 0x1, 0x1, 0xc, 0x2, 0x1, 0x5, 0x4, 0x5, 0x4, 0x8, 0x7, 0x7, 0x5, 0x5, 0x3, 0xa, 0x5, 0x3,
0x5, 0x4, 0x1, 0x6, 0x4, 0x4, 0x1, 0xe, 0x7, 0x2, 0x15, 0x2, 0x2, 0x14, 0x1, 0xc, 0xa, 0x5d,
0x4, 0x3, 0x2, 0xa, 0x5d, 0x19, 0x1, 0x2, 0x1, 0x1, 0xa, 0x14, 0x1, 0x12, 0x2, 0x2, 0x2, 0x2,
0x2, 0x2, 0x17, 0x1, 0x1, 0x13, 0x2, 0x2, 0x1, 0x3, 0x1a, 0x5, 0x15, 0x1, 0x5, 0x1, 0x1a, 0x2,
0x1, 0xc, 0x6, 0x1, 0x1, 0x1, 0x1, 0x7, 0x7, 0x7, 0xc, 0xd, 0xd, 0x10, 0x1b, 0x1, 0x1, 0x1, 0x1,
0x1, 0x1, 0x5, 0x2, 0x4d, 0x2b, 0x8, 0x1, 0x2, 0x1, 0x1, 0x1, 0x1, 0x1, 0x9, 0xe, 0xb, 0xa, 0x1,
0xb, 0x1, 0xb, 0xa, 0x1, 0x2, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x9, 0x1, 0x1, 0x15, 0x11, 0x1, 0x8,
0x1, 0x5, 0x1, 0x1, 0x5, 0x4, 0x4, 0x5, 0xb, 0x6, 0x7, 0x2, 0x1, 0x1, 0x2, 0x1, 0x19, 0x19, 0x2,
0x2, 0x2, 0x6, 0x8, 0x3, 0x3, 0x4, 0x8, 0x8, 0x3, 0x1, 0x1a, 0xe, 0x3, 0x1, 0xf, 0x1, 0x9, 0x4,
0xc, 0x5, 0x5, 0x6, 0x1, 0x3b, 0x16, 0x8, 0x7, 0x2, 0x5, 0x32, 0xd, 0x2, 0x55, 0xe, 0x3, 0x14,
0x3, 0x9, 0x9, 0x3, 0x2, 0x12, 0x12, 0x8, 0x14, 0x13, 0x12, 0x12, 0x9, 0xa, 0x39, 0xf, 0x7, 0x6,
0x2, 0x1, 0x5, 0x9, 0x9, 0x9, 0x1, 0x9, 0xe, 0x18, 0x1, 0x3, 0x9, 0x3, 0x9, 0x1, 0x4, 0x2, 0x4,
0x4, 0x2, 0x9, 0x9, 0x9, 0x3, 0x1, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x3, 0x16, 0x5, 0x2,
0x2, 0x3, 0x1, 0x9, 0x3, 0x3f, 0x28, 0x9, 0x26, 0x9, 0xa, 0x65, 0x39, 0xc, 0x15, 0x9, 0x1, 0x2,
0x7, 0xb, 0xc, 0xb, 0xb, 0x2e, 0x4, 0x1e, 0x15, 0x1, 0x2, 0x1, 0x1, 0x2, 0x3, 0x2, 0x2, 0xb,
0x9, 0x1, 0x4, 0x4, 0x65, 0x16, 0x8f, 0x1, 0x10, 0xf, 0xf, 0x7, 0x9, 0x41, 0x9, 0xb, 0xb, 0xe,
0x12, 0x20, 0x2, 0x2, 0x2, 0x2, 0x2, 0x9, 0x15, 0x2, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1,
0x1, 0x1, 0x1, 0xa, 0xd, 0xd, 0x9, 0x1, 0x1, 0xd, 0x68, 0x17, 0x94, 0x1, 0xf, 0x1, 0x1, 0x1,
0xd, 0x79, 0x17, 0x94, 0xd, 0xf, 0x10, 0x16, 0xf, 0x13, 0xd, 0xc, 0x10, 0xb, 0x8, 0x4, 0x2, 0x2,
0x1, 0xb, 0x4, 0x9, 0x61, 0x1, 0x2, 0x7, 0xb, 0xb, 0xf, 0xa, 0x1d, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2,
0x2, 0x2, 0x10, 0x4, 0x5, 0x1, 0x9, 0x9, 0x1, 0x9, 0x3, 0x3f, 0x13, 0x9, 0x41, 0xa, 0x20, 0x9,
0x3f, 0xc, 0x3a, 0x9, 0xa, 0x63, 0x39, 0x1, 0xb, 0xb, 0x1, 0xa, 0x6, 0x1, 0x4, 0x4, 0x4, 0x18,
0xa, 0x39, 0x10, 0x19, 0x7, 0x8, 0x9, 0x53, 0x6, 0x2b, 0x1, 0x2, 0x1, 0x2, 0x5, 0x3, 0x1, 0x1,
0x2, 0xd, 0x9, 0x2, 0x1, 0x17, 0x3, 0x1, 0xc, 0xf, 0x10, 0x16, 0x1, 0xd, 0x9, 0x4, 0x7, 0xd,
0xb, 0xd, 0xc, 0xc, 0x1a, 0x2, 0xc, 0x15, 0x2, 0x2, 0xd, 0x1, 0x1, 0xa, 0x8, 0x8, 0xa, 0xa, 0xa,
0x8, 0x7, 0xd, 0x9, 0x2, 0x3, 0xf, 0xb, 0xf, 0xf, 0x1, 0xd, 0xa, 0x14, 0x11, 0x16, 0x12, 0x1,
0x7, 0x1, 0x2, 0x2, 0x1, 0x9, 0x9, 0x2, 0x2, 0x3, 0x9, 0x61, 0x5, 0xb1, 0x12, 0x2a, 0x4a, 0x6,
0x2, 0x6, 0x13, 0x13, 0x1, 0x2f, 0xb, 0x12, 0x9, 0x3e, 0x4, 0x28, 0x2, 0x1, 0x4, 0x5, 0x3, 0x3,
0x4, 0x1, 0xf, 0x19, 0x10, 0x1, 0x1, 0x1, 0x1, 0x1, 0x9, 0x17, 0x27, 0x3, 0x9, 0x7, 0x3, 0x27,
0x2, 0x1, 0x5, 0x6, 0xe, 0x8, 0x8, 0x1, 0x8, 0x9, 0x3, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1a, 0x1,
0x10, 0x3, 0x9, 0x1, 0x9, 0x9, 0x9, 0x9, 0x3, 0x3, 0x3, 0x19, 0x9, 0x3a, 0x3, 0x1, 0x5, 0x11,
0xa, 0xa, 0x1, 0x11, 0x1, 0x1, 0x1, 0x4, 0x4, 0x4, 0x6, 0x9, 0x9, 0x2, 0x3, 0xa, 0xf, 0x8, 0x6,
0x7, 0xb, 0x9, 0xa, 0x5, 0xa, 0x5, 0x9, 0x6, 0x9, 0x4, 0x1, 0x3, 0x3, 0x4, 0x4, 0x3, 0x3, 0xa,
0x11, 0x9, 0xe, 0x11, 0xe, 0x8, 0x7, 0x8, 0x7, 0x8, 0x4, 0x5, 0x6, 0x5, 0xa, 0x5, 0xe, 0xd, 0x5,
0xe, 0xd, 0x5, 0x5, 0x5, 0x6, 0x5, 0x6, 0xf, 0x8, 0x8, 0x7, 0x6, 0x8, 0x3, 0x1, 0x5, 0x1, 0x1,
0x4, 0x4, 0x1, 0x1, 0x9, 0x2, 0xd, 0x7, 0xc, 0xc, 0xa, 0x6, 0x4, 0x1, 0x1, 0x3, 0x2, 0x9, 0x4,
0x2, 0x2, 0x4, 0x4, 0x1, 0x4, 0x2, 0x21, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x2,
0x3,
// Pc port texture page:
EXTRA_PC_PORT_TEXTURE_COUNT};
}
const std::vector<u32> get_jak1_tpage_dir() {
return tpage_dir;
} | 87.901961 | 100 | 0.593241 | Hat-Kid |
b7919637242c503f2e2d26342b5b56d84824bc24 | 14,642 | cpp | C++ | depricated/acyclic_graph_nodes.cpp | imikejackson/bingocpp | 6ba00a490c8cb46edebfd78f56b1604a76d668e9 | [
"Apache-2.0"
] | 13 | 2019-03-14T09:54:02.000Z | 2021-09-26T14:01:30.000Z | depricated/acyclic_graph_nodes.cpp | imikejackson/bingocpp | 6ba00a490c8cb46edebfd78f56b1604a76d668e9 | [
"Apache-2.0"
] | 35 | 2019-08-29T19:12:05.000Z | 2021-07-15T22:17:53.000Z | depricated/acyclic_graph_nodes.cpp | imikejackson/bingocpp | 6ba00a490c8cb46edebfd78f56b1604a76d668e9 | [
"Apache-2.0"
] | 9 | 2018-10-18T02:43:03.000Z | 2021-09-02T22:08:39.000Z | /*!
* \file acyclic_graph_nodes.cc
*
* \author Ethan Adams
* \date 2/6/2018
*
* This file contains the functions associated with each class
* implementation of Operation.
*/
#include "BingoCpp/acyclic_graph_nodes.h"
namespace agraphnodes{
namespace {
void x_load_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = x.col(stack(result_location, 1));
}
void x_load_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
}
void c_load_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
if (stack(result_location, 1) != -1) {
buffer[result_location] = Eigen::ArrayXXd::Constant(x.rows(), 1,
constants[stack(result_location, 1)]);
} else {
buffer[result_location] = Eigen::ArrayXXd::Zero(x.rows(), 1);
}
}
void c_load_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
}
void addition_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = buffer[stack(result_location, 1)] +
buffer[stack(result_location, 2)];
}
void addition_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
if (stack(dependency, 1) == command_index) {
reverse_buffer[command_index] += reverse_buffer[dependency];
}
if (stack(dependency, 2) == command_index) {
reverse_buffer[command_index] += reverse_buffer[dependency];
}
}
void subtraction_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = buffer[stack(result_location, 1)] -
buffer[stack(result_location, 2)];
}
void subtraction_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
if (stack(dependency, 1) == command_index) {
reverse_buffer[command_index] += reverse_buffer[dependency];
}
if (stack(dependency, 2) == command_index) {
reverse_buffer[command_index] -= reverse_buffer[dependency];
}
}
void multiplication_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = buffer[stack(result_location, 1)] *
buffer[stack(result_location, 2)];
}
void multiplication_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
if (stack(dependency, 1) == command_index) {
reverse_buffer[command_index] += reverse_buffer[dependency] *
forward_buffer[stack(dependency, 2)];
}
if (stack(dependency, 2) == command_index) {
reverse_buffer[command_index] += reverse_buffer[dependency] *
forward_buffer[stack(dependency, 1)];
}
}
void division_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = buffer[stack(result_location, 1)] /
buffer[stack(result_location, 2)];
}
void division_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
if (stack(dependency, 1) == command_index) {
reverse_buffer[command_index] += reverse_buffer[dependency] /
forward_buffer[stack(dependency, 2)];
}
if (stack(dependency, 2) == command_index) {
reverse_buffer[command_index] += reverse_buffer[dependency] *
(-forward_buffer[dependency] /
forward_buffer[stack(dependency, 2)]);
}
}
void sin_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = buffer[stack(result_location, 1)].sin();
}
void sin_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
reverse_buffer[command_index] += reverse_buffer[dependency] *
forward_buffer[stack(dependency, 1)].cos();
}
void cos_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = buffer[stack(result_location, 1)].cos();
}
void cos_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
reverse_buffer[command_index] -= reverse_buffer[dependency] *
forward_buffer[stack(dependency, 1)].sin();
}
void exp_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = buffer[stack(result_location, 1)].exp();
}
void exp_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
reverse_buffer[command_index] += reverse_buffer[dependency] *
forward_buffer[dependency];
}
void log_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = (buffer[stack(result_location, 1)].abs()).log();
}
void log_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
reverse_buffer[command_index] += reverse_buffer[dependency] /
forward_buffer[stack(dependency, 1)];
}
void power_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = (buffer[stack(result_location, 1)].abs()).pow(
buffer[stack(result_location, 2)]);
}
void power_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
if (stack(dependency, 1) == command_index) {
reverse_buffer[command_index] += forward_buffer[dependency] *
reverse_buffer[dependency] *
forward_buffer[stack(dependency, 2)] /
forward_buffer[stack(dependency, 1)];
}
if (stack(dependency, 2) == command_index) {
reverse_buffer[command_index] += forward_buffer[dependency] *
reverse_buffer[dependency] *
(forward_buffer[stack(dependency, 1)].abs()).log();
}
}
void absolute_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = buffer[stack(result_location, 1)].abs();
}
void absolute_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
reverse_buffer[command_index] += reverse_buffer[dependency] *
forward_buffer[stack(dependency, 1)].sign();
}
void sqrt_evaluate(const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
buffer[result_location] = (buffer[stack(result_location, 1)].abs()).sqrt();
}
void sqrt_deriv_evaluate(const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
reverse_buffer[command_index] += 0.5 * reverse_buffer[dependency] /
forward_buffer[dependency] *
forward_buffer[stack(dependency, 1)].sign();
}
} //namespace
const std::vector<forward_operator_function> forward_eval_map {
x_load_evaluate,
c_load_evaluate,
addition_evaluate,
subtraction_evaluate,
multiplication_evaluate,
division_evaluate,
sin_evaluate,
cos_evaluate,
exp_evaluate,
log_evaluate,
power_evaluate,
absolute_evaluate,
sqrt_evaluate
};
const std::vector<derivative_operator_function> derivative_eval_map {
x_load_deriv_evaluate,
c_load_deriv_evaluate,
addition_deriv_evaluate,
subtraction_deriv_evaluate,
multiplication_deriv_evaluate,
division_deriv_evaluate,
sin_deriv_evaluate,
cos_deriv_evaluate,
exp_deriv_evaluate,
log_deriv_evaluate,
power_deriv_evaluate,
absolute_deriv_evaluate,
sqrt_deriv_evaluate
};
void forward_eval_function(int node, const Eigen::ArrayX3i &stack,
const Eigen::ArrayXXd &x,
const Eigen::VectorXd &constants,
std::vector<Eigen::ArrayXXd> &buffer,
std::size_t result_location) {
forward_eval_map.at(node)(stack, x, constants, buffer, result_location);
}
void derivative_eval_function(int node, const Eigen::ArrayX3i &stack,
const int command_index,
const std::vector<Eigen::ArrayXXd> &forward_buffer,
std::vector<Eigen::ArrayXXd> &reverse_buffer,
int dependency) {
derivative_eval_map.at(node)(stack, command_index, forward_buffer, reverse_buffer, dependency);
}
} | 46.044025 | 99 | 0.523562 | imikejackson |
b7962ad897f8c79a4958223474666710ab234556 | 3,059 | cpp | C++ | GP/FrmProj.cpp | wsu-cb/cbwindows | 55d3797ed0c639b36fe3f677777fcc31e3449360 | [
"MIT"
] | 4 | 2020-06-22T16:59:51.000Z | 2020-06-28T19:35:23.000Z | GP/FrmProj.cpp | wsu-cb/cbwindows | 55d3797ed0c639b36fe3f677777fcc31e3449360 | [
"MIT"
] | 59 | 2020-09-12T23:54:16.000Z | 2022-03-24T18:51:43.000Z | GP/FrmProj.cpp | wsu-cb/cbwindows | 55d3797ed0c639b36fe3f677777fcc31e3449360 | [
"MIT"
] | 4 | 2020-06-22T13:37:40.000Z | 2021-01-29T12:42:54.000Z | // FrmProg.cpp
//
// Copyright (c) 1994-2020 By Dale L. Larson, 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.
//
#include "stdafx.h"
#include "Gp.h"
#include "GamDoc.h"
#include "FrmProj.h"
#include "VwPrjgsn.h"
#include "VwPrjgam.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CProjFrame
IMPLEMENT_DYNCREATE(CProjFrame, CMDIChildWndEx)
CProjFrame::CProjFrame()
{
}
CProjFrame::~CProjFrame()
{
}
BEGIN_MESSAGE_MAP(CProjFrame, CMDIChildWndEx)
//{{AFX_MSG_MAP(CProjFrame)
ON_WM_SYSCOMMAND()
//}}AFX_MSG_MAP
ON_WM_CLOSE()
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CProjFrame message handlers
BOOL CProjFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if (!CMDIChildWndEx::PreCreateWindow(cs))
return FALSE;
cs.style |= WS_CLIPCHILDREN;
cs.style &= ~(DWORD)FWS_ADDTOTITLE;
return TRUE;
}
void CProjFrame::OnUpdateFrameTitle(BOOL bAddToTitle)
{
CGamDoc* pDoc = (CGamDoc*)GetActiveDocument();
CString str = pDoc->GetTitle();
str += " - ";
CString strType;
if (pDoc->IsScenario())
strType.LoadString(IDS_PROJTYPE_SCENARIO);
else
strType.LoadString(IDS_PROJTYPE_GAME);
str += strType;
SetWindowText(str);
}
void CProjFrame::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == SC_CLOSE)
{
CView *pView = GetActiveView();
if (pView)
{
if (pView->IsKindOf(RUNTIME_CLASS(CGsnProjView)) ||
pView->IsKindOf(RUNTIME_CLASS(CGamProjView)))
{
((CGamDoc*)GetActiveDocument())->OnFileClose();
return;
}
}
}
CMDIChildWndEx::OnSysCommand(nID, lParam);
}
void CProjFrame::OnClose()
{
// Close the document when the main document window is closed.
((CGamDoc*)GetActiveDocument())->OnFileClose();
}
| 28.324074 | 77 | 0.652501 | wsu-cb |
b7979d4151b9fc7fe8cc8bc8d2db246cdb4860fc | 2,018 | hh | C++ | include/Apertures/StandardAperturePolygon.hh | aaronbamberger/gerber_rs274x_parser | d2bbd6c66d322ab47715771642255f8302521300 | [
"BSD-2-Clause"
] | 6 | 2016-09-28T18:26:42.000Z | 2021-04-10T13:19:05.000Z | include/Apertures/StandardAperturePolygon.hh | aaronbamberger/gerber_rs274x_parser | d2bbd6c66d322ab47715771642255f8302521300 | [
"BSD-2-Clause"
] | 1 | 2021-02-09T00:24:04.000Z | 2021-02-27T22:08:05.000Z | include/Apertures/StandardAperturePolygon.hh | aaronbamberger/gerber_rs274x_parser | d2bbd6c66d322ab47715771642255f8302521300 | [
"BSD-2-Clause"
] | 5 | 2017-09-14T09:48:17.000Z | 2021-07-19T07:58:34.000Z | /*
* Copyright 2021 Aaron Bamberger
* Licensed under BSD 2-clause license
* See LICENSE file at root of source tree,
* or https://opensource.org/licenses/BSD-2-Clause
*/
#ifndef _STANDARD_APERTURE_POLYGON_H
#define _STANDARD_APERTURE_POLYGON_H
#include "Apertures/StandardAperture.hh"
#include "GlobalDefs.hh"
#include "SemanticIssueList.hh"
#include "location.hh"
#include <iostream>
#include <memory>
class StandardAperturePolygon : public StandardAperture {
public:
StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle, double hole_diameter);
StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle);
StandardAperturePolygon(double diameter, double num_vertices);
StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle, double hole_diameter,
yy::location diameter_location, yy::location num_vertices_location, yy::location rotation_angle_location,
yy::location hole_diameter_location, yy::location location);
StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle,
yy::location diameter_location, yy::location num_vertices_location, yy::location rotation_angle_location,
yy::location location);
StandardAperturePolygon(double diameter, double num_vertices,
yy::location diameter_location, yy::location num_vertices_location, yy::location location);
virtual ~StandardAperturePolygon();
private:
Gerber::SemanticValidity do_check_semantic_validity(SemanticIssueList& issue_list);
std::ostream& do_print(std::ostream& os) const;
std::shared_ptr<StandardAperture> do_clone();
double m_diameter;
double m_num_vertices;
double m_rotation_angle;
double m_hole_diameter;
bool m_has_rotation;
bool m_has_hole;
yy::location m_diameter_location;
yy::location m_num_vertices_location;
yy::location m_rotation_angle_location;
yy::location m_hole_diameter_location;
yy::location m_location;
};
#endif // _STANDARD_APERTURE_POLYGON_H
| 38.075472 | 113 | 0.806739 | aaronbamberger |
b79d98c9ccf6ae2243b193a04a675881028db9e4 | 12,562 | cpp | C++ | core/RTAudio.cpp | amilo/soundcoreA | 30b14ce3d34f74c2385126fc244a0c252c3aa4c4 | [
"MIT"
] | null | null | null | core/RTAudio.cpp | amilo/soundcoreA | 30b14ce3d34f74c2385126fc244a0c252c3aa4c4 | [
"MIT"
] | null | null | null | core/RTAudio.cpp | amilo/soundcoreA | 30b14ce3d34f74c2385126fc244a0c252c3aa4c4 | [
"MIT"
] | null | null | null | /*
* RTAudio.cpp
*
* Central control code for hard real-time audio on BeagleBone Black
* using PRU and Xenomai Linux extensions. This code began as part
* of the Hackable Instruments project (EPSRC) at Queen Mary University
* of London, 2013-14.
*
* (c) 2014 Victor Zappi and Andrew McPherson
* Queen Mary University of London
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include <iostream>
#include <assert.h>
#include <vector>
// Xenomai-specific includes
#include <sys/mman.h>
#include <native/task.h>
#include <native/timer.h>
#include <rtdk.h>
#include "../include/RTAudio.h"
#include "../include/PRU.h"
#include "../include/I2c_Codec.h"
#include "../include/render.h"
#include "../include/GPIOcontrol.h"
using namespace std;
// Data structure to keep track of auxiliary tasks we
// can schedule
typedef struct {
RT_TASK task;
void (*function)(void);
char *name;
int priority;
} InternalAuxiliaryTask;
const char gRTAudioThreadName[] = "beaglert-audio";
// Real-time tasks and objects
RT_TASK gRTAudioThread;
PRU *gPRU = 0;
I2c_Codec *gAudioCodec = 0;
vector<InternalAuxiliaryTask*> gAuxTasks;
// Flag which tells the audio task to stop
bool gShouldStop = false;
// general settings
int gRTAudioVerbose = 0; // Verbosity level for debugging
int gAmplifierMutePin = -1;
int gAmplifierShouldBeginMuted = 0;
// Number of audio and matrix channels, globally accessible
// At least gNumMatrixChannels needs to be global to be used
// by the analogRead() and analogWrite() macros without creating
// extra confusion in their use cases by passing this argument
int gNumAudioChannels = 0;
int gNumMatrixChannels = 0;
// initAudio() prepares the infrastructure for running PRU-based real-time
// audio, but does not actually start the calculations.
// periodSize indicates the number of _sensor_ frames per period: the audio period size
// is twice this value. In total, the audio latency in frames will be 4*periodSize,
// plus any latency inherent in the ADCs and DACs themselves.
// useMatrix indicates whether to enable the ADC and DAC or just use the audio codec.
// numMatrixChannels indicates how many ADC and DAC channels to use.
// userData is an opaque pointer which will be passed through to the initialise_render()
// function for application-specific use
//
// Returns 0 on success.
int BeagleRT_initAudio(RTAudioSettings *settings, void *userData)
{
rt_print_auto_init(1);
setVerboseLevel(settings->verbose);
if(gRTAudioVerbose == 1)
rt_printf("Running with Xenomai\n");
if(gRTAudioVerbose) {
cout << "Starting with period size " << settings->periodSize << "; ";
if(settings->useMatrix)
cout << "matrix enabled\n";
else
cout << "matrix disabled\n";
cout << "DAC level " << settings->dacLevel << "dB; ADC level " << settings->adcLevel;
cout << "dB; headphone level " << settings->headphoneLevel << "dB\n";
if(settings->beginMuted)
cout << "Beginning with speaker muted\n";
}
// Prepare GPIO pins for amplifier mute and status LED
if(settings->ampMutePin >= 0) {
gAmplifierMutePin = settings->ampMutePin;
gAmplifierShouldBeginMuted = settings->beginMuted;
if(gpio_export(settings->ampMutePin)) {
if(gRTAudioVerbose)
cout << "Warning: couldn't export amplifier mute pin\n";
}
if(gpio_set_dir(settings->ampMutePin, OUTPUT_PIN)) {
if(gRTAudioVerbose)
cout << "Couldn't set direction on amplifier mute pin\n";
return -1;
}
if(gpio_set_value(settings->ampMutePin, LOW)) {
if(gRTAudioVerbose)
cout << "Couldn't set value on amplifier mute pin\n";
return -1;
}
}
// Limit the matrix channels to sane values
if(settings->numMatrixChannels >= 8)
settings->numMatrixChannels = 8;
else if(settings->numMatrixChannels >= 4)
settings->numMatrixChannels = 4;
else
settings->numMatrixChannels = 2;
// Sanity check the combination of channels and period size
if(settings->numMatrixChannels <= 4 && settings->periodSize < 2) {
cout << "Error: " << settings->numMatrixChannels << " channels and period size of " << settings->periodSize << " not supported.\n";
return 1;
}
if(settings->numMatrixChannels <= 2 && settings->periodSize < 4) {
cout << "Error: " << settings->numMatrixChannels << " channels and period size of " << settings->periodSize << " not supported.\n";
return 1;
}
// Use PRU for audio
gPRU = new PRU();
gAudioCodec = new I2c_Codec();
if(gPRU->prepareGPIO(settings->useMatrix, 1, 1)) {
cout << "Error: unable to prepare GPIO for PRU audio\n";
return 1;
}
if(gPRU->initialise(0, settings->periodSize, settings->numMatrixChannels, true)) {
cout << "Error: unable to initialise PRU\n";
return 1;
}
if(gAudioCodec->initI2C_RW(2, settings->codecI2CAddress, -1)) {
cout << "Unable to open codec I2C\n";
return 1;
}
if(gAudioCodec->initCodec()) {
cout << "Error: unable to initialise audio codec\n";
return 1;
}
// Set default volume levels
BeagleRT_setDACLevel(settings->dacLevel);
BeagleRT_setADCLevel(settings->adcLevel);
BeagleRT_setHeadphoneLevel(settings->headphoneLevel);
// Initialise the rendering environment: pass the number of audio and matrix
// channels, the period size for matrix and audio, and the sample rates
int audioPeriodSize = settings->periodSize * 2;
float audioSampleRate = 44100.0;
float matrixSampleRate = 22050.0;
if(settings->useMatrix) {
audioPeriodSize = settings->periodSize * settings->numMatrixChannels / 4;
matrixSampleRate = audioSampleRate * 4.0 / (float)settings->numMatrixChannels;
}
gNumAudioChannels = 2;
gNumMatrixChannels = settings->useMatrix ? settings->numMatrixChannels : 0;
if(!initialise_render(gNumMatrixChannels, gNumAudioChannels,
settings->useMatrix ? settings->periodSize : 0, /* matrix period size */
audioPeriodSize,
matrixSampleRate, audioSampleRate,
userData)) {
cout << "Couldn't initialise audio rendering\n";
return 1;
}
return 0;
}
// audioLoop() is the main function which starts the PRU audio code
// and then transfers control to the PRU object. The PRU object in
// turn will call the audio render() callback function every time
// there is new data to process.
void audioLoop(void *)
{
if(gRTAudioVerbose==1)
rt_printf("_________________Audio Thread!\n");
// PRU audio
assert(gAudioCodec != 0 && gPRU != 0);
if(gAudioCodec->startAudio(0)) {
rt_printf("Error: unable to start I2C audio codec\n");
gShouldStop = 1;
}
else {
if(gPRU->start()) {
rt_printf("Error: unable to start PRU\n");
gShouldStop = 1;
}
else {
// All systems go. Run the loop; it will end when gShouldStop is set to 1
if(!gAmplifierShouldBeginMuted) {
// First unmute the amplifier
if(BeagleRT_muteSpeakers(0)) {
if(gRTAudioVerbose)
rt_printf("Warning: couldn't set value (high) on amplifier mute pin\n");
}
}
gPRU->loop();
// Now clean up
// gPRU->waitForFinish();
gPRU->disable();
gAudioCodec->stopAudio();
gPRU->cleanupGPIO();
}
}
if(gRTAudioVerbose == 1)
rt_printf("audio thread ended\n");
}
// Create a calculation loop which can run independently of the audio, at a different
// (equal or lower) priority. Audio priority is 99; priority should be generally be less than this.
// Returns an (opaque) pointer to the created task on success; 0 on failure
AuxiliaryTask createAuxiliaryTaskLoop(void (*functionToCall)(void), int priority, const char *name)
{
InternalAuxiliaryTask *newTask = (InternalAuxiliaryTask*)malloc(sizeof(InternalAuxiliaryTask));
// Attempt to create the task
if(rt_task_create(&(newTask->task), name, 0, priority, T_JOINABLE | T_FPU)) {
cout << "Error: unable to create auxiliary task " << name << endl;
free(newTask);
return 0;
}
// Populate the rest of the data structure and store it in the vector
newTask->function = functionToCall;
newTask->name = strdup(name);
newTask->priority = priority;
gAuxTasks.push_back(newTask);
return (AuxiliaryTask)newTask;
}
// Schedule a previously created auxiliary task. It will run when the priority rules next
// allow it to be scheduled.
void scheduleAuxiliaryTask(AuxiliaryTask task)
{
InternalAuxiliaryTask *taskToSchedule = (InternalAuxiliaryTask *)task;
rt_task_resume(&taskToSchedule->task);
}
// Calculation loop that can be used for other tasks running at a lower
// priority than the audio thread. Simple wrapper for Xenomai calls.
// Treat the argument as containing the task structure
void auxiliaryTaskLoop(void *taskStruct)
{
// Get function to call from the argument
void (*auxiliary_function)(void) = ((InternalAuxiliaryTask *)taskStruct)->function;
const char *name = ((InternalAuxiliaryTask *)taskStruct)->name;
// Wait for a notification
rt_task_suspend(NULL);
while(!gShouldStop) {
// Then run the calculations
auxiliary_function();
// Wait for a notification
rt_task_suspend(NULL);
}
if(gRTAudioVerbose == 1)
rt_printf("auxiliary task %s ended\n", name);
}
// startAudio() should be called only after initAudio() successfully completes.
// It launches the real-time Xenomai task which runs the audio loop. Returns 0
// on success.
int BeagleRT_startAudio()
{
// Create audio thread with the highest priority
if(rt_task_create(&gRTAudioThread, gRTAudioThreadName, 0, 99, T_JOINABLE | T_FPU)) {
cout << "Error: unable to create Xenomai audio thread" << endl;
return -1;
}
// Start all RT threads
if(rt_task_start(&gRTAudioThread, &audioLoop, 0)) {
cout << "Error: unable to start Xenomai audio thread" << endl;
return -1;
}
// The user may have created other tasks. Start those also.
vector<InternalAuxiliaryTask*>::iterator it;
for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) {
InternalAuxiliaryTask *taskStruct = *it;
if(rt_task_start(&(taskStruct->task), &auxiliaryTaskLoop, taskStruct)) {
cerr << "Error: unable to start Xenomai task " << taskStruct->name << endl;
return -1;
}
}
return 0;
}
// Stop the PRU-based audio from running and wait
// for the tasks to complete before returning.
void BeagleRT_stopAudio()
{
// Tell audio thread to stop (if this hasn't been done already)
gShouldStop = true;
if(gRTAudioVerbose)
cout << "Stopping audio...\n";
// Now wait for threads to respond and actually stop...
rt_task_join(&gRTAudioThread);
// Stop all the auxiliary threads too
vector<InternalAuxiliaryTask*>::iterator it;
for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) {
InternalAuxiliaryTask *taskStruct = *it;
// Wake up each thread and join it
rt_task_resume(&(taskStruct->task));
rt_task_join(&(taskStruct->task));
}
}
// Free any resources associated with PRU real-time audio
void BeagleRT_cleanupAudio()
{
cleanup_render();
// Clean up the auxiliary tasks
vector<InternalAuxiliaryTask*>::iterator it;
for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) {
InternalAuxiliaryTask *taskStruct = *it;
// Free the name string and the struct itself
free(taskStruct->name);
free(taskStruct);
}
gAuxTasks.clear();
if(gPRU != 0)
delete gPRU;
if(gAudioCodec != 0)
delete gAudioCodec;
if(gAmplifierMutePin >= 0)
gpio_unexport(gAmplifierMutePin);
gAmplifierMutePin = -1;
}
// Set the level of the DAC; affects all outputs (headphone, line, speaker)
// 0dB is the maximum, -63.5dB is the minimum; 0.5dB steps
int BeagleRT_setDACLevel(float decibels)
{
if(gAudioCodec == 0)
return -1;
return gAudioCodec->setDACVolume((int)floorf(decibels * 2.0 + 0.5));
}
// Set the level of the ADC
// 0dB is the maximum, -12dB is the minimum; 1.5dB steps
int BeagleRT_setADCLevel(float decibels)
{
if(gAudioCodec == 0)
return -1;
return gAudioCodec->setADCVolume((int)floorf(decibels * 2.0 + 0.5));
}
// Set the level of the onboard headphone amplifier; affects headphone
// output only (not line out or speaker)
// 0dB is the maximum, -63.5dB is the minimum; 0.5dB steps
int BeagleRT_setHeadphoneLevel(float decibels)
{
if(gAudioCodec == 0)
return -1;
return gAudioCodec->setHPVolume((int)floorf(decibels * 2.0 + 0.5));
}
// Mute or unmute the onboard speaker amplifiers
// mute == 0 means unmute; otherwise mute
// Returns 0 on success
int BeagleRT_muteSpeakers(int mute)
{
int pinValue = mute ? LOW : HIGH;
// Check that we have an enabled pin for controlling the mute
if(gAmplifierMutePin < 0)
return -1;
return gpio_set_value(gAmplifierMutePin, pinValue);
}
// Set the verbosity level
void setVerboseLevel(int level)
{
gRTAudioVerbose = level;
}
| 29.419204 | 133 | 0.71581 | amilo |
b79dc57c8d87ed9ac355024072cc3b95897d7c8d | 412 | hpp | C++ | src/graphics/index-buffer.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 44 | 2019-06-06T21:33:30.000Z | 2022-03-26T06:18:23.000Z | src/graphics/index-buffer.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 1 | 2019-09-27T12:04:52.000Z | 2019-09-29T13:30:42.000Z | src/graphics/index-buffer.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 8 | 2019-07-26T16:44:26.000Z | 2020-11-24T17:56:18.000Z | #pragma once
class IndexBuffer {
private:
unsigned int m_rendererID;
unsigned int m_count;
public:
IndexBuffer();
IndexBuffer(const unsigned int* data, unsigned int count);
~IndexBuffer();
void init(const unsigned int* data, unsigned int count);
void bind() const;
void unbind() const;
inline unsigned int getCount() const { return m_count; }
unsigned int getID() const { return m_rendererID; }
};
| 20.6 | 59 | 0.735437 | guillaume-haerinck |
b7a6d58765808f0bc9e9d6961d800f875ee4e177 | 740 | cpp | C++ | Difficulty 1/luhn_check_sum.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 1/luhn_check_sum.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 1/luhn_check_sum.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int tests;
cin >> tests;
for (int j = 0; j < tests; j++) {
string number;
int curr_number, ans = 0;
cin >> number;
int size = number.size();
bool second = false;
for(int i = 1; i <= size; i++) {
curr_number = stoi(number.substr(size-i, 1));
if (second) curr_number *= 2;
if (curr_number > 9) {
ans += curr_number % 10 + 1;
} else {
ans += curr_number;
}
second = !second;
}
if (ans % 10 == 0) {
cout << "PASS " << endl;
} else {
cout << "FAIL " << endl;
}
}
} | 23.870968 | 57 | 0.412162 | BrynjarGeir |
b7a7a97dc4621a06fda2b867d490ded5d636c919 | 545 | cpp | C++ | examples/multithreading/bots/abstractbot.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 58 | 2015-08-09T14:56:35.000Z | 2022-01-15T22:06:58.000Z | examples/multithreading/bots/abstractbot.cpp | mamontov-cpp/saddy-graphics-engine-2d | e25a6637fcc49cb26614bf03b70e5d03a3a436c7 | [
"BSD-2-Clause"
] | 245 | 2015-08-08T08:44:22.000Z | 2022-01-04T09:18:08.000Z | examples/multithreading/bots/abstractbot.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 23 | 2015-12-06T03:57:49.000Z | 2020-10-12T14:15:50.000Z | #include "abstractbot.h"
bots::AbstractBot::AbstractBot() : m_strategy(nullptr)
{
}
bots::AbstractBot::~AbstractBot()
{
if (m_strategy)
{
m_strategy->delRef();
}
}
void bots::AbstractBot::setStrategy(bots::shootingstrategies::ShootingStrategy* strategy)
{
if (m_strategy)
{
m_strategy->delRef();
}
m_strategy = strategy;
if (m_strategy)
{
m_strategy->addRef();
}
}
bots::shootingstrategies::ShootingStrategy* bots::AbstractBot::strategy() const
{
return m_strategy;
}
| 16.515152 | 89 | 0.638532 | mamontov-cpp |
b7a8f645c57e2970d5f4437928de8934fc50f6de | 619 | cpp | C++ | test/ordinal/container/ordinal_range/ordinal_range_pass.cpp | jwakely/std-make | f09d052983ace70cf371bb8ddf78d4f00330bccd | [
"BSL-1.0"
] | 105 | 2015-01-24T13:26:41.000Z | 2022-02-18T15:36:53.000Z | test/ordinal/container/ordinal_range/ordinal_range_pass.cpp | jwakely/std-make | f09d052983ace70cf371bb8ddf78d4f00330bccd | [
"BSL-1.0"
] | 37 | 2015-09-04T06:57:10.000Z | 2021-09-09T18:01:44.000Z | test/ordinal/container/ordinal_range/ordinal_range_pass.cpp | jwakely/std-make | f09d052983ace70cf371bb8ddf78d4f00330bccd | [
"BSL-1.0"
] | 23 | 2015-01-27T11:09:18.000Z | 2021-10-04T02:23:30.000Z | // Copyright (C) 2016 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// <experimental/ordinal_range.hpp>
#include <experimental/ordinal_range.hpp>
#include "../../Bool.hpp"
#include "../../Bounded.hpp"
#include <boost/detail/lightweight_test.hpp>
int main()
{
namespace stde = std::experimental;
using Indx = Bounded<1,4,unsigned char>;
{
stde::ordinal_range<Indx> rng;
auto b = rng.begin();
BOOST_TEST(b->value==1);
}
return ::boost::report_errors();
}
| 22.107143 | 80 | 0.688207 | jwakely |
b7abb6c084120928b4a69973d6c300eb896ff568 | 128 | hpp | C++ | command.hpp | RustedBot/Pong | 8e75d64b306cc4c3db433061dd2e3418b7102354 | [
"MIT"
] | null | null | null | command.hpp | RustedBot/Pong | 8e75d64b306cc4c3db433061dd2e3418b7102354 | [
"MIT"
] | null | null | null | command.hpp | RustedBot/Pong | 8e75d64b306cc4c3db433061dd2e3418b7102354 | [
"MIT"
] | null | null | null | #ifndef COMMAND_H
#define COMMAND_H
class Command
{
public:
virtual void execute() = 0;
private:
};
#endif // COMMAND_H
| 9.142857 | 31 | 0.6875 | RustedBot |
5d9a76fabdd5f79b03fb5b4e69757d24f1f55a0f | 5,766 | cpp | C++ | src/resqml2_0_1/NonSealedSurfaceFrameworkRepresentation.cpp | ringmesh/fesapi | 0b518e71f805f35679a65c78332b5cb64ed97830 | [
"Apache-2.0"
] | null | null | null | src/resqml2_0_1/NonSealedSurfaceFrameworkRepresentation.cpp | ringmesh/fesapi | 0b518e71f805f35679a65c78332b5cb64ed97830 | [
"Apache-2.0"
] | null | null | null | src/resqml2_0_1/NonSealedSurfaceFrameworkRepresentation.cpp | ringmesh/fesapi | 0b518e71f805f35679a65c78332b5cb64ed97830 | [
"Apache-2.0"
] | null | null | null | /*-----------------------------------------------------------------------
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"; you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-----------------------------------------------------------------------*/
#include "resqml2_0_1/NonSealedSurfaceFrameworkRepresentation.h"
#include <algorithm>
#include <stdexcept>
#include <sstream>
#include "H5public.h"
#include "resqml2_0_1/StructuralOrganizationInterpretation.h"
#include "resqml2/AbstractFeatureInterpretation.h"
#include "common/AbstractHdfProxy.h"
#include "resqml2/AbstractLocal3dCrs.h"
using namespace std;
using namespace epc;
using namespace RESQML2_0_1_NS;
using namespace gsoap_resqml2_0_1;
const char* NonSealedSurfaceFrameworkRepresentation::XML_TAG = "NonSealedSurfaceFrameworkRepresentation";
NonSealedSurfaceFrameworkRepresentation::NonSealedSurfaceFrameworkRepresentation(
StructuralOrganizationInterpretation* interp,
const std::string & guid,
const std::string & title,
const bool & isSealed):
RepresentationSetRepresentation(interp)
{
if (!interp)
throw invalid_argument("The structural organization interpretation cannot be null.");
// proxy constructor
gsoapProxy2_0_1 = soap_new_resqml2__obj_USCORENonSealedSurfaceFrameworkRepresentation(interp->getGsoapContext(), 1);
_resqml2__NonSealedSurfaceFrameworkRepresentation* orgRep = static_cast<_resqml2__NonSealedSurfaceFrameworkRepresentation*>(gsoapProxy2_0_1);
orgRep->RepresentedInterpretation = soap_new_eml20__DataObjectReference(gsoapProxy2_0_1->soap, 1);
orgRep->RepresentedInterpretation->UUID.assign(interp->getUuid());
initMandatoryMetadata();
setMetadata(guid, title, "", -1, "", "", -1, "", "");
setInterpretation(interp);
}
void NonSealedSurfaceFrameworkRepresentation::pushBackNonSealedContactRepresentation(const unsigned int & pointCount, double * points, RESQML2_NS::AbstractLocal3dCrs* crs, COMMON_NS::AbstractHdfProxy * proxy)
{
if (pointCount == 0)
throw invalid_argument("Contact point count cannot be zero.");
if (!points)
throw invalid_argument("The contact points cannot be null.");
if (!proxy)
throw invalid_argument("The HDF proxy cannot be null.");
if (localCrs == nullptr)
{
localCrs = crs;
localCrs->addRepresentation(this);
}
setHdfProxy(proxy);
_resqml2__NonSealedSurfaceFrameworkRepresentation* orgRep = static_cast<_resqml2__NonSealedSurfaceFrameworkRepresentation*>(gsoapProxy2_0_1);
resqml2__NonSealedContactRepresentationPart* contactRep = soap_new_resqml2__NonSealedContactRepresentationPart(gsoapProxy2_0_1->soap, 1);
contactRep->Index = orgRep->NonSealedContactRepresentation.size();
orgRep->NonSealedContactRepresentation.push_back(contactRep);
resqml2__PointGeometry* contactGeom = soap_new_resqml2__PointGeometry(gsoapProxy2_0_1->soap, 1);
contactRep->Geometry = contactGeom;
contactGeom->LocalCrs = localCrs->newResqmlReference();
resqml2__Point3dHdf5Array* contactGeomPoints = soap_new_resqml2__Point3dHdf5Array(gsoapProxy2_0_1->soap, 1);
contactGeom->Points = contactGeomPoints;
contactGeomPoints->Coordinates = soap_new_eml20__Hdf5Dataset(gsoapProxy2_0_1->soap, 1);
contactGeomPoints->Coordinates->HdfProxy = hdfProxy->newResqmlReference();
ostringstream oss;
oss << "points_contact_representation" << orgRep->NonSealedContactRepresentation.size()-1;
contactGeomPoints->Coordinates->PathInHdfFile = "/RESQML/" + getUuid() + "/" + oss.str();
// HDF
hsize_t numValues[2];
numValues[0] = pointCount;
numValues[1] = 3; // 3 for X, Y and Z
hdfProxy->writeArrayNdOfDoubleValues(getUuid(), oss.str(), points, numValues, 2);
}
std::string NonSealedSurfaceFrameworkRepresentation::getHdfProxyUuid() const
{
string result = "";
_resqml2__NonSealedSurfaceFrameworkRepresentation* orgRep = static_cast<_resqml2__NonSealedSurfaceFrameworkRepresentation*>(gsoapProxy2_0_1);
if (orgRep->NonSealedContactRepresentation.size() > 0)
{
resqml2__NonSealedContactRepresentationPart* firstContact = static_cast<resqml2__NonSealedContactRepresentationPart*>(orgRep->NonSealedContactRepresentation[0]);
if (firstContact->Geometry->soap_type() == SOAP_TYPE_gsoap_resqml2_0_1_resqml2__PointGeometry)
{
resqml2__PointGeometry* pointGeom = static_cast<resqml2__PointGeometry*>(firstContact->Geometry);
if (pointGeom->Points->soap_type() == SOAP_TYPE_gsoap_resqml2_0_1_resqml2__Point3dHdf5Array)
{
return static_cast<resqml2__Point3dHdf5Array*>(pointGeom->Points)->Coordinates->HdfProxy->UUID;
}
}
}
return result;
}
vector<Relationship> NonSealedSurfaceFrameworkRepresentation::getAllEpcRelationships() const
{
vector<Relationship> result = RepresentationSetRepresentation::getAllEpcRelationships();
// supporting representations of organization sub representations
for (unsigned int i = 0; i < supportingRepOfContactPatchSet.size(); i++)
{
Relationship rel(supportingRepOfContactPatchSet[i]->getPartNameInEpcDocument(), "", supportingRepOfContactPatchSet[i]->getUuid());
rel.setDestinationObjectType();
result.push_back(rel);
}
return result;
}
| 41.482014 | 208 | 0.776968 | ringmesh |
5d9f9f81221136850585ba427482db4aef9ce359 | 3,499 | cpp | C++ | MasterServer/LMasterServer_PacketProcess_Proc.cpp | MBeanwenshengming/linuxgameserver | f03bf6ba0d625609c9654ddf0dc821386337e7dc | [
"MIT"
] | 5 | 2018-04-02T07:16:20.000Z | 2021-08-01T05:25:37.000Z | MasterServer/LMasterServer_PacketProcess_Proc.cpp | MBeanwenshengming/linuxgameserver | f03bf6ba0d625609c9654ddf0dc821386337e7dc | [
"MIT"
] | null | null | null | MasterServer/LMasterServer_PacketProcess_Proc.cpp | MBeanwenshengming/linuxgameserver | f03bf6ba0d625609c9654ddf0dc821386337e7dc | [
"MIT"
] | 2 | 2015-08-21T07:31:41.000Z | 2018-05-10T12:36:32.000Z | /*
The MIT License (MIT)
Copyright (c) <2010-2020> <wenshengming>
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.
*/
#include "LMasterServer_PacketProcess_Proc.h"
#include "../NetWork/LPacketSingle.h"
#include "LMainLogicThread.h"
#include "../include/Server_To_Server_Packet_Define.h"
LMasterServerPacketProcessProc::LMasterServerPacketProcessProc()
{
m_pMainLogicThread = NULL;
}
LMasterServerPacketProcessProc::~LMasterServerPacketProcessProc()
{
}
void LMasterServerPacketProcessProc::SetMainLogicThread(LMainLogicThread* pmlt)
{
m_pMainLogicThread = pmlt;
}
LMainLogicThread* LMasterServerPacketProcessProc::GetMainLogicThread()
{
return m_pMainLogicThread;
}
bool LMasterServerPacketProcessProc::Initialize()
{
if (m_pMainLogicThread == NULL)
{
return false;
}
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Start_Req);
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Register_Server_Req1);
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Server_Will_Connect_Req);
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Server_Will_Connect_Res);
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Server_Current_Serve_Count);
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_L2M_USER_ONLINE);
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_GA2M_USER_WILL_LOGIN);
;
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_GA2M_USER_GATESERVER_OFFLINE);
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_GA2M_USER_GATESERVER_ONLINE);
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_GA2M_SELECT_LOBBYSERVER);
REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_LB2M_NOTIFY_USER_WILL_ONLINE);
return true;
}
// 注册函数
bool LMasterServerPacketProcessProc::Register(unsigned int unPacketID, MASTERSERVER_PACKET_PROCESS_PROC pProc)
{
if (pProc == NULL)
{
return false;
}
map<unsigned int, MASTERSERVER_PACKET_PROCESS_PROC>::iterator _ito = m_mapPacketProcessProcManager.find(unPacketID);
if (_ito != m_mapPacketProcessProcManager.end())
{
return false;
}
m_mapPacketProcessProcManager[unPacketID] = pProc;
return true;
}
// 派遣处理函数
void LMasterServerPacketProcessProc::DispatchMessageProcess(uint64_t u64SessionID, LPacketSingle* pPacket)
{
if (pPacket == NULL)
{
return ;
}
unsigned int unPacketID = pPacket->GetPacketID();
map<unsigned int, MASTERSERVER_PACKET_PROCESS_PROC>::iterator _ito = m_mapPacketProcessProcManager.find(unPacketID);
if (_ito == m_mapPacketProcessProcManager.end())
{
// error
return;
}
_ito->second(this, u64SessionID, pPacket);
}
| 31.809091 | 117 | 0.823092 | MBeanwenshengming |
5da40434f93e40fac22f2e9e9ea7bee7395e3bcd | 1,761 | hpp | C++ | RType.Server/Headers/TCPServer.hpp | Mikyan0207/RType | ae3d0e4b3192577eccfb3ba55ac86bd7238e9451 | [
"MIT",
"Unlicense"
] | null | null | null | RType.Server/Headers/TCPServer.hpp | Mikyan0207/RType | ae3d0e4b3192577eccfb3ba55ac86bd7238e9451 | [
"MIT",
"Unlicense"
] | null | null | null | RType.Server/Headers/TCPServer.hpp | Mikyan0207/RType | ae3d0e4b3192577eccfb3ba55ac86bd7238e9451 | [
"MIT",
"Unlicense"
] | null | null | null | #pragma once
#include <memory>
#include <vector>
#include <optional>
#include <thread>
#include <string>
#include <Network/IPacketManager.hpp>
#include <Network/ITCPNetwork.hpp>
#include <Network/Connection.hpp>
#include <Lobby.hpp>
namespace RType
{
class TCPServer : public ITCPNetwork
{
public:
TCPServer(const std::int32_t& port);
public:
void Start() final;
void Stop() final;
void CheckClosedConnection();
void WriteAsync(const std::string& ip, const RType::RTypePack& p);
void StartGame() override {}
void CreateRoom(const std::uint32_t& maxPlayer) override {}
void JoinRoom(const std::string& roomId) override {}
void LeaveRoom(const std::string& roomId) override {}
public:
void AddLobby(Shared<Lobby> lobby);
void RemoveLobby(const std::string &lobbyId);
Shared<Lobby> GetLobby(const std::string& id);
private:
void StartAccept();
void OnAccept(Connection::ConnectionPtr socket, const boost::system::error_code& error);
public:
[[nodiscard]] boost::asio::io_context& GetIoContext() { return m_IoContext; }
[[nodiscard]] std::optional<std::string> GetServerIp() const;
[[nodiscard]] std::optional<Connection::ConnectionPtr> GetConnectionFromIp(const std::string& ip);
[[nodiscard]] Shared<RType::IUDPNetwork> GetUdpNetwork() const override { return {}; }
private:
std::vector<Shared<Lobby>> m_Rooms;
boost::asio::io_context m_IoContext;
boost::asio::ip::tcp::acceptor m_Acceptor;
std::vector<Connection::ConnectionPtr> m_Connections;
std::thread m_Thread;
bool m_IsRunning;
Unique<IPacketManager> m_PacketManager;
};
} | 32.611111 | 106 | 0.664395 | Mikyan0207 |
5da4c4c25c5180de10e006f11ebaa79e2b4777e8 | 4,925 | cpp | C++ | Crowny/Source/Crowny/Scripting/Mono/MonoMethod.cpp | bojosos/Nworc | a59cb18412a45a101f877caedf6ed0025a9e44a9 | [
"MIT"
] | 2 | 2021-05-13T17:57:04.000Z | 2021-10-04T07:07:01.000Z | Crowny/Source/Crowny/Scripting/Mono/MonoMethod.cpp | bojosos/Crowny | 5aef056d2c95e04870d2372a87257ad9dccf168a | [
"MIT"
] | null | null | null | Crowny/Source/Crowny/Scripting/Mono/MonoMethod.cpp | bojosos/Crowny | 5aef056d2c95e04870d2372a87257ad9dccf168a | [
"MIT"
] | null | null | null | #include "cwpch.h"
#include "Crowny/Scripting/Mono/MonoClass.h"
#include "Crowny/Scripting/Mono/MonoManager.h"
#include "Crowny/Scripting/Mono/MonoMethod.h"
#include "Crowny/Scripting/Mono/MonoUtils.h"
#include <mono/metadata/attrdefs.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/loader.h>
#include <mono/metadata/object.h>
#include <mono/metadata/reflection.h>
namespace Crowny
{
MonoMethod::MonoMethod(::MonoMethod* method)
: m_Method(method), m_CachedParams(nullptr), m_CachedReturnType(nullptr), m_HasCachedSignature(false),
m_CachedNumParams(0)
{
m_Name = mono_method_get_name(m_Method);
m_FullDeclName = CrownyMonoVisibilityToString(GetVisibility()) + (IsStatic() ? " static " : " ") +
mono_method_full_name(m_Method, true);
}
MonoClass* MonoMethod::GetParameterType(uint32_t idx) const
{
if (!m_HasCachedSignature)
CacheSignature();
if (idx >= m_CachedNumParams)
{
CW_ENGINE_ERROR("Param index out of range.");
return nullptr;
}
return m_CachedParams[idx];
}
MonoObject* MonoMethod::Invoke(MonoObject* instance, void** params)
{
MonoObject* exception = nullptr;
MonoObject* ret = mono_runtime_invoke(m_Method, instance, params, &exception);
MonoUtils::CheckException(exception);
return ret;
}
void* MonoMethod::GetThunk() const { return mono_method_get_unmanaged_thunk(m_Method); }
bool MonoMethod::HasAttribute(MonoClass* monoClass) const
{
MonoCustomAttrInfo* info = mono_custom_attrs_from_method(m_Method);
if (info == nullptr)
return false;
bool hasAttrs = mono_custom_attrs_has_attr(info, monoClass->GetInternalPtr()) != 0;
mono_custom_attrs_free(info);
return hasAttrs;
}
MonoObject* MonoMethod::GetAttribute(MonoClass* monoClass) const
{
MonoCustomAttrInfo* info = mono_custom_attrs_from_method(m_Method);
if (info == nullptr)
return nullptr;
MonoObject* attrs = nullptr;
if (mono_custom_attrs_has_attr(info, monoClass->GetInternalPtr()))
{
attrs = mono_custom_attrs_get_attr(info, monoClass->GetInternalPtr());
}
mono_custom_attrs_free(info);
return attrs;
}
bool MonoMethod::IsStatic() const
{
if (!m_HasCachedSignature)
CacheSignature();
return m_IsStatic;
}
MonoClass* MonoMethod::GetReturnType() const
{
if (!m_HasCachedSignature)
CacheSignature();
return m_CachedReturnType;
}
void MonoMethod::CacheSignature() const
{
MonoMethodSignature* signature = mono_method_signature(m_Method);
MonoType* returnType = mono_signature_get_return_type(signature);
if (returnType != nullptr)
{
::MonoClass* returnTypeClass = mono_class_from_mono_type(returnType);
if (returnTypeClass != nullptr)
m_CachedReturnType = MonoManager::Get().FindClass(returnTypeClass);
}
m_CachedNumParams = (uint32_t)mono_signature_get_param_count(signature);
if (m_CachedParams != nullptr)
{
delete[] m_CachedParams;
m_CachedParams = nullptr;
}
if (m_CachedNumParams > 0)
{
m_CachedParams = new MonoClass*[m_CachedNumParams];
void* iter = nullptr;
for (uint32_t i = 0; i < m_CachedNumParams; i++)
{
MonoType* curParamType = mono_signature_get_params(signature, &iter);
::MonoClass* returnTypeClass = mono_class_from_mono_type(curParamType);
m_CachedParams[i] = MonoManager::Get().FindClass(returnTypeClass);
}
}
m_IsStatic = !mono_signature_is_instance(signature);
m_HasCachedSignature = true;
}
uint32_t MonoMethod::GetNumParams() const
{
if (!m_HasCachedSignature)
CacheSignature();
return m_CachedNumParams;
}
CrownyMonoVisibility MonoMethod::GetVisibility()
{
uint32_t flags = mono_method_get_flags(m_Method, nullptr) & MONO_METHOD_ATTR_ACCESS_MASK;
switch (flags)
{
case (MONO_METHOD_ATTR_PRIVATE):
return CrownyMonoVisibility::Private;
case (MONO_METHOD_ATTR_FAM_AND_ASSEM):
return CrownyMonoVisibility::ProtectedInternal;
case (MONO_METHOD_ATTR_ASSEM):
return CrownyMonoVisibility::Internal;
case (MONO_METHOD_ATTR_FAMILY):
return CrownyMonoVisibility::Protected;
case (MONO_METHOD_ATTR_PUBLIC):
return CrownyMonoVisibility::Public;
}
CW_ENGINE_ASSERT(false, "Unknown visibility.");
return CrownyMonoVisibility::Private;
}
} // namespace Crowny | 32.615894 | 108 | 0.643249 | bojosos |
5da760efdd8c8eaa8b7bff8dbd6d3dc1c382a22f | 4,019 | cpp | C++ | simplefvm/src/FVMSolver/MatrixBuilder/SleMatrixBuilder.cpp | artvns/SimpleFvm | 5a8eca332d6780e738c0bc6c8c2b787b47b5b20d | [
"MIT"
] | 4 | 2022-01-03T08:45:55.000Z | 2022-01-06T19:57:11.000Z | simplefvm/src/FVMSolver/MatrixBuilder/SleMatrixBuilder.cpp | artvns/SimpleFvm | 5a8eca332d6780e738c0bc6c8c2b787b47b5b20d | [
"MIT"
] | null | null | null | simplefvm/src/FVMSolver/MatrixBuilder/SleMatrixBuilder.cpp | artvns/SimpleFvm | 5a8eca332d6780e738c0bc6c8c2b787b47b5b20d | [
"MIT"
] | null | null | null | #include "SleMatrixBuilder.h"
namespace fvmsolver {
SleMatrixBuilder::SleMatrixBuilder(
AbstractCoeffsCalculator& coeffsCalculator,
uPtrDataPort spData) :
spDataPort_(std::move(spData)),
dataPort_(*spDataPort_),
coeffsCalculator_(coeffsCalculator),
aP_(dataPort_.getAp()),
aW_(dataPort_.getAw()),
aE_(dataPort_.getAe()),
aN_(dataPort_.getAn()),
aS_(dataPort_.getAs()) {
}
void SleMatrixBuilder::build(std::shared_ptr<SleSolver> sleSolver) {
pSleSolver_ = sleSolver;
createMatrixAndVectors();
buildInterior();
buildBoundary();
}
void SleMatrixBuilder::buildInterior() {
size_t domainParts = dataPort_.getInteriorPartsAmount();
for (size_t partId = 0; partId < domainParts; partId++) {
std::string name = dataPort_.getInteriorName(partId);
coeffsCalculator_.chooseActualDomainPart(name);
size_t partCells = dataPort_.getPartCellsAmount(name);
for (size_t i = 0; i < partCells; i++) {
coeffsCalculator_.calculateInterior(i);
placeAllCoeffs();
}
}
}
void SleMatrixBuilder::buildBoundary() {
size_t domainParts = dataPort_.getBcPartsAmount();
for (size_t partId = 0; partId < domainParts; partId++) {
std::string name = dataPort_.getBoundaryName(partId);
coeffsCalculator_.chooseActualDomainPart(name);
size_t partCells = dataPort_.getPartCellsAmount(name);
for (size_t i = 0; i < partCells; i++) {
coeffsCalculator_.calculateBoundary(i);
placeAllCoeffs();
}
}
}
void SleMatrixBuilder::placeAllCoeffs() {
double a_w = coeffsCalculator_.getAw();
double a_e = coeffsCalculator_.getAe();
double a_n = coeffsCalculator_.getAn();
double a_s = coeffsCalculator_.getAs();
double a_p = coeffsCalculator_.getAp();
size_t posW_ = coeffsCalculator_.get_wNum();
size_t posE_ = coeffsCalculator_.get_eNum();
size_t posN_ = coeffsCalculator_.get_nNum();
size_t posS_ = coeffsCalculator_.get_sNum();
size_t posP_ = coeffsCalculator_.get_pNum() - 1;
bool isInteriorW_ = coeffsCalculator_.is_wInterior();
bool isInteriorE_ = coeffsCalculator_.is_eInterior();
bool isInteriorN_ = coeffsCalculator_.is_nInterior();
bool isInteriorS_ = coeffsCalculator_.is_sInterior();
placeCoeffsOtherDiags(posP_, posW_, -a_w, isInteriorW_);
placeCoeffsOtherDiags(posP_, posE_, -a_e, isInteriorE_);
placeCoeffsOtherDiags(posP_, posN_, -a_n, isInteriorN_);
placeCoeffsOtherDiags(posP_, posS_, -a_s, isInteriorS_);
placeCoeffsMainDiag(posP_, posP_, a_p);
pSleSolver_->placeRhsValue(posP_, coeffsCalculator_.getRHS());
aP_[posP_] = a_p;
dataPort_.setRhs(posP_, coeffsCalculator_.getRHS());
dataPort_.set_b(posP_, coeffsCalculator_.get_b());
saveCoeff(posW_, a_w, aW_);
saveCoeff(posE_, a_e, aE_);
saveCoeff(posN_, a_n, aN_);
saveCoeff(posS_, a_s, aS_);
}
void SleMatrixBuilder::placeCoeffsMainDiag(size_t rowNum,
size_t colNum, double value) {
pSleSolver_->placeCoeff(rowNum, colNum, value);
}
void SleMatrixBuilder::placeCoeffsOtherDiags(size_t rowNum,
size_t colNum, double value, bool isInteriorCell) {
if (isInteriorCell) {
pSleSolver_->placeCoeff(rowNum, colNum - 1, value);
}
}
void SleMatrixBuilder::createMatrixAndVectors() {
size_t matrixDimention_ = dataPort_.getAllCellsAmount();
pSleSolver_->createContainers(matrixDimention_);
}
void SleMatrixBuilder::saveCoeff(size_t pos, double value,
std::vector<double>& coeff) {
if (0 < pos) {
coeff.at(pos - 1) = value;
}
}
} | 33.491667 | 91 | 0.631003 | artvns |
5da8da04f30037a3ebffb28d5b021149c11fed2d | 951 | cpp | C++ | 2017-08-19/C.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 3 | 2018-04-02T06:00:51.000Z | 2018-05-29T04:46:29.000Z | 2017-08-19/C.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-03-31T17:54:30.000Z | 2018-05-02T11:31:06.000Z | 2017-08-19/C.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-10-07T00:08:06.000Z | 2021-06-28T11:02:59.000Z | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int NMAX = 31;
int T, N;
int adj[NMAX][NMAX];
int main()
{
int i, j, k, t;
bool flag;
scanf("%d", &T);
for(t = 0;t < T;t += 1)
{
flag = true;
scanf("%d", &N);
if(N >= 6)
{
for(i = 1;i <= N;i += 1)
{
for(j = 1;j <= N - i;j += 1)
scanf("%*d");
}
}
else
{
for(i = 1;i <= N;i += 1)
{
for(j = 1;j <= N - i;j += 1)
{
scanf("%d", &adj[i][i + j]);
adj[i + j][i] = adj[i][i + j];
}
}
}
if(N >= 6)
printf("Bad Team!\n");
else
{
for(i = 1;i <= N;i += 1)
{
for(j = i + 1;j <= N;j += 1)
{
for(k = j + 1;k <= N;k += 1)
{
if((adj[i][j] && adj[j][k] && adj[k][i])
|| (!adj[i][j] && !adj[j][k] && !adj[k][i]))
flag = false;
}
}
}
if(flag)
printf("Great Team!\n");
else
printf("Bad Team!\n");
}
}
exit(0);
}
| 14.630769 | 51 | 0.392219 | tangjz |
5daa35f4e79a8828c2318ae5eb271a8db9a6d1ab | 1,742 | cpp | C++ | PE/ch14/14.2/winei.cpp | DustOfStars/CppPrimerPlus6 | 391e3ad76eaa99f331981cee72139d83115fc93d | [
"MIT"
] | null | null | null | PE/ch14/14.2/winei.cpp | DustOfStars/CppPrimerPlus6 | 391e3ad76eaa99f331981cee72139d83115fc93d | [
"MIT"
] | null | null | null | PE/ch14/14.2/winei.cpp | DustOfStars/CppPrimerPlus6 | 391e3ad76eaa99f331981cee72139d83115fc93d | [
"MIT"
] | null | null | null | #include <iostream>
#include "winei.h"
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
Wine::Wine(const char * l, int y, const int yr[], const int bot[])
: string(l), years(y), PairArray(ArrayInt(yr,y),ArrayInt(bot,y))
{
}
Wine::Wine(const char * l, const ArrayInt & yr, const ArrayInt & bot)
: string(l), years(yr.size()), PairArray(ArrayInt(yr), ArrayInt(yr))
{
if (yr.size() != bot.size())
{
cerr << "Year data, bottle data mismatch! Array set to 0 size.\n";
years = 0;
PairArray::operator=(PairArray(ArrayInt(),ArrayInt()));
}
else
{
PairArray::first() = yr;
PairArray::second() = bot;
}
}
Wine::Wine(const char * l, const PairArray & yr_bot)
: string(l), years(yr_bot.first().size()), PairArray(yr_bot)
{
}
Wine::Wine(const char * l, int y) : string(l), years(y),
PairArray(ArrayInt(0,y),ArrayInt(0,y))
{
}
void Wine::GetBottles()
{
if (years < 1)
{
cout << "No space to get data\n";
return;
}
cout << "Enter " << Label() <<
" data for " << years << " year(s):\n";
for (int i = 0; i < years; i++)
{
cout << "Enter year: ";
cin >> PairArray::first()[i];
cout << "Enter bottles for that year: ";
cin >> PairArray::second()[i];
}
}
void Wine::Show() const
{
cout << "Wine: " << Label() << endl;
cout << "\tYear\tBottles\n";
for (int i = 0; i < years; i++)
{
cout << "\t" << PairArray::first()[i];
cout << "\t" << PairArray::second()[i] << endl;
}
}
const string & Wine::Label() const
{
return (const string &)(*this);
}
int Wine::sum() const
{
return PairArray::second().sum();
}
| 21.775 | 74 | 0.538462 | DustOfStars |
5dacb2657b4b72c1f174c12be72a8cc9e8347f3b | 194 | hpp | C++ | include/mruby_integration/models/colour.hpp | HellRok/Taylor | aa9d901b4db77395a0bde896500016353adcd73b | [
"MIT"
] | 40 | 2021-05-25T04:21:49.000Z | 2022-02-19T05:05:45.000Z | include/mruby_integration/models/colour.hpp | HellRok/Taylor | aa9d901b4db77395a0bde896500016353adcd73b | [
"MIT"
] | 4 | 2021-09-17T06:52:35.000Z | 2021-12-29T23:07:18.000Z | include/mruby_integration/models/colour.hpp | HellRok/Taylor | aa9d901b4db77395a0bde896500016353adcd73b | [
"MIT"
] | 1 | 2021-12-23T00:59:27.000Z | 2021-12-23T00:59:27.000Z | #pragma once
#include "mruby.h"
#include "raylib.h"
extern RClass *Colour_class;
void setup_Colour(mrb_state*, mrb_value, Color*, int, int, int, int);
void append_models_Colour(mrb_state*);
| 17.636364 | 69 | 0.747423 | HellRok |
5dad76ffbddaefea91423f5e315c49c177c7cac1 | 2,745 | cpp | C++ | 图论/差分约束/acwing_1170.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | 3 | 2020-11-16T08:58:30.000Z | 2020-11-16T08:58:33.000Z | 图论/差分约束/acwing_1170.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | 图论/差分约束/acwing_1170.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i = a; i< n; i++)
#define per(i,a,n) for(int i=n-1; i>=a; i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define x first
#define y second
#define sz(x) ((int)(x).size())
typedef vector<int> vi;
typedef long long ll;
typedef pair<int, int> pii;
mt19937 mrand(random_device{}());
const ll mod = 1000000007;
int rnd(int x) { return mrand() % x;}
ll mulmod(ll a, ll b) {ll res=0;a%=mod;assert(b>=0);for(;b;b>>=1){if(b&1)res=(res+a)%mod;a=2*a%mod;}return res;}
ll powmod(ll a, ll b) {ll res=1;a%=mod;assert(b>=0);for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a;}
//snippet-head
//第一个就是判负环 全部加入队列跑一次SPFA即可
//所有奶牛的距离都是相对距离,所以需要虚拟原点,假设所有牛都在数轴的正半轴 所有点都在x0的左边 也就是说x0是最右边的
//对于第二个要求 直接把1号点固定在0 也就是 x1 = 0 因为都是相对距离 不影响距离 最后看一下xn是不是可以无限大 这也等价于1号点到其他点的最短距离
//但是虚拟原点 不需要实现 实际上 在判断负环的时候所有点都已经入队 可以起到同样的效果
//求一下xn的最长路 如果无穷大 就是无穷大 否则就是最大值
//约束条件:xi <= x[i+1] + 0, xb <= xa + l, xa <= xb - d
const int INF = 0x3f3f3f3f;
const int N = 1010, M = 21010; //边数判断就是满足条件的类 每类需要多少点 全部加起来
//因为加边 的时候 会满足所有条件 也就是说每个条件 都要单独加边
int q[N], h[N], e[M], ne[M], idx, w[M], cnt[N], dist[N];
bool st[N];
int n, m1, m2;
void add(int a, int b, int c){
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx ++;
}
bool spfa(int sz){
memset(dist, 0x3f, sizeof dist);
memset(st, 0, sizeof st);
memset(cnt, 0, sizeof cnt);
int hh = 0, tt = 1;
for(int i = 1; i <= sz; i++){ //加入队列 求负环
dist[i] = 0;
q[tt++] = i;
st[i] = true;
}
while(hh != tt){
int t = q[hh++];
if(hh == N) hh = 0;
st[t] = false;
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
if(dist[j] > dist[t] + w[i]){
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if(cnt[j] >= n) return false;
if(!st[j]){
q[tt++] = j;
if(tt == N) tt = 0;
st[j] = true;
}
}
}
}
return true;
}
int main(){
memset(h, -1, sizeof h);
scanf("%d%d%d", &n, &m1, &m2);
for(int i = 1; i < n; i++) add(i + 1, i, 0);
while(m1 --){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
if(b < a ) swap(a, b);
add(a, b, c);
}
while(m2 --){
int a,b ,c;
scanf("%d%d%d", &a, &b, &c);
if(b < a) swap(a, b);
add(b, a, -c);
}
if(!spfa(n)) puts("-1"); //前n个点的图有负环
else{
spfa(1); //将第一个点放进去求
if(dist[n] == INF) puts("-2");
else printf("%d\n", dist[n]);
}
return 0;
}
| 26.394231 | 112 | 0.488889 | tempure |
5dade33a7eb95eb746d98e0eecfccaeba73f0c6f | 3,870 | cpp | C++ | MMC/MMCKeys/keysmanager.cpp | Myweik/MMC_qgroundcontrol | 3aa97928d30fc9de56fde2a0d37a49245de83da4 | [
"Apache-2.0"
] | 2 | 2020-04-14T12:50:53.000Z | 2021-07-19T02:09:04.000Z | MMC/MMCKeys/keysmanager.cpp | Myweik/MMC_qgroundcontrol | 3aa97928d30fc9de56fde2a0d37a49245de83da4 | [
"Apache-2.0"
] | 5 | 2020-07-01T21:31:53.000Z | 2021-02-01T10:53:39.000Z | MMC/MMCKeys/keysmanager.cpp | Myweik/MMC_qgroundcontrol | 3aa97928d30fc9de56fde2a0d37a49245de83da4 | [
"Apache-2.0"
] | 2 | 2020-05-11T03:11:11.000Z | 2021-02-03T10:53:03.000Z | #include "keysmanager.h"
#include "QGCApplication.h"
#include "MMC/MMCMount/mmcmount.h"
MMCKey::MMCKey(int id, QObject *parent) : QObject(parent), _id(id)
{
_timer = new QTimer(this);
_timer->setInterval(100);
connect(_timer, SIGNAL(timeout()), this, SLOT(onTimerOut()));
}
void MMCKey::setKey(bool key)
{
if(key == _key) return;
_key = key;
emit keyChanged(_key);
if(_key){
emit press(this);
_accumulatedTime = 1;
_timer->start();
}else{
emit upspring(this);
_timer->stop();
if(_accumulatedTime < 5) emit click(this);
}
}
void MMCKey::onTimerOut()
{
_accumulatedTime++;
emit longPress(this);
}
//------------------------------------------------------------------------------
KeysManager::KeysManager(QObject *parent) : QObject(parent)
{
for(int i = 0; i < 5; i++){
_key[i] = new MMCKey(i, this);
connect(_key[i], SIGNAL(press(MMCKey*)), this, SLOT(onPress(MMCKey*)));
connect(_key[i], SIGNAL(upspring(MMCKey*)), this, SLOT(onUpspring(MMCKey*)));
connect(_key[i], SIGNAL(longPress(MMCKey*)), this, SLOT(onLongPress(MMCKey*)));
connect(_key[i], SIGNAL(click(MMCKey*)), this, SLOT(onClick(MMCKey*)));
}
/* an jian yu gong neng bang ding */
/* 0-A 1-B 2-C 3-D 4-E */
_keyId[4] = KEY_REC_OR_PHOTO;
}
void KeysManager::setKey(int id, bool key)
{
if(id < 0 || id > 4) return;
_key[id]->setKey(key);
}
/* ----------------------------------------- */
void KeysManager::onPress(MMCKey *key)
{
switch (_keyId[key->id()]) {
case KEY_REC_OR_PHOTO:
break;
case KEY_ZOOM_DOWN:
break;
case KEY_ZOOM_UP:
break;
default:
break;
}
}
void KeysManager::onUpspring(MMCKey *key)
{
switch (_keyId[key->id()]) {
case KEY_REC_OR_PHOTO:
if(key->accumulatedTime() > 1)
REC();
break;
case KEY_ZOOM_DOWN:
break;
case KEY_ZOOM_UP:
break;
default:
break;
}
}
void KeysManager::onLongPress(MMCKey *key)
{
switch (_keyId[key->id()]) {
case KEY_REC_OR_PHOTO:
break;
case KEY_ZOOM_DOWN:
break;
case KEY_ZOOM_UP:
break;
default:
break;
}
}
void KeysManager::onClick(MMCKey *key)
{
switch (_keyId[key->id()]) {
case KEY_REC_OR_PHOTO:
photo();
break;
case KEY_ZOOM_DOWN:
break;
case KEY_ZOOM_UP:
break;
default:
break;
}
}
/* ----------------------------------------- */
void KeysManager::photo()
{
// if(qgcApp()->toolbox()->multiVehicleManager()->activeVehicleAvailable()){
// Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle();
// if(activeVehicle && !activeVehicle->mountLost() && activeVehicle->currentMount() && activeVehicle->currentMount()->mountType() ==MountInfo::MOUNT_CUSTOM){
// CustomMount* camMount = dynamic_cast<CustomMount*>(activeVehicle->currentMount());
// camMount->doCameraTrigger();
// }
// }
if(qgcApp()->toolbox()->multiVehicleManager()->activeVehicleAvailable()){
Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle();
if(activeVehicle){
activeVehicle->doCameraTrigger();
}
}
}
void KeysManager::REC()
{
if(qgcApp()->toolbox()->multiVehicleManager()->activeVehicleAvailable()){
Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle();
if(activeVehicle && !activeVehicle->mountLost() && activeVehicle->currentMount() && activeVehicle->currentMount()->mountType() ==MountInfo::MOUNT_CUSTOM){
CustomMount* camMount = dynamic_cast<CustomMount*>(activeVehicle->currentMount());
camMount->videoTape();
}
}
}
| 26.326531 | 164 | 0.576486 | Myweik |
5db2c6544db63edb6f90ac06ac4cdcc4bd2e6add | 2,796 | cpp | C++ | src/vm/systemCalls.optionals.cpp | DosWorld/tmbasic | 99bd593bb074df6af83d952259b5eb81588f1e3f | [
"MIT"
] | 1 | 2022-01-29T05:45:46.000Z | 2022-01-29T05:45:46.000Z | src/vm/systemCalls.optionals.cpp | DosWorld/tmbasic | 99bd593bb074df6af83d952259b5eb81588f1e3f | [
"MIT"
] | null | null | null | src/vm/systemCalls.optionals.cpp | DosWorld/tmbasic | 99bd593bb074df6af83d952259b5eb81588f1e3f | [
"MIT"
] | null | null | null | #include "systemCall.h"
#include "Error.h"
#include "Optional.h"
namespace vm {
static std::pair<const ValueOptional*, const ObjectOptional*> valueOrObjectOptional(const Object& object) {
const auto* valueOptional = dynamic_cast<const ValueOptional*>(&object);
if (valueOptional != nullptr) {
return { valueOptional, nullptr };
}
const auto* objectOptional = dynamic_cast<const ObjectOptional*>(&object);
if (objectOptional != nullptr) {
return { nullptr, objectOptional };
}
throw Error(
ErrorCode::kInternalTypeConfusion,
fmt::format(
"Internal type confusion error. Target is neither {} nor {}.", NAMEOF_TYPE(ValueOptional),
NAMEOF_TYPE(ObjectOptional)));
}
void initSystemCallsOptionals() {
initSystemCall(SystemCall::kHasValue, [](const auto& input, auto* result) {
const auto valueOrObject = valueOrObjectOptional(input.getObject(-1));
const auto* valueOptional = valueOrObject.first;
const auto* objectOptional = valueOrObject.second;
result->returnedValue.setBoolean(
valueOptional != nullptr ? valueOptional->item.has_value() : objectOptional->item.has_value());
});
initSystemCall(SystemCall::kObjectOptionalNewMissing, [](const auto& /*input*/, auto* result) {
result->returnedObject = boost::make_local_shared<ObjectOptional>();
});
initSystemCall(SystemCall::kObjectOptionalNewPresent, [](const auto& input, auto* result) {
result->returnedObject = boost::make_local_shared<ObjectOptional>(input.getObjectPtr(-1));
});
initSystemCall(SystemCall::kValueOptionalNewMissing, [](const auto& /*input*/, auto* result) {
result->returnedObject = boost::make_local_shared<ValueOptional>();
});
initSystemCall(SystemCall::kValueOptionalNewPresent, [](const auto& input, auto* result) {
result->returnedObject = boost::make_local_shared<ValueOptional>(input.getValue(-1));
});
initSystemCall(SystemCall::kValue, [](const auto& input, auto* result) {
const auto valueOrObject = valueOrObjectOptional(input.getObject(-1));
const auto* valueOptional = valueOrObject.first;
const auto* objectOptional = valueOrObject.second;
if (valueOptional != nullptr) {
if (!valueOptional->item.has_value()) {
throw Error(ErrorCode::kValueNotPresent, "Optional value is not present.");
}
result->returnedValue = *valueOptional->item;
} else {
if (!objectOptional->item.has_value()) {
throw Error(ErrorCode::kValueNotPresent, "Optional value is not present.");
}
result->returnedObject = *objectOptional->item;
}
});
}
} // namespace vm
| 39.380282 | 107 | 0.664521 | DosWorld |
5db4dcaa97c8e90d29947b66e5a3ddc51388d606 | 7,673 | hpp | C++ | contrib/native/client/src/clientlib/streamSocket.hpp | akumarb2010/incubator-drill | a690b97074376a65ac0c1d86ee2a9fa32e997003 | [
"Apache-2.0"
] | 1 | 2020-12-27T04:08:49.000Z | 2020-12-27T04:08:49.000Z | contrib/native/client/src/clientlib/streamSocket.hpp | akumarb2010/incubator-drill | a690b97074376a65ac0c1d86ee2a9fa32e997003 | [
"Apache-2.0"
] | null | null | null | contrib/native/client/src/clientlib/streamSocket.hpp | akumarb2010/incubator-drill | a690b97074376a65ac0c1d86ee2a9fa32e997003 | [
"Apache-2.0"
] | 2 | 2019-11-12T09:21:02.000Z | 2019-12-16T09:51:25.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef STREAMSOCKET_HPP
#define STREAMSOCKET_HPP
#include "logger.hpp"
#include "wincert.ipp"
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
namespace Drill {
typedef boost::asio::ip::tcp::socket::lowest_layer_type streamSocket_t;
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> sslTCPSocket_t;
typedef boost::asio::ip::tcp::socket basicTCPSocket_t;
// Some helper typedefs to define the highly templatized boost::asio methods
typedef boost::asio::const_buffers_1 ConstBufferSequence;
typedef boost::asio::mutable_buffers_1 MutableBufferSequence;
// ReadHandlers have different possible signatures.
//
// As a standard C-type callback
// typedef void (*ReadHandler)(const boost::system::error_code& ec, std::size_t bytes_transferred);
//
// Or as a C++ functor
// struct ReadHandler {
// virtual void operator()(
// const boost::system::error_code& ec,
// std::size_t bytes_transferred) = 0;
//};
//
// We need a different signature though, since we need to pass in a member function of a drill client
// class (which is C++), as a functor generated by boost::bind as a ReadHandler
//
typedef boost::function<void (const boost::system::error_code& ec, std::size_t bytes_transferred) > ReadHandler;
class AsioStreamSocket{
public:
virtual ~AsioStreamSocket(){};
virtual streamSocket_t& getInnerSocket() = 0;
virtual std::size_t writeSome(
const ConstBufferSequence& buffers,
boost::system::error_code & ec) = 0;
virtual std::size_t readSome(
const MutableBufferSequence& buffers,
boost::system::error_code & ec) = 0;
//
// boost::asio::async_read has the signature
// template<
// typename AsyncReadStream,
// typename MutableBufferSequence,
// typename ReadHandler>
// void-or-deduced async_read(
// AsyncReadStream & s,
// const MutableBufferSequence & buffers,
// ReadHandler handler);
//
// For our use case, the derived class will have an instance of a concrete type for AsyncReadStream which
// will implement the requirements for the AsyncReadStream type. We need not pass that in as a parameter
// since the class already has the value
// The method is templatized since the ReadHandler type is dependent on the class implementing the read
// handler (basically the class using the asio stream)
//
virtual void asyncRead( const MutableBufferSequence & buffers, ReadHandler handler) = 0;
// call the underlying protocol's handshake method.
// if the useSystemConfig flag is true, then use properties read
// from the underlying operating system
virtual void protocolHandshake(bool useSystemConfig) = 0;
virtual void protocolClose() = 0;
};
class Socket:
public AsioStreamSocket,
public basicTCPSocket_t{
public:
Socket(boost::asio::io_service& ioService) : basicTCPSocket_t(ioService) {
}
~Socket(){
boost::system::error_code ignorederr;
this->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignorederr);
this->close();
};
basicTCPSocket_t& getSocketStream(){ return *this;}
streamSocket_t& getInnerSocket(){ return this->lowest_layer();}
std::size_t writeSome(
const ConstBufferSequence& buffers,
boost::system::error_code & ec){
return this->write_some(buffers, ec);
}
std::size_t readSome(
const MutableBufferSequence& buffers,
boost::system::error_code & ec){
return this->read_some(buffers, ec);
}
void asyncRead( const MutableBufferSequence & buffers, ReadHandler handler){
return async_read(*this, buffers, handler);
}
void protocolHandshake(bool useSystemConfig){}; //nothing to do
void protocolClose(){
// shuts down the socket!
boost::system::error_code ignorederr;
((basicTCPSocket_t*)this)->shutdown(boost::asio::ip::tcp::socket::shutdown_both,
ignorederr
);
}
};
#if defined(IS_SSL_ENABLED)
class SslSocket:
public AsioStreamSocket,
public sslTCPSocket_t{
public:
SslSocket(boost::asio::io_service& ioService, boost::asio::ssl::context &sslContext) :
sslTCPSocket_t(ioService, sslContext) {
}
~SslSocket(){
this->lowest_layer().close();
};
sslTCPSocket_t& getSocketStream(){ return *this;}
streamSocket_t& getInnerSocket(){ return this->lowest_layer();}
std::size_t writeSome(
const ConstBufferSequence& buffers,
boost::system::error_code & ec){
return this->write_some(buffers, ec);
}
std::size_t readSome(
const MutableBufferSequence& buffers,
boost::system::error_code & ec){
return this->read_some(buffers, ec);
}
void asyncRead( const MutableBufferSequence & buffers, ReadHandler handler){
return async_read(*this, buffers, handler);
}
//
// public method that can be invoked by callers to invoke the ssl handshake
// throws: boost::system::system_error
void protocolHandshake(bool useSystemConfig){
if(useSystemConfig){
std::string msg = "";
int ret = loadSystemTrustStore(this->native_handle(), msg);
if(!msg.empty()){
DRILL_LOG(LOG_WARNING) << msg.c_str() << std::endl;
}
if(ret){
boost::system::error_code ec(EPROTO, boost::system::system_category());
boost::asio::detail::throw_error(ec, msg.c_str());
}
}
this->handshake(boost::asio::ssl::stream<boost::asio::ip::tcp::socket>::client);
return;
};
//
// public method that can be invoked by callers to invoke a clean ssl shutdown
// throws: boost::system::system_error
void protocolClose(){
try{
this->shutdown();
}catch(boost::system::system_error e){
//swallow the exception. The channel is unusable anyway
}
// shuts down the socket!
boost::system::error_code ignorederr;
this->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both,
ignorederr
);
return;
};
};
#endif
} // namespace Drill
#endif //STREAMSOCKET_HPP
| 35.03653 | 114 | 0.619314 | akumarb2010 |
5db85986044fcfd4415bf089cdc1a101c59bbf90 | 12,638 | hpp | C++ | src/bpsw.hpp | NewYaroslav/xalgorithms | ffb9abc6107bed496382b053f333c40fab61a700 | [
"MIT"
] | null | null | null | src/bpsw.hpp | NewYaroslav/xalgorithms | ffb9abc6107bed496382b053f333c40fab61a700 | [
"MIT"
] | null | null | null | src/bpsw.hpp | NewYaroslav/xalgorithms | ffb9abc6107bed496382b053f333c40fab61a700 | [
"MIT"
] | null | null | null | /*
Тест BPSW на простоту чисел
Источник: http://e-maxx.ru/algo/bpsw
*/
#ifndef XA_BPSW_HPP_INCLUDED
#define XA_BPSW_HPP_INCLUDED
#include <algorithm>
#include <cmath>
#include <map>
#include <vector>
namespace xaBPSW {
//! Модуль 64-битного числа
long long abs (long long n) {
return n < 0 ? -n : n;
}
unsigned long long abs (unsigned long long n) {
return n;
}
//! Возвращает true, если n четное
template <class T>
bool even (const T & n) {
// return n % 2 == 0;
return (n & 1) == 0;
}
//! Делит число на 2
template <class T>
void bisect (T & n) {
// n /= 2;
n >>= 1;
}
//! Умножает число на 2
template <class T>
void redouble (T & n) {
// n *= 2;
n <<= 1;
}
//! Возвращает true, если n - точный квадрат простого числа
template <class T>
bool perfect_square (const T & n) {
T sq = (T) ceil (sqrt ((double)n));
return sq*sq == n;
}
//! Вычисляет корень из числа, округляя его вниз
template <class T>
T sq_root (const T & n) {
return (T) floor (sqrt ((double) n));
}
//! Возвращает количество бит в числе (т.е. минимальное количество бит, которыми можно представить данное число)
template <class T>
unsigned bits_in_number (T n) {
if (n == 0)
return 1;
unsigned result = 0;
while (n) {
bisect (n);
++result;
}
return result;
}
//! Возвращает значение k-го бита числа (биты нумеруются с нуля)
template <class T>
bool test_bit (const T & n, unsigned k) {
return (n & (T(1) << k)) != 0;
}
//! Умножает a *= b (mod n)
template <class T>
void mulmod (T & a, T b, const T & n) {
// наивная версия, годится только для длинной арифметики
a *= b;
a %= n;
}
template <>
void mulmod (int & a, int b, const int & n) {
a = int( (((long long)a) * b) % n );
}
template <>
void mulmod (unsigned & a, unsigned b, const unsigned & n) {
a = unsigned( (((unsigned long long)a) * b) % n );
}
template <>
void mulmod (unsigned long long & a, unsigned long long b, const unsigned long long & n) {
// сложная версия, основанная на бинарном разложении произведения в сумму
if (a >= n)
a %= n;
if (b >= n)
b %= n;
unsigned long long res = 0;
while (b)
if (!even (b))
{
res += a;
while (res >= n)
res -= n;
--b;
}
else
{
redouble (a);
while (a >= n)
a -= n;
bisect (b);
}
a = res;
}
template <>
void mulmod (long long & a, long long b, const long long & n) {
bool neg = false;
if (a < 0)
{
neg = !neg;
a = -a;
}
if (b < 0)
{
neg = !neg;
b = -b;
}
unsigned long long aa = a;
mulmod<unsigned long long> (aa, (unsigned long long)b, (unsigned long long)n);
a = (long long)aa * (neg ? -1 : 1);
}
//! Вычисляет a^k (mod n). Использует бинарное возведение в степень
template <class T, class T2>
T powmod (T a, T2 k, const T & n) {
T res = 1;
while (k)
if (!even (k))
{
mulmod (res, a, n);
--k;
}
else
{
mulmod (a, a, n);
bisect (k);
}
return res;
}
//! Переводит число n в форму q*2^p
template <class T>
void transform_num (T n, T & p, T & q) {
T p_res = 0;
while (even (n))
{
++p_res;
bisect (n);
}
p = p_res;
q = n;
}
//! Алгоритм Евклида
template <class T, class T2>
T gcd (const T & a, const T2 & b) {
return (a == 0) ? b : gcd (b % a, a);
}
//! Вычисляет jacobi(a,b)
template <class T>
T jacobi (T a, T b) {
//#pragma warning (push)
//#pragma warning (disable: 4146)
if (a == 0)
return 0;
if (a == 1)
return 1;
if (a < 0)
if ((b & 2) == 0)
return jacobi (-a, b);
else
return - jacobi (-a, b);
T e, a1;
transform_num (a, e, a1);
T s;
if (even (e) || (b & 7) == 1 || (b & 7) == 7)
s = 1;
else
s = -1;
if ((b & 3) == 3 && (a1 & 3) == 3)
s = -s;
if (a1 == 1)
return s;
return s * jacobi (b % a1, a1);
//#pragma warning (pop)
}
//! Вычисляет pi(b) первых простых чисел. Возвращает ссылку на вектор с простыми (в векторе может оказаться больше простых, чем надо) и в pi - pi(b)
template <class T, class T2>
const std::vector<T> & get_primes (const T & b, T2 & pi) {
static std::vector<T> primes;
static T counted_b;
// если результат уже был вычислен ранее, возвращаем его, иначе довычисляем простые
if (counted_b >= b)
pi = T2 (std::upper_bound (primes.begin(), primes.end(), b) - primes.begin());
else
{
// число 2 обрабатываем отдельно
if (counted_b == 0)
{
primes.push_back (2);
counted_b = 2;
}
// теперь обрабатываем все нечётные, пока не наберём нужное количество простых
T first = counted_b == 2 ? 3 : primes.back()+2;
for (T cur=first; cur<=b; ++++cur)
{
bool cur_is_prime = true;
for (typename std::vector<T>::const_iterator iter = primes.begin(), end = primes.end(); iter != end; ++iter)
{
const T & div = *iter;
if (div * div > cur)
break;
if (cur % div == 0)
{
cur_is_prime = false;
break;
}
}
if (cur_is_prime)
primes.push_back (cur);
}
counted_b = b;
pi = (T2) primes.size();
}
return primes;
}
//! Тривиальная проверка n на простоту, перебираются все делители до m. Результат: 1 - если n точно простое, p - его найденный делитель, 0 - если неизвестно, является ли n простым или нет
template <class T, class T2>
T2 prime_div_trivial (const T & n, T2 m)
{
// сначала проверяем тривиальные случаи
if (n == 2 || n == 3)
return 1;
if (n < 2)
return 0;
if (even (n))
return 2;
// генерируем простые от 3 до m
T2 pi;
const std::vector<T2> & primes = get_primes (m, pi);
// делим на все простые
for (typename std::vector<T2>::const_iterator iter=primes.begin(), end=primes.end();
iter!=end && *iter <= m; ++iter) {
const T2 & div = *iter;
if (div * div > n)
break;
else
if (n % div == 0)
return div;
}
if (n < m*m)
return 1;
return 0;
}
//! Усиленный алгоритм Миллера-Рабина проверки n на простоту по основанию b
template <class T, class T2>
bool miller_rabin (T n, T2 b) {
// сначала проверяем тривиальные случаи
if (n == 2)
return true;
if (n < 2 || even (n))
return false;
// проверяем, что n и b взаимно просты (иначе это приведет к ошибке)
// если они не взаимно просты, то либо n не просто, либо нужно увеличить b
if (b < 2)
b = 2;
for (T g; (g = gcd (n, b)) != 1; ++b)
if (n > g)
return false;
// разлагаем n-1 = q*2^p
T n_1 = n;
--n_1;
T p, q;
transform_num (n_1, p, q);
// вычисляем b^q mod n, если оно равно 1 или n-1, то n, вероятно, простое
T rem = powmod (T(b), q, n);
if (rem == 1 || rem == n_1)
return true;
// теперь вычисляем b^2q, b^4q, ... , b^((n-1)/2)
// если какое-либо из них равно n-1, то n, вероятно, простое
for (T i=1; i<p; i++)
{
mulmod (rem, rem, n);
if (rem == n_1)
return true;
}
return false;
}
//! Усиленный алгоритм Лукаса-Селфриджа проверки n на простоту. Используется усиленный алгоритм Лукаса с параметрами Селфриджа. Работает только с знаковыми типами!!! Второй параметр unused не используется, он только дает тип
template <class T, class T2>
bool lucas_selfridge (const T & n, T2 unused) {
// сначала проверяем тривиальные случаи
if (n == 2)
return true;
if (n < 2 || even (n))
return false;
// проверяем, что n не является точным квадратом, иначе алгоритм даст ошибку
if (perfect_square (n))
return false;
// алгоритм Селфриджа: находим первое число d такое, что:
// jacobi(d,n)=-1 и оно принадлежит ряду { 5,-7,9,-11,13,... }
T2 dd;
for (T2 d_abs = 5, d_sign = 1; ; d_sign = -d_sign, ++++d_abs)
{
dd = d_abs * d_sign;
T g = gcd (n, d_abs);
if (1 < g && g < n)
// нашли делитель - d_abs
return false;
if (jacobi (T(dd), n) == -1)
break;
}
// параметры Селфриджа
T2
p = 1,
q = (p*p - dd) / 4;
// разлагаем n+1 = d*2^s
T n_1 = n;
++n_1;
T s, d;
transform_num (n_1, s, d);
// алгоритм Лукаса
T
u = 1,
v = p,
u2m = 1,
v2m = p,
qm = q,
qm2 = q*2,
qkd = q;
for (unsigned bit = 1, bits = bits_in_number(d); bit < bits; bit++) {
mulmod (u2m, v2m, n);
mulmod (v2m, v2m, n);
while (v2m < qm2)
v2m += n;
v2m -= qm2;
mulmod (qm, qm, n);
qm2 = qm;
redouble (qm2);
if (test_bit (d, bit))
{
T t1, t2;
t1 = u2m;
mulmod (t1, v, n);
t2 = v2m;
mulmod (t2, u, n);
T t3, t4;
t3 = v2m;
mulmod (t3, v, n);
t4 = u2m;
mulmod (t4, u, n);
mulmod (t4, (T)dd, n);
u = t1 + t2;
if (!even (u))
u += n;
bisect (u);
u %= n;
v = t3 + t4;
if (!even (v))
v += n;
bisect (v);
v %= n;
mulmod (qkd, qm, n);
}
}
// точно простое (или псевдо-простое)
if (u == 0 || v == 0)
return true;
// вычисляем оставшиеся члены
T qkd2 = qkd;
redouble (qkd2);
for (T2 r = 1; r < s; ++r) {
mulmod (v, v, n);
v -= qkd2;
if (v < 0) v += n;
if (v < 0) v += n;
if (v >= n) v -= n;
if (v >= n) v -= n;
if (v == 0)
return true;
if (r < s-1)
{
mulmod (qkd, qkd, n);
qkd2 = qkd;
redouble (qkd2);
}
}
return false;
}
//! Алгоритм Бэйли-Померанс-Селфридж-Вагстафф (BPSW) проверки n на простоту
template <class T>
bool baillie_pomerance_selfridge_wagstaff (T n) {
// перебираем тривиальные делители до 1000
int div = prime_div_trivial (n, 1000);
if (div == 1)
return true;
if (div > 1)
return false;
// тест Миллера-Рабина по основанию 2
if (!miller_rabin (n, 2))
return false;
// усиленный тест Лукаса-Селфриджа
return lucas_selfridge (n, 0);
}
//! Алгоритм Бэйли-Померанс-Селфридж-Вагстафф (BPSW) проверки n на простоту
template <class T>
bool isprime (T n) {
return baillie_pomerance_selfridge_wagstaff (n);
}
}
#endif // BPSW_HPP_INCLUDED
| 26.219917 | 228 | 0.438835 | NewYaroslav |
5dbcd6f5f5fb732707e72a761ff1cc70ea0b752d | 1,202 | hpp | C++ | src/custom_topic/include/topic_pubsub/pub.hpp | IntelligentSystemsLabUTV/ros2_examples | b34d9238d680dd6b06177586f81bfed0bae31eb2 | [
"MIT"
] | null | null | null | src/custom_topic/include/topic_pubsub/pub.hpp | IntelligentSystemsLabUTV/ros2_examples | b34d9238d680dd6b06177586f81bfed0bae31eb2 | [
"MIT"
] | null | null | null | src/custom_topic/include/topic_pubsub/pub.hpp | IntelligentSystemsLabUTV/ros2_examples | b34d9238d680dd6b06177586f81bfed0bae31eb2 | [
"MIT"
] | null | null | null | /**
* Publisher definition.
*
* Roberto Masocco <[email protected]>
*
* November 22, 2021
*/
#ifndef PUB_HPP
#define PUB_HPP
#include <rclcpp/rclcpp.hpp> //! rclcpp base library
#include <ros2_examples_interfaces/msg/string.hpp> //! This time we use our own
#define PUB_PERIOD 300 // Publisher transmission time period [ms]
/**
* Simple publisher node: transmits strings on a topic.
*/
//! Every node must extend publicly the Node base class
class Pub : public rclcpp::Node
{
public:
//! There must always be a constructor, with arbitrary input arguments
Pub();
//! ROS-specific members better be private
private:
//! DDS endpoint, acting as a publisher
//! Syntax is: rclcpp::Publisher<INTERFACE_TYPE>::SharedPtr OBJ;
rclcpp::Publisher<ros2_examples_interfaces::msg::String>::SharedPtr publisher_;
//! ROS-2 managed timer: enables one to set up a periodic job
//! The job is coded in a callback, which better be a private method
//! Syntax is: rclcpp::TimerBase::SharedPtr OBJ;
//! Callback signature must be: void FUNC_NAME(void);
rclcpp::TimerBase::SharedPtr pub_timer_;
void pub_timer_callback(void);
unsigned long pub_cnt_; // Marks messages
};
#endif
| 26.130435 | 81 | 0.72629 | IntelligentSystemsLabUTV |
5dbfe826e98c69989b1f53d2c6478b563182aedc | 1,664 | cpp | C++ | B05576_07_Code/rosbook_arm_snippets/src/move_group_plan_single_target.cpp | podhrmic/Effective-Robotics-Programming-with-ROS | 9c5f3188bfdb47d6d0ee5c36da803e2381fb1a00 | [
"MIT"
] | 46 | 2017-02-11T18:28:57.000Z | 2021-12-12T07:55:22.000Z | B05576_07_Code/rosbook_arm_snippets/src/move_group_plan_single_target.cpp | podhrmic/Effective-Robotics-Programming-with-ROS | 9c5f3188bfdb47d6d0ee5c36da803e2381fb1a00 | [
"MIT"
] | 1 | 2017-03-22T13:07:55.000Z | 2020-11-02T09:12:52.000Z | B05576_07_Code/rosbook_arm_snippets/src/move_group_plan_single_target.cpp | podhrmic/Effective-Robotics-Programming-with-ROS | 9c5f3188bfdb47d6d0ee5c36da803e2381fb1a00 | [
"MIT"
] | 23 | 2016-12-30T05:11:37.000Z | 2021-05-04T15:08:34.000Z | #include <moveit/move_group_interface/move_group.h>
#include <moveit_msgs/DisplayTrajectory.h>
int main(int argc, char **argv)
{
// Initialize ROS, create the node handle and an async spinner
ros::init(argc, argv, "move_group_plan_single_target");
ros::NodeHandle nh;
ros::AsyncSpinner spin(1);
spin.start();
// Get the arm planning group
moveit::planning_interface::MoveGroup plan_group("arm");
// Create a published for the arm plan visualization
ros::Publisher display_pub = nh.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
// Set a goal message as a pose of the end effector
geometry_msgs::Pose goal;
goal.orientation.x = -0.000764819;
goal.orientation.y = 0.0366097;
goal.orientation.z = 0.00918912;
goal.orientation.w = 0.999287;
goal.position.x = 0.775884;
goal.position.y = 0.43172;
goal.position.z = 2.71809;
// Set the tolerance to consider the goal achieved
plan_group.setGoalTolerance(0.2);
// Set the target pose, which is the goal we already defined
plan_group.setPoseTarget(goal);
// Perform the planning step, and if it succeeds display the current
// arm trajectory and move the arm
moveit::planning_interface::MoveGroup::Plan goal_plan;
if (plan_group.plan(goal_plan))
{
moveit_msgs::DisplayTrajectory display_msg;
display_msg.trajectory_start = goal_plan.start_state_;
display_msg.trajectory.push_back(goal_plan.trajectory_);
display_pub.publish(display_msg);
sleep(5.0);
plan_group.move();
}
ros::shutdown();
return 0;
}
| 30.254545 | 123 | 0.695913 | podhrmic |
5dc04855bd8ddedfd58cc73ff07656b9fcc9f8ac | 882 | cpp | C++ | leetcode/Hashmap/49.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | leetcode/Hashmap/49.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | leetcode/Hashmap/49.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | #include<iostream>
#include<unordered_map>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string,vector<string>> map;
for(string s : strs){
string key = s;
sort(key.begin(),key.end());
map[key].push_back(s);
}
// 想要拷贝元素:for(auto x : range)
// 想要修改元素 : for(auto&& x : range)
// 想要只读元素:for(const auto& x : range)
for(const auto& p : map){
res.push_back(p.second);
}
return res;
}
};
void print_vec(vector<vector<string>>& s){
for(vector<string> vec : s){
for(string c : vec){
cout<<c<<' ';
}
cout<<endl;
}
}
int main(){
}
| 23.837838 | 65 | 0.510204 | codehuanglei |
5dc40e9c639f7b42e1895144a209170499da2c2e | 561 | hpp | C++ | include/ccbase/utility/bytes.hpp | adityaramesh/ccbase | 595e1416aab3cc8bc976aad9bb3e262c7d11e3b2 | [
"BSD-3-Clause-Clear"
] | 8 | 2015-01-08T05:44:43.000Z | 2021-05-11T15:54:17.000Z | include/ccbase/utility/bytes.hpp | adityaramesh/ccbase | 595e1416aab3cc8bc976aad9bb3e262c7d11e3b2 | [
"BSD-3-Clause-Clear"
] | 1 | 2016-01-31T08:48:53.000Z | 2016-01-31T08:54:28.000Z | include/ccbase/utility/bytes.hpp | adityaramesh/ccbase | 595e1416aab3cc8bc976aad9bb3e262c7d11e3b2 | [
"BSD-3-Clause-Clear"
] | 2 | 2015-03-26T11:08:18.000Z | 2016-01-30T03:28:06.000Z | /*
** File Name: bytes.hpp
** Author: Aditya Ramesh
** Date: 07/09/2014
** Contact: [email protected]
*/
#ifndef Z66BE627C_AD04_47FD_9360_9A51E7280DC8
#define Z66BE627C_AD04_47FD_9360_9A51E7280DC8
#include <cstdint>
constexpr uint64_t
operator ""_KB(unsigned long long int x)
{ return x << 10; }
constexpr uint64_t
operator ""_MB(unsigned long long int x)
{ return x << 20; }
constexpr uint64_t
operator ""_GB(unsigned long long int x)
{ return x << 30; }
constexpr uint64_t
operator ""_TB(unsigned long long int x)
{ return x << 40; }
#endif
| 18.7 | 45 | 0.716578 | adityaramesh |
5dc5ddbdb072da284c0a9d7aafb8e7ebed1790e8 | 2,377 | cpp | C++ | mp/src/game/server/Mod/ClassicPhases.cpp | hekar/luminousforts-2013 | 09f07df4def93fa0d774721375a6c7c9da26d71f | [
"Unlicense"
] | 7 | 2019-02-04T01:17:26.000Z | 2022-02-26T21:36:34.000Z | mp/src/game/server/Mod/ClassicPhases.cpp | hekar/luminousforts-2013 | 09f07df4def93fa0d774721375a6c7c9da26d71f | [
"Unlicense"
] | 11 | 2016-05-06T22:44:46.000Z | 2016-05-06T22:45:03.000Z | mp/src/game/server/Mod/ClassicPhases.cpp | hekar/luminousforts-2013 | 09f07df4def93fa0d774721375a6c7c9da26d71f | [
"Unlicense"
] | 2 | 2016-06-28T11:34:53.000Z | 2017-04-01T18:08:46.000Z | /* ***** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/LGPL 2.1/GPL 2.0
The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
...
for the specific language governing rights and limitations under the
License.
The Original Code is for LuminousForts.
The Initial Developer of the Original Code is Hekar Khani.
Portions created by the Hekar Khani are Copyright (C) 2010
Hekar Khani. All Rights Reserved.
Contributor(s):
Hekar Khani <[email protected]>
Alternatively, the contents of this file may be used under the terms of
either of the GNU General Public License Version 2 or later (the "GPL"),
...
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK ***** */
/*===============================================================
Server
This is a pretty old file from probably around March 2009.
Only the phase manager really applies. If you want you can
use the other stuff though.
Last Updated Sept 13 2009
===============================================================*/
#include "cbase.h"
#include "PhaseControl.h"
#include "ClassicPhases.h"
#define LUMINOUSFORTS_SOUND_BUILD "Luminousforts.Build"
#define LUMINOUSFORTS_SOUND_COMBAT "Luminousforts.Combat"
class CPrecachePhaseSounds : public CBaseEntity
{
public:
void Precache()
{
PrecacheScriptSound( LUMINOUSFORTS_SOUND_BUILD );
PrecacheScriptSound( LUMINOUSFORTS_SOUND_COMBAT );
//HODO: Move hacky precaches
PrecacheScriptSound( "CTF.Draw" );
PrecacheScriptSound( "CTF.BlueWins" );
PrecacheScriptSound( "CTF.RedWins" );
}
};
LINK_ENTITY_TO_CLASS( precache_sourceforts_sounds, CPrecachePhaseSounds );
//
// Name: CBuildPhase
// Author: Hekar Khani
// Description: On the switch to build phase
// Notes:
//
CBuildPhase::CBuildPhase() :
CPhaseBase( PHASE_BUILD, "BuildPhase" )
{
}
CBuildPhase::~CBuildPhase()
{
}
void CBuildPhase::SwitchTo()
{
Msg( "[LF] Build Phase Has Begun\n" );
PlaySound( LUMINOUSFORTS_SOUND_BUILD );
}
//
// Name: CCombatPhase
// Author: Hekar Khani
// Description: On the switch to combat phase
// Notes:
//
CCombatPhase::CCombatPhase() :
CPhaseBase( PHASE_COMBAT, "CombatPhase" )
{
}
CCombatPhase::~CCombatPhase()
{
}
void CCombatPhase::SwitchTo()
{
Msg( "[LF] Combat Phase Has Begun\n" );
PlaySound( LUMINOUSFORTS_SOUND_COMBAT );
}
| 22.855769 | 76 | 0.700042 | hekar |
5dcaaef856d43a2166ded3825b63f727ed989dbf | 770 | hpp | C++ | src/OpenJijDotNet.Native/openjij/utility/Xorshift.hpp | takuya-takeuchi/OpenJijDotNet | e1cd30efbf0c561e89bc10bd90cd36a3176ad09a | [
"MIT"
] | null | null | null | src/OpenJijDotNet.Native/openjij/utility/Xorshift.hpp | takuya-takeuchi/OpenJijDotNet | e1cd30efbf0c561e89bc10bd90cd36a3176ad09a | [
"MIT"
] | null | null | null | src/OpenJijDotNet.Native/openjij/utility/Xorshift.hpp | takuya-takeuchi/OpenJijDotNet | e1cd30efbf0c561e89bc10bd90cd36a3176ad09a | [
"MIT"
] | null | null | null | #ifndef _CPP_UTILITY_XORSHIFT_H_
#define _CPP_UTILITY_XORSHIFT_H_
#include "../export.hpp"
#include "../shared.hpp"
#include <random>
#include <utility/random.hpp>
using namespace openjij;
using namespace openjij::utility;
DLLEXPORT Xorshift* utility_Xorshift_new()
{
return new Xorshift();
}
DLLEXPORT Xorshift* utility_Xorshift_new2(const uint32_t s)
{
return new Xorshift(s);
}
DLLEXPORT void utility_Xorshift_delete(Xorshift* xorshift)
{
delete xorshift;
}
DLLEXPORT uint32_t utility_Xorshift_operator(Xorshift* xorshift)
{
return xorshift->operator()();
}
DLLEXPORT uint32_t utility_Xorshift_min()
{
return Xorshift::min();
}
DLLEXPORT uint32_t utility_Xorshift_max()
{
return Xorshift::max();
}
#endif // _CPP_UTILITY_XORSHIFT_H_
| 17.5 | 64 | 0.758442 | takuya-takeuchi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.