hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
553e2f47b76fae3019b8a3ac9ad95c7fcd99c4ad | 245 | h | C | dehydrator.h | benlau/quikit | e6aa7fa024bf6d456022e33b6dd98740118767cf | [
"Apache-2.0"
] | null | null | null | dehydrator.h | benlau/quikit | e6aa7fa024bf6d456022e33b6dd98740118767cf | [
"Apache-2.0"
] | null | null | null | dehydrator.h | benlau/quikit | e6aa7fa024bf6d456022e33b6dd98740118767cf | [
"Apache-2.0"
] | null | null | null | #ifndef DEHYDRATOR_H
#define DEHYDRATOR_H
#include <QString>
#include <QObject>
#include <QVariantMap>
namespace QUIKit {
class Dehydrator
{
public:
Dehydrator();
QVariantMap dehydrate(QObject* object);
};
}
#endif // DEHYDRATOR_H
| 11.666667 | 43 | 0.726531 | [
"object"
] |
554014b9734999e4829734b13d9bd3cdd748ecef | 1,013 | h | C | drawObject.h | dfyzy/simpleGL | 55790726559b46be596d16c294940ba629bd838c | [
"MIT"
] | 1 | 2016-10-16T21:19:21.000Z | 2016-10-16T21:19:21.000Z | drawObject.h | dfyzy/simpleGL | 55790726559b46be596d16c294940ba629bd838c | [
"MIT"
] | null | null | null | drawObject.h | dfyzy/simpleGL | 55790726559b46be596d16c294940ba629bd838c | [
"MIT"
] | null | null | null | /* The base visual class
* Draws quads
*/
#ifndef SIMPLE_DRAW_OBJECT_H
#define SIMPLE_DRAW_OBJECT_H
#include "openGLContextTypes.h"
#include "color.h"
#include "matrix.h"
#include "texture.h"
namespace simpleGL {
constexpr Vector QUAD[] = {{-0.5f, 0.5f},
{-0.5f, -0.5f},
{0.5f, 0.5f},
{0.5f, -0.5f}};
class DrawObject {
private:
GLint qid;
public:
DrawObject();
~DrawObject();
GLint getId() const { return qid; }
void bindData(EBufferDataType type, float data[]) const;
void bindQuadData(EBufferDataType type, Matrix model) const {
float data[QUAD_VERTS*2];
int offset = 0;
for (int i = 0; i < QUAD_VERTS; i++)
(model*QUAD[i]).load(data, &offset);
bindData(type, data);
}
void bindVertexData(Matrix model) const {
bindQuadData(EBufferDataType::Vertex, model);
}
void bindTextureData(Texture texture) const {
bindQuadData(EBufferDataType::Texture, texture.getMatrix());
}
void bindColorData(Color color) const;
void draw() const;
};
}
#endif
| 17.77193 | 62 | 0.675222 | [
"vector",
"model"
] |
5545712b1cb47b05759c22dadf8e5aed99ea00d9 | 14,548 | h | C | String/KString.h | RobR89/KayLib | a78fa37b185685028f8bfac0a31c4d47f9ff1998 | [
"Apache-2.0"
] | null | null | null | String/KString.h | RobR89/KayLib | a78fa37b185685028f8bfac0a31c4d47f9ff1998 | [
"Apache-2.0"
] | null | null | null | String/KString.h | RobR89/KayLib | a78fa37b185685028f8bfac0a31c4d47f9ff1998 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 Robert Reinhart.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef KSTRING_H
#define KSTRING_H
#include <string>
#include <stdio.h>
#include <sstream>
#include <algorithm>
namespace KayLib
{
class KString
{
public:
/**
* Convert a character to its numeric digit value.
* @param c The character to convert.
* @return The value (0-9) or -1 if it was not a digit.
*/
static int digit(const int c)
{
int d = c - '0';
if(d >= 0 && d <= 9)
{
return d;
}
return -1;
}
/**
* Convert a character to its numeric digit value.
* @param c The character to convert.
* @return The value (0-15) or -1 if it was not a digit.
*/
static int digitHex(const int c)
{
int d = c - '0';
if(d >= 0 && d <= 9)
{
return d;
}
d = c - 'a';
if(d >= 0 && d <= 5)
{
return d + 10;
}
d = c - 'A';
if(d >= 0 && d <= 5)
{
return d + 10;
}
return -1;
}
/**
* Create a string containing the hex values of the data.
* @param data The data to convert.
* @param length The length of the data.
* @param separator A string to insert between each 2 byte hex code.
* @return The created string.
*/
static std::string toHex(const unsigned char *data, const int length, const std::string separator)
{
char hexChar[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
std::string hex;
for(int i = 0; i < length; i++)
{
unsigned char v = data[i];
unsigned char low = v & 0x0f;
unsigned char high = (v >> 4) & 0x0f;
hex += hexChar[high];
hex += hexChar[low];
if(i < length - 1)
{
hex += separator;
}
}
return hex;
}
/**
* Create a string containing the hex values of the data.
* @param data The data to convert.
* @param length The length of the data.
* @return The created string.
*/
static std::string toHex(const unsigned char *data, const int length)
{
char hexChar[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
std::string hex;
for(int i = 0; i < length; i++)
{
unsigned char v = data[i];
unsigned char low = v & 0x0f;
unsigned char high = (v >> 4) & 0x0f;
hex += hexChar[high];
hex += hexChar[low];
}
return hex;
}
/**
* Create a string containing the 2 character hex value.
* @param value The value to convert.
* @return The created string.
*/
static std::string toHex(const unsigned char value)
{
char hexChar[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
unsigned char low = value & 0x0f;
unsigned char high = (value >> 4) & 0x0f;
std::string hex;
hex += hexChar[high];
hex += hexChar[low];
return hex;
}
/**
* Convert the string to all lower case.
* @param str The string to convert.
* @return The converted string.
*/
static std::string strToLower(std::string str)
{
std::string str2;
str2.resize(str.size());
std::transform(str.begin(), str.end(), str2.begin(), std::ptr_fun<int, int>(std::tolower));
return str2;
}
/**
* Convert the string to all upper case.
* @param str The string to convert.
* @return The converted string.
*/
static std::string strToUpper(std::string str)
{
std::string str2;
str2.resize(str.size());
std::transform(str.begin(), str.end(), str2.begin(), std::ptr_fun<int, int>(std::toupper));
return str2;
}
/**
* Does the string 'str' begin with the string 'begin'?
* @param str The string to check.
* @param begin The string to look for
* @return true if 'str' begins with 'begin'
*/
static bool beginsWith(const std::string &str, const std::string &begin)
{
return str.find(begin) == 0;
}
/**
* Does the string 'str' end with the string 'end'?
* @param str The string to check.
* @param end The string to look for
* @return true if 'str' ends with 'end'
*/
static bool endsWith(const std::string &str, const std::string &end)
{
if(&str != nullptr && &end != nullptr)
{
int sLen = str.length();
int eLen = end.length();
if(sLen >= eLen)
{
if(str.substr(sLen - eLen).compare(end) == 0)
{
return true;
}
}
}
return false;
}
/**
* Converts non-escaped characters to escape characters.
* @param str The string to convert.
* @param assumeEscapes Assume that backslashes may already be escaping characters.
* @return The converted string.
* @note If assumeEscapes is true the function will preserve current escape sequences
* for backslash and quote "\\"" will remain as "\\"" and "\\\\" as "\\\\".
* If it is false the backslash and quotes will be escaped "\\"" will become "\\\\\\""
* and "\\\\" will become "\\\\\\\\".
*/
static std::string escape(const std::string &str, bool assumeEscapes = false)
{
std::stringstream out;
int len = str.length();
for(int i = 0; i < len; i++)
{
char c = str[i];
switch(c)
{
case '\a': // 0x07
out << "\\a";
continue;
case '\b': // 0x08
out << "\\b";
continue;
case '\t': // 0x09
out << "\\t";
continue;
case '\n': // 0x0a
out << "\\n";
continue;
case '\v': // 0x0b
out << "\\v";
continue;
case '\f': // 0x0c
out << "\\f";
continue;
case '\r': // 0x0d
out << "\\r";
continue;
case '\"':
out << "\\\"";
continue;
case '\'':
out << "\\\'";
continue;
case '\\':
if(i < len - 1 && assumeEscapes)
{
// backslash or quote already escaped.
if(str[i + 1] == '\\' || str[i + 1] == '\"' || str[i + 1] == '\'')
{
i++;
out << c << str[i];
continue;
}
}
out << "\\\\";
continue;
default:
if(c <= 0x0F)
{
out << "\\u00" + toHex(c);
}
else
{
out << c;
}
continue;
}
}
return out.str();
}
/**
* Converts escaped characters to non-escape characters.
* @param str The string to convert.
* @return The converted string.
*/
static std::string unescape(const std::string &str)
{
std::stringstream out;
int len = str.length();
for(int i = 0; i < len; i++)
{
char c = str[i];
if(c != '\\')
{
// Not an escape sequence.
out << c;
continue;
}
// An escape sequence.
i++;
if(i >= len)
{
// Error: occured at end of line.
// Output and end.
out << c;
break;
}
c = str[i];
switch(c)
{
case 'a': // 0x07
out << "\a";
continue;
case 'b': // 0x08
out << "\b";
continue;
case 't': // 0x09
out << "\t";
continue;
case 'n': // 0x0a
out << "\n";
continue;
case 'v': // 0x0b
out << "\v";
continue;
case 'f': // 0x0c
out << "\f";
continue;
case 'r': // 0x0d
out << "\r";
continue;
case '\"':
out << "\"";
continue;
case '\'':
out << "\'";
continue;
case '\\':
out << "\\";
continue;
default:
// Unknown escape sequence, output as-is and continue.
if(c <= 0x0F)
{
out << "\\\\u00" + toHex(c);
}
else
{
out << "\\" << c;
}
continue;
}
}
return out.str();
}
/**
* Convert the string for use in an xml document.
* @param str The string to convert.
* @return The converted string.
*/
static std::string xmlEscape(const std::string &str)
{
std::stringstream out;
int len = str.length();
for(int i = 0; i < len; i++)
{
char c = str[i];
switch(c)
{
case '<':
out << "<";
continue;
case '>':
out << ">";
continue;
case '&':
out << "&";
continue;
case '\"':
out << """;
continue;
case '\'':
out << "'";
continue;
default:
out << c;
}
}
return out.str();
}
/**
* Convert the xml string to a normal string.
* @param str The string to convert.
* @return The converted string.
*/
static std::string xmlUnescape(const std::string &str)
{
std::stringstream out;
int len = str.length();
for(int i = 0; i < len; i++)
{
char c = str[i];
if(c != '&')
{
// Not an escape sequence.
out << c;
continue;
}
int j = i;
while(j < len && c != ';' && j - i <= 6)
{
c = str[++j];
}
if(c != ';')
{
// Unknown escape sequence, output & and continue.
out << "&";
continue;
}
std::string token = str.substr(i, (j - i) + 1);
token = strToLower(token);
if(token == "<")
{
i = j;
out << "<";
continue;
}
if(token == ">")
{
i = j;
out << ">";
continue;
}
if(token == """)
{
i = j;
out << "\"";
continue;
}
if(token == "&")
{
i = j;
out << "&";
continue;
}
if(token == "'")
{
i = j;
out << "\'";
continue;
}
// Unknown escape sequence, output & and continue.
out << "&";
}
return out.str();
}
};
}
#endif /* KSTRING_H */
| 31.833698 | 110 | 0.345615 | [
"transform"
] |
56b52aa1f09f348bd6a84deed9026b794b650564 | 3,566 | h | C | src/Filter/MinSpanTree.h | fermi-lat/TkrRecon | 9174a0ab1310038d3956ab4dcc26e06b8a845daf | [
"BSD-3-Clause"
] | null | null | null | src/Filter/MinSpanTree.h | fermi-lat/TkrRecon | 9174a0ab1310038d3956ab4dcc26e06b8a845daf | [
"BSD-3-Clause"
] | null | null | null | src/Filter/MinSpanTree.h | fermi-lat/TkrRecon | 9174a0ab1310038d3956ab4dcc26e06b8a845daf | [
"BSD-3-Clause"
] | null | null | null | /**
* @class MinSpanTree
*
* @brief This class implements a mininum spanning tree following Prim's Algorithm
*
* @author Tracy Usher
*
* $Header: /nfs/slac/g/glast/ground/cvs/TkrRecon/src/Filter/MinSpanTree.h,v 1.2 2011/01/04 22:37:26 usher Exp $
*/
#ifndef MinSpanTree_h
#define MinSpanTree_h
#include "IMSTObject.h"
#include "TkrUtil/ITkrGeometrySvc.h"
#include "src/Track/TkrControl.h"
class MinSpanTreeNode
{
public:
MinSpanTreeNode(const IMSTObject* point) :
m_point(point), m_parent(0), m_distToParent(100000.) {}
~MinSpanTreeNode() {}
void setParent(const IMSTObject* parent) {m_parent = parent;}
void setDistToParent(double distance) {m_distToParent = distance;}
const IMSTObject* getPoint() const {return m_point;}
const IMSTObject* getParent() const {return m_parent;}
const double getDistToParent() const {return m_distToParent;}
private:
const IMSTObject* m_point;
const IMSTObject* m_parent;
double m_distToParent;
};
// We will need to this to go from IMSTObjects to nodes
typedef std::map<const IMSTObject*, MinSpanTreeNode*> MSTObjectToNodeMap;
class MinSpanTreeNodeList : public std::list<MinSpanTreeNode*>
{
public:
MinSpanTreeNodeList() : m_distanceToParentGroup(0.), m_meanDistance(0.), m_rmsDistance(0.)
{}
~MinSpanTreeNodeList()
{
clear(); // Note that it is assumed that we are not the owner of the reference MinSpanTreeNodes
}
void setDistanceToParentGroup(double dist) {m_distanceToParentGroup = dist;}
void setMeanDistance(double meanDist) {m_meanDistance = meanDist;}
void setRmsDistance(double rmsDist) {m_rmsDistance = rmsDist;}
const double getDistanceToParentGroup() const {return m_distanceToParentGroup;}
const double getMeanDistance() const {return m_meanDistance;}
const double getRmsDistance() const {return m_rmsDistance;}
const int getNumPoints() const {return size();}
private:
double m_distanceToParentGroup;
double m_meanDistance;
double m_rmsDistance;
};
typedef std::list<MinSpanTreeNodeList > MinSpanTreeNodeLists;
typedef std::pair<int, MinSpanTreeNodeLists > MinSpanTreeNodeListsPair;
typedef std::map<int, MinSpanTreeNodeList > MinSpanTreeNodeListMap;
typedef std::map<int, MinSpanTreeNodeLists > MinSpanTreeNodeListsMap;
class MinSpanTree
{
public:
// Constructors
MinSpanTree(MSTObjectVec& mstObjectVec, const ITkrGeometrySvc* tkrGeo);
~MinSpanTree();
// Initialization of inputNodeList can be accessed externally for case of
// re-setting in the event of "isolated" nodes
void setInputNodeList(MSTObjectVec& mstObjectVec);
// Running of the Minimum Spanning Tree algorithm can also be externally accessed
int runPrimsAlgorithm();
// Give access to the results
const MinSpanTreeNodeList& getOutputNodeList() const {return m_outputNodeList;}
private:
/// Keep track of the input map
MSTObjectToObjectDistMap m_objToObjDistMap;
/// The original list of nodes
MinSpanTreeNodeList m_inputNodeList;
/// A mapping between IMSTObjects and MinSpanTreeNodes
MSTObjectToNodeMap m_objectToNodeMap;
/// The output list of nodes related by the MST
MinSpanTreeNodeList m_outputNodeList;
/// Keep track of all nodes owned by this object
MinSpanTreeNodeList m_ownedNodeList;
const ITkrGeometrySvc* m_tkrGeom;
TkrControl* m_control;
};
#endif
| 32.418182 | 112 | 0.714246 | [
"object"
] |
56b66f23cbd1ace33ed08234f4a56a9c9795dc7a | 1,255 | h | C | Source/Common/Foundation/MathSupport.h | pgrabas/MoonGlare | 25807680700697023d04830402af168f624ffb35 | [
"MIT"
] | 1 | 2018-03-18T16:29:16.000Z | 2018-03-18T16:29:16.000Z | Source/Common/Foundation/MathSupport.h | pgrabas/MoonGlare | 25807680700697023d04830402af168f624ffb35 | [
"MIT"
] | null | null | null | Source/Common/Foundation/MathSupport.h | pgrabas/MoonGlare | 25807680700697023d04830402af168f624ffb35 | [
"MIT"
] | null | null | null | #pragma once
#include <type_traits>
namespace math {
template<class T>
inline T clamp(T t, T tmin, T tmax) {
if (t > tmax) return tmax;
if (t < tmin) return tmin;
return t;
}
template<class VEC, class POS>
inline VEC LinearVectorMix(const VEC &v1, const VEC &v2, POS t) {
return v1 * t + v2 * (static_cast<POS>(1.0) - t);
}
/** Calculate plane normal from 3 points */
template<class VEC> inline VEC PlaneNormal(const VEC &p1, const VEC &p2, const VEC &p3) {
return PlaneNormalVectors(p2 - p1, p3 - p1);
}
/** Calculate plane normal from 2 points and vector */
template<class VEC> inline VEC PlaneNormalPointPointVector(const VEC &p1, const VEC &p2, const VEC &v1) {
return PlaneNormalVectors(p2 - p1, v1);
}
/** Calculate plane normal from 2 vectors */
template<class VEC> inline VEC PlaneNormalVectors(const VEC &v1, const VEC &v2) {
return v1.cross(v2);
}
template<class T>
inline T next_power2(T v) {
static_assert(std::is_integral_v<T>);
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
}
| 26.702128 | 109 | 0.557769 | [
"vector"
] |
56ba54fda9aa62be5ff781f3aac3d77ee5d38b0b | 2,644 | h | C | PIPS-NLP/Core/NlpGen/NlpGenStoch.h | jalving/PIPS | 62f664237447c7ce05a62552952c86003d90e68f | [
"BSD-3-Clause-LBNL"
] | 65 | 2016-02-04T18:03:39.000Z | 2022-03-24T08:59:38.000Z | PIPS-NLP/Core/NlpGen/NlpGenStoch.h | jalving/PIPS | 62f664237447c7ce05a62552952c86003d90e68f | [
"BSD-3-Clause-LBNL"
] | 34 | 2015-11-17T04:26:51.000Z | 2020-09-24T16:00:22.000Z | PIPS-NLP/Core/NlpGen/NlpGenStoch.h | jalving/PIPS | 62f664237447c7ce05a62552952c86003d90e68f | [
"BSD-3-Clause-LBNL"
] | 26 | 2015-10-15T20:27:52.000Z | 2021-07-14T08:13:34.000Z | /* PIPS-NLP *
* Authors: Nai-Yuan Chiang *
* (C) 2015 Argonne National Laboratory */
#ifndef SPSTOCHNLPGENFACTORY_NLP
#define SPSTOCHNLPGENFACTORY_NLP
#include "NlpGen.h"
#include "mpi.h"
class NlpGenData;
class NlpGenStochData;
class NlpGenVars;
class StochInputTree;
class StochTree;
class StochSymMatrix;
class NlpGenResiduals2;
class NlpGenStochVars;
class NlpGenStochLinsys;
class NlpGenStochLinsysRoot;
class NlpGenStochLinsysLeaf;
class NlpInfo;
#include "StochResourcesMonitor.h"
class NlpGenStoch : public NlpGen {
protected:
int m_blocks;
int nnzQ, nnzA, nnzC;
public:
NlpGenStoch( StochInputTree* );
protected:
NlpGenStoch( int nx_, int my_, int mz_, int nnzQ_, int nnzA_, int nnzC_ );
NlpGenStoch();
public:
virtual ~NlpGenStoch();
virtual Data * makeData();
virtual Data * makeDataMulti(){return NULL;};
virtual Data * makeData(NlpInfo * updateNlp);
virtual Residuals * makeResiduals( Data * prob_in );
virtual Variables * makeVariables( Data * prob_in );
virtual LinearSystem* makeLinsys( Data * prob_in );
virtual void joinRHS( OoqpVector& rhs_in, OoqpVector& rhs1_in,
OoqpVector& rhs2_in, OoqpVector& rhs3_in );
virtual void separateVars( OoqpVector& x_in, OoqpVector& y_in,
OoqpVector& z_in, OoqpVector& vars_in );
virtual void joinRHSXSYZ( OoqpVector& rhs_in, OoqpVector& rhs1_in,
OoqpVector& rhs2_in, OoqpVector& rhs3_in, OoqpVector& rhs4_in );
virtual void separateVarsXSYZ( OoqpVector& x_in, OoqpVector& s_in,
OoqpVector& y_in, OoqpVector& z_in, OoqpVector& vars_in);
virtual NlpGenStochLinsysRoot* newLinsysRoot() = 0;
virtual NlpGenStochLinsysRoot* newLinsysRoot(NlpGenStochData* prob,
OoqpVector* dd,OoqpVector* dq,
OoqpVector* nomegaInv, OoqpVector* rhs) = 0;
virtual NlpGenStochLinsysLeaf* newLinsysLeaf();
virtual NlpGenStochLinsysLeaf* newLinsysLeaf(NlpGenStochData* prob,
OoqpVector* dd,OoqpVector* dq,
OoqpVector* nomegaInv, OoqpVector* rhs);
StochTree* tree;
NlpGenStochData * data;
// Variables
virtual void iterateStarted();
virtual void iterateEnded();
NlpGenResiduals2 *resid;
std::vector<NlpGenStochVars*> registeredVars;
NlpGenStochLinsys* linsys;
NlpGenStochLinsys* linsys_2;
StochIterateResourcesMonitor iterTmMonitor;
double m_tmTotal;
std::string datarootname;
// int nxLOri_All, nxUOri_All,nsLOri_All,nsUOri_All;
};
#endif
| 25.180952 | 77 | 0.684191 | [
"vector"
] |
56d66a23384333a52526e8aa32626d55fb68c636 | 8,593 | h | C | Modules/LibDistrubutor/Distributor.h | alanzw/FGCG | 9819ff9c543cf52bfac16655d1d30417291b5d4c | [
"Apache-2.0"
] | 13 | 2016-10-24T11:39:12.000Z | 2021-04-11T13:24:05.000Z | Modules/LibDistrubutor/Distributor.h | zhangq49/sharerender | 9819ff9c543cf52bfac16655d1d30417291b5d4c | [
"Apache-2.0"
] | 1 | 2017-07-28T06:29:00.000Z | 2017-07-28T06:29:00.000Z | Modules/LibDistrubutor/Distributor.h | zhangq49/sharerender | 9819ff9c543cf52bfac16655d1d30417291b5d4c | [
"Apache-2.0"
] | 4 | 2018-06-05T03:39:06.000Z | 2020-06-06T04:44:20.000Z | #ifndef __DISTRIBUTOR_H__
#define __DISTRIBUTOR_H__
#define USE_LIBEVENT
#include <string>
#include <WinSock2.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#include <stdio.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/util.h>
#include <event2/listener.h>
#include <event2/keyvalq_struct.h>
#include <map>
#include <list>
#include "Context.h"
using namespace std;
#define MAX_BUFFER_SIZE 1024
#define MAX_CMD_LEN 50
#define MAX_RENDER_COUNT 4
#define OVERLOAD_THRESHOLD 95 // 95% usage is the overload bound
#define HEAVEYLOAD_THRESHOLD 80 // 80% usage is the heavy load bound
#define THREATLOAD_THRESHOLD 60
#define GREEN_THRESHOLD 30
/// define the port
#define DIS_PORT_CLIENT 8556 // game process to connect game loader
#define DIS_PORT_CTRL 8555 // for control connection
#define DIS_PORT_DOMAIN 8557 // dis server, logic server and render, user client to request games
#define DIS_PORT_GRAPHIC 60000 // graphic connection between logic and render
#define DIS_PORT_RTSP 8554 // rtsp connection between render and client
#define LOCAL_TEST
#ifdef LOCAL_TEST
#define LOGCAL_HOST "127.0.0.1"
#define DIS_URL_DISSERVER "127.0.0.1"
#define DIS_URL_LOGIC "127.0.0.1"
#define DIS_URL_RENDER "127.0.01"
#else // LOCAL_TEST
#define LOGCAL_HOST "192.168.1.100"
#define DIS_URL_DISSERVER "192.168.1.100"
#define DIS_URL_LOGIC "192.168.1.100"
#define DIS_URL_RENDER "192.168.1.100"
#endif // LOCAL_TEST
// for regulation, define the regulation threshold
#define REGULATION_THRESHOLD 10
// enable use best-fit strategy, default is worst fit
//#define SCHEDULE_USE_BEST_FIT
#ifndef chBEGINTHREADEX
#include <process.h>
typedef unsigned(__stdcall * PTHREAD_START)(void *);
#define chBEGINTHREADEX(psa, cbStack, pfnStartAddr, \
pvParam, fdwCreate, pdwThreadID) \
((HANDLE)_beginthreadex(\
(void *)(psa), \
(unsigned)(cbStack), \
(PTHREAD_START)(pfnStartAddr), \
(void *)(pvParam), \
(unsigned)(fdwCreate), \
(unsigned *)(pdwThreadID)))
#endif
#ifndef EVUTIL_ERR_CONNECT_RETRIABLE
#define EVUTIL_ERR_CONNECT_RETRIABLE(e) \
((e) == WSAEWOULDBLOCK || \
(e) == WSAEINTR || \
(e) == WSAEINPROGRESS || \
(e) == WSAEINVAL)
#endif
namespace cg{
///////////////////////// command to deal for each side /////////////////////
////////////// cmd for dis server//////////////////
extern const char * INFO; // recv info from domains
extern const char * REGISTER; /// recv register cmd from domains
extern const char * REQ_GAME; // recv game request from client
extern const char * RENDER_OVERLOAD; // recv render overload cmd from render proxy
extern const char * LOGIC_OVERLOAD; // recv logic server overload cmd from logic server
extern const char * CLIENT_EXIT; // recv client exit cmd from client or render proxy
extern const char * LOGIC_READY; //recv logic ready cmd from logic server, means that the game is started
extern const char * RENDER_READY; // recv render ready cmd from render server, means that the render thread is started
extern const char * RENDER_CONTEXT_READY; // when complete the context synchronize in the logic server
extern const char * RTSP_READY;
extern const char * RTSP_READY; // rtsp service ready from logic server or render
extern const char * ADD_RTSP_CONNECTION;
extern const char * OPTION; // the option cmd
extern const char * START_TASK;
extern const char * START_GAME; // only game server and render, render send start game to request the game
extern const char * CANCEL_TASK;
////////////// const string for DATA ////////////////
extern const char * LOGIC; // dis server get the data with REGISTER
extern const char * RENDER; // dis server get the data with REGISTER
extern const char * CLIENT; // dis server may get the data with REGISTER, not sure
//////////// const string for client///////////////
extern const char * ADD_RENDER; // recv add render cmd from dis
extern const char * DECLINE_RENDER; // recv decline render cmd from dis
extern const char * ADD_LOGIC; // add the logic domain to receive control
extern const char * CLIENT_CONNECTED;
class DisServer{
bool watchdoaRunning;
int collectionInterval; // interval to collect information
char * disServerUrl;
// all maps for ctx, domain and task
//map<evutil_socket_t, BaseContext *> ctxMap;
map<evutil_socket_t, DomainInfo *> domainMap;
map<IDENTIFIER, TaskInfo *> taskMap;
map<evutil_socket_t, DomainInfo *> logicMap;
map<evutil_socket_t, DomainInfo *> renderMap;
map<evutil_socket_t, DomainInfo *> clientMap;
list<DomainInfo *> lightWeightLogic;
list<DomainInfo *> heavyLoadLogic;
list<DomainInfo *> overloadLogic;
list<DomainInfo *> lightweightRender;
list<DomainInfo *> heavyLoadRender;
list<DomainInfo *> overloadRender;
DisServer();
event_base * base;
HANDLE mutex;
// timer
struct event *clockEvent;
static DisServer * server;
// for the domains
static short offsetBase;
DomainInfo * getLogicCandidate(float cpuRe, float gpure);
DomainInfo * getRenderCandidate(float cpuRe, float gpuRe);
bool sendCmdToRender(TaskInfo * task, char * cmddata, int len);
bool sendCmdToRender(TaskInfo * task, const char * cmd);
// base function for render
bool migrateRendering(DomainInfo * src, DomainInfo * dst, TaskInfo * task);
bool addRender(TaskInfo * task, DomainInfo * dstRender);
// solve the overload of the domains
bool solveRenderOverload(DomainInfo * render);
bool solveLogicOverload(DomainInfo * logic);
// send cmd to logic of the task to decline older render
bool cancelRender(TaskInfo * task, DomainInfo * oldRender);
bool cancelRender(TaskInfo * task, IDENTIFIER oldRenderId);
// send cmd to new render add logic
bool mergeRender(DomainInfo * render);
bool mergeLogic(DomainInfo * logic);
// schedule when a domain updated
bool scheduleWhenUpdate(DomainInfo * domain);
// build the task for game request
TaskInfo * buildTask(string taskName, DomainInfo * client);
// dispatch new task to logic and renders
bool dispatchToLogic(TaskInfo * task);
public:
inline void setDisUrl(char * url){
int len = strlen(url);
disServerUrl = (char *)malloc(sizeof(char) * len + 10);
strcpy(disServerUrl, url);
}
inline char * getServerUrl(){ return disServerUrl;}
inline void lock(){
WaitForSingleObject(mutex, INFINITE);
}
inline void unlock(){
ReleaseMutex(mutex);
}
virtual ~DisServer();
inline void setEventBase(event_base * _b){
base = _b;
}
inline void dispatch(){
event_base_dispatch(base);
}
static DisServer * GetDisServer(){
if (server){
return server;
}
server = new DisServer();
return server;
}
bool dealEvent(DomainInfo * ctx);
void startWatchdog();
void collectInfo();
bool isWatchdogRunning(){ return watchdoaRunning; }
int getSleepInterval(){ return collectionInterval; }
bool ableToMigrate();
void printDomain();
void printTask();
// helper API
void AddRenderToTask(IDENTIFIER id);
void ChangeOffloadLevel(IDENTIFIER id, TASK_MODE taskMode = MODE_FULL_OFFLOAD);
void ChangeEncoderType(IDENTIFIER taskId, IDENTIFIER domainId);
bool sendCmdToRender(TaskInfo * task, const char * cmd, DomainInfo * render);
};
// this client is for logic and render
class DisClient{
evutil_socket_t sock; // the connection socket
struct evconnlistener * connlistener;
public:
BaseContext * ctx;
event_base * base;
bool connectToServer(char * ip, short port); // connect to dis server
void collectInfo(float & cpuUsage, float & gpuUsage, float & memUsage);
inline void setEventBase(event_base * b){ base = b; }
inline BaseContext * getCtx(){ return ctx; }
inline void dispatch(){
printf("[DisClient]: dispatch.\n");
event_base_dispatch(base);
}
virtual bool dealEvent(BaseContext * ctx);
virtual bool start(); // start the dis client
//virtual bool listenRTSP(); // wait for rtsp connection
virtual ~DisClient(){}
DisClient(){
ctx = NULL;
base = NULL;
sock = NULL;
connlistener = NULL;
}
// for rtsp
bool listenRTSP(short portOffset);
virtual bool startRTSP(evutil_socket_t sock){
printf("[DisStartRTSP]:\n");
return true;
}
inline event_base * getBase(){ return base; }
};
extern BaseContext * ctxToDis;
void frobSocket(evutil_socket_t sock);
void DisClientReadCB(struct bufferevent * bev, void * arg);
void DisClientEventCB(struct bufferevent * bev, short what, void * arg);
void DisClientWriteCB(struct bufferevent * bev, void * arg);
}
#endif | 31.591912 | 119 | 0.723379 | [
"render"
] |
56d9e1753af9f741b1b1221c61fddcebb53b65cf | 1,593 | h | C | Object Oriented Programming (C++)/Lab Works/Ask4/VideoGame.h | Lefti97/UniversityWorks | 8c8c01a98ad0ceaf414d2f9c9c3a981b5d88bc5b | [
"MIT"
] | 3 | 2021-08-19T13:30:32.000Z | 2022-01-16T19:42:53.000Z | Object Oriented Programming (C++)/Lab Works/Ask4/VideoGame.h | Lefti97/UniversityWorks | 8c8c01a98ad0ceaf414d2f9c9c3a981b5d88bc5b | [
"MIT"
] | null | null | null | Object Oriented Programming (C++)/Lab Works/Ask4/VideoGame.h | Lefti97/UniversityWorks | 8c8c01a98ad0ceaf414d2f9c9c3a981b5d88bc5b | [
"MIT"
] | null | null | null | #ifndef VideoGame_h
#define VideoGame_h
#include <iostream>
#include <string>
#include <vector>
#include "Application.h"
class VideoGame : public Application
{
private:
bool online;
std::string category;
public:
VideoGame(const char *idF="-", std::string nameF="-", unsigned int versionF=0,
float priceF=0, bool onlineF=false, std::string categoryF="-",
AppManufacturer manF=AppManufacturer(),
std::vector<class UserEvaluation> evaluationsF=std::vector<class UserEvaluation>())
{
setId(idF);
setName(nameF);
setVersion(versionF);
setPrice(priceF);
setMan(manF);
setEvaluations(evaluationsF);
online = onlineF;
category = categoryF;
}
virtual void printData()
{
std::cout << "ID: " << getId() << "\tName: " << getName() << std::endl;
std::cout << "Version: " << getVersion() << "\tPrice: " << getPrice() << std::endl;
std::cout << "Online: " << online << "\tCategory: " << category << std::endl;
std::cout << "Manufacturer Info:" << std::endl;
getMan().printData();
std::cout << "User Evaluations:" << std::endl;
for(int i=0; i<getEvaluations().size(); i++)
{
std::cout << i+1 << ":";
getEvaluations().at(i).printData();
}
}
virtual bool getOnline(){return online;}
virtual std::string getCategory(){return category;}
virtual void setOnline(bool onlineF){online = onlineF;}
virtual void setCategory(std::string categoryF){category = categoryF;}
};
#endif | 31.235294 | 91 | 0.591965 | [
"vector"
] |
56fd2813499080a9050e29e2f5553bc439e9264e | 1,326 | h | C | include/cbpro++/marketdata/products.h | Phantim97/cbpro-cpp | 44428f1f9aea1c84307a9bfd3d86e95ae36cc332 | [
"Apache-2.0"
] | 18 | 2021-02-25T01:38:25.000Z | 2022-01-27T19:08:23.000Z | include/cbpro++/marketdata/products.h | Phantim97/cbpro-cpp | 44428f1f9aea1c84307a9bfd3d86e95ae36cc332 | [
"Apache-2.0"
] | null | null | null | include/cbpro++/marketdata/products.h | Phantim97/cbpro-cpp | 44428f1f9aea1c84307a9bfd3d86e95ae36cc332 | [
"Apache-2.0"
] | 4 | 2021-04-02T21:34:37.000Z | 2021-09-09T06:25:02.000Z | //
// Created by Bradley Bottomlee on 1/19/21.
//
#ifndef CBPRO_PRODUCTS_H
#define CBPRO_PRODUCTS_H
#include <cbpro++/marketdata/product.h>
#include <cbpro++/marketdata/book.h>
#include <cbpro++/marketdata/ticker.h>
#include <cbpro++/marketdata/trade.h>
#include <cbpro++/marketdata/stats.h>
#include <cbpro++/auth.h>
#include <utility>
#include <unordered_map>
namespace marketdata {
namespace products {
std::vector<responses::product> getProducts(Auth &auth);
responses::product getProduct(Auth &auth, const std::string &productId);
responses::ticker getTicker(Auth &auth, const std::string &productId);
responses::stats getStats(Auth &auth, const std::string &productId);
std::vector<responses::trade> getTrades(Auth &auth, const std::string &productId);
responses::book<responses::bidLevel1_2, responses::askLevel1_2>
getOrderBookLevelOne(Auth &auth, const std::string &productId);
responses::book<responses::bidLevel1_2, responses::askLevel1_2>
getOrderBookLevelTwo(Auth &auth, const std::string &productId);
responses::book<responses::bidLevel3, responses::askLevel3>
getOrderBookLevelThree(Auth &auth, const std::string &productId);
} // namespace products
} // namespace marketdata
#endif //CBPRO_PRODUCTS_H
| 30.837209 | 90 | 0.711916 | [
"vector"
] |
710a5f5781e3137fa81c17f273cdf19b6c8f734a | 1,156 | h | C | view/ingredientpage.h | lcala99/MakeIThome | dc8767391bb64c96e5374670d7ceb494050b081b | [
"MIT"
] | null | null | null | view/ingredientpage.h | lcala99/MakeIThome | dc8767391bb64c96e5374670d7ceb494050b081b | [
"MIT"
] | null | null | null | view/ingredientpage.h | lcala99/MakeIThome | dc8767391bb64c96e5374670d7ceb494050b081b | [
"MIT"
] | null | null | null | #ifndef INGREDIENTPAGE_H
#define INGREDIENTPAGE_H
#include "view/header.h"
#include "model/vettore.h"
#include "model/ingrediente.h"
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLayout>
#include <QAction>
#include <QMenu>
#include <QMenuBar>
#include <QFrame>
#include <QScrollArea>
#include <QScrollBar>
#include <QLabel>
#include <QListView>
#include <QLineEdit>
#include <QWidgetAction>
#include <QFormLayout>
#include <QListWidget>
#include <QListWidgetItem>
#include <QString>
#include <iostream>
#include <QTabWidget>
#include <QSpinBox>
#include <QSizePolicy>
class IngredientPage : public QWidget {
Q_OBJECT
private:
QVBoxLayout* mainLayout;
QPushButton* back;
QPushButton* switchToCarrello;
QLabel* quantity;
Vettore<Ingrediente> ingr;
QListWidget* cart;
public:
explicit IngredientPage(QWidget* parent, const Vettore<Ingrediente>& list);
void setLista(Vettore<Ingrediente>);
void addList();
signals:
void toHomePage();
void toCarrelloPage();
public slots:
void showHomePage();
void showCarrelloPage();
};
#endif // INGREDIENTPAGE_H
| 21.407407 | 79 | 0.740484 | [
"model"
] |
710abbeaa379112f7ef3ccb240186f5e60b0a2b1 | 2,403 | h | C | TurboX-Engine/TurboX-Engine/Application.h | moon-funding/TurboX-Engine | 0ebcc94f0c93fa0a5d1f88f8f46e90df28b5c8a6 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | TurboX-Engine/TurboX-Engine/Application.h | moon-funding/TurboX-Engine | 0ebcc94f0c93fa0a5d1f88f8f46e90df28b5c8a6 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | TurboX-Engine/TurboX-Engine/Application.h | moon-funding/TurboX-Engine | 0ebcc94f0c93fa0a5d1f88f8f46e90df28b5c8a6 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | #ifndef __APPLICATION_H__
#define __APPLICATION_H__
#include "Globals.h"
#include "Timer.h"
#include "./JSON/parson.h"
#include "ImGuizmo/ImGuizmo.h"
#include <vector>
#include <list>
#include <string>
struct Event
{
enum EventType
{
scene_file_dropped,
texture_file_dropped,
input,
active_Vsync,
invalid
} type;
union
{
const char* string;
struct {
int x, y;
} point2d;
};
Event(EventType type) : type(type)
{}
Event() {};
};
class Module;
class ModuleFileSystem;
class ModuleWindow;
class ModuleInput;
class ModuleAudio;
class ModuleScene;
class ModuleEditor;
class ModuleRenderer3D;
class ModuleCamera3D;
class ModulePhysics3D;
class ModuleGui;
class ModuleScene;
class ModuleConsole;
class SceneImporter;
class ModuleTimeManagement;
class ModuleResources;
class TextureImporter;
class Application
{
public:
ModuleFileSystem* file_system = NULL;
ModuleWindow* window = NULL;
ModuleInput* input = NULL;
ModuleAudio* audio = NULL;
ModuleEditor* editor = NULL;
ModuleRenderer3D* renderer3D = NULL;
ModuleCamera3D* camera = NULL;
ModulePhysics3D* physics = NULL;
ModuleGui* gui = NULL;
ModuleScene* scene = NULL;
ModuleConsole* console = NULL;
SceneImporter* scene_loader = NULL;
ModuleTimeManagement* timeManagement = NULL;
ModuleResources* resources = NULL;
TextureImporter* texture_importer = NULL;
private:
float time_scale = 1.0f;
float prevTime_scale = 1.f;
int time_scaleFrames = -1;
Timer ms_timer;
float dt;
std::vector<Module*> modules_list;
public:
Application();
~Application();
bool Init();
update_status Update();
bool CleanUp();
void CloseApp();
void LoadEngine();
void SaveEngine();
bool LoadEngineNow();
bool SaveEngineNow() const;
void SetEngineName(const char* newName);
const char* GetEngineName() const;
void SetOrganizationName(const char* newName);
const char* GetOrganizationName() const;
void SetEngineVersion(double newVersion);
double GetEngineVersion() const;
const float GetTimeScale()const;
void SetTimeScale(float ts, int frameNumber = -1);
void PauseGame(bool pause);
private:
void AddModule(Module* mod);
void PrepareUpdate();
void FinishUpdate();
bool closeApp = false;
private:
mutable bool want_to_save;
bool want_to_load;
std::string engine_name;
std::string organization_name;
double current_version;
};
extern Application* App;
#endif //__APPLICATION_H__ | 18.773438 | 51 | 0.748231 | [
"vector"
] |
710ccefd82225ebaa97890b35958e90ce36bb977 | 154 | h | C | code/code/Platform.h | WarzesProject/0003_LostIslands | a349228ace5646726a12ef4d394c5388c0b80e44 | [
"MIT"
] | null | null | null | code/code/Platform.h | WarzesProject/0003_LostIslands | a349228ace5646726a12ef4d394c5388c0b80e44 | [
"MIT"
] | null | null | null | code/code/Platform.h | WarzesProject/0003_LostIslands | a349228ace5646726a12ef4d394c5388c0b80e44 | [
"MIT"
] | null | null | null | #pragma once
std::wstring FixPathSeparators(std::wstring name);
std::vector<uint8_t> ReadFile(std::wstring name);
std::wstring GetClipboardContents(); | 22 | 50 | 0.772727 | [
"vector"
] |
710f4f7ec9c56e2accbb404a8c1ca615b43081f0 | 11,002 | h | C | paginglandscape/Samples/Common/include/PagingLandScape2Application.h | chen0040/cpp-ogre-mllab | b85305cd7e95559a178664577c8e858a5b9dd05b | [
"MIT"
] | 1 | 2021-10-04T09:40:26.000Z | 2021-10-04T09:40:26.000Z | paginglandscape/Samples/Common/include/PagingLandScape2Application.h | chen0040/cpp-ogre-mllab | b85305cd7e95559a178664577c8e858a5b9dd05b | [
"MIT"
] | null | null | null | paginglandscape/Samples/Common/include/PagingLandScape2Application.h | chen0040/cpp-ogre-mllab | b85305cd7e95559a178664577c8e858a5b9dd05b | [
"MIT"
] | 6 | 2019-05-05T22:29:55.000Z | 2022-01-03T14:18:54.000Z |
/**
@file
LandScape.h
@brief
Specialisation of OGRE's framework application to show the
LandScape rendering plugin
*/
#ifndef PagingLandScapeApplication_H
#define PagingLandScapeApplication_H
#include "ExampleApplication.h"
#include "OgreStringConverter.h"
#include "OgreSphere.h"
#include "OgrePanelOverlayElement.h"
using namespace Ogre;
#include "OgrePagingLandScapeRaySceneQuery.h"
#include "OgrePagingLandScapeListenerManager.h"
#include "PagingLandScape2Terrainlistener.h"
#include "PagingLandScape2Overlay.h"
#include "PagingLandScape2FrameListener.h"
class PagingLandScapeApplication : public ExampleApplication
{
public:
//-----------------------------------------------------------------------
PagingLandScapeApplication()
{
mPagingFrameListener = 0;
}
//-----------------------------------------------------------------------
~PagingLandScapeApplication()
{
if (mPagingFrameListener)
delete mPagingFrameListener;
}
protected:
// These internal methods package up the stages in the startup process
/** Sets up the application - returns false if the user chooses to abandon configuration. */
virtual bool setup(void)
{
mRoot = new Root("plugins.cfg", "plsm2_display.cfg", "plsm2.log");
// Linux plugin is created as Plugin_PagingLandScape2.so and set up to run
// via the plugins.cfg config file
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#ifdef _DEBUG
Root::getSingleton().loadPlugin("Plugin_PagingLandScapeSceneManager2_d");
#else
Root::getSingleton().loadPlugin("Plugin_PagingLandScapeSceneManager2");
#endif
#endif
setupResources();
bool carryOn = configure();
if (!carryOn) return false;
chooseSceneManager();
createCamera();
createViewports();
// Set default mipmap level (NB some APIs ignore this)
TextureManager::getSingleton().setDefaultNumMipmaps(20);
// Create any resource listeners (for loading screens)
createResourceListener();
// Load resources
loadResources();
// Create the scene
createScene();
createFrameListener();
return true;
}
/// Method which will define the source of resources (other than current folder)
void setupResources(void)
{
// Load resource paths from config file
ConfigFile cf;
cf.load("resources.cfg");
// Go through all sections & settings in the file
ConfigFile::SectionIterator seci = cf.getSectionIterator();
String secName, typeName, archName;
while (seci.hasMoreElements())
{
secName = seci.peekNextKey();
ConfigFile::SettingsMultiMap *settings = seci.getNext();
ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i)
{
typeName = i->first;
archName = i->second;
ResourceGroupManager::getSingleton().addResourceLocation(
archName, typeName, secName);
}
}
// if folders aren't in the resources.cfg try some others as well
ResourceGroupManager *rsm = ResourceGroupManager::getSingletonPtr();
StringVector groups = rsm->getResourceGroups();
if (std::find(groups.begin(), groups.end(), String("PLSM2")) == groups.end())
{
FileInfoListPtr finfo = ResourceGroupManager::getSingleton().findResourceFileInfo (
"Bootstrap", "axes.mesh");
const bool isSDK = (!finfo->empty()) &&
StringUtil::startsWith (finfo->begin()->archive->getName(), "../../media/packs/ogrecore.zip", true);
rsm->createResourceGroup("PLSM2");
if (isSDK)
{
rsm->addResourceLocation("../../../paginglandscape/Samples/Media/paginglandscape2","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../paginglandscape/Samples/Media/paginglandscape2/models","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../paginglandscape/Samples/Media/paginglandscape2/overlays","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../paginglandscape/Samples/Media/paginglandscape2/materials","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../paginglandscape/Samples/Media/paginglandscape2/materials/scripts","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../paginglandscape/Samples/Media/paginglandscape2/materials/textures","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../paginglandscape/Samples/Media/paginglandscape2/materials/programs","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../paginglandscape/Samples/Media/paginglandscape2/datasrcs","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../paginglandscape/Samples/Media/paginglandscape2/terrains","FileSystem", "PLSM2");
}
else
{
rsm->addResourceLocation("../../../../../ogreaddons/paginglandscape/Samples/Media/paginglandscape2","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../../../ogreaddons/paginglandscape/Samples/Media/paginglandscape2/models","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../../../ogreaddons/paginglandscape/Samples/Media/paginglandscape2/overlays","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../../../ogreaddons/paginglandscape/Samples/Media/paginglandscape2/materials","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../../../ogreaddons/paginglandscape/Samples/Media/paginglandscape2/materials/scripts","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../../../ogreaddons/paginglandscape/Samples/Media/paginglandscape2/materials/textures","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../../../ogreaddons/paginglandscape/Samples/Media/paginglandscape2/materials/programs","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../../../ogreaddons/paginglandscape/Samples/Media/paginglandscape2/datasrcs","FileSystem", "PLSM2");
rsm->addResourceLocation("../../../../../ogreaddons/paginglandscape/Samples/Media/paginglandscape2/terrains","FileSystem", "PLSM2");
}
}
}
//-----------------------------------------------------------------------
virtual void createFrameListener(void)
{
mPagingFrameListener= new PagingLandScapeFrameListener(mWindow,
mCamera, false, true);
mRoot->addFrameListener(mPagingFrameListener);
}
//-----------------------------------------------------------------------
virtual void chooseSceneManager(void)
{
bool notFound = true;
// Get the SceneManager, in this case the Paging LandScape specialization
SceneManagerEnumerator::MetaDataIterator it = mRoot->getSceneManagerMetaDataIterator();
while (it.hasMoreElements ())
{
const SceneManagerMetaData* metaData = it.getNext ();
/// A mask describing which sorts of scenes this manager can handle
if (metaData->sceneTypeMask == ST_EXTERIOR_REAL_FAR &&
metaData->worldGeometrySupported == true &&
metaData->typeName == "PagingLandScapeSceneManager")
{
notFound = false;
break;
}
}
if (notFound)
{
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Could not find Paging Landscape plugin. Check if it's in plugins.cfg.",
"chooseSceneManager");
}
mSceneMgr = mRoot->createSceneManager("PagingLandScapeSceneManager", "PagingLandScapeDemo" );
}
//-----------------------------------------------------------------------
virtual void createCamera(void)
{
// Create the camera
mCamera = mSceneMgr->createCamera( "PlayerCam" );
Vector3 pos(128,25,128);
//Vector3 pos(3085, 0, 3085);
mCamera->lookAt( pos );
// Place the camera a little over the terrain
pos.y += 38700;
// Position it at 500 in Z direction
mCamera->setPosition( pos );
mCamera->setNearClipDistance(5);
}
//-----------------------------------------------------------------------
virtual void createViewports(void)
{
// Create one viewport, entire window
Viewport* vp = mWindow->addViewport(mCamera);
vp->setBackgroundColour(ColourValue::Blue);
mCamera->setAspectRatio(
(Real)vp->getActualWidth() / vp->getActualHeight());
}
//-----------------------------------------------------------------------
/// Optional override method where you can perform resource group loading
/// Must at least do ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
virtual void loadResources(void)
{
// Initialise, parse scripts etc
//ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
ResourceGroupManager::getSingleton().initialiseResourceGroup(ResourceGroupManager::BOOTSTRAP_RESOURCE_GROUP_NAME);
ResourceGroupManager::getSingleton().initialiseResourceGroup("General");
ResourceGroupManager::getSingleton().initialiseResourceGroup("PLSM2");
}
//-----------------------------------------------------------------------
// Just override the mandatory create scene method
void createScene(void)
{
mSceneMgr->setWorldGeometry( Ogre::String("paginglandscape2.cfg") );
// Set ambient light
mSceneMgr->setAmbientLight( ColourValue (0.7f, 0.7f, 0.7f));//g_DayColor );
//lights
Vector3 LightPos(0.0f, 0.0f, 0.0f);
mLight = mSceneMgr->createLight("MainLight");
mLight->setPosition(LightPos);
mLight->setDiffuseColour(0.93f, 0.93f, 0.93f);
mLight->setAttenuation(10000.0f, 1.0f, 1.0f, 0.0f);
mLight->setType (Light::LT_DIRECTIONAL);
mLight->setDirection (Vector3( -1, -1, 0 ));
SceneNode *BaseNode = mSceneMgr->getRootSceneNode()->createChildSceneNode ("LightHandler");
BaseNode->setPosition (-3500.0f, 0.0f, -2600.0f);
mLightNode = BaseNode->createChildSceneNode ("LightHandlerSon");
mLightNode->setPosition (0.0f, 15000.0f, 0.0f);
mLightNode->attachObject (mLight);
BillboardSet* LightSet = mSceneMgr->createBillboardSet("RedYellowLights");
LightSet->setMaterialName("Examples/Flare");
mLightNode->attachObject(LightSet);
Billboard* LightBoard = LightSet->createBillboard(LightPos);
//LightBoard->setDimensions(10.0f, 10.0f);
LightBoard->setColour(ColourValue(1.0f, 1.0f, 0.2f, 1.0f));
}
protected:
Light* mLight;
SceneNode* mLightNode;
PagingLandScapeFrameListener* mPagingFrameListener;
};
#endif
| 40.300366 | 162 | 0.614888 | [
"mesh"
] |
711277ee95eda8c51eb9620274a691c9b54e0a9c | 4,309 | h | C | libraries/trainers/include/ThresholdFinder.h | awf/ELL | 25c94a1422efc41d5560db11b136f9d8f957ad41 | [
"MIT"
] | 2,094 | 2016-09-28T05:55:24.000Z | 2019-05-04T19:06:36.000Z | libraries/trainers/include/ThresholdFinder.h | awesomemachinelearning/ELL | cb897e3aec148a1e9bd648012b5f53ab9d0dd20c | [
"MIT"
] | 213 | 2017-06-30T12:53:40.000Z | 2019-05-03T06:35:38.000Z | libraries/trainers/include/ThresholdFinder.h | awesomemachinelearning/ELL | cb897e3aec148a1e9bd648012b5f53ab9d0dd20c | [
"MIT"
] | 301 | 2017-03-24T08:40:00.000Z | 2019-05-02T21:22:28.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: ThresholdFinder.h (trainers)
// Authors: Ofer Dekel
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <data/include/Dataset.h>
#include <predictors/include/SingleElementThresholdPredictor.h>
#include <algorithm>
#include <vector>
namespace ell
{
namespace trainers
{
/// <summary> Base class for threshold predictor finders. </summary>
class ThresholdFinder
{
protected:
using DataVectorType = predictors::SingleElementThresholdPredictor::DataVectorType;
struct ValueWeight
{
double value;
double weight;
operator double() { return value; }
};
// the result of a call to UniqueValues
struct UniqueValuesResult
{
std::vector<std::vector<ThresholdFinder::ValueWeight>> weightedValues;
double totalWeight;
};
// Gets a vector of sorted unique values from each feature, with counts
template <typename ExampleIteratorType>
UniqueValuesResult UniqueValues(ExampleIteratorType exampleIterator) const;
private:
size_t SortReduceCopy(std::vector<ValueWeight>::iterator begin, const std::vector<ValueWeight>::iterator end) const;
};
/// <summary> A threshold finder that finds all possible thresholds. </summary>
class ExhaustiveThresholdFinder : public ThresholdFinder
{
public:
/// <summary> Returns a vector of SingleElementThresholdPredictor. </summary>
///
/// <typeparam name="ExampleIteratorType"> Type of example iterator. </typeparam>
/// <param name="exampleIterator"> The example iterator. </param>
///
/// <returns> The thresholds. </returns>
template <typename ExampleIteratorType>
std::vector<predictors::SingleElementThresholdPredictor> GetThresholds(ExampleIteratorType exampleIterator) const;
};
} // namespace trainers
} // namespace ell
#pragma region implementation
namespace ell
{
namespace trainers
{
template <typename ExampleIteratorType>
ThresholdFinder::UniqueValuesResult ThresholdFinder::UniqueValues(ExampleIteratorType exampleIterator) const
{
std::vector<std::vector<ValueWeight>> result;
double totalWeight = 0.0;
// invert and densify result
while (exampleIterator.IsValid())
{
const auto& example = exampleIterator.Get();
const auto& denseDataVector = example.GetDataVector();
double weight = example.GetMetadata().weak.weight;
totalWeight += weight;
if (result.size() < denseDataVector.PrefixLength())
{
result.resize(denseDataVector.PrefixLength());
}
for (size_t j = 0; j < denseDataVector.PrefixLength(); ++j)
{
result[j].push_back({ denseDataVector[j], weight });
}
exampleIterator.Next();
}
// sort and unique each feature
for (size_t j = 0; j < result.size(); ++j)
{
auto newSize = SortReduceCopy(result[j].begin(), result[j].end());
result[j].resize(newSize);
}
return { result, totalWeight };
}
template <typename ExampleIteratorType>
std::vector<predictors::SingleElementThresholdPredictor> trainers::ExhaustiveThresholdFinder::GetThresholds(ExampleIteratorType exampleIterator) const
{
auto uniqueValuesResult = UniqueValues(exampleIterator);
std::vector<predictors::SingleElementThresholdPredictor> thresholdPredictors;
for (size_t j = 0; j < uniqueValuesResult.weightedValues.size(); ++j)
{
const auto& featureValues = uniqueValuesResult.weightedValues[j];
for (size_t i = 0; i < featureValues.size() - 1; ++i)
{
thresholdPredictors.push_back({ j, 0.5 * (featureValues[i].value + featureValues[i + 1].value) });
}
}
return thresholdPredictors;
}
} // namespace trainers
} // namespace ell
#pragma endregion implementation
| 32.643939 | 154 | 0.610583 | [
"vector"
] |
7123f548d4dd4005bb917a86137c7c098d8e0aad | 1,100 | h | C | include/fieldtrack/DimensionParser.h | Humhu/fieldtrack | 78f787e08c14ebbb102efbfb7bf1cffcb81fb099 | [
"AFL-3.0"
] | 1 | 2021-06-15T09:32:18.000Z | 2021-06-15T09:32:18.000Z | include/fieldtrack/DimensionParser.h | Humhu/fieldtrack | 78f787e08c14ebbb102efbfb7bf1cffcb81fb099 | [
"AFL-3.0"
] | null | null | null | include/fieldtrack/DimensionParser.h | Humhu/fieldtrack | 78f787e08c14ebbb102efbfb7bf1cffcb81fb099 | [
"AFL-3.0"
] | 1 | 2018-01-24T18:42:35.000Z | 2018-01-24T18:42:35.000Z | #include <string>
#include <vector>
#include "argus_utils/utils/LinalgTypes.h"
namespace argus
{
MatrixType promote_3d_matrix( bool twoDimensional, unsigned int order );
/*! \brief Parses strings of the format [type]_[dim]_[order] to indices
* for a filter. Assumes order 0 corresponds to pose, 1 to velocity, etc.
*
* Parameter minOrder is subtracted from the specified order to allow
* offsetting, ie. for a velocity-only filter, minOrder = 1
*/
unsigned int parse_dim_string( const std::string& s,
bool twoDimensional,
unsigned int maxOrder,
unsigned int minOrder = 0 );
/*! \brief Convenience method for parsing containers of strings. */
// TODO Upgrade to a template-template to take different containers...
std::vector<unsigned int> parse_dim_string( const std::vector<std::string>& s,
bool twoDimensional,
unsigned int maxOrder,
unsigned int minOrder = 0 );
} | 40.740741 | 78 | 0.603636 | [
"vector"
] |
71296fe9035171fd311f92244c33373e4b776da8 | 760 | h | C | apps/vanilla/core/Object.h | torrvision/straighttoshapes | 59739d8020d176dddc759e4122d0c1d4f5179f31 | [
"RSA-MD"
] | 36 | 2017-01-28T07:16:58.000Z | 2021-05-06T14:30:39.000Z | apps/vanilla/core/Object.h | torrvision/straighttoshapes | 59739d8020d176dddc759e4122d0c1d4f5179f31 | [
"RSA-MD"
] | 1 | 2019-04-12T12:27:02.000Z | 2019-04-12T12:27:02.000Z | apps/vanilla/core/Object.h | torrvision/straighttoshapes | 59739d8020d176dddc759e4122d0c1d4f5179f31 | [
"RSA-MD"
] | 11 | 2017-01-21T13:24:05.000Z | 2019-02-22T10:25:53.000Z | /**
* vanilla: Object.h
* Copyright (c) Torr Vision Group, University of Oxford, 2016. All rights reserved.
*/
#ifndef H_VANILLA_OBJECT
#define H_VANILLA_OBJECT
#include <iostream>
template <typename Rep>
class Object
{
//#################### PUBLIC MEMBER VARIABLES ####################
public:
int categoryId;
Rep rep;
//#################### CONSTRUCTORS ####################
public:
Object(const Rep& rep_, int categoryId_ = -1)
: categoryId(categoryId_),
rep(rep_)
{}
};
//#################### OUTPUT ####################
template <typename Rep>
std::ostream& operator<<(std::ostream& os, const Object<Rep>& o)
{
os << "category: " << o.categoryId << '\n';
os << "representation: " << o.rep << '\n';
return os;
}
#endif
| 20.540541 | 84 | 0.55 | [
"object"
] |
712d64ae5345880e80fba7f7c4bc5e62d06b3e81 | 722 | h | C | ZSSModel/ZSSModel+extentions.h | yuyuepeng/ZSSModel | 6a65642573bc4583221af102102f908b1fa64368 | [
"MIT"
] | 2 | 2019-04-29T04:44:26.000Z | 2019-05-07T05:57:44.000Z | ZSSModel/ZSSModel+extentions.h | yuyuepeng/ZSSModel | 6a65642573bc4583221af102102f908b1fa64368 | [
"MIT"
] | null | null | null | ZSSModel/ZSSModel+extentions.h | yuyuepeng/ZSSModel | 6a65642573bc4583221af102102f908b1fa64368 | [
"MIT"
] | null | null | null | //
// ZSSModel+extentions.h
// ZSSModelDemo
//
// Created by 玉岳鹏 on 2019/4/26.
// Copyright © 2019 玉岳鹏. All rights reserved.
//
#import "ZSSModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface ZSSModel (extentions)
/**
字典数组转model数组
@param dictArray 字典数组
@return model数组
*/
+ (NSArray *)zss_modelArrayWithDictArray:(NSArray <NSDictionary *>*)dictArray;
/**
model数组转字典数组
@param modelArray model数组
@return 字典数组
*/
+ (NSArray *)zss_DictArrayWithModelArray:(NSArray *)modelArray;
/**
json字符串转model数组
@param json json 字符串
@return model数组
*/
+ (NSArray *)zss_modelArrayWithJson:(id)json;
/**
model转字典
@param model model
@return 字典
*/
+ (NSDictionary *)dictFromModel:(id)model;
@end
NS_ASSUME_NONNULL_END
| 14.44 | 78 | 0.714681 | [
"model"
] |
713136f38c3f3e3a69c3e686a144bf553e22a537 | 125,986 | h | C | petition.pb.h | UVG-Teams/so-chat | 95782a52568f2ed2e7036625316c046bbc34fc07 | [
"MIT"
] | null | null | null | petition.pb.h | UVG-Teams/so-chat | 95782a52568f2ed2e7036625316c046bbc34fc07 | [
"MIT"
] | null | null | null | petition.pb.h | UVG-Teams/so-chat | 95782a52568f2ed2e7036625316c046bbc34fc07 | [
"MIT"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: petition.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_petition_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_petition_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3015000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3015008 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_petition_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_petition_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[8]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_petition_2eproto;
::PROTOBUF_NAMESPACE_ID::Metadata descriptor_table_petition_2eproto_metadata_getter(int index);
namespace chat {
class ChangeStatus;
struct ChangeStatusDefaultTypeInternal;
extern ChangeStatusDefaultTypeInternal _ChangeStatus_default_instance_;
class ClientPetition;
struct ClientPetitionDefaultTypeInternal;
extern ClientPetitionDefaultTypeInternal _ClientPetition_default_instance_;
class ConnectedUsersResponse;
struct ConnectedUsersResponseDefaultTypeInternal;
extern ConnectedUsersResponseDefaultTypeInternal _ConnectedUsersResponse_default_instance_;
class MessageCommunication;
struct MessageCommunicationDefaultTypeInternal;
extern MessageCommunicationDefaultTypeInternal _MessageCommunication_default_instance_;
class ServerResponse;
struct ServerResponseDefaultTypeInternal;
extern ServerResponseDefaultTypeInternal _ServerResponse_default_instance_;
class UserInfo;
struct UserInfoDefaultTypeInternal;
extern UserInfoDefaultTypeInternal _UserInfo_default_instance_;
class UserRegistration;
struct UserRegistrationDefaultTypeInternal;
extern UserRegistrationDefaultTypeInternal _UserRegistration_default_instance_;
class UserRequest;
struct UserRequestDefaultTypeInternal;
extern UserRequestDefaultTypeInternal _UserRequest_default_instance_;
} // namespace chat
PROTOBUF_NAMESPACE_OPEN
template<> ::chat::ChangeStatus* Arena::CreateMaybeMessage<::chat::ChangeStatus>(Arena*);
template<> ::chat::ClientPetition* Arena::CreateMaybeMessage<::chat::ClientPetition>(Arena*);
template<> ::chat::ConnectedUsersResponse* Arena::CreateMaybeMessage<::chat::ConnectedUsersResponse>(Arena*);
template<> ::chat::MessageCommunication* Arena::CreateMaybeMessage<::chat::MessageCommunication>(Arena*);
template<> ::chat::ServerResponse* Arena::CreateMaybeMessage<::chat::ServerResponse>(Arena*);
template<> ::chat::UserInfo* Arena::CreateMaybeMessage<::chat::UserInfo>(Arena*);
template<> ::chat::UserRegistration* Arena::CreateMaybeMessage<::chat::UserRegistration>(Arena*);
template<> ::chat::UserRequest* Arena::CreateMaybeMessage<::chat::UserRequest>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace chat {
// ===================================================================
class UserRegistration PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:chat.UserRegistration) */ {
public:
inline UserRegistration() : UserRegistration(nullptr) {}
virtual ~UserRegistration();
explicit constexpr UserRegistration(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
UserRegistration(const UserRegistration& from);
UserRegistration(UserRegistration&& from) noexcept
: UserRegistration() {
*this = ::std::move(from);
}
inline UserRegistration& operator=(const UserRegistration& from) {
CopyFrom(from);
return *this;
}
inline UserRegistration& operator=(UserRegistration&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const UserRegistration& default_instance() {
return *internal_default_instance();
}
static inline const UserRegistration* internal_default_instance() {
return reinterpret_cast<const UserRegistration*>(
&_UserRegistration_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(UserRegistration& a, UserRegistration& b) {
a.Swap(&b);
}
inline void Swap(UserRegistration* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(UserRegistration* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline UserRegistration* New() const final {
return CreateMaybeMessage<UserRegistration>(nullptr);
}
UserRegistration* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<UserRegistration>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const UserRegistration& from);
void MergeFrom(const UserRegistration& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(UserRegistration* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "chat.UserRegistration";
}
protected:
explicit UserRegistration(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
return ::descriptor_table_petition_2eproto_metadata_getter(kIndexInFileMessages);
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kUsernameFieldNumber = 1,
kIpFieldNumber = 2,
};
// string username = 1;
bool has_username() const;
private:
bool _internal_has_username() const;
public:
void clear_username();
const std::string& username() const;
void set_username(const std::string& value);
void set_username(std::string&& value);
void set_username(const char* value);
void set_username(const char* value, size_t size);
std::string* mutable_username();
std::string* release_username();
void set_allocated_username(std::string* username);
private:
const std::string& _internal_username() const;
void _internal_set_username(const std::string& value);
std::string* _internal_mutable_username();
public:
// string ip = 2;
bool has_ip() const;
private:
bool _internal_has_ip() const;
public:
void clear_ip();
const std::string& ip() const;
void set_ip(const std::string& value);
void set_ip(std::string&& value);
void set_ip(const char* value);
void set_ip(const char* value, size_t size);
std::string* mutable_ip();
std::string* release_ip();
void set_allocated_ip(std::string* ip);
private:
const std::string& _internal_ip() const;
void _internal_set_ip(const std::string& value);
std::string* _internal_mutable_ip();
public:
// @@protoc_insertion_point(class_scope:chat.UserRegistration)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr username_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr ip_;
friend struct ::TableStruct_petition_2eproto;
};
// -------------------------------------------------------------------
class UserInfo PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:chat.UserInfo) */ {
public:
inline UserInfo() : UserInfo(nullptr) {}
virtual ~UserInfo();
explicit constexpr UserInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
UserInfo(const UserInfo& from);
UserInfo(UserInfo&& from) noexcept
: UserInfo() {
*this = ::std::move(from);
}
inline UserInfo& operator=(const UserInfo& from) {
CopyFrom(from);
return *this;
}
inline UserInfo& operator=(UserInfo&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const UserInfo& default_instance() {
return *internal_default_instance();
}
static inline const UserInfo* internal_default_instance() {
return reinterpret_cast<const UserInfo*>(
&_UserInfo_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
friend void swap(UserInfo& a, UserInfo& b) {
a.Swap(&b);
}
inline void Swap(UserInfo* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(UserInfo* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline UserInfo* New() const final {
return CreateMaybeMessage<UserInfo>(nullptr);
}
UserInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<UserInfo>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const UserInfo& from);
void MergeFrom(const UserInfo& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(UserInfo* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "chat.UserInfo";
}
protected:
explicit UserInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
return ::descriptor_table_petition_2eproto_metadata_getter(kIndexInFileMessages);
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kUsernameFieldNumber = 1,
kStatusFieldNumber = 2,
kIpFieldNumber = 3,
};
// string username = 1;
bool has_username() const;
private:
bool _internal_has_username() const;
public:
void clear_username();
const std::string& username() const;
void set_username(const std::string& value);
void set_username(std::string&& value);
void set_username(const char* value);
void set_username(const char* value, size_t size);
std::string* mutable_username();
std::string* release_username();
void set_allocated_username(std::string* username);
private:
const std::string& _internal_username() const;
void _internal_set_username(const std::string& value);
std::string* _internal_mutable_username();
public:
// string status = 2;
bool has_status() const;
private:
bool _internal_has_status() const;
public:
void clear_status();
const std::string& status() const;
void set_status(const std::string& value);
void set_status(std::string&& value);
void set_status(const char* value);
void set_status(const char* value, size_t size);
std::string* mutable_status();
std::string* release_status();
void set_allocated_status(std::string* status);
private:
const std::string& _internal_status() const;
void _internal_set_status(const std::string& value);
std::string* _internal_mutable_status();
public:
// string ip = 3;
bool has_ip() const;
private:
bool _internal_has_ip() const;
public:
void clear_ip();
const std::string& ip() const;
void set_ip(const std::string& value);
void set_ip(std::string&& value);
void set_ip(const char* value);
void set_ip(const char* value, size_t size);
std::string* mutable_ip();
std::string* release_ip();
void set_allocated_ip(std::string* ip);
private:
const std::string& _internal_ip() const;
void _internal_set_ip(const std::string& value);
std::string* _internal_mutable_ip();
public:
// @@protoc_insertion_point(class_scope:chat.UserInfo)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr username_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr status_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr ip_;
friend struct ::TableStruct_petition_2eproto;
};
// -------------------------------------------------------------------
class UserRequest PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:chat.UserRequest) */ {
public:
inline UserRequest() : UserRequest(nullptr) {}
virtual ~UserRequest();
explicit constexpr UserRequest(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
UserRequest(const UserRequest& from);
UserRequest(UserRequest&& from) noexcept
: UserRequest() {
*this = ::std::move(from);
}
inline UserRequest& operator=(const UserRequest& from) {
CopyFrom(from);
return *this;
}
inline UserRequest& operator=(UserRequest&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const UserRequest& default_instance() {
return *internal_default_instance();
}
static inline const UserRequest* internal_default_instance() {
return reinterpret_cast<const UserRequest*>(
&_UserRequest_default_instance_);
}
static constexpr int kIndexInFileMessages =
2;
friend void swap(UserRequest& a, UserRequest& b) {
a.Swap(&b);
}
inline void Swap(UserRequest* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(UserRequest* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline UserRequest* New() const final {
return CreateMaybeMessage<UserRequest>(nullptr);
}
UserRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<UserRequest>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const UserRequest& from);
void MergeFrom(const UserRequest& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(UserRequest* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "chat.UserRequest";
}
protected:
explicit UserRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
return ::descriptor_table_petition_2eproto_metadata_getter(kIndexInFileMessages);
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kUserFieldNumber = 1,
};
// string user = 1;
bool has_user() const;
private:
bool _internal_has_user() const;
public:
void clear_user();
const std::string& user() const;
void set_user(const std::string& value);
void set_user(std::string&& value);
void set_user(const char* value);
void set_user(const char* value, size_t size);
std::string* mutable_user();
std::string* release_user();
void set_allocated_user(std::string* user);
private:
const std::string& _internal_user() const;
void _internal_set_user(const std::string& value);
std::string* _internal_mutable_user();
public:
// @@protoc_insertion_point(class_scope:chat.UserRequest)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr user_;
friend struct ::TableStruct_petition_2eproto;
};
// -------------------------------------------------------------------
class ConnectedUsersResponse PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:chat.ConnectedUsersResponse) */ {
public:
inline ConnectedUsersResponse() : ConnectedUsersResponse(nullptr) {}
virtual ~ConnectedUsersResponse();
explicit constexpr ConnectedUsersResponse(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
ConnectedUsersResponse(const ConnectedUsersResponse& from);
ConnectedUsersResponse(ConnectedUsersResponse&& from) noexcept
: ConnectedUsersResponse() {
*this = ::std::move(from);
}
inline ConnectedUsersResponse& operator=(const ConnectedUsersResponse& from) {
CopyFrom(from);
return *this;
}
inline ConnectedUsersResponse& operator=(ConnectedUsersResponse&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const ConnectedUsersResponse& default_instance() {
return *internal_default_instance();
}
static inline const ConnectedUsersResponse* internal_default_instance() {
return reinterpret_cast<const ConnectedUsersResponse*>(
&_ConnectedUsersResponse_default_instance_);
}
static constexpr int kIndexInFileMessages =
3;
friend void swap(ConnectedUsersResponse& a, ConnectedUsersResponse& b) {
a.Swap(&b);
}
inline void Swap(ConnectedUsersResponse* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(ConnectedUsersResponse* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline ConnectedUsersResponse* New() const final {
return CreateMaybeMessage<ConnectedUsersResponse>(nullptr);
}
ConnectedUsersResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<ConnectedUsersResponse>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const ConnectedUsersResponse& from);
void MergeFrom(const ConnectedUsersResponse& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(ConnectedUsersResponse* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "chat.ConnectedUsersResponse";
}
protected:
explicit ConnectedUsersResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
return ::descriptor_table_petition_2eproto_metadata_getter(kIndexInFileMessages);
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kConnectedUsersFieldNumber = 1,
};
// repeated .chat.UserInfo connectedUsers = 1;
int connectedusers_size() const;
private:
int _internal_connectedusers_size() const;
public:
void clear_connectedusers();
::chat::UserInfo* mutable_connectedusers(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::chat::UserInfo >*
mutable_connectedusers();
private:
const ::chat::UserInfo& _internal_connectedusers(int index) const;
::chat::UserInfo* _internal_add_connectedusers();
public:
const ::chat::UserInfo& connectedusers(int index) const;
::chat::UserInfo* add_connectedusers();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::chat::UserInfo >&
connectedusers() const;
// @@protoc_insertion_point(class_scope:chat.ConnectedUsersResponse)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::chat::UserInfo > connectedusers_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_petition_2eproto;
};
// -------------------------------------------------------------------
class ChangeStatus PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:chat.ChangeStatus) */ {
public:
inline ChangeStatus() : ChangeStatus(nullptr) {}
virtual ~ChangeStatus();
explicit constexpr ChangeStatus(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
ChangeStatus(const ChangeStatus& from);
ChangeStatus(ChangeStatus&& from) noexcept
: ChangeStatus() {
*this = ::std::move(from);
}
inline ChangeStatus& operator=(const ChangeStatus& from) {
CopyFrom(from);
return *this;
}
inline ChangeStatus& operator=(ChangeStatus&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const ChangeStatus& default_instance() {
return *internal_default_instance();
}
static inline const ChangeStatus* internal_default_instance() {
return reinterpret_cast<const ChangeStatus*>(
&_ChangeStatus_default_instance_);
}
static constexpr int kIndexInFileMessages =
4;
friend void swap(ChangeStatus& a, ChangeStatus& b) {
a.Swap(&b);
}
inline void Swap(ChangeStatus* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(ChangeStatus* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline ChangeStatus* New() const final {
return CreateMaybeMessage<ChangeStatus>(nullptr);
}
ChangeStatus* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<ChangeStatus>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const ChangeStatus& from);
void MergeFrom(const ChangeStatus& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(ChangeStatus* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "chat.ChangeStatus";
}
protected:
explicit ChangeStatus(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
return ::descriptor_table_petition_2eproto_metadata_getter(kIndexInFileMessages);
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kUsernameFieldNumber = 1,
kStatusFieldNumber = 2,
};
// string username = 1;
bool has_username() const;
private:
bool _internal_has_username() const;
public:
void clear_username();
const std::string& username() const;
void set_username(const std::string& value);
void set_username(std::string&& value);
void set_username(const char* value);
void set_username(const char* value, size_t size);
std::string* mutable_username();
std::string* release_username();
void set_allocated_username(std::string* username);
private:
const std::string& _internal_username() const;
void _internal_set_username(const std::string& value);
std::string* _internal_mutable_username();
public:
// string status = 2;
bool has_status() const;
private:
bool _internal_has_status() const;
public:
void clear_status();
const std::string& status() const;
void set_status(const std::string& value);
void set_status(std::string&& value);
void set_status(const char* value);
void set_status(const char* value, size_t size);
std::string* mutable_status();
std::string* release_status();
void set_allocated_status(std::string* status);
private:
const std::string& _internal_status() const;
void _internal_set_status(const std::string& value);
std::string* _internal_mutable_status();
public:
// @@protoc_insertion_point(class_scope:chat.ChangeStatus)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr username_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr status_;
friend struct ::TableStruct_petition_2eproto;
};
// -------------------------------------------------------------------
class MessageCommunication PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:chat.MessageCommunication) */ {
public:
inline MessageCommunication() : MessageCommunication(nullptr) {}
virtual ~MessageCommunication();
explicit constexpr MessageCommunication(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
MessageCommunication(const MessageCommunication& from);
MessageCommunication(MessageCommunication&& from) noexcept
: MessageCommunication() {
*this = ::std::move(from);
}
inline MessageCommunication& operator=(const MessageCommunication& from) {
CopyFrom(from);
return *this;
}
inline MessageCommunication& operator=(MessageCommunication&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const MessageCommunication& default_instance() {
return *internal_default_instance();
}
static inline const MessageCommunication* internal_default_instance() {
return reinterpret_cast<const MessageCommunication*>(
&_MessageCommunication_default_instance_);
}
static constexpr int kIndexInFileMessages =
5;
friend void swap(MessageCommunication& a, MessageCommunication& b) {
a.Swap(&b);
}
inline void Swap(MessageCommunication* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(MessageCommunication* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline MessageCommunication* New() const final {
return CreateMaybeMessage<MessageCommunication>(nullptr);
}
MessageCommunication* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<MessageCommunication>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const MessageCommunication& from);
void MergeFrom(const MessageCommunication& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(MessageCommunication* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "chat.MessageCommunication";
}
protected:
explicit MessageCommunication(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
return ::descriptor_table_petition_2eproto_metadata_getter(kIndexInFileMessages);
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kMessageFieldNumber = 1,
kRecipientFieldNumber = 2,
kSenderFieldNumber = 3,
};
// string message = 1;
bool has_message() const;
private:
bool _internal_has_message() const;
public:
void clear_message();
const std::string& message() const;
void set_message(const std::string& value);
void set_message(std::string&& value);
void set_message(const char* value);
void set_message(const char* value, size_t size);
std::string* mutable_message();
std::string* release_message();
void set_allocated_message(std::string* message);
private:
const std::string& _internal_message() const;
void _internal_set_message(const std::string& value);
std::string* _internal_mutable_message();
public:
// string recipient = 2;
bool has_recipient() const;
private:
bool _internal_has_recipient() const;
public:
void clear_recipient();
const std::string& recipient() const;
void set_recipient(const std::string& value);
void set_recipient(std::string&& value);
void set_recipient(const char* value);
void set_recipient(const char* value, size_t size);
std::string* mutable_recipient();
std::string* release_recipient();
void set_allocated_recipient(std::string* recipient);
private:
const std::string& _internal_recipient() const;
void _internal_set_recipient(const std::string& value);
std::string* _internal_mutable_recipient();
public:
// string sender = 3;
bool has_sender() const;
private:
bool _internal_has_sender() const;
public:
void clear_sender();
const std::string& sender() const;
void set_sender(const std::string& value);
void set_sender(std::string&& value);
void set_sender(const char* value);
void set_sender(const char* value, size_t size);
std::string* mutable_sender();
std::string* release_sender();
void set_allocated_sender(std::string* sender);
private:
const std::string& _internal_sender() const;
void _internal_set_sender(const std::string& value);
std::string* _internal_mutable_sender();
public:
// @@protoc_insertion_point(class_scope:chat.MessageCommunication)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr message_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr recipient_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr sender_;
friend struct ::TableStruct_petition_2eproto;
};
// -------------------------------------------------------------------
class ClientPetition PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:chat.ClientPetition) */ {
public:
inline ClientPetition() : ClientPetition(nullptr) {}
virtual ~ClientPetition();
explicit constexpr ClientPetition(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
ClientPetition(const ClientPetition& from);
ClientPetition(ClientPetition&& from) noexcept
: ClientPetition() {
*this = ::std::move(from);
}
inline ClientPetition& operator=(const ClientPetition& from) {
CopyFrom(from);
return *this;
}
inline ClientPetition& operator=(ClientPetition&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const ClientPetition& default_instance() {
return *internal_default_instance();
}
static inline const ClientPetition* internal_default_instance() {
return reinterpret_cast<const ClientPetition*>(
&_ClientPetition_default_instance_);
}
static constexpr int kIndexInFileMessages =
6;
friend void swap(ClientPetition& a, ClientPetition& b) {
a.Swap(&b);
}
inline void Swap(ClientPetition* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(ClientPetition* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline ClientPetition* New() const final {
return CreateMaybeMessage<ClientPetition>(nullptr);
}
ClientPetition* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<ClientPetition>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const ClientPetition& from);
void MergeFrom(const ClientPetition& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(ClientPetition* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "chat.ClientPetition";
}
protected:
explicit ClientPetition(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
return ::descriptor_table_petition_2eproto_metadata_getter(kIndexInFileMessages);
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kRegistrationFieldNumber = 2,
kUsersFieldNumber = 3,
kChangeFieldNumber = 4,
kMessageCommunicationFieldNumber = 5,
kOptionFieldNumber = 1,
};
// .chat.UserRegistration registration = 2;
bool has_registration() const;
private:
bool _internal_has_registration() const;
public:
void clear_registration();
const ::chat::UserRegistration& registration() const;
::chat::UserRegistration* release_registration();
::chat::UserRegistration* mutable_registration();
void set_allocated_registration(::chat::UserRegistration* registration);
private:
const ::chat::UserRegistration& _internal_registration() const;
::chat::UserRegistration* _internal_mutable_registration();
public:
void unsafe_arena_set_allocated_registration(
::chat::UserRegistration* registration);
::chat::UserRegistration* unsafe_arena_release_registration();
// .chat.UserRequest users = 3;
bool has_users() const;
private:
bool _internal_has_users() const;
public:
void clear_users();
const ::chat::UserRequest& users() const;
::chat::UserRequest* release_users();
::chat::UserRequest* mutable_users();
void set_allocated_users(::chat::UserRequest* users);
private:
const ::chat::UserRequest& _internal_users() const;
::chat::UserRequest* _internal_mutable_users();
public:
void unsafe_arena_set_allocated_users(
::chat::UserRequest* users);
::chat::UserRequest* unsafe_arena_release_users();
// .chat.ChangeStatus change = 4;
bool has_change() const;
private:
bool _internal_has_change() const;
public:
void clear_change();
const ::chat::ChangeStatus& change() const;
::chat::ChangeStatus* release_change();
::chat::ChangeStatus* mutable_change();
void set_allocated_change(::chat::ChangeStatus* change);
private:
const ::chat::ChangeStatus& _internal_change() const;
::chat::ChangeStatus* _internal_mutable_change();
public:
void unsafe_arena_set_allocated_change(
::chat::ChangeStatus* change);
::chat::ChangeStatus* unsafe_arena_release_change();
// .chat.MessageCommunication messageCommunication = 5;
bool has_messagecommunication() const;
private:
bool _internal_has_messagecommunication() const;
public:
void clear_messagecommunication();
const ::chat::MessageCommunication& messagecommunication() const;
::chat::MessageCommunication* release_messagecommunication();
::chat::MessageCommunication* mutable_messagecommunication();
void set_allocated_messagecommunication(::chat::MessageCommunication* messagecommunication);
private:
const ::chat::MessageCommunication& _internal_messagecommunication() const;
::chat::MessageCommunication* _internal_mutable_messagecommunication();
public:
void unsafe_arena_set_allocated_messagecommunication(
::chat::MessageCommunication* messagecommunication);
::chat::MessageCommunication* unsafe_arena_release_messagecommunication();
// int32 option = 1;
bool has_option() const;
private:
bool _internal_has_option() const;
public:
void clear_option();
::PROTOBUF_NAMESPACE_ID::int32 option() const;
void set_option(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_option() const;
void _internal_set_option(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// @@protoc_insertion_point(class_scope:chat.ClientPetition)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::chat::UserRegistration* registration_;
::chat::UserRequest* users_;
::chat::ChangeStatus* change_;
::chat::MessageCommunication* messagecommunication_;
::PROTOBUF_NAMESPACE_ID::int32 option_;
friend struct ::TableStruct_petition_2eproto;
};
// -------------------------------------------------------------------
class ServerResponse PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:chat.ServerResponse) */ {
public:
inline ServerResponse() : ServerResponse(nullptr) {}
virtual ~ServerResponse();
explicit constexpr ServerResponse(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
ServerResponse(const ServerResponse& from);
ServerResponse(ServerResponse&& from) noexcept
: ServerResponse() {
*this = ::std::move(from);
}
inline ServerResponse& operator=(const ServerResponse& from) {
CopyFrom(from);
return *this;
}
inline ServerResponse& operator=(ServerResponse&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const ServerResponse& default_instance() {
return *internal_default_instance();
}
static inline const ServerResponse* internal_default_instance() {
return reinterpret_cast<const ServerResponse*>(
&_ServerResponse_default_instance_);
}
static constexpr int kIndexInFileMessages =
7;
friend void swap(ServerResponse& a, ServerResponse& b) {
a.Swap(&b);
}
inline void Swap(ServerResponse* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(ServerResponse* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline ServerResponse* New() const final {
return CreateMaybeMessage<ServerResponse>(nullptr);
}
ServerResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<ServerResponse>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const ServerResponse& from);
void MergeFrom(const ServerResponse& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(ServerResponse* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "chat.ServerResponse";
}
protected:
explicit ServerResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
return ::descriptor_table_petition_2eproto_metadata_getter(kIndexInFileMessages);
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kServerMessageFieldNumber = 3,
kConnectedUsersFieldNumber = 4,
kMessageCommunicationFieldNumber = 5,
kUserInfoResponseFieldNumber = 6,
kChangeFieldNumber = 7,
kOptionFieldNumber = 1,
kCodeFieldNumber = 2,
};
// string serverMessage = 3;
bool has_servermessage() const;
private:
bool _internal_has_servermessage() const;
public:
void clear_servermessage();
const std::string& servermessage() const;
void set_servermessage(const std::string& value);
void set_servermessage(std::string&& value);
void set_servermessage(const char* value);
void set_servermessage(const char* value, size_t size);
std::string* mutable_servermessage();
std::string* release_servermessage();
void set_allocated_servermessage(std::string* servermessage);
private:
const std::string& _internal_servermessage() const;
void _internal_set_servermessage(const std::string& value);
std::string* _internal_mutable_servermessage();
public:
// .chat.ConnectedUsersResponse connectedUsers = 4;
bool has_connectedusers() const;
private:
bool _internal_has_connectedusers() const;
public:
void clear_connectedusers();
const ::chat::ConnectedUsersResponse& connectedusers() const;
::chat::ConnectedUsersResponse* release_connectedusers();
::chat::ConnectedUsersResponse* mutable_connectedusers();
void set_allocated_connectedusers(::chat::ConnectedUsersResponse* connectedusers);
private:
const ::chat::ConnectedUsersResponse& _internal_connectedusers() const;
::chat::ConnectedUsersResponse* _internal_mutable_connectedusers();
public:
void unsafe_arena_set_allocated_connectedusers(
::chat::ConnectedUsersResponse* connectedusers);
::chat::ConnectedUsersResponse* unsafe_arena_release_connectedusers();
// .chat.MessageCommunication messageCommunication = 5;
bool has_messagecommunication() const;
private:
bool _internal_has_messagecommunication() const;
public:
void clear_messagecommunication();
const ::chat::MessageCommunication& messagecommunication() const;
::chat::MessageCommunication* release_messagecommunication();
::chat::MessageCommunication* mutable_messagecommunication();
void set_allocated_messagecommunication(::chat::MessageCommunication* messagecommunication);
private:
const ::chat::MessageCommunication& _internal_messagecommunication() const;
::chat::MessageCommunication* _internal_mutable_messagecommunication();
public:
void unsafe_arena_set_allocated_messagecommunication(
::chat::MessageCommunication* messagecommunication);
::chat::MessageCommunication* unsafe_arena_release_messagecommunication();
// .chat.UserInfo userInfoResponse = 6;
bool has_userinforesponse() const;
private:
bool _internal_has_userinforesponse() const;
public:
void clear_userinforesponse();
const ::chat::UserInfo& userinforesponse() const;
::chat::UserInfo* release_userinforesponse();
::chat::UserInfo* mutable_userinforesponse();
void set_allocated_userinforesponse(::chat::UserInfo* userinforesponse);
private:
const ::chat::UserInfo& _internal_userinforesponse() const;
::chat::UserInfo* _internal_mutable_userinforesponse();
public:
void unsafe_arena_set_allocated_userinforesponse(
::chat::UserInfo* userinforesponse);
::chat::UserInfo* unsafe_arena_release_userinforesponse();
// .chat.ChangeStatus change = 7;
bool has_change() const;
private:
bool _internal_has_change() const;
public:
void clear_change();
const ::chat::ChangeStatus& change() const;
::chat::ChangeStatus* release_change();
::chat::ChangeStatus* mutable_change();
void set_allocated_change(::chat::ChangeStatus* change);
private:
const ::chat::ChangeStatus& _internal_change() const;
::chat::ChangeStatus* _internal_mutable_change();
public:
void unsafe_arena_set_allocated_change(
::chat::ChangeStatus* change);
::chat::ChangeStatus* unsafe_arena_release_change();
// int32 option = 1;
bool has_option() const;
private:
bool _internal_has_option() const;
public:
void clear_option();
::PROTOBUF_NAMESPACE_ID::int32 option() const;
void set_option(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_option() const;
void _internal_set_option(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// int32 code = 2;
bool has_code() const;
private:
bool _internal_has_code() const;
public:
void clear_code();
::PROTOBUF_NAMESPACE_ID::int32 code() const;
void set_code(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_code() const;
void _internal_set_code(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// @@protoc_insertion_point(class_scope:chat.ServerResponse)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr servermessage_;
::chat::ConnectedUsersResponse* connectedusers_;
::chat::MessageCommunication* messagecommunication_;
::chat::UserInfo* userinforesponse_;
::chat::ChangeStatus* change_;
::PROTOBUF_NAMESPACE_ID::int32 option_;
::PROTOBUF_NAMESPACE_ID::int32 code_;
friend struct ::TableStruct_petition_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// UserRegistration
// string username = 1;
inline bool UserRegistration::_internal_has_username() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool UserRegistration::has_username() const {
return _internal_has_username();
}
inline void UserRegistration::clear_username() {
username_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& UserRegistration::username() const {
// @@protoc_insertion_point(field_get:chat.UserRegistration.username)
return _internal_username();
}
inline void UserRegistration::set_username(const std::string& value) {
_internal_set_username(value);
// @@protoc_insertion_point(field_set:chat.UserRegistration.username)
}
inline std::string* UserRegistration::mutable_username() {
// @@protoc_insertion_point(field_mutable:chat.UserRegistration.username)
return _internal_mutable_username();
}
inline const std::string& UserRegistration::_internal_username() const {
return username_.Get();
}
inline void UserRegistration::_internal_set_username(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
username_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void UserRegistration::set_username(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
username_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.UserRegistration.username)
}
inline void UserRegistration::set_username(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
username_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.UserRegistration.username)
}
inline void UserRegistration::set_username(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
username_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.UserRegistration.username)
}
inline std::string* UserRegistration::_internal_mutable_username() {
_has_bits_[0] |= 0x00000001u;
return username_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* UserRegistration::release_username() {
// @@protoc_insertion_point(field_release:chat.UserRegistration.username)
if (!_internal_has_username()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return username_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UserRegistration::set_allocated_username(std::string* username) {
if (username != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
username_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), username,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.UserRegistration.username)
}
// string ip = 2;
inline bool UserRegistration::_internal_has_ip() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool UserRegistration::has_ip() const {
return _internal_has_ip();
}
inline void UserRegistration::clear_ip() {
ip_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& UserRegistration::ip() const {
// @@protoc_insertion_point(field_get:chat.UserRegistration.ip)
return _internal_ip();
}
inline void UserRegistration::set_ip(const std::string& value) {
_internal_set_ip(value);
// @@protoc_insertion_point(field_set:chat.UserRegistration.ip)
}
inline std::string* UserRegistration::mutable_ip() {
// @@protoc_insertion_point(field_mutable:chat.UserRegistration.ip)
return _internal_mutable_ip();
}
inline const std::string& UserRegistration::_internal_ip() const {
return ip_.Get();
}
inline void UserRegistration::_internal_set_ip(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
ip_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void UserRegistration::set_ip(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
ip_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.UserRegistration.ip)
}
inline void UserRegistration::set_ip(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
ip_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.UserRegistration.ip)
}
inline void UserRegistration::set_ip(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
ip_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.UserRegistration.ip)
}
inline std::string* UserRegistration::_internal_mutable_ip() {
_has_bits_[0] |= 0x00000002u;
return ip_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* UserRegistration::release_ip() {
// @@protoc_insertion_point(field_release:chat.UserRegistration.ip)
if (!_internal_has_ip()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return ip_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UserRegistration::set_allocated_ip(std::string* ip) {
if (ip != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
ip_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ip,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.UserRegistration.ip)
}
// -------------------------------------------------------------------
// UserInfo
// string username = 1;
inline bool UserInfo::_internal_has_username() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool UserInfo::has_username() const {
return _internal_has_username();
}
inline void UserInfo::clear_username() {
username_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& UserInfo::username() const {
// @@protoc_insertion_point(field_get:chat.UserInfo.username)
return _internal_username();
}
inline void UserInfo::set_username(const std::string& value) {
_internal_set_username(value);
// @@protoc_insertion_point(field_set:chat.UserInfo.username)
}
inline std::string* UserInfo::mutable_username() {
// @@protoc_insertion_point(field_mutable:chat.UserInfo.username)
return _internal_mutable_username();
}
inline const std::string& UserInfo::_internal_username() const {
return username_.Get();
}
inline void UserInfo::_internal_set_username(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
username_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void UserInfo::set_username(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
username_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.UserInfo.username)
}
inline void UserInfo::set_username(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
username_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.UserInfo.username)
}
inline void UserInfo::set_username(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
username_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.UserInfo.username)
}
inline std::string* UserInfo::_internal_mutable_username() {
_has_bits_[0] |= 0x00000001u;
return username_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* UserInfo::release_username() {
// @@protoc_insertion_point(field_release:chat.UserInfo.username)
if (!_internal_has_username()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return username_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UserInfo::set_allocated_username(std::string* username) {
if (username != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
username_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), username,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.UserInfo.username)
}
// string status = 2;
inline bool UserInfo::_internal_has_status() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool UserInfo::has_status() const {
return _internal_has_status();
}
inline void UserInfo::clear_status() {
status_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& UserInfo::status() const {
// @@protoc_insertion_point(field_get:chat.UserInfo.status)
return _internal_status();
}
inline void UserInfo::set_status(const std::string& value) {
_internal_set_status(value);
// @@protoc_insertion_point(field_set:chat.UserInfo.status)
}
inline std::string* UserInfo::mutable_status() {
// @@protoc_insertion_point(field_mutable:chat.UserInfo.status)
return _internal_mutable_status();
}
inline const std::string& UserInfo::_internal_status() const {
return status_.Get();
}
inline void UserInfo::_internal_set_status(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
status_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void UserInfo::set_status(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
status_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.UserInfo.status)
}
inline void UserInfo::set_status(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
status_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.UserInfo.status)
}
inline void UserInfo::set_status(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
status_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.UserInfo.status)
}
inline std::string* UserInfo::_internal_mutable_status() {
_has_bits_[0] |= 0x00000002u;
return status_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* UserInfo::release_status() {
// @@protoc_insertion_point(field_release:chat.UserInfo.status)
if (!_internal_has_status()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return status_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UserInfo::set_allocated_status(std::string* status) {
if (status != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
status_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), status,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.UserInfo.status)
}
// string ip = 3;
inline bool UserInfo::_internal_has_ip() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
return value;
}
inline bool UserInfo::has_ip() const {
return _internal_has_ip();
}
inline void UserInfo::clear_ip() {
ip_.ClearToEmpty();
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& UserInfo::ip() const {
// @@protoc_insertion_point(field_get:chat.UserInfo.ip)
return _internal_ip();
}
inline void UserInfo::set_ip(const std::string& value) {
_internal_set_ip(value);
// @@protoc_insertion_point(field_set:chat.UserInfo.ip)
}
inline std::string* UserInfo::mutable_ip() {
// @@protoc_insertion_point(field_mutable:chat.UserInfo.ip)
return _internal_mutable_ip();
}
inline const std::string& UserInfo::_internal_ip() const {
return ip_.Get();
}
inline void UserInfo::_internal_set_ip(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
ip_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void UserInfo::set_ip(std::string&& value) {
_has_bits_[0] |= 0x00000004u;
ip_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.UserInfo.ip)
}
inline void UserInfo::set_ip(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000004u;
ip_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.UserInfo.ip)
}
inline void UserInfo::set_ip(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000004u;
ip_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.UserInfo.ip)
}
inline std::string* UserInfo::_internal_mutable_ip() {
_has_bits_[0] |= 0x00000004u;
return ip_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* UserInfo::release_ip() {
// @@protoc_insertion_point(field_release:chat.UserInfo.ip)
if (!_internal_has_ip()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
return ip_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UserInfo::set_allocated_ip(std::string* ip) {
if (ip != nullptr) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
ip_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ip,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.UserInfo.ip)
}
// -------------------------------------------------------------------
// UserRequest
// string user = 1;
inline bool UserRequest::_internal_has_user() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool UserRequest::has_user() const {
return _internal_has_user();
}
inline void UserRequest::clear_user() {
user_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& UserRequest::user() const {
// @@protoc_insertion_point(field_get:chat.UserRequest.user)
return _internal_user();
}
inline void UserRequest::set_user(const std::string& value) {
_internal_set_user(value);
// @@protoc_insertion_point(field_set:chat.UserRequest.user)
}
inline std::string* UserRequest::mutable_user() {
// @@protoc_insertion_point(field_mutable:chat.UserRequest.user)
return _internal_mutable_user();
}
inline const std::string& UserRequest::_internal_user() const {
return user_.Get();
}
inline void UserRequest::_internal_set_user(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
user_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void UserRequest::set_user(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
user_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.UserRequest.user)
}
inline void UserRequest::set_user(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
user_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.UserRequest.user)
}
inline void UserRequest::set_user(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
user_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.UserRequest.user)
}
inline std::string* UserRequest::_internal_mutable_user() {
_has_bits_[0] |= 0x00000001u;
return user_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* UserRequest::release_user() {
// @@protoc_insertion_point(field_release:chat.UserRequest.user)
if (!_internal_has_user()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return user_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UserRequest::set_allocated_user(std::string* user) {
if (user != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
user_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), user,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.UserRequest.user)
}
// -------------------------------------------------------------------
// ConnectedUsersResponse
// repeated .chat.UserInfo connectedUsers = 1;
inline int ConnectedUsersResponse::_internal_connectedusers_size() const {
return connectedusers_.size();
}
inline int ConnectedUsersResponse::connectedusers_size() const {
return _internal_connectedusers_size();
}
inline void ConnectedUsersResponse::clear_connectedusers() {
connectedusers_.Clear();
}
inline ::chat::UserInfo* ConnectedUsersResponse::mutable_connectedusers(int index) {
// @@protoc_insertion_point(field_mutable:chat.ConnectedUsersResponse.connectedUsers)
return connectedusers_.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::chat::UserInfo >*
ConnectedUsersResponse::mutable_connectedusers() {
// @@protoc_insertion_point(field_mutable_list:chat.ConnectedUsersResponse.connectedUsers)
return &connectedusers_;
}
inline const ::chat::UserInfo& ConnectedUsersResponse::_internal_connectedusers(int index) const {
return connectedusers_.Get(index);
}
inline const ::chat::UserInfo& ConnectedUsersResponse::connectedusers(int index) const {
// @@protoc_insertion_point(field_get:chat.ConnectedUsersResponse.connectedUsers)
return _internal_connectedusers(index);
}
inline ::chat::UserInfo* ConnectedUsersResponse::_internal_add_connectedusers() {
return connectedusers_.Add();
}
inline ::chat::UserInfo* ConnectedUsersResponse::add_connectedusers() {
// @@protoc_insertion_point(field_add:chat.ConnectedUsersResponse.connectedUsers)
return _internal_add_connectedusers();
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::chat::UserInfo >&
ConnectedUsersResponse::connectedusers() const {
// @@protoc_insertion_point(field_list:chat.ConnectedUsersResponse.connectedUsers)
return connectedusers_;
}
// -------------------------------------------------------------------
// ChangeStatus
// string username = 1;
inline bool ChangeStatus::_internal_has_username() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool ChangeStatus::has_username() const {
return _internal_has_username();
}
inline void ChangeStatus::clear_username() {
username_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& ChangeStatus::username() const {
// @@protoc_insertion_point(field_get:chat.ChangeStatus.username)
return _internal_username();
}
inline void ChangeStatus::set_username(const std::string& value) {
_internal_set_username(value);
// @@protoc_insertion_point(field_set:chat.ChangeStatus.username)
}
inline std::string* ChangeStatus::mutable_username() {
// @@protoc_insertion_point(field_mutable:chat.ChangeStatus.username)
return _internal_mutable_username();
}
inline const std::string& ChangeStatus::_internal_username() const {
return username_.Get();
}
inline void ChangeStatus::_internal_set_username(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
username_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void ChangeStatus::set_username(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
username_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.ChangeStatus.username)
}
inline void ChangeStatus::set_username(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
username_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.ChangeStatus.username)
}
inline void ChangeStatus::set_username(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
username_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.ChangeStatus.username)
}
inline std::string* ChangeStatus::_internal_mutable_username() {
_has_bits_[0] |= 0x00000001u;
return username_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* ChangeStatus::release_username() {
// @@protoc_insertion_point(field_release:chat.ChangeStatus.username)
if (!_internal_has_username()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return username_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void ChangeStatus::set_allocated_username(std::string* username) {
if (username != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
username_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), username,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.ChangeStatus.username)
}
// string status = 2;
inline bool ChangeStatus::_internal_has_status() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool ChangeStatus::has_status() const {
return _internal_has_status();
}
inline void ChangeStatus::clear_status() {
status_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& ChangeStatus::status() const {
// @@protoc_insertion_point(field_get:chat.ChangeStatus.status)
return _internal_status();
}
inline void ChangeStatus::set_status(const std::string& value) {
_internal_set_status(value);
// @@protoc_insertion_point(field_set:chat.ChangeStatus.status)
}
inline std::string* ChangeStatus::mutable_status() {
// @@protoc_insertion_point(field_mutable:chat.ChangeStatus.status)
return _internal_mutable_status();
}
inline const std::string& ChangeStatus::_internal_status() const {
return status_.Get();
}
inline void ChangeStatus::_internal_set_status(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
status_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void ChangeStatus::set_status(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
status_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.ChangeStatus.status)
}
inline void ChangeStatus::set_status(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
status_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.ChangeStatus.status)
}
inline void ChangeStatus::set_status(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
status_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.ChangeStatus.status)
}
inline std::string* ChangeStatus::_internal_mutable_status() {
_has_bits_[0] |= 0x00000002u;
return status_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* ChangeStatus::release_status() {
// @@protoc_insertion_point(field_release:chat.ChangeStatus.status)
if (!_internal_has_status()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return status_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void ChangeStatus::set_allocated_status(std::string* status) {
if (status != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
status_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), status,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.ChangeStatus.status)
}
// -------------------------------------------------------------------
// MessageCommunication
// string message = 1;
inline bool MessageCommunication::_internal_has_message() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool MessageCommunication::has_message() const {
return _internal_has_message();
}
inline void MessageCommunication::clear_message() {
message_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& MessageCommunication::message() const {
// @@protoc_insertion_point(field_get:chat.MessageCommunication.message)
return _internal_message();
}
inline void MessageCommunication::set_message(const std::string& value) {
_internal_set_message(value);
// @@protoc_insertion_point(field_set:chat.MessageCommunication.message)
}
inline std::string* MessageCommunication::mutable_message() {
// @@protoc_insertion_point(field_mutable:chat.MessageCommunication.message)
return _internal_mutable_message();
}
inline const std::string& MessageCommunication::_internal_message() const {
return message_.Get();
}
inline void MessageCommunication::_internal_set_message(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
message_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void MessageCommunication::set_message(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
message_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.MessageCommunication.message)
}
inline void MessageCommunication::set_message(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
message_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.MessageCommunication.message)
}
inline void MessageCommunication::set_message(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
message_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.MessageCommunication.message)
}
inline std::string* MessageCommunication::_internal_mutable_message() {
_has_bits_[0] |= 0x00000001u;
return message_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* MessageCommunication::release_message() {
// @@protoc_insertion_point(field_release:chat.MessageCommunication.message)
if (!_internal_has_message()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return message_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void MessageCommunication::set_allocated_message(std::string* message) {
if (message != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
message_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), message,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.MessageCommunication.message)
}
// string recipient = 2;
inline bool MessageCommunication::_internal_has_recipient() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool MessageCommunication::has_recipient() const {
return _internal_has_recipient();
}
inline void MessageCommunication::clear_recipient() {
recipient_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& MessageCommunication::recipient() const {
// @@protoc_insertion_point(field_get:chat.MessageCommunication.recipient)
return _internal_recipient();
}
inline void MessageCommunication::set_recipient(const std::string& value) {
_internal_set_recipient(value);
// @@protoc_insertion_point(field_set:chat.MessageCommunication.recipient)
}
inline std::string* MessageCommunication::mutable_recipient() {
// @@protoc_insertion_point(field_mutable:chat.MessageCommunication.recipient)
return _internal_mutable_recipient();
}
inline const std::string& MessageCommunication::_internal_recipient() const {
return recipient_.Get();
}
inline void MessageCommunication::_internal_set_recipient(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
recipient_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void MessageCommunication::set_recipient(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
recipient_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.MessageCommunication.recipient)
}
inline void MessageCommunication::set_recipient(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
recipient_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.MessageCommunication.recipient)
}
inline void MessageCommunication::set_recipient(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
recipient_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.MessageCommunication.recipient)
}
inline std::string* MessageCommunication::_internal_mutable_recipient() {
_has_bits_[0] |= 0x00000002u;
return recipient_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* MessageCommunication::release_recipient() {
// @@protoc_insertion_point(field_release:chat.MessageCommunication.recipient)
if (!_internal_has_recipient()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return recipient_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void MessageCommunication::set_allocated_recipient(std::string* recipient) {
if (recipient != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
recipient_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), recipient,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.MessageCommunication.recipient)
}
// string sender = 3;
inline bool MessageCommunication::_internal_has_sender() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
return value;
}
inline bool MessageCommunication::has_sender() const {
return _internal_has_sender();
}
inline void MessageCommunication::clear_sender() {
sender_.ClearToEmpty();
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& MessageCommunication::sender() const {
// @@protoc_insertion_point(field_get:chat.MessageCommunication.sender)
return _internal_sender();
}
inline void MessageCommunication::set_sender(const std::string& value) {
_internal_set_sender(value);
// @@protoc_insertion_point(field_set:chat.MessageCommunication.sender)
}
inline std::string* MessageCommunication::mutable_sender() {
// @@protoc_insertion_point(field_mutable:chat.MessageCommunication.sender)
return _internal_mutable_sender();
}
inline const std::string& MessageCommunication::_internal_sender() const {
return sender_.Get();
}
inline void MessageCommunication::_internal_set_sender(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
sender_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void MessageCommunication::set_sender(std::string&& value) {
_has_bits_[0] |= 0x00000004u;
sender_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.MessageCommunication.sender)
}
inline void MessageCommunication::set_sender(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000004u;
sender_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.MessageCommunication.sender)
}
inline void MessageCommunication::set_sender(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000004u;
sender_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.MessageCommunication.sender)
}
inline std::string* MessageCommunication::_internal_mutable_sender() {
_has_bits_[0] |= 0x00000004u;
return sender_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* MessageCommunication::release_sender() {
// @@protoc_insertion_point(field_release:chat.MessageCommunication.sender)
if (!_internal_has_sender()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
return sender_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void MessageCommunication::set_allocated_sender(std::string* sender) {
if (sender != nullptr) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
sender_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), sender,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.MessageCommunication.sender)
}
// -------------------------------------------------------------------
// ClientPetition
// int32 option = 1;
inline bool ClientPetition::_internal_has_option() const {
bool value = (_has_bits_[0] & 0x00000010u) != 0;
return value;
}
inline bool ClientPetition::has_option() const {
return _internal_has_option();
}
inline void ClientPetition::clear_option() {
option_ = 0;
_has_bits_[0] &= ~0x00000010u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ClientPetition::_internal_option() const {
return option_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ClientPetition::option() const {
// @@protoc_insertion_point(field_get:chat.ClientPetition.option)
return _internal_option();
}
inline void ClientPetition::_internal_set_option(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000010u;
option_ = value;
}
inline void ClientPetition::set_option(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_option(value);
// @@protoc_insertion_point(field_set:chat.ClientPetition.option)
}
// .chat.UserRegistration registration = 2;
inline bool ClientPetition::_internal_has_registration() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
PROTOBUF_ASSUME(!value || registration_ != nullptr);
return value;
}
inline bool ClientPetition::has_registration() const {
return _internal_has_registration();
}
inline void ClientPetition::clear_registration() {
if (GetArena() == nullptr && registration_ != nullptr) {
delete registration_;
}
registration_ = nullptr;
_has_bits_[0] &= ~0x00000001u;
}
inline const ::chat::UserRegistration& ClientPetition::_internal_registration() const {
const ::chat::UserRegistration* p = registration_;
return p != nullptr ? *p : reinterpret_cast<const ::chat::UserRegistration&>(
::chat::_UserRegistration_default_instance_);
}
inline const ::chat::UserRegistration& ClientPetition::registration() const {
// @@protoc_insertion_point(field_get:chat.ClientPetition.registration)
return _internal_registration();
}
inline void ClientPetition::unsafe_arena_set_allocated_registration(
::chat::UserRegistration* registration) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(registration_);
}
registration_ = registration;
if (registration) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:chat.ClientPetition.registration)
}
inline ::chat::UserRegistration* ClientPetition::release_registration() {
_has_bits_[0] &= ~0x00000001u;
::chat::UserRegistration* temp = registration_;
registration_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::chat::UserRegistration* ClientPetition::unsafe_arena_release_registration() {
// @@protoc_insertion_point(field_release:chat.ClientPetition.registration)
_has_bits_[0] &= ~0x00000001u;
::chat::UserRegistration* temp = registration_;
registration_ = nullptr;
return temp;
}
inline ::chat::UserRegistration* ClientPetition::_internal_mutable_registration() {
_has_bits_[0] |= 0x00000001u;
if (registration_ == nullptr) {
auto* p = CreateMaybeMessage<::chat::UserRegistration>(GetArena());
registration_ = p;
}
return registration_;
}
inline ::chat::UserRegistration* ClientPetition::mutable_registration() {
// @@protoc_insertion_point(field_mutable:chat.ClientPetition.registration)
return _internal_mutable_registration();
}
inline void ClientPetition::set_allocated_registration(::chat::UserRegistration* registration) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete registration_;
}
if (registration) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(registration);
if (message_arena != submessage_arena) {
registration = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, registration, submessage_arena);
}
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
registration_ = registration;
// @@protoc_insertion_point(field_set_allocated:chat.ClientPetition.registration)
}
// .chat.UserRequest users = 3;
inline bool ClientPetition::_internal_has_users() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
PROTOBUF_ASSUME(!value || users_ != nullptr);
return value;
}
inline bool ClientPetition::has_users() const {
return _internal_has_users();
}
inline void ClientPetition::clear_users() {
if (GetArena() == nullptr && users_ != nullptr) {
delete users_;
}
users_ = nullptr;
_has_bits_[0] &= ~0x00000002u;
}
inline const ::chat::UserRequest& ClientPetition::_internal_users() const {
const ::chat::UserRequest* p = users_;
return p != nullptr ? *p : reinterpret_cast<const ::chat::UserRequest&>(
::chat::_UserRequest_default_instance_);
}
inline const ::chat::UserRequest& ClientPetition::users() const {
// @@protoc_insertion_point(field_get:chat.ClientPetition.users)
return _internal_users();
}
inline void ClientPetition::unsafe_arena_set_allocated_users(
::chat::UserRequest* users) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(users_);
}
users_ = users;
if (users) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:chat.ClientPetition.users)
}
inline ::chat::UserRequest* ClientPetition::release_users() {
_has_bits_[0] &= ~0x00000002u;
::chat::UserRequest* temp = users_;
users_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::chat::UserRequest* ClientPetition::unsafe_arena_release_users() {
// @@protoc_insertion_point(field_release:chat.ClientPetition.users)
_has_bits_[0] &= ~0x00000002u;
::chat::UserRequest* temp = users_;
users_ = nullptr;
return temp;
}
inline ::chat::UserRequest* ClientPetition::_internal_mutable_users() {
_has_bits_[0] |= 0x00000002u;
if (users_ == nullptr) {
auto* p = CreateMaybeMessage<::chat::UserRequest>(GetArena());
users_ = p;
}
return users_;
}
inline ::chat::UserRequest* ClientPetition::mutable_users() {
// @@protoc_insertion_point(field_mutable:chat.ClientPetition.users)
return _internal_mutable_users();
}
inline void ClientPetition::set_allocated_users(::chat::UserRequest* users) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete users_;
}
if (users) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(users);
if (message_arena != submessage_arena) {
users = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, users, submessage_arena);
}
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
users_ = users;
// @@protoc_insertion_point(field_set_allocated:chat.ClientPetition.users)
}
// .chat.ChangeStatus change = 4;
inline bool ClientPetition::_internal_has_change() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
PROTOBUF_ASSUME(!value || change_ != nullptr);
return value;
}
inline bool ClientPetition::has_change() const {
return _internal_has_change();
}
inline void ClientPetition::clear_change() {
if (GetArena() == nullptr && change_ != nullptr) {
delete change_;
}
change_ = nullptr;
_has_bits_[0] &= ~0x00000004u;
}
inline const ::chat::ChangeStatus& ClientPetition::_internal_change() const {
const ::chat::ChangeStatus* p = change_;
return p != nullptr ? *p : reinterpret_cast<const ::chat::ChangeStatus&>(
::chat::_ChangeStatus_default_instance_);
}
inline const ::chat::ChangeStatus& ClientPetition::change() const {
// @@protoc_insertion_point(field_get:chat.ClientPetition.change)
return _internal_change();
}
inline void ClientPetition::unsafe_arena_set_allocated_change(
::chat::ChangeStatus* change) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(change_);
}
change_ = change;
if (change) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:chat.ClientPetition.change)
}
inline ::chat::ChangeStatus* ClientPetition::release_change() {
_has_bits_[0] &= ~0x00000004u;
::chat::ChangeStatus* temp = change_;
change_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::chat::ChangeStatus* ClientPetition::unsafe_arena_release_change() {
// @@protoc_insertion_point(field_release:chat.ClientPetition.change)
_has_bits_[0] &= ~0x00000004u;
::chat::ChangeStatus* temp = change_;
change_ = nullptr;
return temp;
}
inline ::chat::ChangeStatus* ClientPetition::_internal_mutable_change() {
_has_bits_[0] |= 0x00000004u;
if (change_ == nullptr) {
auto* p = CreateMaybeMessage<::chat::ChangeStatus>(GetArena());
change_ = p;
}
return change_;
}
inline ::chat::ChangeStatus* ClientPetition::mutable_change() {
// @@protoc_insertion_point(field_mutable:chat.ClientPetition.change)
return _internal_mutable_change();
}
inline void ClientPetition::set_allocated_change(::chat::ChangeStatus* change) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete change_;
}
if (change) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(change);
if (message_arena != submessage_arena) {
change = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, change, submessage_arena);
}
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
change_ = change;
// @@protoc_insertion_point(field_set_allocated:chat.ClientPetition.change)
}
// .chat.MessageCommunication messageCommunication = 5;
inline bool ClientPetition::_internal_has_messagecommunication() const {
bool value = (_has_bits_[0] & 0x00000008u) != 0;
PROTOBUF_ASSUME(!value || messagecommunication_ != nullptr);
return value;
}
inline bool ClientPetition::has_messagecommunication() const {
return _internal_has_messagecommunication();
}
inline void ClientPetition::clear_messagecommunication() {
if (GetArena() == nullptr && messagecommunication_ != nullptr) {
delete messagecommunication_;
}
messagecommunication_ = nullptr;
_has_bits_[0] &= ~0x00000008u;
}
inline const ::chat::MessageCommunication& ClientPetition::_internal_messagecommunication() const {
const ::chat::MessageCommunication* p = messagecommunication_;
return p != nullptr ? *p : reinterpret_cast<const ::chat::MessageCommunication&>(
::chat::_MessageCommunication_default_instance_);
}
inline const ::chat::MessageCommunication& ClientPetition::messagecommunication() const {
// @@protoc_insertion_point(field_get:chat.ClientPetition.messageCommunication)
return _internal_messagecommunication();
}
inline void ClientPetition::unsafe_arena_set_allocated_messagecommunication(
::chat::MessageCommunication* messagecommunication) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(messagecommunication_);
}
messagecommunication_ = messagecommunication;
if (messagecommunication) {
_has_bits_[0] |= 0x00000008u;
} else {
_has_bits_[0] &= ~0x00000008u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:chat.ClientPetition.messageCommunication)
}
inline ::chat::MessageCommunication* ClientPetition::release_messagecommunication() {
_has_bits_[0] &= ~0x00000008u;
::chat::MessageCommunication* temp = messagecommunication_;
messagecommunication_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::chat::MessageCommunication* ClientPetition::unsafe_arena_release_messagecommunication() {
// @@protoc_insertion_point(field_release:chat.ClientPetition.messageCommunication)
_has_bits_[0] &= ~0x00000008u;
::chat::MessageCommunication* temp = messagecommunication_;
messagecommunication_ = nullptr;
return temp;
}
inline ::chat::MessageCommunication* ClientPetition::_internal_mutable_messagecommunication() {
_has_bits_[0] |= 0x00000008u;
if (messagecommunication_ == nullptr) {
auto* p = CreateMaybeMessage<::chat::MessageCommunication>(GetArena());
messagecommunication_ = p;
}
return messagecommunication_;
}
inline ::chat::MessageCommunication* ClientPetition::mutable_messagecommunication() {
// @@protoc_insertion_point(field_mutable:chat.ClientPetition.messageCommunication)
return _internal_mutable_messagecommunication();
}
inline void ClientPetition::set_allocated_messagecommunication(::chat::MessageCommunication* messagecommunication) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete messagecommunication_;
}
if (messagecommunication) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(messagecommunication);
if (message_arena != submessage_arena) {
messagecommunication = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, messagecommunication, submessage_arena);
}
_has_bits_[0] |= 0x00000008u;
} else {
_has_bits_[0] &= ~0x00000008u;
}
messagecommunication_ = messagecommunication;
// @@protoc_insertion_point(field_set_allocated:chat.ClientPetition.messageCommunication)
}
// -------------------------------------------------------------------
// ServerResponse
// int32 option = 1;
inline bool ServerResponse::_internal_has_option() const {
bool value = (_has_bits_[0] & 0x00000020u) != 0;
return value;
}
inline bool ServerResponse::has_option() const {
return _internal_has_option();
}
inline void ServerResponse::clear_option() {
option_ = 0;
_has_bits_[0] &= ~0x00000020u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ServerResponse::_internal_option() const {
return option_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ServerResponse::option() const {
// @@protoc_insertion_point(field_get:chat.ServerResponse.option)
return _internal_option();
}
inline void ServerResponse::_internal_set_option(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000020u;
option_ = value;
}
inline void ServerResponse::set_option(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_option(value);
// @@protoc_insertion_point(field_set:chat.ServerResponse.option)
}
// int32 code = 2;
inline bool ServerResponse::_internal_has_code() const {
bool value = (_has_bits_[0] & 0x00000040u) != 0;
return value;
}
inline bool ServerResponse::has_code() const {
return _internal_has_code();
}
inline void ServerResponse::clear_code() {
code_ = 0;
_has_bits_[0] &= ~0x00000040u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ServerResponse::_internal_code() const {
return code_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ServerResponse::code() const {
// @@protoc_insertion_point(field_get:chat.ServerResponse.code)
return _internal_code();
}
inline void ServerResponse::_internal_set_code(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000040u;
code_ = value;
}
inline void ServerResponse::set_code(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_code(value);
// @@protoc_insertion_point(field_set:chat.ServerResponse.code)
}
// string serverMessage = 3;
inline bool ServerResponse::_internal_has_servermessage() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool ServerResponse::has_servermessage() const {
return _internal_has_servermessage();
}
inline void ServerResponse::clear_servermessage() {
servermessage_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& ServerResponse::servermessage() const {
// @@protoc_insertion_point(field_get:chat.ServerResponse.serverMessage)
return _internal_servermessage();
}
inline void ServerResponse::set_servermessage(const std::string& value) {
_internal_set_servermessage(value);
// @@protoc_insertion_point(field_set:chat.ServerResponse.serverMessage)
}
inline std::string* ServerResponse::mutable_servermessage() {
// @@protoc_insertion_point(field_mutable:chat.ServerResponse.serverMessage)
return _internal_mutable_servermessage();
}
inline const std::string& ServerResponse::_internal_servermessage() const {
return servermessage_.Get();
}
inline void ServerResponse::_internal_set_servermessage(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
servermessage_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void ServerResponse::set_servermessage(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
servermessage_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:chat.ServerResponse.serverMessage)
}
inline void ServerResponse::set_servermessage(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
servermessage_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:chat.ServerResponse.serverMessage)
}
inline void ServerResponse::set_servermessage(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
servermessage_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:chat.ServerResponse.serverMessage)
}
inline std::string* ServerResponse::_internal_mutable_servermessage() {
_has_bits_[0] |= 0x00000001u;
return servermessage_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* ServerResponse::release_servermessage() {
// @@protoc_insertion_point(field_release:chat.ServerResponse.serverMessage)
if (!_internal_has_servermessage()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return servermessage_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void ServerResponse::set_allocated_servermessage(std::string* servermessage) {
if (servermessage != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
servermessage_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), servermessage,
GetArena());
// @@protoc_insertion_point(field_set_allocated:chat.ServerResponse.serverMessage)
}
// .chat.ConnectedUsersResponse connectedUsers = 4;
inline bool ServerResponse::_internal_has_connectedusers() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
PROTOBUF_ASSUME(!value || connectedusers_ != nullptr);
return value;
}
inline bool ServerResponse::has_connectedusers() const {
return _internal_has_connectedusers();
}
inline void ServerResponse::clear_connectedusers() {
if (GetArena() == nullptr && connectedusers_ != nullptr) {
delete connectedusers_;
}
connectedusers_ = nullptr;
_has_bits_[0] &= ~0x00000002u;
}
inline const ::chat::ConnectedUsersResponse& ServerResponse::_internal_connectedusers() const {
const ::chat::ConnectedUsersResponse* p = connectedusers_;
return p != nullptr ? *p : reinterpret_cast<const ::chat::ConnectedUsersResponse&>(
::chat::_ConnectedUsersResponse_default_instance_);
}
inline const ::chat::ConnectedUsersResponse& ServerResponse::connectedusers() const {
// @@protoc_insertion_point(field_get:chat.ServerResponse.connectedUsers)
return _internal_connectedusers();
}
inline void ServerResponse::unsafe_arena_set_allocated_connectedusers(
::chat::ConnectedUsersResponse* connectedusers) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(connectedusers_);
}
connectedusers_ = connectedusers;
if (connectedusers) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:chat.ServerResponse.connectedUsers)
}
inline ::chat::ConnectedUsersResponse* ServerResponse::release_connectedusers() {
_has_bits_[0] &= ~0x00000002u;
::chat::ConnectedUsersResponse* temp = connectedusers_;
connectedusers_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::chat::ConnectedUsersResponse* ServerResponse::unsafe_arena_release_connectedusers() {
// @@protoc_insertion_point(field_release:chat.ServerResponse.connectedUsers)
_has_bits_[0] &= ~0x00000002u;
::chat::ConnectedUsersResponse* temp = connectedusers_;
connectedusers_ = nullptr;
return temp;
}
inline ::chat::ConnectedUsersResponse* ServerResponse::_internal_mutable_connectedusers() {
_has_bits_[0] |= 0x00000002u;
if (connectedusers_ == nullptr) {
auto* p = CreateMaybeMessage<::chat::ConnectedUsersResponse>(GetArena());
connectedusers_ = p;
}
return connectedusers_;
}
inline ::chat::ConnectedUsersResponse* ServerResponse::mutable_connectedusers() {
// @@protoc_insertion_point(field_mutable:chat.ServerResponse.connectedUsers)
return _internal_mutable_connectedusers();
}
inline void ServerResponse::set_allocated_connectedusers(::chat::ConnectedUsersResponse* connectedusers) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete connectedusers_;
}
if (connectedusers) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(connectedusers);
if (message_arena != submessage_arena) {
connectedusers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, connectedusers, submessage_arena);
}
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
connectedusers_ = connectedusers;
// @@protoc_insertion_point(field_set_allocated:chat.ServerResponse.connectedUsers)
}
// .chat.MessageCommunication messageCommunication = 5;
inline bool ServerResponse::_internal_has_messagecommunication() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
PROTOBUF_ASSUME(!value || messagecommunication_ != nullptr);
return value;
}
inline bool ServerResponse::has_messagecommunication() const {
return _internal_has_messagecommunication();
}
inline void ServerResponse::clear_messagecommunication() {
if (GetArena() == nullptr && messagecommunication_ != nullptr) {
delete messagecommunication_;
}
messagecommunication_ = nullptr;
_has_bits_[0] &= ~0x00000004u;
}
inline const ::chat::MessageCommunication& ServerResponse::_internal_messagecommunication() const {
const ::chat::MessageCommunication* p = messagecommunication_;
return p != nullptr ? *p : reinterpret_cast<const ::chat::MessageCommunication&>(
::chat::_MessageCommunication_default_instance_);
}
inline const ::chat::MessageCommunication& ServerResponse::messagecommunication() const {
// @@protoc_insertion_point(field_get:chat.ServerResponse.messageCommunication)
return _internal_messagecommunication();
}
inline void ServerResponse::unsafe_arena_set_allocated_messagecommunication(
::chat::MessageCommunication* messagecommunication) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(messagecommunication_);
}
messagecommunication_ = messagecommunication;
if (messagecommunication) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:chat.ServerResponse.messageCommunication)
}
inline ::chat::MessageCommunication* ServerResponse::release_messagecommunication() {
_has_bits_[0] &= ~0x00000004u;
::chat::MessageCommunication* temp = messagecommunication_;
messagecommunication_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::chat::MessageCommunication* ServerResponse::unsafe_arena_release_messagecommunication() {
// @@protoc_insertion_point(field_release:chat.ServerResponse.messageCommunication)
_has_bits_[0] &= ~0x00000004u;
::chat::MessageCommunication* temp = messagecommunication_;
messagecommunication_ = nullptr;
return temp;
}
inline ::chat::MessageCommunication* ServerResponse::_internal_mutable_messagecommunication() {
_has_bits_[0] |= 0x00000004u;
if (messagecommunication_ == nullptr) {
auto* p = CreateMaybeMessage<::chat::MessageCommunication>(GetArena());
messagecommunication_ = p;
}
return messagecommunication_;
}
inline ::chat::MessageCommunication* ServerResponse::mutable_messagecommunication() {
// @@protoc_insertion_point(field_mutable:chat.ServerResponse.messageCommunication)
return _internal_mutable_messagecommunication();
}
inline void ServerResponse::set_allocated_messagecommunication(::chat::MessageCommunication* messagecommunication) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete messagecommunication_;
}
if (messagecommunication) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(messagecommunication);
if (message_arena != submessage_arena) {
messagecommunication = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, messagecommunication, submessage_arena);
}
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
messagecommunication_ = messagecommunication;
// @@protoc_insertion_point(field_set_allocated:chat.ServerResponse.messageCommunication)
}
// .chat.UserInfo userInfoResponse = 6;
inline bool ServerResponse::_internal_has_userinforesponse() const {
bool value = (_has_bits_[0] & 0x00000008u) != 0;
PROTOBUF_ASSUME(!value || userinforesponse_ != nullptr);
return value;
}
inline bool ServerResponse::has_userinforesponse() const {
return _internal_has_userinforesponse();
}
inline void ServerResponse::clear_userinforesponse() {
if (GetArena() == nullptr && userinforesponse_ != nullptr) {
delete userinforesponse_;
}
userinforesponse_ = nullptr;
_has_bits_[0] &= ~0x00000008u;
}
inline const ::chat::UserInfo& ServerResponse::_internal_userinforesponse() const {
const ::chat::UserInfo* p = userinforesponse_;
return p != nullptr ? *p : reinterpret_cast<const ::chat::UserInfo&>(
::chat::_UserInfo_default_instance_);
}
inline const ::chat::UserInfo& ServerResponse::userinforesponse() const {
// @@protoc_insertion_point(field_get:chat.ServerResponse.userInfoResponse)
return _internal_userinforesponse();
}
inline void ServerResponse::unsafe_arena_set_allocated_userinforesponse(
::chat::UserInfo* userinforesponse) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(userinforesponse_);
}
userinforesponse_ = userinforesponse;
if (userinforesponse) {
_has_bits_[0] |= 0x00000008u;
} else {
_has_bits_[0] &= ~0x00000008u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:chat.ServerResponse.userInfoResponse)
}
inline ::chat::UserInfo* ServerResponse::release_userinforesponse() {
_has_bits_[0] &= ~0x00000008u;
::chat::UserInfo* temp = userinforesponse_;
userinforesponse_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::chat::UserInfo* ServerResponse::unsafe_arena_release_userinforesponse() {
// @@protoc_insertion_point(field_release:chat.ServerResponse.userInfoResponse)
_has_bits_[0] &= ~0x00000008u;
::chat::UserInfo* temp = userinforesponse_;
userinforesponse_ = nullptr;
return temp;
}
inline ::chat::UserInfo* ServerResponse::_internal_mutable_userinforesponse() {
_has_bits_[0] |= 0x00000008u;
if (userinforesponse_ == nullptr) {
auto* p = CreateMaybeMessage<::chat::UserInfo>(GetArena());
userinforesponse_ = p;
}
return userinforesponse_;
}
inline ::chat::UserInfo* ServerResponse::mutable_userinforesponse() {
// @@protoc_insertion_point(field_mutable:chat.ServerResponse.userInfoResponse)
return _internal_mutable_userinforesponse();
}
inline void ServerResponse::set_allocated_userinforesponse(::chat::UserInfo* userinforesponse) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete userinforesponse_;
}
if (userinforesponse) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(userinforesponse);
if (message_arena != submessage_arena) {
userinforesponse = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, userinforesponse, submessage_arena);
}
_has_bits_[0] |= 0x00000008u;
} else {
_has_bits_[0] &= ~0x00000008u;
}
userinforesponse_ = userinforesponse;
// @@protoc_insertion_point(field_set_allocated:chat.ServerResponse.userInfoResponse)
}
// .chat.ChangeStatus change = 7;
inline bool ServerResponse::_internal_has_change() const {
bool value = (_has_bits_[0] & 0x00000010u) != 0;
PROTOBUF_ASSUME(!value || change_ != nullptr);
return value;
}
inline bool ServerResponse::has_change() const {
return _internal_has_change();
}
inline void ServerResponse::clear_change() {
if (GetArena() == nullptr && change_ != nullptr) {
delete change_;
}
change_ = nullptr;
_has_bits_[0] &= ~0x00000010u;
}
inline const ::chat::ChangeStatus& ServerResponse::_internal_change() const {
const ::chat::ChangeStatus* p = change_;
return p != nullptr ? *p : reinterpret_cast<const ::chat::ChangeStatus&>(
::chat::_ChangeStatus_default_instance_);
}
inline const ::chat::ChangeStatus& ServerResponse::change() const {
// @@protoc_insertion_point(field_get:chat.ServerResponse.change)
return _internal_change();
}
inline void ServerResponse::unsafe_arena_set_allocated_change(
::chat::ChangeStatus* change) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(change_);
}
change_ = change;
if (change) {
_has_bits_[0] |= 0x00000010u;
} else {
_has_bits_[0] &= ~0x00000010u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:chat.ServerResponse.change)
}
inline ::chat::ChangeStatus* ServerResponse::release_change() {
_has_bits_[0] &= ~0x00000010u;
::chat::ChangeStatus* temp = change_;
change_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::chat::ChangeStatus* ServerResponse::unsafe_arena_release_change() {
// @@protoc_insertion_point(field_release:chat.ServerResponse.change)
_has_bits_[0] &= ~0x00000010u;
::chat::ChangeStatus* temp = change_;
change_ = nullptr;
return temp;
}
inline ::chat::ChangeStatus* ServerResponse::_internal_mutable_change() {
_has_bits_[0] |= 0x00000010u;
if (change_ == nullptr) {
auto* p = CreateMaybeMessage<::chat::ChangeStatus>(GetArena());
change_ = p;
}
return change_;
}
inline ::chat::ChangeStatus* ServerResponse::mutable_change() {
// @@protoc_insertion_point(field_mutable:chat.ServerResponse.change)
return _internal_mutable_change();
}
inline void ServerResponse::set_allocated_change(::chat::ChangeStatus* change) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete change_;
}
if (change) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(change);
if (message_arena != submessage_arena) {
change = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, change, submessage_arena);
}
_has_bits_[0] |= 0x00000010u;
} else {
_has_bits_[0] &= ~0x00000010u;
}
change_ = change;
// @@protoc_insertion_point(field_set_allocated:chat.ServerResponse.change)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace chat
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_petition_2eproto
| 37.596538 | 122 | 0.733304 | [
"object"
] |
71321e92a6edaad2f46d79953514fd4d96303bc4 | 443 | c | C | d/avatars/kelemvor/mysteryegg.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/avatars/kelemvor/mysteryegg.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | null | null | null | d/avatars/kelemvor/mysteryegg.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
inherit OBJECT;
void create(){
::create();
set_name("A mysterious egg");
set_id(({ "egg" }));
set_short("A mysterious looking egg. It is about the size of an ostritch egg, and has dark purple spots on it.");
set_obvious_short("A large and mysterious egg");
set_long(
@AVATAR
A mysterious looking egg. It is about the size of an ostritch egg, and has dark purple spots on it.
AVATAR
);
set_weight(1);
set_value(0);
} | 24.611111 | 114 | 0.708804 | [
"object"
] |
71351b6df93a14a01e8cf23004fb112b289b02a1 | 1,187 | h | C | src/sort/sort.h | ryukinix/data-structures-ufc | 983e323e2080089edb335517b01384769d6d2fb2 | [
"MIT"
] | 6 | 2017-09-18T22:22:01.000Z | 2021-12-01T20:20:18.000Z | src/sort/sort.h | ryukinix/data-structures-ufc | 983e323e2080089edb335517b01384769d6d2fb2 | [
"MIT"
] | 11 | 2019-03-13T01:15:38.000Z | 2019-03-21T22:52:35.000Z | src/sort/sort.h | ryukinix/data-structures-ufc | 983e323e2080089edb335517b01384769d6d2fb2 | [
"MIT"
] | null | null | null | /**
* ================================================
*
* Copyright 2017 Manoel Vilela
*
* Author: Manoel Vilela
* Contact: manoel_vilela@engineer.com
* Organization: UFC
*
* ===============================================
*/
#ifndef SORT_H
#define SORT_H
#ifndef Type
#define Type int
#endif
#ifndef TypeFormat
#define TypeFormat "%d"
#endif
/**********************/
/* SORTING ALGORITHMS */
/**********************/
/* Apply BubbleSort Algorithm on the v */
void bubblesort(Type *v, int n);
/* Apply the InsertionSort Algorithm on the v */
void insertionsort(Type *v, int n);
/* Apply the MergeSort Algorithm on the v */
void mergesort(Type *v, int n);
/* Apply the QuickSort Algorithm on the v */
void quicksort(Type *v, int n);
/* Apply the HeapSort Algorithm on the v */
void heapsort(Type *v, int n);
/*********/
/* UTILS */
/*********/
/* Print the v in a pretty format */
void print_vector(Type *v, int n);
/* Swap the values between e1 and e2 */
void swap(Type *e1, Type *e2);
/* Check if the vector v is sorted */
int check_sorted(Type *v, int n);
/* Return a random_vector with n values */
Type* random_vector(int n);
#endif
| 19.783333 | 51 | 0.571188 | [
"vector"
] |
7146f08a913186aea6b8c5604e542e8efd297eab | 816 | h | C | LoveLiveWallpaper/src/Vector.h | Juvwxyz/LoveLiveWallpaper | a0eeac941b5ccd53af538192cb92b7df049839c4 | [
"MIT"
] | 2 | 2020-05-09T00:13:06.000Z | 2020-05-25T05:49:40.000Z | LoveLiveWallpaper/src/Vector.h | Juvwxyz/LoveLiveWallpaper | a0eeac941b5ccd53af538192cb92b7df049839c4 | [
"MIT"
] | null | null | null | LoveLiveWallpaper/src/Vector.h | Juvwxyz/LoveLiveWallpaper | a0eeac941b5ccd53af538192cb92b7df049839c4 | [
"MIT"
] | 1 | 2020-05-25T05:49:44.000Z | 2020-05-25T05:49:44.000Z | #pragma once
#include <DirectXMath.h>
namespace LLWP
{
class Matrix;
class Vector
{
public :
Vector(float a = 0, float b = 0, float c = 0);
Vector(DirectX::FXMVECTOR& m);
float x() const;
float y() const;
float z() const;
operator DirectX::XMVECTOR() const;
Vector operator+(const Vector& right);
Vector& operator+=(const Vector& d);
Vector operator*(const Matrix& m);
Vector operator*(float f);
Vector operator*(const Vector& right);
Vector& operator*=(float s);
Vector& operator*=(const Matrix& m);
Vector operator-();
~Vector();
private:
DirectX::XMVECTOR vec;
};
Vector operator/(float f, Vector vec);
Vector operator/(Vector vec, float f);
} | 20.923077 | 54 | 0.566176 | [
"vector"
] |
512dcba66212e9992c3162b647fd74ae7238974f | 13,232 | c | C | dsp/tskrgb2ycbcr-dsp.c | allangj/rgb2ycbcr-dsp | 0f631084775595acc00b9d25d2f645dc78dabc10 | [
"Unlicense"
] | null | null | null | dsp/tskrgb2ycbcr-dsp.c | allangj/rgb2ycbcr-dsp | 0f631084775595acc00b9d25d2f645dc78dabc10 | [
"Unlicense"
] | null | null | null | dsp/tskrgb2ycbcr-dsp.c | allangj/rgb2ycbcr-dsp | 0f631084775595acc00b9d25d2f645dc78dabc10 | [
"Unlicense"
] | null | null | null | /** ============================================================================
* @file tskrgb2ycbcr-dsp.c
*
* @path $(DSPLINK)/dsp/src/samples/rgb2ycbcr-dsp/
*
* @desc This is simple TSK based application that uses SIO interface to
* implement rgb2ycbcr-dsp for GPP.
*
* @ver 1.65.00.03
* ============================================================================
* Copyright (C) 2015, Allan Granados
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
* ============================================================================
*/
/* ----------------------------------- DSP/BIOS Headers */
#include <std.h>
#include <log.h>
#include <swi.h>
#include <sys.h>
#include <sio.h>
#if defined (DSP_BOOTMODE_NOBOOT)
#include <dio.h>
#include <iom.h>
#endif
#include <tsk.h>
/* ----------------------------------- DSP/BIOS LINK Headers */
#include <failure.h>
#include <dsplink.h>
#include <platform.h>
#if defined (DSP_BOOTMODE_NOBOOT)
#include <sma_pool.h>
#include <zcpy_data.h>
#endif
/* ----------------------------------- Sample Headers */
#include <rgb2ycbcr-dsp_config.h>
#include <tskrgb2ycbcr-dsp.h>
/** ============================================================================
* @const DXY or CZ
*
* @desc Values for the D and C matrix used for color space transformation
* D = [0.257 0.502 0.098;
* -.148 -0.289 0.438;
* 0.438 -0.366 -0.071];
* C = [16; 128; 128];
* ============================================================================
*/
#define D11 257
#define D12 502
#define D13 98
#define D21 -148
#define D22 -289
#define D23 438
#define D31 438
#define D32 -366
#define D33 -71
#define C1 16
#define C2 128
#define C3 128
/** ============================================================================
* @const FILEID
*
* @desc FILEID is used by SET_FAILURE_REASON macro.
* ============================================================================
*/
#define FILEID FID_APP_C
/** ============================================================================
* @name xferBufSize
*
* @desc Size of the buffer size for TSK.
* ============================================================================
*/
extern Uint32 xferBufSize ;
/** ============================================================================
* @name numTransfers
*
* @desc Iterations of data transfer to be done by the application.
* A value of 0 in numTransfers implies infinite iterations.
* ============================================================================
*/
extern Uint16 numTransfers ;
#if defined (DSP_BOOTMODE_NOBOOT)
/** ============================================================================
* @name smaPoolObj
*
* @desc Global object for pool parameters for the dynamic POOL_open call
* ============================================================================
*/
SMAPOOL_Params smaPoolObj ;
extern IOM_Fxns ZCPYDATA_FXNS ;
extern Void ZCPYDATA_init (Void) ;
DIO_Params dioAttrs = {
"/dsplink",
NULL
} ;
DEV_Attrs devAttrs = {
0, /* devId */
0, /* dsplink deviceParams */
DEV_IOMTYPE, /* dsplink driver type */
0 /* dsplink devp */
} ;
DEV_Attrs dioDevAttrs = {
0, /* devId */
&dioAttrs, /* DIO deviceParams */
DEV_SIOTYPE, /* DIO type */
0 /* devp */
} ;
#endif
/** ============================================================================
* @func TSKRGB2YCBCR_DSP_create
*
* @desc Create phase function for the TSKRGB2YCBCR_DSP application. Initializes the
* TSKRGB2YCBCR_DSP_TransferInfo structure with the information that will be
* used by the other phases of the application.
*
* @modif None.
* ============================================================================
*/
Int TSKRGB2YCBCR_DSP_create (TSKRGB2YCBCR_DSP_TransferInfo ** infoPtr)
{
Int status = SYS_OK ;
TSKRGB2YCBCR_DSP_TransferInfo * info = NULL ;
SIO_Attrs attrs ;
Uint16 i ;
Uint16 j ;
#if defined (DSP_BOOTMODE_NOBOOT)
POOL_Obj poolObj ;
smaPoolObj.poolId = 0;
smaPoolObj.exactMatchReq = TRUE ;
poolObj.initFxn = SMAPOOL_init ;
poolObj.fxns = (POOL_Fxns *) &SMAPOOL_FXNS ;
poolObj.params = &(smaPoolObj) ;
poolObj.object = NULL ;
status = POOL_open (0, &poolObj) ;
/* Create IOM driver dynamically */
status = DEV_createDevice("/dsplink", &ZCPYDATA_FXNS, (Fxn) &ZCPYDATA_init, &devAttrs) ;
/* Create DIO adapter dynamically */
status = DEV_createDevice("/dio_dsplink", &DIO_tskDynamicFxns, NULL, &dioDevAttrs);
#endif
/* Allocate TSKRGB2YCBCR_DSP_TransferInfo structure that will be initialized
* and passed to other phases of the application
*/
*infoPtr = MEM_calloc (DSPLINK_SEGID,
sizeof (TSKRGB2YCBCR_DSP_TransferInfo),
DSPLINK_BUF_ALIGN) ;
if (*infoPtr == NULL) {
status = SYS_EALLOC ;
}
else {
info = *infoPtr ;
}
if (status == SYS_OK) {
/* Filling up the transfer info structure */
info->numTransfers = numTransfers ;
info->bufferSize = xferBufSize ;
info->numBuffers = TSK_NUM_BUFFERS ;
/* Attributes for the stream creation */
attrs = SIO_ATTRS ;
attrs.nbufs = info->numBuffers ;
attrs.segid = DSPLINK_SEGID ;
attrs.align = DSPLINK_BUF_ALIGN ;
attrs.flush = TRUE ;
attrs.model = SIO_ISSUERECLAIM ;
attrs.timeout = SYS_FOREVER ;
/* Creating input and output streams */
info->inputStream = SIO_create (INPUT_CHANNEL,
SIO_INPUT,
info->bufferSize,
&attrs) ;
info->outputStream = SIO_create (OUTPUT_CHANNEL,
SIO_OUTPUT,
info->bufferSize,
&attrs) ;
if ( (info->inputStream == NULL)
|| (info->outputStream == NULL)) {
status = SYS_EALLOC ;
}
}
/* Allocating all the buffers that will be used in the transfer */
if (status == SYS_OK) {
for (i = 0 ; (i < info->numBuffers) && (status == SYS_OK) ; i++) {
status = POOL_alloc (SAMPLE_POOL_ID,
(Ptr *) &(info->buffers [i]),
info->bufferSize) ;
if (status != SYS_OK) {
for (j = 0 ; j < i ; j++) {
POOL_free (SAMPLE_POOL_ID,
info->buffers [i],
info->bufferSize) ;
info->buffers [j] = NULL ;
}
status = SYS_EALLOC ;
}
}
}
return status ;
}
/** ============================================================================
* @func TSKRGB2YCBCR_DSP_execute
*
* @desc Execute phase function for the TSKRGB2YCBCR_DSP application. Application
* receives the data from the input channel and sends the same data
* back on output channel. Channel numbers can be configured through
* header file.
*
* @modif None.
* ============================================================================
*/
Int TSKRGB2YCBCR_DSP_execute(TSKRGB2YCBCR_DSP_TransferInfo * info)
{
Int status = SYS_OK ;
Char * buffer = info->buffers [0] ;
Arg arg = 0 ;
Uint32 i ;
Int nmadus ;
Uint32 y,cb,cr;
/* Execute the rgb2ycbcr-dsp for configured number of transfers
* A value of 0 in numTransfers implies infinite iterations
*/
for (i = 0 ;
( ((info->numTransfers == 0) || (i < info->numTransfers))
&& (status == SYS_OK)) ;
i++) {
/* Receive a data buffer from GPP */
status = SIO_issue(info->inputStream,
buffer,
info->bufferSize,
arg) ;
if (status == SYS_OK) {
nmadus = SIO_reclaim (info->inputStream,
(Ptr *) &buffer,
&arg) ;
if (nmadus < 0) {
status = -nmadus ;
SET_FAILURE_REASON (status) ;
}
else {
info->receivedSize = nmadus ;
}
}
else {
SET_FAILURE_REASON(status);
}
/* Do processing on this buffer */
if (status == SYS_OK) {
/* Add code to process the buffer here*/
for (i = 0 ; (i+3) <= info->receivedSize ; i = i+3) {
y = (((D11 * info->buffers[0][i]) + (D12 * info->buffers[0][i+1]) + (D13 * info->buffers[0][i+2])) / 100) + C1;
cb = (((D21 * info->buffers[0][i]) + (D22 * info->buffers[0][i+1]) + (D23 * info->buffers[0][i+2])) / 100) + C2;
cr = (((D31 * info->buffers[0][i]) + (D32 * info->buffers[0][i+1]) + (D33 * info->buffers[0][i+2])) / 100) + C3;
info->buffers[0][i] = y;
info->buffers[0][i+1] = cb;
info->buffers[0][i+2] = cr;
}
}
/* Send the processed buffer back to GPP */
if (status == SYS_OK) {
status = SIO_issue(info->outputStream,
buffer,
info->receivedSize,
arg);
if (status == SYS_OK) {
nmadus = SIO_reclaim (info->outputStream,
(Ptr *) &(buffer),
&arg) ;
if (nmadus < 0) {
status = -nmadus ;
SET_FAILURE_REASON (status) ;
}
}
else {
SET_FAILURE_REASON (status) ;
}
}
}
return status ;
}
/** ============================================================================
* @func TSKRGB2YCBCR_DSP_delete
*
* @desc Delete phase function for the TSKRGB2YCBCR_DSP application. It deallocates
* all the resources of allocated during create phase of the
* application.
*
* @modif None.
* ============================================================================
*/
Int TSKRGB2YCBCR_DSP_delete (TSKRGB2YCBCR_DSP_TransferInfo * info)
{
Int status = SYS_OK ;
Uint16 tmpStatus = SYS_OK ;
Bool freeStatus = FALSE ;
Uint16 j ;
/* Delete input stream */
if (info->inputStream != NULL) {
status = SIO_delete (info->inputStream) ;
if (status != SYS_OK) {
SET_FAILURE_REASON (status) ;
}
}
/* Delete output stream */
if (info->outputStream != NULL) {
tmpStatus = SIO_delete(info->outputStream);
if ((status == SYS_OK) && (tmpStatus != SYS_OK)) {
status = tmpStatus ;
SET_FAILURE_REASON (status) ;
}
}
/* Delete the buffers */
if (info->numBuffers > 0) {
for (j = 0 ;
(j < info->numBuffers) && (info->buffers [j] != NULL) ;
j++) {
POOL_free (SAMPLE_POOL_ID, info->buffers [j], info->bufferSize) ;
}
}
/* Free the info structure */
freeStatus = MEM_free (DSPLINK_SEGID, info, sizeof (TSKRGB2YCBCR_DSP_TransferInfo)) ;
if ((status == SYS_OK) && (freeStatus != TRUE)) {
status = SYS_EFREE ;
SET_FAILURE_REASON (status) ;
}
return status ;
}
| 34.279793 | 127 | 0.477177 | [
"object",
"model"
] |
512f73daad196e69c872ade02edd842470e024e1 | 2,139 | h | C | NesEmulator/Cpu.h | kevlu123/NesEmulator | 43437f56d15d57634f1c6364c7b6a51905b4b2cb | [
"MIT"
] | null | null | null | NesEmulator/Cpu.h | kevlu123/NesEmulator | 43437f56d15d57634f1c6364c7b6a51905b4b2cb | [
"MIT"
] | null | null | null | NesEmulator/Cpu.h | kevlu123/NesEmulator | 43437f56d15d57634f1c6364c7b6a51905b4b2cb | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "SaveStateUtil.h"
class Nes;
class Cpu
{
friend class Emulator;
public:
Cpu(Nes& nes);
Cpu(Nes& nes, Snapshot& bytes);
Cpu(const Cpu&) = delete;
Cpu& operator=(const Cpu&) = delete;
void Clock();
void Reset();
void Irq();
void Nmi();
void ClockInstruction();
bool InstructionComplete() const;
Snapshot SaveState() const;
private:
Nes& nes;
uint8_t opcode = 0;
uint8_t data = 0;
uint16_t addr = 0;
int cyclesToNextInstruction = 0;
void ReadAddr();
void WriteStack(uint8_t data);
uint8_t ReadStack();
static bool PageChanged(uint16_t addr0, uint16_t addr1);
static uint16_t JoinBytes(uint8_t lo, uint8_t hi);
using AddrModeFn = bool(void);
using OpcodeFn = bool(void);
using AddrMode = bool(Cpu::*)();
using Opcode = bool(Cpu::*)();
static struct Instruction
{
std::string opname;
Opcode op = nullptr;
std::string addrname;
AddrMode addrmode = nullptr;
int cycles = 0;
int bytes = 0;
Instruction() = default;
Instruction(
std::string opname,
Opcode op,
std::string addrname,
AddrMode addrmode,
int cycles
);
Instruction& operator=(const Instruction&) = default;
} instructions[256];
// Registers
uint8_t ra = 0;
uint8_t rx = 0;
uint8_t ry = 0;
uint8_t sp = 0;
uint16_t pc = 0;
union
{
struct
{
bool c : 1;
bool z : 1;
bool i : 1;
bool d : 1;
bool b : 1;
bool u : 1;
bool v : 1;
bool n : 1;
};
uint8_t reg = 0;
} status;
// Addressing modes
AddrModeFn IMP, IMM, ACC;
AddrModeFn ABS, ABX, ABY;
AddrModeFn ZRP, ZPX, ZPY;
AddrModeFn IDX, IDY, IND;
AddrModeFn REL;
// Opcodes
OpcodeFn ADC, AND, ASL, BCC, BCS, BEQ, BIT, BMI, BNE, BPL, BRK, BVC, BVS, CLC;
OpcodeFn CLD, CLI, CLV, CMP, CPX, CPY, DEC, DEX, DEY, EOR, INC, INX, INY, JMP;
OpcodeFn JSR, LDA, LDX, LDY, LSR, NOP, ORA, PHA, PHP, PLA, PLP, ROL, ROR, RTI;
OpcodeFn RTS, SBC, SEC, SED, SEI, STA, STX, STY, TAX, TAY, TSX, TXA, TXS, TYA;
// Illegal opcodes
OpcodeFn AAC, SAX, ARR, ASR, ATX, AXA, AXS, DCP, DOP, ISB, KIL;
OpcodeFn LAR, LAX, RLA, RRA, SLO, SRE, SXA, SYA, TOP, XAA, XAS;
};
| 21.606061 | 79 | 0.652174 | [
"vector"
] |
51502e2d1590308de662cdb5112237de4068f37c | 5,840 | h | C | direction_constraint.h | fire/ewbik | e783bbbc721b8519efce4fcf4519d1cf85262bdf | [
"MIT"
] | null | null | null | direction_constraint.h | fire/ewbik | e783bbbc721b8519efce4fcf4519d1cf85262bdf | [
"MIT"
] | null | null | null | direction_constraint.h | fire/ewbik | e783bbbc721b8519efce4fcf4519d1cf85262bdf | [
"MIT"
] | null | null | null | /*************************************************************************/
/* ik_direction_limi.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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. */
/*************************************************************************/
#ifndef GODOT_ANIMATION_UNIFIED_BEZIERS_IK_DIRECTION_LIMIT_H
#define GODOT_ANIMATION_UNIFIED_BEZIERS_IK_DIRECTION_LIMIT_H
#include "core/object/reference.h"
#include "core/io/resource.h"
#include "core/string/string_name.h"
#include "core/string/ustring.h"
#include "core/templates/list.h"
#include "core/variant/variant.h"
#include "core/object/object.h"
#include "core/object/reference.h"
#include "core/templates/hash_map.h"
#include "core/templates/set.h"
#include "core/os/memory.h"
#include "core/os/rw_lock.h"
#include "core/object/class_db.h"
#include "core/typedefs.h"
#include "core/error/error_macros.h"
#include "kusudama_constraint.h"
class KusudamaConstraint;
class DirectionConstraint : public Resource {
GDCLASS(DirectionConstraint, Resource);
private:
/**
* a triangle where the [1] is the tangentCircleNext_n, and [0] and [2]
* are the points at which the tangent circle intersects this directional limit and the
* next directional limit
*/
Vector<Vector3> first_triangle_next;
Vector<Vector3> second_triangle_next;
//radius stored as cosine to save on the acos call necessary for angleBetween.
float radius = 1.0f;
float radius_cosine = Math::cos(radius);
Ref<KusudamaConstraint> parent_kusudama = nullptr;
Vector3 tangent_circle_center_next_1;
Vector3 tangent_circle_center_next_2;
float tangent_circle_radius_next = 0.0f;
float tangent_circle_radius_next_cos = 0.0f;
Vector3 tangent_circle_center_previous_1;
Vector3 tangent_circle_center_previous_2;
float tangent_circle_radius_previous = 0.0f;
float tangent_circle_radius_previous_cos = 0.0f;
void compute_triangles(Ref<DirectionConstraint> p_next);
protected:
static void _bind_methods();
public:
~DirectionConstraint() {
}
Vector3 get_on_great_tangent_triangle(Ref<DirectionConstraint> next, Vector3 input) const;
/**
* returns Vector3(0, 0, 0) if no rectification is required.
* @param input
* @param inBounds
* @return
*/
Vector3 closest_to_cone(Vector3 input, Vector<bool> inBounds) const;
/**
* returns Vector3(0, 0, 0) if no rectification is required.
* @param next
* @param input
* @param inBounds
* @return
*/
Vector3 closest_point_on_closest_cone(Ref<DirectionConstraint> next, Vector3 input, Vector<bool> inBounds) const;
/**
*
* @param next
* @param input
* @return Vector3(0, 0, 0) if the input point is already in bounds, or the point's rectified position
* if the point was out of bounds.
*/
Vector3 get_closest_collision(Ref<DirectionConstraint> next, Vector3 input) const;
/**
*
* @param next
* @param input
* @param collisionPoint will be set to the rectified (if necessary) position of the input after accounting for collisions
* @return
*/
bool in_bounds_from_this_to_next(Ref<DirectionConstraint> next, Vector3 input, Vector3 collisionPoint) const;
Vector3 control_point;
Vector3 radial_point;
Vector3 get_on_path_sequence(Ref<DirectionConstraint> p_next, Vector3 p_input) const;
Vector3 closest_directional_limit(Ref<DirectionConstraint> p_next, Vector3 p_input) const;
Vector3 get_closest_path_point(Ref<DirectionConstraint> p_next, Vector3 p_input) const;
float get_radius() const;
float get_radius_cosine() const;
Vector3 get_control_point() const;
Vector3 get_orthogonal(Vector3 p_vec);
DirectionConstraint() {}
void set_control_point(Vector3 p_control_point);
void update_tangent_handles(Ref<DirectionConstraint> p_next);
void initialize(Vector3 p_location, real_t p_rad, Ref<KusudamaConstraint> p_attached_to);
void set_radius(real_t p_radius);
};
#endif //GODOT_ANIMATION_UNIFIED_BEZIERS_IK_DIRECTION_LIMIT_H
| 41.714286 | 123 | 0.653596 | [
"object",
"vector"
] |
515b2d0550fb3d23dc30c9e8e5d1ed48ddae605f | 3,581 | c | C | ImperasLib/source/mips.ovpworld.org/peripheral/SmartLoaderLinux/1.0/pse/pse.igen.c | emanuellucas2/OVPsimProject | 6c9f5bfaaa135fa63d63746bacf5759c6d6c0e9e | [
"TCL"
] | null | null | null | ImperasLib/source/mips.ovpworld.org/peripheral/SmartLoaderLinux/1.0/pse/pse.igen.c | emanuellucas2/OVPsimProject | 6c9f5bfaaa135fa63d63746bacf5759c6d6c0e9e | [
"TCL"
] | null | null | null | ImperasLib/source/mips.ovpworld.org/peripheral/SmartLoaderLinux/1.0/pse/pse.igen.c | emanuellucas2/OVPsimProject | 6c9f5bfaaa135fa63d63746bacf5759c6d6c0e9e | [
"TCL"
] | null | null | null | /*
* Copyright (c) 2005-2021 Imperas Software Ltd., www.imperas.com
*
* 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.
*
*/
////////////////////////////////////////////////////////////////////////////////
//
// W R I T T E N B Y I M P E R A S I G E N
//
// Version 20211118.0
//
////////////////////////////////////////////////////////////////////////////////
#include "pse.igen.h"
/////////////////////////////// Port Declarations //////////////////////////////
idport_ab_dataT idport_ab_data;
handlesT handles;
/////////////////////////////// Diagnostic level ///////////////////////////////
// Test this variable to determine what diagnostics to output.
// eg. if (diagnosticLevel >= 1) bhmMessage("I", "SmartLoaderLinux", "Example");
// Predefined macros PSE_DIAG_LOW, PSE_DIAG_MEDIUM and PSE_DIAG_HIGH may be used
Uns32 diagnosticLevel;
/////////////////////////// Diagnostic level callback //////////////////////////
static void setDiagLevel(Uns32 new) {
diagnosticLevel = new;
}
//////////////////////////////// Bus Slave Ports ///////////////////////////////
static void installSlavePorts(void) {
handles.idport = ppmCreateSlaveBusPort("idport", 4);
ppmInstallReadCallback(readBoardId, (void*)0 , handles.idport + 0x0, 0x4);
ppmInstallWriteCallback(writeBoardId, (void*)0 , handles.idport + 0x0, 0x4);
}
/////////////////////////////// Bus Master Ports ///////////////////////////////
static void installMasterPorts(void) {
handles.mport = ppmOpenAddressSpace("mport");
}
PPM_DOC_FN(installDocs){
ppmDocNodeP Root1_node = ppmDocAddSection(0, "Root");
{
ppmDocNodeP doc2_node = ppmDocAddSection(Root1_node, "Licensing");
ppmDocAddText(doc2_node, "Open Source Apache 2.0");
ppmDocNodeP doc_12_node = ppmDocAddSection(Root1_node, "Description");
ppmDocAddText(doc_12_node, "Smart peripheral creates memory initialisation for a MIPS32 based Linux kernel boot.\n Performs the generation of boot code at the reset vector (virtual address 0xbfc00000) of the MIPS32 processor. \n Loads both the linux kernel and initial ramdisk into memory and patches the boot code to jump to the kernel start. \n Initialises the MIPS32 registers and Linux command line.");
ppmDocNodeP doc_22_node = ppmDocAddSection(Root1_node, "Reference");
ppmDocAddText(doc_22_node, "MIPS Malta User Manual. MIPS Boot code reference.");
ppmDocNodeP doc_32_node = ppmDocAddSection(Root1_node, "Limitations");
ppmDocAddText(doc_32_node, "None");
}
}
////////////////////////////////// Constructor /////////////////////////////////
PPM_CONSTRUCTOR_CB(periphConstructor) {
installSlavePorts();
installMasterPorts();
}
///////////////////////////////////// Main /////////////////////////////////////
int main(int argc, char *argv[]) {
diagnosticLevel = 0;
bhmInstallDiagCB(setDiagLevel);
constructor();
bhmWaitEvent(bhmGetSystemEvent(BHM_SE_END_OF_SIMULATION));
destructor();
return 0;
}
| 36.171717 | 423 | 0.59341 | [
"vector"
] |
5163ac9e2a71e1223fdd2b5510f009e26fe25ff4 | 9,221 | h | C | usr/src/cmd/format/global.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/format/global.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/format/global.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
*/
#ifndef _GLOBAL_H
#define _GLOBAL_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* Definitions for Label types: L_TYPE_SOLORIS is the default Sun label
* a.k.a VTOC. L_TYPE_EFI is the EFI label type.
*/
#define L_TYPE_SOLARIS 0
#define L_TYPE_EFI 1
#ifndef UINT_MAX64
#define UINT_MAX64 0xffffffffffffffffULL
#endif
#ifndef UINT_MAX32
#define UINT_MAX32 0xffffffffU
#endif
#if !defined(_EXTVTOC)
#define _EXTVTOC /* extented vtoc (struct extvtoc) format is used */
#endif
/*
* This file contains global definitions and declarations. It is intended
* to be included by everyone.
*/
#include <stdio.h>
#include <assert.h>
#include <memory.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/isa_defs.h>
#include <sys/dklabel.h>
#include <sys/vtoc.h>
#include <sys/dkio.h>
#include "hardware_structs.h"
#include "defect.h"
#include "io.h"
#include <sys/dktp/fdisk.h>
#include <sys/fcntl.h>
/*
* These declarations are global state variables.
*/
struct disk_info *disk_list; /* list of found disks */
struct ctlr_info *ctlr_list; /* list of found ctlrs */
char cur_menu; /* current menu level */
char last_menu; /* last menu level */
char option_msg; /* extended message options */
char diag_msg; /* extended diagnostic msgs */
char option_s; /* silent mode option */
char *option_f; /* input redirect option */
char *option_l; /* log file option */
FILE *log_file; /* log file pointer */
char *option_d; /* forced disk option */
char *option_t; /* forced disk type option */
char *option_p; /* forced partition table option */
char *option_x; /* data file redirection option */
FILE *data_file; /* data file pointer */
char *file_name; /* current data file name */
/* for useful error messages */
int expert_mode; /* enable for expert mode */
/* commands */
int need_newline; /* for correctly formatted output */
int dev_expert; /* enable for developer mode */
/* commands */
/*
* These declarations are used for quick access to information about
* the disk being worked on.
*/
int cur_file; /* file descriptor for current disk */
int cur_flags; /* flags for current disk */
int cur_label; /* current label type */
uint_t cur_blksz; /* currect disk block size */
struct disk_info *cur_disk; /* current disk */
struct disk_type *cur_dtype; /* current dtype */
struct ctlr_info *cur_ctlr; /* current ctlr */
struct ctlr_type *cur_ctype; /* current ctype */
struct ctlr_ops *cur_ops; /* current ctlr's ops vector */
struct partition_info *cur_parts; /* current disk's partitioning */
struct defect_list cur_list; /* current disk's defect list */
void *cur_buf; /* current disk's I/O buffer */
void *pattern_buf; /* current disk's pattern buffer */
uint_t pcyl; /* # physical cyls */
uint_t ncyl; /* # data cyls */
uint_t acyl; /* # alt cyls */
uint_t nhead; /* # heads */
uint_t phead; /* # physical heads */
uint_t nsect; /* # data sects/track */
uint_t psect; /* # physical sects/track */
uint_t apc; /* # alternates/cyl */
uint_t solaris_offset; /* Solaris offset, this value is zero */
/* for non-fdisk machines. */
int prot_type; /* protection type to format disk */
#if defined(_SUNOS_VTOC_16)
uint_t bcyl; /* # other cyls */
#endif /* defined(_SUNOS_VTOC_16) */
struct mboot boot_sec; /* fdisk partition info */
uint_t xstart; /* solaris partition start */
char x86_devname[MAXNAMELEN]; /* saved device name for fdisk */
/* information accesses */
struct mctlr_list *controlp; /* master controller list ptr */
/*
* These defines are used to manipulate the physical characteristics of
* the current disk.
*/
#define sectors(h) ((h) == nhead - 1 ? nsect - apc : nsect)
#define spc() (nhead * nsect - apc)
#define chs2bn(c, h, s) (((diskaddr_t)(c) * spc() + (h) * nsect + (s)))
#define bn2c(bn) (uint_t)((diskaddr_t)(bn) / spc())
#define bn2h(bn) (uint_t)(((diskaddr_t)(bn) % spc()) / nsect)
#define bn2s(bn) (uint_t)(((diskaddr_t)(bn) % spc()) % nsect)
#define datasects() (ncyl * spc())
#define totalsects() ((ncyl + acyl) * spc())
#define physsects() (pcyl * spc())
/*
* Macro to convert a device number into a partition number
*/
#define PARTITION(dev) (minor(dev) & 0x07)
/*
* These values define flags for the current disk (cur_flags).
*/
#define DISK_FORMATTED 0x01 /* disk is formatted */
#define LABEL_DIRTY 0x02 /* label has been scribbled */
/*
* These flags are for the controller type flags field.
*/
#define CF_NONE 0x0000 /* NO FLAGS */
#define CF_BLABEL 0x0001 /* backup labels in funny place */
#define CF_DEFECTS 0x0002 /* disk has manuf. defect list */
#define CF_APC 0x0004 /* ctlr uses alternates per cyl */
#define CF_SMD_DEFS 0x0008 /* ctlr does smd defect handling */
#define CF_SCSI 0x0040 /* ctlr is for SCSI disks */
#define CF_EMBEDDED 0x0080 /* ctlr is for embedded SCSI disks */
#define CF_IPI 0x0100 /* ctlr is for IPI disks */
#define CF_WLIST 0x0200 /* ctlt handles working list */
#define CF_NOFORMAT 0x0400 /* Manufacture formatting only */
/*
* This flag has been introduced only for SPARC ATA. Which has been approved
* at that time with the agreement in the next fix it will be removed and the
* format will be revamped with controller Ops structure not to have
* any operation to be NULL. As it makes things more modular.
*
* This flag is also used for PCMCIA pcata driver.
* The flag prevents reading or writing a defect list on the disk
* testing and console error reporting still work normally.
* This is appropriate for the PCMCIA disks which often have MS/DOS filesystems
* and have not allocated any space for alternate cylinders to keep
* the bab block lists.
*/
#define CF_NOWLIST 0x0800 /* Ctlr doesnot handle working list */
/*
* Do not require confirmation to extract defect lists on SCSI
* and IPI drives, since this operation is instantaneous
*/
#define CF_CONFIRM (CF_SCSI|CF_IPI)
/*
* Macros to make life easier
*/
#define SMD (cur_ctype->ctype_flags & CF_SMD_DEFS)
#define SCSI (cur_ctype->ctype_flags & CF_SCSI)
#define EMBEDDED_SCSI ((cur_ctype->ctype_flags & (CF_SCSI|CF_EMBEDDED)) == \
(CF_SCSI|CF_EMBEDDED))
/*
* These flags are for the disk type flags field.
*/
#define DT_NEED_SPEFS 0x01 /* specifics fields are uninitialized */
/*
* These defines are used to access the ctlr specific
* disk type fields (based on ctlr flags).
*/
#define dtype_bps dtype_specifics[0] /* bytes/sector */
#define dtype_dr_type dtype_specifics[1] /* drive type */
#define dtype_dr_type_data dtype_specifics[2] /* drive type in data file */
/*
* These flags are for the disk info flags field.
*/
#define DSK_LABEL 0x01 /* disk is currently labelled */
#define DSK_LABEL_DIRTY 0x02 /* disk auto-sensed, but not */
/* labeled yet. */
#define DSK_AUTO_CONFIG 0x04 /* disk was auto-configured */
#define DSK_RESERVED 0x08 /* disk is reserved by other host */
#define DSK_UNAVAILABLE 0x10 /* disk not available, could be */
/* currently formatting */
/*
* These flags are used to control disk command execution.
*/
#define F_NORMAL 0x00 /* normal operation */
#define F_SILENT 0x01 /* no error msgs at all */
#define F_ALLERRS 0x02 /* return any error, not just fatal */
#define F_RQENABLE 0x04 /* no error msgs at all */
/*
* Directional parameter for the op_rdwr controller op.
*/
#define DIR_READ 0
#define DIR_WRITE 1
/*
* These defines are the mode parameter for the checksum routines.
*/
#define CK_CHECKSUM 0 /* check checksum */
#define CK_MAKESUM 1 /* generate checksum */
/*
* This is the base character for partition identifiers
*/
#define PARTITION_BASE '0'
/*
* Base pathname for devfs names to be stripped from physical name.
*/
#define DEVFS_PREFIX "/devices"
/*
* Protection type by SCSI-3
*/
#define PROT_TYPE_0 0
#define PROT_TYPE_1 1
#define PROT_TYPE_2 2
#define PROT_TYPE_3 3
#define NUM_PROT_TYPE 4
/*
* Function prototypes ... Both for ANSI and non-ANSI C compilers
*/
#ifdef __STDC__
int copy_solaris_part(struct ipart *);
int good_fdisk(void);
int fdisk_physical_name(char *);
#else /* __STDC__ */
int copy_solaris_part();
int good_fdisk();
int fdisk_physical_name();
#endif /* __STDC__ */
#ifdef __cplusplus
}
#endif
#endif /* _GLOBAL_H */
| 31.047138 | 79 | 0.705889 | [
"vector"
] |
5179ebf130ba6f6a350f403798748f931c8ce4ed | 3,778 | h | C | video/decoderinterface.h | aliakseis/FFmpegPlayer | c47206438a66b19d2e95cc775a1aa0f4819a3579 | [
"MIT"
] | 64 | 2016-10-15T13:44:24.000Z | 2022-03-29T11:58:29.000Z | video/decoderinterface.h | aliakseis/FFmpegPlayer | c47206438a66b19d2e95cc775a1aa0f4819a3579 | [
"MIT"
] | 25 | 2016-01-21T02:21:01.000Z | 2022-03-03T03:30:08.000Z | video/decoderinterface.h | aliakseis/FFmpegPlayer | c47206438a66b19d2e95cc775a1aa0f4819a3579 | [
"MIT"
] | 36 | 2016-01-04T19:12:33.000Z | 2021-12-25T12:55:40.000Z | #pragma once
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <initializer_list>
#include <functional>
#ifdef _WIN32
using PathType = std::wstring;
#else
using PathType = std::string;
#endif
struct IDirect3DDevice9;
struct IDirect3DSurface9;
struct IFrameDecoder;
struct FrameRenderingData
{
uint8_t** image{};
const int* pitch{};
int width;
int height;
int aspectNum;
int aspectDen;
IDirect3DDevice9* d3d9device{};
IDirect3DSurface9* surface{};
};
struct IFrameListener
{
virtual ~IFrameListener() = default;
virtual void updateFrame(IFrameDecoder* decoder) = 0;
virtual void drawFrame(IFrameDecoder* decoder, unsigned int generation) = 0; // decoder->finishedDisplayingFrame() must be called
virtual void decoderClosing() = 0;
};
struct FrameDecoderListener
{
virtual ~FrameDecoderListener() = default;
virtual void changedFramePosition(
long long /*start*/, long long /*frame*/, long long /*total*/) {}
virtual void decoderClosed(bool /*fileReleased*/) {}
virtual void fileLoaded(long long /*start*/, long long /*total*/) {}
virtual void volumeChanged(double /*volume*/) {}
virtual void onEndOfStream(bool /*error*/) {}
virtual void playingFinished() {}
};
struct RationalNumber
{
int numerator;
int denominator;
};
inline bool operator == (const RationalNumber& left, const RationalNumber& right)
{
return left.numerator == right.numerator && left.denominator == right.denominator;
}
struct IFrameDecoder
{
enum FrameFormat {
PIX_FMT_YUV420P, ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
PIX_FMT_YUYV422, ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
PIX_FMT_RGB24, ///< packed RGB 8:8:8, 24bpp, RGBRGB...
PIX_FMT_BGR24, ///< packed RGB 8:8:8, 24bpp, BGRBGR...
};
typedef std::function<void(uint8_t*, int, int, int, std::vector<uint8_t>&, int&, int&)> ImageConversionFunc;
virtual ~IFrameDecoder() = default;
virtual void SetFrameFormat(FrameFormat format, bool allowDirect3dData) = 0;
virtual bool openUrls(std::initializer_list<std::string> urls) = 0;
virtual void play(bool isPaused = false) = 0;
virtual bool pauseResume() = 0;
virtual bool nextFrame() = 0;
virtual void setVolume(double volume) = 0;
virtual bool seekByPercent(double percent) = 0;
virtual void videoReset() = 0;
virtual void setFrameListener(IFrameListener* listener) = 0;
virtual void setDecoderListener(FrameDecoderListener* listener) = 0;
virtual bool getFrameRenderingData(FrameRenderingData* data) = 0;
virtual void finishedDisplayingFrame(unsigned int generation) = 0;
virtual void close() = 0;
virtual bool isPlaying() const = 0;
virtual bool isPaused() const = 0;
virtual double volume() const = 0;
virtual double getDurationSecs(int64_t duration) const = 0;
virtual int getNumAudioTracks() const = 0;
virtual int getAudioTrack() const = 0;
virtual void setAudioTrack(int idx) = 0;
virtual RationalNumber getSpeedRational() const = 0;
virtual void setSpeedRational(const RationalNumber& speed) = 0;
virtual bool getHwAccelerated() const = 0;
virtual void setHwAccelerated(bool hwAccelerated) = 0;
virtual std::vector<std::string> getProperties() const = 0;
virtual std::vector<std::string> listSubtitles() const = 0;
virtual bool getSubtitles(int idx, std::function<void(double, double, const std::string&)> addIntervalCallback) const = 0;
virtual void setImageConversionFunc(ImageConversionFunc func) = 0;
};
struct IAudioPlayer;
std::unique_ptr<IFrameDecoder> GetFrameDecoder(std::unique_ptr<IAudioPlayer> audioPlayer);
| 29.286822 | 133 | 0.701694 | [
"vector"
] |
51987a223d26ea774be89fc614de05daa4686050 | 1,643 | h | C | cpp/src/strategy/mcts_strategy.h | kongjiellx/AlphaGoZero-like-Renju | ac9025f2d8ec66d4975efbcb55bbe67f7c7b62c3 | [
"MIT"
] | 19 | 2019-06-04T02:40:55.000Z | 2021-03-26T07:20:45.000Z | cpp/src/strategy/mcts_strategy.h | kongjiellx/AlphaGoZero-like-Renju | ac9025f2d8ec66d4975efbcb55bbe67f7c7b62c3 | [
"MIT"
] | 2 | 2020-10-03T07:33:36.000Z | 2020-12-02T07:24:49.000Z | cpp/src/strategy/mcts_strategy.h | kongjiellx/AlphaGoZero-like-Renju | ac9025f2d8ec66d4975efbcb55bbe67f7c7b62c3 | [
"MIT"
] | 7 | 2019-06-04T02:41:11.000Z | 2022-01-05T00:34:45.000Z | //
// Created by 刘也宽 on 2020/11/18.
//
#ifndef ALPHAZERO_RENJU_MCTS_STRATEGY_H
#define ALPHAZERO_RENJU_MCTS_STRATEGY_H
#include "strategy.h"
#include "conf/conf_cc_proto_pb/conf/conf.pb.h"
#include <tuple>
#include <unordered_map>
class Node: public std::enable_shared_from_this<Node> {
private:
weak_ptr<Node> parent;
int N;
float W;
float P;
Player player;
std::unordered_map<int, shared_ptr<Node>> children;
public:
Player getPlayer() const;
void setParent(weak_ptr<Node> parent);
std::unordered_map<int, shared_ptr<Node>> &getChildren();
Node(weak_ptr<Node> parent, float p, Player player);
float Q();
int getN();
float getP();
tuple<shared_ptr<Node>, int> select();
void expand(vector<float> ps, Player player);
void backup(float v);
bool is_leaf();
};
class MctsStrategy : public Strategy {
private:
shared_ptr<Node> root;
shared_ptr<Node> current_root;
int current_step;
conf::MctsConf mcts_conf;
MODEL_TYPE model_type;
bool with_lock; // is predict with mutex
bool sample; // true: choice from distribution; false: choice max
void dirichlet_noise(std::vector<float> &ps);
std::vector<float> search(const Board &board, int simulate_num, int T, bool add_dirichlet_noise);
void change_root(int action);
public:
MctsStrategy(conf::MctsConf mcts_conf, Player player, MODEL_TYPE model_type, bool with_lock=true, bool sample=true);
void post_process(const Board &board) override;
std::tuple<int, int> step(const Board &board, StepRecord &record) override;
};
#endif //ALPHAZERO_RENJU_MCTS_STRATEGY_H
| 23.140845 | 120 | 0.707851 | [
"vector"
] |
51a665dcc9c642fd1d1b3bd0ee791e0c614a17bb | 3,115 | h | C | CsPlugin/Source/CsCore/Public/Managers/Damage/Data/Shape/CsData_DamageShape.h | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsPlugin/Source/CsCore/Public/Managers/Damage/Data/Shape/CsData_DamageShape.h | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsPlugin/Source/CsCore/Public/Managers/Damage/Data/Shape/CsData_DamageShape.h | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved.
// Interfaces
#include "Containers/CsGetInterfaceMap.h"
// Types
#include "Types/CsTypes_Macro.h"
#include "CsData_DamageShape.generated.h"
#pragma once
// NCsDamage::NValue::IValue
CS_FWD_DECLARE_STRUCT_NAMESPACE_2(NCsDamage, NValue, IValue)
// NCsDamage::NRange::IRange
CS_FWD_DECLARE_STRUCT_NAMESPACE_2(NCsDamage, NRange, IRange)
namespace NCsDamage
{
namespace NData
{
namespace NShape
{
/**
* Interface to describe the shape of Damage. This should be used with
* the interface "base" NCsDamage::NData::IData.
*/
struct CSCORE_API IShape : public ICsGetInterfaceMap
{
public:
static const FName Name;
private:
typedef NCsDamage::NValue::IValue ValueType;
typedef NCsDamage::NRange::IRange RangeType;
public:
virtual ~IShape(){}
/**
*
*
* return
*/
virtual const RangeType* GetRange() const = 0;
/**
* Calculate damage given an origin and point.
*
* @param Value
* @param Range
* @param Origin The center of the damage event.
* @param Point The location to evaluate for how much damage
* return Damage
*
*/
virtual float CalculateDamage(const ValueType* Value, const RangeType* Range, const FVector& Origin, const FVector& Point) const = 0;
/**
* Check if a given Point is within the bounds of an Origin.
*
* @param Origin The center of the bounds.
* @param Point The location to evaluate if in bounds.
* return Whether the point is in bounds of the origin.
*/
virtual bool IsInBounds(const FVector& Origin, const FVector& Point) const = 0;
};
}
}
}
UINTERFACE(BlueprintType)
class CSCORE_API UCsData_DamageShape : public UCsGetInterfaceMap
{
GENERATED_UINTERFACE_BODY()
};
// NCsDamage::NValue::IValue
CS_FWD_DECLARE_STRUCT_NAMESPACE_2(NCsDamage, NValue, IValue)
// NCsDamage::NRange::IRange
CS_FWD_DECLARE_STRUCT_NAMESPACE_2(NCsDamage, NRange, IRange)
/**
* Interface to describe the shape of Damage. This should be used with
* the interface "base" ICsData_Damage.
*/
class CSCORE_API ICsData_DamageShape : public ICsGetInterfaceMap
{
GENERATED_IINTERFACE_BODY()
public:
static const FName Name;
private:
typedef NCsDamage::NValue::IValue ValueType;
typedef NCsDamage::NRange::IRange RangeType;
public:
/**
*
*
* return
*/
virtual const RangeType* GetRange() const = 0;
/**
* Calculate damage given an origin and point.
*
* @param Value
* @param Range
* @param Origin The center of the damage event.
* @param Point The location to evaluate for how much damage
* return Damage
*
*/
virtual float CalculateDamage(const ValueType* Value, const RangeType* Range, const FVector& Origin, const FVector& Point) const = 0;
/**
* Check if a given Point is within the bounds of an Origin.
*
* @param Origin The center of the bounds.
* @param Point The location to evaluate if in bounds.
* return Whether the point is in bounds of the origin.
*/
virtual bool IsInBounds(const FVector& Origin, const FVector& Point) const = 0;
}; | 24.147287 | 137 | 0.708186 | [
"shape"
] |
51a7904f21df48f62acba19532038e06343088a1 | 19,367 | c | C | nitan/adm/daemons/smtpd.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/adm/daemons/smtpd.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/adm/daemons/smtpd.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | /**************************
* *
* /adm/daemons/smtp_d.c *
* *
* by Find@TX. *
* *
**************************/
#include <net/socket.h>
#include <login.h>
#include <ansi.h>
#include <origin.h>
#include <mudlib.h>
#define PUBLIC_MUD_MAIL "lonely-21@163.com"
#define RANDOM_PWD_LEN 8 /* 隨機密碼長度 */
#define REGFILE "/data/mail_reg.o"
#define REG_ROOM "/d/register/regroom"
#define BASE64_D "/adm/daemons/base64d"
inherit F_SAVE;
// class類型是C++新增的,想不到LPC也支持
class email
{
string rcpt; // 收件者地址
string body; // 內容
int status; // 狀態碼
string id; // 用户 ID
string passwd; // 密碼
object user;
int normal;
}
protected void write_callback(int fd,string outgoing);
protected varargs void write_callback(int fd,string outgoing);
protected void close_callback(int fd);
protected int permit_reg_email(string mail);
protected int mail_have_reg(object user,string mail);
string random_passwd(int len);
void check_user(object user);
/*
* 這裏是服務器你的登陸名和密碼。有一些服務器發信也是要進行
* 身份認證的,現在不少提供商深受垃圾郵件毀壞名譽之苦,越來
* 越多的採用發信身份認證,就像用 Outlook express 設置服務
* 器必須選擇“我的服務器要求身份認證”。
* 這個程序 SMTP 和 ESMTP 都可用,如果你的服務提供商不要求
* 身份認證,你儘可以不理會這個設定。
*/
// ESMTP在新的FoxMail v3.11也支持。
string *mail_reg; // 這裏保存已註冊的Email地址。
mapping user_unreg=([]); // 這裏保存郵件已發出但尚未確認的用户的ID
protected string mailname = "lonely-21",mailpasswd = "921121";
protected mixed content = ([]);
/* 這裏設定你的 SMTP 服務器的域名和 IP 地址 */
protected string domain_name = "smtp.163.com", address = "123.125.50.135";
/*
* 下面這部分是進行 SMTP 服務器 IP 地址的解析用的。
* 一般 SMTP 服務器的域名是不會變的,但 IP 地址有可
* 能變化。而且在遊戲運行中很少會注意這個。一旦出現
* 變化是很麻煩的,263 有一次就改變了 IP 地址也沒有
* 通知我們,我到三天以後才發現,搞的我很尷尬,因此
* 加上了這個功能。
*/
protected void resolve_callback( string o_address, string resolved, int key )
{
if( stringp(resolved) && (resolved != "") && (address != resolved) )
{
address = resolved;
save();
restore();
log_file("smtp",sprintf("SMTP: 遠程 SMTP 郵件服務器IP地址被轉換為 %s\n",address));
}
}
/* 這個函數我們是由 CRON_D 定時呼叫的,我們是1小時檢查一次。*/
void update_mail_server_ip()
{/*
if(previous_object() && (geteuid(previous_object()) != ROOT_UID))
return;*/
resolve( domain_name, "resolve_callback" );
}
string query_save_file()
{
return REGFILE;
}
protected void create()
{
seteuid(getuid());
if (file_size(REGFILE)<=0){
mail_reg=({});
user_unreg=([]);
save();
}
restore();
resolve( domain_name, "resolve_callback" );
}
/*
* 這個函數是由玩家註冊用的那個房間裏的註冊命令
* 呼叫的,user 是進行註冊的玩家物件,mail 是注
* 冊的電子郵件地址。
* 謹慎的人應當對呼叫此函數的物件進行一下檢查。
*/
void register_mail(object user,string mail)
{
object link;
string msg,passwd,server;
int s,err;
class email newmail;
if(!user) return;
if(!stringp(mail) || mail == "") return;
mail = lower_case(mail);
if( !objectp(link=query_temp("link_ob", user)) )
{
tell_object(user,"您的檔案不完全,無法進行註冊,請重新連線完成註冊.\n\n");
destruct(user);
return;
}
if(strsrch(mail,',') >= 0)
{
write(sprintf("你的電子郵件地址:%s 裏包含非法字符,\n請認真檢查後重新註冊。\n",mail));
return;
}
if(mail_have_reg(user,mail)) return;
passwd = random_passwd(RANDOM_PWD_LEN);
server = sprintf("%s 25",address);
/*
* PUBLIC_MUD_MAIL 是在其它的地方定義的,就是遊戲
* 對外交流的電子郵件地址。
*/
msg = sprintf("From: \"%s\" <%s>\nTo: %s\nSubject: 您在%s的密碼\n\n",
MUD_NAME,PUBLIC_MUD_MAIL,mail,CHINESE_MUD_NAME);
msg+=sprintf(user->name()+",你好,感謝您光臨"+MUD_NAME+"網絡遊戲。\n\n您的賬號:%s\n密碼:%s\n",query("id", user),passwd);
msg += "\n注意:這個賬號目前為臨時賬號,請您於48小時之內登陸確認。\n";
msg += "\t 過期未登陸將會被自動刪除。\n";
msg += "\t 如有註冊登陸方面的問題可以與 "+ PUBLIC_MUD_MAIL+" 聯繫。\n";
msg += "\n\t 本遊戲的主頁在 "+MUD_WEB+"
那裏有詳細的幫助和玩家寫的新手指南、經驗介紹,相信會\n\t 對你很有用處。
祝您在"+CHINESE_MUD_NAME+"玩的愉快!";
newmail = new(class email);
newmail->rcpt = mail;
newmail->body = msg;
newmail->id=query("id", user);
newmail->passwd = passwd;
newmail->user = user;
user->start_busy(100);
s = socket_create(STREAM,"read_callback", "close_callback");
if(s<0)
{
log_file("socket","Socket create err: "+socket_error(s)+"\n");
tell_object(user,"註冊過程中服務器發生錯誤,請再註冊一次。\n");
return;
}
content += ([ s : newmail ]);
err = socket_connect(s,server,"read_callback", "write_call_back");
if(err < 0)
{
map_delete(content,s);
log_file("socket","Socket connect err: "+socket_error(err)+"\n");
tell_object(user,"註冊過程中服務器發生錯誤,請再註冊一次。\n");
socket_close(s);
return;
}
tell_object(user,"郵件發送中,請稍候1分半鐘.....\n");
call_out("time_out",90,s);
}
protected void time_out(int fd)
{
class email mailmsg;
if(undefinedp(content[fd]))
return;
mailmsg = content[fd];
if(objectp(mailmsg->user))
{
tell_object(mailmsg->user,"\n發送過程超時,請重新再試一次。
問題有可能是:SMTP郵件服務器的IP地址已經更改。\n");
(mailmsg->user)->stop_busy();
}
map_delete(content,fd);
socket_close(fd);
}
void send_mail(object user, string mail_from, string mail_to, string topic, string data)
{
string server;
int s, err;
class email newmail;
if(strlen(data) > 65536)
{
write("你不能發送大於64K的郵件。\n");
return;
}
log_file("mail", sprintf("%s %s try to send mail <%s> Size:%d\n",
log_time(),(user?query("id", user):"SYSTEM"),
topic, strlen(data)));
if(!mail_from || sscanf(mail_from, "%*s@%*s") != 2)
mail_from = "lonely-21@163.com";
if(!mail_to || sscanf(mail_to, "%*s@%*s") != 2)
{
write("無法向這個地址發送郵件。\n");
return;
}
mail_to = lower_case(mail_to);
if(strsrch(mail_to, ',') >= 0)
{
write(sprintf("電子郵件地址:%s 裏包含非法字符,無法發送。\n", mail_to));
return;
}
server = sprintf("%s 25",address);
newmail = new(class email);
newmail->rcpt = mail_to;
newmail->body = data;
newmail->id=(user?query("id", user):"SYSTEM");
newmail->passwd = "abcdefg";
newmail->user = 0;
s = socket_create(STREAM,"read_callback", "close_callback");
if(s<0)
{
log_file("socket","Socket create err: "+socket_error(s)+"\n");
write("郵件發送過程中服務器發生錯誤,請重試一次。\n");
return;
}
content += ([ s : newmail ]);
err = socket_connect(s,server,"read_callback", "write_call_back");
if(err < 0)
{
map_delete(content,s);
log_file("socket","Socket connect err: "+socket_error(err)+"\n");
write("郵件發送過程中服務器發生錯誤,請重試一次。\n");
socket_close(s);
return;
}
tell_object(user,"郵件發送中,請稍候1分半鐘.....\n");
call_out("time_out",90,s);
}
protected void success_register(int fd)
{
class email mailmsg;
object usr,link;
if(undefinedp(content[fd]))
return;
mailmsg = content[fd];
if(!objectp(usr = mailmsg->user))
return;
if( !objectp(link=query_temp("link_ob", usr)) )
return;
(mailmsg->user)->stop_busy();
map_delete(content,fd);
tell_object(usr,sprintf("給您分配的隨機密碼已根據您登記的地址發往:"HIW"%s"NOR"
請您"HIG"五分鐘"NOR"後檢查您的郵箱。如果您在"HIC"24"NOR"小時後還未能收到我們
給您發出的郵件,請您向 "HIY"%s"NOR" 發信説明詳細情況,
我們會盡快為您解決。不便之處請多諒解。
祝您在%s玩的愉快,再見!\n",mailmsg->rcpt,PUBLIC_MUD_MAIL,MUD_NAME));
mail_reg=mail_reg+({mailmsg->rcpt});
save();
restore();
set("last_on", time(), link);
set("last_from", query_ip_name(usr), link);
set("email", mailmsg->rcpt, link);
set("oldpass",query("ad_password", link), link);
set("ad_password", crypt(mailmsg->passwd,0), link);
set("email", mailmsg->rcpt, usr);
set("have_reg", 1, usr);
delete("new_begin", usr);
link->save();
usr->save();
tell_room(environment(usr),"你只覺得眼前一花,"+query("name", usr)+"不見了。\n",({usr}));
message("channel:sys",sprintf(HIR"【郵件註冊精靈】"HIW"%s(%s)郵件發出退出遊戲。\n"NOR,
usr->name(),geteuid(usr)),filter_array(users(),(: wizardp($1) :)));
user_unreg[mailmsg->id]=time(); // 添加這個用户的ID到未確認名單中
log_file("smtp",sprintf("%s(%s)的郵件已經發往 %s。\n",usr->name(),geteuid(usr),mailmsg->rcpt));
save();
restore();
destruct(link);
destruct(usr);
}
protected void close_callback(int fd)
{
socket_close(fd);
}
/* 此函數處理髮送過程中的致命錯誤 */
protected void mail_error(int fd,string message)
{
class email mailmsg;
mailmsg = content[fd];
log_file("smtp_err",sprintf("ERROR:\n%s\nid: %s\nmail: %s\n\n",
message,mailmsg->id,mailmsg->rcpt));
if(objectp(mailmsg->user))
{
tell_object(mailmsg->user,sprintf("\n發送過程中出現異常錯誤:\n%s\n請重試一次。\n\n",
message));
(mailmsg->user)->stop_busy();
}
map_delete(content,fd);
socket_close(fd);
}
protected void read_callback(int fd,string message)
{
int rcode,err;
string mechanism;
class email mailmsg;
if(undefinedp(content[fd]))
{
socket_close(fd);
return;
}
mailmsg = content[fd];
rcode = atoi(message[0..2]);
if(!rcode || (rcode > 500))
{
mail_error(fd,message);
return;
}
if(!mailmsg->status) // 握手連通
{
socket_write(fd,sprintf("EHLO %s\r\n",query_host_name()));
mailmsg->status++;
return;
}
if(mailmsg->status == 1) // server ready
{
if((rcode == 500)) // command not recognized
{
if(mailmsg->normal)
{
mail_error(fd,message);
return;
}
socket_write(fd,sprintf("HELO %s\r\n",query_host_name()));
mailmsg->normal = 1;
return;
}
if(mailmsg->normal)
{
socket_write(fd,sprintf("MAIL FROM: <%s>\r\n",PUBLIC_MUD_MAIL));
mailmsg->status = 3;
return;
}
if(sscanf(message,"%*sAUTH=%s\n%*s",mechanism) == 3)
{
socket_write(fd,sprintf("AUTH %s\r\n",mechanism));
mailmsg->status = 2;
return;
}
// ESMTP 協議不需要認證
socket_write(fd,sprintf("MAIL FROM: <%s>\r\n",PUBLIC_MUD_MAIL));
mailmsg->status = 3;
return;
}
if(mailmsg->status == 2) // Authentication
{
string quest;
if(rcode == 334) // 認證提問
{
/*
* 這裏是 ESMTP 協議的認證部分,ESMTP 協議規定
* 認證信息使用 BASE64 編碼。
* 這裏的 base64_decode 和 base64_encode 函數
* 就是 base64_d 裏面的 decode 和 encode 函數,
* 我們是定義成了 simul_efun。
*/
quest = message[4..];
quest = replace_string(quest,"\n","");
quest = replace_string(quest,"\r","");
quest = BASE64_D->decode(quest);
if(quest[0..3] == "User")
{
socket_write(fd,sprintf("%s\r\n",BASE64_D->encode(mailname)));
return;
}
else if(quest[0..3] == "Pass")
{
socket_write(fd,sprintf("%s\r\n",BASE64_D->encode(mailpasswd)));
return;
}
}
// 認證通過
socket_write(fd,sprintf("MAIL FROM: <%s>\r\n",PUBLIC_MUD_MAIL));
mailmsg->status = 3;
return;
}
if(mailmsg->status == 3)
{
socket_write(fd,sprintf("RCPT TO: <%s>\r\n",mailmsg->rcpt));
mailmsg->status = 4;
return;
}
if(mailmsg->status == 4)
{
socket_write(fd,sprintf("DATA\r\n"));
mailmsg->status = 5;
return;
}
if(mailmsg->status == 5)
{
if(rcode == 354) // ready receive data
{
err = socket_write(fd,sprintf("%s\r\n.\r\n",mailmsg->body));
if( (err < 0) && (err != EEALREADY) )
call_out("write_callback",1,fd,sprintf("%s\r\n.\r\n",mailmsg->body));
mailmsg->status = 6;
return;
}
else
{
mail_error(fd,message);
return;
}
}
if(mailmsg->status == 6)
{
socket_write(fd,sprintf("QUIT\r\n"));
mailmsg->status = 7;
return;
}
if((mailmsg->status == 7) && (rcode == 221))
{
success_register(fd);
return;
}
mail_error(fd,message);
}
protected varargs void write_callback(int fd,string outgoing)
{
int err;
if(stringp(outgoing) && (outgoing != ""))
{
err = socket_write(fd,outgoing);
if( (err < 0) && (err != EEALREADY) )
{
call_out("write_callback",1,fd,outgoing);
return;
}
}
}
/*
* 對玩家註冊的電子郵件地址的各類檢查就在這裏實現,
* 可以根據自己的需要增減代碼。
* 要加入對某些 mail 地址的限制,也在這裏實現。
*/
protected int mail_have_reg(object user,string mail)
{
object link;
string id;
if(!user) return 1;
link=query_temp("link_ob", user);
if(!link) return 1;
if(!stringp(mail)) return 1;
id=query("id", user);
if(member_array(mail,mail_reg)!=-1)
{
tell_object(user,"這個郵件地址已經註冊過了,本遊戲不允許同一地址多重註冊。\n對不起!\n");
message("channel:sys",sprintf(HIR"【郵件註冊精靈】:%s(%s)註冊請求被拒絕,退出遊戲。\n"NOR,
user->name(),geteuid(user)),filter_array(users(),(: wizardp($1) :)));
destruct(user);
destruct(link);
rm(DATA_DIR + "login/" + id[0..0] + "/" + id + ".o");
rm(DATA_DIR + "user/" + id[0..0] + "/" + id + ".o");
return 1;
}
else
return 0;
}
/*
* 超過48小時未連線確認刪除檔案
* 這個函數我們是由 CRON_D 定時呼叫的,
* 一小時檢查一次。
*/
void user_no_login()
{
string *player;
string time;
string *name;
object user,link;
int i;
// 這兩句是用來檢查權限的
if(!previous_object()||(geteuid(previous_object()) != ROOT_UID)&&(geteuid(previous_object()) != "lonely"))
return;
name=keys(user_unreg); // 獲得所有郵件已發出等待確認的用户array
for(i=0; i<sizeof(name); i++){
if ((time()-user_unreg[name[i]])>=172800){ // 假如這些id的註冊時間與現在時間相差2天=48小時=172800秒
if (!sizeof(player)) player=({name[i]});
else player+=({name[i]}); // 在player 這個array中加入這個玩家
map_delete(user_unreg,name[i]); // 在原先的mapping中刪除這個玩家
save();
restore();
}
}
// 下面就是對player這個array的處理了
if(!player || !sizeof(player)){
message("system",HIW"...無符合條件的玩家" NOR,users() );
return;
}
time = ctime(time());
foreach(string one in player)
{
string f;
if(objectp(user = find_player(one)))
{
if( objectp(link=query("link_ob", user)) )
destruct(link);
destruct(user);
}
if(file_size(f = sprintf(DATA_DIR+"login/%c/%s.o",one[0],one)) > 0)
rm(f);
if(file_size(f = sprintf(DATA_DIR+"user/%c/%s.o",one[0],one)) > 0)
rm(f);
log_file("smtp",sprintf("(%s)超過48小時未連線確認被刪除。%s\n",one,time));
}
}
/* 這個函數產生一個長度為 len 的隨機密碼 */
string random_passwd(int len)
{
int cap,low,num,n;
string passwd;
string Random_Passwd ="ABCDEFGHIJKL1234567890mnopqrstuvwxyzabcdefghi1jk9MNOPQRS4TUVW9XYZ";
if(!intp(len))
return "12345";
if(len < 4 || len > 8)
len = 8;
do
{
cap=0; low=0; num=0; passwd = "";
for(int i=0;i<len;i++)
{
n = random(sizeof(Random_Passwd));
if( Random_Passwd[n] <='Z' && Random_Passwd[n] >='A' )
cap++;
else if( Random_Passwd[n] <='z' && Random_Passwd[n] >='a' )
low++;
else if( Random_Passwd[n] <='9' && Random_Passwd[n] >='0' )
num++;
passwd += Random_Passwd[n..n];
}
}
while(!cap || !low || !num);
return passwd;
}
// 下面的這個函數時我加上為了處理48小時內已經登陸的玩家,從未註冊用户列表中刪除這些玩家。
void finish_reg(string id)
{
int i;
for (i=0;i<sizeof(user_unreg);i++)
if (intp(user_unreg[id])&&user_unreg[id]!=0)
{
map_delete(user_unreg, id);
save();
restore();
return;
}
}
// 下面的是我用來調試的接口函數
mapping query_users()
{return user_unreg;}
string *query_mail_reg() { return mail_reg; }
string query_smtp_info()
{
string msg;
msg="\n服務器域名:"+domain_name;
msg+=("\n服務器IP地址:"+address);
msg+=("\n用户名:"+mailname);
msg+=(" 用户密碼:*****");
msg+="\n";
return msg;
}
void remove_mail(string mail)
{
mail_reg -= ({ mail });
save();
}
void stop_reg(object ob)
{
delete("ad_password", ob);
set("ad_password",query("oldpass", ob), ob);
delete("have_reg", ob);
delete("oldpass", ob);
remove_mail(query("email", ob));
map_delete(user_unreg,query("id", ob));
} | 28.314327 | 114 | 0.476842 | [
"object"
] |
1fbf62b84ad8cd77000de2a66020da1cfdafc52a | 3,568 | h | C | src/shogun/mathematics/linalg/eigsolver/EigenSolver.h | srgnuclear/shogun | 33c04f77a642416376521b0cd1eed29b3256ac13 | [
"Ruby",
"MIT"
] | 1 | 2015-11-05T18:31:14.000Z | 2015-11-05T18:31:14.000Z | src/shogun/mathematics/linalg/eigsolver/EigenSolver.h | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | src/shogun/mathematics/linalg/eigsolver/EigenSolver.h | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2013 Soumyajit De
*/
#ifndef EIGEN_SOLVER_H_
#define EIGEN_SOLVER_H_
#include <shogun/lib/config.h>
#include <shogun/base/Parameter.h>
#include <shogun/mathematics/linalg/linop/LinearOperator.h>
namespace shogun
{
/** @brief Abstract base class that provides an abstract compute method for
* computing eigenvalues of a real valued, self-adjoint linear operator. It
* also provides method for getting min and max eigenvalues.
*/
class CEigenSolver : public CSGObject
{
public:
/** default constructor */
CEigenSolver()
: CSGObject()
{
init();
}
/**
* constructor
*
* @param linear_operator real valued self-adjoint linear operator
* whose eigenvalues have to be found
*/
CEigenSolver(CLinearOperator<SGVector<float64_t>, SGVector<float64_t> >* linear_operator)
: CSGObject()
{
init();
m_linear_operator=linear_operator;
SG_REF(m_linear_operator);
}
/** destructor */
virtual ~CEigenSolver()
{
SG_UNREF(m_linear_operator);
}
/**
* abstract compute method for computing eigenvalues of a real
* valued linear operator
*/
virtual void compute() = 0;
/** sets the min eigelvalue of a real valued self-adjoint linear operator */
void set_min_eigenvalue(float64_t min_eigenvalue)
{
m_min_eigenvalue=min_eigenvalue;
m_is_computed_min=true;
}
/** @return min eigenvalue of a real valued self-adjoint linear operator */
const float64_t get_min_eigenvalue() const
{
return m_min_eigenvalue;
}
/** sets the max eigelvalue of a real valued self-adjoint linear operator */
void set_max_eigenvalue(float64_t max_eigenvalue)
{
m_max_eigenvalue=max_eigenvalue;
m_is_computed_max=true;
}
/** @return max eigenvalue of a real valued self-adjoint linear operator */
const float64_t get_max_eigenvalue() const
{
return m_max_eigenvalue;
}
/** @return object name */
virtual const char* get_name() const
{
return "EigenSolver";
}
protected:
/** min eigenvalue */
float64_t m_min_eigenvalue;
/** max eigenvalue */
float64_t m_max_eigenvalue;
/** the linear solver whose eigenvalues have to be found */
CLinearOperator<SGVector<float64_t>, SGVector<float64_t> >* m_linear_operator;
/** flag that denotes that the minimum eigenvalue is already computed */
bool m_is_computed_min;
/** flag that denotes that the maximum eigenvalue is already computed */
bool m_is_computed_max;
private:
/** initialize with default values and register params */
void init()
{
m_min_eigenvalue=0.0;
m_max_eigenvalue=0.0;
m_linear_operator=NULL;
m_is_computed_min=false;
m_is_computed_max=false;
SG_ADD(&m_min_eigenvalue, "min_eigenvalue",
"Minimum eigenvalue of a real valued self-adjoint linear operator",
MS_NOT_AVAILABLE);
SG_ADD(&m_max_eigenvalue, "max_eigenvalue",
"Maximum eigenvalue of a real valued self-adjoint linear operator",
MS_NOT_AVAILABLE);
SG_ADD((CSGObject**)&m_linear_operator, "linear_operator",
"Self-adjoint linear operator",
MS_NOT_AVAILABLE);
SG_ADD(&m_is_computed_min, "is_computed_min",
"Flag denoting that the minimum eigenvalue has already been computed",
MS_NOT_AVAILABLE);
SG_ADD(&m_max_eigenvalue, "is_computed_max",
"Flag denoting that the maximum eigenvalue has already been computed",
MS_NOT_AVAILABLE);
}
};
}
#endif // EIGEN_SOLVER_H_
| 24.951049 | 90 | 0.745516 | [
"object"
] |
1fc16b88efbf7543b424effd19231b08bf7ab824 | 5,633 | c | C | datasets/linux-4.11-rc3/security/apparmor/context.c | yijunyu/demo-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 1 | 2019-05-03T19:27:45.000Z | 2019-05-03T19:27:45.000Z | datasets/linux-4.11-rc3/security/apparmor/context.c | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | datasets/linux-4.11-rc3/security/apparmor/context.c | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | /*
* AppArmor security module
*
* This file contains AppArmor functions used to manipulate object security
* contexts.
*
* Copyright (C) 1998-2008 Novell/SUSE
* Copyright 2009-2010 Canonical Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*
*
* AppArmor sets confinement on every task, via the the aa_task_ctx and
* the aa_task_ctx.profile, both of which are required and are not allowed
* to be NULL. The aa_task_ctx is not reference counted and is unique
* to each cred (which is reference count). The profile pointed to by
* the task_ctx is reference counted.
*
* TODO
* If a task uses change_hat it currently does not return to the old
* cred or task context but instead creates a new one. Ideally the task
* should return to the previous cred if it has not been modified.
*
*/
#include "include/context.h"
#include "include/policy.h"
/**
* aa_alloc_task_context - allocate a new task_ctx
* @flags: gfp flags for allocation
*
* Returns: allocated buffer or NULL on failure
*/
struct aa_task_ctx *aa_alloc_task_context(gfp_t flags)
{
return kzalloc(sizeof(struct aa_task_ctx), flags);
}
/**
* aa_free_task_context - free a task_ctx
* @ctx: task_ctx to free (MAYBE NULL)
*/
void aa_free_task_context(struct aa_task_ctx *ctx)
{
if (ctx) {
aa_put_profile(ctx->profile);
aa_put_profile(ctx->previous);
aa_put_profile(ctx->onexec);
kzfree(ctx);
}
}
/**
* aa_dup_task_context - duplicate a task context, incrementing reference counts
* @new: a blank task context (NOT NULL)
* @old: the task context to copy (NOT NULL)
*/
void aa_dup_task_context(struct aa_task_ctx *new, const struct aa_task_ctx *old)
{
*new = *old;
aa_get_profile(new->profile);
aa_get_profile(new->previous);
aa_get_profile(new->onexec);
}
/**
* aa_get_task_profile - Get another task's profile
* @task: task to query (NOT NULL)
*
* Returns: counted reference to @task's profile
*/
struct aa_profile *aa_get_task_profile(struct task_struct *task)
{
struct aa_profile *p;
rcu_read_lock();
p = aa_get_profile(__aa_task_profile(task));
rcu_read_unlock();
return p;
}
/**
* aa_replace_current_profile - replace the current tasks profiles
* @profile: new profile (NOT NULL)
*
* Returns: 0 or error on failure
*/
int aa_replace_current_profile(struct aa_profile *profile)
{
struct aa_task_ctx *ctx = current_ctx();
struct cred *new;
AA_BUG(!profile);
if (ctx->profile == profile)
return 0;
if (current_cred() != current_real_cred())
return -EBUSY;
new = prepare_creds();
if (!new)
return -ENOMEM;
ctx = cred_ctx(new);
if (unconfined(profile) || (ctx->profile->ns != profile->ns))
/* if switching to unconfined or a different profile namespace
* clear out context state
*/
aa_clear_task_ctx_trans(ctx);
/*
* be careful switching ctx->profile, when racing replacement it
* is possible that ctx->profile->proxy->profile is the reference
* keeping @profile valid, so make sure to get its reference before
* dropping the reference on ctx->profile
*/
aa_get_profile(profile);
aa_put_profile(ctx->profile);
ctx->profile = profile;
commit_creds(new);
return 0;
}
/**
* aa_set_current_onexec - set the tasks change_profile to happen onexec
* @profile: system profile to set at exec (MAYBE NULL to clear value)
*
* Returns: 0 or error on failure
*/
int aa_set_current_onexec(struct aa_profile *profile)
{
struct aa_task_ctx *ctx;
struct cred *new = prepare_creds();
if (!new)
return -ENOMEM;
ctx = cred_ctx(new);
aa_get_profile(profile);
aa_put_profile(ctx->onexec);
ctx->onexec = profile;
commit_creds(new);
return 0;
}
/**
* aa_set_current_hat - set the current tasks hat
* @profile: profile to set as the current hat (NOT NULL)
* @token: token value that must be specified to change from the hat
*
* Do switch of tasks hat. If the task is currently in a hat
* validate the token to match.
*
* Returns: 0 or error on failure
*/
int aa_set_current_hat(struct aa_profile *profile, u64 token)
{
struct aa_task_ctx *ctx;
struct cred *new = prepare_creds();
if (!new)
return -ENOMEM;
AA_BUG(!profile);
ctx = cred_ctx(new);
if (!ctx->previous) {
/* transfer refcount */
ctx->previous = ctx->profile;
ctx->token = token;
} else if (ctx->token == token) {
aa_put_profile(ctx->profile);
} else {
/* previous_profile && ctx->token != token */
abort_creds(new);
return -EACCES;
}
ctx->profile = aa_get_newest_profile(profile);
/* clear exec on switching context */
aa_put_profile(ctx->onexec);
ctx->onexec = NULL;
commit_creds(new);
return 0;
}
/**
* aa_restore_previous_profile - exit from hat context restoring the profile
* @token: the token that must be matched to exit hat context
*
* Attempt to return out of a hat to the previous profile. The token
* must match the stored token value.
*
* Returns: 0 or error of failure
*/
int aa_restore_previous_profile(u64 token)
{
struct aa_task_ctx *ctx;
struct cred *new = prepare_creds();
if (!new)
return -ENOMEM;
ctx = cred_ctx(new);
if (ctx->token != token) {
abort_creds(new);
return -EACCES;
}
/* ignore restores when there is no saved profile */
if (!ctx->previous) {
abort_creds(new);
return 0;
}
aa_put_profile(ctx->profile);
ctx->profile = aa_get_newest_profile(ctx->previous);
AA_BUG(!ctx->profile);
/* clear exec && prev information when restoring to previous context */
aa_clear_task_ctx_trans(ctx);
commit_creds(new);
return 0;
}
| 24.70614 | 80 | 0.712942 | [
"object"
] |
1fc4573b75878ae76785e61407eaf136808cd7fe | 7,003 | c | C | rrd_update.c | cmb69/pecl-processing-rrd | d24179ade06457a9b3a864a9c09a14ee91da0d67 | [
"BSD-2-Clause"
] | 3 | 2021-04-20T05:43:53.000Z | 2021-04-22T12:56:23.000Z | rrd_update.c | cmb69/pecl-processing-rrd | d24179ade06457a9b3a864a9c09a14ee91da0d67 | [
"BSD-2-Clause"
] | 2 | 2021-04-22T14:21:24.000Z | 2021-12-20T15:44:32.000Z | rrd_update.c | cmb69/pecl-processing-rrd | d24179ade06457a9b3a864a9c09a14ee91da0d67 | [
"BSD-2-Clause"
] | 3 | 2021-04-19T08:08:46.000Z | 2021-08-29T06:54:26.000Z | /**
* PHP bindings to the rrdtool
*
* This source file is subject to the BSD license that is bundled
* with this package in the file LICENSE.
* ---------------------------------------------------------------
* Author: Miroslav Kubelik <koubel@php.net>
* ---------------------------------------------------------------
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "zend_exceptions.h"
#include "ext/standard/php_smart_string.h"
#include <rrd.h>
#include "php_rrd.h"
#include "rrd_update.h"
/* declare class entry */
static zend_class_entry *ce_rrd_update;
/* declare class handlers */
static zend_object_handlers rrd_update_handlers;
/**
* overloading the standard zend object structure (std property) in the need
* of having dedicated creating/cloning/destruction functions
*/
typedef struct _rrd_update_object {
/** path to newly created rrd file */
char *file_path;
zend_object std;
} rrd_update_object;
/**
* fetch our custom object from user space object
*/
static inline rrd_update_object *php_rrd_update_fetch_object(zend_object *obj) {
return (rrd_update_object *)((char*)(obj) - XtOffsetOf(rrd_update_object, std));
}
/* {{{ rrd_update_object_dtor
close all resources and the memory allocated for our internal object
*/
static void rrd_update_object_dtor(zend_object *object)
{
rrd_update_object *intern_obj = php_rrd_update_fetch_object(object);
if (!intern_obj) return;
if (intern_obj->file_path)
efree(intern_obj->file_path);
zend_object_std_dtor(&intern_obj->std);
}
/* }}} */
/* {{{ rrd_update_object_new
creates new rrd update object
*/
static zend_object *rrd_update_object_new(zend_class_entry *ce)
{
rrd_update_object *intern_obj = ecalloc(1, sizeof(rrd_update_object) +
zend_object_properties_size(ce));
intern_obj->file_path = NULL;
zend_object_std_init(&intern_obj->std, ce);
object_properties_init(&intern_obj->std, ce);
intern_obj->std.handlers = &rrd_update_handlers;
return &intern_obj->std;
}
/* }}} */
/* {{{ proto void RRDUpdater::__construct(string path)
creates new object for rrd update function
*/
PHP_METHOD(RRDUpdater, __construct)
{
rrd_update_object *intern_obj;
char *path;
size_t path_length;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &path, &path_length) == FAILURE) {
return;
}
intern_obj = php_rrd_update_fetch_object(Z_OBJ_P(getThis()));
intern_obj->file_path = estrdup(path);
}
/* }}} */
/* {{{ proto array RRDUpdater::update(array $values, [string time=time()])
Updates data sources in RRD database
*/
PHP_METHOD(RRDUpdater, update)
{
rrd_update_object *intern_obj;
zval *zv_values_array;
/* help structures for preparing arguments for rrd_update call */
zval zv_update_argv;
rrd_args *update_argv;
/* 'N' means default time string for rrd update,
* see rrdtool update man page
*/
char *time = "N";
size_t time_str_length = 1;
int argc = ZEND_NUM_ARGS();
zend_string *zs_ds_name;
zval *zv_ds_val;
/* string for all data source names formated for rrd_update call */
smart_string ds_names = {0};
/* string for all data source values for rrd_update call */
smart_string ds_vals = {0};
if (zend_parse_parameters(argc, "a|s", &zv_values_array, &time,
&time_str_length) == FAILURE) {
return;
}
if (zend_hash_num_elements(Z_ARRVAL_P(zv_values_array)) <= 0) {
RETURN_TRUE;
}
intern_obj = php_rrd_update_fetch_object(Z_OBJ_P(getThis()));
if (php_check_open_basedir(intern_obj->file_path)) {
RETURN_FALSE;
}
if (argc > 1 && time_str_length == 0) {
zend_throw_exception(NULL, "time cannot be empty string", 0);
return;
}
ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(zv_values_array), zs_ds_name, zv_ds_val) {
if (ds_names.len) {
smart_string_appendc(&ds_names, ':');
} else {
smart_string_appends(&ds_names, "--template=");
}
smart_string_appends(&ds_names, ZSTR_VAL(zs_ds_name));
/* "timestamp:ds1Value:ds2Value" string */
if (!ds_vals.len) {
smart_string_appends(&ds_vals, time);
}
smart_string_appendc(&ds_vals, ':');
if (Z_TYPE_P(zv_ds_val) != IS_STRING) {
convert_to_string(zv_ds_val);
}
smart_string_appendl(&ds_vals, Z_STRVAL_P(zv_ds_val), Z_STRLEN_P(zv_ds_val));
} ZEND_HASH_FOREACH_END();
smart_string_0(&ds_names);
smart_string_0(&ds_vals);
/* add copy of names and values strings into arguments array and free
* original strings
*/
array_init(&zv_update_argv);
add_next_index_string(&zv_update_argv, ds_names.c);
add_next_index_string(&zv_update_argv, ds_vals.c);
smart_string_free(&ds_names);
smart_string_free(&ds_vals);
update_argv = rrd_args_init_by_phparray("update", intern_obj->file_path, &zv_update_argv);
if (!update_argv) {
zend_error(E_WARNING, "cannot allocate arguments options");
zval_dtor(&zv_update_argv);
if (time_str_length == 0) efree(time);
RETURN_FALSE;
}
if (rrd_test_error()) rrd_clear_error();
/* call rrd_update and test if fails */
if (rrd_update(update_argv->count - 1, &update_argv->args[1]) == -1) {
zval_dtor(&zv_update_argv);
rrd_args_free(update_argv);
/* throw exception with rrd error string */
zend_throw_exception(NULL, rrd_get_error(), 0);
rrd_clear_error();
return;
}
zval_dtor(&zv_update_argv);
rrd_args_free(update_argv);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int rrd_update(string file, array options)
Updates the RRD file with a particular options and values.
*/
PHP_FUNCTION(rrd_update)
{
char *filename;
size_t filename_length;
zval *zv_arr_options;
rrd_args *argv;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "pa", &filename,
&filename_length, &zv_arr_options) == FAILURE) {
return;
}
if (php_check_open_basedir(filename)) RETURN_FALSE;
argv = rrd_args_init_by_phparray("update", filename, zv_arr_options);
if (!argv) {
zend_error(E_WARNING, "cannot allocate arguments options");
RETURN_FALSE;
}
if (rrd_test_error()) rrd_clear_error();
if (rrd_update(argv->count - 1, &argv->args[1]) == -1 ) {
RETVAL_FALSE;
} else {
RETVAL_TRUE;
}
rrd_args_free(argv);
}
/* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_rrdupdater_construct, 0)
ZEND_ARG_INFO(0, path)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_rrdupdater_update, 0, 0, 1)
ZEND_ARG_INFO(0, values)
ZEND_ARG_INFO(0, time)
ZEND_END_ARG_INFO()
/* class method table */
static zend_function_entry rrd_update_methods[] = {
PHP_ME(RRDUpdater, __construct, arginfo_rrdupdater_construct, ZEND_ACC_PUBLIC)
PHP_ME(RRDUpdater, update, arginfo_rrdupdater_update, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* minit hook, called from main module minit */
void rrd_update_minit()
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "RRDUpdater", rrd_update_methods);
ce.create_object = rrd_update_object_new;
ce_rrd_update = zend_register_internal_class(&ce);
memcpy(&rrd_update_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
rrd_update_handlers.clone_obj = NULL;
rrd_update_handlers.offset = XtOffsetOf(rrd_update_object, std);
rrd_update_handlers.free_obj = rrd_update_object_dtor;
}
| 26.228464 | 92 | 0.730401 | [
"object"
] |
1fd5497f15e20dd89bf1ee517208cbe7f9a30ce1 | 2,007 | h | C | include/connection.h | MICHAEL-ZENGZF/Online-Chess | 325e6a4858194e16ad9aeaa9758976bec30744a5 | [
"MIT"
] | 1 | 2019-02-21T07:59:45.000Z | 2019-02-21T07:59:45.000Z | include/connection.h | MICHAEL-ZENGZF/Online-Chess | 325e6a4858194e16ad9aeaa9758976bec30744a5 | [
"MIT"
] | null | null | null | include/connection.h | MICHAEL-ZENGZF/Online-Chess | 325e6a4858194e16ad9aeaa9758976bec30744a5 | [
"MIT"
] | null | null | null | #include"codec.h"
#include<gtk/gtk.h>
#include"vector.h"
#include<stdint.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/select.h>
#include<netdb.h>
#include<stdbool.h>
#include<stdio.h>
#include<stdlib.h>
#include"util.h"
#include<assert.h>
#include<pthread.h>
#ifndef CONNECTION_H
#define CONNECTION_H
//this header and it`s corresponding c file
//contains the connection functions that
//can be used for the connection of both server and another client
//the buffer size to send
#define BUFFERSIZE 256
#define MAX_SERVICE_NAME_LEN 20
//open socket and record the server address
void init_connection2server(char *program,char *host, char *port);
//sets up connection and send a message to server
char* sendToServer(char* msg);
//Register the given service in the Service List that a
//Status or terminal is going to show
//service: service name
int GetServiceID(char *service);
//print the status of the given service
//ServiceID: The id that attain from GetServiceID
//ServiceIsRunning: true if the service is now running
void PrintStatus(int ServiceID, bool ServiceIsRunning);
/* create a socket on this server */
//PortNo: port number
int MakeServerSocket(uint16_t PortNo);
//WARNING: the char* that this function returns must be free
//Otherwise there will be memory leak
char* readFullBuffer(int DataSocketFD);
//Send a msg to user
void SendMsgToUser(char *dstUser, char* msg);
//as is its name describes
void ChallengeUser(char *dstUser);
//init the connection to the qport of the server
void init_connection2qport();
//inits the routine query task
//as is its name describes....
void InitQueryTimeredTask();
//as is its name describes
typedef void(*AddNewFriendCallback)(char *);
//if friend is added successfully, this callback will be called
void AddNewFriend(char *newFriend, AddNewFriendCallback callback);
//as is its name describes
//same as above
typedef void(*RemoveFriendCallback)();
void DeleteFriend(char *oldFriend, RemoveFriendCallback callback);
#endif | 27.493151 | 66 | 0.773293 | [
"vector"
] |
1fd804f0bdebbc0ecef95ab410669ce16c557590 | 1,341 | h | C | PrebidMobile/PrebidMobileRendering/Prebid/PBMCore/NativeAssets/NativeAdResponse/NativeAdMarkup/PBMNativeAdMarkupTitle.h | motesp/prebid-mobile-ios | 92b85d9fcf22b4b5f905040f438f34ec10f46610 | [
"Apache-2.0"
] | null | null | null | PrebidMobile/PrebidMobileRendering/Prebid/PBMCore/NativeAssets/NativeAdResponse/NativeAdMarkup/PBMNativeAdMarkupTitle.h | motesp/prebid-mobile-ios | 92b85d9fcf22b4b5f905040f438f34ec10f46610 | [
"Apache-2.0"
] | null | null | null | PrebidMobile/PrebidMobileRendering/Prebid/PBMCore/NativeAssets/NativeAdResponse/NativeAdMarkup/PBMNativeAdMarkupTitle.h | motesp/prebid-mobile-ios | 92b85d9fcf22b4b5f905040f438f34ec10f46610 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "PBMJsonDecodable.h"
NS_ASSUME_NONNULL_BEGIN
@interface PBMNativeAdMarkupTitle : NSObject <PBMJsonDecodable>
/// The text associated with the text element.
@property (nonatomic, copy, nullable) NSString *text;
/// [Integer]
/// The length of the title being provided.
/// Required if using assetsurl/dcourl representation, optional if using embedded asset representation.
@property (nonatomic, strong, nullable) NSNumber *length;
/// This object is a placeholder that may contain custom JSON agreed to by the parties to support flexibility beyond the standard defined in this specification
@property (nonatomic, strong, nullable) NSDictionary<NSString *, id> *ext;
- (instancetype)initWithText:(nullable NSString *)text;
@end
NS_ASSUME_NONNULL_END
| 35.289474 | 159 | 0.780761 | [
"object"
] |
1fe31d21d19f650c7076a9370576801f8238f255 | 1,724 | h | C | core/src/index/thirdparty/faiss/IndexSQHybrid.h | ReigenAraka/milvus | b2f19ace0e1dcd431a512141f42b748581d4b92d | [
"Apache-2.0"
] | null | null | null | core/src/index/thirdparty/faiss/IndexSQHybrid.h | ReigenAraka/milvus | b2f19ace0e1dcd431a512141f42b748581d4b92d | [
"Apache-2.0"
] | null | null | null | core/src/index/thirdparty/faiss/IndexSQHybrid.h | ReigenAraka/milvus | b2f19ace0e1dcd431a512141f42b748581d4b92d | [
"Apache-2.0"
] | 1 | 2019-12-16T10:13:43.000Z | 2019-12-16T10:13:43.000Z | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// -*- c++ -*-
#ifndef FAISS_INDEX_SQ_HYBRID_H
#define FAISS_INDEX_SQ_HYBRID_H
#include <stdint.h>
#include <vector>
#include <faiss/IndexIVF.h>
#include <faiss/impl/ScalarQuantizer.h>
namespace faiss {
/** An IVF implementation where the components of the residuals are
* encoded with a scalar uniform quantizer. All distance computations
* are asymmetric, so the encoded vectors are decoded and approximate
* distances are computed.
*/
struct IndexIVFSQHybrid: IndexIVF {
ScalarQuantizer sq;
bool by_residual;
IndexIVFSQHybrid(Index *quantizer, size_t d, size_t nlist,
ScalarQuantizer::QuantizerType qtype,
MetricType metric = METRIC_L2,
bool encode_residual = true);
IndexIVFSQHybrid();
void train_residual(idx_t n, const float* x) override;
void encode_vectors(idx_t n, const float* x,
const idx_t *list_nos,
uint8_t * codes,
bool include_listnos=false) const override;
void add_with_ids(idx_t n, const float* x, const idx_t* xids) override;
InvertedListScanner *get_InvertedListScanner (bool store_pairs)
const override;
void reconstruct_from_offset (int64_t list_no, int64_t offset,
float* recons) const override;
/* standalone codec interface */
void sa_decode (idx_t n, const uint8_t *bytes,
float *x) const override;
};
}
#endif
| 26.121212 | 75 | 0.645592 | [
"vector"
] |
1fe82b0132612c047766e048a52c120a61b880da | 2,478 | h | C | coast/modules/WorkerPoolManager/WorkerPoolManagerModulePoolManager.h | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/modules/WorkerPoolManager/WorkerPoolManagerModulePoolManager.h | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/modules/WorkerPoolManager/WorkerPoolManagerModulePoolManager.h | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#ifndef _WorkerPoolManagerModulePoolManager_H
#define _WorkerPoolManagerModulePoolManager_H
#include "ThreadPools.h"
//---- WorkerPoolManagerModuleWorker -----------------------------------------------
class WorkerPoolManagerModuleWorker : public WorkerThread
{
public:
WorkerPoolManagerModuleWorker(const char *name = "WorkerPoolManagerModuleWorker");
~WorkerPoolManagerModuleWorker();
protected:
//--- redefine the following virtual methods for your specific workers
//: used for general initialization of the worker when it is created
// arbitrary parameters may be passed using the ROAnything...
// CAUTION: make sure to copy whatever you need from the ROAnything
// into some instance variable
virtual void DoInit(ROAnything workerInit);
//: do the work (using the informations you stored in the instance variables)
virtual void DoProcessWorkload();
//:subclass hook
virtual void DoWorkingHook(ROAnything workerConfig);
virtual void DoTerminationRequestHook(ROAnything);
virtual void DoTerminatedHook();
private:
Anything fWork;
Anything fWorkerInitCfg;
};
//---- SybCTPoolManager ------------------------------------------------
// this class demonstrates how to properly subclass WorkerPoolManager
class WorkerPoolManagerModulePoolManager : public WorkerPoolManager
{
public:
WorkerPoolManagerModulePoolManager(String name);
virtual ~WorkerPoolManagerModulePoolManager();
bool Init(const ROAnything config);
void Enter(Anything &args);
protected:
// friend WorkerPoolManagerTest;
//:allocate the handle request thread pool
virtual void DoAllocPool(ROAnything args);
//:cleanup hook for re-initialization of pool
virtual void DoDeletePool(ROAnything args);
virtual WorkerThread *DoGetWorker(long i);
private:
// block the following default elements of this class
// because they're not allowed to be used
WorkerPoolManagerModulePoolManager(const WorkerPoolManagerModulePoolManager &);
WorkerPoolManagerModulePoolManager &operator=(const WorkerPoolManagerModulePoolManager &);
protected:
WorkerPoolManagerModuleWorker *fRequests; // vector storing all request thread objects
};
#endif
| 32.181818 | 102 | 0.765133 | [
"vector"
] |
1feb7ff895f586d8fdddf79ebe699fa6a9e271e8 | 1,400 | h | C | Forms_Chinczyk/Gracz.h | qvx3/KrystianLudo | a26c238a469ab87e5de50a756b57b3990bc9eac7 | [
"CC0-1.0"
] | null | null | null | Forms_Chinczyk/Gracz.h | qvx3/KrystianLudo | a26c238a469ab87e5de50a756b57b3990bc9eac7 | [
"CC0-1.0"
] | null | null | null | Forms_Chinczyk/Gracz.h | qvx3/KrystianLudo | a26c238a469ab87e5de50a756b57b3990bc9eac7 | [
"CC0-1.0"
] | null | null | null | #pragma once
#include "Pion.h"
// Konsola, string
#include < iostream >
#include < conio.h >
// Kolekcje pionow
#include < vector >
// Obowiazkowo dla STL/CLR
using namespace std ;
class Gracz
{
static int PIONOW ;
static bool BETATEST ;
// Personalia
string imie ;
int numer ;
// Ile pionow ukonczylo mape
int naMecie ;
// Ile pionow moich na mapie
int naMapie ;
// Kolekcje pionkow kazdego z graczy
// Symbole
// Gracza 0: a do d
// Gracza 1: e do h itd.
vector < Pion > start ;
// METODY
public :
// Interfejs dla kompozycji w planszy
~Gracz(void);
Gracz( bool betatest , string imie , int numer );
// Ruch postaciami tam i z powrotem
void setPion ( int ktory , Pion ::Stan stan ) ;
// Ruch tylko wprzod po planszy
// pod warunkiem, ze jeszcze starczy mapy,
// Zwraca false jesli nie mozna dalej isc
bool setPion ( int ktory , int ile ) ;
// Sprawdz czy gracz spelnil warunek zwyciestwa
// Przykladowo wystarczy 1 pionek
bool wygrana () ;
string getImie () ;
void setImie ( string imie ) ;
// Ruch i wyswietlanie w konsoli
Pion & getPion ( int ktory ) ;
//////////////////////////
// Nowe dla GUI
int getNaMapie () ;
int getNaMecie () ;
private :
// Placeholders
// Po ukonczeniu mapy
vector < Pion * > meta ;
// Niepotrzebne
Gracz(void);
};
| 8.860759 | 50 | 0.610714 | [
"vector"
] |
1fff90dacdb778f7906b3348e5d9262aca3b98d8 | 1,533 | h | C | camera/hal/intel/ipu6/src/core/StreamSource.h | dgreid/platform2 | 9b8b30df70623c94f1c8aa634dba94195343f37b | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | camera/hal/intel/ipu6/src/core/StreamSource.h | dgreid/platform2 | 9b8b30df70623c94f1c8aa634dba94195343f37b | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | camera/hal/intel/ipu6/src/core/StreamSource.h | dgreid/platform2 | 9b8b30df70623c94f1c8aa634dba94195343f37b | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2019-2020 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "BufferQueue.h"
#include "iutils/Errors.h"
namespace icamera {
/**
* \interface StreamSource
* It's an abstract interface for buffer producers, like CaptureUnit, FileSource
* or external source producer.
*/
class StreamSource : public BufferProducer {
public:
StreamSource(int memType) : BufferProducer(memType) {}
virtual ~StreamSource() {}
/* Initialize stream source */
virtual int init() = 0;
/* Deinitialize stream source */
virtual void deinit() = 0;
/* Configure stream source */
virtual int configure(const std::map<Port, stream_t>& outputFrames,
const std::vector<ConfigMode>& configModes) = 0;
/* Start stream source */
virtual int start() = 0;
/* Stop stream source */
virtual int stop() = 0;
/* Remove all liateners */
virtual void removeAllFrameAvailableListener() = 0;
};
} //namespace icamera
| 31.285714 | 80 | 0.692107 | [
"vector"
] |
9504b2fe8db7bdc997a285e4f73c8d20462850a5 | 4,133 | h | C | CPP/Targets/SupportWFLib/symbian/NewAudioServerTypes.h | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 6 | 2015-12-01T01:12:33.000Z | 2021-07-24T09:02:34.000Z | CPP/Targets/SupportWFLib/symbian/NewAudioServerTypes.h | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | null | null | null | CPP/Targets/SupportWFLib/symbian/NewAudioServerTypes.h | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 2 | 2017-02-02T19:31:29.000Z | 2018-12-17T21:00:45.000Z | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef NEWAUDIOSERVERTYPES_H
#define NEWAUDIOSERVERTYPES_H
#include "config.h"
// #include<e32std.h>
#include<vector>
// #include<badesca.h>
namespace NewAudioServerTypes {
enum TRequestTypes {
CancelAnyRequest,
PrepareSoundRequest,
PlaySoundRequest,
VolumeRequest,
};
/// Special sound for timing
_LIT(KSoundTiming, "XXXSoundTiming");
/// Special sound for the last clip
_LIT(KSoundEnd, "XXXSoundEnd");
}
/// Callback class for the audio player
class NewAudioPlayerListener {
public:
virtual void playCompleteL(TInt aErr) = 0;
};
/// Callback for the audio converter class.
class NewAudioConverterListener {
public:
virtual void conversionCompleteL(TInt aErr, long durationMS ) = 0;
};
/**
* Class containing info about a clip and the converted clip.
* FIXME: Leave-safety.
*/
class ClipBuf {
public:
void initEmpty( const TDesC& fileName );
ClipBuf(const TDesC& fileName );
/// Copy constructor
ClipBuf(const ClipBuf& other);
/// Sets number of channels and samplerate in Hz
void setAudioProperties( int numchannels,
int samplerate ) ;
void handoverAudioData( TDes8& audioData,
const TTimeIntervalMicroSeconds& timeMicro ) ;
void setAudioData(const TDesC8& audioData,
const TTimeIntervalMicroSeconds& timeMicro ) ;
int sampleRate() const ;
int numChannels() const ;
bool isConverted() const;
int getNbrBuffers() const;
const TPtrC8& getBuffer(int i );
const TDesC& getFileName() const;
~ClipBuf();
private:
/// Pointer to the data.
TPtrC8 m_des;
/// Buffer where the data is stored
TUint8* m_realBuf;
/// File name of the clip
HBufC* m_fileName;
public:
/// Duration of the clip
class TTimeIntervalMicroSeconds m_time;
/// Pointers to different parts of the buffers
class CPtrC8Array* m_array;
/// Number of channels
int m_numChannels;
/// Sample rate in Hz
int m_sampleRate;
};
typedef std::vector<ClipBuf*> TClips;
class ClipBufIterator {
public:
ClipBufIterator();
ClipBufIterator(const TClips& clips);
ClipBufIterator& operator++();
const TDesC8* operator*() const;
private:
/// Empty vector to use when initializing empty. Remove later
TClips m_emptyClips;
const TClips* m_clips;
TClips::const_iterator m_clipIt;
int m_bufNbr;
};
#endif
| 31.075188 | 207 | 0.699008 | [
"vector"
] |
950d13a40ab655608b163e58d78580fb29b6de19 | 4,775 | h | C | libtsuba/include/tsuba/RDG.h | swreinehr/katana | 9b4eef12dfeb79e35aa07a3a335ce35b3e97c08d | [
"BSD-3-Clause"
] | 1 | 2021-01-29T23:08:11.000Z | 2021-01-29T23:08:11.000Z | libtsuba/include/tsuba/RDG.h | swreinehr/katana | 9b4eef12dfeb79e35aa07a3a335ce35b3e97c08d | [
"BSD-3-Clause"
] | null | null | null | libtsuba/include/tsuba/RDG.h | swreinehr/katana | 9b4eef12dfeb79e35aa07a3a335ce35b3e97c08d | [
"BSD-3-Clause"
] | 1 | 2021-05-06T02:58:13.000Z | 2021-05-06T02:58:13.000Z | #ifndef GALOIS_LIBTSUBA_TSUBA_RDG_H_
#define GALOIS_LIBTSUBA_TSUBA_RDG_H_
#include <cstdint>
#include <memory>
#include <string>
#include <arrow/api.h>
#include <arrow/chunked_array.h>
#include <nlohmann/json.hpp>
#include "galois/Result.h"
#include "galois/Uri.h"
#include "galois/config.h"
#include "tsuba/Errors.h"
#include "tsuba/FileFrame.h"
#include "tsuba/FileView.h"
#include "tsuba/PartitionMetadata.h"
#include "tsuba/RDGLineage.h"
#include "tsuba/WriteGroup.h"
#include "tsuba/tsuba.h"
namespace tsuba {
class RDGMeta;
class RDGCore;
struct PropStorageInfo;
class GALOIS_EXPORT RDG {
public:
RDG(const RDG& no_copy) = delete;
RDG& operator=(const RDG& no_dopy) = delete;
RDG();
~RDG();
RDG(RDG&& other) noexcept;
RDG& operator=(RDG&& other) noexcept;
/// Perform some checks on assumed invariants
galois::Result<void> Validate() const;
/// Determine if two RDGs are Equal
bool Equals(const RDG& other) const;
/// Store this RDG at `handle`, if `ff` is not null, it is assumed to contain
/// an updated topology and persisted as such
galois::Result<void> Store(
RDGHandle handle, const std::string& command_line,
std::unique_ptr<FileFrame> ff = nullptr);
galois::Result<void> AddNodeProperties(
const std::shared_ptr<arrow::Table>& table);
galois::Result<void> AddEdgeProperties(
const std::shared_ptr<arrow::Table>& table);
galois::Result<void> RemoveNodeProperty(uint32_t i);
galois::Result<void> RemoveEdgeProperty(uint32_t i);
void MarkAllPropertiesPersistent();
galois::Result<void> MarkNodePropertiesPersistent(
const std::vector<std::string>& persist_node_props);
galois::Result<void> MarkEdgePropertiesPersistent(
const std::vector<std::string>& persist_edge_props);
/// Explain to graph how it is derived from previous version
void AddLineage(const std::string& command_line);
/// Load the RDG described by the metadata in handle into memory
static galois::Result<RDG> Make(
RDGHandle handle, const std::vector<std::string>* node_props = nullptr,
const std::vector<std::string>* edge_props = nullptr);
galois::Result<void> UnbindTopologyFileStorage();
void AddMirrorNodes(std::shared_ptr<arrow::ChunkedArray>&& a) {
mirror_nodes_.emplace_back(std::move(a));
}
void AddMasterNodes(std::shared_ptr<arrow::ChunkedArray>&& a) {
master_nodes_.emplace_back(std::move(a));
}
//
// accessors and mutators
//
const galois::Uri& rdg_dir() const { return rdg_dir_; }
void set_rdg_dir(const galois::Uri& rdg_dir) { rdg_dir_ = rdg_dir; }
/// The table of node properties
const std::shared_ptr<arrow::Table>& node_table() const;
/// The table of edge properties
const std::shared_ptr<arrow::Table>& edge_table() const;
const std::vector<std::shared_ptr<arrow::ChunkedArray>>& master_nodes()
const {
return master_nodes_;
}
void set_master_nodes(std::vector<std::shared_ptr<arrow::ChunkedArray>>&& a) {
master_nodes_ = std::move(a);
}
const std::vector<std::shared_ptr<arrow::ChunkedArray>>& mirror_nodes()
const {
return mirror_nodes_;
}
void set_mirror_nodes(std::vector<std::shared_ptr<arrow::ChunkedArray>>&& a) {
mirror_nodes_ = std::move(a);
}
const std::shared_ptr<arrow::ChunkedArray>& local_to_global_vector() const {
return local_to_global_vector_;
}
void set_local_to_global_vector(std::shared_ptr<arrow::ChunkedArray>&& a) {
local_to_global_vector_ = std::move(a);
}
const PartitionMetadata& part_metadata() const;
void set_part_metadata(const PartitionMetadata& metadata);
const FileView& topology_file_storage() const;
private:
RDG(std::unique_ptr<RDGCore>&& core);
void InitEmptyTables();
galois::Result<void> DoMake(const galois::Uri& metadata_dir);
static galois::Result<RDG> Make(
const RDGMeta& meta, const std::vector<std::string>* node_props,
const std::vector<std::string>* edge_props);
galois::Result<void> AddPartitionMetadataArray(
const std::shared_ptr<arrow::Table>& table);
galois::Result<std::vector<tsuba::PropStorageInfo>> WritePartArrays(
const galois::Uri& dir, tsuba::WriteGroup* desc);
galois::Result<void> DoStore(
RDGHandle handle, const std::string& command_line,
std::unique_ptr<WriteGroup> desc);
//
// Data
//
std::unique_ptr<RDGCore> core_;
std::vector<std::shared_ptr<arrow::ChunkedArray>> mirror_nodes_;
std::vector<std::shared_ptr<arrow::ChunkedArray>> master_nodes_;
std::shared_ptr<arrow::ChunkedArray> local_to_global_vector_;
/// name of the graph that was used to load this RDG
galois::Uri rdg_dir_;
// How this graph was derived from the previous version
RDGLineage lineage_;
};
} // namespace tsuba
#endif
| 28.76506 | 80 | 0.717696 | [
"vector"
] |
95148872619ae5bdded6d8cbfac371fdc387cf2c | 3,014 | h | C | Engine/ModuleRenderer3D.h | elliotjb/CulverinEngine-Project3 | cc386713dd786e2a52cc9b219a0d701a9398f202 | [
"MIT"
] | 2 | 2018-01-20T18:17:22.000Z | 2018-01-20T18:17:28.000Z | Engine/ModuleRenderer3D.h | TempName0/TempMotor3D_P3 | cc386713dd786e2a52cc9b219a0d701a9398f202 | [
"MIT"
] | null | null | null | Engine/ModuleRenderer3D.h | TempName0/TempMotor3D_P3 | cc386713dd786e2a52cc9b219a0d701a9398f202 | [
"MIT"
] | 1 | 2018-06-16T16:12:11.000Z | 2018-06-16T16:12:11.000Z | #ifndef _MODULERENDERER3D_
#define _MODULERENDERER3D_
#include "Globals.h"
#include "Module.h"
#include "Light.h"
#include "parson.h"
#include "ModuleShaders.h"
#include "Materials.h"
#include "Screenshot_and_gif.h"
#include <gl/GL.h>
#include <gl/GLU.h>
#define MAX_LIGHTS 9
class CompCamera;
class CubeMap_Texture;
class DepthCubeMap;
enum RenderMode
{
DEFAULT,
GLOW,
DEPTH
};
class ModuleRenderer3D : public Module
{
public:
ModuleRenderer3D(bool start_enabled = true);
~ModuleRenderer3D();
bool Init(JSON_Object* node);
bool Start();
update_status PreUpdate(float dt);
//update_status Update(float dt);
update_status PostUpdate(float dt);
update_status UpdateConfig(float dt);
bool SaveConfig(JSON_Object* node);
bool CleanUp();
void SetActiveCamera(CompCamera* cam);
void SetSceneCamera(CompCamera* cam);
void SetGameCamera(CompCamera* cam);
CompCamera* GetActiveCamera();
void UpdateProjection(CompCamera* cam);
void OnResize(int width, int height);
float2 LoadImage_devil(const char * theFileName, GLuint *buff);
bool loadTextureFromPixels32(GLuint * id_pixels, GLuint width_img, GLuint height_img, GLuint *buff);
void RenderSceneWiewport();
void BlurShaderVars(int i);
void GlowShaderVars();
public:
SDL_GLContext context;
CompCamera* active_camera = nullptr; /* Render the scene through the active camera (it can be SCENE camera or GAME camera)*/
CompCamera* scene_camera = nullptr;
CompCamera* game_camera = nullptr;
// Configuration Options -----
bool depth_test = false;
bool cull_face = false;
bool lighting = false;
bool color_material = false;
bool texture_2d = false;
bool wireframe = false;
bool smooth = true;
bool fog_active = false;
bool normals = false;
bool bounding_box = false;
GLfloat fog_density = 0;
// --------------------------
//Texture Creation Default
uint id_checkImage = 0;
unsigned char checkImage[64][32][4];
// Shaders
ShaderProgram* default_shader = nullptr;
ShaderProgram* particles_shader = nullptr;
ShaderProgram* lights_billboard_shader = nullptr;
ShaderProgram* non_glow_shader = nullptr;
ShaderProgram* non_glow_skinning_shader = nullptr;
ShaderProgram* blur_shader_tex = nullptr;
ShaderProgram* final_shader_tex = nullptr;
ShaderProgram* cube_map_shader = nullptr;
ResourceMaterial* default_texture = nullptr;
Material* default_material = nullptr;
Material* non_glow_material = nullptr;
Material* non_glow_skinning_material = nullptr;
Material* final_tex_material = nullptr;
RenderMode render_mode = RenderMode::DEFAULT;
GLuint vertexbuffer;
GLuint UVbuffer;
GLuint VertexArrayID;
GLuint ibo_cube_elements;
std::string dmg_texture_name = "";
uint dmg_texture_uid = 0;
ResourceMaterial* dmg_texture_res = nullptr;
//Reflexion Cubemaps
CubeMap_Texture* temp_cubemap = nullptr;
std::vector<CubeMap_Texture*> cube_maps;
//TEMP
int blur_amount = 28;
float blur_scale = 0.3;
float blur_strength = 0.0f;
private:
Culverin_Screenshot screenshot;
Culverin_Gif gif;
};
#endif
| 23.546875 | 125 | 0.760451 | [
"render",
"vector"
] |
95175af0bcef3faae476de9311a770e76f570e73 | 2,331 | h | C | kr_viz/rviz_ba_viewer/include/rviz_ba_viewer/ba_display.h | KumarRobotics/kr_utils | 049685a8fd9bb8a37490cafeda94b4ab652c829e | [
"Apache-2.0"
] | 3 | 2016-10-12T01:59:44.000Z | 2019-10-19T05:03:26.000Z | kr_viz/rviz_ba_viewer/include/rviz_ba_viewer/ba_display.h | KumarRobotics/kr_utils | 049685a8fd9bb8a37490cafeda94b4ab652c829e | [
"Apache-2.0"
] | 3 | 2016-02-25T08:58:26.000Z | 2016-02-29T07:25:38.000Z | kr_viz/rviz_ba_viewer/include/rviz_ba_viewer/ba_display.h | KumarRobotics/kr_utils | 049685a8fd9bb8a37490cafeda94b4ab652c829e | [
"Apache-2.0"
] | 11 | 2015-01-13T12:39:24.000Z | 2019-10-19T05:03:30.000Z | /*
* ba_display.h
*
* Copyright (c) 2014 Gareth Cross, Chao Qu. All rights reserved.
*/
#ifndef RVIZ_BA_DISPLAY_H_
#define RVIZ_BA_DISPLAY_H_
#include <rviz/display.h>
#include <QObject>
#include <map>
#include <rviz_ba_viewer/keyframe_object.hpp>
#include <rviz_ba_viewer/feature_rays_object.hpp>
#include <rviz_ba_viewer/BaGraph.h> // generated message
#include <rviz_ba_viewer/KeyFrame.h>
#include <rviz_ba_viewer/BaPoint.h>
namespace rviz {
class Property;
class IntProperty;
class RosTopicProperty;
class FloatProperty;
class BoolProperty;
/**
* @brief RViz plugin for rendering a bundle-adjustment graph.
*/
class BAGraphDisplay : public Display {
Q_OBJECT
public:
BAGraphDisplay();
virtual ~BAGraphDisplay();
/// Overrides from Display
virtual void onInitialize();
virtual void fixedFrameChanged();
virtual void reset();
virtual void update(float,float);
protected Q_SLOTS:
void updateTopic(); /// When topic is changed.
void updateRenderEvery(); /// When 'render every' option is changed.
void updateScale(); /// When scale option is changed.
void updateImageEnabled(); /// When images are enabled/disabled
protected:
/// Properties for the GUI
RosTopicProperty * topic_property_;
IntProperty * render_every_property_;
FloatProperty * scale_property_;
BoolProperty * image_enabled_property_;
/// ROS objects
ros::Subscriber sub_graph_;
/// Graph objects
/// @todo: as this plugin scales up, this should be probably refactored into a
/// proper class
struct KeyFrame {
typedef std::shared_ptr<KeyFrame> Ptr;
std::map<int, rviz_ba_viewer::BaPoint> points;
};
std::map<int, KeyFrame::Ptr> keyframes_;
/// Display objects
std::map<int, KeyFrameObject::Ptr> kf_objects_;
std::map<int, FeatureRaysObject::Ptr> rays_;
bool dirty_{false};
double scale_{1};
bool image_enabled_{true};
std::string frame_;
/// Overrides from Display
virtual void onEnable();
virtual void onDisable();
virtual void subscribe();
virtual void unsubscribe();
/// Apply the fixed-frame transform.
void applyFixedTransform();
/// Callback initiated by ROS topic.
void topicCallback(const rviz_ba_viewer::BaGraphConstPtr&msg);
/// Destroy the scene and ogre objects.
void cleanup();
};
} // namespace rviz
#endif
| 23.785714 | 80 | 0.724153 | [
"render",
"transform"
] |
95178441bc79b4653cee6a546c10751862cdf46c | 2,416 | h | C | Engine/Source/Editor/Sequencer/Private/SequencerMovieSceneObjectManager.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Editor/Sequencer/Private/SequencerMovieSceneObjectManager.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Editor/Sequencer/Private/SequencerMovieSceneObjectManager.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "MovieSceneObjectManager.h"
#include "SequencerPossessedObject.h"
#include "SequencerMovieSceneObjectManager.generated.h"
/**
* Movie scene object manager used by Sequencer.
*/
UCLASS(BlueprintType, MinimalAPI)
class USequencerMovieSceneObjectManager
: public UObject
, public IMovieSceneObjectManager
{
GENERATED_UCLASS_BODY()
/** Virtual destructor. */
virtual ~USequencerMovieSceneObjectManager();
public:
// IMovieSceneObjectManager interface
virtual bool AllowsSpawnableObjects() const override;
virtual void BindPossessableObject(const FGuid& ObjectId, UObject& PossessedObject) override;
virtual bool CanPossessObject(UObject& Object) const override;
virtual void DestroyAllSpawnedObjects(UMovieScene& MovieScene) override;
virtual FGuid FindObjectId(const UMovieScene& MovieScene, UObject& Object) const override;
virtual UObject* FindObject(const FGuid& ObjectId) const override;
virtual void SpawnOrDestroyObjects(UMovieScene* MovieScene, bool DestroyAll) override;
virtual bool TryGetObjectDisplayName(const FGuid& ObjectId, FText& OutDisplayName) const override;
virtual void UnbindPossessableObjects(const FGuid& ObjectId) override;
protected:
/**
* Deselect all proxy actors in the Editor.
*
* @todo sequencer: remove Editor dependencies from this class
*/
SEQUENCER_API void DeselectAllActors();
/**
* Get the world that possessed actors belong to or where spawned actors should go.
*
* @return The world object.
* @todo sequencer: remove Editor dependencies from this class
*/
SEQUENCER_API UWorld* GetWorld() const;
private:
/** Handles changes of non-auto-keyed properties on any object. */
void HandlePropagateObjectChanges(UObject* Object);
/** Refresh either the reference actor or the data descriptor BP after its puppet proxy actor has been changed. */
void PropagateActorChanges(const FGuid& ObjectId, AActor* Actor);
private:
/** Collection of possessed objects. */
// @todo sequencer: gmp: need support for UStruct keys in TMap
UPROPERTY()
TMap<FString, FSequencerPossessedObject> PossessedObjects;
//TMap<FGuid, FSequencerBinding> Bindings;
/** The object change listener. */
TWeakPtr<ISequencerObjectChangeListener> ObjectChangeListener;
/** Collection of spawned proxy actors. */
TMap<FGuid, TWeakObjectPtr<AActor>> SpawnedActors;
};
| 31.789474 | 115 | 0.784354 | [
"object"
] |
9524050e9b105b5c10f71ddfa6d2f94c543f391a | 225 | h | C | GameEngine/Headers/ModelCE.h | GPUWorks/OpenGL-Mini-CAD-2D | fedb903302f82a1d1ff0ca6776687a60a237008a | [
"MIT"
] | 1 | 2021-08-10T02:48:57.000Z | 2021-08-10T02:48:57.000Z | GameEngine/Headers/ModelCE.h | GPUWorks/OpenGL-Mini-CAD-2D | fedb903302f82a1d1ff0ca6776687a60a237008a | [
"MIT"
] | null | null | null | GameEngine/Headers/ModelCE.h | GPUWorks/OpenGL-Mini-CAD-2D | fedb903302f82a1d1ff0ca6776687a60a237008a | [
"MIT"
] | null | null | null | #pragma once
namespace model
{
enum CurveType
{
NONE = 0,
HERMITE = 1,
BEZIER = 2,
BSPLINE = 4,
NURBS = 8,
SPLINE = 16,
S_BEZIER = 32,
S_SPLINE = 64,
S_NURBS = 128,
AXIS = 256
};
} | 11.25 | 17 | 0.515556 | [
"model"
] |
953523254c74b68dfcb1f05e456a582692859bae | 766 | h | C | SOLVER/src/core/point/solid_fluid/SFCoupling3D.h | kuangdai/AxiSEM3D | fd9da14e9107783e3b07b936c67af2412146e099 | [
"MIT"
] | 17 | 2016-12-16T03:13:57.000Z | 2021-12-15T01:56:45.000Z | SOLVER/src/core/point/solid_fluid/SFCoupling3D.h | syzeng-duduxi/AxiSEM3D | fd9da14e9107783e3b07b936c67af2412146e099 | [
"MIT"
] | 6 | 2018-01-15T17:17:20.000Z | 2020-03-18T09:53:58.000Z | SOLVER/src/core/point/solid_fluid/SFCoupling3D.h | syzeng-duduxi/AxiSEM3D | fd9da14e9107783e3b07b936c67af2412146e099 | [
"MIT"
] | 19 | 2016-12-28T16:55:00.000Z | 2021-06-23T01:02:16.000Z | // SFCoupling3D.h
// created by Kuangdai on 5-Apr-2016
// 3D solid-fluid boundary condition
#pragma once
#include "SFCoupling.h"
class SFCoupling3D: public SFCoupling {
public:
SFCoupling3D(const RMatX3 &n, const RMatX3 &n_invmf):
mNormal_unassembled(n),
mNormal_assembled_invMassFluid(n_invmf) {};
// solid-fluid coupling
void coupleFluidToSolid(const CColX &fluidStiff, CMatX3 &solidStiff) const;
void coupleSolidToFluid(const CMatX3 &solidDispl, CColX &fluidStiff) const;
// verbose
std::string verbose() const {return "SFCoupling3D";};
// check compatibility
void checkCompatibility(int nr) const;
private:
RMatX3 mNormal_unassembled;
RMatX3 mNormal_assembled_invMassFluid;
};
| 26.413793 | 80 | 0.708877 | [
"3d",
"solid"
] |
4e667c4fa01d4769e176ded1a78353923e0af25c | 1,190 | h | C | Code/Modules/mutalisk/mesh.h | mrneo240/suicide-barbie | c8b01f9c04755e7f6d1d261fc4a1600cd6705b96 | [
"MIT"
] | 57 | 2021-01-02T00:18:22.000Z | 2022-03-27T14:40:25.000Z | Code/Modules/mutalisk/mesh.h | mrneo240/suicide-barbie | c8b01f9c04755e7f6d1d261fc4a1600cd6705b96 | [
"MIT"
] | 1 | 2021-01-05T20:43:02.000Z | 2021-01-11T23:04:41.000Z | Code/Modules/mutalisk/mesh.h | mrneo240/suicide-barbie | c8b01f9c04755e7f6d1d261fc4a1600cd6705b96 | [
"MIT"
] | 8 | 2021-01-01T22:34:43.000Z | 2022-03-22T01:21:26.000Z | #ifndef MUTALISK_DATA_MESH_H_
#define MUTALISK_DATA_MESH_H_
#include "common.h"
#include <string>
namespace mutalisk { namespace data
{
struct base_mesh
{
unsigned int vertexCount;
unsigned int vertexStride;
unsigned int vertexDataSize;
byte* vertexData;
unsigned int indexCount;
unsigned int indexSize;
byte* indexData;
struct Subset
{
unsigned int offset;
unsigned int count;
};
array<Subset> subsets;
// memory management
base_mesh(); ~base_mesh();
};
struct skin_info
{
struct Bone
{
Mat16 matrix;
std::string name;
};
unsigned int weightsPerVertex;
// unsigned int boneCount;
array<Bone> bones;
// memory management
skin_info(); ~skin_info();
};
// I/O
template <typename In> In& operator>> (In& i, base_mesh& mesh);
template <typename Out> Out& operator<< (Out& o, base_mesh const& mesh);
template <typename In> In& operator>> (In& i, skin_info& skin);
template <typename Out> Out& operator<< (Out& o, skin_info const& skin);
// memory management
void clear(base_mesh& mesh);
void clear(skin_info& skin);
} // namespace data
} // namespace mutalisk
#include "mesh.inl"
#endif // MUTALISK_DATA_MESH_H_
| 18.307692 | 73 | 0.696639 | [
"mesh"
] |
4e6ba0c5dab945e5924edf856fd075a173592e79 | 12,796 | c | C | components/aos/src/ringblk_buf.c | 1847123212/YoC-open | f4e20c67256472d863ea6d118e3ecbaa1e879d4a | [
"Apache-2.0"
] | 9 | 2020-05-12T03:01:55.000Z | 2021-08-12T10:22:31.000Z | components/aos/src/ringblk_buf.c | 1847123212/YoC-open | f4e20c67256472d863ea6d118e3ecbaa1e879d4a | [
"Apache-2.0"
] | null | null | null | components/aos/src/ringblk_buf.c | 1847123212/YoC-open | f4e20c67256472d863ea6d118e3ecbaa1e879d4a | [
"Apache-2.0"
] | 12 | 2020-04-15T11:37:33.000Z | 2021-09-13T13:19:04.000Z | /*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2018-08-25 armink the first version
*/
#include "aos/ringblk_buf.h"
#include <aos/debug.h>
#include <aos/kernel.h>
/**
* ring block buffer object initialization
*
* @param rbb ring block buffer object
* @param buf buffer
* @param buf_size buffer size
* @param block_set block set
* @param blk_max_num max block number
*
* @note When your application need align access, please make the buffer address is aligned.
*/
void rbb_init(rbb_t rbb, uint8_t *buf, size_t buf_size, rbb_blk_t block_set, size_t blk_max_num)
{
size_t i;
aos_assert(rbb);
aos_assert(buf);
aos_assert(block_set);
rbb->buf = buf;
rbb->buf_size = buf_size;
rbb->blk_set = block_set;
rbb->blk_max_num = blk_max_num;
slist_init(&rbb->blk_list);
/* initialize block status */
for (i = 0; i < blk_max_num; i++) {
block_set[i].status = RBB_BLK_UNUSED;
}
}
/**
* ring block buffer object create
*
* @param buf_size buffer size
* @param blk_max_num max block number
*
* @return != NULL: ring block buffer object
* NULL: create failed
*/
rbb_t rbb_create(size_t buf_size, size_t blk_max_num)
{
rbb_t rbb = NULL;
uint8_t *buf;
rbb_blk_t blk_set;
rbb = (rbb_t)aos_malloc(sizeof(struct _rbb));
if (!rbb) {
return NULL;
}
buf = (uint8_t *)aos_malloc(buf_size);
if (!buf) {
aos_free(rbb);
return NULL;
}
blk_set = (rbb_blk_t)aos_malloc(sizeof(struct rbb_blk) * blk_max_num);
if (!blk_set) {
aos_free(buf);
aos_free(rbb);
return NULL;
}
rbb_init(rbb, buf, buf_size, blk_set, blk_max_num);
return rbb;
}
/**
* ring block buffer object destroy
*
* @param rbb ring block buffer object
*/
void rbb_destroy(rbb_t rbb)
{
aos_assert(rbb);
aos_free(rbb);
aos_free(rbb->buf);
aos_free(rbb->blk_set);
}
static rbb_blk_t find_empty_blk_in_set(rbb_t rbb)
{
size_t i;
aos_assert(rbb);
for (i = 0; i < rbb->blk_max_num; i ++) {
if (rbb->blk_set[i].status == RBB_BLK_UNUSED) {
return &rbb->blk_set[i];
}
}
return NULL;
}
/**
* Allocate a block by given size. The block will add to blk_list when allocate success.
*
* @param rbb ring block buffer object
* @param blk_size block size
*
* @note When your application need align access, please make the blk_szie is aligned.
*
* @return != NULL: allocated block
* NULL: allocate failed
*/
rbb_blk_t rbb_blk_alloc(rbb_t rbb, size_t blk_size)
{
size_t empty1 = 0, empty2 = 0;
rbb_blk_t head, tail, new = NULL;
aos_assert(rbb);
aos_assert(blk_size < (1L << 24));
new = find_empty_blk_in_set(rbb);
if (slist_entry_number(&rbb->blk_list) < rbb->blk_max_num && new) {
if (slist_entry_number(&rbb->blk_list) > 0) {
head = slist_first_entry(&rbb->blk_list, struct rbb_blk, list);
tail = slist_tail_entry(&rbb->blk_list, struct rbb_blk, list);
if (head->buf <= tail->buf) {
/**
* head tail
* +--------------------------------------+-----------------+------------------+
* | empty2 | block1 | block2 | block3 | empty1 |
* +--------------------------------------+-----------------+------------------+
* rbb->buf
*/
empty1 = (rbb->buf + rbb->buf_size) - (tail->buf + tail->size);
empty2 = head->buf - rbb->buf;
if (empty1 >= blk_size) {
// slist_add_tail(&rbb->blk_list, &new->list);
slist_add_tail(&new->list, &rbb->blk_list);
new->status = RBB_BLK_INITED;
new->buf = tail->buf + tail->size;
new->size = blk_size;
} else if (empty2 >= blk_size) {
// slist_add_tail(&rbb->blk_list, &new->list);
slist_add_tail(&new->list, &rbb->blk_list);
new->status = RBB_BLK_INITED;
new->buf = rbb->buf;
new->size = blk_size;
} else {
/* no space */
new = NULL;
}
} else {
/**
* tail head
* +----------------+-------------------------------------+--------+-----------+
* | block3 | empty1 | block1 | block2 |
* +----------------+-------------------------------------+--------+-----------+
* rbb->buf
*/
empty1 = head->buf - (tail->buf + tail->size);
if (empty1 >= blk_size) {
// slist_add_tail(&rbb->blk_list, &new->list);
slist_add_tail(&new->list, &rbb->blk_list);
new->status = RBB_BLK_INITED;
new->buf = tail->buf + tail->size;
new->size = blk_size;
} else {
/* no space */
new = NULL;
}
}
} else {
/* the list is empty */
// slist_add_tail(&rbb->blk_list, &new->list);
slist_add_tail(&new->list, &rbb->blk_list);
new->status = RBB_BLK_INITED;
new->buf = rbb->buf;
new->size = blk_size;
}
} else {
new = NULL;
}
return new;
}
/**
* put a block to ring block buffer object
*
* @param block the block
*/
void rbb_blk_put(rbb_blk_t block)
{
aos_assert(block);
aos_assert(block->status == RBB_BLK_INITED);
block->status = RBB_BLK_PUT;
}
/**
* get a block from the ring block buffer object
*
* @param rbb ring block buffer object
*
* @return != NULL: block
* NULL: get failed
*/
rbb_blk_t rbb_blk_get(rbb_t rbb)
{
rbb_blk_t block = NULL;
slist_t *node;
aos_assert(rbb);
if (slist_empty(&rbb->blk_list))
return 0;
for (node = slist_first(&rbb->blk_list); node; node = slist_next(node)) {
block = slist_entry(node, struct rbb_blk, list);
if (block->status == RBB_BLK_PUT) {
block->status = RBB_BLK_GET;
goto __exit;
}
}
/* not found */
block = NULL;
__exit:
return block;
}
/**
* return the block size
*
* @param block the block
*
* @return block size
*/
size_t rbb_blk_size(rbb_blk_t block)
{
aos_assert(block);
return block->size;
}
/**
* return the block buffer
*
* @param block the block
*
* @return block buffer
*/
uint8_t *rbb_blk_buf(rbb_blk_t block)
{
aos_assert(block);
return block->buf;
}
/**
* free the block
*
* @param rbb ring block buffer object
* @param block the block
*/
void rbb_blk_free(rbb_t rbb, rbb_blk_t block)
{
aos_assert(rbb);
aos_assert(block);
aos_assert(block->status != RBB_BLK_UNUSED);
/* remove it on rbb block list */
slist_remove(&rbb->blk_list, &block->list);
block->status = RBB_BLK_UNUSED;
}
/**
* get a continuous block to queue by given size
*
* tail head
* +------------------+---------------+--------+----------+--------+
* | block3 | empty1 | block1 | block2 |fragment|
* +------------------+------------------------+----------+--------+
* |<-- return_size -->| |
* |<--- queue_data_len --->|
*
* tail head
* +------------------+---------------+--------+----------+--------+
* | block3 | empty1 | block1 | block2 |fragment|
* +------------------+------------------------+----------+--------+
* |<-- return_size -->| out of len(b1+b2+b3) |
* |<-------------------- queue_data_len -------------------->|
*
* @param rbb ring block buffer object
* @param queue_data_len The max queue data size, and the return size must less then it.
* @param queue continuous block queue
*
* @return the block queue data total size
*/
size_t rbb_blk_queue_get(rbb_t rbb, size_t queue_data_len, rbb_blk_queue_t blk_queue)
{
size_t data_total_size = 0;
slist_t *node;
rbb_blk_t last_block = NULL, block;
aos_assert(rbb);
aos_assert(blk_queue);
if (slist_empty(&rbb->blk_list))
return 0;
for (node = slist_first(&rbb->blk_list); node; node = slist_next(node)) {
if (!last_block) {
last_block = slist_entry(node, struct rbb_blk, list);
if (last_block->status == RBB_BLK_PUT) {
/* save the first put status block to queue */
blk_queue->blocks = last_block;
blk_queue->blk_num = 0;
} else {
/* the first block must be put status */
last_block = NULL;
continue;
}
} else {
block = slist_entry(node, struct rbb_blk, list);
/*
* these following conditions will break the loop:
* 1. the current block is not put status
* 2. the last block and current block is not continuous
* 3. the data_total_size will out of range
*/
if (block->status != RBB_BLK_PUT ||
last_block->buf > block->buf ||
data_total_size + block->size > queue_data_len) {
break;
}
/* backup last block */
last_block = block;
}
/* remove current block */
slist_remove(&rbb->blk_list, &last_block->list);
data_total_size += last_block->size;
last_block->status = RBB_BLK_GET;
blk_queue->blk_num++;
}
return data_total_size;
}
/**
* get all block length on block queue
*
* @param blk_queue the block queue
*
* @return total length
*/
size_t rbb_blk_queue_len(rbb_blk_queue_t blk_queue)
{
size_t i, data_total_size = 0;
aos_assert(blk_queue);
for (i = 0; i < blk_queue->blk_num; i++) {
data_total_size += blk_queue->blocks[i].size;
}
return data_total_size;
}
/**
* return the block queue buffer
*
* @param blk_queue the block queue
*
* @return block queue buffer
*/
uint8_t *rbb_blk_queue_buf(rbb_blk_queue_t blk_queue)
{
aos_assert(blk_queue);
return blk_queue->blocks[0].buf;
}
/**
* free the block queue
*
* @param rbb ring block buffer object
* @param blk_queue the block queue
*/
void rbb_blk_queue_free(rbb_t rbb, rbb_blk_queue_t blk_queue)
{
size_t i;
aos_assert(rbb);
aos_assert(blk_queue);
for (i = 0; i < blk_queue->blk_num; i++) {
rbb_blk_free(rbb, &blk_queue->blocks[i]);
}
}
/**
* The put status and buffer continuous blocks can be make a block queue.
* This function will return the length which from next can be make block queue.
*
* @param rbb ring block buffer object
*
* @return the next can be make block queue's length
*/
size_t rbb_next_blk_queue_len(rbb_t rbb)
{
size_t data_len = 0;
slist_t *node;
rbb_blk_t last_block = NULL, block;
aos_assert(rbb);
if (slist_empty(&rbb->blk_list))
return 0;
for (node = slist_first(&rbb->blk_list); node; node = slist_next(node)) {
if (!last_block) {
last_block = slist_entry(node, struct rbb_blk, list);
if (last_block->status != RBB_BLK_PUT) {
/* the first block must be put status */
last_block = NULL;
continue;
}
} else {
block = slist_entry(node, struct rbb_blk, list);
/*
* these following conditions will break the loop:
* 1. the current block is not put status
* 2. the last block and current block is not continuous
*/
if (block->status != RBB_BLK_PUT || last_block->buf > block->buf) {
break;
}
/* backup last block */
last_block = block;
}
data_len += last_block->size;
}
return data_len;
}
/**
* get the ring block buffer object buffer size
*
* @param rbb ring block buffer object
*
* @return buffer size
*/
size_t rbb_get_buf_size(rbb_t rbb)
{
aos_assert(rbb);
return rbb->buf_size;
}
| 26.658333 | 98 | 0.513832 | [
"object"
] |
4e6ec6f939b426f4fa0ec3db1e3f32a544796731 | 6,105 | h | C | LFR/include/util/window.h | zhouheping239/AOS | 2346ab523dacffe7612da2e45173b98c4433fc5a | [
"Intel"
] | 26 | 2021-06-24T07:21:16.000Z | 2022-03-10T17:16:26.000Z | LFR/include/util/window.h | zhouheping239/AOS | 2346ab523dacffe7612da2e45173b98c4433fc5a | [
"Intel"
] | 3 | 2021-08-06T18:56:37.000Z | 2022-01-24T15:13:13.000Z | LFR/include/util/window.h | zhouheping239/AOS | 2346ab523dacffe7612da2e45173b98c4433fc5a | [
"Intel"
] | 11 | 2021-07-13T13:29:53.000Z | 2022-03-08T02:25:30.000Z | #pragma once
#ifndef WINDOW_H
#define WINDOW_H
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include <glad/glad.h> // holds all OpenGL type declarations
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
//#include <nanogui/nanogui.h>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <optional>
GLFWwindow* window = nullptr;
bool gui = false;
// utility function to derminate the window
// ---------------------------------------------------
void DestroyWindow(void)
{
//if (screen) delete screen;
if (window)
{
glfwTerminate(); //delete window;
}
}
// utility function to instantiate a GLFW3 window
// ---------------------------------------------------
int InitWindow(const int width, const int height, const char *appname = "OpenGL" )
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_RED_BITS, 8);
glfwWindowHint(GLFW_GREEN_BITS, 8);
glfwWindowHint(GLFW_BLUE_BITS, 8);
glfwWindowHint(GLFW_ALPHA_BITS, 8);
glfwWindowHint(GLFW_STENCIL_BITS, 8);
glfwWindowHint(GLFW_DEPTH_BITS, 24);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// glfw window creation
// --------------------
window = glfwCreateWindow(width, height, appname, NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// tell GLFW to capture our mouse
//glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLES2Loader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
/*
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
*/
return 0;
}
// utility function to instantiate a GLFW3 window and a GUI
// ---------------------------------------------------
int InitWindowAndGUI(int &width, int &height, const char* appname = "OpenGL")
{
if (InitWindow(width, height, appname) >= 0)
{
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL(window, true);
const char *glsl_version = "#version 100"; // OpenGL ES 2.0
ImGui_ImplOpenGL3_Init(glsl_version);
gui = true;
}
else
return -1;
}
bool firstUpdate = true;
void UpdateWindow(float deltaTime = 0.0f)
{
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
GLFWframebuffersizefun global_fbsize_fun;
void SetFramebufferSizeCallback(GLFWframebuffersizefun fun)
{
global_fbsize_fun = fun;
glfwSetFramebufferSizeCallback(window,
[](GLFWwindow* window_, int width, int height) {
global_fbsize_fun(window_, width, height);
}
);
}
GLFWcursorposfun global_cursorpos_fun;
void SetCursorPosCallback(GLFWcursorposfun fun)
{
global_cursorpos_fun = fun;
glfwSetCursorPosCallback(window,
[](GLFWwindow* window_, double x, double y) {
if (!gui || !ImGui::GetIO().WantCaptureMouse)
global_cursorpos_fun(window_, x, y);
}
);
}
GLFWscrollfun global_scroll_fun;
void SetScrollCallback(GLFWscrollfun fun)
{
global_scroll_fun = fun;
glfwSetScrollCallback(window,
[](GLFWwindow* window_, double x, double y) {
if (!gui || !ImGui::GetIO().WantCaptureMouse)
global_scroll_fun(window_, x, y);
}
);
}
GLFWmousebuttonfun global_mousbutton_fun;
void SetMouseButtonCallback(GLFWmousebuttonfun fun)
{
global_mousbutton_fun = fun;
glfwSetMouseButtonCallback(window,
[](GLFWwindow* w_, int button, int action, int modifiers) {
if (!gui || !ImGui::GetIO().WantCaptureMouse)
global_mousbutton_fun(w_, button, action, modifiers);
}
);
}
GLFWkeyfun global_key_fun;
void SetKeyCallback(GLFWkeyfun fun)
{
global_key_fun = fun;
glfwSetKeyCallback(window,
[](GLFWwindow* w, int key, int scancode, int action, int mods) {
if (!gui || !ImGui::GetIO().WantCaptureKeyboard)
global_key_fun(w, key, scancode, action, mods);
}
);
}
GLFWcharfun global_char_fun;
void SetCharCallback(GLFWcharfun fun)
{
global_char_fun = fun;
glfwSetCharCallback(window,
[](GLFWwindow*w, unsigned int codepoint) {
if (!gui || !ImGui::GetIO().WantCaptureKeyboard)
global_char_fun(w, codepoint);
}
);
}
/*
GLFWdropfun global_drop_fun;
void SetDropCallback(GLFWdropfun fun)
{
global_drop_fun = fun;
glfwSetDropCallback(window,
[](GLFWwindow* w, int count, const char** filenames) {
global_drop_fun(w, count, filenames);
}
);
}
*/
#endif
| 26.543478 | 95 | 0.619984 | [
"vector"
] |
4e7c5c54b214ccdb5cd2007804a9e605a3d8e127 | 1,420 | h | C | modulemd/v1/include/modulemd-1.0/private/modulemd-subdocument-private.h | AarushiSingh09/libmodulemd | 707a59858252fe176759f75fe2851212b30f0b87 | [
"MIT"
] | 1 | 2019-03-12T05:36:55.000Z | 2019-03-12T05:36:55.000Z | modulemd/v1/include/modulemd-1.0/private/modulemd-subdocument-private.h | AarushiSingh09/libmodulemd | 707a59858252fe176759f75fe2851212b30f0b87 | [
"MIT"
] | null | null | null | modulemd/v1/include/modulemd-1.0/private/modulemd-subdocument-private.h | AarushiSingh09/libmodulemd | 707a59858252fe176759f75fe2851212b30f0b87 | [
"MIT"
] | null | null | null | /*
* This file is part of libmodulemd
* Copyright (C) 2017-2018 Stephen Gallagher
*
* Fedora-License-Identifier: MIT
* SPDX-2.0-License-Identifier: MIT
* SPDX-3.0-License-Identifier: MIT
*
* This program is free software.
* For more information on the license, see COPYING.
* For more information on free software, see <https://www.gnu.org/philosophy/free-sw.en.html>.
*/
/*
* This header includes functions for this object that should be considered
* internal to libmodulemd
*/
#pragma once
#include "modulemd.h"
#include <modulemd-subdocument.h>
G_BEGIN_DECLS
void
modulemd_subdocument_set_doctype (ModulemdSubdocument *self, const GType type);
/**
* modulemd_subdocument_get_doctype:
*
* Returns: A #GType of the GObject that represents this subdocument
*
* Since: 1.4
*/
const GType
modulemd_subdocument_get_doctype (ModulemdSubdocument *self);
void
modulemd_subdocument_set_version (ModulemdSubdocument *self,
const guint64 version);
/**
* modulemd_subdocument_get_version:
*
* Returns: A 64-bit integer describing the document version
*
* Since: 1.4
*/
guint64
modulemd_subdocument_get_version (ModulemdSubdocument *self);
void
modulemd_subdocument_set_yaml (ModulemdSubdocument *self, const gchar *yaml);
void
modulemd_subdocument_set_gerror (ModulemdSubdocument *self,
const GError *gerror);
G_END_DECLS
| 21.846154 | 95 | 0.730986 | [
"object"
] |
4e7ebd41bc5c8a6eae5fce6f4dc5a0b76827208e | 1,169 | h | C | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/FuseJS.Bundle.ExtractClosure.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/FuseJS.Bundle.ExtractClosure.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/FuseJS.Bundle.ExtractClosure.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | // This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/FuseJS/1.9.0/Bundle.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace FuseJS{struct Bundle__ExtractClosure;}}
namespace g{
namespace FuseJS{
// private sealed class Bundle.ExtractClosure :225
// {
uType* Bundle__ExtractClosure_typeof();
void Bundle__ExtractClosure__ctor__fn(Bundle__ExtractClosure* __this, uString* searchPath, uString* destinationPath, bool* overwriteIfExists);
void Bundle__ExtractClosure__Invoke_fn(Bundle__ExtractClosure* __this, uString** __retval);
void Bundle__ExtractClosure__New1_fn(uString* searchPath, uString* destinationPath, bool* overwriteIfExists, Bundle__ExtractClosure** __retval);
struct Bundle__ExtractClosure : uObject
{
uStrong<uString*> _searchPath;
uStrong<uString*> _destPath;
bool _overwrite;
void ctor_(uString* searchPath, uString* destinationPath, bool overwriteIfExists);
uString* Invoke();
static Bundle__ExtractClosure* New1(uString* searchPath, uString* destinationPath, bool overwriteIfExists);
};
// }
}} // ::g::FuseJS
| 37.709677 | 144 | 0.791275 | [
"object"
] |
4e7f6fd9dce0938d878aadc76eb1147ea6081166 | 1,616 | h | C | ConfProfile/jni/strongswan/src/libcharon/plugins/eap_identity/eap_identity.h | Infoss/conf-profile-4-android | 619bd63095bb0f5a67616436d5510d24a233a339 | [
"MIT"
] | 2 | 2017-10-16T07:51:18.000Z | 2019-06-16T12:07:52.000Z | strongswan/strongswan-5.3.2/src/libcharon/plugins/eap_identity/eap_identity.h | SECURED-FP7/secured-mobility-ned | 36fdbfee58a31d42f7047f7a7eaa1b2b70246151 | [
"Apache-2.0"
] | 5 | 2016-01-25T18:04:42.000Z | 2016-02-25T08:54:56.000Z | strongswan/strongswan-5.3.2/src/libcharon/plugins/eap_identity/eap_identity.h | SECURED-FP7/secured-mobility-ned | 36fdbfee58a31d42f7047f7a7eaa1b2b70246151 | [
"Apache-2.0"
] | 2 | 2016-01-25T17:14:17.000Z | 2016-02-13T20:14:09.000Z | /*
* Copyright (C) 2008 Martin Willi
* Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
/**
* @defgroup eap_identity_i eap_identity
* @{ @ingroup eap_identity
*/
#ifndef EAP_IDENTITY_H_
#define EAP_IDENTITY_H_
typedef struct eap_identity_t eap_identity_t;
#include <sa/eap/eap_method.h>
/**
* Implementation of the eap_method_t interface using EAP Identity.
*/
struct eap_identity_t {
/**
* Implemented eap_method_t interface.
*/
eap_method_t eap_method;
};
/**
* Creates the EAP method EAP Identity, acting as server.
*
* @param server ID of the EAP server
* @param peer ID of the EAP client
* @return eap_identity_t object
*/
eap_identity_t *eap_identity_create_server(identification_t *server,
identification_t *peer);
/**
* Creates the EAP method EAP Identity, acting as peer.
*
* @param server ID of the EAP server
* @param peer ID of the EAP client
* @return eap_identity_t object
*/
eap_identity_t *eap_identity_create_peer(identification_t *server,
identification_t *peer);
#endif /** EAP_IDENTITY_H_ @}*/
| 26.933333 | 77 | 0.731436 | [
"object"
] |
4e8ce3b65d998d04c8db67e2b3b132d656938961 | 741 | h | C | include/vm_object.h | wmoczulsky/mimiker | de6511df5aeeddaab2cfffa4a7fbbf27d9f4c08a | [
"BSD-3-Clause"
] | null | null | null | include/vm_object.h | wmoczulsky/mimiker | de6511df5aeeddaab2cfffa4a7fbbf27d9f4c08a | [
"BSD-3-Clause"
] | null | null | null | include/vm_object.h | wmoczulsky/mimiker | de6511df5aeeddaab2cfffa4a7fbbf27d9f4c08a | [
"BSD-3-Clause"
] | null | null | null | #ifndef _SYS_VM_OBJECT_H_
#define _SYS_VM_OBJECT_H_
#include <queue.h>
#include <pmap.h>
#include <vm.h>
/* At the moment assume object is owned by only one vm_map */
typedef struct vm_object {
TAILQ_HEAD(, vm_page) list;
RB_HEAD(vm_object_tree, vm_page) tree;
size_t size;
size_t npages;
pager_t *pgr;
} vm_object_t;
/* TODO in future this function will need to be parametrized by type */
vm_object_t *vm_object_alloc(void);
void vm_object_free(vm_object_t *obj);
bool vm_object_add_page(vm_object_t *obj, vm_page_t *pg);
void vm_object_remove_page(vm_object_t *obj, vm_page_t *pg);
vm_page_t *vm_object_find_page(vm_object_t *obj, vm_addr_t offset);
void vm_map_object_dump(vm_object_t *obj);
#endif /* !_SYS_VM_OBJECT_H_ */
| 28.5 | 71 | 0.77193 | [
"object"
] |
4e97fb1634a76ec842d272aae941f3a4ddf864e7 | 20,280 | h | C | robowflex_tesseract/include/robowflex_tesseract/trajopt_planner.h | aorthey/robowflex | 09eeb3a380344500508f53cf8469e9878e746c39 | [
"BSD-3-Clause"
] | null | null | null | robowflex_tesseract/include/robowflex_tesseract/trajopt_planner.h | aorthey/robowflex | 09eeb3a380344500508f53cf8469e9878e746c39 | [
"BSD-3-Clause"
] | null | null | null | robowflex_tesseract/include/robowflex_tesseract/trajopt_planner.h | aorthey/robowflex | 09eeb3a380344500508f53cf8469e9878e746c39 | [
"BSD-3-Clause"
] | null | null | null | /* Author: Carlos Quintero Pena */
#ifndef ROBOWFLEX_TRAJOPT_PLANNER_
#define ROBOWFLEX_TRAJOPT_PLANNER_
#include <robowflex_library/class_forward.h>
#include <robowflex_library/builder.h>
#include <robowflex_library/planning.h>
#include <tesseract_planning/trajopt/trajopt_planner.h>
#include <tesseract_ros/kdl/kdl_env.h>
namespace robowflex
{
/** \cond IGNORE */
ROBOWFLEX_CLASS_FORWARD(Robot);
ROBOWFLEX_CLASS_FORWARD(Scene);
ROBOWFLEX_CLASS_FORWARD(RobotTrajectory);
ROBOWFLEX_CLASS_FORWARD(MotionRequestBuilder);
/** \endcond */
/** \cond IGNORE */
ROBOWFLEX_CLASS_FORWARD(TrajOptPlanner);
/** \endcond */
/** \class robowflex::TrajOptPlannerPtr
\brief A shared pointer wrapper for robowflex::TrajOptPlanner. */
/** \class robowflex::TrajOptPlannerConstPtr
\brief A const shared pointer wrapper for robowflex::TrajOptPlanner. */
/** \brief Robowflex Tesseract TrajOpt Planner.
*/
class TrajOptPlanner : public Planner
{
public:
/** \brief Options structure with parameter values for TrajOpt planner.
*/
struct Options
{
sco::ModelType backend_optimizer{sco::ModelType::AUTO_SOLVER}; ///< Optimizer to use.
bool perturb_init_traj{false}; ///< Whether the initial trajectory should be randomly perturbed
///< or not.
double noise_init_traj{0.09}; ///< Max and (negative) min amount of uniform noise added to each
///< joint value for all waypoints of an initial trajectory.
bool verbose{true}; ///< Verbosity.
bool return_first_sol{true}; ///< Whether the planner runs only once or not. This has higher
///< piority than return_until_timeout. Choosing false will set
///< perturb_init_traj to true.
bool return_after_timeout{false}; ///< Whether the planner returns after timeout or after the
///< first feasible solution.
double max_planning_time{1.0}; ///< Maximum amount of time the planner is allowed to search for a
///< feasible solution.
bool use_cont_col_avoid{true}; ///< Whether to use continuous collision avoidance or not.
int num_waypoints{20}; ///< Number of waypoints.
double dt_lower_lim{2.0}; ///< 1/max_dt.
double dt_upper_lim{100.0}; ///< 1/min_dt.
bool start_fixed{false}; ///< Whether to use the current env state as a fixed initial state.
bool use_time{false}; ///< Whether any cost/cnt use time.
double init_info_dt{0.5}; ///< Value of dt in init_info.
double joint_vel_coeffs{5.0}; ///< Coefficients for joint_vel costs.
int collision_gap{1}; ///< For continuous collision avoidance, compute swept-volume between
///< timestep t and t+gap.
double default_safety_margin{0.025}; ///< Default safety margin for collision avoidance.
double default_safety_margin_coeffs{50.0}; ///< Coefficients for safety margin.
double joint_pose_safety_margin_coeffs{50.0}; ///< Coefficients for safety margin when using
///< joint pose costs/cnts.
double joint_state_safety_margin_coeffs{20.0}; ///< Coefficients for safety margin when using
///< joint state costs/cnts.
double pose_cnt_pos_coeffs{10.0}; ///< Coefficients for pose constraints (position).
double pose_cnt_rot_coeffs{10.0}; ///< Coefficients for pose constraints (rotation).
double joint_pos_cnt_coeffs{1.0}; ///< Coefficients for joint position constraints.
double improve_ratio_threshold{0.25}; ///< Minimum ratio true_improve/approx_improve to accept
///< step.
double min_trust_box_size{1e-4}; ///< If trust region gets any smaller, exit and report
///< convergence.
double min_approx_improve{1e-4}; ///< If model improves less than this, exit and report
///< convergence.
double min_approx_improve_frac{
-std::numeric_limits<double>::infinity()}; ///< If model improves less than this, exit and
///< report convergence.
double max_iter{50.0}; ///< The max number of iterations.
double trust_shrink_ratio{0.1}; // If improvement is less than improve_ratio_threshold, shrink
// trust region by this ratio.
double trust_expand_ratio{1.5}; ///< If improvement is greater than improve_ratio_threshold,
///< expand trust region by this ratio.
double cnt_tolerance{1e-4}; ///< After convergence of penalty subproblem, if constraint violation
///< is less than this, we're done.
double max_merit_coeff_increases{5.0}; ///< Number of times that we jack up penalty coefficient.
double merit_coeff_increase_ratio{10.0}; ///< Ratio that we increate coeff each time.
double merit_error_coeff{10.0}; ///< Initial penalty coefficient.
double trust_box_size{1e-1}; ///< Current size of trust region (component-wise).
} options;
/** \brief Planner result: first->converged, second->collision_free
*/
typedef std::pair<bool, bool> PlannerResult;
/** \brief Constructor.
* \param[in] robot Robot to plan for.
* \param[in] group_name Name of the (joint) group to plan for.
* \param[in] name Name of planner.
*/
TrajOptPlanner(const RobotPtr &robot, const std::string &group_name,
const std::string &name = "trajopt");
/** \brief Initialize planner. The user must specify a chain group defined in the robot's srdf
* that contains all the links of the manipulator.
* \param[in] manip Name of chain group with all the links of the manipulator.
* \return True if initialization succeded.
*/
bool initialize(const std::string &manip);
/** \brief Initialize planner. All links between \a base_link and \a tip_link will be added to
* the manipulator.
* \param[in] base_link Base link of the \a manip.
* \param[in] tip_link Tip link of the \a manip.
* \return True if initialization succeded.
*/
bool initialize(const std::string &base_link, const std::string &tip_link);
/** \name Set and get TrajOpt parameters
\{*/
/** \brief Set initial trajectory for TrajOpt and set init_type to GIVEN_TRAJ
* \param[in] init_trajectory Trajectory to initialize TrajOpt.
*/
void setInitialTrajectory(const robot_trajectory::RobotTrajectoryPtr &init_trajectory);
/** \brief Set initial trajectory for TrajOpt and set init_type to GIVEN_TRAJ
* \param[in] init_trajectory Trajectory to initialize TrajOpt.
*/
void setInitialTrajectory(const trajopt::TrajArray &init_trajectory);
/** \brief Set type of initialization to use for the trajectory optimization.
* Current options are:
* STATIONARY
* JOINT_INTERPOLATED
* The user can also provide their own trajectory using setInitialTrajectory(). In
* such case, there is no need to call setInitType().
* \param[in] init_type Type of initial trajectory to be used.
*/
void setInitType(const trajopt::InitInfo::Type &init_type);
/** \brief Get the trajectory that resulted in the last call to plan().
* \return Last trajectory computed using plan().
*/
const robot_trajectory::RobotTrajectoryPtr &getTrajectory() const;
/** \brief Get the trajectory that resulted in the last call to plan() in Tesseract
* format.
* \return Last trajectory computed using plan().
*/
const trajopt::TrajArray &getTesseractTrajectory() const;
/** \brief Get the link names in the tesseract KDL environment.
* \return Name of links in the KDL environment.
*/
const std::vector<std::string> &getEnvironmentLinks() const;
/** \brief Get the link names of the env manipulator.
* \return Name of links in the manipulator.
*/
const std::vector<std::string> &getManipulatorLinks() const;
/** \brief Get the joint names of the env manipulator.
* \return Name of joints in the manipulator.
*/
const std::vector<std::string> &getManipulatorJoints() const;
/** \brief Get the time spent by the planner the last time it was called.
* \return Planning time.
*/
double getPlanningTime() const;
/** \brief Constrain certain joints during optimization to their initial value.
* \param[in] joints Vector of joints to freeze.
*/
void fixJoints(const std::vector<std::string> &joints);
/** \} */
/** \name Planning functions
\{ */
/** \brief Plan a motion given a \a request and a \a scene.
* \param[in] scene A planning scene to compute the plan in.
* \param[in] request The motion planning request to solve.
* \return The motion planning response generated by the planner.
*/
planning_interface::MotionPlanResponse
plan(const SceneConstPtr &scene, const planning_interface::MotionPlanRequest &request) override;
/** \brief Plan a motion using a \a scene from \a start_state to a \a goal_state.
* \param[in] scene Scene to plan for.
* \param[in] start_state Start state for the robot.
* \param[in] goal_state Goal state for the robot.
* \return Planner result with convergence and collision status.
*/
PlannerResult plan(const SceneConstPtr &scene, const robot_state::RobotStatePtr &start_state,
const robot_state::RobotStatePtr &goal_state);
/** \brief Plan a motion given a \a start_state, a \a goal_pose for a \a link and a \a
* scene.
* \param[in] scene A planning scene for the same robot to compute the plan in.
* \param[in] start_state Start state for the robot.
* \param[in] goal_pose Cartesian goal pose for \a link.
* \param[in] link Link to find pose for.
* \return Planner result with convergence and collision status.
*/
PlannerResult plan(const SceneConstPtr &scene, const robot_state::RobotStatePtr &start_state,
const RobotPose &goal_pose, const std::string &link);
/** \brief Plan a motion given a \a start_state, a \a goal_pose for a \a link and a \a
* scene.
* \param[in] scene A planning scene for the same robot to compute the plan in.
* \param[in] start_state Start state for the robot.
* \param[in] goal_pose Cartesian goal pose for \a link.
* \param[in] link Link to find pose for.
* \return Planner result with convergence and collision status.
*/
PlannerResult plan(const SceneConstPtr &scene,
const std::unordered_map<std::string, double> &start_state,
const RobotPose &goal_pose, const std::string &link);
/** \brief Plan a motion given a \a start_pose for \a start_link and a \a goal_pose
* for \a goal_link.
* \param[in] scene A planning scene to compute the plan in.
* \param[in] start_pose Cartesian start pose for \a start_link.
* \param[in] start_link Robot's link with \a start_pose.
* \param[in] goal_pose Cartesian goal pose for \a goal_link.
* \param[in] goal_link Robot's link with \a goal_pose.
* \return Planner result with convergence and collision status.
*/
PlannerResult plan(const SceneConstPtr &scene, const RobotPose &start_pose,
const std::string &start_link, const RobotPose &goal_pose,
const std::string &goal_link);
/** \brief Get planner configurations offered by this planner.
* Any of the configurations returned can be set as the planner for a motion planning
* query sent to plan().
* \return A vector of strings of planner configuration names.
*/
std::vector<std::string> getPlannerConfigs() const override;
/** \} */
/** \name Debugging Options
\{ */
/** \brief Set whether a report file (for the optimization) should be written or not.
* \param[in] file_write_cb Whether to write the file or not.
* \param[in] file_path File path
*/
void setWriteFile(bool file_write_cb, const std::string &file_path = "");
/** \} */
private:
/** \brief Create a TrajOpt problem construction info object with default values.
* \param[out] pci Pointer to problem construction info initialized.
*/
void problemConstructionInfo(std::shared_ptr<trajopt::ProblemConstructionInfo> pci) const;
/** \brief Add collision avoidance cost to the trajectory optimization for all waypoints.
* \param[out] pci Pointer to problem construction info with collision avoidance added.
*/
void addCollisionAvoidance(std::shared_ptr<trajopt::ProblemConstructionInfo> pci) const;
/** \brief Add a (joint) configuration constraint in the first waypoint taken from \a request.
* \param[in] request Request motion planning problem.
* \param[out] pci Pointer to problem construction info with start state constraint added.
*/
void addStartState(const MotionRequestBuilderPtr &request,
std::shared_ptr<trajopt::ProblemConstructionInfo> pci);
/** \brief Add a (joint) configuration constraint \a start_state in the first waypoint.
* \param[in] start_state Desired robot's start state.
* \param[out] pci Pointer to problem construction info with start state constraint added.
*/
void addStartState(const robot_state::RobotStatePtr &start_state,
std::shared_ptr<trajopt::ProblemConstructionInfo> pci);
/** \brief Add a (joint) configuration constraint \a start_state in the first waypoint.
* \param[in] start_state Desired start manipulator's joint names/values.
* \param[out] pci Pointer to problem construction info with start state constraint added.
*/
void addStartState(const std::unordered_map<std::string, double> &start_state,
std::shared_ptr<trajopt::ProblemConstructionInfo> pci);
/** \brief Add a cartesian pose constraint \a start_pose for \a link in the first waypoint.
* \param[in] start_pose Desired start cartesian pose of \a link.
* \param[in] link Link that will be constrained to be in \a start_pose in the first waypoint.
* \param[out] pci Pointer to problem construction info with start pose constraint added.
*/
void addStartPose(const RobotPose &start_pose, const std::string &link,
std::shared_ptr<trajopt::ProblemConstructionInfo> pci) const;
/** \brief Add a (joint) configuration constraint in the last waypoint taken from \a request.
* \param[in] request Request motion planning problem.
* \param[out] pci Pointer to problem construction info with goal state constraint added.
*/
void addGoalState(const MotionRequestBuilderPtr &request,
std::shared_ptr<trajopt::ProblemConstructionInfo> pci) const;
/** \brief Add a (joint) configuration constraint \a goal_state in the last waypoint.
* \param[in] goal_state Desired robot's goal state.
* \param[out] pci Pointer to problem construction info with goal state constraint added.
*/
void addGoalState(const robot_state::RobotStatePtr &goal_state,
std::shared_ptr<trajopt::ProblemConstructionInfo> pci) const;
/** \brief Add a (joint) configuration constraint \a goal_state in the last waypoint.
* \param[in] goal_state Desired goal manipulator's joint values.
* \param[out] pci Pointer to problem construction info with goal state constraint added.
*/
void addGoalState(const std::vector<double> goal_state,
std::shared_ptr<trajopt::ProblemConstructionInfo> pci) const;
/** \brief Add a cartesian pose constraint \a goal_pose for \a link in the last waypoint.
* \param[in] goal_pose Desired goal cartesian pose of \a link.
* \param[in] link Link that will be constrained to be in \a goal_pose in the last waypoint.
* \param[out] pci Pointer to problem construction info with goal pose constraint added.
*/
void addGoalPose(const RobotPose &goal_pose, const std::string &link,
std::shared_ptr<trajopt::ProblemConstructionInfo> pci) const;
/** \brief Solve SQP optimization problem.
* \param[in] scene Scene to plan for.
* \param[in] pci Pointer to problem construction info initialized.
* \return Planner result with convergence and collision status.
*/
PlannerResult solve(const SceneConstPtr &scene,
const std::shared_ptr<trajopt::ProblemConstructionInfo> &pci);
/** \brief Get parameters of the SQP.
* \return SQP parameters.
*/
sco::BasicTrustRegionSQPParameters getTrustRegionSQPParameters() const;
robot_trajectory::RobotTrajectoryPtr trajectory_; ///< Last successful trajectory generated by the
///< planner.
trajopt::TrajArray tesseract_trajectory_; ///< Last successful trajectory generated by the
///< planner in Tesseract format.
tesseract::tesseract_ros::KDLEnvPtr env_; ///< KDL environment.
std::string group_; ///< Name of group to plan for.
std::string manip_; ///< Name of manipulator chain to check for collisions.
bool cont_cc_{true}; ///< Use continuous collision checking.
std::shared_ptr<std::ofstream> stream_ptr_; ///< Debug file stream.
std::string file_path_; ///< Path of debug file.
bool file_write_cb_{false}; ///< Whether to write a debug file or not.
trajopt::InitInfo::Type init_type_{trajopt::InitInfo::Type::STATIONARY}; ///< Type of initial
///< trajectory.
trajopt::TrajArray initial_trajectory_; ///< Initial trajectory (if any).
double time_{0.0}; ///< Time taken by the optimizer the last time it was called.
std::vector<int> fixed_joints_; ///< List of joints that need to be fixed, indexed in the order they
///< appear in the manipulator.
robot_state::RobotStatePtr ref_state_; ///< Reference state to build moveit trajectory waypoints.
};
} // namespace robowflex
#endif
| 56.177285 | 110 | 0.605572 | [
"object",
"vector",
"model"
] |
4e9e36b4b9ce39586b96339bb58ad8f07c6ed350 | 3,007 | h | C | IOS/Carthage/Checkouts/spark-setup-ios/Carthage/Checkouts/spark-sdk-ios/Example/SparkDevice.h | Connorrr/ParticleAlarm | aafb89820579c5a281461514ecbd42b52ea36915 | [
"MIT"
] | 57 | 2015-03-11T22:41:48.000Z | 2017-08-28T02:24:05.000Z | IOS/Carthage/Checkouts/spark-setup-ios/Carthage/Checkouts/spark-sdk-ios/Example/SparkDevice.h | Connorrr/ParticleAlarm | aafb89820579c5a281461514ecbd42b52ea36915 | [
"MIT"
] | 34 | 2015-03-11T08:40:57.000Z | 2016-12-25T20:45:18.000Z | IOS/Carthage/Checkouts/spark-setup-ios/Carthage/Checkouts/spark-sdk-ios/Example/SparkDevice.h | Connorrr/ParticleAlarm | aafb89820579c5a281461514ecbd42b52ea36915 | [
"MIT"
] | 44 | 2015-03-11T08:57:02.000Z | 2017-09-25T21:11:12.000Z | //
// SparkDevice.h
// mobile-sdk-ios
//
// Created by Ido Kleinman on 11/7/14.
// Copyright (c) 2014-2015 Spark. All rights reserved.
//
#import <Foundation/Foundation.h>
//#import <AFNetworking/AFNetworking.h>
typedef NS_ENUM(NSInteger, SparkDeviceType) {
SparkDeviceTypeCore=1,
SparkDeviceTypePhoton,
};
@interface SparkDevice : NSObject
/**
* Device ID string
*/
@property (strong, nonatomic, readonly) NSString* id;
/**
* Device name. Device can be renamed in the cloud by setting this property. If renaming fails name will stay the same.
*/
@property (strong, nonatomic) NSString* name;
/**
* Is device connected to the cloud?
*/
@property (nonatomic, readonly) BOOL connected;
/**
* List of function names exposed by device
*/
@property (strong, nonatomic, readonly) NSArray *functions;
/**
* Dictionary of exposed variables on device with their respective types.
*/
@property (strong, nonatomic, readonly) NSDictionary *variables; // @{varName : varType, ...}
@property (strong, nonatomic, readonly) NSString *lastApp;
@property (strong, nonatomic, readonly) NSDate *lastHeard;
/**
* Device firmware version string
*/
@property (strong, nonatomic, readonly) NSString *version;
@property (nonatomic, readonly) BOOL requiresUpdate;
//@property (nonatomic, readonly) SparkDeviceType type; // inactive for now
-(instancetype)initWithParams:(NSDictionary *)params NS_DESIGNATED_INITIALIZER;
-(instancetype)init __attribute__((unavailable("Must use initWithParams:")));
/**
* Retrieve a variable value from the device
*
* @param variableName Variable name
* @param completion Completion block to be called with the result value or error
*/
-(void)getVariable:(NSString *)variableName completion:(void(^)(id result, NSError* error))completion;
/**
* Call a function on the device
*
* @param functionName Function name
* @param args Array of arguments to pass to the function on the device. Arguments will be converted to string maximum length 63 chars.
* @param completion Completion block will be called when function finished running on device. First argument of block is the integer return value of the function, second is NSError object in case of an error invoking the function
*/
-(void)callFunction:(NSString *)functionName withArguments:(NSArray *)args completion:(void (^)(NSNumber *, NSError *))completion;
/*
-(void)addEventHandler:(NSString *)eventName handler:(void(^)(void))handler;
-(void)removeEventHandler:(NSString *)eventName;
*/
// Request device refresh from cloud - update online status/function/variables/name etc
-(void)refresh;
/**
* Remove device from current logged in user account
*
* @param completion Completion with NSError object in case of an error.
*/
-(void)unclaim:(void(^)(NSError* error))completion;
/*
-(void)compileAndFlash:(NSString *)sourceCode completion:(void(^)(NSError* error))completion;
-(void)flash:(NSData *)binary completion:(void(^)(NSError* error))completion;
*/
@end
| 31.989362 | 233 | 0.734952 | [
"object"
] |
4ec0c9b631f04b04685017d7525de7229cf830b1 | 2,836 | h | C | src/lib/SceMi/bsvxactors/BSVVectorT.h | GaloisInc/BESSPIN-BSC | 21a0a8cba9e643ef5afcb87eac164cc33ea83e94 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2022-02-11T01:52:42.000Z | 2022-02-11T01:52:42.000Z | src/lib/SceMi/bsvxactors/BSVVectorT.h | GaloisInc/BESSPIN-BSC | 21a0a8cba9e643ef5afcb87eac164cc33ea83e94 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | src/lib/SceMi/bsvxactors/BSVVectorT.h | GaloisInc/BESSPIN-BSC | 21a0a8cba9e643ef5afcb87eac164cc33ea83e94 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009, Bluespec, Inc. ALL RIGHTS RESERVED
#pragma once
#include "BSVType.h"
#include <cstdio>
#include <sstream>
// Wrapper Class for Bluespec's Vector#(n,t) type and its conversion to and from SceMiMessages
template <unsigned int N, class T>
class BSVVectorT : public BSVType {
public:
T v[N];
BSVVectorT ()
: v()
{
if ((N == 0)) {
throw std::logic_error ("illegal size in class BSVVectorT<T, N>, N must be > 0.");
}
}
BSVVectorT (const SceMiMessageDataInterface *msg, unsigned int &off) {
if ((N == 0)) {
throw std::logic_error ("illegal size in class BSVVectorT<T, N>, N must be > 0.");
}
for (unsigned int i = 0 ; i < N ; ++i) {
v[i] = T(msg, off) ;
}
}
unsigned int setMessageData ( SceMiMessageDataInterface &msg, const unsigned int off=0) const {
unsigned int running = off ;
for (unsigned int i = 0 ; i < N ; ++i) {
running = v[i].setMessageData ( msg, running );
}
return running ;
}
friend std::ostream & operator<< (std::ostream &os, const BSVVectorT &d) {
BSVType::PutTo * override = lookupPutToOverride ( d.getClassName() ) ;
if ( override != 0 ) {
return override(os, d);
}
os << "{" ;
for (unsigned int i = 0 ; i < N; ++i) {
if (i!=0) os << " " ;
os << std::dec << "V[" << i << "] " << d.v[i] ;
}
os << "}" ;
return os;
}
T & operator[] (size_t idx) {
if (idx >= N) throw std::logic_error ("illegal index accessing BSVVectorT<T, N>, 0 <= i < N");
return v[idx];
}
const T & operator[] (size_t idx) const {
if (idx >= N) throw std::logic_error ("illegal index accessing BSVVectorT<T, N>, 0 <= i < N");
return v[idx];
}
virtual std::ostream & getBitString ( std::ostream & os ) const {
for (unsigned int i = 0 ; i < N ; ++i ) {
// MSB to LSB
v[N-(i+1)].getBitString(os);
}
return os;
}
virtual std::ostream & getBitStringRange (std::ostream &os, unsigned int from,
unsigned int to) const {
os << "BSVVectorT getBitStringRange() not implemented" ;
return os;
}
virtual std::ostream & getBSVType (std::ostream &os ) const {
os << "Vector#( " << std::dec << N << ", " ;
T x;
x.getBSVType (os) ;
os << ")" ;
return os;
}
virtual unsigned int getBitSize () const {
T x;
return N * (x.getBitSize()) ;
}
virtual const char * getClassName () const {
return "VectorT";
}
virtual BSVKind getKind() const {
return BSV_Vector ;
}
virtual unsigned int getMemberCount() const {
return N;
}
virtual BSVType * getMember (unsigned int idx) {
if (idx < N) return & v[idx];
return 0;
}
virtual const char * getMemberName (unsigned int idx) const {
static char buf[12];
sprintf (buf, "V%d", idx);
return buf;
}
};
| 28.079208 | 99 | 0.574048 | [
"vector"
] |
4eca838340c62baec965be7af61b832a353161e3 | 6,913 | c | C | common/mex/com3.c | elgw/dotter | 8fe0ab3610ff5473bccbac169795a0d1b72c1938 | [
"MIT"
] | 1 | 2021-12-15T08:20:13.000Z | 2021-12-15T08:20:13.000Z | common/mex/com3.c | elgw/dotter | 8fe0ab3610ff5473bccbac169795a0d1b72c1938 | [
"MIT"
] | null | null | null | common/mex/com3.c | elgw/dotter | 8fe0ab3610ff5473bccbac169795a0d1b72c1938 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include "com3.h"
// #define debugmode 1
int unit_tests(void);
const int64_t comr = 2; // Radius of com filter in pixels
// The filter will be (2*comr+1)^3 pixels
int pointInDomain(int64_t * restrict Point, size_t * Domain, int nDim)
// Check if a point is in the domain of a 3D image
{
for(int kk = 0; kk<nDim; kk++)
if(Point[kk]<0 || Point[kk]>= (int64_t) Domain[kk])
return 0;
return 1;
}
int checkBounds(int64_t * restrict D,
const size_t M, const size_t N, const size_t P)
{
if(D[0]>=comr && D[0]+comr<(int64_t) M &&
D[1]>=comr && D[1]+comr<(int64_t) N &&
D[2]>=comr && D[2]+comr<(int64_t) P)
return 1; // ok
return 0;
}
void com3_localw(double * restrict V, double * restrict W, const size_t M, const size_t N, const size_t P,
int64_t * restrict D, double * restrict C)
{
#ifdef debugmode
printf("D: [%u %u %u]\n", D[0], D[1], D[2]);
printf("M: %lu N: %lu P: %lu\n", M, N, P);
#endif
double sum = 0;
double dx = 0;
double dy = 0;
double dz = 0;
#ifdef debugmode
printf("sum: %f\n", sum);
#endif
if(checkBounds(D, M, N, P))
{
double val = V[D[0] + D[1]*M + D[2]*M*N];
for(int kk = -comr; kk<=comr; kk++) {
for(int ll = -comr; ll<=comr; ll++) {
for(int mm = -comr; mm<=comr; mm++) {
size_t pos = (D[0]+kk) + (D[1]+ll)*M + (D[2]+mm)*M*N;
// printf("pos: %lu V[pos]: %f\n", pos, V[pos]);
dx += kk*V[pos]*val/W[pos];
dy += ll*V[pos]*val/W[pos];
dz += mm*V[pos]*val/W[pos];
sum += V[pos];
} } }
//printf("sum: %f\n", sum);
}
if(sum>0)
{
#ifdef debugmode
printf("sum: %f (%f, %f, %f)\n", sum, dx, dy, dz);
#endif
C[0] = D[0] + dx/sum;
C[1] = D[1] + dy/sum;
C[2] = D[2] + dz/sum;
}
else
{
#ifdef debugmode
printf("No com calculation\n");
#endif
C[0] = D[0];
C[1] = D[1];
C[2] = D[2];
}
}
void com3_local(double * restrict V, const size_t M, const size_t N, const size_t P,
int64_t * restrict D, double * restrict C)
{
#ifdef debugmode
printf("D: [%u %u %u]\n", D[0], D[1], D[2]);
printf("M: %lu N: %lu P: %lu\n", M, N, P);
#endif
double sum = 0;
double dx = 0;
double dy = 0;
double dz = 0;
#ifdef debugmode
printf("sum: %f\n", sum);
#endif
if(checkBounds(D, M, N, P))
{
for(int kk = -comr; kk<=comr; kk++) {
for(int ll = -comr; ll<=comr; ll++) {
for(int mm = -comr; mm<=comr; mm++) {
size_t pos = (D[0]+kk) + (D[1]+ll)*M + (D[2]+mm)*M*N;
// printf("pos: %lu V[pos]: %f\n", pos, V[pos]);
dx += kk*V[pos];
dy += ll*V[pos];
dz += mm*V[pos];
sum += V[pos];
} } }
//printf("sum: %f\n", sum);
}
if(sum>0)
{
#ifdef debugmode
printf("sum: %f (%f, %f, %f)\n", sum, dx, dy, dz);
#endif
C[0] = D[0] + dx/sum;
C[1] = D[1] + dy/sum;
C[2] = D[2] + dz/sum;
}
else
{
#ifdef debugmode
printf("No com calculation\n");
#endif
C[0] = D[0];
C[1] = D[1];
C[2] = D[2];
}
}
void setLmax(double *V, double * W, size_t * Domain, int64_t * Dot)
// Adds V(dot) to all W within comr of dot
// uses global value comr
{
uint32_t m = Dot[0];
uint32_t n = Dot[1];
uint32_t p = Dot[2];
size_t M = Domain[0];
size_t N = Domain[1];
size_t P = Domain[2];
double val = V[m + n*M + p*M*N];
for(uint32_t pp = GSL_MAX(p-comr,0) ; pp<= GSL_MIN(p+comr, P-1) ; pp++) {
for(uint32_t nn = GSL_MAX(n-comr,0) ; nn<= GSL_MIN(n+comr, N-1) ; nn++) {
for(uint32_t mm = GSL_MAX(m-comr,0) ; mm<= GSL_MIN(m+comr, M-1) ; mm++) {
W[mm + nn*M + pp*M*N] += val;
}
}
}
}
void setWeights(double * V, double * W, size_t M, size_t N, size_t P, double * D, size_t nD)
{
size_t Domain[] = {M, N, P};
int64_t Dot[] = {0,0,0};
for(size_t kk = 0; kk<nD; kk++) {
Dot[0] = D[kk*3 + 0];
Dot[1] = D[kk*3 + 1];
Dot[2] = D[kk*3 + 2];
setLmax(V, W, Domain, Dot);
}
}
void com3(double * V, size_t M, size_t N, size_t P,
double * D, double * C, size_t L, int weighted) {
/* Centre of mass
*
* V: MxNxP image
* P 3xL list of dots
* C 3xL list of fitted dots
*/
int64_t Dround[] = {0,0,0};
size_t Domain[] = {M, N, P};
double * W;
if(weighted == 1)
// Set up the weighting matrix
{
W = (double *) calloc(M*N*P, sizeof(double));
for(size_t kk = 0; kk<L; kk++)
{
Dround[0] = nearbyint(D[kk*3]-1);
Dround[1] = nearbyint(D[kk*3+1]-1);
Dround[2] = nearbyint(D[kk*3+2]-1);
if(pointInDomain(Dround, Domain, 3))
setLmax(V, W, Domain, Dround);
}
}
if(weighted == 1)
for(size_t kk = 0; kk<L; kk++)
{
Dround[0] = nearbyint(D[kk*3]-1);
Dround[1] = nearbyint(D[kk*3+1]-1);
Dround[2] = nearbyint(D[kk*3+2]-1);
// printf("%d %d %d\n", Dround[0], Dround[1], Dround[2]);
com3_localw(V, W, M, N, P, Dround, C+kk*3);
}
if(weighted ==0)
for(size_t kk = 0; kk<L; kk++)
{
Dround[0] = nearbyint(D[kk*3]-1);
Dround[1] = nearbyint(D[kk*3+1]-1);
Dround[2] = nearbyint(D[kk*3+2]-1);
// printf("%d %d %d\n", Dround[0], Dround[1], Dround[2]);
com3_local(V, M, N, P, Dround, C+kk*3);
}
if(weighted == 1){
// This was used for debugging
//for(size_t xx = 0; xx<M*N*P; xx++)
// V[xx] = W[xx];
free(W);
}
}
#ifdef standalone
int unit_tests() {
// Size of image
uint32_t M = 100;
uint32_t N = 100;
uint32_t P = 100;
uint32_t L = 2; // number of dots
double * V = malloc(M*N*P*sizeof(double));
double * D = malloc(L*3*sizeof(double));
double * C = malloc(L*3*sizeof(double));
memset(V, 0, M*N*P*sizeof(double));
memset(C, 0, 3*L*sizeof(double));
for(size_t kk = 0; kk<M*N*P; kk++)
V[kk] = 0;
D[0] = 11; D[1] = 12; D[2] = 13;
D[3] = 0; D[4] = 15; D[5] = 16;
size_t pos = D[0] + M*D[1] + M*N*D[2];
V[pos] = 3;
// V[pos+1] = 1;
// V[pos + M] = 1;
V[pos + M*N] = 1;
// Ordinary
com3(V, M, N, P,
D, C, L, 0);
// Weighted
com3(V, M, N, P,
D, C, L, 1);
for(uint32_t kk=0; kk<L; kk++) {
printf("%d [%f %f %f] -> ", kk, D[3*kk], D[3*kk+1], D[3*kk+2]);
printf(" [%f %f %f]\n", C[3*kk], C[3*kk+1], C[3*kk+2]);
}
free(C);
free(D);
free(V);
return 0;
}
int main(int argc, char ** argv)
{
printf("%s\n", argv[0]);
if(argc == 1)
return unit_tests();
}
#endif
| 22.3 | 108 | 0.48416 | [
"3d"
] |
4ee2ce54e6ed3fd3ec885cba8390e84e5c86e283 | 314 | h | C | src/server/entity/ts_grenadeprojectile.h | Frag-Net/FreeTS | e5d070d4a6a0ecc88df7f61bac36486be5fb6a3b | [
"0BSD"
] | 6 | 2021-07-30T10:14:24.000Z | 2022-02-10T21:51:38.000Z | src/server/entity/ts_grenadeprojectile.h | Frag-Net/FreeTS | e5d070d4a6a0ecc88df7f61bac36486be5fb6a3b | [
"0BSD"
] | null | null | null | src/server/entity/ts_grenadeprojectile.h | Frag-Net/FreeTS | e5d070d4a6a0ecc88df7f61bac36486be5fb6a3b | [
"0BSD"
] | 1 | 2021-07-30T19:10:46.000Z | 2021-07-30T19:10:46.000Z |
class TS_GrenadeProjectile{
void(void) TS_GrenadeProjectile;
static void(void) precache;
static TS_GrenadeProjectile(player arg_player, vector arg_vOrigin, vector arg_vThrowDir, vector arg_vPlayerForward, int arg_weaponTypeID) generate;
virtual void(void) touch;
};
void TS_GrenadeProjectile_Explode(void);
| 31.4 | 148 | 0.828025 | [
"vector"
] |
4eefc8350a4f43116631d1910b7a79e89bc737d1 | 1,840 | h | C | src/chrono_vehicle/chassis/ChassisConnectorArticulated.h | Benatti1991/chrono | d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf | [
"BSD-3-Clause"
] | 1,383 | 2015-02-04T14:17:40.000Z | 2022-03-30T04:58:16.000Z | src/chrono_vehicle/chassis/ChassisConnectorArticulated.h | Benatti1991/chrono | d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf | [
"BSD-3-Clause"
] | 245 | 2015-01-11T15:30:51.000Z | 2022-03-30T21:28:54.000Z | src/chrono_vehicle/chassis/ChassisConnectorArticulated.h | Benatti1991/chrono | d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf | [
"BSD-3-Clause"
] | 351 | 2015-02-04T14:17:47.000Z | 2022-03-30T04:42:52.000Z | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Articulated chassis connector model constructed with data from file (JSON format).
//
// =============================================================================
#ifndef CHASSIS_CONNECTOR_ARTICULATED_H
#define CHASSIS_CONNECTOR_ARTICULATED_H
#include "chrono_vehicle/ChApiVehicle.h"
#include "chrono_vehicle/chassis/ChChassisConnectorArticulated.h"
#include "chrono_thirdparty/rapidjson/document.h"
namespace chrono {
namespace vehicle {
/// @addtogroup vehicle
/// @{
/// Articulated chassis connector model constructed with data from file (JSON format).
class CH_VEHICLE_API ChassisConnectorArticulated : public ChChassisConnectorArticulated {
public:
ChassisConnectorArticulated(const std::string& filename);
ChassisConnectorArticulated(const rapidjson::Document& d);
~ChassisConnectorArticulated() {}
/// Return the maximum steering angle. The steering input is scaled by this value to produce the angle applied to
/// the underlying rotational motor.
virtual double GetMaxSteeringAngle() const override { return m_maxangle; }
private:
virtual void Create(const rapidjson::Document& d) override;
double m_maxangle;
};
/// @} vehicle
} // end namespace vehicle
} // end namespace chrono
#endif
| 33.454545 | 119 | 0.625543 | [
"model"
] |
4ef3bb05f6080cf907cc9a5bb6ef68b803d9f931 | 7,108 | h | C | mysqlshdk/libs/utils/utils_path.h | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 119 | 2016-04-14T14:16:22.000Z | 2022-03-08T20:24:38.000Z | mysqlshdk/libs/utils/utils_path.h | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 9 | 2017-04-26T20:48:42.000Z | 2021-09-07T01:52:44.000Z | mysqlshdk/libs/utils/utils_path.h | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 51 | 2016-07-20T05:06:48.000Z | 2022-03-09T01:20:53.000Z | /*
* Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0,
* as published by the Free Software Foundation.
*
* This program is also distributed with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms, as
* designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an additional
* permission to link the program and your derivative works with the
* separately licensed software that they have included with MySQL.
* 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, version 2.0, 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
*/
#ifndef MYSQLSHDK_LIBS_UTILS_UTILS_PATH_H_
#define MYSQLSHDK_LIBS_UTILS_UTILS_PATH_H_
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "scripting/common.h"
namespace shcore {
namespace path {
namespace detail {
std::string expand_user(const std::string &path, const std::string &sep);
std::tuple<std::string, std::string> split_extension(const std::string &path,
const std::string &sep);
size_t span_dirname(const std::string &path);
} // namespace detail
std::string SHCORE_PUBLIC join_path(const std::vector<std::string> &components);
inline std::string SHCORE_PUBLIC join_path(const std::string &a,
const std::string &b) {
return join_path({a, b});
}
template <typename... Args>
std::string join_path(const std::string &a, const std::string &b,
Args... args) {
return join_path(a, join_path(b, args...));
}
std::pair<std::string, std::string> SHCORE_PUBLIC
splitdrive(const std::string &path);
std::string SHCORE_PUBLIC dirname(const std::string &path);
std::string SHCORE_PUBLIC basename(const std::string &path);
#ifdef WIN32
const char path_separator = '\\';
const char pathlist_separator = ';';
#else
const char path_separator = '/';
const char pathlist_separator = ':';
#endif
const char pathlist_separator_s[] = {pathlist_separator, '\0'};
extern const char *k_valid_path_separators;
/**
* Get home directory path of the user executing the shell.
*
* On Unix: `HOME` environment variable is returned if is set, otherwise current
* user home directory is looked up in password directory.
*
* On Windows: `%HOME%` or `%USERPROFILE%` or `%HOMEDRIVE%` + `%HOMEPATH%`
* environment variable is returned if is set, otherwise user home
* directory is obtained from system KnownFolder ID
* `FOLDERID_Profile`.
* If all of above fail, empty string is returned.
*
* @return User home directory path.
*/
std::string SHCORE_PUBLIC home();
/**
* Get home directory path of user associated with the specified login name.
*
* On Unix: User home directory path associated with `loginname` is looked up
* directly in the password directory.
*
* On Windows: Retrieving home directory of another user on Windows platform
* is *NOT SUPPORTED*.
*
* @param loginname Login name of existing user in system.
*
* @return User home directory associated with `loginname` or empty string
* if such user does not exist.
*/
std::string SHCORE_PUBLIC home(const std::string &loginname);
/**
* `expand_user` expand paths beginning with `~` or `~user` (also known as
* "tilde expansion").
*
* Home directory for `~` prefix is obtained by `home()` function.
* Home directory for `~user` prefix is obtained by `home(user)` function.
*
* @param path Path string.
*
* @return Return `path` with prefix `~` or `~user` replaced by that user's home
* directory. @see home() and @see home(user).
* If the expansion fails or if the path does not begin with `~`, the
* path is returned unchanged.
*/
std::string SHCORE_PUBLIC expand_user(const std::string &path);
/**
* Unix:
* Normalize a path collapsing redundant separators and relative references
* (`.`, `..`). This string path manipulation, might affect paths containing
* symbolic links.
*
* Windows:
* Retrieves the full path and file name of the specified file. If error
* occur path isn't altered.
*
* @param path Input path string to normalize.
* @return Normalized string path.
*/
std::string SHCORE_PUBLIC normalize(const std::string &path);
/**
* Split path to (root, extension) tuple such that [root + extenstion == path].
*
* @param path
* @return Tuple (root, extension). Leading periods on basename are ignored,
* i.e. split_extension(".dotfile") returns (".dotfile", "").
*/
std::tuple<std::string, std::string> SHCORE_PUBLIC
split_extension(const std::string &path);
/**
* Returns true if the path exists.
*/
bool SHCORE_PUBLIC exists(const std::string &path);
/**
* Returns path to the given executable name searched in PATH.
*/
std::string SHCORE_PUBLIC search_stdpath(const std::string &name);
/**
* Returns path to the given executable name searched in the given path list
* string, separated by the given separator.
*
* @param name name of the executable. .exe is automatically appended in Win32
* @param pathlist string with list of paths to search
* @param separator separator character used in pathlist. If 0, the default
* PATH separator for the platform is used.
*/
std::string SHCORE_PUBLIC search_path_list(const std::string &name,
const std::string &pathlist,
const char separator = 0);
/**
* Provides path to the system-specific temporary directory.
*
* @throws std::runtime_error in case of any errors
*/
std::string SHCORE_PUBLIC tmpdir();
/**
* Checks if character is a path separator.
*
* @param c - character to be checked.
*
* @returns true if the given character is a path separator.
*/
bool SHCORE_PUBLIC is_path_separator(char c);
/**
* Checks if path is absolute.
*
* @param path - path to be checked.
*
* @returns true if the given path is absolute.
*/
bool SHCORE_PUBLIC is_absolute(const std::string &path);
/**
* Provides path to the current working directory.
*/
std::string SHCORE_PUBLIC getcwd();
/**
* Return the canonical version of the pathname path.
* @param path the path for which we want to find out the canonical path
* @return the canonical path
* @throws std::runtime_error in case of any errors
*/
std::string SHCORE_PUBLIC get_canonical_path(const std::string &path);
} // namespace path
} // namespace shcore
#endif // MYSQLSHDK_LIBS_UTILS_UTILS_PATH_H_
| 33.687204 | 80 | 0.695554 | [
"vector"
] |
4ef51db76dcace97c171b0455f5afc9aa5139ec0 | 240 | h | C | eos_dev/eos_dev/eos/eos.h | amortaza/eos | 23ca52203fa0beece14430d6eee43f2b249376a6 | [
"MIT"
] | null | null | null | eos_dev/eos_dev/eos/eos.h | amortaza/eos | 23ca52203fa0beece14430d6eee43f2b249376a6 | [
"MIT"
] | null | null | null | eos_dev/eos_dev/eos/eos.h | amortaza/eos | 23ca52203fa0beece14430d6eee43f2b249376a6 | [
"MIT"
] | null | null | null | #pragma once
#include "bellina/bl-node.h"
namespace eos {
void render(bl::Node *);
namespace _ {
void renderLabel(bl::Node *node, int dx, int dy);
void renderBorder(bl::Node *node, bool mustTopCanvas, int deltaX, int deltaY);
}
}
| 18.461538 | 80 | 0.6875 | [
"render"
] |
4ef5bd79fb7f36c4993ef97c02ce50b51358a810 | 21,922 | h | C | core-src/AlphaBeta.h | Quuxplusone/Homeworlds | 8e193a60a0cc59901df1980f3866731d5c1ee15a | [
"BSD-2-Clause"
] | 11 | 2016-07-01T10:51:58.000Z | 2021-03-18T07:59:32.000Z | core-src/AlphaBeta.h | Quuxplusone/Homeworlds | 8e193a60a0cc59901df1980f3866731d5c1ee15a | [
"BSD-2-Clause"
] | 1 | 2017-06-11T04:30:09.000Z | 2017-06-11T04:30:09.000Z | core-src/AlphaBeta.h | Quuxplusone/Homeworlds | 8e193a60a0cc59901df1980f3866731d5c1ee15a | [
"BSD-2-Clause"
] | 3 | 2016-02-27T16:53:28.000Z | 2017-06-10T19:21:24.000Z | #pragma once
#include <stddef.h>
#include <assert.h>
#include <queue>
#include <vector>
template<typename State // a state of the world, not necessarily including whose turn it is
,typename Move // an indication of how to get from one state to another state
,typename Value // a scalar "goodness" measure (e.g., "int" or "double")
>
class AlphaBeta {
// Given a State, return an approximation of its Value to the defender.
// (Its value to the attacker is just the negation of this value.)
// A State which the defender is happy to defend will have a high Value.
// Given a move M between states S1 and S2, one would expect M to be
// chosen if findattacker(S1)!=findattacker(S2) and evaluate(S2) > 0
// (the usual case), or if findattacker(S1)==findattacker(S2) and
// (-evaluate(S2)) > 0 --- that is, iff evaluate2(S1,S2) > 0.
typedef Value (*Evaluator)(const State &st);
// Given a State, apply the given Move to produce a new State.
typedef void (*MoveApplier)(State &st, const Move &move);
// Given a State, find all moves available to the attacker and add them
// to the given vector (which will be initially empty).
typedef void (*MoveFinder)(const State &st, std::vector<Move> &allmoves);
// Given a State, tell me which player is the next to move.
// Generally the State will contain a field that flips between 0 and 1
// each time applymove() is called, and findattacker() will just return
// that field.
typedef int (*AttackerFinder)(const State &st);
const Evaluator evaluate;
const MoveApplier applymove;
const MoveFinder findmoves;
const AttackerFinder findattacker;
int finddefender(const State &st) {
return 1-findattacker(st);
}
// Return a high Value if s1's attacker wants to move to s2.
Value evaluate2(const State &s1, const State &s2) {
if (findattacker(s1) != findattacker(s2)) {
return evaluate(s2);
}
return -evaluate(s2);
}
public:
AlphaBeta(Evaluator ev, MoveApplier app, MoveFinder fm, AttackerFinder fa):
evaluate(ev), applymove(app), findmoves(fm), findattacker(fa) { }
/* Given a State, return the best possible move for the attacker (looking
* "ply" plies deep). If the attacker has no legal moves (not even
* "pass"), then return false; else return true.
* The state after applying this move will have a chain of "best plays"
* leading away from it down the tree; return the expected value of the
* endpoint of that chain to the current defender. That is, if we find
* a winning move for "attacker", we'll set "bestvalue" to a negative value.
*/
bool depth_first(const State &st, int ply,
Move &bestmove, Value &bestvalue);
/* Same deal as above, but using alpha-beta pruning to speed up the search
* for large values of "ply". On the initial call, "alpha" should be set
* to the most negative Value and "beta" to the most positive Value.
* To search for a winning move (looking "ply" plies deep), start "alpha"
* at something just a tiny bit less than the value of a won game, and "beta"
* at the most positive Value.
* Alternatively, to search for the first move that simply doesn't lose
* the game (looking "ply" plies deep), start "beta" at something just a
* tiny bit greater than the value of a lost game, and "alpha" at the most
* negative Value.
*/
bool depth_first_alpha_beta(const State &st, int ply,
Move &bestmove, Value &bestvalue,
Value alpha, Value beta);
/* Given a State, return the best possible move using alpha-beta pruning,
* as above. However, rather than searching depth-first, we'll search
* breadth-first. This means that instead of recursively calling
* breadth_first_alpha_beta(), we'll push an "action record" of all
* the call's parameters onto an action queue, and then suspend the
* call until that "action record" reaches the front of the queue.
* At that point we'll continue processing that state.
* In the depth-first search, after we'd recursed on all of a given
* state's children, we would take the maximum of all their outputs.
* In this breadth-first search, after we've pushed action records for
* all of a given state's children, we will push another action record
* indicating that it's time to "return a value" from this state.
* Once we've inserted "maxnodes" states into our queue,
* we'll bottom out by using this->evaluate() on all the remaining
* states in the queue and processing the rest of the "value-returning"
* action records.
*/
bool breadth_first(const State &st, int maxnodes,
Move &bestmove, Value &bestvalue);
private:
enum BFR_type_t { RECURSE, RETURN };
struct BFRecord {
BFR_type_t type;
BFRecord *parent;
Move move; // What move did we use to get here?
// record->move may become record->parent->bestmove.
/* If type==RECURSE: */
State st; // starting state
/* If type==RETURN: */
int unreported_children;
int attacker;
bool hasbestvalue;
Value bestvalue;
Move bestmove; // The best move from this point; its value is bestvalue
BFRecord(BFR_type_t t, const State &s, const Move &m, BFRecord *p):
type(t), parent(p), move(m), st(s)
{ assert(t == RECURSE); assert(!p || p->type == RETURN); }
BFRecord(BFR_type_t t, const Move &m, int u, int a, BFRecord *p):
type(t), parent(p), move(m), unreported_children(u), attacker(a), hasbestvalue(false)
{ assert(t == RETURN); assert(!p || p->type == RETURN); }
#if 1
void print() const {
printf("%s, parent=%p, move=%c, ", type==RETURN?"RETURN":"RECURSE", (void*)parent, move.letter);
if (type == RECURSE) {
printf("st=??\n");
} else {
printf("uch=%d, attacker=%d", unreported_children, attacker);
if (hasbestvalue) {
printf(": bestmove is %c (value=%d)\n", bestmove.letter, bestvalue);
} else {
printf(": has no bestmove yet\n", parent);
}
}
}
#endif /* 1 */
};
};
template <typename State, typename Move, typename Value>
bool AlphaBeta<State,Move,Value>::depth_first(const State &st, int ply,
Move &bestmove, Value &bestvalue)
{
assert(ply >= 0);
/* This is the base case. Returning false from depth_first() basically
* means "game over; stop and evaluate() this position heuristically".
* This is exactly correct in the case where the game is actually over
* (see below), and coincidentally it turns out to be the right thing
* to do when we hit the ply limit as well. */
if (ply == 0) {
return false;
}
const int attacker = this->findattacker(st);
std::vector<Move> allmoves;
this->findmoves(st, allmoves);
/* If the attacker has no possible moves (not even a move corresponding
* to "pass", if this game allows players to pass), then the game is
* over. Return false, meaning "game over", as explained above. */
if (allmoves.empty()) {
return false;
}
/* Otherwise, the attacker has some possible moves, and we're going to
* look more than one ply deep. The best move in these cases is the move
* which the attacker is happiest to defend --- i.e., the move where if
* we run AlphaBeta.depth_first() on it from the opponent's point of view,
* we get back a very positive number.
*/
Value highestvalue(0);
int highestidx = -1;
for (int i=0; i < (int)allmoves.size(); ++i) {
State newstate = st;
this->applymove(newstate, allmoves[i]);
Move dbestmove; // unused
/* "dhighestvalue" will receive the value of "newstate" from the
* point of view of "newattacker" (who is trying to maximize that
* value). If newattacker != attacker, as in chess or checkers,
* then the value of this move to "attacker" will be the negation
* of "dhighestvalue". But if newattacker == attacker, then the value
* of this move to the attacker is obviously dhighestvalue itself. */
Value dhighestvalue;
Value value_to_me;
int newattacker = findattacker(newstate);
/* Generally, we'd expect that newattacker != attacker. */
bool foundmove = this->depth_first(newstate, ply-1, dbestmove, dhighestvalue);
if (!foundmove) {
/* If the defender has no moves left, then the game is definitely
* over. We must evaluate this position to see how happy we are
* with it. If we are very happy to defend it, then it is a
* position in which we have won the game. If we are very unhappy
* with it, then it is a position in which we have lost the game
* by making this move.
*/
value_to_me = this->evaluate2(st, newstate);
} else {
value_to_me = (newattacker != attacker) ? -dhighestvalue : dhighestvalue;
}
if (highestidx == -1 || value_to_me > highestvalue) {
highestidx = i;
highestvalue = value_to_me;
}
}
assert(highestidx != -1);
bestmove = allmoves[highestidx];
bestvalue = highestvalue;
return true;
}
/* This version is equivalent to depth_first(), but it takes two extra
* parameters "alpha" and "beta". "Alpha" is the smallest value the attacker
* can get if he plays optimally to maximize his score; it starts at -inf
* and gets higher.
* "Beta" is the biggest value the attacker can get if the defender plays
* optimally to counter him; it starts at +inf and gets lower.
* "Alpha" and "beta" swap places every half-move down the tree.
*/
template <typename State, typename Move, typename Value>
bool AlphaBeta<State,Move,Value>::depth_first_alpha_beta(
const State &st, int ply,
Move &bestmove, Value &bestvalue,
Value alpha, Value beta)
{
assert(ply >= 0);
/* This is the base case. Returning false from depth_first() basically
* means "game over; stop and evaluate() this position heuristically".
* This is exactly correct in the case where the game is actually over
* (see below), and coincidentally it turns out to be the right thing
* to do when we hit the ply limit as well. */
if (ply == 0) {
return false;
}
const int attacker = this->findattacker(st);
std::vector<Move> allmoves;
this->findmoves(st, allmoves);
/* If the attacker has no possible moves (not even a move corresponding
* to "pass", if this game allows players to pass), then the game is
* over. Return false, meaning "game over", as explained above. */
if (allmoves.empty()) {
return false;
}
/* Otherwise, the attacker has some possible moves, and we're going to
* look more than one ply deep. The best move in these cases is the move
* which the attacker is happiest to defend --- i.e., the move where if
* we run AlphaBeta.depth_first() on it from the opponent's point of view,
* we get back a very positive number.
*/
Value highestvalue;
int highestidx = -1;
bool bail_out_early = false;
for (int i=0; i < (int)allmoves.size(); ++i) {
if (bail_out_early) continue;
State newstate = st;
this->applymove(newstate, allmoves[i]);
Move dbestmove; // unused
/* "dhighestvalue" will receive the value of "newstate" from the
* point of view of "newattacker" (who is trying to maximize that
* value). If newattacker != attacker, as in chess or checkers,
* then the value of this move to "attacker" will be the negation
* of "dhighestvalue". But if newattacker == attacker, then the value
* of this move to the attacker is obviously dhighestvalue itself. */
Value dhighestvalue;
Value value_to_me;
int newattacker = findattacker(newstate);
/* Generally, we'd expect that newattacker != attacker. */
bool foundmove = this->depth_first(newstate, ply-1, dbestmove, dhighestvalue);
if (!foundmove) {
/* If the defender has no moves left, then the game is definitely
* over. We must evaluate this position to see how happy we are
* with it. If we are very happy to defend it, then it is a
* position in which we have won the game. If we are very unhappy
* with it, then it is a position in which we have lost the game
* by making this move.
*/
value_to_me = this->evaluate2(st, newstate);
} else {
value_to_me = (newattacker != attacker) ? -dhighestvalue : dhighestvalue;
}
if (highestidx == -1 || value_to_me > highestvalue) {
highestidx = i;
highestvalue = value_to_me;
/* We just found a move we are very happy to defend.
* Since we now know that we can do at least this well,
* we should set alpha = max(alpha, value_to_me). */
if (value_to_me > alpha) {
alpha = value_to_me;
if (value_to_me >= beta) {
/* We know we can't possibly do better than beta,
* so if we've found a move worth at least beta
* then we can stop looking. */
bail_out_early = true;
}
}
}
}
assert(highestidx != -1);
bestmove = allmoves[highestidx];
bestvalue = highestvalue;
return true;
}
template <typename State, typename Move, typename Value>
bool AlphaBeta<State,Move,Value>::breadth_first(const State &st, int maxnodes,
Move &bestmove, Value &bestvalue)
{
assert(maxnodes >= 0);
if (maxnodes == 0) {
return false;
}
std::queue<BFRecord *> Q;
/* The queue starts out with all the moves from this state. */
std::vector<Move> allmoves;
this->findmoves(st, allmoves);
/* If the attacker has no moves, return false. */
if (allmoves.empty()) {
return false;
}
/* Otherwise, initialize the queue by pushing action records for each of
* the attacker's possible moves. Link them all to "return_record", which
* has a parent of NULL --- that's how we'll know when we hit the top of
* the game tree again. */
int insertednodes = 0;
BFRecord *top_level_return_record = new BFRecord(RETURN, Move(), (int)allmoves.size(), this->findattacker(st), nullptr);
for (int i=0; i < (int)allmoves.size(); ++i) {
Q.push(new BFRecord(RECURSE, st, allmoves[i], top_level_return_record));
insertednodes += 1;
if (insertednodes == maxnodes) {
top_level_return_record->unreported_children = i+1;
break;
}
}
Q.push(top_level_return_record);
/* The queue is now initialized. */
for ( ; !Q.empty(); Q.pop()) {
assert(insertednodes <= maxnodes);
BFRecord *record = Q.front();
if (record->type == RETURN) {
assert(record->unreported_children >= 0);
if (record->unreported_children > 0) {
/* We can't process this record yet; not all of its children
* have reported in. Throw it back into the queue. */
Q.push(record);
continue;
} else {
assert(record->unreported_children == 0);
if (record->parent == nullptr) {
/* This is the very first record pushed on the queue,
* the one that holds this function's actual return
* values. Break out of the loop at this point. */
assert(record == top_level_return_record);
assert(record->hasbestvalue);
bestmove = record->bestmove;
bestvalue = record->bestvalue;
/* Note that "record" is still in the queue. */
goto delete_any_remaining_queue_elements;
}
/* Otherwise, record.bestvalue holds the Value of record.move
* (a move which yields record.state), from the point of view
* of the attacker who just made that move. We need to
* propagate that bestvalue up to our parent. */
assert(record->parent != nullptr);
/* Namely, this record is a child of its parent, and this
* record has not yet reported. */
assert(record->parent->unreported_children > 0);
assert(record->hasbestvalue);
Value value_to_parent;
if (record->attacker != record->parent->attacker) {
value_to_parent = -record->bestvalue;
} else {
value_to_parent = record->bestvalue;
}
if (!record->parent->hasbestvalue || value_to_parent > record->parent->bestvalue) {
record->parent->hasbestvalue = true;
record->parent->bestvalue = value_to_parent;
record->parent->bestmove = record->move;
}
record->parent->unreported_children -= 1;
delete record;
continue;
}
}
assert(record->type == RECURSE);
assert(record->parent != nullptr);
assert(record->parent->type == RETURN);
/* Namely, this record is a child of its parent, and this record has
* not yet reported. */
assert(record->parent->unreported_children > 0);
State newstate = record->st;
this->applymove(newstate, record->move);
const int newattacker = this->findattacker(newstate);
/* Now this is basically the same code as depth_first(). */
/* If we're wrapping up already, then we'll just take the value
* of this position to be its value according to this->evaluate().
* We'll do the same easy evaluate() route if the attacker has
* no possible moves.
*/
if (insertednodes == maxnodes) {
easy_evaluate:
Value value_to_me = this->evaluate2(record->st, newstate);
Value value_to_parent;
if (this->findattacker(record->st) != record->parent->attacker) {
value_to_parent = -value_to_me;
} else {
value_to_parent = value_to_me;
}
if (!record->parent->hasbestvalue || value_to_parent > record->parent->bestvalue) {
record->parent->hasbestvalue = true;
record->parent->bestvalue = value_to_parent;
record->parent->bestmove = record->move;
}
record->parent->unreported_children -= 1;
delete record;
continue;
}
assert(insertednodes < maxnodes);
/* Otherwise, if we are not yet in the wrapping-up stage, the value
* of this position is going to be computed by taking the maximum of
* the values of all its children. Push a record for each child, where
* that record contains a link to the new RETURN record. */
std::vector<Move> allmoves;
this->findmoves(newstate, allmoves);
if (allmoves.empty()) {
/* If the new attacker has no moves left, then the game is
* definitely over. We must evaluate this position to see how
* happy our parent is to defend it. See above. */
goto easy_evaluate;
}
/* The new attacker has some possible moves, and we're not yet
* wrapping things up. So push a RECURSE record for each possible
* move, and push a RETURN record to defer the final processing on
* this node.
*/
BFRecord *return_record = new BFRecord(RETURN, record->move, (int)allmoves.size(), newattacker, record->parent);
for (int i=0; i < (int)allmoves.size(); ++i) {
Q.push(new BFRecord(RECURSE, newstate, allmoves[i], return_record));
insertednodes += 1;
if (insertednodes == maxnodes) {
return_record->unreported_children = i+1;
break;
}
}
Q.push(return_record);
/* We have now successfully suspended the rest of this computation.
* This record can now be disposed of. */
delete record;
assert(insertednodes <= maxnodes);
/* If insertednodes == maxnodes at this point, we enter the
* "wrapping things up" phase (see above), in which we start using
* this->evaluate() on whatever nodes of the game tree still remain
* in Q, rather than calling findmoves() on them.
*/
}
/* The loop above will exit only if the queue becomes empty. This should
* never happen, because before the queue can empty completely we must
* encounter "top_level_return_record", and at that point we'll jump to
* "delete_any_remaining_queue_elements" below. */
assert(false);
delete_any_remaining_queue_elements:
delete Q.front();
Q.pop();
assert(Q.empty());
while (!Q.empty()) {
delete Q.front();
Q.pop();
}
return true;
}
| 45.481328 | 124 | 0.600128 | [
"vector"
] |
4ef660d873aa9bc68c2fcdf415c416385aca5f48 | 8,241 | h | C | matchinglib_poselib/source/poselib/include/arrsac/sample_consensus_estimator.h | josefmaierfl/matchinglib_poselib | 3bd7125a1ddfea68dfa95c8b3f978cba4a678348 | [
"MIT"
] | 1 | 2021-12-30T14:58:18.000Z | 2021-12-30T14:58:18.000Z | matchinglib_poselib/source/poselib/include/arrsac/sample_consensus_estimator.h | josefmaierfl/matchinglib_poselib | 3bd7125a1ddfea68dfa95c8b3f978cba4a678348 | [
"MIT"
] | 1 | 2020-08-19T16:11:15.000Z | 2020-08-19T16:11:15.000Z | matchinglib_poselib/source/poselib/include/arrsac/sample_consensus_estimator.h | josefmaierfl/matchinglib_poselib | 3bd7125a1ddfea68dfa95c8b3f978cba4a678348 | [
"MIT"
] | 2 | 2020-09-28T13:20:59.000Z | 2022-01-04T10:56:02.000Z | // Copyright (C) 2013 The Regents of the University of California (Regents).
// 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 or 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 THE COPYRIGHT HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#ifndef THEIA_SOLVERS_SAMPLE_CONSENSUS_ESTIMATOR_H_
#define THEIA_SOLVERS_SAMPLE_CONSENSUS_ESTIMATOR_H_
//#include <glog/logging.h>
#include <memory>
#include <vector>
#include "estimator.h"
#include "quality_measurement.h"
#include "sampler.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
namespace theia {
template <class Datum, class Model> class SampleConsensusEstimator {
public:
SampleConsensusEstimator() {}
virtual ~SampleConsensusEstimator() {
/*sampler_->~Sampler;
sampler_ = NULL;
quality_measurement_->~QualityMeasurement;
quality_measurement_ = NULL;*/
}
// Computes the best-fitting model using RANSAC. Returns false if RANSAC
// calculation fails and true (with the best_model output) if successful.
// Params:
// data: the set from which to sample
// estimator: The estimator used to estimate the model based on the Datum
// and Model type
// best_model: The output parameter that will be filled with the best model
// estimated from RANSAC
virtual bool Estimate(const std::vector<Datum>& data,
const Estimator<Datum, Model>& estimator,
Model* best_model);
// Returns a bool vector with true for inliers, false for outliers.
const std::vector<bool>& GetInliers() { return inliers_; }
// Count the number of inliers.
int GetNumInliers() {
int num_inliers = 0;
for(size_t i = 0; i < inliers_.size(); i++) {
if (inliers_[i]) num_inliers++;
}
return num_inliers;
}
int GetNumIterations() { return num_iters_; }
protected:
// sampler: The class that instantiates the sampling strategy for this
// particular type of sampling consensus.
// quality_measurement: class that instantiates the quality measurement of
// the data. This determines the stopping criterion.
// max_iters: Maximum number of iterations to run RANSAC. To set the number
// of iterations based on the outlier probability, use SetMaxIters.
SampleConsensusEstimator(Sampler<Datum>* sampler,
QualityMeasurement* quality_measurement,
int max_iters = 10000)
: sampler_(sampler), quality_measurement_(quality_measurement),
max_iters_(max_iters), num_iters_(-1) {
assert(sampler != nullptr);
// CHECK_NOTNULL(sampler);
//sampler_.reset(sampler);
assert(quality_measurement != nullptr);
// CHECK_NOTNULL(quality_measurement);
//quality_measurement_.reset(quality_measurement);
}
// Our sampling strategy.
cv::Ptr<Sampler<Datum>> sampler_;
// Our quality metric for the estimated model and data.
cv::Ptr<QualityMeasurement> quality_measurement_;
// Inliners from the recent data. Only valid if Estimate has been called!
std::vector<bool> inliers_;
// Max number of iterations to perform before terminating .
int max_iters_;
// Number of iterations performed before succeeding.
int num_iters_;
};
template <class Datum, class Model>
bool SampleConsensusEstimator<Datum, Model>::Estimate(
const std::vector<Datum>& data, const Estimator<Datum, Model>& estimator,
Model* best_model) {
assert(data.size() != 0);
/*CHECK_GT(data.size(), 0)
<< "Cannot perform estimation with 0 data measurements!";*/
double best_quality = static_cast<double>(QualityMeasurement::INVALID);
for (int iters = 0; iters < max_iters_; iters++) {
// Sample subset. Proceed if successfully sampled.
std::vector<Datum> data_subset;
if (!sampler_->Sample(data, &data_subset)) {
continue;
}
// Estimate model from subset. Skip to next iteration if the model fails to
// estimate.
std::vector<Model> temp_models;
if (!estimator.EstimateModel(data_subset, &temp_models)) {
continue;
}
// Calculate residuals from estimated model.
for(size_t j = 0; j < temp_models.size();j++) {
std::vector<double> residuals = estimator.Residuals(data, temp_models[j]);
// Determine quality of the generated model.
std::vector<bool> temp_inlier_set(data.size());
double sample_quality =
quality_measurement_->Calculate(residuals, &temp_inlier_set);
// Update best model if error is the best we have seen.
if (quality_measurement_->Compare(sample_quality, best_quality) ||
best_quality == static_cast<double>(QualityMeasurement::INVALID)) {
*best_model = temp_models[j];
best_quality = sample_quality;
// If the inlier termination criterion is met, re-estimate the model
// based on all inliers and return;
if (quality_measurement_->SufficientlyHighQuality(best_quality)) {
// Grab inliers to refine the model.
std::vector<Datum> temp_consensus_set;
for (size_t i = 0; i < temp_inlier_set.size(); i++) {
if (temp_inlier_set[i]) {
temp_consensus_set.push_back(data[i]);
}
}
// Refine the model based on all current inliers.
estimator.RefineModel(temp_consensus_set, best_model);
num_iters_ = iters + 1;
// Calculate the final inliers.
inliers_.resize(data.size());
std::vector<double> final_residuals =
estimator.Residuals(data, *best_model);
quality_measurement_->Calculate(final_residuals, &inliers_);
return true;
}
}
}
}
// Grab inliers to refine the model.
std::vector<double> residuals = estimator.Residuals(data, *best_model);
std::vector<bool> temp_inlier_set(data.size());
quality_measurement_->Calculate(residuals, &temp_inlier_set);
std::vector<Datum> temp_consensus_set;
for (size_t i = 0; i < temp_inlier_set.size(); i++) {
if (temp_inlier_set[i]) {
temp_consensus_set.push_back(data[i]);
}
}
// Refine the model based on all current inliers.
estimator.RefineModel(temp_consensus_set, best_model);
// Calculate the final inliers.
inliers_.resize(data.size());
std::vector<double> final_residuals = estimator.Residuals(data, *best_model);
quality_measurement_->Calculate(final_residuals, &inliers_);
return true;
}
} // namespace theia
#endif // THEIA_SOLVERS_SAMPLE_CONSENSUS_ESTIMATOR_H_
| 39.620192 | 81 | 0.683776 | [
"vector",
"model"
] |
4efac4e9cce861fb123e66e39fe68877e021c616 | 1,284 | h | C | Files/CollectionsAdditions.h | n-b/Bicyclette | 18393a2accd71ffc4317879835a103aa69db9b16 | [
"BSD-2-Clause"
] | 13 | 2015-01-25T17:07:14.000Z | 2021-07-17T13:37:58.000Z | Files/CollectionsAdditions.h | n-b/Bicyclette | 18393a2accd71ffc4317879835a103aa69db9b16 | [
"BSD-2-Clause"
] | 6 | 2015-03-14T09:41:13.000Z | 2018-01-08T08:03:13.000Z | Files/CollectionsAdditions.h | n-b/Bicyclette | 18393a2accd71ffc4317879835a103aa69db9b16 | [
"BSD-2-Clause"
] | 7 | 2015-08-25T20:48:07.000Z | 2021-07-17T13:38:02.000Z | //
// CollectionsAdditions.h
//
// Created by Nicolas Bouilleaud a long time ago.
//
#import <Foundation/Foundation.h>
@interface NSArray (Additions)
/*
* KVC related addition : find and return the first object in the array whose value for key *key* is equal to *value*.
* will return n il if no such object is found.
*/
- (id) firstObjectWithValue:(id)value forKeyPath:(NSString*)key;
/*
* KVC related addition : find and return the objects in the array whose value for key *key* is equal to *value*.
* will return an empty array if no such object is found.
*/
- (NSArray*) filteredArrayWithValue:(id)value forKeyPath:(NSString*)key;
/*
* arrayByRemovingObjectsInArray
*/
- (NSArray*) arrayByRemovingObjectsInArray:(NSArray*)otherArray;
@end
@interface NSSet (Additions)
/*
* KVC related addition : find and return the first object in the array whose value for key *key* is equal to *value*.
* will return n il if no such object is found.
*/
- (id) anyObjectWithValue:(id)value forKeyPath:(NSString*)key;
/*
* KVC related addition : find and return the objects in the array whose value for key *key* is equal to *value*.
* will return an empty array if no such object is found.
*/
- (NSSet*) filteredSetWithValue:(id)value forKeyPath:(NSString*)key;
@end
| 27.319149 | 118 | 0.722741 | [
"object"
] |
4efc6d71ac35f9edf5e9632786415bfb4f1dd83d | 2,704 | h | C | plugins/material/parser/ParseGrammarContext.h | zapolnov/game_engine | cd22dc0f49aeadd660eec3ea9b95b1ca2696f97a | [
"MIT",
"Unlicense"
] | null | null | null | plugins/material/parser/ParseGrammarContext.h | zapolnov/game_engine | cd22dc0f49aeadd660eec3ea9b95b1ca2696f97a | [
"MIT",
"Unlicense"
] | null | null | null | plugins/material/parser/ParseGrammarContext.h | zapolnov/game_engine | cd22dc0f49aeadd660eec3ea9b95b1ca2696f97a | [
"MIT",
"Unlicense"
] | null | null | null | /*
* Copyright (c) 2015 Nikolay Zapolnov (zapolnov@gmail.com).
*
* 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.
*/
struct Context
{
CullFace cullFaceValue;
bool blendingEnabled;
std::vector<bool> boolValues;
std::vector<std::string> stringValues;
std::vector<float> floatValues;
std::vector<BlendFunc> blendFuncValues;
std::unique_ptr<Tree::Uniform> uniformValue;
std::unique_ptr<std::string> techniqueName;
std::unique_ptr<std::string> passName;
std::vector<std::shared_ptr<Tree::OptionList>> optionLists;
std::shared_ptr<Tree::Pass> currentPass;
std::shared_ptr<Tree::Technique> currentTechnique;
std::shared_ptr<Tree::File> currentFile;
std::string materialFileName;
Context()
{
currentFile = std::make_shared<Tree::File>();
optionLists.emplace_back(currentFile);
}
Tree::OptionList& currentOptionList()
{
assert(!optionLists.empty());
return *optionLists.back();
}
template <class TYPE, class... ARGS> void emitOption(ARGS&&... args)
{
currentOptionList().options.emplace_back(std::make_shared<TYPE>(std::forward<ARGS>(args)...));
}
void pushOptionList(std::shared_ptr<Tree::OptionList>&& list)
{
optionLists.emplace_back(list);
}
void popOptionList(Tree::OptionList& current)
{
assert(!optionLists.empty());
assert(optionLists.back().get() == ¤t);
(void)current;
optionLists.pop_back();
}
};
template <class TYPE> TYPE pop(std::vector<TYPE>& array)
{
assert(!array.empty());
TYPE value(std::move(array.back()));
array.pop_back();
return value;
}
| 34.666667 | 102 | 0.697485 | [
"vector"
] |
ab8c3ba3da7cec195051b460cb05af44bf2862f0 | 3,410 | h | C | utils_tests.h | martinjvickers/alfsc_rewrite | a4f265fa7d30d8b98d8e5df3f0a223b0cc5a31f0 | [
"MIT"
] | 5 | 2018-04-09T13:28:16.000Z | 2021-04-26T04:59:29.000Z | utils_tests.h | martinjvickers/KAST | b58649a253f34d888a49f6c251f166744257289f | [
"MIT"
] | 30 | 2017-04-03T16:20:21.000Z | 2018-11-23T15:43:03.000Z | utils_tests.h | martinjvickers/alfsc_rewrite | a4f265fa7d30d8b98d8e5df3f0a223b0cc5a31f0 | [
"MIT"
] | 1 | 2022-03-15T14:55:58.000Z | 2022-03-15T14:55:58.000Z | #include "utils.h"
using namespace seqan;
using namespace std;
SEQAN_DEFINE_TEST(count_dna)
{
}
SEQAN_DEFINE_TEST(mask_count_dna)
{
String<Dna5> seq = "AGGCAGCGTACGAACCTACTGGAGTTGCGGTATGGGACCAGGCGACCTCTGATGCAGAGATACAGGAGCGCCGCGCCGGGTCTTCCTTGTAGAAGTCCTG";
String<unsigned> counts;
int klen = 5;
int effectiveLength = 1;
vector<CharString> mask;
mask.push_back("10000");
countKmersNew(counts, seq, klen, effectiveLength, mask);
/*
Result should be;
A = 21
C = 24
G = 33
T = 18
*/
/*Set up a results kmer counts with the known result*/
String<unsigned> kmerCounts;
Shape<Dna> myShape;
resize(myShape, effectiveLength);
int kmerNumber = _intPow((unsigned)ValueSize<Dna>::VALUE, weight(myShape));
seqan::clear(kmerCounts);
seqan::resize(kmerCounts, kmerNumber, 0);
kmerCounts[0] = 21;
kmerCounts[1] = 24;
kmerCounts[2] = 33;
kmerCounts[3] = 18;
for(int i = 0; i < length(counts); i++)
{
SEQAN_ASSERT_EQ(kmerCounts[i], counts[i]);
}
}
SEQAN_DEFINE_TEST(mask_count_raa)
{
String<ReducedAminoAcidMurphy10> seq = "MVLTIYPDELVQIVS";
String<unsigned> counts;
int klen = 5;
int effectiveLength = 1;
vector<CharString> mask;
mask.push_back("10000");
countKmersNew(counts, seq, klen, effectiveLength, mask);
String<unsigned> kmerCounts;
Shape<ReducedAminoAcidMurphy10> myShape;
resize(myShape, effectiveLength);
int kmerNumber = _intPow((unsigned)ValueSize<ReducedAminoAcidMurphy10>::VALUE, weight(myShape));
seqan::clear(kmerCounts);
seqan::resize(kmerCounts, kmerNumber, 0);
kmerCounts[0] = 0;
kmerCounts[1] = 2;
kmerCounts[2] = 0;
kmerCounts[3] = 1;
kmerCounts[4] = 0;
kmerCounts[5] = 0;
kmerCounts[6] = 6;
kmerCounts[7] = 0;
kmerCounts[8] = 1;
kmerCounts[9] = 1;
for(unsigned int i = 0; i < length(counts); i++)
{
SEQAN_ASSERT_EQ(kmerCounts[i], counts[i]);
// String<ReducedAminoAcidMurphy10> orig;
// unhash(orig, i, effectiveLength);
// cout << orig << "\t" << counts[i] << endl;
// cout << "kmerCounts[" << i << "] = " << counts[i] << ";" << endl;
}
}
SEQAN_DEFINE_TEST(mask_count_aa)
{
String<AminoAcid> seq = "MVLTIYPDELVQIVS";
String<unsigned> counts;
int klen = 5;
int effectiveLength = 1;
vector<CharString> mask;
mask.push_back("10000");
countKmersNew(counts, seq, klen, effectiveLength, mask);
String<unsigned> kmerCounts;
Shape<ReducedAminoAcidMurphy10> myShape;
resize(myShape, effectiveLength);
int kmerNumber = _intPow((unsigned)ValueSize<AminoAcid>::VALUE, weight(myShape));
seqan::clear(kmerCounts);
seqan::resize(kmerCounts, kmerNumber, 0);
kmerCounts[0] = 0;
kmerCounts[1] = 0;
kmerCounts[2] = 0;
kmerCounts[3] = 1;
kmerCounts[4] = 1;
kmerCounts[5] = 0;
kmerCounts[6] = 0;
kmerCounts[7] = 0;
kmerCounts[8] = 1;
kmerCounts[9] = 0;
kmerCounts[10] = 0;
kmerCounts[11] = 2;
kmerCounts[12] = 1;
kmerCounts[13] = 0;
kmerCounts[14] = 0;
kmerCounts[15] = 1;
kmerCounts[16] = 0;
kmerCounts[17] = 0;
kmerCounts[18] = 0;
kmerCounts[19] = 1;
kmerCounts[20] = 0;
kmerCounts[21] = 2;
kmerCounts[22] = 0;
kmerCounts[23] = 1;
kmerCounts[24] = 0;
kmerCounts[25] = 0;
kmerCounts[26] = 0;
for(int i = 0; i < length(counts); i++)
{
SEQAN_ASSERT_EQ(kmerCounts[i], counts[i]);
}
}
| 25.259259 | 125 | 0.648094 | [
"shape",
"vector"
] |
aba7a3b10f8a465c31e7473c02dbae592b47d729 | 398 | h | C | TeslaEngine/tesla/tesla.h | ericmux/tesla-engine | 8c156e75de9d2fc2afe29987b028c54649d9b212 | [
"MIT"
] | null | null | null | TeslaEngine/tesla/tesla.h | ericmux/tesla-engine | 8c156e75de9d2fc2afe29987b028c54649d9b212 | [
"MIT"
] | 4 | 2015-03-12T21:12:07.000Z | 2015-03-12T21:20:10.000Z | TeslaEngine/tesla/tesla.h | ericmux/tesla-engine | 8c156e75de9d2fc2afe29987b028c54649d9b212 | [
"MIT"
] | null | null | null | //
// tesla.h
// TeslaEngine
//
// Created by Eric Muxagata on 2/11/15.
// Copyright (c) 2015 Eric Muxagata. All rights reserved.
//
#ifndef TeslaEngine_tesla_h
#define TeslaEngine_tesla_h
#include "Director.h"
//render
#include "Renderer.h"
#include "Texture.h"
#include "RenderCommand.h"
//scene
#include "Scene.h"
#include "Node.h"
#include "Sprite.h"
#include "RenderTest.h"
#endif
| 13.724138 | 58 | 0.701005 | [
"render"
] |
abb170cdf8730233e0d894eb6bd419d12bd75b11 | 5,242 | h | C | src/test/ur_test/include/test_delay.h | Slifer64/ur5_test_delay | c7e8460a89d967615592471ad5d196900c5e89df | [
"MIT"
] | null | null | null | src/test/ur_test/include/test_delay.h | Slifer64/ur5_test_delay | c7e8460a89d967615592471ad5d196900c5e89df | [
"MIT"
] | null | null | null | src/test/ur_test/include/test_delay.h | Slifer64/ur5_test_delay | c7e8460a89d967615592471ad5d196900c5e89df | [
"MIT"
] | null | null | null | #include <memory>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <exception>
#include <armadillo>
#include <ros/ros.h>
#include <ros/package.h>
#include <io_lib/io_lib.h>
#include <ur_robot/ur_robot.h>
#include <io_utils.h>
using namespace as64_;
class Worker
{
public:
Worker(const std::string &ip, int port)
{
robot.reset(new ur_::Robot("10.0.0.1", 50001));
}
void setFreeDriveMode()
{
robot->setMode(ur_::Mode::FREEDRIVE_MODE);
}
void printJointsPos()
{
std::thread([this]()
{
arma::vec jpos = robot->getJointsPosition();
std::cout << "jpos = " << jpos.t() << "\n";
}).detach();
}
bool setJointsTrajectory(const arma::vec &qT, double duration)
{
// keep last known robot mode
ur_::Mode prev_mode = robot->getMode();
// start controller
robot->setMode(ur_::Mode::VELOCITY_CONTROL);
// waits for the next tick
robot->waitNextCycle();
arma::vec q0 = robot->getJointsPosition();
arma::vec q = q0;
arma::vec qref = q0;
arma::vec qref_dot;
double t = 0.0;
double click = 0.0;
// the main while
while (t < duration)
{
if (!robot->isOk())
{
std::cerr << robot->getErrMsg();
return false;
}
// compute time now
t += robot->getCtrlCycle();
// update trajectory
arma::mat ref_traj = get5thOrder(t, q0, qT, duration);
qref = ref_traj.col(0);
qref_dot = ref_traj.col(1);
arma::vec q_dot_cmd = qref_dot; // + click*(qref-q);
robot->setJointsVelocity(q_dot_cmd, qref);
// waits for the next tick
robot->waitNextCycle();
q = robot->getJointsPosition();
}
// reset last known robot mode
robot->setMode(prev_mode);
return true;
}
void executeTrajectory()
{
arma::vec q;
arma::vec q_start = {-0.7827, -1.2511, -1.4126, -1.6371, 1.6009, 0.0254};
arma::vec q_end = {0.3761, -1.8148, -1.4127, -2.7396, 1.6009, 0.0254};
// Set the robot in position control mode
robot->setMode(ur_::Mode::POSITION_CONTROL);
std::cout << io_::bold << io_::green << "=== The robot is in position control ===\n" << io_::reset;
if (!ros::ok()) exit(-1);
robot->waitNextCycle();
q = robot->getJointsPosition();
double duration = 6.5;
std::cout << io_::bold << io_::cyan << "The robot will move to its initial pose in " << duration << " sec.\n" << io_::reset;
robot->setJointsTrajectory(q_start, duration);
std::cout << io_::bold << io_::cyan << "Initial pose reached!\n" << io_::reset;
if (!ros::ok()) exit(-1);
robot->waitNextCycle();
q = robot->getJointsPosition();
duration = 6.5;
std::cout << io_::bold << io_::cyan << "The robot will move to its final pose in " << duration << " sec.\n" << io_::reset;
robot->startLogging();
robot->setJointsTrajectory(q_end, duration);
robot->stopLogging();
std::cout << io_::bold << io_::cyan << "*** Final pose reached! ***\n" << io_::reset;
robot->saveLoggedData(ros::package::getPath("ur_test") + "/data/logged_data.bin");
}
std::shared_ptr<ur_::Robot> robot;
private:
arma::mat get5thOrder(double t, arma::vec p0, arma::vec pT, double totalTime)
{
arma::mat retTemp = arma::zeros<arma::mat>(p0.n_rows, 3);
if (t < 0)
{
// before start
retTemp.col(0) = p0;
}
else if (t > totalTime)
{
// after the end
retTemp.col(0) = pT;
}
else
{
// somewhere betweeen ...
// position
retTemp.col(0) = p0 +
(pT - p0) * (10 * pow(t / totalTime, 3) -
15 * pow(t / totalTime, 4) +
6 * pow(t / totalTime, 5));
// vecolity
retTemp.col(1) = (pT - p0) * (30 * pow(t, 2) / pow(totalTime, 3) -
60 * pow(t, 3) / pow(totalTime, 4) +
30 * pow(t, 4) / pow(totalTime, 5));
// acceleration
retTemp.col(2) = (pT - p0) * (60 * t / pow(totalTime, 3) -
180 * pow(t, 2) / pow(totalTime, 4) +
120 * pow(t, 3) / pow(totalTime, 5));
}
// return vector
return retTemp;
}
};
int main(int argc, char** argv)
{
// =========== Initialize the ROS node ==================
ros::init(argc, argv, "test_ur");
// =========== Create robot ==================
Worker worker("10.0.0.1", 50001);
worker.setFreeDriveMode();
arma::vec q1 = {-0.7827, -1.2511, -1.4126, -1.6371, 1.6009, 0.0254};
arma::vec q2 = {0.3761, -1.8148, -1.4127, -2.7396, 1.6009, 0.0254};
while (ros::ok())
{
worker.robot->waitNextCycle();
char ch = ' ';
ch = getch();
if (ch == 'f') worker.setFreeDriveMode();
if (ch == 't') worker.executeTrajectory();
if (ch == '1') worker.robot->movej(q1, 1.4, 1.05, 8); //worker.setJointsTrajectory(q1, 6);
if (ch == '2') worker.robot->movej(q1, 1.4, 1.05, 8); //worker.setJointsTrajectory(q2, 6);
if (ch == 'j') worker.printJointsPos();
if (ch == 'q') break;
}
// =========== Shutdown ROS node ==================
// ros::shutdown();
return 0;
}
| 26.341709 | 128 | 0.547692 | [
"vector"
] |
abbdddcc9711f853770802b4cb506592b1957c24 | 16,444 | h | C | Modelica_DeviceDrivers/Resources/Include/MDDMQTT.h | hubertus65/Modelica_DeviceDrivers | 79df766871e2451f65882fb69e1cfa784df3d792 | [
"BSD-3-Clause"
] | 29 | 2015-04-16T08:02:33.000Z | 2019-02-22T03:06:16.000Z | Modelica_DeviceDrivers/Resources/Include/MDDMQTT.h | hubertus65/Modelica_DeviceDrivers | 79df766871e2451f65882fb69e1cfa784df3d792 | [
"BSD-3-Clause"
] | 172 | 2015-02-06T11:10:55.000Z | 2019-04-03T08:31:39.000Z | Modelica_DeviceDrivers/Resources/Include/MDDMQTT.h | hubertus65/Modelica_DeviceDrivers | 79df766871e2451f65882fb69e1cfa784df3d792 | [
"BSD-3-Clause"
] | 20 | 2015-01-27T10:50:50.000Z | 2019-03-15T11:13:17.000Z | /** MQTT client support (header-only library).
*
* @file
* @author tbeu
* @since 2018-08-13
* @copyright see accompanying file LICENSE_Modelica_DeviceDrivers.txt
*
*/
#ifndef MDDMQTT_H_
#define MDDMQTT_H_
#if !defined(ITI_COMP_SIM)
#include <stdlib.h>
#include <stdio.h>
#if defined(_MSC_VER) && _MSC_VER < 1900
#define snprintf _snprintf
#endif
#if defined(_MSC_VER) || defined(__MINGW32__)
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
#include "../src/include/CompatibilityDefs.h"
#include "../thirdParty/paho.mqtt.c/MQTTClient.h"
#include "ModelicaUtilities.h"
#include "MDDSerialPackager.h"
#if defined(__linux__) || defined(__CYGWIN__)
#include <errno.h>
#include <pthread.h>
#endif
#define MDD_SSL_ERROR_MSG_LENGTH_MAX (512)
typedef struct {
MQTTClient* client;
char* receiveBuffer;
char* receiveChannel;
char sslErrorMsg[MDD_SSL_ERROR_MSG_LENGTH_MAX];
int bufferSize;
int nReceivedBytes;
int QoS;
int disconnectTimeout;
#if defined(_MSC_VER) || defined(__MINGW32__)
CRITICAL_SECTION lock;
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_t mutex;
#else
#warning "No thread syncronization available for your platform"
#endif
} MQTT;
static int MDD_mqttSSLErrorHandler(const char *str, size_t len, void *p_mqtt) {
MQTT* mqtt = (MQTT*) p_mqtt;
if (NULL != mqtt) {
#if defined(_MSC_VER) || defined(__MINGW32__)
EnterCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_lock(&mqtt->mutex);
#endif
if (NULL == strstr(mqtt->sslErrorMsg, str) && strlen(mqtt->sslErrorMsg) + len + 1 < MDD_SSL_ERROR_MSG_LENGTH_MAX) {
strcat(mqtt->sslErrorMsg, str);
strcat(mqtt->sslErrorMsg, "\n");
}
#if defined(_MSC_VER) || defined(__MINGW32__)
LeaveCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_unlock(&mqtt->mutex);
#endif
}
return 1;
}
static int MDD_mqttMsgArrivedHandler(void* p_mqtt, char* channel, int len, MQTTClient_message* message) {
MQTT* mqtt = (MQTT*) p_mqtt;
if (NULL != mqtt) {
#if defined(_MSC_VER) || defined(__MINGW32__)
EnterCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_lock(&mqtt->mutex);
#endif
if (message->payloadlen <= mqtt->bufferSize) {
memcpy(mqtt->receiveBuffer, message->payload, message->payloadlen);
mqtt->nReceivedBytes = message->payloadlen;
}
if (message->payloadlen < mqtt->bufferSize) {
mqtt->receiveBuffer[message->payloadlen] = '\0';
}
#if defined(_MSC_VER) || defined(__MINGW32__)
LeaveCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_unlock(&mqtt->mutex);
#endif
}
MQTTClient_freeMessage(&message);
MQTTClient_free(channel);
return 1;
}
static void MDD_mqttDisconnectedHandler(void* p_mqtt, char* cause) {
#ifndef ITI_MDD
ModelicaMessage("MDDMQTT.h: The MQTT client was disconnected\n");
#endif
}
static void MDD_mqttTraceHandler(enum MQTTCLIENT_TRACE_LEVELS level, char* message) {
ModelicaFormatMessage("%s\n", message);
}
DllExport void * MDD_mqttConstructor(const char* provider, const char* address,
int port, int receiver, int QoS,
const char* channel, int bufferSize,
const char* clientID, const char* userName,
const char* password, const char* trustStore,
const char* keyStore, const char* privateKey,
int keepAliveInterval, int cleanSession,
int reliable, int connectTimeout,
int MQTTVersion, int disconnectTimeout,
int enableServerCertAuth, int verify, int sslVersion,
int traceLevel) {
MQTT* mqtt = (MQTT*) calloc(1, sizeof(MQTT));
if (NULL != mqtt) {
int rc;
char url[201];
MQTTClient_SSLOptions ssl_opts = MQTTClient_SSLOptions_initializer;
MQTTClient_SSLOptions* p_ssl_opts;
char* receiveBuffer = NULL;
char* receiveChannel = NULL;
if (receiver) {
receiveBuffer = (char*)calloc(bufferSize, 1);
if (NULL == receiveBuffer) {
free(mqtt);
mqtt = NULL;
ModelicaError("MDDMQTT.h: Could not allocate MQTT client receive buffer\n");
return mqtt;
}
receiveChannel = (char*)malloc(strlen(channel) + 1);
if (NULL == receiveChannel) {
free(receiveBuffer);
free(mqtt);
mqtt = NULL;
ModelicaError("MDDMQTT.h: Could not allocate MQTT client receive channel name\n");
return mqtt;
}
strcpy(receiveChannel, channel);
}
snprintf(url, 200, "%s%s:%d", provider, address, port);
if (0 == strcmp("ssl://", provider) || 0 == strcmp("wss://", provider)) {
/* SSL/TLS */
p_ssl_opts = &ssl_opts;
ssl_opts.enableServerCertAuth = enableServerCertAuth;
ssl_opts.verify = verify;
ssl_opts.sslVersion = sslVersion;
ssl_opts.ssl_error_cb = MDD_mqttSSLErrorHandler;
ssl_opts.ssl_error_context = mqtt;
if ('\0' != trustStore[0]) {
ssl_opts.trustStore = trustStore;
}
if ('\0' != keyStore[0]) {
ssl_opts.keyStore = keyStore;
}
if ('\0' != privateKey[0]) {
ssl_opts.privateKey = privateKey;
}
}
else {
p_ssl_opts = NULL;
}
mqtt->client = (MQTTClient*) malloc(sizeof(MQTTClient));
if (NULL == mqtt->client) {
free(receiveBuffer);
free(receiveChannel);
free(mqtt);
mqtt = NULL;
ModelicaError("MDDMQTT.h: Could not allocate MQTT client object\n");
return mqtt;
}
if (0 != traceLevel) {
MQTTClient_setTraceLevel((enum MQTTCLIENT_TRACE_LEVELS) traceLevel);
MQTTClient_setTraceCallback(MDD_mqttTraceHandler);
}
else {
MQTTClient_setTraceCallback(NULL);
}
mqtt->bufferSize = bufferSize;
mqtt->receiveBuffer = receiveBuffer;
mqtt->receiveChannel = receiveChannel;
mqtt->QoS = QoS;
mqtt->disconnectTimeout = disconnectTimeout;
rc = MQTTClient_create(mqtt->client, url, clientID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
if (MQTTCLIENT_SUCCESS == rc) {
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
conn_opts.keepAliveInterval = keepAliveInterval;
conn_opts.cleansession = cleanSession;
conn_opts.reliable = reliable;
conn_opts.connectTimeout = connectTimeout;
conn_opts.MQTTVersion = MQTTVersion;
conn_opts.ssl = p_ssl_opts;
if ('\0' != userName[0]) {
conn_opts.username = userName;
}
if ('\0' != password[0]) {
conn_opts.password = password;
}
if (receiver) {
MQTTClient_setCallbacks(*mqtt->client, mqtt, MDD_mqttDisconnectedHandler, MDD_mqttMsgArrivedHandler, NULL);
}
#if defined(_MSC_VER) || defined(__MINGW32__)
InitializeCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
int ret = pthread_mutex_init(&mqtt->mutex, NULL);
if (ret != 0) {
MQTTClient_destroy(mqtt->client);
free(receiveBuffer);
free(receiveChannel);
free(mqtt);
mqtt = NULL;
ModelicaFormatError("MDDMQTT.h: pthread_mutex_init() failed (%s)\n", strerror(errno));
}
#endif
rc = MQTTClient_connect(*mqtt->client, &conn_opts);
if (MQTTCLIENT_SUCCESS == rc) {
if (receiver) {
rc = MQTTClient_subscribe(*mqtt->client, receiveChannel, QoS);
}
}
else {
const char* errString = rc != MQTTCLIENT_FAILURE ? MQTTClient_strerror(rc) : NULL;
char msg[MDD_SSL_ERROR_MSG_LENGTH_MAX];
#if defined(_MSC_VER) || defined(__MINGW32__)
EnterCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_lock(&mqtt->mutex);
#endif
strcpy(msg, mqtt->sslErrorMsg);
#if defined(_MSC_VER) || defined(__MINGW32__)
LeaveCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_unlock(&mqtt->mutex);
#endif
#if defined(_MSC_VER) || defined(__MINGW32__)
DeleteCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_destroy(&mqtt->mutex);
#endif
MQTTClient_destroy(mqtt->client);
free(receiveBuffer);
free(receiveChannel);
free(mqtt);
mqtt = NULL;
if (NULL != errString) {
ModelicaFormatError("MDDMQTT.h: Could not connect to server \"%s\" "
"with client ID \"%s\": %s\n", url, clientID, errString);
}
else if ('\0' != msg[0]) {
ModelicaFormatError("MDDMQTT.h: Could not connect to server \"%s\" "
"with client ID \"%s\":\n%s", url, clientID, msg);
}
else {
ModelicaFormatError("MDDMQTT.h: Could not connect to server \"%s\" "
"with client ID \"%s\"\n", url, clientID);
}
}
}
else {
const char* errString = rc != MQTTCLIENT_FAILURE ? MQTTClient_strerror(rc) : NULL;
free(receiveBuffer);
free(receiveChannel);
free(mqtt);
mqtt = NULL;
if (NULL != errString) {
ModelicaFormatError("MDDMQTT.h: Could not create MQTT client object for "
"server \"%s\" with client ID \"%s\": %s\n", url, clientID, errString);
}
else {
ModelicaFormatError("MDDMQTT.h: Could not create MQTT client object for "
"server \"%s\" with client ID \"%s\"\n", url, clientID);
}
}
}
return (void*) mqtt;
}
DllExport void MDD_mqttDestructor(void* p_mqtt) {
MQTT* mqtt = (MQTT*) p_mqtt;
if (NULL != mqtt) {
if (NULL != mqtt->client) {
if (NULL != mqtt->receiveChannel) {
int rc = MQTTClient_unsubscribe(*mqtt->client, mqtt->receiveChannel);
if (MQTTCLIENT_SUCCESS != rc) {
ModelicaFormatMessage("MDDMQTT.h: MQTTClient_unsubscribe() failed (%s)\n", strerror(errno));
}
free(mqtt->receiveBuffer);
free(mqtt->receiveChannel);
}
MQTTClient_disconnect(*mqtt->client, 1000*mqtt->disconnectTimeout);
MQTTClient_destroy(mqtt->client);
#if defined(_MSC_VER) || defined(__MINGW32__)
DeleteCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
if (0 != pthread_mutex_destroy(&mqtt->mutex)) {
ModelicaFormatMessage("MDDMQTT.h: pthread_mutex_destroy() failed (%s)\n", strerror(errno));
}
#endif
}
free(mqtt);
}
}
DllExport void MDD_mqttSend(void* p_mqtt, const char* channel, const char* data, int retained, int deliveryTimeout, int dataSize) {
MQTT* mqtt = (MQTT*) p_mqtt;
if (NULL != mqtt) {
int rc;
MQTTClient_deliveryToken token;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
pubmsg.payload = (void*)data;
pubmsg.payloadlen = dataSize;
pubmsg.qos = mqtt->QoS;
pubmsg.retained = retained;
rc = MQTTClient_publishMessage(*mqtt->client, channel, &pubmsg, &token);
if (MQTTCLIENT_SUCCESS == rc) {
if (0 < mqtt->QoS) {
rc = MQTTClient_waitForCompletion(*mqtt->client, token, deliveryTimeout);
}
}
else {
const char* errString = rc != MQTTCLIENT_FAILURE ? MQTTClient_strerror(rc) : NULL;
if (NULL != errString) {
ModelicaFormatError("MDDMQTT.h: MQTTClient_publishMessage failed: %s\n", errString);
}
else {
ModelicaError("MDDMQTT.h: MQTTClient_publishMessage failed\n");
}
}
}
}
DllExport void MDD_mqttSendP(void * p_mqtt, const char* channel, void* p_package, int retained, int deliveryTimeout, int dataSize) {
MDD_mqttSend(p_mqtt, channel, MDD_SerialPackagerGetData(p_package), retained, deliveryTimeout, dataSize);
}
DllExport const char* MDD_mqttRead(void* p_mqtt) {
MQTT* mqtt = (MQTT*) p_mqtt;
if (NULL != mqtt) {
char* mqttBuf;
#if defined(_MSC_VER) || defined(__MINGW32__)
EnterCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_lock(&mqtt->mutex);
#endif
mqttBuf = ModelicaAllocateStringWithErrorReturn(mqtt->bufferSize);
if (mqttBuf) {
memcpy(mqttBuf, mqtt->receiveBuffer, mqtt->nReceivedBytes);
if (mqtt->nReceivedBytes < mqtt->bufferSize) {
/* Which strategy to use if the new data size is less than the old size, e.g., in case of disconnection? */
/* Strategy: Return previous values */
memcpy(mqttBuf + mqtt->nReceivedBytes, mqtt->receiveBuffer + mqtt->nReceivedBytes, mqtt->bufferSize - mqtt->nReceivedBytes);
}
mqtt->nReceivedBytes = 0;
#if defined(_MSC_VER) || defined(__MINGW32__)
LeaveCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_unlock(&mqtt->mutex);
#endif
return (const char*) mqttBuf;
}
else {
#if defined(_MSC_VER) || defined(__MINGW32__)
LeaveCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_unlock(&mqtt->mutex);
#endif
ModelicaError("MDDMQTT.h: ModelicaAllocateString failed\n");
}
}
return "";
}
DllExport void MDD_mqttReadP(void* p_mqtt, void* p_package) {
MQTT* mqtt = (MQTT*) p_mqtt;
if (NULL != mqtt) {
int rc;
#if defined(_MSC_VER) || defined(__MINGW32__)
EnterCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_lock(&mqtt->mutex);
#endif
rc = MDD_SerialPackagerSetDataWithErrorReturn(p_package, mqtt->receiveBuffer, mqtt->nReceivedBytes);
mqtt->nReceivedBytes = 0;
#if defined(_MSC_VER) || defined(__MINGW32__)
LeaveCriticalSection(&mqtt->lock);
#elif defined(__linux__) || defined(__CYGWIN__)
pthread_mutex_unlock(&mqtt->mutex);
#endif
if (rc) {
ModelicaError("MDDMQTT.h: MDD_SerialPackagerSetData failed. Buffer overflow.\n");
}
}
}
DllExport const char* MDD_mqttGetVersionInfo(void * p_mqtt) {
MQTTClient_nameValue* verInfo = MQTTClient_getVersionInfo();
if (NULL != verInfo) {
const char* name = NULL;
const char* ver = NULL;
while (NULL != verInfo->name) {
if (0 == strcmp(verInfo->name, "Product name")) {
name = verInfo->value;
}
else if (0 == strcmp(verInfo->name, "Version")) {
ver = verInfo->value;
}
verInfo++;
}
if (NULL != name && NULL != ver) {
size_t len = strlen(name) + strlen(ver) + 1;
char* buf = ModelicaAllocateString(len + 1);
snprintf(buf, len + 1, "%s %s", name, ver);
buf[len] = '\0';
return (const char*) buf;
}
}
return "";
}
#endif /* !defined(ITI_COMP_SIM) */
#endif /* MDDMQTT_H_ */
| 37.543379 | 140 | 0.583617 | [
"object"
] |
abc837bc2c95b16c083f2cd1cca543c4ca459016 | 1,972 | h | C | closed/Centaur Technology/code/ssd-small/runner/runner.h | ctuning/inference_results_v1.1 | d9176eca28fcf6d7a05ccb97994362a76a1eb5ab | [
"Apache-2.0"
] | 12 | 2021-09-23T08:05:57.000Z | 2022-03-21T03:52:11.000Z | closed/Centaur Technology/code/ssd-small/runner/runner.h | ctuning/inference_results_v1.1 | d9176eca28fcf6d7a05ccb97994362a76a1eb5ab | [
"Apache-2.0"
] | 24 | 2021-07-19T01:09:35.000Z | 2022-03-17T11:44:02.000Z | closed/Centaur Technology/code/ssd-small/runner/runner.h | ctuning/inference_results_v1.1 | d9176eca28fcf6d7a05ccb97994362a76a1eb5ab | [
"Apache-2.0"
] | 16 | 2021-09-23T20:26:38.000Z | 2022-03-09T12:59:56.000Z | #ifndef MLPERF_INFERENCE_RUNNER_RUNNER_H_
#define MLPERF_INFERENCE_RUNNER_RUNNER_H_
#include <stdint.h>
#include <vector>
#include "tensorflow/core/framework/tensor.h"
#include "experimental/mlperf/inference/loadgen/query_sample.h"
#include "experimental/mlperf/inference/runner/loader.h"
#include "experimental/mlperf/inference/runner/options.h"
#include "experimental/mlperf/inference/runner/dataset.h"
#include "experimental/mlperf/inference/runner/queue.h"
namespace mlperf {
using int64 = long long int;
typedef std::vector<QuerySample> QuerySamples;
typedef std::vector<QuerySampleResponse*> QuerySampleResponses;
class Runner {
public:
Runner(const mlperf::Option& option,
bool standalone = false, bool latency_mode = true);
void Enqueue(const QuerySamples& samples);
void StartRun();
void HandleTask(int thread_id);
void UpdateQSL(const tensorflow::Tensor& qsl,
std::unordered_map<QuerySampleIndex, QuerySampleIndex> sample_id_to_qsl_index_map);
void UpdateQslIndexMap(
std::unordered_map<QuerySampleIndex, QuerySampleIndex> sample_id_to_qsl_index_map);
void WarmUp();
void Finish();
~Runner() {
Finish();
for (int i = 0; i < num_threads_; i++) {
delete[] responses_[i];
}
}
private:
const mlperf::BatchingOption batching_option_;
const int num_threads_;
const std::string export_model_path_;
const bool standalone_;
int num_aics_;
mlperf::Option option_;
Queue<QuerySamples> queue_;
std::vector<std::thread> workers_;
QuerySampleResponses responses_;
std::vector<std::unique_ptr<mlperf::Loader>> loader_;
std::vector<std::string> aic_target_;
std::vector<tensorflow::Tensor> inputs_;
std::vector<tensorflow::Tensor> inputs_max_batch_size_;
std::vector<std::vector<tensorflow::Tensor>> outputs_;
std::unordered_map<QuerySampleIndex, QuerySampleIndex> sample_id_to_qsl_index_map_;
};
} // namespace mlperf
#endif // MLPERF_INFERENCE_RUNNER_RUNNER_H_
| 30.8125 | 100 | 0.760142 | [
"vector"
] |
abc906197b31194d6f0853d6869564161b38361b | 2,323 | h | C | DPSDParametricModel/Axis.h | agalex1974/ProToolkitLExtrusion | 08948465970597d301544e27ae33bdca386528bb | [
"MIT"
] | 2 | 2021-04-02T16:16:04.000Z | 2021-06-16T19:42:14.000Z | DPSDParametricModel/Axis.h | LR-LULU/ProToolkitLExtrusion | 08948465970597d301544e27ae33bdca386528bb | [
"MIT"
] | null | null | null | DPSDParametricModel/Axis.h | LR-LULU/ProToolkitLExtrusion | 08948465970597d301544e27ae33bdca386528bb | [
"MIT"
] | 2 | 2022-02-22T15:25:53.000Z | 2022-03-04T06:24:21.000Z | // Developed by Alexander G. Agathos
// e-mail: alexander.agathos@gmail.com
// MIT license, see the license file in the Git repository.
#ifndef AXIS_H
#define AXIS_H
#include <ProElemId.h>
#include <ProFeatType.h>
#include <ProFeatForm.h>
#include <ProExtrude.h>
#include <ProStdSection.h>
#include <ProSection.h>
#include <ProDtmPln.h>
#include "HelperStructures.h"
class Axis
{
protected:
// Axis feature three used to define the axis.
// In this case the axis will be defined by the intersection of two planes
ElemTreeData axis_tree[9] = {
/* 0 */ {0, PRO_E_FEATURE_TREE, {(ProValueDataType)-1}},
/* 1 */ {1, PRO_E_FEATURE_TYPE, {PRO_VALUE_TYPE_INT, PRO_FEAT_DATUM_AXIS}},
/* 2 */ {1, PRO_E_DTMAXIS_CONSTRAINTS, {(ProValueDataType)-1}},
/* 3 */ {2, PRO_E_DTMAXIS_CONSTRAINT, {(ProValueDataType)-1}},
/* 4 */ {3, PRO_E_DTMAXIS_CONSTR_TYPE, {PRO_VALUE_TYPE_INT, 1}},
/* 5 */ {3, PRO_E_DTMAXIS_CONSTR_REF, {PRO_VALUE_TYPE_SELECTION}},
/* 6 */ {2, PRO_E_DTMAXIS_CONSTRAINT, {(ProValueDataType)-1}},
/* 7 */ {3, PRO_E_DTMAXIS_CONSTR_TYPE, {PRO_VALUE_TYPE_INT, 1}},
/* 8 */ {3, PRO_E_DTMAXIS_CONSTR_REF, {PRO_VALUE_TYPE_SELECTION}}
};
int axis_id; /**< This is the axis id, throughout the example it should not change even
when it is redefined by the dialog */
/**
* Set the axis intersecting planes
*
* @param model The input part session of the creo parametric environment
* @param planeIdFirst The first intersecting plane id
* @param planeIdSecond The second intersecting plane id
*/
void setInstsectionPlanes(ProMdl model, int planeIdFirst, int planeIdSecond);
/**
* Create the axis after the two intersecting planes has been provided
*
* @param model The input part session of the creo parametric environment
* @param name The name that the axis will have in creo.
* @return a status value
*/
int createAxis(ProMdl model, const char* name);
public:
/**
* Constructor of the axis class
*
* @param model The input part session of the creo parametric environment
* @param planeIdFirst The first intersecting plane id
* @param planeIdSecond The second intersecting plane id
*/
Axis(ProMdl model, int planeIdFirst, int planeIdSecond, const char* name);
/**
* Get axis id.
*
* @return The axis id
*/
int getAxisid();
};
#endif | 30.565789 | 88 | 0.713302 | [
"model"
] |
abca239ea58d324d35e4ecde74bc4a061f9d5c12 | 2,239 | h | C | ConfProfile/jni/strongswan/src/frontends/android/jni/libandroidbridge/kernel/network_manager.h | Infoss/conf-profile-4-android | 619bd63095bb0f5a67616436d5510d24a233a339 | [
"MIT"
] | null | null | null | ConfProfile/jni/strongswan/src/frontends/android/jni/libandroidbridge/kernel/network_manager.h | Infoss/conf-profile-4-android | 619bd63095bb0f5a67616436d5510d24a233a339 | [
"MIT"
] | 5 | 2016-01-25T18:04:42.000Z | 2016-02-25T08:54:56.000Z | ConfProfile/jni/strongswan/src/frontends/android/jni/libandroidbridge/kernel/network_manager.h | Infoss/conf-profile-4-android | 619bd63095bb0f5a67616436d5510d24a233a339 | [
"MIT"
] | 2 | 2016-01-25T17:14:17.000Z | 2016-02-13T20:14:09.000Z | /*
* Copyright (C) 2012-2013 Tobias Brunner
* Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
/**
* @defgroup network_manager network_manager
* @{ @ingroup android_kernel
*/
#ifndef NETWORK_MANAGER_H_
#define NETWORK_MANAGER_H_
#include <jni.h>
#include <library.h>
#include <networking/host.h>
typedef struct network_manager_t network_manager_t;
/**
* Callback called if connectivity changes somehow.
*
* Implementation should be quick as the call is made by the Java apps main
* thread.
*
* @param data data supplied during registration
* @param disconnected TRUE if currently disconnected
*/
typedef void (*connectivity_cb_t)(void *data, bool disconnected);
/**
* NetworkManager, used to listen for network changes.
*
* Communicates with NetworkManager via JNI
*/
struct network_manager_t {
/**
* Register a callback that is called if connectivity changes
*
* @note Only the first registered callback is currently used
*
* @param cb callback to register
* @param data data provided to callback
*/
void (*add_connectivity_cb)(network_manager_t *this, connectivity_cb_t cb,
void *data);
/**
* Unregister a previously registered callback for connectivity changes
*
* @param cb previously registered callback
*/
void (*remove_connectivity_cb)(network_manager_t *this,
connectivity_cb_t cb);
/**
* Destroy a network_manager_t instance
*/
void (*destroy)(network_manager_t *this);
};
/**
* Create a network_manager_t instance
*
* @param context Context object
* @return network_manager_t instance
*/
network_manager_t *network_manager_create(jobject context);
#endif /** NETWORK_MANAGER_H_ @}*/
| 26.975904 | 77 | 0.731577 | [
"object"
] |
abe42ebdad0f7faa7f8852691cca1fcad163c01a | 1,110 | h | C | include/submesh.h | jjimenezg93/u-gine3d | 5232dd5e911414a8840b8bfcb4eb7f6952d4c4b8 | [
"MIT"
] | null | null | null | include/submesh.h | jjimenezg93/u-gine3d | 5232dd5e911414a8840b8bfcb4eb7f6952d4c4b8 | [
"MIT"
] | null | null | null | include/submesh.h | jjimenezg93/u-gine3d | 5232dd5e911414a8840b8bfcb4eb7f6952d4c4b8 | [
"MIT"
] | null | null | null | #ifndef UGINE_SUBMESH_H
#define UGINE_SUBMESH_H
#include "array.h"
#include "smartptr.h"
#include "texture.h"
#include "vertex.h"
class Submesh {
public:
static Ptr<Submesh> Create(Ptr<Texture> tex = nullptr);
void AddVertex(const Vertex& v);
void AddTriangle(uint32 v0, uint32 v1, uint32 v2);
Ptr<Texture> GetTexture() const { return mTexture; }
void SetTexture(Ptr<Texture> tex) { mTexture = tex; }
const Array<Vertex>& GetVertices() const { return mVertices; }
Array<Vertex>& GetVertices() { return mVertices; }
const glm::vec3& GetColor() const { return mDiffuse; }
void SetColor(const glm::vec3& color) { mDiffuse = color; }
uint8 GetShininess() const { return mShininess; }
void SetShininess(uint8 shininess) { mShininess = shininess; }
void Rebuild();
void Render();
protected:
Submesh(Ptr<Texture> tex);
~Submesh();
private:
Ptr<Texture> mTexture;
uint32 mVertexBuffer;
uint32 mIndexBuffer;
Array<Vertex> mVertices;
Array<uint16> mIndices;
glm::vec3 mDiffuse;
uint8 mShininess;
friend class Ptr<Submesh>;
friend class Ptr<const Submesh>;
};
#endif // UGINE_SUBMESH_H
| 23.125 | 63 | 0.727928 | [
"render"
] |
abe72c82960a2cd1089db3f7edac2b247a9df83e | 856 | h | C | profiling/sol_memory/mailparser.h | allstarschh/training-handout | 86b16316e99ed5c1c7bc8dbb0a77dcf49c7e0a57 | [
"BSD-3-Clause-Clear"
] | null | null | null | profiling/sol_memory/mailparser.h | allstarschh/training-handout | 86b16316e99ed5c1c7bc8dbb0a77dcf49c7e0a57 | [
"BSD-3-Clause-Clear"
] | null | null | null | profiling/sol_memory/mailparser.h | allstarschh/training-handout | 86b16316e99ed5c1c7bc8dbb0a77dcf49c7e0a57 | [
"BSD-3-Clause-Clear"
] | null | null | null | /*************************************************************************
*
* Copyright (c) 2016-2019, Klaralvdalens Datakonsult AB (KDAB)
* All rights reserved.
*
* See the LICENSE.txt file shipped along with this file for the license.
*
*************************************************************************/
#ifndef MAILPARSER_H
#define MAILPARSER_H
#include <memory>
#include <string>
#include <vector>
struct Mail
{
std::shared_ptr<std::string> from;
std::string dateTime;
std::shared_ptr<std::string> subject;
std::vector<std::pair<std::string, unsigned>> wordCount;
bool isValid() const
{
return from && subject && !dateTime.empty();
}
};
typedef std::vector<Mail> MailList;
class MailParser
{
public:
MailParser();
MailList parse(const std::string &filePath);
};
#endif // MAILPARSER_H
| 21.4 | 75 | 0.558411 | [
"vector"
] |
8626ff5c6d696562a71c859ab0c5b34d7bd52965 | 7,049 | h | C | tools/oxsmconv/src/OBJ.h | corvance/oxide-nds | e60d26206af81da6617b8f8d5fe9769440d1b3cc | [
"MIT"
] | 1 | 2022-02-26T18:40:20.000Z | 2022-02-26T18:40:20.000Z | tools/oxsmconv/src/OBJ.h | corvance/oxide-nds | e60d26206af81da6617b8f8d5fe9769440d1b3cc | [
"MIT"
] | 1 | 2022-02-26T12:11:45.000Z | 2022-02-26T12:11:45.000Z | tools/oxsmconv/src/OBJ.h | corvance/oxide-nds | e60d26206af81da6617b8f8d5fe9769440d1b3cc | [
"MIT"
] | null | null | null | // ┌────────────────────────────────────────────────────────────────────────────┐
// | |
// | ██████╗ ██╗ ██╗██╗██████╗ ███████╗███╗ ██╗██████╗ ███████╗ |
// | ██╔═══██╗╚██╗██╔╝██║██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔════╝ |
// | ██║ ██║ ╚███╔╝ ██║██║ ██║█████╗ ██╔██╗ ██║██║ ██║███████╗ |
// | ██║ ██║ ██╔██╗ ██║██║ ██║██╔══╝ ██║╚██╗██║██║ ██║╚════██║ |
// | ╚██████╔╝██╔╝ ██╗██║██████╔╝███████╗██║ ╚████║██████╔╝███████║ |
// | ╚═════╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚══════╝╚═╝ ╚═══╝╚═════╝ ╚══════╝ |
// | |
// | OxideNDS - A 2D + 3D Game/Application Engine for the Nintendo DS (NTR), |
// | built on devkitARM and libnds. |
// | |
// | Copyright (C) 2022 - 2022 Conaer Macpherson a.k.a Corvance |
// | OxideNDS is licensed under the terms of the MIT License. |
// | |
// | If you discover any bugs, issues or room for improvement, open an issue. |
// | |
// | https://www.github.com/corvance/oxide-nds |
// | |
// └────────────────────────────────────────────────────────────────────────────┘
/**
* @file OBJ.h
* @author Corvance
* @brief Wavefront OBJ -> OXSM Conversion
* @version 0.1
* @date 2022-02-24
*/
#pragma once
#include <fstream>
#include <string>
#include <oxtool_log.h>
#include <oxtool_stringutils.h>
#define floattot16(n) ((int16_t)((n) * (1 << 4)))
#define floattov16(n) ((int16_t)((n) * (1 << 12)))
#define floattov10(n) ((n > 0.998) ? 0x1FF : ((short int)((n)*(1<<9))))
class OBJConv
{
public:
static bool convert(const std::string& inPath, const std::string& outPath)
{
// Open input OBJ as text file.
std::ifstream objIn(inPath);
std::vector<std::vector<int16_t>> vertices = {};
std::vector<std::vector<int16_t>> t_vertices = {};
std::vector<std::vector<int16_t>> n_vertices = {};
std::vector<std::vector<uint32_t>> indices = {};
if (objIn.is_open())
{
for (std::string str; std::getline(objIn, str);)
{
std::string elem_type = StringUtils::splitString(str, ' ')[0];
std::vector<std::string> vals = StringUtils::splitString(str, ' ');
vals.erase(vals.begin()); // Remove elem type to leave only the vals.
// Mesh vertex.
if (elem_type == "v")
{
// Vertex must have 3 coordinates
if (vals.size() != 3)
{
log_err("Vertex has %i coordinates, should have 3.\n", vals.size());
return false;
}
vertices.push_back({0, 0, 0});
for (int v = 0; v < 3; v++)
vertices[vertices.size() - 1][v] = floattov16(std::stof(vals[v]));
}
// Texture vertex.
else if (elem_type == "vt")
{
// Texture vertex must have 2 coordinates.
if (vals.size() != 2)
{
log_err("Mesh vertex has %i coordinates, should have 2.\n", vals.size());
return false;
}
t_vertices.push_back({0, 0});
for (int vt = 0; vt < 2; vt++)
t_vertices[t_vertices.size() - 1][vt] = floattot16(std::stof(vals[vt]));
}
// Normal vertex.
else if (elem_type == "vn")
{
// Vertex must have 3 coordinates
if (vals.size() != 3)
{
log_err("Normal vertex has %i coordinates, should have 3.\n", vals.size());
return false;
}
n_vertices.push_back({0, 0, 0});
for (int vn = 0; vn < 3; vn++)
n_vertices[n_vertices.size() - 1][vn] = floattov10(std::stof(vals[vn]));
}
// Index triangle.
else if (elem_type == "f")
{
// Index must have 3 elements.
if (vals.size() != 3)
{
log_err("Index has %i vertices, should have 3.\n", vals.size());
return false;
}
std::vector<std::string> vertex_vals;
for (int i = 0; i < 3; i++)
{
vertex_vals = StringUtils::splitString(vals[i], '/');
// Triangle vertex must have 3 elements, v/vt/vn.
if (vertex_vals.size() != 3)
{
log_err("Index triangle vertex has %i elements, should have 3.\n", vals.size());
return false;
}
indices.push_back({(uint32_t)std::stoi(vertex_vals[0]) - 1, (uint32_t)std::stoi(vertex_vals[1]) - 1, (uint32_t)std::stoi(vertex_vals[2]) - 1});
}
}
}
uint32_t header[4] = {(uint32_t)vertices.size(), (uint32_t)t_vertices.size(), (uint32_t)n_vertices.size(), (uint32_t)indices.size()};
// Write to binary .oxsm format.
std::ofstream out(outPath, std::ios::out | std::ios::binary);
out.write((char*)header, sizeof(header));
for (auto vertex: vertices)
{
for (int16_t elem: vertex)
out.write((char*)&elem, sizeof(elem));
}
for (auto t_vertex: t_vertices)
{
for (int16_t elem: t_vertex)
out.write((char*)&elem, sizeof(elem));
}
for (auto n_vertex: n_vertices)
{
for (int16_t elem: n_vertex)
out.write((char*)&elem, sizeof(elem));
}
for (auto index: indices)
{
for (uint32_t elem: index)
out.write((char*)&elem, sizeof(elem));
}
out.flush();
out.close();
}
else
{
// File doesn't exist, incorrect access rights, already in use, etc.
log_err("Cannot open file %s\n", inPath.c_str());
return false;
}
// Conversion succeeded.
return true;
}
}; | 41.464706 | 167 | 0.371258 | [
"mesh",
"vector",
"3d"
] |
862bb7d61fb09d23cc5dac76cc370ddd7f2a215a | 37,154 | c | C | usr/src/cmd/sgs/rtld/common/setup.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/sgs/rtld/common/setup.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/sgs/rtld/common/setup.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Copyright (c) 1988 AT&T
* All Rights Reserved
*/
/*
* Copyright (c) 2012, Joyent, Inc. All rights reserved.
*/
/*
* Run time linker common setup.
*
* Called from _setup to get the process going at startup.
*/
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
#include <sys/sysconfig.h>
#include <sys/auxv.h>
#include <debug.h>
#include <conv.h>
#include "_rtld.h"
#include "_audit.h"
#include "_elf.h"
#include "_a.out.h"
#include "msg.h"
extern int _end, _edata, _etext;
extern void _init(void);
extern int _brk_unlocked(void *);
#ifndef SGS_PRE_UNIFIED_PROCESS
/* needed for _brk_unlocked() */
void *_nd = &_end;
#endif
/*
* Counters that are incremented every time an object is mapped/unmapped.
*
* Note that exec() will usually map 2 objects before we receive control,
* but this can be 1 if ld.so.1 is executed directly. We count one of these
* here, and add another as necessary in setup().
*/
u_longlong_t cnt_map = 1;
u_longlong_t cnt_unmap = 0;
/*
* Define for the executable's interpreter.
* Usually it is ld.so.1, but for the first release of ICL binaries
* it is libc.so.1. We keep this information so that we don't end
* up mapping libc twice if it is the interpreter.
*/
static Interp _interp;
/*
* LD_PRELOAD objects.
*/
static int
preload(const char *str, Rt_map *mlmp, Rt_map **clmp)
{
Alist *palp = NULL;
char *objs, *ptr, *next;
Word lmflags = lml_main.lm_flags;
int lddstub;
DBG_CALL(Dbg_util_nl(&lml_main, DBG_NL_STD));
if ((objs = strdup(str)) == NULL)
return (0);
/*
* Determine if we've been called from lddstub.
*/
lddstub = (lmflags & LML_FLG_TRC_ENABLE) &&
(FLAGS1(*clmp) & FL1_RT_LDDSTUB);
for (ptr = strtok_r(objs, MSG_ORIG(MSG_STR_DELIMIT), &next);
ptr != NULL;
ptr = strtok_r(NULL, MSG_ORIG(MSG_STR_DELIMIT), &next)) {
Rt_map *nlmp = NULL;
uint_t flags;
DBG_CALL(Dbg_file_preload(&lml_main, ptr));
/*
* Establish the flags for loading each object. If we're
* called via lddstub, then the first preloaded object is the
* object being inspected by ldd(1). This object should not be
* marked as an interposer, as this object is intended to act
* as the target object of the process.
*/
if (lddstub)
flags = FLG_RT_PRELOAD;
else
flags = (FLG_RT_PRELOAD | FLG_RT_OBJINTPO);
/*
* If this a secure application, then preload errors are
* reduced to warnings, as the errors are non-fatal.
*/
if (rtld_flags & RT_FL_SECURE)
rtld_flags2 |= RT_FL2_FTL2WARN;
if (expand_paths(*clmp, ptr, &palp, AL_CNT_NEEDED,
PD_FLG_EXTLOAD, 0) != 0)
nlmp = load_one(&lml_main, ALIST_OFF_DATA, palp, *clmp,
MODE(mlmp), flags, 0, NULL);
remove_alist(&palp, 0);
if (rtld_flags & RT_FL_SECURE)
rtld_flags2 &= ~RT_FL2_FTL2WARN;
if (nlmp && (bind_one(*clmp, nlmp, BND_NEEDED) == 0))
nlmp = NULL;
if (lddstub && nlmp) {
lddstub = 0;
/*
* Fabricate a binding between the target shared object
* and lddstub so that the target object isn't called
* out from unused() processing.
*/
if (lmflags &
(LML_FLG_TRC_UNREF | LML_FLG_TRC_UNUSED)) {
if (bind_one(*clmp, nlmp, BND_REFER) == 0)
nlmp = NULL;
}
/*
* By identifying lddstub as the caller, several
* confusing ldd() diagnostics get suppressed. These
* diagnostics would reveal how the target shared object
* was found from lddstub. Now that the real target is
* loaded, identify the target as the caller so that all
* ldd() diagnostics are enabled for subsequent objects.
*/
if (nlmp)
*clmp = nlmp;
}
/*
* If no error occurred with loading this object, indicate that
* this link-map list contains an interposer.
*/
if (nlmp == NULL) {
if ((lmflags & LML_FLG_TRC_ENABLE) ||
(rtld_flags & RT_FL_SECURE))
continue;
else
return (0);
}
if (flags & FLG_RT_OBJINTPO)
lml_main.lm_flags |= LML_FLG_INTRPOSE;
}
free(palp);
free(objs);
return (1);
}
Rt_map *
setup(char **envp, auxv_t *auxv, Word _flags, char *_platform, int _syspagsz,
char *_rtldname, ulong_t ld_base, ulong_t interp_base, int fd, Phdr *phdr,
char *execname, char **argv, uid_t uid, uid_t euid, gid_t gid, gid_t egid,
void *aoutdyn, int auxflags, uint_t *hwcap)
{
Rt_map *rlmp, *mlmp, *clmp, **tobj = NULL;
Ehdr *ehdr;
rtld_stat_t status;
int features = 0, ldsoexec = 0;
size_t eaddr, esize;
char *str, *argvname;
Word lmflags;
mmapobj_result_t *mpp;
Fdesc fdr = { 0 }, fdm = { 0 };
Rej_desc rej = { 0 };
APlist *ealp = NULL;
/*
* Now that ld.so has relocated itself, initialize our own 'environ' so
* as to establish an address suitable for any libc requirements.
*/
_environ = (char **)((ulong_t)auxv - sizeof (char *));
_init();
_environ = envp;
/*
* Establish a base time. Total time diagnostics start from entering
* ld.so.1 here, however the base time is reset each time the ld.so.1
* is re-entered. Note also, there will be a large time associated
* with the first diagnostic from ld.so.1, as bootstrapping ld.so.1
* and establishing the liblddbg infrastructure takes some time.
*/
(void) gettimeofday(&DBG_TOTALTIME, NULL);
DBG_DELTATIME = DBG_TOTALTIME;
/*
* Determine how ld.so.1 has been executed.
*/
if ((fd == -1) && (phdr == NULL)) {
/*
* If we received neither the AT_EXECFD nor the AT_PHDR aux
* vector, ld.so.1 must have been invoked directly from the
* command line.
*/
ldsoexec = 1;
/*
* AT_SUN_EXECNAME provides the most precise name, if it is
* available, otherwise fall back to argv[0]. At this time,
* there is no process name.
*/
if (execname)
rtldname = execname;
else if (argv[0])
rtldname = argv[0];
else
rtldname = (char *)MSG_INTL(MSG_STR_UNKNOWN);
} else {
/*
* Otherwise, we have a standard process. AT_SUN_EXECNAME
* provides the most precise name, if it is available,
* otherwise fall back to argv[0]. Provided the application
* is already mapped, the process is the application, so
* simplify the application name for use in any diagnostics.
*/
if (execname)
argvname = execname;
else if (argv[0])
argvname = execname = argv[0];
else
argvname = execname = (char *)MSG_INTL(MSG_STR_UNKNOWN);
if (fd == -1) {
if ((str = strrchr(argvname, '/')) != NULL)
procname = ++str;
else
procname = argvname;
}
/*
* At this point, we don't know the runtime linkers full path
* name. The _rtldname passed to us is the SONAME of the
* runtime linker, which is typically /lib/ld.so.1 no matter
* what the full path is. Use this for now, we'll reset the
* runtime linkers name once the application is analyzed.
*/
if (_rtldname) {
if ((str = strrchr(_rtldname, '/')) != NULL)
rtldname = ++str;
else
rtldname = _rtldname;
} else
rtldname = (char *)MSG_INTL(MSG_STR_UNKNOWN);
/* exec() brought in two objects for us. Count the second one */
cnt_map++;
}
/*
* Initialize any global variables.
*/
at_flags = _flags;
if ((org_scapset->sc_plat = _platform) != NULL)
org_scapset->sc_platsz = strlen(_platform);
if (org_scapset->sc_plat == NULL)
platform_name(org_scapset);
if (org_scapset->sc_mach == NULL)
machine_name(org_scapset);
/*
* If pagesize is unspecified find its value.
*/
if ((syspagsz = _syspagsz) == 0)
syspagsz = _sysconfig(_CONFIG_PAGESIZE);
/*
* Add the unused portion of the last data page to the free space list.
* The page size must be set before doing this. Here, _end refers to
* the end of the runtime linkers bss. Note that we do not use the
* unused data pages from any included .so's to supplement this free
* space as badly behaved .os's may corrupt this data space, and in so
* doing ruin our data.
*/
eaddr = S_DROUND((size_t)&_end);
esize = eaddr % syspagsz;
if (esize) {
esize = syspagsz - esize;
addfree((void *)eaddr, esize);
}
/*
* Establish initial link-map list flags, and link-map list alists.
*/
if (alist_append(&lml_main.lm_lists, NULL, sizeof (Lm_cntl),
AL_CNT_LMLISTS) == NULL)
return (0);
lml_main.lm_flags |= LML_FLG_BASELM;
lml_main.lm_lmid = LM_ID_BASE;
lml_main.lm_lmidstr = (char *)MSG_ORIG(MSG_LMID_BASE);
if (alist_append(&lml_rtld.lm_lists, NULL, sizeof (Lm_cntl),
AL_CNT_LMLISTS) == NULL)
return (0);
lml_rtld.lm_flags |= (LML_FLG_RTLDLM | LML_FLG_HOLDLOCK);
lml_rtld.lm_tflags |= LML_TFLG_NOAUDIT;
lml_rtld.lm_lmid = LM_ID_LDSO;
lml_rtld.lm_lmidstr = (char *)MSG_ORIG(MSG_LMID_LDSO);
/*
* Determine whether we have a secure executable.
*/
security(uid, euid, gid, egid, auxflags);
/*
* Make an initial pass of environment variables to pick off those
* related to locale processing. At the same time, collect and save
* any LD_XXXX variables for later processing. Note that this later
* processing will be skipped if ld.so.1 is invoked from the command
* line with -e LD_NOENVIRON.
*/
if (envp && (readenv_user((const char **)envp, &ealp) == 1))
return (0);
/*
* If ld.so.1 has been invoked directly, process its arguments.
*/
if (ldsoexec) {
/*
* Process any arguments that are specific to ld.so.1, and
* reorganize the process stack to effectively remove ld.so.1
* from the stack. Reinitialize the environment pointer, as
* this pointer may have been shifted after skipping ld.so.1's
* arguments.
*/
if (rtld_getopt(argv, &envp, &auxv, &(lml_main.lm_flags),
&(lml_main.lm_tflags), (aoutdyn != 0)) == 1) {
eprintf(&lml_main, ERR_NONE, MSG_INTL(MSG_USG_BADOPT));
return (0);
}
_environ = envp;
/*
* Open the object that ld.so.1 is to execute.
*/
argvname = execname = argv[0];
if ((fd = open(argvname, O_RDONLY)) == -1) {
int err = errno;
eprintf(&lml_main, ERR_FATAL, MSG_INTL(MSG_SYS_OPEN),
argvname, strerror(err));
return (0);
}
}
/*
* Having processed any ld.so.1 command line options, return to process
* any LD_XXXX environment variables.
*/
if (ealp) {
if (((rtld_flags & RT_FL_NOENVIRON) == 0) &&
(procenv_user(ealp, &(lml_main.lm_flags),
&(lml_main.lm_tflags), (aoutdyn != 0)) == 1))
return (0);
free(ealp);
}
/*
* Initialize a hardware capability descriptor for use in comparing
* each loaded object. The aux vector must provide AF_SUN_HWCAPVERIFY,
* as prior to this setting any hardware capabilities that were found
* could not be relied upon.
*/
if (auxflags & AF_SUN_HWCAPVERIFY) {
rtld_flags2 |= RT_FL2_HWCAP;
org_scapset->sc_hw_1 = (Xword)hwcap[0];
org_scapset->sc_hw_2 = (Xword)hwcap[1];
}
/*
* Create a mapping descriptor for ld.so.1. We can determine our
* two segments information from known symbols.
*/
if ((mpp = calloc(2, sizeof (mmapobj_result_t))) == NULL)
return (0);
mpp[0].mr_addr = (caddr_t)M_PTRUNC(ld_base);
mpp[0].mr_msize = (caddr_t)&_etext - mpp[0].mr_addr;
mpp[0].mr_fsize = mpp[0].mr_msize;
mpp[0].mr_prot = (PROT_READ | PROT_EXEC);
mpp[1].mr_addr = (caddr_t)M_PTRUNC((uintptr_t)&r_debug);
mpp[1].mr_msize = (caddr_t)&_end - mpp[1].mr_addr;
mpp[1].mr_fsize = (caddr_t)&_edata - mpp[1].mr_addr;
mpp[1].mr_prot = (PROT_READ | PROT_WRITE | PROT_EXEC);
if ((fdr.fd_nname = stravl_insert(_rtldname, 0, 0, 0)) == NULL)
return (0);
if ((rlmp = elf_new_lmp(&lml_rtld, ALIST_OFF_DATA, &fdr,
(Addr)mpp->mr_addr, (size_t)((uintptr_t)eaddr - (uintptr_t)ld_base),
NULL, NULL, NULL)) == NULL)
return (0);
MMAPS(rlmp) = mpp;
MMAPCNT(rlmp) = 2;
PADSTART(rlmp) = (ulong_t)mpp[0].mr_addr;
PADIMLEN(rlmp) = (ulong_t)mpp[0].mr_addr + (ulong_t)mpp[1].mr_addr +
(ulong_t)mpp[1].mr_msize;
MODE(rlmp) |= (RTLD_LAZY | RTLD_NODELETE | RTLD_GLOBAL | RTLD_WORLD);
FLAGS(rlmp) |= (FLG_RT_ANALYZED | FLG_RT_RELOCED | FLG_RT_INITDONE |
FLG_RT_INITCLCT | FLG_RT_FINICLCT | FLG_RT_MODESET);
/*
* Initialize the runtime linkers information.
*/
interp = &_interp;
interp->i_name = (char *)rtldname;
interp->i_faddr = (caddr_t)ADDR(rlmp);
ldso_plt_init(rlmp);
/*
* Map in the file, if exec has not already done so, or if the file
* was passed as an argument to an explicit execution of ld.so.1 from
* the command line.
*/
if (fd != -1) {
/*
* Map the file. Once the object is mapped we no longer need
* the file descriptor.
*/
(void) rtld_fstat(fd, &status);
fdm.fd_oname = argvname;
fdm.fd_ftp = map_obj(&lml_main, &fdm, status.st_size, argvname,
fd, &rej);
(void) close(fd);
if (fdm.fd_ftp == NULL) {
Conv_reject_desc_buf_t rej_buf;
eprintf(&lml_main, ERR_FATAL,
MSG_INTL(err_reject[rej.rej_type]), argvname,
conv_reject_desc(&rej, &rej_buf, M_MACH));
return (0);
}
/*
* Finish processing the loading of the file.
*/
if ((fdm.fd_nname = stravl_insert(argvname, 0, 0, 0)) == NULL)
return (0);
fdm.fd_dev = status.st_dev;
fdm.fd_ino = status.st_ino;
if ((mlmp = load_file(&lml_main, ALIST_OFF_DATA, NULL, &fdm,
NULL)) == NULL)
return (0);
/*
* We now have a process name for error diagnostics.
*/
if ((str = strrchr(argvname, '/')) != NULL)
procname = ++str;
else
procname = argvname;
if (ldsoexec) {
mmapobj_result_t *mpp = MMAPS(mlmp);
uint_t mnum, mapnum = MMAPCNT(mlmp);
void *brkbase = NULL;
/*
* Since ld.so.1 was the primary executed object - the
* brk() base has not yet been initialized, we need to
* initialize it. For an executable, initialize it to
* the end of the object. For a shared object (ET_DYN)
* initialize it to the first page in memory.
*/
for (mnum = 0; mnum < mapnum; mnum++, mpp++)
brkbase = mpp->mr_addr + mpp->mr_msize;
if (brkbase == NULL)
brkbase = (void *)syspagsz;
if (_brk_unlocked(brkbase) == -1) {
int err = errno;
eprintf(&lml_main, ERR_FATAL,
MSG_INTL(MSG_SYS_BRK), argvname,
strerror(err));
return (0);
}
}
} else {
/*
* Set up function ptr and arguments according to the type
* of file class the executable is. (Currently only supported
* types are ELF and a.out format.) Then create a link map
* for the executable.
*/
if (aoutdyn) {
#ifdef A_OUT
mmapobj_result_t *mpp;
/*
* Create a mapping structure sufficient to describe
* a single two segments. The ADDR() of the a.out is
* established as 0, which is required but the AOUT
* relocation code.
*/
if ((mpp =
calloc(sizeof (mmapobj_result_t), 2)) == NULL)
return (0);
if ((fdm.fd_nname =
stravl_insert(execname, 0, 0, 0)) == NULL)
return (0);
if ((mlmp = aout_new_lmp(&lml_main, ALIST_OFF_DATA,
&fdm, 0, 0, aoutdyn, NULL, NULL)) == NULL)
return (0);
/*
* Establish the true mapping information for the a.out.
*/
if (aout_get_mmap(&lml_main, mpp)) {
free(mpp);
return (0);
}
MSIZE(mlmp) =
(size_t)(mpp[1].mr_addr + mpp[1].mr_msize) -
S_ALIGN((size_t)mpp[0].mr_addr, syspagsz);
MMAPS(mlmp) = mpp;
MMAPCNT(mlmp) = 2;
PADSTART(mlmp) = (ulong_t)mpp->mr_addr;
PADIMLEN(mlmp) = mpp->mr_msize;
/*
* Disable any object configuration cache (BCP apps
* bring in sbcp which can benefit from any object
* cache, but both the app and sbcp can't use the same
* objects).
*/
rtld_flags |= RT_FL_NOOBJALT;
/*
* Make sure no-direct bindings are in effect.
*/
lml_main.lm_tflags |= LML_TFLG_NODIRECT;
#else
eprintf(&lml_main, ERR_FATAL,
MSG_INTL(MSG_ERR_REJ_UNKFILE), argvname);
return (0);
#endif
} else if (phdr) {
Phdr *pptr;
Off i_offset = 0;
Addr base = 0;
ulong_t phsize;
mmapobj_result_t *mpp, *fmpp, *hmpp = NULL;
uint_t mapnum = 0;
int i;
size_t msize;
/*
* Using the executables phdr address determine the base
* address of the input file. NOTE, this assumes the
* program headers and elf header are part of the same
* mapped segment. Although this has held for many
* years now, it might be more flexible if the kernel
* gave use the ELF headers start address, rather than
* the Program headers.
*
* Determine from the ELF header if we're been called
* from a shared object or dynamic executable. If the
* latter, then any addresses within the object are used
* as is. Addresses within shared objects must be added
* to the process's base address.
*/
ehdr = (Ehdr *)((Addr)phdr - phdr->p_offset);
phsize = ehdr->e_phentsize;
if (ehdr->e_type == ET_DYN)
base = (Addr)ehdr;
/*
* Allocate a mapping array to retain mapped segment
* information.
*/
if ((fmpp = mpp = calloc(ehdr->e_phnum,
sizeof (mmapobj_result_t))) == NULL)
return (0);
/*
* Extract the needed information from the segment
* headers.
*/
for (i = 0, pptr = phdr; i < ehdr->e_phnum; i++) {
if (pptr->p_type == PT_INTERP) {
i_offset = pptr->p_offset;
interp->i_faddr =
(caddr_t)interp_base;
}
if ((pptr->p_type == PT_LOAD) &&
(pptr->p_filesz || pptr->p_memsz)) {
int perm = (PROT_READ | PROT_EXEC);
size_t off;
if (i_offset && pptr->p_filesz &&
(i_offset >= pptr->p_offset) &&
(i_offset <=
(pptr->p_memsz + pptr->p_offset))) {
interp->i_name = (char *)
pptr->p_vaddr + i_offset -
pptr->p_offset + base;
i_offset = 0;
}
if (pptr->p_flags & PF_W)
perm |= PROT_WRITE;
/*
* Retain segments mapping info. Round
* each segment to a page boundary, as
* this insures addresses are suitable
* for mprotect() if required.
*/
off = pptr->p_vaddr + base;
if (hmpp == NULL) {
hmpp = mpp;
mpp->mr_addr = (caddr_t)ehdr;
} else
mpp->mr_addr = (caddr_t)off;
off -= (size_t)(uintptr_t)mpp->mr_addr;
mpp->mr_msize = pptr->p_memsz + off;
mpp->mr_fsize = pptr->p_filesz + off;
mpp->mr_prot = perm;
mpp++, mapnum++;
}
pptr = (Phdr *)((ulong_t)pptr + phsize);
}
mpp--;
msize = (size_t)(mpp->mr_addr + mpp->mr_msize) -
S_ALIGN((size_t)fmpp->mr_addr, syspagsz);
if ((fdm.fd_nname =
stravl_insert(execname, 0, 0, 0)) == NULL)
return (0);
if ((mlmp = elf_new_lmp(&lml_main, ALIST_OFF_DATA,
&fdm, (Addr)hmpp->mr_addr, msize,
NULL, NULL, NULL)) == NULL)
return (0);
MMAPS(mlmp) = fmpp;
MMAPCNT(mlmp) = mapnum;
PADSTART(mlmp) = (ulong_t)fmpp->mr_addr;
PADIMLEN(mlmp) = (ulong_t)fmpp->mr_addr +
(ulong_t)mpp->mr_addr + (ulong_t)mpp->mr_msize;
}
}
/*
* Establish the interpretors name as that defined within the initial
* object (executable). This provides for ORIGIN processing of ld.so.1
* dependencies. Note, the NAME() of the object remains that which was
* passed to us as the SONAME on execution.
*/
if (ldsoexec == 0) {
size_t len = strlen(interp->i_name);
if (expand(&interp->i_name, &len, 0, 0,
(PD_TKN_ISALIST | PD_TKN_CAP), rlmp) & PD_TKN_RESOLVED)
fdr.fd_flags |= FLG_FD_RESOLVED;
}
fdr.fd_pname = interp->i_name;
(void) fullpath(rlmp, &fdr);
/*
* The runtime linker acts as a filtee for various dl*() functions that
* are defined in libc (and libdl). Make sure this standard name for
* the runtime linker is also registered in the FullPathNode AVL tree.
*/
(void) fpavl_insert(&lml_rtld, rlmp, _rtldname, 0);
/*
* Having established the true runtime linkers name, simplify the name
* for error diagnostics.
*/
if ((str = strrchr(PATHNAME(rlmp), '/')) != NULL)
rtldname = ++str;
else
rtldname = PATHNAME(rlmp);
/*
* Expand the fullpath name of the application. This typically occurs
* as a part of loading an object, but as the kernel probably mapped
* it in, complete this processing now.
*/
(void) fullpath(mlmp, 0);
/*
* Some troublesome programs will change the value of argv[0]. Dupping
* the process string protects us, and insures the string is left in
* any core files.
*/
if ((str = (char *)strdup(procname)) == NULL)
return (0);
procname = str;
FLAGS(mlmp) |= (FLG_RT_ISMAIN | FLG_RT_MODESET);
FLAGS1(mlmp) |= FL1_RT_USED;
/*
* It's the responsibility of MAIN(crt0) to call it's _init and _fini
* section, therefore null out any INIT/FINI so that this object isn't
* collected during tsort processing. And, if the application has no
* initarray or finiarray we can economize on establishing bindings.
*/
INIT(mlmp) = FINI(mlmp) = NULL;
if ((INITARRAY(mlmp) == NULL) && (FINIARRAY(mlmp) == NULL))
FLAGS1(mlmp) |= FL1_RT_NOINIFIN;
/*
* Identify lddstub if necessary.
*/
if (lml_main.lm_flags & LML_FLG_TRC_LDDSTUB)
FLAGS1(mlmp) |= FL1_RT_LDDSTUB;
/*
* Retain our argument information for use in dlinfo.
*/
argsinfo.dla_argv = argv--;
argsinfo.dla_argc = (long)*argv;
argsinfo.dla_envp = envp;
argsinfo.dla_auxv = auxv;
(void) enter(0);
/*
* Add our two main link-maps to the dynlm_list
*/
if (aplist_append(&dynlm_list, &lml_main, AL_CNT_DYNLIST) == NULL)
return (0);
if (aplist_append(&dynlm_list, &lml_rtld, AL_CNT_DYNLIST) == NULL)
return (0);
/*
* Reset the link-map counts for both lists. The init count is used to
* track how many objects have pending init sections, this gets incre-
* mented each time an object is relocated. Since ld.so.1 relocates
* itself, it's init count will remain zero.
* The object count is used to track how many objects have pending fini
* sections, as ld.so.1 handles its own fini we can zero its count.
*/
lml_main.lm_obj = 1;
lml_rtld.lm_obj = 0;
/*
* Initialize debugger information structure. Some parts of this
* structure were initialized statically.
*/
r_debug.rtd_rdebug.r_map = (Link_map *)lml_main.lm_head;
r_debug.rtd_rdebug.r_ldsomap = (Link_map *)lml_rtld.lm_head;
r_debug.rtd_rdebug.r_ldbase = r_debug.rtd_rdebug.r_ldsomap->l_addr;
r_debug.rtd_dynlmlst = &dynlm_list;
/*
* Determine the dev/inode information for the executable to complete
* load_so() checking for those who might dlopen(a.out).
*/
if (rtld_stat(PATHNAME(mlmp), &status) == 0) {
STDEV(mlmp) = status.st_dev;
STINO(mlmp) = status.st_ino;
}
/*
* Initialize any configuration information.
*/
if (!(rtld_flags & RT_FL_NOCFG)) {
if ((features = elf_config(mlmp, (aoutdyn != 0))) == -1)
return (0);
}
#if defined(_ELF64)
/*
* If this is a 64-bit process, determine whether this process has
* restricted the process address space to 32-bits. Any dependencies
* that are restricted to a 32-bit address space can only be loaded if
* the executable has established this requirement.
*/
if (CAPSET(mlmp).sc_sf_1 & SF1_SUNW_ADDR32)
rtld_flags2 |= RT_FL2_ADDR32;
#endif
/*
* Establish any alternative capabilities, and validate this object
* if it defines it's own capabilities information.
*/
if (cap_alternative() == 0)
return (0);
if (cap_check_lmp(mlmp, &rej) == 0) {
if (lml_main.lm_flags & LML_FLG_TRC_ENABLE) {
/* LINTED */
(void) printf(MSG_INTL(ldd_warn[rej.rej_type]),
NAME(mlmp), rej.rej_str);
} else {
/* LINTED */
eprintf(&lml_main, ERR_FATAL,
MSG_INTL(err_reject[rej.rej_type]),
NAME(mlmp), rej.rej_str);
return (0);
}
}
/*
* Establish the modes of the initial object. These modes are
* propagated to any preloaded objects and explicit shared library
* dependencies.
*
* If we're generating a configuration file using crle(1), remove
* any RTLD_NOW use, as we don't want to trigger any relocation proc-
* essing during crle(1)'s first past (this would just be unnecessary
* overhead). Any filters are explicitly loaded, and thus RTLD_NOW is
* not required to trigger filter loading.
*
* Note, RTLD_NOW may have been established during analysis of the
* application had the application been built -z now.
*/
MODE(mlmp) |= (RTLD_NODELETE | RTLD_GLOBAL | RTLD_WORLD);
if (rtld_flags & RT_FL_CONFGEN) {
MODE(mlmp) |= RTLD_CONFGEN;
MODE(mlmp) &= ~RTLD_NOW;
rtld_flags2 &= ~RT_FL2_BINDNOW;
}
if ((MODE(mlmp) & RTLD_NOW) == 0) {
if (rtld_flags2 & RT_FL2_BINDNOW)
MODE(mlmp) |= RTLD_NOW;
else
MODE(mlmp) |= RTLD_LAZY;
}
/*
* If debugging was requested initialize things now that any cache has
* been established. A user can specify LD_DEBUG=help to discover the
* list of debugging tokens available without running the application.
* However, don't allow this setting from a configuration file.
*
* Note, to prevent recursion issues caused by loading and binding the
* debugging libraries themselves, a local debugging descriptor is
* initialized. Once the debugging setup has completed, this local
* descriptor is copied to the global descriptor which effectively
* enables diagnostic output.
*
* Ignore any debugging request if we're being monitored by a process
* that expects the old getpid() initialization handshake.
*/
if ((rpl_debug || prm_debug) && ((rtld_flags & RT_FL_DEBUGGER) == 0)) {
Dbg_desc _dbg_desc = {0};
struct timeval total = DBG_TOTALTIME;
struct timeval delta = DBG_DELTATIME;
if (rpl_debug) {
if (dbg_setup(rpl_debug, &_dbg_desc) == 0)
return (0);
if (_dbg_desc.d_extra & DBG_E_HELP_EXIT)
rtldexit(&lml_main, 0);
}
if (prm_debug)
(void) dbg_setup(prm_debug, &_dbg_desc);
*dbg_desc = _dbg_desc;
DBG_TOTALTIME = total;
DBG_DELTATIME = delta;
}
/*
* Now that debugging is enabled generate any diagnostics from any
* previous events.
*/
if (DBG_ENABLED) {
DBG_CALL(Dbg_cap_val(&lml_main, org_scapset, alt_scapset,
M_MACH));
DBG_CALL(Dbg_file_config_dis(&lml_main, config->c_name,
features));
DBG_CALL(Dbg_file_ldso(rlmp, envp, auxv,
LIST(rlmp)->lm_lmidstr, ALIST_OFF_DATA));
if (THIS_IS_ELF(mlmp)) {
DBG_CALL(Dbg_file_elf(&lml_main, PATHNAME(mlmp),
ADDR(mlmp), MSIZE(mlmp), LIST(mlmp)->lm_lmidstr,
ALIST_OFF_DATA));
} else {
DBG_CALL(Dbg_file_aout(&lml_main, PATHNAME(mlmp),
ADDR(mlmp), MSIZE(mlmp), LIST(mlmp)->lm_lmidstr,
ALIST_OFF_DATA));
}
}
/*
* Enable auditing.
*/
if (rpl_audit || prm_audit || profile_lib) {
int ndx;
const char *aud[3];
aud[0] = rpl_audit;
aud[1] = prm_audit;
aud[2] = profile_lib;
/*
* Any global auditing (set using LD_AUDIT or LD_PROFILE) that
* can't be established is non-fatal.
*/
if ((auditors = calloc(1, sizeof (Audit_desc))) == NULL)
return (0);
for (ndx = 0; ndx < 3; ndx++) {
if (aud[ndx]) {
if ((auditors->ad_name =
strdup(aud[ndx])) == NULL)
return (0);
rtld_flags2 |= RT_FL2_FTL2WARN;
(void) audit_setup(mlmp, auditors,
PD_FLG_EXTLOAD, NULL);
rtld_flags2 &= ~RT_FL2_FTL2WARN;
}
}
lml_main.lm_tflags |= auditors->ad_flags;
}
if (AUDITORS(mlmp)) {
/*
* Any object required auditing (set with a DT_DEPAUDIT dynamic
* entry) that can't be established is fatal.
*/
if (FLAGS1(mlmp) & FL1_RT_GLOBAUD) {
/*
* If this object requires global auditing, use the
* local auditing information to set the global
* auditing descriptor. The effect is that a
* DT_DEPAUDIT act as an LD_AUDIT.
*/
if ((auditors == NULL) && ((auditors = calloc(1,
sizeof (Audit_desc))) == NULL))
return (0);
auditors->ad_name = AUDITORS(mlmp)->ad_name;
if (audit_setup(mlmp, auditors, 0, NULL) == 0)
return (0);
lml_main.lm_tflags |= auditors->ad_flags;
/*
* Clear the local auditor information.
*/
free((void *) AUDITORS(mlmp));
AUDITORS(mlmp) = NULL;
} else {
/*
* Establish any local auditing.
*/
if (audit_setup(mlmp, AUDITORS(mlmp), 0, NULL) == 0)
return (0);
AFLAGS(mlmp) |= AUDITORS(mlmp)->ad_flags;
lml_main.lm_flags |= LML_FLG_LOCAUDIT;
}
}
/*
* Explicitly add the initial object and ld.so.1 to those objects being
* audited. Note, although the ld.so.1 link-map isn't auditable,
* establish a cookie for ld.so.1 as this may be bound to via the
* dl*() family.
*/
if ((lml_main.lm_tflags | AFLAGS(mlmp)) & LML_TFLG_AUD_MASK) {
if (((audit_objopen(mlmp, mlmp) == 0) ||
(audit_objopen(mlmp, rlmp) == 0)) &&
(AFLAGS(mlmp) & LML_TFLG_AUD_MASK))
return (0);
}
/*
* Map in any preloadable shared objects. Establish the caller as the
* head of the main link-map list. In the case of being exercised from
* lddstub, the caller gets reassigned to the first target shared object
* so as to provide intuitive diagnostics from ldd().
*
* Note, it is valid to preload a 4.x shared object with a 5.0
* executable (or visa-versa), as this functionality is required by
* ldd(1).
*/
clmp = mlmp;
if (rpl_preload && (preload(rpl_preload, mlmp, &clmp) == 0))
return (0);
if (prm_preload && (preload(prm_preload, mlmp, &clmp) == 0))
return (0);
/*
* Load all dependent (needed) objects.
*/
if (analyze_lmc(&lml_main, ALIST_OFF_DATA, mlmp, mlmp, NULL) == NULL)
return (0);
/*
* Relocate all the dependencies we've just added.
*
* If this process has been established via crle(1), the environment
* variable LD_CONFGEN will have been set. crle(1) may create this
* process twice. The first time crle only needs to gather dependency
* information. The second time, is to dldump() the images.
*
* If we're only gathering dependencies, relocation is unnecessary.
* As crle(1) may be building an arbitrary family of objects, they may
* not fully relocate either. Hence the relocation phase is not carried
* out now, but will be called by crle(1) once all objects have been
* loaded.
*/
if ((rtld_flags & RT_FL_CONFGEN) == 0) {
DBG_CALL(Dbg_util_nl(&lml_main, DBG_NL_STD));
if (relocate_lmc(&lml_main, ALIST_OFF_DATA, mlmp,
mlmp, NULL) == 0)
return (0);
/*
* Inform the debuggers that basic process initialization is
* complete, and that the state of ld.so.1 (link-map lists,
* etc.) is stable. This handshake enables the debugger to
* initialize themselves, and consequently allows the user to
* set break points in .init code.
*
* Most new debuggers use librtld_db to monitor activity events.
* Older debuggers indicated their presence by setting the
* DT_DEBUG entry in the dynamic executable (see elf_new_lm()).
* In this case, getpid() is called so that the debugger can
* catch the system call. This old mechanism has some
* restrictions, as getpid() should not be called prior to
* basic process initialization being completed. This
* restriction has become increasingly difficult to maintain,
* as the use of auditors, LD_DEBUG, and the initialization
* handshake with libc can result in "premature" getpid()
* calls. The use of this getpid() handshake is expected to
* disappear at some point in the future, and there is intent
* to work towards that goal.
*/
rd_event(&lml_main, RD_DLACTIVITY, RT_CONSISTENT);
rd_event(&lml_rtld, RD_DLACTIVITY, RT_CONSISTENT);
if (rtld_flags & RT_FL_DEBUGGER) {
r_debug.rtd_rdebug.r_flags |= RD_FL_ODBG;
(void) getpid();
}
}
/*
* Indicate preinit activity, and call any auditing routines. These
* routines are called before initializing any threads via libc, or
* before collecting the complete set of .inits on the primary link-map.
* Although most libc interfaces are encapsulated in local routines
* within libc, they have been known to escape (ie. call a .plt). As
* the appcert auditor uses preinit as a trigger to establish some
* external interfaces to the main link-maps libc, we need to activate
* this trigger before exercising any code within libc. Additionally,
* I wouldn't put it past an auditor to add additional objects to the
* primary link-map. Hence, we collect .inits after the audit call.
*/
rd_event(&lml_main, RD_PREINIT, 0);
if (aud_activity ||
((lml_main.lm_tflags | AFLAGS(mlmp)) & LML_TFLG_AUD_ACTIVITY))
audit_activity(mlmp, LA_ACT_CONSISTENT);
if (aud_preinit ||
((lml_main.lm_tflags | AFLAGS(mlmp)) & LML_TFLG_AUD_PREINIT))
audit_preinit(mlmp);
/*
* If we're creating initial configuration information, we're done
* now that the auditing step has been called.
*/
if (rtld_flags & RT_FL_CONFGEN) {
leave(LIST(mlmp), 0);
return (mlmp);
}
/*
* Sort the .init sections of all objects we've added. If we're
* tracing we only need to execute this under ldd(1) with the -i or -u
* options.
*/
lmflags = lml_main.lm_flags;
if (((lmflags & LML_FLG_TRC_ENABLE) == 0) ||
(lmflags & (LML_FLG_TRC_INIT | LML_FLG_TRC_UNREF))) {
if ((tobj = tsort(mlmp, LIST(mlmp)->lm_init,
RT_SORT_REV)) == (Rt_map **)S_ERROR)
return (0);
}
/*
* If we are tracing we're done. This is the one legitimate use of a
* direct call to rtldexit() rather than return, as we don't want to
* return and jump to the application.
*/
if (lmflags & LML_FLG_TRC_ENABLE) {
unused(&lml_main);
rtldexit(&lml_main, 0);
}
/*
* Check if this instance of the linker should have a primary link
* map. This flag allows multiple copies of the -same- -version-
* of the linker (and libc) to run in the same address space.
*
* Without this flag we only support one copy of the linker in a
* process because by default the linker will always try to
* initialize at one primary link map The copy of libc which is
* initialized on a primary link map will initialize global TLS
* data which can be shared with other copies of libc in the
* process. The problem is that if there is more than one copy
* of the linker, only one copy should link libc onto a primary
* link map, otherwise libc will attempt to re-initialize global
* TLS data. So when a copy of the linker is loaded with this
* flag set, it will not initialize any primary link maps since
* presumably another copy of the linker will do this.
*
* Note that this flag only allows multiple copies of the -same-
* -version- of the linker (and libc) to coexist. This approach
* will not work if we are trying to load different versions of
* the linker and libc into the same process. The reason for
* this is that the format of the global TLS data may not be
* the same for different versions of libc. In this case each
* different version of libc must have it's own primary link map
* and be able to maintain it's own TLS data. The only way this
* can be done is by carefully managing TLS pointers on transitions
* between code associated with each of the different linkers.
* Note that this is actually what is done for processes in lx
* branded zones. Although in the lx branded zone case, the
* other linker and libc are actually gld and glibc. But the
* same general TLS management mechanism used by the lx brand
* would apply to any attempts to run multiple versions of the
* solaris linker and libc in a single process.
*/
if (auxflags & AF_SUN_NOPLM)
rtld_flags2 |= RT_FL2_NOPLM;
/*
* Establish any static TLS for this primary link-map. Note, regardless
* of whether TLS is available, an initial handshake occurs with libc to
* indicate we're processing the primary link-map. Having identified
* the primary link-map, initialize threads.
*/
if (rt_get_extern(&lml_main, mlmp) == 0)
return (0);
if ((rtld_flags2 & RT_FL2_NOPLM) == 0) {
if (tls_statmod(&lml_main, mlmp) == 0)
return (0);
rt_thr_init(&lml_main);
rtld_flags2 |= RT_FL2_PLMSETUP;
} else {
rt_thr_init(&lml_main);
}
/*
* Fire all dependencies .init sections. Identify any unused
* dependencies, and leave the runtime linker - effectively calling
* the dynamic executables entry point.
*/
call_array(PREINITARRAY(mlmp), (uint_t)PREINITARRAYSZ(mlmp), mlmp,
SHT_PREINIT_ARRAY);
if (tobj)
call_init(tobj, DBG_INIT_SORT);
rd_event(&lml_main, RD_POSTINIT, 0);
unused(&lml_main);
DBG_CALL(Dbg_util_call_main(mlmp));
rtld_flags |= (RT_FL_OPERATION | RT_FL_APPLIC);
leave(LIST(mlmp), 0);
return (mlmp);
}
| 30.2557 | 79 | 0.670237 | [
"object",
"vector"
] |
862bd4eeb287eaef648ea8e2d1f6e669149c262b | 665 | h | C | render-pipeline/shader/s_lab/shader_mg.h | zyansheep/SvarogGameEngine | 87f5285f9d5e8fa8a5f0de7e61617625a9de75ca | [
"MIT"
] | null | null | null | render-pipeline/shader/s_lab/shader_mg.h | zyansheep/SvarogGameEngine | 87f5285f9d5e8fa8a5f0de7e61617625a9de75ca | [
"MIT"
] | null | null | null | render-pipeline/shader/s_lab/shader_mg.h | zyansheep/SvarogGameEngine | 87f5285f9d5e8fa8a5f0de7e61617625a9de75ca | [
"MIT"
] | null | null | null | #pragma once
#ifndef SHADER_MG_H
#define SHADER_MG_H
#include <fstream>
#include <ostream>
#include "core/ds-classes/ArrayList.h"
#include "core/String.h"
#include "render-pipeline/shader/s_lab/svarog_material.h"
#include "render-pipeline/shader/glsl_shader_generation/shader_defs.h"
class SvarogMaterial;
class ShaderManager {
private:
static ShaderManager* shader_manager;
ArrayList<ShaderProgram>*shader_mats = new ArrayList<ShaderProgram>();
ShaderManager(){}
public:
~ShaderManager() {}
static ShaderManager* getShaderManager();
void pass_code(VertexShader vert_mat, FragmentShader frag_mat);
};
#endif | 30.227273 | 78 | 0.738346 | [
"render"
] |
8633f76ed6b67eeb4e656b3a410581a98caf7cfd | 1,923 | h | C | app/draw_list.h | ryechat/ImageViewer | 1e7503dad46b9c5357da00d1b433b6445147cd90 | [
"MIT"
] | 1 | 2021-06-24T12:19:29.000Z | 2021-06-24T12:19:29.000Z | app/draw_list.h | ryechat/ImageViewer | 1e7503dad46b9c5357da00d1b433b6445147cd90 | [
"MIT"
] | null | null | null | app/draw_list.h | ryechat/ImageViewer | 1e7503dad46b9c5357da00d1b433b6445147cd90 | [
"MIT"
] | null | null | null | #pragma once
#ifndef GUID_2BBA94E8F65D481D904502F7C1B79E19
#define GUID_2BBA94E8F65D481D904502F7C1B79E19
#include "movable.h"
#include "list_item.h"
#include "image_viewer.h"
#include "surface.h"
namespace image_viewer {
class CImageViewer::CDrawList {
public:
using Surface = basis::Surface;
CDrawList(CImageViewer &parent_);
~CDrawList();
// Shows the list.
void show() {
m_enable = true;
invalidate();
}
// Hides the list.
void hide() {
m_enable = false;
invalidate();
}
// Invalidate the rectangle to where it draws the list.
void invalidate();
//! Returns rectangle that the list was drawn expressed by client coordinate.
Rect rect() { return m_offset.rect(); }
//! Draws the list.
Rect draw(Surface *s) { return drawList(s, true); }
//! Moves the list. This will cause WM_PAINT message posted.
void move(basis::Size diff) {
parent.invalidate(rect());
m_offset.move(diff);
invalidate();
}
iterator itemFromPt(basis::Point pt);
bool isInclusive(basis::Point pt);
private:
/*! Draws the list and returns the rectangle.
If bDraw was set to be false then not drawn,
this allows getting next area to draw.
*/
Rect drawList(Surface *s, bool bDraw);
Rect do_drawList(Surface *s, bool bDraw);
using Position = std::pair<iterator, Rect>;
std::vector<Position> m_pos;
CImageViewer &parent;
bool m_enable;
HFONT boldFont;
basis::CMovable m_offset;
std::basic_string<TCHAR> sNoFileInfo; // Drawn if there was no file to show.
enum ColorType { not_read, now_loading, loaded_image, current_file };
static constexpr COLORREF Colors[sizeof(ColorType)] =
{ 0, RGB(0, 0, 255), RGB(0, 255, 0), RGB(255, 0, 0) };
};
} // namespace
#endif | 26.342466 | 82 | 0.627145 | [
"vector"
] |
863b7187f81716189be77829b1c290469ef7e295 | 6,592 | h | C | TSSGE.h | Criarino/Sistema-Posto-de-Gasolina | e22fd89ef9b9c13451bbae79ffc4c7c75df71234 | [
"MIT"
] | null | null | null | TSSGE.h | Criarino/Sistema-Posto-de-Gasolina | e22fd89ef9b9c13451bbae79ffc4c7c75df71234 | [
"MIT"
] | null | null | null | TSSGE.h | Criarino/Sistema-Posto-de-Gasolina | e22fd89ef9b9c13451bbae79ffc4c7c75df71234 | [
"MIT"
] | null | null | null | #pragma once
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"
#include "SDL2/SDL_ttf.h"
#include <vector>
#include <string>
#include <stdexcept>
#include <memory>
//#include <iostream>
using namespace std;
struct TS_Rect //representa um retangulo desenhado pela engine
{
SDL_Rect r;
SDL_Color c;
bool fil;
};
struct TS_Texto //representa um texto simples na tela (não caixa de texto)
{
string msg;
int f;
int x, y;
SDL_Color c;
};
class TS_Objeto //representa objetos na tela
{
private:
SDL_Rect dest; //onde na tela vai ficar
SDL_Rect src; //escala da imagem original
SDL_Texture* tex; //textura
int id=0;
public:
TS_Objeto(){tex=NULL;}
~TS_Objeto(){SDL_DestroyTexture(tex);}
//getters e setters
SDL_Rect getDest() {return dest;}
SDL_Rect getSource() {return src;}
SDL_Texture* getTex() {return tex;}
int getSW() {return src.w;}//pegar informações da imagem original
int getSH() {return src.h;}
int getDX() {return dest.x;}//para saber posição do objeto (getDestX)
int getDY() {return dest.y;}
int getDW() {return dest.w;}
int getDH() {return dest.h;}
int getID() {return id;}
void setDest(int x, int y, int w, int h);
void setDest(int x, int y);//para mover a tela
void setSource(int x, int y, int w, int h);//de onde vai começar a carregar a imagem, qual a porção da imagem que vai carregar. Pode cortar partes da imagem
void setImage(string filename, SDL_Renderer* ren);//carrega uma textura
void setID(int ID){id=ID;}
};
class TS_audio //para audio
{
private:
SDL_AudioSpec wavSpec;//apenas arquivos wave
Uint32 wavLength; //TEM que ser esse o tipo
Uint8* wavBuffer;
SDL_AudioDeviceID deviceID;
public:
~TS_audio();
void Adicionar(string filename);
void Play();
};
class TS_Botao : public TS_Objeto//um objeto com função extra de botão
{
private:
bool click=false;
public:
int tamx, tamy;
void Setclick(bool set){click=set;}
bool Getclick(){return click;}
bool Sobre();//verifica se o mouse está sobre o botão
void setDest(int x, int y, int w, int h);
};
class TS_CaixaTxt : public TS_Botao//um botão com função extra de caixa de texto
{
private:
string txt;//guarda o texto
bool ativ;//se a caixa está ativa ou não
int ajx, ajy;//ajuste da posição do texto dentro da caixa
public:
TS_CaixaTxt();
int r, g, b, f; //cor, handle da fonte
//getters e setters
string Gettxt(){return txt;}
bool Getativ(){return ativ;}
int GetAjx(){return ajx;}
int GetAjy(){return ajy;}
void Setativ(bool set){ativ=set;}
void SetAj(int x, int y){ajx=x;ajy=y;}//seta as posições de ajuste do texto
void Texto(string a);//para atualizar o texto da caixa
void Limpar(){txt="";}//para limpar o texto da caixa
void Ativar();//para ativar/desativar a caixa de texto
};
class TS //engine em si
{
private:
int altura;//tamanho da janela
int largura;
SDL_Renderer* rende;//renderizador
SDL_Window* janela;//janela
vector<TTF_Font*>FontHandles;//fontes abertas
SDL_Event eventos;//fila de eventos
double frameCount=0, timerFPS, lastFrame=0;//para calcular e limitar fps
public:
string buftxt;
~TS();
TS();
SDL_Window* getJanela(){return janela;}
SDL_Event* getEvent(){return &eventos;}
SDL_Renderer* getRende(){return rende;}
void CriarJanela(int alt, int lar, string nome);
vector<int> HaInput();//verificar se há input e qual é esse input. Retorna 0 se não tiver, -1 se o usuário clicou no X da janela, retorna um vector de duas posições nos outros casos: o primeiro elemento do vector é o tipo de evento e o segundo o código do evento (ascii caso seja do teclado)
void SetBackground(int r, int g, int b, int a);//seta um fundo
void SetBackground(int r, int g, int b, int a, TS_Objeto* o);//setar um fundo com imagem
int AbrirFonte(string arqv, int tam);//abre uma fonte de texto. Retorna o código para essa fonte (diretório do arquivo ttf, tamanho)
void Limite(int fps);//limita o número de vezes que uma seção de código vai rodar por segundo
void Commit();//mostra o renderizador (frame) na tela
void CriarObj(TS_Objeto* aux, string img, int x, int y, int l, int a);//cria um objeto (referência de um objeto, caminho de diretório para a textura, posção xy de onde vai começar a carregar essa textura, largura e altura dessa textura)
void CriarBtn(TS_Botao* aux, string img, int x, int y, int l, int a);//criar um botão a partir de uma imagem
void CriarBtn(TS_Botao* aux, int l, int a);//cria um botão invisível, NÃO SE DEVE CHAMAR A FUNÇÃO "DESENHAR" NESSE CASO
void CriarCaixaTxt(TS_CaixaTxt* aux, string img, int f, int r, int g, int b, int x, int y, int l, int a);//cria uma caixa de texto com imagem (fonte, cor do texto, ponto do qual começará a carregar a imagem original, tamanho)
void CriarCaixaTxt(TS_CaixaTxt* aux, int f, int r, int g, int b, int l, int a);//para criar uma caixa de texto invisível(mesmo que o anterior, mas sem ponto para carregar imagem)
TS_Rect CriarRect(bool fil, int x, int y, int alt, int lar, int r, int g, int b, int a);//criar um TS_Rect
TS_Texto CriarTexto(string msg, int f, int x, int y, int r, int g, int b);//criar um TS_Texto
void Desenhar(TS_Objeto* o);//quando o objeto já tem posição
void Desenhar(TS_Objeto* o, int x, int y);//quando quer atribuir posição ao objeto
void Desenhar(string msg, int f, int x, int y, int r, int g, int b);//para texto (mensagem, codigo da fonte, posição xy, cor rgb)
void Desenhar(bool fil, int alt, int lar, int x, int y, int r, int g, int b, int a);//para retangulos(se é para preencher, altura x largura, posição xy, cor)
void Desenhar(int x, int y, int fx, int fy, int r, int g, int b);//Para linhas(ponto xy inicial, ponto xy final,...)
void Desenhar(int x, int y, int r, int g, int b);//Para pontos
void Desenhar(TS_CaixaTxt* a, int mx, int my);//para desenhar o texto de uma caixa (caixa, ajuste x y do texto)
};
class TS_Tela//classe abstrata para telas
{
protected:
vector<shared_ptr<TS_Objeto>>conteudo;//onde ficam todos os TS_Objetos a serem desenhados na tela
vector<shared_ptr<TS_Botao>>botoes;//onde ficam todos os TS_Botao
vector<shared_ptr<TS_Botao>>botoesInv;//botoes que não devem ser desenhados
vector<shared_ptr<TS_CaixaTxt>>caixastxt;//caixas de texto
vector<shared_ptr<TS_CaixaTxt>>caixastxtInv;//caixas de texto que não devem ser desenhadas
vector<TS_Rect>retangulos;//onde ficam todos os retangulos a serem desenhados
vector<TS_Texto>textoSimples;//onde fica todo o texto simples a ser desenhado na tela
public:
void Desenhar (TS* Engine);//implementada em TSSGE.cpp. Desenha tudo que está nos vectors na tela
virtual void MenuPrinc()=0;//o que será o menu principal da sua tela
};
| 40.691358 | 292 | 0.729521 | [
"vector"
] |
8648a1a4b6edcbfbd5830da0a055f53beaef2494 | 4,129 | h | C | src/Demos/particle-221/src/DMcTools/Image/ColorMap.h | smokhov/comp477-samples | a1416f1c1e2000e27c375a39363dd94cf3bfa3d0 | [
"Apache-2.0"
] | 5 | 2019-09-18T16:41:23.000Z | 2019-09-23T18:58:44.000Z | src/Demos/particle-221/src/DMcTools/Image/ColorMap.h | smokhov/comp477-samples | a1416f1c1e2000e27c375a39363dd94cf3bfa3d0 | [
"Apache-2.0"
] | 2 | 2019-10-09T20:42:28.000Z | 2019-10-14T17:10:57.000Z | src/Demos/particle-221/src/DMcTools/Image/ColorMap.h | smokhov/comp477-samples | a1416f1c1e2000e27c375a39363dd94cf3bfa3d0 | [
"Apache-2.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////
// ColorMap.h - A color map implementation
//
// Maps a scalar to a color. Map can be arbitrary size. Pixel type is templated.
#ifndef dmc_colormap_h
#define dmc_colormap_h
#include "Util/Assert.h"
#include <vector>
template<class Pixel_T>
class ColorMap : public std::vector<Pixel_T>
{
// Returns a linearly interpolated color.
// s must be on 0.0 -> 1.0.
// 0.0 maps exactly to (*this)[0].
// 1.0 maps exactly to (*this)[Size-1].
Pixel_T Sample01(const float s) const
{
ASSERT_R(s >= 0.0f && s <= 1.0f);
float sS = s * float(std::vector<Pixel_T>::size()-1);
size_t iLo = sS;
float a = sS - float(iLo);
size_t iHi = iLo + 1;
if(iHi >= std::vector<Pixel_T>::size()) iHi = std::vector<Pixel_T>::size() - 1;
Pixel_T V = (*this)[iHi] * a + (*this)[iLo] * (1.0f - a);
return V;
}
// Set a portion of the map by linearly blending from vLo to vHigh
// replacing the range (*this)[iLo] through (*this)[iHi].
void RealSetSpan(const size_t iLo, const size_t iHi, const Pixel_T &vLo, const Pixel_T &vHi)
{
ASSERT_R(iLo >= 0 && iHi < std::vector<Pixel_T>::size() && iLo <= iHi);
if(iLo == iHi) {
(*this)[iLo] = vLo;
} else {
float Tmp = 1.0f / float(iHi-iLo);
Pixel_T vSp = vHi - vLo;
for(size_t i=iLo; i<=iHi; i++) {
float s = (i-iLo) * Tmp;
(*this)[i] = vLo + s * vSp;
}
}
}
public:
ColorMap() { }
ColorMap(const size_t Size_)
{
std::vector<Pixel_T>::resize(Size_);
}
// Returns a linearly interpolated color.
// s gets clamped to 0.0 -> 1.0.
Pixel_T operator()(const float s_) const
{
float s = Saturate(s_);
return Sample01(s);
}
// Returns a linearly interpolated color.
// s is wrapped to 0.0 -> 1.0.
Pixel_T SampleWrapped(const float s_) const
{
float s = (s_ >= 0.0f) ? fmodf(s_, 1.0f) : (1.0f - fmodf(s_, 1.0f));
return Sample01(s);
}
// Create a copy of this colormap and return a pointer to it
DMC_INLINE ColorMap<Pixel_T> *Copy() const
{
ColorMap<Pixel_T> *C = new ColorMap<Pixel_T>();
*C = *this;
return C;
}
// Set a portion of the map by linearly blending from vLo to vHigh
// replacing the range (*this)[iLo] through (*this)[iHi].
void SetSpan(const size_t iLo_, const size_t iHi_, const Pixel_T &vLo_, const Pixel_T &vHi_)
{
size_t iLo, iHi;
Pixel_T vLo, vHi;
if(iHi_ < iLo_) {
iLo = iHi_; vLo = vHi_;
iHi = iLo_; vHi = vLo_;
} else {
iLo = iLo_; vLo = vLo_;
iHi = iHi_; vHi = vHi_;
}
RealSetSpan(iLo, iHi, vLo, vHi);
}
// Set a portion of the map by linearly blending from vLo to vHigh
// replacing the range sLo through sHi, which are on 0..1.
void SetSpan(const float sLo_, const float sHi_, const Pixel_T &vLo_, const Pixel_T &vHi_)
{
float sLo, sHi;
Pixel_T vLo, vHi;
if(sHi_ < sLo_) {
sLo = sHi_; vLo = vHi_;
sHi = sLo_; vHi = vLo_;
} else {
sLo = sLo_; vLo = vLo_;
sHi = sHi_; vHi = vHi_;
}
sLo = Saturate(sLo);
sHi = Saturate(sHi);
size_t iLo = size_t(Round(sLo * (float(std::vector<Pixel_T>::size()-1))));
size_t iHi = size_t(Round(sHi * (float(std::vector<Pixel_T>::size()-1))));
RealSetSpan(iLo, iHi, vLo, vHi);
}
};
// True if the colormaps are identical.
template<class Pixel_T>
bool Equal(const ColorMap<Pixel_T> &Aa, const ColorMap<Pixel_T> &Bb)
{
if(Aa.size() != Bb.size())
return false;
size_t Sz = Aa.size();
for(size_t i=0; i<Sz; i++)
if(Aa[i] != Bb[i])
return false;
return true;
}
#endif
| 30.138686 | 97 | 0.517317 | [
"vector"
] |
8660b8dcddac9b7eaf06f385ee4c6795f1badb17 | 4,269 | h | C | ecm/include/tencentcloud/ecm/v20190719/model/PhysicalPosition.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | ecm/include/tencentcloud/ecm/v20190719/model/PhysicalPosition.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | ecm/include/tencentcloud/ecm/v20190719/model/PhysicalPosition.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_ECM_V20190719_MODEL_PHYSICALPOSITION_H_
#define TENCENTCLOUD_ECM_V20190719_MODEL_PHYSICALPOSITION_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Ecm
{
namespace V20190719
{
namespace Model
{
/**
* 物理位置信息
*/
class PhysicalPosition : public AbstractModel
{
public:
PhysicalPosition();
~PhysicalPosition() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取机位
注意:此字段可能返回 null,表示取不到有效值。
* @return PosId 机位
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetPosId() const;
/**
* 设置机位
注意:此字段可能返回 null,表示取不到有效值。
* @param PosId 机位
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetPosId(const std::string& _posId);
/**
* 判断参数 PosId 是否已赋值
* @return PosId 是否已赋值
*/
bool PosIdHasBeenSet() const;
/**
* 获取机架
注意:此字段可能返回 null,表示取不到有效值。
* @return RackId 机架
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetRackId() const;
/**
* 设置机架
注意:此字段可能返回 null,表示取不到有效值。
* @param RackId 机架
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetRackId(const std::string& _rackId);
/**
* 判断参数 RackId 是否已赋值
* @return RackId 是否已赋值
*/
bool RackIdHasBeenSet() const;
/**
* 获取交换机
注意:此字段可能返回 null,表示取不到有效值。
* @return SwitchId 交换机
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetSwitchId() const;
/**
* 设置交换机
注意:此字段可能返回 null,表示取不到有效值。
* @param SwitchId 交换机
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetSwitchId(const std::string& _switchId);
/**
* 判断参数 SwitchId 是否已赋值
* @return SwitchId 是否已赋值
*/
bool SwitchIdHasBeenSet() const;
private:
/**
* 机位
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_posId;
bool m_posIdHasBeenSet;
/**
* 机架
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_rackId;
bool m_rackIdHasBeenSet;
/**
* 交换机
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_switchId;
bool m_switchIdHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_ECM_V20190719_MODEL_PHYSICALPOSITION_H_
| 29.441379 | 116 | 0.482783 | [
"vector",
"model"
] |
86693d3e182ca746a37f3bf8644f9be6a16f7e94 | 8,919 | c | C | libcog/Engine/cognode.c | dcerjan/old-cog-engine | e6aa34989af7ae359f2550f430dba567a0a1c313 | [
"MIT"
] | 1 | 2020-05-14T18:52:22.000Z | 2020-05-14T18:52:22.000Z | libcog/Engine/cognode.c | dcerjan/old-cog-engine | e6aa34989af7ae359f2550f430dba567a0a1c313 | [
"MIT"
] | null | null | null | libcog/Engine/cognode.c | dcerjan/old-cog-engine | e6aa34989af7ae359f2550f430dba567a0a1c313 | [
"MIT"
] | null | null | null | #include "cognode.h"
#include "cogcamera.h"
#include "coglight.h"
#include "cogmodel.h"
#include "cogplatform.h"
#include "cogscene.h"
#include "cogscenemanager.h"
#include "cogshader.h"
CogNode CogNodeAlloc(const char* name, CogNode parent) {
CogNode self = malloc(sizeof(struct CogNode));
self->name = CogStringAlloc(name);
self->children = CogListAlloc(CogNode);
self->dirty = True;
self->model = CogMatrix4Identity();
self->scale = (CogVector3){1.0f, 1.0f, 1.0f};
self->position = (CogVector3){0.0f, 0.0f, 0.0f};
self->rotation = CogMatrix4Identity();
self->parent = parent;
if(parent) {
CogNodeAttachNode(parent, self);
}
self->attachments.cameras = CogListAlloc(CogCamera);
//self->attachments.emitters = CogListAlloc(CogParticleEmitter);
self->attachments.lights = CogListAlloc(CogLight);
self->attachments.models = CogListAlloc(CogModel);
return self;
}
void CogNodeInspect(CogNode self) {
}
void CogNodeFree(CogNode self) {
CogStringFree(self->name);
CogListFree(self->attachments.cameras);
//CogListFree(self->attachments.emitters);
CogListFree(self->attachments.lights);
CogListFree(self->attachments.models);
free(self);
}
// entity attachment
void CogNodeAttachModel(CogNode self, struct CogModel* model) {
CogListPushBack(self->attachments.models, model);
}
void CogNodeAttachLight(CogNode self, struct CogLight* light) {
CogListPushBack(self->attachments.lights, light);
}
void CogNodeAttachCamera(CogNode self, struct CogCamera* CogCamera) {
CogListPushBack(self->attachments.cameras, CogCamera);
CogCamera->anchor = self;
}
void CogNodeAttachEmitter(CogNode self, struct CogParticleEmitter* emitter) {
}
// node attachment stuff
CogNode CogNodeGetChildNode(CogNode self, const char* name) {
CogListForEach(self->children, node, {
if(!strcmp(name, node->name->data)) {
return node;
}
});
return NULL;
}
CogNode CogNodeAttachNode(CogNode self, CogNode child) {
CogListForEach(self->children, node, {
if(!strcmp(c_str(child->name), c_str(node->name))) {
CogLoggerWarning(CogPlatformGetLogger(), "[CogNode] CogNode %s already contains child named %s.\n", c_str(self->name), c_str(child->name));
return child;
}
});
CogListPushBack(self->children, child);
return child;
}
CogNode CogNodeDetachNode(CogNode self, CogNode child) {
return CogListRemove(self->children, child);
}
// all transform functions are returning modified self to allow chaining
CogNode CogNodeSetRotatation(CogNode self, CogVector3 axis, float angle) {
self->dirty = True;
self->rotation = CogMatrix4Rotation(CogVector3Normalized(axis), angle);
return self;
}
CogNode CogNodeSetTranslation(CogNode self, CogVector3 position) {
self->dirty = True;
self->position = position;
return self;
}
CogNode CogNodeSetScale(CogNode self, float s, float t, float u) {
self->dirty = True;
self->scale = (CogVector3){s,t,u};
return self;
}
CogNode CogNodeTranslate(CogNode self, CogVector3 position) {
self->dirty = True;
self->position = CogVector3Add(self->position, position);
return self;
}
CogNode CogNodeTranslateLeft(CogNode self, float t) {
self->dirty = True;
self->position = CogVector3Sub(self->position, (CogVector3){self->rotation.vector.x.x * t, self->rotation.vector.x.y * t, self->rotation.vector.x.z * t});
return self;
}
CogNode CogNodeTranslateRight(CogNode self, float t) {
self->dirty = True;
self->position = CogVector3Add(self->position, (CogVector3){self->rotation.vector.x.x * t, self->rotation.vector.x.y * t, self->rotation.vector.x.z * t});
return self;
}
CogNode CogNodeTranslateUp(CogNode self, float t) {
self->dirty = True;
self->position = CogVector3Add(self->position, (CogVector3){self->rotation.vector.y.x * t, self->rotation.vector.y.y * t, self->rotation.vector.y.z * t});
return self;
}
CogNode CogNodeTranslateDown(CogNode self, float t) {
self->dirty = True;
self->position = CogVector3Sub(self->position, (CogVector3){self->rotation.vector.y.x * t, self->rotation.vector.y.y * t, self->rotation.vector.y.z * t});
return self;
}
CogNode CogNodeTranslateForward(CogNode self, float t) {
self->dirty = True;
self->position = CogVector3Sub(self->position, (CogVector3){self->rotation.vector.z.x * t, self->rotation.vector.z.y * t, self->rotation.vector.z.z * t});
return self;
}
CogNode CogNodeTranslateBackward(CogNode self, float t) {
self->dirty = True;
self->position = CogVector3Add(self->position, (CogVector3){self->rotation.vector.z.x * t, self->rotation.vector.z.y * t, self->rotation.vector.z.z * t});
return self;
}
CogNode CogNodeRotate(CogNode self, CogVector3 axis, float angle) {
self->dirty = True;
self->rotation = CogMatrix4MulMatrix4(self->rotation, CogMatrix4Rotation( CogVector3Normalized(axis), angle));
return self;
}
CogNode CogNodeYaw(CogNode self, float angle) {
self->dirty = True;
self->rotation = CogMatrix4MulMatrix4(CogMatrix4Rotation((CogVector3){0.0f, 1.0f, 0.0f}, angle), self->rotation);
return self;
}
CogNode CogNodePitch(CogNode self, float angle) {
self->dirty = True;
self->rotation = CogMatrix4MulMatrix4(CogMatrix4Rotation((CogVector3){1.0f, 0.0f, 0.0f}, angle), self->rotation);
return self;
}
CogNode CogNodeRoll(CogNode self, float angle) {
self->dirty = True;
self->rotation = CogMatrix4MulMatrix4(CogMatrix4Rotation((CogVector3){0.0f, 0.0f, -1.0f}, angle), self->rotation);
return self;
}
CogNode CogNodeScale(CogNode self, float s, float t, float u) {
self->dirty = True;
self->scale.x *= s;
self->scale.y *= t;
self->scale.z *= u;
return self;
}
CogNode CogNodeLookAt(CogNode self, CogVector3 target, CogVector3 up) {
self->dirty = True;
CogVector3 wp = {self->model.vector.w.x, self->model.vector.w.y, self->model.vector.w.z};
self->rotation = CogMatrix4LookAt(wp, target, up);
self->rotation.vector.w = (CogVector4){0.0f, 0.0f, 0.0f, 1.0f};
return self;
}
CogVector3 CogNodeGetPosition(CogNode self, const CogNodeSpace space) {
switch(space) {
case CogNodeSpaceLocal:
return self->position;
case CogNodeSpaceWorld: {
CogMatrix4 toWorld = CogMatrix4Inverted(self->model);
return (CogVector3){-toWorld.vector.w.x, -toWorld.vector.w.y, -toWorld.vector.w.z};
}
case CogNodeSpaceCogCamera:
return (CogVector3){self->model.vector.w.x, self->model.vector.w.y, self->model.vector.w.z};
}
}
CogVector3 CogNodeGetScale(CogNode self) {
return self->scale;
}
void CogNodeUpdateTransforms(CogNode self) {
if(self->dirty) {
CogMatrix4 T = CogMatrix4Translation(self->position);
CogMatrix4 S = CogMatrix4Scale(self->scale.x, self->scale.y, self->scale.z);
CogMatrix4 R = self->rotation;
CogMatrix4 M = CogMatrix4MulMatrix4( CogMatrix4MulMatrix4(S, T), R );
if(self->parent) {
self->model = CogMatrix4MulMatrix4( self->parent->model, M );
} else {
self->model = M;
}
}
CogListForEach(self->children, child, {
CogNodeUpdateTransforms(child);
});
}
void CogNodeUpdate(CogNode self, float t) {
/* TODO: update attached models, particle emitters and CogCameras*/
CogListForEach(self->attachments.cameras, CogCamera, {
CogCamera->view = CogMatrix4Inverted(self->model);
});
CogListCogNode_CogLight* light;
CogCamera c = CogSceneManagerGetActiveScene()->activeCamera;
for(light = self->attachments.lights->first; light != NULL; light = light->next) {
if(light->data->type == CogLightTypePoint) {
CogPointLight l = (CogPointLight)light->data;
l->position = CogMatrix4MulCogVector3(c->view, (CogVector3){self->model.vector.w.x, self->model.vector.w.y, self->model.vector.w.z});
} else if(light->data->type == CogLightTypeDirectional) {
CogDirectionalLight l = (CogDirectionalLight)light->data;
CogVector4 camSpaceDirection = CogMatrix4MulVector4(c->view, (CogVector4){self->model.vector.z.x, self->model.vector.z.y, self->model.vector.z.z, 0.0f});
l->direction.x = camSpaceDirection.x;
l->direction.y = camSpaceDirection.y;
l->direction.z = camSpaceDirection.z;
} else if(light->data->type == CogLightTypeSpot) {
CogSpotLight l = (CogSpotLight)light->data;
l->position = CogMatrix4MulCogVector3(c->view, (CogVector3){self->model.vector.w.x, self->model.vector.w.y, self->model.vector.w.z});
CogVector4 camSpaceDirection = CogMatrix4MulVector4(c->view, (CogVector4){self->model.vector.z.x, self->model.vector.z.y, self->model.vector.z.z, 0.0f});
l->direction.x = camSpaceDirection.x;
l->direction.y = camSpaceDirection.y;
l->direction.z = camSpaceDirection.z;
}
}
CogListForEach(self->children, child, {
CogNodeUpdate(child, t);
});
}
void CogNodeBind(CogNode self, struct CogShader* shader) {
glUniformMatrix4fv(shader->uniforms.vertex.matrix.model, 1, GL_FALSE, (const float*)&self->model);
} | 34.172414 | 159 | 0.709048 | [
"vector",
"model",
"transform"
] |
866f3ad200f29f19d682cbd7a620e07faa7f19be | 328 | h | C | FaceWarrant/FaceWarrant/Main/Me/C/MyFaceGroup/FWFaceGroupEditVC.h | WeaponChan/FaceWarrant | 6cc8051ec5c51d6f88f85bae8cc515f52459941c | [
"MIT"
] | 1 | 2019-01-11T02:43:39.000Z | 2019-01-11T02:43:39.000Z | FaceWarrant/FaceWarrant/Main/Me/C/MyFaceGroup/FWFaceGroupEditVC.h | WeaponChan/FaceWarrant | 6cc8051ec5c51d6f88f85bae8cc515f52459941c | [
"MIT"
] | null | null | null | FaceWarrant/FaceWarrant/Main/Me/C/MyFaceGroup/FWFaceGroupEditVC.h | WeaponChan/FaceWarrant | 6cc8051ec5c51d6f88f85bae8cc515f52459941c | [
"MIT"
] | null | null | null | //
// FWFaceGroupEditVC.h
// FaceWarrantDel
//
// Created by LHKH on 2018/7/23.
// Copyright © 2018年 LHKH. All rights reserved.
//
#import "FWBaseViewController.h"
#import "FWFaceLibraryClassifyModel.h"
@interface FWFaceGroupEditVC : FWBaseViewController
@property(strong, nonatomic)FWFaceLibraryClassifyModel *model;
@end
| 23.428571 | 62 | 0.768293 | [
"model"
] |
8670e32695be3e7dbedc6f27f744dc74d57c74b2 | 1,813 | h | C | src/audio/audio_player.h | Df458/dfgame | 3e0312d6d027ff617c1be7c0d72309fcdfc461e2 | [
"Zlib"
] | 4 | 2017-06-26T16:52:34.000Z | 2021-11-14T20:37:19.000Z | src/audio/audio_player.h | Df458/dfgame | 3e0312d6d027ff617c1be7c0d72309fcdfc461e2 | [
"Zlib"
] | null | null | null | src/audio/audio_player.h | Df458/dfgame | 3e0312d6d027ff617c1be7c0d72309fcdfc461e2 | [
"Zlib"
] | null | null | null | #ifndef DF_AUDIO_PLAYER
#define DF_AUDIO_PLAYER
#include "audio/audio_player.hd"
#include "audio/audio_source.hd"
#include "math/vector.h"
// Creates a new audio player for the given source
audio_player audio_player_new(audio_source src);
// Gets/sets the player's playing status
bool audio_player_get_playing(audio_player player);
void audio_player_set_playing(audio_player player, bool playing);
// Gets/sets whether or not the player should loop audio when it finishes
bool audio_player_get_loop(audio_player player);
void audio_player_set_loop(audio_player player, bool loop);
// Gets/sets the position in the audio
float audio_player_get_position(audio_player player);
void audio_player_set_position(audio_player player, float pos);
// Gets/sets the position of the listener relative to the player
vec3 audio_player_get_translation(audio_player player);
void audio_player_set_translation(audio_player player, vec3 pos);
// Sets the minimum/maximum distances for volume purposes
void audio_player_set_distances(audio_player player, float reference_distance, float max_distance);
// Gets/sets the relative volume of the audio playback
float audio_player_get_gain(audio_player player);
void audio_player_set_gain(audio_player player, float gain);
// Gets the source that is playing
audio_source audio_player_get_source(audio_player player);
// Updates the player, buffering new audio data as needed
void audio_player_update(audio_player player, float dt);
// Frees the player and sets it to NULL to make it harder to double-free.
#define audio_player_free(p, d) { _audio_player_free(p, d); p = NULL; }
// Frees the player. NOTE: Don't call this function. Use the macro without
// the leading _ instead, as it also NULLs your pointer.
void _audio_player_free(audio_player player, bool deep);
#endif
| 37.770833 | 99 | 0.811914 | [
"vector"
] |
86722ca790a86f2a3cd32c3cb882aa60e94099a6 | 9,207 | h | C | uppdev/DrawOutputTest/DrawOutputTest.h | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | uppdev/DrawOutputTest/DrawOutputTest.h | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | uppdev/DrawOutputTest/DrawOutputTest.h | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #ifndef _DrawOutputTest_DrawOutputTest_h
#define _DrawOutputTest_DrawOutputTest_h
#include <CtrlLib/CtrlLib.h>
#include <PdfDraw/PdfDraw.h>
#include <plugin/cairo/CairoCtrl.h>
using namespace Upp;
#define LAYOUTFILE <DrawOutputTest/DrawOutputTest.lay>
#include <CtrlCore/lay.h>
class DrawOutputTest : public WithDrawOutputTestLayout<TopWindow>
{
typedef DrawOutputTest CLASSNAME;
private:
Drawing _drawing;
String _fileName;
int _currentTest;
Vector<Callback> _callbacks;
public:
DrawOutputTest()
{
CtrlLayout(*this, "Draw test");
previousButton <<= THISBACK(PreviousButtonClicked);
nextButton <<= THISBACK(NextButtonClicked);
savePdfButton <<= THISBACK(SavePdfButtonClicked);
saveSvgButton <<= THISBACK(SaveSvgButtonClicked);
_callbacks.Add(THISBACK(TestProportions));
_callbacks.Add(THISBACK(TestDrawLine));
_callbacks.Add(THISBACK(TestDrawPolyline));
_callbacks.Add(THISBACK(TestDrawRect));
_callbacks.Add(THISBACK(TestDrawImage));
_callbacks.Add(THISBACK(TestDrawEllipse));
_callbacks.Add(THISBACK(TestDrawText));
_callbacks.Add(THISBACK(TestOffset));
_callbacks.Add(THISBACK(TestFontMetrics));
_callbacks.Add(THISBACK(TestBasicDrawing));
_callbacks.Add(THISBACK(TestExcludeClip));
_currentTest = 0;
NavButtonClicked();
}
private:
void PreviousButtonClicked()
{
_currentTest--;
NavButtonClicked();
}
void NextButtonClicked()
{
_currentTest++;
NavButtonClicked();
}
void NavButtonClicked()
{
previousButton.Enable(_currentTest > 0);
nextButton.Enable(_currentTest < _callbacks.GetCount() - 1);
_callbacks[_currentTest]();
}
void SavePdfButtonClicked()
{
Cairo c;
c.CreatePdfSurface(_fileName + ".pdf", 450, 450);
CairoDraw draw(c);
draw.DrawDrawing(0, 0, 450, 450, _drawing);
}
void SaveSvgButtonClicked()
{
Cairo c;
c.CreateSvgSurface(_fileName + ".svg", 450, 450);
CairoDraw draw(c);
draw.DrawDrawing(0, 0, 450, 450, _drawing);
}
void TestProportions() // Test0
{
DrawingDraw d(450, 450);
d.DrawEllipse(10, 10, 10, 10);
d.DrawEllipse(10, 100, 10, 10);
d.Offset(90, 0);
d.DrawEllipse(10, 10, 10, 10);
d.DrawEllipse(10, 100, 10, 10);
d.End();
d.DrawEllipse(100, 10, 10, 10, Red());
d.DrawEllipse(150, 10, 10, 10, Red());
d.Offset(0, 50);
d.DrawEllipse(100, 10, 10, 10, Red());
d.DrawEllipse(150, 10, 10, 10, Red());
d.End();
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestExcludeClip";
}
void TestDrawLine() // Test1
{
DrawingDraw d(450, 450);
for (int i = 0; i < 17; i++)
d.DrawLine(0 + (i * 13), (i + 1) * 25,
450 - (i * 13), (i + 1) * 25,
i);
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestDrawLine";
}
void TestDrawPolyline() // Test2
{
DrawingDraw d(450, 450);
Vector<Point> p;
p << Point(3, 3) << Point(200, 100) << Point(430, 25);
d.DrawPolyline(p, 1, Color(255, 0, 0));
p.Clear();
p << Point(6, 60) << Point(250, 150) << Point(420, 60);
d.DrawPolyline(p, 10, Color(0, 255, 0));
p.Clear();
p << Point(6, 100) << Point(250, 390) << Point(420, 100);
d.DrawPolyline(p, 15, Color(0, 255, 0), Color(0, 90, 0));
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestDrawPolyline";
}
void TestDrawRect() // Test3
{
DrawingDraw d(450, 450);
for (int i = 0; i < 50; i++)
d.DrawRect((i * 34) % 300, ((i + 14) * 15) % 300, (i * 40) % 450, (i * 142) % 450,
Color((i * 12 + 23) % 205, (i * 29 + 53) % 255, (i * 10 + 3) % 255));
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestDrawRect";
}
void TestDrawImage() // Test4
{
DrawingDraw d(450, 450);
d.DrawImage(40, 240, CtrlImg::save());
d.DrawImage(110, 210, 80, 80, CtrlImg::save());
d.DrawImage(240, 240, CtrlImg::save(), Blue);
d.DrawImage(310, 210, 80, 80, CtrlImg::save(), Blue);
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestDrawImage";
}
void TestDrawEllipse() // Test5
{
DrawingDraw d(450, 450);
for (int i = 1; i < 30; i++)
d.DrawEllipse((i * 34) % 300, ((i + 14) * 15) % 300, (i * 40) % 450, (i * 142) % 450,
Color((i * 12 + 23) % 205, (i * 29 + 53) % 255, (i * 10 + 3) % 255));
d.DrawEllipse(40, 60, 36, 200, Color(23, 24, 25), 3, Color(255, 255, 123));
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestDrawEllipse";
}
void TestDrawText() // Test6
{
DrawingDraw d(450, 450);
Font font = StdFont(15);
d.DrawText(10, 10, "Standard text", font);
font.FaceName("Arial");
d.DrawText(10, 40, "Arial text: T U i I AVAVAVAVAVAVAVA", font);
font.FaceName("Times New Roman");
d.DrawText(10, 70, "Times New Roman text: T U i I AVAVAVAVAVAVAVA", font);
font.Underline();
d.DrawText(10, 100, "Underlined text", font);
font.Italic();
d.DrawText(10, 130, "Italic text", font);
font.Strikeout();
d.DrawText(10, 160, "Strikeout text", font);
font.Bold();
d.DrawText(10, 190, "Bold text", font);
d.DrawText(10, 220, "Colored text", font, Color(123, 23, 248));
d.DrawText(10, 250, "Special characters äöüßéàè#°§¬|¢", StdFont(15));
d.DrawText(300, 230, 3200, "Rotated text", StdFont(15));
d.DrawText(10, 400, "abcdefghijklmnopqrstuvwxyz", Arial(40), Color(0, 0, 255));
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestDrawText";
}
void DoPainting(Draw& d)
{
d.DrawEllipse(0, 0, 100, 30, WhiteGray(), 1, Cyan);
d.DrawText(0, 0, "Hello<w\"orld", Roman(30).Bold());
}
void TestOffset() // Test7
{
DrawingDraw d(450, 450);
d.DrawRect(d.GetSize(), White());
DoPainting(d);
d.Offset(30, 50);
DoPainting(d);
d.End();
d.Offset(20, 100);
d.Clip(5, 5, 40, 20);
DoPainting(d);
d.End();
d.End();
d.Clipoff(10, 150, 60, 20);
DoPainting(d);
d.End();
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestOffset";
}
void TestFontMetrics() // Test8
{
DrawingDraw d(450, 450);
d.Offset(10, 50);
const char *text = "Programming is fun";
Font fnt = StdFont(40);
FontInfo fi = fnt.Info();
int x = 0;
Vector<int> dx;
for(const char *s = text; *s; s++)
{
int width = fi[*s];
d.DrawRect(x, 0, width - 1, fi.GetAscent(), Color(255, 255, 200));
d.DrawRect(x, fi.GetAscent(), width - 1, fi.GetDescent(), Color(255, 200, 255));
d.DrawRect(x + width - 1, 0, 1, fi.GetHeight(), Black());
dx.Add(width + 4);
x += width;
}
d.DrawRect(0, 0, 4, 4, Black());
d.DrawText(0, 0, text, fnt);
d.DrawText(0, 70, text, fnt, Blue(), dx.GetCount(), dx.Begin());
d.End();
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestFontMetrics";
}
void TestBasicDrawing() // Test9
{
DrawingDraw d(450, 450);
d.DrawRect(10, 10, 60, 80, Green());
d.DrawLine(100, 10, 160, 80, 0, Black());
d.DrawLine(160, 10, 100, 80, 4, Red());
d.DrawLine(160, 40, 100, 50, PEN_DOT, Red());
d.DrawEllipse(210, 20, 80, 60, Blue());
d.DrawEllipse(310, 20, 80, 60, LtBlue(), 5, Red());
d.DrawArc(RectC(410, 20, 80, 60), Point(10, 10), Point(450, 80), 3, Cyan);
Vector<Point> p;
p << Point(30, 110) << Point(60, 180) << Point(10, 150) << Point(70, 150);
d.DrawPolyline(p, 4, Black);
p.Clear();
p << Point(130, 110) << Point(160, 180) << Point(110, 150) << Point(170, 120)
<< Point(130, 110);
d.DrawPolygon(p, Blue);
p.Clear();
p << Point(230, 110) << Point(260, 180) << Point(210, 150) << Point(270, 120)
<< Point(230, 110);
d.DrawPolygon(p, Cyan, 5, Magenta);
d.DrawImage(40, 240, CtrlImg::save());
d.DrawImage(110, 210, 80, 80, CtrlImg::save());
d.DrawImage(240, 240, CtrlImg::save(), Blue);
d.DrawImage(310, 210, 80, 80, CtrlImg::save(), Blue);
d.DrawText(20, 330, "Hello world!");
d.DrawText(120, 330, "Hello world!", Arial(15).Bold());
d.DrawText(220, 330, "Hello world!", Roman(15).Italic(), Red);
d.DrawText(320, 380, 400, "Hello world!", Courier(15).Underline());
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestBasicDrawing";
}
void TestExcludeClip() // Test10
{
DrawingDraw d(450, 450);
d.Clipoff(60, 60, 200, 200);
d.ExcludeClip(120, 20, 200, 30);
d.IntersectClip(10, 10, 200, 100);
d.DrawRect(10, 10, 400, 400, Color(255, 0, 0));
d.DrawEllipse(40, 60, 36, 200, Color(23, 24, 25), 3, Color(255, 255, 123));
d.DrawEllipse(100, 80, 30, 100, Color(77, 44, 11), 6, Color(128, 128, 128));
d.End();
_drawing = d;
_cairoCtrl.Set(&_drawing);
_picture.Set(_drawing);
_fileName = "TestExcludeClip";
}
};
#endif
| 25.504155 | 90 | 0.594113 | [
"vector"
] |
8676b603848a9fee34b4e3180c22520a3e9302d6 | 3,177 | h | C | updater/include/updater/updater.h | imranpopz/android_bootable_recovery-1 | ec4512ad1e20f640b3dcd6faf8c04cae711e4f30 | [
"Apache-2.0"
] | null | null | null | updater/include/updater/updater.h | imranpopz/android_bootable_recovery-1 | ec4512ad1e20f640b3dcd6faf8c04cae711e4f30 | [
"Apache-2.0"
] | null | null | null | updater/include/updater/updater.h | imranpopz/android_bootable_recovery-1 | ec4512ad1e20f640b3dcd6faf8c04cae711e4f30 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include <stdio.h>
#include <memory>
#include <string>
#include <string_view>
#include <ziparchive/zip_archive.h>
#include "edify/expr.h"
#include "edify/updater_interface.h"
#include "otautil/error_code.h"
#include "otautil/sysutil.h"
class Updater : public UpdaterInterface {
public:
explicit Updater(std::unique_ptr<UpdaterRuntimeInterface> run_time)
: runtime_(std::move(run_time)) {}
~Updater() override;
// Memory-maps the OTA package and opens it as a zip file. Also sets up the command pipe and
// UpdaterRuntime.
bool Init(int fd, const std::string_view package_filename, bool is_retry);
// Parses and evaluates the updater-script in the OTA package. Reports the error code if the
// evaluation fails.
bool RunUpdate();
// Writes the message to command pipe, adds a new line in the end.
void WriteToCommandPipe(const std::string_view message, bool flush = false) const override;
// Sends over the message to recovery to print it on the screen.
void UiPrint(const std::string_view message) const override;
std::string FindBlockDeviceName(const std::string_view name) const override;
UpdaterRuntimeInterface* GetRuntime() const override {
return runtime_.get();
}
ZipArchiveHandle GetPackageHandle() const override {
return package_handle_;
}
std::string GetResult() const override {
return result_;
}
uint8_t* GetMappedPackageAddress() const override {
return mapped_package_.addr;
}
size_t GetMappedPackageLength() const override {
return mapped_package_.length;
}
private:
friend class UpdaterTestBase;
friend class UpdaterTest;
// Where in the package we expect to find the edify script to execute.
// (Note it's "updateR-script", not the older "update-script".)
static constexpr const char* SCRIPT_NAME = "META-INF/com/google/android/updater-script";
// Reads the entry |name| in the zip archive and put the result in |content|.
bool ReadEntryToString(ZipArchiveHandle za, const std::string& entry_name, std::string* content);
// Parses the error code embedded in state->errmsg; and reports the error code and cause code.
void ParseAndReportErrorCode(State* state);
std::unique_ptr<UpdaterRuntimeInterface> runtime_;
MemMapping mapped_package_;
ZipArchiveHandle package_handle_{ nullptr };
std::string updater_script_;
bool is_retry_{ false };
std::unique_ptr<FILE, decltype(&fclose)> cmd_pipe_{ nullptr, fclose };
std::string result_;
std::vector<std::string> skipped_functions_;
};
| 32.752577 | 99 | 0.743154 | [
"vector"
] |
8681a7f1443da55ebff81f7990f39c9ba347cf83 | 6,893 | h | C | Core/SGCoreCpp/incl/HandPose.h | dic-iit/SenseGlove-API | baad587d4e165d7bfafd7f0c8ee6a1ce8ad651d6 | [
"MIT"
] | 4 | 2020-08-27T13:14:46.000Z | 2021-08-30T03:04:32.000Z | Core/SGCoreCpp/incl/HandPose.h | dic-iit/SenseGlove-API | baad587d4e165d7bfafd7f0c8ee6a1ce8ad651d6 | [
"MIT"
] | 12 | 2020-03-26T16:17:21.000Z | 2021-11-20T18:58:56.000Z | Core/SGCoreCpp/incl/HandPose.h | dic-iit/SenseGlove-API | baad587d4e165d7bfafd7f0c8ee6a1ce8ad651d6 | [
"MIT"
] | 4 | 2020-03-16T14:50:50.000Z | 2021-08-04T01:45:03.000Z | // ----------------------------------------------------------------------------------
// Data class containing all variables to draw or analyze a virtual hand
// in different formats.
// @author: Max Lammers
// ----------------------------------------------------------------------------------
#pragma once
#include "SGCore.h"
#include <vector>
#include <string>
#include "Vect3D.h"
#include "Quat.h"
#include "Fingers.h"
#include "BasicHandModel.h"
namespace SGCore
{
/// <summary> Contains all variables required to draw or analyze a virtual hand. </summary>
class SGCORE_API HandPose
{
protected:
///<summary> Returns the total flexion of a specific finger as a value between 0 (fully extended) and 1 (fully flexed). </summary>
///<remarks> Separate function because we use it multiple times, protected because we don't want indexOutOfRange exceptions. </remarks>
float GetNormalizedFlexion(int finger, bool clamp01 = true);
public:
//---------------------------------------------------------------------------------------------------------------------
// Properties
///<summary> Whether or not this HandPose was created for be a right- or left hand. </summary>
bool isRight;
///<summary> Positions of all hand joints relative to the Sense Glove origin. From thumb to pinky, proximal to distal. </summary>
std::vector< std::vector<Kinematics::Vect3D> > jointPositions;
///<summary> Quaternion rotations of all hand joints. From thumb to pinky, proximal to distal. </summary>
std::vector< std::vector<Kinematics::Quat> > jointRotations;
///<summary> Euler representations of all possible hand angles. From thumb to pinky, proximal to distal. </summary>
std::vector< std::vector<Kinematics::Vect3D> > handAngles;
//---------------------------------------------------------------------------------------------------------------------
// Construction
/// <summary> Default Constructor. </summary>
HandPose();
/// <summary> Default Destructor. </summary>
~HandPose();
/// <summary> Create a new instance of HandPose. </summary>
HandPose(bool right, std::vector< std::vector<Kinematics::Vect3D> > jointPos,
std::vector< std::vector<Kinematics::Quat> > jointRot,
std::vector< std::vector<Kinematics::Vect3D> > hAngles);
/// <summary> Returns true of these two handposes are roughly equal. </summary>
bool Equals(HandPose other);
//---------------------------------------------------------------------------------------------------------------------
// Serialization
std::string ToString(bool shortFormat = false);
///<summary> Serialize this HandProfile into a string representation </summary>
std::string Serialize();
///<summary> Deserialize a HandProfile back into useable values. </summary>
static HandPose Deserialize(std::string serializedString);
//---------------------------------------------------------------------------------------------------------------------
// Formats
//GetFormat (animator), GetFormat (MoCap), etc?
///<summary> Returns the total flexion of a specific finger as a value between 0 (fully extended) and 1 (fully flexed). </summary>
///<remarks> Useful for animation or for detecting gestures </remarks>
float GetNormalizedFlexion(Finger finger, bool clamp01 = true);
///<summary> Returns the total flexion the fingers as a value between 0 (fully extended) and 1 (fully flexed). </summary>
///<remarks> Useful for animation or for detecting gestures </remarks>
std::vector<float> GetNormalizedFlexion(bool clamp01 = true);
//---------------------------------------------------------------------------------------------------------------------
// Generating Poses
/// <summary> Generate a HandPose based on articulation angles (handAngles). </summary>
/// <param name="handAngles"></param>
/// <param name="rightHanded"></param>
/// <param name="handDimensions"></param>
/// <returns></returns>
static HandPose FromHandAngles(std::vector<std::vector<Kinematics::Vect3D>>& handAngles, bool rightHanded, Kinematics::BasicHandModel& handDimensions);
/// <summary> Generate a HandPose based on articulation angles (handAngles), with a default HandModel. </summary>
/// <param name="handAngles"></param>
/// <param name="rightHanded"></param>
/// <returns></returns>
static HandPose FromHandAngles(std::vector<std::vector<Kinematics::Vect3D>>& handAngles, bool rightHanded);
/// <summary> Create a new instance of a left or right handed Pose that is "idle"; in a neutral position. </summary>
/// <param name="rightHand"></param>
/// <param name="handDimensions"></param>
/// <returns></returns>
static HandPose DefaultIdle(bool rightHand, Kinematics::BasicHandModel& handDimensions);
/// <summary> Create a new instance of a left or right handed Pose that is "idle"; in a neutral position. </summary>
/// <param name="rightHand"></param>
/// <returns></returns>
static HandPose DefaultIdle(bool rightHand);
/// <summary> Generates a HandPose representing an 'open hand', used in calibration to determine finger extension. </summary>
/// <param name="rightHand"></param>
/// <param name="handDimensions"></param>
/// <returns></returns>
static HandPose FlatHand(bool rightHand, Kinematics::BasicHandModel& handDimensions);
/// <summary> Generates a HandPose representing an 'open hand', used in calibration to determine finger extension. </summary>
/// <param name="rightHand"></param>
/// <returns></returns>
static HandPose FlatHand(bool rightHand);
/// <summary> Generates a HandPose representing a 'thumbs up', used in calibration to determine finger flexion, thumb extension and adduction. </summary>
/// <param name="rightHand"></param>
/// <param name="handDimensions"></param>
/// <returns></returns>
static HandPose ThumbsUp(bool rightHand, Kinematics::BasicHandModel& handDimensions);
/// <summary> Generates a HandPose representing a 'thumbs up', used in calibration to determine finger flexion, thumb extension and adduction. </summary>
/// <param name="rightHand"></param>
/// <returns></returns>
static HandPose ThumbsUp(bool rightHand);
/// <summary> Generates a HandPose representing a 'fist', used in calibration to determine, thumb flexion and abduction. </summary>
/// <param name="rightHand"></param>
/// <param name="handDimensions"></param>
/// <returns></returns>
static HandPose Fist(bool rightHand, Kinematics::BasicHandModel& handDimensions);
/// <summary> Generates a HandPose representing a 'fist', used in calibration to determine, thumb flexion and abduction. </summary>
/// <param name="rightHand"></param>
/// <returns></returns>
static HandPose Fist(bool rightHand);
};
}
| 44.75974 | 161 | 0.6215 | [
"vector"
] |
868b67db611f6124958b3b544925869d934e7b68 | 3,306 | h | C | FVACommonLib/fvacommonlib.h | dimanikulin/fva | 372c91edd2d188ab9fe73b8f83e00a68fc3fb76e | [
"RSA-MD"
] | null | null | null | FVACommonLib/fvacommonlib.h | dimanikulin/fva | 372c91edd2d188ab9fe73b8f83e00a68fc3fb76e | [
"RSA-MD"
] | 10 | 2022-02-06T15:18:17.000Z | 2022-02-22T20:10:20.000Z | FVACommonLib/fvacommonlib.h | dimanikulin/fva | 372c91edd2d188ab9fe73b8f83e00a68fc3fb76e | [
"RSA-MD"
] | null | null | null | /*!
* \file fvacommonlib.h
* \copyright Copyright 2021 FVA Software. All rights reserved. This file is released under the XXX License.
* \author Dima Nikulin.
* \version 0.29
* \date 2014-2021
*/
#ifndef FVACOMMONLIB_H
#define FVACOMMONLIB_H
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QVector>
#include <QtCore/QDateTime>
#include <QtCore/QVariantMap>
#include "fvadevice.h"
#include "fvaexitcodes.h"
#include "fvafmtcontext.h"
/*!
* \brief it converts file extention to file type if it is possible
*/
FVA_FS_TYPE fvaConvertFileExt2FileType ( const QString& type );
/*!
* \brief it answers if file is internal purpose for
*/
bool fvaIsInternalFile( const QString& fileName );
/*!
* \brief it answers if file is supported type of (by its file extention)
*/
bool fvaIsFVAFile(const QString& extention );
/*!
* \brief it answers if dir is internal one
*/
bool fvaIsInternalDir(const QString& dir);
/*!
* \brief it tries to parse dir name into period of date
* \param dirName directory name to be parsed
* \param from to fill as a date from
* \param to - to fill as a date to
* \param ctx - to use formatting options from
* \returns it returns code of error if any or FVA_NO_ERROR if parsing was successful
*/
FVA_EXIT_CODE fvaParseDirName(const QString& dirName, QDateTime& from, QDateTime& to, const FvaFmtContext& ctx );
/*!
* \brief it tries to parse file name into date
* \param fileName file name to be parsed
* \param date a date to be filled up
* \param ctx - to use formatting options from
* \returns it returns code of error if any or FVA_NO_ERROR if parsing was successful
*/
FVA_EXIT_CODE fvaParseFileName(const QString& fileName, QDateTime& date, const FvaFmtContext& ctx);
/*!
* \brief it returns device id from map loaded
* \param deviceIds a map to be find in
* \param pathToFile path to file to get device name from
* \param deviceName contains device link name
* \returns it returns map of devices found or empty map if not
*/
DEVICE_MAP fvaGetDeviceMapForImg(const DEVICE_MAP& deviceMap, const QString& pathToFile, QString& deviceName);
/*!
* \brief it convert identifiers list from string to int vector
*/
QVector<unsigned int> fvaStringToIds(const QString& strList);
/*!
* \brief it removes the dir if there is no content inside
* \param dirPath - path to folder to remove
* \returns it returns true if folder has been deleted, otherwize it return false
*/
bool fvaRemoveDirIfEmpty(const QString& dirPath);
/*!
* \brief it creates directory if it does not exist
* \param dirPath - dir path to create
* \returns it returns FVA_EXIT_CODE
*/
FVA_EXIT_CODE fvaCreateDirIfNotExists(const QString& dirPath);
/*!
* \brief it simply writes the QString list to a file
* \param path - a file path to write strList into
* \param strList - a list of QString to be written
* \returns it returns FVA_EXIT_CODE
*/
FVA_EXIT_CODE fvaSaveStrListToFile(const QString& path, const QList<QString>& strList);
/*!
* \brief it simply gets the QString list from a file
* \param path - a file path to get strList from
* \param strList - a list of QString to be filledUp
* \returns it returns FVA_EXIT_CODE
*/
FVA_EXIT_CODE fvaLoadStrListFromFile(const QString& path, QList<QString>& strList);
#endif // FVACOMMONLIB_H
| 30.897196 | 113 | 0.742589 | [
"vector"
] |
868e61301a90bb439a726633533deb7ed7a67e42 | 6,146 | h | C | forts/native/fortsgeneralcontainer_m.h | thomasms/forts | e2677fc3505bb8cf1ad3f38aaf256093c2afefe9 | [
"BSD-3-Clause"
] | 1 | 2018-04-02T20:53:29.000Z | 2018-04-02T20:53:29.000Z | forts/native/fortsgeneralcontainer_m.h | thomasms/forts | e2677fc3505bb8cf1ad3f38aaf256093c2afefe9 | [
"BSD-3-Clause"
] | null | null | null | forts/native/fortsgeneralcontainer_m.h | thomasms/forts | e2677fc3505bb8cf1ad3f38aaf256093c2afefe9 | [
"BSD-3-Clause"
] | null | null | null |
public :: MACRO_CONTAINER_STORE_NAME !< Store array to unit
public :: MACRO_CONTAINER_RETRIEVE_NAME !< Fill array from unit
!> A dynamic container object which can append and reset values
type, public :: MACRO_CLASS_NAME
private
integer(ki4) :: count = 0_ki4
MACRO_CONTAINER_TYPE(MACRO_CONTAINER_KIND), allocatable :: values(:)
integer(ki4), public :: scalefactor = 2_ki4
contains
procedure :: reset !> Resets data
procedure :: length !> Gets the number of entries in array
procedure :: fill !> Fills the values from another array
procedure :: set !> Set the value for a given key
procedure :: get !> Get the value for a given key
procedure :: append !> Append a new key
procedure :: iterate !> Iterate through the container
procedure, private :: cleanup !> Deallocate
final :: finalize
end type MACRO_CLASS_NAME
contains
!> reset values
subroutine reset(this)
class(MACRO_CLASS_NAME), intent(inout) :: this
! Cleanup
call this%cleanup()
end subroutine reset
!> Fills the values from another array
!! allocates values but does not deallocate tocopy
subroutine fill(this, tocopy)
class(MACRO_CLASS_NAME), intent(inout) :: this
MACRO_CONTAINER_TYPE(MACRO_CONTAINER_KIND), intent(in) :: tocopy(:)
call this%cleanup()
this%count = size(tocopy)
allocate(this%values(1_ki4:this%count))
this%values(:) = tocopy(:)
end subroutine fill
!> get the number of entries
integer(ki4) function length(this)
class(MACRO_CLASS_NAME), intent(in) :: this
length = this%count
end function length
!> Iterate through the array
subroutine iterate(this, iterator_func)
class(MACRO_CLASS_NAME), intent(in) :: this
interface
subroutine iterator_func(value)
import MACRO_CONTAINER_KIND
MACRO_CONTAINER_TYPE(MACRO_CONTAINER_KIND), intent(in) :: value
end subroutine iterator_func
end interface
integer(ki4) :: i
do i = 1, this%count
call iterator_func(this%values(i))
end do
end subroutine iterate
!> Set value
subroutine set(this, index, value)
class(MACRO_CLASS_NAME), intent(inout) :: this
integer(ki4), intent(in) :: index
MACRO_CONTAINER_TYPE(MACRO_CONTAINER_KIND), intent(in) :: value
! if index out of range then do nothing
if(index > 0 .and. index <= this%count) then
this%values(index) = value
endif
end subroutine set
!> Get value
function get(this, index) result(value)
class(MACRO_CLASS_NAME), intent(in) :: this
integer(ki4), intent(in) :: index
MACRO_CONTAINER_TYPE(MACRO_CONTAINER_KIND) :: value
! if index out of range then return undefined
if(index > 0 .and. index <= this%count) then
value = this%values(index)
endif
end function get
!> cleanup
subroutine cleanup(this)
class(MACRO_CLASS_NAME), intent(inout) :: this
! Cleanup
if(this%count > 0 .and. allocated(this%values))then
deallocate(this%values)
this%count = 0
endif
end subroutine cleanup
!> Append a new value
subroutine append(this, value)
class(MACRO_CLASS_NAME), intent(inout) :: this
MACRO_CONTAINER_TYPE(MACRO_CONTAINER_KIND), intent(in) :: value
MACRO_CONTAINER_TYPE(MACRO_CONTAINER_KIND), allocatable :: values_tmp(:)
integer(ki4) :: prevcount
integer(ki4) :: prevsize
integer(ki4) :: newsize
! the actual number of items appended
prevcount = this%count
! the actual size of the container - not necessarily the same as the count
prevsize = 0_ki4
if(allocated(this%values))then
prevsize = size(this%values)
end if
if(prevcount >= prevsize)then
newsize = max(prevsize*this%scalefactor, prevsize+1_ki4)
allocate(values_tmp(1_ki4:newsize))
if(prevsize > 0_ki4)then
values_tmp(1_ki4:prevsize) = this%values
end if
call move_alloc(values_tmp, this%values)
end if
this%count = this%count + 1_ki4
this%values(this%count) = value
end subroutine append
!> finalize
subroutine finalize(this)
type(MACRO_CLASS_NAME), intent(inout) :: this
call this%cleanup()
end subroutine finalize
!> Subroutine to write container array to a unit
subroutine MACRO_CONTAINER_STORE_NAME(container, storeunit)
type(MACRO_CLASS_NAME), intent(in) :: container
integer(ki4), intent(in) :: storeunit
write(storeunit) container%count
if(container%count > 0) then
write(storeunit) container%values
end if
end subroutine MACRO_CONTAINER_STORE_NAME
!> Subroutine to retrieve container array from a unit
subroutine MACRO_CONTAINER_RETRIEVE_NAME(container, retrieveunit)
type(MACRO_CLASS_NAME), intent(inout) :: container
integer(ki4), intent(in) :: retrieveunit
integer(ki4) :: len_array
call container%cleanup()
read(retrieveunit) len_array
if(len_array > 0_ki4) then
container%count = len_array
allocate(container%values(1_ki4:len_array))
read(retrieveunit) container%values
end if
end subroutine MACRO_CONTAINER_RETRIEVE_NAME
| 33.584699 | 102 | 0.578913 | [
"object"
] |
868f828cebf0ea791bcf524661e5e142abd76312 | 6,784 | h | C | layer2.h | codercold/layer2 | 42cad83b3ce6a2e575130c397657a211d2560e2a | [
"BSD-2-Clause"
] | 13 | 2015-03-11T14:25:13.000Z | 2021-09-12T15:02:33.000Z | layer2.h | pabit/layer2 | 42cad83b3ce6a2e575130c397657a211d2560e2a | [
"BSD-2-Clause"
] | 1 | 2019-09-23T08:37:44.000Z | 2019-09-23T08:37:44.000Z | layer2.h | pabit/layer2 | 42cad83b3ce6a2e575130c397657a211d2560e2a | [
"BSD-2-Clause"
] | 8 | 2015-04-29T02:51:28.000Z | 2020-04-11T17:05:20.000Z | /* layer2.h - layer2 core definitions
*
* Copyright (c) 2005 Vivek Mohan <vivek@sig9.com>
* All rights reserved.
* See (LICENSE)
*/
#ifndef _LAYER2_H_
#define _LAYER2_H_
#include <libnet.h>
#include <pcap.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
/* ----------------------------------------------------------------------------
* L2_PROTO_NUM This is the protocol number used by L2 to transport a
* frame from one border gateway to another.
* L2_FILTER_BUFSIZ Buffer size of a filter rule associated with a route.
* ----------------------------------------------------------------------------
*/
#define L2_PROTO_NUM 64
#define L2_FILTER_BUFSIZ 256
/* ----------------------------------------------------------------------------
* l2_route_t - Routing information associated with a interface.
*
* dst_addr: The destination address of the packet to be routed.
* msk_addr: The mask associated with the address.
* bgw_addr: Border gateway address.
* iface: Pointer to an interface object.
* eth_proto_arp: Non-zero, filter ARP packets.
* eth_proto_rarp: Non-zero, filter REVARP packets.
* eth_proto_dec: Non-zero, filter DEC packets.
* filter: Pcap filter rule for this route.
* next: Pointer to the next object for linked lists.
* ----------------------------------------------------------------------------
*/
typedef struct l2_route_t
{
u_long dst_addr;
u_long msk_addr;
u_long bgw_addr;
struct l2_iface_t* iface;
int eth_proto_arp;
int eth_proto_rarp;
int eth_proto_dec;
char filter[L2_FILTER_BUFSIZ];
struct l2_route_t* next;
} l2_route_t;
/* ----------------------------------------------------------------------------
* l2_iface_t - Interface object. This stucture defines an object associated
* with an interface that participates in this program.
*
* dev_name: Interface device name, eg "eth0", "eth1", "tap0" etc.
* net_addr: network address of the interface.
* msk_addr: net msk_addr of interface.
* pcap_desc: This is the libpcap pcap_t context block associated with
* the interface.
* ll_desc: The libnet link layer interface structure.
* mutex: Mutext lock for exclusive iface write access.
* next: 'next' for linked lists.
* route_head: route rules list head.
* route_tail: route rules list tail.
* ----------------------------------------------------------------------------
*/
typedef struct l2_iface_t
{
char dev_name[32];
bpf_u_int32 net_addr;
bpf_u_int32 msk_addr;
pcap_t* pcap_desc;
libnet_t* ll_desc;
pthread_mutex_t mutex;
pthread_t thread;
libnet_ptag_t ptag;
struct l2_route_t* route_head;
struct l2_route_t* route_tail;
unsigned int route_cnt;
struct l2_iface_t* next;
} l2_iface_t;
/* ----------------------------------------------------------------------------
* l2_frame_t - Holds essential data extracted from an ether frame. This is for
* internal use, and does not map any protocol structures.
*
* frame_ptr: Points to the packet in memory.
* size: Size of Frame.
* eth_header: Points to the ether header.
* eth_type: Ethernet type (IP/ARP/RARP/DEC)
* eth_addr_src: Source Ethernet address.
* eth_addr_dst: Destination Ethernet address.
* arp: Points to the arp header if the protocol is ARP.
* ip_header: Points to ip header.
* ip_proto: The upper layer protocol for the IP packet.
* ip_len: Overall length of the IP packet.
* ip_dst_addr: Destination IP Address of IP Packet.
* ip_src_addr: Source IP Address of IP Packet.
* payload: Pointer to the packet payload.
* ----------------------------------------------------------------------------
*/
typedef struct l2_frame_t
{
void* frame_ptr;
size_t size;
struct ether_header* eth_header;
u_int16_t eth_type;
char eth_addr_src[32];
char eth_addr_dst[32];
struct ether_arp* arp;
struct ip* ip_header;
u_int8_t ip_proto;
u_short ip_len;
u_long ip_dst_addr;
u_long ip_src_addr;
const u_char* payload;
} l2_frame_t;
/* ----------------------------------------------------------------------------
* Global functions. Prefix = l2_
* ----------------------------------------------------------------------------
*/
extern int l2_init();
extern l2_iface_t* l2_dev_to_iface(const char*);
extern l2_iface_t* l2_add_iface(char*);
extern l2_route_t* l2_add_route(l2_iface_t*, u_long, u_long, u_long, l2_iface_t*, int, int, int);
extern int l2_set_filters();
extern int l2_route();
extern void l2_deinit();
/* ----------------------------------------------------------------------------
* ntop() - Converts an ip address in network form to presentation form.
* - ip: The ip address in network byte order.
* - buf: The buffer to which the converted form is to be stored.
* - Returns, pointer to buf if successful else NULL.
* ! Thread Safe.
* ! Assumes buf is atleast INET_ADDRSTRLEN bytes long.
* ----------------------------------------------------------------------------
*/
static inline char* ntop(u_long ip, char* buf)
{
struct in_addr in;
in.s_addr = ip;
if (inet_ntop(AF_INET, (const void *) &in, buf, INET_ADDRSTRLEN) == NULL)
return(NULL);
return buf;
}
/* ----------------------------------------------------------------------------
* pton() - Converts an ip address in presentation form to network form.
* - buf: The buffer which contains the ip address in presentation form
* - ip: pointer to u_long to which ip address will be stored.
* - Returns, pointer tp ip address in network byte order if successful
* else NULL.
* ! Thread Safe.
* ----------------------------------------------------------------------------
*/
static inline u_long* pton(char* buf, u_long* ip)
{
struct in_addr in;
if (inet_pton(AF_INET, buf, &in) <= 0)
return(NULL);
*ip = in.s_addr;
return ip;
}
/* ----------------------------------------------------------------------------
* _printd() - Print function for debugging.
* - line: Line number.
* - file: Source File Name.
* - fmt: Output format.
* ! NOT Thread Safe.
* ----------------------------------------------------------------------------
*/
static inline void _printd(unsigned int line, const char* file,
const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
printf("===> ");
#ifdef L2_VERBOSE_POS
printf("%s:%d ", file, line);
#endif
vprintf(fmt, ap);
printf("\n");
va_end(ap);
}
/* ----------------------------------------------------------------------------
* printd(): Wrapper for _printd();
* printd_r(): Thread safe version of printd().
* ----------------------------------------------------------------------------
*/
#ifdef L2_VERBOSE
# define printd(fmt, n...) _printd(__LINE__, __FILE__, fmt, ##n)
#else
# define printd(fmt, n...)
#endif
#endif
| 33.418719 | 97 | 0.565006 | [
"object"
] |
86944e2cdade88d5d24b6747805d560a98ca666e | 904 | h | C | sourcecode/Runtime/Loader.h | fabianmuehlboeck/monnom | 609b307d9fa9e6641443f34dbcc0b035b34d3044 | [
"BSD-3-Clause",
"MIT"
] | 2 | 2021-11-16T20:58:02.000Z | 2021-12-05T18:15:41.000Z | sourcecode/Runtime/Loader.h | fabianmuehlboeck/monnom | 609b307d9fa9e6641443f34dbcc0b035b34d3044 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | sourcecode/Runtime/Loader.h | fabianmuehlboeck/monnom | 609b307d9fa9e6641443f34dbcc0b035b34d3044 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <map>
#include "NomProgram.h"
#include "StringDict.h"
namespace Nom
{
namespace Runtime
{
class LibrarySource;
class LibraryVersion;
class Loader
{
private:
Loader();
mutable NomProgram program;
mutable StringDict<LibraryVersion *> libraries;
std::vector<LibrarySource *> sources;
public:
Loader(Loader&) = delete;
Loader(const Loader&) = delete;
Loader(Loader&&) = delete;
static const Loader * GetInstance() {
static const Loader instance;
return &instance;
}
~Loader();
/*
const NomClass * const GetClass(const std::string *libraryName, const std::string *name) const;*/
const LibraryVersion * GetLibrary(const std::string *libraryName) const;
//bool LoadAssemblyUnit(const std::string &name, NomProgram *parent) const;
//const Library *GetLibrary(const std::string &name) const;
};
}
}
| 21.023256 | 100 | 0.692478 | [
"vector"
] |
86b78474885f4a8a51532827f336564583d3c3db | 553 | h | C | include/grape/params/connection_list_params.h | sunnythree/JaverNN | 8c5dc803ac3e49b569a89118fcaf5d4ca6ec673b | [
"BSD-2-Clause"
] | 19 | 2019-11-09T08:51:21.000Z | 2022-03-25T07:55:45.000Z | include/grape/params/connection_list_params.h | sunnythree/JaverNN | 8c5dc803ac3e49b569a89118fcaf5d4ca6ec673b | [
"BSD-2-Clause"
] | null | null | null | include/grape/params/connection_list_params.h | sunnythree/JaverNN | 8c5dc803ac3e49b569a89118fcaf5d4ca6ec673b | [
"BSD-2-Clause"
] | 7 | 2019-11-19T14:20:43.000Z | 2022-03-25T18:36:34.000Z | #ifndef __GRAPE_CONNECTION_LIST_PARAMS_H__
#define __GRAPE_CONNECTION_LIST_PARAMS_H__
#include <cstdint>
#include <string>
#include <vector>
#include "cereal/archives/json.hpp"
#include "cereal/types/map.hpp"
#include "grape/params/connection_params.h"
namespace Grape{
class ConnectionListParams{
public:
std::vector<ConnectionParams> connection_list_;
template <class Archive>
void serialize( Archive & ar )
{
ar(cereal::make_nvp("connection_list",connection_list_));
}
};
}
#endif | 21.269231 | 69 | 0.701627 | [
"vector"
] |
b647a253c33007cf0d06da1872c9c3f7b730fc4d | 12,263 | h | C | thirdparty/sfs2x/Entities/Data/SFSObject.h | godot-addons/godot-sfs2x | a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1 | [
"MIT"
] | 2 | 2020-05-14T07:48:32.000Z | 2021-02-03T14:58:11.000Z | thirdparty/sfs2x/Entities/Data/SFSObject.h | godot-addons/godot-sfs2x | a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1 | [
"MIT"
] | 1 | 2020-05-28T16:39:20.000Z | 2020-05-28T16:39:20.000Z | thirdparty/sfs2x/Entities/Data/SFSObject.h | godot-addons/godot-sfs2x | a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1 | [
"MIT"
] | 2 | 2018-07-07T20:15:00.000Z | 2018-10-26T05:18:30.000Z | // ===================================================================
//
// Description
// Contains the definition of SFSObject
//
// Revision history
// Date Description
// 30-Nov-2012 First version
//
// ===================================================================
#ifndef __SFSObject__
#define __SFSObject__
#include "../../Protocol/Serialization/DefaultObjectDumpFormatter.h"
#include "../../Protocol/Serialization/DefaultSFSDataSerializer.h"
#include "ISFSObject.h"
#include "../../Util/StringFormatter.h"
#include <boost/exception/exception.hpp>
#include <boost/exception/all.hpp>
#include <boost/shared_ptr.hpp> // Boost Asio shared pointer
#include <boost/enable_shared_from_this.hpp> // Boost shared_ptr for this
#if defined(_MSC_VER)
#pragma warning(disable:4786) // STL library: disable warning 4786; this warning is generated due to a Microsoft bug
#endif
#include <string> // STL library: string object
#include <map> // STL library: map object
using namespace std; // STL library: declare the STL namespace
using namespace Sfs2X::Exceptions;
using namespace Sfs2X::Protocol::Serialization;
using namespace Sfs2X::Util;
namespace Sfs2X {
namespace Entities {
namespace Data {
/// <summary>
/// SFSObject
/// </summary>
/// <remarks>
/// <b>SFSObject</b> is used from server and client side to exchange data. It can be thought of a specialized Dictionary/Map object that can contain any type of data. <br/>
/// The advantage of using SFSObject is that you can fine tune the way your data will be transmitted over the network.<br/>
/// For instance, a number like 100 can be transmitted as a normal <b>integer</b> (which takes 32 bits) but also a <b>short</b> (16 bit) or even a <b>byte</b> (8 bit)
/// <para/>
/// <b>SFSObject</b> supports many primitive data types and related arrays of primitives. It also allows to serialize class instances and rebuild them on the Java side. <br/>
/// This is explained in greater detail in a separate document.
/// </remarks>
/// <seealso cref="SFSArray"/>
class DLLImportExport SFSObject : public ISFSObject, public boost::enable_shared_from_this<SFSObject>
{
public:
// -------------------------------------------------------------------
// Public methods
// -------------------------------------------------------------------
/// <summary>
/// Alternative static constructor that builds an SFSObject populated with the data found in the passed Object
/// </summary>
/// <param name="o">
/// A void pointer
/// </param>
/// <returns>
/// Pointer to a <see cref="SFSObject"/> instance
/// </returns>
static boost::shared_ptr<SFSObject> NewFromObject(boost::shared_ptr<void> o);
/// <summary>
/// Alternative static constructor that builds an SFSObject from a valid SFSObject binary representation
/// </summary>
/// <param name="ba">
/// Pointer to a <see cref="ByteArray"/> instance
/// </param>
/// <returns>
/// Pointer to a <see cref="SFSObject"/> instance
/// </returns>
static boost::shared_ptr<SFSObject> NewFromBinaryData(boost::shared_ptr<ByteArray> ba);
/// <summary>
/// Alternative static constructor
/// </summary>
/// <returns>
/// Pointer to a <see cref="SFSObject"/> instance
/// </returns>
static boost::shared_ptr<SFSObject> NewInstance();
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
SFSObject();
virtual ~SFSObject();
boost::shared_ptr<SFSDataWrapper> GetData(string key);
boost::shared_ptr<SFSDataWrapper> GetData(boost::shared_ptr<string> key);
//T GetValue<T>(string key);
boost::shared_ptr<bool> GetBool(string key);
boost::shared_ptr<bool> GetBool(boost::shared_ptr<string> key);
boost::shared_ptr<unsigned char> GetByte(string key);
boost::shared_ptr<unsigned char> GetByte(boost::shared_ptr<string> key);
boost::shared_ptr<short int> GetShort(string key);
boost::shared_ptr<short int> GetShort(boost::shared_ptr<string> key);
boost::shared_ptr<long int> GetInt(string key);
boost::shared_ptr<long int> GetInt(boost::shared_ptr<string> key);
boost::shared_ptr<long long> GetLong(string key);
boost::shared_ptr<long long> GetLong(boost::shared_ptr<string> key);
boost::shared_ptr<float> GetFloat(string key);
boost::shared_ptr<float> GetFloat(boost::shared_ptr<string> key);
boost::shared_ptr<double> GetDouble(string key);
boost::shared_ptr<double> GetDouble(boost::shared_ptr<string> key);
boost::shared_ptr<string> GetUtfString(string key);
boost::shared_ptr<string> GetUtfString(boost::shared_ptr<string> key);
boost::shared_ptr<string> GetText(string key);
boost::shared_ptr<string> GetText(boost::shared_ptr<string> key);
boost::shared_ptr<vector<unsigned char> > GetArray(string key);
boost::shared_ptr<vector<unsigned char> > GetArray(boost::shared_ptr<string> key);
boost::shared_ptr<vector<bool> > GetBoolArray(string key);
boost::shared_ptr<vector<bool> > GetBoolArray(boost::shared_ptr<string> key);
boost::shared_ptr<ByteArray> GetByteArray(string key);
boost::shared_ptr<ByteArray> GetByteArray(boost::shared_ptr<string> key);
boost::shared_ptr<vector<short int> > GetShortArray(string key);
boost::shared_ptr<vector<short int> > GetShortArray(boost::shared_ptr<string> key);
boost::shared_ptr<vector<long int> > GetIntArray(string key);
boost::shared_ptr<vector<long int> > GetIntArray(boost::shared_ptr<string> key);
boost::shared_ptr<vector<long long> > GetLongArray(string key);
boost::shared_ptr<vector<long long> > GetLongArray(boost::shared_ptr<string> key);
boost::shared_ptr<vector<float> > GetFloatArray(string key);
boost::shared_ptr<vector<float> > GetFloatArray(boost::shared_ptr<string> key);
boost::shared_ptr<vector<double> > GetDoubleArray(string key);
boost::shared_ptr<vector<double> > GetDoubleArray(boost::shared_ptr<string> key);
boost::shared_ptr<vector<string> > GetUtfStringArray(string key);
boost::shared_ptr<vector<string> > GetUtfStringArray(boost::shared_ptr<string> key);
boost::shared_ptr<ISFSArray> GetSFSArray(string key);
boost::shared_ptr<ISFSArray> GetSFSArray(boost::shared_ptr<string> key);
boost::shared_ptr<ISFSObject> GetSFSObject(string key);
boost::shared_ptr<ISFSObject> GetSFSObject(boost::shared_ptr<string> key);
void PutNull(string key);
void PutNull(boost::shared_ptr<string> key);
void PutBool(string key, boost::shared_ptr<bool> val);
void PutBool(boost::shared_ptr<string> key, boost::shared_ptr<bool> val);
void PutBool(string key, bool val);
void PutBool(boost::shared_ptr<string> key, bool val);
void PutByte(string key, boost::shared_ptr<unsigned char> val);
void PutByte(boost::shared_ptr<string> key, boost::shared_ptr<unsigned char> val);
void PutByte(string key, unsigned char val);
void PutByte(boost::shared_ptr<string> key, unsigned char val);
void PutShort(string key, boost::shared_ptr<short int> val);
void PutShort(boost::shared_ptr<string> key, boost::shared_ptr<short int> val);
void PutShort(string key, short int val);
void PutShort(boost::shared_ptr<string> key, short int val);
void PutInt(string key, boost::shared_ptr<long int> val);
void PutInt(boost::shared_ptr<string> key, boost::shared_ptr<long int> val);
void PutInt(string key, long int val);
void PutInt(boost::shared_ptr<string> key, long int val);
void PutLong(string key, boost::shared_ptr<long long> val);
void PutLong(boost::shared_ptr<string> key, boost::shared_ptr<long long> val);
void PutLong(string key, long long val);
void PutLong(boost::shared_ptr<string> key, long long val);
void PutFloat(string key, boost::shared_ptr<float> val);
void PutFloat(boost::shared_ptr<string> key, boost::shared_ptr<float> val);
void PutFloat(string key, float val);
void PutFloat(boost::shared_ptr<string> key, float val);
void PutDouble(string key, boost::shared_ptr<double> val);
void PutDouble(boost::shared_ptr<string> key, boost::shared_ptr<double> val);
void PutDouble(string key, double val);
void PutDouble(boost::shared_ptr<string> key, double val);
void PutUtfString(string key, boost::shared_ptr<string> val);
void PutUtfString(boost::shared_ptr<string> key, boost::shared_ptr<string> val);
void PutUtfString(string key, string val);
void PutUtfString(boost::shared_ptr<string> key, string val);
void PutText(string key, boost::shared_ptr<string> val);
void PutText(boost::shared_ptr<string> key, boost::shared_ptr<string> val);
void PutText(string key, string val);
void PutText(boost::shared_ptr<string> key, string val);
void PutBoolArray(string key, boost::shared_ptr<vector<bool> > val);
void PutBoolArray(boost::shared_ptr<string> key, boost::shared_ptr<vector<bool> > val);
void PutByteArray(string key, boost::shared_ptr<ByteArray> val);
void PutByteArray(boost::shared_ptr<string> key, boost::shared_ptr<ByteArray> val);
void PutShortArray(string key, boost::shared_ptr<vector<short int> > val);
void PutShortArray(boost::shared_ptr<string> key, boost::shared_ptr<vector<short int> > val);
void PutIntArray(string key, boost::shared_ptr<vector<long int> > val);
void PutIntArray(boost::shared_ptr<string> key, boost::shared_ptr<vector<long int> > val);
void PutLongArray(string key, boost::shared_ptr<vector<long long> > val);
void PutLongArray(boost::shared_ptr<string> key, boost::shared_ptr<vector<long long> > val);
void PutFloatArray(string key, boost::shared_ptr<vector<float> > val);
void PutFloatArray(boost::shared_ptr<string> key, boost::shared_ptr<vector<float> > val);
void PutDoubleArray(string key, boost::shared_ptr<vector<double> > val);
void PutDoubleArray(boost::shared_ptr<string> key, boost::shared_ptr<vector<double> > val);
void PutUtfStringArray(string key, boost::shared_ptr<vector<string> > val);
void PutUtfStringArray(boost::shared_ptr<string> key, boost::shared_ptr<vector<string> > val);
void PutSFSArray(string key, boost::shared_ptr<ISFSArray> val);
void PutSFSArray(boost::shared_ptr<string> key, boost::shared_ptr<ISFSArray> val);
void PutSFSObject(string key, boost::shared_ptr<ISFSObject> val);
void PutSFSObject(boost::shared_ptr<string> key, boost::shared_ptr<ISFSObject> val);
void Put(string key, boost::shared_ptr<SFSDataWrapper> val);
void Put(boost::shared_ptr<string> key, boost::shared_ptr<SFSDataWrapper> val);
bool ContainsKey(string key);
bool ContainsKey(boost::shared_ptr<string> key);
boost::shared_ptr<void> GetClass(string key);
boost::shared_ptr<void> GetClass(boost::shared_ptr<string> key);
boost::shared_ptr<string> GetDump(bool format);
boost::shared_ptr<string> GetDump();
boost::shared_ptr<string> GetHexDump();
boost::shared_ptr<vector<string> > GetKeys();
bool IsNull(boost::shared_ptr<string> key);
bool IsNull(string key);
void PutClass(string key, boost::shared_ptr<void> val);
void PutClass(boost::shared_ptr<string> key, boost::shared_ptr<void> val);
void RemoveElement(string key);
void RemoveElement(boost::shared_ptr<string> key);
long int Size();
boost::shared_ptr<ByteArray> ToBinary();
// -------------------------------------------------------------------
// Public members
// -------------------------------------------------------------------
protected:
// -------------------------------------------------------------------
// Protected methods
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// Protected members
// -------------------------------------------------------------------
private:
// -------------------------------------------------------------------
// Private methods
// -------------------------------------------------------------------
boost::shared_ptr<string> Dump();
// -------------------------------------------------------------------
// Private members
// -------------------------------------------------------------------
boost::shared_ptr<map<string, boost::shared_ptr<SFSDataWrapper> > > dataHolder;
boost::shared_ptr<ISFSDataSerializer> serializer;
};
} // namespace Data
} // namespace Entities
} // namespace Sfs2X
#endif
| 47.902344 | 175 | 0.674142 | [
"object",
"vector"
] |
b648bc54fb0a667b5e5a5cabc07ab7db659f9cd1 | 4,651 | h | C | apps/common/third_party_profile/sig_mesh/api/sig_mesh_api.h | yzb201611/fw-AC630N_BT_SDK | b4954b3d83ab9e1db92fd97910ea4e00f94e77f4 | [
"Apache-2.0"
] | 8 | 2020-06-16T03:40:27.000Z | 2022-01-20T02:22:43.000Z | apps/common/third_party_profile/sig_mesh/api/sig_mesh_api.h | yzb201611/fw-AC630N_BT_SDK | b4954b3d83ab9e1db92fd97910ea4e00f94e77f4 | [
"Apache-2.0"
] | 1 | 2020-06-22T04:05:12.000Z | 2020-06-22T11:33:50.000Z | apps/common/third_party_profile/sig_mesh/api/sig_mesh_api.h | yzb201611/fw-AC630N_BT_SDK | b4954b3d83ab9e1db92fd97910ea4e00f94e77f4 | [
"Apache-2.0"
] | 9 | 2020-06-18T11:53:26.000Z | 2022-02-15T05:54:45.000Z | #ifndef __SIG_MESH_API_H__
#define __SIG_MESH_API_H__
#include "api/basic_depend.h"
#include "api/mesh_config.h"
#include "api/access.h"
#include "api/main.h"
#include "api/proxy.h"
#include "api/cfg_cli.h"
#include "api/cfg_srv.h"
#include "api/health_cli.h"
#include "api/health_srv.h"
/*******************************************************************/
/*
*------------------- common
*/
#define __noinit
#define ADV_SCAN_UNIT(_ms) ((_ms) * 8 / 5)
#define BT_MESH_ADDR_IS_UNICAST(addr) ((addr) && (addr) < 0x8000)
#define BT_MESH_ADDR_IS_GROUP(addr) ((addr) >= 0xc000 && (addr) <= 0xff00)
#define BT_MESH_ADDR_IS_VIRTUAL(addr) ((addr) >= 0x8000 && (addr) < 0xc000)
#define BT_MESH_ADDR_IS_RFU(addr) ((addr) >= 0xff00 && (addr) <= 0xfffb)
// -- output terminal color
#define RedBold "\033[31;1;7m" // 红色加粗
#define RedBoldBlink "\033[31;1;5m" // 红色加粗、闪烁
#define BlueBold "\033[34;1;7m" // 蓝色加粗
#define BlueBoldBlink "\033[34;1;5m" // 蓝色加粗、闪烁
#define PurpleBold "\033[35;1m" // 紫色加粗
#define PurpleBoldBlink "\033[35;1;5m" // 紫色加粗、闪烁
#define Reset "\033[0;25m" // 颜色复位
/*******************************************************************/
/*
*------------------- models
*/
/** @def NET_BUF_SIMPLE_DEFINE
* @brief Define a net_buf_simple stack variable.
*
* This is a helper macro which is used to define a net_buf_simple object
* on the stack.
*
* @param _name Name of the net_buf_simple object.
* @param _size Maximum data storage for the buffer.
*/
#define NET_BUF_SIMPLE_DEFINE(_name, _size) \
u8_t net_buf_data_##_name[_size]; \
struct net_buf_simple _name = { \
.data = net_buf_data_##_name, \
.len = 0, \
.size = _size, \
.__buf = net_buf_data_##_name, \
}
/** @def NET_BUF_SIMPLE_DEFINE_STATIC
* @brief Define a static net_buf_simple variable.
*
* This is a helper macro which is used to define a static net_buf_simple
* object.
*
* @param _name Name of the net_buf_simple object.
* @param _size Maximum data storage for the buffer.
*/
#define NET_BUF_SIMPLE_DEFINE_STATIC(_name, _size) \
static __noinit u8_t net_buf_data_##_name[_size]; \
static struct net_buf_simple _name = { \
.data = net_buf_data_##_name, \
.len = 0, \
.size = _size, \
.__buf = net_buf_data_##_name, \
}
/** @brief Simple network buffer representation.
*
* This is a simpler variant of the net_buf object (in fact net_buf uses
* net_buf_simple internally). It doesn't provide any kind of reference
* counting, user data, dynamic allocation, or in general the ability to
* pass through kernel objects such as FIFOs.
*
* The main use of this is for scenarios where the meta-data of the normal
* net_buf isn't needed and causes too much overhead. This could be e.g.
* when the buffer only needs to be allocated on the stack or when the
* access to and lifetime of the buffer is well controlled and constrained.
*
*/
struct net_buf_simple {
/** Pointer to the start of data in the buffer. */
u8_t *data;
/** Length of the data behind the data pointer. */
u16_t len;
/** Amount of data that this buffer can store. */
u16_t size;
/** Start of the data storage. Not to be accessed directly
* (the data pointer should be used instead).
*/
u8_t *__buf;
};
/**
* @brief Add a unsigned char variable at the tail of the buffer.
*
* @param buf Target buffer head address.
*
* @param val The variable will set.
*
* @return The tail address of the buffer.
*/
u8 *buffer_add_u8_at_tail(void *buf, u8 val);
/**
* @brief Get the unsigned char variable from the buffer head address.
*
* @param buf Target buffer head address.
*
* @return Target variable.
*/
u8 buffer_pull_u8_from_head(void *buf);
/**
* @brief Memcpy a array at the tail of the buffer.
*
* @param buf Target buffer head address.
*
* @param mem The source memory address.
*
* @param len The copy length.
*
* @return The result of the process : 0 is succ.
*/
void *buffer_memcpy(void *buf, const void *mem, u32 len);
/**
* @brief Memset at the tail of the buffer.
*
* @param buf Target buffer head address.
*
* @param mem The set value.
*
* @param len The set length.
*
* @return The result of the process : 0 is succ.
*/
void *buffer_memset(struct net_buf_simple *buf, u8 val, u32 len);
/**
* @brief Loading the node info from storage (such as flash and so on).
*/
void settings_load(void);
#endif /* __SIG_MESH_API_H__ */
| 29.436709 | 76 | 0.628897 | [
"object"
] |
b6506ad003e2169068a3e6c1909b96164ea153c5 | 997 | h | C | tree/94_Binary_Tree_Inorder_Traversal/Solution.h | IncludeLau/leetcode | f10fbdd3fca1b869fea8af55077cee5468e4ad1d | [
"Apache-2.0"
] | null | null | null | tree/94_Binary_Tree_Inorder_Traversal/Solution.h | IncludeLau/leetcode | f10fbdd3fca1b869fea8af55077cee5468e4ad1d | [
"Apache-2.0"
] | null | null | null | tree/94_Binary_Tree_Inorder_Traversal/Solution.h | IncludeLau/leetcode | f10fbdd3fca1b869fea8af55077cee5468e4ad1d | [
"Apache-2.0"
] | null | null | null | /**
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/
#ifndef LEETCODE_SOLUTION_H
#define LEETCODE_SOLUTION_H
#include <vector>
#include <stack>
#include "../TreeNode.h"
using namespace std;
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
if(root == nullptr) return res;
inorderTraversal(root->left);
res.push_back(root->val);
inorderTraversal(root->right);
return res;
}
vector<int> inorderTraversal2(TreeNode* root) {
if(root == nullptr) return res;
stack<TreeNode*> s;
while (!s.empty() || root) {
while (root) {
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
private:
vector<int> res;
};
#endif //LEETCODE_SOLUTION_H
| 17.189655 | 51 | 0.534604 | [
"vector"
] |
b651af99f8219d2f9bf6cc2ec3079fa6a6e15e6b | 254 | h | C | src/ai/aiutils.h | Eae02/tank-game | 0c526b177ccc15dd49e3228489163f13335040db | [
"Zlib"
] | null | null | null | src/ai/aiutils.h | Eae02/tank-game | 0c526b177ccc15dd49e3228489163f13335040db | [
"Zlib"
] | null | null | null | src/ai/aiutils.h | Eae02/tank-game | 0c526b177ccc15dd49e3228489163f13335040db | [
"Zlib"
] | null | null | null | #pragma once
#include "../world/path/path.h"
#include "../transform.h"
namespace TankGame
{
void WalkPath(float dt, const Path& path, float& progress, Transform& transform,
float movementSpeed, float turnRate, bool modulate = false);
}
| 23.090909 | 81 | 0.692913 | [
"transform"
] |
b660768257d79d089f9cebe43591c69a71317f75 | 1,127 | h | C | Source/FSD/Public/ParasiteEnemy.h | Dr-Turtle/DRG_ModPresetManager | abd7ff98a820969504491a1fe68cf2f9302410dc | [
"MIT"
] | 8 | 2021-07-10T20:06:05.000Z | 2022-03-04T19:03:50.000Z | Source/FSD/Public/ParasiteEnemy.h | Dr-Turtle/DRG_ModPresetManager | abd7ff98a820969504491a1fe68cf2f9302410dc | [
"MIT"
] | 9 | 2022-01-13T20:49:44.000Z | 2022-03-27T22:56:48.000Z | Source/FSD/Public/ParasiteEnemy.h | Dr-Turtle/DRG_ModPresetManager | abd7ff98a820969504491a1fe68cf2f9302410dc | [
"MIT"
] | 2 | 2021-07-10T20:05:42.000Z | 2022-03-14T17:05:35.000Z | #pragma once
#include "CoreMinimal.h"
#include "EnemyPawn.h"
#include "ParasiteEnemy.generated.h"
class USkeletalMeshComponent;
class UOutlineComponent;
class USceneComponent;
class UHealthComponentBase;
class UStaticMeshComponent;
class UParticleSystem;
class USoundBase;
UCLASS()
class AParasiteEnemy : public AEnemyPawn {
GENERATED_BODY()
public:
UPROPERTY(Export, VisibleAnywhere)
USceneComponent* Root;
UPROPERTY(BlueprintReadWrite, Export, VisibleAnywhere)
USkeletalMeshComponent* Mesh;
UPROPERTY(BlueprintReadWrite, Export, VisibleAnywhere)
UStaticMeshComponent* Tentacles1;
UPROPERTY(BlueprintReadWrite, Export, VisibleAnywhere)
UStaticMeshComponent* Tentacles2;
UPROPERTY(Export, VisibleAnywhere)
UOutlineComponent* outline;
protected:
UPROPERTY(BlueprintReadOnly, EditDefaultsOnly)
UParticleSystem* deathParticles;
UPROPERTY(BlueprintReadOnly, EditDefaultsOnly)
USoundBase* deathSound;
UFUNCTION(BlueprintCallable)
void OnSelfDeath(UHealthComponentBase* aHealthComponent);
public:
AParasiteEnemy();
};
| 23.978723 | 61 | 0.76575 | [
"mesh"
] |
b662d15a4e4d2c69ce1003daa28e8b260fb49e22 | 913 | h | C | headers/crypto/Md5.h | iugomobile/cryptography | 59d4e75de06a19d3b1eed72ca2525641310d411b | [
"MIT"
] | null | null | null | headers/crypto/Md5.h | iugomobile/cryptography | 59d4e75de06a19d3b1eed72ca2525641310d411b | [
"MIT"
] | null | null | null | headers/crypto/Md5.h | iugomobile/cryptography | 59d4e75de06a19d3b1eed72ca2525641310d411b | [
"MIT"
] | null | null | null | #pragma once
/**
* 2003 IUGO Mobile Entertainment Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property of
* IUGO Mobile Entertainment Inc. The intellectual and technical concepts
* contained herein are proprietary to IUGO Mobile Entertainment Inc. and
* may be covered by U.S. and Foreign Patents, patents in process, and are
* protected by trade secret or copyright law.
*/
#include "igl/crypto/Defs.h"
namespace iugo::crypto
{
#pragma mark - Md5Hash
using Md5Hash = Array<byte, 16, 16>;
#pragma mark - Md5Encipher
struct Md5Encipher final
{
using WordType = uint;
using VectorType = Array<uint, 4, 16>;
Array<uint, 16> Matrix;
VectorType Transform(VectorType vector) const noexcept;
static VectorType Reset() noexcept;
};
using Md5 = HashFunction<Md5Encipher>;
using HMacMd5 = HMac<Md5>;
}
| 23.410256 | 76 | 0.703176 | [
"vector",
"transform"
] |
b673f29250afe6c40acf2c15816acc9fdae76922 | 10,909 | h | C | include/dmlite/cpp/catalog.h | EricKTCheung/dmlite | 7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d | [
"Apache-2.0"
] | null | null | null | include/dmlite/cpp/catalog.h | EricKTCheung/dmlite | 7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d | [
"Apache-2.0"
] | null | null | null | include/dmlite/cpp/catalog.h | EricKTCheung/dmlite | 7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d | [
"Apache-2.0"
] | null | null | null | /// @file include/dmlite/cpp/catalog.h
/// @brief Catalog API.
/// @author Alejandro Álvarez Ayllón <aalvarez@cern.ch>
#ifndef DMLITE_CPP_CATALOG_H
#define DMLITE_CPP_CATALOG_H
#include "dmlite/common/config.h"
#include "base.h"
#include "exceptions.h"
#include "status.h"
#include "inode.h"
#include "utils/extensible.h"
#include <dirent.h>
#include <sys/stat.h>
#include <string>
#include <vector>
#include <utime.h>
namespace dmlite {
// Forward declarations.
class StackInstance;
class PluginManager;
/// Typedef for directories.
struct Directory { virtual ~Directory(); };
/// Interface for Catalog (Namespaces).
class Catalog: public virtual BaseInterface {
public:
/// Destructor.
virtual ~Catalog();
/// Change the working dir. Future not-absolute paths will use this as root.
/// @param path The new working dir.
virtual void changeDir(const std::string& path) throw (DmException);
/// Get the current working dir.
/// @return The current working dir.
virtual std::string getWorkingDir(void) throw (DmException);
/// Do an extended stat of a file or directory.
/// @param path The path of the file or directory.
/// @param followSym If true, symlinks will be followed.
/// @return The extended status of the file.
virtual ExtendedStat extendedStat(const std::string& path,
bool followSym = true) throw (DmException);
/// Do an extended stat of a file or directory. Exception-safe version, returns a status
/// @param path The path of the file or directory.
/// @param followSym If true, symlinks will be followed.
/// @param xstat The extended status of the file.
/// @return A status object
virtual DmStatus extendedStat(ExtendedStat &xstat,
const std::string& path,
bool followSym = true) throw (DmException);
/// Do an extended stat of a logical file using an associated replica file name.
/// @param rfn The replica.
/// @return The extended status of the file.
virtual ExtendedStat extendedStatByRFN(const std::string& rfn) throw (DmException);
/// Checks wether the process would be allowed to read, write, or check existence.
/// @param lfn Logical filename.
/// @param mode A mask consisting of one or more of R_OK, W_OK, X_OK and F_OK.
/// @return true if the file can be accessed.
/// @note If the file does not exist, an exception will be thrown.
virtual bool access(const std::string& path, int mode) throw (DmException);
/// Checks wether the process would be allowed to read, write, or check existence.
/// @param rfn Replica filename.
/// @param mode A mask consisting of one or more of R_OK, W_OK, X_OK and F_OK.
/// @return true if the file can be accessed.
/// @note If the file does not exist, an exception will be thrown.
virtual bool accessReplica(const std::string& replica, int mode) throw (DmException);
/// Add a new replica for a file.
/// @param replica Stores the data that is going to be added. fileid must
/// point to the id of the logical file in the catalog.
virtual void addReplica(const Replica& replica) throw (DmException);
/// Delete a replica.
/// @param replica The replica to remove.
virtual void deleteReplica(const Replica& replica) throw (DmException);
/// Get replicas for a file.
/// @param path The file for which replicas will be retrieved.
virtual std::vector<Replica> getReplicas(const std::string& path) throw (DmException);
/// Creates a new symlink.
/// @param path The existing path.
/// @param symlink The new access path.
virtual void symlink(const std::string& path,
const std::string& symlink) throw (DmException);
/// Returns the path pointed by the symlink path
/// @param path The symlink file.
/// @return The symlink target.
virtual std::string readLink(const std::string& path) throw (DmException);
/// Remove a file.
/// @param path The path to remove.
virtual void unlink(const std::string& path) throw (DmException);
/// Creates an entry in the catalog.
/// @param path The new file.
/// @param mode The creation mode.
virtual void create(const std::string& path,
mode_t mode) throw (DmException);
/// Sets the calling process’s file mode creation mask to mask & 0777.
/// @param mask The new mask.
/// @return The value of the previous mask.
virtual mode_t umask(mode_t mask) throw ();
/// Set the mode of a file.
/// @param path The file to modify.
/// @param mode The new mode as an integer (i.e. 0755)
virtual void setMode(const std::string& path,
mode_t mode) throw (DmException);
/// Set the owner of a file.
/// @param path The file to modify.
/// @param newUid The uid of the new owneer.
/// @param newGid The gid of the new group.
/// @param followSymLink If set to true, symbolic links will be followed.
virtual void setOwner(const std::string& path, uid_t newUid, gid_t newGid,
bool followSymLink = true) throw (DmException);
/// Set the size of a file.
/// @param path The file to modify.
/// @param newSize The new file size.
virtual void setSize(const std::string& path,
size_t newSize) throw (DmException);
/// Set the checksum of a file.
/// @param path The file to modify.
/// @param csumtype The checksum type cc
/// @param csumvalue The checksum value.
virtual void setChecksum(const std::string& path,
const std::string& csumtype,
const std::string& csumvalue) throw (DmException);
/// Get the checksum of a file, eventually waiting for it to be calculated.
/// @param path The file to query
/// @param csumtype The checksum type (CS, AD or MD. We can also pass a long checksum name (e.g. checksum.adler32)).
/// @param csumvalue The checksum value.
/// @param forcerecalc Force recalculation of the checksum (may take long and throw EAGAIN)
/// @param waitsecs Seconds to wait for a checksum to be calculated. Throws EAGAIN if timeouts. Set to 0 for blocking behavior.
virtual void getChecksum(const std::string& path,
const std::string& csumtype,
std::string& csumvalue,
const std::string& pfn, const bool forcerecalc = false, const int waitsecs = 0) throw (DmException);
/// Set the ACLs
/// @param path The file to modify.
/// @param acl The Access Control List.
virtual void setAcl(const std::string& path,
const Acl& acl) throw (DmException);
/// Set access and/or modification time.
/// @param path The file path.
/// @param buf A struct holding the new times.
virtual void utime(const std::string& path,
const struct utimbuf* buf) throw (DmException);
/// Get the comment associated with a file.
/// @param path The file or directory.
/// @return The associated comment.
virtual std::string getComment(const std::string& path) throw (DmException);
/// Set the comment associated with a file.
/// @param path The file or directory.
/// @param comment The new comment.
virtual void setComment(const std::string& path,
const std::string& comment) throw (DmException);
/// Set GUID of a file.
/// @param path The file.
/// @param guid The new GUID.
virtual void setGuid(const std::string& path,
const std::string &guid) throw (DmException);
/// Update extended metadata on the catalog.
/// @param path The file to update.
/// @param attr The extended attributes struct.
virtual void updateExtendedAttributes(const std::string& path,
const Extensible& attr) throw (DmException);
/// Open a directory for reading.
/// @param path The directory to open.
/// @return A pointer to a handle that can be used for later calls.
virtual Directory* openDir(const std::string& path) throw (DmException);
/// Close a directory opened previously.
/// @param dir The directory handle as returned by NsInterface::openDir.
virtual void closeDir(Directory* dir) throw (DmException);
/// Read next entry from a directory (simple read).
/// @param dir The directory handle as returned by NsInterface::openDir.
/// @return 0x00 on failure or end of directory.
virtual struct dirent* readDir(Directory* dir) throw (DmException);
/// Read next entry from a directory (stat information added).
/// @param dir The directory handle as returned by NsInterface::openDir.
/// @return 0x00 on failure (and errno is set) or end of directory.
virtual ExtendedStat* readDirx(Directory* dir) throw (DmException);
/// Create a new empty directory.
/// @param path The path of the new directory.
/// @param mode The creation mode.
virtual void makeDir(const std::string& path,
mode_t mode) throw (DmException);
/// Rename a file or directory.
/// @param oldPath The old name.
/// @param newPath The new name.
virtual void rename(const std::string& oldPath,
const std::string& newPath) throw (DmException);
/// Remove a directory.
/// @param path The path of the directory to remove.
virtual void removeDir(const std::string& path) throw (DmException);
/// Get a replica.
/// @param rfn The replica file name.
virtual Replica getReplicaByRFN(const std::string& rfn) throw (DmException);
/// Update a replica.
/// @param replica The replica to modify.
/// @return 0 on success, error code otherwise.
virtual void updateReplica(const Replica& replica) throw (DmException);
};
/// Plug-ins must implement a concrete factory to be instantiated.
class CatalogFactory: public virtual BaseFactory {
public:
/// Virtual destructor
virtual ~CatalogFactory();
protected:
// Stack instance is allowed to instantiate catalogs
friend class StackInstance;
/// Children of CatalogFactory are allowed to instantiate too (decorator)
static Catalog* createCatalog(CatalogFactory* factory,
PluginManager* pm) throw (DmException);
/// Instantiate a implementation of Catalog
virtual Catalog* createCatalog(PluginManager* pm) throw (DmException);
};
};
#endif // DMLITE_CPP_CATALOG_H
| 42.447471 | 136 | 0.641122 | [
"object",
"vector"
] |
b67ba12b4fa95454f5b463e6f7364820a7cde7a5 | 3,940 | h | C | Include/Scene/Transform.h | nalexandru/NekoEngineClassic | d304e15e0c6b50ae40ad50f5aefbb19150aa9f34 | [
"BSD-3-Clause"
] | 1 | 2021-04-11T21:40:48.000Z | 2021-04-11T21:40:48.000Z | Include/Scene/Transform.h | nalexandru/NekoEngineClassic | d304e15e0c6b50ae40ad50f5aefbb19150aa9f34 | [
"BSD-3-Clause"
] | null | null | null | Include/Scene/Transform.h | nalexandru/NekoEngineClassic | d304e15e0c6b50ae40ad50f5aefbb19150aa9f34 | [
"BSD-3-Clause"
] | null | null | null | #ifndef _SCN_TRANSFORM_H_
#define _SCN_TRANSFORM_H_
#include <Math/Math.h>
#include <Runtime/Runtime.h>
#include <Engine/Component.h>
struct Transform
{
COMPONENT_BASE;
struct mat4 mat;
bool dirty;
struct vec3 position, scale;
struct quat rotation;
struct vec3 forward, right, up;
struct Transform *parent;
Array children;
};
bool Scn_InitTransform(struct Transform *xform, const void **args);
void Scn_TermTransform(struct Transform *xform);
void Scn_UpdateTransform(void **comp, void *args);
static inline void
xform_move(struct Transform *t, struct vec3 *movement)
{
v3_add(&t->position, &t->position, movement);
t->dirty = true;
}
static inline void
xform_rotate(struct Transform *t, float angle, const struct vec3 *axis)
{
quat_rot_axis_angle(&t->rotation, axis, angle);
t->dirty = true;
}
static inline void
xform_scale(struct Transform *t, const struct vec3 *scale)
{
v3_mul(&t->scale, &t->scale, scale);
t->dirty = true;
}
static inline void
xform_set_pos(struct Transform *t, const struct vec3 *pos)
{
v3_copy(&t->position, pos);
t->dirty = true;
}
static inline void
xform_set_scale(struct Transform *t, const struct vec3 *scale)
{
v3_copy(&t->scale, scale);
t->scale.x = fmaxf(t->scale.x, .0000001f);
t->scale.y = fmaxf(t->scale.y, .0000001f);
t->scale.z = fmaxf(t->scale.z, .0000001f);
t->dirty = true;
}
static inline void
xform_look_at(struct Transform *t, struct vec3 *target, struct vec3 *up)
{
//
}
static inline void
xform_update(struct Transform *t)
{
struct mat4 m1;
struct mat4 m2;
struct vec4 tmp;
size_t i;
if ((t->parent && !t->parent->dirty) && !t->dirty)
return;
m4_rot_quat(&m1, &t->rotation);
v4_mul_m4(&tmp, v4(&tmp, 0.f, 0.f, 1.f, 1.f), &m1);
v3(&t->forward, tmp.x, tmp.y, tmp.z);
v4_mul_m4(&tmp, v4(&tmp, 1.f, 0.f, 0.f, 1.f), &m1);
v3(&t->right, tmp.x, tmp.y, tmp.z);
v4_mul_m4(&tmp, v4(&tmp, 0.f, 1.f, 0.f, 1.f), &m1);
v3(&t->up, tmp.x, tmp.y, tmp.z);
m4_translate(&m2, t->position.x, t->position.y, t->position.z);
m4_mul(&m1, &m2, &m1);
m4_scale(&m2, t->scale.x, t->scale.y, t->scale.z);
m4_mul(&t->mat, &m1, &m2);
for (i = 0; i < t->children.count; ++i)
xform_update((struct Transform *)Rt_ArrayGetPtr(&t->children, i));
t->dirty = false;
}
static inline struct vec3 *
xform_position(const struct Transform *t, struct vec3 *pos)
{
if (t->parent) {
struct vec3 tmp;
xform_position(t->parent, pos);
v3_add(pos, &tmp, &t->position);
} else {
memcpy(pos, &t->position, sizeof(*pos));
}
return pos;
}
static inline struct quat *
xform_rotation(const struct Transform *t, struct quat *rot)
{
if (t->parent) {
struct quat tmp;
xform_rotation(t->parent, &tmp);
quat_mul(rot, &tmp, &t->rotation);
} else {
memcpy(rot, &t->rotation, sizeof(*rot));
}
return rot;
}
static inline struct vec3 *
xform_rotation_angles(const struct Transform *t, struct vec3 *rot)
{
struct quat q;
xform_rotation(t, &q);
rot->x = quat_roll(&q);
rot->y = quat_pitch(&q);
rot->z = quat_yaw(&q);
return rot;
}
static inline void
xform_move_forward(struct Transform *t, float distance)
{
struct vec3 tmp;
v3_add(&t->position, &t->position, v3_muls(&tmp, &t->forward, distance));
t->dirty = true;
}
static inline void
xform_move_backward(struct Transform *t, float distance)
{
xform_move_forward(t, -distance);
}
static inline void
xform_move_right(struct Transform *t, float distance)
{
struct vec3 tmp;
v3_add(&t->position, &t->position, v3_muls(&tmp, &t->right, distance));
t->dirty = true;
}
static inline void
xform_move_left(struct Transform *t, float distance)
{
xform_move_right(t, -distance);
}
static inline void
xform_move_up(struct Transform *t, float distance)
{
struct vec3 tmp;
v3_add(&t->position, &t->position, v3_muls(&tmp, &t->up, distance));
t->dirty = true;
}
static inline void
xform_move_down(struct Transform *t, float distance)
{
xform_move_up(t, -distance);
}
#endif /* _SCN_TRANSOFRM_H_ */
| 20.628272 | 74 | 0.685787 | [
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.