hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
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 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2613106580d834e6f6c23229ec8e14b28bab861e
| 1,837
|
cpp
|
C++
|
cpp/Maya Calendar/Maya Calendar.cpp
|
xuzishan/Algorithm-learning-through-Problems
|
4aee347af6fd7fd935838e1cbea57c197e88705c
|
[
"MIT"
] | 27
|
2016-11-04T09:18:25.000Z
|
2022-02-12T12:34:01.000Z
|
cpp/Maya Calendar/Maya Calendar.cpp
|
Der1128/Algorithm-learning-through-Problems
|
4aee347af6fd7fd935838e1cbea57c197e88705c
|
[
"MIT"
] | 1
|
2016-11-05T02:30:24.000Z
|
2016-11-16T10:21:09.000Z
|
cpp/Maya Calendar/Maya Calendar.cpp
|
Der1128/Algorithm-learning-through-Problems
|
4aee347af6fd7fd935838e1cbea57c197e88705c
|
[
"MIT"
] | 20
|
2016-11-04T10:26:02.000Z
|
2021-09-25T05:41:21.000Z
|
//
// Maya Calendar.cpp
// laboratory
//
// Created by 徐子珊 on 16/4/4.
// Copyright (c) 2016年 xu_zishan. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <hash_map>
using namespace std;
pair<string, int> a[]={make_pair("pop", 0), make_pair("no", 1), make_pair("zip", 2), make_pair("zotz", 3),
make_pair("tzec", 4), make_pair("xul", 5), make_pair("yoxkin", 6), make_pair("mol", 7),
make_pair("chen", 8), make_pair("yax", 9), make_pair("zac", 10), make_pair("ceh", 11),
make_pair("mac", 12), make_pair("kankin", 13), make_pair("muan", 14), make_pair("pax", 15),
make_pair("koyab", 16), make_pair("cumhu", 17), make_pair("uayet", 18)};
hash_map<string, int> Haab(a, a+19);
string Tzolkin[]={"imix", "ik", "akbal", "kan", "chicchan", "cimi", "manik", "lamat", "muluk", "ok",
"chuen", "eb", "ben", "ix", "mem", "cib", "caban", "eznab", "canac", "ahau"};
string mayaCalendar(string &haab){
istringstream s(haab);
int NumberOfTheDay, Year;
string Month;
char dot;
s>>NumberOfTheDay>>dot>>Month>>Year;
int days=365*Year+20*Haab[Month]+NumberOfTheDay;
Year=days/260;
int r=days%260;
int Number=(r%13)+1;
string NameOfTheDay=Tzolkin[r%20];
ostringstream os;
os<<Number<<" "<<NameOfTheDay<<" "<<Year;
return os.str();
}
int main(){
ifstream inputdata("Maya Calendar/inputdata.txt");
ofstream outputdata("Maya Calendar/outputdata.txt");
int n;
inputdata>>n;
outputdata<<n<<endl;
cout<<n<<endl;
string haab;
getline(inputdata, haab);
for(int i=0; i<n; i++){
getline(inputdata, haab);
string tzolkin=mayaCalendar(haab);
outputdata<<tzolkin<<endl;
cout<<tzolkin<<endl;
}
inputdata.close();
outputdata.close();
return 0;
}
| 32.22807
| 107
| 0.62221
|
xuzishan
|
2613699c22b337a40d0a7955cf85646d1082af29
| 549
|
cc
|
C++
|
test/lattice/parameter.cc
|
Alexhuszagh/funxx
|
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
|
[
"MIT",
"BSD-3-Clause"
] | 1
|
2017-07-21T22:58:38.000Z
|
2017-07-21T22:58:38.000Z
|
test/lattice/parameter.cc
|
Alexhuszagh/funxx
|
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
test/lattice/parameter.cc
|
Alexhuszagh/funxx
|
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
// :copyright: (c) 2017 Alex Huszagh.
// :license: MIT, see LICENSE.md for more details.
#include <pycpp/lattice/parameter.h>
#include <gtest/gtest.h>
PYCPP_USING_NAMESPACE
// TESTS
// -----
TEST(parameters_t, get)
{
parameters_t parameters = {
{"name", "value"},
};
EXPECT_EQ(parameters.get(), "?name=value");
}
TEST(parameters_t, add)
{
parameters_t parameters = {
{"name", "value"},
};
parameters.add(parameter_t("name2", "value2"));
EXPECT_EQ(parameters.get(), "?name=value&name2=value2");
}
| 18.3
| 60
| 0.622951
|
Alexhuszagh
|
26138d64ec152d2b5f041c77ae3b068cfb7a950c
| 1,254
|
cpp
|
C++
|
LeetCode/187. Repeated DNA Sequences.cpp
|
Joon7891/Competitive-Programming
|
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
|
[
"MIT"
] | 2
|
2021-04-13T00:19:56.000Z
|
2021-04-13T01:19:45.000Z
|
LeetCode/187. Repeated DNA Sequences.cpp
|
Joon7891/Competitive-Programming
|
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
|
[
"MIT"
] | null | null | null |
LeetCode/187. Repeated DNA Sequences.cpp
|
Joon7891/Competitive-Programming
|
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
|
[
"MIT"
] | 1
|
2020-08-26T12:36:08.000Z
|
2020-08-26T12:36:08.000Z
|
class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
map<char, int> charToBit;
charToBit['A'] = 0b00;
charToBit['C'] = 0b01;
charToBit['G'] = 0b10;
charToBit['T'] = 0b11;
map<int, char> bitToChar;
bitToChar[0b00] = 'A';
bitToChar[0b01] = 'C';
bitToChar[0b10] = 'G';
bitToChar[0b11] = 'T';
int cur = 0;
vector<int> seen;
map<int, int> freq;
for (int i = 0; i < s.length(); i++){
cur = ((cur << 2) | charToBit[s[i]]);
if (i >= 9){
cur &= 0b11111111111111111111;
if (freq[cur] == 0) seen.push_back(cur);
freq[cur]++;
}
}
vector<string> ans;
for (int x : seen){
if (freq[x] >= 2){
string dna = "";
for (int i = 0; i < 10; i++){
int bit = (x >> (2 * i)) & 0b11;
dna = bitToChar[bit] + dna;
}
ans.push_back(dna);
}
}
return ans;
}
};
| 27.866667
| 56
| 0.360447
|
Joon7891
|
261cdd21729796c74dc94d854f918e1929207d29
| 3,081
|
cpp
|
C++
|
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/pathpage.cpp
|
GrinCash/Grinc-core
|
1377979453ba84082f70f9c128be38e57b65a909
|
[
"MIT"
] | null | null | null |
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/pathpage.cpp
|
GrinCash/Grinc-core
|
1377979453ba84082f70f9c128be38e57b65a909
|
[
"MIT"
] | null | null | null |
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/pathpage.cpp
|
GrinCash/Grinc-core
|
1377979453ba84082f70f9c128be38e57b65a909
|
[
"MIT"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Assistant of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets/QFileDialog>
#include "pathpage.h"
QT_BEGIN_NAMESPACE
PathPage::PathPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Source File Paths"));
setSubTitle(tr("Specify the paths where the sources files "
"are located. By default, all files in those directories "
"matched by the file filter will be included."));
m_ui.setupUi(this);
connect(m_ui.addButton, &QAbstractButton::clicked,
this, &PathPage::addPath);
connect(m_ui.removeButton, &QAbstractButton::clicked,
this, &PathPage::removePath);
m_ui.filterLineEdit->setText(QLatin1String("*.html, *.htm, *.png, *.jpg, *.css"));
registerField(QLatin1String("sourcePathList"), m_ui.pathListWidget);
m_firstTime = true;
}
void PathPage::setPath(const QString &path)
{
if (!m_firstTime)
return;
m_ui.pathListWidget->addItem(path);
m_firstTime = false;
m_ui.pathListWidget->setCurrentRow(0);
}
QStringList PathPage::paths() const
{
QStringList lst;
for (int i = 0; i < m_ui.pathListWidget->count(); ++i)
lst.append(m_ui.pathListWidget->item(i)->text());
return lst;
}
QStringList PathPage::filters() const
{
QStringList lst;
for (const QString &s : m_ui.filterLineEdit->text().split(QLatin1Char(','))) {
lst.append(s.trimmed());
}
return lst;
}
void PathPage::addPath()
{
QString dir = QFileDialog::getExistingDirectory(this,
tr("Source File Path"));
if (!dir.isEmpty())
m_ui.pathListWidget->addItem(dir);
}
void PathPage::removePath()
{
QListWidgetItem *i = m_ui.pathListWidget
->takeItem(m_ui.pathListWidget->currentRow());
delete i;
if (!m_ui.pathListWidget->count())
m_ui.removeButton->setEnabled(false);
}
QT_END_NAMESPACE
| 30.81
| 86
| 0.66407
|
GrinCash
|
261f35817fc8033d8bbf94f018bb61bac851283a
| 37,455
|
cpp
|
C++
|
src/libraries/dynamicMesh/dynamicMesh/meshCut/meshModifiers/meshCutAndRemove/meshCutAndRemove.cpp
|
MrAwesomeRocks/caelus-cml
|
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
|
[
"mpich2"
] | null | null | null |
src/libraries/dynamicMesh/dynamicMesh/meshCut/meshModifiers/meshCutAndRemove/meshCutAndRemove.cpp
|
MrAwesomeRocks/caelus-cml
|
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
|
[
"mpich2"
] | null | null | null |
src/libraries/dynamicMesh/dynamicMesh/meshCut/meshModifiers/meshCutAndRemove/meshCutAndRemove.cpp
|
MrAwesomeRocks/caelus-cml
|
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
|
[
"mpich2"
] | null | null | null |
/*---------------------------------------------------------------------------*\
Copyright (C) 2011-2012 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS 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.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "meshCutAndRemove.hpp"
#include "polyMesh.hpp"
#include "polyTopoChange.hpp"
#include "polyAddFace.hpp"
#include "polyAddPoint.hpp"
#include "polyRemovePoint.hpp"
#include "polyRemoveFace.hpp"
#include "polyModifyFace.hpp"
#include "cellCuts.hpp"
#include "mapPolyMesh.hpp"
#include "meshTools.hpp"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace CML
{
defineTypeNameAndDebug(meshCutAndRemove, 0);
}
// * * * * * * * * * * * * * Private Static Functions * * * * * * * * * * * //
// Returns -1 or index in elems1 of first shared element.
CML::label CML::meshCutAndRemove::firstCommon
(
const labelList& elems1,
const labelList& elems2
)
{
forAll(elems1, elemI)
{
label index1 = findIndex(elems2, elems1[elemI]);
if (index1 != -1)
{
return index1;
}
}
return -1;
}
// Check if twoCuts at two consecutive position in cuts.
bool CML::meshCutAndRemove::isIn
(
const edge& twoCuts,
const labelList& cuts
)
{
label index = findIndex(cuts, twoCuts[0]);
if (index == -1)
{
return false;
}
return
(
cuts[cuts.fcIndex(index)] == twoCuts[1]
|| cuts[cuts.rcIndex(index)] == twoCuts[1]
);
}
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
// Returns the cell in cellLabels that is cut. Or -1.
CML::label CML::meshCutAndRemove::findCutCell
(
const cellCuts& cuts,
const labelList& cellLabels
) const
{
forAll(cellLabels, labelI)
{
label cellI = cellLabels[labelI];
if (cuts.cellLoops()[cellI].size())
{
return cellI;
}
}
return -1;
}
//- Returns first pointI in pointLabels that uses an internal
// face. Used to find point to inflate cell/face from (has to be
// connected to internal face). Returns -1 (so inflate from nothing) if
// none found.
CML::label CML::meshCutAndRemove::findInternalFacePoint
(
const labelList& pointLabels
) const
{
forAll(pointLabels, labelI)
{
label pointI = pointLabels[labelI];
const labelList& pFaces = mesh().pointFaces()[pointI];
forAll(pFaces, pFaceI)
{
label faceI = pFaces[pFaceI];
if (mesh().isInternalFace(faceI))
{
return pointI;
}
}
}
if (pointLabels.empty())
{
FatalErrorInFunction
<< "Empty pointLabels" << abort(FatalError);
}
return -1;
}
// Find point on face that is part of original mesh and that is point connected
// to the patch
CML::label CML::meshCutAndRemove::findPatchFacePoint
(
const face& f,
const label exposedPatchI
) const
{
const labelListList& pointFaces = mesh().pointFaces();
const polyBoundaryMesh& patches = mesh().boundaryMesh();
forAll(f, fp)
{
label pointI = f[fp];
if (pointI < mesh().nPoints())
{
const labelList& pFaces = pointFaces[pointI];
forAll(pFaces, i)
{
if (patches.whichPatch(pFaces[i]) == exposedPatchI)
{
return pointI;
}
}
}
}
return -1;
}
// Get new owner and neighbour of face. Checks anchor points to see if
// cells have been removed.
void CML::meshCutAndRemove::faceCells
(
const cellCuts& cuts,
const label exposedPatchI,
const label faceI,
label& own,
label& nei,
label& patchID
) const
{
const labelListList& anchorPts = cuts.cellAnchorPoints();
const labelListList& cellLoops = cuts.cellLoops();
const face& f = mesh().faces()[faceI];
own = mesh().faceOwner()[faceI];
if (cellLoops[own].size() && firstCommon(f, anchorPts[own]) == -1)
{
// owner has been split and this is the removed part.
own = -1;
}
nei = -1;
if (mesh().isInternalFace(faceI))
{
nei = mesh().faceNeighbour()[faceI];
if (cellLoops[nei].size() && firstCommon(f, anchorPts[nei]) == -1)
{
nei = -1;
}
}
patchID = mesh().boundaryMesh().whichPatch(faceI);
if (patchID == -1 && (own == -1 || nei == -1))
{
// Face was internal but becomes external
patchID = exposedPatchI;
}
}
void CML::meshCutAndRemove::getZoneInfo
(
const label faceI,
label& zoneID,
bool& zoneFlip
) const
{
zoneID = mesh().faceZones().whichZone(faceI);
zoneFlip = false;
if (zoneID >= 0)
{
const faceZone& fZone = mesh().faceZones()[zoneID];
zoneFlip = fZone.flipMap()[fZone.whichFace(faceI)];
}
}
// Adds a face from point.
void CML::meshCutAndRemove::addFace
(
polyTopoChange& meshMod,
const label faceI,
const label masterPointI,
const face& newFace,
const label own,
const label nei,
const label patchID
)
{
label zoneID;
bool zoneFlip;
getZoneInfo(faceI, zoneID, zoneFlip);
if ((nei == -1) || (own != -1 && own < nei))
{
// Ordering ok.
if (debug & 2)
{
Pout<< "Adding face " << newFace
<< " with new owner:" << own
<< " with new neighbour:" << nei
<< " patchID:" << patchID
<< " anchor:" << masterPointI
<< " zoneID:" << zoneID
<< " zoneFlip:" << zoneFlip
<< endl;
}
meshMod.setAction
(
polyAddFace
(
newFace, // face
own, // owner
nei, // neighbour
masterPointI, // master point
-1, // master edge
-1, // master face for addition
false, // flux flip
patchID, // patch for face
zoneID, // zone for face
zoneFlip // face zone flip
)
);
}
else
{
// Reverse owner/neighbour
if (debug & 2)
{
Pout<< "Adding (reversed) face " << newFace.reverseFace()
<< " with new owner:" << nei
<< " with new neighbour:" << own
<< " patchID:" << patchID
<< " anchor:" << masterPointI
<< " zoneID:" << zoneID
<< " zoneFlip:" << zoneFlip
<< endl;
}
meshMod.setAction
(
polyAddFace
(
newFace.reverseFace(), // face
nei, // owner
own, // neighbour
masterPointI, // master point
-1, // master edge
-1, // master face for addition
false, // flux flip
patchID, // patch for face
zoneID, // zone for face
zoneFlip // face zone flip
)
);
}
}
// Modifies existing faceI for either new owner/neighbour or new face points.
void CML::meshCutAndRemove::modFace
(
polyTopoChange& meshMod,
const label faceI,
const face& newFace,
const label own,
const label nei,
const label patchID
)
{
label zoneID;
bool zoneFlip;
getZoneInfo(faceI, zoneID, zoneFlip);
if
(
(own != mesh().faceOwner()[faceI])
|| (
mesh().isInternalFace(faceI)
&& (nei != mesh().faceNeighbour()[faceI])
)
|| (newFace != mesh().faces()[faceI])
)
{
if (debug & 2)
{
Pout<< "Modifying face " << faceI
<< " old vertices:" << mesh().faces()[faceI]
<< " new vertices:" << newFace
<< " new owner:" << own
<< " new neighbour:" << nei
<< " new patch:" << patchID
<< " new zoneID:" << zoneID
<< " new zoneFlip:" << zoneFlip
<< endl;
}
if ((nei == -1) || (own != -1 && own < nei))
{
meshMod.setAction
(
polyModifyFace
(
newFace, // modified face
faceI, // label of face being modified
own, // owner
nei, // neighbour
false, // face flip
patchID, // patch for face
false, // remove from zone
zoneID, // zone for face
zoneFlip // face flip in zone
)
);
}
else
{
meshMod.setAction
(
polyModifyFace
(
newFace.reverseFace(), // modified face
faceI, // label of face being modified
nei, // owner
own, // neighbour
false, // face flip
patchID, // patch for face
false, // remove from zone
zoneID, // zone for face
zoneFlip // face flip in zone
)
);
}
}
}
// Copies face starting from startFp up to and including endFp.
void CML::meshCutAndRemove::copyFace
(
const face& f,
const label startFp,
const label endFp,
face& newFace
) const
{
label fp = startFp;
label newFp = 0;
while (fp != endFp)
{
newFace[newFp++] = f[fp];
fp = (fp + 1) % f.size();
}
newFace[newFp] = f[fp];
}
// Actually split face in two along splitEdge v0, v1 (the two vertices in new
// vertex numbering). Generates faces in same ordering
// as original face. Replaces cutEdges by the points introduced on them
// (addedPoints_).
void CML::meshCutAndRemove::splitFace
(
const face& f,
const label v0,
const label v1,
face& f0,
face& f1
) const
{
// Check if we find any new vertex which is part of the splitEdge.
label startFp = findIndex(f, v0);
if (startFp == -1)
{
FatalErrorInFunction
<< "Cannot find vertex (new numbering) " << v0
<< " on face " << f
<< abort(FatalError);
}
label endFp = findIndex(f, v1);
if (endFp == -1)
{
FatalErrorInFunction
<< "Cannot find vertex (new numbering) " << v1
<< " on face " << f
<< abort(FatalError);
}
f0.setSize((endFp + 1 + f.size() - startFp) % f.size());
f1.setSize(f.size() - f0.size() + 2);
copyFace(f, startFp, endFp, f0);
copyFace(f, endFp, startFp, f1);
}
// Adds additional vertices (from edge cutting) to face. Used for faces which
// are not split but still might use edge that has been cut.
CML::face CML::meshCutAndRemove::addEdgeCutsToFace(const label faceI) const
{
const face& f = mesh().faces()[faceI];
face newFace(2 * f.size());
label newFp = 0;
forAll(f, fp)
{
// Duplicate face vertex.
newFace[newFp++] = f[fp];
// Check if edge has been cut.
label fp1 = f.fcIndex(fp);
HashTable<label, edge, Hash<edge> >::const_iterator fnd =
addedPoints_.find(edge(f[fp], f[fp1]));
if (fnd != addedPoints_.end())
{
// edge has been cut. Introduce new vertex.
newFace[newFp++] = fnd();
}
}
newFace.setSize(newFp);
return newFace;
}
// Walk loop (loop of cuts) across circumference of cellI. Returns face in
// new vertices.
// Note: tricky bit is that it can use existing edges which have been split.
CML::face CML::meshCutAndRemove::loopToFace
(
const label cellI,
const labelList& loop
) const
{
face newFace(2*loop.size());
label newFaceI = 0;
forAll(loop, fp)
{
label cut = loop[fp];
if (isEdge(cut))
{
label edgeI = getEdge(cut);
const edge& e = mesh().edges()[edgeI];
label vertI = addedPoints_[e];
newFace[newFaceI++] = vertI;
}
else
{
// cut is vertex.
label vertI = getVertex(cut);
newFace[newFaceI++] = vertI;
label nextCut = loop[loop.fcIndex(fp)];
if (!isEdge(nextCut))
{
// From vertex to vertex -> cross cut only if no existing edge.
label nextVertI = getVertex(nextCut);
label edgeI = meshTools::findEdge(mesh(), vertI, nextVertI);
if (edgeI != -1)
{
// Existing edge. Insert split-edge point if any.
HashTable<label, edge, Hash<edge> >::const_iterator fnd =
addedPoints_.find(mesh().edges()[edgeI]);
if (fnd != addedPoints_.end())
{
newFace[newFaceI++] = fnd();
}
}
}
}
}
newFace.setSize(newFaceI);
return newFace;
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Construct from components
CML::meshCutAndRemove::meshCutAndRemove(const polyMesh& mesh)
:
edgeVertex(mesh),
addedFaces_(),
addedPoints_()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void CML::meshCutAndRemove::setRefinement
(
const label exposedPatchI,
const cellCuts& cuts,
const labelList& cutPatch,
polyTopoChange& meshMod
)
{
// Clear and size maps here since mesh size will change.
addedFaces_.clear();
addedFaces_.resize(cuts.nLoops());
addedPoints_.clear();
addedPoints_.resize(cuts.nLoops());
if (cuts.nLoops() == 0)
{
return;
}
const labelListList& anchorPts = cuts.cellAnchorPoints();
const labelListList& cellLoops = cuts.cellLoops();
const polyBoundaryMesh& patches = mesh().boundaryMesh();
if (exposedPatchI < 0 || exposedPatchI >= patches.size())
{
FatalErrorInFunction
<< "Illegal exposed patch " << exposedPatchI
<< abort(FatalError);
}
//
// Add new points along cut edges.
//
forAll(cuts.edgeIsCut(), edgeI)
{
if (cuts.edgeIsCut()[edgeI])
{
const edge& e = mesh().edges()[edgeI];
// Check if there is any cell using this edge.
if (debug && findCutCell(cuts, mesh().edgeCells()[edgeI]) == -1)
{
FatalErrorInFunction
<< "Problem: cut edge but none of the cells using it is\n"
<< "edge:" << edgeI << " verts:" << e
<< abort(FatalError);
}
// One of the edge end points should be master point of nbCellI.
label masterPointI = e.start();
const point& v0 = mesh().points()[e.start()];
const point& v1 = mesh().points()[e.end()];
scalar weight = cuts.edgeWeight()[edgeI];
point newPt = weight*v1 + (1.0-weight)*v0;
label addedPointI =
meshMod.setAction
(
polyAddPoint
(
newPt, // point
masterPointI, // master point
-1, // zone for point
true // supports a cell
)
);
// Store on (hash of) edge.
addedPoints_.insert(e, addedPointI);
if (debug & 2)
{
Pout<< "Added point " << addedPointI
<< " to vertex "
<< masterPointI << " of edge " << edgeI
<< " vertices " << e << endl;
}
}
}
//
// Remove all points that will not be used anymore
//
{
boolList usedPoint(mesh().nPoints(), false);
forAll(cellLoops, cellI)
{
const labelList& loop = cellLoops[cellI];
if (loop.size())
{
// Cell is cut. Uses only anchor points and loop itself.
forAll(loop, fp)
{
label cut = loop[fp];
if (!isEdge(cut))
{
usedPoint[getVertex(cut)] = true;
}
}
const labelList& anchors = anchorPts[cellI];
forAll(anchors, i)
{
usedPoint[anchors[i]] = true;
}
}
else
{
// Cell is not cut so use all its points
const labelList& cPoints = mesh().cellPoints()[cellI];
forAll(cPoints, i)
{
usedPoint[cPoints[i]] = true;
}
}
}
// Check
const Map<edge>& faceSplitCut = cuts.faceSplitCut();
forAllConstIter(Map<edge>, faceSplitCut, iter)
{
const edge& fCut = iter();
forAll(fCut, i)
{
label cut = fCut[i];
if (!isEdge(cut))
{
label pointI = getVertex(cut);
if (!usedPoint[pointI])
{
FatalErrorInFunction
<< "Problem: faceSplitCut not used by any loop"
<< " or cell anchor point"
<< "face:" << iter.key() << " point:" << pointI
<< " coord:" << mesh().points()[pointI]
<< abort(FatalError);
}
}
}
}
forAll(cuts.pointIsCut(), pointI)
{
if (cuts.pointIsCut()[pointI])
{
if (!usedPoint[pointI])
{
FatalErrorInFunction
<< "Problem: point is marked as cut but"
<< " not used by any loop"
<< " or cell anchor point"
<< "point:" << pointI
<< " coord:" << mesh().points()[pointI]
<< abort(FatalError);
}
}
}
// Remove unused points.
forAll(usedPoint, pointI)
{
if (!usedPoint[pointI])
{
meshMod.setAction(polyRemovePoint(pointI));
if (debug & 2)
{
Pout<< "Removing unused point " << pointI << endl;
}
}
}
}
//
// For all cut cells add an internal or external face
//
forAll(cellLoops, cellI)
{
const labelList& loop = cellLoops[cellI];
if (loop.size())
{
if (cutPatch[cellI] < 0 || cutPatch[cellI] >= patches.size())
{
FatalErrorInFunction
<< "Illegal patch " << cutPatch[cellI]
<< " provided for cut cell " << cellI
<< abort(FatalError);
}
//
// Convert loop (=list of cuts) into proper face.
// cellCuts sets orientation is towards anchor side so reverse.
//
face newFace(loopToFace(cellI, loop));
reverse(newFace);
// Pick any anchor point on cell
label masterPointI = findPatchFacePoint(newFace, exposedPatchI);
label addedFaceI =
meshMod.setAction
(
polyAddFace
(
newFace, // face
cellI, // owner
-1, // neighbour
masterPointI, // master point
-1, // master edge
-1, // master face for addition
false, // flux flip
cutPatch[cellI], // patch for face
-1, // zone for face
false // face zone flip
)
);
addedFaces_.insert(cellI, addedFaceI);
if (debug & 2)
{
Pout<< "Added splitting face " << newFace << " index:"
<< addedFaceI << " from masterPoint:" << masterPointI
<< " to owner " << cellI << " with anchors:"
<< anchorPts[cellI]
<< " from Loop:";
// Gets edgeweights of loop
scalarField weights(loop.size());
forAll(loop, i)
{
label cut = loop[i];
weights[i] =
(
isEdge(cut)
? cuts.edgeWeight()[getEdge(cut)]
: -GREAT
);
}
writeCuts(Pout, loop, weights);
Pout<< endl;
}
}
}
//
// Modify faces to use only anchorpoints and loop points
// (so throw away part without anchorpoints)
//
// Maintain whether face has been updated (for -split edges
// -new owner/neighbour)
boolList faceUptodate(mesh().nFaces(), false);
const Map<edge>& faceSplitCuts = cuts.faceSplitCut();
forAllConstIter(Map<edge>, faceSplitCuts, iter)
{
label faceI = iter.key();
// Renumber face to include split edges.
face newFace(addEdgeCutsToFace(faceI));
// Edge splitting the face. Convert edge to new vertex numbering.
const edge& splitEdge = iter();
label cut0 = splitEdge[0];
label v0;
if (isEdge(cut0))
{
label edgeI = getEdge(cut0);
v0 = addedPoints_[mesh().edges()[edgeI]];
}
else
{
v0 = getVertex(cut0);
}
label cut1 = splitEdge[1];
label v1;
if (isEdge(cut1))
{
label edgeI = getEdge(cut1);
v1 = addedPoints_[mesh().edges()[edgeI]];
}
else
{
v1 = getVertex(cut1);
}
// Split face along the elements of the splitEdge.
face f0, f1;
splitFace(newFace, v0, v1, f0, f1);
label own = mesh().faceOwner()[faceI];
label nei = -1;
if (mesh().isInternalFace(faceI))
{
nei = mesh().faceNeighbour()[faceI];
}
if (debug & 2)
{
Pout<< "Split face " << mesh().faces()[faceI]
<< " own:" << own << " nei:" << nei
<< " into f0:" << f0
<< " and f1:" << f1 << endl;
}
// Check which cell using face uses anchorPoints (so is kept)
// and which one doesn't (gets removed)
// Bit tricky. We have to know whether this faceSplit splits owner/
// neighbour or both. Even if cell is cut we have to make sure this is
// the one that cuts it (this face cut might not be the one splitting
// the cell)
// The face f gets split into two parts, f0 and f1.
// Each of these can have a different owner and or neighbour.
const face& f = mesh().faces()[faceI];
label f0Own = -1;
label f1Own = -1;
if (cellLoops[own].empty())
{
// Owner side is not split so keep both halves.
f0Own = own;
f1Own = own;
}
else if (isIn(splitEdge, cellLoops[own]))
{
// Owner is cut by this splitCut. See which of f0, f1 gets
// preserved and becomes owner, and which gets removed.
if (firstCommon(f0, anchorPts[own]) != -1)
{
// f0 preserved so f1 gets deleted
f0Own = own;
f1Own = -1;
}
else
{
f0Own = -1;
f1Own = own;
}
}
else
{
// Owner not cut by this splitCut but by another.
// Check on original face whether
// use anchorPts.
if (firstCommon(f, anchorPts[own]) != -1)
{
// both f0 and f1 owner side preserved
f0Own = own;
f1Own = own;
}
else
{
// both f0 and f1 owner side removed
f0Own = -1;
f1Own = -1;
}
}
label f0Nei = -1;
label f1Nei = -1;
if (nei != -1)
{
if (cellLoops[nei].empty())
{
f0Nei = nei;
f1Nei = nei;
}
else if (isIn(splitEdge, cellLoops[nei]))
{
// Neighbour is cut by this splitCut. So anchor part of it
// gets kept, non-anchor bit gets removed. See which of f0, f1
// connects to which part.
if (firstCommon(f0, anchorPts[nei]) != -1)
{
f0Nei = nei;
f1Nei = -1;
}
else
{
f0Nei = -1;
f1Nei = nei;
}
}
else
{
// neighbour not cut by this splitCut. Check on original face
// whether use anchorPts.
if (firstCommon(f, anchorPts[nei]) != -1)
{
f0Nei = nei;
f1Nei = nei;
}
else
{
// both f0 and f1 on neighbour side removed
f0Nei = -1;
f1Nei = -1;
}
}
}
if (debug & 2)
{
Pout<< "f0 own:" << f0Own << " nei:" << f0Nei
<< " f1 own:" << f1Own << " nei:" << f1Nei
<< endl;
}
// If faces were internal but now become external set a patch.
// If they were external already keep the patch.
label patchID = patches.whichPatch(faceI);
if (patchID == -1)
{
patchID = exposedPatchI;
}
// Do as much as possible by modifying faceI. Delay any remove
// face. Keep track of whether faceI has been used.
bool modifiedFaceI = false;
if (f0Own == -1)
{
if (f0Nei != -1)
{
// f0 becomes external face (note:modFace will reverse face)
modFace(meshMod, faceI, f0, f0Own, f0Nei, patchID);
modifiedFaceI = true;
}
}
else
{
if (f0Nei == -1)
{
// f0 becomes external face
modFace(meshMod, faceI, f0, f0Own, f0Nei, patchID);
modifiedFaceI = true;
}
else
{
// f0 stays internal face.
modFace(meshMod, faceI, f0, f0Own, f0Nei, -1);
modifiedFaceI = true;
}
}
// f1 is added face (if at all)
if (f1Own == -1)
{
if (f1Nei == -1)
{
// f1 not needed.
}
else
{
// f1 becomes external face (note:modFace will reverse face)
if (!modifiedFaceI)
{
modFace(meshMod, faceI, f1, f1Own, f1Nei, patchID);
modifiedFaceI = true;
}
else
{
label masterPointI = findPatchFacePoint(f1, patchID);
addFace
(
meshMod,
faceI, // face for zone info
masterPointI, // inflation point
f1, // vertices of face
f1Own,
f1Nei,
patchID // patch for new face
);
}
}
}
else
{
if (f1Nei == -1)
{
// f1 becomes external face
if (!modifiedFaceI)
{
modFace(meshMod, faceI, f1, f1Own, f1Nei, patchID);
modifiedFaceI = true;
}
else
{
label masterPointI = findPatchFacePoint(f1, patchID);
addFace
(
meshMod,
faceI,
masterPointI,
f1,
f1Own,
f1Nei,
patchID
);
}
}
else
{
// f1 is internal face.
if (!modifiedFaceI)
{
modFace(meshMod, faceI, f1, f1Own, f1Nei, -1);
modifiedFaceI = true;
}
else
{
label masterPointI = findPatchFacePoint(f1, -1);
addFace(meshMod, faceI, masterPointI, f1, f1Own, f1Nei, -1);
}
}
}
if (f0Own == -1 && f0Nei == -1 && !modifiedFaceI)
{
meshMod.setAction(polyRemoveFace(faceI));
if (debug & 2)
{
Pout<< "Removed face " << faceI << endl;
}
}
faceUptodate[faceI] = true;
}
//
// Faces that have not been split but just appended to. Are guaranteed
// to be reachable from an edgeCut.
//
const boolList& edgeIsCut = cuts.edgeIsCut();
forAll(edgeIsCut, edgeI)
{
if (edgeIsCut[edgeI])
{
const labelList& eFaces = mesh().edgeFaces()[edgeI];
forAll(eFaces, i)
{
label faceI = eFaces[i];
if (!faceUptodate[faceI])
{
// So the face has not been split itself (i.e. its owner
// or neighbour have not been split) so it only
// borders by edge a cell which has been split.
// Get (new or original) owner and neighbour of faceI
label own, nei, patchID;
faceCells(cuts, exposedPatchI, faceI, own, nei, patchID);
if (own == -1 && nei == -1)
{
meshMod.setAction(polyRemoveFace(faceI));
if (debug & 2)
{
Pout<< "Removed face " << faceI << endl;
}
}
else
{
// Renumber face to include split edges.
face newFace(addEdgeCutsToFace(faceI));
if (debug & 2)
{
Pout<< "Added edge cuts to face " << faceI
<< " f:" << mesh().faces()[faceI]
<< " newFace:" << newFace << endl;
}
modFace
(
meshMod,
faceI,
newFace,
own,
nei,
patchID
);
}
faceUptodate[faceI] = true;
}
}
}
}
//
// Remove any faces on the non-anchor side of a split cell.
// Note: could loop through all cut cells only and check their faces but
// looping over all faces is cleaner and probably faster for dense
// cut patterns.
const faceList& faces = mesh().faces();
forAll(faces, faceI)
{
if (!faceUptodate[faceI])
{
// Get (new or original) owner and neighbour of faceI
label own, nei, patchID;
faceCells(cuts, exposedPatchI, faceI, own, nei, patchID);
if (own == -1 && nei == -1)
{
meshMod.setAction(polyRemoveFace(faceI));
if (debug & 2)
{
Pout<< "Removed face " << faceI << endl;
}
}
else
{
modFace(meshMod, faceI, faces[faceI], own, nei, patchID);
}
faceUptodate[faceI] = true;
}
}
if (debug)
{
Pout<< "meshCutAndRemove:" << nl
<< " cells split:" << cuts.nLoops() << nl
<< " faces added:" << addedFaces_.size() << nl
<< " points added on edges:" << addedPoints_.size() << nl
<< endl;
}
}
void CML::meshCutAndRemove::updateMesh(const mapPolyMesh& map)
{
// Update stored labels for mesh change.
{
Map<label> newAddedFaces(addedFaces_.size());
forAllConstIter(Map<label>, addedFaces_, iter)
{
label cellI = iter.key();
label newCellI = map.reverseCellMap()[cellI];
label addedFaceI = iter();
label newAddedFaceI = map.reverseFaceMap()[addedFaceI];
if ((newCellI >= 0) && (newAddedFaceI >= 0))
{
if
(
(debug & 2)
&& (newCellI != cellI || newAddedFaceI != addedFaceI)
)
{
Pout<< "meshCutAndRemove::updateMesh :"
<< " updating addedFace for cell " << cellI
<< " from " << addedFaceI
<< " to " << newAddedFaceI
<< endl;
}
newAddedFaces.insert(newCellI, newAddedFaceI);
}
}
// Copy
addedFaces_.transfer(newAddedFaces);
}
{
HashTable<label, edge, Hash<edge> > newAddedPoints(addedPoints_.size());
for
(
HashTable<label, edge, Hash<edge> >::const_iterator iter =
addedPoints_.begin();
iter != addedPoints_.end();
++iter
)
{
const edge& e = iter.key();
label newStart = map.reversePointMap()[e.start()];
label newEnd = map.reversePointMap()[e.end()];
label addedPointI = iter();
label newAddedPointI = map.reversePointMap()[addedPointI];
if ((newStart >= 0) && (newEnd >= 0) && (newAddedPointI >= 0))
{
edge newE = edge(newStart, newEnd);
if
(
(debug & 2)
&& (e != newE || newAddedPointI != addedPointI)
)
{
Pout<< "meshCutAndRemove::updateMesh :"
<< " updating addedPoints for edge " << e
<< " from " << addedPointI
<< " to " << newAddedPointI
<< endl;
}
newAddedPoints.insert(newE, newAddedPointI);
}
}
// Copy
addedPoints_.transfer(newAddedPoints);
}
}
// ************************************************************************* //
| 27.479824
| 80
| 0.435055
|
MrAwesomeRocks
|
2622eab5a23a648711817362a3f70a54c2c7b51c
| 10,696
|
hpp
|
C++
|
src/core/ArrayTraits.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
src/core/ArrayTraits.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
src/core/ArrayTraits.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | 1
|
2021-07-21T06:48:19.000Z
|
2021-07-21T06:48:19.000Z
|
// Copyright (c) 2020 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)
#ifndef OVK_CORE_ARRAY_TRAITS_HPP_INCLUDED
#define OVK_CORE_ARRAY_TRAITS_HPP_INCLUDED
#include <ovk/core/ArrayTraitsBase.hpp>
#include <ovk/core/Elem.hpp>
#include <ovk/core/Global.hpp>
#include <ovk/core/IntegerSequence.hpp>
#include <ovk/core/Interval.hpp>
#include <ovk/core/IteratorTraits.hpp>
#include <ovk/core/Requires.hpp>
#include <ovk/core/TypeTraits.hpp>
#include <array>
#include <cstddef>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
namespace ovk {
// C-style array
template <typename T> struct array_traits<T, OVK_SPECIALIZATION_REQUIRES(std::is_array<T>::value)> {
using value_type = typename std::remove_all_extents<T>::type;
static constexpr int Rank = std::rank<T>::value;
static constexpr array_layout Layout = array_layout::ROW_MAJOR;
template <int> static constexpr long long ExtentBegin() { return 0; }
template <int iDim> static constexpr long long ExtentEnd() { return std::extent<T,iDim>::value; }
// Not sure if there's a better way to do this that works for general multidimensional arrays
static const value_type *Data(const T &Array) {
return reinterpret_cast<const value_type *>(&Array[0]);
}
static value_type *Data(T &Array) {
return reinterpret_cast<value_type *>(&Array[0]);
}
};
// std::array
template <typename T, std::size_t N> struct array_traits<std::array<T,N>> {
using value_type = T;
static constexpr int Rank = 1;
static constexpr array_layout Layout = array_layout::ROW_MAJOR;
template <int> static constexpr long long ExtentBegin() { return 0; }
template <int> static constexpr long long ExtentEnd() { return N; }
static const T *Data(const std::array<T,N> &Array) { return Array.data(); }
static T *Data(std::array<T,N> &Array) { return Array.data(); }
};
// std::vector
template <typename T, typename Allocator> struct array_traits<std::vector<T, Allocator>> {
using value_type = T;
static constexpr int Rank = 1;
static constexpr array_layout Layout = array_layout::ROW_MAJOR;
template <int> static long long ExtentBegin(const std::vector<T, Allocator> &) { return 0; }
template <int> static long long ExtentEnd(const std::vector<T, Allocator> &Vec) {
return Vec.size();
}
static const T *Data(const std::vector<T, Allocator> &Vec) { return Vec.data(); }
static T *Data(std::vector<T, Allocator> &Vec) { return Vec.data(); }
};
// std::basic_string
template <typename CharT, typename Traits, typename Allocator> struct array_traits<
std::basic_string<CharT, Traits, Allocator>> {
using value_type = CharT;
static constexpr int Rank = 1;
static constexpr array_layout Layout = array_layout::ROW_MAJOR;
template <int> static long long ExtentBegin(const std::basic_string<CharT, Traits, Allocator> &) {
return 0;
}
template <int> static long long ExtentEnd(const std::basic_string<CharT, Traits, Allocator>
&String) {
return String.length();
}
static const CharT *Data(const std::basic_string<CharT, Traits, Allocator> &String) {
return String.c_str();
}
// No non-const Data access
};
namespace core {
namespace array_value_type_internal {
template <typename T, typename=void> struct helper;
template <typename T> struct helper<T, OVK_SPECIALIZATION_REQUIRES(IsArray<T>())> {
using type = typename array_traits<T>::value_type;
};
template <typename T> struct helper<T, OVK_SPECIALIZATION_REQUIRES(!IsArray<T>())> {
using type = std::false_type;
};
}
template <typename T> using array_value_type = typename array_value_type_internal::helper<T>::type;
template <typename T, OVK_FUNCTION_REQUIRES(IsArray<T>())> constexpr array_layout ArrayLayout() {
return array_traits<T>::Layout;
}
template <typename T, OVK_FUNCTION_REQUIRES(!IsArray<T>())> constexpr array_layout ArrayLayout() {
return array_layout::ROW_MAJOR;
}
template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(IsArray<T>())>
constexpr bool ArrayHasFootprint() {
return ArrayRank<T>() == Rank && (Rank == 1 || ArrayLayout<T>() == Layout);
}
template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(!IsArray<T>())>
constexpr bool ArrayHasFootprint() {
return false;
}
template <typename T, typename U, OVK_FUNCTION_REQUIRES(IsArray<T>() && IsArray<U>())>
constexpr bool ArraysAreCongruent() {
return ArrayRank<T>() == ArrayRank<U>() && (ArrayRank<T>() == 1 || ArrayLayout<T>() ==
ArrayLayout<U>());
}
template <typename T, typename U, OVK_FUNCTION_REQUIRES(!IsArray<T>() || !IsArray<U>())>
constexpr bool ArraysAreCongruent() {
return false;
}
namespace array_extents_internal {
template <typename TupleElementType, typename ArrayType, std::size_t... Indices> constexpr
interval<TupleElementType,ArrayRank<ArrayType>()> StaticHelper(core::index_sequence<Indices...>) {
return {
{TupleElementType(array_traits<ArrayType>::template ExtentBegin<Indices>())...},
{TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>())...}
};
}
template <typename TupleElementType, typename ArrayType, std::size_t... Indices> interval<
TupleElementType,ArrayRank<ArrayType>()> RuntimeHelper(core::index_sequence<Indices...>, const
ArrayType &Array) {
return {
{TupleElementType(array_traits<ArrayType>::template ExtentBegin<Indices>(Array))...},
{TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>(Array))...}
};
}
}
template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasStaticExtents<ArrayType>())> constexpr interval<TupleElementType,
ArrayRank<ArrayType>()> ArrayExtents(const ArrayType &) {
return array_extents_internal::StaticHelper<TupleElementType, ArrayType>(
core::index_sequence_of_size<ArrayRank<ArrayType>()>());
}
template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasRuntimeExtents<ArrayType>())> interval<TupleElementType,ArrayRank<
ArrayType>()> ArrayExtents(const ArrayType &Array) {
return array_extents_internal::RuntimeHelper<TupleElementType, ArrayType>(
core::index_sequence_of_size<ArrayRank<ArrayType>()>(), Array);
}
namespace array_size_internal {
template <typename TupleElementType, typename ArrayType, std::size_t... Indices> constexpr
elem<TupleElementType,ArrayRank<ArrayType>()> StaticHelper(core::index_sequence<Indices...>) {
return {TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>() -
array_traits<ArrayType>::template ExtentBegin<Indices>())...};
}
template <typename TupleElementType, typename ArrayType, std::size_t... Indices> elem<
TupleElementType,ArrayRank<ArrayType>()> RuntimeHelper(core::index_sequence<Indices...>, const
ArrayType &Array) {
return {TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>(Array) -
array_traits<ArrayType>::template ExtentBegin<Indices>(Array))...};
}
}
template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasStaticExtents<ArrayType>())> constexpr elem<TupleElementType,ArrayRank<
ArrayType>()> ArraySize(const ArrayType &) {
return array_size_internal::StaticHelper<TupleElementType, ArrayType>(
core::index_sequence_of_size<ArrayRank<ArrayType>()>());
}
template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasRuntimeExtents<ArrayType>())> elem<TupleElementType,ArrayRank<ArrayType>()
> ArraySize(const ArrayType &Array) {
return array_size_internal::RuntimeHelper<TupleElementType, ArrayType>(
core::index_sequence_of_size<ArrayRank<ArrayType>()>(), Array);
}
namespace array_count_internal {
template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim ==
ArrayRank<ArrayType>()-1)> constexpr IndexType StaticHelper() {
return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>() -
array_traits<ArrayType>::template ExtentBegin<Dim>());
}
template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim <
ArrayRank<ArrayType>()-1)> constexpr IndexType StaticHelper() {
return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>() - array_traits<ArrayType>::
template ExtentBegin<Dim>()) * StaticHelper<IndexType, ArrayType, Dim+1>();
}
template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim ==
ArrayRank<ArrayType>()-1)> IndexType RuntimeHelper(const ArrayType &Array) {
return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>(Array) -
array_traits<ArrayType>::template ExtentBegin<Dim>(Array));
}
template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim <
ArrayRank<ArrayType>()-1)> IndexType RuntimeHelper(const ArrayType &Array) {
return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>(Array) - array_traits<
ArrayType>::template ExtentBegin<Dim>(Array)) * RuntimeHelper<IndexType, ArrayType, Dim+1>(
Array);
}
}
template <typename IndexType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasStaticExtents<ArrayType>())> constexpr IndexType ArrayCount(const
ArrayType &) {
return array_count_internal::StaticHelper<IndexType, ArrayType, 0>();
}
template <typename IndexType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasRuntimeExtents<ArrayType>())> IndexType ArrayCount(const ArrayType
&Array) {
return array_count_internal::RuntimeHelper<IndexType, ArrayType, 0>(Array);
}
template <typename ArrayRefType, OVK_FUNCTION_REQUIRES(IsArray<remove_cvref<ArrayRefType>>())> auto
ArrayData(ArrayRefType &&Array) -> decltype(array_traits<remove_cvref<ArrayRefType>>::Data(
std::forward<ArrayRefType>(Array))) {
return array_traits<remove_cvref<ArrayRefType>>::Data(std::forward<ArrayRefType>(Array));
}
template <typename ArrayRefType, OVK_FUNCTION_REQUIRES(IsArray<remove_cvref<ArrayRefType>>())> auto
ArrayBegin(ArrayRefType &&Array) -> decltype(MakeForwardingIterator<array_access_type<
ArrayRefType &&>>(ArrayData(Array))) {
return MakeForwardingIterator<array_access_type<ArrayRefType &&>>(ArrayData(Array));
}
template <typename ArrayRefType, OVK_FUNCTION_REQUIRES(IsArray<remove_cvref<ArrayRefType>>())> auto
ArrayEnd(ArrayRefType &&Array) -> decltype(MakeForwardingIterator<array_access_type<
ArrayRefType &&>>(core::ArrayData(Array)+ArrayCount(Array))) {
return MakeForwardingIterator<array_access_type<ArrayRefType &&>>(ArrayData(Array)+
ArrayCount(Array));
}
}
}
#endif
| 45.130802
| 100
| 0.755984
|
gyzhangqm
|
2626448ee8c472a55023f86a2caaea7f08d76247
| 158
|
cpp
|
C++
|
old/Codeforces/466/A.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 7
|
2018-04-14T14:55:51.000Z
|
2022-01-31T10:49:49.000Z
|
old/Codeforces/466/A.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 5
|
2018-04-14T14:28:49.000Z
|
2019-05-11T02:22:10.000Z
|
old/Codeforces/466/A.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | null | null | null |
#include "template.hpp"
int main() {
int n, m, a, b;
cin >> n >> m >> a >> b;
cout << min(n * a, min(n / m * b + n % m * a, n / m * b + b)) << endl;
}
| 19.75
| 72
| 0.411392
|
not522
|
26290ecf777c44a6fc4b1ab9cd0cbf89918f0d97
| 1,208
|
hh
|
C++
|
recorder/src/main/cpp/blocking_ring_buffer.hh
|
Flipkart/fk-prof
|
ed801c32a8c3704204be670e16c6465297431e1a
|
[
"Apache-2.0",
"MIT"
] | 7
|
2017-01-17T11:29:08.000Z
|
2021-06-07T10:36:59.000Z
|
recorder/src/main/cpp/blocking_ring_buffer.hh
|
Flipkart/fk-prof
|
ed801c32a8c3704204be670e16c6465297431e1a
|
[
"Apache-2.0",
"MIT"
] | 106
|
2017-01-12T04:38:40.000Z
|
2017-10-04T11:12:54.000Z
|
recorder/src/main/cpp/blocking_ring_buffer.hh
|
Flipkart/fk-prof
|
ed801c32a8c3704204be670e16c6465297431e1a
|
[
"Apache-2.0",
"MIT"
] | 4
|
2016-12-22T08:56:27.000Z
|
2018-07-26T17:13:42.000Z
|
#ifndef BLOCKING_RING_BUFFER_H
#define BLOCKING_RING_BUFFER_H
#include <thread>
#include <mutex>
#include <condition_variable>
#include "globals.hh"
class BlockingRingBuffer {
private:
std::uint32_t read_idx, write_idx, capacity, available;
std::uint8_t *buff;
bool allow_writes;
std::mutex m;
std::condition_variable writable, readable;
std::uint32_t write_noblock(const std::uint8_t *from, std::uint32_t& offset, std::uint32_t& sz);
std::uint32_t read_noblock(std::uint8_t *to, std::uint32_t& offset, std::uint32_t& sz);
metrics::Timer& s_t_write;
metrics::Timer& s_t_write_wait;
metrics::Hist& s_h_write_sz;
metrics::Timer& s_t_read;
metrics::Timer& s_t_read_wait;
metrics::Hist& s_h_read_sz;
public:
static constexpr std::uint32_t DEFAULT_RING_SZ = 1024 * 1024;
BlockingRingBuffer(std::uint32_t _capacity = DEFAULT_RING_SZ);
~BlockingRingBuffer();
std::uint32_t write(const std::uint8_t *from, std::uint32_t offset, std::uint32_t sz, bool do_block = true);
std::uint32_t read(std::uint8_t *to, std::uint32_t offset, std::uint32_t sz, bool do_block = true);
std::uint32_t reset();
void readonly();
};
#endif
| 26.844444
| 112
| 0.712748
|
Flipkart
|
262cab7befc0663f26883159779c9a7d1d2edb3a
| 4,246
|
hpp
|
C++
|
include/gamma/basis.hpp
|
robashaw/gamma
|
26fba31be640c9bc429f8c22d5c61c0f8e9215e6
|
[
"MIT"
] | 8
|
2019-09-13T10:35:26.000Z
|
2022-03-26T13:20:54.000Z
|
include/gamma/basis.hpp
|
robashaw/gamma
|
26fba31be640c9bc429f8c22d5c61c0f8e9215e6
|
[
"MIT"
] | null | null | null |
include/gamma/basis.hpp
|
robashaw/gamma
|
26fba31be640c9bc429f8c22d5c61c0f8e9215e6
|
[
"MIT"
] | null | null | null |
/*
*
* PURPOSE: To define the class Basis representing a
* basis set.
*
* class Basis:
* owns: bfs - a set of BFs
* data: name - the name of the basis set, needed for file io
* charges - a list of atomic numbers corresponding to
* each BF in bfs.
* shells - a list representing which bfs are in which
* shells - i.e. if the first 3 are in one shell,
* the next two in another, etc, it would be
* 3, 2, ...
* lnums - a list with the angular quantum number
* of each shell in shells
* routines:
* findPosition(q) - find the first position in the bfs
* array of an atom of atomic number q
* findShellPosition(q) - find the first position in the
* shells array
* getNBFs() - returns the total number of basis functions
* getName() - returns the name
* getCharges() - returns the vector of charges
* getBF(charge, i) - return the ith BF corresponding to
* an atom of atomic number charge
* getSize(charge) - return how many basis functions an atom
* of atomic number charge has
* getShellSize(charge) - return how many shells it has
* getShells(charge) - return a vector of the correct subset
* of shells
* getLnums(charge) - return vector of subset of lnums
*
*
* DATE AUTHOR CHANGES
* ====================================================================
* 27/08/15 Robert Shaw Original code.
*
*/
#ifndef BASISHEADERDEF
#define BASISHEADERDEF
// Includes
#include "eigen_wrapper.hpp"
#include <string>
#include <libint2.hpp>
#include <vector>
#include <map>
#include "libecpint/gshell.hpp"
// Forward declarations
class BF;
// Begin class definitions
class Basis
{
private:
std::map<int, std::string> names;
std::string name;
int maxl, nexps;
bool ecps;
std::vector<std::vector <libint2::Shell::Contraction>> raw_contractions;
std::vector<libint2::Shell> intShells;
std::vector<libint2::Shell> jkShells;
std::vector<libint2::Shell> riShells;
std::vector<int> shellAtomList;
std::vector<int> jkShellAtomList;
std::vector<int> riShellAtomList;
public:
// Constructors and destructor
// Note - no copy constructor, as it doesn't really seem necessary
// Need to specify the name of the basis, n, and a list of the
// distinct atoms that are needed (as a vector of atomic numbers)
Basis() : name("Undefined"), nexps(-1) { } // Default constructor
Basis(std::map<int, std::string> ns, bool _ecps = false);
// Accessors
bool hasECPS() const { return ecps; }
std::string getName(int q) const;
std::string getName() const { return name; }
std::map<int, std::string>& getNames() { return names; }
int getShellAtom(int i) const { return shellAtomList[i]; }
int getJKShellAtom(int i) const { return jkShellAtomList[i]; }
int getRIShellAtom(int i) const { return riShellAtomList[i]; }
std::vector<libint2::Shell>& getIntShells() { return intShells; }
std::vector<libint2::Shell>& getJKShells() { return jkShells; }
std::vector<libint2::Shell>& getRIShells() { return riShells; }
std::vector<int>& getShellAtomList() { return shellAtomList; }
std::vector<int>& getJKShellAtomList() { return jkShellAtomList; }
std::vector<int>& getRIShellAtomList() { return riShellAtomList; }
int getNExps();
int getMaxL() const { return maxl; }
void setMaxL(int l) { maxl = l; }
double getExp(int i) const;
void setExp(int i, double value);
double extent() const;
void addShell(libecpint::GaussianShell& g, int atom, int type = 0);
// Overloaded operators
Basis& operator=(const Basis& other);
};
#endif
| 38.252252
| 79
| 0.567358
|
robashaw
|
262e2c6360952d755e2279fb0b1cfb7972446d70
| 1,348
|
cpp
|
C++
|
Kattis/Week0/Wk0j_interpreter.cpp
|
Frodocz/CS2040C
|
d2e132a2f3cf56eef3f725990c7ffcf71a6a76d5
|
[
"MIT"
] | null | null | null |
Kattis/Week0/Wk0j_interpreter.cpp
|
Frodocz/CS2040C
|
d2e132a2f3cf56eef3f725990c7ffcf71a6a76d5
|
[
"MIT"
] | null | null | null |
Kattis/Week0/Wk0j_interpreter.cpp
|
Frodocz/CS2040C
|
d2e132a2f3cf56eef3f725990c7ffcf71a6a76d5
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
#define MEMORY_SIZE 1000
#define REGISTER_NUM 10
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int i, cnt = 0, idx = 0;
vector<int> registers(REGISTER_NUM), ram(MEMORY_SIZE);
while (cin >> i) {
ram[idx++] = i;
}
idx = 0;
while (true) {
++cnt;
i = ram[idx];
int op = i / 100, a = (i / 10) % 10, b = i % 10;
if (op == 1) {
break;
} else if (op == 2) {
registers[a] = b;
} else if (op == 3) {
registers[a] = (registers[a] + b) % 1000;
} else if (op == 4) {
registers[a] = (registers[a] * b) % 1000;
} else if (op == 5) {
registers[a] = registers[b];
} else if (op == 6) {
registers[a] = (registers[a] + registers[b]) % 1000;
} else if (op == 7) {
registers[a] = (registers[a] * registers[b]) % 1000;
} else if (op == 8) {
registers[a] = ram[registers[b]];
} else if (i / 100 == 9) {
ram[registers[b]] = registers[a];
} else {
if (registers[b] != 0) {
idx = registers[a];
continue;
}
}
++idx;
}
cout << cnt << endl;
return 0;
}
| 24.962963
| 64
| 0.432493
|
Frodocz
|
262e2d197cb7945f4341134e31eac2a8530912dd
| 1,966
|
cpp
|
C++
|
AMM/multiPage.cpp
|
CatOfBlades/ArbitraryMemoryMapper
|
ef49c548b6171ca1b3cac61c5cb6366ca6039abc
|
[
"MIT"
] | null | null | null |
AMM/multiPage.cpp
|
CatOfBlades/ArbitraryMemoryMapper
|
ef49c548b6171ca1b3cac61c5cb6366ca6039abc
|
[
"MIT"
] | null | null | null |
AMM/multiPage.cpp
|
CatOfBlades/ArbitraryMemoryMapper
|
ef49c548b6171ca1b3cac61c5cb6366ca6039abc
|
[
"MIT"
] | null | null | null |
#include "multiPage.h"
#include "../Defines.h"
#ifdef WINBUILD
#include <windows.h>
#endif // WINBUILD
unsigned long int multiPage::_size()
{
if(!bankList.size()){return 0;}
return bankList[_bankNum]->_size();
}
bool multiPage::_is_free()
{
if(!bankList.size()){return 0;}
return bankList[_bankNum]->_is_free();
}
unsigned char* multiPage::_content()
{
if(!bankList.size()){return 0;}
return bankList[_bankNum]->_content();
}
unsigned char multiPage::readByte(unsigned long int offset)
{
if(!bankList.size()){return 0;}
return bankList[_bankNum]->readByte(offset);
}
void multiPage::writeByte(unsigned long int offset,unsigned char Byt)
{
if(!bankList.size()){return;}
bankList[_bankNum]->writeByte(offset, Byt);
return;
}
void multiPage::readMem(unsigned long int offset,unsigned char* buffer ,unsigned long int len)
{
if(!bankList.size()){return;}
bankList[_bankNum]->readMem(offset, buffer, len);
return;
}
void multiPage::writeMem(unsigned long int offset,unsigned char* Byt,unsigned long int len)
{
if(!bankList.size()){return;}
bankList[_bankNum]->writeMem(offset, Byt, len);
return;
}
void multiPage::cleanupAndUnlink()
{
while(bankList.size()>0)
{
//bankList.back()->cleanupAndUnlink();
//If we handle the cleanup elsewhere it allows us even more self reference nonsense.
bankList.pop_back();
}
return;
}
void multiPage::addBank(addressSpace* AS)
{
bankList.push_back(AS);
}
void multiPage::switchBank(int bankNum)
{
bankNum = bankNum%bankList.size();
_bankNum = bankNum;
}
void multiPage::removeBank(int bankNum)
{
bankList.erase(bankList.begin()+bankNum);
}
void multiPage::removeAndUnlinkBank(int bankNum)
{
addressSpace* bank = bankList[bankNum];
bankList.erase(bankList.begin()+bankNum);
bank->cleanupAndUnlink();
}
multiPage::multiPage():addressSpace()
{
memoryTypeID = "multpage";
_bankNum=0;
}
| 22.860465
| 96
| 0.685656
|
CatOfBlades
|
1c79f5bbe1b6b243c5446a39d6116e47b4c0efac
| 2,049
|
cpp
|
C++
|
ECOO/ECOO '19 R1 P3 - Side Scrolling Simulator.cpp
|
Joon7891/Competitive-Programming
|
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
|
[
"MIT"
] | 2
|
2021-04-13T00:19:56.000Z
|
2021-04-13T01:19:45.000Z
|
ECOO/ECOO '19 R1 P3 - Side Scrolling Simulator.cpp
|
Joon7891/Competitive-Programming
|
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
|
[
"MIT"
] | null | null | null |
ECOO/ECOO '19 R1 P3 - Side Scrolling Simulator.cpp
|
Joon7891/Competitive-Programming
|
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
|
[
"MIT"
] | 1
|
2020-08-26T12:36:08.000Z
|
2020-08-26T12:36:08.000Z
|
#include <bits/stdc++.h>
#define MEM(a, b) memset(a, b, sizeof(a))
using namespace std;
void solve(){
char a[105][13];
MEM(a,'@');
int j, w, h;
cin>> j >> w >> h;
string s;
int x = 0,y = h - 2;
for(int i = 0; i < h; i++)
{
cin >> s;
for(int j = 0; j < w; j++)
{
a[j][i] = s[j];
if(s[j] == 'L')
{
x = j;
}
}
}
while(1)
{
if(a[x][y] == 'G'){
cout << "CLEAR" << endl;
return;
}
else if (a[x + 1][y] == '.'|| a[x + 1][y] == 'G')
{
x++;
}
else if(a[x + 1][y] != '.')
{
bool c = 0;
for(int i = 1; i <= j; i++)
{
if(y - i < 0) continue;
if(x + 2 >= w) continue;
bool l = 1;
for(int k = h - 1; k >= y - i; k--)
{
if(a[x][k] == '@') l = 0;
}
if(!l) continue;
bool n=1;
for(int k = h-1; k >= y-i; k--)
{
if(a[x + 2][k] == '@') n = 0;
}
if(n==0) continue;
if(a[x][y - i] != '.') continue;
if(y - i < 0)
{
if(a[x + 2][y - i] == '.')
{
x = x + 2;
y = y - i;
c = 1;
break;
}
}
if (a[x + 1][y - i] == '.')
{
c = 1;
x = x+2;
break;
}
}
if(!c)
{
cout << x+2 << endl;
return;
}
}
}
}
int main()
{
ios_base::sync_with_stdio(NULL);
cin.tie(0);
cout.tie(0);
for(int i = 0; i < 10; i++)
{
solve();
}
}
| 19.514286
| 57
| 0.226452
|
Joon7891
|
1c7a23c69da6a8ca7bcfc1c13c3afcd7d8b5ab15
| 11,114
|
cpp
|
C++
|
src/EBV_Triangulator.cpp
|
fdebrain/Stereo-Event-Based-Reconstruction-with-Active-Laser-Features
|
9e63a5d15edffba65d6e6ab521c5f6413832a97c
|
[
"MIT"
] | 4
|
2021-08-10T17:35:35.000Z
|
2021-12-06T08:43:07.000Z
|
src/EBV_Triangulator.cpp
|
fdebrain/Stereo-Event-Based-Reconstruction-with-Active-Laser-Features
|
9e63a5d15edffba65d6e6ab521c5f6413832a97c
|
[
"MIT"
] | null | null | null |
src/EBV_Triangulator.cpp
|
fdebrain/Stereo-Event-Based-Reconstruction-with-Active-Laser-Features
|
9e63a5d15edffba65d6e6ab521c5f6413832a97c
|
[
"MIT"
] | null | null | null |
#include <EBV_Triangulator.h>
#include <EBV_Benchmarking.h>
void Triangulator::switchMode()
{
m_mode = static_cast<Triangulator::StereoPair>((m_mode+1)%3);
std::cout << "Switch triangulation mode to: " << stereoPairNames[m_mode] << "\n\r";
}
void Triangulator::resetCalibration()
{
for (auto &k : m_K) { k = cv::Mat(3,3,CV_64FC1); }
for (auto &d : m_D) { d = cv::Mat(1,5,CV_32FC1); }
for (auto &r : m_R) { r = cv::Mat(3,3,CV_32FC1); }
for (auto &t : m_T) { t = cv::Mat(3,1,CV_32FC1); }
for (auto &f : m_F) { f = cv::Mat(3,3,CV_32FC1); }
for (auto &q : m_Q) { q = cv::Mat(4,4,CV_32FC1); }
for (auto &p : m_P) { p[0] = cv::Mat(3,4,CV_32FC1); p[1] = cv::Mat(3,4,CV_32FC1); }
for (auto &rect : m_Rect) { rect[0] = cv::Mat(3,3,CV_32FC1); rect[1] = cv::Mat(3,3,CV_32FC1); }
m_Pfix = cv::Mat(3,4,CV_32FC1);
}
void Triangulator::importCalibration()
{
resetCalibration();
cv::FileStorage fs;
// Import camera calibration
fs.open(m_path_calib_cam, cv::FileStorage::READ);
fs["camera_matrix0"] >> m_K[0];
fs["dist_coeffs0"] >> m_D[0];
fs["camera_matrix1"] >> m_K[1];
fs["dist_coeffs1"] >> m_D[1];
fs["R"] >> m_R[0];
fs["T"] >> m_T[0];
fs["F"] >> m_F[0];
std::cout << "K0: " << m_K[0] << "\n\r";
std::cout << "D0: " << m_D[0] << "\n\r";
std::cout << "K1: " << m_K[1] << "\n\r";
std::cout << "D1: " << m_D[1] << "\n\r";
std::cout << "R: " << m_R[0] << "\n\r";
std::cout << "T: " << m_T[0] << "\n\r";
std::cout << "F: " << m_F[0] << "\n\r";
fs.release();
// Import laser calibration
fs.open(m_path_calib_laser, cv::FileStorage::READ);
fs["camera_matrix_laser"] >> m_K[2];
fs["dist_coeffs_laser"] >> m_D[2];
fs["R1"] >> m_R[1];
fs["T1"] >> m_T[1];
fs["F1"] >> m_F[1];
fs["R2"] >> m_R[2];
fs["T2"] >> m_T[2];
fs["F2"] >> m_F[2];
std::cout << "KLaser: " << m_K[2] << "\n\r";
std::cout << "DLaser: " << m_D[2] << "\n\r";
std::cout << "R1: " << m_R[1] << "\n\r";
std::cout << "T1: " << m_T[1] << "\n\r";
std::cout << "F1: " << m_F[1] << "\n\r";
std::cout << "R2: " << m_R[2] << "\n\r";
std::cout << "T2: " << m_T[2] << "\n\r";
std::cout << "F2: " << m_F[2] << "\n\r";
fs.release();
// Initialize projection matrices for cam0-cam1 stereo pair
if (isValid(0) && isValid(1))
{
m_enable = true;
cv::stereoRectify(m_K[0],m_D[0],
m_K[1],m_D[1],
cv::Size(m_cols,m_rows),
m_R[0],m_T[0],
m_Rect[0][0], m_Rect[0][1],
m_P[0][0], m_P[0][1],
m_Q[0], cv::CALIB_ZERO_DISPARITY);
}
else
{
m_enable = false;
printf("Please press C to calibrate the cameras.\n\r");
return;
}
// Initialize projection matrices for cam0-laser & cam1-laser stereo pairs
if (isValid(0) && isValid(1) && isValid(2))
{
m_enable = true;
// CameraLeft-laser
cv::stereoRectify(m_K[0],m_D[0],
m_K[2],m_D[2],
cv::Size(m_cols,m_rows),
m_R[1],m_T[1],
m_Rect[1][0], m_Rect[1][1],
m_P[1][0], m_P[1][1],
m_Q[1], cv::CALIB_ZERO_DISPARITY);
//CameraRight-laser
cv::stereoRectify(m_K[1],m_D[1],
m_K[2],m_D[2],
cv::Size(m_cols,m_rows),
m_R[2],m_T[2],
m_Rect[2][0], m_Rect[2][1],
m_P[2][0], m_P[2][1],
m_Q[2], cv::CALIB_ZERO_DISPARITY);
}
else
{
m_enable = false;
printf("Please press C to calibrate the laser.\n\r");
return;
}
}
bool Triangulator::isValid(const int id) const
{
return m_K[id].rows==3 && m_K[id].cols==3 &&
m_D[id].rows==1 && m_D[id].cols==5;
}
Triangulator::Triangulator(Matcher* matcher,
LaserController* laser)
: m_matcher(matcher),
m_laser(laser)
{
// Initialize datastructures
resetCalibration();
// Listen to matcher
m_matcher->registerMatcherListener(this);
// Recording triangulation
if (m_record){ m_recorder.open(m_eventRecordFile); }
// Calibration
this->importCalibration();
if (m_enable) { m_thread = std::thread(&Triangulator::run,this); }
}
Triangulator::~Triangulator()
{
m_matcher->deregisterMatcherListener(this);
if (m_record){ m_recorder.close(); }
}
void Triangulator::run()
{
bool hasQueueEvent0;
bool hasQueueEvent1;
DAVIS240CEvent event0;
DAVIS240CEvent event1;
while(true)
{
m_queueAccessMutex0.lock();
hasQueueEvent0 =! m_evtQueue0.empty();
m_queueAccessMutex0.unlock();
m_queueAccessMutex1.lock();
hasQueueEvent1 =! m_evtQueue1.empty();
m_queueAccessMutex1.unlock();
// Process only if incoming filtered events in both cameras
if(hasQueueEvent0 && hasQueueEvent1)
{
m_queueAccessMutex0.lock();
event0 = m_evtQueue0.front();
m_evtQueue0.pop_front();
m_queueAccessMutex0.unlock();
m_queueAccessMutex1.lock();
event1 = m_evtQueue1.front();
m_evtQueue1.pop_front();
m_queueAccessMutex1.unlock();
process(event0,event1);
}
else
{
std::unique_lock<std::mutex> condLock(m_condWaitMutex);
m_condWait.wait(condLock);
condLock.unlock();
}
}
}
void Triangulator::receivedNewMatch(const DAVIS240CEvent& event0,
const DAVIS240CEvent& event1)
{
m_queueAccessMutex0.lock();
m_evtQueue0.push_back(event0);
m_queueAccessMutex0.unlock();
m_queueAccessMutex1.lock();
m_evtQueue1.push_back(event1);
m_queueAccessMutex1.unlock();
std::unique_lock<std::mutex> condLock(m_condWaitMutex);
m_condWait.notify_one();
}
void Triangulator::process(const DAVIS240CEvent& event0, const DAVIS240CEvent& event1)
{
//Timer timer; // 0.1ms on average
std::vector<cv::Point2d> coords0, coords1;
std::vector<cv::Point2d> undistCoords0, undistCoords1;
std::vector<cv::Point2d> undistCoordsCorrected0, undistCoordsCorrected1;
cv::Vec4d point3D;
m_queueAccessMutex0.lock();
const int x0 = event0.m_x;
const int y0 = event0.m_y;
const int x1 = event1.m_x;
const int y1 = event1.m_y;
//const int laser_x = 180*(m_laser->getX()-500)/(4000 - 500);
//const int laser_y = 240*(m_laser->getY())/(4000);
const int laser_x = static_cast<int>(180.*(event0.m_laser_x-500.)/(4000. - 500.));
const int laser_y = static_cast<int>(240.*(event0.m_laser_y)/(4000.));
m_queueAccessMutex0.unlock();
switch (m_mode)
{
case Cameras:
coords0.emplace_back(y0,x0);
coords1.emplace_back(y1,x1);
cv::undistortPoints(coords0, undistCoords0,
m_K[0], m_D[0],
m_Rect[m_mode][0],
m_P[m_mode][0]);
cv::undistortPoints(coords1, undistCoords1,
m_K[1], m_D[1],
m_Rect[m_mode][1],
m_P[m_mode][1]);
cv::triangulatePoints(m_P[m_mode][0], m_P[m_mode][1],
undistCoords0, //undistCoordsCorrected0
undistCoords1, //undistCoordsCorrected1
point3D);
break;
case CamLeftLaser:
coords0.emplace_back(y0,x0);
coords1.emplace_back(laser_y,laser_x);
cv::undistortPoints(coords0, undistCoords0,
m_K[0], m_D[0],
m_Rect[m_mode][0],
m_P[m_mode][0]);
cv::undistortPoints(coords1, undistCoords1,
m_K[2], m_D[2],
m_Rect[m_mode][1],
m_P[m_mode][1]);
// Refine matches coordinates (using epipolar constraint)
cv::correctMatches(m_F[m_mode],undistCoords0,undistCoords1,
undistCoordsCorrected0,
undistCoordsCorrected1);
cv::triangulatePoints(m_P[m_mode][0], m_P[m_mode][1],
undistCoordsCorrected0,
undistCoordsCorrected1,
point3D);
break;
case CamRightLaser:
coords0.emplace_back(y1,x1);
coords1.emplace_back(laser_y,laser_x);
cv::undistortPoints(coords0, undistCoords0,
m_K[1], m_D[1],
m_Rect[m_mode][0],
m_P[m_mode][0]);
cv::undistortPoints(coords1, undistCoords1,
m_K[2], m_D[2],
m_Rect[m_mode][1],
m_P[m_mode][1]);
// Refine matches coordinates (using epipolar constraint)
cv::correctMatches(m_F[m_mode],undistCoords0,undistCoords1,
undistCoordsCorrected0,
undistCoordsCorrected1);
cv::triangulatePoints(m_P[m_mode][0], m_P[m_mode][1],
undistCoordsCorrected0,
undistCoordsCorrected1,
point3D);
break;
}
// Convert to cm + scale
double scale = point3D[3];
double X = 100*point3D[0]/scale;
double Y = 100*point3D[1]/scale;
double Z = 100*point3D[2]/scale;
if (m_record) { recordPoint(X,Y,Z); }
warnDepth(x0,y0,X,Y,Z);
coords0.clear();
coords1.clear();
// DEBUG - CHECK 3D POINT POSITION
if (m_debug) { printf("Point at: (%2.1f,%2.1f,%2.1f,%2.1f). \n\r ",X,Y,Z,scale); }
// END DEBUG
}
void Triangulator::recordPoint(double X, double Y, double Z)
{
m_recorder << X << '\t'
<< Y << '\t'
<< Z << '\n';
}
void Triangulator::computeProjectionMatrix(cv::Mat K, cv::Mat R,
cv::Mat T, cv::Mat& P)
{
K.convertTo(K,CV_64FC1);
cv::hconcat(K*R,K*T,P);
}
void Triangulator::registerTriangulatorListener(TriangulatorListener* listener)
{
m_triangulatorListeners.push_back(listener);
}
void Triangulator::deregisterTriangulatorListener(TriangulatorListener* listener)
{
m_triangulatorListeners.remove(listener);
}
void Triangulator::warnDepth(const int u,
const int v,
const double X,
const double Y,
const double Z)
{
std::list<TriangulatorListener*>::iterator it;
for(it = m_triangulatorListeners.begin(); it!=m_triangulatorListeners.end(); it++)
{
(*it)->receivedNewDepth(u,v,X,Y,Z);
}
}
| 31.936782
| 99
| 0.520875
|
fdebrain
|
1c8540e0cc6f5f8955cf146e09cf4feb22d1cf64
| 9,058
|
cpp
|
C++
|
unittest/testTimer.cpp
|
airekans/Tpool
|
2ba21ca68588d90e738f35c6ddcc17bb8b1f3f1d
|
[
"MIT"
] | 13
|
2015-05-19T11:08:44.000Z
|
2021-07-11T01:00:35.000Z
|
unittest/testTimer.cpp
|
guker/Tpool
|
2ba21ca68588d90e738f35c6ddcc17bb8b1f3f1d
|
[
"MIT"
] | 17
|
2015-01-04T15:16:51.000Z
|
2015-04-16T04:43:38.000Z
|
unittest/testTimer.cpp
|
guker/Tpool
|
2ba21ca68588d90e738f35c6ddcc17bb8b1f3f1d
|
[
"MIT"
] | 11
|
2015-04-30T09:21:59.000Z
|
2021-10-04T07:48:34.000Z
|
#include "Timer.h"
#include "Atomic.h"
#include "Thread.h"
#include "TestUtil.h"
#include <gtest/gtest.h>
using namespace tpool;
using namespace tpool::unittest;
namespace {
class TimerTestSuite : public ::testing::Test
{
protected:
Atomic<int> counter;
TimerTestSuite()
: counter(0)
{}
virtual void SetUp()
{
counter = 0;
}
};
struct TestTimerTask : public TimerTask
{
Atomic<int>& counter;
TestTimerTask(Atomic<int>& cnt)
: counter(cnt)
{}
virtual void DoRun()
{
++counter;
}
};
}
TEST_F(TimerTestSuite, test_Ctor)
{
Timer timer;
}
TEST_F(TimerTestSuite, test_RunLater)
{
{
Timer timer;
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 200);
ASSERT_EQ(0, counter);
MilliSleep(500);
ASSERT_EQ(1, counter);
}
ASSERT_EQ(1, counter);
}
TEST_F(TimerTestSuite, test_RunLater_and_cancel_task)
{
{
Timer timer;
TimerTask::Ptr task(new TestTimerTask(counter));
timer.RunLater(task, 200);
ASSERT_EQ(0, counter);
task->Cancel();
ASSERT_EQ(0, counter);
}
ASSERT_EQ(0, counter);
}
TEST_F(TimerTestSuite, test_RunLater_and_async_cancel_task)
{
{
Timer timer;
TimerTask::Ptr task(new TestTimerTask(counter));
timer.RunLater(task, 200);
ASSERT_EQ(0, counter);
task->CancelAsync();
ASSERT_EQ(0, counter);
}
ASSERT_EQ(0, counter);
}
TEST_F(TimerTestSuite, test_RunLater_with_same_task)
{
{
Timer timer;
TimerTask::Ptr task(new TestTimerTask(counter));
ASSERT_TRUE(timer.RunLater(task, 200));
ASSERT_FALSE(timer.RunLater(task, 200));
ASSERT_EQ(0, counter);
MilliSleep(300);
ASSERT_EQ(1, counter);
}
ASSERT_EQ(1, counter);
}
TEST_F(TimerTestSuite, test_RunEvery)
{
{
Timer timer;
TimerTask::Ptr task(new TestTimerTask(counter));
timer.RunEvery(task, 500, true);
MilliSleep(100);
ASSERT_EQ(1, counter);
MilliSleep(1100);
ASSERT_EQ(3, counter);
}
ASSERT_EQ(3, counter);
}
TEST_F(TimerTestSuite, test_RunEvery_with_same_task)
{
{
Timer timer;
TimerTask::Ptr task(new TestTimerTask(counter));
ASSERT_TRUE(timer.RunEvery(task, 500, true));
ASSERT_FALSE(timer.RunEvery(task, 500, true));
MilliSleep(100);
ASSERT_EQ(1, counter);
MilliSleep(1100);
ASSERT_EQ(3, counter);
}
ASSERT_EQ(3, counter);
}
TEST_F(TimerTestSuite, test_RunEvery_and_not_run_now)
{
{
Timer timer;
TimerTask::Ptr task(new TestTimerTask(counter));
timer.RunEvery(task, 500, false);
MilliSleep(100);
ASSERT_EQ(0, counter);
MilliSleep(1100);
ASSERT_EQ(2, counter);
}
ASSERT_EQ(2, counter);
}
TEST_F(TimerTestSuite, test_RunEvery_and_cancel)
{
{
Timer timer;
TimerTask::Ptr task(new TestTimerTask(counter));
timer.RunEvery(task, 500, true);
MilliSleep(100);
ASSERT_EQ(1, counter);
MilliSleep(500);
ASSERT_EQ(2, counter);
task->Cancel();
MilliSleep(500);
ASSERT_EQ(2, counter);
}
ASSERT_EQ(2, counter);
}
TEST_F(TimerTestSuite, test_Run_with_multiple_tasks)
{
{
Timer timer;
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 200);
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 100);
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 300);
ASSERT_EQ(0, counter);
MilliSleep(200);
ASSERT_GT(counter, 0);
MilliSleep(500);
ASSERT_EQ(3, counter);
}
ASSERT_EQ(3, counter);
}
namespace {
struct TestTimerFunc
{
Atomic<int>& counter;
TestTimerFunc(Atomic<int>& cnt)
: counter(cnt)
{}
void operator()()
{
++counter;
}
};
}
TEST_F(TimerTestSuite, test_RunLater_with_functor)
{
{
Timer timer;
timer.RunLater(TestTimerFunc(counter), 200);
ASSERT_EQ(0, counter);
MilliSleep(500);
ASSERT_EQ(1, counter);
}
ASSERT_EQ(1, counter);
}
namespace {
struct RunLaterThread {
Timer& m_timer;
Atomic<int>& m_counter;
TimeValue m_delay;
RunLaterThread(Timer& timer, Atomic<int>& counter,
TimeValue delay)
: m_timer(timer), m_counter(counter), m_delay(delay)
{}
void operator()()
{
m_timer.RunLater(TestTimerFunc(m_counter), m_delay);
}
};
}
TEST_F(TimerTestSuite, test_RunLater_with_multiple_threads)
{
{
Timer timer;
// create 2 threads to do RunLater
Thread thread1(RunLaterThread(timer, counter, 100));
Thread thread2(RunLaterThread(timer, counter, 100));
timer.RunLater(TestTimerFunc(counter), 100);
MilliSleep(300);
ASSERT_EQ(3, counter);
}
ASSERT_EQ(3, counter);
}
TEST_F(TimerTestSuite, test_RunEvery_with_functor)
{
{
Timer timer;
timer.RunEvery(TestTimerFunc(counter), 500, false);
ASSERT_EQ(0, counter);
MilliSleep(600);
ASSERT_EQ(1, counter);
MilliSleep(500);
ASSERT_EQ(2, counter);
}
ASSERT_EQ(2, counter);
}
namespace {
struct RunEveryThread {
Timer& m_timer;
Atomic<int>& m_counter;
TimeValue m_delay;
bool m_is_run_now;
RunEveryThread(Timer& timer, Atomic<int>& counter,
TimeValue delay, bool is_run_now)
: m_timer(timer), m_counter(counter), m_delay(delay),
m_is_run_now(is_run_now)
{}
void operator()()
{
m_timer.RunEvery(TestTimerFunc(m_counter), m_delay,
m_is_run_now);
}
};
}
TEST_F(TimerTestSuite, test_RunEvery_with_multiple_threads)
{
{
Timer timer;
// create 2 threads to do RunEvery
Thread thread1(RunEveryThread(timer, counter, 200, true));
Thread thread2(RunEveryThread(timer, counter, 200, true));
timer.RunEvery(TestTimerFunc(counter), 200, true);
MilliSleep(100);
ASSERT_EQ(3, counter);
MilliSleep(200);
ASSERT_EQ(6, counter);
}
ASSERT_EQ(6, counter);
}
namespace {
struct SelfCancelTimerTask : public TimerTask
{
Atomic<int>& counter;
const int cancel_count;
SelfCancelTimerTask(Atomic<int>& cnt, int cancel_cnt)
: counter(cnt), cancel_count(cancel_cnt)
{}
virtual void DoRun()
{
++counter;
if (counter == cancel_count)
{
CancelAsync();
}
}
};
}
TEST_F(TimerTestSuite, test_RunEvery_with_self_cancel_task)
{
{
Timer timer;
TimerTask::Ptr task(new SelfCancelTimerTask(counter, 3));
timer.RunEvery(task, 200, false);
MilliSleep(100);
ASSERT_EQ(0, counter);
while (!(task->IsCancelled()))
{
MilliSleep(200);
}
ASSERT_EQ(3, counter);
}
ASSERT_EQ(3, counter);
}
TEST_F(TimerTestSuite, test_StopAsync)
{
{
Timer timer;
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 500);
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 100);
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 1000);
ASSERT_EQ(0, counter);
MilliSleep(200);
ASSERT_EQ(1, counter);
timer.StopAsync();
}
ASSERT_EQ(1, counter);
}
TEST_F(TimerTestSuite, test_RunLater_after_StopAsync)
{
{
Timer timer;
TimerTask::Ptr task(new TestTimerTask(counter));
ASSERT_TRUE(timer.RunLater(task, 100));
ASSERT_EQ(0, counter);
MilliSleep(300);
ASSERT_EQ(1, counter);
timer.StopAsync();
TimerTask::Ptr task1(new TestTimerTask(counter));
ASSERT_FALSE(timer.RunLater(task1, 100));
ASSERT_EQ(1, counter);
MilliSleep(300);
ASSERT_EQ(1, counter);
}
ASSERT_EQ(1, counter);
}
TEST_F(TimerTestSuite, test_Stop)
{
{
Timer timer;
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 500);
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 100);
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 1000);
ASSERT_EQ(0, counter);
MilliSleep(200);
ASSERT_EQ(1, counter);
timer.Stop();
MilliSleep(500);
ASSERT_EQ(1, counter);
}
ASSERT_EQ(1, counter);
}
namespace {
struct TimerStopThread {
Timer& m_timer;
TimerStopThread(Timer& timer)
: m_timer(timer)
{}
void operator()()
{
m_timer.Stop();
}
};
}
TEST_F(TimerTestSuite, test_Stop_with_multiple_threads)
{
{
Timer timer;
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 500);
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 100);
timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 1000);
ASSERT_EQ(0, counter);
MilliSleep(200);
ASSERT_EQ(1, counter);
Thread thread1((TimerStopThread(timer)));
Thread thread2((TimerStopThread(timer)));
timer.Stop();
MilliSleep(500);
ASSERT_EQ(1, counter);
}
ASSERT_EQ(1, counter);
}
TEST_F(TimerTestSuite, test_RunLater_after_Stop)
{
{
Timer timer;
TimerTask::Ptr task(new TestTimerTask(counter));
ASSERT_TRUE(timer.RunLater(task, 100));
ASSERT_EQ(0, counter);
MilliSleep(300);
ASSERT_EQ(1, counter);
timer.Stop();
TimerTask::Ptr task1(new TestTimerTask(counter));
ASSERT_FALSE(timer.RunLater(task1, 100));
ASSERT_EQ(1, counter);
MilliSleep(300);
ASSERT_EQ(1, counter);
}
ASSERT_EQ(1, counter);
}
| 19.64859
| 69
| 0.659417
|
airekans
|
1c888ffbcbdae678e1772280f72ea0065ce94d34
| 3,040
|
cpp
|
C++
|
2018/0804_mujin-pc-2018/E.cpp
|
kazunetakahashi/atcoder
|
16ce65829ccc180260b19316e276c2fcf6606c53
|
[
"MIT"
] | 7
|
2019-03-24T14:06:29.000Z
|
2020-09-17T21:16:36.000Z
|
2018/0804_mujin-pc-2018/E.cpp
|
kazunetakahashi/atcoder
|
16ce65829ccc180260b19316e276c2fcf6606c53
|
[
"MIT"
] | null | null | null |
2018/0804_mujin-pc-2018/E.cpp
|
kazunetakahashi/atcoder
|
16ce65829ccc180260b19316e276c2fcf6606c53
|
[
"MIT"
] | 1
|
2020-07-22T17:27:09.000Z
|
2020-07-22T17:27:09.000Z
|
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 2018-8-4 22:09:58
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const char ds[4] = {'D', 'R', 'U', 'L'};
typedef tuple<ll, int, int> state;
// const int C = 1e6+10;
const ll infty = 10000000000007;
int N, M, K;
string D;
string S[1010];
ll dist[300010][4];
ll ans[1010][1010];
int main()
{
cin >> N >> M >> K;
cin >> D;
D = D + D + D;
for (auto i = 0; i < N; i++)
{
cin >> S[i];
}
for (auto k = 0; k < 4; k++)
{
dist[3 * K][k] = infty;
}
for (int i = 3 * K - 1; i >= 0; i--)
{
for (auto k = 0; k < 4; k++)
{
if (D[i] == ds[k])
{
dist[i][k] = 1;
}
else
{
dist[i][k] = dist[i + 1][k] + 1;
}
}
}
/*
for (auto i = 0; i < K; i++)
{
for (auto k = 0; k < 4; k++)
{
cerr << "dist[" << i << "][" << k << "] = " << dist[i][k] << endl;
}
}
*/
int sx, sy, gx, gy;
fill(&ans[0][0], &ans[0][0] + 1010 * 1010, -1);
for (auto i = 0; i < N; i++)
{
for (auto j = 0; j < M; j++)
{
if (S[i][j] == 'S')
{
sx = i;
sy = j;
}
else if (S[i][j] == 'G')
{
gx = i;
gy = j;
}
}
}
priority_queue<state, vector<state>, greater<state>> Q;
Q.push(state(0, sx, sy));
while (!Q.empty())
{
ll d = get<0>(Q.top());
int x = get<1>(Q.top());
int y = get<2>(Q.top());
Q.pop();
if (ans[x][y] == -1)
{
ans[x][y] = d;
// cerr << "ans[" << x << "][" << y << "] = " << ans[x][y] << endl;
if (x == gx && y == gy)
{
cout << d << endl;
return 0;
}
for (auto k = 0; k < 4; k++)
{
int new_x = x + dx[k];
int new_y = y + dy[k];
if (0 <= new_x && new_x < N && 0 <= new_y && new_y < M && S[new_x][new_y] != '#' && ans[new_x][new_y] == -1)
{
ll new_d = d + dist[d % K][k];
if (new_d < infty)
{
Q.push(state(new_d, new_x, new_y));
}
}
}
}
}
cout << -1 << endl;
}
| 22.189781
| 116
| 0.464474
|
kazunetakahashi
|
1c88b3e9ef72afba9c9d5b45ba8a309c3ef87f97
| 1,032
|
hpp
|
C++
|
src/emp_dist.hpp
|
dcjones/isolator
|
24bafc0a102dce213bfc2b5b9744136ceadaba03
|
[
"MIT"
] | 33
|
2015-07-13T03:00:01.000Z
|
2021-03-20T08:49:07.000Z
|
src/emp_dist.hpp
|
dcjones/isolator
|
24bafc0a102dce213bfc2b5b9744136ceadaba03
|
[
"MIT"
] | 9
|
2016-11-29T00:04:30.000Z
|
2020-02-10T17:46:01.000Z
|
src/emp_dist.hpp
|
dcjones/isolator
|
24bafc0a102dce213bfc2b5b9744136ceadaba03
|
[
"MIT"
] | 6
|
2015-09-10T15:49:34.000Z
|
2017-03-09T05:14:06.000Z
|
#ifndef ISOLATOR_EMP_DIST
#define ISOLATOR_EMP_DIST
#include <climits>
#include <vector>
class EmpDist
{
public:
EmpDist(EmpDist&);
/* Construct a emperical distribution from n observations stored in xs.
*
* Input in run-length encoded samples, which must be in sorted order.
*
* Args:
* vals: An array of unique observations.
* lens: Nuber of occurances for each observation.
* n: Length of vals and lens.
*/
EmpDist(const unsigned int* vals,
const unsigned int* lens,
size_t n);
/* Compute the median of the distribution. */
float median() const;
/* Probability density function. */
float pdf(unsigned int x) const;
/* Comulative p robabability. */
float cdf(unsigned int x) const;
private:
std::vector<float> pdfvals;
std::vector<float> cdfvals;
/* Precomputed median */
float med;
};
#endif
| 21.061224
| 79
| 0.573643
|
dcjones
|
1c90d631037316fe7681bb0a8018a698d72eeb8c
| 7,897
|
cpp
|
C++
|
src/toolbar.cpp
|
alekratz/fiefdom
|
d0ddb1cc4fe24b57319b3089928c1a576d0c1bbc
|
[
"0BSD"
] | 1
|
2017-05-19T15:24:51.000Z
|
2017-05-19T15:24:51.000Z
|
src/toolbar.cpp
|
alekratz/fiefdom
|
d0ddb1cc4fe24b57319b3089928c1a576d0c1bbc
|
[
"0BSD"
] | null | null | null |
src/toolbar.cpp
|
alekratz/fiefdom
|
d0ddb1cc4fe24b57319b3089928c1a576d0c1bbc
|
[
"0BSD"
] | null | null | null |
#include "toolbar.hpp"
#include "game_scene.hpp"
#include "globals.hpp"
#include <SDL_ttf.h>
#include <SDL.h>
#include <cassert>
constexpr auto TOOLBAR_HEIGHT = 23;
constexpr auto TOOLBAR_ITEM_VPADDING = 3;
constexpr auto TOOLBAR_ITEM_HPADDING = 13;
//const SDL_Color WHITE { 255, 255, 255, SDL_ALPHA_OPAQUE };
// const SDL_Color BLACK { 0, 0, 0, SDL_ALPHA_OPAQUE };
template<typename CallbackT>
Toolbar<CallbackT>::Toolbar(CallbackT& game_state, int32_t y_offset)
: m_game_state(game_state)
, m_x_offset(TOOLBAR_ITEM_HPADDING)
, m_y_offset(y_offset) { }
template<typename CallbackT>
void Toolbar<CallbackT>::untoggle_all() {
for(auto& t : m_items) {
t->toggled = false;
}
}
template<typename CallbackT>
void Toolbar<CallbackT>::draw() {
// Base toolbar
SDL_Rect bar { -1, m_y_offset, GAME_WIDTH + 2, TOOLBAR_HEIGHT };
SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
SDL_RenderFillRect(renderer, &bar);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderDrawRect(renderer, &bar);
// Toolbar items
for(auto& t : m_items) {
t->draw();
}
}
template<typename CallbackT>
void Toolbar<CallbackT>::update() {
for(auto& t : m_items) {
t->update();
}
}
template<typename CallbackT>
void Toolbar<CallbackT>::add_item(cstref text, Callback_t callback) {
auto new_item = std::make_unique<ToolbarItem<CallbackT>>(m_game_state, m_x_offset, TOOLBAR_ITEM_VPADDING + m_y_offset, text, callback);
m_x_offset += new_item->get_width() + TOOLBAR_ITEM_HPADDING;
m_items.push_back(std::move(new_item));
}
template<typename CallbackT>
ToolbarItem<CallbackT>::ToolbarItem(CallbackT& game_state, int32_t x_offset, int32_t y_offset, cstref name, typename Toolbar<CallbackT>::Callback_t callback)
: Loggable("ToolbarItem")
, name(name)
, callback(callback)
, hotkey(0)
, toggled(false)
, x_offset(x_offset)
, y_offset(y_offset)
, m_game_state(game_state)
, m_normal_texture(nullptr)
, m_toggled_texture(nullptr) {
auto index = name.find("&");
if(index != str::npos) {
assert(index <= (name.size() - 2) && "& must come before a character in ToolbarItem");
this->name.erase(index, 1);
}
// Create textures for this item so we don't have to do these weird calculations every frame
TTF_SizeText(regular_font, this->name.c_str(), &m_width, &m_height);
m_normal_texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_STATIC | SDL_TEXTUREACCESS_TARGET, m_width, m_height);
assert(m_normal_texture && "Could not create texture");
m_toggled_texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_STATIC | SDL_TEXTUREACCESS_TARGET, m_width, m_height);
assert(m_toggled_texture && "Could not create texture");
SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_TRANSPARENT);
SDL_SetRenderTarget(renderer, m_normal_texture);
SDL_RenderClear(renderer);
// Draw the text on each, and highlight the hotkey if necessary
SDL_Surface* text_surface = nullptr;
SDL_Texture* text_texture = nullptr;
if(index != str::npos) {
/* normal texture */
text_surface = TTF_RenderText_Blended(regular_font, this->name.c_str(), SDL_Color { 0, 0, 0, SDL_ALPHA_OPAQUE });
text_texture = SDL_CreateTextureFromSurface(renderer, text_surface);
SDL_Rect draw_rect { 0, 0, m_width, m_height };
SDL_RenderCopy(renderer, text_texture, nullptr, &draw_rect);
assert(text_surface && "Could not render font");
hotkey = this->name[index];
auto hotkey_str = str() + hotkey;
/* the way we figure out where to blit the hotkey is to get the length of the string before the hotkey, and
then blit starting from there */
auto pre = this->name.substr(0, index);
int32_t pre_width;
TTF_SizeText(regular_font, pre.c_str(), &pre_width, nullptr);
int32_t hotkey_w;
TTF_SizeText(regular_font, hotkey_str.c_str(), &hotkey_w, nullptr);
draw_rect.x = pre_width;
draw_rect.w = hotkey_w;
draw_rect.h = m_height;
auto hotkey_surface = TTF_RenderText_Shaded(regular_font, (str() + hotkey).c_str(), WHITE_OPAQUE, BLACK_OPAQUE);
auto hotkey_texture = SDL_CreateTextureFromSurface(renderer, hotkey_surface);
SDL_RenderCopy(renderer, hotkey_texture, nullptr, &draw_rect);
SDL_FreeSurface(hotkey_surface);
SDL_DestroyTexture(hotkey_texture);
/* toggled texture */
SDL_FreeSurface(text_surface);
SDL_DestroyTexture(text_texture);
text_surface = TTF_RenderText_Shaded(regular_font, this->name.c_str(), WHITE_OPAQUE, BLACK_OPAQUE);
SDL_SetRenderTarget(renderer, m_toggled_texture);
SDL_RenderClear(renderer);
text_texture = SDL_CreateTextureFromSurface(renderer, text_surface);
draw_rect = { 0, 0, m_width, m_height };
SDL_RenderCopy(renderer, text_texture, nullptr, &draw_rect);
draw_rect.x = pre_width;
draw_rect.w = hotkey_w;
draw_rect.h = m_height;
hotkey_surface = TTF_RenderText_Shaded(regular_font, (str() + hotkey).c_str(), BLACK_OPAQUE, WHITE_OPAQUE);
hotkey_texture = SDL_CreateTextureFromSurface(renderer, hotkey_surface);
SDL_RenderCopy(renderer, hotkey_texture, nullptr, &draw_rect);
SDL_FreeSurface(hotkey_surface);
SDL_DestroyTexture(hotkey_texture);
}
else {
text_surface = TTF_RenderText_Blended(regular_font, this->name.c_str(), SDL_Color { 0, 0, 0, SDL_ALPHA_OPAQUE });
assert(text_surface && "Could not render font");
text_texture = SDL_CreateTextureFromSurface(renderer, text_surface);
SDL_RenderCopy(renderer, text_texture, nullptr, nullptr);
/* toggled texture */
SDL_FreeSurface(text_surface);
SDL_DestroyTexture(text_texture);
text_surface = TTF_RenderText_Shaded(regular_font, this->name.c_str(), WHITE_OPAQUE, BLACK_OPAQUE);
text_texture = SDL_CreateTextureFromSurface(renderer, text_surface);
SDL_Rect draw_rect { 0, 0, m_width, m_height };
SDL_RenderCopy(renderer, text_texture, nullptr, &draw_rect);
}
assert(m_normal_texture && "Default texture was not created");
assert(text_surface);
SDL_FreeSurface(text_surface);
assert(text_texture);
SDL_DestroyTexture(text_texture);
SDL_SetRenderTarget(renderer, nullptr);
}
template<typename CallbackT>
ToolbarItem<CallbackT>::~ToolbarItem() {
SDL_DestroyTexture(m_normal_texture);
SDL_DestroyTexture(m_toggled_texture);
}
template<typename CallbackT>
void ToolbarItem<CallbackT>::draw() {
SDL_SetRenderTarget(renderer, nullptr);
auto texture = toggled ? m_toggled_texture : m_normal_texture;
SDL_Rect rect { x_offset, y_offset, m_width, m_height };
SDL_RenderCopy(renderer, texture, nullptr, &rect);
}
template<typename CallbackT>
void ToolbarItem<CallbackT>::update() {
constexpr auto EVENT_SZ = 128; // arbitrary event size
static SDL_Event evs[EVENT_SZ];
int count = SDL_PeepEvents(evs, EVENT_SZ, SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT);
for(int i = 0; i < count; i++) {
auto ev = evs[i];
if(hotkey != 0 && ev.type == SDL_KEYDOWN && ev.key.keysym.sym == hotkey && !ev.key.repeat)
callback(m_game_state, *this);
else if(ev.type == SDL_MOUSEBUTTONDOWN && ev.button.button == SDL_BUTTON_LEFT) {
SDL_Rect mouse_rect = { ev.button.x, ev.button.y, 1, 1 };
SDL_Rect text_rect = { x_offset, y_offset, m_width, m_height };
SDL_Rect result;
if(SDL_IntersectRect(&mouse_rect, &text_rect, &result) == SDL_TRUE) {
callback(m_game_state, *this);
}
}
}
}
| 41.34555
| 157
| 0.694314
|
alekratz
|
1c93f82b414d383676dcdfc79956b5141e8135b4
| 1,104
|
hxx
|
C++
|
tests/cvinvaffine.hxx
|
zardchim/opencvx
|
f3727c9be5532f9a41c29f558e72aa19b6db97a4
|
[
"Unlicense"
] | 10
|
2015-01-29T23:21:06.000Z
|
2019-07-05T06:27:16.000Z
|
tests/cvinvaffine.hxx
|
zardchim/opencvx
|
f3727c9be5532f9a41c29f558e72aa19b6db97a4
|
[
"Unlicense"
] | null | null | null |
tests/cvinvaffine.hxx
|
zardchim/opencvx
|
f3727c9be5532f9a41c29f558e72aa19b6db97a4
|
[
"Unlicense"
] | 13
|
2015-04-13T20:50:36.000Z
|
2022-03-20T16:06:05.000Z
|
#ifdef _MSC_VER
#pragma warning(disable:4996)
#pragma comment(lib, "cv.lib")
#pragma comment(lib, "cxcore.lib")
#pragma comment(lib, "cvaux.lib")
#pragma comment(lib, "highgui.lib")
#endif
#include <stdio.h>
#include <stdlib.h>
#include "cv.h"
#include "cvaux.h"
#include "cxcore.h"
#include "highgui.h"
#include "cvcreateaffine.h"
#include "cvinvaffine.h"
#include <cxxtest/TestSuite.h>
class CvInvAffineTest : public CxxTest::TestSuite
{
public:
void testInvAffine()
{
CvMat* affine = cvCreateMat( 2, 3, CV_64FC1 );
CvMat* invaffine = cvCreateMat( 2, 3, CV_64FC1 );
cvCreateAffine( affine, cvRect32f( 3, 10, 2, 20, 45 ), cvPoint2D32f( 4, 5 ) );
cvInvAffine( affine, invaffine );
double ans[] = {
0.565685, -0.848528, 6.788225,
-0.106066, 0.247487, -2.156676,
};
CvMat Ans = cvMat( 2, 3, CV_64FC1, ans );
for( int i = 0; i < 2; i++ ) {
for( int j = 0; j < 3; j++ ) {
TS_ASSERT_DELTA( cvmGet( invaffine, i, j ), cvmGet( &Ans, i, j ), 0.0001 );
}
}
}
};
| 26.926829
| 91
| 0.577899
|
zardchim
|
1c9b1e3e468091ba85c0dae6153ff9f95968ca8b
| 1,604
|
hpp
|
C++
|
tainthlp.hpp
|
yqw1212/demovfuscator
|
d27dd1c87ba6956dae4a3003497fe8760b7299f9
|
[
"BSD-2-Clause"
] | 614
|
2016-06-19T21:39:02.000Z
|
2022-03-27T06:07:53.000Z
|
tainthlp.hpp
|
yqw1212/demovfuscator
|
d27dd1c87ba6956dae4a3003497fe8760b7299f9
|
[
"BSD-2-Clause"
] | 20
|
2016-06-19T21:44:20.000Z
|
2022-03-31T05:21:34.000Z
|
tainthlp.hpp
|
yqw1212/demovfuscator
|
d27dd1c87ba6956dae4a3003497fe8760b7299f9
|
[
"BSD-2-Clause"
] | 54
|
2016-06-20T07:01:22.000Z
|
2021-12-14T13:34:56.000Z
|
#ifndef TAINTHLP_H
#define TAINTHLP_H
#include <map>
#include <unordered_map>
#include <capstone/x86.h>
class tainthlp{
public:
/**
* Adds taint to a specified address and (len - 1) subsequent addresses
* @param base base address to taint
* @param len length of the area to taint
* @param ref the taint reference number (or colour or whatever)
* @return 0 if successful, else 1
*/
int add_taint(uint64_t base, size_t len, size_t ref);
/**
* Querys whether an address is tainted
* @param addr The Querryed address
* @param len The length of the quarryed area
* @return true if any of the addresses are tainted, else false
*/
bool has_taint(uint64_t addr, size_t len);
/**
* Returns the taint information of an memory cell
* @param addr The Memory address
* @return the taint reference number
*/
size_t get_taint(uint64_t addr);
/**
* Taints a register and the subregisters (tainting ax also taints ah an al, but not eax)
* @param reg The register to taint
* @param ref The taint reference number
* @return 0 on success, 1 on failur
*/
int add_taint(x86_reg reg, size_t ref);
/**
* Get the taintness status from the register
* @param reg The register
* @return true if tainted, false if not
*/
bool has_taint(x86_reg reg);
/**
* @param get the taint information off a specific register
* @return the taint reference number
*/
size_t get_taint(x86_reg reg);
private:
std::map<uint32_t, size_t> mem_taint;
std::unordered_map<x86_reg, size_t, std::hash<unsigned int> > reg_taint;
}
#endif
| 26.733333
| 91
| 0.69015
|
yqw1212
|
1c9d69b28786bc646d051ce2fbbde45848874949
| 312
|
cpp
|
C++
|
codeforces/1337A.cpp
|
LordRonz/cp-solutions
|
d95eabbdbf6a04fba912f4e8be203b180af7f46d
|
[
"WTFPL"
] | 2
|
2021-04-19T06:20:11.000Z
|
2021-05-04T14:30:00.000Z
|
codeforces/1337A.cpp
|
LordRonz/cp-solutions
|
d95eabbdbf6a04fba912f4e8be203b180af7f46d
|
[
"WTFPL"
] | 2
|
2022-03-01T09:28:46.000Z
|
2022-03-02T09:52:33.000Z
|
codeforces/1337A.cpp
|
LordRonz/cp-solutions
|
d95eabbdbf6a04fba912f4e8be203b180af7f46d
|
[
"WTFPL"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define MAX(a,b,c) max(a,max(b,c))
#define MIN(a,b,c) min(a,min(b,c))
typedef pair<int, int> pii;
//0xACCE97ED
int main()
{
int t, a, b, c, d;
scanf("%d", &t);
while(t--) {
scanf("%d %d %d %d", &a, &b, &c, &d);
printf("%d %d %d\n", b, c, c);
}
return 0;
}
| 17.333333
| 39
| 0.532051
|
LordRonz
|
1ca384e980b06811e0353de766b843292a6a672c
| 7,384
|
cpp
|
C++
|
ExternalLibraries/NvGameworksFramework/src/NvGLUtils/NvUIGL.cpp
|
centauroWaRRIor/VulkanSamples
|
5a7c58de820207cc0931a9db8c90f00453e31631
|
[
"MIT"
] | 175
|
2018-08-28T14:40:34.000Z
|
2022-03-19T03:10:02.000Z
|
ExternalLibraries/NvGameworksFramework/src/NvGLUtils/NvUIGL.cpp
|
centauroWaRRIor/VulkanSamples
|
5a7c58de820207cc0931a9db8c90f00453e31631
|
[
"MIT"
] | null | null | null |
ExternalLibraries/NvGameworksFramework/src/NvGLUtils/NvUIGL.cpp
|
centauroWaRRIor/VulkanSamples
|
5a7c58de820207cc0931a9db8c90f00453e31631
|
[
"MIT"
] | 11
|
2019-05-13T12:06:53.000Z
|
2022-03-18T09:56:37.000Z
|
//----------------------------------------------------------------------------------
// File: NvGLUtils/NvUIGL.cpp
// SDK Version: v3.00
// Email: gameworks@nvidia.com
// Site: http://developer.nvidia.com/
//
// Copyright (c) 2014-2015, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------------
#include "../../src/NvUI/NvBitFontInternal.h"
#include "../../src/NvUI/NvUIInternal.h"
#include "NvUIGL.h"
#include "NvGLUtils/NvImageGL.h"
#include "NV/NvPlatformGL.h"
static int32_t TestPrintGLError(const char* str)
{
int32_t err;
err = glGetError();
if (err)
VERBOSE_LOG(str, err);
return err;
}
//========================================================================
//========================================================================
#define SAVED_ATTRIBS_MAX 16 /* something for now */
typedef struct
{
GLboolean enabled;
GLint size;
GLint stride;
GLint type;
GLint norm;
GLvoid *ptr;
} NvUIGLAttribInfo;
typedef struct
{
GLint programBound;
NvUIGLAttribInfo attrib[SAVED_ATTRIBS_MAX];
GLboolean depthMaskEnabled;
GLboolean depthTestEnabled;
GLboolean cullFaceEnabled;
GLboolean blendEnabled;
//gStateBlock.blendFunc // !!!!TBD
//blendFuncSep // tbd
GLint vboBound;
GLint iboBound;
GLint texBound;
GLint texActive;
// stencil? viewport? // !!!!TBD
} NvUIGLStateBlock;
static NvUIGLStateBlock gStateBlock;
//========================================================================
void NvUISaveStateGL()
{
int32_t i;
int32_t tmpi;
TestPrintGLError("Error 0x%x in SaveState @ start...\n");
glGetIntegerv(GL_CURRENT_PROGRAM, &(gStateBlock.programBound));
for (i = 0; i<SAVED_ATTRIBS_MAX; i++)
{
glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &tmpi);
gStateBlock.attrib[i].enabled = (GLboolean)tmpi;
if (tmpi)
{
glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &(gStateBlock.attrib[i].size));
glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &(gStateBlock.attrib[i].stride));
glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &(gStateBlock.attrib[i].type));
glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &(gStateBlock.attrib[i].norm));
glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &(gStateBlock.attrib[i].ptr));
}
}
glGetBooleanv(GL_DEPTH_WRITEMASK, &(gStateBlock.depthMaskEnabled));
gStateBlock.depthTestEnabled = glIsEnabled(GL_DEPTH_TEST);
gStateBlock.blendEnabled = glIsEnabled(GL_BLEND);
gStateBlock.cullFaceEnabled = glIsEnabled(GL_CULL_FACE);
// glGetIntegerv(GL_CULL_FACE_MODE, &(gStateBlock.cullMode));
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &(gStateBlock.vboBound));
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &(gStateBlock.iboBound));
glGetIntegerv(GL_TEXTURE_BINDING_2D, &(gStateBlock.texBound));
glGetIntegerv(GL_ACTIVE_TEXTURE, &(gStateBlock.texActive));
TestPrintGLError("Error 0x%x in SaveState @ end...\n");
}
//========================================================================
void NvUIRestoreStateGL()
{
int32_t i;
// !!!!TBD TODO probably should ensure we can do this still... wasn't before though.
// nv_flush_tracked_attribs(); // turn ours off...
TestPrintGLError("Error 0x%x in RestoreState @ start...\n");
glUseProgram(gStateBlock.programBound);
// set buffers first, in case attribs bound to them...
glBindBuffer(GL_ARRAY_BUFFER, gStateBlock.vboBound);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gStateBlock.iboBound);
if (gStateBlock.programBound)
{ // restore program stuff..
for (i = 0; i<SAVED_ATTRIBS_MAX; i++)
{
if (gStateBlock.attrib[i].enabled) // only restore enabled ones.. ;)
{
glVertexAttribPointer(i,
gStateBlock.attrib[i].size,
gStateBlock.attrib[i].type,
(GLboolean)(gStateBlock.attrib[i].norm),
gStateBlock.attrib[i].stride,
gStateBlock.attrib[i].ptr);
glEnableVertexAttribArray(i);
}
else
glDisableVertexAttribArray(i);
}
}
if (gStateBlock.depthMaskEnabled)
glDepthMask(GL_TRUE); // we turned off.
if (gStateBlock.depthTestEnabled)
glEnable(GL_DEPTH_TEST); // we turned off.
if (!gStateBlock.blendEnabled)
glDisable(GL_BLEND); // we turned ON.
if (gStateBlock.cullFaceEnabled)
glEnable(GL_CULL_FACE); // we turned off.
// glGetIntegerv(GL_CULL_FACE_MODE, &(gStateBlock.cullMode));
// restore tex BEFORE switching active state...
glBindTexture(GL_TEXTURE_2D, gStateBlock.texBound);
if (gStateBlock.texActive != GL_TEXTURE0)
glActiveTexture(gStateBlock.texActive); // we set to 0
TestPrintGLError("Error 0x%x in RestoreState @ end...\n");
}
extern void NvBitfontUseGL();
static int32_t doNothing() { return 0; }
static void doNothingVoid() { /* */ }
static bool sIsUsingGL = false;
bool NvUIIsGL() {
return sIsUsingGL;
}
void NvUIUseGL() {
NvUIRenderFactory::GlobalInit = &doNothing;
NvUIRenderFactory::GraphicCreate = &NvUIGraphicRenderGL::Create;
NvUIRenderFactory::GraphicFrameCreate = &NvUIGraphicFrameRenderGL::Create;
NvUIRenderFactory::TextureRenderCreate = &NvUITextureRenderGL::Create;
NvUIRenderFactory::GlobalRenderPrep = &NvUISaveStateGL;
NvUIRenderFactory::GlobalRenderDone = &NvUIRestoreStateGL;
NvUIRenderFactory::GlobalShutdown = &doNothingVoid;
NvBitfontUseGL();
sIsUsingGL = true;
}
| 37.105528
| 103
| 0.643418
|
centauroWaRRIor
|
1cacd2e8237bc3da55355501ac313c2b8d666f59
| 5,986
|
cpp
|
C++
|
NEST-14.0-FPGA/nestkernel/nest_time.cpp
|
OpenHEC/SNN-simulator-on-PYNQcluster
|
14f86a76edf4e8763b58f84960876e95d4efc43a
|
[
"MIT"
] | 45
|
2019-12-09T06:45:53.000Z
|
2022-01-29T12:16:41.000Z
|
NEST-14.0-FPGA/nestkernel/nest_time.cpp
|
zlchai/SNN-simulator-on-PYNQcluster
|
14f86a76edf4e8763b58f84960876e95d4efc43a
|
[
"MIT"
] | 2
|
2020-05-23T05:34:21.000Z
|
2021-09-08T02:33:46.000Z
|
NEST-14.0-FPGA/nestkernel/nest_time.cpp
|
OpenHEC/SNN-simulator-on-PYNQcluster
|
14f86a76edf4e8763b58f84960876e95d4efc43a
|
[
"MIT"
] | 10
|
2019-12-09T06:45:59.000Z
|
2021-03-25T09:32:56.000Z
|
/*
* nest_time.cpp
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST 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.
*
* NEST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "nest_time.h"
// C++ includes:
#include <string>
// Generated includes:
#include "config.h"
// Includes from libnestutil:
#include "numerics.h"
// Includes from sli:
#include "doubledatum.h"
#include "integerdatum.h"
#include "token.h"
using namespace nest;
/* Obtain time resolution information from configuration
variables or use defaults.
*/
#ifndef CONFIG_TICS_PER_MS
#define CONFIG_TICS_PER_MS 1000.0
#endif
#ifndef CONFIG_TICS_PER_STEP
#define CONFIG_TICS_PER_STEP 100
#endif
const double Time::Range::TICS_PER_MS_DEFAULT = CONFIG_TICS_PER_MS;
const tic_t Time::Range::TICS_PER_STEP_DEFAULT = CONFIG_TICS_PER_STEP;
tic_t Time::Range::TICS_PER_STEP = Time::Range::TICS_PER_STEP_DEFAULT;
double Time::Range::TICS_PER_STEP_INV =
1. / static_cast< double >( Time::Range::TICS_PER_STEP );
tic_t Time::Range::TICS_PER_STEP_RND = Time::Range::TICS_PER_STEP - 1;
double Time::Range::TICS_PER_MS = Time::Range::TICS_PER_MS_DEFAULT;
double Time::Range::MS_PER_TIC = 1 / Time::Range::TICS_PER_MS;
double Time::Range::MS_PER_STEP = TICS_PER_STEP / TICS_PER_MS;
double Time::Range::STEPS_PER_MS = 1 / Time::Range::MS_PER_STEP;
// define for unit -- const'ness is in the header
// should only be necessary when not folded away
// by the compiler as compile time consts
const tic_t Time::LimitPosInf::tics;
const delay Time::LimitPosInf::steps;
const tic_t Time::LimitNegInf::tics;
const delay Time::LimitNegInf::steps;
tic_t
Time::compute_max()
{
const long lmax = std::numeric_limits< long >::max();
const tic_t tmax = std::numeric_limits< tic_t >::max();
tic_t tics;
if ( lmax < tmax * Range::TICS_PER_STEP_INV ) // step size is limiting factor
{
tics = Range::TICS_PER_STEP * ( lmax / Range::INF_MARGIN );
}
else // tic size is limiting factor
{
tics = tmax / Range::INF_MARGIN;
} // make sure that tics and steps match so that we can have simple range
// checking when going back and forth, regardless of limiting factor
return tics - ( tics % Range::TICS_PER_STEP );
}
Time::Limit::Limit( const tic_t& t )
: tics( t )
, steps( t * Range::TICS_PER_STEP_INV )
, ms( steps * Range::MS_PER_STEP )
{
}
Time::Limit Time::LIM_MAX( +Time::compute_max() );
Time::Limit Time::LIM_MIN( -Time::compute_max() );
void
Time::set_resolution( double ms_per_step )
{
assert( ms_per_step > 0 );
Range::TICS_PER_STEP =
static_cast< tic_t >( dround( Range::TICS_PER_MS * ms_per_step ) );
Range::TICS_PER_STEP_INV = 1. / static_cast< double >( Range::TICS_PER_STEP );
Range::TICS_PER_STEP_RND = Range::TICS_PER_STEP - 1;
// Recalculate ms_per_step to be consistent with rounding above
Range::MS_PER_STEP = Range::TICS_PER_STEP / Range::TICS_PER_MS;
Range::STEPS_PER_MS = 1 / Range::MS_PER_STEP;
const tic_t max = compute_max();
LIM_MAX = +max;
LIM_MIN = -max;
}
void
Time::set_resolution( double tics_per_ms, double ms_per_step )
{
Range::TICS_PER_MS = tics_per_ms;
Range::MS_PER_TIC = 1 / tics_per_ms;
set_resolution( ms_per_step );
}
void
Time::reset_resolution()
{
Range::TICS_PER_STEP = Range::TICS_PER_STEP_DEFAULT;
Range::TICS_PER_STEP_INV = 1. / static_cast< double >( Range::TICS_PER_STEP );
Range::TICS_PER_STEP_RND = Range::TICS_PER_STEP - 1;
const tic_t max = compute_max();
LIM_MAX = +max;
LIM_MIN = -max;
}
double
Time::ms::fromtoken( const Token& t )
{
IntegerDatum* idat = dynamic_cast< IntegerDatum* >( t.datum() );
if ( idat )
{
return static_cast< double >( idat->get() );
}
DoubleDatum* ddat = dynamic_cast< DoubleDatum* >( t.datum() );
if ( ddat )
{
return ddat->get();
}
throw TypeMismatch( IntegerDatum().gettypename().toString() + " or "
+ DoubleDatum().gettypename().toString(),
t.datum()->gettypename().toString() );
}
tic_t
Time::fromstamp( Time::ms_stamp t )
{
if ( t.t > LIM_MAX.ms )
{
return LIM_POS_INF.tics;
}
else if ( t.t < LIM_MIN.ms )
{
return LIM_NEG_INF.tics;
}
// why not just fmod STEPS_PER_MS? This gives different
// results in corner cases --- and I don't think the
// intended ones.
tic_t n = static_cast< tic_t >( t.t * Range::TICS_PER_MS );
n -= ( n % Range::TICS_PER_STEP );
const double ms = n * Range::TICS_PER_STEP_INV * Range::MS_PER_STEP;
if ( ms < t.t )
{
n += Range::TICS_PER_STEP;
}
return n;
}
void
Time::reset_to_defaults()
{
// reset the TICS_PER_MS to compiled in default values
Range::TICS_PER_MS = Range::TICS_PER_MS_DEFAULT;
Range::MS_PER_TIC = 1 / Range::TICS_PER_MS_DEFAULT;
// reset TICS_PER_STEP to compiled in default values
Range::TICS_PER_STEP = Range::TICS_PER_STEP_DEFAULT;
Range::TICS_PER_STEP_INV = 1. / static_cast< double >( Range::TICS_PER_STEP );
Range::TICS_PER_STEP_RND = Range::TICS_PER_STEP - 1;
Range::MS_PER_STEP = Range::TICS_PER_STEP / Range::TICS_PER_MS;
Range::STEPS_PER_MS = 1 / Range::MS_PER_STEP;
}
std::ostream& operator<<( std::ostream& strm, const Time& t )
{
if ( t.is_neg_inf() )
{
strm << "-INF";
}
else if ( t.is_pos_inf() )
{
strm << "+INF";
}
else
{
strm << t.get_ms() << " ms (= " << t.get_tics()
<< " tics = " << t.get_steps()
<< ( t.get_steps() != 1 ? " steps)" : " step)" );
}
return strm;
}
| 26.963964
| 80
| 0.688607
|
OpenHEC
|
1cafef81519c467dc4d7a545f84ecbf83849af10
| 63,947
|
cpp
|
C++
|
src/execution/util/fast_double_parser.cpp
|
rohanaggarwal7997/terrier2
|
275d96fdb3f16f94b043230553a8d8d4a26f4168
|
[
"MIT"
] | null | null | null |
src/execution/util/fast_double_parser.cpp
|
rohanaggarwal7997/terrier2
|
275d96fdb3f16f94b043230553a8d8d4a26f4168
|
[
"MIT"
] | 2
|
2020-08-24T16:29:40.000Z
|
2020-09-08T16:34:51.000Z
|
src/execution/util/fast_double_parser.cpp
|
rohanaggarwal7997/terrier2
|
275d96fdb3f16f94b043230553a8d8d4a26f4168
|
[
"MIT"
] | null | null | null |
#include "execution/util/fast_double_parser.h"
namespace terrier::execution::util {
const double FastDoubleParser::POWER_OF_TEN[] = {1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11,
1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22};
const FastDoubleParser::components FastDoubleParser::POWER_OF_TEN_COMPONENTS[] = {
{0xa5ced43b7e3e9188L, 7}, {0xcf42894a5dce35eaL, 10}, {0x818995ce7aa0e1b2L, 14}, {0xa1ebfb4219491a1fL, 17},
{0xca66fa129f9b60a6L, 20}, {0xfd00b897478238d0L, 23}, {0x9e20735e8cb16382L, 27}, {0xc5a890362fddbc62L, 30},
{0xf712b443bbd52b7bL, 33}, {0x9a6bb0aa55653b2dL, 37}, {0xc1069cd4eabe89f8L, 40}, {0xf148440a256e2c76L, 43},
{0x96cd2a865764dbcaL, 47}, {0xbc807527ed3e12bcL, 50}, {0xeba09271e88d976bL, 53}, {0x93445b8731587ea3L, 57},
{0xb8157268fdae9e4cL, 60}, {0xe61acf033d1a45dfL, 63}, {0x8fd0c16206306babL, 67}, {0xb3c4f1ba87bc8696L, 70},
{0xe0b62e2929aba83cL, 73}, {0x8c71dcd9ba0b4925L, 77}, {0xaf8e5410288e1b6fL, 80}, {0xdb71e91432b1a24aL, 83},
{0x892731ac9faf056eL, 87}, {0xab70fe17c79ac6caL, 90}, {0xd64d3d9db981787dL, 93}, {0x85f0468293f0eb4eL, 97},
{0xa76c582338ed2621L, 100}, {0xd1476e2c07286faaL, 103}, {0x82cca4db847945caL, 107}, {0xa37fce126597973cL, 110},
{0xcc5fc196fefd7d0cL, 113}, {0xff77b1fcbebcdc4fL, 116}, {0x9faacf3df73609b1L, 120}, {0xc795830d75038c1dL, 123},
{0xf97ae3d0d2446f25L, 126}, {0x9becce62836ac577L, 130}, {0xc2e801fb244576d5L, 133}, {0xf3a20279ed56d48aL, 136},
{0x9845418c345644d6L, 140}, {0xbe5691ef416bd60cL, 143}, {0xedec366b11c6cb8fL, 146}, {0x94b3a202eb1c3f39L, 150},
{0xb9e08a83a5e34f07L, 153}, {0xe858ad248f5c22c9L, 156}, {0x91376c36d99995beL, 160}, {0xb58547448ffffb2dL, 163},
{0xe2e69915b3fff9f9L, 166}, {0x8dd01fad907ffc3bL, 170}, {0xb1442798f49ffb4aL, 173}, {0xdd95317f31c7fa1dL, 176},
{0x8a7d3eef7f1cfc52L, 180}, {0xad1c8eab5ee43b66L, 183}, {0xd863b256369d4a40L, 186}, {0x873e4f75e2224e68L, 190},
{0xa90de3535aaae202L, 193}, {0xd3515c2831559a83L, 196}, {0x8412d9991ed58091L, 200}, {0xa5178fff668ae0b6L, 203},
{0xce5d73ff402d98e3L, 206}, {0x80fa687f881c7f8eL, 210}, {0xa139029f6a239f72L, 213}, {0xc987434744ac874eL, 216},
{0xfbe9141915d7a922L, 219}, {0x9d71ac8fada6c9b5L, 223}, {0xc4ce17b399107c22L, 226}, {0xf6019da07f549b2bL, 229},
{0x99c102844f94e0fbL, 233}, {0xc0314325637a1939L, 236}, {0xf03d93eebc589f88L, 239}, {0x96267c7535b763b5L, 243},
{0xbbb01b9283253ca2L, 246}, {0xea9c227723ee8bcbL, 249}, {0x92a1958a7675175fL, 253}, {0xb749faed14125d36L, 256},
{0xe51c79a85916f484L, 259}, {0x8f31cc0937ae58d2L, 263}, {0xb2fe3f0b8599ef07L, 266}, {0xdfbdcece67006ac9L, 269},
{0x8bd6a141006042bdL, 273}, {0xaecc49914078536dL, 276}, {0xda7f5bf590966848L, 279}, {0x888f99797a5e012dL, 283},
{0xaab37fd7d8f58178L, 286}, {0xd5605fcdcf32e1d6L, 289}, {0x855c3be0a17fcd26L, 293}, {0xa6b34ad8c9dfc06fL, 296},
{0xd0601d8efc57b08bL, 299}, {0x823c12795db6ce57L, 303}, {0xa2cb1717b52481edL, 306}, {0xcb7ddcdda26da268L, 309},
{0xfe5d54150b090b02L, 312}, {0x9efa548d26e5a6e1L, 316}, {0xc6b8e9b0709f109aL, 319}, {0xf867241c8cc6d4c0L, 322},
{0x9b407691d7fc44f8L, 326}, {0xc21094364dfb5636L, 329}, {0xf294b943e17a2bc4L, 332}, {0x979cf3ca6cec5b5aL, 336},
{0xbd8430bd08277231L, 339}, {0xece53cec4a314ebdL, 342}, {0x940f4613ae5ed136L, 346}, {0xb913179899f68584L, 349},
{0xe757dd7ec07426e5L, 352}, {0x9096ea6f3848984fL, 356}, {0xb4bca50b065abe63L, 359}, {0xe1ebce4dc7f16dfbL, 362},
{0x8d3360f09cf6e4bdL, 366}, {0xb080392cc4349decL, 369}, {0xdca04777f541c567L, 372}, {0x89e42caaf9491b60L, 376},
{0xac5d37d5b79b6239L, 379}, {0xd77485cb25823ac7L, 382}, {0x86a8d39ef77164bcL, 386}, {0xa8530886b54dbdebL, 389},
{0xd267caa862a12d66L, 392}, {0x8380dea93da4bc60L, 396}, {0xa46116538d0deb78L, 399}, {0xcd795be870516656L, 402},
{0x806bd9714632dff6L, 406}, {0xa086cfcd97bf97f3L, 409}, {0xc8a883c0fdaf7df0L, 412}, {0xfad2a4b13d1b5d6cL, 415},
{0x9cc3a6eec6311a63L, 419}, {0xc3f490aa77bd60fcL, 422}, {0xf4f1b4d515acb93bL, 425}, {0x991711052d8bf3c5L, 429},
{0xbf5cd54678eef0b6L, 432}, {0xef340a98172aace4L, 435}, {0x9580869f0e7aac0eL, 439}, {0xbae0a846d2195712L, 442},
{0xe998d258869facd7L, 445}, {0x91ff83775423cc06L, 449}, {0xb67f6455292cbf08L, 452}, {0xe41f3d6a7377eecaL, 455},
{0x8e938662882af53eL, 459}, {0xb23867fb2a35b28dL, 462}, {0xdec681f9f4c31f31L, 465}, {0x8b3c113c38f9f37eL, 469},
{0xae0b158b4738705eL, 472}, {0xd98ddaee19068c76L, 475}, {0x87f8a8d4cfa417c9L, 479}, {0xa9f6d30a038d1dbcL, 482},
{0xd47487cc8470652bL, 485}, {0x84c8d4dfd2c63f3bL, 489}, {0xa5fb0a17c777cf09L, 492}, {0xcf79cc9db955c2ccL, 495},
{0x81ac1fe293d599bfL, 499}, {0xa21727db38cb002fL, 502}, {0xca9cf1d206fdc03bL, 505}, {0xfd442e4688bd304aL, 508},
{0x9e4a9cec15763e2eL, 512}, {0xc5dd44271ad3cdbaL, 515}, {0xf7549530e188c128L, 518}, {0x9a94dd3e8cf578b9L, 522},
{0xc13a148e3032d6e7L, 525}, {0xf18899b1bc3f8ca1L, 528}, {0x96f5600f15a7b7e5L, 532}, {0xbcb2b812db11a5deL, 535},
{0xebdf661791d60f56L, 538}, {0x936b9fcebb25c995L, 542}, {0xb84687c269ef3bfbL, 545}, {0xe65829b3046b0afaL, 548},
{0x8ff71a0fe2c2e6dcL, 552}, {0xb3f4e093db73a093L, 555}, {0xe0f218b8d25088b8L, 558}, {0x8c974f7383725573L, 562},
{0xafbd2350644eeacfL, 565}, {0xdbac6c247d62a583L, 568}, {0x894bc396ce5da772L, 572}, {0xab9eb47c81f5114fL, 575},
{0xd686619ba27255a2L, 578}, {0x8613fd0145877585L, 582}, {0xa798fc4196e952e7L, 585}, {0xd17f3b51fca3a7a0L, 588},
{0x82ef85133de648c4L, 592}, {0xa3ab66580d5fdaf5L, 595}, {0xcc963fee10b7d1b3L, 598}, {0xffbbcfe994e5c61fL, 601},
{0x9fd561f1fd0f9bd3L, 605}, {0xc7caba6e7c5382c8L, 608}, {0xf9bd690a1b68637bL, 611}, {0x9c1661a651213e2dL, 615},
{0xc31bfa0fe5698db8L, 618}, {0xf3e2f893dec3f126L, 621}, {0x986ddb5c6b3a76b7L, 625}, {0xbe89523386091465L, 628},
{0xee2ba6c0678b597fL, 631}, {0x94db483840b717efL, 635}, {0xba121a4650e4ddebL, 638}, {0xe896a0d7e51e1566L, 641},
{0x915e2486ef32cd60L, 645}, {0xb5b5ada8aaff80b8L, 648}, {0xe3231912d5bf60e6L, 651}, {0x8df5efabc5979c8fL, 655},
{0xb1736b96b6fd83b3L, 658}, {0xddd0467c64bce4a0L, 661}, {0x8aa22c0dbef60ee4L, 665}, {0xad4ab7112eb3929dL, 668},
{0xd89d64d57a607744L, 671}, {0x87625f056c7c4a8bL, 675}, {0xa93af6c6c79b5d2dL, 678}, {0xd389b47879823479L, 681},
{0x843610cb4bf160cbL, 685}, {0xa54394fe1eedb8feL, 688}, {0xce947a3da6a9273eL, 691}, {0x811ccc668829b887L, 695},
{0xa163ff802a3426a8L, 698}, {0xc9bcff6034c13052L, 701}, {0xfc2c3f3841f17c67L, 704}, {0x9d9ba7832936edc0L, 708},
{0xc5029163f384a931L, 711}, {0xf64335bcf065d37dL, 714}, {0x99ea0196163fa42eL, 718}, {0xc06481fb9bcf8d39L, 721},
{0xf07da27a82c37088L, 724}, {0x964e858c91ba2655L, 728}, {0xbbe226efb628afeaL, 731}, {0xeadab0aba3b2dbe5L, 734},
{0x92c8ae6b464fc96fL, 738}, {0xb77ada0617e3bbcbL, 741}, {0xe55990879ddcaabdL, 744}, {0x8f57fa54c2a9eab6L, 748},
{0xb32df8e9f3546564L, 751}, {0xdff9772470297ebdL, 754}, {0x8bfbea76c619ef36L, 758}, {0xaefae51477a06b03L, 761},
{0xdab99e59958885c4L, 764}, {0x88b402f7fd75539bL, 768}, {0xaae103b5fcd2a881L, 771}, {0xd59944a37c0752a2L, 774},
{0x857fcae62d8493a5L, 778}, {0xa6dfbd9fb8e5b88eL, 781}, {0xd097ad07a71f26b2L, 784}, {0x825ecc24c873782fL, 788},
{0xa2f67f2dfa90563bL, 791}, {0xcbb41ef979346bcaL, 794}, {0xfea126b7d78186bcL, 797}, {0x9f24b832e6b0f436L, 801},
{0xc6ede63fa05d3143L, 804}, {0xf8a95fcf88747d94L, 807}, {0x9b69dbe1b548ce7cL, 811}, {0xc24452da229b021bL, 814},
{0xf2d56790ab41c2a2L, 817}, {0x97c560ba6b0919a5L, 821}, {0xbdb6b8e905cb600fL, 824}, {0xed246723473e3813L, 827},
{0x9436c0760c86e30bL, 831}, {0xb94470938fa89bceL, 834}, {0xe7958cb87392c2c2L, 837}, {0x90bd77f3483bb9b9L, 841},
{0xb4ecd5f01a4aa828L, 844}, {0xe2280b6c20dd5232L, 847}, {0x8d590723948a535fL, 851}, {0xb0af48ec79ace837L, 854},
{0xdcdb1b2798182244L, 857}, {0x8a08f0f8bf0f156bL, 861}, {0xac8b2d36eed2dac5L, 864}, {0xd7adf884aa879177L, 867},
{0x86ccbb52ea94baeaL, 871}, {0xa87fea27a539e9a5L, 874}, {0xd29fe4b18e88640eL, 877}, {0x83a3eeeef9153e89L, 881},
{0xa48ceaaab75a8e2bL, 884}, {0xcdb02555653131b6L, 887}, {0x808e17555f3ebf11L, 891}, {0xa0b19d2ab70e6ed6L, 894},
{0xc8de047564d20a8bL, 897}, {0xfb158592be068d2eL, 900}, {0x9ced737bb6c4183dL, 904}, {0xc428d05aa4751e4cL, 907},
{0xf53304714d9265dfL, 910}, {0x993fe2c6d07b7fabL, 914}, {0xbf8fdb78849a5f96L, 917}, {0xef73d256a5c0f77cL, 920},
{0x95a8637627989aadL, 924}, {0xbb127c53b17ec159L, 927}, {0xe9d71b689dde71afL, 930}, {0x9226712162ab070dL, 934},
{0xb6b00d69bb55c8d1L, 937}, {0xe45c10c42a2b3b05L, 940}, {0x8eb98a7a9a5b04e3L, 944}, {0xb267ed1940f1c61cL, 947},
{0xdf01e85f912e37a3L, 950}, {0x8b61313bbabce2c6L, 954}, {0xae397d8aa96c1b77L, 957}, {0xd9c7dced53c72255L, 960},
{0x881cea14545c7575L, 964}, {0xaa242499697392d2L, 967}, {0xd4ad2dbfc3d07787L, 970}, {0x84ec3c97da624ab4L, 974},
{0xa6274bbdd0fadd61L, 977}, {0xcfb11ead453994baL, 980}, {0x81ceb32c4b43fcf4L, 984}, {0xa2425ff75e14fc31L, 987},
{0xcad2f7f5359a3b3eL, 990}, {0xfd87b5f28300ca0dL, 993}, {0x9e74d1b791e07e48L, 997}, {0xc612062576589ddaL, 1000},
{0xf79687aed3eec551L, 1003}, {0x9abe14cd44753b52L, 1007}, {0xc16d9a0095928a27L, 1010}, {0xf1c90080baf72cb1L, 1013},
{0x971da05074da7beeL, 1017}, {0xbce5086492111aeaL, 1020}, {0xec1e4a7db69561a5L, 1023}, {0x9392ee8e921d5d07L, 1027},
{0xb877aa3236a4b449L, 1030}, {0xe69594bec44de15bL, 1033}, {0x901d7cf73ab0acd9L, 1037}, {0xb424dc35095cd80fL, 1040},
{0xe12e13424bb40e13L, 1043}, {0x8cbccc096f5088cbL, 1047}, {0xafebff0bcb24aafeL, 1050}, {0xdbe6fecebdedd5beL, 1053},
{0x89705f4136b4a597L, 1057}, {0xabcc77118461cefcL, 1060}, {0xd6bf94d5e57a42bcL, 1063}, {0x8637bd05af6c69b5L, 1067},
{0xa7c5ac471b478423L, 1070}, {0xd1b71758e219652bL, 1073}, {0x83126e978d4fdf3bL, 1077}, {0xa3d70a3d70a3d70aL, 1080},
{0xccccccccccccccccL, 1083}, {0x8000000000000000L, 1087}, {0xa000000000000000L, 1090}, {0xc800000000000000L, 1093},
{0xfa00000000000000L, 1096}, {0x9c40000000000000L, 1100}, {0xc350000000000000L, 1103}, {0xf424000000000000L, 1106},
{0x9896800000000000L, 1110}, {0xbebc200000000000L, 1113}, {0xee6b280000000000L, 1116}, {0x9502f90000000000L, 1120},
{0xba43b74000000000L, 1123}, {0xe8d4a51000000000L, 1126}, {0x9184e72a00000000L, 1130}, {0xb5e620f480000000L, 1133},
{0xe35fa931a0000000L, 1136}, {0x8e1bc9bf04000000L, 1140}, {0xb1a2bc2ec5000000L, 1143}, {0xde0b6b3a76400000L, 1146},
{0x8ac7230489e80000L, 1150}, {0xad78ebc5ac620000L, 1153}, {0xd8d726b7177a8000L, 1156}, {0x878678326eac9000L, 1160},
{0xa968163f0a57b400L, 1163}, {0xd3c21bcecceda100L, 1166}, {0x84595161401484a0L, 1170}, {0xa56fa5b99019a5c8L, 1173},
{0xcecb8f27f4200f3aL, 1176}, {0x813f3978f8940984L, 1180}, {0xa18f07d736b90be5L, 1183}, {0xc9f2c9cd04674edeL, 1186},
{0xfc6f7c4045812296L, 1189}, {0x9dc5ada82b70b59dL, 1193}, {0xc5371912364ce305L, 1196}, {0xf684df56c3e01bc6L, 1199},
{0x9a130b963a6c115cL, 1203}, {0xc097ce7bc90715b3L, 1206}, {0xf0bdc21abb48db20L, 1209}, {0x96769950b50d88f4L, 1213},
{0xbc143fa4e250eb31L, 1216}, {0xeb194f8e1ae525fdL, 1219}, {0x92efd1b8d0cf37beL, 1223}, {0xb7abc627050305adL, 1226},
{0xe596b7b0c643c719L, 1229}, {0x8f7e32ce7bea5c6fL, 1233}, {0xb35dbf821ae4f38bL, 1236}, {0xe0352f62a19e306eL, 1239},
{0x8c213d9da502de45L, 1243}, {0xaf298d050e4395d6L, 1246}, {0xdaf3f04651d47b4cL, 1249}, {0x88d8762bf324cd0fL, 1253},
{0xab0e93b6efee0053L, 1256}, {0xd5d238a4abe98068L, 1259}, {0x85a36366eb71f041L, 1263}, {0xa70c3c40a64e6c51L, 1266},
{0xd0cf4b50cfe20765L, 1269}, {0x82818f1281ed449fL, 1273}, {0xa321f2d7226895c7L, 1276}, {0xcbea6f8ceb02bb39L, 1279},
{0xfee50b7025c36a08L, 1282}, {0x9f4f2726179a2245L, 1286}, {0xc722f0ef9d80aad6L, 1289}, {0xf8ebad2b84e0d58bL, 1292},
{0x9b934c3b330c8577L, 1296}, {0xc2781f49ffcfa6d5L, 1299}, {0xf316271c7fc3908aL, 1302}, {0x97edd871cfda3a56L, 1306},
{0xbde94e8e43d0c8ecL, 1309}, {0xed63a231d4c4fb27L, 1312}, {0x945e455f24fb1cf8L, 1316}, {0xb975d6b6ee39e436L, 1319},
{0xe7d34c64a9c85d44L, 1322}, {0x90e40fbeea1d3a4aL, 1326}, {0xb51d13aea4a488ddL, 1329}, {0xe264589a4dcdab14L, 1332},
{0x8d7eb76070a08aecL, 1336}, {0xb0de65388cc8ada8L, 1339}, {0xdd15fe86affad912L, 1342}, {0x8a2dbf142dfcc7abL, 1346},
{0xacb92ed9397bf996L, 1349}, {0xd7e77a8f87daf7fbL, 1352}, {0x86f0ac99b4e8dafdL, 1356}, {0xa8acd7c0222311bcL, 1359},
{0xd2d80db02aabd62bL, 1362}, {0x83c7088e1aab65dbL, 1366}, {0xa4b8cab1a1563f52L, 1369}, {0xcde6fd5e09abcf26L, 1372},
{0x80b05e5ac60b6178L, 1376}, {0xa0dc75f1778e39d6L, 1379}, {0xc913936dd571c84cL, 1382}, {0xfb5878494ace3a5fL, 1385},
{0x9d174b2dcec0e47bL, 1389}, {0xc45d1df942711d9aL, 1392}, {0xf5746577930d6500L, 1395}, {0x9968bf6abbe85f20L, 1399},
{0xbfc2ef456ae276e8L, 1402}, {0xefb3ab16c59b14a2L, 1405}, {0x95d04aee3b80ece5L, 1409}, {0xbb445da9ca61281fL, 1412},
{0xea1575143cf97226L, 1415}, {0x924d692ca61be758L, 1419}, {0xb6e0c377cfa2e12eL, 1422}, {0xe498f455c38b997aL, 1425},
{0x8edf98b59a373fecL, 1429}, {0xb2977ee300c50fe7L, 1432}, {0xdf3d5e9bc0f653e1L, 1435}, {0x8b865b215899f46cL, 1439},
{0xae67f1e9aec07187L, 1442}, {0xda01ee641a708de9L, 1445}, {0x884134fe908658b2L, 1449}, {0xaa51823e34a7eedeL, 1452},
{0xd4e5e2cdc1d1ea96L, 1455}, {0x850fadc09923329eL, 1459}, {0xa6539930bf6bff45L, 1462}, {0xcfe87f7cef46ff16L, 1465},
{0x81f14fae158c5f6eL, 1469}, {0xa26da3999aef7749L, 1472}, {0xcb090c8001ab551cL, 1475}, {0xfdcb4fa002162a63L, 1478},
{0x9e9f11c4014dda7eL, 1482}, {0xc646d63501a1511dL, 1485}, {0xf7d88bc24209a565L, 1488}, {0x9ae757596946075fL, 1492},
{0xc1a12d2fc3978937L, 1495}, {0xf209787bb47d6b84L, 1498}, {0x9745eb4d50ce6332L, 1502}, {0xbd176620a501fbffL, 1505},
{0xec5d3fa8ce427affL, 1508}, {0x93ba47c980e98cdfL, 1512}, {0xb8a8d9bbe123f017L, 1515}, {0xe6d3102ad96cec1dL, 1518},
{0x9043ea1ac7e41392L, 1522}, {0xb454e4a179dd1877L, 1525}, {0xe16a1dc9d8545e94L, 1528}, {0x8ce2529e2734bb1dL, 1532},
{0xb01ae745b101e9e4L, 1535}, {0xdc21a1171d42645dL, 1538}, {0x899504ae72497ebaL, 1542}, {0xabfa45da0edbde69L, 1545},
{0xd6f8d7509292d603L, 1548}, {0x865b86925b9bc5c2L, 1552}, {0xa7f26836f282b732L, 1555}, {0xd1ef0244af2364ffL, 1558},
{0x8335616aed761f1fL, 1562}, {0xa402b9c5a8d3a6e7L, 1565}, {0xcd036837130890a1L, 1568}, {0x802221226be55a64L, 1572},
{0xa02aa96b06deb0fdL, 1575}, {0xc83553c5c8965d3dL, 1578}, {0xfa42a8b73abbf48cL, 1581}, {0x9c69a97284b578d7L, 1585},
{0xc38413cf25e2d70dL, 1588}, {0xf46518c2ef5b8cd1L, 1591}, {0x98bf2f79d5993802L, 1595}, {0xbeeefb584aff8603L, 1598},
{0xeeaaba2e5dbf6784L, 1601}, {0x952ab45cfa97a0b2L, 1605}, {0xba756174393d88dfL, 1608}, {0xe912b9d1478ceb17L, 1611},
{0x91abb422ccb812eeL, 1615}, {0xb616a12b7fe617aaL, 1618}, {0xe39c49765fdf9d94L, 1621}, {0x8e41ade9fbebc27dL, 1625},
{0xb1d219647ae6b31cL, 1628}, {0xde469fbd99a05fe3L, 1631}, {0x8aec23d680043beeL, 1635}, {0xada72ccc20054ae9L, 1638},
{0xd910f7ff28069da4L, 1641}, {0x87aa9aff79042286L, 1645}, {0xa99541bf57452b28L, 1648}, {0xd3fa922f2d1675f2L, 1651},
{0x847c9b5d7c2e09b7L, 1655}, {0xa59bc234db398c25L, 1658}, {0xcf02b2c21207ef2eL, 1661}, {0x8161afb94b44f57dL, 1665},
{0xa1ba1ba79e1632dcL, 1668}, {0xca28a291859bbf93L, 1671}, {0xfcb2cb35e702af78L, 1674}, {0x9defbf01b061adabL, 1678},
{0xc56baec21c7a1916L, 1681}, {0xf6c69a72a3989f5bL, 1684}, {0x9a3c2087a63f6399L, 1688}, {0xc0cb28a98fcf3c7fL, 1691},
{0xf0fdf2d3f3c30b9fL, 1694}, {0x969eb7c47859e743L, 1698}, {0xbc4665b596706114L, 1701}, {0xeb57ff22fc0c7959L, 1704},
{0x9316ff75dd87cbd8L, 1708}, {0xb7dcbf5354e9beceL, 1711}, {0xe5d3ef282a242e81L, 1714}, {0x8fa475791a569d10L, 1718},
{0xb38d92d760ec4455L, 1721}, {0xe070f78d3927556aL, 1724}, {0x8c469ab843b89562L, 1728}, {0xaf58416654a6babbL, 1731},
{0xdb2e51bfe9d0696aL, 1734}, {0x88fcf317f22241e2L, 1738}, {0xab3c2fddeeaad25aL, 1741}, {0xd60b3bd56a5586f1L, 1744},
{0x85c7056562757456L, 1748}, {0xa738c6bebb12d16cL, 1751}, {0xd106f86e69d785c7L, 1754}, {0x82a45b450226b39cL, 1758},
{0xa34d721642b06084L, 1761}, {0xcc20ce9bd35c78a5L, 1764}, {0xff290242c83396ceL, 1767}, {0x9f79a169bd203e41L, 1771},
{0xc75809c42c684dd1L, 1774}, {0xf92e0c3537826145L, 1777}, {0x9bbcc7a142b17ccbL, 1781}, {0xc2abf989935ddbfeL, 1784},
{0xf356f7ebf83552feL, 1787}, {0x98165af37b2153deL, 1791}, {0xbe1bf1b059e9a8d6L, 1794}, {0xeda2ee1c7064130cL, 1797},
{0x9485d4d1c63e8be7L, 1801}, {0xb9a74a0637ce2ee1L, 1804}, {0xe8111c87c5c1ba99L, 1807}, {0x910ab1d4db9914a0L, 1811},
{0xb54d5e4a127f59c8L, 1814}, {0xe2a0b5dc971f303aL, 1817}, {0x8da471a9de737e24L, 1821}, {0xb10d8e1456105dadL, 1824},
{0xdd50f1996b947518L, 1827}, {0x8a5296ffe33cc92fL, 1831}, {0xace73cbfdc0bfb7bL, 1834}, {0xd8210befd30efa5aL, 1837},
{0x8714a775e3e95c78L, 1841}, {0xa8d9d1535ce3b396L, 1844}, {0xd31045a8341ca07cL, 1847}, {0x83ea2b892091e44dL, 1851},
{0xa4e4b66b68b65d60L, 1854}, {0xce1de40642e3f4b9L, 1857}, {0x80d2ae83e9ce78f3L, 1861}, {0xa1075a24e4421730L, 1864},
{0xc94930ae1d529cfcL, 1867}, {0xfb9b7cd9a4a7443cL, 1870}, {0x9d412e0806e88aa5L, 1874}, {0xc491798a08a2ad4eL, 1877},
{0xf5b5d7ec8acb58a2L, 1880}, {0x9991a6f3d6bf1765L, 1884}, {0xbff610b0cc6edd3fL, 1887}, {0xeff394dcff8a948eL, 1890},
{0x95f83d0a1fb69cd9L, 1894}, {0xbb764c4ca7a4440fL, 1897}, {0xea53df5fd18d5513L, 1900}, {0x92746b9be2f8552cL, 1904},
{0xb7118682dbb66a77L, 1907}, {0xe4d5e82392a40515L, 1910}, {0x8f05b1163ba6832dL, 1914}, {0xb2c71d5bca9023f8L, 1917},
{0xdf78e4b2bd342cf6L, 1920}, {0x8bab8eefb6409c1aL, 1924}, {0xae9672aba3d0c320L, 1927}, {0xda3c0f568cc4f3e8L, 1930},
{0x8865899617fb1871L, 1934}, {0xaa7eebfb9df9de8dL, 1937}, {0xd51ea6fa85785631L, 1940}, {0x8533285c936b35deL, 1944},
{0xa67ff273b8460356L, 1947}, {0xd01fef10a657842cL, 1950}, {0x8213f56a67f6b29bL, 1954}, {0xa298f2c501f45f42L, 1957},
{0xcb3f2f7642717713L, 1960}, {0xfe0efb53d30dd4d7L, 1963}, {0x9ec95d1463e8a506L, 1967}, {0xc67bb4597ce2ce48L, 1970},
{0xf81aa16fdc1b81daL, 1973}, {0x9b10a4e5e9913128L, 1977}, {0xc1d4ce1f63f57d72L, 1980}, {0xf24a01a73cf2dccfL, 1983},
{0x976e41088617ca01L, 1987}, {0xbd49d14aa79dbc82L, 1990}, {0xec9c459d51852ba2L, 1993}, {0x93e1ab8252f33b45L, 1997},
{0xb8da1662e7b00a17L, 2000}, {0xe7109bfba19c0c9dL, 2003}, {0x906a617d450187e2L, 2007}, {0xb484f9dc9641e9daL, 2010},
{0xe1a63853bbd26451L, 2013}, {0x8d07e33455637eb2L, 2017}, {0xb049dc016abc5e5fL, 2020}, {0xdc5c5301c56b75f7L, 2023},
{0x89b9b3e11b6329baL, 2027}, {0xac2820d9623bf429L, 2030}, {0xd732290fbacaf133L, 2033}, {0x867f59a9d4bed6c0L, 2037},
{0xa81f301449ee8c70L, 2040}, {0xd226fc195c6a2f8cL, 2043}, {0x83585d8fd9c25db7L, 2047}, {0xa42e74f3d032f525L, 2050},
{0xcd3a1230c43fb26fL, 2053}, {0x80444b5e7aa7cf85L, 2057}, {0xa0555e361951c366L, 2060}, {0xc86ab5c39fa63440L, 2063},
{0xfa856334878fc150L, 2066}, {0x9c935e00d4b9d8d2L, 2070}, {0xc3b8358109e84f07L, 2073}, {0xf4a642e14c6262c8L, 2076},
{0x98e7e9cccfbd7dbdL, 2080}, {0xbf21e44003acdd2cL, 2083}, {0xeeea5d5004981478L, 2086}, {0x95527a5202df0ccbL, 2090},
{0xbaa718e68396cffdL, 2093}, {0xe950df20247c83fdL, 2096}, {0x91d28b7416cdd27eL, 2100}, {0xb6472e511c81471dL, 2103},
{0xe3d8f9e563a198e5L, 2106}, {0x8e679c2f5e44ff8fL, 2110}};
const uint64_t FastDoubleParser::MANTISSA_128[] = {0x419ea3bd35385e2d,
0x52064cac828675b9,
0x7343efebd1940993,
0x1014ebe6c5f90bf8,
0xd41a26e077774ef6,
0x8920b098955522b4,
0x55b46e5f5d5535b0,
0xeb2189f734aa831d,
0xa5e9ec7501d523e4,
0x47b233c92125366e,
0x999ec0bb696e840a,
0xc00670ea43ca250d,
0x380406926a5e5728,
0xc605083704f5ecf2,
0xf7864a44c633682e,
0x7ab3ee6afbe0211d,
0x5960ea05bad82964,
0x6fb92487298e33bd,
0xa5d3b6d479f8e056,
0x8f48a4899877186c,
0x331acdabfe94de87,
0x9ff0c08b7f1d0b14,
0x7ecf0ae5ee44dd9,
0xc9e82cd9f69d6150,
0xbe311c083a225cd2,
0x6dbd630a48aaf406,
0x92cbbccdad5b108,
0x25bbf56008c58ea5,
0xaf2af2b80af6f24e,
0x1af5af660db4aee1,
0x50d98d9fc890ed4d,
0xe50ff107bab528a0,
0x1e53ed49a96272c8,
0x25e8e89c13bb0f7a,
0x77b191618c54e9ac,
0xd59df5b9ef6a2417,
0x4b0573286b44ad1d,
0x4ee367f9430aec32,
0x229c41f793cda73f,
0x6b43527578c1110f,
0x830a13896b78aaa9,
0x23cc986bc656d553,
0x2cbfbe86b7ec8aa8,
0x7bf7d71432f3d6a9,
0xdaf5ccd93fb0cc53,
0xd1b3400f8f9cff68,
0x23100809b9c21fa1,
0xabd40a0c2832a78a,
0x16c90c8f323f516c,
0xae3da7d97f6792e3,
0x99cd11cfdf41779c,
0x40405643d711d583,
0x482835ea666b2572,
0xda3243650005eecf,
0x90bed43e40076a82,
0x5a7744a6e804a291,
0x711515d0a205cb36,
0xd5a5b44ca873e03,
0xe858790afe9486c2,
0x626e974dbe39a872,
0xfb0a3d212dc8128f,
0x7ce66634bc9d0b99,
0x1c1fffc1ebc44e80,
0xa327ffb266b56220,
0x4bf1ff9f0062baa8,
0x6f773fc3603db4a9,
0xcb550fb4384d21d3,
0x7e2a53a146606a48,
0x2eda7444cbfc426d,
0xfa911155fefb5308,
0x793555ab7eba27ca,
0x4bc1558b2f3458de,
0x9eb1aaedfb016f16,
0x465e15a979c1cadc,
0xbfacd89ec191ec9,
0xcef980ec671f667b,
0x82b7e12780e7401a,
0xd1b2ecb8b0908810,
0x861fa7e6dcb4aa15,
0x67a791e093e1d49a,
0xe0c8bb2c5c6d24e0,
0x58fae9f773886e18,
0xaf39a475506a899e,
0x6d8406c952429603,
0xc8e5087ba6d33b83,
0xfb1e4a9a90880a64,
0x5cf2eea09a55067f,
0xf42faa48c0ea481e,
0xf13b94daf124da26,
0x76c53d08d6b70858,
0x54768c4b0c64ca6e,
0xa9942f5dcf7dfd09,
0xd3f93b35435d7c4c,
0xc47bc5014a1a6daf,
0x359ab6419ca1091b,
0xc30163d203c94b62,
0x79e0de63425dcf1d,
0x985915fc12f542e4,
0x3e6f5b7b17b2939d,
0xa705992ceecf9c42,
0x50c6ff782a838353,
0xa4f8bf5635246428,
0x871b7795e136be99,
0x28e2557b59846e3f,
0x331aeada2fe589cf,
0x3ff0d2c85def7621,
0xfed077a756b53a9,
0xd3e8495912c62894,
0x64712dd7abbbd95c,
0xbd8d794d96aacfb3,
0xecf0d7a0fc5583a0,
0xf41686c49db57244,
0x311c2875c522ced5,
0x7d633293366b828b,
0xae5dff9c02033197,
0xd9f57f830283fdfc,
0xd072df63c324fd7b,
0x4247cb9e59f71e6d,
0x52d9be85f074e608,
0x67902e276c921f8b,
0xba1cd8a3db53b6,
0x80e8a40eccd228a4,
0x6122cd128006b2cd,
0x796b805720085f81,
0xcbe3303674053bb0,
0xbedbfc4411068a9c,
0xee92fb5515482d44,
0x751bdd152d4d1c4a,
0xd262d45a78a0635d,
0x86fb897116c87c34,
0xd45d35e6ae3d4da0,
0x8974836059cca109,
0x2bd1a438703fc94b,
0x7b6306a34627ddcf,
0x1a3bc84c17b1d542,
0x20caba5f1d9e4a93,
0x547eb47b7282ee9c,
0xe99e619a4f23aa43,
0x6405fa00e2ec94d4,
0xde83bc408dd3dd04,
0x9624ab50b148d445,
0x3badd624dd9b0957,
0xe54ca5d70a80e5d6,
0x5e9fcf4ccd211f4c,
0x7647c3200069671f,
0x29ecd9f40041e073,
0xf468107100525890,
0x7182148d4066eeb4,
0xc6f14cd848405530,
0xb8ada00e5a506a7c,
0xa6d90811f0e4851c,
0x908f4a166d1da663,
0x9a598e4e043287fe,
0x40eff1e1853f29fd,
0xd12bee59e68ef47c,
0x82bb74f8301958ce,
0xe36a52363c1faf01,
0xdc44e6c3cb279ac1,
0x29ab103a5ef8c0b9,
0x7415d448f6b6f0e7,
0x111b495b3464ad21,
0xcab10dd900beec34,
0x3d5d514f40eea742,
0xcb4a5a3112a5112,
0x47f0e785eaba72ab,
0x59ed216765690f56,
0x306869c13ec3532c,
0x1e414218c73a13fb,
0xe5d1929ef90898fa,
0xdf45f746b74abf39,
0x6b8bba8c328eb783,
0x66ea92f3f326564,
0xc80a537b0efefebd,
0xbd06742ce95f5f36,
0x2c48113823b73704,
0xf75a15862ca504c5,
0x9a984d73dbe722fb,
0xc13e60d0d2e0ebba,
0x318df905079926a8,
0xfdf17746497f7052,
0xfeb6ea8bedefa633,
0xfe64a52ee96b8fc0,
0x3dfdce7aa3c673b0,
0x6bea10ca65c084e,
0x486e494fcff30a62,
0x5a89dba3c3efccfa,
0xf89629465a75e01c,
0xf6bbb397f1135823,
0x746aa07ded582e2c,
0xa8c2a44eb4571cdc,
0x92f34d62616ce413,
0x77b020baf9c81d17,
0xace1474dc1d122e,
0xd819992132456ba,
0x10e1fff697ed6c69,
0xca8d3ffa1ef463c1,
0xbd308ff8a6b17cb2,
0xac7cb3f6d05ddbde,
0x6bcdf07a423aa96b,
0x86c16c98d2c953c6,
0xe871c7bf077ba8b7,
0x11471cd764ad4972,
0xd598e40d3dd89bcf,
0x4aff1d108d4ec2c3,
0xcedf722a585139ba,
0xc2974eb4ee658828,
0x733d226229feea32,
0x806357d5a3f525f,
0xca07c2dcb0cf26f7,
0xfc89b393dd02f0b5,
0xbbac2078d443ace2,
0xd54b944b84aa4c0d,
0xa9e795e65d4df11,
0x4d4617b5ff4a16d5,
0x504bced1bf8e4e45,
0xe45ec2862f71e1d6,
0x5d767327bb4e5a4c,
0x3a6a07f8d510f86f,
0x890489f70a55368b,
0x2b45ac74ccea842e,
0x3b0b8bc90012929d,
0x9ce6ebb40173744,
0xcc420a6a101d0515,
0x9fa946824a12232d,
0x47939822dc96abf9,
0x59787e2b93bc56f7,
0x57eb4edb3c55b65a,
0xede622920b6b23f1,
0xe95fab368e45eced,
0x11dbcb0218ebb414,
0xd652bdc29f26a119,
0x4be76d3346f0495f,
0x6f70a4400c562ddb,
0xcb4ccd500f6bb952,
0x7e2000a41346a7a7,
0x8ed400668c0c28c8,
0x728900802f0f32fa,
0x4f2b40a03ad2ffb9,
0xe2f610c84987bfa8,
0xdd9ca7d2df4d7c9,
0x91503d1c79720dbb,
0x75a44c6397ce912a,
0xc986afbe3ee11aba,
0xfbe85badce996168,
0xfae27299423fb9c3,
0xdccd879fc967d41a,
0x5400e987bbc1c920,
0x290123e9aab23b68,
0xf9a0b6720aaf6521,
0xf808e40e8d5b3e69,
0xb60b1d1230b20e04,
0xb1c6f22b5e6f48c2,
0x1e38aeb6360b1af3,
0x25c6da63c38de1b0,
0x579c487e5a38ad0e,
0x2d835a9df0c6d851,
0xf8e431456cf88e65,
0x1b8e9ecb641b58ff,
0xe272467e3d222f3f,
0x5b0ed81dcc6abb0f,
0x98e947129fc2b4e9,
0x3f2398d747b36224,
0x8eec7f0d19a03aad,
0x1953cf68300424ac,
0x5fa8c3423c052dd7,
0x3792f412cb06794d,
0xe2bbd88bbee40bd0,
0x5b6aceaeae9d0ec4,
0xf245825a5a445275,
0xeed6e2f0f0d56712,
0x55464dd69685606b,
0xaa97e14c3c26b886,
0xd53dd99f4b3066a8,
0xe546a8038efe4029,
0xde98520472bdd033,
0x963e66858f6d4440,
0xdde7001379a44aa8,
0x5560c018580d5d52,
0xaab8f01e6e10b4a6,
0xcab3961304ca70e8,
0x3d607b97c5fd0d22,
0x8cb89a7db77c506a,
0x77f3608e92adb242,
0x55f038b237591ed3,
0x6b6c46dec52f6688,
0x2323ac4b3b3da015,
0xabec975e0a0d081a,
0x96e7bd358c904a21,
0x7e50d64177da2e54,
0xdde50bd1d5d0b9e9,
0x955e4ec64b44e864,
0xbd5af13bef0b113e,
0xecb1ad8aeacdd58e,
0x67de18eda5814af2,
0x80eacf948770ced7,
0xa1258379a94d028d,
0x96ee45813a04330,
0x8bca9d6e188853fc,
0x775ea264cf55347d,
0x95364afe032a819d,
0x3a83ddbd83f52204,
0xc4926a9672793542,
0x75b7053c0f178293,
0x5324c68b12dd6338,
0xd3f6fc16ebca5e03,
0x88f4bb1ca6bcf584,
0x2b31e9e3d06c32e5,
0x3aff322e62439fcf,
0x9befeb9fad487c2,
0x4c2ebe687989a9b3,
0xf9d37014bf60a10,
0x538484c19ef38c94,
0x2865a5f206b06fb9,
0xf93f87b7442e45d3,
0xf78f69a51539d748,
0xb573440e5a884d1b,
0x31680a88f8953030,
0xfdc20d2b36ba7c3d,
0x3d32907604691b4c,
0xa63f9a49c2c1b10f,
0xfcf80dc33721d53,
0xd3c36113404ea4a8,
0x645a1cac083126e9,
0x3d70a3d70a3d70a3,
0xcccccccccccccccc,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x4000000000000000,
0x5000000000000000,
0xa400000000000000,
0x4d00000000000000,
0xf020000000000000,
0x6c28000000000000,
0xc732000000000000,
0x3c7f400000000000,
0x4b9f100000000000,
0x1e86d40000000000,
0x1314448000000000,
0x17d955a000000000,
0x5dcfab0800000000,
0x5aa1cae500000000,
0xf14a3d9e40000000,
0x6d9ccd05d0000000,
0xe4820023a2000000,
0xdda2802c8a800000,
0xd50b2037ad200000,
0x4526f422cc340000,
0x9670b12b7f410000,
0x3c0cdd765f114000,
0xa5880a69fb6ac800,
0x8eea0d047a457a00,
0x72a4904598d6d880,
0x47a6da2b7f864750,
0x999090b65f67d924,
0xfff4b4e3f741cf6d,
0xbff8f10e7a8921a4,
0xaff72d52192b6a0d,
0x9bf4f8a69f764490,
0x2f236d04753d5b4,
0x1d762422c946590,
0x424d3ad2b7b97ef5,
0xd2e0898765a7deb2,
0x63cc55f49f88eb2f,
0x3cbf6b71c76b25fb,
0x8bef464e3945ef7a,
0x97758bf0e3cbb5ac,
0x3d52eeed1cbea317,
0x4ca7aaa863ee4bdd,
0x8fe8caa93e74ef6a,
0xb3e2fd538e122b44,
0x60dbbca87196b616,
0xbc8955e946fe31cd,
0x6babab6398bdbe41,
0xc696963c7eed2dd1,
0xfc1e1de5cf543ca2,
0x3b25a55f43294bcb,
0x49ef0eb713f39ebe,
0x6e3569326c784337,
0x49c2c37f07965404,
0xdc33745ec97be906,
0x69a028bb3ded71a3,
0xc40832ea0d68ce0c,
0xf50a3fa490c30190,
0x792667c6da79e0fa,
0x577001b891185938,
0xed4c0226b55e6f86,
0x544f8158315b05b4,
0x696361ae3db1c721,
0x3bc3a19cd1e38e9,
0x4ab48a04065c723,
0x62eb0d64283f9c76,
0x3ba5d0bd324f8394,
0xca8f44ec7ee36479,
0x7e998b13cf4e1ecb,
0x9e3fedd8c321a67e,
0xc5cfe94ef3ea101e,
0xbba1f1d158724a12,
0x2a8a6e45ae8edc97,
0xf52d09d71a3293bd,
0x593c2626705f9c56,
0x6f8b2fb00c77836c,
0xb6dfb9c0f956447,
0x4724bd4189bd5eac,
0x58edec91ec2cb657,
0x2f2967b66737e3ed,
0xbd79e0d20082ee74,
0xecd8590680a3aa11,
0xe80e6f4820cc9495,
0x3109058d147fdcdd,
0xbd4b46f0599fd415,
0x6c9e18ac7007c91a,
0x3e2cf6bc604ddb0,
0x84db8346b786151c,
0xe612641865679a63,
0x4fcb7e8f3f60c07e,
0xe3be5e330f38f09d,
0x5cadf5bfd3072cc5,
0x73d9732fc7c8f7f6,
0x2867e7fddcdd9afa,
0xb281e1fd541501b8,
0x1f225a7ca91a4226,
0x3375788de9b06958,
0x52d6b1641c83ae,
0xc0678c5dbd23a49a,
0xf840b7ba963646e0,
0xb650e5a93bc3d898,
0xa3e51f138ab4cebe,
0xc66f336c36b10137,
0xb80b0047445d4184,
0xa60dc059157491e5,
0x87c89837ad68db2f,
0x29babe4598c311fb,
0xf4296dd6fef3d67a,
0x1899e4a65f58660c,
0x5ec05dcff72e7f8f,
0x76707543f4fa1f73,
0x6a06494a791c53a8,
0x487db9d17636892,
0x45a9d2845d3c42b6,
0xb8a2392ba45a9b2,
0x8e6cac7768d7141e,
0x3207d795430cd926,
0x7f44e6bd49e807b8,
0x5f16206c9c6209a6,
0x36dba887c37a8c0f,
0xc2494954da2c9789,
0xf2db9baa10b7bd6c,
0x6f92829494e5acc7,
0xcb772339ba1f17f9,
0xff2a760414536efb,
0xfef5138519684aba,
0x7eb258665fc25d69,
0xef2f773ffbd97a61,
0xaafb550ffacfd8fa,
0x95ba2a53f983cf38,
0xdd945a747bf26183,
0x94f971119aeef9e4,
0x7a37cd5601aab85d,
0xac62e055c10ab33a,
0x577b986b314d6009,
0xed5a7e85fda0b80b,
0x14588f13be847307,
0x596eb2d8ae258fc8,
0x6fca5f8ed9aef3bb,
0x25de7bb9480d5854,
0xaf561aa79a10ae6a,
0x1b2ba1518094da04,
0x90fb44d2f05d0842,
0x353a1607ac744a53,
0x42889b8997915ce8,
0x69956135febada11,
0x43fab9837e699095,
0x94f967e45e03f4bb,
0x1d1be0eebac278f5,
0x6462d92a69731732,
0x7d7b8f7503cfdcfe,
0x5cda735244c3d43e,
0x3a0888136afa64a7,
0x88aaa1845b8fdd0,
0x8aad549e57273d45,
0x36ac54e2f678864b,
0x84576a1bb416a7dd,
0x656d44a2a11c51d5,
0x9f644ae5a4b1b325,
0x873d5d9f0dde1fee,
0xa90cb506d155a7ea,
0x9a7f12442d588f2,
0xc11ed6d538aeb2f,
0x8f1668c8a86da5fa,
0xf96e017d694487bc,
0x37c981dcc395a9ac,
0x85bbe253f47b1417,
0x93956d7478ccec8e,
0x387ac8d1970027b2,
0x6997b05fcc0319e,
0x441fece3bdf81f03,
0xd527e81cad7626c3,
0x8a71e223d8d3b074,
0xf6872d5667844e49,
0xb428f8ac016561db,
0xe13336d701beba52,
0xecc0024661173473,
0x27f002d7f95d0190,
0x31ec038df7b441f4,
0x7e67047175a15271,
0xf0062c6e984d386,
0x52c07b78a3e60868,
0xa7709a56ccdf8a82,
0x88a66076400bb691,
0x6acff893d00ea435,
0x583f6b8c4124d43,
0xc3727a337a8b704a,
0x744f18c0592e4c5c,
0x1162def06f79df73,
0x8addcb5645ac2ba8,
0x6d953e2bd7173692,
0xc8fa8db6ccdd0437,
0x1d9c9892400a22a2,
0x2503beb6d00cab4b,
0x2e44ae64840fd61d,
0x5ceaecfed289e5d2,
0x7425a83e872c5f47,
0xd12f124e28f77719,
0x82bd6b70d99aaa6f,
0x636cc64d1001550b,
0x3c47f7e05401aa4e,
0x65acfaec34810a71,
0x7f1839a741a14d0d,
0x1ede48111209a050,
0x934aed0aab460432,
0xf81da84d5617853f,
0x36251260ab9d668e,
0xc1d72b7c6b426019,
0xb24cf65b8612f81f,
0xdee033f26797b627,
0x169840ef017da3b1,
0x8e1f289560ee864e,
0xf1a6f2bab92a27e2,
0xae10af696774b1db,
0xacca6da1e0a8ef29,
0x17fd090a58d32af3,
0xddfc4b4cef07f5b0,
0x4abdaf101564f98e,
0x9d6d1ad41abe37f1,
0x84c86189216dc5ed,
0x32fd3cf5b4e49bb4,
0x3fbc8c33221dc2a1,
0xfabaf3feaa5334a,
0x29cb4d87f2a7400e,
0x743e20e9ef511012,
0x914da9246b255416,
0x1ad089b6c2f7548e,
0xa184ac2473b529b1,
0xc9e5d72d90a2741e,
0x7e2fa67c7a658892,
0xddbb901b98feeab7,
0x552a74227f3ea565,
0xd53a88958f87275f,
0x8a892abaf368f137,
0x2d2b7569b0432d85,
0x9c3b29620e29fc73,
0x8349f3ba91b47b8f,
0x241c70a936219a73,
0xed238cd383aa0110,
0xf4363804324a40aa,
0xb143c6053edcd0d5,
0xdd94b7868e94050a,
0xca7cf2b4191c8326,
0xfd1c2f611f63a3f0,
0xbc633b39673c8cec,
0xd5be0503e085d813,
0x4b2d8644d8a74e18,
0xddf8e7d60ed1219e,
0xcabb90e5c942b503,
0x3d6a751f3b936243,
0xcc512670a783ad4,
0x27fb2b80668b24c5,
0xb1f9f660802dedf6,
0x5e7873f8a0396973,
0xdb0b487b6423e1e8,
0x91ce1a9a3d2cda62,
0x7641a140cc7810fb,
0xa9e904c87fcb0a9d,
0x546345fa9fbdcd44,
0xa97c177947ad4095,
0x49ed8eabcccc485d,
0x5c68f256bfff5a74,
0x73832eec6fff3111,
0xc831fd53c5ff7eab,
0xba3e7ca8b77f5e55,
0x28ce1bd2e55f35eb,
0x7980d163cf5b81b3,
0xd7e105bcc332621f,
0x8dd9472bf3fefaa7,
0xb14f98f6f0feb951,
0x6ed1bf9a569f33d3,
0xa862f80ec4700c8,
0xcd27bb612758c0fa,
0x8038d51cb897789c,
0xe0470a63e6bd56c3,
0x1858ccfce06cac74,
0xf37801e0c43ebc8,
0xd30560258f54e6ba,
0x47c6b82ef32a2069,
0x4cdc331d57fa5441,
0xe0133fe4adf8e952,
0x58180fddd97723a6,
0x570f09eaa7ea7648};
} // namespace terrier::execution::util
| 79.437267
| 120
| 0.399315
|
rohanaggarwal7997
|
1cb443b558689eb8476d57651ccbc56b0b20d513
| 4,703
|
inl
|
C++
|
matlab_code/jjcao_code-head/toolbox/jjcao_mesh/geodesic/mex/gw/gw_core/GW_SmartCounter.inl
|
joycewangsy/normals_pointnet
|
fc74a8ed1a009b18785990b1b4c20eda0549721c
|
[
"MIT"
] | null | null | null |
matlab_code/jjcao_code-head/toolbox/jjcao_mesh/geodesic/mex/gw/gw_core/GW_SmartCounter.inl
|
joycewangsy/normals_pointnet
|
fc74a8ed1a009b18785990b1b4c20eda0549721c
|
[
"MIT"
] | null | null | null |
matlab_code/jjcao_code-head/toolbox/jjcao_mesh/geodesic/mex/gw/gw_core/GW_SmartCounter.inl
|
joycewangsy/normals_pointnet
|
fc74a8ed1a009b18785990b1b4c20eda0549721c
|
[
"MIT"
] | null | null | null |
/*------------------------------------------------------------------------------*/
/**
* \file GW_SmartCounter.inl
* \brief Inlined methods for \c GW_SmartCounter
* \author Gabriel Peyr?2001-09-12
*/
/*------------------------------------------------------------------------------*/
#include "GW_SmartCounter.h"
namespace GW {
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter constructor
*
* \author Gabriel Peyr?2001-09-12
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
GW_SmartCounter::GW_SmartCounter()
: nReferenceCounter_ ( 0 )
{
/* NOTHING */
}
/*------------------------------------------------------------------------------
* Name : GW_SmartCounter constructor
*
* \param Dup EXPLANATION
* \return PUT YOUR RETURN VALUE AND ITS EXPLANATION
* \author Antoine Bouthors 2001-11-24
*
* PUT YOUR COMMENTS HERE
*------------------------------------------------------------------------------*/
GW_INLINE
GW_SmartCounter::GW_SmartCounter( const GW_SmartCounter& Dup )
: nReferenceCounter_(0)
{
/* NOTHING */
}
/*------------------------------------------------------------------------------
* Name : GW_SmartCounter::operator
*
* \param Dup EXPLANATION
* \return PUT YOUR RETURN VALUE AND ITS EXPLANATION
* \author Antoine Bouthors 2001-11-24
*
* PUT YOUR COMMENTS HERE
*------------------------------------------------------------------------------*/
GW_INLINE
GW_SmartCounter& GW_SmartCounter::operator=( const GW_SmartCounter& Dup )
{
nReferenceCounter_ = 0;
return (*this);
}
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter destructor
*
* \author Gabriel Peyr?2001-09-12
*
* Check that nobody is still using the object.
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
GW_SmartCounter::~GW_SmartCounter()
{
GW_ASSERT( nReferenceCounter_==0 );
}
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter::UseIt
*
* \author Gabriel Peyr?2001-09-10
*
* Declare that we use this object. We must call \c ReleaseIt when we no longer use this object.
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
void GW_SmartCounter::UseIt()
{
GW_ASSERT( nReferenceCounter_<=50000 );
nReferenceCounter_++;
}
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter::ReleaseIt
*
* \author Gabriel Peyr?2001-09-10
*
* Declare that we no longer use this object.
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
void GW_SmartCounter::ReleaseIt()
{
GW_ASSERT( nReferenceCounter_>0 );
nReferenceCounter_--;
}
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter::NoLongerUsed
*
* \return true if no one use this object anymore.
* \author Gabriel Peyr?2001-09-10
*
* We can delete the object only if \c NoLongerUsed return true.
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
bool GW_SmartCounter::NoLongerUsed()
{
GW_ASSERT( nReferenceCounter_>=0 );
return nReferenceCounter_==0;
}
/*------------------------------------------------------------------------------
* Name : GW_SmartCounter::GetReferenceCounter
*
* \return the value of the reference counter
* \author Antoine Bouthors 2001-11-30
*
*------------------------------------------------------------------------------*/
GW_INLINE
GW_I32 GW_SmartCounter::GetReferenceCounter()
{
return nReferenceCounter_;
}
} // End namespace GW
///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2000-2001 The Orion3D Rewiew Board //
//---------------------------------------------------------------------------//
// This file is under the Orion3D licence. //
// Refer to orion3d_licence.txt for more details about the Orion3D Licence. //
//---------------------------------------------------------------------------//
// Ce fichier est soumis a la Licence Orion3D. //
// Se reporter a orion3d_licence.txt pour plus de details sur cette licence.//
///////////////////////////////////////////////////////////////////////////////
// END OF FILE //
///////////////////////////////////////////////////////////////////////////////
| 29.21118
| 96
| 0.402296
|
joycewangsy
|
1cb60bcb0a7f2747bb34edc4ffef8a1ae21c6fac
| 415
|
cpp
|
C++
|
src/1064b/emm.cpp
|
lifeich1/play-cf
|
7eb6dbb290fcf7935e88d3f090d4af79e7308773
|
[
"WTFPL"
] | null | null | null |
src/1064b/emm.cpp
|
lifeich1/play-cf
|
7eb6dbb290fcf7935e88d3f090d4af79e7308773
|
[
"WTFPL"
] | 8
|
2018-10-15T06:47:19.000Z
|
2019-02-15T09:58:02.000Z
|
src/1064b/emm.cpp
|
lifeich1/play-cf
|
7eb6dbb290fcf7935e88d3f090d4af79e7308773
|
[
"WTFPL"
] | null | null | null |
//-[
#include "type.h"
//-]
namespace licf {
namespace emm_1064b {
// placeholder
}
}
using namespace licf::emm_1064b;
int emm_1064b(const _in_t & in_, _out_t & out_)
{
int n;
while (in_.read(&n))
{
LL res = 1;
for (; n > 0; n >>= 1)
{
if (n & 1)
{
res <<= 1ll;
}
}
in_.put(res);
}
return 0;
}
| 12.96875
| 47
| 0.414458
|
lifeich1
|
1cb6b50ac4e909f6822ded0ee163ee38682adb8b
| 1,093
|
cpp
|
C++
|
src/lib/cert/cvc/cvc_req.cpp
|
el-forkorama/botan
|
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
|
[
"BSD-2-Clause"
] | null | null | null |
src/lib/cert/cvc/cvc_req.cpp
|
el-forkorama/botan
|
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
|
[
"BSD-2-Clause"
] | null | null | null |
src/lib/cert/cvc/cvc_req.cpp
|
el-forkorama/botan
|
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* (C) 2007 FlexSecure GmbH
* 2008-2010 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/cvc_req.h>
#include <botan/cvc_cert.h>
#include <botan/ber_dec.h>
namespace Botan {
bool EAC1_1_Req::operator==(EAC1_1_Req const& rhs) const
{
return (this->tbs_data() == rhs.tbs_data() &&
this->get_concat_sig() == rhs.get_concat_sig());
}
void EAC1_1_Req::force_decode()
{
std::vector<byte> enc_pk;
BER_Decoder tbs_cert(m_tbs_bits);
size_t cpi;
tbs_cert.decode(cpi, ASN1_Tag(41), APPLICATION)
.start_cons(ASN1_Tag(73))
.raw_bytes(enc_pk)
.end_cons()
.decode(m_chr)
.verify_end();
if(cpi != 0)
throw Decoding_Error("EAC1_1 requests cpi was not 0");
m_pk = decode_eac1_1_key(enc_pk, m_sig_algo);
}
EAC1_1_Req::EAC1_1_Req(DataSource& in)
{
init(in);
m_self_signed = true;
do_decode();
}
EAC1_1_Req::EAC1_1_Req(const std::string& in)
{
DataSource_Stream stream(in, true);
init(stream);
m_self_signed = true;
do_decode();
}
}
| 20.240741
| 70
| 0.651418
|
el-forkorama
|
1cc139eda2b6b5a9c47ddadf86860934f1467cea
| 2,592
|
hpp
|
C++
|
lib/core/test/fakelogger.hpp
|
DanglingPointer/veridie-native
|
dd75c92617094d20ae34fa2d26fa9b1b5eab54f1
|
[
"Apache-2.0"
] | null | null | null |
lib/core/test/fakelogger.hpp
|
DanglingPointer/veridie-native
|
dd75c92617094d20ae34fa2d26fa9b1b5eab54f1
|
[
"Apache-2.0"
] | null | null | null |
lib/core/test/fakelogger.hpp
|
DanglingPointer/veridie-native
|
dd75c92617094d20ae34fa2d26fa9b1b5eab54f1
|
[
"Apache-2.0"
] | null | null | null |
#ifndef TESTS_FAKELOGGER_HPP
#define TESTS_FAKELOGGER_HPP
#include "utils/log.hpp"
#include <algorithm>
#include <vector>
class FakeLogger
{
public:
enum class Level
{
DEBUG,
INFO,
WARNING,
ERROR,
FATAL
};
struct LogLine
{
Level lvl;
std::string tag;
std::string text;
};
FakeLogger()
{
s_lines.clear();
Log::s_debugHandler = LogDebug;
Log::s_infoHandler = LogInfo;
Log::s_warningHandler = LogWarning;
Log::s_errorHandler = LogError;
Log::s_fatalHandler = LogFatal;
}
~FakeLogger()
{
s_lines.clear();
Log::s_debugHandler = nullptr;
Log::s_infoHandler = nullptr;
Log::s_warningHandler = nullptr;
Log::s_errorHandler = nullptr;
Log::s_fatalHandler = nullptr;
}
std::vector<LogLine> GetEntries() const { return s_lines; }
std::string GetLastStateLine() const
{
auto it = std::find_if(s_lines.crbegin(), s_lines.crend(), [](const LogLine & line) {
return line.text.starts_with("New state:");
});
if (it != s_lines.crend())
return it->text;
return "";
}
bool Empty() const { return s_lines.empty(); }
void Clear() { s_lines.clear(); }
bool NoWarningsOrErrors() const
{
for (const auto & line : s_lines) {
switch (line.lvl) {
case Level::ERROR:
case Level::WARNING:
case Level::FATAL:
return false;
default:
break;
}
}
return true;
}
void DumpLines() const
{
for (const auto & entry : s_lines) {
fprintf(stderr,
"Tag(%s) Prio(%d): %s\n",
entry.tag.c_str(),
static_cast<int>(entry.lvl),
entry.text.c_str());
}
}
private:
static inline std::vector<LogLine> s_lines;
static void LogDebug(const char * tag, const char * text)
{
s_lines.emplace_back(LogLine{Level::DEBUG, tag, text});
}
static void LogInfo(const char * tag, const char * text)
{
s_lines.emplace_back(LogLine{Level::INFO, tag, text});
}
static void LogWarning(const char * tag, const char * text)
{
s_lines.emplace_back(LogLine{Level::WARNING, tag, text});
}
static void LogError(const char * tag, const char * text)
{
s_lines.emplace_back(LogLine{Level::ERROR, tag, text});
}
static void LogFatal(const char * tag, const char * text)
{
s_lines.emplace_back(LogLine{Level::FATAL, tag, text});
}
};
#endif // TESTS_FAKELOGGER_HPP
| 23.142857
| 91
| 0.580247
|
DanglingPointer
|
1cc2c32fe849253ec5bcaa89abc100f454914d6b
| 6,048
|
cpp
|
C++
|
code/source/thread_capture.cpp
|
DEAKSoftware/KFX
|
8a759d21a651d9f8acbfef2e3d19b1e8580a74b5
|
[
"MIT"
] | null | null | null |
code/source/thread_capture.cpp
|
DEAKSoftware/KFX
|
8a759d21a651d9f8acbfef2e3d19b1e8580a74b5
|
[
"MIT"
] | null | null | null |
code/source/thread_capture.cpp
|
DEAKSoftware/KFX
|
8a759d21a651d9f8acbfef2e3d19b1e8580a74b5
|
[
"MIT"
] | null | null | null |
/*===========================================================================
Video Capture Thread
Dominik Deak
===========================================================================*/
#ifndef ___THREAD_CAPTURE_CPP___
#define ___THREAD_CAPTURE_CPP___
/*---------------------------------------------------------------------------
Header files
---------------------------------------------------------------------------*/
#include "common.h"
#include "debug.h"
#include "mutex.h"
#include "thread_capture.h"
/*---------------------------------------------------------------------------
Static data.
---------------------------------------------------------------------------*/
const char* CaptureThread::ExtTGA = "tga";
const char* CaptureThread::ExtPNG = "png";
/*---------------------------------------------------------------------------
Opens a new target directory for streaming. The subdirectory names are
generated automatically, based on the current date and timestamp, and with
the Prefix added.
---------------------------------------------------------------------------*/
CaptureThread::CaptureThread(QObject* Parent, const QString &Path, const QString &Prefix, CapFormat Format, bool Compress) : QThread(Parent)
{
Clear();
if (Parent == nullptr) {throw dexception("Invalid parameters.");}
setTerminationEnabled(true);
//Hook signal functions to the parent class' slot functions
QObject::connect(this, SIGNAL(SignalError(QString)), Parent, SLOT(CaptureError(QString)));
CaptureThread::Format = Format;
CaptureThread::Compress = Compress;
Dir = Path;
switch (CaptureThread::Format)
{
case CaptureThread::FormatTGA : Ext = CaptureThread::ExtTGA; break;
case CaptureThread::FormatPNG : Ext = CaptureThread::ExtPNG; break;
default : throw dexception("The specified file format is unknown.");
}
QString SubDir;
bool Exists = false;
uint I = 0;
do {
QDate Date = QDate::currentDate();
QTime Time = QTime::currentTime();
SubDir = Prefix;
SubDir += Date.toString(" yyyy-MM-dd ");
SubDir += Time.toString("HH-mm-ss-zzz");
if (I > 0) {SubDir += QString(" %1").arg(I);}
I++;
Exists = Dir.exists(SubDir);
}
while (Exists && I < MaxSubDirAttempts);
if (Exists) {throw dexception("Failed to create a unique subdirectory.");}
if (!Dir.mkdir(SubDir))
{throw dexception("Failed to create a new subdirectory.");}
if (!Dir.cd(SubDir))
{throw dexception("Failed to change into subdirectory.");}
start();
}
/*---------------------------------------------------------------------------
Destructor.
---------------------------------------------------------------------------*/
CaptureThread::~CaptureThread(void)
{
Destroy();
}
/*---------------------------------------------------------------------------
Clears the structure.
---------------------------------------------------------------------------*/
void CaptureThread::Clear(void)
{
Count = 0;
Format = CaptureThread::FormatTGA;
Ext = CaptureThread::ExtTGA;
Compress = false;
Exit = false;
}
/*---------------------------------------------------------------------------
Destroys the structure.
---------------------------------------------------------------------------*/
void CaptureThread::Destroy(void)
{
Clear();
}
/*---------------------------------------------------------------------------
Thread entry point.
---------------------------------------------------------------------------*/
void CaptureThread::run(void)
{
debug("Started capture thread.\n");
try {
while (!Exit)
{
//Wait for new frame
QMutexLocker MutexLocker(&UpdateMutex);
UpdateWait.wait(&UpdateMutex);
//Lock frame
NAMESPACE_PROJECT::MutexControl Mutex(Frame.GetMutexHandle());
if (!Mutex.LockRequest()) {debug("Mutex already locked, dropping frame.\n"); continue;}
if (Frame.Size() < 1) {debug("No data in frame, dropping frame.\n"); continue;}
//Construct file name
FileName = QString("%1.").arg((long)Count, FileNameDigits, FileNameBase, QLatin1Char('0')) + Ext;
FileName = Dir.absoluteFilePath(FileName);
Path = FileName.toAscii();
//Save frame
switch (Format)
{
case CaptureThread::FormatTGA :
TGA.Save(Frame, Path.constData(), false, Compress);
break;
case CaptureThread::FormatPNG :
PNG.Save(Frame, Path.constData(), Compress ? NAMESPACE_PROJECT::File::PNG::CompSpeed : NAMESPACE_PROJECT::File::PNG::CompNone);
break;
default : throw dexception("The specified file format is unknown.");
}
Count++;
}
}
catch (std::exception &e)
{
SignalError(e.what());
Exit = true;
}
catch (...)
{
SignalError("Trapped an unhandled exception in the capture thread.");
Exit = true;
}
debug("Stopping capture thread.\n");
}
/*---------------------------------------------------------------------------
Signals to exit thread.
---------------------------------------------------------------------------*/
void CaptureThread::stop(void)
{
Exit = true;
UpdateWait.wakeAll();
}
/*---------------------------------------------------------------------------
Signals thread to saves a frame to file.
---------------------------------------------------------------------------*/
void CaptureThread::update(void)
{
if (Exit) {return;}
UpdateWait.wakeAll();
}
//==== End of file ===========================================================
#endif
| 31.175258
| 144
| 0.430556
|
DEAKSoftware
|
1cc82007e7d7bf67fbd363d61d85c060a6120404
| 5,276
|
cpp
|
C++
|
src/directions/VDWDirection.cpp
|
XiyuChenFAU/kgs_vibration_entropy
|
117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9
|
[
"MIT"
] | 1
|
2020-05-23T18:26:14.000Z
|
2020-05-23T18:26:14.000Z
|
src/directions/VDWDirection.cpp
|
XiyuChenFAU/kgs_vibration_entropy
|
117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9
|
[
"MIT"
] | 8
|
2017-01-26T19:54:38.000Z
|
2021-02-06T16:06:30.000Z
|
src/directions/VDWDirection.cpp
|
XiyuChenFAU/kgs_vibration_entropy
|
117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9
|
[
"MIT"
] | null | null | null |
/*
Excited States software: KGS
Contributors: See CONTRIBUTORS.txt
Contact: kgs-contact@simtk.org
Copyright (C) 2009-2017 Stanford University
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:
This entire text, including 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, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "VDWDirection.h"
#include <vector>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include "core/Molecule.h"
#include "core/Grid.h"
#include "core/Chain.h"
void VDWDirection::computeGradient(Configuration* conf, Configuration* target, gsl_vector* ret)
{
gsl_vector_set_all(ret, 0.0);
Molecule * protein = conf->updatedMolecule();
gsl_matrix* atomJacobian1 = gsl_matrix_calloc(3,protein->totalDofNum());
gsl_matrix* atomJacobian2 = gsl_matrix_calloc(3,protein->totalDofNum());
gsl_vector* p12 = gsl_vector_calloc(3);
gsl_vector* p_temp = gsl_vector_calloc(protein->totalDofNum());
for (auto const& atom1: protein->getAtoms()) {
std::vector<Atom*> neighbors = protein->getGrid()->getNeighboringAtomsVDW(atom1, //atom
true, //neighborWithLargerId
true, //noCovBondNeighbor
true, //noSecondCovBondNeighbor
true, //noHbondNeighbor
VDW_R_MAX); //radius
computeAtomJacobian(atom1,atomJacobian1);
for(auto const& atom2: neighbors){
double r_12 = atom1->distanceTo(atom2);
//Dimitars version
//double atomContribution = (-12)*VDW_SIGMA*(pow(VDW_R0,6)*pow(r_12,-8)-pow(VDW_R0,12)*pow(r_12,-14));
double vdw_r12 = atom1->getRadius() + atom2->getRadius() ; // from CHARMM: arithmetic mean
double eps_r12 = sqrt(atom1->getEpsilon() * atom2->getEpsilon()); // from CHARMM: geometric mean
double ratio = vdw_r12/r_12;
//double atomContribution = 4 * eps_r12 * (pow(ratio,12)-2*pow(ratio,6));
double atomContribution = 12 * 4 * eps_r12 * (pow(ratio,6)-pow(ratio,12))/r_12;
computeAtomJacobian(atom2,atomJacobian2);
gsl_matrix_sub(atomJacobian1,atomJacobian2); // atomJacobian1 = atomJacobian1 - atomJacobian2
Math3D::Vector3 p12_v3 = atom1->m_position - atom2->m_position;//TODO: Subtract directly into gsl_vector
Coordinate::copyToGslVector(p12_v3, p12);
gsl_blas_dgemv(CblasTrans,1,atomJacobian1,p12,0,p_temp);
//std::cout<<"VDWDirection::computeGradient - pair-gradient norm: "<<gsl_blas_dnrm2(p_temp)<<std::endl;
gsl_vector_scale(p_temp, atomContribution/gsl_blas_dnrm2(p_temp));
//std::cout<<"VDWDirection::computeGradient - after scaling: "<<gsl_blas_dnrm2(p_temp)<<std::endl;
gsl_vector_add(ret,p_temp);
}
}
gsl_vector_scale(ret,0.001);
//std::cout<<"VDWDirection::computeGradient - total gradient norm: "<<gsl_blas_dnrm2(ret)<<std::endl;
//TODO: Improve to minimize reallocations
gsl_matrix_free(atomJacobian1);
gsl_matrix_free(atomJacobian2);
gsl_vector_free(p12);
gsl_vector_free(p_temp);
}
void VDWDirection::computeAtomJacobian (Atom* atom, gsl_matrix* jacobian) {
Molecule * protein = atom->getResidue()->getChain()->getMolecule();
//KinVertex *vertex = protein->getRigidbodyGraphVertex(atom);
KinVertex *vertex = atom->getRigidbody()->getVertex();
while (vertex->m_parent!=nullptr) {
KinEdge* edge = vertex->m_parent->findEdge(vertex);
int dof_id = edge->getDOF()->getIndex();
// Bond * bond_ptr = edge->getBond();
// Coordinate bp1 = bond_ptr->Atom1->m_position;
// Coordinate bp2 = bond_ptr->m_atom2->m_position;
// Math3D::Vector3 jacobian_entry = ComputeJacobianEntry(bp1,bp2,atom->m_position);
Math3D::Vector3 jacobian_entry = edge->getDOF()->getDerivative(atom->m_position);
gsl_matrix_set(jacobian,0,dof_id,jacobian_entry.x);
gsl_matrix_set(jacobian,1,dof_id,jacobian_entry.y);
gsl_matrix_set(jacobian,2,dof_id,jacobian_entry.z);
vertex = vertex->m_parent;
}
//Todo: This should be optimizable using the sorted vertices and the Abé implementation of the MSD gradient
}
| 45.094017
| 115
| 0.682714
|
XiyuChenFAU
|
1cd27e671a0ca1a0581041df32c1c948f55e5809
| 4,119
|
cpp
|
C++
|
src/tanktextures.cpp
|
Eae02/tank-game
|
0c526b177ccc15dd49e3228489163f13335040db
|
[
"Zlib"
] | null | null | null |
src/tanktextures.cpp
|
Eae02/tank-game
|
0c526b177ccc15dd49e3228489163f13335040db
|
[
"Zlib"
] | null | null | null |
src/tanktextures.cpp
|
Eae02/tank-game
|
0c526b177ccc15dd49e3228489163f13335040db
|
[
"Zlib"
] | null | null | null |
#include "tanktextures.h"
#include "exceptions/invalidstateexception.h"
#include "utils/utils.h"
#include "utils/ioutils.h"
#include "graphics/textureloadoperation.h"
namespace TankGame
{
static std::unique_ptr<TankTextures> instance;
class TankTexturesLoadOperation : public IASyncOperation
{
public:
TankTexturesLoadOperation()
: m_baseDiffuseLoadOps{ TextureLoadOperation(GetResDirectory() / "tank" / "base0.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base1.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base2.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base3.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base4.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base5.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base6.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base7.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base8.png", nullptr) },
m_baseNormalsLoadOp(GetResDirectory() / "tank" / "base-normals.png", nullptr) { }
virtual void DoWork() override
{
for (TextureLoadOperation& loadOperation : m_baseDiffuseLoadOps)
loadOperation.DoWork();
m_baseNormalsLoadOp.DoWork();
}
virtual void ProcessResult() override
{
instance = std::make_unique<TankTextures>(m_baseDiffuseLoadOps[0].CreateTexture(),
m_baseDiffuseLoadOps[1].CreateTexture(), m_baseDiffuseLoadOps[2].CreateTexture(),
m_baseDiffuseLoadOps[3].CreateTexture(), m_baseDiffuseLoadOps[4].CreateTexture(),
m_baseDiffuseLoadOps[5].CreateTexture(), m_baseDiffuseLoadOps[6].CreateTexture(),
m_baseDiffuseLoadOps[7].CreateTexture(), m_baseDiffuseLoadOps[8].CreateTexture(),
m_baseNormalsLoadOp.CreateTexture());
}
private:
TextureLoadOperation m_baseDiffuseLoadOps[9];
TextureLoadOperation m_baseNormalsLoadOp;
};
TankTextures::TankTextures(Texture2D&& baseDiffuse0, Texture2D&& baseDiffuse1, Texture2D&& baseDiffuse2,
Texture2D&& baseDiffuse3, Texture2D&& baseDiffuse4, Texture2D&& baseDiffuse5,
Texture2D&& baseDiffuse6, Texture2D&& baseDiffuse7, Texture2D&& baseDiffuse8,
Texture2D&& baseNormals)
: m_baseDiffuse{ std::move(baseDiffuse0), std::move(baseDiffuse1), std::move(baseDiffuse2),
std::move(baseDiffuse3), std::move(baseDiffuse4), std::move(baseDiffuse5),
std::move(baseDiffuse6), std::move(baseDiffuse7), std::move(baseDiffuse8) },
m_baseNormals(std::move(baseNormals)),
m_baseMaterials{ SpriteMaterial(m_baseDiffuse[0], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[1], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[2], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[3], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[4], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[5], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[6], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[7], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[8], m_baseNormals, 1, 30)
}
{
for (Texture2D& texture : m_baseDiffuse)
texture.SetWrapMode(GL_CLAMP_TO_EDGE);
m_baseNormals.SetWrapMode(GL_CLAMP_TO_EDGE);
}
std::unique_ptr<IASyncOperation> TankTextures::CreateInstance()
{
if (instance != nullptr)
throw InvalidStateException("Tank textures already loaded.");
CallOnClose([] { instance = nullptr; });
return std::make_unique<TankTexturesLoadOperation>();
}
const TankTextures& TankTextures::GetInstance()
{ return *instance; }
}
| 49.035714
| 105
| 0.646759
|
Eae02
|
1cd2b5bee1b0b729cf337ab461287ad15a9185f9
| 46,483
|
cpp
|
C++
|
external/vsomeip/implementation/endpoints/src/tcp_server_endpoint_impl.cpp
|
lixiaolia/ndk-someip-lib
|
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
|
[
"Apache-2.0"
] | 3
|
2021-06-17T14:01:04.000Z
|
2022-03-18T09:22:44.000Z
|
external/vsomeip/implementation/endpoints/src/tcp_server_endpoint_impl.cpp
|
lixiaolia/ndk-someip-lib
|
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
|
[
"Apache-2.0"
] | 1
|
2022-03-15T06:21:33.000Z
|
2022-03-28T06:31:12.000Z
|
external/vsomeip/implementation/endpoints/src/tcp_server_endpoint_impl.cpp
|
lixiaolia/ndk-someip-lib
|
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
|
[
"Apache-2.0"
] | 4
|
2021-06-17T14:12:18.000Z
|
2021-12-13T11:53:10.000Z
|
// Copyright (C) 2014-2017 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <iomanip>
#include <boost/asio/write.hpp>
#include <vsomeip/constants.hpp>
#include <vsomeip/internal/logger.hpp>
#include "../include/endpoint_definition.hpp"
#include "../include/endpoint_host.hpp"
#include "../../routing/include/routing_host.hpp"
#include "../include/tcp_server_endpoint_impl.hpp"
#include "../../utility/include/utility.hpp"
#include "../../utility/include/byteorder.hpp"
namespace ip = boost::asio::ip;
namespace vsomeip_v3 {
tcp_server_endpoint_impl::tcp_server_endpoint_impl(
const std::shared_ptr<endpoint_host>& _endpoint_host,
const std::shared_ptr<routing_host>& _routing_host,
const endpoint_type& _local,
boost::asio::io_service &_io,
const std::shared_ptr<configuration>& _configuration)
: tcp_server_endpoint_base_impl(_endpoint_host, _routing_host, _local, _io,
_configuration->get_max_message_size_reliable(_local.address().to_string(), _local.port()),
_configuration->get_endpoint_queue_limit(_local.address().to_string(), _local.port()),
_configuration),
acceptor_(_io),
buffer_shrink_threshold_(configuration_->get_buffer_shrink_threshold()),
local_port_(_local.port()),
// send timeout after 2/3 of configured ttl, warning after 1/3
send_timeout_(configuration_->get_sd_ttl() * 666) {
is_supporting_magic_cookies_ = true;
boost::system::error_code ec;
acceptor_.open(_local.protocol(), ec);
boost::asio::detail::throw_error(ec, "acceptor open");
acceptor_.set_option(boost::asio::socket_base::reuse_address(true), ec);
boost::asio::detail::throw_error(ec, "acceptor set_option");
#ifndef _WIN32
// If specified, bind to device
std::string its_device(configuration_->get_device());
if (its_device != "") {
if (setsockopt(acceptor_.native_handle(),
SOL_SOCKET, SO_BINDTODEVICE, its_device.c_str(), (int)its_device.size()) == -1) {
VSOMEIP_WARNING << "TCP Server: Could not bind to device \"" << its_device << "\"";
}
}
#endif
acceptor_.bind(_local, ec);
boost::asio::detail::throw_error(ec, "acceptor bind");
acceptor_.listen(boost::asio::socket_base::max_connections, ec);
boost::asio::detail::throw_error(ec, "acceptor listen");
}
tcp_server_endpoint_impl::~tcp_server_endpoint_impl() {
}
bool tcp_server_endpoint_impl::is_local() const {
return false;
}
void tcp_server_endpoint_impl::start() {
std::lock_guard<std::mutex> its_lock(acceptor_mutex_);
if (acceptor_.is_open()) {
connection::ptr new_connection = connection::create(
std::dynamic_pointer_cast<tcp_server_endpoint_impl>(
shared_from_this()), max_message_size_,
buffer_shrink_threshold_, has_enabled_magic_cookies_,
service_, send_timeout_);
{
std::unique_lock<std::mutex> its_socket_lock(new_connection->get_socket_lock());
acceptor_.async_accept(new_connection->get_socket(),
std::bind(&tcp_server_endpoint_impl::accept_cbk,
std::dynamic_pointer_cast<tcp_server_endpoint_impl>(
shared_from_this()), new_connection,
std::placeholders::_1));
}
}
}
void tcp_server_endpoint_impl::stop() {
server_endpoint_impl::stop();
{
std::lock_guard<std::mutex> its_lock(acceptor_mutex_);
if(acceptor_.is_open()) {
boost::system::error_code its_error;
acceptor_.close(its_error);
}
}
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
for (const auto &c : connections_) {
c.second->stop();
}
connections_.clear();
}
}
bool tcp_server_endpoint_impl::send_to(
const std::shared_ptr<endpoint_definition> _target,
const byte_t *_data, uint32_t _size) {
std::lock_guard<std::mutex> its_lock(mutex_);
endpoint_type its_target(_target->get_address(), _target->get_port());
return send_intern(its_target, _data, _size);
}
bool tcp_server_endpoint_impl::send_error(
const std::shared_ptr<endpoint_definition> _target,
const byte_t *_data, uint32_t _size) {
bool ret(false);
std::lock_guard<std::mutex> its_lock(mutex_);
const endpoint_type its_target(_target->get_address(), _target->get_port());
const queue_iterator_type target_queue_iterator(find_or_create_queue_unlocked(its_target));
auto& its_qpair = target_queue_iterator->second;
const bool queue_size_zero_on_entry(its_qpair.second.empty());
if (check_message_size(nullptr, _size, its_target) == endpoint_impl::cms_ret_e::MSG_OK &&
check_queue_limit(_data, _size, its_qpair.first)) {
its_qpair.second.emplace_back(
std::make_shared<message_buffer_t>(_data, _data + _size));
its_qpair.first += _size;
if (queue_size_zero_on_entry) { // no writing in progress
send_queued(target_queue_iterator);
}
ret = true;
}
return ret;
}
void tcp_server_endpoint_impl::send_queued(const queue_iterator_type _queue_iterator) {
connection::ptr its_connection;
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
auto connection_iterator = connections_.find(_queue_iterator->first);
if (connection_iterator != connections_.end()) {
its_connection = connection_iterator->second;
} else {
VSOMEIP_INFO << "Didn't find connection: "
<< _queue_iterator->first.address().to_string() << ":" << std::dec
<< static_cast<std::uint16_t>(_queue_iterator->first.port())
<< " dropping outstanding messages (" << std::dec
<< _queue_iterator->second.second.size() << ").";
queues_.erase(_queue_iterator->first);
}
}
if (its_connection) {
its_connection->send_queued(_queue_iterator);
}
}
void tcp_server_endpoint_impl::get_configured_times_from_endpoint(
service_t _service, method_t _method,
std::chrono::nanoseconds *_debouncing,
std::chrono::nanoseconds *_maximum_retention) const {
configuration_->get_configured_timing_responses(_service,
tcp_server_endpoint_base_impl::local_.address().to_string(),
tcp_server_endpoint_base_impl::local_.port(), _method,
_debouncing, _maximum_retention);
}
bool tcp_server_endpoint_impl::is_established(const std::shared_ptr<endpoint_definition>& _endpoint) {
bool is_connected = false;
endpoint_type endpoint(_endpoint->get_address(), _endpoint->get_port());
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
auto connection_iterator = connections_.find(endpoint);
if (connection_iterator != connections_.end()) {
is_connected = true;
} else {
VSOMEIP_INFO << "Didn't find TCP connection: Subscription "
<< "rejected for: " << endpoint.address().to_string() << ":"
<< std::dec << static_cast<std::uint16_t>(endpoint.port());
}
}
return is_connected;
}
bool tcp_server_endpoint_impl::get_default_target(service_t,
tcp_server_endpoint_impl::endpoint_type &) const {
return false;
}
void tcp_server_endpoint_impl::remove_connection(
tcp_server_endpoint_impl::connection *_connection) {
std::lock_guard<std::mutex> its_lock(connections_mutex_);
for (auto it = connections_.begin(); it != connections_.end();) {
if (it->second.get() == _connection) {
it = connections_.erase(it);
break;
} else {
++it;
}
}
}
void tcp_server_endpoint_impl::accept_cbk(const connection::ptr& _connection,
boost::system::error_code const &_error) {
if (!_error) {
boost::system::error_code its_error;
endpoint_type remote;
{
std::unique_lock<std::mutex> its_socket_lock(_connection->get_socket_lock());
socket_type &new_connection_socket = _connection->get_socket();
remote = new_connection_socket.remote_endpoint(its_error);
_connection->set_remote_info(remote);
// Nagle algorithm off
new_connection_socket.set_option(ip::tcp::no_delay(true), its_error);
new_connection_socket.set_option(boost::asio::socket_base::keep_alive(true), its_error);
if (its_error) {
VSOMEIP_WARNING << "tcp_server_endpoint::connect: couldn't enable "
<< "keep_alive: " << its_error.message();
}
}
if (!its_error) {
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
connections_[remote] = _connection;
}
_connection->start();
}
}
if (_error != boost::asio::error::bad_descriptor
&& _error != boost::asio::error::operation_aborted
&& _error != boost::asio::error::no_descriptors) {
start();
} else if (_error == boost::asio::error::no_descriptors) {
VSOMEIP_ERROR<< "tcp_server_endpoint_impl::accept_cbk: "
<< _error.message() << " (" << std::dec << _error.value()
<< ") Will try to accept again in 1000ms";
std::shared_ptr<boost::asio::steady_timer> its_timer =
std::make_shared<boost::asio::steady_timer>(service_,
std::chrono::milliseconds(1000));
auto its_ep = std::dynamic_pointer_cast<tcp_server_endpoint_impl>(
shared_from_this());
its_timer->async_wait([its_timer, its_ep]
(const boost::system::error_code& _error) {
if (!_error) {
its_ep->start();
}
});
}
}
std::uint16_t tcp_server_endpoint_impl::get_local_port() const {
return local_port_;
}
bool tcp_server_endpoint_impl::is_reliable() const {
return true;
}
///////////////////////////////////////////////////////////////////////////////
// class tcp_service_impl::connection
///////////////////////////////////////////////////////////////////////////////
tcp_server_endpoint_impl::connection::connection(
const std::weak_ptr<tcp_server_endpoint_impl>& _server,
std::uint32_t _max_message_size,
std::uint32_t _recv_buffer_size_initial,
std::uint32_t _buffer_shrink_threshold,
bool _magic_cookies_enabled,
boost::asio::io_service &_io_service,
std::chrono::milliseconds _send_timeout) :
socket_(_io_service),
server_(_server),
max_message_size_(_max_message_size),
recv_buffer_size_initial_(_recv_buffer_size_initial),
recv_buffer_(_recv_buffer_size_initial, 0),
recv_buffer_size_(0),
missing_capacity_(0),
shrink_count_(0),
buffer_shrink_threshold_(_buffer_shrink_threshold),
remote_port_(0),
magic_cookies_enabled_(_magic_cookies_enabled),
last_cookie_sent_(std::chrono::steady_clock::now() - std::chrono::seconds(11)),
send_timeout_(_send_timeout),
send_timeout_warning_(_send_timeout / 2) {
}
tcp_server_endpoint_impl::connection::ptr
tcp_server_endpoint_impl::connection::create(
const std::weak_ptr<tcp_server_endpoint_impl>& _server,
std::uint32_t _max_message_size,
std::uint32_t _buffer_shrink_threshold,
bool _magic_cookies_enabled,
boost::asio::io_service & _io_service,
std::chrono::milliseconds _send_timeout) {
const std::uint32_t its_initial_receveive_buffer_size =
VSOMEIP_SOMEIP_HEADER_SIZE + 8 + MAGIC_COOKIE_SIZE + 8;
return ptr(new connection(_server, _max_message_size,
its_initial_receveive_buffer_size,
_buffer_shrink_threshold, _magic_cookies_enabled,
_io_service, _send_timeout));
}
tcp_server_endpoint_impl::socket_type &
tcp_server_endpoint_impl::connection::get_socket() {
return socket_;
}
std::unique_lock<std::mutex>
tcp_server_endpoint_impl::connection::get_socket_lock() {
return std::unique_lock<std::mutex>(socket_mutex_);
}
void tcp_server_endpoint_impl::connection::start() {
receive();
}
void tcp_server_endpoint_impl::connection::receive() {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
if(socket_.is_open()) {
const std::size_t its_capacity(recv_buffer_.capacity());
size_t buffer_size = its_capacity - recv_buffer_size_;
try {
if (missing_capacity_) {
if (missing_capacity_ > MESSAGE_SIZE_UNLIMITED) {
VSOMEIP_ERROR << "Missing receive buffer capacity exceeds allowed maximum!";
return;
}
const std::size_t its_required_capacity(recv_buffer_size_ + missing_capacity_);
if (its_capacity < its_required_capacity) {
recv_buffer_.reserve(its_required_capacity);
recv_buffer_.resize(its_required_capacity, 0x0);
if (recv_buffer_.size() > 1048576) {
VSOMEIP_INFO << "tse: recv_buffer size is: " <<
recv_buffer_.size()
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
}
}
buffer_size = missing_capacity_;
missing_capacity_ = 0;
} else if (buffer_shrink_threshold_
&& shrink_count_ > buffer_shrink_threshold_
&& recv_buffer_size_ == 0) {
recv_buffer_.resize(recv_buffer_size_initial_, 0x0);
recv_buffer_.shrink_to_fit();
buffer_size = recv_buffer_size_initial_;
shrink_count_ = 0;
}
} catch (const std::exception &e) {
handle_recv_buffer_exception(e);
// don't start receiving again
return;
}
socket_.async_receive(boost::asio::buffer(&recv_buffer_[recv_buffer_size_], buffer_size),
std::bind(&tcp_server_endpoint_impl::connection::receive_cbk,
shared_from_this(), std::placeholders::_1,
std::placeholders::_2));
}
}
void tcp_server_endpoint_impl::connection::stop() {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
if (socket_.is_open()) {
boost::system::error_code its_error;
socket_.shutdown(socket_.shutdown_both, its_error);
socket_.close(its_error);
}
}
void tcp_server_endpoint_impl::connection::send_queued(
const queue_iterator_type _queue_iterator) {
std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock());
if (!its_server) {
VSOMEIP_TRACE << "tcp_server_endpoint_impl::connection::send_queued "
" couldn't lock server_";
return;
}
message_buffer_ptr_t its_buffer = _queue_iterator->second.second.front();
const service_t its_service = VSOMEIP_BYTES_TO_WORD(
(*its_buffer)[VSOMEIP_SERVICE_POS_MIN],
(*its_buffer)[VSOMEIP_SERVICE_POS_MAX]);
const method_t its_method = VSOMEIP_BYTES_TO_WORD(
(*its_buffer)[VSOMEIP_METHOD_POS_MIN],
(*its_buffer)[VSOMEIP_METHOD_POS_MAX]);
const client_t its_client = VSOMEIP_BYTES_TO_WORD(
(*its_buffer)[VSOMEIP_CLIENT_POS_MIN],
(*its_buffer)[VSOMEIP_CLIENT_POS_MAX]);
const session_t its_session = VSOMEIP_BYTES_TO_WORD(
(*its_buffer)[VSOMEIP_SESSION_POS_MIN],
(*its_buffer)[VSOMEIP_SESSION_POS_MAX]);
if (magic_cookies_enabled_) {
const std::chrono::steady_clock::time_point now =
std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::milliseconds>(
now - last_cookie_sent_) > std::chrono::milliseconds(10000)) {
if (send_magic_cookie(its_buffer)) {
last_cookie_sent_ = now;
_queue_iterator->second.first += sizeof(SERVICE_COOKIE);
}
}
}
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
{
std::lock_guard<std::mutex> its_sent_lock(its_server->sent_mutex_);
its_server->is_sending_ = true;
}
boost::asio::async_write(socket_, boost::asio::buffer(*its_buffer),
std::bind(&tcp_server_endpoint_impl::connection::write_completion_condition,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2,
its_buffer->size(),
its_service, its_method, its_client, its_session,
std::chrono::steady_clock::now()),
std::bind(&tcp_server_endpoint_base_impl::send_cbk,
its_server,
_queue_iterator,
std::placeholders::_1,
std::placeholders::_2));
}
}
void tcp_server_endpoint_impl::connection::send_queued_sync(
const queue_iterator_type _queue_iterator) {
message_buffer_ptr_t its_buffer = _queue_iterator->second.second.front();
if (magic_cookies_enabled_) {
const std::chrono::steady_clock::time_point now =
std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::milliseconds>(
now - last_cookie_sent_) > std::chrono::milliseconds(10000)) {
if (send_magic_cookie(its_buffer)) {
last_cookie_sent_ = now;
_queue_iterator->second.first += sizeof(SERVICE_COOKIE);
}
}
}
try {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
boost::asio::write(socket_, boost::asio::buffer(*its_buffer));
} catch (const boost::system::system_error &e) {
if (e.code() != boost::asio::error::broken_pipe) {
VSOMEIP_ERROR << "tcp_server_endpoint_impl::connection::"
<< __func__ << " " << e.what();
}
}
}
bool tcp_server_endpoint_impl::connection::send_magic_cookie(
message_buffer_ptr_t &_buffer) {
if (max_message_size_ == MESSAGE_SIZE_UNLIMITED
|| max_message_size_ - _buffer->size() >=
VSOMEIP_SOMEIP_HEADER_SIZE + VSOMEIP_SOMEIP_MAGIC_COOKIE_SIZE) {
_buffer->insert(_buffer->begin(), SERVICE_COOKIE,
SERVICE_COOKIE + sizeof(SERVICE_COOKIE));
return true;
}
return false;
}
bool tcp_server_endpoint_impl::connection::is_magic_cookie(size_t _offset) const {
return (0 == std::memcmp(CLIENT_COOKIE, &recv_buffer_[_offset],
sizeof(CLIENT_COOKIE)));
}
void tcp_server_endpoint_impl::connection::receive_cbk(
boost::system::error_code const &_error,
std::size_t _bytes) {
if (_error == boost::asio::error::operation_aborted) {
// endpoint was stopped
return;
}
std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock());
if (!its_server) {
VSOMEIP_ERROR << "tcp_server_endpoint_impl::connection::receive_cbk "
" couldn't lock server_";
return;
}
#if 0
std::stringstream msg;
for (std::size_t i = 0; i < _bytes + recv_buffer_size_; ++i)
msg << std::hex << std::setw(2) << std::setfill('0')
<< (int) recv_buffer_[i] << " ";
VSOMEIP_INFO << msg.str();
#endif
std::shared_ptr<routing_host> its_host = its_server->routing_host_.lock();
if (its_host) {
if (!_error && 0 < _bytes) {
if (recv_buffer_size_ + _bytes < recv_buffer_size_) {
VSOMEIP_ERROR << "receive buffer overflow in tcp client endpoint ~> abort!";
return;
}
recv_buffer_size_ += _bytes;
size_t its_iteration_gap = 0;
bool has_full_message;
do {
uint64_t read_message_size
= utility::get_message_size(&recv_buffer_[its_iteration_gap],
recv_buffer_size_);
if (read_message_size > MESSAGE_SIZE_UNLIMITED) {
VSOMEIP_ERROR << "Message size exceeds allowed maximum!";
return;
}
uint32_t current_message_size = static_cast<uint32_t>(read_message_size);
has_full_message = (current_message_size > VSOMEIP_RETURN_CODE_POS
&& current_message_size <= recv_buffer_size_);
if (has_full_message) {
bool needs_forwarding(true);
if (is_magic_cookie(its_iteration_gap)) {
magic_cookies_enabled_ = true;
} else {
if (magic_cookies_enabled_) {
uint32_t its_offset
= its_server->find_magic_cookie(&recv_buffer_[its_iteration_gap],
recv_buffer_size_);
if (its_offset < current_message_size) {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Detected Magic Cookie within message data. Resyncing."
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
}
if (!is_magic_cookie(its_iteration_gap)) {
auto its_endpoint_host = its_server->endpoint_host_.lock();
if (its_endpoint_host) {
its_endpoint_host->on_error(&recv_buffer_[its_iteration_gap],
static_cast<length_t>(recv_buffer_size_),its_server.get(),
remote_address_, remote_port_);
}
}
current_message_size = its_offset;
needs_forwarding = false;
}
}
}
if (needs_forwarding) {
if (utility::is_request(
recv_buffer_[its_iteration_gap
+ VSOMEIP_MESSAGE_TYPE_POS])) {
const client_t its_client = VSOMEIP_BYTES_TO_WORD(
recv_buffer_[its_iteration_gap + VSOMEIP_CLIENT_POS_MIN],
recv_buffer_[its_iteration_gap + VSOMEIP_CLIENT_POS_MAX]);
if (its_client != MAGIC_COOKIE_CLIENT) {
const session_t its_session = VSOMEIP_BYTES_TO_WORD(
recv_buffer_[its_iteration_gap + VSOMEIP_SESSION_POS_MIN],
recv_buffer_[its_iteration_gap + VSOMEIP_SESSION_POS_MAX]);
its_server->clients_mutex_.lock();
its_server->clients_[its_client][its_session] = remote_;
its_server->clients_mutex_.unlock();
}
}
if (!magic_cookies_enabled_) {
its_host->on_message(&recv_buffer_[its_iteration_gap],
current_message_size, its_server.get(),
boost::asio::ip::address(),
VSOMEIP_ROUTING_CLIENT,
std::make_pair(ANY_UID, ANY_GID),
remote_address_, remote_port_);
} else {
// Only call on_message without a magic cookie in front of the buffer!
if (!is_magic_cookie(its_iteration_gap)) {
its_host->on_message(&recv_buffer_[its_iteration_gap],
current_message_size, its_server.get(),
boost::asio::ip::address(),
VSOMEIP_ROUTING_CLIENT,
std::make_pair(ANY_UID, ANY_GID),
remote_address_, remote_port_);
}
}
}
calculate_shrink_count();
missing_capacity_ = 0;
recv_buffer_size_ -= current_message_size;
its_iteration_gap += current_message_size;
} else if (magic_cookies_enabled_ && recv_buffer_size_ > 0) {
uint32_t its_offset =
its_server->find_magic_cookie(&recv_buffer_[its_iteration_gap],
recv_buffer_size_);
if (its_offset < recv_buffer_size_) {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Detected Magic Cookie within message data. Resyncing."
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
}
if (!is_magic_cookie(its_iteration_gap)) {
auto its_endpoint_host = its_server->endpoint_host_.lock();
if (its_endpoint_host) {
its_endpoint_host->on_error(&recv_buffer_[its_iteration_gap],
static_cast<length_t>(recv_buffer_size_), its_server.get(),
remote_address_, remote_port_);
}
}
recv_buffer_size_ -= its_offset;
its_iteration_gap += its_offset;
has_full_message = true; // trigger next loop
if (!is_magic_cookie(its_iteration_gap)) {
auto its_endpoint_host = its_server->endpoint_host_.lock();
if (its_endpoint_host) {
its_endpoint_host->on_error(&recv_buffer_[its_iteration_gap],
static_cast<length_t>(recv_buffer_size_), its_server.get(),
remote_address_, remote_port_);
}
}
}
}
if (!has_full_message) {
if (recv_buffer_size_ > VSOMEIP_RETURN_CODE_POS &&
(recv_buffer_[its_iteration_gap + VSOMEIP_PROTOCOL_VERSION_POS] != VSOMEIP_PROTOCOL_VERSION ||
!utility::is_valid_message_type(static_cast<message_type_e>(recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS])) ||
!utility::is_valid_return_code(static_cast<return_code_e>(recv_buffer_[its_iteration_gap + VSOMEIP_RETURN_CODE_POS]))
)) {
if (recv_buffer_[its_iteration_gap + VSOMEIP_PROTOCOL_VERSION_POS] != VSOMEIP_PROTOCOL_VERSION) {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "tse: Wrong protocol version: 0x"
<< std::hex << std::setw(2) << std::setfill('0')
<< std::uint32_t(recv_buffer_[its_iteration_gap + VSOMEIP_PROTOCOL_VERSION_POS])
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< ". Closing connection due to missing/broken data TCP stream.";
}
// ensure to send back a error message w/ wrong protocol version
its_host->on_message(&recv_buffer_[its_iteration_gap],
VSOMEIP_SOMEIP_HEADER_SIZE + 8, its_server.get(),
boost::asio::ip::address(),
VSOMEIP_ROUTING_CLIENT,
std::make_pair(ANY_UID, ANY_GID),
remote_address_, remote_port_);
} else if (!utility::is_valid_message_type(static_cast<message_type_e>(
recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS]))) {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "tse: Invalid message type: 0x"
<< std::hex << std::setw(2) << std::setfill('0')
<< std::uint32_t(recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS])
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< ". Closing connection due to missing/broken data TCP stream.";
} else if (!utility::is_valid_return_code(static_cast<return_code_e>(
recv_buffer_[its_iteration_gap + VSOMEIP_RETURN_CODE_POS]))) {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "tse: Invalid return code: 0x"
<< std::hex << std::setw(2) << std::setfill('0')
<< std::uint32_t(recv_buffer_[its_iteration_gap + VSOMEIP_RETURN_CODE_POS])
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< ". Closing connection due to missing/broken data TCP stream.";
}
wait_until_sent(boost::asio::error::operation_aborted);
return;
} else if (max_message_size_ != MESSAGE_SIZE_UNLIMITED
&& current_message_size > max_message_size_) {
recv_buffer_size_ = 0;
recv_buffer_.resize(recv_buffer_size_initial_, 0x0);
recv_buffer_.shrink_to_fit();
if (magic_cookies_enabled_) {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Received a TCP message which exceeds "
<< "maximum message size ("
<< std::dec << current_message_size
<< " > " << std::dec << max_message_size_
<< "). Magic Cookies are enabled: "
<< "Resetting receiver. local: "
<< get_address_port_local() << " remote: "
<< get_address_port_remote();
} else {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Received a TCP message which exceeds "
<< "maximum message size ("
<< std::dec << current_message_size
<< " > " << std::dec << max_message_size_
<< ") Magic cookies are disabled: "
<< "Connection will be closed! local: "
<< get_address_port_local() << " remote: "
<< get_address_port_remote();
}
wait_until_sent(boost::asio::error::operation_aborted);
return;
}
} else if (current_message_size > recv_buffer_size_) {
missing_capacity_ = current_message_size
- static_cast<std::uint32_t>(recv_buffer_size_);
} else if (VSOMEIP_SOMEIP_HEADER_SIZE > recv_buffer_size_) {
missing_capacity_ = VSOMEIP_SOMEIP_HEADER_SIZE
- static_cast<std::uint32_t>(recv_buffer_size_);
} else if (magic_cookies_enabled_ && recv_buffer_size_ > 0) {
// no need to check for magic cookie here again: has_full_message
// would have been set to true if there was one present in the data
recv_buffer_size_ = 0;
recv_buffer_.resize(recv_buffer_size_initial_, 0x0);
recv_buffer_.shrink_to_fit();
missing_capacity_ = 0;
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Didn't find magic cookie in broken"
<< " data, trying to resync."
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
} else {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "tse::c<" << this
<< ">rcb: recv_buffer_size is: " << std::dec
<< recv_buffer_size_ << " but couldn't read "
"out message_size. recv_buffer_capacity: "
<< recv_buffer_.capacity()
<< " its_iteration_gap: " << its_iteration_gap
<< "local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< ". Closing connection due to missing/broken data TCP stream.";
}
wait_until_sent(boost::asio::error::operation_aborted);
return;
}
}
} while (has_full_message && recv_buffer_size_);
if (its_iteration_gap) {
// Copy incomplete message to front for next receive_cbk iteration
for (size_t i = 0; i < recv_buffer_size_; ++i) {
recv_buffer_[i] = recv_buffer_[i + its_iteration_gap];
}
// Still more capacity needed after shifting everything to front?
if (missing_capacity_ &&
missing_capacity_ <= recv_buffer_.capacity() - recv_buffer_size_) {
missing_capacity_ = 0;
}
}
receive();
}
}
if (_error == boost::asio::error::eof
|| _error == boost::asio::error::connection_reset
|| _error == boost::asio::error::timed_out) {
if(_error == boost::asio::error::timed_out) {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_WARNING << "tcp_server_endpoint receive_cbk: " << _error.message()
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
}
wait_until_sent(boost::asio::error::operation_aborted);
}
}
void tcp_server_endpoint_impl::connection::calculate_shrink_count() {
if (buffer_shrink_threshold_) {
if (recv_buffer_.capacity() != recv_buffer_size_initial_) {
if (recv_buffer_size_ < (recv_buffer_.capacity() >> 1)) {
shrink_count_++;
} else {
shrink_count_ = 0;
}
}
}
}
void tcp_server_endpoint_impl::connection::set_remote_info(
const endpoint_type &_remote) {
remote_ = _remote;
remote_address_ = _remote.address();
remote_port_ = _remote.port();
}
const std::string tcp_server_endpoint_impl::connection::get_address_port_remote() const {
std::string its_address_port;
its_address_port.reserve(21);
boost::system::error_code ec;
its_address_port += remote_address_.to_string(ec);
its_address_port += ":";
its_address_port += std::to_string(remote_port_);
return its_address_port;
}
const std::string tcp_server_endpoint_impl::connection::get_address_port_local() const {
std::string its_address_port;
its_address_port.reserve(21);
boost::system::error_code ec;
if (socket_.is_open()) {
endpoint_type its_local_endpoint = socket_.local_endpoint(ec);
if (!ec) {
its_address_port += its_local_endpoint.address().to_string(ec);
its_address_port += ":";
its_address_port += std::to_string(its_local_endpoint.port());
}
}
return its_address_port;
}
void tcp_server_endpoint_impl::connection::handle_recv_buffer_exception(
const std::exception &_e) {
std::stringstream its_message;
its_message <<"tcp_server_endpoint_impl::connection catched exception"
<< _e.what() << " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< " shutting down connection. Start of buffer: ";
for (std::size_t i = 0; i < recv_buffer_size_ && i < 16; i++) {
its_message << std::setw(2) << std::setfill('0') << std::hex
<< (int) (recv_buffer_[i]) << " ";
}
its_message << " Last 16 Bytes captured: ";
for (int i = 15; recv_buffer_size_ > 15 && i >= 0; i--) {
its_message << std::setw(2) << std::setfill('0') << std::hex
<< (int) (recv_buffer_[static_cast<size_t>(i)]) << " ";
}
VSOMEIP_ERROR << its_message.str();
recv_buffer_.clear();
if (socket_.is_open()) {
boost::system::error_code its_error;
socket_.shutdown(socket_.shutdown_both, its_error);
socket_.close(its_error);
}
std::shared_ptr<tcp_server_endpoint_impl> its_server = server_.lock();
if (its_server) {
its_server->remove_connection(this);
}
}
std::size_t
tcp_server_endpoint_impl::connection::get_recv_buffer_capacity() const {
return recv_buffer_.capacity();
}
std::size_t
tcp_server_endpoint_impl::connection::write_completion_condition(
const boost::system::error_code& _error,
std::size_t _bytes_transferred, std::size_t _bytes_to_send,
service_t _service, method_t _method, client_t _client, session_t _session,
const std::chrono::steady_clock::time_point _start) {
if (_error) {
VSOMEIP_ERROR << "tse::write_completion_condition: "
<< _error.message() << "(" << std::dec << _error.value()
<< ") bytes transferred: " << std::dec << _bytes_transferred
<< " bytes to sent: " << std::dec << _bytes_to_send << " "
<< "remote:" << get_address_port_remote() << " ("
<< std::hex << std::setw(4) << std::setfill('0') << _client <<"): ["
<< std::hex << std::setw(4) << std::setfill('0') << _service << "."
<< std::hex << std::setw(4) << std::setfill('0') << _method << "."
<< std::hex << std::setw(4) << std::setfill('0') << _session << "]";
stop_and_remove_connection();
return 0;
}
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
const std::chrono::milliseconds passed = std::chrono::duration_cast<std::chrono::milliseconds>(now - _start);
if (passed > send_timeout_warning_) {
if (passed > send_timeout_) {
VSOMEIP_ERROR << "tse::write_completion_condition: "
<< _error.message() << "(" << std::dec << _error.value()
<< ") took longer than " << std::dec << send_timeout_.count()
<< "ms bytes transferred: " << std::dec << _bytes_transferred
<< " bytes to sent: " << std::dec << _bytes_to_send
<< " remote:" << get_address_port_remote() << " ("
<< std::hex << std::setw(4) << std::setfill('0') << _client <<"): ["
<< std::hex << std::setw(4) << std::setfill('0') << _service << "."
<< std::hex << std::setw(4) << std::setfill('0') << _method << "."
<< std::hex << std::setw(4) << std::setfill('0') << _session << "]";
} else {
VSOMEIP_WARNING << "tse::write_completion_condition: "
<< _error.message() << "(" << std::dec << _error.value()
<< ") took longer than " << std::dec << send_timeout_warning_.count()
<< "ms bytes transferred: " << std::dec << _bytes_transferred
<< " bytes to sent: " << std::dec << _bytes_to_send
<< " remote:" << get_address_port_remote() << " ("
<< std::hex << std::setw(4) << std::setfill('0') << _client <<"): ["
<< std::hex << std::setw(4) << std::setfill('0') << _service << "."
<< std::hex << std::setw(4) << std::setfill('0') << _method << "."
<< std::hex << std::setw(4) << std::setfill('0') << _session << "]";
}
}
return _bytes_to_send - _bytes_transferred;
}
void tcp_server_endpoint_impl::connection::stop_and_remove_connection() {
std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock());
if (!its_server) {
VSOMEIP_ERROR << "tse::connection::stop_and_remove_connection "
" couldn't lock server_";
return;
}
{
std::lock_guard<std::mutex> its_lock(its_server->connections_mutex_);
stop();
}
its_server->remove_connection(this);
}
// Dummies
void tcp_server_endpoint_impl::receive() {
// intentionally left empty
}
void tcp_server_endpoint_impl::print_status() {
std::lock_guard<std::mutex> its_lock(mutex_);
connections_t its_connections;
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
its_connections = connections_;
}
VSOMEIP_INFO << "status tse: " << std::dec << local_port_
<< " connections: " << std::dec << its_connections.size()
<< " queues: " << std::dec << queues_.size();
for (const auto &c : its_connections) {
std::size_t its_data_size(0);
std::size_t its_queue_size(0);
std::size_t its_recv_size(0);
{
std::unique_lock<std::mutex> c_s_lock(c.second->get_socket_lock());
its_recv_size = c.second->get_recv_buffer_capacity();
}
auto found_queue = queues_.find(c.first);
if (found_queue != queues_.end()) {
its_queue_size = found_queue->second.second.size();
its_data_size = found_queue->second.first;
}
VSOMEIP_INFO << "status tse: client: "
<< c.second->get_address_port_remote()
<< " queue: " << std::dec << its_queue_size
<< " data: " << std::dec << its_data_size
<< " recv_buffer: " << std::dec << its_recv_size;
}
}
std::string tcp_server_endpoint_impl::get_remote_information(
const queue_iterator_type _queue_iterator) const {
boost::system::error_code ec;
return _queue_iterator->first.address().to_string(ec) + ":"
+ std::to_string(_queue_iterator->first.port());
}
std::string tcp_server_endpoint_impl::get_remote_information(
const endpoint_type& _remote) const {
boost::system::error_code ec;
return _remote.address().to_string(ec) + ":"
+ std::to_string(_remote.port());
}
bool tcp_server_endpoint_impl::tp_segmentation_enabled(service_t _service,
method_t _method) const {
(void)_service;
(void)_method;
return false;
}
void tcp_server_endpoint_impl::connection::wait_until_sent(const boost::system::error_code &_error) {
std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock());
std::unique_lock<std::mutex> its_sent_lock(its_server->sent_mutex_);
if (!its_server->is_sending_ || !_error) {
its_sent_lock.unlock();
if (!_error)
VSOMEIP_WARNING << __func__
<< ": Maximum wait time for send operation exceeded for tse.";
{
std::lock_guard<std::mutex> its_lock(its_server->connections_mutex_);
stop();
}
its_server->remove_connection(this);
} else {
std::chrono::milliseconds its_timeout(VSOMEIP_MAX_TCP_SENT_WAIT_TIME);
boost::system::error_code ec;
its_server->sent_timer_.expires_from_now(its_timeout, ec);
its_server->sent_timer_.async_wait(std::bind(&tcp_server_endpoint_impl::connection::wait_until_sent,
std::dynamic_pointer_cast<tcp_server_endpoint_impl::connection>(shared_from_this()),
std::placeholders::_1));
}
}
} // namespace vsomeip_v3
| 47.383282
| 148
| 0.553557
|
lixiaolia
|
1cd624056df2e7aaa352ab483ad1d97874aba4d5
| 2,228
|
cpp
|
C++
|
src/code-examples/chapter-04/printing-people/main.cpp
|
nhatvu148/helpers
|
1a6875017cf39790dfe40ecec9dcee4410b1d89e
|
[
"MIT"
] | null | null | null |
src/code-examples/chapter-04/printing-people/main.cpp
|
nhatvu148/helpers
|
1a6875017cf39790dfe40ecec9dcee4410b1d89e
|
[
"MIT"
] | null | null | null |
src/code-examples/chapter-04/printing-people/main.cpp
|
nhatvu148/helpers
|
1a6875017cf39790dfe40ecec9dcee4410b1d89e
|
[
"MIT"
] | null | null | null |
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <fstream>
#include "../../common/person.h"
void print_person(const person_t &person,
std::ostream &out,
person_t::output_format_t format)
{
if (format == person_t::name_only) {
out << person.name() << '\n';
} else if (format == person_t::full_name) {
out << person.name() << ' '
<< person.surname() << '\n';
}
}
int main(int argc, char *argv[])
{
using namespace std::placeholders;
std::vector<person_t> people {
{ "David" , person_t::male },
{ "Jane" , person_t::female },
{ "Martha" , person_t::female },
{ "Peter" , person_t::male },
{ "Rose" , person_t::female },
{ "Tom" , person_t::male }
};
std::ofstream file("test");
// Passing a non-member function as the function object to std::bind
std::for_each(people.cbegin(), people.cend(),
std::bind(print_person,
_1,
std::ref(std::cout),
person_t::name_only
));
std::for_each(people.cbegin(), people.cend(),
std::bind(print_person,
_1,
std::ref(file),
person_t::full_name
));
// Passing a member function pointer to std::bind
std::for_each(people.cbegin(), people.cend(),
std::bind(&person_t::print,
_1,
std::ref(std::cout),
person_t::name_only
));
// Passing a lambda function instead of using std::bind
std::for_each(people.cbegin(), people.cend(),
[] (const person_t &person) {
print_person(person,
std::cout,
person_t::name_only);
});
std::for_each(people.cbegin(), people.cend(),
[&file] (const person_t &person) {
print_person(person,
file,
person_t::full_name);
});
return 0;
}
| 27.85
| 72
| 0.474865
|
nhatvu148
|
1cdb59d29336c26315412dcf45704dbc2251c68b
| 4,803
|
cc
|
C++
|
deps/smmr/example/client_server/client_server.cc
|
xflagstudio/network-bfd-sample
|
89a21dd7ff195527fd8c3ce811ed0520acaac6b5
|
[
"MIT"
] | 6
|
2017-03-24T08:37:39.000Z
|
2020-07-24T08:08:30.000Z
|
deps/smmr/example/client_server/client_server.cc
|
xflagstudio/network-bfd-sample
|
89a21dd7ff195527fd8c3ce811ed0520acaac6b5
|
[
"MIT"
] | null | null | null |
deps/smmr/example/client_server/client_server.cc
|
xflagstudio/network-bfd-sample
|
89a21dd7ff195527fd8c3ce811ed0520acaac6b5
|
[
"MIT"
] | 2
|
2017-07-17T03:25:34.000Z
|
2019-06-09T18:14:15.000Z
|
#include "smmr_pagedbuffer.h"
#include "smmr_categories.h"
#include "smmr_memory.h"
#include "smmr_database.h"
#include "smmr_tree.h"
#include <sys/types.h>
#include <sys/wait.h>
#define UNUSED(x) (void)(x)
const char *SERVER_MSGKEY = "from_server_to_client";
char SERVER_HELLOW[] = "hellow client.";
const char *CLIENT_MSGKEY = "from_client_to_server";
char CLIENT_HELLOW[] = "hi server.";
#define CLIENT_TO (10)
// -----------------------
// クライアント
// -----------------------
static void do_client(void){
//
ipcshm_categories_ptr CATEGORIES_C = (ipcshm_categories_ptr)-1;
ipcshm_datafiles_ptr DATAFILES_C = (ipcshm_datafiles_ptr)-1;
datafiles_on_process_t DATAFILES_INDEX_C;
categories_on_process_t CATEGORIES_INDEX_C;
tree_instance_ptr ROOT_C;
printf("client\n");
//
if (childinit_categories_area(&CATEGORIES_C,&CATEGORIES_INDEX_C) != RET_OK){ exit(1); }
if (childinit_db_area(&DATAFILES_C,&DATAFILES_INDEX_C) != RET_OK){ exit(3); }
// インデックス ルートオブジェクト構築
ROOT_C = create_tree_unsafe(CATEGORIES_C,&CATEGORIES_INDEX_C);
if (!ROOT_C){ exit(2); }
// サーバメッセージを読み取る
char *resp = NULL;
uint32_t resplen = 0;
//
if (search(DATAFILES_C,&DATAFILES_INDEX_C,ROOT_C,SERVER_MSGKEY,strlen(SERVER_MSGKEY),&resp,&resplen) == RET_OK){
if (resp && resplen){
printf("from server .. %s == %s\n", SERVER_HELLOW, resp);
}else{
fprintf(stderr, "failed.search.:resp(%s)\n", SERVER_MSGKEY);
}
}else{
fprintf(stderr, "failed.search.(%s)\n", SERVER_MSGKEY);
}
// ack to server
if (store(DATAFILES_C,&DATAFILES_INDEX_C,ROOT_C,CLIENT_MSGKEY,strlen(CLIENT_MSGKEY),CLIENT_HELLOW,strlen(CLIENT_HELLOW),0)!= RET_OK){
fprintf(stderr, "failed.store.(%s)\n", CLIENT_MSGKEY);
}
// 子プロセスでリソース解放
if (childuninit_db_area(&DATAFILES_C,&DATAFILES_INDEX_C) != RET_OK){ exit(4); }
if (ROOT_C != NULL){
free(ROOT_C);
}
ROOT_C = NULL;
if (childuninit_categories_area(&CATEGORIES_C,&CATEGORIES_INDEX_C) != RET_OK){ exit(5); }
printf("client-completed.\n");
}
// -----------------------
// サーバ
// -----------------------
static void do_server(pid_t pid){
printf("server\n");
//
ipcshm_categories_ptr CATEGORIES = (ipcshm_categories_ptr)-1;
ipcshm_datafiles_ptr DATAFILES = (ipcshm_datafiles_ptr)-1;
datafiles_on_process_t DATAFILES_INDEX;
categories_on_process_t CATEGORIES_INDEX;
tree_instance_ptr ROOT;
int cstat = 0;
int timeout = 0;
char index_dir[128] = {0},data_dir[128] = {0};
snprintf(index_dir,sizeof(index_dir)-1,"/tmp/%u/", (unsigned)getpid());
mkdir(index_dir,0755);
snprintf(data_dir,sizeof(data_dir)-1,"/tmp/%u/db/", (unsigned)getpid());
mkdir(data_dir,0755);
// システム初期化
// サーバプロセスでインデクス初期化
if (create_categories_area(index_dir,&CATEGORIES,&CATEGORIES_INDEX) != RET_OK){ exit(1); }
if (init_categories_from_file(CATEGORIES,&CATEGORIES_INDEX,0) != RET_OK){ exit(1); }
if (rebuild_pages_area(&CATEGORIES_INDEX) != RET_OK){ exit(1); }
// サーバプロセスでデータファイル初期化
if (create_db_area_parent(data_dir,&DATAFILES) != RET_OK){ exit(1); }
if (init_datafiles_from_file(DATAFILES,&DATAFILES_INDEX) != RET_OK){ exit(1); }
// ツリールート
if ((ROOT = create_tree_unsafe(CATEGORIES,&CATEGORIES_INDEX)) ==NULL){ exit(1); }
// サーバでデータを書き込み
if (store(DATAFILES,&DATAFILES_INDEX,ROOT,SERVER_MSGKEY,strlen(SERVER_MSGKEY),SERVER_HELLOW,strlen(SERVER_HELLOW),0)!= RET_OK){ exit(1); }
// クライアントのデータ書き込みを待機
for(timeout=0;timeout < CLIENT_TO;timeout++){
char *resp = NULL;
uint32_t resplen = 0;
sleep(1);
if (search(DATAFILES,&DATAFILES_INDEX,ROOT,CLIENT_MSGKEY,strlen(CLIENT_MSGKEY),&resp,&resplen) == RET_OK){
if (resp && resplen){
printf("%s -> %s\n",CLIENT_MSGKEY, resp);
free(resp);
}
break;
}
fprintf(stderr, "nothing client. responce...(%d)\n", timeout);
}
if (timeout >= CLIENT_TO){
fprintf(stderr, "timeout client. responce...\n");
}
// parent
pid_t pidr = waitpid(pid, &cstat, 0);
printf("waitpid(for client complete) /%d -> %d : %d\n",pid ,pidr, cstat);
// システム終了処理
if (remove_db_area_parent(&DATAFILES,&DATAFILES_INDEX) != RET_OK){ exit(1); }
if (remove_categories_area(&CATEGORIES,&CATEGORIES_INDEX) != RET_OK){ exit(1); }
remove_safe(index_dir);
remove_safe(data_dir);
}
int main(int argc, char** argv) {
pid_t pid = fork();
//
if (pid < 0){ exit(1);
}else if (pid == 0){
// wait for prepared shared area from parent.
sleep(3);
do_client();
exit(0);
}else{
do_server(pid);
}
return(0);
}
| 34.804348
| 142
| 0.634812
|
xflagstudio
|
1cdd107e2bbce48e8df7103aa1c0817e30708734
| 985
|
cpp
|
C++
|
09_QueueWithTwoStacks/main09.cpp
|
HaoliangLi/CodingInterviewChinese2
|
c3ae0d7bec404d92dc3f5f395ccefb5455d08eb3
|
[
"BSD-3-Clause"
] | null | null | null |
09_QueueWithTwoStacks/main09.cpp
|
HaoliangLi/CodingInterviewChinese2
|
c3ae0d7bec404d92dc3f5f395ccefb5455d08eb3
|
[
"BSD-3-Clause"
] | null | null | null |
09_QueueWithTwoStacks/main09.cpp
|
HaoliangLi/CodingInterviewChinese2
|
c3ae0d7bec404d92dc3f5f395ccefb5455d08eb3
|
[
"BSD-3-Clause"
] | null | null | null |
/***
* @Date: 2021-11-27 17:36:41
* @LastEditors: zjulhl
* @LastEditTime: 2021-11-28 13:25:47
* @Description:
* @FilePath: /CodingInterviewChinese2/09_QueueWithTwoStacks/main09.cpp
*/
#include <stack>
using namespace std;
class CQueue
{
stack<int> stack1, stack2;
public:
CQueue()
{
while (!stack1.empty())
{
stack1.pop();
}
while (!stack2.empty())
{
stack2.pop();
}
}
void appendTail(int value)
{
stack1.push(value);
}
int deleteHead()
{
// 如果第二个栈为空
if (stack2.empty())
{
while (!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
if (stack2.empty())
{
return -1;
}
else
{
int deleteItem = stack2.top();
stack2.pop();
return deleteItem;
}
}
};
| 17.589286
| 71
| 0.447716
|
HaoliangLi
|
1cde2492418251c053d007af77a2e1f334cd06e9
| 228
|
hpp
|
C++
|
include/FindTheDifference.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 43
|
2015-10-10T12:59:52.000Z
|
2018-07-11T18:07:00.000Z
|
include/FindTheDifference.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | null | null | null |
include/FindTheDifference.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 11
|
2015-10-10T14:41:11.000Z
|
2018-07-28T06:03:16.000Z
|
#ifndef FIND_THE_DIFFERENCE_HPP_
#define FIND_THE_DIFFERENCE_HPP_
#include <string>
using namespace std;
class FindTheDifference {
public:
char findTheDifference(string s, string t);
};
#endif // FIND_THE_DIFFERENCE_HPP_
| 17.538462
| 47
| 0.798246
|
yanzhe-chen
|
1ce098a977b00d0e57343ab54ff9a2978c182aec
| 1,218
|
cpp
|
C++
|
Solutions/Longest Valid Parentheses/main.cpp
|
Crayzero/LeetCodeProgramming
|
b10ebe22c0de1501722f0f5c934c0c1902a26789
|
[
"MIT"
] | 1
|
2015-04-13T10:58:30.000Z
|
2015-04-13T10:58:30.000Z
|
Solutions/Longest Valid Parentheses/main.cpp
|
Crayzero/LeetCodeProgramming
|
b10ebe22c0de1501722f0f5c934c0c1902a26789
|
[
"MIT"
] | null | null | null |
Solutions/Longest Valid Parentheses/main.cpp
|
Crayzero/LeetCodeProgramming
|
b10ebe22c0de1501722f0f5c934c0c1902a26789
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s) {
int s_size = s.size();
if (s_size <= 1) {
return 0;
}
int *dp = new int [s_size];
for(int i = 0; i < s_size; i++) {
dp[i] = 0;
}
int res = 0;
for(int i = 1; i < s_size; i++) {
if (s[i] == ')' && s[i-1] == '(') {
dp[i] = (i>=2 ? dp[i-2] : 0) + 2;
}
else if (dp[i-1] != 0 && s[i] == ')') {
if (i-dp[i-1] > 0 && s[i-dp[i-1]-1] == '(') {
dp[i] = dp[i-1] + 2;
if (i-dp[i] > 0 && dp[i-dp[i]] != 0) {
dp[i] = dp[i] + dp[i-dp[i]];
}
}
}
else {
dp[i] = 0;
}
res = max(res, dp[i]);
for(int i = 0; i < s_size; i++) {
cout<<dp[i]<<" ";
}
cout<<endl;
}
return res;
}
};
int main()
{
string s1 = "()(())";
string s2 = "(()())";
Solution s;
cout<<s.longestValidParentheses(s1);
return 0;
}
| 23.882353
| 61
| 0.325123
|
Crayzero
|
1ce1eaa1c65f735565091b2e87477fb75e979f02
| 2,271
|
hpp
|
C++
|
include/Core/Castor3D/Render/ShadowMap/ShadowMapPassPoint.hpp
|
Mu-L/Castor3D
|
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
|
[
"MIT"
] | 245
|
2015-10-29T14:31:45.000Z
|
2022-03-31T13:04:45.000Z
|
include/Core/Castor3D/Render/ShadowMap/ShadowMapPassPoint.hpp
|
Mu-L/Castor3D
|
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
|
[
"MIT"
] | 64
|
2016-03-11T19:45:05.000Z
|
2022-03-31T23:58:33.000Z
|
include/Core/Castor3D/Render/ShadowMap/ShadowMapPassPoint.hpp
|
Mu-L/Castor3D
|
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
|
[
"MIT"
] | 11
|
2018-05-24T09:07:43.000Z
|
2022-03-21T21:05:20.000Z
|
/*
See LICENSE file in root folder
*/
#ifndef ___C3D_SHADOW_MAP_PASS_POINT_H___
#define ___C3D_SHADOW_MAP_PASS_POINT_H___
#include "ShadowMapModule.hpp"
#include "Castor3D/Render/ShadowMap/ShadowMapPass.hpp"
#include "Castor3D/Render/Viewport.hpp"
#include <ashespp/Buffer/UniformBuffer.hpp>
namespace castor3d
{
class ShadowMapPassPoint
: public ShadowMapPass
{
public:
/**
*\~english
*\brief Constructor.
*\param[in] engine The engine.
*\param[in] index The pass index.
*\param[in] matrixUbo The scene matrices UBO.
*\param[in] culler The culler for this pass.
*\param[in] shadowMap The parent shadow map.
*\~french
*\brief Constructeur.
*\param[in] engine Le moteur.
*\param[in] index L'indice de la passe.
*\param[in] matrixUbo L'UBO de matrices de la scène.
*\param[in] culler Le culler pour cette passe.
*\param[in] shadowMap La shadow map parente.
*/
C3D_API ShadowMapPassPoint( crg::FramePass const & pass
, crg::GraphContext & context
, crg::RunnableGraph & graph
, RenderDevice const & device
, uint32_t index
, MatrixUbo & matrixUbo
, SceneCuller & culler
, ShadowMap const & shadowMap );
/**
*\~english
*\brief Destructor.
*\~french
*\brief Destructeur.
*/
C3D_API ~ShadowMapPassPoint()override;
/**
*\copydoc castor3d::ShadowMapPass::update
*/
bool update( CpuUpdater & updater )override;
/**
*\copydoc castor3d::ShadowMapPass::update
*/
void update( GpuUpdater & updater )override;
protected:
void doUpdateNodes( QueueCulledRenderNodes & nodes );
private:
void doUpdateUbos( CpuUpdater & updater )override;
ashes::PipelineDepthStencilStateCreateInfo doCreateDepthStencilState( PipelineFlags const & flags )const override;
ashes::PipelineColorBlendStateCreateInfo doCreateBlendState( PipelineFlags const & flags )const override;
void doUpdateFlags( PipelineFlags & flags )const override;
ShaderPtr doGetVertexShaderSource( PipelineFlags const & flags )const override;
ShaderPtr doGetPixelShaderSource( PipelineFlags const & flags )const override;
public:
C3D_API static uint32_t const TextureSize;
private:
OnSceneNodeChangedConnection m_onNodeChanged;
castor::Matrix4x4f m_projection;
};
}
#endif
| 28.037037
| 116
| 0.730956
|
Mu-L
|
1ce309004a88acddaa5b3abce61c11ee69147d9b
| 309
|
cpp
|
C++
|
2_formulas/is_leap.cpp
|
alphaolomi/cpp-examples
|
eda9c371ddf4264f2830425c036fd1570b9efda1
|
[
"Apache-2.0"
] | null | null | null |
2_formulas/is_leap.cpp
|
alphaolomi/cpp-examples
|
eda9c371ddf4264f2830425c036fd1570b9efda1
|
[
"Apache-2.0"
] | null | null | null |
2_formulas/is_leap.cpp
|
alphaolomi/cpp-examples
|
eda9c371ddf4264f2830425c036fd1570b9efda1
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int year;
cout << "Enter a year: " << endl;
cin >> year;
if ((year % 4) == 0)
{
cout << " Leap Year ";
}
else
{
cout << " Not a Leap Year" << endl;
}
return 0;
}
/*
Enter a year: 2016
Leap Year
*/
| 12.875
| 43
| 0.466019
|
alphaolomi
|
1ce568a02137152b50ce38760832e528aa88db29
| 3,318
|
cpp
|
C++
|
examples/rara.cpp
|
rodriguescr/libfastlib
|
b89172ae727cd36f84d0d02359ce635eb11b8472
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
examples/rara.cpp
|
rodriguescr/libfastlib
|
b89172ae727cd36f84d0d02359ce635eb11b8472
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
examples/rara.cpp
|
rodriguescr/libfastlib
|
b89172ae727cd36f84d0d02359ce635eb11b8472
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
// $Id$
// Author: John Wu <John.Wu at ACM.org> Lawrence Berkeley National Laboratory
// Copyright (c) 2008-2017 the Regents of the University of California
/** @file rara.cpp
This is meant to be the simplest test program for the querying
functions of ibis::query and ibis::part. It accepts the following
fixed list of arguments to simplify the program:
data-dir query-conditions [column-to-print [column-to-print ...]]
The data-dir must exist and contain valid data files and query
conditions much be specified as well. If no column-to-print, this
program effective is answering the following SQL query
SELECT count(*) FROM data-dir WHERE query-conditions
If any column-to-print is specified, all of them are concatenated
together and the SQL query answered is of the form
SELECT column-to-print, column-to-print, ... FROM data-dir WHERE query-conditions
About the name: Bostrychia rara, Spot-breasted Ibis, the smallest ibis
<http://www.sandiegozoo.org/animalbytes/t-ibis.html>. As an example
program for using FastBit IBIS, this might be also the smallest.
@ingroup FastBitExamples
*/
#include "ibis.h" // FastBit IBIS primary include file
// printout the usage string
static void usage(const char* name) {
std::cout << "usage:\n" << name << " data-dir query-conditions"
<< " [column-to-print [column-to-print ...]]\n"
<< std::endl;
} // usage
int main(int argc, char** argv) {
if (argc < 3) {
usage(*argv);
return -1;
}
// construct a data partition from the given data directory.
ibis::part apart(argv[1], static_cast<const char*>(0));
// create a query object with the current user name.
ibis::query aquery(ibis::util::userName(), &apart);
// assign the query conditions as the where clause.
int ierr = aquery.setWhereClause(argv[2]);
if (ierr < 0) {
std::clog << *argv << " setWhereClause(" << argv[2]
<< ") failed with error code " << ierr << std::endl;
return -2;
}
// collect all column-to-print together
std::string sel;
for (int j = 3; j < argc; ++ j) {
if (j > 3)
sel += ", ";
sel += argv[j];
}
if (sel.empty()) { // select count(*)...
ierr = aquery.evaluate(); // evaluate the query
std::cout << "SELECT count(*) FROM " << argv[1] << " WHERE "
<< argv[2] << "\n--> ";
if (ierr >= 0) {
std::cout << aquery.getNumHits();
}
else {
std::cout << "error " << ierr;
}
}
else { // select column-to-print...
ierr = aquery.setSelectClause(sel.c_str());
if (ierr < 0) {
std::clog << *argv << " setSelectClause(" << sel
<< ") failed with error code " << ierr << std::endl;
return -3;
}
ierr = aquery.evaluate(); // evaluate the query
std::cout << "SELECT " << sel << " FROM " << argv[1] << " WHERE "
<< argv[2] << "\n--> ";
if (ierr >= 0) { // print out the select values
aquery.printSelected(std::cout);
}
else {
std::cout << "error " << ierr;
}
}
std::cout << std::endl;
return ierr;
} // main
| 35.677419
| 85
| 0.570223
|
rodriguescr
|
1ce6121b396bcd37b7818d11901a5a873c67387c
| 193
|
hpp
|
C++
|
src/linux/linux_platform.hpp
|
NickCao/ebpf-verifier
|
ccbfd158ca2b4c24b91c235ce21a1fbd192d458e
|
[
"Apache-2.0",
"MIT"
] | 181
|
2019-03-12T22:39:25.000Z
|
2022-03-28T13:34:35.000Z
|
src/linux/linux_platform.hpp
|
NickCao/ebpf-verifier
|
ccbfd158ca2b4c24b91c235ce21a1fbd192d458e
|
[
"Apache-2.0",
"MIT"
] | 153
|
2019-02-21T18:44:11.000Z
|
2022-03-31T23:22:11.000Z
|
src/linux/linux_platform.hpp
|
NickCao/ebpf-verifier
|
ccbfd158ca2b4c24b91c235ce21a1fbd192d458e
|
[
"Apache-2.0",
"MIT"
] | 30
|
2019-04-19T18:33:55.000Z
|
2022-01-04T19:49:31.000Z
|
// Copyright (c) Prevail Verifier contributors.
// SPDX-License-Identifier: MIT
#pragma once
EbpfHelperPrototype get_helper_prototype_linux(int32_t n);
bool is_helper_usable_linux(int32_t n);
| 27.571429
| 58
| 0.818653
|
NickCao
|
1ce74f81493c64aa21f249d0f83e812d93f2f98d
| 306
|
cpp
|
C++
|
tutorials/learncpp.com#1.0#1/variables_part_ii/enumerated_types/source2.cpp
|
officialrafsan/CppDroid
|
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
|
[
"MIT"
] | null | null | null |
tutorials/learncpp.com#1.0#1/variables_part_ii/enumerated_types/source2.cpp
|
officialrafsan/CppDroid
|
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
|
[
"MIT"
] | null | null | null |
tutorials/learncpp.com#1.0#1/variables_part_ii/enumerated_types/source2.cpp
|
officialrafsan/CppDroid
|
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
|
[
"MIT"
] | null | null | null |
enum Color
{
COLOR_BLACK, // assigned 0
COLOR_RED, // assigned 1
COLOR_BLUE, // assigned 2
COLOR_GREEN, // assigned 3
COLOR_WHITE, // assigned 4
COLOR_CYAN, // assigned 5
COLOR_YELLOW, // assigned 6
COLOR_MAGENTA // assigned 7
};
Color eColor = COLOR_WHITE;
cout << eColor;
| 21.857143
| 31
| 0.653595
|
officialrafsan
|
1ce9df55b36a4a6a72489cde35526546cb787727
| 1,236
|
hpp
|
C++
|
src/shuffler.hpp
|
nikolaimerkel/edgepart
|
58b3d57eebd850dfdd7016e90352bddcf840e1f5
|
[
"MIT"
] | 21
|
2018-04-19T07:27:18.000Z
|
2022-02-23T19:33:04.000Z
|
src/shuffler.hpp
|
nikolaimerkel/edgepart
|
58b3d57eebd850dfdd7016e90352bddcf840e1f5
|
[
"MIT"
] | 1
|
2020-12-30T01:40:51.000Z
|
2021-02-20T03:36:17.000Z
|
src/shuffler.hpp
|
nikolaimerkel/edgepart
|
58b3d57eebd850dfdd7016e90352bddcf840e1f5
|
[
"MIT"
] | 9
|
2019-06-19T13:40:57.000Z
|
2021-12-09T19:30:50.000Z
|
#pragma once
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "util.hpp"
#include "conversions.hpp"
class Shuffler : public Converter
{
private:
struct work_t {
Shuffler *shuffler;
int nchunks;
std::vector<edge_t> chunk_buf;
void operator()() {
std::random_shuffle(chunk_buf.begin(), chunk_buf.end());
int file =
open(shuffler->chunk_filename(nchunks).c_str(),
O_WRONLY | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR);
size_t chunk_size = chunk_buf.size() * sizeof(edge_t);
writea(file, (char *)&chunk_buf[0], chunk_size);
close(file);
chunk_buf.clear();
}
};
size_t chunk_bufsize;
int nchunks, old_nchunks;
std::vector<edge_t> chunk_buf, old_chunk_buf;
std::string chunk_filename(int chunk);
void chunk_clean();
void cwrite(edge_t e, bool flush = false);
public:
Shuffler(std::string basefilename) : Converter(basefilename) {}
bool done() { return is_exists(shuffled_binedgelist_name(basefilename)); }
void init();
void finalize();
void add_edge(vid_t source, vid_t target);
};
| 26.297872
| 80
| 0.618123
|
nikolaimerkel
|
1cec0fe776c42b019c1dff63883f60e3d7408525
| 31,587
|
cc
|
C++
|
MT_systems/matxin-lex/squoia_xfer_lex.cc
|
ariosquoia/squoia
|
3f3c3c253bdb2d891889e0427790e6c972870f08
|
[
"Apache-2.0"
] | 9
|
2016-04-27T16:48:58.000Z
|
2021-01-17T21:55:55.000Z
|
MT_systems/matxin-lex/squoia_xfer_lex.cc
|
ariosquoia/squoia
|
3f3c3c253bdb2d891889e0427790e6c972870f08
|
[
"Apache-2.0"
] | null | null | null |
MT_systems/matxin-lex/squoia_xfer_lex.cc
|
ariosquoia/squoia
|
3f3c3c253bdb2d891889e0427790e6c972870f08
|
[
"Apache-2.0"
] | 6
|
2016-03-29T22:26:50.000Z
|
2021-01-17T21:56:21.000Z
|
/*
* Copyright (C) 2005 IXA Research Group / IXA Ikerkuntza Taldea.
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
/*
* This file has been adapted for SQUOIA.
*/
#include <lttoolbox/fst_processor.h>
#include <lttoolbox/ltstr.h>
#include <lttoolbox/xml_parse_util.h>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <locale>
#include <getopt.h>
#include <libgen.h>
#include <wctype.h>
using namespace std;
// Method prototypes
// from string_utils: tolower
wstring tolower(wstring const &s);
// from data_manager: init_lexInfo, get_lexInfo, lexical_selection
void init_lexInfo(wstring name, string fitxName);
wstring get_lexInfo(wstring name, wstring type_es);
vector<wstring> lexical_selection(wstring parent_attributes, wstring common_attributes, vector<wstring> child_attributes);
// from matxin_string_utils
void Tokenize(const wstring& str, vector<wstring>& tokens, const wstring& delimiter = L" ");
void Tokenize2(const wstring& str, wstring& tokens, const wstring& delimiter = L" ");
/*
* Splits multi-attribute text from a elment into
* attributes from separate elements.
*
* For example, having this input string:
* str = L"lem='beste\bat' pos='[DET][DZG]\[DET][DZH]' pos='4'"
* it will return a vector with these elements:
* v = {L"lem='beste' pos='[DET][DZG]' pos='4'" ,
* L"lem='bat' pos='[DET][DZH]' pos='4'"}
*/
vector<wstring> split_multiattrib(wstring str);
wstring v2s(vector<wstring> vector, wstring delimiter = L" ");
// from XML_reader
string xmlc2s(xmlChar const * entrada);
wstring write_xml(wstring input);
wstring getTagName(xmlTextReaderPtr reader);
int nextTag(xmlTextReaderPtr reader);
wstring attrib(xmlTextReaderPtr reader, string const &nombre);
wstring allAttrib(xmlTextReaderPtr reader);
wstring allAttrib_except(xmlTextReaderPtr reader, wstring attrib_no);
wstring text_attrib(wstring attributes, wstring const &nombre);
wstring text_allAttrib_except(wstring attributes, const wstring &nombre);
// original matxin_xfer_lex
wstring upper_type(wstring form, wstring mi, wstring ord);
wstring get_dict_attributes(const wstring full);
wstring getsyn(vector<wstring> translations);
void order_ordainak(vector<wstring> &ordainak);
vector<wstring> disambiguate(wstring &full);
vector<wstring> get_translation(wstring lem, wstring mi, bool &unknown);
wstring multiNodes (wstring &full, wstring attributes);
std::pair<wstring,wstring> procNODE(xmlTextReaderPtr reader, bool head, wstring parent_attribs, wstring& attributes);
wstring procCHUNK(xmlTextReaderPtr reader, wstring parent_attribs);
wstring procSENTENCE (xmlTextReaderPtr reader);
void endProgram(char *name);
FSTProcessor fstp; // Transducer with bilingual dictionary
// from string_utils
wstring tolower(wstring const &s)
{
wstring l=s;
for(unsigned i=0; i<s.length(); i++)
{
l[i] = (wchar_t) towlower(s[i]);
}
return l;
}
// from data_manager
struct lexInfo {
wstring name;
map<wstring,wstring> info;
};
static vector<lexInfo> lexical_information;
void init_lexInfo(wstring name, string fitxName)
{
wifstream fitx;
lexInfo lex;
lex.name = name;
fitx.open(fitxName.c_str());
wstring lerro;
while (getline(fitx, lerro))
{
// Remove comments
if (lerro.find(L'#') != wstring::npos)
lerro = lerro.substr(0, lerro.find(L'#'));
// Remove whitespace and so...
for (int i = 0; i < int(lerro.size()); i++)
{
if (lerro[i] == L' ' and (lerro[i+1] == L' ' or lerro[i+1] == L'\t'))
lerro[i] = L'\t';
if ((lerro[i] == L' ' or lerro[i] == L'\t') and
(i == 0 or lerro[i-1] == L'\t'))
{
lerro.erase(i,1);
i--;
}
}
if (lerro[lerro.size()-1] == L' ' or lerro[lerro.size()-1] == L'\t')
lerro.erase(lerro.size()-1,1);
size_t pos = lerro.find(L"\t");
if (pos == wstring::npos)
continue;
wstring key = lerro.substr(0,pos);
wstring value = lerro.substr(pos+1);
lex.info[key] = value;
}
fitx.close();
lexical_information.push_back(lex);
}
wstring get_lexInfo(wstring name, wstring key)
{
for (size_t i = 0; i < lexical_information.size(); i++)
{
if (lexical_information[i].name == name) {
return lexical_information[i].info[key];
}
}
return L"";
}
vector<wstring> lexical_selection(wstring parent_attributes, wstring common_attribs,
vector<wstring> child_attributes)
{
wstring src_lemma;
wstring trgt_lemma;
wstring attributes;
vector<wstring> default_case;
src_lemma = text_attrib(common_attribs, L"slem");
// Save the first value just in case there's no default set in the rules
if (child_attributes.size() > 0)
default_case.push_back(child_attributes[0]);
for (size_t i = 0; i < child_attributes.size(); i++)
{
attributes = common_attribs + L" " + child_attributes[i];
trgt_lemma = text_attrib(attributes, L"lem");
}
return default_case;
}
// from matxin_string_utils
void Tokenize(const wstring& str,
vector<wstring>& tokens,
const wstring& delimiters)
{
// Skip delimiters at beginning
size_t lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter"
size_t pos = str.find_first_of(delimiters, lastPos);
while (pos != wstring::npos || lastPos != wstring::npos)
{
// Found a token, add it to the vector
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
void Tokenize2(const wstring& str,
wstring& tokens,
const wstring& delimiters)
{
// Skip delimiters at beginning
size_t lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter"
size_t pos = str.find_first_of(delimiters, lastPos);
while (pos != wstring::npos || lastPos != wstring::npos)
{
// Found a token, add it to the resulting string
tokens += str.substr(lastPos, pos - lastPos);
// Skip delimiters
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
vector<wstring> split_multiattrib(wstring str)
{
vector<wstring> tokens;
vector<wstring> result;
wstring resultStr;
Tokenize(str, tokens);
for (size_t i = 0; i < tokens.size(); i++)
{
vector<wstring> attribs;
vector<wstring> valueparts;
wstring values;
Tokenize(tokens[i], attribs, L"=");
Tokenize2(attribs[1], values, L"'");
Tokenize(values, valueparts, L"\\");
for (size_t j = 0; j < valueparts.size(); j++)
{
resultStr = attribs[0] + L"='" + valueparts[j] + L"' ";
if (result.size() > j)
result[j].append(resultStr);
else {
result.resize(valueparts.size());
result[j] = resultStr;
}
}
}
return result;
}
wstring v2s(vector<wstring> vector, wstring delimiter)
{
wstring result = L"";
for (size_t i = 0; i < vector.size(); i++)
result += delimiter + vector[i];
return result;
}
// from XML_reader
// Converts xmlChar strings used by libxml2 to ordinary strings
string xmlc2s(xmlChar const *entrada)
{
if (entrada == NULL)
return "";
return reinterpret_cast<char const *>(entrada);
}
wstring getTagName(xmlTextReaderPtr reader)
{
xmlChar const *xname = xmlTextReaderConstName(reader);
wstring tagName = XMLParseUtil::stows(xmlc2s(xname));
return tagName;
}
int nextTag(xmlTextReaderPtr reader)
{
int ret = xmlTextReaderRead(reader);
wstring tagName = getTagName(reader);
int tagType = xmlTextReaderNodeType(reader);
while (ret == 1 and (tagType == XML_READER_TYPE_DOCUMENT_TYPE or tagName == L"#text"))
{
ret = xmlTextReaderRead(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
}
return ret;
}
wstring attrib(xmlTextReaderPtr reader, string const &nombre)
{
if (nombre[0] == '\'' && nombre[nombre.size() - 1] == '\'')
return XMLParseUtil::stows(nombre.substr(1, nombre.size() - 2));
xmlChar *nomatrib = xmlCharStrdup(nombre.c_str());
xmlChar *atrib = xmlTextReaderGetAttribute(reader,nomatrib);
wstring result = XMLParseUtil::stows(xmlc2s(atrib));
xmlFree(atrib);
xmlFree(nomatrib);
return result;
}
wstring allAttrib(xmlTextReaderPtr reader)
{
wstring output = L"";
for (int hasAttrib = xmlTextReaderMoveToFirstAttribute(reader);
hasAttrib > 0;
hasAttrib = xmlTextReaderMoveToNextAttribute(reader))
{
xmlChar const *xname = xmlTextReaderConstName(reader);
xmlChar const *xvalue = xmlTextReaderConstValue(reader);
output += L" " + XMLParseUtil::stows(xmlc2s(xname)) + L"='" +
XMLParseUtil::stows(xmlc2s(xvalue)) + L"'";
}
xmlTextReaderMoveToElement(reader);
return output;
}
wstring allAttrib_except(xmlTextReaderPtr reader, wstring attrib_no)
{
wstring output = L"";
for (int hasAttrib=xmlTextReaderMoveToFirstAttribute(reader);
hasAttrib > 0;
hasAttrib = xmlTextReaderMoveToNextAttribute(reader))
{
xmlChar const *xname = xmlTextReaderConstName(reader);
xmlChar const *xvalue = xmlTextReaderConstValue(reader);
if (XMLParseUtil::stows(xmlc2s(xname)) != attrib_no)
output += L" " + XMLParseUtil::stows(xmlc2s(xname)) + L"='" +
XMLParseUtil::stows(xmlc2s(xvalue)) + L"'";
}
xmlTextReaderMoveToElement(reader);
return output;
}
wstring text_allAttrib_except(wstring attributes, const wstring &nombre)
{
vector<wstring> tokens;
Tokenize(attributes, tokens);
for (size_t i = 0; i < tokens.size(); i++)
{
vector<wstring> attribs;
Tokenize(tokens[i], attribs, L"=");
if (attribs[0] == nombre)
{
tokens.erase(tokens.begin() + i);
break;
}
}
return v2s(tokens);
}
wstring write_xml(wstring s)
{
size_t pos = 0;
while ((pos = s.find(L"&", pos)) != wstring::npos)
{
s.replace(pos, 1, L"&");
pos += 4;
}
while ((pos = s.find(L'"')) != wstring::npos)
{
s.replace(pos, 1, L""");
}
pos = 0;
while ((pos = s.find(L'\'', pos)) != wstring::npos)
{
if (s[pos - 1] != L'=' && s[pos + 1] != L' ' && pos != (s.size() - 1))
s.replace(pos, 1, L"'");
else
pos++;
}
while ((pos = s.find(L"<")) != wstring::npos)
{
s.replace(pos, 1, L"<");
}
while ((pos = s.find(L">")) != wstring::npos)
{
s.replace(pos, 1, L">");
}
return s;
}
wstring text_attrib(wstring attributes, const wstring& nombre)
{
vector<wstring> tokens;
wstring value = L"";
Tokenize(attributes, tokens);
for (size_t i = 0; i < tokens.size(); i++)
{
vector<wstring> attribs;
Tokenize(tokens[i], attribs, L"=");
if (attribs[0] == nombre)
{
Tokenize2(attribs[1], value, L"'");
break;
}
}
return value;
}
// original matxin_xfer_lex
wstring upper_type(wstring form, wstring mi, wstring ord)
{
wstring case_type = L"none";
size_t form_begin, form_end;
int upper_case, lower_case;
form_begin = 0;
if (form.find(L"_", form_begin + 1) == wstring::npos)
form_end = form.size();
else
form_end = form.find(L"_", form_begin + 1);
upper_case = lower_case = 0;
while (form_begin != form.size())
{
if (tolower(form[form_begin]) != form[form_begin] and
(ord != L"1" or mi.substr(0, 2) == L"NP"))
{
if (form_begin == 0)
case_type = L"first";
else
case_type = L"title";
}
for (size_t i = form_begin; i < form_end; i++)
{
if (form[i] != tolower(form[i]))
upper_case++;
else
lower_case++;
}
if (form.size() > form_end)
form_begin = form_end + 1;
else
form_begin = form.size();
if (form.find(L"_", form_begin + 1) == wstring::npos)
form_end = form.size();
else
form_end = form.find(L"_", form_begin + 1);
}
if (upper_case > lower_case)
case_type = L"all";
return case_type;
}
/*
* Gets attributes from the bilingual dictionary
* input: "lemma<key1>value1<key2>value2...<keyn>valueN"
* output: "lem='lemma' key1='value1' ... keyN='valueN'"
*/
wstring get_dict_attributes(const wstring full)
{
vector<wstring> tokens;
wstring result = L"";
bool empty_lemma = false;
Tokenize(full, tokens, L"<");
// Special case, empty lemma
if (full.substr(0, 1) == L"<")
{
result += L"lem=''";
empty_lemma = true;
}
for (size_t i = 0; i < tokens.size(); i ++)
{
if (i == 0 && !empty_lemma)
{
result += L"lem='" + write_xml(tokens[i]) + L"'";
}
else
{
vector<wstring> attribs;
Tokenize(tokens[i], attribs, L">");
result += L" " + attribs[0] + L"='" + write_xml(attribs[1]) + L"'";
}
}
return result;
}
wstring getsyn2lems(vector<wstring> translations, wstring slem)
{
wstring output;
for (size_t i = 0; i < translations.size(); i++)
output += L"<SYN " + translations[i] + L" slem='" + slem + L"' />\n";
return output;
}
wstring getsyn(vector<wstring> translations)
{
wstring output;
for (size_t i = 0; i < translations.size(); i++)
output += L"<SYN " + translations[i] + L"/>\n";
return output;
}
void order_ordainak(vector<wstring> &ordainak)
{
vector<wstring> ordered_ordain;
int sense;
bool zero_sense = false;
vector<wstring>::iterator it;
for (it = ordainak.begin(); it != ordainak.end(); it++)
{
sense = 0;
size_t pos, pos2;
if ((pos = (*it).find(L" sense='")) != wstring::npos)
{
if ((pos2 = (*it).find(L"'", pos+8)) != wstring::npos)
sense = wcstol((*it).substr(pos+8, pos2-pos-8).c_str(), NULL, 10);
}
if (sense == 0)
{
zero_sense = true;
ordered_ordain.insert(ordered_ordain.begin(), *it);
}
else
{
if (!zero_sense)
sense--;
if (ordered_ordain.size() < sense+1)
ordered_ordain.resize(sense+1);
ordered_ordain[sense] = *it;
}
}
ordainak = ordered_ordain;
}
// Hiztegi elebidunaren euskarazko ordainetik lehenengoa lortzen du.
// IN: Euskarazko ordainak ( ordain1[/ordain2]* )
// note: segfaults if full has no mi
// OUT: lehenengoa ( oradin1 )
vector<wstring> disambiguate(wstring &full)
{
wstring output = full;
vector<wstring> ordainak;
// Això no és precisament disambiguació, és més aviat dit
// 'selecció de la primera opció'
for (size_t i = 0; i < output.size(); i++)
{
if (output[i] == L'/')
{
ordainak.push_back(get_dict_attributes(output.substr(0, i)));
output = output.substr(i + 1);
i = 0;
}
if (output[i] == L'\\')
output.erase(i, 1);
}
ordainak.push_back(get_dict_attributes(output));
order_ordainak(ordainak);
return ordainak;
}
vector<wstring> get_translation(wstring lem, wstring mi,
bool &unknown)
{
vector<wstring> translation;
wstring trad = L"";
wstring input = L"";
input = L"^" + lem + L"<parol>" + mi + L"$";
trad = fstp.biltrans(input);
trad = trad.substr(1, trad.size() - 2);
unknown = false;
if (trad[0] == L'@' || trad.find(L">") < trad.find(L"<"))
{
unknown = true;
return translation;
}
translation = disambiguate(trad);
return translation;
}
// Hiztegi elebidunaren euskarazko ordaina NODO bat baino gehiagoz osaturik badago.
// Adb. oso<ADB><ADOARR><+><MG><+>\eskas<ADB><ADJ><+><MG><+>.
// Azken NODOa ezik besteak tratatzen ditu
// IN: Euskarazko ordain bat, NODO bat baino gehiago izan ditzake.
// OUT: Lehen NODOei dagokien XML zuhaitza.
//wstring multiNodes (xmlTextReaderPtr reader, wstring &full, wstring attributes)
wstring multiNodes (wstring &full, wstring attributes)
{
wstring output = L"";
vector<wstring> tmp;
tmp = split_multiattrib(full);
for (size_t i = 1; i < tmp.size(); i++)
{
output += L"<NODE " + attributes;
output += L" " + tmp[i] + L" />\n";
}
return output;
}
// NODE etiketa irakurri eta prozesatzen du, NODE hori AS motakoa ez den CHUNK baten barruan dagoela:
// - ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du (helmugak jatorrizkoaren erreferentzia izateko postedizioan)
// - (S) preposizioen eta (F) puntuazio ikurren kasuan ez da transferentzia egiten.
// - Beste kasuetan:
// - Transferentzia lexikoa egiten da, lem, pos, mi, cas eta sub attributuak sortuz.
// - Hitz horren semantika begiratzen da
// - NODEaren azpian dauden NODEak irakurri eta prozesatzen ditu.
std::pair<wstring,wstring> procNODE(xmlTextReaderPtr reader, bool head,
wstring parent_attribs, wstring& attributes)
{
wstring nodes, pos;
wstring subnodes;
wstring synonyms;
wstring synonyms2;
wstring child_attributes;
wstring tagName = getTagName(reader);
vector<wstring> trad;
// squoia: ambiguos lemmas-> need 2nd trad
vector<wstring> trad2;
wstring lem1, lem2;
vector<wstring> select;
int tagType = xmlTextReaderNodeType(reader);
bool head_child = false;
bool unknown = false;
bool ambilem = false;
// ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du
// alloc atributua mantentzen da
if (tagName == L"NODE" and tagType != XML_READER_TYPE_END_ELEMENT)
{
nodes = L"<NODE ";
attributes = L"ref='" + write_xml(attrib(reader, "ord")) + L"'" +
L" alloc='" + write_xml(attrib(reader, "alloc")) + L"'" +
L" slem='" + write_xml(attrib(reader, "lem")) + L"'" +
L" smi='" + write_xml(attrib(reader, "mi")) + L"'" +
L" sform='" + write_xml(attrib(reader, "form")) + L"'" +
L" UpCase='" + write_xml(upper_type(attrib(reader, "form"),
attrib(reader, "mi"),
attrib(reader, "ord"))) +
L"'";
if (attrib(reader, "unknown") != L"")
{
attributes += L" unknown='" + write_xml(attrib(reader, "unknown")) + L"'";
}
// TODO: LANGUAGE INDEPENDENCE
// else if (attrib(reader,"mi") != L"" &&
// attrib(reader, "mi").substr(0,1) == L"W" or
// attrib(reader, "mi").substr(0,1) == L"Z")
// {
// // Daten (W) eta zenbakien (Z) kasuan ez da transferentzia egiten.
// // lem eta mi mantentzen dira
// attributes += L" lem='" + write_xml(attrib(reader, "lem")) + L"'" +
// L" pos='[" + write_xml(attrib(reader, "mi")) + L"]'";
// }
else
{
// Beste kasuetan:
// Transferentzia lexikoa egiten da, lem, pos, mi, cas eta sub attributuak sortuz.
// trad = get_translation(attrib(reader, "lem"), attrib(reader, "mi"), unknown);
// changed squoia: if number 'Z' or 'DN' -> use word form for lookup, not lemma
if(attrib(reader, "mi").substr(0,1) == L"Z" or attrib(reader, "mi").substr(0,2) == L"DN"){
trad = get_translation(attrib(reader, "form"), attrib(reader, "mi"), unknown);
}
else{
// squoia: split ambiguous lemmas from tagging (e.g. asiento: asentir/asentar) and lookup both
// TODO: insert some attribute to know which slem belongs to which lem!
int split =attrib(reader, "lem").find(L"#");
if(split != wstring::npos){
ambilem = true;
// wcerr << attrib(reader, "lem") << L"1 split at: " << split << L"\n";
lem1 = attrib(reader, "lem").substr(0,split);
lem2 = attrib(reader, "lem").substr(split+2,wstring::npos);
//wcerr << L"lemma 1" << lem1 << L" lemma 2: " << lem2 << L"\n";
bool unknown1 = false;
trad = get_translation(lem1, attrib(reader, "mi"), unknown1);
bool unknown2 = false;
trad2 = get_translation(lem2, attrib(reader, "mi"), unknown2);
unknown = unknown1 and unknown2;
//wcerr << L"trad size lem1 " <<trad.size() << L" trad size lem2:" << trad2[0] << L"\n";
}
else{
trad = get_translation(attrib(reader, "lem"),attrib(reader, "mi"), unknown);
}
}
if (unknown) {
attributes += L" unknown='transfer'";
}
else // either trad or trad2 has at least one translation
{
if (trad.size() > 1 ) {
select = lexical_selection(parent_attribs, attributes, trad);
} else if (trad.size() > 0) {
select = trad;
} else if (trad2.size() > 1) {
select = lexical_selection(parent_attribs, attributes, trad2);
} else {
select = trad2;
}
if (trad.size() > 1 and not ambilem) {
synonyms = getsyn(trad);
}
// if there was a second lemma translated: add slem to synonyms to avoid confusion
else if (trad.size() > 1 or (trad.size() > 0 and trad2.size() > 0)) {
synonyms = getsyn2lems(trad, lem1);
}
if (trad2.size() > 1 or (trad2.size() > 0 and trad.size() > 0)) {
synonyms2 = getsyn2lems(trad2,lem2);
}
if (ambilem) {
if (trad.size() > 0) {
// add tradlem='lem1' to node, so that we know which lemma belongs to the first translation
attributes += L" tradlem='" + lem1 + L"' ";
} else {
attributes += L" tradlem='" + lem2 + L"' ";
}
}
if (select[0].find(L"\\") != wstring::npos) {
subnodes = multiNodes(select[0], attributes);
}
attributes += L" " + select[0];
head_child = head && (text_attrib(select[0], L"lem") == L"");
}
}
if (xmlTextReaderIsEmptyElement(reader) == 1 and
subnodes == L"" && synonyms == L"" && synonyms2 == L"")
{
// NODE hutsa bada (<NODE .../>), NODE hutsa sortzen da eta
// momentuko NODEarekin bukatzen dugu.
// empty nodes (?)
nodes += attributes + L"/>\n";
return std::make_pair(nodes,pos);
}
else if (xmlTextReaderIsEmptyElement(reader) == 1)
{
// NODE hutsa bada (<NODE .../>), NODE hutsa sortzen da eta
// momentuko NODEarekin bukatzen dugu.
nodes += attributes + L">\n" + synonyms +synonyms2 + subnodes + L"</NODE>\n";
return std::make_pair(nodes,pos);
}
else
{
// bestela NODE hasiera etiketaren bukaera idatzi eta
// etiketa barrukoa tratatzera pasatzen gara.
nodes += attributes + L">\n" + synonyms + synonyms2 + subnodes;
}
}
else
{
wcerr << L"ERROR: invalid tag: <" << tagName << allAttrib(reader)
<< L"> when <NODE> was expected..." << endl;
exit(-1);
}
int ret = nextTag(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
wstring attribs = attributes;
if (text_attrib(attributes, L"lem") == L"")
attribs = parent_attribs;
// NODEaren azpian dauden NODE guztietarako
while (ret == 1 and tagName == L"NODE" and
tagType == XML_READER_TYPE_ELEMENT)
{
// NODEa irakurri eta prozesatzen du.
//nodes += procNODE(reader, head_child, attributes, cfg);
std::pair<wstring,wstring> pr = procNODE(reader, head_child, attribs,
child_attributes);
wstring NODOA = pr.first;
nodes += NODOA;
ret = nextTag(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
}
if (text_attrib(attributes, L"lem") == L"")
attributes = child_attributes;
// NODE bukaera etiketa tratatzen da.
if (tagName == L"NODE" and tagType == XML_READER_TYPE_END_ELEMENT)
{
nodes += L"</NODE>\n";
}
else
{
wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader)
<< L"> when </NODE> was expected..." << endl;
exit(-1);
}
return std::make_pair(nodes,pos);
}
// CHUNK etiketa irakurri eta prozesatzen du:
// - ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du (helmugak jatorrizkoaren erreferentzia izateko postedizioan)
// - type : CHUNKaren type atributua itzultzen da
wstring procCHUNK(xmlTextReaderPtr reader, wstring parent_attribs)
{
wstring tagName = getTagName(reader);
int tagType = xmlTextReaderNodeType(reader);
wstring tree, chunk_type, head_attribs;
wstring old_type, si, ref, other_attribs, nodes;
if (tagName == L"CHUNK" and tagType == XML_READER_TYPE_ELEMENT)
{
// ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du
// type : CHUNKaren type atributua itzultzen da
// si atributua mantentzen da
old_type = attrib(reader, "type");
chunk_type = get_lexInfo(L"chunkType", old_type); // might change below
si = attrib(reader, "si");
ref = attrib(reader, "ord");
other_attribs = text_allAttrib_except(allAttrib_except(reader, L"ord"), L"type");
// Store CHUNK attribs before call to nextTag(reader). These are
// written to the tree after the call to procNODE in case
// chunk_type has to be based on the pos attrib of the first NODE
}
else
{
wcerr << L"ERROR: invalid tag: <" << tagName << allAttrib(reader)
<< L"> when <CHUNK> was expected..." << endl;
exit(-1);
}
int ret = nextTag(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
std::pair<wstring,wstring> pr = procNODE(reader, true, parent_attribs, head_attribs);
nodes = pr.first;
if (old_type == L"") {
wstring pos = pr.second;
chunk_type = get_lexInfo(L"chunkType", si + pos);
if (chunk_type == L"") {
// if syntactic function wasn't in chunktype_file, or no chunktype_file given:
chunk_type = si + pos;
}
}
else {
chunk_type = get_lexInfo(L"chunkType", old_type);
if (chunk_type == L"") {
chunk_type = old_type;
}
}
tree = L"<CHUNK ref='" + write_xml(ref) +
L"' type='" + write_xml(chunk_type) + L"'" +
write_xml(other_attribs) + L">\n" +
nodes;
ret = nextTag(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
while (ret == 1 and tagName == L"CHUNK" and tagType == XML_READER_TYPE_ELEMENT)
{
tree += procCHUNK(reader, head_attribs);
ret = nextTag(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
}
if (tagName == L"CHUNK" and tagType == XML_READER_TYPE_END_ELEMENT)
{
tree += L"</CHUNK>\n";
}
else
{
wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader)
<< L"> when </CHUNK> was expected..." << endl;
exit(-1);
}
return tree;
}
// SENTENCE etiketa irakurri eta prozesatzen du:
// - ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du (helmugak jatorrizkoaren erreferentzia izateko postedizioan)
// - SENTENCE barruan dauden CHUNKak irakurri eta prozesatzen ditu.
wstring procSENTENCE (xmlTextReaderPtr reader)
{
wstring tree;
wstring tagName = getTagName(reader);
int tagType = xmlTextReaderNodeType(reader);
if (tagName == L"SENTENCE" and tagType != XML_READER_TYPE_END_ELEMENT)
{
// ord -> ref : ord atributuan dagoen balioa, ref atributuan gordetzen du
tree = L"<SENTENCE ref='" + write_xml(attrib(reader, "ord")) + L"'"
+ write_xml(allAttrib_except(reader, L"ord"))
+ L">\n";
}
else
{
wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader)
<< L"> when <SENTENCE> was expected..." << endl;
exit(-1);
}
int ret = nextTag(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
// SENTENCE barruan dauden CHUNK guztietarako
while (ret == 1 and tagName == L"CHUNK")
{
// CHUNKa irakurri eta prozesatzen du.
tree += procCHUNK(reader, L"");
ret = nextTag(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
}
if (ret == 1 and tagName == L"SENTENCE" and
tagType == XML_READER_TYPE_END_ELEMENT)
{
tree += L"</SENTENCE>\n";
}
else
{
wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader)
<< L"> when </SENTENCE> was expected..." << endl;
exit(-1);
}
return tree;
}
void endProgram(char *name)
{
cout << basename(name) << ": run lexical transfer on a Matxin input stream" << endl;
cout << "USAGE: " << basename(name) << " [-c chunktype_file] fst_file" << endl;
cout << "Options:" << endl;
#if HAVE_GETOPT_LONG
cout << " -c, --chunktype-file: give a file listing chunk types" << endl;
#else
cout << " -c: give a file listing chunk types" << endl;
#endif
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
// This sets the C++ locale and affects to C and C++ locales.
// wcout.imbue doesn't have any effect but the in/out streams use the proper encoding.
#ifndef NeXTBSD
#ifdef __APPLE__
setlocale(LC_ALL, "");
// locale("") doesn't work on mac, except with C/POSIX
#else
locale::global(locale(""));
#endif
#else
setlocale(LC_ALL, "");
#endif
if(argc < 2) {
endProgram(argv[0]);
}
#if HAVE_GETOPT_LONG
static struct option long_options[]=
{
{"chunk-file", 0, 0, 'c'},
};
#endif
while(true)
{
#if HAVE_GETOPT_LONG
int option_index;
int c = getopt_long(argc, argv, "c:", long_options, &option_index);
#else
int c = getopt(argc, argv, "c:");
#endif
if(c == -1)
{
break;
}
switch(c)
{
case 'c':
//check if the file exists and is readable
init_lexInfo(L"chunkType", optarg);
break;
default:
endProgram(argv[0]);
break;
}
}
FILE *transducer = 0;
transducer = fopen(argv[optind], "r");
fstp.load(transducer);
fclose(transducer);
fstp.initBiltrans();
// libXml liburutegiko reader hasieratzen da, sarrera estandarreko fitxategia irakurtzeko.
xmlTextReaderPtr reader;
reader = xmlReaderForFd(0, "", NULL, 0);
int ret = nextTag(reader);
wstring tagName = getTagName(reader);
int tagType = xmlTextReaderNodeType(reader);
if(tagName == L"corpus" and tagType != XML_READER_TYPE_END_ELEMENT)
{
wcout << L"<?xml version='1.0' encoding='UTF-8'?>" << endl;
wcout << L"<corpus " << write_xml(allAttrib(reader)) << ">" << endl;
}
else
{
wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader)
<< L"> when <corpus> was expected..." << endl;
exit(-1);
}
ret = nextTag(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
int i = 0;
// corpus barruan dauden SENTENCE guztietarako
while (ret == 1 and tagName == L"SENTENCE")
{
//SENTENCE irakurri eta prozesatzen du.
wstring tree = procSENTENCE(reader);
wcout << tree << endl;
wcout.flush();
ret = nextTag(reader);
tagName = getTagName(reader);
tagType = xmlTextReaderNodeType(reader);
}
xmlFreeTextReader(reader);
xmlCleanupParser();
if(ret == 1 and tagName == L"corpus" and
tagType == XML_READER_TYPE_END_ELEMENT)
{
wcout << L"</corpus>\n";
}
else
{
wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader)
<< L"> when </corpus> was expected..." << endl;
exit(-1);
}
}
| 28.00266
| 134
| 0.629246
|
ariosquoia
|
1ced0d82f1e0edc30c2e913f425fbac2084d7fd7
| 1,858
|
cpp
|
C++
|
Source/Game/MainMenuScene.cpp
|
nathanlink169/3D-Shaders-Test
|
2493fb71664d75100fbb4a80ac70f657a189593d
|
[
"MIT"
] | null | null | null |
Source/Game/MainMenuScene.cpp
|
nathanlink169/3D-Shaders-Test
|
2493fb71664d75100fbb4a80ac70f657a189593d
|
[
"MIT"
] | null | null | null |
Source/Game/MainMenuScene.cpp
|
nathanlink169/3D-Shaders-Test
|
2493fb71664d75100fbb4a80ac70f657a189593d
|
[
"MIT"
] | null | null | null |
#include "CommonHeader.h"
MainMenuScene::MainMenuScene()
{
}
MainMenuScene::~MainMenuScene()
{
}
void MainMenuScene::OnSurfaceChanged(unsigned int aWidth, unsigned int aHeight)
{
Scene::OnSurfaceChanged(aWidth, aHeight);
}
void MainMenuScene::LoadContent()
{
Scene::LoadContent();
CreateCameraObject();
Label* label = new Label(this, "Loading Label", "Loading", vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.035f, 0.035f, 0.035f), nullptr, g_pGame->GetShader("2D Colour"), g_pGame->GetTexture("Black"));
label->Colour = Colours::Crimson;
label->SetFont("arial");
label->Text = "Press Space To Start";
label->Orientation = Center;
AddGameObject(label, "Label");
//AudioManager::PlayBGM("Main Theme");
std::ifstream myfile("Data/SaveData/Score.npwscore");
if (myfile.is_open())
{
std::string line;
ScoreEntry entries;
getline(myfile, line);
entries.Name = line;
getline(myfile, line);
entries.Score = (uint)(std::stoi(line));
Label* score = new Label(this, "High Score Label", "Label", vec3(0.0f, -0.1f, 0.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.015f, 0.015f, 0.015f), nullptr, g_pGame->GetShader("2D Colour"), g_pGame->GetTexture("Black"));
score->Colour = Colours::Crimson;
score->SetFont("arial");
score->Text = "Highscore: " + entries.Name + " - " + std::to_string(entries.Score);
score->Orientation = Center;
AddGameObject(score, "HighScoreLabel");
}
}
void MainMenuScene::Update(double aDelta)
{
Scene::Update(aDelta);
if (Input::KeyJustPressed(VK_SPACE))
g_pGame->StartGame();
}
void MainMenuScene::Draw()
{
m_Matrix.CreatePerspectiveVFoV(CAMERA_PERSPECTIVE_ANGLE, CAMERA_ASPECT_RATIO, CAMERA_NEAR_Z, CAMERA_FAR_Z);
m_MainCamera->CreateLookAtLeftHandAndReturn(Vector3(0, 1, 0), GetGameObject("Label")->GetPosition());
Scene::Draw();
}
| 28.151515
| 213
| 0.684069
|
nathanlink169
|
1cf05e916039a1c77ac99a82b67ece7c35271c0c
| 756
|
cpp
|
C++
|
cpp/bjyd/06/TestGeometricObject2.cpp
|
skyofsmith/servePractice
|
d143497ec7c13dcbb55354c9050fd48e5b1c7b51
|
[
"MIT"
] | null | null | null |
cpp/bjyd/06/TestGeometricObject2.cpp
|
skyofsmith/servePractice
|
d143497ec7c13dcbb55354c9050fd48e5b1c7b51
|
[
"MIT"
] | 18
|
2020-07-16T21:36:57.000Z
|
2022-03-25T18:59:38.000Z
|
cpp/bjyd/06/TestGeometricObject2.cpp
|
skyofsmith/servePractice
|
d143497ec7c13dcbb55354c9050fd48e5b1c7b51
|
[
"MIT"
] | null | null | null |
#include <iostream>
//#include "AbstractGeometricObject.h"
#include "DerivedCircle2.h"
#include "Rectangle2.h"
using namespace std;
bool equalArea(GeometricObject &object1, GeometricObject &object2)
{
return object1.getArea() == object2.getArea();
}
void displayGeometricObject(GeometricObject &object)
{
cout << "The area is " << object.getArea() << endl;
cout << "The perimeter is " << object.getPerimeter() << endl;
}
int main() {
Circle circle(5);
Rectangle rectangle(5, 3);
cout << "Circle info: " << endl;
displayGeometricObject(circle);
cout << "\nRectangle info: " << endl;
displayGeometricObject(rectangle);
cout << "\nThe two objects have the same area? " <<
(equalArea(circle, rectangle) ? "Yes" : "No") << endl;
return 0;
}
| 22.909091
| 66
| 0.691799
|
skyofsmith
|
1cf6d96673df89a58ee0fc7bb8581a94ce538a35
| 321
|
cxx
|
C++
|
cxx/extends.cxx
|
coalpha/coalpha.github.io
|
8a620314a5c0bcbe2225d29f733379d181534430
|
[
"Apache-2.0"
] | null | null | null |
cxx/extends.cxx
|
coalpha/coalpha.github.io
|
8a620314a5c0bcbe2225d29f733379d181534430
|
[
"Apache-2.0"
] | 1
|
2020-04-12T07:48:18.000Z
|
2020-04-12T07:49:29.000Z
|
cxx/extends.cxx
|
coalpha/coalpha.github.io
|
8a620314a5c0bcbe2225d29f733379d181534430
|
[
"Apache-2.0"
] | 1
|
2020-09-30T05:27:07.000Z
|
2020-09-30T05:27:07.000Z
|
#include <type_traits>
using namespace std;
template <typename Base, typename Derived>
using extends = enable_if_t<is_base_of_v<Base, Derived>>;
struct cat{};
struct dog{};
template <typename T, typename = extends<cat, T>>
void only_cats(T) noexcept;
int main() noexcept {
only_cats(cat{});
only_dogs(dog{});
}
| 18.882353
| 57
| 0.719626
|
coalpha
|
7f2fbcd1d85fa5f4336de189dfc07777ac507a16
| 12,108
|
cpp
|
C++
|
src/Sparrow/Sparrow/Implementations/Dftb/Utils/SKPair.cpp
|
qcscine/sparrow
|
387e56ed8da78e10d96861758c509f7c375dcf07
|
[
"BSD-3-Clause"
] | 45
|
2019-06-12T20:04:00.000Z
|
2022-02-28T21:43:54.000Z
|
src/Sparrow/Sparrow/Implementations/Dftb/Utils/SKPair.cpp
|
qcscine/sparrow
|
387e56ed8da78e10d96861758c509f7c375dcf07
|
[
"BSD-3-Clause"
] | 12
|
2019-06-12T23:53:57.000Z
|
2022-03-28T18:35:57.000Z
|
src/Sparrow/Sparrow/Implementations/Dftb/Utils/SKPair.cpp
|
qcscine/sparrow
|
387e56ed8da78e10d96861758c509f7c375dcf07
|
[
"BSD-3-Clause"
] | 11
|
2019-06-22T22:52:51.000Z
|
2022-03-11T16:59:59.000Z
|
/**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include "SKPair.h"
#include "SKAtom.h"
#include <Utils/IO/Regex.h>
#include <Utils/Scf/MethodExceptions.h>
#include <Utils/Technical/ScopedLocale.h>
#include <cmath>
#include <fstream>
#include <regex>
namespace Scine {
namespace Sparrow {
using std::exp;
using namespace Utils::AutomaticDifferentiation;
namespace dftb {
// Declare space for values in binary at runtime
constexpr decltype(SKPair::integralIndexes) SKPair::integralIndexes;
SKPair::SKPair(SKAtom* atomicParameters1, SKAtom* atomicParameters2, SkfData data)
: atomType1(atomicParameters1),
atomType2(atomicParameters2),
gridDist(data.gridDistance),
nGridPoints(data.integralTable.front().size()),
rMax(gridDist * nGridPoints + distFudge),
integralTable(std::move(data.integralTable)),
repulsion_(std::move(data.repulsion)),
extrC3(28),
extrC4(28),
extrC5(28) {
if (integralTable.back().empty()) {
throw std::runtime_error("Back columns of integral table are empty instead of default-initialized!");
}
if (data.atomicParameters) {
const auto& p = data.atomicParameters.value();
atomicParameters1->setEnergies(p.Es, p.Ep, p.Ed);
atomicParameters1->setHubbardParameter(p.Us, p.Up, p.Ud);
atomicParameters1->setOccupations(p.fs, p.fp, p.fd);
}
// Set the number of integrals for the atom pair
const int nAOsA = atomicParameters1->getnAOs();
const int nAOsB = atomicParameters2->getnAOs();
if (nAOsA + nAOsB == 2) { // Only s orbitals
nIntegrals = 2;
}
else if (nAOsA + nAOsB == 5) { // one atom only has s, the other one s and p
nIntegrals = 4;
}
else if (nAOsA + nAOsB == 8) { // Both atoms have s and p
nIntegrals = 10;
}
else if (nAOsA + nAOsB == 10) { // one has s, one has d
nIntegrals = 14;
}
else if (nAOsA + nAOsB == 13) { // one has p, one has d
nIntegrals = 22;
}
else if (nAOsA + nAOsB == 18) { // both have d
nIntegrals = 28;
}
}
void SKPair::precalculateGammaTerms() {
// Precondition: not same atom type. In this case the gamma terms are not needed
if (atomType1 == atomType2)
return;
double ta = atomType1->getHubbardParameter() * 3.2;
double tb = atomType2->getHubbardParameter() * 3.2;
double ta2 = ta * ta;
double tb2 = tb * tb;
gamma.g1a = (tb2 * tb2 * ta) / (2.0 * (ta2 - tb2) * (ta2 - tb2));
gamma.g1b = (ta2 * ta2 * tb) / (2.0 * (tb2 - ta2) * (tb2 - ta2));
gamma.g2a = tb2 * tb2 * (tb2 - 3 * ta2) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2));
gamma.g2b = ta2 * ta2 * (ta2 - 3 * tb2) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2));
gammaDerivative.dgab1a = (tb2 * tb2 * tb2 + 3.0 * ta2 * tb2 * tb2) / (2.0 * (ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2));
gammaDerivative.dgab2a = (12.0 * ta2 * ta * tb2 * tb2) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2));
gammaDerivative.dgab1b = (2.0 * ta2 * ta * tb2 * tb) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2));
gammaDerivative.dgab2b = (12.0 * ta2 * ta2 * tb2 * tb) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2));
gammaDerivative.dgba1a = (ta2 * ta2 * ta2 + 3.0 * tb2 * ta2 * ta2) / (2.0 * (tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2));
gammaDerivative.dgba2a = (12.0 * tb2 * tb * ta2 * ta2) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2));
gammaDerivative.dgba1b = (2.0 * tb2 * tb * ta2 * ta) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2));
gammaDerivative.dgba2b = (12.0 * tb2 * tb2 * ta2 * ta) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2));
gammaDerivative.dgadr = (tb2 * tb2 * tb2 - 3.0 * ta2 * tb2 * tb2) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2));
gammaDerivative.dgbdr = (ta2 * ta2 * ta2 - 3.0 * tb2 * ta2 * ta2) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2));
}
const SKPair::GammaTerms& SKPair::getGammaTerms() const {
return gamma;
}
const SKPair::GammaDerivativeTerms& SKPair::getGammaDerTerms() const {
return gammaDerivative;
}
void SKPair::complete(SKPair* p) {
assert(p != nullptr);
constexpr double factor = -1.0;
for (int i = 0; i < nGridPoints; i++) {
integralTable[20][i] = factor * p->integralTable[3][i];
integralTable[21][i] = factor * p->integralTable[4][i];
integralTable[22][i] = p->integralTable[7][i];
integralTable[23][i] = factor * p->integralTable[8][i];
integralTable[24][i] = factor * p->integralTable[13][i];
integralTable[25][i] = factor * p->integralTable[14][i];
integralTable[26][i] = p->integralTable[17][i];
integralTable[27][i] = factor * p->integralTable[18][i];
}
// Precompute the coefficients for the extrapolation
precompute5Extrapolation();
}
void SKPair::precompute5Extrapolation() {
int indStart = nGridPoints - nInter;
InterpolationValues<Utils::DerivativeOrder::One> t1;
InterpolationValues<Utils::DerivativeOrder::One> t2;
// Calculate interpolated values right after and right before the last given
// point in parameter table; these values are used to compute the numerical
// derivatives at the last point
interpolate(t1, static_cast<double>(nGridPoints - 1) - deltaR, indStart); // Get values right before last given point
interpolate(t2, static_cast<double>(nGridPoints - 1) + deltaR, indStart); // Get values right after last given point
double yd0, yd1, yd2; // zero, first and second order derivatives
double dx1, dx2; // Temporary variables needed for the extrapolation
for (int L = 0; L < nIntegrals; L++) {
assert(integralIndexes[L] < static_cast<int>(integralTable.size()));
yd0 = integralTable[integralIndexes[L]][nGridPoints - 1];
yd1 = t1.derivIntegral[L].derivative();
yd2 = (t2.derivIntegral[L].derivative() - t1.derivIntegral[L].derivative()) / (deltaR);
// 5th order extrapolation (impose derivatives at last gridpoint, and zero value and derivatives at rMax)
dx1 = -yd1 * (distFudge / gridDist);
dx2 = yd2 * (distFudge / gridDist) * (distFudge / gridDist);
extrC3[L] = 10 * yd0 - 4 * dx1 + 0.5 * dx2;
extrC4[L] = -15 * yd0 + 7 * dx1 - dx2;
extrC5[L] = 6 * yd0 - 3 * dx1 + 0.5 * dx2;
}
}
template<Utils::DerivativeOrder O>
Value1DType<O> SKPair::getRepulsion(double const& r) const {
auto R = variableWithUnitDerivative<O>(r);
if (r > repulsion_.cutoff)
return constant1D<O>(0);
if (r < repulsion_.splines[0].start)
return exp(-repulsion_.a1 * R + repulsion_.a2) + repulsion_.a3;
auto i = static_cast<int>((r - repulsion_.splines[0].start) / (repulsion_.cutoff - repulsion_.splines[0].start) *
repulsion_.nSplineInts);
// If not the right bin, find the right one:
if (repulsion_.splines[i].start > r) {
while (repulsion_.splines[--i].start > r) {
}
}
else if (repulsion_.splines[i].end < r) {
while (repulsion_.splines[++i].end < r) {
}
}
const auto& spline = repulsion_.splines[i];
auto dr = R - spline.start;
auto conditional = (i == repulsion_.nSplineInts - 1 ? dr * (repulsion_.c4 + dr * repulsion_.c5) : constant1D<O>(0.0));
// clang-format off
return (
spline.c0 + dr * (
spline.c1 + dr * (
spline.c2 + dr * (
spline.c3 + conditional
)
)
)
);
// clang-format on
}
template<Utils::DerivativeOrder O>
int SKPair::getHS(double dist, InterpolationValues<O>& val) const {
// If 'dist' too short or too large, return 0
if (dist < gridDist || dist > rMax) {
for (int L = 0; L < nIntegrals; L++)
val.derivIntegral[L] = constant1D<O>(0.0);
return 0;
}
// If 'dist' is in the extrapolation zone, take simple formula
if (dist > nGridPoints * gridDist) {
double dr = dist - rMax;
auto xr = variableWithUnitDerivative<O>(-dr / distFudge);
// 5th order extrapolation (impose derivatives at last gridpoint, and zero value and derivatives at rMax)
for (int L = 0; L < nIntegrals; L++)
val.derivIntegral[L] = ((extrC5[L] * xr + extrC4[L]) * xr + extrC3[L]) * xr * xr * xr;
return 1;
}
// Else: do interpolation
getHSIntegral(val, dist);
return 1;
}
template<Utils::DerivativeOrder O>
int SKPair::getHSIntegral(InterpolationValues<O>& val, double dist) const {
double position = dist / gridDist - 1.0;
int ind; // Current index during interpolation
ind = static_cast<int>(position);
int indStart; // first index for interpolation
indStart = (ind >= nGridPoints - nInterRight) ? nGridPoints - nInter : ((ind < nInterLeft) ? 0 : ind - nInterLeft + 1);
// -1 because loop afterward goes from i = 0 to nInter - 1 ->
// first item accessed is indStart + 0, last element
// accessed is indStart + nInter - 1
assert(indStart + nInter - 1 < nGridPoints);
interpolate(val, position, indStart);
return 1;
}
template<Utils::DerivativeOrder O>
void SKPair::interpolate(InterpolationValues<O>& val, double x, int start) const {
/*
* Taken from Numerical recipes
* Adapted to treat simultaneously the different orbitals
*/
double dift, dif = x - start;
int ns = 0; // index of closest table entry
for (int L = 0; L < nIntegrals; L++) {
for (int i = 0; i < nInter; i++) {
val.ya[L][i] = integralTable[integralIndexes[L]][start + i];
val.C[L][i] = constant1D<O>(integralTable[integralIndexes[L]][start + i]);
val.D[L][i] = constant1D<O>(integralTable[integralIndexes[L]][start + i]);
}
}
for (int i = 0; i < nInter; i++) {
val.xa[i] = static_cast<double>(start + i);
if ((dift = std::abs(x - val.xa[i])) < dif) {
dif = dift;
ns = i;
}
}
for (int L = 0; L < nIntegrals; L++) {
val.derivIntegral[L] = constant1D<O>(val.ya[L][ns]);
}
ns--;
Value1DType<O> w, den;
double ho, hp;
for (int m = 1; m < nInter; m++) {
for (int i = 0; i <= nInter - 1 - m; i++) {
ho = val.xa[i] - x;
hp = val.xa[i + m] - x;
for (int L = 0; L < nIntegrals; L++) {
w = val.C[L][i + 1] - val.D[L][i];
den = w / (ho - hp);
val.D[L][i] = getFromFull<O>(hp, -1.0 / gridDist, 0) * den;
val.C[L][i] = getFromFull<O>(ho, -1.0 / gridDist, 0) * den;
}
}
for (int L = 0; L < nIntegrals; L++) {
val.derivIntegral[L] += (2 * (ns + 1) < (nInter - m)) ? val.C[L][ns + 1] : val.D[L][ns];
}
if (!(2 * (ns + 1) < (nInter - m)))
ns--;
}
}
template int SKPair::getHS<Utils::DerivativeOrder::Zero>(double, InterpolationValues<Utils::DerivativeOrder::Zero>&) const;
template int SKPair::getHS<Utils::DerivativeOrder::One>(double, InterpolationValues<Utils::DerivativeOrder::One>&) const;
template int SKPair::getHS<Utils::DerivativeOrder::Two>(double, InterpolationValues<Utils::DerivativeOrder::Two>&) const;
template int SKPair::getHSIntegral<Utils::DerivativeOrder::Zero>(InterpolationValues<Utils::DerivativeOrder::Zero>&, double) const;
template int SKPair::getHSIntegral<Utils::DerivativeOrder::One>(InterpolationValues<Utils::DerivativeOrder::One>&, double) const;
template int SKPair::getHSIntegral<Utils::DerivativeOrder::Two>(InterpolationValues<Utils::DerivativeOrder::Two>&, double) const;
template void SKPair::interpolate<Utils::DerivativeOrder::Zero>(InterpolationValues<Utils::DerivativeOrder::Zero>&,
double, int) const;
template void SKPair::interpolate<Utils::DerivativeOrder::One>(InterpolationValues<Utils::DerivativeOrder::One>&,
double, int) const;
template void SKPair::interpolate<Utils::DerivativeOrder::Two>(InterpolationValues<Utils::DerivativeOrder::Two>&,
double, int) const;
template double SKPair::getRepulsion<Utils::DerivativeOrder::Zero>(double const& r) const;
template First1D SKPair::getRepulsion<Utils::DerivativeOrder::One>(double const& r) const;
template Second1D SKPair::getRepulsion<Utils::DerivativeOrder::Two>(double const& r) const;
} // namespace dftb
} // namespace Sparrow
} // namespace Scine
| 39.439739
| 131
| 0.631318
|
qcscine
|
7f33db92718d0e225f767b59142b526a75fdc42c
| 605
|
cpp
|
C++
|
tests/unit/appc/util/test_option.cpp
|
cdaylward/libappc
|
4f7316b584d92a110198a3f1573c170e5492194c
|
[
"Apache-2.0"
] | 63
|
2015-01-20T18:35:27.000Z
|
2021-11-16T10:53:40.000Z
|
tests/unit/appc/util/test_option.cpp
|
Manu343726/libappc
|
8d181ef4ee80c8f1bcbf6ca04cf66e04e5e5bc8a
|
[
"Apache-2.0"
] | 5
|
2015-01-20T17:28:54.000Z
|
2015-02-09T17:36:54.000Z
|
tests/unit/appc/util/test_option.cpp
|
cdaylward/libappc
|
4f7316b584d92a110198a3f1573c170e5492194c
|
[
"Apache-2.0"
] | 12
|
2015-01-26T04:37:08.000Z
|
2020-11-14T02:19:13.000Z
|
#include "gtest/gtest.h"
#include "appc/util/option.h"
TEST(Option, none_is_false) {
auto none = None<int>();
ASSERT_FALSE(none);
}
TEST(Option, some_is_true) {
auto some = Some(std::string{""});
ASSERT_TRUE(some);
}
TEST(Option, some_is_shared_ptr) {
auto some = Some(std::string(""));
std::shared_ptr<std::string> ptr = some;
ASSERT_EQ(2, ptr.use_count());
}
TEST(Option, some_dereferences) {
auto some = Some(std::string("one"));
ASSERT_EQ(typeid(std::string), typeid(*some));
ASSERT_EQ(typeid(std::string), typeid(from_some(some)));
ASSERT_EQ(std::string{"one"}, *some);
}
| 21.607143
| 58
| 0.669421
|
cdaylward
|
7f34132ef268ccb61428758f166ec384c7d0ad3d
| 14,400
|
cc
|
C++
|
chrome/browser/ui/views/page_info/permission_selector_row.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chrome/browser/ui/views/page_info/permission_selector_row.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chrome/browser/ui/views/page_info/permission_selector_row.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/page_info/permission_selector_row.h"
#include "base/i18n/rtl.h"
#include "base/macros.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/page_info/page_info_ui.h"
#include "chrome/browser/ui/page_info/permission_menu_model.h"
#include "chrome/browser/ui/views/harmony/chrome_typography.h"
#include "chrome/browser/ui/views/page_info/non_accessible_image_view.h"
#include "chrome/browser/ui/views/page_info/page_info_bubble_view.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/material_design/material_design_controller.h"
#include "ui/base/models/combobox_model.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/combobox/combobox_listener.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace internal {
// The |PermissionMenuButton| provides a menu for selecting a setting a
// permissions type.
class PermissionMenuButton : public views::MenuButton,
public views::MenuButtonListener {
public:
// Creates a new |PermissionMenuButton| with the passed |text|. The ownership
// of the |model| remains with the caller and is not transfered to the
// |PermissionMenuButton|. If the |show_menu_marker| flag is true, then a
// small icon is be displayed next to the button |text|, indicating that the
// button opens a drop down menu.
PermissionMenuButton(const base::string16& text,
PermissionMenuModel* model,
bool show_menu_marker);
~PermissionMenuButton() override;
// Overridden from views::View.
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void OnNativeThemeChanged(const ui::NativeTheme* theme) override;
private:
// Overridden from views::MenuButtonListener.
void OnMenuButtonClicked(views::MenuButton* source,
const gfx::Point& point,
const ui::Event* event) override;
PermissionMenuModel* menu_model_; // Owned by |PermissionSelectorRow|.
std::unique_ptr<views::MenuRunner> menu_runner_;
bool is_rtl_display_;
DISALLOW_COPY_AND_ASSIGN(PermissionMenuButton);
};
///////////////////////////////////////////////////////////////////////////////
// PermissionMenuButton
///////////////////////////////////////////////////////////////////////////////
PermissionMenuButton::PermissionMenuButton(const base::string16& text,
PermissionMenuModel* model,
bool show_menu_marker)
: MenuButton(text, this, show_menu_marker), menu_model_(model) {
// Since PermissionMenuButtons are added to a GridLayout, they are not always
// sized to their preferred size. Disclosure arrows are always right-aligned,
// so if the text is not right-aligned, awkward space appears between the text
// and the arrow.
SetHorizontalAlignment(gfx::ALIGN_RIGHT);
// Update the themed border before the NativeTheme is applied. Usually this
// happens in a call to LabelButton::OnNativeThemeChanged(). However, if
// PermissionMenuButton called that from its override, the NativeTheme would
// be available, and the button would get native GTK styling on Linux.
UpdateThemedBorder();
SetFocusForPlatform();
set_request_focus_on_press(true);
is_rtl_display_ =
base::i18n::RIGHT_TO_LEFT == base::i18n::GetStringDirection(text);
}
PermissionMenuButton::~PermissionMenuButton() {}
void PermissionMenuButton::GetAccessibleNodeData(ui::AXNodeData* node_data) {
MenuButton::GetAccessibleNodeData(node_data);
node_data->SetValue(GetText());
}
void PermissionMenuButton::OnNativeThemeChanged(const ui::NativeTheme* theme) {
SetTextColor(
views::Button::STATE_NORMAL,
theme->GetSystemColor(ui::NativeTheme::kColorId_LabelEnabledColor));
SetTextColor(
views::Button::STATE_HOVERED,
theme->GetSystemColor(ui::NativeTheme::kColorId_LabelEnabledColor));
SetTextColor(
views::Button::STATE_DISABLED,
theme->GetSystemColor(ui::NativeTheme::kColorId_LabelDisabledColor));
}
void PermissionMenuButton::OnMenuButtonClicked(views::MenuButton* source,
const gfx::Point& point,
const ui::Event* event) {
menu_runner_.reset(
new views::MenuRunner(menu_model_, views::MenuRunner::HAS_MNEMONICS));
gfx::Point p(point);
p.Offset(is_rtl_display_ ? source->width() : -source->width(), 0);
menu_runner_->RunMenuAt(source->GetWidget()->GetTopLevelWidget(), this,
gfx::Rect(p, gfx::Size()), views::MENU_ANCHOR_TOPLEFT,
ui::MENU_SOURCE_NONE);
}
// This class adapts a |PermissionMenuModel| into a |ui::ComboboxModel| so that
// |PermissionCombobox| can use it.
class ComboboxModelAdapter : public ui::ComboboxModel {
public:
explicit ComboboxModelAdapter(PermissionMenuModel* model) : model_(model) {}
~ComboboxModelAdapter() override {}
void OnPerformAction(int index);
// Returns the checked index of the underlying PermissionMenuModel, of which
// there must be exactly one. This is used to choose which index is selected
// in the PermissionCombobox.
int GetCheckedIndex();
// ui::ComboboxModel:
int GetItemCount() const override;
base::string16 GetItemAt(int index) override;
private:
PermissionMenuModel* model_;
};
void ComboboxModelAdapter::OnPerformAction(int index) {
model_->ExecuteCommand(index, 0);
}
int ComboboxModelAdapter::GetCheckedIndex() {
int checked_index = -1;
for (int i = 0; i < model_->GetItemCount(); ++i) {
if (model_->IsCommandIdChecked(i)) {
// This function keeps track of |checked_index| instead of returning early
// here so that it can DCHECK that there's exactly one selected item,
// which is not normally guaranteed by MenuModel, but *is* true of
// PermissionMenuModel.
DCHECK_EQ(checked_index, -1);
checked_index = i;
}
}
return checked_index;
}
int ComboboxModelAdapter::GetItemCount() const {
DCHECK(model_);
return model_->GetItemCount();
}
base::string16 ComboboxModelAdapter::GetItemAt(int index) {
return model_->GetLabelAt(index);
}
// The |PermissionCombobox| provides a combobox for selecting a permission type.
// This is only used on platforms where the permission dialog uses a combobox
// instead of a MenuButton (currently, Mac).
class PermissionCombobox : public views::Combobox,
public views::ComboboxListener {
public:
PermissionCombobox(ComboboxModelAdapter* model,
bool enabled,
bool use_default);
~PermissionCombobox() override;
void UpdateSelectedIndex(bool use_default);
private:
// views::Combobox:
void OnPaintBorder(gfx::Canvas* canvas) override;
// views::ComboboxListener:
void OnPerformAction(Combobox* combobox) override;
ComboboxModelAdapter* model_;
};
PermissionCombobox::PermissionCombobox(ComboboxModelAdapter* model,
bool enabled,
bool use_default)
: views::Combobox(model), model_(model) {
set_listener(this);
SetEnabled(enabled);
UpdateSelectedIndex(use_default);
if (ui::MaterialDesignController::IsSecondaryUiMaterial()) {
set_size_to_largest_label(false);
ModelChanged();
}
}
PermissionCombobox::~PermissionCombobox() {}
void PermissionCombobox::UpdateSelectedIndex(bool use_default) {
int index = model_->GetCheckedIndex();
if (use_default && index == -1) {
index = 0;
}
SetSelectedIndex(index);
}
void PermissionCombobox::OnPaintBorder(gfx::Canvas* canvas) {
// No border except a focus indicator for MD mode.
if (ui::MaterialDesignController::IsSecondaryUiMaterial() && !HasFocus()) {
return;
}
Combobox::OnPaintBorder(canvas);
}
void PermissionCombobox::OnPerformAction(Combobox* combobox) {
model_->OnPerformAction(combobox->selected_index());
}
} // namespace internal
///////////////////////////////////////////////////////////////////////////////
// PermissionSelectorRow
///////////////////////////////////////////////////////////////////////////////
PermissionSelectorRow::PermissionSelectorRow(
Profile* profile,
const GURL& url,
const PageInfoUI::PermissionInfo& permission,
views::GridLayout* layout)
: profile_(profile), icon_(NULL), menu_button_(NULL), combobox_(NULL) {
// Create the permission icon.
icon_ = new NonAccessibleImageView();
const gfx::Image& image = PageInfoUI::GetPermissionIcon(permission);
icon_->SetImage(image.ToImageSkia());
layout->AddView(icon_, 1, 1, views::GridLayout::CENTER,
views::GridLayout::CENTER);
// Create the label that displays the permission type.
label_ =
new views::Label(PageInfoUI::PermissionTypeToUIString(permission.type),
CONTEXT_BODY_TEXT_LARGE);
layout->AddView(label_, 1, 1, views::GridLayout::LEADING,
views::GridLayout::CENTER);
// Create the menu model.
menu_model_.reset(new PermissionMenuModel(
profile, url, permission,
base::Bind(&PermissionSelectorRow::PermissionChanged,
base::Unretained(this))));
// Create the permission menu button.
#if defined(OS_MACOSX)
bool use_real_combobox = true;
#else
bool use_real_combobox =
ui::MaterialDesignController::IsSecondaryUiMaterial();
#endif
if (use_real_combobox) {
InitializeComboboxView(layout, permission);
} else {
InitializeMenuButtonView(layout, permission);
}
// Show the permission decision reason, if it was not the user.
base::string16 reason =
PageInfoUI::PermissionDecisionReasonToUIString(profile, permission, url);
if (!reason.empty()) {
layout->StartRow(1, 1);
layout->SkipColumns(1);
views::Label* permission_decision_reason = new views::Label(reason);
permission_decision_reason->SetEnabledColor(
PageInfoUI::GetPermissionDecisionTextColor());
// Long labels should span the remaining width of the row.
views::ColumnSet* column_set = layout->GetColumnSet(1);
DCHECK(column_set);
layout->AddView(permission_decision_reason, column_set->num_columns() - 2,
1, views::GridLayout::LEADING, views::GridLayout::CENTER);
}
}
void PermissionSelectorRow::AddObserver(
PermissionSelectorRowObserver* observer) {
observer_list_.AddObserver(observer);
}
PermissionSelectorRow::~PermissionSelectorRow() {
// Gross. On paper the Combobox and the ComboboxModelAdapter are both owned by
// this class, but actually, the Combobox is owned by View and will be
// destroyed in ~View(), which runs *after* ~PermissionSelectorRow() is done,
// which means the Combobox gets destroyed after its ComboboxModel, which
// causes an explosion when the Combobox attempts to stop observing the
// ComboboxModel. This hack ensures the Combobox is deleted before its
// ComboboxModel.
//
// Technically, the MenuButton has the same problem, but MenuButton doesn't
// use its model in its destructor.
if (combobox_) {
combobox_->parent()->RemoveChildView(combobox_);
}
}
void PermissionSelectorRow::InitializeMenuButtonView(
views::GridLayout* layout,
const PageInfoUI::PermissionInfo& permission) {
bool button_enabled =
permission.source == content_settings::SETTING_SOURCE_USER;
menu_button_ = new internal::PermissionMenuButton(
PageInfoUI::PermissionActionToUIString(
profile_, permission.type, permission.setting,
permission.default_setting, permission.source),
menu_model_.get(), button_enabled);
menu_button_->SetEnabled(button_enabled);
menu_button_->SetAccessibleName(
PageInfoUI::PermissionTypeToUIString(permission.type));
layout->AddView(menu_button_);
}
void PermissionSelectorRow::InitializeComboboxView(
views::GridLayout* layout,
const PageInfoUI::PermissionInfo& permission) {
bool button_enabled =
permission.source == content_settings::SETTING_SOURCE_USER;
combobox_model_adapter_.reset(
new internal::ComboboxModelAdapter(menu_model_.get()));
combobox_ = new internal::PermissionCombobox(combobox_model_adapter_.get(),
button_enabled, true);
combobox_->SetEnabled(button_enabled);
combobox_->SetAccessibleName(
PageInfoUI::PermissionTypeToUIString(permission.type));
layout->AddView(combobox_);
}
void PermissionSelectorRow::PermissionChanged(
const PageInfoUI::PermissionInfo& permission) {
// Change the permission icon to reflect the selected setting.
const gfx::Image& image = PageInfoUI::GetPermissionIcon(permission);
icon_->SetImage(image.ToImageSkia());
// Update the menu button text to reflect the new setting.
if (menu_button_) {
menu_button_->SetText(PageInfoUI::PermissionActionToUIString(
profile_, permission.type, permission.setting,
permission.default_setting, content_settings::SETTING_SOURCE_USER));
menu_button_->SizeToPreferredSize();
// Re-layout will be done at the |PageInfoBubbleView| level, since
// that view may need to resize itself to accomodate the new sizes of its
// contents.
menu_button_->InvalidateLayout();
} else if (combobox_) {
bool use_default = permission.setting == CONTENT_SETTING_DEFAULT;
combobox_->UpdateSelectedIndex(use_default);
}
for (PermissionSelectorRowObserver& observer : observer_list_) {
observer.OnPermissionChanged(permission);
}
}
views::View* PermissionSelectorRow::button() {
// These casts are required because the two arms of a ?: cannot have different
// types T1 and T2, even if the resulting value of the ?: is about to be a T
// and T1 and T2 are both subtypes of T.
return menu_button_ ? static_cast<views::View*>(menu_button_)
: static_cast<views::View*>(combobox_);
}
| 38.4
| 80
| 0.702083
|
metux
|
7f344ec08e017dcdf3c41926a1d07bd06a239b8b
| 757
|
hpp
|
C++
|
bia/memory/gc/root.hpp
|
bialang/bia
|
b54fff096b4fe91ddb0b1d509ea828daa11cee7e
|
[
"BSD-3-Clause"
] | 2
|
2017-09-09T17:03:18.000Z
|
2018-03-02T20:02:02.000Z
|
bia/memory/gc/root.hpp
|
terrakuh/Bia
|
412b7e8aeb259f4925c3b588f6025760a43cd0b7
|
[
"BSD-3-Clause"
] | 7
|
2018-10-11T18:14:19.000Z
|
2018-12-26T15:31:04.000Z
|
bia/memory/gc/root.hpp
|
terrakuh/Bia
|
412b7e8aeb259f4925c3b588f6025760a43cd0b7
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef BIA_MEMORY_GC_ROOT_HPP_
#define BIA_MEMORY_GC_ROOT_HPP_
#include <bia/util/gsl.hpp>
#include <cstddef>
#include <memory>
#include <mutex>
namespace bia {
namespace memory {
namespace gc {
class GC;
/// Defines the root for the search tree for the marking phase during garbage collection. This class is not
/// thread-safe.
class Root
{
public:
Root(const Root& copy) = delete;
~Root() noexcept;
void* at(std::size_t index);
void put(std::size_t index, void* ptr);
Root& operator=(const Root& copy) = delete;
private:
friend GC;
typedef util::Span<void**> Data;
GC* _parent = nullptr;
Data _data;
std::mutex _mutex;
Root(GC* parent, std::size_t size) noexcept;
};
} // namespace gc
} // namespace memory
} // namespace bia
#endif
| 18.02381
| 107
| 0.712021
|
bialang
|
7f379093ec9f642f9797b97b5696ef29a2f9e7dc
| 469
|
hpp
|
C++
|
archive/stan/src/stan/model/standalone_functions_header.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
archive/stan/src/stan/model/standalone_functions_header.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
archive/stan/src/stan/model/standalone_functions_header.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_MODEL_STANDALONE_FUNCTIONS_HEADER_HPP
#define STAN_MODEL_STANDALONE_FUNCTIONS_HEADER_HPP
#include <stan/math.hpp>
#include <boost/random/additive_combine.hpp>
#include <stan/io/program_reader.hpp>
#include <stan/lang/rethrow_located.hpp>
#include <stan/model/indexing.hpp>
#include <cmath>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <utility>
#include <vector>
#endif
| 22.333333
| 51
| 0.763326
|
alashworth
|
7f3ebfb97f2fa4678666afd5f2133eaaafbea074
| 1,762
|
cc
|
C++
|
thirdparty/jplayer/thirdparty/libde265/libde265/encoder/algo/tb-rateestim.cc
|
Houkime/echo
|
d115ca55faf3a140bea04feffeb2efdedb0e7f82
|
[
"MIT"
] | 675
|
2019-02-07T01:23:19.000Z
|
2022-03-28T05:45:10.000Z
|
thirdparty/jplayer/thirdparty/libde265/libde265/encoder/algo/tb-rateestim.cc
|
Houkime/echo
|
d115ca55faf3a140bea04feffeb2efdedb0e7f82
|
[
"MIT"
] | 843
|
2019-01-25T01:06:46.000Z
|
2022-03-16T11:15:53.000Z
|
thirdparty/jplayer/thirdparty/libde265/libde265/encoder/algo/tb-rateestim.cc
|
Houkime/echo
|
d115ca55faf3a140bea04feffeb2efdedb0e7f82
|
[
"MIT"
] | 83
|
2019-02-20T06:18:46.000Z
|
2022-03-20T09:36:09.000Z
|
/*
* H.265 video codec.
* Copyright (c) 2013-2014 struktur AG, Dirk Farin <farin@struktur.de>
*
* Authors: struktur AG, Dirk Farin <farin@struktur.de>
*
* This file is part of libde265.
*
* libde265 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* libde265 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with libde265. If not, see <http://www.gnu.org/licenses/>.
*/
#include "libde265/encoder/algo/tb-rateestim.h"
#include "libde265/encoder/encoder-syntax.h"
#include <assert.h>
#include <iostream>
float Algo_TB_RateEstimation_Exact::encode_transform_unit(encoder_context* ectx,
context_model_table& ctxModel,
const enc_tb* tb, const enc_cb* cb,
int x0,int y0, int xBase,int yBase,
int log2TrafoSize, int trafoDepth,
int blkIdx)
{
CABAC_encoder_estim estim;
estim.set_context_models(&ctxModel);
leaf(cb, NULL);
::encode_transform_unit(ectx, &estim, tb,cb, x0,y0, xBase,yBase,
log2TrafoSize, trafoDepth, blkIdx);
return estim.getRDBits();
}
| 37.489362
| 93
| 0.613507
|
Houkime
|
7f470ee74bb40907b5c8a97d042ed1ee216e9aef
| 74,059
|
cc
|
C++
|
lullaby/systems/render/next/render_system_next.cc
|
jjzhang166/lullaby
|
d9b11ea811cb5869b46165b9b9537b6063c6cbae
|
[
"Apache-2.0"
] | null | null | null |
lullaby/systems/render/next/render_system_next.cc
|
jjzhang166/lullaby
|
d9b11ea811cb5869b46165b9b9537b6063c6cbae
|
[
"Apache-2.0"
] | null | null | null |
lullaby/systems/render/next/render_system_next.cc
|
jjzhang166/lullaby
|
d9b11ea811cb5869b46165b9b9537b6063c6cbae
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2017 Google Inc. 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.
*/
#include "lullaby/systems/render/next/render_system_next.h"
#include <inttypes.h>
#include <stdio.h>
#include "fplbase/glplatform.h"
#include "fplbase/internal/type_conversions_gl.h"
#include "fplbase/render_utils.h"
#include "lullaby/events/render_events.h"
#include "lullaby/modules/config/config.h"
#include "lullaby/modules/dispatcher/dispatcher.h"
#include "lullaby/modules/ecs/entity_factory.h"
#include "lullaby/modules/file/file.h"
#include "lullaby/modules/flatbuffers/mathfu_fb_conversions.h"
#include "lullaby/modules/render/mesh_util.h"
#include "lullaby/modules/render/triangle_mesh.h"
#include "lullaby/modules/script/function_binder.h"
#include "lullaby/systems/dispatcher/dispatcher_system.h"
#include "lullaby/systems/dispatcher/event.h"
#include "lullaby/systems/render/detail/profiler.h"
#include "lullaby/systems/render/next/render_state.h"
#include "lullaby/systems/render/render_stats.h"
#include "lullaby/systems/render/simple_font.h"
#include "lullaby/util/logging.h"
#include "lullaby/util/make_unique.h"
#include "lullaby/util/math.h"
#include "lullaby/util/trace.h"
#include "lullaby/generated/render_def_generated.h"
namespace lull {
namespace {
constexpr int kInitialRenderPoolSize = 512;
const HashValue kRenderDefHash = Hash("RenderDef");
const RenderSystemNext::RenderComponentID kDefaultRenderId = 0;
constexpr int kNumVec4sInAffineTransform = 3;
constexpr const char* kColorUniform = "color";
constexpr const char* kTextureBoundsUniform = "uv_bounds";
constexpr const char* kClampBoundsUniform = "clamp_bounds";
constexpr const char* kBoneTransformsUniform = "bone_transforms";
// We break the naming convention here for compatibility with early VR apps.
constexpr const char* kIsRightEyeUniform = "uIsRightEye";
template <typename T>
void RemoveFromVector(std::vector<T>* vector, const T& value) {
if (!vector) {
return;
}
for (auto it = vector->cbegin(); it != vector->cend(); ++it) {
if (*it == value) {
vector->erase(it);
return;
}
}
}
bool IsSupportedUniformDimension(int dimension) {
return (dimension == 1 || dimension == 2 || dimension == 3 ||
dimension == 4 || dimension == 16);
}
void SetDebugUniform(Shader* shader, const char* name, const float values[4]) {
const fplbase::UniformHandle location = shader->FindUniform(name);
if (fplbase::ValidUniformHandle(location)) {
shader->SetUniform(location, values, 4);
}
}
void DrawDynamicMesh(const MeshData* mesh) {
const fplbase::Mesh::Primitive prim =
Mesh::GetFplPrimitiveType(mesh->GetPrimitiveType());
const VertexFormat& vertex_format = mesh->GetVertexFormat();
const uint32_t vertex_size =
static_cast<uint32_t>(vertex_format.GetVertexSize());
fplbase::Attribute fpl_attribs[Mesh::kMaxFplAttributeArraySize];
Mesh::GetFplAttributes(vertex_format, fpl_attribs);
if (mesh->GetNumIndices() > 0) {
fplbase::RenderArray(prim, static_cast<int>(mesh->GetNumIndices()),
fpl_attribs, vertex_size, mesh->GetVertexBytes(),
mesh->GetIndexData());
} else {
fplbase::RenderArray(prim, mesh->GetNumVertices(), fpl_attribs, vertex_size,
mesh->GetVertexBytes());
}
}
fplbase::RenderTargetTextureFormat RenderTargetTextureFormatToFpl(
TextureFormat format) {
switch (format) {
case TextureFormat_A8:
return fplbase::kRenderTargetTextureFormatA8;
break;
case TextureFormat_R8:
return fplbase::kRenderTargetTextureFormatR8;
break;
case TextureFormat_RGB8:
return fplbase::kRenderTargetTextureFormatRGB8;
break;
case TextureFormat_RGBA8:
return fplbase::kRenderTargetTextureFormatRGBA8;
break;
default:
LOG(DFATAL) << "Unknown render target texture format.";
return fplbase::kRenderTargetTextureFormatCount;
}
}
fplbase::DepthStencilFormat DepthStencilFormatToFpl(DepthStencilFormat format) {
switch (format) {
case DepthStencilFormat_None:
return fplbase::kDepthStencilFormatNone;
break;
case DepthStencilFormat_Depth16:
return fplbase::kDepthStencilFormatDepth16;
break;
case DepthStencilFormat_Depth24:
return fplbase::kDepthStencilFormatDepth24;
break;
case DepthStencilFormat_Depth32F:
return fplbase::kDepthStencilFormatDepth32F;
break;
case DepthStencilFormat_Depth24Stencil8:
return fplbase::kDepthStencilFormatDepth24Stencil8;
break;
case DepthStencilFormat_Depth32FStencil8:
return fplbase::kDepthStencilFormatDepth32FStencil8;
break;
case DepthStencilFormat_Stencil8:
return fplbase::kDepthStencilFormatStencil8;
break;
default:
LOG(DFATAL) << "Unknown depth stencil format.";
return fplbase::kDepthStencilFormatCount;
}
}
void UpdateUniformBinding(Uniform::Description* desc, const ShaderPtr& shader) {
if (!desc) {
return;
}
if (shader) {
const Shader::UniformHnd handle = shader->FindUniform(desc->name.c_str());
if (fplbase::ValidUniformHandle(handle)) {
desc->binding = fplbase::GlUniformHandle(handle);
return;
}
}
desc->binding = -1;
}
} // namespace
RenderSystemNext::RenderSystemNext(Registry* registry)
: System(registry),
components_(kInitialRenderPoolSize),
sort_order_manager_(registry_) {
renderer_.Initialize(mathfu::kZeros2i, "lull::RenderSystem");
factory_ = registry->Create<RenderFactory>(registry, &renderer_);
registry_->Get<Dispatcher>()->Connect(
this,
[this](const ParentChangedEvent& event) { OnParentChanged(event); });
FunctionBinder* binder = registry->Get<FunctionBinder>();
if (binder) {
binder->RegisterMethod("lull.Render.Show", &lull::RenderSystem::Show);
binder->RegisterMethod("lull.Render.Hide", &lull::RenderSystem::Hide);
binder->RegisterFunction("lull.Render.GetTextureId", [this](Entity entity) {
TexturePtr texture = GetTexture(entity, 0);
return texture ? static_cast<int>(texture->GetResourceId().handle) : 0;
});
}
}
RenderSystemNext::~RenderSystemNext() {
FunctionBinder* binder = registry_->Get<FunctionBinder>();
if (binder) {
binder->UnregisterFunction("lull.Render.Show");
binder->UnregisterFunction("lull.Render.Hide");
binder->UnregisterFunction("lull.Render.GetTextureId");
}
registry_->Get<Dispatcher>()->DisconnectAll(this);
}
void RenderSystemNext::Initialize() {
InitDefaultRenderPasses();
}
void RenderSystemNext::SetStereoMultiviewEnabled(bool enabled) {
multiview_enabled_ = enabled;
}
void RenderSystemNext::PreloadFont(const char* name) {
LOG(FATAL) << "Deprecated.";
}
FontPtr RenderSystemNext::LoadFonts(const std::vector<std::string>& names) {
LOG(FATAL) << "Deprecated.";
return nullptr;
}
const TexturePtr& RenderSystemNext::GetWhiteTexture() const {
return factory_->GetWhiteTexture();
}
const TexturePtr& RenderSystemNext::GetInvalidTexture() const {
return factory_->GetInvalidTexture();
}
TexturePtr RenderSystemNext::LoadTexture(const std::string& filename,
bool create_mips) {
return factory_->LoadTexture(filename, create_mips);
}
TexturePtr RenderSystemNext::GetTexture(HashValue texture_hash) const {
return factory_->GetCachedTexture(texture_hash);
}
void RenderSystemNext::LoadTextureAtlas(const std::string& filename) {
const bool create_mips = false;
factory_->LoadTextureAtlas(filename, create_mips);
}
MeshPtr RenderSystemNext::LoadMesh(const std::string& filename) {
return factory_->LoadMesh(filename);
}
ShaderPtr RenderSystemNext::LoadShader(const std::string& filename) {
return factory_->LoadShader(filename);
}
void RenderSystemNext::Create(Entity e, HashValue component_id,
HashValue pass) {
const EntityIdPair entity_id_pair(e, component_id);
RenderComponent* component = components_.Emplace(entity_id_pair);
if (!component) {
LOG(DFATAL) << "RenderComponent for Entity " << e << " with id "
<< component_id << " already exists.";
return;
}
entity_ids_[e].push_back(entity_id_pair);
component->pass = pass;
SetSortOrderOffset(e, 0);
}
void RenderSystemNext::Create(Entity e, HashValue pass) {
Create(e, kDefaultRenderId, pass);
}
void RenderSystemNext::Create(Entity e, HashValue type, const Def* def) {
if (type != kRenderDefHash) {
LOG(DFATAL) << "Invalid type passed to Create. Expecting RenderDef!";
return;
}
const RenderDef& data = *ConvertDef<RenderDef>(def);
if (data.font()) {
LOG(FATAL) << "Deprecated.";
}
const EntityIdPair entity_id_pair(e, data.id());
RenderComponent* component = components_.Emplace(entity_id_pair);
if (!component) {
LOG(DFATAL) << "RenderComponent for Entity " << e << " with id "
<< data.id() << " already exists.";
return;
}
entity_ids_[e].push_back(entity_id_pair);
if (data.pass() == RenderPass_Pano) {
component->pass = ConstHash("Pano");
} else if (data.pass() == RenderPass_Opaque) {
component->pass = ConstHash("Opaque");
} else if (data.pass() == RenderPass_Main) {
component->pass = ConstHash("Main");
} else if (data.pass() == RenderPass_OverDraw) {
component->pass = ConstHash("OverDraw");
} else if (data.pass() == RenderPass_Debug) {
component->pass = ConstHash("Debug");
} else if (data.pass() == RenderPass_Invisible) {
component->pass = ConstHash("Invisible");
} else if (data.pass() == RenderPass_OverDrawGlow) {
component->pass = ConstHash("OverDrawGlow");
}
component->hidden = data.hidden();
if (data.shader()) {
SetShader(e, data.id(), LoadShader(data.shader()->str()));
}
if (data.textures()) {
for (unsigned int i = 0; i < data.textures()->size(); ++i) {
TexturePtr texture =
factory_->LoadTexture(data.textures()->Get(i)->c_str(),
data.create_mips());
SetTexture(e, data.id(), i, texture);
}
} else if (data.texture() && data.texture()->size() > 0) {
TexturePtr texture =
factory_->LoadTexture(data.texture()->c_str(), data.create_mips());
SetTexture(e, data.id(), 0, texture);
} else if (data.external_texture()) {
#ifdef GL_TEXTURE_EXTERNAL_OES
GLuint texture_id;
GL_CALL(glGenTextures(1, &texture_id));
GL_CALL(glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture_id));
GL_CALL(glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE));
GL_CALL(glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE));
GL_CALL(glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER,
GL_NEAREST));
GL_CALL(glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER,
GL_NEAREST));
SetTextureId(e, data.id(), 0, GL_TEXTURE_EXTERNAL_OES, texture_id);
#else
LOG(WARNING) << "External textures are not available.";
#endif // GL_TEXTURE_EXTERNAL_OES
}
if (data.mesh()) {
SetMesh(e, data.id(), factory_->LoadMesh(data.mesh()->c_str()));
}
if (data.color()) {
mathfu::vec4 color;
MathfuVec4FromFbColor(data.color(), &color);
SetUniform(e, data.id(), kColorUniform, &color[0], 4, 1);
component->default_color = color;
} else if (data.color_hex()) {
mathfu::vec4 color;
MathfuVec4FromFbColorHex(data.color_hex()->c_str(), &color);
SetUniform(e, data.id(), kColorUniform, &color[0], 4, 1);
component->default_color = color;
}
if (data.uniforms()) {
for (const UniformDef* uniform : *data.uniforms()) {
if (!uniform->name() || !uniform->float_value()) {
LOG(DFATAL) << "Missing required uniform name or value";
continue;
}
if (uniform->dimension() <= 0) {
LOG(DFATAL) << "Uniform dimension must be positive: "
<< uniform->dimension();
continue;
}
if (uniform->count() <= 0) {
LOG(DFATAL) << "Uniform count must be positive: " << uniform->count();
continue;
}
if (uniform->float_value()->size() !=
static_cast<size_t>(uniform->dimension() * uniform->count())) {
LOG(DFATAL) << "Uniform must have dimension x count values: "
<< uniform->float_value()->size();
continue;
}
SetUniform(e, data.id(), uniform->name()->c_str(),
uniform->float_value()->data(), uniform->dimension(),
uniform->count());
}
}
SetSortOrderOffset(e, data.id(), data.sort_order_offset());
}
void RenderSystemNext::PostCreateInit(Entity e, HashValue type,
const Def* def) {
if (type == kRenderDefHash) {
auto& data = *ConvertDef<RenderDef>(def);
if (data.text()) {
LOG(FATAL) << "Deprecated.";
} else if (data.quad()) {
const QuadDef& quad_def = *data.quad();
Quad quad;
quad.size = mathfu::vec2(quad_def.size_x(), quad_def.size_y());
quad.verts = mathfu::vec2i(quad_def.verts_x(), quad_def.verts_y());
quad.has_uv = quad_def.has_uv();
quad.corner_radius = quad_def.corner_radius();
quad.corner_verts = quad_def.corner_verts();
if (data.shape_id()) {
quad.id = Hash(data.shape_id()->c_str());
}
SetQuad(e, data.id(), quad);
}
}
}
void RenderSystemNext::Destroy(Entity e) {
SetStencilMode(e, StencilMode::kDisabled, 0);
auto iter = entity_ids_.find(e);
if (iter != entity_ids_.end()) {
for (const EntityIdPair& entity_id_pair : iter->second) {
components_.Destroy(entity_id_pair);
}
entity_ids_.erase(iter);
}
deformations_.erase(e);
sort_order_manager_.Destroy(e);
}
void RenderSystemNext::Destroy(Entity e, HashValue component_id) {
const EntityIdPair entity_id_pair(e, component_id);
SetStencilMode(e, component_id, StencilMode::kDisabled, 0);
auto iter = entity_ids_.find(e);
if (iter != entity_ids_.end()) {
RemoveFromVector(&iter->second, entity_id_pair);
}
deformations_.erase(e);
sort_order_manager_.Destroy(entity_id_pair);
}
void RenderSystemNext::SetQuadImpl(Entity e, HashValue component_id,
const Quad& quad) {
if (quad.has_uv) {
SetMesh(e, component_id, CreateQuad<VertexPT>(e, component_id, quad));
} else {
SetMesh(e, component_id, CreateQuad<VertexP>(e, component_id, quad));
}
}
void RenderSystemNext::CreateDeferredMeshes() {
while (!deferred_meshes_.empty()) {
DeferredMesh& defer = deferred_meshes_.front();
switch (defer.type) {
case DeferredMesh::kQuad:
SetQuadImpl(defer.entity_id_pair.entity, defer.entity_id_pair.id,
defer.quad);
break;
case DeferredMesh::kMesh:
DeformMesh(defer.entity_id_pair.entity, defer.entity_id_pair.id,
&defer.mesh);
SetMesh(defer.entity_id_pair.entity, defer.entity_id_pair.id,
defer.mesh);
break;
}
deferred_meshes_.pop();
}
}
void RenderSystemNext::ProcessTasks() {
LULLABY_CPU_TRACE_CALL();
CreateDeferredMeshes();
factory_->UpdateAssetLoad();
}
void RenderSystemNext::WaitForAssetsToLoad() {
CreateDeferredMeshes();
factory_->WaitForAssetsToLoad();
}
const mathfu::vec4& RenderSystemNext::GetDefaultColor(Entity entity) const {
const RenderComponent* component = components_.Get(entity);
if (component) {
return component->default_color;
}
return mathfu::kOnes4f;
}
void RenderSystemNext::SetDefaultColor(Entity entity,
const mathfu::vec4& color) {
RenderComponent* component = components_.Get(entity);
if (component) {
component->default_color = color;
}
}
bool RenderSystemNext::GetColor(Entity entity, mathfu::vec4* color) const {
return GetUniform(entity, kColorUniform, 4, &(*color)[0]);
}
void RenderSystemNext::SetColor(Entity entity, const mathfu::vec4& color) {
SetUniform(entity, kColorUniform, &color[0], 4, 1);
}
void RenderSystemNext::SetUniform(Entity e, const char* name, const float* data,
int dimension, int count) {
SetUniform(e, kDefaultRenderId, name, data, dimension, count);
}
void RenderSystemNext::SetUniform(Entity e, HashValue component_id,
const char* name, const float* data,
int dimension, int count) {
if (!IsSupportedUniformDimension(dimension)) {
LOG(DFATAL) << "Unsupported uniform dimension " << dimension;
return;
}
const EntityIdPair entity_id_pair(e, component_id);
auto* render_component = components_.Get(entity_id_pair);
if (!render_component || !render_component->material.GetShader()) {
return;
}
const size_t num_bytes = dimension * count * sizeof(float);
Uniform* uniform = render_component->material.GetUniformByName(name);
if (!uniform || uniform->GetDescription().num_bytes != num_bytes) {
Uniform::Description desc(
name, (dimension > 4) ? Uniform::Type::kMatrix : Uniform::Type::kFloats,
num_bytes, count);
if (!uniform) {
render_component->material.AddUniform(desc);
} else {
render_component->material.UpdateUniform(desc);
}
}
render_component->material.SetUniformByName(name, data, dimension * count);
uniform = render_component->material.GetUniformByName(name);
if (uniform && uniform->GetDescription().binding == -1) {
UpdateUniformBinding(&uniform->GetDescription(),
render_component->material.GetShader());
}
}
bool RenderSystemNext::GetUniform(Entity e, const char* name, size_t length,
float* data_out) const {
return GetUniform(e, kDefaultRenderId, name, length, data_out);
}
bool RenderSystemNext::GetUniform(Entity e, HashValue component_id,
const char* name, size_t length,
float* data_out) const {
const EntityIdPair entity_id_pair(e, component_id);
auto* render_component = components_.Get(entity_id_pair);
if (!render_component) {
return false;
}
const Uniform* uniform = render_component->material.GetUniformByName(name);
if (!uniform) {
return false;
}
const Uniform::Description& desc = uniform->GetDescription();
// Length is the number of floats expected. Convert it into size in bytes.
const size_t expected_bytes = length * sizeof(float);
if (expected_bytes < desc.num_bytes) {
return false;
}
memcpy(data_out, uniform->GetData<float>(), sizeof(float) * length);
return true;
}
void RenderSystemNext::CopyUniforms(Entity entity, Entity source) {
RenderComponent* component = components_.Get(entity);
if (!component) {
return;
}
component->material.ClearUniforms();
const RenderComponent* source_component = components_.Get(source);
if (source_component) {
const UniformVector& uniforms = source_component->material.GetUniforms();
for (auto& uniform : uniforms) {
component->material.AddUniform(uniform);
}
if (component->material.GetShader() !=
source_component->material.GetShader()) {
// Fix the locations using |entity|'s shader.
UpdateUniformLocations(component);
}
}
}
void RenderSystemNext::UpdateUniformLocations(RenderComponent* component) {
if (!component->material.GetShader()) {
return;
}
auto& uniforms = component->material.GetUniforms();
for (Uniform& uniform : uniforms) {
UpdateUniformBinding(&uniform.GetDescription(),
component->material.GetShader());
}
}
int RenderSystemNext::GetNumBones(Entity entity) const {
const RenderComponent* component = components_.Get(entity);
if (!component || !component->mesh) {
return 0;
}
return component->mesh->GetNumBones();
}
const uint8_t* RenderSystemNext::GetBoneParents(Entity e, int* num) const {
auto* render_component = components_.Get(e);
if (!render_component || !render_component->mesh) {
if (num) {
*num = 0;
}
return nullptr;
}
return render_component->mesh->GetBoneParents(num);
}
const std::string* RenderSystemNext::GetBoneNames(Entity e, int* num) const {
auto* render_component = components_.Get(e);
if (!render_component || !render_component->mesh) {
if (num) {
*num = 0;
}
return nullptr;
}
return render_component->mesh->GetBoneNames(num);
}
const mathfu::AffineTransform*
RenderSystemNext::GetDefaultBoneTransformInverses(Entity e, int* num) const {
auto* render_component = components_.Get(e);
if (!render_component || !render_component->mesh) {
if (num) {
*num = 0;
}
return nullptr;
}
return render_component->mesh->GetDefaultBoneTransformInverses(num);
}
void RenderSystemNext::SetBoneTransforms(
Entity entity, const mathfu::AffineTransform* transforms,
int num_transforms) {
RenderComponent* component = components_.Get(entity);
if (!component || !component->mesh) {
return;
}
const int num_shader_bones = component->mesh->GetNumShaderBones();
shader_transforms_.resize(num_shader_bones);
if (num_transforms != component->mesh->GetNumBones()) {
LOG(DFATAL) << "Mesh must have " << num_transforms << " bones.";
return;
}
component->mesh->GatherShaderTransforms(transforms,
shader_transforms_.data());
// GLES2 only supports square matrices, so send the affine transforms as an
// array of 3 * num_transforms vec4s.
const float* data = &(shader_transforms_[0][0]);
const int dimension = 4;
const int count = kNumVec4sInAffineTransform * num_shader_bones;
SetUniform(entity, kBoneTransformsUniform, data, dimension, count);
}
void RenderSystemNext::OnTextureLoaded(const RenderComponent& component,
int unit, const TexturePtr& texture) {
const Entity entity = component.GetEntity();
const mathfu::vec4 clamp_bounds = texture->CalculateClampBounds();
SetUniform(entity, kClampBoundsUniform, &clamp_bounds[0], 4, 1);
if (factory_->IsTextureValid(texture)) {
// TODO(b/38130323) Add CheckTextureSizeWarning that does not depend on HMD.
auto* dispatcher_system = registry_->Get<DispatcherSystem>();
if (dispatcher_system) {
dispatcher_system->Send(entity, TextureReadyEvent(entity, unit));
if (IsReadyToRenderImpl(component)) {
dispatcher_system->Send(entity, ReadyToRenderEvent(entity));
}
}
}
}
void RenderSystemNext::SetTexture(Entity e, int unit,
const TexturePtr& texture) {
SetTexture(e, kDefaultRenderId, unit, texture);
}
void RenderSystemNext::SetTexture(Entity e, HashValue component_id, int unit,
const TexturePtr& texture) {
const EntityIdPair entity_id_pair(e, component_id);
auto* render_component = components_.Get(entity_id_pair);
if (!render_component) {
return;
}
render_component->material.SetTexture(unit, texture);
max_texture_unit_ = std::max(max_texture_unit_, unit);
// Add subtexture coordinates so the vertex shaders will pick them up. These
// are known when the texture is created; no need to wait for load.
SetUniform(e, component_id, kTextureBoundsUniform, &texture->UvBounds()[0], 4,
1);
if (texture->IsLoaded()) {
OnTextureLoaded(*render_component, unit, texture);
} else {
texture->AddOnLoadCallback([this, unit, entity_id_pair, texture]() {
RenderComponent* render_component = components_.Get(entity_id_pair);
if (render_component &&
render_component->material.GetTexture(unit) == texture) {
OnTextureLoaded(*render_component, unit, texture);
}
});
}
}
TexturePtr RenderSystemNext::CreateProcessedTexture(
const TexturePtr& source_texture, bool create_mips,
RenderSystem::TextureProcessor processor) {
return factory_->CreateProcessedTexture(source_texture, create_mips,
processor);
}
TexturePtr RenderSystemNext::CreateProcessedTexture(
const TexturePtr& source_texture, bool create_mips,
const RenderSystem::TextureProcessor& processor,
const mathfu::vec2i& output_dimensions) {
return factory_->CreateProcessedTexture(source_texture, create_mips,
processor, output_dimensions);
}
void RenderSystemNext::SetTextureId(Entity e, int unit, uint32_t texture_target,
uint32_t texture_id) {
SetTextureId(e, kDefaultRenderId, unit, texture_target, texture_id);
}
void RenderSystemNext::SetTextureId(Entity e, HashValue component_id, int unit,
uint32_t texture_target,
uint32_t texture_id) {
const EntityIdPair entity_id_pair(e, component_id);
auto* render_component = components_.Get(entity_id_pair);
if (!render_component) {
return;
}
auto texture = factory_->CreateTexture(texture_target, texture_id);
SetTexture(e, component_id, unit, texture);
}
TexturePtr RenderSystemNext::GetTexture(Entity entity, int unit) const {
const auto* render_component = components_.Get(entity);
if (!render_component) {
return TexturePtr();
}
return render_component->material.GetTexture(unit);
}
void RenderSystemNext::SetPano(Entity entity, const std::string& filename,
float heading_offset_deg) {
LOG(FATAL) << "Deprecated.";
}
void RenderSystemNext::SetText(Entity e, const std::string& text) {
LOG(FATAL) << "Deprecated.";
}
void RenderSystemNext::SetFont(Entity entity, const FontPtr& font) {
LOG(FATAL) << "Deprecated.";
}
void RenderSystemNext::SetTextSize(Entity entity, int size) {
LOG(FATAL) << "Deprecated.";
}
const std::vector<LinkTag>* RenderSystemNext::GetLinkTags(Entity e) const {
LOG(FATAL) << "Deprecated.";
return nullptr;
}
const std::vector<mathfu::vec3>* RenderSystemNext::GetCaretPositions(
Entity e) const {
LOG(FATAL) << "Deprecated.";
return nullptr;
}
bool RenderSystemNext::GetQuad(Entity e, Quad* quad) const {
const auto* render_component = components_.Get(e);
if (!render_component) {
return false;
}
*quad = render_component->quad;
return true;
}
void RenderSystemNext::SetQuad(Entity e, const Quad& quad) {
SetQuad(e, kDefaultRenderId, quad);
}
void RenderSystemNext::SetQuad(Entity e, HashValue component_id,
const Quad& quad) {
const EntityIdPair entity_id_pair(e, component_id);
auto* render_component = components_.Get(entity_id_pair);
if (!render_component) {
LOG(WARNING) << "Missing entity for SetQuad: " << entity_id_pair.entity
<< ", with id: " << entity_id_pair.id;
return;
}
render_component->quad = quad;
auto iter = deformations_.find(entity_id_pair);
if (iter != deformations_.end()) {
DeferredMesh defer;
defer.entity_id_pair = entity_id_pair;
defer.type = DeferredMesh::kQuad;
defer.quad = quad;
deferred_meshes_.push(std::move(defer));
} else {
SetQuadImpl(e, component_id, quad);
}
}
void RenderSystemNext::SetMesh(Entity e, const TriangleMesh<VertexPT>& mesh) {
SetMesh(e, kDefaultRenderId, mesh);
}
void RenderSystemNext::SetMesh(Entity e, HashValue component_id,
const TriangleMesh<VertexPT>& mesh) {
SetMesh(e, component_id, factory_->CreateMesh(mesh));
}
void RenderSystemNext::SetAndDeformMesh(Entity entity,
const TriangleMesh<VertexPT>& mesh) {
SetAndDeformMesh(entity, kDefaultRenderId, mesh);
}
void RenderSystemNext::SetAndDeformMesh(Entity entity, HashValue component_id,
const TriangleMesh<VertexPT>& mesh) {
const EntityIdPair entity_id_pair(entity, component_id);
auto iter = deformations_.find(entity_id_pair);
if (iter != deformations_.end()) {
DeferredMesh defer;
defer.entity_id_pair = entity_id_pair;
defer.type = DeferredMesh::kMesh;
defer.mesh.GetVertices() = mesh.GetVertices();
defer.mesh.GetIndices() = mesh.GetIndices();
deferred_meshes_.emplace(std::move(defer));
} else {
SetMesh(entity, component_id, mesh);
}
}
void RenderSystemNext::SetMesh(Entity e, const MeshData& mesh) {
SetMesh(e, factory_->CreateMesh(mesh));
}
void RenderSystemNext::SetMesh(Entity e, const std::string& file) {
SetMesh(e, factory_->LoadMesh(file));
}
RenderSystemNext::SortOrderOffset RenderSystemNext::GetSortOrderOffset(
Entity entity) const {
return sort_order_manager_.GetOffset(entity);
}
void RenderSystemNext::SetSortOrderOffset(Entity e,
SortOrderOffset sort_order_offset) {
SetSortOrderOffset(e, kDefaultRenderId, sort_order_offset);
}
void RenderSystemNext::SetSortOrderOffset(Entity e, HashValue component_id,
SortOrderOffset sort_order_offset) {
const EntityIdPair entity_id_pair(e, component_id);
sort_order_manager_.SetOffset(entity_id_pair, sort_order_offset);
sort_order_manager_.UpdateSortOrder(entity_id_pair,
[this](EntityIdPair entity_id_pair) {
return components_.Get(entity_id_pair);
});
}
bool RenderSystemNext::IsTextureSet(Entity e, int unit) const {
auto* render_component = components_.Get(e);
if (!render_component) {
return false;
}
return render_component->material.GetTexture(unit) != nullptr;
}
bool RenderSystemNext::IsTextureLoaded(Entity e, int unit) const {
const auto* render_component = components_.Get(e);
if (!render_component) {
return false;
}
if (!render_component->material.GetTexture(unit)) {
return false;
}
return render_component->material.GetTexture(unit)->IsLoaded();
}
bool RenderSystemNext::IsTextureLoaded(const TexturePtr& texture) const {
return texture->IsLoaded();
}
bool RenderSystemNext::IsReadyToRender(Entity entity) const {
const auto* render_component = components_.Get(entity);
if (!render_component) {
// No component, no textures, no fonts, no problem.
return true;
}
return IsReadyToRenderImpl(*render_component);
}
bool RenderSystemNext::IsReadyToRenderImpl(
const RenderComponent& component) const {
const auto& textures = component.material.GetTextures();
for (const auto& pair : textures) {
const TexturePtr& texture = pair.second;
if (!texture->IsLoaded() || !factory_->IsTextureValid(texture)) {
return false;
}
}
return true;
}
bool RenderSystemNext::IsHidden(Entity e) const {
const auto* render_component = components_.Get(e);
const bool render_component_hidden =
render_component && render_component->hidden;
// If there are no models associated with this entity, then it is hidden.
// Otherwise, it is hidden if the RenderComponent is hidden.
return (render_component_hidden || !render_component);
}
ShaderPtr RenderSystemNext::GetShader(Entity entity,
HashValue component_id) const {
const EntityIdPair entity_id_pair(entity, component_id);
const RenderComponent* component = components_.Get(entity_id_pair);
return component ? component->material.GetShader() : ShaderPtr();
}
ShaderPtr RenderSystemNext::GetShader(Entity entity) const {
const RenderComponent* component = components_.Get(entity);
return component ? component->material.GetShader() : ShaderPtr();
}
void RenderSystemNext::SetShader(Entity e, const ShaderPtr& shader) {
SetShader(e, kDefaultRenderId, shader);
}
void RenderSystemNext::SetShader(Entity e, HashValue component_id,
const ShaderPtr& shader) {
const EntityIdPair entity_id_pair(e, component_id);
auto* render_component = components_.Get(entity_id_pair);
if (!render_component) {
return;
}
render_component->material.SetShader(shader);
// Update the uniforms' locations in the new shader.
UpdateUniformLocations(render_component);
}
void RenderSystemNext::SetMesh(Entity e, MeshPtr mesh) {
SetMesh(e, kDefaultRenderId, mesh);
}
void RenderSystemNext::SetMesh(Entity e, HashValue component_id,
const MeshPtr& mesh) {
const EntityIdPair entity_id_pair(e, component_id);
auto* render_component = components_.Get(entity_id_pair);
if (!render_component) {
LOG(WARNING) << "Missing RenderComponent, "
<< "skipping mesh update for entity: " << e
<< ", with id: " << component_id;
return;
}
render_component->mesh = std::move(mesh);
if (render_component->mesh) {
auto& transform_system = *registry_->Get<TransformSystem>();
transform_system.SetAabb(e, render_component->mesh->GetAabb());
const int num_shader_bones = render_component->mesh->GetNumShaderBones();
if (num_shader_bones > 0) {
const mathfu::AffineTransform identity =
mathfu::mat4::ToAffineTransform(mathfu::mat4::Identity());
shader_transforms_.clear();
shader_transforms_.resize(num_shader_bones, identity);
const float* data = &(shader_transforms_[0][0]);
const int dimension = 4;
const int count = kNumVec4sInAffineTransform * num_shader_bones;
SetUniform(e, component_id, kBoneTransformsUniform, data, dimension,
count);
}
}
}
MeshPtr RenderSystemNext::GetMesh(Entity e, HashValue component_id) {
const EntityIdPair entity_id_pair(e, component_id);
auto* render_component = components_.Get(entity_id_pair);
if (!render_component) {
LOG(WARNING) << "Missing RenderComponent for entity: " << e
<< ", with id: " << component_id;
return nullptr;
}
return render_component->mesh;
}
template <typename Vertex>
void RenderSystemNext::DeformMesh(Entity entity, HashValue component_id,
TriangleMesh<Vertex>* mesh) {
const EntityIdPair entity_id_pair(entity, component_id);
auto iter = deformations_.find(entity_id_pair);
const Deformation deform =
iter != deformations_.end() ? iter->second : nullptr;
if (deform) {
// TODO(b/28313614) Use TriangleMesh::ApplyDeformation.
if (sizeof(Vertex) % sizeof(float) == 0) {
const int stride = static_cast<int>(sizeof(Vertex) / sizeof(float));
std::vector<Vertex>& vertices = mesh->GetVertices();
deform(reinterpret_cast<float*>(vertices.data()),
vertices.size() * stride, stride);
} else {
LOG(ERROR) << "Tried to deform an unsupported vertex format.";
}
}
}
template <typename Vertex>
MeshPtr RenderSystemNext::CreateQuad(Entity e, HashValue component_id,
const Quad& quad) {
if (quad.size.x == 0 || quad.size.y == 0) {
return nullptr;
}
TriangleMesh<Vertex> mesh;
mesh.SetQuad(quad.size.x, quad.size.y, quad.verts.x, quad.verts.y,
quad.corner_radius, quad.corner_verts, quad.corner_mask);
DeformMesh<Vertex>(e, component_id, &mesh);
if (quad.id != 0) {
return factory_->CreateMesh(quad.id, mesh);
} else {
return factory_->CreateMesh(mesh);
}
}
void RenderSystemNext::SetStencilMode(Entity e, StencilMode mode, int value) {
SetStencilMode(e, kDefaultRenderId, mode, value);
}
void RenderSystemNext::SetStencilMode(Entity e, HashValue component_id,
StencilMode mode, int value) {
const EntityIdPair entity_id_pair(e, component_id);
auto* render_component = components_.Get(entity_id_pair);
if (!render_component || render_component->stencil_mode == mode) {
return;
}
render_component->stencil_mode = mode;
render_component->stencil_value = value;
}
void RenderSystemNext::SetDeformationFunction(Entity e,
const Deformation& deform) {
if (deform) {
deformations_.emplace(e, deform);
} else {
deformations_.erase(e);
}
}
void RenderSystemNext::Hide(Entity e) {
auto* render_component = components_.Get(e);
if (render_component && !render_component->hidden) {
render_component->hidden = true;
SendEvent(registry_, e, HiddenEvent(e));
}
}
void RenderSystemNext::Show(Entity e) {
auto* render_component = components_.Get(e);
if (render_component && render_component->hidden) {
render_component->hidden = false;
SendEvent(registry_, e, UnhiddenEvent(e));
}
}
HashValue RenderSystemNext::GetRenderPass(Entity entity) const {
const RenderComponent* component = components_.Get(entity);
return component ? component->pass : 0;
}
void RenderSystemNext::SetRenderPass(Entity e, HashValue pass) {
RenderComponent* render_component = components_.Get(e);
if (render_component) {
render_component->pass = pass;
}
}
RenderSystem::SortMode RenderSystemNext::GetSortMode(HashValue pass) const {
const auto it = pass_definitions_.find(pass);
return (it != pass_definitions_.cend()) ? it->second.sort_mode
: SortMode::kNone;
}
void RenderSystemNext::SetSortMode(HashValue pass, SortMode mode) {
pass_definitions_[pass].sort_mode = mode;
}
RenderSystem::CullMode RenderSystemNext::GetCullMode(HashValue pass) {
const auto it = pass_definitions_.find(pass);
return (it != pass_definitions_.cend()) ? it->second.cull_mode
: CullMode::kNone;
}
void RenderSystemNext::SetCullMode(HashValue pass, CullMode mode) {
pass_definitions_[pass].cull_mode = mode;
}
void RenderSystemNext::SetRenderState(HashValue pass,
const fplbase::RenderState& state) {
pass_definitions_[pass].render_state = state;
}
const fplbase::RenderState* RenderSystemNext::GetRenderState(
HashValue pass) const {
const auto& it = pass_definitions_.find(pass);
if (it == pass_definitions_.end()) {
return nullptr;
}
return &it->second.render_state;
}
void RenderSystemNext::SetDepthTest(const bool enabled) {
if (enabled) {
#if !ION_PRODUCTION
// GL_DEPTH_BITS was deprecated in desktop GL 3.3, so make sure this get
// succeeds before checking depth_bits.
GLint depth_bits = 0;
glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
if (glGetError() == 0 && depth_bits == 0) {
// This has been known to cause problems on iOS 10.
LOG_ONCE(WARNING) << "Enabling depth test without a depth buffer; this "
"has known issues on some platforms.";
}
#endif // !ION_PRODUCTION
renderer_.SetDepthFunction(fplbase::kDepthFunctionLess);
return;
}
renderer_.SetDepthFunction(fplbase::kDepthFunctionDisabled);
}
void RenderSystemNext::SetDepthWrite(const bool enabled) {
renderer_.SetDepthWrite(enabled);
}
void RenderSystemNext::SetViewport(const View& view) {
LULLABY_CPU_TRACE_CALL();
renderer_.SetViewport(fplbase::Viewport(view.viewport, view.dimensions));
}
void RenderSystemNext::SetClipFromModelMatrix(const mathfu::mat4& mvp) {
renderer_.set_model_view_projection(mvp);
}
void RenderSystemNext::BindStencilMode(StencilMode mode, int ref) {
// Stencil mask setting all the bits to be 1.
static const fplbase::StencilMask kStencilMaskAllBits = ~0;
switch (mode) {
case StencilMode::kDisabled:
renderer_.SetStencilMode(fplbase::kStencilDisabled, ref,
kStencilMaskAllBits);
break;
case StencilMode::kTest:
renderer_.SetStencilMode(fplbase::kStencilCompareEqual, ref,
kStencilMaskAllBits);
break;
case StencilMode::kWrite:
renderer_.SetStencilMode(fplbase::kStencilWrite, ref,
kStencilMaskAllBits);
break;
}
}
void RenderSystemNext::BindVertexArray(uint32_t ref) {
// VAOs are part of the GLES3 & GL3 specs.
if (renderer_.feature_level() == fplbase::kFeatureLevel30) {
#if GL_ES_VERSION_3_0 || defined(GL_VERSION_3_0)
GL_CALL(glBindVertexArray(ref));
#endif
return;
}
// VAOs were available prior to GLES3 using an extension.
#if GL_OES_vertex_array_object
#ifndef GL_GLEXT_PROTOTYPES
static PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES = []() {
return (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress(
"glBindVertexArrayOES");
};
if (glBindVertexArrayOES) {
GL_CALL(glBindVertexArrayOES(ref));
}
#else // GL_GLEXT_PROTOTYPES
GL_CALL(glBindVertexArrayOES(ref));
#endif // !GL_GLEXT_PROTOTYPES
#endif // GL_OES_vertex_array_object
}
void RenderSystemNext::ClearSamplers() {
if (renderer_.feature_level() != fplbase::kFeatureLevel30) {
return;
}
// Samplers are part of GLES3 & GL3.3 specs.
#if GL_ES_VERSION_3_0 || defined(GL_VERSION_3_3)
for (int i = 0; i <= max_texture_unit_; ++i) {
// Confusingly, glBindSampler takes an index, not the raw texture unit
// (GL_TEXTURE0 + index).
GL_CALL(glBindSampler(i, 0));
}
#endif // GL_ES_VERSION_3_0 || GL_VERSION_3_3
}
void RenderSystemNext::ResetState() {
const fplbase::RenderState& render_state = renderer_.GetRenderState();
// Clear render state.
SetBlendMode(fplbase::kBlendModeOff);
renderer_.SetCulling(fplbase::kCullingModeBack);
SetDepthTest(true);
GL_CALL(glEnable(GL_DEPTH_TEST));
renderer_.ScissorOff();
GL_CALL(glDisable(GL_STENCIL_TEST));
GL_CALL(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE));
GL_CALL(
glDepthMask(render_state.depth_state.write_enabled ? GL_TRUE : GL_FALSE));
GL_CALL(glStencilMask(~0));
GL_CALL(glFrontFace(GL_CCW));
GL_CALL(glPolygonOffset(0, 0));
// Clear sampler objects, since FPL doesn't use them.
ClearSamplers();
// Clear VAO since it overrides VBOs.
BindVertexArray(0);
// Clear attributes, though we can leave position.
GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeNormal));
GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeTangent));
GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeTexCoord));
GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeTexCoordAlt));
GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeColor));
GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeBoneIndices));
GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeBoneWeights));
shader_.reset();
}
void RenderSystemNext::SetBlendMode(fplbase::BlendMode blend_mode) {
renderer_.SetBlendMode(blend_mode);
blend_mode_ = blend_mode;
}
mathfu::vec4 RenderSystemNext::GetClearColor() const {
return clear_color_;
}
void RenderSystemNext::SetClearColor(float r, float g, float b, float a) {
clear_color_ = mathfu::vec4(r, g, b, a);
}
void RenderSystemNext::SubmitRenderData() {
RenderData* data = render_data_buffer_.LockWriteBuffer();
if (!data) {
return;
}
data->clear();
const auto* transform_system = registry_->Get<TransformSystem>();
components_.ForEach([&](RenderComponent& render_component) {
if (render_component.hidden) {
return;
}
if (render_component.pass == 0) {
return;
}
const Entity entity = render_component.GetEntity();
if (entity == kNullEntity) {
return;
}
const mathfu::mat4* world_from_entity_matrix =
transform_system->GetWorldFromEntityMatrix(entity);
if (world_from_entity_matrix == nullptr ||
!transform_system->IsEnabled(entity)) {
return;
}
RenderObject render_obj;
render_obj.mesh = render_component.mesh;
render_obj.material = render_component.material;
render_obj.sort_order = render_component.sort_order;
render_obj.stencil_mode = render_component.stencil_mode;
render_obj.stencil_value = render_component.stencil_value;
render_obj.world_from_entity_matrix = *world_from_entity_matrix;
RenderPassAndObjects& entry = (*data)[render_component.pass];
entry.render_objects.emplace_back(std::move(render_obj));
});
for (auto& iter : *data) {
const RenderPassDefinition& pass = pass_definitions_[iter.first];
iter.second.pass_definition = pass;
// Sort only objects with "static" sort order, such as explicit sort order
// or absolute z-position.
if (IsSortModeViewIndependent(pass.sort_mode)) {
SortObjects(&iter.second.render_objects, pass.sort_mode);
}
}
render_data_buffer_.UnlockWriteBuffer();
}
void RenderSystemNext::BeginRendering() {
LULLABY_CPU_TRACE_CALL();
GL_CALL(glClearColor(clear_color_.x, clear_color_.y, clear_color_.z,
clear_color_.w));
GL_CALL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT));
// Retrieve the (current) default frame buffer.
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &default_frame_buffer_);
active_render_data_ = render_data_buffer_.LockReadBuffer();
}
void RenderSystemNext::EndRendering() {
GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0));
GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
render_data_buffer_.UnlockReadBuffer();
active_render_data_ = nullptr;
default_frame_buffer_ = 0;
}
void RenderSystemNext::SetViewUniforms(const View& view) {
renderer_.set_camera_pos(view.world_from_eye_matrix.TranslationVector3D());
rendering_right_eye_ = view.eye == 1;
}
void RenderSystemNext::RenderAt(const RenderObject* component,
const mathfu::mat4& world_from_entity_matrix,
const View& view) {
LULLABY_CPU_TRACE_CALL();
const ShaderPtr& shader = component->material.GetShader();
if (!shader || !component->mesh) {
return;
}
const mathfu::mat4 clip_from_entity_matrix =
view.clip_from_world_matrix * world_from_entity_matrix;
renderer_.set_model_view_projection(clip_from_entity_matrix);
renderer_.set_model(world_from_entity_matrix);
BindShader(shader);
SetShaderUniforms(component->material.GetUniforms());
const Shader::UniformHnd mat_normal_uniform_handle =
shader->FindUniform("mat_normal");
if (fplbase::ValidUniformHandle(mat_normal_uniform_handle)) {
const int uniform_gl = fplbase::GlUniformHandle(mat_normal_uniform_handle);
// Compute the normal matrix. This is the transposed matrix of the inversed
// world position. This is done to avoid non-uniform scaling of the normal.
// A good explanation of this can be found here:
// http://www.lighthouse3d.com/tutorials/glsl-12-tutorial/the-normal-matrix/
const mathfu::mat3 normal_matrix =
ComputeNormalMatrix(world_from_entity_matrix);
mathfu::vec3_packed packed[3];
normal_matrix.Pack(packed);
GL_CALL(glUniformMatrix3fv(uniform_gl, 1, false, packed[0].data));
}
const Shader::UniformHnd camera_dir_handle =
shader->FindUniform("camera_dir");
if (fplbase::ValidUniformHandle(camera_dir_handle)) {
const int uniform_gl = fplbase::GlUniformHandle(camera_dir_handle);
mathfu::vec3_packed camera_dir;
CalculateCameraDirection(view.world_from_eye_matrix).Pack(&camera_dir);
GL_CALL(glUniform3fv(uniform_gl, 1, camera_dir.data));
}
const auto& textures = component->material.GetTextures();
for (const auto& texture : textures) {
texture.second->Bind(texture.first);
}
// Bit of magic to determine if the scalar is negative and if so flip the cull
// face. This possibly be revised (b/38235916).
CorrectFrontFaceFromMatrix(world_from_entity_matrix);
BindStencilMode(component->stencil_mode, component->stencil_value);
DrawMeshFromComponent(component);
}
void RenderSystemNext::RenderAtMultiview(
const RenderObject* component, const mathfu::mat4& world_from_entity_matrix,
const View* views) {
LULLABY_CPU_TRACE_CALL();
const ShaderPtr& shader = component->material.GetShader();
if (!shader || !component->mesh) {
return;
}
const mathfu::mat4 clip_from_entity_matrix[] = {
views[0].clip_from_world_matrix * world_from_entity_matrix,
views[1].clip_from_world_matrix * world_from_entity_matrix,
};
renderer_.set_model(world_from_entity_matrix);
BindShader(shader);
SetShaderUniforms(component->material.GetUniforms());
const Shader::UniformHnd mvp_uniform_handle =
shader->FindUniform("model_view_projection");
if (fplbase::ValidUniformHandle(mvp_uniform_handle)) {
const int uniform_gl = fplbase::GlUniformHandle(mvp_uniform_handle);
GL_CALL(glUniformMatrix4fv(uniform_gl, 2, false,
&(clip_from_entity_matrix[0][0])));
}
const Shader::UniformHnd mat_normal_uniform_handle =
shader->FindUniform("mat_normal");
if (fplbase::ValidUniformHandle(mat_normal_uniform_handle)) {
const int uniform_gl = fplbase::GlUniformHandle(mat_normal_uniform_handle);
const mathfu::mat3 normal_matrix =
ComputeNormalMatrix(world_from_entity_matrix);
mathfu::VectorPacked<float, 3> packed[3];
normal_matrix.Pack(packed);
GL_CALL(glUniformMatrix3fv(uniform_gl, 1, false, packed[0].data));
}
const Shader::UniformHnd camera_dir_handle =
shader->FindUniform("camera_dir");
if (fplbase::ValidUniformHandle(camera_dir_handle)) {
const int uniform_gl = fplbase::GlUniformHandle(camera_dir_handle);
mathfu::vec3_packed camera_dir[2];
for (size_t i = 0; i < 2; ++i) {
CalculateCameraDirection(views[i].world_from_eye_matrix)
.Pack(&camera_dir[i]);
}
GL_CALL(glUniform3fv(uniform_gl, 2, camera_dir[0].data));
}
const auto& textures = component->material.GetTextures();
for (const auto& texture : textures) {
texture.second->Bind(texture.first);
}
// Bit of magic to determine if the scalar is negative and if so flip the cull
// face. This possibly be revised (b/38235916).
CorrectFrontFaceFromMatrix(world_from_entity_matrix);
BindStencilMode(component->stencil_mode, component->stencil_value);
DrawMeshFromComponent(component);
}
void RenderSystemNext::SetShaderUniforms(const UniformVector& uniforms) {
for (const auto& uniform : uniforms) {
BindUniform(uniform);
}
}
void RenderSystemNext::DrawMeshFromComponent(const RenderObject* component) {
if (component->mesh) {
component->mesh->Render(&renderer_);
detail::Profiler* profiler = registry_->Get<detail::Profiler>();
if (profiler) {
profiler->RecordDraw(component->material.GetShader(),
component->mesh->GetNumVertices(),
component->mesh->GetNumTriangles());
}
}
}
void RenderSystemNext::RenderPanos(const View* views, size_t num_views) {
LOG(FATAL) << "Deprecated.";
}
void RenderSystemNext::Render(const View* views, size_t num_views) {
renderer_.BeginRendering();
ResetState();
known_state_ = true;
// assume a max of 2 views, one for each eye.
RenderView pano_views[2];
CHECK_LE(num_views, 2);
GenerateEyeCenteredViews({views, num_views}, pano_views);
Render(pano_views, num_views, ConstHash("Pano"));
Render(views, num_views, ConstHash("Opaque"));
Render(views, num_views, ConstHash("Main"));
Render(views, num_views, ConstHash("OverDraw"));
Render(views, num_views, ConstHash("OverDrawGlow"));
known_state_ = false;
renderer_.EndRendering();
}
void RenderSystemNext::Render(const View* views, size_t num_views,
HashValue pass) {
LULLABY_CPU_TRACE_CALL();
if (!active_render_data_) {
LOG(DFATAL) << "Render between BeginRendering() and EndRendering()!";
return;
}
auto iter = active_render_data_->find(pass);
if (iter == active_render_data_->end()) {
// No data associated with this pass.
return;
}
if (iter->second.render_objects.empty()) {
// No objects to render with this pass.
return;
}
if (!known_state_) {
renderer_.BeginRendering();
if (pass != 0) {
ResetState();
}
}
bool reset_state = true;
auto* config = registry_->Get<Config>();
if (config) {
static const HashValue kRenderResetStateHash =
Hash("lull.Render.ResetState");
reset_state = config->Get(kRenderResetStateHash, reset_state);
}
const RenderPassDefinition& pass_definition = iter->second.pass_definition;
// Set the render target, if needed.
if (pass_definition.render_target) {
pass_definition.render_target->SetAsRenderTarget();
}
// Prepare the pass.
renderer_.SetRenderState(pass_definition.render_state);
cached_render_state_ = pass_definition.render_state;
// Draw the elements.
if (pass == ConstHash("Debug")) {
RenderDebugStats(views, num_views);
} else {
RenderObjectList& objects = iter->second.render_objects;
if (!IsSortModeViewIndependent(pass_definition.sort_mode)) {
SortObjectsUsingView(&objects, pass_definition.sort_mode, views,
num_views);
}
RenderObjects(objects, views, num_views);
}
// Set the render target back to default, if needed.
if (pass_definition.render_target) {
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, default_frame_buffer_));
}
if (reset_state) {
static const fplbase::RenderState kDefaultRenderState;
renderer_.SetRenderState(kDefaultRenderState);
}
if (!known_state_) {
renderer_.EndRendering();
}
}
void RenderSystemNext::RenderObjects(const std::vector<RenderObject>& objects,
const View* views, size_t num_views) {
if (objects.empty()) {
return;
}
if (multiview_enabled_) {
SetViewport(views[0]);
SetViewUniforms(views[0]);
for (const RenderObject& obj : objects) {
RenderAtMultiview(&obj, obj.world_from_entity_matrix, views);
}
} else {
for (size_t i = 0; i < num_views; ++i) {
const View& view = views[i];
SetViewport(view);
SetViewUniforms(view);
for (const RenderObject& obj : objects) {
RenderAt(&obj, obj.world_from_entity_matrix, views[i]);
}
}
}
// Reset states that are set at the entity level in RenderAt.
BindStencilMode(StencilMode::kDisabled, 0);
GL_CALL(glFrontFace(GL_CCW));
}
void RenderSystemNext::BindShader(const ShaderPtr& shader) {
// Don't early exit if shader == shader_, since fplbase::Shader::Set also sets
// the common fpl uniforms.
shader_ = shader;
shader->Bind();
// Bind uniform describing whether or not we're rendering in the right eye.
// This uniform is an int due to legacy reasons, but there's no pipeline in
// FPL for setting int uniforms, so we have to make a direct gl call instead.
fplbase::UniformHandle uniform_is_right_eye =
shader->FindUniform(kIsRightEyeUniform);
if (fplbase::ValidUniformHandle(uniform_is_right_eye)) {
GL_CALL(glUniform1i(fplbase::GlUniformHandle(uniform_is_right_eye),
static_cast<int>(rendering_right_eye_)));
}
}
void RenderSystemNext::BindTexture(int unit, const TexturePtr& texture) {
texture->Bind(unit);
}
void RenderSystemNext::BindUniform(const char* name, const float* data,
int dimension) {
if (!IsSupportedUniformDimension(dimension)) {
LOG(DFATAL) << "Unsupported uniform dimension " << dimension;
return;
}
if (!shader_) {
LOG(DFATAL) << "Cannot bind uniform on unbound shader!";
return;
}
const fplbase::UniformHandle location = shader_->FindUniform(name);
if (fplbase::ValidUniformHandle(location)) {
shader_->SetUniform(location, data, dimension);
}
}
void RenderSystemNext::DrawPrimitives(PrimitiveType type,
const VertexFormat& format,
const void* vertex_data,
size_t num_vertices) {
const fplbase::Mesh::Primitive fpl_type = Mesh::GetFplPrimitiveType(type);
fplbase::Attribute attributes[Mesh::kMaxFplAttributeArraySize];
Mesh::GetFplAttributes(format, attributes);
fplbase::RenderArray(fpl_type, static_cast<int>(num_vertices), attributes,
static_cast<int>(format.GetVertexSize()), vertex_data);
}
void RenderSystemNext::DrawIndexedPrimitives(
PrimitiveType type, const VertexFormat& format, const void* vertex_data,
size_t num_vertices, const uint16_t* indices, size_t num_indices) {
const fplbase::Mesh::Primitive fpl_type = Mesh::GetFplPrimitiveType(type);
fplbase::Attribute attributes[Mesh::kMaxFplAttributeArraySize];
Mesh::GetFplAttributes(format, attributes);
fplbase::RenderArray(fpl_type, static_cast<int>(num_indices), attributes,
static_cast<int>(format.GetVertexSize()), vertex_data,
indices);
}
void RenderSystemNext::UpdateDynamicMesh(
Entity entity, PrimitiveType primitive_type,
const VertexFormat& vertex_format, const size_t max_vertices,
const size_t max_indices,
const std::function<void(MeshData*)>& update_mesh) {
RenderComponent* component = components_.Get(entity);
if (!component) {
return;
}
if (max_vertices > 0) {
DataContainer vertex_data = DataContainer::CreateHeapDataContainer(
max_vertices * vertex_format.GetVertexSize());
DataContainer index_data = DataContainer::CreateHeapDataContainer(
max_indices * sizeof(MeshData::Index));
MeshData data(primitive_type, vertex_format, std::move(vertex_data),
std::move(index_data));
update_mesh(&data);
component->mesh = factory_->CreateMesh(data);
} else {
component->mesh.reset();
}
}
void RenderSystemNext::RenderDebugStats(const View* views, size_t num_views) {
RenderStats* render_stats = registry_->Get<RenderStats>();
if (!render_stats || num_views == 0) {
return;
}
const bool stats_enabled =
render_stats->IsLayerEnabled(RenderStats::Layer::kRenderStats);
const bool fps_counter =
render_stats->IsLayerEnabled(RenderStats::Layer::kFpsCounter);
if (!stats_enabled && !fps_counter) {
return;
}
SimpleFont* font = render_stats->GetFont();
if (!font || !font->GetShader()) {
return;
}
// Calculate the position and size of the text from the projection matrix.
const bool is_perspective = views[0].clip_from_eye_matrix[15] == 0.0f;
const bool is_stereo = (num_views == 2 && is_perspective &&
views[1].clip_from_eye_matrix[15] == 0.0f);
mathfu::vec3 start_pos;
float font_size;
// TODO(b/29914331) Separate, tested matrix decomposition util functions.
if (is_perspective) {
const float kTopOfTextScreenScale = .45f;
const float kFontScreenScale = .075f;
const float z = -1.0f;
const float tan_half_fov = 1.0f / views[0].clip_from_eye_matrix[5];
font_size = .5f * kFontScreenScale * -z * tan_half_fov;
start_pos =
mathfu::vec3(-.5f, kTopOfTextScreenScale * -z * tan_half_fov, z);
} else {
const float kNearPlaneOffset = .0001f;
const float bottom = (-1.0f - views[0].clip_from_eye_matrix[13]) /
views[0].clip_from_eye_matrix[5];
const float top = bottom + 2.0f / views[0].clip_from_eye_matrix[5];
const float near_z = (1.0f + views[0].clip_from_eye_matrix[14]) /
views[0].clip_from_eye_matrix[10];
const int padding = 20;
font_size = 16;
start_pos =
mathfu::vec3(padding, top - padding, -(near_z - kNearPlaneOffset));
}
// Setup shared render state.
font->GetTexture()->Bind(0);
font->SetSize(font_size);
const float uv_bounds[4] = {0, 0, 1, 1};
SetDebugUniform(font->GetShader().get(), kTextureBoundsUniform, uv_bounds);
const float color[4] = {1, 1, 1, 1};
SetDebugUniform(font->GetShader().get(), kColorUniform, color);
SetDepthTest(false);
SetDepthWrite(false);
char buf[512] = "";
// Draw in each view.
for (size_t i = 0; i < num_views; ++i) {
SetViewport(views[i]);
SetViewUniforms(views[i]);
renderer_.set_model_view_projection(views[i].clip_from_eye_matrix);
BindShader(
font->GetShader()); // Shader needs to be bound after setting MVP.
mathfu::vec3 pos = start_pos;
if (is_stereo && i > 0) {
// Reposition text so that it's consistently placed in both eye views.
pos = views[i].world_from_eye_matrix.Inverse() *
(views[0].world_from_eye_matrix * start_pos);
}
SimpleFontRenderer text(font);
text.SetCursor(pos);
// Draw basic render stats.
const detail::Profiler* profiler = registry_->Get<detail::Profiler>();
if (profiler && stats_enabled) {
snprintf(buf, sizeof(buf),
"FPS %0.2f\n"
"CPU ms %0.2f\n"
"GPU ms %0.2f\n"
"# draws %d\n"
"# shader swaps %d\n"
"# verts %d\n"
"# tris %d",
profiler->GetFilteredFps(), profiler->GetCpuFrameMs(),
profiler->GetGpuFrameMs(), profiler->GetNumDraws(),
profiler->GetNumShaderSwaps(), profiler->GetNumVerts(),
profiler->GetNumTris());
text.Print(buf);
} else if (profiler) {
DCHECK(fps_counter);
snprintf(buf, sizeof(buf), "FPS %0.2f\n", profiler->GetFilteredFps());
text.Print(buf);
}
if (!text.GetMesh().IsEmpty()) {
const TriangleMesh<VertexPT>& mesh = text.GetMesh();
auto vertices = mesh.GetVertices();
auto indices = mesh.GetIndices();
DrawIndexedPrimitives(MeshData::PrimitiveType::kTriangles,
VertexPT::kFormat, vertices.data(), vertices.size(),
indices.data(), indices.size());
}
}
// Cleanup render state.
SetDepthTest(true);
SetDepthWrite(true);
}
void RenderSystemNext::OnParentChanged(const ParentChangedEvent& event) {
sort_order_manager_.UpdateSortOrder(
event.target,
[this](EntityIdPair entity) { return components_.Get(entity); });
}
const fplbase::RenderState& RenderSystemNext::GetRenderState() const {
return renderer_.GetRenderState();
}
void RenderSystemNext::UpdateCachedRenderState(
const fplbase::RenderState& render_state) {
renderer_.UpdateCachedRenderState(render_state);
}
bool RenderSystemNext::IsSortModeViewIndependent(SortMode mode) {
switch (mode) {
case SortMode::kAverageSpaceOriginBackToFront:
case SortMode::kAverageSpaceOriginFrontToBack:
return false;
default:
return true;
}
}
void RenderSystemNext::SortObjects(RenderObjectList* objects, SortMode mode) {
switch (mode) {
case SortMode::kNone:
// Do nothing.
break;
case SortMode::kSortOrderDecreasing:
std::sort(objects->begin(), objects->end(),
[](const RenderObject& a, const RenderObject& b) {
return a.sort_order > b.sort_order;
});
break;
case SortMode::kSortOrderIncreasing:
std::sort(objects->begin(), objects->end(),
[](const RenderObject& a, const RenderObject& b) {
return a.sort_order < b.sort_order;
});
break;
case SortMode::kWorldSpaceZBackToFront:
std::sort(objects->begin(), objects->end(),
[](const RenderObject& a, const RenderObject& b) {
return a.world_from_entity_matrix.TranslationVector3D().z <
b.world_from_entity_matrix.TranslationVector3D().z;
});
break;
case SortMode::kWorldSpaceZFrontToBack:
std::sort(objects->begin(), objects->end(),
[](const RenderObject& a, const RenderObject& b) {
return a.world_from_entity_matrix.TranslationVector3D().z >
b.world_from_entity_matrix.TranslationVector3D().z;
});
break;
default:
LOG(DFATAL) << "SortObjects called with unsupported sort mode!";
break;
}
}
void RenderSystemNext::SortObjectsUsingView(RenderObjectList* objects,
SortMode mode, const View* views,
size_t num_views) {
// Get the average camera position.
if (num_views <= 0) {
LOG(DFATAL) << "Must have at least 1 view.";
return;
}
mathfu::vec3 avg_pos = mathfu::kZeros3f;
mathfu::vec3 avg_z(0, 0, 0);
for (size_t i = 0; i < num_views; ++i) {
avg_pos += views[i].world_from_eye_matrix.TranslationVector3D();
avg_z += GetMatrixColumn3D(views[i].world_from_eye_matrix, 2);
}
avg_pos /= static_cast<float>(num_views);
avg_z.Normalize();
// Give relative values to the elements.
for (RenderObject& obj : *objects) {
const mathfu::vec3 world_pos =
obj.world_from_entity_matrix.TranslationVector3D();
obj.z_sort_order = mathfu::vec3::DotProduct(world_pos - avg_pos, avg_z);
}
switch (mode) {
case SortMode::kAverageSpaceOriginBackToFront:
std::sort(objects->begin(), objects->end(),
[&](const RenderObject& a, const RenderObject& b) {
return a.z_sort_order < b.z_sort_order;
});
break;
case SortMode::kAverageSpaceOriginFrontToBack:
std::sort(objects->begin(), objects->end(),
[&](const RenderObject& a, const RenderObject& b) {
return a.z_sort_order > b.z_sort_order;
});
break;
default:
LOG(DFATAL)
<< "SortObjectsUsingView called with unsupported sort mode!";
break;
}
}
void RenderSystemNext::InitDefaultRenderPasses() {
fplbase::RenderState render_state;
// RenderPass_Pano. Premultiplied alpha blend state, everything else default.
render_state.blend_state.enabled = true;
render_state.blend_state.src_alpha = fplbase::BlendState::kOne;
render_state.blend_state.src_color = fplbase::BlendState::kOne;
render_state.blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha;
SetRenderState(ConstHash("Pano"), render_state);
// RenderPass_Opaque. Depth test and write on. BlendMode disabled, face cull
// mode back.
render_state.blend_state.enabled = false;
render_state.depth_state.test_enabled = true;
render_state.depth_state.write_enabled = true;
render_state.depth_state.function = fplbase::kRenderLessEqual;
render_state.cull_state.enabled = true;
render_state.cull_state.face = fplbase::CullState::kBack;
SetRenderState(ConstHash("Opaque"), render_state);
// RenderPass_Main. Depth test on, write off. Premultiplied alpha blend state,
// face cull mode back.
render_state.blend_state.enabled = true;
render_state.blend_state.src_alpha = fplbase::BlendState::kOne;
render_state.blend_state.src_color = fplbase::BlendState::kOne;
render_state.blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.depth_state.test_enabled = true;
render_state.depth_state.function = fplbase::kRenderLessEqual;
render_state.depth_state.write_enabled = false;
render_state.cull_state.enabled = true;
render_state.cull_state.face = fplbase::CullState::kBack;
SetRenderState(ConstHash("Main"), render_state);
// RenderPass_OverDraw. Depth test and write false, premultiplied alpha, back
// face culling.
render_state.depth_state.test_enabled = false;
render_state.depth_state.write_enabled = false;
render_state.blend_state.enabled = true;
render_state.blend_state.src_alpha = fplbase::BlendState::kOne;
render_state.blend_state.src_color = fplbase::BlendState::kOne;
render_state.blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.cull_state.enabled = true;
render_state.cull_state.face = fplbase::CullState::kBack;
SetRenderState(ConstHash("OverDraw"), render_state);
// RenderPass_OverDrawGlow. Depth test and write off, additive blend mode, no
// face culling.
render_state.depth_state.test_enabled = false;
render_state.depth_state.write_enabled = false;
render_state.blend_state.enabled = true;
render_state.blend_state.src_alpha = fplbase::BlendState::kOne;
render_state.blend_state.src_color = fplbase::BlendState::kOne;
render_state.blend_state.dst_alpha = fplbase::BlendState::kOne;
render_state.blend_state.dst_color = fplbase::BlendState::kOne;
render_state.cull_state.enabled = false;
SetRenderState(ConstHash("OverDrawGlow"), render_state);
SetSortMode(ConstHash("Opaque"), SortMode::kAverageSpaceOriginFrontToBack);
SetSortMode(ConstHash("Main"), SortMode::kSortOrderIncreasing);
}
void RenderSystemNext::SetRenderPass(const RenderPassDefT& data) {
const HashValue pass = Hash(data.name.c_str());
RenderPassDefinition& def = pass_definitions_[pass];
switch (data.sort_mode) {
case SortMode_None:
break;
case SortMode_SortOrderDecreasing:
def.sort_mode = SortMode::kSortOrderDecreasing;
break;
case SortMode_SortOrderIncreasing:
def.sort_mode = SortMode::kSortOrderIncreasing;
break;
case SortMode_WorldSpaceZBackToFront:
def.sort_mode = SortMode::kWorldSpaceZBackToFront;
break;
case SortMode_WorldSpaceZFrontToBack:
def.sort_mode = SortMode::kWorldSpaceZFrontToBack;
break;
case SortMode_AverageSpaceOriginBackToFront:
def.sort_mode = SortMode::kAverageSpaceOriginBackToFront;
break;
case SortMode_AverageSpaceOriginFrontToBack:
def.sort_mode = SortMode::kAverageSpaceOriginFrontToBack;
break;
case SortMode_Optimized:
break;
}
Apply(&def.render_state, data.render_state);
}
void RenderSystemNext::CreateRenderTarget(
HashValue render_target_name, const mathfu::vec2i& dimensions,
TextureFormat texture_format, DepthStencilFormat depth_stencil_format) {
DCHECK_EQ(render_targets_.count(render_target_name), 0);
// Create the render target.
auto render_target = MakeUnique<fplbase::RenderTarget>();
render_target->Initialize(dimensions,
RenderTargetTextureFormatToFpl(texture_format),
DepthStencilFormatToFpl(depth_stencil_format));
// Create a bindable texture.
TexturePtr texture = factory_->CreateTexture(
GL_TEXTURE_2D, fplbase::GlTextureHandle(render_target->GetTextureId()));
factory_->CacheTexture(render_target_name, texture);
// Store the render target.
render_targets_[render_target_name] = std::move(render_target);
}
void RenderSystemNext::SetRenderTarget(HashValue pass,
HashValue render_target_name) {
auto iter = render_targets_.find(render_target_name);
if (iter == render_targets_.end()) {
LOG(FATAL) << "SetRenderTarget called with non-existent render target: "
<< render_target_name;
return;
}
pass_definitions_[pass].render_target = iter->second.get();
}
void RenderSystemNext::CorrectFrontFaceFromMatrix(const mathfu::mat4& matrix) {
if (CalculateDeterminant3x3(matrix) >= 0.0f) {
// If the scalar is positive, match the default settings.
renderer_.SetFrontFace(cached_render_state_.cull_state.front);
} else {
// Otherwise, reverse the order.
renderer_.SetFrontFace(static_cast<fplbase::CullState::FrontFace>(
fplbase::CullState::kFrontFaceCount -
cached_render_state_.cull_state.front - 1));
}
}
void RenderSystemNext::BindUniform(const Uniform& uniform) {
const Uniform::Description& desc = uniform.GetDescription();
int binding = 0;
if (desc.binding >= 0) {
binding = desc.binding;
} else {
const Shader::UniformHnd handle = shader_->FindUniform(desc.name.c_str());
if (fplbase::ValidUniformHandle(handle)) {
binding = fplbase::GlUniformHandle(handle);
} else {
return;
}
}
const size_t bytes_per_component = desc.num_bytes / desc.count;
switch (desc.type) {
case Uniform::Type::kFloats: {
switch (bytes_per_component) {
case 4:
GL_CALL(glUniform1fv(binding, desc.count, uniform.GetData<float>()));
break;
case 8:
GL_CALL(glUniform2fv(binding, desc.count, uniform.GetData<float>()));
break;
case 12:
GL_CALL(glUniform3fv(binding, desc.count, uniform.GetData<float>()));
break;
case 16:
GL_CALL(glUniform4fv(binding, desc.count, uniform.GetData<float>()));
break;
default:
LOG(DFATAL) << "Uniform named \"" << desc.name
<< "\" is set to unsupported type floats with size "
<< desc.num_bytes;
}
} break;
case Uniform::Type::kMatrix: {
switch (bytes_per_component) {
case 64:
GL_CALL(glUniformMatrix4fv(binding, desc.count, false,
uniform.GetData<float>()));
break;
case 36:
GL_CALL(glUniformMatrix3fv(binding, desc.count, false,
uniform.GetData<float>()));
break;
case 16:
GL_CALL(glUniformMatrix2fv(binding, desc.count, false,
uniform.GetData<float>()));
break;
default:
LOG(DFATAL) << "Uniform named \"" << desc.name
<< "\" is set to unsupported type matrix with size "
<< desc.num_bytes;
}
} break;
default:
// Error or missing implementation.
LOG(DFATAL) << "Trying to bind uniform of unknown type.";
}
}
} // namespace lull
| 34.542444
| 80
| 0.686439
|
jjzhang166
|
7f5039992eb67ceedc2414dfed8e29ad0caf0b2e
| 109
|
cpp
|
C++
|
sources/shared_ptr.cpp
|
Denis-Gorbachev/lab-03-shared-ptr
|
555967045a5893a0f79507e60e5ccf386335fbe6
|
[
"MIT"
] | null | null | null |
sources/shared_ptr.cpp
|
Denis-Gorbachev/lab-03-shared-ptr
|
555967045a5893a0f79507e60e5ccf386335fbe6
|
[
"MIT"
] | null | null | null |
sources/shared_ptr.cpp
|
Denis-Gorbachev/lab-03-shared-ptr
|
555967045a5893a0f79507e60e5ccf386335fbe6
|
[
"MIT"
] | null | null | null |
// Copyright 2021 Denis <denis.gorbachev2002@yandex.ru>
//#include <stdexcept>
//#include <shared_ptr.hpp>
| 18.166667
| 55
| 0.733945
|
Denis-Gorbachev
|
7f56ba7b9b0425620218970964694ac78674c346
| 3,703
|
cpp
|
C++
|
lib/common/Shader.cpp
|
ynsn/rendor
|
b4d9da7ccedd472c7fc6d0155000c5b6a031dd1a
|
[
"MIT"
] | null | null | null |
lib/common/Shader.cpp
|
ynsn/rendor
|
b4d9da7ccedd472c7fc6d0155000c5b6a031dd1a
|
[
"MIT"
] | null | null | null |
lib/common/Shader.cpp
|
ynsn/rendor
|
b4d9da7ccedd472c7fc6d0155000c5b6a031dd1a
|
[
"MIT"
] | null | null | null |
/**
* MIT License
*
* Copyright (c) 2019 Yoram
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <glad/glad.h>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include "cg/common/Shader.h"
namespace cg {
Shader::Shader(const ShaderType &type) : shaderType(type) {
this->shaderHandle = glCreateShader(static_cast<GLenum>(this->shaderType));
if (this->shaderHandle == 0) {
fprintf(stderr, "Error: could not create shader, id = 0...\n");
}
}
Shader::~Shader() {
glDeleteShader(this->shaderHandle);
}
void Shader::setShaderSource(const std::string &shaderSource) const {
const char *source = shaderSource.c_str();
glShaderSource(this->shaderHandle, 1, &source, nullptr);
}
bool Shader::compileShader() {
glCompileShader(this->shaderHandle);
int status = 0;
glGetShaderiv(this->shaderHandle, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
int length = 0;
glGetShaderiv(this->shaderHandle, GL_INFO_LOG_LENGTH, &length);
std::vector<char> log(length);
glGetShaderInfoLog(this->shaderHandle, length, &length, &log[0]);
std::string logString(log.begin(), log.end());
fprintf(stderr,
"Shader compilation log (id = %u, type = %u): %s",
this->shaderHandle,
this->shaderType,
logString.c_str());
this->compiled = false;
} else {
this->compiled = true;
}
return this->compiled;
}
const ShaderType &Shader::getShaderType() const {
return this->shaderType;
}
const std::string Shader::getShaderSource() const {
std::vector<char> sourceBuf(getShaderSourceLength());
glGetShaderSource(this->shaderHandle, sourceBuf.size(), NULL, &sourceBuf[0]);
std::string source(sourceBuf.begin(), sourceBuf.end());
return source;
}
const int Shader::getShaderSourceLength() const {
int length;
glGetShaderiv(this->shaderHandle, GL_SHADER_SOURCE_LENGTH, &length);
return length;
}
const bool Shader::isDeleted() const {
int deleted = false;
glGetShaderiv(this->shaderHandle, GL_DELETE_STATUS, &deleted);
return static_cast<const bool>(deleted);
}
bool Shader::isCompiled() const {
return this->compiled;
}
const unsigned int Shader::getHandle() const {
return this->shaderHandle;
}
Shader *Shader::LoadFromSourceFile(const ShaderType &type1, const std::string &path) {
std::ifstream file;
file.open(path);
if (!file.is_open()) {
fprintf(stderr, "Error: could not read file '%s'\n", path.c_str());
return nullptr;
}
std::stringstream source;
source << file.rdbuf();
auto *shader = new Shader(type1);
shader->setShaderSource(source.str());
return shader;
}
}
| 29.15748
| 86
| 0.709155
|
ynsn
|
7f59467bbebf778457679b5aae0d9fca38b6115d
| 578
|
cpp
|
C++
|
util/mod_count_in_range.cpp
|
sekiya9311/CplusplusAlgorithmLibrary
|
f29dbdfbf3594da055185e39765880ff5d1e64ae
|
[
"Apache-2.0"
] | null | null | null |
util/mod_count_in_range.cpp
|
sekiya9311/CplusplusAlgorithmLibrary
|
f29dbdfbf3594da055185e39765880ff5d1e64ae
|
[
"Apache-2.0"
] | 8
|
2019-04-13T15:11:11.000Z
|
2020-03-19T17:14:18.000Z
|
util/mod_count_in_range.cpp
|
sekiya9311/CplusplusAlgorithmLibrary
|
f29dbdfbf3594da055185e39765880ff5d1e64ae
|
[
"Apache-2.0"
] | null | null | null |
// 範囲内のmodごとの数
// [l, r] 閉区間
std::vector<long long> mod_count_in_range(long long left, long long right, int mod) {
const long long range = (right - left + 1);
std::vector<long long> mod_count(mod, range / mod);
if (range % mod > 0) {
const int add_of_rest_left = left % mod;
int add_of_rest_right;
if (left % mod <= right % mod) {
add_of_rest_right = right % mod;
} else {
add_of_rest_right = right % mod + mod;
}
for (int i = add_of_rest_left; i <= add_of_rest_right; i++) {
mod_count[i % mod]++;
}
}
return mod_count;
}
| 28.9
| 85
| 0.610727
|
sekiya9311
|
7f5d6320aa10eee491059fc407abd1e679737819
| 366
|
cpp
|
C++
|
basic/root.cpp
|
ray2060/learn-cpp
|
bcf322d32574e1741a048219acff5697c99b2614
|
[
"MIT"
] | null | null | null |
basic/root.cpp
|
ray2060/learn-cpp
|
bcf322d32574e1741a048219acff5697c99b2614
|
[
"MIT"
] | null | null | null |
basic/root.cpp
|
ray2060/learn-cpp
|
bcf322d32574e1741a048219acff5697c99b2614
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string root(string s) {
if (s.size() == 1) return s;
int m;
for (int i = 0; i < s.size(); i ++) m += s[i] - 48;
stringstream st;
st << m;
string t;
st >> t;
return root(t);
}
int main() {
string s;
cin >> s;
cout << root(s);
return 0;
}
| 15.25
| 55
| 0.510929
|
ray2060
|
7f5fd23d9e82092bb4d7066d6d588405d98299aa
| 23,640
|
cpp
|
C++
|
DesignPages/DesignFormPanel.cpp
|
LibertyWarriorMusic/DBWorks
|
4bda411608cecb86f2cfc7f9319b160ed558a853
|
[
"MIT"
] | 1
|
2020-03-10T03:26:50.000Z
|
2020-03-10T03:26:50.000Z
|
DesignPages/DesignFormPanel.cpp
|
LibertyWarriorMusic/DBWorks
|
4bda411608cecb86f2cfc7f9319b160ed558a853
|
[
"MIT"
] | 1
|
2020-03-20T05:16:14.000Z
|
2020-03-20T05:17:25.000Z
|
DesignPages/DesignFormPanel.cpp
|
LibertyWarriorMusic/DBWorks
|
4bda411608cecb86f2cfc7f9319b160ed558a853
|
[
"MIT"
] | null | null | null |
//
// DrawPan.cpp
// P2
//
// Created by Nicholas Zounis on 27/2/20.
//
#include <wx/artprov.h>
#include <wx/xrc/xmlres.h>
#include <wx/button.h>
#include <wx/string.h>
#include <wx/bitmap.h>
#include <wx/image.h>
#include <wx/icon.h>
#include <wx/gdicmn.h>
#include <wx/font.h>
#include <wx/colour.h>
#include <wx/settings.h>
#include <wx/combobox.h>
#include <wx/textctrl.h>
#include <wx/gbsizer.h>
#include <wx/minifram.h>
#include <wx/sizer.h>
#include "wx/wx.h"
#include "wx/sizer.h"
#include "ObControl.h"
#include "../Shared/global.h"
#include "../Shared/Utility.h"
#include "../MyEvent.h"
#include "../Dialog/DlgTableSelect.h"
#include "../Dialog/LinkedTableDlg.h"
#include "../Dialog/MultiTextDlg.h"
#include "../Dialog/SelectionFieldQueryDlg.h"
#include "../Dialog/SetFlagsDlg.h"
#include "../Dialog/ListBoxDlg.h"
#include "../Dialog/SingleTextDlg.h"
#include "../Dialog/ManageActionsDlg.h"
#include "../Generic/GenericQueryGrid.h"
#include "mysql.h"
#include "mysql++.h"
#include "DesignFormPanel.h"
#include <cmath>
#include <wx/arrimpl.cpp>
WX_DEFINE_OBJARRAY(ArrayDrawControls);
using namespace mysqlpp;
enum {
ID_MENU_ADD_CONTROL = wxID_HIGHEST + 600,
ID_MENU_EDIT_LINKED_FIELD,
ID_MENU_DELETE_CONTROL,
ID_BUTTON_ADD_VALUE,
ID_BUTTON_REMOVE_LAST,
ID_CHK_AS,
ID_CHK_EQUAL,
ID_CHK_LIKE,
ID_MENU_EDIT_STATIC,
ID_MENU_RUN_QUERY,
ID_MENU_EDIT_SET_FLAGS,
ID_MENU_SELECTION_OPTIONS,
ID_MENU_EDIT_LINKED_TABLE,
ID_MENU_EDIT_DESCRIPTION,
ID_MENU_MANAGE_ACTIONS
};
BEGIN_EVENT_TABLE(DesignFormPanel, wxPanel)
// some useful events
EVT_MOTION(DesignFormPanel::mouseMoved)
EVT_LEFT_DOWN(DesignFormPanel::mouseDown)
EVT_LEFT_DCLICK(DesignFormPanel::mouseDoubleClick)
EVT_LEFT_UP(DesignFormPanel::mouseReleased)
EVT_RIGHT_DOWN(DesignFormPanel::rightClick)
EVT_LEAVE_WINDOW(DesignFormPanel::mouseLeftWindow)
EVT_KEY_DOWN(DesignFormPanel::keyPressed)
EVT_KEY_UP(DesignFormPanel::keyReleased)
EVT_MOUSEWHEEL(DesignFormPanel::mouseWheelMoved)
EVT_MENU(ID_MENU_EDIT_LINKED_FIELD, DesignFormPanel::OnMenuEditLinkedFields)
EVT_MENU(ID_MENU_DELETE_CONTROL, DesignFormPanel::OnMenuDeleteControl)
EVT_MENU(ID_MENU_EDIT_STATIC, DesignFormPanel::OnMenuEditStatic)
EVT_MENU(ID_MENU_EDIT_DESCRIPTION, DesignFormPanel::OnMenuEditDescription)
EVT_MENU(ID_MENU_RUN_QUERY, DesignFormPanel::OnRunQuery)
EVT_MENU(ID_MENU_EDIT_SET_FLAGS, DesignFormPanel::OnSetFlags)
EVT_MENU(ID_MENU_SELECTION_OPTIONS, DesignFormPanel::OnSetSelectionOptions)
EVT_MENU(ID_MENU_EDIT_LINKED_TABLE, DesignFormPanel::OnSetLinkedTable)
EVT_MENU(ID_MENU_MANAGE_ACTIONS, DesignFormPanel::OnManageActions)
EVT_PAINT(DesignFormPanel::paintEvent)
END_EVENT_TABLE()
void DesignFormPanel::rightClick(wxMouseEvent& event)
{
m_pObCurrentFormControl= nullptr;
m_MousePos = event.GetPosition(); //Remember the mouse position to draw
ObControl* pCtl = GetObjectHitByMouse(m_MousePos);
//Diagram menus
//Create a context menu to do stuff here.
auto *menu = new wxMenu;
if(pCtl!= nullptr)
{
m_pObCurrentFormControl = pCtl;
if(m_pObCurrentFormControl->GetTypeName()=="CTL_STATIC" )
{
menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Label"), wxT("Set the Label."));
}
else if(m_pObCurrentFormControl->GetTypeName()=="CTL_SPACER" ){
}
else if(m_pObCurrentFormControl->GetTypeName()=="CTL_SELECTION" || m_pObCurrentFormControl->GetTypeName()=="CTL_SELECTION_ADDITIVE"){
menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Label"), wxT("Set the Label."));
menu->Append(ID_MENU_EDIT_LINKED_FIELD, wxT("Set Linked Field"), wxT("Edit table definitions."));
menu->Append(ID_MENU_SELECTION_OPTIONS, wxT("Manage Options"), wxT("Manage options."));
}
else if(m_pObCurrentFormControl->GetTypeName()=="CTL_SELECTION_LINKED_NAME"
|| m_pObCurrentFormControl->GetTypeName()=="CTL_SELECTION_LOOKUP_NAME"){
menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Label"), wxT("Set the Label."));
menu->Append(ID_MENU_EDIT_LINKED_FIELD, wxT("Set Linked Field"), wxT("Edit table definitions."));
menu->Append(ID_MENU_EDIT_LINKED_TABLE, wxT("Set Linked Table"), wxT("Set Linked Table."));
}
else if(m_pObCurrentFormControl->GetTypeName()=="CTL_BUTTON")
{
menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Button Label"), wxT("Set the Button Label."));
menu->Append(ID_MENU_EDIT_DESCRIPTION, wxT("Set Button Description"), wxT("Set Button Description."));
menu->Append(ID_MENU_MANAGE_ACTIONS, wxT("Manage Actions"), wxT("Manage Actions"));
}
else if(m_pObCurrentFormControl->GetTypeName()=="CTL_GRID_DISPLAY")
{
}
else if(m_pObCurrentFormControl->GetTypeName()!="CTL_RECORD_SELECTOR")
{
menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Label"), wxT("Set the Label."));
menu->Append(ID_MENU_EDIT_LINKED_FIELD, wxT("Set Linked Field"), wxT("Edit table definitions."));
//Don't do this.
//menu->Append(ID_MENU_EDIT_SET_FLAGS, wxT("Set Flags"), wxT("Set flags for this controlFS."));
}
menu->Append(ID_MENU_DELETE_CONTROL, wxT("Delete Control"), wxT("Delete Control."));
}
else{
menu->Append(ID_MENU_RUN_QUERY, wxT("Test query"), wxT("Test query."));
// menu->AppendSeparator();
}
PopupMenu( menu, m_MousePos);
//Tell the parent to add a table to the drawing at the mouse point.
MyEvent my_event( this );
my_event.m_bStatusMessage=true;
my_event.m_pMousePoint=m_MousePos;
GetParent()->ProcessWindowEvent( my_event );
}
DesignFormPanel::~DesignFormPanel()
{
DeleteDrawObject();
}
DesignFormPanel::DesignFormPanel(wxFrame* parent) : wxPanel(parent)
{
m_pObjectToDrawTEMP = nullptr;
m_pObCurrentFormControl = nullptr;
m_MouseMoveOffset.x=0;
m_MouseMoveOffset.y=0;
m_sizeWinObjectsExtend.x=0;
m_sizeWinObjectsExtend.y=0;
}
void DesignFormPanel::SetFormID(wxString sFormId)
{
m_sFormId=sFormId;
}
wxString DesignFormPanel::GetFormID()
{
return m_sFormId;
}
//===================
//MENU EVENT FUNCTIONS
void DesignFormPanel::OnMenuEditStatic(wxCommandEvent& event)
{
wxString sData = PromptEditSingleTextDialog("Label","Set Label","Label");
m_pObCurrentFormControl->SetLabel(sData);
RedrawControlObjects();
}
void DesignFormPanel::OnMenuEditDescription(wxCommandEvent& event)
{
wxString sData = PromptEditSingleTextDialog("Short_Description","Edit short description","Short Description.");
m_pObCurrentFormControl->SetDescription(sData);
RedrawControlObjects();
}
wxString DesignFormPanel::PromptEditSingleTextDialog(wxString sKey, wxString sDialogTitle, wxString sLabel)
{
if(m_pObCurrentFormControl!= nullptr){
wxString sControlId = m_pObCurrentFormControl->GetControlID();
SingleTextDlg * pDlg = new SingleTextDlg(nullptr, sDialogTitle, sLabel);
Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,sKey,sLabel);
pDlg->SetDataValue("ID_TEXT",sLabel);
if(pDlg->ShowModal()==wxOK) {
sLabel = pDlg->GetDataValue("ID_TEXT");
Utility::SaveTableData(Settings.sDatabase,"usr_controls",sControlId,sKey,sLabel);
//We need to create a new entry in the Form queries.
}
pDlg->Destroy();
}
return sLabel;
}
void DesignFormPanel::OnManageActions(wxCommandEvent& event)
{
if(m_pObCurrentFormControl!= nullptr){
wxString sControlId = m_pObCurrentFormControl->GetControlID();
ManageActionsDlg * pDlg = new ManageActionsDlg(nullptr, sControlId, "Avaliable actions", "Select Action");
if(pDlg->ShowModal()==wxOK) {
pDlg->Save();
//So we can redraw on the screen.
m_pObCurrentFormControl->SetAction(pDlg->GetAction());
RedrawControlObjects();
//We need to create a new entry in the Form queries.
}
pDlg->Destroy();
}
}
void DesignFormPanel::OnMenuEditLinkedFields(wxCommandEvent& event)
{
if(m_pObCurrentFormControl!= nullptr){
wxString sControlId = m_pObCurrentFormControl->GetControlID();
SelectionFieldQueryDlg * pDlg = new SelectionFieldQueryDlg(nullptr, "Avaliable Fields", "Select Field");
pDlg->SetControlID(sControlId);
pDlg->SetQuery(m_sBuildQuery);
pDlg->Load();
if(pDlg->ShowModal()==wxOK) {
pDlg->Save();
//So we can redraw on the screen.
m_pObCurrentFormControl->SetField(pDlg->GetField());
RedrawControlObjects();
//We need to create a new entry in the Form queries.
}
pDlg->Destroy();
}
}
void DesignFormPanel::OnSetFlags(wxCommandEvent& event)
{
SetFlagsDlg * pDlg = new SetFlagsDlg(nullptr, "Avaliable Fields", "Select Field");
wxString sControlId = m_pObCurrentFormControl->GetControlID();
wxString flags="";
wxString sKey="FLAGS";
Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,sKey,flags);
pDlg->SetDataValue("ID_FLAGS",flags);
if(pDlg->ShowModal()==wxOK) {
wxString flags = pDlg->GetDataValue("ID_FLAGS");
Utility::SaveTableData(Settings.sDatabase,"usr_controls",sControlId,"FLAGS",flags);
}
pDlg->Destroy();
}
void DesignFormPanel::OnSetSelectionOptions(wxCommandEvent& event)
{
ListBoxDlg * pDlg = new ListBoxDlg(nullptr, "Selection Options List", "Selection Options");
wxString sControlId = m_pObCurrentFormControl->GetControlID();
pDlg->SetControlID(sControlId);
pDlg->LoadItems();
if(pDlg->ShowModal()==wxOK)
pDlg->SaveItems();
pDlg->Destroy();
}
void DesignFormPanel::OnSetLinkedTable(wxCommandEvent& event)
{
LinkedTableDlg * pDlg = new LinkedTableDlg(nullptr, "Selection Options List", "Selection Options");
wxString sControlId = m_pObCurrentFormControl->GetControlID();
pDlg->SetControlID(sControlId);
pDlg->Load();
if(pDlg->ShowModal()==wxOK)
pDlg->Save();
pDlg->Destroy();
}
void DesignFormPanel::OnMenuDeleteControl(wxCommandEvent& event)
{
if(m_pObCurrentFormControl!= nullptr){
wxString sControlTypeName = m_pObCurrentFormControl->GetTypeName();
wxString sControlId = m_pObCurrentFormControl->GetControlID();
//The field doesn't exist, do you want to add it.
auto *dlg = new wxMessageDialog(nullptr, "Are you sure you want to delete this control? \n\n", wxT("Delete Control"), wxYES_NO | wxICON_EXCLAMATION);
if ( dlg->ShowModal() == wxID_YES ){
wxString dropQuery= "DELETE FROM usr_controls WHERE usr_controlsId= "+m_pObCurrentFormControl->GetControlID();
Utility::ExecuteQuery(dropQuery);
RemoveControlFromList(m_pObCurrentFormControl->GetControlID());
RedrawControlObjects();
dlg->Destroy();
}
}
}
void DesignFormPanel::OnRunQuery(wxCommandEvent& event) {
MyEvent my_event( this );
my_event.m_bOpenRunQuery=true;
GetParent()->ProcessWindowEvent( my_event );
}
void DesignFormPanel::OnMenuOpenControl(wxCommandEvent& event) {
if(m_pObCurrentFormControl!= nullptr){
MyEvent my_event( this );
my_event.m_bOpen=true;
my_event.m_sTableName=m_pObCurrentFormControl->GetTypeName();
my_event.m_sTableId=m_pObCurrentFormControl->GetControlID();
GetParent()->ProcessWindowEvent( my_event );
}
}
// Testing draw the position when the mouse is down.
void DesignFormPanel::mouseDown(wxMouseEvent& event) {
m_MousePos = event.GetPosition(); //Remember the mouse position to draw
wxString fieldName="";
wxRect fieldRect;
ObControl* pCtl = GetObjectHitByMouse(m_MousePos,fieldName,fieldRect);
if(pCtl!= nullptr)
{
if(!fieldName.IsEmpty()){
}
else
m_MouseMoveOffset=Utility::CalcPtInRectOffset(m_MousePos,pCtl->GetControlRect());
//NOTE we never want to delete m_pObjectToDrawTEMP because this is the object on the screen, but we want to make the pointer null when we are finished with it.
m_pObjectToDrawTEMP = pCtl;
m_pObjectToDrawTEMP->TurnSnapOff();
}
MyEvent my_event( this );
my_event.m_bStatusMessage=true;
my_event.m_sData="mouseDown";
GetParent()->ProcessWindowEvent( my_event );
}
void DesignFormPanel::mouseMoved(wxMouseEvent& event)
{
m_MousePos = event.GetPosition(); //Remember the mouse position to draw
if (m_pObjectToDrawTEMP != nullptr){
wxPoint pos;
pos.x = m_MousePos.x - m_MouseMoveOffset.x;
pos.y = m_MousePos.y - m_MouseMoveOffset.y;
//Drag the object
m_pObjectToDrawTEMP->SetControlPosition(pos);
//This is going to be too show. We need to only move the object.
wxClientDC dc(this);
m_pObjectToDrawTEMP->DrawControlObject(dc);
}
}
void DesignFormPanel::mouseReleased(wxMouseEvent& event)
{
m_MousePos = event.GetPosition(); //Remember the mouse position to draw
if(m_pObjectToDrawTEMP!=nullptr){
//Restore the snap condition to what is was before we moved the object
m_pObjectToDrawTEMP->RestorePreviousSnapCondition();
wxPoint pos;
pos.x = m_MousePos.x - m_MouseMoveOffset.x;
pos.y = m_MousePos.y - m_MouseMoveOffset.y;
m_pObjectToDrawTEMP->SetControlPosition(pos); //This also checks the limits and doesn't draw the object in the query builder section.
wxClientDC dc(this);
m_pObjectToDrawTEMP->DrawControlObject(dc);
m_pObjectToDrawTEMP->SaveDB(m_pObjectToDrawTEMP->GetControlID()); //We can save it directly
//Reset these
m_pObjectToDrawTEMP = nullptr;
m_MouseMoveOffset.x=0;
m_MouseMoveOffset.y=0;
}
MyEvent my_event( this );
my_event.m_bStatusMessage=true;
my_event.m_sData="mouseReleased";
GetParent()->ProcessWindowEvent( my_event );
}
void DesignFormPanel::DeleteDrawObject()
{
/* You don't need to do this I believe, I haven't yet checked if the program leaks memory, but if you do this the program crashes.
// I think the object array deletes the objects when it is destroyed.
int count = m_ObTableList.GetCount();
if(m_ObTableList.GetCount()>0){
for (int index=0; index<m_ObTableList.GetCount();index++)
delete &m_ObTableList[index];
}
*/
}
wxSize DesignFormPanel::GetSizeDiagramExtend()
{
wxSize size = m_sizeWinObjectsExtend;
size.x = m_sizeWinObjectsExtend.x + 300;
size.y = m_sizeWinObjectsExtend.y + 300;
return size;
}
void DesignFormPanel::mouseDoubleClick(wxMouseEvent& event)
{
m_MousePos = event.GetPosition(); //Remember the mouse position to draw
ObControl* pCtl = GetObjectHitByMouse(m_MousePos);
if(pCtl!= nullptr)
{
MyEvent my_event( this );
my_event.m_bOpen=true;
my_event.m_sTableName=pCtl->GetTypeName();
my_event.m_sTableId=pCtl->GetControlID();
GetParent()->ProcessWindowEvent( my_event );
}
}
void DesignFormPanel::mouseWheelMoved(wxMouseEvent& event)
{
MyEvent my_event( this );
my_event.m_bStatusMessage=true;
my_event.m_sData="mouseWheelMoved";
GetParent()->ProcessWindowEvent( my_event );
}
void DesignFormPanel::mouseLeftWindow(wxMouseEvent& event)
{
/*
m_MousePos = event.GetPosition(); //Remember the mouse position to draw
MyEvent my_event( this );
my_event.m_bStatusMessage=true;
my_event.m_sData="mouseLeftWindow";
GetParent()->ProcessWindowEvent( my_event );*/
}
void DesignFormPanel::keyPressed(wxKeyEvent& event)
{
/* m_MousePos = event.GetPosition(); //Remember the mouse position to draw
MyEvent my_event( this );
my_event.m_bStatusMessage=true;
my_event.m_sData="keyPressed";
GetParent()->ProcessWindowEvent( my_event );*/
}
void DesignFormPanel::keyReleased(wxKeyEvent& event)
{
/* m_MousePos = event.GetPosition(); //Remember the mouse position to draw
MyEvent my_event( this );
my_event.m_bStatusMessage=true;
my_event.m_sData="keyReleased";
GetParent()->ProcessWindowEvent( my_event );*/
}
/*
* Called by the system of by wxWidgets when the panel needs
* to be redrawn. You can also trigger this call by
* calling Refresh()/Update().
*/
void DesignFormPanel::paintEvent(wxPaintEvent & evt)
{
wxPaintDC dc(this);
render(dc);
}
void DesignFormPanel::RedrawControlObjects()
{
wxClientDC dc(this);
dc.Clear();
render(dc);
//dc.Clear(); //NOT SURE why I put this after render, was it a mistake? I should of commented this.
//Now we might want to put the default background colour on
}
//This is where you place stuff you need to do on refresh.
void DesignFormPanel::Refresh()
{
RedrawControlObjects();
}
/*
* Here we do the actual rendering. I put it in a separate
* method so that it can work no matter what type of DC
* (e.g. wxPaintDC or wxClientDC) is used.
*/
void DesignFormPanel::render(wxDC& dc)
{
//Draw all the object to the screen.
for (int index=0; index<m_ControlList.GetCount();index++) {
ObControl* pCtl = &m_ControlList[index];
if(pCtl!= nullptr)
pCtl->DrawControlObject(dc);
}
}
ObControl * DesignFormPanel::GetObjectHitByMouse(wxPoint mousePt)
{
//Draw all the object to the screen.
for (int index=0; index<m_ControlList.GetCount();index++) {
ObControl* pCtl = &m_ControlList[index];
if(pCtl!= nullptr){
if(pCtl->HitTest(mousePt)){
return pCtl;
}
}
}
return nullptr;
}
//The the mouse point hit a field, will return the field name
ObControl * DesignFormPanel::GetObjectHitByMouse(wxPoint mousePt, wxString& sHitFieldName, wxRect& sfieldRect)
{
ObControl * pCtl = GetObjectHitByMouse(mousePt);
//if(pCtl != nullptr)
//sHitFieldName = pCtl->HitTestField(mousePt,sfieldRect);
return pCtl;
}
//Adds a drawing object to the diagram panel.
void DesignFormPanel::AddControlObject(const wxString& sTypeID)
{
ObControl *pCtl = NewCtlObject();
if(pCtl != nullptr)
{
//The Control doesn't exist, so add it.
pCtl->SetTypeID(sTypeID);
pCtl->SetControlPosition(m_MousePos);
pCtl->SetFormID(GetFormID());
wxArrayString sArray;
Utility::GetFieldFromTableWhereFieldEquals(Settings.sDatabase, sArray, "usr_control_types", "typeName", "usr_control_typesId", sTypeID);
if(sArray.GetCount()==1){
pCtl->SetTypeName(sArray[0]);
}
m_ControlList.Add(pCtl);
pCtl->SaveDB("");
}
RedrawControlObjects(); // Redraw all the objects.
}
void DesignFormPanel::RemoveControlFromList(wxString sControlId)
{
int count = m_ControlList.GetCount();
if(m_ControlList.GetCount()>0) {
for (int index = 0; index < count; index++) {
if(m_ControlList[index].GetControlID()==sControlId){
//Remove this from the list, redraw and exit
m_ControlList.RemoveAt(index);
break;
}
}
}
}
//Loads all the controls from the database and creates the drawing
void DesignFormPanel::LoadControlObjects()
{
// If we have existing object, clear the list.
if(m_ControlList.GetCount()>0)
m_ControlList.Clear();
wxString QueryString = "SELECT usr_control_types.usr_control_typesId, usr_control_types.typeName, usr_controls.usr_controlsId, usr_controls.table_data ";
QueryString += " FROM usr_control_types, usr_controls ";
QueryString += " WHERE usr_control_types.usr_control_typesId = usr_controls.usr_control_typesId";
QueryString += " AND usr_controls.usr_formsId = "+GetFormID();
ArrayFieldRecord saControl;
Utility::LoadArrayFieldRecordFromQuery(saControl, QueryString);
int count = saControl.GetCount();
if(saControl.GetCount()>0){
for(int index=0;index<count;index++){
wxString sData="";
wxString sControlId = saControl[index].GetData("usr_controlsId");
wxString sTypeName = saControl[index].GetData("typeName");
wxString sTypeID = saControl[index].GetData("usr_control_typesId");
wxString sEntireTableData = saControl[index].GetData("table_data");
Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,"ObControlShow",sData,sEntireTableData);
if(sData=="yes"){
//Load the data and create the table object.
//wxString sTableID = Utility::GetTableIdFromSYS_TABLESByTableName(Settings.sDatabase,saControlId[index]);
//The table doesn't exist, so add it.
ObControl * pCtl = NewCtlObject();
pCtl->SetControlID(sControlId);
pCtl->SetFormID(GetFormID());
pCtl->SetTypeName(sTypeName);
pCtl->SetTypeID(sTypeID);
wxString sLabel="";
wxString sField="";
wxString xPos = "";
wxString yPos = "";
Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("ObControlPositionX"),xPos);
Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("ObControlPositionY"),yPos);
Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("Label"),sLabel);
pCtl->SetLabel(sLabel);
Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("Short_Description"),sLabel);
pCtl->SetDescription(sLabel);
Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("Action"),sLabel);
pCtl->SetAction(sLabel);
Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("Field"),sField);
pCtl->SetField(sField);
int lxPos = Utility::StringToInt(xPos);
int lyPos = Utility::StringToInt(yPos);
if(lxPos> m_sizeWinObjectsExtend.x){
m_sizeWinObjectsExtend.x = lxPos;
}
if(lyPos> m_sizeWinObjectsExtend.y){
m_sizeWinObjectsExtend.y = lyPos;
}
wxPoint pt(Utility::StringToInt(xPos),Utility::StringToInt(yPos));
pCtl->SetControlPosition(pt);
m_ControlList.Add(pCtl);
}
}
RedrawControlObjects(); // Draw them to the screen.
}
}
void DesignFormPanel::SetQuery(wxString sQuery)
{
m_sBuildQuery=sQuery;
}
wxString DesignFormPanel::GetQuery()
{
return m_sBuildQuery;
}
ObControl* DesignFormPanel::NewCtlObject()
{
ObControl* pCtl= new ObControl;
return pCtl;
}
/*
//Check to make sure we already don't have an existing table.
ObControl* DesignFormPanel::DoesControlExist(wxString sControlId)
{
for (int index=0; index<m_ControlList.GetCount();index++) {
ObControl *pCtl = &m_ControlList[index];
if(pCtl->GetID()== sControlId)
return pCtl;
}
return nullptr;
}
*/
//We can send a message to the parent that this window is destroyed.
bool DesignFormPanel::Destroy()
{
MyEvent my_event( this );
my_event.m_bDestroyed=true;
GetParent()->ProcessWindowEvent( my_event );
//bool bResult = wxPanel::Destroy();
return true;
}
| 32.383562
| 167
| 0.677876
|
LibertyWarriorMusic
|
7f60bb0f944ba4d08ab554d599ac5ea4d433bb12
| 19,513
|
cc
|
C++
|
Archive/Stroika_FINAL_for_STERL_1992/Library/Graphix/Sources/Shape.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Library/Graphix/Sources/Shape.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Library/Graphix/Sources/Shape.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/Shape.cc,v 1.7 1992/09/11 18:41:55 sterling Exp $
*
* TODO:
*
* - Desperately need the ability to scale shapes - probably shouyld add general
* transform capabilty - at least scale, etc..
*
* Changes:
* $Log: Shape.cc,v $
* Revision 1.7 1992/09/11 18:41:55 sterling
* new Shape stuff, got rid of String Peek references
*
* Revision 1.6 1992/09/05 16:14:25 lewis
* Renamed Nil->Nil.
*
* Revision 1.5 1992/09/01 15:36:53 sterling
* Lots of Foundation changes.
*
* Revision 1.4 1992/07/08 02:11:42 lewis
* Renamed PointInside->Contains ().
*
* Revision 1.3 1992/07/04 14:50:03 lewis
* Added BlockAllocation/operator new/delete overrides to the shape reps for
* better performance. Also, lots of cleanups including removing ifdefed out
* code.
*
* Revision 1.2 1992/07/04 02:37:40 lewis
* See header for big picture - but mainly here we renamed all shape classes X,
* to XRepresention, and commented out methods that were setters - just recreate
* the object - with out new paradigm its a little harder to do sets - may support
* them again, if sterl thinks its worth it...
*
* Revision 1.1 1992/06/19 22:34:01 lewis
* Initial revision
*
* Revision 1.12 1992/05/23 00:10:07 lewis
* #include BlockAllocated instead of Memory.hh
*
* Revision 1.11 92/04/15 14:31:18 14:31:18 lewis (Lewis Pringle)
* Adjust asserts to be call AsDegrees () when comparing with hardwired degress values.
*
* Revision 1.9 1992/02/21 18:06:44 lewis
* Got rid of qGPlus_ClassOpNewDelBroke workaround.
*
*
*
*
*/
#include "OSRenamePre.hh"
#if qMacGDI
#include <Memory.h>
#include <OSUtils.h>
#include <QuickDraw.h>
#endif /*qMacGDI*/
#include "OSRenamePost.hh"
#include "BlockAllocated.hh"
#include "Debug.hh"
#include "PixelMap.hh"
#include "Tablet.hh"
#include "Shape.hh"
#if !qRealTemplatesAvailable
Implement (Iterator, Point);
Implement (Collection, Point);
Implement (AbSequence, Point);
Implement (Array, Point);
Implement (Sequence_Array, Point);
Implement (Sequence, Point);
#endif /*!qRealTemplatesAvailable*/
#if qMacGDI
struct WorkTablet : Tablet {
WorkTablet (osGrafPort* osg):
Tablet (osg)
{
AssertNotNil (osg);
}
};
static struct ModuleInit {
ModuleInit ()
{
osGrafPort* port = new (osGrafPort);
::OpenPort (port);
fTablet = new WorkTablet (port);
}
Tablet* fTablet;
} kModuleGlobals;
#endif /*qMacGDI*/
#if !qRealTemplatesAvailable
Implement (Shared, ShapeRepresentation);
#endif
/*
********************************************************************************
***************************** ShapeRepresentation ******************************
********************************************************************************
*/
Boolean ShapeRepresentation::Contains (const Point& p, const Rect& shapeBounds) const
{
if (shapeBounds.Contains (p)) {
return (ToRegion (shapeBounds).Contains (p));
}
else {
return (False);
}
}
Region ShapeRepresentation::ToRegion (const Rect& shapeBounds) const
{
#if qMacGDI
static osRegion** tmp = ::NewRgn ();
static const Pen kRegionPen = Pen (kBlackTile, eCopyTMode, Point (1, 1));
AssertNotNil (kModuleGlobals.fTablet->GetOSGrafPtr ());
osGrafPort* oldPort = qd.thePort;
Tablet::xDoSetPort (kModuleGlobals.fTablet->GetOSGrafPtr ());
::OpenRgn ();
OutLine (*kModuleGlobals.fTablet, shapeBounds, kRegionPen);
::CloseRgn (tmp);
Tablet::xDoSetPort (oldPort);
return (Region (tmp));
#elif qXGDI
// for now, hack and just return bounding rectable - we must fix this soon!!!
return (shapeBounds);
#endif /*qMacGDI || qXGDI*/
}
Point ShapeRepresentation::GetLogicalSize () const
{
return (kZeroPoint);
}
/*
********************************************************************************
*************************** RectangleRepresentation ****************************
********************************************************************************
*/
RectangleRepresentation::RectangleRepresentation ()
{
}
Boolean RectangleRepresentation::Contains (const Point& p, const Rect& shapeBounds) const
{
return (shapeBounds.Contains (p));
}
void RectangleRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const
{
on.PaintRect (shapeBounds, brush);
}
void RectangleRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const
{
on.OutLineRect (shapeBounds, pen);
}
Region RectangleRepresentation::ToRegion (const Rect& shapeBounds) const
{
return (Region (shapeBounds));
}
#if !qRealTemplatesAvailable
BlockAllocatedDeclare (RectangleRepresentation);
BlockAllocatedImplement (RectangleRepresentation);
#endif /*!qRealTemplatesAvailable*/
void* RectangleRepresentation::operator new (size_t n)
{
#if qRealTemplatesAvailable
return (BlockAllocated<RectangleRepresentation>::operator new (n));
#else /*qRealTemplatesAvailable*/
return (BlockAllocated(RectangleRepresentation)::operator new (n));
#endif /*qRealTemplatesAvailable*/
}
void RectangleRepresentation::operator delete (void* p)
{
#if qRealTemplatesAvailable
BlockAllocated<RectangleRepresentation>::operator delete (p);
#else /*qRealTemplatesAvailable*/
BlockAllocated(RectangleRepresentation)::operator delete (p);
#endif /*qRealTemplatesAvailable*/
}
/*
********************************************************************************
****************************** RoundedRectangle ********************************
********************************************************************************
*/
Point RoundedRectangle::kDefaultRounding = Point (10, 10);
/*
********************************************************************************
*********************** RoundedRectangleRepresentation *************************
********************************************************************************
*/
RoundedRectangleRepresentation::RoundedRectangleRepresentation (const Point& rounding):
fRounding (rounding)
{
Require (rounding.GetH () == (short)rounding.GetH ());
Require (rounding.GetV () == (short)rounding.GetV ());
}
void RoundedRectangleRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const
{
on.PaintRoundedRect (shapeBounds, fRounding, brush);
}
void RoundedRectangleRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const
{
on.OutLineRoundedRect (shapeBounds, fRounding, pen);
}
Point RoundedRectangleRepresentation::GetRounding () const
{
return (fRounding);
}
#if !qRealTemplatesAvailable
BlockAllocatedDeclare (RoundedRectangleRepresentation);
BlockAllocatedImplement (RoundedRectangleRepresentation);
#endif /*!qRealTemplatesAvailable*/
void* RoundedRectangleRepresentation::operator new (size_t n)
{
#if qRealTemplatesAvailable
return (BlockAllocated<RoundedRectangleRepresentation>::operator new (n));
#else /*qRealTemplatesAvailable*/
return (BlockAllocated(RoundedRectangleRepresentation)::operator new (n));
#endif /*qRealTemplatesAvailable*/
}
void RoundedRectangleRepresentation::operator delete (void* p)
{
#if qRealTemplatesAvailable
BlockAllocated<RoundedRectangleRepresentation>::operator delete (p);
#else /*qRealTemplatesAvailable*/
BlockAllocated(RoundedRectangleRepresentation)::operator delete (p);
#endif /*qRealTemplatesAvailable*/
}
/*
********************************************************************************
******************************** OvalRepresentation ****************************
********************************************************************************
*/
OvalRepresentation::OvalRepresentation ()
{
}
void OvalRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const
{
on.PaintOval (shapeBounds, brush);
}
void OvalRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const
{
on.OutLineOval (shapeBounds, pen);
}
#if !qRealTemplatesAvailable
BlockAllocatedDeclare (OvalRepresentation);
BlockAllocatedImplement (OvalRepresentation);
#endif /*!qRealTemplatesAvailable*/
void* OvalRepresentation::operator new (size_t n)
{
#if qRealTemplatesAvailable
return (BlockAllocated<OvalRepresentation>::operator new (n));
#else /*qRealTemplatesAvailable*/
return (BlockAllocated(OvalRepresentation)::operator new (n));
#endif /*qRealTemplatesAvailable*/
}
void OvalRepresentation::operator delete (void* p)
{
#if qRealTemplatesAvailable
BlockAllocated<OvalRepresentation>::operator delete (p);
#else /*qRealTemplatesAvailable*/
BlockAllocated(OvalRepresentation)::operator delete (p);
#endif /*qRealTemplatesAvailable*/
}
/*
********************************************************************************
******************************* ArcRepresentation *****************************
********************************************************************************
*/
ArcRepresentation::ArcRepresentation (Angle startAngle, Angle arcAngle):
fStartAngle (startAngle),
fArcAngle (arcAngle)
{
Require (startAngle.AsDegrees () >= 0);
Require (arcAngle.AsDegrees () <= 360);
}
void ArcRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const
{
on.PaintArc (fStartAngle, fArcAngle, shapeBounds, brush);
}
void ArcRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const
{
on.OutLineArc (fStartAngle, fArcAngle, shapeBounds, pen);
}
Angle ArcRepresentation::GetStart () const
{
return (fStartAngle);
}
Angle ArcRepresentation::GetAngle () const
{
return (fArcAngle);
}
#if !qRealTemplatesAvailable
BlockAllocatedDeclare (ArcRepresentation);
BlockAllocatedImplement (ArcRepresentation);
#endif /*!qRealTemplatesAvailable*/
void* ArcRepresentation::operator new (size_t n)
{
#if qRealTemplatesAvailable
return (BlockAllocated<ArcRepresentation>::operator new (n));
#else /*qRealTemplatesAvailable*/
return (BlockAllocated(ArcRepresentation)::operator new (n));
#endif /*qRealTemplatesAvailable*/
}
void ArcRepresentation::operator delete (void* p)
{
#if qRealTemplatesAvailable
BlockAllocated<ArcRepresentation>::operator delete (p);
#else /*qRealTemplatesAvailable*/
BlockAllocated(ArcRepresentation)::operator delete (p);
#endif /*qRealTemplatesAvailable*/
}
/*
********************************************************************************
************************** RegionShapeRepresentation ***************************
********************************************************************************
*/
RegionShapeRepresentation::RegionShapeRepresentation (const Region& rgn):
fRegion (rgn)
{
}
void RegionShapeRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const
{
on.PaintRegion (fRegion, shapeBounds, brush);
}
void RegionShapeRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const
{
on.OutLineRegion (fRegion, shapeBounds, pen);
}
Region RegionShapeRepresentation::ToRegion (const Rect& shapeBounds) const
{
if ((shapeBounds.Empty ()) or (fRegion == kEmptyRegion)) {
return (kEmptyRegion);
}
if (shapeBounds == fRegion.GetBounds ()) {
return (fRegion);
}
else {
Region tempRgn = fRegion;
#if qMacGDI
osRect osr;
osRect osBounds;
os_cvt (fRegion.GetBounds (), osBounds);
os_cvt (shapeBounds, osr);
::MapRgn (tempRgn.GetOSRegion (), &osBounds, &osr);
#elif qXGDI
return (shapeBounds); // see Shape::ToRegion ()!!! THIS IS BROKEN!!!
#endif /*qMacGDI*/
return (tempRgn);
}
}
Point RegionShapeRepresentation::GetLogicalSize () const
{
return (fRegion.GetBounds ().GetSize ());
}
#if !qRealTemplatesAvailable
BlockAllocatedDeclare (RegionShapeRepresentation);
BlockAllocatedImplement (RegionShapeRepresentation);
#endif /*!qRealTemplatesAvailable*/
void* RegionShapeRepresentation::operator new (size_t n)
{
#if qRealTemplatesAvailable
return (BlockAllocated<RegionShapeRepresentation>::operator new (n));
#else /*qRealTemplatesAvailable*/
return (BlockAllocated(RegionShapeRepresentation)::operator new (n));
#endif /*qRealTemplatesAvailable*/
}
void RegionShapeRepresentation::operator delete (void* p)
{
#if qRealTemplatesAvailable
BlockAllocated<RegionShapeRepresentation>::operator delete (p);
#else /*qRealTemplatesAvailable*/
BlockAllocated(RegionShapeRepresentation)::operator delete (p);
#endif /*qRealTemplatesAvailable*/
}
/*
********************************************************************************
******************************** PolygonRepresentation *************************
********************************************************************************
*/
PolygonRepresentation::PolygonRepresentation (const AbSequence(Point)& points):
ShapeRepresentation (),
#if qMacGDI
fOSPolygon (Nil),
#endif /*qMacGDI*/
fPoints (points)
{
RebuildOSPolygon ();
#if qXGDI
AssertNotImplemented ();
#endif /*qXGDI*/
}
PolygonRepresentation::~PolygonRepresentation ()
{
#if qMacGDI
if (fOSPolygon != Nil) {
::KillPoly (fOSPolygon);
}
#endif /*qMacGDI*/
}
void PolygonRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const
{
#if qMacGDI
on.PaintPolygon (fOSPolygon, shapeBounds, brush);
#endif /*qMacGDI*/
}
void PolygonRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const
{
#if qMacGDI
on.OutLinePolygon (fOSPolygon, shapeBounds, pen);
#endif /*qMacGDI*/
}
Point PolygonRepresentation::GetLogicalSize () const
{
#if qMacGDI
return (os_cvt ((*fOSPolygon)->polyBBox).GetSize ());
#endif /*qMacGDI*/
}
const AbSequence(Point)& PolygonRepresentation::GetPoints () const
{
return (fPoints);
}
void PolygonRepresentation::RebuildOSPolygon () const
{
#if qMacGDI
if (fOSPolygon != Nil) {
::KillPoly (fOSPolygon);
}
Tablet::xDoSetPort (kModuleGlobals.fTablet->GetOSGrafPtr ());
*((osPolygon***)&fOSPolygon) = ::OpenPoly (); // avoid const violation error
if (fPoints.GetLength () >= 2) {
Iterator(Point)* i = fPoints;
Point p = i->Current ();
::MoveTo ((short)p.GetH (), (short)p.GetV ());
for (i->Next (); not (i->Done ()); i->Next ()) {
p = i->Current ();
Assert ((short)p.GetH () == p.GetH ());
Assert ((short)p.GetV () == p.GetV ());
::LineTo ((short)p.GetH (), (short)p.GetV ());
}
delete i;
}
::ClosePoly ();
#endif /*qMacGDI*/
}
#if !qRealTemplatesAvailable
BlockAllocatedDeclare (PolygonRepresentation);
BlockAllocatedImplement (PolygonRepresentation);
#endif /*!qRealTemplatesAvailable*/
void* PolygonRepresentation::operator new (size_t n)
{
#if qRealTemplatesAvailable
return (BlockAllocated<PolygonRepresentation>::operator new (n));
#else /*qRealTemplatesAvailable*/
return (BlockAllocated(PolygonRepresentation)::operator new (n));
#endif /*qRealTemplatesAvailable*/
}
void PolygonRepresentation::operator delete (void* p)
{
#if qRealTemplatesAvailable
BlockAllocated<PolygonRepresentation>::operator delete (p);
#else /*qRealTemplatesAvailable*/
BlockAllocated(PolygonRepresentation)::operator delete (p);
#endif /*qRealTemplatesAvailable*/
}
/*
********************************************************************************
******************************** LineRepresentation ****************************
********************************************************************************
*/
LineRepresentation::LineRepresentation (const Point& from, const Point& to):
fFrom (from),
fTo (to)
{
}
void LineRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const
{
/* lines have no interior, only an outline */
}
void LineRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const
{
// probably should somehow use shapeBounds, probably by scaling points (EG QD's ::MapRect, :MapRgn)
// SORRY STERL, But this attemt is wrong! It does not
// use the shapeSize, which it needs to. Use QD mapPt() I think!!!, or do equiv.
on.DrawLine (GetFrom () + shapeBounds.GetOrigin (), GetTo () + shapeBounds.GetOrigin (), pen);
}
Point LineRepresentation::GetLogicalSize () const
{
return (BoundingRect (fFrom, fTo).GetSize ());
}
Point LineRepresentation::GetFrom () const
{
return (fFrom);
}
Point LineRepresentation::GetTo () const
{
return (fTo);
}
Region LineRepresentation::ToRegion (const Rect& shapeBounds) const
{
/*
* Unfortunately, (and I must think this out further) the definition of regions is
* that they are on a pixel basis and represent how many pixels are enclosed. Also,
* somewhat strangly, if a Region contains no pixels, we rename it kEmptyRegion. Since
* lines are infinitely thin, they contain no pixels, and thus their region is empty.
* We may want to consider changing lines to have a thickness, or to intrduce a new
* class that adds this concept.
*/
return (kEmptyRegion);
}
Real LineRepresentation::GetSlope () const
{
AssertNotReached ();
return (0);
}
Real LineRepresentation::GetXIntercept () const
{
AssertNotReached ();
return (0);
}
Real LineRepresentation::GetYIntercept () const
{
AssertNotReached ();
return (0);
}
Point LineRepresentation::GetPointOnLine (Real percentFrom) const
{
AssertNotReached ();
return (kZeroPoint);
}
Line LineRepresentation::GetPerpendicular (const Point& throughPoint) const
{
AssertNotReached ();
return ((LineRepresentation*)this); // just a hack - hack around const and later
// build real line...
}
Line LineRepresentation::GetBisector () const
{
return (GetPerpendicular (GetPointOnLine (0.5)));
}
Real LineRepresentation::GetLength () const
{
return (Distance (fFrom, fTo));
}
#if !qRealTemplatesAvailable
BlockAllocatedDeclare (LineRepresentation);
BlockAllocatedImplement (LineRepresentation);
#endif /*!qRealTemplatesAvailable*/
void* LineRepresentation::operator new (size_t n)
{
#if qRealTemplatesAvailable
return (BlockAllocated<LineRepresentation>::operator new (n));
#else /*qRealTemplatesAvailable*/
return (BlockAllocated(LineRepresentation)::operator new (n));
#endif /*qRealTemplatesAvailable*/
}
void LineRepresentation::operator delete (void* p)
{
#if qRealTemplatesAvailable
BlockAllocated<LineRepresentation>::operator delete (p);
#else /*qRealTemplatesAvailable*/
BlockAllocated(LineRepresentation)::operator delete (p);
#endif /*qRealTemplatesAvailable*/
}
/*
********************************************************************************
*************************** OrientedRectShapeRepresentation ********************
********************************************************************************
*/
// INCOMPLETE!!!! MAYBE BAD IDEA???
OrientedRectShapeRepresentation::OrientedRectShapeRepresentation (const Rect& rect, Angle angle):
ShapeRepresentation (),
fRect (kZeroRect),
fAngle (0),
fRegion (kEmptyRegion)
{
}
OrientedRectShapeRepresentation::OrientedRectShapeRepresentation (const Point& aCorner, const Point& bCorner, Coordinate height):
ShapeRepresentation (),
fRect (kZeroRect),
fAngle (0),
fRegion (kEmptyRegion)
{
}
void OrientedRectShapeRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const
{
}
void OrientedRectShapeRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const
{
}
Region OrientedRectShapeRepresentation::ToRegion (const Rect& shapeBounds) const
{
}
Point OrientedRectShapeRepresentation::GetLogicalSize () const
{
}
// For gnuemacs:
// Local Variables: ***
// mode:C++ ***
// tab-width:4 ***
// End: ***
| 25.810847
| 129
| 0.656178
|
SophistSolutions
|
7f64675a48af53579e50b10fcf74a2893e7bf43b
| 730
|
cc
|
C++
|
ash/quick_pair/common/account_key_failure.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
ash/quick_pair/common/account_key_failure.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86
|
2015-10-21T13:02:42.000Z
|
2022-03-14T07:50:50.000Z
|
ash/quick_pair/common/account_key_failure.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/quick_pair/common/account_key_failure.h"
namespace ash {
namespace quick_pair {
std::ostream& operator<<(std::ostream& stream, AccountKeyFailure failure) {
switch (failure) {
case AccountKeyFailure::kAccountKeyCharacteristicDiscovery:
stream << "[Failed to find the Account Key GATT characteristic]";
break;
case AccountKeyFailure::kAccountKeyCharacteristicWrite:
stream << "[Failed to write to the Account Key GATT characteristic]";
break;
}
return stream;
}
} // namespace quick_pair
} // namespace ash
| 28.076923
| 75
| 0.730137
|
zealoussnow
|
7f648ca329c34393391088b306750f82f8dc4b08
| 5,949
|
cpp
|
C++
|
mbed-glove-firmware/sensor_tests.cpp
|
apadin1/Team-GLOVE
|
d5f5134da79d050164dffdfdf87f12504f6b1370
|
[
"Apache-2.0"
] | null | null | null |
mbed-glove-firmware/sensor_tests.cpp
|
apadin1/Team-GLOVE
|
d5f5134da79d050164dffdfdf87f12504f6b1370
|
[
"Apache-2.0"
] | null | null | null |
mbed-glove-firmware/sensor_tests.cpp
|
apadin1/Team-GLOVE
|
d5f5134da79d050164dffdfdf87f12504f6b1370
|
[
"Apache-2.0"
] | 1
|
2019-01-09T05:16:42.000Z
|
2019-01-09T05:16:42.000Z
|
/*
* Copyright (c) 2016 by Nick Bertoldi, Ben Heckathorn, Ryan O'Keefe,
* Adrian Padin, Timothy Schumacher
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "mbed.h"
#include "rtos.h"
#include "drivers/flex_sensor.h"
#include "drivers/imu.h"
#include "drivers/touch_sensor.h"
#include "drivers/analog_button.h"
#include "drivers/dot_star_leds.h"
#define INCLUDE_TOUCH 1
const PinName GLOVE_I2C_SDA = p30; //I2C_SDA0; // p30
const PinName GLOVE_I2C_SCL = p7; //I2C_SCL0; // p7
static I2C i2c(GLOVE_I2C_SDA, GLOVE_I2C_SCL);
static Serial pc(USBTX, USBRX);
static DigitalOut led(LED1);
static DigitalOut l2(LED2);
static DigitalOut l3(LED3);
static DigitalOut l4(LED4);
void touch_to_lights() {
key_states_t keys;
DigitalOut led1(P0_15);
DigitalOut led2(P0_14);
DigitalOut led3(P0_13);
DigitalOut led4(P0_12);
I2C i2c(I2C_SDA0, I2C_SCL0);
TouchSensor touch_sensor(i2c, TOUCH_INTERRUPT);
for (;;) {
touch_sensor.spawnUpdateThread();
Thread::wait(15);
touch_sensor.writeKeys(&keys);
if (keys.a == 1)
led1 = 0;
else led1 = 1;
if (keys.b == 1)
led2 = 0;
else led2 = 1;
if (keys.c == 1)
led3 = 0;
else led3 = 1;
if (keys.d == 1)
led4 = 0;
else led4 = 1;
touch_sensor.terminateUpdateThreadIfBlocking();
Thread::wait(5);
}
}
void imu_to_lights() {
bno_imu_t data;
DigitalOut led1(P0_15);
DigitalOut led2(P0_14);
DigitalOut led3(P0_13);
DigitalOut led4(P0_12);
led3 = 1;
led1 = 1;
led4 = 1;
led2 = 1;
I2C i2c(I2C_SDA0, I2C_SCL0);
IMU_BNO055 imu(i2c);
/*DEBUG if (imu.hwDebugCheckVal()) {
led4 = 1;
wait_ms(500);
}
for (;;) {
led2 = !led2;
wait_ms(20);
}*/
for (;;) {
led4 = !led4;
imu.updateAndWrite(&data);
if (data.orient_pitch > 30) {
led3 = 0;
}
else led3 = 1;
if (data.orient_roll > 40) {
led2 = 0;
}
else led2 = 1;
//if (data.orient_yaw > 15) {
// led3 = 0;
//}
//else led3 = 1;
wait_ms(20);
}
}
void blink() {
l2 = 1;
led = 0;
for (;;) {
led = !led;
l2 = !l2;
Thread::wait(520);
}
}
void boot_delay(uint8_t t) {
// this loop is to prevent the strange fatal state
// happening with serial debug
led = 1;
for (uint8_t i = 0; i < t; ++i) {
led = 0;
l2 = 0;
l3 = 0;
l4 = 0;
wait(0.25);
led = 1;
l2 = 1;
l3 = 1;
l4 = 1;
wait(0.75);
}
}
void calibration_mode() {
/*
* The idea here is to go into a special mode for a fixed time,
* and measure the maximum and minimum values on all the sensors
*/
// setup objects
const uint16_t ms_period = 20;
for (uint32_t i = 0; i < 8000 / (ms_period - 8); ++i) {
// gather data
// update max/mins
// print results
Thread::wait(ms_period - 8);
}
}
void sensors_to_lights() {
led = 1;
l2 = 1;
l3 = 1;
l4 = 1;
DotStarLEDs ds_leds(2);
uint8_t red, green, blue;
IMU_BNO055 imu(i2c);
bno_imu_t imu_vals;
FlexSensors flex_sensors;
flex_sensor_t flex_vals[4];
//TouchSensor touch_sensor(i2c, p16);
key_states_t keys;
float flex_val;
uint16_t flex_min = 250;
uint16_t flex_max = 750;
/*
* Flex zero sets led 0 red/blue
*
* Any touch sets both lights to bright white
*
* Light one is the combined IMU status
*/
for (;;) {
led = !led;
//touch_sensor.spawnUpdateThread();
imu.updateAndWrite(&imu_vals);
flex_sensors.updateAndWrite(flex_vals);
//touch_sensor.writeKeys(&keys);
imu.print(pc);
//printf("f: %d, clib: 0x%x, p: %f\r\n", flex_vals[0], imu.hwDebugCheckVal(), imu_vals.orient_pitch);
if (flex_vals[0] < flex_min) {
flex_min = flex_vals[0];
}
if (flex_vals[0] > flex_max) {
flex_max = flex_vals[0];
}
if (keys.pack()) {
ds_leds.set_RGB(0,0,255,0);
}
else {
// set flex light
flex_val = map_unsigned_analog_to_percent(flex_min, flex_max, flex_vals[0]);
red = 255*flex_val;
green = 0;
blue = 255*(1-flex_val);
ds_leds.set_RGB(0, red, green, blue);
// set imu light
blue = 255*map_float_analog_to_percent(-45.0, 45.0, imu_vals.orient_pitch);
red = 255*map_float_analog_to_percent(-45.0, 45.0, imu_vals.orient_roll);
green = 255*map_float_analog_to_percent(0.0, 360.0, imu_vals.orient_yaw);
ds_leds.set_RGB(1, red, green, blue, 3);
}
//touch_sensor.terminateUpdateThreadIfBlocking();
Thread::wait(1000);
}
}
| 25.207627
| 109
| 0.593713
|
apadin1
|
7f65000118ec2d9709cec5f5792f3d4512aeba66
| 1,607
|
hpp
|
C++
|
src/component/symbol_table.hpp
|
aabaa/mizcore
|
5542f080278d79a993df741bd3bf3daa24ac28f9
|
[
"MIT"
] | 1
|
2020-11-17T12:47:29.000Z
|
2020-11-17T12:47:29.000Z
|
src/component/symbol_table.hpp
|
aabaa/mizcore
|
5542f080278d79a993df741bd3bf3daa24ac28f9
|
[
"MIT"
] | null | null | null |
src/component/symbol_table.hpp
|
aabaa/mizcore
|
5542f080278d79a993df741bd3bf3daa24ac28f9
|
[
"MIT"
] | 2
|
2020-02-28T09:19:45.000Z
|
2020-02-28T09:26:17.000Z
|
#pragma once
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include "symbol_type.hpp"
#include "tsl/htrie_map.h"
namespace mizcore {
class Symbol;
class SymbolTable
{
public:
// ctor, dtor
SymbolTable();
virtual ~SymbolTable() = default;
SymbolTable(const SymbolTable&) = delete;
SymbolTable(SymbolTable&&) = delete;
SymbolTable& operator=(const SymbolTable&) = delete;
SymbolTable& operator=(SymbolTable&&) = delete;
// attributes
Symbol* AddSymbol(std::string_view filename,
std::string_view text,
SYMBOL_TYPE type,
uint8_t priority = 64);
void AddSynonym(Symbol* s0, Symbol* s1);
void AddValidFileName(std::string_view filename)
{
valid_filenames_.emplace_back(filename);
}
std::vector<Symbol*> CollectFileSymbols(std::string_view filename) const;
const std::vector<std::pair<Symbol*, Symbol*>>& CollectSynonyms() const;
// operations
void Initialize();
void BuildQueryMap();
Symbol* QueryLongestMatchSymbol(std::string_view text) const;
private:
// implementation
void BuildQueryMapOne(std::string_view filename);
static bool IsWordBoundary(std::string_view text, size_t pos);
static bool IsWordBoundaryCharacter(char x);
std::map<std::string, std::vector<std::unique_ptr<Symbol>>> file2symbols_;
std::vector<std::pair<Symbol*, Symbol*>> synonyms_;
std::vector<std::string> valid_filenames_;
tsl::htrie_map<char, Symbol*> query_map_;
};
} // namespace mizcore
| 27.237288
| 78
| 0.676416
|
aabaa
|
7f6e05b69da4a03db5b0fa024ad65f9d7d59f3ae
| 1,312
|
cpp
|
C++
|
src/Compiler/CodeGen/For.cpp
|
BenjaminNavarro/Feral
|
579411c36a1cc66f96fcda1b82e3259e22022ac2
|
[
"BSD-3-Clause"
] | null | null | null |
src/Compiler/CodeGen/For.cpp
|
BenjaminNavarro/Feral
|
579411c36a1cc66f96fcda1b82e3259e22022ac2
|
[
"BSD-3-Clause"
] | null | null | null |
src/Compiler/CodeGen/For.cpp
|
BenjaminNavarro/Feral
|
579411c36a1cc66f96fcda1b82e3259e22022ac2
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2020, Electrux
All rights reserved.
Using the BSD 3-Clause license for the project,
main LICENSE file resides in project's root directory.
Please read that file and understand the license terms
before using or altering the project.
*/
#include "Internal.hpp"
bool stmt_for_t::gen_code( bcode_t & bc, const bool f1, const bool f2 ) const
{
bc.add( idx(), OP_PUSH_LOOP );
if( m_init ) m_init->gen_code( bc );
size_t iter_jmp_loc = bc.size();
if( m_cond ) m_cond->gen_code( bc );
size_t cond_fail_jmp_from = bc.size();
if( m_cond ) {
// placeholder location
bc.addsz( m_cond->idx(), OP_JMPFPOP, 0 );
}
size_t body_begin = bc.size();
m_body->gen_code( bc );
size_t body_end = bc.size();
size_t continue_jmp_loc = bc.size();
if( m_incr ) m_incr->gen_code( bc );
bc.addsz( idx(), OP_JMP, iter_jmp_loc );
if( m_cond ) {
bc.updatesz( cond_fail_jmp_from, bc.size() );
}
// pos where break goes
size_t break_jmp_loc = bc.size();
bc.add( idx(), OP_POP_LOOP );
// update all continue and break calls
for( size_t i = body_begin; i < body_end; ++i ) {
if( bc.at( i ) == OP_CONTINUE && bc.get()[ i ].data.sz == 0 ) bc.updatesz( i, continue_jmp_loc );
if( bc.at( i ) == OP_BREAK && bc.get()[ i ].data.sz == 0 ) bc.updatesz( i, break_jmp_loc );
}
return true;
}
| 25.230769
| 99
| 0.664634
|
BenjaminNavarro
|
7f7265728b572c76da1e29ebe58b29a88f345161
| 2,169
|
cpp
|
C++
|
src/core/features/defuse.cpp
|
mov-rax-rax/gamesneeze
|
09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1
|
[
"MIT"
] | 1
|
2022-01-13T07:05:26.000Z
|
2022-01-13T07:05:26.000Z
|
src/core/features/defuse.cpp
|
mov-rax-rax/gamesneeze
|
09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1
|
[
"MIT"
] | null | null | null |
src/core/features/defuse.cpp
|
mov-rax-rax/gamesneeze
|
09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1
|
[
"MIT"
] | 1
|
2021-12-31T13:02:42.000Z
|
2021-12-31T13:02:42.000Z
|
#include "../../includes.hpp"
#include "features.hpp"
void Features::Defuse::createMoveStart(Command *cmd) {
auto autoDefuse = CONFIGBOOL("Misc>Misc>Misc>Auto Defuse");
auto silentDefuse = CONFIGBOOL("Misc>Misc>Misc>Silent Defuse");
auto antiAiming = CONFIGINT("Rage>AntiAim>Type") != 0;
if (!(autoDefuse || silentDefuse || antiAiming)) {
return;
}
if (Features::Defuse::performDefuse) {
cmd->buttons |= IN_USE;
}
if ((cmd->buttons & IN_USE) != 0 && Features::Defuse::canDefuse && (silentDefuse || antiAiming)) {
cmd->viewAngle = Features::Defuse::angles;
}
}
void Features::Defuse::createMoveEnd(Command *cmd) {
Features::Defuse::canDefuse = false;
Features::Defuse::performDefuse = false;
}
void Features::Defuse::onBombRender(PlantedC4 *bomb) {
auto autoDefuse = CONFIGBOOL("Misc>Misc>Misc>Auto Defuse");
auto silentDefuse = CONFIGBOOL("Misc>Misc>Misc>Silent Defuse");
auto antiAiming = CONFIGINT("Rage>AntiAim>Type") != 0;
if (!(autoDefuse || silentDefuse || antiAiming)) {
Features::Defuse::canDefuse = false;
Features::Defuse::performDefuse = false;
return;
}
auto playerOrigin = Globals::localPlayer->origin();
auto bombOrigin = bomb->origin();
if (getDistanceNoSqrt(playerOrigin, bombOrigin) < 5625) {
Features::Defuse::canDefuse = true;
} else {
Features::Defuse::canDefuse = false;
}
if (silentDefuse || antiAiming) {
auto eyePos = Globals::localPlayer->eyePos();
auto angles = calcAngle(eyePos, bombOrigin);
clampAngle(angles);
Features::Defuse::angles = angles;
}
if (CONFIGBOOL("Misc>Misc>Misc>Latest Defuse")) {
auto timeRemaining = bomb->time() - (Interfaces::globals->currentTime + ((float)playerResource->GetPing(Globals::localPlayer->index()) / 1000.f));
if (timeRemaining < (Globals::localPlayer->defuser() ? 5.1f: 10.1f)) {
Features::Defuse::performDefuse = true;
return;
}
} else {
Features::Defuse::performDefuse = true;
}
Features::Defuse::performDefuse = false;
}
| 30.549296
| 154
| 0.632089
|
mov-rax-rax
|
7f771b35efe4c9619b2da87401e3ab7679742766
| 3,159
|
hpp
|
C++
|
packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.hpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 10
|
2019-11-14T19:58:30.000Z
|
2021-04-04T17:44:09.000Z
|
packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.hpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 43
|
2020-03-03T19:59:20.000Z
|
2021-09-08T03:36:08.000Z
|
packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.hpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 6
|
2020-02-12T17:37:07.000Z
|
2020-09-08T18:59:51.000Z
|
//---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_AdjointPhotonProbeState.hpp
//! \author Alex Robinson
//! \brief Adjoint photon probe state class declaration
//!
//---------------------------------------------------------------------------//
#ifndef MONTE_CARLO_ADJOINT_PHOTON_PROBE_STATE_HPP
#define MONTE_CARLO_ADJOINT_PHOTON_PROBE_STATE_HPP
// Boost Includes
#include <boost/serialization/shared_ptr.hpp>
// FRENSIE Includes
#include "MonteCarlo_AdjointPhotonState.hpp"
#include "Utility_TypeNameTraits.hpp"
namespace MonteCarlo{
/*! The adjoint photon probe state class
* \details The probe state get killed when its energy changes (after being
* activated).
*/
class AdjointPhotonProbeState : public AdjointPhotonState
{
public:
// The adjoint photon probe tag
struct AdjointPhotonProbeTag{};
// Typedef for the adjoint photon probe tag
struct AdjointPhotonProbeTag ParticleTag;
//! Default constructor
AdjointPhotonProbeState();
//! Constructor
AdjointPhotonProbeState(
const ParticleState::historyNumberType history_number );
//! Copy constructor (with possible creation of new generation)
AdjointPhotonProbeState( const ParticleState& existing_base_state,
const bool increment_generation_number = false,
const bool reset_collision_number = false );
//! Copy constructor (with possible creation of new generation)
AdjointPhotonProbeState( const AdjointPhotonProbeState& existing_base_state,
const bool increment_generation_number = false,
const bool reset_collision_number = false );
//! Destructor
~AdjointPhotonProbeState()
{ /* ... */ }
//! Set the energy of the particle (MeV)
void setEnergy( const energyType energy );
//! Check if this is a probe
bool isProbe() const;
//! Activate the probe
void activate();
//! Returns if the probe is active
bool isActive() const;
//! Clone the particle state (do not use to generate new particles!)
AdjointPhotonProbeState* clone() const;
//! Print the adjoint photon state
void toStream( std::ostream& os ) const;
private:
// Save the state to an archive
template<typename Archive>
void serialize( Archive& ar, const unsigned version )
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(AdjointPhotonState);
ar & BOOST_SERIALIZATION_NVP( d_active );
}
// Declare the boost serialization access object as a friend
friend class boost::serialization::access;
// Flag that indicates if the probe is active
bool d_active;
};
} // end MonteCarlo namespace
BOOST_CLASS_VERSION( MonteCarlo::AdjointPhotonProbeState, 0 );
BOOST_CLASS_EXPORT_KEY2( MonteCarlo::AdjointPhotonProbeState, "AdjointPhotonProbeState" );
EXTERN_EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo, AdjointPhotonProbeState );
TYPE_NAME_TRAITS_QUICK_DECL2( AdjointPhotonProbeState, MonteCarlo );
#endif // end MONTE_CARLO_ADJOINT_PHOTON_PROBE_STATE_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_AdjointPhotonProbeState.hpp
//---------------------------------------------------------------------------//
| 30.375
| 90
| 0.686926
|
bam241
|
7f7a350edbf1b381dbd5d2994a11701cbd83b77b
| 3,015
|
cpp
|
C++
|
Ejercicios/Ejercicio44-Punto-de-Venta-parte-V/productos.cpp
|
DanielaVH/cpp
|
c54c853681cdd46d85172546b14019ed48909999
|
[
"MIT"
] | null | null | null |
Ejercicios/Ejercicio44-Punto-de-Venta-parte-V/productos.cpp
|
DanielaVH/cpp
|
c54c853681cdd46d85172546b14019ed48909999
|
[
"MIT"
] | null | null | null |
Ejercicios/Ejercicio44-Punto-de-Venta-parte-V/productos.cpp
|
DanielaVH/cpp
|
c54c853681cdd46d85172546b14019ed48909999
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
extern void agregarProducto(string descripcion, int cantidad, double precio);
void productos(int opcion)
{
system("cls");
int opcionProducto = 0;
switch (opcion)
{
case 1:
{
cout << "BEBIDAS CALIENTES" << endl;
cout << "******************" << endl;
cout << "1- Capuccino" << endl;
cout << "2- Expresso" << endl;
cout << "3- Cafe Latte" << endl;
cout << endl;
cout << "Ingrese una opcion: ";
cin >> opcionProducto;
switch (opcionProducto)
{
case 1:
agregarProducto("1 Capuccino - L 40.00", 1, 40);
break;
case 2:
agregarProducto("1 Expresso - L 30.00", 1, 30);
break;
case 3:
agregarProducto("1 Cafe Latte - L 40.00", 1, 40);
break;
default:
{
cout << "opcion no valida";
return;
break;
}
}
cout << endl;
cout << "Producto agregado" << endl << endl;
system("pause");
break;
}
case 2:
{
cout << "BEBIDAS FRIAS" << endl;
cout << "************" << endl;
cout << "1- Granita de cafe" << endl;
cout << "2- Mochaccino" << endl;
cout << "3- Frapuchatta" << endl;
cout << endl;
cout << "Ingrese una opcion: ";
cin >> opcionProducto;
switch (opcionProducto)
{
case 1:
agregarProducto("1 Granita de cafe - L 30.00", 1, 30);
break;
case 2:
agregarProducto("1 Expresso - L 60.00", 1, 60);
break;
case 3:
agregarProducto("1 Frapuchatta - L 70.00", 1, 70);
break;
default:
{
cout << "opcion no valida";
return;
break;
}
}
cout << endl;
cout << "Producto agregado" << endl << endl;
system("pause");
break;
}
case 3:
{
cout << "REPOSTERIA" << endl;
cout << "*********" << endl;
cout << "1- Porcion-Pastel de Zanahoria" << endl;
cout << "2- Galleta alfajor" << endl;
cout << "3- Porcion-Pastel de Limon" << endl;
cout << endl;
cout << "Ingrese una opcion: ";
cin >> opcionProducto;
switch (opcionProducto)
{
case 1:
agregarProducto("1 Porcion-Pastel de Zanahoria - L 40.00", 1, 40);
break;
case 2:
agregarProducto("1 Galleta alfajor - L 30.00", 1, 30);
break;
case 3:
agregarProducto("1 Porcion-Pastel de limon - L 60.00", 1, 60);
break;
default:
{
cout << "opcion no valida";
return;
break;
}
}
cout << endl;
cout << "Producto agregado" << endl << endl;
system("pause");
break;
}
default:
break;
}
}
| 22.333333
| 78
| 0.448093
|
DanielaVH
|
7f7eb0c1e0f936d0f4e7a2690c69c17e9e1d80e0
| 5,504
|
cpp
|
C++
|
tests/bint_div.cpp
|
mrdcvlsc/bintlib
|
9290f779eb50101bd35b00148eea94c5c30dcc61
|
[
"MIT"
] | 2
|
2020-10-30T06:39:01.000Z
|
2020-10-31T02:18:00.000Z
|
tests/bint_div.cpp
|
mrdcvlsc/bintlib
|
9290f779eb50101bd35b00148eea94c5c30dcc61
|
[
"MIT"
] | 2
|
2020-10-30T06:49:01.000Z
|
2020-10-31T11:12:42.000Z
|
tests/bint_div.cpp
|
mrdcvlsc/bintlib
|
9290f779eb50101bd35b00148eea94c5c30dcc61
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#ifndef _MAKE_LIB
#include "../core.hpp"
#else
#include <bint.hpp>
#endif
#include "mini-test.hpp"
int main() { START_TEST;
// test variables
apa::bint ONE = 1, ZERO = 0;
apa::bint NUM1(
"0x19cf0546f6a3fc1e93d8dbda5ea2889551cb7248d21125fbf60f3c622a4ab01456703c3"
"39c96f18bed4ce4fa268983f97dcb83ae847f8ecf19f81870578c41ede22ccf76553d1c38"
"deb692820ac53f361c2a2e0b0dc6e6b77810b15d656775b37fc2afb2200632008419c0555"
"ccffd2f9377262ef48b6a096629b8af1048f07dc1a8152eebd3d209041dfccb9df9e5ef94"
"f4b55bae8fb825d7dcfb68e89e0ab027f27bbd2d0b226a82e0fbcc85eeb8b1df2c6fd6ee3"
"8e4b43e78649af542686ba5a385d34ed7c51c6b77c5ab1ff868deca9b0158edc44de55c44",16
);
apa::bint NUM2(
"0xa4027a170efee729e543877bc6d8cb88c00810d0b3f18c77f9755907f470a1a94f4ab26"
"825e763265c216490f5a93c0426485cc2bfc99ed1fd883aa983759e4662f26cdd96cf3289",16
);
apa::bint NUM3 = 2;
apa::bint NUM1_DIV_NUM2(
"0x2848ca2401c26ea27bfc2689ff8ce447b6092adcab3c610c5d646521e7a4358f0aa93a39"
"d8ec904a02856cf99e4456452e00a219a64b823b59edadaa23841fa573d848bc586e2840ca"
"c74808ed76bff1a3168be007b1f2270efbbb42156794955629291df55af4ae1f3933e5dc77"
"9f5c0b38f66e4a48da1d91a4461c682f0bdd4d688f6b70b338b7895a4ce0fb3236c7be0e",16
);
apa::bint NUM1_DIV_NUM3(
"0xce782a37b51fe0f49ec6ded2f51444aa8e5b924690892fdfb079e311525580a2b381e19ce"
"4b78c5f6a6727d1344c1fcbee5c1d7423fc7678cfc0c382bc620f6f11667bb2a9e8e1c6f5b4"
"94105629f9b0e15170586e3735bbc0858aeb2b3bad9bfe157d910031900420ce02aae67fe97"
"c9bb93177a45b504b314dc578824783ee0d40a9775e9e904820efe65cefcf2f7ca7a5aadd74"
"7dc12ebee7db4744f055813f93dde9685913541707de642f75c58ef9637eb771c725a1f3c32"
"4d7aa13435d2d1c2e9a76be28e35bbe2d58ffc346f654d80ac76e226f2ae22",16
);
apa::bint NUM2_DIV_NUM3(
"0x52013d0b877f7394f2a1c3bde36c65c46004086859f8c63bfcbaac83fa3850d4a7a559341"
"2f3b1932e10b2487ad49e0213242e615fe4cf68fec41d54c1bacf233179366ecb679944",16
);
apa::bint NUM1_MOD_NUM2(
"0x79b744150065c5ae9c0a197c73841d9a27735226bdd3e6177c1956e524095dad2dd6f9799"
"fb95a944dc7b49a9bc204b1b81eb48bd25ecf6d7eef5f8afdcfc44cce56623d188feac6",16
);
apa::bint NUM1_MOD_NUM3 = 0;
apa::bint NUM2_MOD_NUM3 = 1;
apa::bint
ANSQ1 = NUM1/NUM2, ANSQ1_NEG = -NUM1 / NUM2,
ANSQ2 = NUM1/NUM3,
ANSQ3 = NUM2/NUM3,
ANSR1 = NUM1%NUM2,
ANSR2 = NUM1%NUM3,
ANSR3 = NUM2%NUM3;
ASSERT_EQUALITY((-NUM1)/NUM1,(-ONE), "1 -NUM1/NUM1 ");
ASSERT_EQUALITY(NUM2/NUM2,ONE, "2 NUM2/NUM2 ");
ASSERT_EQUALITY(NUM3/NUM3,ONE, "3 NUM3/NUM3 ");
ASSERT_EQUALITY((NUM1/NUM1),ONE, "4 NUM1/NUM1 ");
ASSERT_EQUALITY((NUM2/NUM2),ONE, "5 NUM2/NUM2 ");
ASSERT_EQUALITY((NUM3/NUM3),ONE, "6 NUM3/NUM3 ");
ASSERT_EQUALITY(ANSQ1,NUM1_DIV_NUM2, "7 NUM1/NUM2 ");
ASSERT_EQUALITY(ANSQ1_NEG,-NUM1_DIV_NUM2, "7.5 -NUM1/NUM2");
ASSERT_EQUALITY(ANSQ2,NUM1_DIV_NUM3, "8 NUM1/NUM3 ");
ASSERT_EQUALITY(ANSQ3,NUM2_DIV_NUM3, "9 NUM2/NUM3 ");
ASSERT_EQUALITY((NUM1/(-NUM2)),(-NUM1_DIV_NUM2),"10 -NUM1/NUM2 ");
ASSERT_EQUALITY((NUM1/NUM3),NUM1_DIV_NUM3, "11 NUM1/NUM3 ");
ASSERT_EQUALITY(((-NUM2)/NUM3),(-NUM2_DIV_NUM3),"12 -NUM2/NUM3 ");
ASSERT_EQUALITY((NUM3/NUM1),ZERO, "13 NUM3/NUM1 ");
ASSERT_EQUALITY((NUM3/NUM2),ZERO, "14 NUM3/NUM2 ");
ASSERT_EQUALITY((NUM2/NUM1),ZERO, "15 NUM2/NUM1 ");
apa::bint NEGNUM1_MOD_NUM1 = (-NUM1)%NUM1;
ASSERT_EQUALITY(NEGNUM1_MOD_NUM1,ZERO, "16 -NUM1%NUM1 ");
ASSERT_EQUALITY(NUM2%NUM2,ZERO, "17 NUM2%NUM2 ");
ASSERT_EQUALITY(NUM3%NUM3,ZERO, "18 NUM3%NUM13 ");
ASSERT_EQUALITY((NUM1%NUM1),ZERO, "19 NUM1%NUM1 ");
ASSERT_EQUALITY((NUM2%NUM2),ZERO, "20 NUM2%NUM2 ");
ASSERT_EQUALITY((NUM3%NUM3),ZERO, "21 NUM3%NUM3 ");
ASSERT_EQUALITY(ANSR1,NUM1_MOD_NUM2, "22 NUM1%NUM2 ");
ASSERT_EQUALITY(ANSR2,NUM1_MOD_NUM3, "23 NUM1%NUM3 ");
ASSERT_EQUALITY(ANSR3,NUM2_MOD_NUM3, "24 NUM2%NUM3 ");
apa::bint NEG_NUM1_MOD_NUM2 = -NUM1 % NUM2;
apa::bint NUM1_MOD_NEG_NUM2 = NUM1 % -NUM2;
ASSERT_EQUALITY(NEG_NUM1_MOD_NUM2,-NUM1_MOD_NUM2,"25 -NUM1%NUM2 ");
ASSERT_EQUALITY(NUM1_MOD_NEG_NUM2,NUM1_MOD_NUM2,"26 NUM1%-NUM2 ");
ASSERT_EQUALITY((NUM1%(-NUM3)),(apa::__BINT_ZERO),"27 NUM1%-NUM3 ");
ASSERT_EQUALITY((NUM2%NUM3),NUM2_MOD_NUM3, "28 NUM2%NUM3 ");
ASSERT_EQUALITY((NUM3%NUM1),NUM3, "29 NUM3%NUM1 ");
ASSERT_EQUALITY((NUM3%NUM2),NUM3, "30 NUM3%NUM2 ");
ASSERT_EQUALITY((NUM2%NUM1),NUM2, "31 NUM2%NUM1 ");
#if defined(_BASE2_16)
RESULT("BINT BASE 2^16 DIVISION");
#elif defined(_BASE2_32)
RESULT("BINT BASE 2^32 DIVISION");
#elif defined(_BASE2_64)
RESULT("BINT BASE 2^64 DIVISION");
#endif
}
| 45.866667
| 90
| 0.646802
|
mrdcvlsc
|
7f7fd0a272828d9329a064393a4fb8097fcfcaf6
| 2,850
|
cpp
|
C++
|
ardupilot/libraries/AP_BattMonitor/AP_BattMonitor_SMBus_PX4.cpp
|
quadrotor-IITKgp/emulate_GPS
|
3c888d5b27b81fb17e74d995370f64bdb110fb65
|
[
"MIT"
] | 1
|
2021-07-17T11:37:16.000Z
|
2021-07-17T11:37:16.000Z
|
ardupilot/libraries/AP_BattMonitor/AP_BattMonitor_SMBus_PX4.cpp
|
arl-kgp/emulate_GPS
|
3c888d5b27b81fb17e74d995370f64bdb110fb65
|
[
"MIT"
] | null | null | null |
ardupilot/libraries/AP_BattMonitor/AP_BattMonitor_SMBus_PX4.cpp
|
arl-kgp/emulate_GPS
|
3c888d5b27b81fb17e74d995370f64bdb110fb65
|
[
"MIT"
] | null | null | null |
/*
Battery SMBus PX4 driver
*/
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <AP_HAL/AP_HAL.h>
#if CONFIG_HAL_BOARD == HAL_BOARD_PX4
#include "AP_BattMonitor_SMBus_PX4.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <drivers/drv_batt_smbus.h>
#include <uORB/topics/battery_status.h>
extern const AP_HAL::HAL& hal;
// Constructor
AP_BattMonitor_SMBus_PX4::AP_BattMonitor_SMBus_PX4(AP_BattMonitor &mon, uint8_t instance, AP_BattMonitor::BattMonitor_State &mon_state) :
AP_BattMonitor_SMBus(mon, instance, mon_state),
_batt_fd(-1),
_capacity_updated(false)
{
// orb subscription for battery status
_batt_sub = orb_subscribe(ORB_ID(battery_status));
}
void AP_BattMonitor_SMBus_PX4::init()
{
// open the device
_batt_fd = open(BATT_SMBUS0_DEVICE_PATH, O_RDWR);
if (_batt_fd == -1) {
hal.console->printf("Unable to open " BATT_SMBUS0_DEVICE_PATH);
_state.healthy = false;
}
}
// read - read latest voltage and current
void AP_BattMonitor_SMBus_PX4::read()
{
bool updated = false;
struct battery_status_s batt_status;
// check if new info has arrived from the orb
orb_check(_batt_sub, &updated);
// retrieve latest info
if (updated) {
if (OK == orb_copy(ORB_ID(battery_status), _batt_sub, &batt_status)) {
_state.voltage = batt_status.voltage_v;
_state.current_amps = batt_status.current_a;
_state.last_time_micros = hal.scheduler->micros();
_state.current_total_mah = batt_status.discharged_mah;
_state.healthy = true;
// read capacity
if ((_batt_fd >= 0) && !_capacity_updated) {
uint16_t tmp;
if (ioctl(_batt_fd, BATT_SMBUS_GET_CAPACITY, (unsigned long)&tmp) == OK) {
_capacity_updated = true;
set_capacity(tmp);
}
}
}
} else if (_state.healthy) {
// timeout after 5 seconds
if ((hal.scheduler->micros() - _state.last_time_micros) > AP_BATTMONITOR_SMBUS_TIMEOUT_MICROS) {
_state.healthy = false;
}
}
}
#endif // CONFIG_HAL_BOARD == HAL_BOARD_PX4
| 31.318681
| 137
| 0.669825
|
quadrotor-IITKgp
|
7f8142b6435655dade52964f1658b48d4b45c721
| 276
|
hpp
|
C++
|
tools/editor/utils.hpp
|
ijacquez/SMT-DS-SH
|
6fe6c15b76fb74ecb5bbb735139aa5791d79fcb8
|
[
"MIT"
] | 6
|
2015-10-03T20:51:04.000Z
|
2019-10-21T04:19:06.000Z
|
tools/editor/utils.hpp
|
ijacquez/SMT-DS-SH
|
6fe6c15b76fb74ecb5bbb735139aa5791d79fcb8
|
[
"MIT"
] | null | null | null |
tools/editor/utils.hpp
|
ijacquez/SMT-DS-SH
|
6fe6c15b76fb74ecb5bbb735139aa5791d79fcb8
|
[
"MIT"
] | null | null | null |
#ifndef UTILS_HPP
#define UTILS_HPP
#include "jansson.h"
#define BIG2LE_16(x) (((x) & 0x00FF) << 8) | (((x) >> 8) & 0x00FF)
#define BIG2LE_32(x) (BIG2LE_16((x) & 0x0000FFFF) << 16) | \
BIG2LE_16(((x) >> 16) & 0x0000FFFF)
#endif /* !UTILS_HPP */
| 25.090909
| 80
| 0.547101
|
ijacquez
|
7f83d6e4766ea81b9e559b467aa37682d6ef14dc
| 10,242
|
cc
|
C++
|
tls/src/params.cc
|
centreon-lab/centreon-broker
|
b412470204eedc01422bbfd00bcc306dfb3d2ef5
|
[
"Apache-2.0"
] | 40
|
2015-03-10T07:55:39.000Z
|
2021-06-11T10:13:56.000Z
|
tls/src/params.cc
|
centreon-lab/centreon-broker
|
b412470204eedc01422bbfd00bcc306dfb3d2ef5
|
[
"Apache-2.0"
] | 297
|
2015-04-30T10:02:04.000Z
|
2022-03-09T13:31:54.000Z
|
tls/src/params.cc
|
centreon-lab/centreon-broker
|
b412470204eedc01422bbfd00bcc306dfb3d2ef5
|
[
"Apache-2.0"
] | 29
|
2015-08-03T10:04:15.000Z
|
2021-11-25T12:21:00.000Z
|
/*
** Copyright 2009-2013,2021 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include "com/centreon/broker/tls/params.hh"
#include <gnutls/gnutls.h>
#include <cstdlib>
#include "com/centreon/broker/log_v2.hh"
#include "com/centreon/broker/tls/internal.hh"
#include "com/centreon/exceptions/msg_fmt.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::tls;
using namespace com::centreon::exceptions;
/**
* Params constructor.
*
* @param[in] type Either CLIENT or SERVER, depending on connection
* initialization. This cannot be modified after
* construction.
*/
params::params(params::connection_type type)
: _compress(false), _init(false), _type(type) {}
/**
* Destructor.
*/
params::~params() {
_clean();
}
/**
* Apply parameters to a GNU TLS session object.
*
* @param[out] session Object on which parameters will be applied.
*/
void params::apply(gnutls_session_t session) {
// Set the encryption method (normal ciphers with anonymous
// Diffie-Hellman and optionnally compression).
int ret;
ret = gnutls_priority_set_direct(
session,
(_compress ? "NORMAL:-VERS-DTLS1.0:-VERS-DTLS1.2:-VERS-SSL3.0:-VERS-TLS1."
"0:-VERS-TLS1.1:+ANON-DH:%COMPAT"
: "NORMAL:-VERS-DTLS1.0:-VERS-DTLS1.2:-VERS-SSL3.0:-VERS-TLS1."
"0:-VERS-TLS1.1:+ANON-DH:+COMP-"
"DEFLATE:%COMPAT"),
nullptr);
if (ret != GNUTLS_E_SUCCESS) {
log_v2::tls()->error("TLS: encryption parameter application failed: {}",
gnutls_strerror(ret));
throw msg_fmt("TLS: encryption parameter application failed: {}",
gnutls_strerror(ret));
}
// Set anonymous credentials...
if (_cert.empty() || _key.empty()) {
if (CLIENT == _type) {
log_v2::tls()->info("TLS: using anonymous client credentials");
ret = gnutls_credentials_set(session, GNUTLS_CRD_ANON, _cred.client);
} else {
log_v2::tls()->info("TLS: using anonymous server credentials");
ret = gnutls_credentials_set(session, GNUTLS_CRD_ANON, _cred.server);
}
}
// ... or certificate credentials.
else {
log_v2::tls()->info("TLS: using certificates as credentials");
ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, _cred.cert);
if (SERVER == _type)
gnutls_certificate_server_set_request(session, GNUTLS_CERT_REQUEST);
}
if (ret != GNUTLS_E_SUCCESS) {
log_v2::tls()->error("TLS: could not set credentials: {}",
gnutls_strerror(ret));
throw msg_fmt("TLS: could not set credentials: {}", gnutls_strerror(ret));
}
}
/**
* Load TLS parameters.
*/
void params::load() {
// Certificate-based.
if (!_cert.empty() && !_key.empty()) {
// Initialize credentials.
int ret;
ret = gnutls_certificate_allocate_credentials(&_cred.cert);
if (ret != GNUTLS_E_SUCCESS) {
log_v2::tls()->error("TLS: credentials allocation failed: {}",
gnutls_strerror(ret));
throw msg_fmt("TLS: credentials allocation failed: {}",
gnutls_strerror(ret));
}
gnutls_certificate_set_dh_params(_cred.cert, dh_params);
_init = true;
// Load certificate files.
ret = gnutls_certificate_set_x509_key_file(
_cred.cert, _cert.c_str(), _key.c_str(), GNUTLS_X509_FMT_PEM);
if (ret != GNUTLS_E_SUCCESS) {
log_v2::tls()->error("TLS: could not load certificate ({}, {}): {}",
_cert, _key, gnutls_strerror(ret));
throw msg_fmt("TLS: could not load certificate: {}",
gnutls_strerror(ret));
}
if (!_ca.empty()) {
// Load certificate.
ret = gnutls_certificate_set_x509_trust_file(_cred.cert, _ca.c_str(),
GNUTLS_X509_FMT_PEM);
if (ret <= 0) {
log_v2::tls()->error(
"TLS: could not load trusted Certificate Authority's certificate "
"'{}': {}",
_ca, gnutls_strerror(ret));
throw msg_fmt(
"TLS: could not load trusted Certificate Authority's certificate: "
"{}",
gnutls_strerror(ret));
}
}
}
// Anonymous.
else
_init_anonymous();
}
/**
* @brief Reset parameters to their default values.
*
* Parameters are changed back to the default anonymous mode without
* compression.
*/
void params::reset() {
_clean();
}
/**
* @brief Set certificates to use for connection encryption.
*
* Two encryption mode are provided : anonymous and certificate-based.
* If you want to use certificates for encryption, call this function
* with the name of the PEM-encoded public certificate (cert) and the
* private key (key).
*
* @param[in] cert The path to the PEM-encoded public certificate.
* @param[in] key The path to the PEM-encoded private key.
*/
void params::set_cert(std::string const& cert, std::string const& key) {
_cert = cert;
_key = key;
}
/**
* @brief Set the compression mode (on/off).
*
* Determines whether or not the encrypted stream should also be
* compressed using the Deflate algorithm. This kind of compression
* usually works well on text or other compressible data. The
* compression algorithm, may be useful in high bandwidth TLS tunnels,
* and in cases where network usage has to be minimized. As a drawback,
* compression increases latency.
*
* @param[in] compress true if the stream should be compressed, false
* otherwise.
*/
void params::set_compression(bool compress) {
_compress = compress;
}
/**
* @brief Set the hostname.
*
* If this parameter is set, certificate verify peers use this hostname rather
* than the common name of the certificate.
*
* @param[in] tls_hostname the name of common name on the certificate.
*/
void params::set_tls_hostname(std::string const& tls_hostname) {
_tls_hostname = tls_hostname;
}
/**
* @brief Set the trusted CA certificate.
*
* If this parameter is set, certificate checking will be performed on
* the connection against this CA certificate.
*
* @param[in] ca_cert The path to the PEM-encoded public certificate of
* the trusted Certificate Authority.
*/
void params::set_trusted_ca(std::string const& ca_cert) {
_ca = ca_cert;
}
/**
* @brief Check if the peer's certificate is valid.
*
* Check if the certificate invalid or revoked or untrusted or
* insecure. In those case, the connection should not be trusted. If no
* certificate is used for this connection or no trusted CA has been
* set, the method will return false.
*
* @param[in] session Session on which checks will be performed.
*/
void params::validate_cert(gnutls_session_t session) {
if (!_ca.empty()) {
int ret;
uint32_t status;
if (!_tls_hostname.empty()) {
log_v2::tls()->info(
"TLS: common name '{}' used for certificate verification",
_tls_hostname);
ret = gnutls_certificate_verify_peers3(session, _tls_hostname.c_str(),
&status);
} else {
log_v2::tls()->info(
"TLS: Server hostname used for certificate verification");
ret = gnutls_certificate_verify_peers2(session, &status);
}
if (ret != GNUTLS_E_SUCCESS) {
log_v2::tls()->error(
"TLS: certificate verification failed , assuming invalid "
"certificate: {}",
gnutls_strerror(ret));
throw msg_fmt(
"TLS: certificate verification failed, assuming invalid certificate: "
"{}",
gnutls_strerror(ret));
} else if (status & GNUTLS_CERT_INVALID) {
log_v2::tls()->error("TLS: peer certificate is invalid");
throw msg_fmt("TLS: peer certificate is invalid");
} else if (status & GNUTLS_CERT_REVOKED) {
log_v2::tls()->error("TLS: peer certificate was revoked");
throw msg_fmt("TLS: peer certificate was revoked");
} else if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) {
log_v2::tls()->error(
"TLS: peer certificate was not issued by a trusted authority");
throw msg_fmt(
"TLS: peer certificate was not issued by a trusted authority");
} else if (status & GNUTLS_CERT_INSECURE_ALGORITHM) {
log_v2::tls()->error(
"TLS: peer certificate is using an insecure algorithm that cannot be "
"trusted");
throw msg_fmt(
"TLS: peer certificate is using an insecure algorithm that cannot be "
"trusted");
}
}
}
/**
* @brief Clean the params instance.
*
* All allocated ressources will be released.
*/
void params::_clean() {
if (_init) {
if (_cert.empty() || _key.empty()) {
if (CLIENT == _type)
gnutls_anon_free_client_credentials(_cred.client);
else
gnutls_anon_free_server_credentials(_cred.server);
} else
gnutls_certificate_free_credentials(_cred.cert);
_init = false;
}
}
/**
* Initialize anonymous credentials.
*/
void params::_init_anonymous() {
int ret;
if (CLIENT == _type)
ret = gnutls_anon_allocate_client_credentials(&_cred.client);
else
ret = gnutls_anon_allocate_server_credentials(&_cred.server);
if (ret != GNUTLS_E_SUCCESS) {
log_v2::tls()->error("TLS: anonymous credentials initialization failed: {}",
gnutls_strerror(ret));
throw msg_fmt("TLS: anonymous credentials initialization failed: {}",
gnutls_strerror(ret));
}
if (_type != CLIENT)
gnutls_anon_set_server_dh_params(_cred.server, dh_params);
_init = true;
}
| 33.03871
| 80
| 0.647335
|
centreon-lab
|
7f872e524a56490cc8fea1da694a27bdc9480b4a
| 296
|
cpp
|
C++
|
main.cpp
|
RoliSoft/Obfuscation-Tunnel
|
cbd31a1c80a7bd5b51057e1a976628727fc8987e
|
[
"BSD-2-Clause"
] | 11
|
2020-09-15T11:59:41.000Z
|
2022-02-11T16:49:08.000Z
|
main.cpp
|
RoliSoft/Obfuscation-Tunnel
|
cbd31a1c80a7bd5b51057e1a976628727fc8987e
|
[
"BSD-2-Clause"
] | 2
|
2021-11-13T12:38:01.000Z
|
2021-12-06T01:38:07.000Z
|
main.cpp
|
RoliSoft/Obfuscation-Tunnel
|
cbd31a1c80a7bd5b51057e1a976628727fc8987e
|
[
"BSD-2-Clause"
] | 2
|
2021-08-12T07:43:16.000Z
|
2021-08-23T00:12:20.000Z
|
#include "factory.cpp"
int main(int argc, char* argv[])
{
signal(SIGINT, sig_handler);
struct session session;
int ret = parse_arguments(argc, argv, &session);
if (ret == EXIT_SUCCESS || ret == EXIT_FAILURE)
{
return ret;
}
return run_session(&session);
}
| 17.411765
| 52
| 0.618243
|
RoliSoft
|
7f8da4f6e297a835989c59cdb729061244ed91ea
| 401
|
cpp
|
C++
|
vjezbe3/zadatak2/main.cpp
|
Miillky/objektno_orijentirano_programiranje
|
b41fe690c25a73acd09aff5606524b9e43f0b38a
|
[
"MIT"
] | null | null | null |
vjezbe3/zadatak2/main.cpp
|
Miillky/objektno_orijentirano_programiranje
|
b41fe690c25a73acd09aff5606524b9e43f0b38a
|
[
"MIT"
] | null | null | null |
vjezbe3/zadatak2/main.cpp
|
Miillky/objektno_orijentirano_programiranje
|
b41fe690c25a73acd09aff5606524b9e43f0b38a
|
[
"MIT"
] | null | null | null |
// Prošlu strukturu i funkcije implementirajte u zasebnoj datoteci zaglavlja i implementacije(kompleksniBroj.hpp i KompleksniBroj.cpp)
// U glavnoj datoteci includajte vašu datoteku i prikažite korištenje strukture i pripadnih funkcija.
#include <iostream>
#include "KompleksniBroj.hpp"
int main(){
prikaziKompleksniBroj(23.3, 67.2);
std::cout << zbrojiKompleksneBrojeve(23.3, 67.2).zbroj;
}
| 40.1
| 134
| 0.783042
|
Miillky
|
7f91fcd150dfc74048f2f3e4c806d85457f6bb95
| 50
|
hpp
|
C++
|
include/JsonLoader.hpp
|
0x0015/CP2DG
|
ae919b15dc06631171116b927ff46d7d98da4dd9
|
[
"MIT"
] | 2
|
2021-10-06T03:11:06.000Z
|
2022-01-06T18:53:43.000Z
|
include/JsonLoader.hpp
|
0x0015/CP2DG
|
ae919b15dc06631171116b927ff46d7d98da4dd9
|
[
"MIT"
] | null | null | null |
include/JsonLoader.hpp
|
0x0015/CP2DG
|
ae919b15dc06631171116b927ff46d7d98da4dd9
|
[
"MIT"
] | null | null | null |
#pragma once
#include "JsonLoader/JsonLoader.hpp"
| 16.666667
| 36
| 0.8
|
0x0015
|
7f94b0353c36e3bed4d29bfca747840bde03bc43
| 9,396
|
cpp
|
C++
|
test/test_core_estimator.cpp
|
accosmin/libnan
|
a47c28f22df2c0943697dccb007de946090c7705
|
[
"MIT"
] | null | null | null |
test/test_core_estimator.cpp
|
accosmin/libnan
|
a47c28f22df2c0943697dccb007de946090c7705
|
[
"MIT"
] | null | null | null |
test/test_core_estimator.cpp
|
accosmin/libnan
|
a47c28f22df2c0943697dccb007de946090c7705
|
[
"MIT"
] | null | null | null |
#include <fstream>
#include <utest/utest.h>
#include "fixture/enum.h"
#include <nano/core/stream.h>
#include <nano/core/estimator.h>
using namespace nano;
static auto to_string(const estimator_t& estimator)
{
std::ostringstream stream;
UTEST_REQUIRE_NOTHROW(estimator.write(stream));
UTEST_REQUIRE(stream);
return stream.str();
}
static auto check_stream(const estimator_t& estimator)
{
{
std::ofstream stream;
UTEST_CHECK_THROW(estimator.write(stream), std::runtime_error);
}
string_t str;
{
std::ostringstream stream;
UTEST_CHECK_NOTHROW(estimator.write(stream));
str = stream.str();
}
{
estimator_t xestimator;
std::istringstream stream(str);
UTEST_CHECK_NOTHROW(xestimator.read(stream));
}
{
estimator_t xestimator;
std::ifstream stream;
UTEST_CHECK_THROW(xestimator.read(stream), std::runtime_error);
}
{
std::ostringstream ostream;
UTEST_CHECK_NOTHROW(::nano::write(ostream, estimator));
estimator_t xestimator;
std::istringstream istream(ostream.str());
UTEST_CHECK_NOTHROW(::nano::read(istream, xestimator));
return xestimator;
}
}
UTEST_BEGIN_MODULE(test_core_estimator)
UTEST_CASE(string)
{
for (const auto& string : {std::string{}, std::string("stream strings")})
{
std::ostringstream ostream;
UTEST_REQUIRE_NOTHROW(::nano::write(ostream, string));
UTEST_REQUIRE(ostream);
const auto ostring = ostream.str();
UTEST_CHECK_EQUAL(ostring.size(), string.size() + 4);
std::string istring;
std::istringstream istream(ostring);
UTEST_REQUIRE(istream);
UTEST_REQUIRE_NOTHROW(::nano::read(istream, istring));
UTEST_REQUIRE(istream);
UTEST_CHECK_EQUAL(string, istring);
std::string ifstring;
std::ifstream ifstream;
UTEST_REQUIRE(ifstream);
UTEST_REQUIRE_NOTHROW(::nano::read(ifstream, ifstring));
UTEST_REQUIRE(!ifstream);
}
}
UTEST_CASE(vector)
{
const auto vector = std::vector<int32_t>{2, 3};
std::ostringstream ostream;
UTEST_REQUIRE_NOTHROW(::nano::write(ostream, vector));
UTEST_REQUIRE(ostream);
const auto ostring = ostream.str();
UTEST_CHECK_EQUAL(ostring.size(), 4U * vector.size() + 8U);
std::vector<int32_t> ivector;
std::istringstream istream(ostring);
UTEST_REQUIRE(istream);
UTEST_REQUIRE_NOTHROW(::nano::read(istream, ivector));
UTEST_REQUIRE(istream);
UTEST_CHECK_EQUAL(vector, ivector);
{
std::ifstream ifstream;
UTEST_REQUIRE(ifstream);
UTEST_REQUIRE_NOTHROW(::nano::read(ifstream, ivector));
UTEST_REQUIRE(!ifstream);
}
{
std::ofstream ofstream;
UTEST_REQUIRE(ofstream);
UTEST_REQUIRE_NOTHROW(::nano::write(ofstream, ivector));
UTEST_REQUIRE(!ofstream);
}
}
UTEST_CASE(estimator_default)
{
const auto estimator = estimator_t{};
UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version);
UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version);
UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version);
}
UTEST_CASE(estimator_read_const)
{
auto estimator = estimator_t{};
auto str = to_string(estimator);
UTEST_REQUIRE_EQUAL(str.size(), size_t(3 * 4 + 8));
std::istringstream stream(str);
UTEST_REQUIRE_NOTHROW(estimator.read(stream));
UTEST_REQUIRE(stream);
UTEST_REQUIRE_EQUAL(static_cast<size_t>(stream.tellg()), str.size());
UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version);
UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version);
UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version);
}
UTEST_CASE(estimator_read_major)
{
auto estimator = estimator_t{};
auto str = to_string(estimator);
UTEST_REQUIRE_EQUAL(str.size(), size_t(3 * 4 + 8));
reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[0] = ::nano::major_version - 1; // NOLINT
std::istringstream stream(str);
UTEST_REQUIRE_NOTHROW(estimator.read(stream));
UTEST_REQUIRE(stream);
UTEST_REQUIRE_EQUAL(static_cast<size_t>(stream.tellg()), str.size());
UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version - 1);
UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version - 0);
UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version - 0);
}
UTEST_CASE(estimator_read_minor)
{
auto estimator = estimator_t{};
auto str = to_string(estimator);
UTEST_REQUIRE_EQUAL(str.size(), size_t(3 * 4 + 8));
reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[1] = ::nano::minor_version - 2; // NOLINT
std::istringstream stream(str);
UTEST_REQUIRE_NOTHROW(estimator.read(stream));
UTEST_REQUIRE(stream);
UTEST_REQUIRE_EQUAL(static_cast<size_t>(stream.tellg()), str.size());
UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version - 0);
UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version - 2);
UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version - 0);
}
UTEST_CASE(estimator_read_patch)
{
auto estimator = estimator_t{};
auto str = to_string(estimator);
UTEST_REQUIRE_EQUAL(str.size(), size_t(3 * 4 + 8));
reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[2] = ::nano::patch_version - 3; // NOLINT
std::istringstream stream(str);
UTEST_REQUIRE_NOTHROW(estimator.read(stream));
UTEST_REQUIRE(stream);
UTEST_REQUIRE_EQUAL(static_cast<size_t>(stream.tellg()), str.size());
UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version - 0);
UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version - 0);
UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version - 3);
}
UTEST_CASE(estimator_write_fail)
{
const auto estimator = estimator_t{};
std::ofstream stream;
UTEST_CHECK_THROW(estimator.write(stream), std::runtime_error);
}
UTEST_CASE(estimator_read_fail_major)
{
auto estimator = estimator_t{};
auto str = to_string(estimator);
reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[0] = ::nano::major_version + 1; // NOLINT
std::istringstream stream(str);
UTEST_REQUIRE_THROW(estimator.read(stream), std::runtime_error);
}
UTEST_CASE(estimator_read_fail_minor)
{
auto estimator = estimator_t{};
auto str = to_string(estimator);
reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[1] = ::nano::minor_version + 1; // NOLINT
std::istringstream stream(str);
UTEST_REQUIRE_THROW(estimator.read(stream), std::runtime_error);
}
UTEST_CASE(estimator_read_fail_patch)
{
auto estimator = estimator_t{};
auto str = to_string(estimator);
reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[2] = ::nano::patch_version + 1; // NOLINT
std::istringstream stream(str);
UTEST_REQUIRE_THROW(estimator.read(stream), std::runtime_error);
}
UTEST_CASE(no_parameters)
{
const auto check_params = [] (const estimator_t& estimator)
{
UTEST_CHECK(estimator.parameters().empty());
};
auto estimator = estimator_t{};
check_params(estimator);
const auto* const pname = "nonexistent_param_name";
const auto sname = string_t{"unknown_param_name"};
UTEST_CHECK_THROW(estimator.parameter(pname), std::runtime_error);
UTEST_CHECK_THROW(estimator.parameter(sname), std::runtime_error);
UTEST_CHECK_THROW(const_cast<const estimator_t&>(estimator).parameter(pname), std::runtime_error); // NOLINT
UTEST_CHECK_THROW(const_cast<const estimator_t&>(estimator).parameter(sname), std::runtime_error); // NOLINT
UTEST_CHECK(estimator.parameter_if(pname) == nullptr);
UTEST_CHECK(estimator.parameter_if(sname) == nullptr);
UTEST_CHECK(const_cast<const estimator_t&>(estimator).parameter_if(pname) == nullptr); // NOLINT
UTEST_CHECK(const_cast<const estimator_t&>(estimator).parameter_if(sname) == nullptr); // NOLINT
check_params(check_stream(estimator));
}
UTEST_CASE(parameters)
{
const auto eparam = parameter_t::make_enum("eparam", enum_type::type3);
const auto iparam = parameter_t::make_integer("iparam", 1, LE, 5, LE, 9);
const auto fparam = parameter_t::make_scalar_pair("fparam", 1.0, LT, 2.0, LE, 2.0, LT, 5.0);
const auto check_params = [&] (const estimator_t& estimator)
{
UTEST_CHECK_EQUAL(estimator.parameters().size(), 3U);
UTEST_CHECK_EQUAL(estimator.parameter("eparam"), eparam);
UTEST_CHECK_EQUAL(estimator.parameter("iparam"), iparam);
UTEST_CHECK_EQUAL(estimator.parameter("fparam"), fparam);
};
auto estimator = estimator_t{};
UTEST_CHECK_NOTHROW(estimator.register_parameter(eparam));
UTEST_CHECK_NOTHROW(estimator.register_parameter(iparam));
UTEST_CHECK_NOTHROW(estimator.register_parameter(fparam));
check_params(estimator);
check_params(check_stream(estimator));
UTEST_CHECK_THROW(estimator.register_parameter(eparam), std::runtime_error);
UTEST_CHECK_THROW(estimator.register_parameter(iparam), std::runtime_error);
UTEST_CHECK_THROW(estimator.register_parameter(fparam), std::runtime_error);
check_params(estimator);
check_params(check_stream(estimator));
}
UTEST_END_MODULE()
| 32.4
| 112
| 0.70083
|
accosmin
|
7f94c3b7cd19f83bf8b6492a094d92257be28f5e
| 718
|
cpp
|
C++
|
stable.cpp
|
okosan/AStar
|
867da5417a97cafd620db9016c8b0efb399b139c
|
[
"MIT"
] | 4
|
2016-11-11T10:50:07.000Z
|
2021-04-01T10:06:51.000Z
|
stable.cpp
|
okosan/AStar
|
867da5417a97cafd620db9016c8b0efb399b139c
|
[
"MIT"
] | 1
|
2020-02-11T15:47:43.000Z
|
2020-02-11T15:47:43.000Z
|
stable.cpp
|
okosan/AStar
|
867da5417a97cafd620db9016c8b0efb399b139c
|
[
"MIT"
] | 1
|
2017-10-23T07:24:55.000Z
|
2017-10-23T07:24:55.000Z
|
#include "stable.h"
void xfBeep(int freq, int duration)
{
std::printf ("beeping!!!");
}
bool xfBetween(double val, double val1, double val2)
{
if (val1<val2)
{
if ((val >= val1) && (val <= val2))
return true;
return false;
}
else
{
if ((val >= val2) && (val <= val1))
return true;
return false;
}
}
bool xfBetweenExcl(double val, double val1, double val2)
{
if (val1<val2)
{
if ((val > val1) && (val < val2))
return true;
return false;
}
else
{
if ((val > val2) && (val < val1))
return true;
return false;
}
}
| 17.95
| 57
| 0.448468
|
okosan
|
7f967881b38f927953ac0ffa7aca6fae3a2413f8
| 663
|
cpp
|
C++
|
Programming-Contest/Number Theory/BSGS.cpp
|
ar-pavel/Code-Library
|
2d1b952231c1059bbf98d85d2c23fd8fb21b455c
|
[
"MIT"
] | null | null | null |
Programming-Contest/Number Theory/BSGS.cpp
|
ar-pavel/Code-Library
|
2d1b952231c1059bbf98d85d2c23fd8fb21b455c
|
[
"MIT"
] | null | null | null |
Programming-Contest/Number Theory/BSGS.cpp
|
ar-pavel/Code-Library
|
2d1b952231c1059bbf98d85d2c23fd8fb21b455c
|
[
"MIT"
] | null | null | null |
/*
Shnak's Baby-Step-giant-Step Algorithm
a^x = b (mod m)
return the power x where a , b , m given
*/
#define mod 100000007
ll solve (ll a, ll b, ll m)
{
ll n = (ll) sqrt (m + .0) + 1 , an = 1 , curr ;
rep(i,n) an = (an * a) % m;
map<ll,ll> vals;
curr = an ;
For(i,n){
if ( !vals.count(curr) ) vals[ curr ] = i;
curr = (curr * an) % m;
}
ll ans = mod ;
curr = b ;
rep(i,n+1){
if ( vals.count(curr) ) {
ans = min( ans , vals[ curr ] * n - i ); // finding the minimum solution
//if (ans < m) return ans; // return any solution
}
curr = (curr * a) % m;
}
return ans ;
//return -1; // if no solution cant be found
}
| 21.387097
| 76
| 0.523379
|
ar-pavel
|
7f99b358e33664d4255b10c28de67d0b5d3f8ca5
| 6,590
|
cc
|
C++
|
chrome/browser/chromeos/status/clock_menu_button.cc
|
SlimKatLegacy/android_external_chromium
|
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
|
[
"BSD-3-Clause"
] | 2
|
2017-02-20T14:25:04.000Z
|
2019-12-13T13:58:28.000Z
|
chrome/browser/chromeos/status/clock_menu_button.cc
|
SlimKatLegacy/android_external_chromium
|
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
|
[
"BSD-3-Clause"
] | 2
|
2017-07-25T09:37:22.000Z
|
2017-08-04T07:18:56.000Z
|
chrome/browser/chromeos/status/clock_menu_button.cc
|
SlimKatLegacy/android_external_chromium
|
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
|
[
"BSD-3-Clause"
] | 2
|
2020-01-12T00:55:53.000Z
|
2020-11-04T06:36:41.000Z
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "base/i18n/time_formatting.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font.h"
#include "unicode/datefmt.h"
namespace chromeos {
// Amount of slop to add into the timer to make sure we're into the next minute
// when the timer goes off.
const int kTimerSlopSeconds = 1;
ClockMenuButton::ClockMenuButton(StatusAreaHost* host)
: StatusAreaButton(host, this) {
// Add as SystemAccess observer. We update the clock if timezone changes.
SystemAccess::GetInstance()->AddObserver(this);
CrosLibrary::Get()->GetPowerLibrary()->AddObserver(this);
// Start monitoring the kUse24HourClock preference.
if (host->GetProfile()) { // This can be NULL in the login screen.
registrar_.Init(host->GetProfile()->GetPrefs());
registrar_.Add(prefs::kUse24HourClock, this);
}
UpdateTextAndSetNextTimer();
}
ClockMenuButton::~ClockMenuButton() {
CrosLibrary::Get()->GetPowerLibrary()->RemoveObserver(this);
SystemAccess::GetInstance()->RemoveObserver(this);
}
void ClockMenuButton::UpdateTextAndSetNextTimer() {
UpdateText();
// Try to set the timer to go off at the next change of the minute. We don't
// want to have the timer go off more than necessary since that will cause
// the CPU to wake up and consume power.
base::Time now = base::Time::Now();
base::Time::Exploded exploded;
now.LocalExplode(&exploded);
// Often this will be called at minute boundaries, and we'll actually want
// 60 seconds from now.
int seconds_left = 60 - exploded.second;
if (seconds_left == 0)
seconds_left = 60;
// Make sure that the timer fires on the next minute. Without this, if it is
// called just a teeny bit early, then it will skip the next minute.
seconds_left += kTimerSlopSeconds;
timer_.Start(base::TimeDelta::FromSeconds(seconds_left), this,
&ClockMenuButton::UpdateTextAndSetNextTimer);
}
void ClockMenuButton::UpdateText() {
base::Time time(base::Time::Now());
// If the profie is present, check the use 24-hour clock preference.
const bool use_24hour_clock =
host_->GetProfile() &&
host_->GetProfile()->GetPrefs()->GetBoolean(prefs::kUse24HourClock);
if (use_24hour_clock) {
SetText(UTF16ToWide(base::TimeFormatTimeOfDayWithHourClockType(
time, base::k24HourClock)));
} else {
// Remove the am/pm field if it's present.
scoped_ptr<icu::DateFormat> formatter(
icu::DateFormat::createTimeInstance(icu::DateFormat::kShort));
icu::UnicodeString time_string;
icu::FieldPosition ampm_field(icu::DateFormat::kAmPmField);
formatter->format(
static_cast<UDate>(time.ToDoubleT() * 1000), time_string, ampm_field);
int ampm_length = ampm_field.getEndIndex() - ampm_field.getBeginIndex();
if (ampm_length) {
int begin = ampm_field.getBeginIndex();
// Doesn't include any spacing before the field.
if (begin)
begin--;
time_string.removeBetween(begin, ampm_field.getEndIndex());
}
string16 time_string16 =
string16(time_string.getBuffer(),
static_cast<size_t>(time_string.length()));
SetText(UTF16ToWide(time_string16));
}
SetTooltipText(UTF16ToWide(base::TimeFormatShortDate(time)));
SchedulePaint();
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, NotificationObserver implementation:
void ClockMenuButton::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED) {
std::string* pref_name = Details<std::string>(details).ptr();
if (*pref_name == prefs::kUse24HourClock) {
UpdateText();
}
}
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, ui::MenuModel implementation:
int ClockMenuButton::GetItemCount() const {
// If options dialog is unavailable, don't count a separator and configure
// menu item.
return host_->ShouldOpenButtonOptions(this) ? 3 : 1;
}
ui::MenuModel::ItemType ClockMenuButton::GetTypeAt(int index) const {
// There's a separator between the current date and the menu item to open
// the options menu.
return index == 1 ? ui::MenuModel::TYPE_SEPARATOR:
ui::MenuModel::TYPE_COMMAND;
}
string16 ClockMenuButton::GetLabelAt(int index) const {
if (index == 0)
return base::TimeFormatFriendlyDate(base::Time::Now());
return l10n_util::GetStringUTF16(IDS_STATUSBAR_CLOCK_OPEN_OPTIONS_DIALOG);
}
bool ClockMenuButton::IsEnabledAt(int index) const {
// The 1st item is the current date, which is disabled.
return index != 0;
}
void ClockMenuButton::ActivatedAt(int index) {
host_->OpenButtonOptions(this);
}
///////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, PowerLibrary::Observer implementation:
void ClockMenuButton::SystemResumed() {
UpdateText();
}
///////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, SystemAccess::Observer implementation:
void ClockMenuButton::TimezoneChanged(const icu::TimeZone& timezone) {
UpdateText();
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::ViewMenuDelegate implementation:
void ClockMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
if (!clock_menu_.get())
clock_menu_.reset(new views::Menu2(this));
else
clock_menu_->Rebuild();
clock_menu_->UpdateStates();
clock_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::View implementation:
void ClockMenuButton::OnLocaleChanged() {
UpdateText();
}
} // namespace chromeos
| 35.240642
| 80
| 0.667527
|
SlimKatLegacy
|
7f9b48ea988e27f03c7214538543556df8cbbc24
| 4,133
|
cpp
|
C++
|
deps/MFEM/ComputeFemMassMatrix1/ComputeFemMassMatrixMfem.cpp
|
kailaix/AdFem.jl
|
77eabfeedb297570a42d1f26575c59f0712796d9
|
[
"MIT"
] | 47
|
2020-10-18T01:33:11.000Z
|
2022-03-16T00:13:24.000Z
|
deps/MFEM/ComputeFemMassMatrix1/ComputeFemMassMatrixMfem.cpp
|
kailaix/AdFem.jl
|
77eabfeedb297570a42d1f26575c59f0712796d9
|
[
"MIT"
] | 10
|
2020-10-19T03:51:31.000Z
|
2022-03-22T23:38:46.000Z
|
deps/MFEM/ComputeFemMassMatrix1/ComputeFemMassMatrixMfem.cpp
|
kailaix/AdFem.jl
|
77eabfeedb297570a42d1f26575c59f0712796d9
|
[
"MIT"
] | 11
|
2020-11-05T11:34:16.000Z
|
2022-03-03T19:30:09.000Z
|
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/platform/default/logging.h"
#include "tensorflow/core/framework/shape_inference.h"
#include<cmath>
// Signatures for GPU kernels here
using namespace tensorflow;
#include "ComputeFemMassMatrixMfem.h"
REGISTER_OP("ComputeFemMassMatrixMfem")
.Input("rho : double")
.Output("indices : int64")
.Output("vv : double")
.SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
shape_inference::ShapeHandle rho_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &rho_shape));
c->set_output(0, c->Matrix(-1,2));
c->set_output(1, c->Vector(-1));
return Status::OK();
});
REGISTER_OP("ComputeFemMassMatrixMfemGrad")
.Input("grad_vv : double")
.Input("indices : int64")
.Input("vv : double")
.Input("rho : double")
.Output("grad_rho : double");
/*-------------------------------------------------------------------------------------*/
class ComputeFemMassMatrixMfemOp : public OpKernel {
private:
public:
explicit ComputeFemMassMatrixMfemOp(OpKernelConstruction* context) : OpKernel(context) {
}
void Compute(OpKernelContext* context) override {
DCHECK_EQ(1, context->num_inputs());
const Tensor& rho = context->input(0);
const TensorShape& rho_shape = rho.shape();
DCHECK_EQ(rho_shape.dims(), 1);
// extra check
// create output shape
int N = mmesh.ngauss * mmesh.elem_ndof * mmesh.elem_ndof;
TensorShape indices_shape({N,2});
TensorShape vv_shape({N});
// create output tensor
Tensor* indices = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, indices_shape, &indices));
Tensor* vv = NULL;
OP_REQUIRES_OK(context, context->allocate_output(1, vv_shape, &vv));
// get the corresponding Eigen tensors for data access
auto rho_tensor = rho.flat<double>().data();
auto indices_tensor = indices->flat<int64>().data();
auto vv_tensor = vv->flat<double>().data();
// implement your forward function here
// TODO:
MFEM::ComputeFemMassMatrix1_forward(indices_tensor, vv_tensor, rho_tensor);
}
};
REGISTER_KERNEL_BUILDER(Name("ComputeFemMassMatrixMfem").Device(DEVICE_CPU), ComputeFemMassMatrixMfemOp);
class ComputeFemMassMatrixMfemGradOp : public OpKernel {
private:
public:
explicit ComputeFemMassMatrixMfemGradOp(OpKernelConstruction* context) : OpKernel(context) {
}
void Compute(OpKernelContext* context) override {
const Tensor& grad_vv = context->input(0);
const Tensor& indices = context->input(1);
const Tensor& vv = context->input(2);
const Tensor& rho = context->input(3);
const TensorShape& grad_vv_shape = grad_vv.shape();
const TensorShape& indices_shape = indices.shape();
const TensorShape& vv_shape = vv.shape();
const TensorShape& rho_shape = rho.shape();
DCHECK_EQ(grad_vv_shape.dims(), 1);
DCHECK_EQ(indices_shape.dims(), 2);
DCHECK_EQ(vv_shape.dims(), 1);
DCHECK_EQ(rho_shape.dims(), 1);
// extra check
// int m = Example.dim_size(0);
// create output shape
TensorShape grad_rho_shape(rho_shape);
// create output tensor
Tensor* grad_rho = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, grad_rho_shape, &grad_rho));
// get the corresponding Eigen tensors for data access
auto rho_tensor = rho.flat<double>().data();
auto grad_vv_tensor = grad_vv.flat<double>().data();
auto indices_tensor = indices.flat<int64>().data();
auto vv_tensor = vv.flat<double>().data();
auto grad_rho_tensor = grad_rho->flat<double>().data();
// implement your backward function here
// TODO:
grad_rho->flat<double>().setZero();
MFEM::ComputeFemMassMatrix1_backward(grad_rho_tensor, grad_vv_tensor, vv_tensor, rho_tensor);
}
};
REGISTER_KERNEL_BUILDER(Name("ComputeFemMassMatrixMfemGrad").Device(DEVICE_CPU), ComputeFemMassMatrixMfemGradOp);
| 28.503448
| 113
| 0.66586
|
kailaix
|
7f9ca1a35e2ae5f8187a902da1f17182140c90ad
| 364
|
cpp
|
C++
|
src/codepulsar/pulsar/Parser.cpp
|
FireTheLost/JPulse
|
1c462ef4c605bd844a4a5fb9a28a4e91233286be
|
[
"MIT"
] | null | null | null |
src/codepulsar/pulsar/Parser.cpp
|
FireTheLost/JPulse
|
1c462ef4c605bd844a4a5fb9a28a4e91233286be
|
[
"MIT"
] | null | null | null |
src/codepulsar/pulsar/Parser.cpp
|
FireTheLost/JPulse
|
1c462ef4c605bd844a4a5fb9a28a4e91233286be
|
[
"MIT"
] | null | null | null |
#include "Parser.h"
Pulsar::Parser::Parser(std::string sourceCode) {
this->sourceCode = sourceCode;
}
void Pulsar::Parser::parse() {
Pulsar::Lexer lexer = Lexer(this->sourceCode);
this->tokens = lexer.tokenize();
this->errors = lexer.getErrors();
if (this->errors->hasError()) return;
Pulsar::TokenDisassembler::display(this->tokens);
}
| 24.266667
| 53
| 0.67033
|
FireTheLost
|
7f9d164d35bb5249e38b5ed62e3ebc8530c727ff
| 2,193
|
cpp
|
C++
|
ex1/ex1/osm.cpp
|
nadavWeisler/OperatingSystems
|
8735cb6c7d124c63eba8d03d0654477daefeee9b
|
[
"MIT"
] | null | null | null |
ex1/ex1/osm.cpp
|
nadavWeisler/OperatingSystems
|
8735cb6c7d124c63eba8d03d0654477daefeee9b
|
[
"MIT"
] | 3
|
2021-08-09T11:19:23.000Z
|
2021-08-09T11:19:36.000Z
|
ex1/ex1/osm.cpp
|
nadavWeisler/OperatingSystems
|
8735cb6c7d124c63eba8d03d0654477daefeee9b
|
[
"MIT"
] | null | null | null |
//
// Created by weisler on 06/04/2021.
//
#include <iostream>
#include "osm.h"
#include <sys/time.h>
/**
* An empty function
*/
void empty_func() {}
long get_nano(struct timeval t) {
return ((t.tv_sec * 1000000 + t.tv_usec) * 1000);
}
double osm_operation_time(unsigned int iterations) {
if (iterations == 0) {
return 0;
}
timeval start_time;
int a = 0, b = 1;
gettimeofday(&start_time, NULL);
for (int i = 0; i < (int) iterations; i++) {
a += b;
a += b;
a += b;
a += b;
a += b;
a += b;
a += b;
a += b;
a += b;
a += b;
a += b;
}
timeval end_time;
gettimeofday(&end_time, NULL);
return (double) ((get_nano(end_time)) - get_nano(start_time)) / (iterations * 11);
}
/* Time measurement function for an empty function call.
returns time in nano-seconds upon success,
and -1 upon failure.
*/
double osm_function_time(unsigned int iterations) {
if (iterations == 0) {
return 0;
}
timeval start_time;
gettimeofday(&start_time, NULL);
for (int i = 0; i < (int) iterations; i++) {
empty_func();
empty_func();
empty_func();
empty_func();
empty_func();
empty_func();
empty_func();
empty_func();
empty_func();
empty_func();
empty_func();
}
timeval end_time;
gettimeofday(&end_time, NULL);
return (double) ((get_nano(end_time)) - get_nano(start_time)) / (iterations * 11);
}
double osm_syscall_time(unsigned int iterations) {
if (iterations == 0) {
return 0;
}
timeval start_time;
gettimeofday(&start_time, NULL);
for (int i = 0; i < (int) iterations; i++) {
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
OSM_NULLSYSCALL;
}
timeval end_time;
gettimeofday(&end_time, NULL);
return (double) ((get_nano(end_time)) - get_nano(start_time)) / (iterations * 11);
}
| 22.84375
| 86
| 0.562699
|
nadavWeisler
|
7f9e377060e22224456bd298051adcc9ff9abad8
| 3,855
|
cpp
|
C++
|
modules/vulkan/src/codegen/ops/copy.cpp
|
xhuohai/nncase
|
cf7921c273c7446090939c64f57ef783a62bf29c
|
[
"Apache-2.0"
] | 510
|
2018-12-29T06:49:36.000Z
|
2022-03-30T08:36:29.000Z
|
modules/vulkan/src/codegen/ops/copy.cpp
|
xhuohai/nncase
|
cf7921c273c7446090939c64f57ef783a62bf29c
|
[
"Apache-2.0"
] | 459
|
2019-02-17T13:31:29.000Z
|
2022-03-31T05:55:38.000Z
|
modules/vulkan/src/codegen/ops/copy.cpp
|
xhuohai/nncase
|
cf7921c273c7446090939c64f57ef783a62bf29c
|
[
"Apache-2.0"
] | 155
|
2019-04-16T08:43:24.000Z
|
2022-03-21T07:27:26.000Z
|
/* Copyright 2019-2021 Canaan 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.
*/
#include "../module_builder.h"
#include <nncase/ir/op_utils.h>
#include <nncase/kernels/cpu/reference/runtime_types.h>
#include <nncase/kernels/kernel_utils.h>
#include <nncase/runtime/vulkan/runtime_types.h>
#include <vulkan/vulkan.hpp>
using namespace nncase;
using namespace nncase::codegen;
using namespace nncase::codegen::vulkan;
using namespace nncase::ir;
using namespace nncase::runtime;
using namespace nncase::runtime::vulkan;
using namespace nlohmann;
namespace
{
struct copy_shape_strides
{
shape_t shape;
shape_t strides_shape1;
shape_t strides_shape2;
};
copy_shape_strides optimize_copy_strides(copy_shape_strides src)
{
assert(src.strides_shape1.size() == src.strides_shape1.size());
while (src.shape.size() > 1)
{
if (src.shape.back() == src.strides_shape1.back()
&& src.shape.back() == src.strides_shape2.back())
{
auto value = src.shape.back();
src.shape.pop_back();
src.strides_shape1.pop_back();
src.strides_shape2.pop_back();
src.shape.back() *= value;
src.strides_shape1.back() *= value;
src.strides_shape2.back() *= value;
}
}
return src;
}
}
void vulkan_module_builder::emit(copy &node)
{
auto &tw = text_writer();
auto &input = allocation(node.input());
auto &output = allocation(node.input());
ldbufbarrier_op_t in_bop {};
in_bop.src_access_mask = (uint32_t)vk::AccessFlagBits::eMemoryRead;
in_bop.dest_access_mask = 0;
in_bop.memory = input.runtime_type();
tw.write(in_bop);
ldbufbarrier_op_t out_bop {};
out_bop.src_access_mask = 0;
out_bop.dest_access_mask = (uint32_t)vk::AccessFlagBits::eMemoryWrite;
out_bop.memory = output.runtime_type();
tw.write(out_bop);
barrier_op_t bop {};
bop.src_stage = (uint32_t)vk::PipelineStageFlagBits::eTransfer;
bop.dest_stage = (uint32_t)vk::PipelineStageFlagBits::eTransfer;
bop.buffer_barriers = 2;
tw.write(bop);
ldbuf(input.runtime_type());
ldbuf(output.runtime_type());
uint32_t regions = 0;
auto opt_shape = optimize_copy_strides({ input.shape, input.strides_shape, output.strides_shape });
if (opt_shape.shape.size() == 1)
{
ldbufcopy_op_t lbc_op;
lbc_op.src = 0;
lbc_op.dest = 0;
lbc_op.size = (uint32_t)ir::get_bytes(input.type, opt_shape.shape);
regions++;
tw.write(lbc_op);
}
else
{
auto slice_len = (uint32_t)ir::get_bytes(input.type) * opt_shape.shape.back();
auto src_strides = to_strides(opt_shape.strides_shape1);
auto dest_strides = to_strides(opt_shape.strides_shape2);
auto idx_shape = opt_shape.shape;
idx_shape.back() = 1;
kernels::cpu::reference::apply(idx_shape, [&](const shape_t &idx) -> result<void> {
ldbufcopy_op_t lbc_op;
lbc_op.src = kernels::offset(src_strides, idx);
lbc_op.dest = kernels::offset(dest_strides, idx);
lbc_op.size = slice_len;
regions++;
tw.write(lbc_op);
return ok();
}).unwrap_or_throw();
}
copybuf_op_t cb_op;
cb_op.regions = regions;
text_writer().write(cb_op);
}
| 31.598361
| 103
| 0.664591
|
xhuohai
|
7fa1e787c8778f1a507ab8190f389c33830a6b02
| 1,229
|
cpp
|
C++
|
src/color.cpp
|
yudhik11/OpenGL-LOZ
|
c1add7b09df2b99e1c82c21b56ba18b1cf7c4846
|
[
"MIT"
] | 1
|
2019-08-29T02:01:20.000Z
|
2019-08-29T02:01:20.000Z
|
src/color.cpp
|
yudhik11/OpenGL-LOZ
|
c1add7b09df2b99e1c82c21b56ba18b1cf7c4846
|
[
"MIT"
] | null | null | null |
src/color.cpp
|
yudhik11/OpenGL-LOZ
|
c1add7b09df2b99e1c82c21b56ba18b1cf7c4846
|
[
"MIT"
] | null | null | null |
#include "main.h"
const color_t COLOR_BLACK = { 52, 73, 94 };
const color_t COLOR_BACKGROUND = { 153, 235, 255 };
const color_t COLOR_BLUE = { 0, 138, 230 };
// const color_a COLOR_ABLUE = { 0, 138, 230, 0.3 };
const color_t COLOR_CUBE1 = { 128, 43, 0 };
const color_t COLOR_CUBE2 = { 204, 68, 0 };
const color_t COLOR_CUBE3 = { 128, 43, 0 };
const color_t COLOR_CUBE4 = { 204, 68, 0 };
const color_t COLOR_CUBE5 = { 0, 0, 0 };
const color_t COLOR_CUBE6 = { 135, 211, 124 };
const color_t COLOR_CUBE7 = { 0, 153, 204 };
const color_t COLOR_CUBE8 = { 51, 153, 102 };
const color_t COLOR_CUBE9 = { 135, 211, 124 };
const color_t COLOR_BLAST = { 230, 57, 0 };
const color_t COLOR_BROWN = { 165, 42, 42 };
const color_t COLOR_SMOKE = { 102, 102, 153 };
const color_t COLOR_DBLUE = { 0, 0, 230 };
const color_t COLOR_GIFT = { 128, 255, 255 };
const color_t COLOR_CANNON = { 102, 0, 51};
const color_t COLOR_VIOLET = { 202,0,202};
const color_t COLOR_INDIGO = { 75,0,130};
const color_t COLOR_BBLUE = { 0,191,255};
const color_t COLOR_GREEN = { 135, 211, 124 };
const color_t COLOR_YELLOW = { 255,255,0};
const color_t COLOR_ORANGE = { 255,165,0};
const color_t COLOR_RED = { 255, 128, 128};
const color_t COLOR_DRED = { 255, 0 , 0};
| 40.966667
| 52
| 0.673718
|
yudhik11
|
7fa8f3fdf2ebb64ccf08c6ec947b368c0a81c2ee
| 832
|
hpp
|
C++
|
src/util.hpp
|
triton/cc-wrapper
|
4be147e091897efc080691567034127dfafd75b9
|
[
"Apache-2.0"
] | 1
|
2018-09-27T05:08:35.000Z
|
2018-09-27T05:08:35.000Z
|
src/util.hpp
|
triton/cc-wrapper
|
4be147e091897efc080691567034127dfafd75b9
|
[
"Apache-2.0"
] | null | null | null |
src/util.hpp
|
triton/cc-wrapper
|
4be147e091897efc080691567034127dfafd75b9
|
[
"Apache-2.0"
] | 3
|
2017-12-24T22:07:05.000Z
|
2020-11-26T01:20:16.000Z
|
#pragma once
#include <algorithm>
#include <nonstd/optional.hpp>
#include <nonstd/span.hpp>
#include <nonstd/string_view.hpp>
namespace cc_wrapper {
namespace util {
namespace detail {
char *append(char *out, nonstd::string_view str);
nonstd::string_view removeTrailing(nonstd::string_view path);
} // namespace detail
nonstd::optional<nonstd::string_view> getenv(nonstd::string_view var);
nonstd::string_view dirname(nonstd::string_view path);
nonstd::string_view basename(nonstd::string_view path);
void exec(nonstd::string_view bin,
nonstd::span<const nonstd::string_view> args);
template <typename A, typename B, size_t N>
bool spanEqual(nonstd::span<A, N> a, nonstd::span<B, N> b) {
return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
}
} // namespace util
} // namespace cc_wrapper
| 27.733333
| 75
| 0.725962
|
triton
|
7fa980e5f37645bb45d89cee4ca0ef72ef949387
| 2,003
|
cpp
|
C++
|
Programming and Algorithm/High Level Programming Language 2/mydeque/src/myIterator.cpp
|
Lan-Jing/Courses
|
540db9499b8725ca5b82a2c4e7a3da09f73c0efa
|
[
"MIT"
] | 1
|
2021-12-17T23:09:00.000Z
|
2021-12-17T23:09:00.000Z
|
Programming and Algorithm/High Level Programming Language 2/mydeque/src/myIterator.cpp
|
Lan-Jing/Courses
|
540db9499b8725ca5b82a2c4e7a3da09f73c0efa
|
[
"MIT"
] | null | null | null |
Programming and Algorithm/High Level Programming Language 2/mydeque/src/myIterator.cpp
|
Lan-Jing/Courses
|
540db9499b8725ca5b82a2c4e7a3da09f73c0efa
|
[
"MIT"
] | 1
|
2021-08-03T23:42:06.000Z
|
2021-08-03T23:42:06.000Z
|
#include "myIterator.hpp"
myIterator& myIterator::operator = (const myIterator &iter){
this->setPtr(iter.showPtr());
this->setDequePos(iter.showDequePos());
this->setBlockPos(iter.showBlockPos());
this->setMode(iter.showMode());
return (*this);
}
bool myIterator::operator == (const myIterator &iter){
return this->ptr == iter.ptr &&
this->showDequePos() == iter.showDequePos() &&
this->showBlockPos() == iter.showBlockPos() &&
this->showMode() == iter.showMode();
}
bool myIterator::operator != (const myIterator &iter){
return !((*this) == iter);
}
myIterator& myIterator::operator ++ (){
if(this->showMode()){
if(!this->showBlockPos()){
this->setBlockPos(blockLength - 1);
this->setDequePos(this->showDequePos() - 1);
}else{
this->setBlockPos(this->showBlockPos() - 1);
}
}else{
if(this->showBlockPos() == blockLength - 1){
this->setBlockPos(0);
this->setDequePos(this->showDequePos() + 1);
}else{
this->setBlockPos(this->showBlockPos() + 1);
}
}
return (*this);
}
myIterator& myIterator::operator ++ (int){
// myIterator& result = (*this);
myIterator result(NULL,0,0,0);
if(this->showMode()){
if(!this->blockPos){
this->blockPos = (blockLength - 1);
this->dequePos = (this->dequePos - 1);
}else{
this->blockPos = (this->blockPos - 1);
}
}else{
if(this->blockPos == blockLength - 1){
this->blockPos = 0;
this->dequePos = this->dequePos + 1;
}else{
this->blockPos = this->blockPos + 1;
}
}
return result;
}
myIterator myIterator::operator + (int num){
myIterator result = *this;
for(int i = 0;i < num;i++) result.operator++(1);
return result;
}
int& myIterator::operator * (){
return this->ptr[this->showDequePos()][this->showBlockPos()];
}
| 30.815385
| 65
| 0.558662
|
Lan-Jing
|
7fadd9c58dde2e49eff7ac12fa64aafa57440a02
| 894
|
cpp
|
C++
|
ports/biology/diamond/dragonfly/patch-src_util_system_system.cpp
|
liweitianux/DeltaPorts
|
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
|
[
"BSD-2-Clause-FreeBSD"
] | 31
|
2015-02-06T17:06:37.000Z
|
2022-03-08T19:53:28.000Z
|
ports/biology/diamond/dragonfly/patch-src_util_system_system.cpp
|
liweitianux/DeltaPorts
|
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
|
[
"BSD-2-Clause-FreeBSD"
] | 236
|
2015-06-29T19:51:17.000Z
|
2021-12-16T22:46:38.000Z
|
ports/biology/diamond/dragonfly/patch-src_util_system_system.cpp
|
liweitianux/DeltaPorts
|
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
|
[
"BSD-2-Clause-FreeBSD"
] | 52
|
2015-02-06T17:05:36.000Z
|
2021-10-21T12:13:06.000Z
|
--- src/util/system/system.cpp.orig 2021-02-12 11:50:56 UTC
+++ src/util/system/system.cpp
@@ -16,7 +16,7 @@
#include <fcntl.h>
#include <unistd.h>
#ifndef __APPLE__
- #ifdef __FreeBSD__
+ #if defined(__FreeBSD__) || defined(__DragonFly__)
#include <sys/types.h>
#include <sys/sysctl.h>
#else
@@ -139,8 +139,12 @@ void reset_color(bool err) {
double total_ram() {
#if defined(WIN32) || defined(__APPLE__)
return 0.0;
-#elif defined(__FreeBSD__)
+#elif defined(__FreeBSD__) || defined(__DragonFly__)
+#ifdef __DragonFly__
+ int mib[2] = { CTL_HW, HW_USERMEM };
+#else
int mib[2] = { CTL_HW, HW_REALMEM };
+#endif
u_int namelen = sizeof(mib) / sizeof(mib[0]);
uint64_t oldp;
size_t oldlenp = sizeof(oldp);
@@ -192,4 +196,4 @@ void unmap_file(char* ptr, size_t size,
munmap((void*)ptr, size);
close(fd);
#endif
-}
\ No newline at end of file
+}
| 27.090909
| 59
| 0.649888
|
liweitianux
|
7fb117bc0fa66fc32423df42dc26bf922768b159
| 4,503
|
cpp
|
C++
|
Classes/DroneSystem.cpp
|
InversePalindrome/Apophis
|
c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8
|
[
"MIT"
] | 7
|
2018-08-20T17:28:29.000Z
|
2020-09-05T15:19:31.000Z
|
Classes/DroneSystem.cpp
|
InversePalindrome/JATR66
|
c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8
|
[
"MIT"
] | null | null | null |
Classes/DroneSystem.cpp
|
InversePalindrome/JATR66
|
c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8
|
[
"MIT"
] | 1
|
2019-12-25T12:02:03.000Z
|
2019-12-25T12:02:03.000Z
|
/*
Copyright (c) 2018 Inverse Palindrome
Apophis - DroneSystem.cpp
InversePalindrome.com
*/
#include "DroneSystem.hpp"
#include "ObjectComponent.hpp"
#include "SteeringBehaviors.hpp"
#include "TransformComponent.hpp"
DroneSystem::DroneSystem(entityx::EntityManager& entityManager, entityx::EventManager& eventManager) :
droneTree(beehive::Builder<DroneContext>()
.selector()
.sequence()
.leaf([&entityManager](auto& context)
{
return (context.leaderBody->getPosition() - context.body.getPosition()).Length() <= context.vision.getVisionDistance();
}
).void_leaf([&entityManager](auto& context)
{
auto directionVector = context.leaderBody->getLinearVelocity();
directionVector.Normalize();
directionVector *= context.follow.getDistanceFromLeader();
const auto aheadPoint = context.leaderBody->getPosition() + directionVector;
const auto behindPoint = context.leaderBody->getPosition() - directionVector;
if (b2RayCastOutput rayOutput; context.body.raycast(rayOutput, { context.leaderBody->getPosition(), aheadPoint, 1.f }))
{
context.body.applyLinearImpulse(SteeringBehaviors::evade(context.body.getPosition(), context.leaderBody->getPosition(), context.body.getLinearVelocity(), context.leaderBody->getLinearVelocity(), context.speed.getMaxLinearSpeed()));
}
context.body.applyLinearImpulse(SteeringBehaviors::arrive(context.body.getPosition(), behindPoint, context.body.getLinearVelocity(), context.arrive.getSlowRadius(), context.speed.getMaxLinearSpeed()));
context.body.applyAngularImpulse(SteeringBehaviors::face(context.body.getPosition(), context.body.getPosition() + context.body.getLinearVelocity(), context.body.getAngle(), context.body.getAngularVelocity(), context.body.getInertia()));
std::vector<b2Vec2> neighborPositions;
entityManager.each<FlockComponent, BodyComponent>([&context, &neighborPositions](auto entity, const auto& flock, const auto& body)
{
if (context.drone != entity && context.flock.getGroupID() == flock.getGroupID() && (context.body.getPosition() - body.getPosition()).Length() <= context.flock.getGroupRadius())
{
neighborPositions.push_back(body.getPosition());
}
});
context.body.applyLinearImpulse(SteeringBehaviors::separateForce(context.body.getPosition(), neighborPositions, context.flock.getSeparationForce()));
})
.end()
.void_leaf([](auto& context)
{
context.body.applyLinearImpulse(SteeringBehaviors::wander(context.body.getPosition(), context.body.getLinearVelocity(), context.wander.getWanderDistance(), context.wander.getWanderRadius(), context.wander.getWanderRate(), context.wander.getWanderAngle(), context.speed.getMaxLinearSpeed()));
context.body.applyAngularImpulse(SteeringBehaviors::face(context.body.getPosition(), context.body.getPosition() + context.body.getLinearVelocity(), context.body.getAngle(), context.body.getAngularVelocity(), context.body.getInertia()));
}).end().build())
{
}
void DroneSystem::update(entityx::EntityManager& entityManager, entityx::EventManager& eventManager, entityx::TimeDelta deltaTime)
{
entityManager.each<ObjectComponent, BodyComponent, WanderComponent, SpeedComponent, ArriveComponent, FollowComponent, FlockComponent, VisionComponent>
([this, &entityManager](auto entity, const auto& object, auto& body, auto& wander, const auto& speed, const auto& arrive, const auto& follow, const auto& flock, const auto& vision)
{
if (object.getObjectType() == +ObjectType::Drone)
{
if (auto leaderEntity = entityManager.get(entityManager.create_id(follow.getLeaderID())))
{
if (const auto leaderBody = leaderEntity.component<BodyComponent>())
{
droneTree.process(DroneContext{ entity, leaderEntity, body, wander, speed, arrive, follow, flock, vision, leaderBody });
}
}
}
});
}
| 58.480519
| 315
| 0.641794
|
InversePalindrome
|
7fb4ce55e05517579f0901da106a1f7879d017ec
| 11,238
|
cpp
|
C++
|
thirdparty/cgicc/cgicc/CgiEnvironment.cpp
|
rockchip-linux/ipcweb-backend
|
1885a61babe060c16a84c172712146d4206361df
|
[
"BSD-3-Clause"
] | 1
|
2021-09-16T02:56:35.000Z
|
2021-09-16T02:56:35.000Z
|
thirdparty/cgicc/cgicc/CgiEnvironment.cpp
|
rockchip-linux/ipcweb-backend
|
1885a61babe060c16a84c172712146d4206361df
|
[
"BSD-3-Clause"
] | 1
|
2021-07-08T03:34:02.000Z
|
2021-07-08T03:34:02.000Z
|
thirdparty/cgicc/cgicc/CgiEnvironment.cpp
|
rockchip-linux/ipcweb-backend
|
1885a61babe060c16a84c172712146d4206361df
|
[
"BSD-3-Clause"
] | 2
|
2021-08-24T05:38:18.000Z
|
2021-09-16T02:56:39.000Z
|
/* -*-mode:c++; c-file-style: "gnu";-*- */
/*
* $Id: CgiEnvironment.cpp,v 1.31 2017/06/22 20:26:35 sebdiaz Exp $
*
* Copyright (C) 1996 - 2004 Stephen F. Booth <sbooth@gnu.org>
* 2007 Sebastien DIAZ <sebastien.diaz@gmail.com>
* Part of the GNU cgicc library, http://www.gnu.org/software/cgicc
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
*/
#ifdef __GNUG__
# pragma implementation
#endif
#include <new>
#include <memory>
#include <stdexcept>
#include <cstdlib>
#include <cctype>
#ifdef WIN32
# include <io.h>
# include <fcntl.h>
# include <stdio.h>
#endif
#include "CgiEnvironment.h"
// ========== Constructor/Destructor
cgicc::CgiEnvironment::CgiEnvironment(CgiInput *input)
{
// Create a local CgiInput object for us to use
// In the vast majority of cases, this will be used
// For FastCGI applications it won't but the performance hit of
// an empty inline constructor is negligible
CgiInput local_input;
if(0 == input)
readEnvironmentVariables(&local_input);
else
readEnvironmentVariables(input);
// On Win32, use binary read to avoid CRLF conversion
#ifdef WIN32
# ifdef __BORLANDC__
setmode(_fileno(stdin), O_BINARY);
# else
_setmode(_fileno(stdin), _O_BINARY);
# endif
#endif
if(stringsAreEqual(fRequestMethod, "post") || stringsAreEqual(fRequestMethod, "put")) {
// Don't use auto_ptr, but vector instead
// Bug reported by shinra@j10n.org
std::vector<char> data(fContentLength);
if(getenv("CGICC_MAX_CONTENTLENGTH")&&getContentLength()>(long unsigned int)atoi(getenv("CGICC_MAX_CONTENTLENGTH")))
{
throw std::runtime_error("Malformed input");
}
else
// If input is 0, use the default implementation of CgiInput
if ( getContentLength() )
{
// If input is 0, use the default implementation of CgiInput
if ( input == 0 )
{
if ( local_input.read( &data[0], getContentLength() ) != getContentLength() )
throw std::runtime_error("I/O error");
}
else
if ( input->read( &data[0], getContentLength() ) != getContentLength() )
throw std::runtime_error("I/O error");
fPostData = std::string( &data[0], getContentLength() );
}
}
fCookies.reserve(10);
parseCookies();
}
cgicc::CgiEnvironment::~CgiEnvironment()
{}
// Overloaded operators
bool
cgicc::CgiEnvironment::operator== (const CgiEnvironment& env) const
{
bool result;
result = fServerPort == env.fServerPort;
result &= fContentLength == env.fContentLength;
result &= fUsingHTTPS == env.fUsingHTTPS;
result &= fServerSoftware == env.fServerSoftware;
result &= fServerName == env.fServerName;
result &= fGatewayInterface == env.fGatewayInterface;
result &= fServerProtocol == env.fServerProtocol;
result &= fRequestMethod == env.fRequestMethod;
result &= fPathInfo == env.fPathInfo;
result &= fPathTranslated == env.fPathTranslated;
result &= fScriptName == env.fScriptName;
result &= fQueryString == env.fQueryString;
result &= fRemoteHost == env.fRemoteHost;
result &= fRemoteAddr == env.fRemoteAddr;
result &= fAuthType == env.fAuthType;
result &= fRemoteUser == env.fRemoteUser;
result &= fRemoteIdent == env.fRemoteIdent;
result &= fContentType == env.fContentType;
result &= fAccept == env.fAccept;
result &= fUserAgent == env.fUserAgent;
result &= fPostData == env.fPostData;
result &= fRedirectRequest == env.fRedirectRequest;
result &= fRedirectURL == env.fRedirectURL;
result &= fRedirectStatus == env.fRedirectStatus;
result &= fReferrer == env.fReferrer;
result &= fCookie == env.fCookie;
return result;
}
cgicc::CgiEnvironment&
cgicc::CgiEnvironment::operator= (const CgiEnvironment& env)
{
fServerPort = env.fServerPort;
fContentLength = env.fContentLength;
fUsingHTTPS = env.fUsingHTTPS;
fServerSoftware = env.fServerSoftware;
fServerName = env.fServerName;
fGatewayInterface = env.fGatewayInterface;
fServerProtocol = env.fServerProtocol;
fRequestMethod = env.fRequestMethod;
fPathInfo = env.fPathInfo;
fPathTranslated = env.fPathTranslated;
fScriptName = env.fScriptName;
fQueryString = env.fQueryString;
fRemoteHost = env.fRemoteHost;
fRemoteAddr = env.fRemoteAddr;
fAuthType = env.fAuthType;
fRemoteUser = env.fRemoteUser;
fRemoteIdent = env.fRemoteIdent;
fContentType = env.fContentType;
fAccept = env.fAccept;
fUserAgent = env.fUserAgent;
fPostData = env.fPostData;
fRedirectRequest = env.fRedirectRequest;
fRedirectURL = env.fRedirectURL;
fRedirectStatus = env.fRedirectStatus;
fReferrer = env.fReferrer;
fCookie = env.fCookie;
fCookies.clear();
fCookies.reserve(env.fCookies.size());
parseCookies();
return *this;
}
void
cgicc::CgiEnvironment::parseCookies()
{
std::string data = fCookie;
if(false == data.empty()) {
std::string::size_type pos;
std::string::size_type oldPos = 0;
while(true) {
// find the ';' terminating a name=value pair
pos = data.find(";", oldPos);
// if no ';' was found, the rest of the string is a single cookie
if(std::string::npos == pos) {
parseCookie(data.substr(oldPos));
return;
}
// otherwise, the string contains multiple cookies
// extract it and add the cookie to the list
parseCookie(data.substr(oldPos, pos - oldPos));
// update pos (+1 to skip ';')
oldPos = pos + 1;
}
}
}
void
cgicc::CgiEnvironment::parseCookie(const std::string& data)
{
// find the '=' separating the name and value
std::string::size_type pos = data.find("=", 0);
// if no '=' was found, return
if(std::string::npos == pos)
return;
// skip leading whitespace - " \f\n\r\t\v"
std::string::size_type wscount = 0;
std::string::const_iterator data_iter;
for(data_iter = data.begin(); data_iter != data.end(); ++data_iter,++wscount)
if(0 == std::isspace(*data_iter))
break;
// Per RFC 2091, do not unescape the data (thanks to afm@othello.ch)
std::string name = data.substr(wscount, pos - wscount);
std::string value = data.substr(++pos);
fCookies.push_back(HTTPCookie(name, value));
}
// Read in all the environment variables
void
cgicc::CgiEnvironment::readEnvironmentVariables(CgiInput *input)
{
fServerSoftware = input->getenv("SERVER_SOFTWARE");
fServerName = input->getenv("SERVER_NAME");
fGatewayInterface = input->getenv("GATEWAY_INTERFACE");
fServerProtocol = input->getenv("SERVER_PROTOCOL");
std::string port = input->getenv("SERVER_PORT");
fServerPort = std::atol(port.c_str());
fRequestMethod = input->getenv("REQUEST_METHOD");
fPathInfo = input->getenv("PATH_INFO");
fPathTranslated = input->getenv("PATH_TRANSLATED");
fScriptName = input->getenv("SCRIPT_NAME");
fQueryString = input->getenv("QUERY_STRING");
fRemoteHost = input->getenv("REMOTE_HOST");
fRemoteAddr = input->getenv("REMOTE_ADDR");
fAuthType = input->getenv("AUTH_TYPE");
fRemoteUser = input->getenv("REMOTE_USER");
fRemoteIdent = input->getenv("REMOTE_IDENT");
fContentType = input->getenv("CONTENT_TYPE");
std::string length = input->getenv("CONTENT_LENGTH");
fContentLength = std::atol(length.c_str());
fAccept = input->getenv("HTTP_ACCEPT");
fUserAgent = input->getenv("HTTP_USER_AGENT");
fRedirectRequest = input->getenv("REDIRECT_REQUEST");
fRedirectURL = input->getenv("REDIRECT_URL");
fRedirectStatus = input->getenv("REDIRECT_STATUS");
fReferrer = input->getenv("HTTP_REFERER");
fCookie = input->getenv("HTTP_COOKIE");
fAcceptLanguageString = input->getenv("HTTP_ACCEPT_LANGUAGE");
// Win32 bug fix by Peter Goedtkindt
std::string https = input->getenv("HTTPS");
if(stringsAreEqual(https, "on"))
fUsingHTTPS = true;
else
fUsingHTTPS = false;
}
void
cgicc::CgiEnvironment::save(const std::string& filename) const
{
std::ofstream file( filename.c_str(), std::ios::binary |std::ios::out );
if( ! file )
throw std::runtime_error("I/O error");
writeLong(file, fContentLength);
writeLong(file, fServerPort);
writeLong(file, (unsigned long) usingHTTPS());
writeString(file, fServerSoftware);
writeString(file, fServerName);
writeString(file, fGatewayInterface);
writeString(file, fServerProtocol);
writeString(file, fRequestMethod);
writeString(file, fPathInfo);
writeString(file, fPathTranslated);
writeString(file, fScriptName);
writeString(file, fQueryString);
writeString(file, fRemoteHost);
writeString(file, fRemoteAddr);
writeString(file, fAuthType);
writeString(file, fRemoteUser);
writeString(file, fRemoteIdent);
writeString(file, fContentType);
writeString(file, fAccept);
writeString(file, fUserAgent);
writeString(file, fRedirectRequest);
writeString(file, fRedirectURL);
writeString(file, fRedirectStatus);
writeString(file, fReferrer);
writeString(file, fCookie);
if(stringsAreEqual(fRequestMethod, "post") || stringsAreEqual(fRequestMethod, "put"))
writeString(file, fPostData);
if(file.bad() || file.fail())
throw std::runtime_error("I/O error");
file.close();
}
void
cgicc::CgiEnvironment::restore(const std::string& filename)
{
std::ifstream file( filename.c_str(), std::ios::binary | std::ios::in );
if( ! file )
throw std::runtime_error("I/O error");
file.flags(file.flags() & std::ios::skipws);
fContentLength = readLong(file);
fServerPort = readLong(file);
fUsingHTTPS = (bool) readLong(file);
fServerSoftware = readString(file);
fServerName = readString(file);
fGatewayInterface = readString(file);
fServerProtocol = readString(file);
fRequestMethod = readString(file);
fPathInfo = readString(file);
fPathTranslated = readString(file);
fScriptName = readString(file);
fQueryString = readString(file);
fRemoteHost = readString(file);
fRemoteAddr = readString(file);
fAuthType = readString(file);
fRemoteUser = readString(file);
fRemoteIdent = readString(file);
fContentType = readString(file);
fAccept = readString(file);
fUserAgent = readString(file);
fRedirectRequest = readString(file);
fRedirectURL = readString(file);
fRedirectStatus = readString(file);
fReferrer = readString(file);
fCookie = readString(file);
if(stringsAreEqual(fRequestMethod, "post") || stringsAreEqual(fRequestMethod, "put"))
fPostData = readString(file);
file.close();
fCookies.clear();
fCookies.reserve(10);
parseCookies();
}
| 30.873626
| 120
| 0.69354
|
rockchip-linux
|
7fba04bc263e96728d4aed53624ee7aa4159f8d4
| 700
|
cpp
|
C++
|
src/components/RenderableComponent.cpp
|
SgtCoDFish/obelisk
|
8ff736a720f2604c7990477791cb5a983271f66a
|
[
"CC0-1.0",
"MIT"
] | 1
|
2018-10-03T20:46:57.000Z
|
2018-10-03T20:46:57.000Z
|
src/components/RenderableComponent.cpp
|
SgtCoDFish/obelisk
|
8ff736a720f2604c7990477791cb5a983271f66a
|
[
"CC0-1.0",
"MIT"
] | null | null | null |
src/components/RenderableComponent.cpp
|
SgtCoDFish/obelisk
|
8ff736a720f2604c7990477791cb5a983271f66a
|
[
"CC0-1.0",
"MIT"
] | null | null | null |
#include <utility>
#include "components/RenderableComponent.hpp"
namespace obelisk {
RenderableComponent::RenderableComponent(APG::SpriteBase *sprite) :
sprite{sprite} {
}
RenderableComponent::RenderableComponent(APG::SpriteBase *sprite, APG::SpriteBase *secondary) :
sprite{sprite},
secondary{secondary} {
calculateSecondaryPos();
}
void RenderableComponent::calculateSecondaryPos() {
secondaryPos = glm::vec2{(sprite->getWidth() - secondary->getWidth()) / 2,
(sprite->getHeight() - secondary->getWidth()) / 2};
}
void RenderableComponent::setSecondary(APG::SpriteBase *secondary) {
this->secondary = secondary;
if (secondary != nullptr) {
calculateSecondaryPos();
}
}
}
| 23.333333
| 95
| 0.734286
|
SgtCoDFish
|
7fba614ab0a0ff114d06c1bae69dbcb7ad3a6ca3
| 842
|
cpp
|
C++
|
AdjMatrix.cpp
|
RadheTians/Data-Structre
|
c4ee2d2592ce0eec3bb3f6a582542bb8307220d9
|
[
"MIT"
] | 2
|
2019-09-23T15:17:15.000Z
|
2019-10-15T04:17:07.000Z
|
AdjMatrix.cpp
|
RadheTians/Data-Structre
|
c4ee2d2592ce0eec3bb3f6a582542bb8307220d9
|
[
"MIT"
] | null | null | null |
AdjMatrix.cpp
|
RadheTians/Data-Structre
|
c4ee2d2592ce0eec3bb3f6a582542bb8307220d9
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
class AdjMatrix
{
private:
int v;
int adj[10][10];
public:
AdjMatrix(int);
~AdjMatrix();
void addPath(int,int);
void print();
};
AdjMatrix::AdjMatrix(int v)
{
this->v = v;
for(int i=0;i<v;i++)
for(int j=0;j<v;j++)
adj[i][j] = 0;
}
AdjMatrix::~AdjMatrix()
{
}
void AdjMatrix::addPath(int u,int v){
this->adj[u][v] = 1;
this->adj[v][u] = 1;
}
void AdjMatrix::print(){
for(int i=0;i<v;i++){
cout <<endl << i << " : ";
for(int j =0;j<v;j++){
cout <<" " << this->adj[i][j];
}
}
}
int main(){
AdjMatrix graph(4);
graph.addPath(0,1);
graph.addPath(0,2);
graph.addPath(0,3);
graph.addPath(1,2);
graph.addPath(1,3);
graph.addPath(2,3);
graph.print();
return 0;
}
| 16.84
| 42
| 0.508314
|
RadheTians
|
7fbb8db6cf319ae805704b3c86a1771c8c3a6f12
| 648
|
cpp
|
C++
|
src/public/src/FM7/util/rawReadToD77/main.cpp
|
rothberg-cmu/rothberg-run
|
a42df5ca9fae97de77753864f60d05295d77b59f
|
[
"MIT"
] | 1
|
2019-08-10T00:24:09.000Z
|
2019-08-10T00:24:09.000Z
|
src/public/src/FM7/util/rawReadToD77/main.cpp
|
rothberg-cmu/rothberg-run
|
a42df5ca9fae97de77753864f60d05295d77b59f
|
[
"MIT"
] | null | null | null |
src/public/src/FM7/util/rawReadToD77/main.cpp
|
rothberg-cmu/rothberg-run
|
a42df5ca9fae97de77753864f60d05295d77b59f
|
[
"MIT"
] | 2
|
2019-05-01T03:11:10.000Z
|
2019-05-01T03:30:35.000Z
|
#include "rawread.h"
#include "rawreadutil.h"
int main(int ac,char *av[])
{
FM7RawDiskReadUtil::CommandParameterInfo cpmi;
if(true!=cpmi.RecognizeCommandParameter(ac,av))
{
printf("Usage:\n");
printf(" rawRead2D77 -?\n");
printf(" Show help.\n");
printf(" rawRead2D77 inputFileName.txt outputFileName.d77 <options>\n");
printf(" Read from inputFileName.txt and convert to .D77 file.\n");
printf(" rawRead2D77 inputFileName.txt <options>\n");
printf(" Read from inputFileName.txt and run specified tasks, but don't write to .D77 file.\n");
return 0;
}
FM7RawDiskReadUtil util;
return util.RunBatchMode(cpmi);
}
| 27
| 101
| 0.700617
|
rothberg-cmu
|
7fbb94aa88bdb32f50c0a2e4598ac633593fd68b
| 5,788
|
cpp
|
C++
|
ext/dvdaf3/UnicodeStr.replace.cpp
|
FilmAf/PHP-Extensions
|
f00bd2f1f2b0298fc673c03c9be89dbcceb1a3d4
|
[
"CC0-1.0"
] | null | null | null |
ext/dvdaf3/UnicodeStr.replace.cpp
|
FilmAf/PHP-Extensions
|
f00bd2f1f2b0298fc673c03c9be89dbcceb1a3d4
|
[
"CC0-1.0"
] | null | null | null |
ext/dvdaf3/UnicodeStr.replace.cpp
|
FilmAf/PHP-Extensions
|
f00bd2f1f2b0298fc673c03c9be89dbcceb1a3d4
|
[
"CC0-1.0"
] | null | null | null |
#include "UnicodeStr.h"
/// <summary>
/// Given an item to replace it finds it in the requested translation table and replaces it.
/// </summary>
/// <param name="pTargetPosBegins">Index of the string to be replaced.</param>
/// <param name="pTargetLength">Length of the string to be replaced.</param>
/// <param name="pTranlationTable">Translation table: gs_utf_asci, gs_utf_web, gs_utf_fold, gs_utf_srch or gs_utf_deco</param>
/// <param name="pFound">Indicates if the item was found in the required table.</param>
/// <param name="pReplaceOptions">Options: eMatchCase, eDeleteIfNotFound, eRecursive</param>
/// <returns>Same as CStr::replace.</returns>
int CUnicodeStr::replaceItem(
const int pTargetPosBegins,
int pTargetLength,
const t_utf_replace &pTranlationTable,
bool &pFound,
CUnicodeStr::eReplaceOptions pReplaceOptions)
{
ASSERT(pTargetLength > 0 &&
pTargetPosBegins >= 0 &&
pTargetPosBegins < _Length &&
pTargetPosBegins + pTargetLength <= _Length);
const unsigned char*
lReplacementRef = findItem(_Buffer + pTargetPosBegins,
_Buffer + pTargetPosBegins + pTargetLength,
pTranlationTable,
pReplaceOptions & CUnicodeStr::eMatchCase,
pTargetLength);
if ( lReplacementRef )
{
pFound = true;
if ( *lReplacementRef )
return replace(pTargetPosBegins, pTargetLength, lReplacementRef+1, *lReplacementRef) +
(pReplaceOptions & CUnicodeStr::eRecursive ? pTargetLength - *lReplacementRef : 0);
else
return remove(pTargetPosBegins, pTargetLength);
}
else
{
pFound = false;
if ( pReplaceOptions & CUnicodeStr::eDeleteIfNotFound )
return remove(pTargetPosBegins, pTargetLength);
else
return pTargetPosBegins + pTargetLength;
}
}
/// <summary>
/// Find item in selected translation table
/// </summary>
///
/// <param name="pSourceBeg">Pointer to the string to be replaced.</param>
/// <param name="pSourceEnd">Pointer after the string to be replaced.</param>
/// <param name="pTranslationTable">Translation table.</param>
/// <param name="pMatchCase">Match case.</param>
/// <param name="pTargetLengthOverride">Actual length of string to be replaced.</param>
/// <returns>Reference to replacement string consisting of its length followed by the string itself (similar to a Pascal string).</returns>
const unsigned char *CUnicodeStr::findItem(
const unsigned char *pSourceBeg,
const unsigned char *pSourceEnd,
const t_utf_replace &pTranslationTable,
bool pMatchCase,
int &pTargetLengthOverride)
{
if ( pTranslationTable.pt_ndx_str )
return findItemStringKey(pSourceBeg, pSourceEnd, pTranslationTable, pMatchCase);
unsigned int x = decodeUtf8(pSourceBeg, pTargetLengthOverride);
if ( x <= 0xFFFF )
return findItemShortKey(pTranslationTable, x);
else
return findItemLongKey(pTranslationTable, x);
}
/// <summary>
/// Performs Hangul algorithmic decomposition of Korean characters or table-based decomposition for other characters.
/// </summary>
///
/// <param name="pTarget">String where to append the decomposed string.</param>
/// <param name="pSourceBeg">Beginning of Unicode sequence to decompose.</param>
/// <param name="pLevel">Incremental value to stop endless recursion. Use zero on the first call.</param>
/// <returns>Number of characters consumed.</returns>
int CUnicodeStr::catDecomposed(
const unsigned char *pSourceBeg,
const int pLevel)
{
const int lMaxLevel = 20;
const unsigned int lSBase = 0xAC00,
lSCount = 19 * 21 * 28;
int k = 1, n_foo;
if (pSourceBeg)
{
unsigned char c = *pSourceBeg;
if ( c < 0xC0 )
{
*this << SP(pSourceBeg, 1);
return 1;
}
if ( (c & 0xF0) == 0xE0 )
{
unsigned int x = decodeUtf8(pSourceBeg, n_foo) - lSBase;
if ( x >= 0 && x < lSCount )
return catDecomposedHangul(x);
k = 3;
} else
if ( (c & 0xE0) == 0xC0 ) k = 2; else
if ( (c & 0xF8) == 0xF0 ) k = 4;
if (pLevel < lMaxLevel)
{
if ( k > 1 )
{
// Table-Based Decomposition
const unsigned char *r = findItem(pSourceBeg, pSourceBeg + k, gs_utf_deco, true, n_foo);
if ( r )
for ( int i = 0 ; i < *r ; )
i += catDecomposed(r + i + 1, pLevel + 1);
else
*this << SP(pSourceBeg, k);
}
}
else
{
*this << SP(pSourceBeg, k);
}
}
return k;
}
/// <summary>
/// Get class for 32-bit Unicode.
/// </summary>
/// <param name="c">32-bit Unicode</param>
/// <returns>Unicode class.</returns>
int CUnicodeStr::getUnicodeClass(unsigned int c)
{
int n_class = 0;
// Try class 1 bitmaps
for ( int i = 0 ; i < 7 ; i++ )
{
const t_utf_c1_bmp *p = &(gt_uni_class.c1[i]);
if ( c >= p->n_beg && c <= p->n_end )
{
int j = c - p->n_beg;
unsigned int x = 1 << ( 31 - (j % 32) );
j = j / 32;
if ( j < p->n_count )
{
x = p->pn_bmp[j] & x;
if ( x ) return 0;
}
break;
}
}
// bisection search
if ( c <= 0xFFFF )
{
int n_top, n_bottom;
for ( n_top = gt_uni_class.n_ndx_short - 1, n_bottom = 0 ; n_top >= n_bottom ; )
{
int n_candidate = n_bottom + (n_top - n_bottom) / 2;
unsigned int x = gt_uni_class.pt_ndx_short[n_candidate];
if ( c > x ) n_bottom = n_candidate + 1; else
if ( c < x ) n_top = n_candidate - 1; else
{
n_class = gt_uni_class.ps_class_short[n_candidate];
break;
}
}
}
else
{
int n_top, n_bottom;
for ( n_top = gt_uni_class.n_ndx_long - 1, n_bottom = 0 ; n_top >= n_bottom ; )
{
int n_candidate = n_bottom + (n_top - n_bottom) / 2;
unsigned int x = gt_uni_class.pt_ndx_long[n_candidate];
if ( c > x ) n_bottom = n_candidate + 1; else
if ( c < x ) n_top = n_candidate - 1; else
{
n_class = gt_uni_class.ps_class_long[n_candidate];
break;
}
}
}
return n_class;
}
| 29.989637
| 139
| 0.657222
|
FilmAf
|
7fbbe8613adf38550a1732c9bc237aeb19ef0e49
| 321
|
cpp
|
C++
|
Test/TestMain.cpp
|
aldonunez/Gemini
|
141e060bbc0698370c406046c35f5669eedcce75
|
[
"Apache-2.0"
] | null | null | null |
Test/TestMain.cpp
|
aldonunez/Gemini
|
141e060bbc0698370c406046c35f5669eedcce75
|
[
"Apache-2.0"
] | null | null | null |
Test/TestMain.cpp
|
aldonunez/Gemini
|
141e060bbc0698370c406046c35f5669eedcce75
|
[
"Apache-2.0"
] | null | null | null |
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
int main( int argc, char* argv[] )
{
#if defined( _WIN32 )
_CrtSetDbgFlag(
_crtDbgFlag
| _CRTDBG_LEAK_CHECK_DF
| _CRTDBG_ALLOC_MEM_DF
);
#endif
int result = Catch::Session().run( argc, argv );
return result;
}
| 16.894737
| 53
| 0.598131
|
aldonunez
|
7fbbf68ce630456f4164a72ac083f29abfce8ed4
| 1,147
|
cpp
|
C++
|
Olympiad Solutions/URI/1288.cpp
|
Ashwanigupta9125/code-DS-ALGO
|
49f6cf7d0c682da669db23619aef3f80697b352b
|
[
"MIT"
] | 36
|
2019-12-27T08:23:08.000Z
|
2022-01-24T20:35:47.000Z
|
Olympiad Solutions/URI/1288.cpp
|
Ashwanigupta9125/code-DS-ALGO
|
49f6cf7d0c682da669db23619aef3f80697b352b
|
[
"MIT"
] | 10
|
2019-11-13T02:55:18.000Z
|
2021-10-13T23:28:09.000Z
|
Olympiad Solutions/URI/1288.cpp
|
Ashwanigupta9125/code-DS-ALGO
|
49f6cf7d0c682da669db23619aef3f80697b352b
|
[
"MIT"
] | 53
|
2020-08-15T11:08:40.000Z
|
2021-10-09T15:51:38.000Z
|
// Ivan Carvalho
// Solution to https://www.urionlinejudge.com.br/judge/problems/view/1288
#include <unordered_map>
#include <algorithm>
#define MAXN 1010
using namespace std;
typedef long long ll;
ll n,s,casos,peso[MAXN],valor[MAXN],r,davez,condicional;
unordered_map<ll,ll> tab[MAXN];
int knapsack(ll obj, ll aguenta){
if (condicional) return tab[obj][aguenta] = 0;
if (obj > n || !aguenta) return tab[obj][aguenta]=0;
if (tab[obj].count(aguenta)) return tab[obj][aguenta];
ll nao_coloca = knapsack(obj+1,aguenta);
condicional += int(nao_coloca >= r);
if (peso[obj]<=aguenta){
ll coloca = valor[obj]+knapsack(obj+1,aguenta-peso[obj]);
condicional += int(coloca >= r);
return tab[obj][aguenta]=max(coloca,nao_coloca);
}
return tab[obj][aguenta]=nao_coloca;
}
int main(){
scanf("%lld",&casos);
while(casos--){
condicional = 0;
scanf("%lld",&n);
for(int i=0;i<=n+1;i++) tab[i].clear();
for(ll i=1;i<=n;i++) scanf("%lld %lld",&valor[i],&peso[i]);
scanf("%lld",&s);
scanf("%lld",&r);
davez = knapsack(1,s);
if (davez>=r) printf("Missao completada com sucesso\n");
else printf("Falha na missao\n");
}
return 0;
}
| 30.184211
| 73
| 0.664342
|
Ashwanigupta9125
|
7fbd8fa92bae2899d036ac189f91569770e9621a
| 983
|
cpp
|
C++
|
examples/SDLAssets/MusicHandler.cpp
|
cloudncali/GExL
|
08010f6a3e46e7c633968930a96ff7e98aec4efb
|
[
"MIT"
] | null | null | null |
examples/SDLAssets/MusicHandler.cpp
|
cloudncali/GExL
|
08010f6a3e46e7c633968930a96ff7e98aec4efb
|
[
"MIT"
] | null | null | null |
examples/SDLAssets/MusicHandler.cpp
|
cloudncali/GExL
|
08010f6a3e46e7c633968930a96ff7e98aec4efb
|
[
"MIT"
] | null | null | null |
#include "MusicHandler.hpp"
#include <SDL_image.h>
#include <iostream>
MusicHandler::MusicHandler() :
GExL::TAssetHandler<Music>()
{
}
MusicHandler::~MusicHandler()
{
}
bool MusicHandler::LoadFromFile(const GExL::typeAssetID theAssetID, Music& theAsset)
{
bool anResult = false;
std::string anFilname = GetFilename(theAssetID);
if (anFilname.length() > 0)
{
//Load music
theAsset = Mix_LoadMUS(anFilname.c_str());
if (theAsset == NULL)
{
ELOG() << "ImageHandler::LoadFromFile(" << theAssetID
<< ") Mix_Error: " << Mix_GetError() << std::endl;
}
else
anResult = true;
}
else
{
ELOG() << "ImageHandler::LoadFromFile(" << theAssetID
<< ") No filename provided!" << std::endl;
}
return anResult;
}
bool MusicHandler::LoadFromMemory(const GExL::typeAssetID theAssetID, Music& theAsset)
{
return false;
}
bool MusicHandler::LoadFromNetwork(const GExL::typeAssetID theAssetID, Music& theAsset)
{
return false;
}
| 22.340909
| 87
| 0.668362
|
cloudncali
|
7fbda4d6c5ea5110380e7431ef241ff4083abecc
| 2,300
|
cpp
|
C++
|
nice_matrix.cpp
|
AnkilP/codeforces
|
f0ed588166420b984db1864acfff8b94639422ba
|
[
"MIT"
] | null | null | null |
nice_matrix.cpp
|
AnkilP/codeforces
|
f0ed588166420b984db1864acfff8b94639422ba
|
[
"MIT"
] | null | null | null |
nice_matrix.cpp
|
AnkilP/codeforces
|
f0ed588166420b984db1864acfff8b94639422ba
|
[
"MIT"
] | null | null | null |
#include <string>
#include <iostream>
#include <sstream>
#include <iterator>
#include <fstream>
#include <iomanip>
#include <vector>
#include <queue>
#include <utility>
#include <algorithm>
#include <stdlib.h>
#include <math.h>
long long solution(const std::vector<std::vector<long long>> & sides, std::vector<long long> & NM){
long long answer = 0;
if(NM[0] % 2 != 0){
NM[0]++;
}
if(NM[1] % 2 != 0){
NM[1]++;
}
for(int j = 0; j < NM[1]/2; ++j){
for(int i = 0; i < NM[0]/2; ++i){
long long temp_mean = std::floor(static_cast<double>(sides[sides.size() - i - 1][j] + sides[i][sides[0].size() - j - 1] + sides[i][j] + sides[sides.size() - i - 1][sides[0].size() - j - 1])/4.0);
if(i != sides.size() - i - 1){
answer += std::abs(temp_mean - sides[sides.size() - i - 1][j]);
answer += std::abs(temp_mean - sides[i][sides[0].size() - j - 1]);
}
answer += std::abs(temp_mean - sides[i][j]);
answer += std::abs(temp_mean - sides[sides.size() - i - 1][sides[0].size() - j - 1]);
}
}
return answer;
}
int main(){
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
std::string stones;
std::string NM;
// //assuming that input txt doc is argv[1]
// std::string inputTxt = argv[1];
// // output txt doc is argv[2]
// std::string outputTxt = argv[2];
// std::ifstream inputFile(inputTxt);
// std::ofstream outputFile(outputTxt);
std::string T;
std::getline(std::cin,T);
int testcases = stoi(T);
for(int i = 0; i < testcases; ++i){
std::getline(std::cin, NM);
std::istringstream iss1(NM);
std::vector<long long> NM(std::istream_iterator<long long>(iss1), {});
std::vector<std::vector<long long>> curr_matrix;
for(int i = 0; i < NM[0]; ++i){
std::getline(std::cin, stones);
std::istringstream iss2(stones);
std::vector<long long> e(std::istream_iterator<long long>(iss2), {});
curr_matrix.emplace_back(e);
}
long long sol = solution(curr_matrix, NM);
std::cout << std::to_string(sol) << "\n";
}
// outputFile.close();
// inputFile.close();
return 0;
}
| 31.506849
| 207
| 0.538261
|
AnkilP
|
7fbfd83f68152f001c8b4b6c38b6cb8ef7ab1457
| 15,886
|
hpp
|
C++
|
include/ValkyrieEngine/Component.hpp
|
VD-15/Valkyrie-Engine
|
2287568e24b3ab20dff4feecbbf523c2fbbced65
|
[
"MIT"
] | 2
|
2020-06-18T21:32:29.000Z
|
2021-01-29T04:16:47.000Z
|
include/ValkyrieEngine/Component.hpp
|
VD-15/Valkyrie-Engine
|
2287568e24b3ab20dff4feecbbf523c2fbbced65
|
[
"MIT"
] | 13
|
2020-02-02T19:00:15.000Z
|
2020-02-08T18:32:06.000Z
|
include/ValkyrieEngine/Component.hpp
|
VD-15/Valkyrie-Engine
|
2287568e24b3ab20dff4feecbbf523c2fbbced65
|
[
"MIT"
] | null | null | null |
/*!
* \file Component.hpp
* \brief Provides ECS component class
*/
#ifndef VLK_COMPONENT_HPP
#define VLK_COMPONENT_HPP
#include "ValkyrieEngine/AllocChunk.hpp"
#include "ValkyrieEngine/IComponent.hpp"
#include "ValkyrieEngine/Entity.hpp"
#include <stdexcept>
#include <type_traits>
#include <unordered_map>
#include <functional>
#include <shared_mutex>
namespace vlk
{
/*!
* \brief Hint struct used to specify some component-related behaviour.
*
* \sa GetComponentHints()
* \sa Component
*/
struct ComponentHints
{
/*!
* \brief Number of components in a single allocation block.
*
* Memory for components is allocated internally using fixed-size storage blocks.
* This hint is used to specify the number of components that can fit in each storage block.
*
* \sa allocAutoResize
*/
const Size allocBlockSize = 64;
/*!
* \brief Whether component allocation blocks should be created as they are needed.
*
* Memory for cmponents is allocated internally using fixed-size storage blocks.
*
* If this hint is true, new storage blocks will be created as they fill up,
* providing effectively unbounded storage for components.
*
* If this hint is false, a maximum of one block will be allocated, bounding the
* total number of components that can exist at any one time to allocBlockSize.
* If the storage block is full, attempting to allocate another component will
* throw a <tt>std::range_error</tt>.
*
* \sa allocBlockSize
*/
const bool allocAutoResize = true;
};
/*!
* \brief Function used to retrieve the hints for a specified component type.
*
* This function can be specialized to override the hints used by a component type.
*
* \code
* struct SomeData {...};
*
* // Specify hints used by Component<SomeData>
* template <>
* VLK_CXX14_CONSTEXPR inline ComponentHints GetComponentHints<SomeData> { return ComponentHints {10, false}; }
* \endcode
*
* \sa ComponentHints
* \sa Component
*/
template <typename T>
VLK_CXX14_CONSTEXPR inline ComponentHints GetComponentHints() { return ComponentHints {}; }
/*!
* \brief Template class for ECS components
*
* Components are storage objects that define little to no logic.
* Components can be attached to entities with Attach() to provide the entity with some sort of property.
* A Component attached to an entity can then be fetched using FindOne(EntityID) or FindMany(EntityID).
* Components can also be accessed or modified by passing a function object to either ForEach(std::function<void(const T*)>) or ForEach(std::function<void(T*)>)
*
* Some behaviour related to Components can be controlled by specializing GetComponentHints() for T.
*
* \tparam T The data this entity is storing. Ideally this would be a POD struct, but any type with at least one public constructor and a public destructor will work.
*
* \sa EntityID
* \sa Entity::Create()
* \sa ComponentHints
* \sa GetComponentHints()
*/
template <typename T>
class Component final : public IComponent, public T
{
public:
static VLK_CXX14_CONSTEXPR Size ChunkSize = GetComponentHints<T>().allocBlockSize;
static VLK_CXX14_CONSTEXPR bool AllocResize = GetComponentHints<T>().allocAutoResize;
typedef AllocChunk<Component<T>, ChunkSize> ChunkType;
//typedef typename std::vector<ChunkType*>::iterator Iterator;
//typedef typename std::vector<ChunkType*>::const_iterator ConstIterator;
VLK_STATIC_ASSERT_MSG(std::is_class<T>::value, "T must be a class or struct type.");
private:
static VLK_SHARED_MUTEX_TYPE s_mtx;
static std::vector<ChunkType*> s_chunks;
///////////////////////////////////////////////////////////////////////
template <typename... Args>
Component<T>(Args... args) :
T(std::forward<Args>(args)...)
{ }
~Component<T>() = default;
///////////////////////////////////////////////////////////////////////
public:
Component<T>(const Component<T>&) = delete;
Component<T>(Component<T>&&) = delete;
Component<T>& operator=(const Component<T>&) = delete;
Component<T>& operator=(Component<T>&&) = delete;
///////////////////////////////////////////////////////////////////////
/*!
* \brief Creates a component.
*
* \param eId The entity to attach the new component to.
* \param args Arguments to be forwarded to the constructor for T.
*
* \return A pointer to the new component.
* This component should be destroyed either by calling Delete on it, or calling Entity::Delete on the entity it's attached to.
*
* \ts
* May be called from any thread.<br>
* Resource locking is handled internally.<br>
* Unique access to this class is required.<br>
* This function may block the calling thread.<br>
*
* \code{.cpp}
* class MyData
* {
* public:
* int foo;
*
* MyData(int f) : foo(f) { }
* ~MyData() = default;
* };
*
* EntityID eId = Entity::Create();
*
* Component<MyData>* component = Component<MyData>::Create(eId, 5);
* \endcode
*
* \sa Entity::Create()
* \sa Delete()
*/
template <typename... Args>
static Component<T>* Create(EntityID eId, Args... args)
{
std::unique_lock<VLK_SHARED_MUTEX_TYPE> ulock(s_mtx);
VLK_STATIC_ASSERT_MSG((std::is_constructible<T, Args...>::value), "Cannot construct an instance of T from the provided args.");
for (auto it = s_chunks.begin(); it != s_chunks.end(); it++)
{
ChunkType* ch = *it;
if (!ch->Full())
{
Component<T>* c = new (ch->Allocate()) Component<T>(std::forward<Args>(args)...);
c->entity = eId;
ECRegistry<IComponent>::AddEntry(eId, static_cast<IComponent*>(c));
ECRegistry<Component<T>>::AddEntry(eId, c);
return c;
}
}
if (AllocResize | (s_chunks.size() == 0))
{
//emplace_back returns void until C++17, so we can't use it here
s_chunks.push_back(new ChunkType());
Component<T>* c = new (s_chunks.back()->Allocate()) Component<T>(std::forward<Args>(args)...);
c->entity = eId;
ECRegistry<IComponent>::AddEntry(eId, static_cast<IComponent*>(c));
ECRegistry<Component<T>>::AddEntry(eId, c);
return c;
}
else
{
throw std::range_error("Maximum number of component allocations reached.");
return nullptr;
}
}
///////////////////////////////////////////////////////////////////////
/*!
* \brief Deletes this component.
*
* If this component is attached to an entity, it is detached.
* Also calls the destructor for this object.
*
* \ts
* May be called from any thread.<br>
* Resource locking is handled internally.<br>
* Unique access to this class is required.<br>
* Unique access to the ECRegistry<IComponent> class is required.<br>
* Unique access to the ECRegistry<Component<T>> class is required.<br>
* This function may block the calling thread.<br>
*
* \code{.cpp}
* Component<MyData>* component = Component<MyData>::Create(eId, 5);
*
* // Do something with component.
*
* component->Delete();
* \endcode
*
* \sa Create(EntityID, Args)
*/
virtual void Delete() final override
{
std::unique_lock<VLK_SHARED_MUTEX_TYPE> ulock(s_mtx);
ECRegistry<IComponent>::RemoveOne(this->entity, static_cast<IComponent*>(this));
ECRegistry<Component<T>>::RemoveOne(this->entity, this);
// Call destructor
this->~Component<T>();
// Free chunk memory
for (auto it = s_chunks.begin(); it != s_chunks.end(); it++)
{
ChunkType* c = *it;
if (c->OwnsPointer(this))
{
// Free Memory occupied by this component
c->Deallocate(this);
// Erase chunk if empty
if (c->Empty())
{
// Invalidates iterator
s_chunks.erase(it);
}
return;
}
}
}
///////////////////////////////////////////////////////////////////////
/*!
* \brief Attaches this component to an entity.
*
* \param eId The entity to attach this component to.
*
* A component can only be attached to one entity at a time,
* if this component is already attached to an entity when Attach is called,
* it is detached from that entity and attached to the new one.
* Components cannot exist detached from an entity.
*
* \ts
* May be called from any thread.<br>
* Resource locking is handled internally.<br>
* Unique access to this class is required.<br>
* Unique access to the ECRegistry<IComponent> class is required.<br>
* Unique access to the ECRegistry<Component<T>> class is required.<br>
* This function may block the calling thread.<br>
*
* \code{.cpp}
* EntityID e1 = Entity::Create();
* EntityID e2 = Entity::Create();
*
* Component<MyData>* component = Component<MyData>::Create(e1);
* component->Attach(e2);
* \endcode
*
* \sa Entity::Create()
* \sa Entity::Global
* \sa FindOne(EntityID)
*/
void Attach(EntityID eId)
{
std::unique_lock<VLK_SHARED_MUTEX_TYPE> ulock(s_mtx);
ECRegistry<IComponent>::RemoveOne(this->entity, static_cast<IComponent*>(this));
ECRegistry<Component<T>>::RemoveOne(this->entity, this);
this->entity = eId;
ECRegistry<IComponent>::AddEntry(this->entity, static_cast<IComponent*>(this));
ECRegistry<Component<T>>::AddEntry(this->entity, this);
}
///////////////////////////////////////////////////////////////////////
/*!
* \brief Find a component attached to an entity.
*
* \return One component of this type attached to the given entity.
* \return <tt>nullptr</tt> if no component of this type is found.
* If multiple components of this type are attached to the given entity,
* no guarantees are made as to which component will be returned.
*
* \ts
* May be called from any thread.<br>
* Resource locking is handled internally.<br>
* Shared access to the ECRegistry<Component<T>> class is required.<br>
* This function may block the calling thread.<br>
*
* \code{.cpp}
* Component<MyData>* component = Component<MyData>::FindOne(entity);
* \endcode
*
* \sa Attach(EntityID)
* \sa FindAll(EntityID)
*/
VLK_NODISCARD static inline Component<T>* FindOne(EntityID id)
{
return ECRegistry<Component<T>>::LookupOne(id);
}
///////////////////////////////////////////////////////////////////////
/*!
* \brief Find components attached to an entity.
*
* \param id The entity to find components for.
*
* \param vecOut A vector to write the found components to.
* Existing contents are not modified, but the vector may be resized.
*
* \return The number of components appended to vecOut
*
* \ts
* May be called from any thread.<br>
* Resource locking is handled internally.<br>
* Shared access to the ECRegistry<Component<T>> class is required.<br>
* This function may block the calling thread.<br>
*
* \code{.cpp}
* std::vector<Component<MyData>*> components;
* Component<MyData>::FindMany(entity, components);
*
* for (Component<MyData>* : components)
* {
* ...
* }
* \endcode
*
* \sa Attach(EntityID)
* \sa FindOne(EntityID)
*/
static inline Size FindAll(EntityID id, std::vector<Component<T>*>& vecOut)
{
return ECRegistry<Component<T>>::LookupAll(id, vecOut);
}
///////////////////////////////////////////////////////////////////////
/*!
* \brief Performs a mutating function on every instance of this component.
*
* \param func A function object that returns void and accepts a single pointer to a Component<T>.
*
* \ts
* May be called from any thread.<br>
* Resource locking is handled internally.<br>
* Unique access to this class is required.<br>
* This function may block the calling thread.<br>
*
* \code{.cpp}
* struct MyData
* {
* int foo = 0;
* bool bar = false;
* };
*
* Component<MyData>::ForEach([](Component<MyData*> c)
* {
* if (c->bar)
* {
* c->foo = 15;
* }
* });
*
* \endcode
*
* \sa vlk::Component<T>::CForEach(std::function<void(const Component<T>*)>)
* \sa vlk::Component<T>::ForEach(std::function<void(Iterator begin, Iterator end)>)
*/
static void ForEach(std::function<void(Component<T>*)> func)
{
std::unique_lock<VLK_SHARED_MUTEX_TYPE> ulock(s_mtx);
for (auto it = s_chunks.begin(); it != s_chunks.end(); it++)
{
//Dereference here to avoid ambiguity
ChunkType* ch = *it;
for (Size i = 0; i < ChunkType::ChunkSize; i++)
{
if (ch->IsOccupied(i))
{
func(ch->At(i));
}
}
}
}
///////////////////////////////////////////////////////////////////////
/*!
* \brief Performs a non-mutating function on every instance of this component.
*
* \param func A function object that returns void and accepts a single pointer to a const Component<T>.
*
* \ts
* May be called from any thread.<br>
* Resource locking is handled internally.<br>
* Shared access to this class is required.<br>
* This function may block the calling thread.<br>
*
* \code{.cpp}
* struct MyData
* {
* bool bar = false;
* };
*
* std::vector<const Component<MyData*>> components;
*
* Component<MyData>::CForEach([](const Component<MyData*> c)
* {
* if (c->foo) components.insert_back(c);
* });
* \endcode
*
* \sa ForEach(std::function<void(Component<T>*)>)
*/
static void CForEach(std::function<void(const Component<T>*)> func)
{
std::shared_lock<VLK_SHARED_MUTEX_TYPE> slock(s_mtx);
for (auto it = s_chunks.cbegin(); it != s_chunks.cend(); it++)
{
//Dereference here to avoid ambiguity
const ChunkType* ch = *it;
for (Size i = 0; i < ChunkType::ChunkSize; i++)
{
if (ch->IsOccupied(i))
{
func(ch->At(i));
}
}
}
}
///////////////////////////////////////////////////////////////////////
/*!
* \brief Returns the number of instances of this component that currently exist.
*
* If <tt>GetComponentHints<T>().allocAutoResize</tt> evaluates to true, this number will not exceed the value specified by <tt>GetComponentHints<T>().allocBlockSize</tt>
*
* \ts
* May be called from any thread.<br>
* Resource locking is handled internally.<br>
* Shared access to this class is required.<br>
* This function may block the calling thread.<br>
*
* \code{.cpp}
* struct MyData
* {
* ...
* };
*
* std::vector<const Component<MyData>> components;
* components.reserve(Component<MyData>::Count());
*
* Component<MyData>::CForEach([](const Component<MyData> c)
* {
* components.insert_back(c);
* });
* \endcode
*
* \sa ChunkCount()
*/
static Size Count()
{
std::shared_lock<VLK_SHARED_MUTEX_TYPE> slock(s_mtx);
Size total = 0;
for (auto it = s_chunks.cbegin(); it != s_chunks.cend(); it++)
{
total += (*it)->Count();
}
return total;
}
///////////////////////////////////////////////////////////////////////
/*!
* \brief Returns the number of storage blocks this component has allocated.
*
* If <tt>GetComponentHints<T>().allocAutoResize</tt> evaluates to true, this number will not exceed 1.
*
* \ts
* May be called from any thread.<br>
* Resource locking is handled internally.<br>
* Shared access to this class is required.<br>
* This function may block the calling thread.<br>
*
* \sa Count()
*/
static Size ChunkCount()
{
std::shared_lock<VLK_SHARED_MUTEX_TYPE> slock(s_mtx);
return s_chunks.size();
}
///////////////////////////////////////////////////////////////////////
};
template <typename T>
VLK_SHARED_MUTEX_TYPE Component<T>::s_mtx;
template <typename T>
std::vector<typename Component<T>::ChunkType*> Component<T>::s_chunks;
}
#endif
| 29.418519
| 172
| 0.616077
|
VD-15
|
7fc0ca2ddb5ed554bca7b6b959ba36908fdc425e
| 1,107
|
hpp
|
C++
|
stapl_release/stapl/utility/empty_class.hpp
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
stapl_release/stapl/utility/empty_class.hpp
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
stapl_release/stapl/utility/empty_class.hpp
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_UTILITY_EMPTY_CLASS_HPP
#define STAPL_UTILITY_EMPTY_CLASS_HPP
namespace stapl {
//////////////////////////////////////////////////////////////////////
/// @brief Empty class.
///
/// @ref empty_class is used with when invoking workfunctions returning void
/// to avoid code duplication in @p Task.
///
/// It is also used in @ref stapl::detail::directory_request_base as trivial
/// hook type when not using intrusive containers.
///
/// @sa result_storage_mf, directory_request_base
/// @ingroup utility
//////////////////////////////////////////////////////////////////////
struct empty_class
{
template<typename ...Args>
empty_class(Args&&...)
{ }
};
} // namespace stapl
#endif // STAPL_UTILITY_EMPTY_CLASS_HPP
| 28.384615
| 76
| 0.65131
|
parasol-ppl
|
7fc260b029f5a45c91e06399a37be0e6c61276fd
| 471
|
cpp
|
C++
|
LiteCppDB/LiteCppDB.Console/Cls.cpp
|
pnadan/LiteCppDB
|
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
|
[
"MIT"
] | 2
|
2019-07-18T06:30:33.000Z
|
2020-01-23T17:40:36.000Z
|
LiteCppDB/LiteCppDB.Console/Cls.cpp
|
pnadan/LiteCppDB
|
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
|
[
"MIT"
] | null | null | null |
LiteCppDB/LiteCppDB.Console/Cls.cpp
|
pnadan/LiteCppDB
|
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Cls.h"
namespace LiteCppDB_Console_Commands
{
DataAccess Cls::getAccess() noexcept
{
return DataAccess::None;
}
bool Cls::IsCommand(LiteCppDB::StringScanner& s) noexcept
{
return s.Scan("cls[[:s:]]*").length() > 0;
}
void Cls::Execute(LiteCppDB::LiteEngine engine, LiteCppDB::StringScanner& s, LiteCppDB_Console::Display d, LiteCppDB_Console::InputCommand input, LiteCppDB_Console::Env env) noexcept
{
d.WriteWelcome();
}
}
| 23.55
| 183
| 0.730361
|
pnadan
|
7fc53cb9ecb64a97512fb0d4737c9a4b1ebcf413
| 40,194
|
cpp
|
C++
|
Test/NativeTestHelpers/TestMarshaledStructs.cpp
|
blue3k/ATFClone
|
d1dbadfaaf2bc54cdb7db5c4ccbc5763a4891931
|
[
"Apache-2.0"
] | 1
|
2020-06-20T07:35:34.000Z
|
2020-06-20T07:35:34.000Z
|
Test/NativeTestHelpers/TestMarshaledStructs.cpp
|
blue3k/ATFClone
|
d1dbadfaaf2bc54cdb7db5c4ccbc5763a4891931
|
[
"Apache-2.0"
] | null | null | null |
Test/NativeTestHelpers/TestMarshaledStructs.cpp
|
blue3k/ATFClone
|
d1dbadfaaf2bc54cdb7db5c4ccbc5763a4891931
|
[
"Apache-2.0"
] | null | null | null |
//Copyright ?2014 Sony Computer Entertainment America LLC. See License.txt.
#include "stdafx.h"
// These names conflict with the managed versions.
#undef BROWSEINFO
#undef HDITEM
// Couldn't get this fully working. I'll make the necessary types public instead. --Ron
//// This 'using' is because of an annoying C++/CLI limitation.
//// http://stackoverflow.com/questions/417842/internalsvisibleto-not-working-for-managed-c
//#using <Atf.Core.dll> as_friend
// This 'using' is because the dependency on Atf.Gui.OpenGL.dll is conditional on whether
// or not we're compiling for the x86 (32-bit) processor.
#ifdef _M_IX86
#using <Atf.Gui.OpenGL.dll> as_friend
#endif
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace NUnit::Framework;
using namespace Sce::Atf;
namespace UnitTests
{
// ReSharper's unit test runner does not work with this C++/CLI project. Use
// Visual Studio 2013's Test -> Windows -> Test Explorer command or the VS context
// menu commands (e.g., ctrl+R, ctrl+T for the Debug Tests command) on the Test
// or TestFixture attributes.
[TestFixture]
public ref class TestMarshaledStructs
{
public:
[Test]
static void TestSHFILEINFO()
{
SHFILEINFOW nativeInfo;
Shell32::SHFILEINFO managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hIcon"),
(int) ((UINT8*) (&nativeInfo.hIcon) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "iIcon"),
(int) ((UINT8*) (&nativeInfo.iIcon) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwAttributes"),
(int) ((UINT8*) (&nativeInfo.dwAttributes) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "szDisplayName"),
(int) ((UINT8*) (&nativeInfo.szDisplayName) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int)Marshal::OffsetOf(managedInfo.GetType(), "szTypeName"),
(int) ((UINT8*) (&nativeInfo.szTypeName) - (UINT8*) &nativeInfo));
}
[Test]
static void TestBROWSEINFO()
{
BROWSEINFOW nativeInfo;
Shell32::BROWSEINFO managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hwndOwner"),
(int) ((UINT8*) (&nativeInfo.hwndOwner) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "pidlRoot"),
(int) ((UINT8*) (&nativeInfo.pidlRoot) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "pszDisplayName"),
(int) ((UINT8*) (&nativeInfo.pszDisplayName) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpszTitle"),
(int) ((UINT8*) (&nativeInfo.lpszTitle) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "ulFlags"),
(int) ((UINT8*) (&nativeInfo.ulFlags) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpfn"),
(int) ((UINT8*) (&nativeInfo.lpfn) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lParam"),
(int) ((UINT8*) (&nativeInfo.lParam) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "iImage"),
(int) ((UINT8*) (&nativeInfo.iImage) - (UINT8*) &nativeInfo));
}
[Test]
static void TestBROWSEINFOW()
{
BROWSEINFOW nativeInfo;
Sce::Atf::Wpf::Controls::BrowseForFolderDialog::BROWSEINFOW ^managedInfo =
gcnew Sce::Atf::Wpf::Controls::BrowseForFolderDialog::BROWSEINFOW();
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "hwndOwner"),
(int) ((UINT8*) (&nativeInfo.hwndOwner) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "pidlRoot"),
(int) ((UINT8*) (&nativeInfo.pidlRoot) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "pszDisplayName"),
(int) ((UINT8*) (&nativeInfo.pszDisplayName) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "lpszTitle"),
(int) ((UINT8*) (&nativeInfo.lpszTitle) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "ulFlags"),
(int) ((UINT8*) (&nativeInfo.ulFlags) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "lpfn"),
(int) ((UINT8*) (&nativeInfo.lpfn) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "lParam"),
(int) ((UINT8*) (&nativeInfo.lParam) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "iImage"),
(int) ((UINT8*) (&nativeInfo.iImage) - (UINT8*) &nativeInfo));
}
[Test]
static void TestMEMORYSTATUSEX()
{
MEMORYSTATUSEX nativeInfo;
Kernel32::MEMORYSTATUSEX ^managedInfo = gcnew Kernel32::MEMORYSTATUSEX();
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "dwLength"),
(int) ((UINT8*) (&nativeInfo.dwLength) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "dwMemoryLoad"),
(int) ((UINT8*) (&nativeInfo.dwMemoryLoad) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "ullTotalPhys"),
(int) ((UINT8*) (&nativeInfo.ullTotalPhys) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "ullAvailPhys"),
(int) ((UINT8*) (&nativeInfo.ullAvailPhys) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "ullTotalPageFile"),
(int) ((UINT8*) (&nativeInfo.ullTotalPageFile) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "ullAvailPageFile"),
(int) ((UINT8*) (&nativeInfo.ullAvailPageFile) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "ullTotalVirtual"),
(int) ((UINT8*) (&nativeInfo.ullTotalVirtual) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "ullAvailVirtual"),
(int) ((UINT8*) (&nativeInfo.ullAvailVirtual) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "ullAvailExtendedVirtual"),
(int) ((UINT8*) (&nativeInfo.ullAvailExtendedVirtual) - (UINT8*) &nativeInfo));
}
[Test]
static void TestBITMAP()
{
::BITMAP nativeInfo;
Sce::Atf::Windows::BITMAP managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "bmType"),
(int) ((UINT8*) (&nativeInfo.bmType) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "bmWidth"),
(int) ((UINT8*) (&nativeInfo.bmWidth) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "bmHeight"),
(int) ((UINT8*) (&nativeInfo.bmHeight) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "bmWidthBytes"),
(int) ((UINT8*) (&nativeInfo.bmWidthBytes) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "bmPlanes"),
(int) ((UINT8*) (&nativeInfo.bmPlanes) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "bmBitsPixel"),
(int) ((UINT8*) (&nativeInfo.bmBitsPixel) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "bmBits"),
(int) ((UINT8*) (&nativeInfo.bmBits) - (UINT8*) &nativeInfo));
}
[Test]
static void TestBITMAPINFO_FLAT()
{
::BITMAPINFOHEADER nativeInfo;
Sce::Atf::Windows::BITMAPINFOHEADER managedInfo;
// BITMAPINFO_FLAT has the header in the top plus space at the bottom.
// Let's make sure the header portion matches.
//Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biSize"),
(int) ((UINT8*) (&nativeInfo.biSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biWidth"),
(int) ((UINT8*) (&nativeInfo.biWidth) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biHeight"),
(int) ((UINT8*) (&nativeInfo.biHeight) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biPlanes"),
(int) ((UINT8*) (&nativeInfo.biPlanes) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biBitCount"),
(int) ((UINT8*) (&nativeInfo.biBitCount) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biCompression"),
(int) ((UINT8*) (&nativeInfo.biCompression) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biSizeImage"),
(int) ((UINT8*) (&nativeInfo.biSizeImage) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biXPelsPerMeter"),
(int) ((UINT8*) (&nativeInfo.biXPelsPerMeter) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biYPelsPerMeter"),
(int) ((UINT8*) (&nativeInfo.biYPelsPerMeter) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biClrUsed"),
(int) ((UINT8*) (&nativeInfo.biClrUsed) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "biClrImportant"),
(int) ((UINT8*) (&nativeInfo.biClrImportant) - (UINT8*) &nativeInfo));
}
[Test]
static void TestBITMAPINFOHEADER()
{
::BITMAPINFOHEADER nativeInfo;
Sce::Atf::Windows::BITMAPINFOHEADER ^managedInfo = gcnew Sce::Atf::Windows::BITMAPINFOHEADER();
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biSize"),
(int) ((UINT8*) (&nativeInfo.biSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biWidth"),
(int) ((UINT8*) (&nativeInfo.biWidth) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biHeight"),
(int) ((UINT8*) (&nativeInfo.biHeight) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biPlanes"),
(int) ((UINT8*) (&nativeInfo.biPlanes) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biBitCount"),
(int) ((UINT8*) (&nativeInfo.biBitCount) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biCompression"),
(int) ((UINT8*) (&nativeInfo.biCompression) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biSizeImage"),
(int) ((UINT8*) (&nativeInfo.biSizeImage) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biXPelsPerMeter"),
(int) ((UINT8*) (&nativeInfo.biXPelsPerMeter) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biYPelsPerMeter"),
(int) ((UINT8*) (&nativeInfo.biYPelsPerMeter) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biClrUsed"),
(int) ((UINT8*) (&nativeInfo.biClrUsed) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo->GetType(), "biClrImportant"),
(int) ((UINT8*) (&nativeInfo.biClrImportant) - (UINT8*) &nativeInfo));
}
[Test]
static void TestHDITEM()
{
HDITEMW nativeInfo;
Sce::Atf::User32::HDITEM managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "mask"),
(int) ((UINT8*) (&nativeInfo.mask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "cxy"),
(int) ((UINT8*) (&nativeInfo.cxy) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "pszText"),
(int) ((UINT8*) (&nativeInfo.pszText) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hbm"),
(int) ((UINT8*) (&nativeInfo.hbm) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "cchTextMax"),
(int) ((UINT8*) (&nativeInfo.cchTextMax) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "fmt"),
(int) ((UINT8*) (&nativeInfo.fmt) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lParam"),
(int) ((UINT8*) (&nativeInfo.lParam) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "iImage"),
(int) ((UINT8*) (&nativeInfo.iImage) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "iOrder"),
(int) ((UINT8*) (&nativeInfo.iOrder) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "type"),
(int) ((UINT8*) (&nativeInfo.type) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "pvFilter"),
(int) ((UINT8*) (&nativeInfo.pvFilter) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "state"),
(int) ((UINT8*) (&nativeInfo.state) - (UINT8*) &nativeInfo));
}
[Test]
static void TestPOINT()
{
POINT nativeInfo;
Sce::Atf::Windows::POINT managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "X"),
(int) ((UINT8*) (&nativeInfo.x) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "Y"),
(int) ((UINT8*) (&nativeInfo.y) - (UINT8*) &nativeInfo));
}
[Test]
static void TestRECT()
{
RECT nativeInfo;
Sce::Atf::Windows::RECT managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "Left"),
(int) ((UINT8*) (&nativeInfo.left) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "Top"),
(int) ((UINT8*) (&nativeInfo.top) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "Right"),
(int) ((UINT8*) (&nativeInfo.right) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "Bottom"),
(int) ((UINT8*) (&nativeInfo.bottom) - (UINT8*) &nativeInfo));
}
[Test]
static void TestMINMAXINFO()
{
MINMAXINFO nativeInfo;
Sce::Atf::Windows::MINMAXINFO managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "ptReserved"),
(int) ((UINT8*) (&nativeInfo.ptReserved) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "ptMaxSize"),
(int) ((UINT8*) (&nativeInfo.ptMaxSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "ptMaxPosition"),
(int) ((UINT8*) (&nativeInfo.ptMaxPosition) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "ptMinTrackSize"),
(int) ((UINT8*) (&nativeInfo.ptMinTrackSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "ptMaxTrackSize"),
(int) ((UINT8*) (&nativeInfo.ptMaxTrackSize) - (UINT8*) &nativeInfo));
}
[Test]
static void TestMSG()
{
MSG nativeInfo;
Sce::Atf::Windows::MSG managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hWnd"),
(int) ((UINT8*) (&nativeInfo.hwnd) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "msg"),
(int) ((UINT8*) (&nativeInfo.message) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "wParam"),
(int) ((UINT8*) (&nativeInfo.wParam) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lParam"),
(int) ((UINT8*) (&nativeInfo.lParam) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "time"),
(int) ((UINT8*) (&nativeInfo.time) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "p"),
(int) ((UINT8*) (&nativeInfo.pt) - (UINT8*) &nativeInfo));
}
[Test]
static void TestTRACKMOUSEEVENT()
{
TRACKMOUSEEVENT nativeInfo;
Sce::Atf::Windows::TRACKMOUSEEVENT managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "cbSize"),
(int) ((UINT8*) (&nativeInfo.cbSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwFlags"),
(int) ((UINT8*) (&nativeInfo.dwFlags) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hwndTrack"),
(int) ((UINT8*) (&nativeInfo.hwndTrack) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwHoverTime"),
(int) ((UINT8*) (&nativeInfo.dwHoverTime) - (UINT8*) &nativeInfo));
}
[Test]
static void TestNMHDR()
{
NMHDR nativeInfo;
Sce::Atf::Windows::NMHDR managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hwndFrom"),
(int) ((UINT8*) (&nativeInfo.hwndFrom) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "idFrom"),
(int) ((UINT8*) (&nativeInfo.idFrom) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "code"),
(int) ((UINT8*) (&nativeInfo.code) - (UINT8*) &nativeInfo));
}
[Test]
static void TestWINDOWPOS()
{
WINDOWPOS nativeInfo;
Sce::Atf::Windows::WINDOWPOS managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hwnd"),
(int) ((UINT8*) (&nativeInfo.hwnd) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hwndInsertAfter"),
(int) ((UINT8*) (&nativeInfo.hwndInsertAfter) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "x"),
(int) ((UINT8*) (&nativeInfo.x) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "y"),
(int) ((UINT8*) (&nativeInfo.y) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "cx"),
(int) ((UINT8*) (&nativeInfo.cx) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "cy"),
(int) ((UINT8*) (&nativeInfo.cy) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "flags"),
(int) ((UINT8*) (&nativeInfo.flags) - (UINT8*) &nativeInfo));
}
[Test]
static void TestNCCALCSIZE_PARAMS()
{
NCCALCSIZE_PARAMS nativeInfo;
Sce::Atf::Applications::FormNcRenderer::NCCALCSIZE_PARAMS managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "rect0"),
(int) ((UINT8*) (&nativeInfo.rgrc[0]) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "rect1"),
(int) ((UINT8*) (&nativeInfo.rgrc[1]) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "rect2"),
(int) ((UINT8*) (&nativeInfo.rgrc[2]) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lppos"),
(int) ((UINT8*) (&nativeInfo.lppos) - (UINT8*) &nativeInfo));
}
[Test]
static void TestWINDOWINFO()
{
WINDOWINFO nativeInfo;
Sce::Atf::CustomFileDialog::WINDOWINFO managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "cbSize"),
(int) ((UINT8*) (&nativeInfo.cbSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "rcWindow"),
(int) ((UINT8*) (&nativeInfo.rcWindow) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "rcClient"),
(int) ((UINT8*) (&nativeInfo.rcClient) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwStyle"),
(int) ((UINT8*) (&nativeInfo.dwStyle) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwExStyle"),
(int) ((UINT8*) (&nativeInfo.dwExStyle) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwWindowStatus"),
(int) ((UINT8*) (&nativeInfo.dwWindowStatus) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "cxWindowBorders"),
(int) ((UINT8*) (&nativeInfo.cxWindowBorders) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "cyWindowBorders"),
(int) ((UINT8*) (&nativeInfo.cyWindowBorders) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "atomWindowType"),
(int) ((UINT8*) (&nativeInfo.atomWindowType) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "wCreatorVersion"),
(int) ((UINT8*) (&nativeInfo.wCreatorVersion) - (UINT8*) &nativeInfo));
}
[Test]
static void TestOPENFILENAME()
{
OPENFILENAME nativeInfo;
Sce::Atf::CustomFileDialog::OPENFILENAME managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lStructSize"),
(int) ((UINT8*) (&nativeInfo.lStructSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hwndOwner"),
(int) ((UINT8*) (&nativeInfo.hwndOwner) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hInstance"),
(int) ((UINT8*) (&nativeInfo.hInstance) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpstrFilter"),
(int) ((UINT8*) (&nativeInfo.lpstrFilter) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpstrCustomFilter"),
(int) ((UINT8*) (&nativeInfo.lpstrCustomFilter) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "nMaxCustFilter"),
(int) ((UINT8*) (&nativeInfo.nMaxCustFilter) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "nFilterIndex"),
(int) ((UINT8*) (&nativeInfo.nFilterIndex) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpstrFile"),
(int) ((UINT8*) (&nativeInfo.lpstrFile) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "nMaxFile"),
(int) ((UINT8*) (&nativeInfo.nMaxFile) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpstrFileTitle"),
(int) ((UINT8*) (&nativeInfo.lpstrFileTitle) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "nMaxFileTitle"),
(int) ((UINT8*) (&nativeInfo.nMaxFileTitle) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpstrInitialDir"),
(int) ((UINT8*) (&nativeInfo.lpstrInitialDir) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpstrTitle"),
(int) ((UINT8*) (&nativeInfo.lpstrTitle) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "Flags"),
(int) ((UINT8*) (&nativeInfo.Flags) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "nFileOffset"),
(int) ((UINT8*) (&nativeInfo.nFileOffset) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "nFileExtension"),
(int) ((UINT8*) (&nativeInfo.nFileExtension) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpstrDefExt"),
(int) ((UINT8*) (&nativeInfo.lpstrDefExt) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lCustData"),
(int) ((UINT8*) (&nativeInfo.lCustData) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpfnHook"),
(int) ((UINT8*) (&nativeInfo.lpfnHook) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "lpTemplateName"),
(int) ((UINT8*) (&nativeInfo.lpTemplateName) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "pvReserved"),
(int) ((UINT8*) (&nativeInfo.pvReserved) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwReserved"),
(int) ((UINT8*) (&nativeInfo.dwReserved) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "FlagsEx"),
(int) ((UINT8*) (&nativeInfo.FlagsEx) - (UINT8*) &nativeInfo));
}
[Test]
static void TestDROPDESCRIPTION()
{
DROPDESCRIPTION nativeInfo;
Sce::Atf::DropDescription managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "type"),
(int) ((UINT8*) (&nativeInfo.type) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "szMessage"),
(int) ((UINT8*) (&nativeInfo.szMessage) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "szInsert"),
(int) ((UINT8*) (&nativeInfo.szInsert) - (UINT8*) &nativeInfo));
}
[Test]
static void TestShDragImage()
{
SHDRAGIMAGE nativeInfo;
Sce::Atf::ShDragImage managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "sizeDragImage"),
(int) ((UINT8*) (&nativeInfo.sizeDragImage) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "ptOffset"),
(int) ((UINT8*) (&nativeInfo.ptOffset) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "hbmpDragImage"),
(int) ((UINT8*) (&nativeInfo.hbmpDragImage) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "crColorKey"),
(int) ((UINT8*) (&nativeInfo.crColorKey) - (UINT8*) &nativeInfo));
}
#ifdef _M_IX86
[Test]
static void TestDDSCAPS2()
{
DDSCAPS2 nativeInfo;
Sce::Atf::Rendering::DdsImageLoader::DDSCAPS2 managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwCaps"),
(int) ((UINT8*) (&nativeInfo.dwCaps) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwCaps2"),
(int) ((UINT8*) (&nativeInfo.dwCaps2) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwCaps3"),
(int) ((UINT8*) (&nativeInfo.dwCaps3) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwCaps4"),
(int) ((UINT8*) (&nativeInfo.dwCaps4) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwVolumeDepth"),
(int) ((UINT8*) (&nativeInfo.dwVolumeDepth) - (UINT8*) &nativeInfo));
}
#endif
#ifdef _M_IX86
[Test]
static void TestDDCOLORKEY()
{
DDCOLORKEY nativeInfo;
Sce::Atf::Rendering::DdsImageLoader::DDCOLORKEY managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwColorSpaceLowValue"),
(int) ((UINT8*) (&nativeInfo.dwColorSpaceLowValue) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwColorSpaceHighValue"),
(int) ((UINT8*) (&nativeInfo.dwColorSpaceHighValue) - (UINT8*) &nativeInfo));
}
#endif
#ifdef _M_IX86
[Test]
static void TestDDPIXELFORMAT()
{
DDPIXELFORMAT nativeInfo;
Sce::Atf::Rendering::DdsImageLoader::DDPIXELFORMAT managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwSize"),
(int) ((UINT8*) (&nativeInfo.dwSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwFlags"),
(int) ((UINT8*) (&nativeInfo.dwFlags) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwFourCC"),
(int) ((UINT8*) (&nativeInfo.dwFourCC) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwRGBBitCount"),
(int) ((UINT8*) (&nativeInfo.dwRGBBitCount) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwYUVBitCount"),
(int) ((UINT8*) (&nativeInfo.dwYUVBitCount) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwZBufferBitDepth"),
(int) ((UINT8*) (&nativeInfo.dwZBufferBitDepth) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwAlphaBitDepth"),
(int) ((UINT8*) (&nativeInfo.dwAlphaBitDepth) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwLuminanceBitCount"),
(int) ((UINT8*) (&nativeInfo.dwLuminanceBitCount) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwBumpBitCount"),
(int) ((UINT8*) (&nativeInfo.dwBumpBitCount) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwPrivateFormatBitCount"),
(int) ((UINT8*) (&nativeInfo.dwPrivateFormatBitCount) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwRBitMask"),
(int) ((UINT8*) (&nativeInfo.dwRBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwYBitMask"),
(int) ((UINT8*) (&nativeInfo.dwYBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwStencilBitDepth"),
(int) ((UINT8*) (&nativeInfo.dwStencilBitDepth) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwLuminanceBitMask"),
(int) ((UINT8*) (&nativeInfo.dwLuminanceBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwBumpDuBitMask"),
(int) ((UINT8*) (&nativeInfo.dwBumpDuBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwOperations"),
(int) ((UINT8*) (&nativeInfo.dwOperations) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwGBitMask"),
(int) ((UINT8*) (&nativeInfo.dwGBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwUBitMask"),
(int) ((UINT8*) (&nativeInfo.dwUBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwZBitMask"),
(int) ((UINT8*) (&nativeInfo.dwZBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwBumpDvBitMask"),
(int) ((UINT8*) (&nativeInfo.dwBumpDvBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "MultiSampleCaps"),
(int) ((UINT8*) (&nativeInfo.MultiSampleCaps) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwBBitMask"),
(int) ((UINT8*) (&nativeInfo.dwBBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwVBitMask"),
(int) ((UINT8*) (&nativeInfo.dwVBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwStencilBitMask"),
(int) ((UINT8*) (&nativeInfo.dwStencilBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwBumpLuminanceBitMask"),
(int) ((UINT8*) (&nativeInfo.dwBumpLuminanceBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwRGBAlphaBitMask"),
(int) ((UINT8*) (&nativeInfo.dwRGBAlphaBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwYUVAlphaBitMask"),
(int) ((UINT8*) (&nativeInfo.dwYUVAlphaBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwLuminanceAlphaBitMask"),
(int) ((UINT8*) (&nativeInfo.dwLuminanceAlphaBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwRGBZBitMask"),
(int) ((UINT8*) (&nativeInfo.dwRGBZBitMask) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "dwYUVZBitMask"),
(int) ((UINT8*) (&nativeInfo.dwYUVZBitMask) - (UINT8*) &nativeInfo));
}
#endif //_M_IX86
#ifdef _M_IX86
[Test]
static void TestDDSURFACEDESC2()
{
DDSURFACEDESC2 nativeInfo;
Sce::Atf::Rendering::DdsImageLoader::DDSURFACEDESC2 managedInfo;
Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwSize"),
(int) ((UINT8*) (&nativeInfo.dwSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwFlags"),
(int) ((UINT8*) (&nativeInfo.dwFlags) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwHeight"),
(int) ((UINT8*) (&nativeInfo.dwHeight) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwWidth"),
(int) ((UINT8*) (&nativeInfo.dwWidth) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_lPitch"),
(int) ((UINT8*) (&nativeInfo.lPitch) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwLinearSize"),
(int) ((UINT8*) (&nativeInfo.dwLinearSize) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwBackBufferCount"),
(int) ((UINT8*) (&nativeInfo.dwBackBufferCount) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwDepth"),
(int) ((UINT8*) (&nativeInfo.dwDepth) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwMipMapCount"),
(int) ((UINT8*) (&nativeInfo.dwMipMapCount) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwRefreshRate"),
(int) ((UINT8*) (&nativeInfo.dwRefreshRate) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwSrcVBHandle"),
(int) ((UINT8*) (&nativeInfo.dwSrcVBHandle) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwAlphaBitDepth"),
(int) ((UINT8*) (&nativeInfo.dwAlphaBitDepth) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwReserved"),
(int) ((UINT8*) (&nativeInfo.dwReserved) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_lpSurface"),
(int) ((UINT8*) (&nativeInfo.lpSurface) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_ddckCKDestOverlay"),
(int) ((UINT8*) (&nativeInfo.ddckCKDestOverlay) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwEmptyFaceColor"),
(int) ((UINT8*) (&nativeInfo.dwEmptyFaceColor) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_ddckCKDestBlt"),
(int) ((UINT8*) (&nativeInfo.ddckCKDestBlt) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_ddckCKSrcOverlay"),
(int) ((UINT8*) (&nativeInfo.ddckCKSrcOverlay) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_ddckCKSrcBlt"),
(int) ((UINT8*) (&nativeInfo.ddckCKSrcBlt) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_ddpfPixelFormat"),
(int) ((UINT8*) (&nativeInfo.ddpfPixelFormat) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwFVF"),
(int) ((UINT8*) (&nativeInfo.dwFVF) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_ddsCaps"),
(int) ((UINT8*) (&nativeInfo.ddsCaps) - (UINT8*) &nativeInfo));
Assert::AreEqual(
(int) Marshal::OffsetOf(managedInfo.GetType(), "m_dwTextureStage"),
(int) ((UINT8*) (&nativeInfo.dwTextureStage) - (UINT8*) &nativeInfo));
}
#endif //_M_IX86
// Throws an exception:
// Type 'Sce.Atf.Shell32+ITEMIDLIST' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
//[Test]
//static void TestITEMIDLIST()
//{
// ITEMIDLIST nativeInfo;
// Shell32::ITEMIDLIST managedInfo;
// Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
// Assert::AreEqual(
// (int) Marshal::OffsetOf(managedInfo.GetType(), "mkid"),
// (int) ((UINT8*) (&nativeInfo.mkid) - (UINT8*) &nativeInfo));
//}
// Throws an exception:
// Type 'Sce.Atf.Shell32+ITEMIDLIST' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
//[Test]
//static void TestSHITEMID()
//{
// SHITEMID nativeInfo;
// Shell32::SHITEMID managedInfo;
// Assert::AreEqual(Marshal::SizeOf(managedInfo), (int)sizeof(nativeInfo));
// Assert::AreEqual(
// (int) Marshal::OffsetOf(managedInfo.GetType(), "cb"),
// (int) ((UINT8*) (&nativeInfo.cb) - (UINT8*) &nativeInfo));
// Assert::AreEqual(
// (int) Marshal::OffsetOf(managedInfo.GetType(), "abID"),
// (int) ((UINT8*) (&nativeInfo.abID) - (UINT8*) &nativeInfo));
//}
};
}
| 45.111111
| 131
| 0.662711
|
blue3k
|
7fcfbfa7aa6c45f8e66f00927bb87b8655fbbaaf
| 1,885
|
cpp
|
C++
|
examples/c++/batesprocess.cpp
|
bpmbank/pyql
|
db1fc886a61ab3e234cebf54723abaa4258138b3
|
[
"BSD-3-Clause"
] | 488
|
2015-01-13T11:03:27.000Z
|
2022-03-31T07:19:44.000Z
|
examples/c++/batesprocess.cpp
|
bpmbank/pyql
|
db1fc886a61ab3e234cebf54723abaa4258138b3
|
[
"BSD-3-Clause"
] | 139
|
2015-01-05T18:56:55.000Z
|
2022-01-26T18:33:37.000Z
|
examples/c++/batesprocess.cpp
|
bpmbank/pyql
|
db1fc886a61ab3e234cebf54723abaa4258138b3
|
[
"BSD-3-Clause"
] | 142
|
2015-01-07T14:26:46.000Z
|
2022-01-23T14:08:47.000Z
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Test of bates model constructor from bates process
*/
#include <iostream>
#include <iomanip>
#include "utilities.hpp"
#include <ql/quantlib.hpp>
#ifdef BOOST_MSVC
/* Uncomment the following lines to unmask floating-point
exceptions. Warning: unpredictable results can arise...
See http://www.wilmott.com/messageview.cfm?catid=10&threadid=9481
Is there anyone with a definitive word about this?
*/
// #include <float.h>
// namespace { unsigned int u = _controlfp(_EM_INEXACT, _MCW_EM); }
#endif
using namespace QuantLib;
#if defined(QL_ENABLE_SESSIONS)
namespace QuantLib
{
Integer sessionId()
{
return 0;
}
}
#endif
using namespace QuantLib;
int main() {
Date today = Date::todaysDate();
Settings::instance().evaluationDate() = today;
DayCounter dayCounter = Actual360();
Handle<YieldTermStructure> riskFreeTS(flatRate(0.04, dayCounter));
Handle<YieldTermStructure> dividendTS(flatRate(0.50, dayCounter));
Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));
const Real sigma = 0.1;
const Real v0=0.01;
const Real kappa=0.2;
const Real theta=0.02;
const Real rho=-0.75;
const Real lambda = .123;
const Real nu = .0123;
const Real delta = .00123;
boost::shared_ptr<BatesProcess> process(
new BatesProcess(riskFreeTS, dividendTS,
s0, v0, kappa, theta, sigma, rho, lambda, nu, delta));
std::cout << "Arguments from Bates process:" << std::endl;
std::cout << "lambda: " << process->lambda() << " delta: " << process->delta() << std::endl;
boost::shared_ptr<BatesModel> model(new BatesModel(process));
std::cout << "Arguments from Bates model:" << std::endl;
std::cout << "lambda: " << model->lambda() << " delta: " << model->delta() << std::endl;
return 0;
}
| 24.166667
| 96
| 0.666844
|
bpmbank
|